-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathinstance.ts
More file actions
1153 lines (1014 loc) · 28.8 KB
/
instance.ts
File metadata and controls
1153 lines (1014 loc) · 28.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Logger } from "@/common//log";
import {
type ActorTags,
isJsonSerializable,
stringifyError,
} from "@/common//utils";
import onChange from "on-change";
import type { ActorConfig } from "./config";
import { Conn, type ConnId } from "./connection";
import type { ActorDriver, ConnDrivers } from "./driver";
import type { ConnDriver } from "./driver";
import * as errors from "./errors";
import { processMessage } from "./protocol/message/mod";
import { instanceLogger, logger } from "./log";
import type { ActionContext } from "./action";
import { DeadlineError, Lock, deadline } from "./utils";
import { Schedule } from "./schedule";
import type * as wsToServer from "@/actor/protocol/message/to-server";
import { CachedSerializer } from "./protocol/serde";
import { ActorInspector } from "@/inspector/actor";
import { ActorContext } from "./context";
import invariant from "invariant";
import type {
PersistedActor,
PersistedConn,
PersistedScheduleEvents,
} from "./persisted";
/**
* Options for the `_saveState` method.
*/
export interface SaveStateOptions {
/**
* Forces the state to be saved immediately. This function will return when the state has saved successfully.
*/
immediate?: boolean;
}
/**
* Options for the `_broadcastWithOptions` method.
*/
export interface BroadcastInstanceOptions {
/**
* The connection IDs to be excluded from the broadcast.
*/
exclude?: string[];
}
/** Actor type alias with all `any` types. Used for `extends` in classes referencing this actor. */
// biome-ignore lint/suspicious/noExplicitAny: Needs to be used in `extends`
export type AnyActorInstance = ActorInstance<any, any, any, any>;
export type ExtractActorState<A extends AnyActorInstance> =
A extends ActorInstance<
infer State,
// biome-ignore lint/suspicious/noExplicitAny: Must be used for `extends`
any,
// biome-ignore lint/suspicious/noExplicitAny: Must be used for `extends`
any,
// biome-ignore lint/suspicious/noExplicitAny: Must be used for `extends`
any
>
? State
: never;
export type ExtractActorConnParams<A extends AnyActorInstance> =
A extends ActorInstance<
// biome-ignore lint/suspicious/noExplicitAny: Must be used for `extends`
any,
infer ConnParams,
// biome-ignore lint/suspicious/noExplicitAny: Must be used for `extends`
any,
// biome-ignore lint/suspicious/noExplicitAny: Must be used for `extends`
any
>
? ConnParams
: never;
export type ExtractActorConnState<A extends AnyActorInstance> =
A extends ActorInstance<
// biome-ignore lint/suspicious/noExplicitAny: Must be used for `extends`
any,
// biome-ignore lint/suspicious/noExplicitAny: Must be used for `extends`
any,
infer ConnState,
// biome-ignore lint/suspicious/noExplicitAny: Must be used for `extends`
any
>
? ConnState
: never;
export class ActorInstance<S, CP, CS, V> {
// Shared actor context for this instance
actorContext: ActorContext<S, CP, CS, V>;
isStopping = false;
#persistChanged = false;
/**
* The proxied state that notifies of changes automatically.
*
* Any data that should be stored indefinitely should be held within this object.
*/
#persist!: PersistedActor<S, CP, CS>;
/** Raw state without the proxy wrapper */
#persistRaw!: PersistedActor<S, CP, CS>;
#writePersistLock = new Lock<void>(void 0);
#lastSaveTime = 0;
#pendingSaveTimeout?: NodeJS.Timeout;
#vars?: V;
#backgroundPromises: Promise<void>[] = [];
#config: ActorConfig<S, CP, CS, V>;
#connectionDrivers!: ConnDrivers;
#actorDriver!: ActorDriver;
#actorId!: string;
#name!: string;
#tags!: ActorTags;
#region!: string;
#ready = false;
#connections = new Map<ConnId, Conn<S, CP, CS, V>>();
#subscriptionIndex = new Map<string, Set<Conn<S, CP, CS, V>>>();
#schedule!: Schedule;
/**
* Inspector for the actor.
* @internal
*/
inspector!: ActorInspector;
get id() {
return this.#actorId;
}
/**
* This constructor should never be used directly.
*
* Constructed in {@link ActorInstance.start}.
*
* @private
*/
constructor(config: ActorConfig<S, CP, CS, V>) {
this.#config = config;
this.actorContext = new ActorContext(this);
}
async start(
connectionDrivers: ConnDrivers,
actorDriver: ActorDriver,
actorId: string,
name: string,
tags: ActorTags,
region: string,
) {
this.#connectionDrivers = connectionDrivers;
this.#actorDriver = actorDriver;
this.#actorId = actorId;
this.#name = name;
this.#tags = tags;
this.#region = region;
this.#schedule = new Schedule(this);
this.inspector = new ActorInspector(this);
// Initialize server
//
// Store the promise so network requests can await initialization
await this.#initialize();
// TODO: Exit process if this errors
if (this.#varsEnabled) {
let vars: V | undefined = undefined;
if ("createVars" in this.#config) {
const dataOrPromise = this.#config.createVars(
this.actorContext as unknown as ActorContext<
undefined,
undefined,
undefined,
undefined
>,
this.#actorDriver.getContext(this.#actorId),
);
if (dataOrPromise instanceof Promise) {
vars = await deadline(
dataOrPromise,
this.#config.options.lifecycle.createVarsTimeout,
);
} else {
vars = dataOrPromise;
}
} else if ("vars" in this.#config) {
vars = structuredClone(this.#config.vars);
} else {
throw new Error("Could not variables from 'createVars' or 'vars'");
}
this.#vars = vars;
}
// TODO: Exit process if this errors
logger().info("actor starting");
if (this.#config.onStart) {
const result = this.#config.onStart(this.actorContext);
if (result instanceof Promise) {
await result;
}
}
// Set alarm for next scheduled event if any exist after finishing initiation sequence
if (this.#persist.e.length > 0) {
await this.#actorDriver.setAlarm(this, this.#persist.e[0].t);
}
logger().info("actor ready");
this.#ready = true;
}
async scheduleEvent(
timestamp: number,
fn: string,
args: unknown[],
): Promise<void> {
// Build event
const eventId = crypto.randomUUID();
const newEvent: PersistedScheduleEvents = {
e: eventId,
t: timestamp,
a: fn,
ar: args,
};
this.actorContext.log.info("scheduling event", {
event: eventId,
timestamp,
action: fn,
});
// Insert event in to index
const insertIndex = this.#persist.e.findIndex((x) => x.t > newEvent.t);
if (insertIndex === -1) {
this.#persist.e.push(newEvent);
} else {
this.#persist.e.splice(insertIndex, 0, newEvent);
}
// Update alarm if:
// - this is the newest event (i.e. at beginning of array) or
// - this is the only event (i.e. the only event in the array)
if (insertIndex === 0 || this.#persist.e.length === 1) {
this.actorContext.log.info("setting alarm", { timestamp });
await this.#actorDriver.setAlarm(this, newEvent.t);
}
}
async onAlarm() {
const now = Date.now();
this.actorContext.log.debug("alarm triggered", {
now,
events: this.#persist.e.length,
});
// Remove events from schedule that we're about to run
const runIndex = this.#persist.e.findIndex((x) => x.t <= now);
if (runIndex === -1) {
this.actorContext.log.debug("no events to run", { now });
return;
}
const scheduleEvents = this.#persist.e.splice(0, runIndex + 1);
this.actorContext.log.debug("running events", {
count: scheduleEvents.length,
});
// Set alarm for next event
if (this.#persist.e.length > 0) {
await this.#actorDriver.setAlarm(this, this.#persist.e[0].t);
}
// Iterate by event key in order to ensure we call the events in order
for (const event of scheduleEvents) {
try {
this.actorContext.log.info("running action for event", {
event: event.e,
timestamp: event.t,
action: event.a,
args: event.ar,
});
// Look up function
const fn: unknown = this.#config.actions[event.a];
if (!fn) throw new Error(`Missing action for alarm ${event.a}`);
if (typeof fn !== "function")
throw new Error(
`Alarm function lookup for ${event.a} returned ${typeof fn}`,
);
// Call function
try {
await fn.call(undefined, this.actorContext, ...event.ar);
} catch (error) {
this.actorContext.log.error("error while running event", {
error: stringifyError(error),
event: event.e,
timestamp: event.t,
action: event.a,
args: event.ar,
});
}
} catch (error) {
this.actorContext.log.error("internal error while running event", {
error: stringifyError(error),
event: event.e,
timestamp: event.t,
action: event.a,
args: event.ar,
});
}
}
}
get stateEnabled() {
return "createState" in this.#config || "state" in this.#config;
}
#validateStateEnabled() {
if (!this.stateEnabled) {
throw new errors.StateNotEnabled();
}
}
get #connStateEnabled() {
return "createConnState" in this.#config || "connState" in this.#config;
}
get #varsEnabled() {
return "createVars" in this.#config || "vars" in this.#config;
}
#validateVarsEnabled() {
if (!this.#varsEnabled) {
throw new errors.VarsNotEnabled();
}
}
/** Promise used to wait for a save to complete. This is required since you cannot await `#saveStateThrottled`. */
#onPersistSavedPromise?: PromiseWithResolvers<void>;
/** Throttled save state method. Used to write to KV at a reasonable cadence. */
#savePersistThrottled() {
const now = Date.now();
const timeSinceLastSave = now - this.#lastSaveTime;
const saveInterval = this.#config.options.state.saveInterval;
// If we're within the throttle window and not already scheduled, schedule the next save.
if (timeSinceLastSave < saveInterval) {
if (this.#pendingSaveTimeout === undefined) {
this.#pendingSaveTimeout = setTimeout(() => {
this.#pendingSaveTimeout = undefined;
this.#savePersistInner();
}, saveInterval - timeSinceLastSave);
}
} else {
// If we're outside the throttle window, save immediately
this.#savePersistInner();
}
}
/** Saves the state to KV. You probably want to use #saveStateThrottled instead except for a few edge cases. */
async #savePersistInner() {
try {
this.#lastSaveTime = Date.now();
if (this.#persistChanged) {
// Use a lock in order to avoid race conditions with multiple
// parallel promises writing to KV. This should almost never happen
// unless there are abnormally high latency in KV writes.
await this.#writePersistLock.lock(async () => {
logger().debug("saving persist");
// There might be more changes while we're writing, so we set this
// before writing to KV in order to avoid a race condition.
this.#persistChanged = false;
// Write to KV
await this.#actorDriver.writePersistedData(
this.#actorId,
this.#persistRaw,
);
logger().debug("persist saved");
});
}
this.#onPersistSavedPromise?.resolve();
} catch (error) {
this.#onPersistSavedPromise?.reject(error);
throw error;
}
}
/**
* Creates proxy for `#persist` that handles automatically flagging when state needs to be updated.
*/
#setPersist(target: PersistedActor<S, CP, CS>) {
// Set raw persist object
this.#persistRaw = target;
// TODO: Only validate this for conn state
// TODO: Allow disabling in production
// If this can't be proxied, return raw value
if (target === null || typeof target !== "object") {
let invalidPath = "";
if (
!isJsonSerializable(
target,
(path) => {
invalidPath = path;
},
"",
)
) {
throw new errors.InvalidStateType({ path: invalidPath });
}
return target;
}
// Unsubscribe from old state
if (this.#persist) {
onChange.unsubscribe(this.#persist);
}
// Listen for changes to the object in order to automatically write state
this.#persist = onChange(
target,
// biome-ignore lint/suspicious/noExplicitAny: Don't know types in proxy
(path: string, value: any, _previousValue: any, _applyData: any) => {
let invalidPath = "";
if (
!isJsonSerializable(
value,
(invalidPathPart) => {
invalidPath = invalidPathPart;
},
"",
)
) {
throw new errors.InvalidStateType({
path: path + (invalidPath ? `.${invalidPath}` : ""),
});
}
this.#persistChanged = true;
// Call inspect handler
this.inspector.onStateChange(this.#persistRaw.s);
// Call onStateChange if it exists
if (this.#config.onStateChange && this.#ready) {
try {
this.#config.onStateChange(this.actorContext, this.#persistRaw.s);
} catch (error) {
logger().error("error in `_onStateChange`", {
error: stringifyError(error),
});
}
}
// State will be flushed at the end of the RPC
},
{ ignoreDetached: true },
);
}
async #initialize() {
// Read initial state
const persistData = (await this.#actorDriver.readPersistedData(
this.#actorId,
)) as PersistedActor<S, CP, CS>;
if (persistData !== undefined) {
logger().info("actor restoring", {
connections: persistData.c.length,
});
// Set initial state
this.#setPersist(persistData);
// Load connections
for (const connPersist of this.#persist.c) {
// Create connections
const driver = this.__getConnDriver(connPersist.d);
const conn = new Conn<S, CP, CS, V>(
this,
connPersist,
driver,
this.#connStateEnabled,
);
this.#connections.set(conn.id, conn);
// Register event subscriptions
for (const sub of connPersist.su) {
this.#addSubscription(sub.n, conn, true);
}
}
} else {
logger().info("actor creating");
if (this.#config.onCreate) {
await this.#config.onCreate(this.actorContext);
}
// Initialize actor state
let stateData: unknown = undefined;
if (this.stateEnabled) {
logger().info("actor state initializing");
if ("createState" in this.#config) {
this.#config.createState;
// Convert state to undefined since state is not defined yet here
stateData = await this.#config.createState(
this.actorContext as unknown as ActorContext<
undefined,
undefined,
undefined,
undefined
>,
);
} else if ("state" in this.#config) {
stateData = structuredClone(this.#config.state);
} else {
throw new Error("Both 'createState' or 'state' were not defined");
}
} else {
logger().debug("state not enabled");
}
const persist: PersistedActor<S, CP, CS> = {
s: stateData as S,
c: [],
e: [],
};
// Update state
logger().debug("writing state");
await this.#actorDriver.writePersistedData(this.#actorId, persist);
this.#setPersist(persist);
}
}
__getConnForId(id: string): Conn<S, CP, CS, V> | undefined {
return this.#connections.get(id);
}
/**
* Removes a connection and cleans up its resources.
*/
__removeConn(conn: Conn<S, CP, CS, V> | undefined) {
if (!conn) {
logger().warn("`conn` does not exist");
return;
}
// Remove from persist & save immediately
const connIdx = this.#persist.c.findIndex((c) => c.i === conn.id);
if (connIdx !== -1) {
this.#persist.c.splice(connIdx, 1);
this.saveState({ immediate: true });
} else {
logger().warn("could not find persisted connection to remove", {
connId: conn.id,
});
}
// Remove from state
this.#connections.delete(conn.id);
// Remove subscriptions
for (const eventName of [...conn.subscriptions.values()]) {
this.#removeSubscription(eventName, conn, true);
}
this.inspector.onConnChange(this.#connections);
if (this.#config.onDisconnect) {
try {
const result = this.#config.onDisconnect(this.actorContext, conn);
if (result instanceof Promise) {
// Handle promise but don't await it to prevent blocking
result.catch((error) => {
logger().error("error in `onDisconnect`", {
error: stringifyError(error),
});
});
}
} catch (error) {
logger().error("error in `onDisconnect`", {
error: stringifyError(error),
});
}
}
}
async prepareConn(
// biome-ignore lint/suspicious/noExplicitAny: TypeScript bug with ExtractActorConnParams<this>,
params: any,
request?: Request,
): Promise<CS> {
// Authenticate connection
let connState: CS | undefined = undefined;
const onBeforeConnectOpts = {
request,
params,
};
if (this.#config.onBeforeConnect) {
await this.#config.onBeforeConnect(
this.actorContext,
onBeforeConnectOpts,
);
}
if (this.#connStateEnabled) {
if ("createConnState" in this.#config) {
const dataOrPromise = this.#config.createConnState(
this.actorContext as unknown as ActorContext<
undefined,
undefined,
undefined,
undefined
>,
onBeforeConnectOpts,
);
if (dataOrPromise instanceof Promise) {
connState = await deadline(
dataOrPromise,
this.#config.options.lifecycle.createConnStateTimeout,
);
} else {
connState = dataOrPromise;
}
} else if ("connState" in this.#config) {
connState = structuredClone(this.#config.connState);
} else {
throw new Error(
"Could not create connection state from 'createConnState' or 'connState'",
);
}
}
return connState as CS;
}
__getConnDriver(driverId: string): ConnDriver {
// Get driver
const driver = this.#connectionDrivers[driverId];
if (!driver) throw new Error(`No connection driver: ${driverId}`);
return driver;
}
/**
* Called after establishing a connection handshake.
*/
async createConn(
connectionId: string,
connectionToken: string,
params: CP,
state: CS,
driverId: string,
driverState: unknown,
): Promise<Conn<S, CP, CS, V>> {
if (this.#connections.has(connectionId)) {
throw new Error(`Connection already exists: ${connectionId}`);
}
// Create connection
const driver = this.__getConnDriver(driverId);
const persist: PersistedConn<CP, CS> = {
i: connectionId,
t: connectionToken,
d: driverId,
ds: driverState,
p: params,
s: state,
su: [],
};
const conn = new Conn<S, CP, CS, V>(
this,
persist,
driver,
this.#connStateEnabled,
);
this.#connections.set(conn.id, conn);
// Add to persistence & save immediately
this.#persist.c.push(persist);
this.saveState({ immediate: true });
this.inspector.onConnChange(this.#connections);
// Handle connection
if (this.#config.onConnect) {
try {
const result = this.#config.onConnect(this.actorContext, conn);
if (result instanceof Promise) {
deadline(
result,
this.#config.options.lifecycle.onConnectTimeout,
).catch((error) => {
logger().error("error in `onConnect`, closing socket", {
error,
});
conn?.disconnect("`onConnect` failed");
});
}
} catch (error) {
logger().error("error in `onConnect`", {
error: stringifyError(error),
});
conn?.disconnect("`onConnect` failed");
}
}
// Send init message
conn._sendMessage(
new CachedSerializer({
b: {
i: {
ci: `${conn.id}`,
ct: conn._token,
},
},
}),
);
return conn;
}
// MARK: Messages
async processMessage(message: wsToServer.ToServer, conn: Conn<S, CP, CS, V>) {
await processMessage(message, this, conn, {
onExecuteRpc: async (ctx, name, args) => {
return await this.executeRpc(ctx, name, args);
},
onSubscribe: async (eventName, conn) => {
this.#addSubscription(eventName, conn, false);
},
onUnsubscribe: async (eventName, conn) => {
this.#removeSubscription(eventName, conn, false);
},
});
}
// MARK: Events
#addSubscription(
eventName: string,
connection: Conn<S, CP, CS, V>,
fromPersist: boolean,
) {
if (connection.subscriptions.has(eventName)) {
logger().info("connection already has subscription", { eventName });
return;
}
// Persist subscriptions & save immediately
//
// Don't update persistence if already restoring from persistence
if (!fromPersist) {
connection.__persist.su.push({ n: eventName });
this.saveState({ immediate: true });
}
// Update subscriptions
connection.subscriptions.add(eventName);
// Update subscription index
let subscribers = this.#subscriptionIndex.get(eventName);
if (!subscribers) {
subscribers = new Set();
this.#subscriptionIndex.set(eventName, subscribers);
}
subscribers.add(connection);
}
#removeSubscription(
eventName: string,
connection: Conn<S, CP, CS, V>,
fromRemoveConn: boolean,
) {
if (!connection.subscriptions.has(eventName)) {
logger().warn("connection does not have subscription", { eventName });
return;
}
// Persist subscriptions & save immediately
//
// Don't update the connection itself if the connection is already being removed
if (!fromRemoveConn) {
connection.subscriptions.delete(eventName);
const subIdx = connection.__persist.su.findIndex(
(s) => s.n === eventName,
);
if (subIdx !== -1) {
connection.__persist.su.splice(subIdx, 1);
} else {
logger().warn("subscription does not exist with name", { eventName });
}
this.saveState({ immediate: true });
}
// Update scriptions index
const subscribers = this.#subscriptionIndex.get(eventName);
if (subscribers) {
subscribers.delete(connection);
if (subscribers.size === 0) {
this.#subscriptionIndex.delete(eventName);
}
}
}
#assertReady() {
if (!this.#ready) throw new errors.InternalError("Actor not ready");
}
/**
* Execute an RPC call from a client.
*
* This method handles:
* 1. Validating the RPC name
* 2. Executing the RPC function
* 3. Processing the result through onBeforeRpcResponse (if configured)
* 4. Handling timeouts and errors
* 5. Saving state changes
*
* @param ctx The RPC context
* @param rpcName The name of the RPC being called
* @param args The arguments passed to the RPC
* @returns The result of the RPC call
* @throws {RpcNotFound} If the RPC doesn't exist
* @throws {RpcTimedOut} If the RPC times out
* @internal
*/
async executeRpc(
ctx: ActionContext<S, CP, CS, V>,
rpcName: string,
args: unknown[],
): Promise<unknown> {
invariant(this.#ready, "exucuting rpc before ready");
// Prevent calling private or reserved methods
if (!(rpcName in this.#config.actions)) {
logger().warn("rpc does not exist", { rpcName });
throw new errors.ActionNotFound();
}
// Check if the method exists on this object
// biome-ignore lint/suspicious/noExplicitAny: RPC name is dynamic from client
const rpcFunction = this.#config.actions[rpcName];
if (typeof rpcFunction !== "function") {
logger().warn("action not found", { actionName: rpcName });
throw new errors.ActionNotFound();
}
// TODO: pass abortable to the rpc to decide when to abort
// TODO: Manually call abortable for better error handling
// Call the function on this object with those arguments
try {
// Log when we start executing the action
logger().debug("executing action", { actionName: rpcName, args });
const outputOrPromise = rpcFunction.call(undefined, ctx, ...args);
let output: unknown;
if (outputOrPromise instanceof Promise) {
// Log that we're waiting for an async action
logger().debug("awaiting async action", { actionName: rpcName });
output = await deadline(
outputOrPromise,
this.#config.options.action.timeout,
);
// Log that async action completed
logger().debug("async action completed", { actionName: rpcName });
} else {
output = outputOrPromise;
}
// Process the output through onBeforeRpcResponse if configured
if (this.#config.onBeforeActionResponse) {
try {
const processedOutput = this.#config.onBeforeActionResponse(
this.actorContext,
rpcName,
args,
output,
);
if (processedOutput instanceof Promise) {
logger().debug("awaiting onBeforeActionResponse", {
actionName: rpcName,
});
output = await processedOutput;
logger().debug("onBeforeActionResponse completed", {
actionName: rpcName,
});
} else {
output = processedOutput;
}
} catch (error) {
logger().error("error in `onBeforeRpcResponse`", {
error: stringifyError(error),
});
}
}
// Log the output before returning
logger().debug("action completed", {
actionName: rpcName,
outputType: typeof output,
isPromise: output instanceof Promise,
});
return output;
} catch (error) {
if (error instanceof DeadlineError) {
throw new errors.ActionTimedOut();
}
logger().error("action error", {
actionName: rpcName,
error: stringifyError(error),
});
throw error;
} finally {
this.#savePersistThrottled();
}
}
/**
* Returns a list of RPC methods available on this actor.
*/
get rpcs(): string[] {
return Object.keys(this.#config.actions);
}
// MARK: Lifecycle hooks
// MARK: Exposed methods
/**
* Gets the logger instance.
*/
get log(): Logger {
return instanceLogger();
}
/**
* Gets the name.
*/
get name(): string {
return this.#name;
}
/**
* Gets the tags.
*/
get tags(): ActorTags {
return this.#tags;
}
/**
* Gets the region.
*/
get region(): string {
return this.#region;
}
/**
* Gets the scheduler.
*/
get schedule(): Schedule {
return this.#schedule;
}
/**
* Gets the map of connections.
*/
get conns(): Map<ConnId, Conn<S, CP, CS, V>> {
return this.#connections;
}
/**
* Gets the current state.
*
* Changing properties of this value will automatically be persisted.
*/
get state(): S {
this.#validateStateEnabled();