@restatedev/sessions 0.11.2 → 0.12.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 (96) hide show
  1. package/README.md +330 -178
  2. package/dist/addon.d.ts +1 -0
  3. package/dist/addon.d.ts.map +1 -1
  4. package/dist/addon.js.map +1 -1
  5. package/dist/calls.d.ts +28 -28
  6. package/dist/calls.d.ts.map +1 -1
  7. package/dist/calls.js +25 -25
  8. package/dist/calls.js.map +1 -1
  9. package/dist/database.d.ts +90 -166
  10. package/dist/database.d.ts.map +1 -1
  11. package/dist/database.js +137 -249
  12. package/dist/database.js.map +1 -1
  13. package/dist/driver.d.ts +129 -126
  14. package/dist/driver.d.ts.map +1 -1
  15. package/dist/driver.js +337 -276
  16. package/dist/driver.js.map +1 -1
  17. package/dist/endpoint.d.ts +47 -5
  18. package/dist/endpoint.d.ts.map +1 -1
  19. package/dist/endpoint.js +175 -60
  20. package/dist/endpoint.js.map +1 -1
  21. package/dist/handler.d.ts +20 -17
  22. package/dist/handler.d.ts.map +1 -1
  23. package/dist/handler.js +161 -127
  24. package/dist/handler.js.map +1 -1
  25. package/dist/host.d.ts +29 -0
  26. package/dist/host.d.ts.map +1 -0
  27. package/dist/host.js +2 -0
  28. package/dist/host.js.map +1 -0
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +5 -26
  32. package/dist/index.js.map +1 -1
  33. package/dist/internal.d.ts +11 -11
  34. package/dist/internal.d.ts.map +1 -1
  35. package/dist/internal.js +20 -16
  36. package/dist/internal.js.map +1 -1
  37. package/dist/link.d.ts +1 -2
  38. package/dist/link.d.ts.map +1 -1
  39. package/dist/link.js +4 -5
  40. package/dist/link.js.map +1 -1
  41. package/dist/log.d.ts +14 -0
  42. package/dist/log.d.ts.map +1 -0
  43. package/dist/log.js +21 -0
  44. package/dist/log.js.map +1 -0
  45. package/dist/object.d.ts +217 -142
  46. package/dist/object.d.ts.map +1 -1
  47. package/dist/object.js +195 -241
  48. package/dist/object.js.map +1 -1
  49. package/dist/platform.d.ts +0 -1
  50. package/dist/platform.d.ts.map +1 -1
  51. package/dist/platform.js +4 -6
  52. package/dist/platform.js.map +1 -1
  53. package/dist/schema.d.ts +14 -22
  54. package/dist/schema.d.ts.map +1 -1
  55. package/dist/schema.js +31 -69
  56. package/dist/schema.js.map +1 -1
  57. package/dist/serve.d.ts +11 -17
  58. package/dist/serve.d.ts.map +1 -1
  59. package/dist/serve.js +21 -39
  60. package/dist/serve.js.map +1 -1
  61. package/dist/session.d.ts +58 -240
  62. package/dist/session.d.ts.map +1 -1
  63. package/dist/session.js +206 -532
  64. package/dist/session.js.map +1 -1
  65. package/dist/stop.d.ts +59 -0
  66. package/dist/stop.d.ts.map +1 -0
  67. package/dist/stop.js +220 -0
  68. package/dist/stop.js.map +1 -0
  69. package/dist/vm.d.ts +108 -29
  70. package/dist/vm.d.ts.map +1 -1
  71. package/dist/vm.js +43 -10
  72. package/dist/vm.js.map +1 -1
  73. package/package.json +4 -4
  74. package/src/addon.ts +1 -0
  75. package/src/calls.ts +51 -47
  76. package/src/database.ts +195 -339
  77. package/src/driver.ts +379 -315
  78. package/src/endpoint.ts +217 -62
  79. package/src/handler.ts +183 -164
  80. package/src/host.ts +28 -0
  81. package/src/index.ts +6 -26
  82. package/src/internal.ts +28 -39
  83. package/src/link.ts +4 -5
  84. package/src/log.ts +42 -0
  85. package/src/object.ts +379 -335
  86. package/src/platform.ts +4 -6
  87. package/src/schema.ts +37 -103
  88. package/src/serve.ts +20 -41
  89. package/src/session.ts +236 -629
  90. package/src/stop.ts +225 -0
  91. package/src/vm.ts +151 -55
  92. package/dist/scope.d.ts +0 -38
  93. package/dist/scope.d.ts.map +0 -1
  94. package/dist/scope.js +0 -55
  95. package/dist/scope.js.map +0 -1
  96. package/src/scope.ts +0 -78
package/src/driver.ts CHANGED
@@ -1,46 +1,89 @@
1
- // One attempt of a session object's handler, on the explicit recovery VM
2
- // (`vm.ts`, `native/src/vm.rs`).
1
+ // One attempt of a session object's handler, on the explicit recovery
2
+ // protocol's VM (`vm.ts`, `native/src/vm.rs`).
3
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
4
+ // The protocol has no journal: every attempt runs the handler from its first
5
+ // line, and recovers from the state the earlier attempts stored. An action
6
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:
7
+ // handle, which settles the action's promise here. So the handler can await
8
+ // actions in any combination (`Promise.all`, `Promise.race`).
9
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.
10
+ // Two things move the attempt forward:
11
+ // - The input pump (handler.ts) is the only reader of the request body. It
12
+ // passes each chunk, and the end of the body, to the VM.
13
+ // - The tick runs after every call into the VM, at most once per microtask
14
+ // turn. It writes the VM's output, settles the promises of the actions that
15
+ // completed, and notices the end of the attempt. It is the only place
16
+ // notifications are taken: taking one is processing it, and it counts in
17
+ // the `ShutdownMessage` of an attempt shut down. The cancel signal is the
18
+ // notification of the reserved handle 1.
18
19
  //
19
20
  // 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, unless work in `working` keeps the attempt alive.
21
+ // inactivity timeout; the VM answers with `ShutdownMessage` at once. From then
22
+ // on every action throws, pending promises reject with the reason, the stop
23
+ // signal and `request.attemptCompletedSignal` abort, and Restate decides what
24
+ // follows: it suspends the invocation if a result is outstanding, and starts
25
+ // a new attempt at once otherwise. After the attempt's last message Restate
26
+ // closes its side first, and the response closes after it (`whenClosable`). A
27
+ // process going away ends its attempts with an unasked `ShutdownMessage`
28
+ // (`goAway`).
29
+ //
30
+ // Heartbeats keep Restate from shutting the attempt down while a keep-alive
31
+ // scope is open (see stop.ts). One timer serves them and outlives a run of
32
+ // scopes, so the per-statement database keep-alive does not arm and clear a
33
+ // timer each time. It re-arms only while a scope is open, and beats only after
34
+ // a full interval with nothing written: silence never reaches twice that.
35
+ import { AsyncLocalStorage } from 'node:async_hooks';
23
36
  import * as restate from '@restatedev/restate-sdk';
24
- import { isShutDown, type Vm, type VmFailure, type VmInput, type VmNotification } from './vm.ts';
37
+ import type { SessionRequest } from './object.ts';
38
+ import { Stop } from './stop.ts';
39
+ import {
40
+ invalidInput,
41
+ isShutDown,
42
+ type Vm,
43
+ type VmActionOptions,
44
+ type VmFailure,
45
+ type VmInput,
46
+ type VmNotification,
47
+ type VmScope,
48
+ } from './vm.ts';
49
+
50
+ /** Restate's inactivity timeout when neither the handler nor its object sets one: the server's default. */
51
+ export const DEFAULT_INACTIVITY_TIMEOUT_MS = 60_000;
52
+
53
+ /** The longest delay a timer holds: Node runs a longer one after 1 ms. */
54
+ export const MAX_TIMER_MS = 2 ** 31 - 1;
25
55
 
26
56
  /**
27
- * How often an attempt in `working` tells Restate it makes progress, in
28
- * milliseconds: RESTATE_SESSIONS_HEARTBEAT, or 20 seconds.
57
+ * How often an attempt with a keep-alive scope open tells Restate it makes
58
+ * progress, in milliseconds: RESTATE_SESSIONS_HEARTBEAT if it is a positive
59
+ * number, else a third of the handler's inactivity timeout
60
+ * (`inactivityTimeoutMs`, a minute when it sets none); never more than a
61
+ * timer holds ({@link MAX_TIMER_MS}).
29
62
  *
30
63
  * 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.
64
+ * timeout, and a third of it leaves room for a late beat. A timeout set only
65
+ * on the server, or on the endpoint's default service options, is not seen
66
+ * here: a deployment that shortens it there must shorten this with it.
34
67
  */
35
- function heartbeatMs(): number {
68
+ export function heartbeatMs(inactivityTimeoutMs?: number): number {
36
69
  const set = Number(process.env.RESTATE_SESSIONS_HEARTBEAT);
37
- return Number.isFinite(set) && set > 0 ? set : 20_000;
70
+ if (Number.isFinite(set) && set > 0) return Math.min(set, MAX_TIMER_MS);
71
+ const timeout =
72
+ inactivityTimeoutMs !== undefined && Number.isFinite(inactivityTimeoutMs) && inactivityTimeoutMs > 0
73
+ ? inactivityTimeoutMs
74
+ : DEFAULT_INACTIVITY_TIMEOUT_MS;
75
+ return Math.min(MAX_TIMER_MS, Math.max(1, Math.floor(timeout / 3)));
38
76
  }
39
77
 
40
78
  /**
41
- * Restate shut the attempt down: it is over, and a new attempt runs the
42
- * handler from the start.
79
+ * A value user code passed to an action is one Restate would refuse as
80
+ * malformed (an invocation id that is not one, an empty idempotency key), as
81
+ * the VM checks it (code 400). That action fails alone: nothing was sent, the
82
+ * attempt goes on, and user code may catch it as any `TerminalError`.
43
83
  */
84
+ export class InvalidInput extends restate.TerminalError {}
85
+
86
+ /** Restate shut the attempt down. A new attempt runs the handler from the start. */
44
87
  export class AttemptShutDown extends Error {
45
88
  constructor() {
46
89
  super('Restate shut the attempt down; a new attempt will run the handler from the start');
@@ -56,7 +99,7 @@ export class AttemptFailed extends Error {
56
99
  }
57
100
  }
58
101
 
59
- /** A failed action's terminal error, as the SDK's own, so that user code catches it. */
102
+ /** A failed action as the SDK's `TerminalError`, so that user code catches it. */
60
103
  function terminal(failure: VmFailure): restate.TerminalError {
61
104
  return new restate.TerminalError(failure.message, {
62
105
  errorCode: failure.code,
@@ -65,17 +108,14 @@ function terminal(failure: VmFailure): restate.TerminalError {
65
108
  }
66
109
 
67
110
  /**
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.
111
+ * Mark `promise` handled: the end of the attempt rejects every pending promise,
112
+ * and one nobody awaits (a lost race) would crash the process.
72
113
  */
73
- function quiet<T>(promise: Promise<T>): Promise<T> {
114
+ export function quiet<T>(promise: Promise<T>): Promise<T> {
74
115
  promise.catch(() => {});
75
116
  return promise;
76
117
  }
77
118
 
78
- /** What a notification settles its promise with. */
79
119
  function settled(notification: VmNotification): { value: unknown } | { error: Error } {
80
120
  switch (notification.kind) {
81
121
  case 'void':
@@ -89,59 +129,42 @@ function settled(notification: VmNotification): { value: unknown } | { error: Er
89
129
  case 'invocationId':
90
130
  return { value: notification.id };
91
131
  default:
92
- // A kind this version does not know: no value, rather than an action
93
- // whose promise stays pending forever.
132
+ // An unknown kind settles with no value rather than leaving the promise pending forever.
94
133
  return { value: undefined };
95
134
  }
96
135
  }
97
136
 
98
- /** A call this attempt made: its invocation id, and whether it is over. */
99
137
  interface Call {
100
138
  id: Promise<string>;
101
139
  done: boolean;
102
140
  cancelled: boolean;
103
141
  }
104
142
 
105
- /** A promise waiting for the notification of a handle. */
143
+ /**
144
+ * `spared` marks a wait a cancellation does not reject: a call's invocation
145
+ * id, which cancelling the call needs, and the session's own waits (an
146
+ * invocation-state read, a flush).
147
+ */
106
148
  interface Waiting {
107
149
  resolve: (value: unknown) => void;
108
150
  reject: (error: Error) => void;
109
- /** What it is waiting for, which decides what a cancellation does to it. */
110
- waits: Waits;
151
+ spared: boolean;
111
152
  }
112
153
 
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
154
  /** What the attempt is of: the target it was invoked on, and how it handles cancellation. */
129
155
  export interface AttemptOptions {
130
156
  service: string;
131
157
  handler: string;
132
- /** A view: it reads beside the handlers, and writes nothing. */
133
- shared?: boolean;
158
+ /** The handler stops its own work on the stop signal (see stop.ts). */
159
+ explicitCancellation?: boolean;
134
160
  /**
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.
161
+ * Restate's inactivity timeout for this handler, in milliseconds, as the
162
+ * handler or its object sets it: the heartbeat interval is a third of it
163
+ * (see {@link heartbeatMs}).
137
164
  */
138
- explicitCancellation?: boolean;
165
+ inactivityTimeoutMs?: number;
139
166
  }
140
167
 
141
- /**
142
- * Drives one attempt over its VM: the input pump, the tick, and the promises
143
- * of the actions it issued.
144
- */
145
168
  export class AttemptDriver {
146
169
  private readonly vm: Vm;
147
170
  private readonly write: (chunk: Uint8Array) => void;
@@ -150,69 +173,47 @@ export class AttemptDriver {
150
173
  /** Set once the attempt is over, to what ended it. */
151
174
  private ended: Error | undefined;
152
175
  private readonly waiting = new Map<number, Waiting>();
153
- private readonly onEnd = new Set<() => void>();
176
+ private readonly onClosable = new Set<() => void>();
177
+ private isClosable = false;
154
178
  private queued = false;
155
- /** The calls this attempt made, by the handle of their result. */
179
+ /** The reserved handle of the cancel signal. */
180
+ private readonly cancelHandle: number;
181
+ /** The span the code running now is inside of: actions it makes are inside it too. */
182
+ private readonly span = new AsyncLocalStorage<number>();
183
+ /** The calls this attempt made, keyed by the handle of their result. */
156
184
  private readonly calls = new Map<number, Call>();
157
- /** Issuing the cancellations of the calls, which the handler's end waits for. */
185
+ /** Issuing the cancellations of the calls; the handler's end waits for it. */
158
186
  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
- /**
175
- * The one timer of the heartbeats, armed for `beatDue`. It outlives a run of
176
- * scopes, so the database's scopes (one a statement) do not start and clear
177
- * a timer each: it fires, finds no scope open, and is not armed again.
178
- */
187
+ private cancellationIn = false;
188
+ /** The one cancellation, stop signal and keep-alive scopes of this attempt: see stop.ts. */
189
+ readonly stop = new Stop(() => this.startHeartbeats());
179
190
  private heartbeats: ReturnType<typeof setTimeout> | undefined;
180
- private beatDue = 0;
181
- /** The `working` scopes open: the attempt heartbeats while there is one. */
182
- private scopes = 0;
183
- /** The run of scopes now open: when the first opened, and its interval. */
184
- private runEvery = 0;
185
- /** When the run's next heartbeat is due. */
186
- private nextBeat = 0;
187
- /** The heartbeat interval, read from the environment on first use. */
188
- private beatEvery: number | undefined;
189
- /** When the attempt last wrote to Restate, which restarts Restate's inactivity timer. */
191
+ /** The heartbeat interval, read once as the attempt starts (see {@link heartbeatMs}). */
192
+ private readonly interval: number;
193
+ /** Any write restarts Restate's inactivity timer. */
190
194
  private wroteAt = Date.now();
191
195
  private readonly aborter = new AbortController();
192
- /**
193
- * The invocation's input. Taking it from the VM copies the body across the
194
- * addon, and the key, the body and the request each want it.
195
- */
196
+ /** The request's `attemptCompletedSignal`: aborts with what ended the attempt. */
197
+ readonly completed: AbortSignal = this.aborter.signal;
198
+ /** Read once: taking the input copies the body across the addon. */
196
199
  private theInput: VmInput | undefined;
197
200
 
198
201
  constructor(vm: Vm, write: (chunk: Uint8Array) => void, options: AttemptOptions) {
199
202
  this.vm = vm;
200
203
  this.write = write;
201
204
  this.options = options;
202
- this.cancelledPromise = new Promise<void>((resolve) => {
203
- this.cancelledResolve = resolve;
204
- });
205
+ this.cancelHandle = vm.cancelHandle();
206
+ this.interval = heartbeatMs(options.inactivityTimeoutMs);
205
207
  }
206
208
 
207
209
  // --- Input and output
208
210
 
209
- /** A chunk of the request body. */
210
211
  notifyInput(chunk: Uint8Array): void {
211
212
  this.vm.notifyInput(chunk);
212
213
  this.schedule();
213
214
  }
214
215
 
215
- /** The end of the request body: while the handler runs, Restate shut the attempt down. */
216
+ /** The end of the request body. While the handler runs, this means Restate shut the attempt down. */
216
217
  notifyInputClosed(): void {
217
218
  this.vm.notifyInputClosed();
218
219
  this.schedule();
@@ -222,47 +223,83 @@ export class AttemptDriver {
222
223
  return this.vm.isReadyToExecute();
223
224
  }
224
225
 
225
- /**
226
- * Schedule a tick from outside: what the VM calls after the database's store
227
- * acts on it from the runtime's thread, so that what it wrote is written and
228
- * what it waits for is routed to it.
229
- */
226
+ /** Called by the VM after the database store acted on it from the runtime thread. */
230
227
  scheduleTick(): void {
231
228
  this.schedule();
232
229
  }
233
230
 
234
- /** Schedule a tick, once per turn of the event loop. */
235
231
  private schedule(): void {
236
232
  if (this.queued) return;
237
233
  this.queued = true;
238
234
  queueMicrotask(() => (this.ended === undefined ? this.tick() : this.flush()));
239
235
  }
240
236
 
241
- /** Write what the VM has buffered. A closed attempt still flushes its last words. */
237
+ /**
238
+ * Write what the VM has buffered. A closed attempt still flushes its last
239
+ * output, and then, once Restate closed its side too, the response may close.
240
+ */
242
241
  private flush(): void {
243
242
  this.queued = false;
244
243
  const output = this.vm.takeOutput();
245
- if (output.length === 0) return;
246
- this.write(output);
247
- this.wroteAt = Date.now();
244
+ if (output.length > 0) {
245
+ this.write(output);
246
+ this.wroteAt = Date.now();
247
+ }
248
+ if (this.vm.shouldCloseOutput()) this.closable();
249
+ }
250
+
251
+ /** The response may close now: tell the listeners, once. */
252
+ private closable(): void {
253
+ const listeners = [...this.onClosable];
254
+ this.onClosable.clear();
255
+ this.isClosable = true;
256
+ for (const listener of listeners) listener();
248
257
  }
249
258
 
250
259
  /**
251
- * Write the VM's output, settle the promises of the actions that completed,
252
- * and notice the end of the attempt.
260
+ * Call `listener` once the response may close: the attempt's last message
261
+ * is written and Restate closed its side (Restate closes first).
253
262
  */
263
+ whenClosable(listener: () => void): void {
264
+ if (this.isClosable) listener();
265
+ else this.onClosable.add(listener);
266
+ }
267
+
268
+ /**
269
+ * The process is going away (SIGTERM): end a running attempt with an
270
+ * unasked `ShutdownMessage`, after which Restate starts a new attempt
271
+ * elsewhere, and write it. The caller closes the response.
272
+ */
273
+ goAway(): void {
274
+ if (this.vm.state() !== 'closed') this.vm.shutdown();
275
+ this.tick();
276
+ this.end(this.ended ?? new AttemptShutDown());
277
+ this.flush();
278
+ }
279
+
254
280
  private tick(): void {
255
281
  this.queued = false;
256
282
  this.flush();
257
283
  if (this.ended !== undefined) return;
284
+ // The actions of an atomic group the store aborted in the addon: never notified.
285
+ for (const handle of this.vm.takeAborted()) {
286
+ const waiting = this.waiting.get(handle);
287
+ if (waiting === undefined) continue;
288
+ this.waiting.delete(handle);
289
+ waiting.reject(new Error('the atomic group of this action was aborted'));
290
+ }
258
291
  let notification: VmNotification | null;
259
292
  try {
260
293
  while ((notification = this.vm.takeNotification()) !== null) {
294
+ if (notification.handle === this.cancelHandle) {
295
+ this.cancelled();
296
+ continue;
297
+ }
261
298
  // A call is over once its result arrives, whatever it is.
262
299
  const call = this.calls.get(notification.handle);
263
300
  if (call !== undefined) call.done = true;
264
301
  const waiting = this.waiting.get(notification.handle);
265
- // A handle this attempt did not issue, or settled already: nothing waits for it.
302
+ // A handle nothing waits for (a send's invocation id), or settled already.
266
303
  if (waiting === undefined) continue;
267
304
  this.waiting.delete(notification.handle);
268
305
  const result = settled(notification);
@@ -271,15 +308,15 @@ export class AttemptDriver {
271
308
  }
272
309
  } catch (error) {
273
310
  this.end(isShutDown(error) ? new AttemptShutDown() : new AttemptFailed(String(error)));
311
+ this.flush();
274
312
  return;
275
313
  }
276
- // The VM says whether a cancellation arrived, in this attempt or an
277
- // earlier one; it has no notification of its own.
314
+ // Cancelled before this attempt (`StartMessage.cancelled`): the VM knows
315
+ // from the start, and no notification comes.
278
316
  if (this.vm.isCancelled()) this.cancelled();
279
317
  if (this.vm.state() === 'closed') this.end(new AttemptShutDown());
280
318
  }
281
319
 
282
- /** The attempt ended: fail what still waits, and tell the listeners. */
283
320
  private end(reason: Error): void {
284
321
  if (this.ended !== undefined) return;
285
322
  this.ended = reason;
@@ -287,111 +324,58 @@ export class AttemptDriver {
287
324
  this.waiting.clear();
288
325
  for (const one of waiting) one.reject(reason);
289
326
  this.stopHeartbeats();
290
- // Nothing will answer the database's outstanding reads now, and the
291
- // scheduler holds this driver and the VM alive through the addon.
327
+ // Nothing will answer the database's pending reads now. The scheduler
328
+ // would keep this driver and the VM alive through the addon.
292
329
  this.vm.endStateWaits();
293
330
  this.vm.clearScheduler();
331
+ // After `ended` is set, so nothing the stopping work does is stored. Before the request's signal, so a call
332
+ // its listeners make is not failed by an owed cancellation.
333
+ this.stop.end(reason);
294
334
  this.aborter.abort(reason);
295
- const listeners = [...this.onEnd];
296
- this.onEnd.clear();
297
- for (const listener of listeners) listener();
298
335
  }
299
336
 
300
- /** Whether the attempt is over, and with what. */
301
337
  get over(): Error | undefined {
302
338
  return this.ended;
303
339
  }
304
340
 
305
- /** Call `listener` when the attempt ends; the returned function unregisters it. */
306
- whenEnded(listener: () => void): () => void {
307
- if (this.ended !== undefined) {
308
- listener();
309
- return () => {};
310
- }
311
- this.onEnd.add(listener);
312
- return () => this.onEnd.delete(listener);
313
- }
314
-
315
341
  // --- Cancellation
316
342
 
317
- /**
318
- * Restate cancelled the invocation. A handler with `explicitCancellation`
319
- * stops its own work and nothing else happens; otherwise the calls in flight
320
- * are cancelled and every await of Restate fails, as a cancelled
321
- * invocation's do.
322
- */
343
+ /** Restate cancelled the invocation: cancel the calls in flight and reject pending results (see stop.ts). */
323
344
  private cancelled(): void {
324
- const first = this.cancelledResolve !== undefined;
325
- this.cancelledResolve?.();
326
- this.cancelledResolve = undefined;
327
- if (!first || this.options.explicitCancellation) return;
328
- // What the database waits for in the addon — a state read, the ack of a
329
- // commit's head write — is left to finish. Restate answers those
330
- // promptly, and failing the ack of a head that is already out would
331
- // report a commit as cancelled that landed. A call of the database that
332
- // is in flight completes, and the cancellation goes to what the handler
333
- // awaits next.
334
- // The calls in flight are cancelled, which waits for the ids that have not
335
- // arrived yet: `serveSession` holds the handler's end for it.
345
+ if (this.cancellationIn) return;
346
+ this.cancellationIn = true;
347
+ if (this.options.explicitCancellation) {
348
+ this.stop.cancel({ signalOnly: true });
349
+ return;
350
+ }
351
+ // Database waits in the addon are left to finish: Restate answers them promptly, and failing
352
+ // the result of a commit's group already sent would report a landed commit as cancelled.
353
+ // `serveSession` holds the handler's end until the cancellations are issued.
336
354
  this.cancelling = quiet(this.cancelPreviousCalls().then(() => undefined));
337
355
  const failure = new restate.CancelledError();
338
- // Deleting the entry the loop is on is defined, and a rejection runs its
339
- // handlers in a later microtask, so nothing is added under the iteration.
356
+ // Deleting the current entry during iteration is safe, and rejection
357
+ // handlers run in a later microtask, so nothing is added meanwhile.
340
358
  let failedAResult = false;
341
359
  for (const [handle, waiting] of this.waiting) {
342
- // A call's invocation id still settles: cancelling the call needs it.
343
- if (waiting.waits === 'callId') continue;
344
- if (waiting.waits === 'result') failedAResult = true;
360
+ if (waiting.spared) continue;
361
+ failedAResult = true;
345
362
  this.waiting.delete(handle);
346
363
  waiting.reject(failure);
347
364
  }
348
- // Carried only if nothing the handler awaits was failed. A send's id is
349
- // in `waiting` and is rejected here, but `genericSend` voided it, so the
350
- // handler saw no cancellation and is still owed its one.
351
- this.carriedCancellation = !failedAResult;
365
+ this.stop.cancel({ failedAnAwait: failedAResult });
352
366
  }
353
367
 
354
- /**
355
- * Whether a cancellation is owed to the handler's next await, which the
356
- * caller then delivers: the handler's call of its database, before it
357
- * issues anything, so that a call that fails with the cancellation did
358
- * nothing.
359
- */
360
- takeCarriedCancellation(): boolean {
361
- // The attempt is over: what the handler does then fails with that, as
362
- // its awaits of Restate do, and the attempt that follows gets the
363
- // cancellation.
364
- if (this.ended !== undefined) return false;
365
- const carried = this.carriedCancellation;
366
- this.carriedCancellation = false;
367
- return carried;
368
- }
369
-
370
- /** Issuing the cancellations of the calls, if a cancellation started them. */
371
368
  get cancellingCalls(): Promise<void> | undefined {
372
369
  return this.cancelling;
373
370
  }
374
371
 
375
- /** Resolves once a cancellation arrived, in this attempt or an earlier one. */
376
- cancellation(): Promise<void> {
377
- if (this.vm.isCancelled()) this.cancelled();
378
- return this.cancelledPromise;
379
- }
380
-
381
- isCancelled(): boolean {
382
- return this.vm.isCancelled();
383
- }
384
-
385
372
  /**
386
- * Cancel the calls this attempt made that have not answered; returns their
387
- * ids. A call whose invocation id has not arrived yet is waited for: it was
388
- * made, so Restate will answer with its id, and leaving it uncancelled would
389
- * leave an invocation running that nothing waits for any more.
373
+ * Cancel the calls that have not answered. A call whose id has not arrived
374
+ * is waited for: an uncancelled callee would run on with nothing waiting.
390
375
  */
391
- async cancelPreviousCalls(): Promise<string[]> {
376
+ private async cancelPreviousCalls(): Promise<string[]> {
392
377
  const cancelled: string[] = [];
393
- // A snapshot: the loop awaits, and a call made meanwhile is the handler's
394
- // own business, not one this cancellation set out to stop.
378
+ // A snapshot: a call made while this loop awaits is not one this cancellation set out to stop.
395
379
  for (const call of Array.from(this.calls.values())) {
396
380
  if (call.done || call.cancelled) continue;
397
381
  let id: string;
@@ -410,7 +394,7 @@ export class AttemptDriver {
410
394
 
411
395
  // --- Actions
412
396
 
413
- /** Call the VM with `act`, then schedule a tick. The attempt's end throws. */
397
+ /** Call the VM, then schedule a tick. Throws once the attempt has ended, and an invalid input as a TerminalError. */
414
398
  private act<T>(act: (vm: Vm) => T): T {
415
399
  if (this.ended !== undefined) throw this.ended;
416
400
  try {
@@ -420,56 +404,90 @@ export class AttemptDriver {
420
404
  this.end(new AttemptShutDown());
421
405
  throw this.ended;
422
406
  }
407
+ const refused = invalidInput(error);
408
+ if (refused !== undefined) throw new InvalidInput(refused.message, { errorCode: refused.code });
423
409
  throw error;
424
410
  } finally {
425
411
  this.schedule();
426
412
  }
427
413
  }
428
414
 
429
- /** The promise the notification of `handle` settles. */
430
- private promise(handle: number, waits: Waits = 'result'): Promise<unknown> {
415
+ private promise(handle: number, spared = false): Promise<unknown> {
431
416
  if (this.ended !== undefined) return quiet(Promise.reject(this.ended));
432
- // Only a result takes it: see {@link Waits}.
433
- if (this.carriedCancellation && waits === 'result') {
434
- this.carriedCancellation = false;
435
- return quiet(Promise.reject(new restate.CancelledError()));
436
- }
437
417
  return quiet(
438
418
  new Promise<unknown>((resolve, reject) => {
439
- this.waiting.set(handle, { resolve, reject, waits });
419
+ this.waiting.set(handle, { resolve, reject, spared });
440
420
  }),
441
421
  );
442
422
  }
443
423
 
444
424
  /**
445
- * A fire-and-forget action, which an attempt that ended simply drops. The
446
- * database's store calls these from the addon, where a throw would reach no
447
- * `catch` of ours and bring the process down; and a write of an attempt that
448
- * is over cannot be sent anyway, since a new attempt writes it again.
425
+ * Whether an owed cancellation fails a wait on Restate before it is made
426
+ * (see stop.ts): once made, nothing would cancel what it started.
427
+ */
428
+ private owed(): boolean {
429
+ return this.ended === undefined && this.stop.take();
430
+ }
431
+
432
+ /**
433
+ * A fire-and-forget action. An ended attempt drops it, and a retry makes it
434
+ * again; an invalid input throws, for user code to catch.
449
435
  */
450
436
  private tell(act: (vm: Vm) => unknown): void {
451
437
  if (this.ended !== undefined) return;
452
438
  try {
453
439
  this.act(act);
454
- } catch {
455
- // The attempt ended under us.
440
+ } catch (error) {
441
+ if (error instanceof InvalidInput) throw error;
442
+ // Otherwise the attempt ended meanwhile.
456
443
  }
457
444
  }
458
445
 
459
- /** An action and the promise of its result, in one. */
446
+ /**
447
+ * A wait on Restate that takes a cancellation as a call's result does (a
448
+ * signal read), and its promise: an owed cancellation fails it before it is
449
+ * made, and a cancellation rejects it while it waits.
450
+ */
460
451
  private issue(act: (vm: Vm) => number): Promise<unknown> {
452
+ if (this.owed()) return quiet(Promise.reject(new restate.CancelledError()));
453
+ return this.ask(act, { cancellable: true });
454
+ }
455
+
456
+ /**
457
+ * An action whose result the handler awaits, and its promise. Unless
458
+ * `cancellable`, a cancellation neither fails it before it is made nor
459
+ * rejects it while it waits: the session's own waits (S-20).
460
+ */
461
+ private ask(act: (vm: Vm) => number, { cancellable = false } = {}): Promise<unknown> {
461
462
  let handle: number;
462
463
  try {
463
464
  handle = this.act(act);
464
465
  } catch (error) {
465
466
  return quiet(Promise.reject(error instanceof Error ? error : new Error(String(error))));
466
467
  }
467
- return this.promise(handle);
468
+ return this.promise(handle, !cancellable);
469
+ }
470
+
471
+ /**
472
+ * The options of an action named `name`, inside the span the code running
473
+ * now is inside of, if any.
474
+ */
475
+ optionsOf(name?: string, record?: VmActionOptions['record']): VmActionOptions {
476
+ const parentSpan = this.span.getStore();
477
+ return {
478
+ ...(name !== undefined ? { name } : {}),
479
+ ...(parentSpan !== undefined ? { parentSpan } : {}),
480
+ ...(record !== undefined ? { record } : {}),
481
+ };
482
+ }
483
+
484
+ /** The span the code running now is inside of, if any. */
485
+ get currentSpan(): number | undefined {
486
+ return this.span.getStore();
468
487
  }
469
488
 
470
489
  // --- Calls
471
490
 
472
- /** A call: the promise of its result, and of its invocation id. */
473
491
  call(target: {
474
492
  service: string;
475
493
  handler: string;
@@ -477,35 +495,42 @@ export class AttemptDriver {
477
495
  input: Uint8Array;
478
496
  idempotencyKey?: string;
479
497
  headers?: { key: string; value: string }[];
480
- name?: string;
481
498
  }): { result: Promise<Uint8Array | null>; invocationId: Promise<string> } {
499
+ // An owed cancellation fails the call before it is made: once made, the
500
+ // callee would run and nothing would cancel it.
501
+ if (this.owed()) {
502
+ const cancelled = quiet(Promise.reject(new restate.CancelledError()));
503
+ return { result: cancelled, invocationId: cancelled };
504
+ }
482
505
  let handles: { invocationId: number; result: number };
483
506
  try {
484
507
  handles = this.act((vm) =>
485
508
  vm.call(
486
- target.service,
487
- target.handler,
509
+ {
510
+ service: target.service,
511
+ handler: target.handler,
512
+ key: target.key,
513
+ idempotencyKey: target.idempotencyKey,
514
+ headers: target.headers,
515
+ },
488
516
  target.input,
489
- target.key,
490
- target.idempotencyKey,
491
- target.headers,
492
- target.name,
517
+ undefined,
518
+ this.optionsOf(`${target.service}/${target.handler}`),
493
519
  ),
494
520
  );
495
521
  } catch (error) {
496
522
  const rejected = quiet(Promise.reject(error instanceof Error ? error : new Error(String(error))));
497
523
  return { result: rejected, invocationId: rejected };
498
524
  }
499
- const invocationId = quiet(this.promise(handles.invocationId, 'callId').then((id) => String(id)));
525
+ const invocationId = quiet(this.promise(handles.invocationId, true).then((id) => String(id)));
500
526
  const result = quiet(
501
527
  this.promise(handles.result).then((value) => (value === undefined ? null : (value as Uint8Array))),
502
528
  );
503
- // Keyed by the result's handle, which is what says the call is over.
504
529
  this.calls.set(handles.result, { id: invocationId, done: false, cancelled: false });
505
530
  return { result, invocationId };
506
531
  }
507
532
 
508
- /** A send: the promise of the invocation id it was given. */
533
+ /** A one-way send. A cancellation never fails it. */
509
534
  send(target: {
510
535
  service: string;
511
536
  handler: string;
@@ -514,118 +539,156 @@ export class AttemptDriver {
514
539
  delay?: number;
515
540
  idempotencyKey?: string;
516
541
  headers?: { key: string; value: string }[];
517
- name?: string;
518
- }): Promise<string> {
519
- if (this.ended !== undefined) return quiet(Promise.reject(this.ended));
520
- let handle: number;
542
+ }): void {
543
+ if (this.ended !== undefined) return;
521
544
  try {
522
- handle = this.act((vm) =>
545
+ this.act((vm) =>
523
546
  vm.send(
524
- target.service,
525
- target.handler,
547
+ {
548
+ service: target.service,
549
+ handler: target.handler,
550
+ key: target.key,
551
+ idempotencyKey: target.idempotencyKey,
552
+ headers: target.headers,
553
+ },
526
554
  target.input,
527
- target.key,
528
555
  target.delay,
529
- target.idempotencyKey,
530
- target.headers,
531
- target.name,
556
+ this.optionsOf(`${target.service}/${target.handler}`),
532
557
  ),
533
558
  );
534
559
  } catch (error) {
535
- // An attempt that ended drops it, as it drops a write: a new attempt
536
- // sends it again. Anything else is the caller's — a delay that is not a
537
- // number of milliseconds, say — and throws, as it does on the SDK's
538
- // context, rather than vanishing into a promise nobody holds.
539
- if (this.ended !== undefined) return quiet(Promise.reject(this.ended));
560
+ // An ended attempt drops the send; the next attempt sends it again.
561
+ // Any other error is the caller's (an invalid input, a bad delay) and throws, as on the SDK context.
562
+ if (this.ended !== undefined) return;
540
563
  throw error;
541
564
  }
542
- return quiet(this.promise(handle, 'sendId').then((id) => String(id)));
543
565
  }
544
566
 
545
- /** The result of an invocation, once it ends. */
546
- attach(invocationId: string, name?: string): Promise<Uint8Array | null> {
567
+ cancel(invocationId: string): void {
568
+ this.tell((vm) => vm.cancelInvocation(invocationId, false, this.optionsOf('cancel')));
569
+ }
570
+
571
+ // --- Invocation state: this invocation's own, which every attempt of it
572
+ // finds, and which ends with it. Bytes only. Its reads are the session's
573
+ // own waits: a cancellation neither refuses nor rejects them.
574
+
575
+ stateGet(scope: VmScope, key: string): Promise<Uint8Array | null> {
547
576
  return quiet(
548
- this.issue((vm) => vm.attachInvocation(invocationId, name)).then((value) =>
577
+ this.ask((vm) => vm.getState(scope, key, this.optionsOf(key))).then((value) =>
549
578
  value === undefined ? null : (value as Uint8Array),
550
579
  ),
551
580
  );
552
581
  }
553
582
 
554
- cancel(invocationId: string, name?: string): void {
555
- this.tell((vm) => vm.cancelInvocation(invocationId, name, false));
583
+ stateKeys(scope: VmScope): Promise<string[]> {
584
+ return quiet(this.ask((vm) => vm.getStateKeys(scope, this.optionsOf())).then((keys) => keys as string[]));
556
585
  }
557
586
 
558
- // --- Traces, shown in Restate's UI as runs
587
+ stateSet(scope: VmScope, key: string, value: Uint8Array): void {
588
+ this.act((vm) => vm.setState(scope, key, value, false, this.optionsOf(key)));
589
+ }
559
590
 
560
- startTrace(name: string, parent?: number): number {
561
- return this.act((vm) => vm.startTrace(name, parent));
591
+ stateClear(scope: VmScope, key: string): void {
592
+ this.act((vm) => vm.clearState(scope, key, false, this.optionsOf(key)));
562
593
  }
563
594
 
564
- endTrace(trace: number, output: Uint8Array): void {
565
- this.act((vm) => vm.endTraceSuccess(trace, output));
595
+ stateClearAll(scope: VmScope): void {
596
+ this.act((vm) => vm.clearAllState(scope, false, this.optionsOf()));
566
597
  }
567
598
 
568
- // --- Keeping an attempt at work alive
569
- //
570
- // Restate shuts an attempt down once its inactivity timeout passes with
571
- // nothing heard. That is the default: the attempt suspends on what it waits
572
- // for (or, waiting for nothing, starts again at once), and a wait of days
573
- // holds no process. Work that must not be cut off says so with `working`:
574
- // while any of it runs, the attempt heartbeats, whatever else it waits for.
599
+ // --- Signals: addressed to an invocation, by name
575
600
 
576
601
  /**
577
- * Run `fn`, keeping the attempt alive meanwhile: one heartbeat every
578
- * `everyMs` from the first scope opening to the last closing. The first
579
- * comes at once if the attempt has been silent for `everyMs` already (most
580
- * of the timeout may be gone), so the silence never reaches twice that;
581
- * otherwise the scopes the database opens for each of its calls would each
582
- * send one.
602
+ * The signal `index` (from 0) of `name` this invocation received: its
603
+ * payload, `null` if it carries nothing, or a TerminalError if a failure.
583
604
  */
584
- async working<T>(fn: () => T | Promise<T>, everyMs = (this.beatEvery ??= heartbeatMs())): Promise<T> {
585
- if (this.scopes++ === 0) this.startHeartbeats(everyMs);
586
- try {
587
- return await fn();
588
- } finally {
589
- this.scopes--;
590
- }
605
+ signalRead(name: string, index: number): Promise<Uint8Array | null> {
606
+ return quiet(
607
+ this.issue((vm) => vm.signalRead(name, index, this.optionsOf(`${name}#${index}`))).then((value) =>
608
+ value === undefined ? null : (value as Uint8Array),
609
+ ),
610
+ );
611
+ }
612
+
613
+ /** A signal `name` to invocation `invocationId`, with `value`, a failure, or nothing. */
614
+ signalSend(invocationId: string, name: string, value?: Uint8Array | restate.TerminalError): void {
615
+ const failure =
616
+ value instanceof restate.TerminalError
617
+ ? {
618
+ code: carried((value as { code?: unknown }).code),
619
+ message: value.message,
620
+ metadata: Object.entries(value.metadata ?? {}).map(([key, v]) => ({ key, value: v })),
621
+ }
622
+ : null;
623
+ const bytes = value instanceof Uint8Array ? value : null;
624
+ this.act((vm) => vm.signalSend(invocationId, name, bytes, failure, false, this.optionsOf(name)));
625
+ }
626
+
627
+ /** Resolves once every action made before it is applied. A cancellation neither refuses nor rejects it. */
628
+ flushActions(): Promise<void> {
629
+ return quiet(this.ask((vm) => vm.flush(this.optionsOf())).then(() => undefined));
591
630
  }
592
631
 
632
+ // --- Spans, shown in Restate's UI: the actions made inside one are nested
633
+ // under it
634
+
593
635
  /**
594
- * A run of scopes opens. Its beats are `everyMs` after it opened, and every
595
- * `everyMs` while a scope stays open: the timer is armed for the first, and
596
- * on firing it beats if the run it finds is that old, waits out the rest if
597
- * a run that opened later is younger, and is let go if no scope is open.
636
+ * Run `fn` inside a span `name`: the actions it makes (calls, sends,
637
+ * commits) are inside it. It ends with `fn`: with its value (`output`
638
+ * serializes it, if given), or its failure. An attempt that ended leaves
639
+ * it to Restate, which ends what an attempt left open.
598
640
  */
599
- private startHeartbeats(everyMs: number): void {
600
- if (this.ended !== undefined) return;
601
- const now = Date.now();
602
- if (now - this.wroteAt >= everyMs) this.heartbeat();
603
- this.runEvery = everyMs;
604
- this.nextBeat = now + everyMs;
605
- this.arm(this.nextBeat);
606
- }
607
-
608
- /** Arm the timer for `due`, unless it is armed for that or earlier. */
609
- private arm(due: number): void {
610
- if (this.heartbeats !== undefined) {
611
- if (this.beatDue <= due) return;
612
- clearTimeout(this.heartbeats);
641
+ async inSpan<T>(name: string, fn: () => Promise<T>, output?: (value: T) => Uint8Array | undefined): Promise<T> {
642
+ if (this.ended !== undefined) return fn();
643
+ let span: number;
644
+ try {
645
+ span = this.act((vm) => vm.spanStart(name, this.span.getStore()));
646
+ } catch {
647
+ return fn();
613
648
  }
614
- this.beatDue = due;
615
- this.heartbeats = setTimeout(() => this.beat(), Math.max(0, due - Date.now()));
616
- this.heartbeats.unref?.();
649
+ let value: T;
650
+ try {
651
+ value = await this.span.run(span, fn);
652
+ } catch (error) {
653
+ this.tell((vm) =>
654
+ vm.spanEnd(span, null, {
655
+ code: carried((error as { code?: unknown }).code),
656
+ message: error instanceof Error ? error.message : String(error),
657
+ metadata: [],
658
+ }),
659
+ );
660
+ throw error;
661
+ }
662
+ this.tell((vm) => vm.spanEnd(span, output?.(value) ?? null, null));
663
+ return value;
664
+ }
665
+
666
+ // --- Keep-alive
667
+
668
+ /** The first scope opened: beat now if silent for a full interval, and arm the timer. */
669
+ private startHeartbeats(): void {
670
+ if (this.ended !== undefined) return;
671
+ if (Date.now() - this.wroteAt >= this.interval) this.heartbeat();
672
+ if (this.heartbeats === undefined && this.ended === undefined) this.arm(this.interval);
617
673
  }
618
674
 
619
- /** The timer fired. */
675
+ /** The timer fired. Stop if no scope is open; else beat if silent for a full interval, or wait out the rest. */
620
676
  private beat(): void {
621
677
  this.heartbeats = undefined;
622
- if (this.ended !== undefined || this.scopes === 0) return;
623
- const now = Date.now();
624
- if (now >= this.nextBeat) {
625
- this.heartbeat();
626
- this.nextBeat = now + this.runEvery;
678
+ if (this.ended !== undefined || this.stop.alive === 0) return;
679
+ const silent = Date.now() - this.wroteAt;
680
+ if (silent < this.interval) {
681
+ this.arm(this.interval - silent);
682
+ return;
627
683
  }
628
- this.arm(this.nextBeat);
684
+ this.heartbeat();
685
+ // A heartbeat can end the attempt.
686
+ if (this.ended === undefined) this.arm(this.interval);
687
+ }
688
+
689
+ private arm(ms: number): void {
690
+ this.heartbeats = setTimeout(() => this.beat(), ms);
691
+ this.heartbeats.unref?.();
629
692
  }
630
693
 
631
694
  private heartbeat(): void {
@@ -645,24 +708,22 @@ export class AttemptDriver {
645
708
 
646
709
  // --- The input, and the end
647
710
 
648
- /** The invocation's input, read from the VM once. */
649
711
  private input(): VmInput {
650
712
  this.theInput ??= this.vm.input();
651
713
  return this.theInput;
652
714
  }
653
715
 
654
- /** The invocation's key, once the VM is ready to execute. */
716
+ /** Available once the VM is ready to execute. */
655
717
  get key(): string {
656
718
  return this.input().key;
657
719
  }
658
720
 
659
- /** The handler's input. */
660
721
  get body(): Uint8Array {
661
722
  return this.input().input;
662
723
  }
663
724
 
664
- /** The invocation's request, as a handler's `ctx.request` has it. */
665
- request(attemptHeaders: ReadonlyMap<string, string | string[] | undefined> = new Map()): restate.Request {
725
+ /** The invocation's request, as `ctx.request`. */
726
+ request(attemptHeaders: ReadonlyMap<string, string | string[] | undefined> = new Map()): SessionRequest {
666
727
  const input = this.input();
667
728
  const target = {
668
729
  service: this.options.service,
@@ -684,41 +745,44 @@ export class AttemptDriver {
684
745
  idempotencyKey: input.idempotencyKey,
685
746
  scope: input.scope,
686
747
  limitKey: input.limitKey,
687
- attemptCompletedSignal: this.aborter.signal,
688
- } as unknown as restate.Request;
748
+ attempt: input.attempt,
749
+ attemptCompletedSignal: this.completed,
750
+ } as unknown as SessionRequest;
689
751
  }
690
752
 
691
- /** The handler ended with its output. */
692
753
  endSuccess(output: Uint8Array): void {
693
754
  this.last((vm) => vm.endSuccess(output));
694
755
  }
695
756
 
696
- /** The handler ended with a terminal failure. */
697
757
  endFailure(error: restate.TerminalError): void {
698
758
  this.last((vm) =>
699
759
  vm.endFailure({
700
- code: (error as { code?: number }).code ?? 500,
760
+ code: carried((error as { code?: unknown }).code),
701
761
  message: error.message,
702
762
  metadata: Object.entries(error.metadata ?? {}).map(([key, value]) => ({ key, value })),
703
763
  }),
704
764
  );
705
765
  }
706
766
 
707
- /** The attempt failed, and Restate retries it. */
767
+ /** Fail the attempt; Restate retries it. */
708
768
  fail(message: string, stacktrace?: string, retryAfterMs?: number): void {
709
769
  if (this.ended !== undefined) return;
710
770
  this.vm.notifyError(message, stacktrace, retryAfterMs);
711
771
  this.schedule();
712
772
  }
713
773
 
714
- /** End the attempt with `act`, unless it ended already. */
715
774
  private last(act: (vm: Vm) => void): void {
716
775
  if (this.ended !== undefined) return;
717
776
  try {
718
777
  act(this.vm);
719
778
  } catch {
720
- // The attempt ended under us: the VM wrote why.
779
+ // The attempt ended meanwhile; the VM wrote why.
721
780
  }
722
781
  this.schedule();
723
782
  }
724
783
  }
784
+
785
+ /** A failure's code as the protocol carries it: one that is not an integer in 0..65535 is sent as 500, not truncated. */
786
+ function carried(code: unknown): number {
787
+ return typeof code === 'number' && Number.isInteger(code) && code >= 0 && code <= 0xffff ? code : 500;
788
+ }