@restatedev/sessions 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +52 -26
  2. package/dist/addon.d.ts +9 -0
  3. package/dist/addon.d.ts.map +1 -0
  4. package/dist/addon.js +20 -0
  5. package/dist/addon.js.map +1 -0
  6. package/dist/database.d.ts +13 -0
  7. package/dist/database.d.ts.map +1 -1
  8. package/dist/database.js +44 -17
  9. package/dist/database.js.map +1 -1
  10. package/dist/driver.d.ts +186 -0
  11. package/dist/driver.d.ts.map +1 -0
  12. package/dist/driver.js +549 -0
  13. package/dist/driver.js.map +1 -0
  14. package/dist/endpoint.d.ts +13 -0
  15. package/dist/endpoint.d.ts.map +1 -0
  16. package/dist/endpoint.js +186 -0
  17. package/dist/endpoint.js.map +1 -0
  18. package/dist/handler.d.ts +35 -0
  19. package/dist/handler.d.ts.map +1 -0
  20. package/dist/handler.js +218 -0
  21. package/dist/handler.js.map +1 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +2 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/internal.d.ts +4 -2
  26. package/dist/internal.d.ts.map +1 -1
  27. package/dist/internal.js +7 -3
  28. package/dist/internal.js.map +1 -1
  29. package/dist/object.d.ts +15 -2
  30. package/dist/object.d.ts.map +1 -1
  31. package/dist/object.js +51 -12
  32. package/dist/object.js.map +1 -1
  33. package/dist/serve.d.ts.map +1 -1
  34. package/dist/serve.js +5 -0
  35. package/dist/serve.js.map +1 -1
  36. package/dist/session.d.ts +32 -2
  37. package/dist/session.d.ts.map +1 -1
  38. package/dist/session.js +59 -9
  39. package/dist/session.js.map +1 -1
  40. package/dist/vm.d.ts +151 -0
  41. package/dist/vm.d.ts.map +1 -0
  42. package/dist/vm.js +28 -0
  43. package/dist/vm.js.map +1 -0
  44. package/package.json +4 -4
  45. package/src/addon.ts +29 -0
  46. package/src/database.ts +48 -19
  47. package/src/driver.ts +653 -0
  48. package/src/endpoint.ts +220 -0
  49. package/src/handler.ts +272 -0
  50. package/src/index.ts +2 -1
  51. package/src/internal.ts +7 -4
  52. package/src/object.ts +75 -13
  53. package/src/serve.ts +5 -0
  54. package/src/session.ts +77 -8
  55. package/src/vm.ts +195 -0
  56. package/dist/selector.d.ts +0 -129
  57. package/dist/selector.d.ts.map +0 -1
  58. package/dist/selector.js +0 -251
  59. package/dist/selector.js.map +0 -1
  60. package/src/selector.ts +0 -323
package/src/driver.ts ADDED
@@ -0,0 +1,653 @@
1
+ // One attempt of a session object's handler, on the explicit recovery VM
2
+ // (`vm.ts`, `native/src/vm.rs`).
3
+ //
4
+ // The VM never replays a journal: every attempt runs the handler from the
5
+ // start, and recovers from the state the earlier attempts stored. An action
6
+ // returns a handle, and its result comes back as a notification of that
7
+ // handle, which settles the action's promise here. Two things move the attempt
8
+ // along:
9
+ //
10
+ // - the input pump, the only reader of the request body: it hands the VM
11
+ // each chunk, and the end of the body;
12
+ // - the tick, scheduled after every call into the VM, at most one per turn
13
+ // of the event loop: it writes the VM's output, settles the promises of
14
+ // the actions that completed, and notices the end of the attempt.
15
+ //
16
+ // Scheduling a tick after every call batches the output of the actions issued
17
+ // in the same turn, and flushes it before the event loop can wait on anything.
18
+ //
19
+ // Restate shuts an attempt down by closing the request body, after its
20
+ // inactivity timeout. From then on the attempt is over: every action throws,
21
+ // the promises still pending reject, and a new attempt runs the handler from
22
+ // the start. See the heartbeats on what keeps an attempt at work alive.
23
+ import * as restate from '@restatedev/restate-sdk';
24
+ import { isShutDown, type Vm, type VmFailure, type VmInput, type VmNotification } from './vm.ts';
25
+
26
+ /**
27
+ * How often an attempt at work of its own tells Restate it makes progress, in
28
+ * milliseconds: RESTATE_SESSIONS_HEARTBEAT, or 20 seconds.
29
+ *
30
+ * Restate shuts down an attempt it has heard nothing from for its inactivity
31
+ * timeout, a minute by default, and 20 seconds is well inside that. A
32
+ * deployment that shortens the timeout
33
+ * (`RESTATE_WORKER__INVOKER__INACTIVITY_TIMEOUT`) must shorten this with it.
34
+ */
35
+ function heartbeatMs(): number {
36
+ const set = Number(process.env.RESTATE_SESSIONS_HEARTBEAT);
37
+ return Number.isFinite(set) && set > 0 ? set : 20_000;
38
+ }
39
+
40
+ /**
41
+ * Restate shut the attempt down: it is over, and a new attempt runs the
42
+ * handler from the start.
43
+ */
44
+ export class AttemptShutDown extends Error {
45
+ constructor() {
46
+ super('Restate shut the attempt down; a new attempt will run the handler from the start');
47
+ this.name = 'AttemptShutDown';
48
+ }
49
+ }
50
+
51
+ /** The attempt failed, and Restate retries it. */
52
+ export class AttemptFailed extends Error {
53
+ constructor(message: string) {
54
+ super(message);
55
+ this.name = 'AttemptFailed';
56
+ }
57
+ }
58
+
59
+ /** A failed action's terminal error, as the SDK's own, so that user code catches it. */
60
+ function terminal(failure: VmFailure): restate.TerminalError {
61
+ return new restate.TerminalError(failure.message, {
62
+ errorCode: failure.code,
63
+ metadata: Object.fromEntries(failure.metadata.map(({ key, value }) => [key, value])),
64
+ });
65
+ }
66
+
67
+ /**
68
+ * Keep an unawaited rejection from reaching the process: the attempt's end
69
+ * rejects every promise still waiting, and a handler that stopped awaiting one
70
+ * — a race it lost, say — would otherwise bring the process down. Attaching a
71
+ * handler marks the promise handled; the caller still sees the rejection.
72
+ */
73
+ function quiet<T>(promise: Promise<T>): Promise<T> {
74
+ promise.catch(() => {});
75
+ return promise;
76
+ }
77
+
78
+ /** What a notification settles its promise with. */
79
+ function settled(notification: VmNotification): { value: unknown } | { error: Error } {
80
+ switch (notification.kind) {
81
+ case 'void':
82
+ return { value: undefined };
83
+ case 'success':
84
+ return { value: notification.bytes };
85
+ case 'failure':
86
+ return { error: terminal(notification.failure) };
87
+ case 'stateKeys':
88
+ return { value: notification.keys };
89
+ case 'invocationId':
90
+ return { value: notification.id };
91
+ default:
92
+ // A kind this version does not know: no value, rather than an action
93
+ // whose promise stays pending forever.
94
+ return { value: undefined };
95
+ }
96
+ }
97
+
98
+ /** A call this attempt made: its invocation id, and whether it is over. */
99
+ interface Call {
100
+ id: Promise<string>;
101
+ done: boolean;
102
+ cancelled: boolean;
103
+ }
104
+
105
+ /** A promise waiting for the notification of a handle. */
106
+ interface Waiting {
107
+ resolve: (value: unknown) => void;
108
+ reject: (error: Error) => void;
109
+ /** What it is waiting for, which decides what a cancellation does to it. */
110
+ waits: Waits;
111
+ }
112
+
113
+ /**
114
+ * What a handle's promise is, which decides two things a cancellation does.
115
+ *
116
+ * - `result`: what the handler awaits for an answer. A cancellation nothing
117
+ * was waiting for is carried to the next of these, and never to the others:
118
+ * an id is what a handler is least likely to await, so carrying to one
119
+ * would let the action it belongs to run to completion unnoticed.
120
+ * - `callId`: a call's invocation id, which has to settle even through a
121
+ * cancellation, because cancelling the call needs it.
122
+ * - `sendId`: a send's invocation id. Nothing needs it once the invocation is
123
+ * cancelled, so a cancellation rejects it like any other wait — but it is
124
+ * usually voided, so it must not take the carry.
125
+ */
126
+ type Waits = 'result' | 'callId' | 'sendId';
127
+
128
+ /** What the attempt is of: the target it was invoked on, and how it handles cancellation. */
129
+ export interface AttemptOptions {
130
+ service: string;
131
+ handler: string;
132
+ /** A view: it reads beside the handlers, and writes nothing. */
133
+ shared?: boolean;
134
+ /**
135
+ * The handler stops its own work at a cancellation (`cancelled(ctx)`), so
136
+ * the attempt does not fail its awaits or cancel its calls for it.
137
+ */
138
+ explicitCancellation?: boolean;
139
+ }
140
+
141
+ /**
142
+ * Drives one attempt over its VM: the input pump, the tick, and the promises
143
+ * of the actions it issued.
144
+ */
145
+ export class AttemptDriver {
146
+ private readonly vm: Vm;
147
+ private readonly write: (chunk: Uint8Array) => void;
148
+ private readonly options: AttemptOptions;
149
+
150
+ /** Set once the attempt is over, to what ended it. */
151
+ private ended: Error | undefined;
152
+ private readonly waiting = new Map<number, Waiting>();
153
+ private readonly onEnd = new Set<() => void>();
154
+ private queued = false;
155
+ /** The calls this attempt made, by the handle of their result. */
156
+ private readonly calls = new Map<number, Call>();
157
+ /** Issuing the cancellations of the calls, which the handler's end waits for. */
158
+ private cancelling: Promise<void> | undefined;
159
+ private cancelledResolve: (() => void) | undefined;
160
+ /**
161
+ * A cancellation that failed nothing the handler awaits, carried to the
162
+ * next thing it does await: a result of Restate's ({@link promise}), or a
163
+ * call of its database ({@link takeCarriedCancellation}). A retry of a
164
+ * cancelled invocation knows it was cancelled before the handler starts,
165
+ * and its first call has to fail all the same, rather than run to
166
+ * completion.
167
+ *
168
+ * There is one, and it is here. The addon once carried a second for the
169
+ * database's waits, and the two could not agree on who had delivered: a
170
+ * handler saw one cancellation twice.
171
+ */
172
+ private carriedCancellation = false;
173
+ private readonly cancelledPromise: Promise<void>;
174
+ private heartbeats: ReturnType<typeof setInterval> | undefined;
175
+ private readonly aborter = new AbortController();
176
+ /**
177
+ * The invocation's input. Taking it from the VM copies the body across the
178
+ * addon, and the key, the body and the request each want it.
179
+ */
180
+ private theInput: VmInput | undefined;
181
+
182
+ constructor(vm: Vm, write: (chunk: Uint8Array) => void, options: AttemptOptions) {
183
+ this.vm = vm;
184
+ this.write = write;
185
+ this.options = options;
186
+ this.cancelledPromise = new Promise<void>((resolve) => {
187
+ this.cancelledResolve = resolve;
188
+ });
189
+ }
190
+
191
+ // --- Input and output
192
+
193
+ /** A chunk of the request body. */
194
+ notifyInput(chunk: Uint8Array): void {
195
+ this.vm.notifyInput(chunk);
196
+ this.schedule();
197
+ }
198
+
199
+ /** The end of the request body: while the handler runs, Restate shut the attempt down. */
200
+ notifyInputClosed(): void {
201
+ this.vm.notifyInputClosed();
202
+ this.schedule();
203
+ }
204
+
205
+ isReadyToExecute(): boolean {
206
+ return this.vm.isReadyToExecute();
207
+ }
208
+
209
+ /**
210
+ * Schedule a tick from outside: what the VM calls after the database's store
211
+ * acts on it from the runtime's thread, so that what it wrote is written and
212
+ * what it waits for is routed to it.
213
+ */
214
+ scheduleTick(): void {
215
+ this.schedule();
216
+ }
217
+
218
+ /** Schedule a tick, once per turn of the event loop. */
219
+ private schedule(): void {
220
+ if (this.queued) return;
221
+ this.queued = true;
222
+ queueMicrotask(() => (this.ended === undefined ? this.tick() : this.flush()));
223
+ }
224
+
225
+ /** Write what the VM has buffered. A closed attempt still flushes its last words. */
226
+ private flush(): void {
227
+ this.queued = false;
228
+ const output = this.vm.takeOutput();
229
+ if (output.length > 0) this.write(output);
230
+ }
231
+
232
+ /**
233
+ * Write the VM's output, settle the promises of the actions that completed,
234
+ * and notice the end of the attempt.
235
+ */
236
+ private tick(): void {
237
+ this.queued = false;
238
+ this.flush();
239
+ if (this.ended !== undefined) return;
240
+ let notification: VmNotification | null;
241
+ try {
242
+ while ((notification = this.vm.takeNotification()) !== null) {
243
+ // A call is over once its result arrives, whatever it is.
244
+ const call = this.calls.get(notification.handle);
245
+ if (call !== undefined) call.done = true;
246
+ const waiting = this.waiting.get(notification.handle);
247
+ // A handle this attempt did not issue, or settled already: nothing waits for it.
248
+ if (waiting === undefined) continue;
249
+ this.waiting.delete(notification.handle);
250
+ const result = settled(notification);
251
+ if ('error' in result) waiting.reject(result.error);
252
+ else waiting.resolve(result.value);
253
+ }
254
+ } catch (error) {
255
+ this.end(isShutDown(error) ? new AttemptShutDown() : new AttemptFailed(String(error)));
256
+ return;
257
+ }
258
+ // The VM says whether a cancellation arrived, in this attempt or an
259
+ // earlier one; it has no notification of its own.
260
+ if (this.vm.isCancelled()) this.cancelled();
261
+ if (this.vm.state() === 'closed') this.end(new AttemptShutDown());
262
+ }
263
+
264
+ /** The attempt ended: fail what still waits, and tell the listeners. */
265
+ private end(reason: Error): void {
266
+ if (this.ended !== undefined) return;
267
+ this.ended = reason;
268
+ const waiting = [...this.waiting.values()];
269
+ this.waiting.clear();
270
+ for (const one of waiting) one.reject(reason);
271
+ this.stopHeartbeats();
272
+ // Nothing will answer the database's outstanding reads now, and the
273
+ // scheduler holds this driver and the VM alive through the addon.
274
+ this.vm.endStateWaits();
275
+ this.vm.clearScheduler();
276
+ this.aborter.abort(reason);
277
+ const listeners = [...this.onEnd];
278
+ this.onEnd.clear();
279
+ for (const listener of listeners) listener();
280
+ }
281
+
282
+ /** Whether the attempt is over, and with what. */
283
+ get over(): Error | undefined {
284
+ return this.ended;
285
+ }
286
+
287
+ /** Call `listener` when the attempt ends; the returned function unregisters it. */
288
+ whenEnded(listener: () => void): () => void {
289
+ if (this.ended !== undefined) {
290
+ listener();
291
+ return () => {};
292
+ }
293
+ this.onEnd.add(listener);
294
+ return () => this.onEnd.delete(listener);
295
+ }
296
+
297
+ // --- Cancellation
298
+
299
+ /**
300
+ * Restate cancelled the invocation. A handler with `explicitCancellation`
301
+ * stops its own work and nothing else happens; otherwise the calls in flight
302
+ * are cancelled and every await of Restate fails, as a cancelled
303
+ * invocation's do.
304
+ */
305
+ private cancelled(): void {
306
+ const first = this.cancelledResolve !== undefined;
307
+ this.cancelledResolve?.();
308
+ this.cancelledResolve = undefined;
309
+ if (!first || this.options.explicitCancellation) return;
310
+ // What the database waits for in the addon — a state read, the ack of a
311
+ // commit's head write — is left to finish. Restate answers those
312
+ // promptly, and failing the ack of a head that is already out would
313
+ // report a commit as cancelled that landed. A call of the database that
314
+ // is in flight completes, and the cancellation goes to what the handler
315
+ // awaits next.
316
+ // The calls in flight are cancelled, which waits for the ids that have not
317
+ // arrived yet: `serveSession` holds the handler's end for it.
318
+ this.cancelling = quiet(this.cancelPreviousCalls().then(() => undefined));
319
+ const failure = new restate.CancelledError();
320
+ // Deleting the entry the loop is on is defined, and a rejection runs its
321
+ // handlers in a later microtask, so nothing is added under the iteration.
322
+ let failedAResult = false;
323
+ for (const [handle, waiting] of this.waiting) {
324
+ // A call's invocation id still settles: cancelling the call needs it.
325
+ if (waiting.waits === 'callId') continue;
326
+ if (waiting.waits === 'result') failedAResult = true;
327
+ this.waiting.delete(handle);
328
+ waiting.reject(failure);
329
+ }
330
+ // Carried only if nothing the handler awaits was failed. A send's id is
331
+ // in `waiting` and is rejected here, but `genericSend` voided it, so the
332
+ // handler saw no cancellation and is still owed its one.
333
+ this.carriedCancellation = !failedAResult;
334
+ }
335
+
336
+ /**
337
+ * Whether a cancellation is owed to the handler's next await, which the
338
+ * caller then delivers: the handler's call of its database, before it
339
+ * issues anything, so that a call that fails with the cancellation did
340
+ * nothing.
341
+ */
342
+ takeCarriedCancellation(): boolean {
343
+ const carried = this.carriedCancellation;
344
+ this.carriedCancellation = false;
345
+ return carried;
346
+ }
347
+
348
+ /** Issuing the cancellations of the calls, if a cancellation started them. */
349
+ get cancellingCalls(): Promise<void> | undefined {
350
+ return this.cancelling;
351
+ }
352
+
353
+ /** Resolves once a cancellation arrived, in this attempt or an earlier one. */
354
+ cancellation(): Promise<void> {
355
+ if (this.vm.isCancelled()) this.cancelled();
356
+ return this.cancelledPromise;
357
+ }
358
+
359
+ isCancelled(): boolean {
360
+ return this.vm.isCancelled();
361
+ }
362
+
363
+ /**
364
+ * Cancel the calls this attempt made that have not answered; returns their
365
+ * ids. A call whose invocation id has not arrived yet is waited for: it was
366
+ * made, so Restate will answer with its id, and leaving it uncancelled would
367
+ * leave an invocation running that nothing waits for any more.
368
+ */
369
+ async cancelPreviousCalls(): Promise<string[]> {
370
+ const cancelled: string[] = [];
371
+ // A snapshot: the loop awaits, and a call made meanwhile is the handler's
372
+ // own business, not one this cancellation set out to stop.
373
+ for (const call of Array.from(this.calls.values())) {
374
+ if (call.done || call.cancelled) continue;
375
+ let id: string;
376
+ try {
377
+ id = await call.id;
378
+ } catch {
379
+ continue; // its id never came: the attempt is over, or the call failed
380
+ }
381
+ if (call.done || call.cancelled) continue;
382
+ call.cancelled = true;
383
+ this.cancel(id);
384
+ cancelled.push(id);
385
+ }
386
+ return cancelled;
387
+ }
388
+
389
+ // --- Actions
390
+
391
+ /** Call the VM with `act`, then schedule a tick. The attempt's end throws. */
392
+ private act<T>(act: (vm: Vm) => T): T {
393
+ if (this.ended !== undefined) throw this.ended;
394
+ try {
395
+ return act(this.vm);
396
+ } catch (error) {
397
+ if (isShutDown(error)) {
398
+ this.end(new AttemptShutDown());
399
+ throw this.ended;
400
+ }
401
+ throw error;
402
+ } finally {
403
+ this.schedule();
404
+ }
405
+ }
406
+
407
+ /** The promise the notification of `handle` settles. */
408
+ private promise(handle: number, waits: Waits = 'result'): Promise<unknown> {
409
+ if (this.ended !== undefined) return quiet(Promise.reject(this.ended));
410
+ // Only a result takes it: see {@link Waits}.
411
+ if (this.carriedCancellation && waits === 'result') {
412
+ this.carriedCancellation = false;
413
+ return quiet(Promise.reject(new restate.CancelledError()));
414
+ }
415
+ return quiet(
416
+ new Promise<unknown>((resolve, reject) => {
417
+ this.waiting.set(handle, { resolve, reject, waits });
418
+ }),
419
+ );
420
+ }
421
+
422
+ /**
423
+ * A fire-and-forget action, which an attempt that ended simply drops. The
424
+ * database's store calls these from the addon, where a throw would reach no
425
+ * `catch` of ours and bring the process down; and a write of an attempt that
426
+ * is over cannot be sent anyway, since a new attempt writes it again.
427
+ */
428
+ private tell(act: (vm: Vm) => unknown): void {
429
+ if (this.ended !== undefined) return;
430
+ try {
431
+ this.act(act);
432
+ } catch {
433
+ // The attempt ended under us.
434
+ }
435
+ }
436
+
437
+ /** An action and the promise of its result, in one. */
438
+ private issue(act: (vm: Vm) => number): Promise<unknown> {
439
+ let handle: number;
440
+ try {
441
+ handle = this.act(act);
442
+ } catch (error) {
443
+ return quiet(Promise.reject(error instanceof Error ? error : new Error(String(error))));
444
+ }
445
+ return this.promise(handle);
446
+ }
447
+
448
+ // --- Calls
449
+
450
+ /** A call: the promise of its result, and of its invocation id. */
451
+ call(target: {
452
+ service: string;
453
+ handler: string;
454
+ key?: string;
455
+ input: Uint8Array;
456
+ idempotencyKey?: string;
457
+ headers?: { key: string; value: string }[];
458
+ name?: string;
459
+ }): { result: Promise<Uint8Array | null>; invocationId: Promise<string> } {
460
+ let handles: { invocationId: number; result: number };
461
+ try {
462
+ handles = this.act((vm) =>
463
+ vm.call(
464
+ target.service,
465
+ target.handler,
466
+ target.input,
467
+ target.key,
468
+ target.idempotencyKey,
469
+ target.headers,
470
+ target.name,
471
+ ),
472
+ );
473
+ } catch (error) {
474
+ const rejected = quiet(Promise.reject(error instanceof Error ? error : new Error(String(error))));
475
+ return { result: rejected, invocationId: rejected };
476
+ }
477
+ const invocationId = quiet(this.promise(handles.invocationId, 'callId').then((id) => String(id)));
478
+ const result = quiet(
479
+ this.promise(handles.result).then((value) => (value === undefined ? null : (value as Uint8Array))),
480
+ );
481
+ // Keyed by the result's handle, which is what says the call is over.
482
+ this.calls.set(handles.result, { id: invocationId, done: false, cancelled: false });
483
+ return { result, invocationId };
484
+ }
485
+
486
+ /** A send: the promise of the invocation id it was given. */
487
+ send(target: {
488
+ service: string;
489
+ handler: string;
490
+ key?: string;
491
+ input: Uint8Array;
492
+ delay?: number;
493
+ idempotencyKey?: string;
494
+ headers?: { key: string; value: string }[];
495
+ name?: string;
496
+ }): Promise<string> {
497
+ if (this.ended !== undefined) return quiet(Promise.reject(this.ended));
498
+ let handle: number;
499
+ try {
500
+ handle = this.act((vm) =>
501
+ vm.send(
502
+ target.service,
503
+ target.handler,
504
+ target.input,
505
+ target.key,
506
+ target.delay,
507
+ target.idempotencyKey,
508
+ target.headers,
509
+ target.name,
510
+ ),
511
+ );
512
+ } catch (error) {
513
+ // An attempt that ended drops it, as it drops a write: a new attempt
514
+ // sends it again. Anything else is the caller's — a delay that is not a
515
+ // number of milliseconds, say — and throws, as it does on the SDK's
516
+ // context, rather than vanishing into a promise nobody holds.
517
+ if (this.ended !== undefined) return quiet(Promise.reject(this.ended));
518
+ throw error;
519
+ }
520
+ return quiet(this.promise(handle, 'sendId').then((id) => String(id)));
521
+ }
522
+
523
+ /** The result of an invocation, once it ends. */
524
+ attach(invocationId: string, name?: string): Promise<Uint8Array | null> {
525
+ return quiet(
526
+ this.issue((vm) => vm.attachInvocation(invocationId, name)).then((value) =>
527
+ value === undefined ? null : (value as Uint8Array),
528
+ ),
529
+ );
530
+ }
531
+
532
+ cancel(invocationId: string, name?: string): void {
533
+ this.tell((vm) => vm.cancelInvocation(invocationId, name, false));
534
+ }
535
+
536
+ // --- Traces, shown in Restate's UI as runs
537
+
538
+ startTrace(name: string, parent?: number): number {
539
+ return this.act((vm) => vm.startTrace(name, parent));
540
+ }
541
+
542
+ endTrace(trace: number, output: Uint8Array): void {
543
+ this.act((vm) => vm.endTraceSuccess(trace, output));
544
+ }
545
+
546
+ // --- Keeping an attempt at work alive
547
+ //
548
+ // Restate shuts an attempt down once its inactivity timeout passes with
549
+ // nothing heard. A heartbeat stops that while the handler works outside
550
+ // Restate, on this rule: only while nothing of this attempt waits on
551
+ // Restate. With something
552
+ // waiting, a shutdown is what should happen — Restate starts a new attempt
553
+ // when the answer comes, instead of holding a connection open meanwhile.
554
+
555
+ /** Start the heartbeats of a running handler. */
556
+ startHeartbeats(everyMs = heartbeatMs()): void {
557
+ if (this.heartbeats !== undefined || this.ended !== undefined) return;
558
+ this.heartbeats = setInterval(() => {
559
+ if (this.ended !== undefined || this.waiting.size > 0) return;
560
+ try {
561
+ this.act((vm) => vm.heartbeat());
562
+ } catch {
563
+ // The attempt ended: the tick notices.
564
+ }
565
+ }, everyMs);
566
+ this.heartbeats.unref?.();
567
+ }
568
+
569
+ private stopHeartbeats(): void {
570
+ if (this.heartbeats === undefined) return;
571
+ clearInterval(this.heartbeats);
572
+ this.heartbeats = undefined;
573
+ }
574
+
575
+ // --- The input, and the end
576
+
577
+ /** The invocation's input, read from the VM once. */
578
+ private input(): VmInput {
579
+ this.theInput ??= this.vm.input();
580
+ return this.theInput;
581
+ }
582
+
583
+ /** The invocation's key, once the VM is ready to execute. */
584
+ get key(): string {
585
+ return this.input().key;
586
+ }
587
+
588
+ /** The handler's input. */
589
+ get body(): Uint8Array {
590
+ return this.input().input;
591
+ }
592
+
593
+ /** The invocation's request, as a handler's `ctx.request` has it. */
594
+ request(attemptHeaders: ReadonlyMap<string, string | string[] | undefined> = new Map()): restate.Request {
595
+ const input = this.input();
596
+ const target = {
597
+ service: this.options.service,
598
+ handler: this.options.handler,
599
+ key: input.key || undefined,
600
+ toString(): string {
601
+ return this.key === undefined
602
+ ? `${this.service}/${this.handler}`
603
+ : `${this.service}/${this.key}/${this.handler}`;
604
+ },
605
+ };
606
+ return {
607
+ target,
608
+ id: input.invocationId,
609
+ headers: new Map(input.headers.map(({ key, value }) => [key, value])),
610
+ attemptHeaders,
611
+ body: input.input,
612
+ extraArgs: [],
613
+ idempotencyKey: input.idempotencyKey,
614
+ scope: input.scope,
615
+ limitKey: input.limitKey,
616
+ attemptCompletedSignal: this.aborter.signal,
617
+ } as unknown as restate.Request;
618
+ }
619
+
620
+ /** The handler ended with its output. */
621
+ endSuccess(output: Uint8Array): void {
622
+ this.last((vm) => vm.endSuccess(output));
623
+ }
624
+
625
+ /** The handler ended with a terminal failure. */
626
+ endFailure(error: restate.TerminalError): void {
627
+ this.last((vm) =>
628
+ vm.endFailure({
629
+ code: (error as { code?: number }).code ?? 500,
630
+ message: error.message,
631
+ metadata: Object.entries(error.metadata ?? {}).map(([key, value]) => ({ key, value })),
632
+ }),
633
+ );
634
+ }
635
+
636
+ /** The attempt failed, and Restate retries it. */
637
+ fail(message: string, stacktrace?: string, retryAfterMs?: number): void {
638
+ if (this.ended !== undefined) return;
639
+ this.vm.notifyError(message, stacktrace, retryAfterMs);
640
+ this.schedule();
641
+ }
642
+
643
+ /** End the attempt with `act`, unless it ended already. */
644
+ private last(act: (vm: Vm) => void): void {
645
+ if (this.ended !== undefined) return;
646
+ try {
647
+ act(this.vm);
648
+ } catch {
649
+ // The attempt ended under us: the VM wrote why.
650
+ }
651
+ this.schedule();
652
+ }
653
+ }