@restatedev/sessions 0.9.0 → 0.10.1
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.
- package/README.md +131 -73
- package/dist/addon.d.ts +9 -0
- package/dist/addon.d.ts.map +1 -0
- package/dist/addon.js +20 -0
- package/dist/addon.js.map +1 -0
- package/dist/database.d.ts +13 -0
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +44 -17
- package/dist/database.js.map +1 -1
- package/dist/driver.d.ts +186 -0
- package/dist/driver.d.ts.map +1 -0
- package/dist/driver.js +554 -0
- package/dist/driver.js.map +1 -0
- package/dist/endpoint.d.ts +13 -0
- package/dist/endpoint.d.ts.map +1 -0
- package/dist/endpoint.js +186 -0
- package/dist/endpoint.js.map +1 -0
- package/dist/handler.d.ts +35 -0
- package/dist/handler.d.ts.map +1 -0
- package/dist/handler.js +218 -0
- package/dist/handler.js.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +4 -2
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +7 -3
- package/dist/internal.js.map +1 -1
- package/dist/object.d.ts +15 -2
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +51 -12
- package/dist/object.js.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +5 -0
- package/dist/serve.js.map +1 -1
- package/dist/session.d.ts +32 -2
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +59 -9
- package/dist/session.js.map +1 -1
- package/dist/vm.d.ts +151 -0
- package/dist/vm.d.ts.map +1 -0
- package/dist/vm.js +28 -0
- package/dist/vm.js.map +1 -0
- package/package.json +4 -4
- package/src/addon.ts +29 -0
- package/src/database.ts +48 -19
- package/src/driver.ts +657 -0
- package/src/endpoint.ts +220 -0
- package/src/handler.ts +272 -0
- package/src/index.ts +2 -1
- package/src/internal.ts +7 -4
- package/src/object.ts +75 -13
- package/src/serve.ts +5 -0
- package/src/session.ts +77 -8
- package/src/vm.ts +195 -0
- package/dist/selector.d.ts +0 -129
- package/dist/selector.d.ts.map +0 -1
- package/dist/selector.js +0 -251
- package/dist/selector.js.map +0 -1
- package/src/selector.ts +0 -323
package/src/driver.ts
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
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
|
+
// The attempt is over: what the handler does then fails with that, as
|
|
344
|
+
// its awaits of Restate do, and the attempt that follows gets the
|
|
345
|
+
// cancellation.
|
|
346
|
+
if (this.ended !== undefined) return false;
|
|
347
|
+
const carried = this.carriedCancellation;
|
|
348
|
+
this.carriedCancellation = false;
|
|
349
|
+
return carried;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Issuing the cancellations of the calls, if a cancellation started them. */
|
|
353
|
+
get cancellingCalls(): Promise<void> | undefined {
|
|
354
|
+
return this.cancelling;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Resolves once a cancellation arrived, in this attempt or an earlier one. */
|
|
358
|
+
cancellation(): Promise<void> {
|
|
359
|
+
if (this.vm.isCancelled()) this.cancelled();
|
|
360
|
+
return this.cancelledPromise;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
isCancelled(): boolean {
|
|
364
|
+
return this.vm.isCancelled();
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Cancel the calls this attempt made that have not answered; returns their
|
|
369
|
+
* ids. A call whose invocation id has not arrived yet is waited for: it was
|
|
370
|
+
* made, so Restate will answer with its id, and leaving it uncancelled would
|
|
371
|
+
* leave an invocation running that nothing waits for any more.
|
|
372
|
+
*/
|
|
373
|
+
async cancelPreviousCalls(): Promise<string[]> {
|
|
374
|
+
const cancelled: string[] = [];
|
|
375
|
+
// A snapshot: the loop awaits, and a call made meanwhile is the handler's
|
|
376
|
+
// own business, not one this cancellation set out to stop.
|
|
377
|
+
for (const call of Array.from(this.calls.values())) {
|
|
378
|
+
if (call.done || call.cancelled) continue;
|
|
379
|
+
let id: string;
|
|
380
|
+
try {
|
|
381
|
+
id = await call.id;
|
|
382
|
+
} catch {
|
|
383
|
+
continue; // its id never came: the attempt is over, or the call failed
|
|
384
|
+
}
|
|
385
|
+
if (call.done || call.cancelled) continue;
|
|
386
|
+
call.cancelled = true;
|
|
387
|
+
this.cancel(id);
|
|
388
|
+
cancelled.push(id);
|
|
389
|
+
}
|
|
390
|
+
return cancelled;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// --- Actions
|
|
394
|
+
|
|
395
|
+
/** Call the VM with `act`, then schedule a tick. The attempt's end throws. */
|
|
396
|
+
private act<T>(act: (vm: Vm) => T): T {
|
|
397
|
+
if (this.ended !== undefined) throw this.ended;
|
|
398
|
+
try {
|
|
399
|
+
return act(this.vm);
|
|
400
|
+
} catch (error) {
|
|
401
|
+
if (isShutDown(error)) {
|
|
402
|
+
this.end(new AttemptShutDown());
|
|
403
|
+
throw this.ended;
|
|
404
|
+
}
|
|
405
|
+
throw error;
|
|
406
|
+
} finally {
|
|
407
|
+
this.schedule();
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** The promise the notification of `handle` settles. */
|
|
412
|
+
private promise(handle: number, waits: Waits = 'result'): Promise<unknown> {
|
|
413
|
+
if (this.ended !== undefined) return quiet(Promise.reject(this.ended));
|
|
414
|
+
// Only a result takes it: see {@link Waits}.
|
|
415
|
+
if (this.carriedCancellation && waits === 'result') {
|
|
416
|
+
this.carriedCancellation = false;
|
|
417
|
+
return quiet(Promise.reject(new restate.CancelledError()));
|
|
418
|
+
}
|
|
419
|
+
return quiet(
|
|
420
|
+
new Promise<unknown>((resolve, reject) => {
|
|
421
|
+
this.waiting.set(handle, { resolve, reject, waits });
|
|
422
|
+
}),
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* A fire-and-forget action, which an attempt that ended simply drops. The
|
|
428
|
+
* database's store calls these from the addon, where a throw would reach no
|
|
429
|
+
* `catch` of ours and bring the process down; and a write of an attempt that
|
|
430
|
+
* is over cannot be sent anyway, since a new attempt writes it again.
|
|
431
|
+
*/
|
|
432
|
+
private tell(act: (vm: Vm) => unknown): void {
|
|
433
|
+
if (this.ended !== undefined) return;
|
|
434
|
+
try {
|
|
435
|
+
this.act(act);
|
|
436
|
+
} catch {
|
|
437
|
+
// The attempt ended under us.
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** An action and the promise of its result, in one. */
|
|
442
|
+
private issue(act: (vm: Vm) => number): Promise<unknown> {
|
|
443
|
+
let handle: number;
|
|
444
|
+
try {
|
|
445
|
+
handle = this.act(act);
|
|
446
|
+
} catch (error) {
|
|
447
|
+
return quiet(Promise.reject(error instanceof Error ? error : new Error(String(error))));
|
|
448
|
+
}
|
|
449
|
+
return this.promise(handle);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// --- Calls
|
|
453
|
+
|
|
454
|
+
/** A call: the promise of its result, and of its invocation id. */
|
|
455
|
+
call(target: {
|
|
456
|
+
service: string;
|
|
457
|
+
handler: string;
|
|
458
|
+
key?: string;
|
|
459
|
+
input: Uint8Array;
|
|
460
|
+
idempotencyKey?: string;
|
|
461
|
+
headers?: { key: string; value: string }[];
|
|
462
|
+
name?: string;
|
|
463
|
+
}): { result: Promise<Uint8Array | null>; invocationId: Promise<string> } {
|
|
464
|
+
let handles: { invocationId: number; result: number };
|
|
465
|
+
try {
|
|
466
|
+
handles = this.act((vm) =>
|
|
467
|
+
vm.call(
|
|
468
|
+
target.service,
|
|
469
|
+
target.handler,
|
|
470
|
+
target.input,
|
|
471
|
+
target.key,
|
|
472
|
+
target.idempotencyKey,
|
|
473
|
+
target.headers,
|
|
474
|
+
target.name,
|
|
475
|
+
),
|
|
476
|
+
);
|
|
477
|
+
} catch (error) {
|
|
478
|
+
const rejected = quiet(Promise.reject(error instanceof Error ? error : new Error(String(error))));
|
|
479
|
+
return { result: rejected, invocationId: rejected };
|
|
480
|
+
}
|
|
481
|
+
const invocationId = quiet(this.promise(handles.invocationId, 'callId').then((id) => String(id)));
|
|
482
|
+
const result = quiet(
|
|
483
|
+
this.promise(handles.result).then((value) => (value === undefined ? null : (value as Uint8Array))),
|
|
484
|
+
);
|
|
485
|
+
// Keyed by the result's handle, which is what says the call is over.
|
|
486
|
+
this.calls.set(handles.result, { id: invocationId, done: false, cancelled: false });
|
|
487
|
+
return { result, invocationId };
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** A send: the promise of the invocation id it was given. */
|
|
491
|
+
send(target: {
|
|
492
|
+
service: string;
|
|
493
|
+
handler: string;
|
|
494
|
+
key?: string;
|
|
495
|
+
input: Uint8Array;
|
|
496
|
+
delay?: number;
|
|
497
|
+
idempotencyKey?: string;
|
|
498
|
+
headers?: { key: string; value: string }[];
|
|
499
|
+
name?: string;
|
|
500
|
+
}): Promise<string> {
|
|
501
|
+
if (this.ended !== undefined) return quiet(Promise.reject(this.ended));
|
|
502
|
+
let handle: number;
|
|
503
|
+
try {
|
|
504
|
+
handle = this.act((vm) =>
|
|
505
|
+
vm.send(
|
|
506
|
+
target.service,
|
|
507
|
+
target.handler,
|
|
508
|
+
target.input,
|
|
509
|
+
target.key,
|
|
510
|
+
target.delay,
|
|
511
|
+
target.idempotencyKey,
|
|
512
|
+
target.headers,
|
|
513
|
+
target.name,
|
|
514
|
+
),
|
|
515
|
+
);
|
|
516
|
+
} catch (error) {
|
|
517
|
+
// An attempt that ended drops it, as it drops a write: a new attempt
|
|
518
|
+
// sends it again. Anything else is the caller's — a delay that is not a
|
|
519
|
+
// number of milliseconds, say — and throws, as it does on the SDK's
|
|
520
|
+
// context, rather than vanishing into a promise nobody holds.
|
|
521
|
+
if (this.ended !== undefined) return quiet(Promise.reject(this.ended));
|
|
522
|
+
throw error;
|
|
523
|
+
}
|
|
524
|
+
return quiet(this.promise(handle, 'sendId').then((id) => String(id)));
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** The result of an invocation, once it ends. */
|
|
528
|
+
attach(invocationId: string, name?: string): Promise<Uint8Array | null> {
|
|
529
|
+
return quiet(
|
|
530
|
+
this.issue((vm) => vm.attachInvocation(invocationId, name)).then((value) =>
|
|
531
|
+
value === undefined ? null : (value as Uint8Array),
|
|
532
|
+
),
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
cancel(invocationId: string, name?: string): void {
|
|
537
|
+
this.tell((vm) => vm.cancelInvocation(invocationId, name, false));
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// --- Traces, shown in Restate's UI as runs
|
|
541
|
+
|
|
542
|
+
startTrace(name: string, parent?: number): number {
|
|
543
|
+
return this.act((vm) => vm.startTrace(name, parent));
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
endTrace(trace: number, output: Uint8Array): void {
|
|
547
|
+
this.act((vm) => vm.endTraceSuccess(trace, output));
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// --- Keeping an attempt at work alive
|
|
551
|
+
//
|
|
552
|
+
// Restate shuts an attempt down once its inactivity timeout passes with
|
|
553
|
+
// nothing heard. A heartbeat stops that while the handler works outside
|
|
554
|
+
// Restate, on this rule: only while nothing of this attempt waits on
|
|
555
|
+
// Restate. With something
|
|
556
|
+
// waiting, a shutdown is what should happen — Restate starts a new attempt
|
|
557
|
+
// when the answer comes, instead of holding a connection open meanwhile.
|
|
558
|
+
|
|
559
|
+
/** Start the heartbeats of a running handler. */
|
|
560
|
+
startHeartbeats(everyMs = heartbeatMs()): void {
|
|
561
|
+
if (this.heartbeats !== undefined || this.ended !== undefined) return;
|
|
562
|
+
this.heartbeats = setInterval(() => {
|
|
563
|
+
if (this.ended !== undefined || this.waiting.size > 0) return;
|
|
564
|
+
try {
|
|
565
|
+
this.act((vm) => vm.heartbeat());
|
|
566
|
+
} catch {
|
|
567
|
+
// The attempt ended: the tick notices.
|
|
568
|
+
}
|
|
569
|
+
}, everyMs);
|
|
570
|
+
this.heartbeats.unref?.();
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
private stopHeartbeats(): void {
|
|
574
|
+
if (this.heartbeats === undefined) return;
|
|
575
|
+
clearInterval(this.heartbeats);
|
|
576
|
+
this.heartbeats = undefined;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// --- The input, and the end
|
|
580
|
+
|
|
581
|
+
/** The invocation's input, read from the VM once. */
|
|
582
|
+
private input(): VmInput {
|
|
583
|
+
this.theInput ??= this.vm.input();
|
|
584
|
+
return this.theInput;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** The invocation's key, once the VM is ready to execute. */
|
|
588
|
+
get key(): string {
|
|
589
|
+
return this.input().key;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** The handler's input. */
|
|
593
|
+
get body(): Uint8Array {
|
|
594
|
+
return this.input().input;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** The invocation's request, as a handler's `ctx.request` has it. */
|
|
598
|
+
request(attemptHeaders: ReadonlyMap<string, string | string[] | undefined> = new Map()): restate.Request {
|
|
599
|
+
const input = this.input();
|
|
600
|
+
const target = {
|
|
601
|
+
service: this.options.service,
|
|
602
|
+
handler: this.options.handler,
|
|
603
|
+
key: input.key || undefined,
|
|
604
|
+
toString(): string {
|
|
605
|
+
return this.key === undefined
|
|
606
|
+
? `${this.service}/${this.handler}`
|
|
607
|
+
: `${this.service}/${this.key}/${this.handler}`;
|
|
608
|
+
},
|
|
609
|
+
};
|
|
610
|
+
return {
|
|
611
|
+
target,
|
|
612
|
+
id: input.invocationId,
|
|
613
|
+
headers: new Map(input.headers.map(({ key, value }) => [key, value])),
|
|
614
|
+
attemptHeaders,
|
|
615
|
+
body: input.input,
|
|
616
|
+
extraArgs: [],
|
|
617
|
+
idempotencyKey: input.idempotencyKey,
|
|
618
|
+
scope: input.scope,
|
|
619
|
+
limitKey: input.limitKey,
|
|
620
|
+
attemptCompletedSignal: this.aborter.signal,
|
|
621
|
+
} as unknown as restate.Request;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** The handler ended with its output. */
|
|
625
|
+
endSuccess(output: Uint8Array): void {
|
|
626
|
+
this.last((vm) => vm.endSuccess(output));
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** The handler ended with a terminal failure. */
|
|
630
|
+
endFailure(error: restate.TerminalError): void {
|
|
631
|
+
this.last((vm) =>
|
|
632
|
+
vm.endFailure({
|
|
633
|
+
code: (error as { code?: number }).code ?? 500,
|
|
634
|
+
message: error.message,
|
|
635
|
+
metadata: Object.entries(error.metadata ?? {}).map(([key, value]) => ({ key, value })),
|
|
636
|
+
}),
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** The attempt failed, and Restate retries it. */
|
|
641
|
+
fail(message: string, stacktrace?: string, retryAfterMs?: number): void {
|
|
642
|
+
if (this.ended !== undefined) return;
|
|
643
|
+
this.vm.notifyError(message, stacktrace, retryAfterMs);
|
|
644
|
+
this.schedule();
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** End the attempt with `act`, unless it ended already. */
|
|
648
|
+
private last(act: (vm: Vm) => void): void {
|
|
649
|
+
if (this.ended !== undefined) return;
|
|
650
|
+
try {
|
|
651
|
+
act(this.vm);
|
|
652
|
+
} catch {
|
|
653
|
+
// The attempt ended under us: the VM wrote why.
|
|
654
|
+
}
|
|
655
|
+
this.schedule();
|
|
656
|
+
}
|
|
657
|
+
}
|