@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/stop.ts ADDED
@@ -0,0 +1,225 @@
1
+ // The stop signal, the cancellation and the keep-alive scopes of one attempt.
2
+ // The driver keeps one `Stop` per attempt (`driver.ts`), and so does a test
3
+ // without Restate (`test/support.ts`), so both follow the same rules.
4
+ //
5
+ // Cancellation. When Restate cancels the invocation, the handler is told once:
6
+ // - If a `stoppable` scope is open, or opens while the cancellation is owed,
7
+ // its signal tells the work. Nothing more is owed: the work usually writes
8
+ // how it stopped (an aborted reply), and failing that write would lose it.
9
+ // - Else, if the driver rejected a pending `ctx.rpc` result with it, that was
10
+ // the delivery, even for a call the handler never awaited.
11
+ // - Else it is owed: the next database call or `ctx.rpc` fails with it, before
12
+ // anything is written or sent. It never fails `ctx.send` or a `tx` call.
13
+ // A retry of a cancelled invocation starts with the cancellation owed.
14
+ // After delivery, a handler that fails ends the invocation as cancelled,
15
+ // whatever it threw. One that returns answers it. `withAttempt` (object.ts)
16
+ // decides this when the handler settles. With `explicitCancellation` only
17
+ // the signal aborts.
18
+ //
19
+ // The stop signal aborts once: with the cancellation, or with the error that
20
+ // ended the attempt, whichever comes first. After a cancellation, the end of
21
+ // the attempt is signalled by `request.attemptCompletedSignal`.
22
+ //
23
+ // Keep-alive. While a `working` or `stoppable` scope is open, `alive` is above
24
+ // 0 and the driver sends heartbeats. `suspendable(fn)` pauses the scopes that
25
+ // enclose the call until `fn` settles, so an attempt whose open scopes are all
26
+ // paused may be suspended by Restate. Scopes opened inside `fn` and `pinned`
27
+ // scopes are not paused. Enclosing scopes are found through the async context,
28
+ // or through `locateScopes`; if neither finds one, nothing is paused. The
29
+ // database's `keepAlive` counts but is never paused.
30
+ import { AsyncLocalStorage } from 'node:async_hooks';
31
+ import { CancelledError } from '@restatedev/restate-sdk';
32
+
33
+ /** A scope of an attempt's {@link Stop}, from {@link Stop.open} until it is released. */
34
+ export class Scope {
35
+ readonly parent: Scope | undefined;
36
+ /** A `suspendable` pauses only the scopes of the same attempt. */
37
+ readonly stop: Stop;
38
+ readonly #pinned: boolean;
39
+ readonly #count: (by: 1 | -1) => void;
40
+ readonly #closed: () => void;
41
+ /** How many `suspendable` calls inside it are running. */
42
+ #paused = 0;
43
+ #open = true;
44
+ #signal: AbortSignal | undefined;
45
+ #follow: (() => void) | undefined;
46
+
47
+ constructor(stop: Stop, count: (by: 1 | -1) => void, closed: () => void, pinned: boolean, parent: Scope | undefined) {
48
+ this.stop = stop;
49
+ this.#count = count;
50
+ this.#closed = closed;
51
+ this.#pinned = pinned;
52
+ this.parent = parent;
53
+ count(1);
54
+ }
55
+
56
+ /** Aborts with the stop signal, but only while this scope is open. Created on first read. */
57
+ get signal(): AbortSignal {
58
+ if (this.#signal === undefined) {
59
+ const controller = new AbortController();
60
+ this.#signal = controller.signal;
61
+ const attempt = this.stop.signal;
62
+ if (this.#open && attempt.aborted) controller.abort(attempt.reason);
63
+ else if (this.#open) {
64
+ this.#follow = () => controller.abort(attempt.reason);
65
+ attempt.addEventListener('abort', this.#follow, { once: true });
66
+ }
67
+ }
68
+ return this.#signal;
69
+ }
70
+
71
+ /** Close the scope. Idempotent and synchronous: afterwards it neither counts nor listens. */
72
+ release(): void {
73
+ if (!this.#open) return;
74
+ this.#open = false;
75
+ if (this.#paused === 0) this.#count(-1);
76
+ if (this.#follow !== undefined) this.stop.signal.removeEventListener('abort', this.#follow);
77
+ this.#follow = undefined;
78
+ this.#closed();
79
+ }
80
+
81
+ get pausable(): boolean {
82
+ return this.#open && !this.#pinned;
83
+ }
84
+
85
+ pause(): void {
86
+ if (this.#paused++ === 0 && this.#open) this.#count(-1);
87
+ }
88
+
89
+ resume(): void {
90
+ if (--this.#paused === 0 && this.#open) this.#count(1);
91
+ }
92
+ }
93
+
94
+ /** The innermost scope the running code was called inside. */
95
+ const enclosing = new AsyncLocalStorage<Scope>();
96
+
97
+ const locators = new Set<() => Scope | undefined>();
98
+
99
+ /**
100
+ * Tell `suspendable` which scope a call is made inside when the async context
101
+ * cannot: for a framework whose hooks open a scope around work they do not
102
+ * call themselves (callbacks around a tool). `locate` runs where
103
+ * `suspendable` is called and returns the enclosing scope, if it knows one.
104
+ * Returns what takes `locate` back: `suspendable` no longer calls it.
105
+ */
106
+ export function locateScopes(locate: () => Scope | undefined): () => void {
107
+ locators.add(locate);
108
+ return () => void locators.delete(locate);
109
+ }
110
+
111
+ export class Stop {
112
+ readonly #controller = new AbortController();
113
+ readonly #onAlive: (() => void) | undefined;
114
+ #cancellation: 'none' | 'owed' | 'delivered' = 'none';
115
+ /** Open `stoppable` scopes: a cancellation that arrives meanwhile is delivered to them. */
116
+ #listening = 0;
117
+ #alive = 0;
118
+ readonly #count = (by: 1 | -1): void => {
119
+ this.#alive += by;
120
+ if (by === 1 && this.#alive === 1) this.#onAlive?.();
121
+ };
122
+
123
+ /** `onAlive` is called when the number of live scopes goes from 0 to 1. */
124
+ constructor(onAlive?: () => void) {
125
+ this.#onAlive = onAlive;
126
+ }
127
+
128
+ /** How many scopes keep the attempt alive. The driver sends heartbeats while it is above 0. */
129
+ get alive(): number {
130
+ return this.#alive;
131
+ }
132
+
133
+ get signal(): AbortSignal {
134
+ return this.#controller.signal;
135
+ }
136
+
137
+ /** Whether the cancellation was delivered to the handler, by any path. */
138
+ get cancelled(): boolean {
139
+ return this.#cancellation === 'delivered';
140
+ }
141
+
142
+ /**
143
+ * Restate cancelled the invocation. `signalOnly` is for `explicitCancellation`.
144
+ * `failedAnAwait` says the driver already rejected a pending result with it.
145
+ */
146
+ cancel({ signalOnly = false, failedAnAwait = false }: { signalOnly?: boolean; failedAnAwait?: boolean } = {}): void {
147
+ if (this.#controller.signal.aborted) return;
148
+ if (!signalOnly) this.#cancellation = this.#listening > 0 || failedAnAwait ? 'delivered' : 'owed';
149
+ this.#controller.abort(new CancelledError());
150
+ }
151
+
152
+ /** The attempt ended with `reason`. An owed cancellation is dropped. */
153
+ end(reason: Error): void {
154
+ if (this.#cancellation === 'owed') this.#cancellation = 'none';
155
+ this.#controller.abort(reason);
156
+ }
157
+
158
+ /** Whether a cancellation is owed; if so, the caller delivers it by failing. */
159
+ take(): boolean {
160
+ if (this.#cancellation !== 'owed') return false;
161
+ this.#cancellation = 'delivered';
162
+ return true;
163
+ }
164
+
165
+ /**
166
+ * Open a scope until it is released: the building block of `working`,
167
+ * `stoppable` and the integrations' hooks.
168
+ */
169
+ open({ stoppable = false, pinned = false }: { stoppable?: boolean; pinned?: boolean } = {}): Scope {
170
+ if (stoppable) {
171
+ this.#listening++;
172
+ if (this.#cancellation === 'owed') this.#cancellation = 'delivered';
173
+ }
174
+ const closed = stoppable ? () => void this.#listening-- : () => {};
175
+ return new Scope(this, this.#count, closed, pinned, enclosing.getStore());
176
+ }
177
+
178
+ working<T>(fn: () => T | Promise<T>): Promise<T> {
179
+ return this.#inside(this.open(), fn);
180
+ }
181
+
182
+ stoppable<T>(fn: (signal: AbortSignal) => T | Promise<T>): Promise<T> {
183
+ return this.#inside(this.open({ stoppable: true }), () => fn(this.signal));
184
+ }
185
+
186
+ async suspendable<T>(fn: () => T | Promise<T>): Promise<T> {
187
+ const stopped = this.#enclosing();
188
+ for (const scope of stopped) scope.pause();
189
+ try {
190
+ return await fn();
191
+ } finally {
192
+ for (const scope of stopped) scope.resume();
193
+ }
194
+ }
195
+
196
+ /** The database's keep-alive around a call that waits: counted, but not a scope, so never paused. */
197
+ async keepAlive<T>(fn: () => T | Promise<T>): Promise<T> {
198
+ this.#count(1);
199
+ try {
200
+ return await fn();
201
+ } finally {
202
+ this.#count(-1);
203
+ }
204
+ }
205
+
206
+ async #inside<T>(scope: Scope, fn: () => T | Promise<T>): Promise<T> {
207
+ try {
208
+ return await enclosing.run(scope, fn);
209
+ } finally {
210
+ scope.release();
211
+ }
212
+ }
213
+
214
+ #enclosing(): Set<Scope> {
215
+ const found = new Set<Scope>();
216
+ const add = (innermost: Scope | undefined) => {
217
+ for (let scope = innermost; scope !== undefined; scope = scope.parent) {
218
+ if (scope.stop === this && scope.pausable) found.add(scope);
219
+ }
220
+ };
221
+ add(enclosing.getStore());
222
+ for (const locate of locators) add(locate());
223
+ return found;
224
+ }
225
+ }
package/src/vm.ts CHANGED
@@ -1,12 +1,15 @@
1
- // The VM of a session object's attempt: shared-core's explicit recovery state
2
- // machine, through the addon (`native/src/vm.rs`).
1
+ // The VM of a session object's attempt, on the explicit recovery protocol
2
+ // (version 1): shared-core's state machine, through the addon
3
+ // (`native/src/vm.rs`).
3
4
  //
4
- // It never replays a journal: every attempt runs the handler from the start
5
- // and recovers from the state the earlier attempts stored. An action returns
6
- // a handle, and its result comes back as a notification of that handle
7
- // (`takeNotification`), which the driver settles a promise with. There is no
8
- // `do_progress` and no single await point, so a handler awaits what it likes,
9
- // with its own combinators.
5
+ // It has no journal: every attempt runs the handler from the start and
6
+ // recovers from the state the earlier attempts stored. An action returns a
7
+ // handle, and its result comes back as a notification of that handle
8
+ // (`takeNotification`), which the driver settles a promise with, in its tick:
9
+ // the only place notifications are taken, since taking one is processing it
10
+ // (it counts in the `ShutdownMessage` of a shut-down attempt). There is no
11
+ // single await point, so a handler awaits what it likes, with its own
12
+ // combinators.
10
13
  //
11
14
  // The VM is synchronous and does no I/O: every call only buffers output.
12
15
  import { addon } from './addon.ts';
@@ -39,6 +42,8 @@ export interface VmInput {
39
42
  scope?: string;
40
43
  limitKey?: string;
41
44
  idempotencyKey?: string;
45
+ /** The number of this attempt: 1 for the first. */
46
+ attempt: number;
42
47
  }
43
48
 
44
49
  /** The handles of a call: its invocation id, and its result. */
@@ -47,6 +52,45 @@ export interface VmCallHandle {
47
52
  result: number;
48
53
  }
49
54
 
55
+ /** The target of a call or a send. */
56
+ export interface VmTarget {
57
+ service: string;
58
+ handler: string;
59
+ key?: string;
60
+ idempotencyKey?: string;
61
+ headers?: VmHeader[];
62
+ }
63
+
64
+ /** Whose state a state action is on: the object's, or the invocation's own. */
65
+ export type VmScope = 'object' | 'invocation';
66
+
67
+ /**
68
+ * How an action appears in Restate's record of the attempt (its UI): its
69
+ * name, the span it is inside of, and how much of it is recorded. None of it
70
+ * changes what the action does.
71
+ */
72
+ export interface VmActionOptions {
73
+ name?: string;
74
+ parentSpan?: number;
75
+ record?: 'default' | 'none' | 'summary' | 'full';
76
+ }
77
+
78
+ /** A send that commits with a transaction, inside its commit's atomic group. */
79
+ export interface VmGroupSend {
80
+ target: VmTarget;
81
+ input: Uint8Array;
82
+ /** In milliseconds. */
83
+ delay?: number;
84
+ name?: string;
85
+ }
86
+
87
+ /** What a commit on the VM commits with beside its writes. */
88
+ export interface VmCommit {
89
+ sends: VmGroupSend[];
90
+ /** The span the commit's group is inside of. */
91
+ parentSpan?: number;
92
+ }
93
+
50
94
  /** A ready result: `kind` says which field holds it. */
51
95
  export type VmNotification = { handle: number } & (
52
96
  | { kind: 'void' }
@@ -60,9 +104,9 @@ export type VmNotification = { handle: number } & (
60
104
  export type VmState = 'starting' | 'running' | 'closed';
61
105
 
62
106
  /**
63
- * The attempt's state machine. A command returns a handle, notified later
64
- * through {@link Vm.takeNotification}; a fire-and-forget command with `ack`
65
- * is notified once Restate stores it, and at once without.
107
+ * The attempt's state machine. An action returns a handle, notified later
108
+ * through {@link Vm.takeNotification}; one whose result is optional returns
109
+ * `null` unless asked for it (`wantResult`).
66
110
  */
67
111
  export interface Vm {
68
112
  /**
@@ -79,58 +123,77 @@ export interface Vm {
79
123
  notifyInputClosed(): void;
80
124
  /** The bytes buffered so far for the response body. */
81
125
  takeOutput(): Buffer;
126
+ /** Whether to close the response now: the last message is written, and the runtime closed its side. */
127
+ shouldCloseOutput(): boolean;
82
128
 
83
129
  isReadyToExecute(): boolean;
130
+ isFeatureSupported(feature: number): boolean;
84
131
  input(): VmInput;
85
132
 
86
133
  /**
87
- * The next ready result, in no particular order, or `null`. Throws once
88
- * the attempt is closed: {@link isShutDown} tells a shutdown from a failure.
134
+ * The next ready notification, in arrival order, or `null`: only the
135
+ * driver's tick calls it. Handle {@link Vm.cancelHandle} is the cancel
136
+ * signal. Throws once the attempt is closed: {@link isShutDown} tells a
137
+ * shutdown from a failure.
89
138
  */
90
139
  takeNotification(): VmNotification | null;
140
+ /** The reserved handle of the cancel signal (1). */
141
+ cancelHandle(): number;
142
+ /** The handles of an aborted atomic group's actions: never notified. */
143
+ takeAborted(): number[];
91
144
 
92
- getState(key: string, name?: string): number;
93
- getStateKeys(name?: string): number;
94
- setState(key: string, buffer: Uint8Array, name?: string, ack?: boolean): number;
95
- clearState(key: string, name?: string, ack?: boolean): number;
96
- clearAllState(name?: string, ack?: boolean): number;
97
-
98
- call(
99
- service: string,
100
- handler: string,
145
+ getState(scope: VmScope, key: string, options?: VmActionOptions): number;
146
+ getStateKeys(scope: VmScope, options?: VmActionOptions): number;
147
+ setState(
148
+ scope: VmScope,
149
+ key: string,
101
150
  buffer: Uint8Array,
102
- key?: string,
103
- idempotencyKey?: string,
104
- headers?: VmHeader[],
105
- name?: string,
106
- ): VmCallHandle;
151
+ wantResult?: boolean,
152
+ options?: VmActionOptions,
153
+ ): number | null;
154
+ clearState(scope: VmScope, key: string, wantResult?: boolean, options?: VmActionOptions): number | null;
155
+ clearAllState(scope: VmScope, wantResult?: boolean, options?: VmActionOptions): number | null;
156
+
157
+ /** `delay` is in milliseconds. */
158
+ call(target: VmTarget, buffer: Uint8Array, delay?: number, options?: VmActionOptions): VmCallHandle;
107
159
  /** Returns the handle of the invocation id. `delay` is in milliseconds. */
108
- send(
109
- service: string,
110
- handler: string,
111
- buffer: Uint8Array,
112
- key?: string,
113
- delay?: number,
114
- idempotencyKey?: string,
115
- headers?: VmHeader[],
116
- name?: string,
117
- ): number;
118
- attachInvocation(invocationId: string, name?: string): number;
119
- cancelInvocation(invocationId: string, name?: string, ack?: boolean): number;
120
-
121
- /** A trace, shown in Restate's UI as a run until it is ended. */
122
- startTrace(name: string, parent?: number): number;
123
- endTraceSuccess(trace: number, buffer: Uint8Array): void;
124
- endTraceFailure(trace: number, failure: VmFailure): void;
160
+ send(target: VmTarget, buffer: Uint8Array, delay?: number, options?: VmActionOptions): number;
161
+ attachInvocation(invocationId: string, options?: VmActionOptions): number;
162
+ cancelInvocation(invocationId: string, wantResult?: boolean, options?: VmActionOptions): number | null;
163
+
164
+ /** The signal `index` (from 0) of `signalName` this invocation received. */
165
+ signalRead(signalName: string, index: number, options?: VmActionOptions): number;
166
+ /** A signal to another invocation, carrying `bytes`, `failure`, or nothing. */
167
+ signalSend(
168
+ targetInvocationId: string,
169
+ signalName: string,
170
+ bytes?: Uint8Array | null,
171
+ failure?: VmFailure | null,
172
+ wantResult?: boolean,
173
+ options?: VmActionOptions,
174
+ ): number | null;
175
+
176
+ /** Notified once every action made before it is applied. */
177
+ flush(options?: VmActionOptions): number;
178
+ atomicGroupStart(): void;
179
+ atomicGroupEnd(wantResult?: boolean, options?: VmActionOptions): number | null;
180
+ atomicGroupAbort(): number[];
181
+
182
+ /** A span, shown in Restate's UI; inside `parent`, or the attempt itself. */
183
+ spanStart(name: string, parent?: number): number;
184
+ /** End `span` with `bytes`, with `failure`, or with nothing. */
185
+ spanEnd(span: number, bytes?: Uint8Array | null, failure?: VmFailure | null): void;
125
186
 
126
187
  /** Tells Restate the attempt makes progress, delaying its shutdown. */
127
188
  heartbeat(): void;
128
- /** Whether the invocation was cancelled, in this attempt or an earlier one. */
189
+ /** Whether the invocation was cancelled: before this attempt, or by the cancel signal a tick took. */
129
190
  isCancelled(): boolean;
191
+ /** The SDK ends the attempt on its own (the process is going away): an unasked `ShutdownMessage`. */
192
+ shutdown(): void;
130
193
  /**
131
194
  * Fail what the database's store waits for, once the attempt is over and
132
- * nothing will answer: its reads and acks live in the addon, so the driver
133
- * cannot reject them itself.
195
+ * nothing will answer: its reads and commits wait in the addon, so the
196
+ * driver cannot reject them itself.
134
197
  */
135
198
  endStateWaits(): void;
136
199
  /**
@@ -148,19 +211,51 @@ export interface Vm {
148
211
 
149
212
  interface VmConstructor {
150
213
  /**
151
- * `bidirectional` is false on a request/response transport (AWS Lambda,
152
- * HTTP/1.1), which cannot serve such a handler: no response could reach
153
- * it. The VM then fails the invocation at once, which pauses it.
214
+ * Throws for a request of another protocol family or version: see
215
+ * {@link refusedStatus} for the status to answer it with (415).
154
216
  */
155
- new (headers: VmHeader[], bidirectional: boolean): Vm;
217
+ new (headers: VmHeader[]): Vm;
156
218
  }
157
219
 
158
220
  export const Vm = (addon as { Vm: VmConstructor }).Vm;
159
221
 
222
+ /** The range of versions of the explicit recovery protocol the VM speaks, for discovery. */
223
+ export const explicitRecoveryProtocolRange = (): { minVersion: number; maxVersion: number } =>
224
+ (
225
+ addon as { explicitRecoveryProtocolRange: () => { minVersion: number; maxVersion: number } }
226
+ ).explicitRecoveryProtocolRange();
227
+
228
+ /**
229
+ * The HTTP status to answer a request with whose VM could not be made: 415
230
+ * for a content type of another protocol family or version. `undefined` if
231
+ * `error` is not such a refusal.
232
+ */
233
+ export function refusedStatus(error: unknown): number | undefined {
234
+ const message = (error as { message?: unknown }).message;
235
+ if (typeof message !== 'string') return undefined;
236
+ const match = /^VM_REFUSED (\d+):/.exec(message);
237
+ return match === null ? undefined : Number(match[1]);
238
+ }
239
+
240
+ /**
241
+ * The VM's refusal of a value user code passed to an action, which Restate
242
+ * would refuse as malformed (an invocation id that is not one, say): its code
243
+ * (400) and why. The VM sent nothing, and the attempt goes on: the driver
244
+ * fails that action alone, with a `TerminalError`. `undefined` if `error` is
245
+ * not such a refusal.
246
+ */
247
+ export function invalidInput(error: unknown): { code: number; message: string } | undefined {
248
+ const message = (error as { message?: unknown } | undefined)?.message;
249
+ if (typeof message !== 'string') return undefined;
250
+ // Anywhere in the text: a commit's send crosses the SQL engine, which may wrap it.
251
+ const match = /INVALID_INPUT (\d+): ([\s\S]*)$/.exec(message);
252
+ return match === null ? undefined : { code: Number(match[1]), message: match[2] ?? '' };
253
+ }
254
+
160
255
  /**
161
256
  * Restate's signature on a request, as the SDK verifies it before dispatch.
162
- * This package runs a session object's invocation ahead of that handler, so it
163
- * verifies the signature itself.
257
+ * This package serves a session object's invocations and its discovery ahead
258
+ * of that handler, so it verifies the signature itself.
164
259
  */
165
260
  export interface Identity {
166
261
  /**
@@ -189,7 +284,8 @@ export const STATE_WAIT_OVER = 'restate-sessions: the attempt is over';
189
284
  const SHUT_DOWN = 'ATTEMPT_SHUT_DOWN';
190
285
 
191
286
  /**
192
- * Whether `error` says the attempt was shut down (Restate closed the input),
193
- * rather than failed. A new attempt runs the handler from the start.
287
+ * Whether `error` says the attempt was shut down (Restate closed the input,
288
+ * or the process is going away), rather than failed. A new attempt runs the
289
+ * handler from the start.
194
290
  */
195
291
  export const isShutDown = (error: unknown): boolean => error instanceof Error && error.message.startsWith(SHUT_DOWN);
package/dist/scope.d.ts DELETED
@@ -1,38 +0,0 @@
1
- import type * as restate from '@restatedev/restate-sdk';
2
- import type { SessionContext, ViewContext } from './object.ts';
3
- /** A context of an attempt: a handler's or a view's. */
4
- type Context = SessionContext | ViewContext;
5
- /** The scope's values, which only {@link ScopeKey} reaches. */
6
- declare const VALUES: unique symbol;
7
- /** An attempt's own, as @restatedev/sessions made it, and what its code keeps for it ({@link ScopeKey}). */
8
- export declare class Scope {
9
- /** The SDK's context of the attempt. */
10
- readonly sdk: restate.ObjectContext | restate.ObjectSharedContext;
11
- /** Whether its handler has `explicitCancellation: true`. */
12
- readonly explicitCancellation: boolean;
13
- /** The definition of the session object whose handler or view it runs, if any. */
14
- readonly definition: object | undefined;
15
- readonly [VALUES]: Map<ScopeKey<unknown>, unknown>;
16
- constructor(sdk: restate.ObjectContext | restate.ObjectSharedContext, { explicitCancellation, definition }?: {
17
- definition?: object | undefined;
18
- explicitCancellation?: boolean | undefined;
19
- });
20
- }
21
- /** `context`, holding `scope`: as it is made, before it is frozen. */
22
- export declare const holding: <C extends Context>(context: C, scope: Scope) => C;
23
- /** The scope of the attempt whose context `ctx` is, if it is one of @restatedev/sessions. */
24
- export declare const scopeOf: (ctx: Context) => Scope | undefined;
25
- /** A kind of state an attempt's code keeps, by its context: its key in the attempt's scope. */
26
- export declare class ScopeKey<T> {
27
- /** What it is, for an error. */
28
- private readonly what;
29
- constructor(what: string);
30
- get(ctx: Context): T | undefined;
31
- set(ctx: Context, value: T): void;
32
- delete(ctx: Context): void;
33
- /** The attempt's, made by `make` the first time. */
34
- of(ctx: Context, make: () => T): T;
35
- private values;
36
- }
37
- export {};
38
- //# sourceMappingURL=scope.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"scope.d.ts","sourceRoot":"","sources":["../src/scope.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,KAAK,OAAO,MAAM,yBAAyB,CAAC;AAExD,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/D,wDAAwD;AACxD,KAAK,OAAO,GAAG,cAAc,GAAG,WAAW,CAAC;AAE5C,+DAA+D;AAC/D,QAAA,MAAM,MAAM,eAAmB,CAAC;AAEhC,4GAA4G;AAC5G,qBAAa,KAAK;IAChB,wCAAwC;IACxC,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,aAAa,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAClE,4DAA4D;IAC5D,QAAQ,CAAC,oBAAoB,EAAE,OAAO,CAAC;IACvC,kFAAkF;IAClF,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,QAAQ,CAAC,CAAC,MAAM,CAAC,kCAAyC;IAE1D,YACE,GAAG,EAAE,OAAO,CAAC,aAAa,GAAG,OAAO,CAAC,mBAAmB,EACxD,EAAE,oBAA4B,EAAE,UAA4C,EAAE;;;KAAK,EAKpF;CACF;AAKD,sEAAsE;AACtE,eAAO,MAAM,OAAO,GAAI,CAAC,SAAS,OAAO,WAAW,CAAC,SAAS,KAAK,KAAG,CAA6B,CAAC;AAEpG,6FAA6F;AAC7F,eAAO,MAAM,OAAO,QAAS,OAAO,KAAG,KAAK,GAAG,SAA0B,CAAC;AAE1E,+FAA+F;AAC/F,qBAAa,QAAQ,CAAC,CAAC;IACrB,gCAAgC;IAChC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAS;IAE9B,YAAY,IAAI,EAAE,MAAM,EAEvB;IAED,GAAG,CAAC,GAAG,EAAE,OAAO,GAAG,CAAC,GAAG,SAAS,CAE/B;IAED,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,CAEhC;IAED,MAAM,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAEzB;IAED,oDAAoD;IACpD,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,CAIjC;IAED,OAAO,CAAC,MAAM;CAMf"}
package/dist/scope.js DELETED
@@ -1,55 +0,0 @@
1
- import { Link } from './link.js';
2
- /** The scope's values, which only {@link ScopeKey} reaches. */
3
- const VALUES = Symbol('values');
4
- /** An attempt's own, as @restatedev/sessions made it, and what its code keeps for it ({@link ScopeKey}). */
5
- export class Scope {
6
- /** The SDK's context of the attempt. */
7
- sdk;
8
- /** Whether its handler has `explicitCancellation: true`. */
9
- explicitCancellation;
10
- /** The definition of the session object whose handler or view it runs, if any. */
11
- definition;
12
- [VALUES] = new Map();
13
- constructor(sdk, { explicitCancellation = false, definition = undefined } = {}) {
14
- this.sdk = sdk;
15
- this.explicitCancellation = explicitCancellation;
16
- this.definition = definition;
17
- }
18
- }
19
- /** The attempt's scope, on its context. */
20
- const SCOPE = new Link('scope');
21
- /** `context`, holding `scope`: as it is made, before it is frozen. */
22
- export const holding = (context, scope) => SCOPE.on(context, scope);
23
- /** The scope of the attempt whose context `ctx` is, if it is one of @restatedev/sessions. */
24
- export const scopeOf = (ctx) => SCOPE.of(ctx);
25
- /** A kind of state an attempt's code keeps, by its context: its key in the attempt's scope. */
26
- export class ScopeKey {
27
- /** What it is, for an error. */
28
- what;
29
- constructor(what) {
30
- this.what = what;
31
- }
32
- get(ctx) {
33
- return this.values(ctx).get(this);
34
- }
35
- set(ctx, value) {
36
- this.values(ctx).set(this, value);
37
- }
38
- delete(ctx) {
39
- this.values(ctx).delete(this);
40
- }
41
- /** The attempt's, made by `make` the first time. */
42
- of(ctx, make) {
43
- const values = this.values(ctx);
44
- if (!values.has(this))
45
- values.set(this, make());
46
- return values.get(this);
47
- }
48
- values(ctx) {
49
- const scope = scopeOf(ctx);
50
- if (scope === undefined)
51
- throw new TypeError(`${this.what} takes the context of a session object's handler or view`);
52
- return scope[VALUES];
53
- }
54
- }
55
- //# sourceMappingURL=scope.js.map
package/dist/scope.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"scope.js","sourceRoot":"","sources":["../src/scope.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAMjC,+DAA+D;AAC/D,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AAEhC,4GAA4G;AAC5G,MAAM,OAAO,KAAK;IAChB,wCAAwC;IAC/B,GAAG,CAAsD;IAClE,4DAA4D;IACnD,oBAAoB,CAAU;IACvC,kFAAkF;IACzE,UAAU,CAAqB;IAC/B,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,EAA8B,CAAC;IAE1D,YACE,GAAwD,EACxD,EAAE,oBAAoB,GAAG,KAAK,EAAE,UAAU,GAAG,SAA+B,EAAE,GAAG,EAAE;QAEnF,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,oBAAoB,GAAG,oBAAoB,CAAC;QACjD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;CACF;AAED,2CAA2C;AAC3C,MAAM,KAAK,GAAG,IAAI,IAAI,CAAQ,OAAO,CAAC,CAAC;AAEvC,sEAAsE;AACtE,MAAM,CAAC,MAAM,OAAO,GAAG,CAAoB,OAAU,EAAE,KAAY,EAAK,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAEpG,6FAA6F;AAC7F,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,GAAY,EAAqB,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;AAE1E,+FAA+F;AAC/F,MAAM,OAAO,QAAQ;IACnB,gCAAgC;IACf,IAAI,CAAS;IAE9B,YAAY,IAAY;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,GAAG,CAAC,GAAY;QACd,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,CAAkB,CAAC;IACrD,CAAC;IAED,GAAG,CAAC,GAAY,EAAE,KAAQ;QACxB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,GAAY;QACjB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,oDAAoD;IACpD,EAAE,CAAC,GAAY,EAAE,IAAa;QAC5B,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAChC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC,GAAG,CAAC,IAAI,CAAM,CAAC;IAC/B,CAAC;IAEO,MAAM,CAAC,GAAY;QACzB,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;QAC3B,IAAI,KAAK,KAAK,SAAS;YACrB,MAAM,IAAI,SAAS,CAAC,GAAG,IAAI,CAAC,IAAI,0DAA0D,CAAC,CAAC;QAC9F,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC;CACF"}