@restatedev/sessions 0.11.1 → 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.
- package/README.md +330 -178
- package/dist/addon.d.ts +1 -0
- package/dist/addon.d.ts.map +1 -1
- package/dist/addon.js.map +1 -1
- package/dist/calls.d.ts +28 -28
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +25 -25
- package/dist/calls.js.map +1 -1
- package/dist/database.d.ts +90 -166
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +137 -249
- package/dist/database.js.map +1 -1
- package/dist/driver.d.ts +129 -126
- package/dist/driver.d.ts.map +1 -1
- package/dist/driver.js +337 -276
- package/dist/driver.js.map +1 -1
- package/dist/endpoint.d.ts +47 -5
- package/dist/endpoint.d.ts.map +1 -1
- package/dist/endpoint.js +175 -60
- package/dist/endpoint.js.map +1 -1
- package/dist/handler.d.ts +20 -17
- package/dist/handler.d.ts.map +1 -1
- package/dist/handler.js +161 -127
- package/dist/handler.js.map +1 -1
- package/dist/host.d.ts +29 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +2 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -26
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +11 -11
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +20 -16
- package/dist/internal.js.map +1 -1
- package/dist/link.d.ts +1 -2
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +4 -5
- package/dist/link.js.map +1 -1
- package/dist/log.d.ts +14 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +21 -0
- package/dist/log.js.map +1 -0
- package/dist/object.d.ts +217 -142
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +195 -241
- package/dist/object.js.map +1 -1
- package/dist/platform.d.ts +0 -1
- package/dist/platform.d.ts.map +1 -1
- package/dist/platform.js +4 -6
- package/dist/platform.js.map +1 -1
- package/dist/schema.d.ts +14 -22
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +31 -69
- package/dist/schema.js.map +1 -1
- package/dist/serve.d.ts +11 -17
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +21 -39
- package/dist/serve.js.map +1 -1
- package/dist/session.d.ts +58 -236
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +206 -513
- package/dist/session.js.map +1 -1
- package/dist/stop.d.ts +59 -0
- package/dist/stop.d.ts.map +1 -0
- package/dist/stop.js +220 -0
- package/dist/stop.js.map +1 -0
- package/dist/vm.d.ts +108 -29
- package/dist/vm.d.ts.map +1 -1
- package/dist/vm.js +43 -10
- package/dist/vm.js.map +1 -1
- package/package.json +4 -4
- package/src/addon.ts +1 -0
- package/src/calls.ts +51 -47
- package/src/database.ts +195 -339
- package/src/driver.ts +379 -315
- package/src/endpoint.ts +217 -62
- package/src/handler.ts +183 -164
- package/src/host.ts +28 -0
- package/src/index.ts +6 -26
- package/src/internal.ts +28 -39
- package/src/link.ts +4 -5
- package/src/log.ts +42 -0
- package/src/object.ts +379 -335
- package/src/platform.ts +4 -6
- package/src/schema.ts +37 -103
- package/src/serve.ts +20 -41
- package/src/session.ts +236 -613
- package/src/stop.ts +225 -0
- package/src/vm.ts +151 -55
- package/dist/scope.d.ts +0 -38
- package/dist/scope.d.ts.map +0 -1
- package/dist/scope.js +0 -55
- package/dist/scope.js.map +0 -1
- 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
|
|
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
|
|
5
|
-
//
|
|
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.
|
|
8
|
-
//
|
|
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
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
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
|
|
21
|
-
//
|
|
22
|
-
//
|
|
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
|
|
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
|
|
28
|
-
* milliseconds: RESTATE_SESSIONS_HEARTBEAT
|
|
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
|
|
32
|
-
*
|
|
33
|
-
*
|
|
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
|
-
|
|
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
|
-
*
|
|
42
|
-
*
|
|
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
|
|
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
|
-
*
|
|
69
|
-
*
|
|
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
|
-
//
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
-
/**
|
|
133
|
-
|
|
158
|
+
/** The handler stops its own work on the stop signal (see stop.ts). */
|
|
159
|
+
explicitCancellation?: boolean;
|
|
134
160
|
/**
|
|
135
|
-
*
|
|
136
|
-
*
|
|
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
|
-
|
|
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
|
|
176
|
+
private readonly onClosable = new Set<() => void>();
|
|
177
|
+
private isClosable = false;
|
|
154
178
|
private queued = false;
|
|
155
|
-
/** The
|
|
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
|
|
185
|
+
/** Issuing the cancellations of the calls; the handler's end waits for it. */
|
|
158
186
|
private cancelling: Promise<void> | undefined;
|
|
159
|
-
private
|
|
160
|
-
/**
|
|
161
|
-
|
|
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
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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
|
-
|
|
194
|
-
|
|
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.
|
|
203
|
-
|
|
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
|
|
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
|
-
/**
|
|
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
|
|
246
|
-
|
|
247
|
-
|
|
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
|
-
*
|
|
252
|
-
* and
|
|
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
|
|
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
|
-
//
|
|
277
|
-
//
|
|
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
|
|
291
|
-
//
|
|
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
|
-
|
|
325
|
-
this.
|
|
326
|
-
this.
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
//
|
|
331
|
-
//
|
|
332
|
-
//
|
|
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
|
|
339
|
-
// handlers in a later microtask, so nothing is added
|
|
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
|
-
|
|
343
|
-
|
|
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
|
-
|
|
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
|
|
387
|
-
*
|
|
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:
|
|
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
|
|
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
|
-
|
|
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,
|
|
419
|
+
this.waiting.set(handle, { resolve, reject, spared });
|
|
440
420
|
}),
|
|
441
421
|
);
|
|
442
422
|
}
|
|
443
423
|
|
|
444
424
|
/**
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
|
|
448
|
-
|
|
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
|
-
|
|
440
|
+
} catch (error) {
|
|
441
|
+
if (error instanceof InvalidInput) throw error;
|
|
442
|
+
// Otherwise the attempt ended meanwhile.
|
|
456
443
|
}
|
|
457
444
|
}
|
|
458
445
|
|
|
459
|
-
/**
|
|
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
|
-
|
|
487
|
-
|
|
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
|
-
|
|
490
|
-
target.
|
|
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,
|
|
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
|
|
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
|
-
|
|
518
|
-
|
|
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
|
-
|
|
545
|
+
this.act((vm) =>
|
|
523
546
|
vm.send(
|
|
524
|
-
|
|
525
|
-
|
|
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.
|
|
530
|
-
target.headers,
|
|
531
|
-
target.name,
|
|
556
|
+
this.optionsOf(`${target.service}/${target.handler}`),
|
|
532
557
|
),
|
|
533
558
|
);
|
|
534
559
|
} catch (error) {
|
|
535
|
-
// An attempt
|
|
536
|
-
//
|
|
537
|
-
|
|
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
|
-
|
|
546
|
-
|
|
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.
|
|
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
|
-
|
|
555
|
-
this.
|
|
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
|
-
|
|
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
|
-
|
|
561
|
-
|
|
591
|
+
stateClear(scope: VmScope, key: string): void {
|
|
592
|
+
this.act((vm) => vm.clearState(scope, key, false, this.optionsOf(key)));
|
|
562
593
|
}
|
|
563
594
|
|
|
564
|
-
|
|
565
|
-
this.act((vm) => vm.
|
|
595
|
+
stateClearAll(scope: VmScope): void {
|
|
596
|
+
this.act((vm) => vm.clearAllState(scope, false, this.optionsOf()));
|
|
566
597
|
}
|
|
567
598
|
|
|
568
|
-
// ---
|
|
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
|
-
*
|
|
578
|
-
* `
|
|
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
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
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
|
-
*
|
|
595
|
-
*
|
|
596
|
-
*
|
|
597
|
-
*
|
|
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
|
-
|
|
600
|
-
if (this.ended !== undefined) return;
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
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
|
-
|
|
615
|
-
|
|
616
|
-
|
|
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.
|
|
623
|
-
const
|
|
624
|
-
if (
|
|
625
|
-
this.
|
|
626
|
-
|
|
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.
|
|
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
|
-
/**
|
|
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
|
|
665
|
-
request(attemptHeaders: ReadonlyMap<string, string | string[] | undefined> = new Map()):
|
|
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
|
-
|
|
688
|
-
|
|
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?:
|
|
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
|
-
/**
|
|
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
|
|
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
|
+
}
|