@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/handler.ts CHANGED
@@ -1,19 +1,27 @@
1
- // Serving one invocation of a session object's handler on the explicit
2
- // recovery VM (`driver.ts`), rather than through the SDK's journaled context,
3
- // which replays and would hold such a handler to one await at a time.
1
+ // Serving one attempt of a session object's handler on the explicit recovery
2
+ // protocol (`driver.ts`), rather than through the SDK's journaled context.
4
3
  //
5
4
  // The core takes a stream — the request's headers and body, and where to write
6
- // the response — so that a test can drive it with wire bytes and `serve.ts`
5
+ // the response — so that a test can drive it with wire bytes and `endpoint.ts`
7
6
  // can hand it an HTTP/2 one. It is reached only for a session object's
8
7
  // handler; everything else a deployment serves stays the SDK's.
9
8
  import * as restate from '@restatedev/restate-sdk';
10
- import { millisOrDurationToMillis, type Serde } from '@restatedev/restate-sdk-core';
11
- import { AttemptDriver, AttemptFailed, AttemptShutDown } from './driver.ts';
12
- import { handlerEntry, invoke, type AttemptContext } from './object.ts';
13
- import { Vm, type VmHeader } from './vm.ts';
9
+ import { millisOrDurationToMillis, type Duration } from '@restatedev/restate-sdk-core';
10
+ import { AttemptDriver, AttemptFailed, AttemptShutDown, quiet } from './driver.ts';
11
+ import type { AttemptHost } from './host.ts';
12
+ import { type Invocation, type Log, silent } from './log.ts';
13
+ import { handlerEntry, invoke, type SessionRequest } from './object.ts';
14
+ import { refusedStatus, Vm, type VmHeader } from './vm.ts';
14
15
 
15
- /** The lowest service protocol version the VM accepts; the SDK serves anything below. */
16
- export const MIN_PROTOCOL = 7;
16
+ /** The content type of the explicit recovery protocol's invocations, version 1. */
17
+ export const CONTENT_TYPE = 'application/vnd.restate.invocation.explicitrecovery.v1';
18
+
19
+ /**
20
+ * How long the response waits, after the attempt's last message, for Restate
21
+ * to close the request: Restate closes first, then the attempt (D35). One
22
+ * that never does is closed anyway.
23
+ */
24
+ export const CLOSE_TIMEOUT_MS = 30_000;
17
25
 
18
26
  /** One invocation on the wire: what the core reads, and where it writes. */
19
27
  export interface Stream {
@@ -26,22 +34,6 @@ export interface Stream {
26
34
  close(): void;
27
35
  }
28
36
 
29
- /**
30
- * Whether this package serves `headers`' invocation, or the SDK does. The VM
31
- * accepts the service protocol V7 and V8 only.
32
- *
33
- * A Restate that speaks less once reached the SDK's VM through the selector.
34
- * That is gone, and a session object cannot run on a VM that replays, so an
35
- * older server cannot serve one at all: `endpoint.ts` answers such an
36
- * invocation itself rather than handing it on. Everything that is not a
37
- * session object is still the SDK's at any version it supports.
38
- */
39
- export function servedHere(headers: Readonly<Record<string, string | string[] | undefined>>): boolean {
40
- const type = headers['content-type'];
41
- const match = /application\/vnd\.restate\.invocation\.v(\d+)/.exec((Array.isArray(type) ? type[0] : type) ?? '');
42
- return match !== null && Number(match[1]) >= MIN_PROTOCOL;
43
- }
44
-
45
37
  /** `headers` as the VM takes them. */
46
38
  function vmHeaders(headers: Readonly<Record<string, string | string[] | undefined>>): VmHeader[] {
47
39
  return Object.entries(headers).flatMap(([key, value]) =>
@@ -49,46 +41,86 @@ function vmHeaders(headers: Readonly<Record<string, string | string[] | undefine
49
41
  );
50
42
  }
51
43
 
44
+ /** The attempts this process is serving, with what closes each one's response: a SIGTERM ends them (`goAway`). */
45
+ const live = new Map<AttemptDriver, () => void>();
46
+
47
+ /**
48
+ * The process is going away: end every attempt it serves with an unasked
49
+ * `ShutdownMessage` and close its response at once; Restate starts each
50
+ * again, elsewhere. Returns how many there were.
51
+ */
52
+ export function goAway(): number {
53
+ const attempts = [...live];
54
+ for (const [driver, close] of attempts) {
55
+ driver.goAway();
56
+ close();
57
+ }
58
+ return attempts.length;
59
+ }
60
+
52
61
  /**
53
62
  * Run one attempt of `definition`'s handler `name` over `stream`, and end its
54
- * response. `bidirectional` is false on a request/response transport, which
55
- * cannot serve such a handler: the VM fails the invocation at once, pausing
56
- * it, since no response could reach it.
63
+ * response. A request of another protocol family or version is answered with
64
+ * the status the VM refuses it with (415), and nothing runs. `log` gets a
65
+ * line for that refusal, for an attempt that fails and is retried, and for
66
+ * one the VM failed (a protocol failure): the error's message, never the
67
+ * input or a header.
57
68
  */
58
69
  export async function serveSession(
59
70
  definition: { name: string },
60
71
  name: string,
61
72
  stream: Stream,
62
- { bidirectional = true } = {},
73
+ defaults: restate.DefaultServiceOptions = {},
74
+ log: Log = silent,
63
75
  ): Promise<void> {
64
- const entry = handlerEntry(definition, name);
76
+ const entry = handlerEntry(definition, name, defaults);
65
77
  if (entry === undefined) throw new Error(`${definition.name}/${name} is no handler or view of a session object`);
66
78
 
67
- const vm = new Vm(vmHeaders(stream.headers), bidirectional);
79
+ let vm: Vm;
80
+ try {
81
+ vm = new Vm(vmHeaders(stream.headers));
82
+ } catch (error) {
83
+ const status = refusedStatus(error);
84
+ // Its text may quote a header: the caller logs what it throws.
85
+ if (status === undefined) throw new Error('the VM could not start the invocation', { cause: error });
86
+ log(
87
+ 'warn',
88
+ `${definition.name}/${name}: answered ${status}: the request is not on the explicit recovery protocol, version 1`,
89
+ );
90
+ // Not a 500: Restate offers the next lower version of its range on a 415.
91
+ stream.writeHead(status, {});
92
+ stream.close();
93
+ return;
94
+ }
68
95
  const head = vm.getResponseHead();
69
96
  stream.writeHead(head.statusCode, Object.fromEntries(head.headers.map(({ key, value }) => [key, value])));
70
97
 
71
98
  const driver = new AttemptDriver(vm, (chunk) => stream.write(chunk), {
72
99
  service: definition.name,
73
100
  handler: name,
74
- shared: entry.view,
75
101
  explicitCancellation: entry.explicit,
102
+ inactivityTimeoutMs: entry.inactivityTimeoutMs,
76
103
  });
77
104
  // The database's store acts on the VM from the runtime's thread, in the
78
105
  // addon; this is how it asks for the tick that writes what it sent.
79
106
  vm.setScheduler(() => driver.scheduleTick());
80
107
 
81
- // The response ends with the attempt, once the tick wrote its last words:
82
- // not when the handler returns. Restate starts the next attempt only once
83
- // it has, and a handler that Restate shut down at work of its own (outside
84
- // `ctx.working`) runs on until that work is done, its actions throwing.
108
+ // The response closes once the attempt's last message is written and the
109
+ // runtime closed its side (it closes first), or when the process goes
110
+ // away: not when the handler returns. A handler that Restate shut down at
111
+ // work of its own (outside `ctx.working`) runs on until that work is done,
112
+ // its actions throwing.
85
113
  let closed = false;
114
+ const whenClosed = Promise.withResolvers<void>();
86
115
  const close = () => {
87
116
  if (closed) return;
88
117
  closed = true;
118
+ live.delete(driver);
89
119
  stream.close();
120
+ whenClosed.resolve();
90
121
  };
91
- driver.whenEnded(() => setTimeout(close, 0));
122
+ live.set(driver, close);
123
+ driver.whenClosable(close);
92
124
 
93
125
  // The input pump: the only reader of the request body. It runs until the
94
126
  // body ends, beside the handler.
@@ -109,6 +141,7 @@ export async function serveSession(
109
141
  }
110
142
  })();
111
143
 
144
+ let invocation: Invocation | undefined;
112
145
  try {
113
146
  await ready.promise;
114
147
  if (driver.over !== undefined || !driver.isReadyToExecute()) return;
@@ -116,88 +149,130 @@ export async function serveSession(
116
149
  // either: a terminal failure ends the invocation, where a retryable one
117
150
  // would have Restate send the same bytes forever. The SDK's own handler
118
151
  // does the same for input its journal codec cannot decode.
119
- let input: unknown;
120
- try {
121
- input = entry.inputSerde.deserialize(driver.body);
122
- } catch (error) {
123
- throw new restate.TerminalError(`failed to deserialize the input: ${(error as Error).message}`, {
124
- errorCode: 400,
125
- });
126
- }
127
- const output = await invoke(definition, name, contextOf(driver, stream.headers, vm), input);
152
+ const request = driver.request(new Map(Object.entries(stream.headers)));
153
+ invocation = { id: request.id, service: definition.name, handler: name };
154
+ let output: Uint8Array | undefined;
155
+ // The hooks' handler interceptors wrap all of it, as the SDK's do.
156
+ await intercepted(
157
+ entry.hooks,
158
+ request,
159
+ )(async () => {
160
+ let input: unknown;
161
+ try {
162
+ input = entry.inputSerde.deserialize(driver.body);
163
+ } catch (error) {
164
+ throw new restate.TerminalError(`failed to deserialize the input: ${(error as Error).message}`, {
165
+ errorCode: 400,
166
+ });
167
+ }
168
+ output = entry.outputSerde.serialize(await invoke(definition, name, hostOf(driver, request, vm), input, entry));
169
+ });
128
170
  // A cancellation that arrived while the handler ran is still cancelling
129
171
  // its calls: they go out before the attempt ends, or not at all.
130
172
  await driver.cancellingCalls;
131
- driver.endSuccess(entry.outputSerde.serialize(output));
173
+ driver.endSuccess(output!);
132
174
  } catch (error) {
133
175
  await driver.cancellingCalls;
134
- endWith(driver, error, entry.asTerminalError);
176
+ endWith(driver, error, entry.asTerminalError, (message) => log('warn', message, invocation));
135
177
  } finally {
136
- await pump;
137
- // The attempt's last words are buffered: a turn lets the tick write them.
178
+ if (driver.over instanceof AttemptFailed) log('warn', `the attempt failed: ${driver.over.message}`, invocation);
179
+ // The attempt's last words are buffered: a turn lets the tick write them,
180
+ // and the response closes once Restate closed the request too.
138
181
  await new Promise((resolve) => setTimeout(resolve, 0));
182
+ if (!closed) {
183
+ const timeout = setTimeout(close, CLOSE_TIMEOUT_MS);
184
+ timeout.unref?.();
185
+ await Promise.race([pump, whenClosed.promise]);
186
+ // The end of the input reached the VM: the tick that follows closes.
187
+ await new Promise((resolve) => setTimeout(resolve, 0));
188
+ driver.scheduleTick();
189
+ await new Promise((resolve) => setTimeout(resolve, 0));
190
+ // Restate closed the request, and the VM has no last message to write:
191
+ // it was shut down before it started, say. Nothing more will come.
192
+ if (!closed && driver.over !== undefined) close();
193
+ clearTimeout(timeout);
194
+ }
139
195
  close();
140
196
  }
141
197
  }
142
198
 
143
- /** End the attempt the way `error` says to. */
144
- function endWith(driver: AttemptDriver, error: unknown, asTerminalError?: (error: unknown) => Error | undefined): void {
145
- if (error instanceof AttemptShutDown) return; // the attempt is over; nothing more is sent
146
- // The handler option of the same name: an error it names ends the
147
- // invocation rather than being retried. The SDK applies it, so this does.
148
- if (asTerminalError !== undefined && !(error instanceof restate.TerminalError)) {
149
- const terminal = asTerminalError(error);
150
- if (terminal !== undefined) {
151
- driver.endFailure(
152
- terminal instanceof restate.TerminalError ? terminal : new restate.TerminalError(terminal.message),
153
- );
154
- return;
155
- }
156
- }
157
- if (error instanceof restate.TerminalError) {
158
- driver.endFailure(error);
159
- return;
160
- }
161
- if (error instanceof AttemptFailed) return; // the VM wrote why
162
- const retryable = error as { retryAfter?: number };
163
- const thrown = error instanceof Error ? error : new Error(String(error));
164
- driver.fail(thrown.message, thrown.stack, retryable.retryAfter);
199
+ /** What the SDK's hook context carries for its own instrumentation: whether the invocation is past replay. */
200
+ const IS_PROCESSING = Symbol.for('@restatedev/restate-sdk/hooks.isProcessing');
201
+
202
+ /**
203
+ * Run an attempt inside the `handler` interceptors of `hooks`, the first
204
+ * outermost, as the SDK does (`startUserHandler`, `composeInterceptors`):
205
+ * each provider is called once per attempt with the request. An interceptor
206
+ * and its `next()` reject with what ended the attempt once it ends (a
207
+ * shutdown, say), so that none waits on a function that may never return,
208
+ * as the SDK's `raceWithAttemptEnd` does. A session object's context has no
209
+ * `ctx.run`, so a `run` interceptor is never called, and an attempt is never
210
+ * a replay.
211
+ */
212
+ function intercepted(
213
+ hooks: readonly restate.HooksProvider[],
214
+ request: SessionRequest,
215
+ ): (run: () => Promise<void>) => Promise<void> {
216
+ const interceptors = hooks.flatMap((provider) => {
217
+ const context = { request };
218
+ Object.defineProperty(context, IS_PROCESSING, { value: () => true, enumerable: false });
219
+ const handler = provider(context).interceptor?.handler;
220
+ return handler === undefined ? [] : [handler];
221
+ });
222
+ if (interceptors.length === 0) return (run) => run();
223
+ const signal = request.attemptCompletedSignal;
224
+ const ended = new Promise<never>((_, reject) => {
225
+ if (signal.aborted) reject(signal.reason);
226
+ else signal.addEventListener('abort', () => reject(signal.reason), { once: true });
227
+ });
228
+ ended.catch(() => {});
229
+ const racing = (promise: Promise<void>) => Promise.race([promise, ended]);
230
+ return (run) =>
231
+ interceptors.reduceRight<() => Promise<void>>(
232
+ (next, interceptor) => () => racing(interceptor(() => racing(next()))),
233
+ run,
234
+ )();
165
235
  }
166
236
 
167
237
  /**
168
- * What `invoke` needs of a handler's context, over `driver`: the members of
169
- * the SDK's that a session object's attempt uses, and no others.
238
+ * End the attempt the way `error` says to. The `asTerminalError` option
239
+ * applies as the SDK applies it (`ensureError`, `notifyError`): what it
240
+ * returns takes the error's place, and ends the invocation if it is a
241
+ * `TerminalError`; anything else fails the attempt, and Restate retries it.
170
242
  */
171
- function contextOf(
243
+ function endWith(
172
244
  driver: AttemptDriver,
173
- attemptHeaders: Readonly<Record<string, string | string[] | undefined>>,
174
- vm: Vm,
175
- ): AttemptContext {
176
- const headers = new Map(Object.entries(attemptHeaders));
177
- const request = driver.request(headers);
178
-
179
- /** The attempt's end, as `invocationEndPromise` gives it: a promise that rejects. */
180
- const ending = Promise.withResolvers<never>();
181
- ending.promise.catch(() => {});
182
- driver.whenEnded(() => ending.reject(driver.over ?? new AttemptShutDown()));
245
+ error: unknown,
246
+ asTerminalError: ((error: unknown) => restate.TerminalError | undefined) | undefined,
247
+ retried: (message: string) => void,
248
+ ): void {
249
+ if (error instanceof AttemptShutDown) return; // the attempt is over; nothing more is sent
250
+ if (error instanceof AttemptFailed) return; // the VM wrote why
251
+ const mapped = error instanceof restate.TerminalError ? error : asTerminalError?.(error) || error;
252
+ if (mapped instanceof restate.TerminalError) {
253
+ driver.endFailure(mapped);
254
+ return;
255
+ }
256
+ const { retryAfter } = mapped as { retryAfter?: number | Duration };
257
+ const thrown = mapped instanceof Error ? mapped : new Error(String(mapped));
258
+ // The VM takes a whole number of milliseconds.
259
+ const delay = retryAfter === undefined ? undefined : Math.round(millisOrDurationToMillis(retryAfter));
260
+ retried(
261
+ `the handler failed, and Restate retries it${delay === undefined ? '' : ` in ${delay} ms`}: ${thrown.name}: ${thrown.message}`,
262
+ );
263
+ driver.fail(thrown.message, thrown.stack, delay);
264
+ }
183
265
 
184
- const context = {
266
+ /** The attempt over `driver`, as a session object handler sees it (object.ts). */
267
+ function hostOf(driver: AttemptDriver, request: SessionRequest, vm: Vm): AttemptHost {
268
+ return {
185
269
  key: driver.key,
186
- request: () => request,
187
- // The object's state is the addon's: it reads and writes it as the VM's
188
- // own commands, so nothing of it is implemented here. A session opened on
189
- // a VM never asks (see `commitOnly` in `session.ts`); anything else that
190
- // does is a mistake, and says so.
191
- get: servedByVm('get'),
192
- set: servedByVm('set'),
193
- clear: servedByVm('clear'),
194
- stateKeys: servedByVm('stateKeys'),
195
- run: () => {
196
- throw new restate.TerminalError(
197
- 'a session object has no ctx.run: put journaled work in a restate.object, service or workflow, and call it with ctx.rpc',
198
- );
199
- },
200
- genericCall: (call: GenericCall) => {
270
+ request,
271
+ stop: driver.stop,
272
+ // The addon reads and writes the object state on the VM (see `openOnVm`).
273
+ vm,
274
+ driver,
275
+ call: (call) => {
201
276
  const { result, invocationId } = driver.call({
202
277
  service: call.service,
203
278
  handler: call.method,
@@ -206,80 +281,24 @@ function contextOf(
206
281
  idempotencyKey: call.idempotencyKey,
207
282
  headers: Object.entries(call.headers ?? {}).map(([key, value]) => ({ key, value })),
208
283
  });
209
- // Marked handled: `start()` awaits only the invocation id, so nothing
210
- // holds this, and it rejects when the callee fails, on a cancellation,
211
- // and at the end of every attempt — including a successful one.
284
+ // Marked handled: a handler need not await a call (a lost race), and it
285
+ // rejects at the end of every attempt, even a successful one.
212
286
  const answered = quiet(
213
287
  result.then((value) => (call.outputSerde ?? restate.serde.json).deserialize(value ?? new Uint8Array())),
214
288
  );
215
289
  return Object.assign(answered, { invocationId });
216
290
  },
217
- genericSend: (send: GenericSend) =>
218
- void driver.send({
291
+ send: (send) =>
292
+ driver.send({
219
293
  service: send.service,
220
294
  handler: send.method,
221
295
  key: send.key,
222
296
  input: (send.inputSerde ?? restate.serde.json).serialize(send.parameter),
223
- // `SendOptions.delay` is milliseconds or a `Duration`; the VM takes
224
- // milliseconds.
297
+ // The VM takes milliseconds.
225
298
  delay: send.delay === undefined ? undefined : millisOrDurationToMillis(send.delay),
226
299
  idempotencyKey: send.idempotencyKey,
227
300
  headers: Object.entries(send.headers ?? {}).map(([key, value]) => ({ key, value })),
228
301
  }),
229
- invocation: (invocationId: unknown) => ({
230
- cancel: () => driver.cancel(String(invocationId)),
231
- attach: (serde?: Serde<unknown>) =>
232
- quiet(
233
- driver
234
- .attach(String(invocationId))
235
- .then((value) => (serde ?? restate.serde.json).deserialize(value ?? new Uint8Array())),
236
- ),
237
- }),
238
- cancellation: () => driver.cancellation(),
239
- // A cancellation owed to the handler's next await, which a call of its
240
- // database takes before it issues anything (`session.ts`).
241
- takeCancellation: () => driver.takeCarriedCancellation(),
242
- cancelPreviousCalls: () => driver.cancelPreviousCalls(),
243
- // What `ctx.working` keeps alive, and the database's own calls too (`session.ts`).
244
- working: <T>(fn: () => T | Promise<T>) => driver.working(fn),
245
- invocationEndPromise: { promise: ending.promise },
246
- defaultSerde: restate.serde.json,
247
- // The addon reads and writes the object's state on this, rather than
248
- // calling back into JavaScript for every page (see `openOnVm`).
249
- vm,
302
+ cancel: (invocationId) => driver.cancel(invocationId),
250
303
  };
251
- return context as unknown as AttemptContext;
252
- }
253
-
254
- /**
255
- * Mark a promise handled, so that one the handler never awaits does not bring
256
- * the process down when the attempt ends. The caller still sees the rejection.
257
- */
258
- function quiet<T>(promise: Promise<T>): Promise<T> {
259
- promise.catch(() => {});
260
- return promise;
261
- }
262
-
263
- /** What a state member of the context does if anything calls it. */
264
- const servedByVm = (of: string) => () => {
265
- throw new restate.TerminalError(
266
- `@restatedev/sessions: the VM serves the object's state in the addon; ctx.${of} is not called`,
267
- );
268
- };
269
-
270
- /** `ctx.genericCall`'s argument, as this package makes it (`calls.ts`). */
271
- interface GenericCall {
272
- service: string;
273
- method: string;
274
- key?: string;
275
- parameter: unknown;
276
- inputSerde?: Serde<unknown>;
277
- outputSerde?: Serde<unknown>;
278
- idempotencyKey?: string;
279
- headers?: Record<string, string>;
280
- }
281
-
282
- /** `ctx.genericSend`'s argument. */
283
- interface GenericSend extends GenericCall {
284
- delay?: number | Parameters<typeof millisOrDurationToMillis>[0];
285
304
  }
package/src/host.ts ADDED
@@ -0,0 +1,28 @@
1
+ // What one attempt of a session object's handler runs on.
2
+ import type * as restate from '@restatedev/restate-sdk';
3
+ import type { Store } from './database.ts';
4
+ import type { AttemptDriver } from './driver.ts';
5
+ import type { SessionRequest } from './object.ts';
6
+ import type { Stop } from './stop.ts';
7
+ import type { Vm } from './vm.ts';
8
+
9
+ /** What one attempt runs on: the driver over its VM (handler.ts), or a test's fake (test/support.ts). */
10
+ export interface AttemptHost {
11
+ readonly key: string;
12
+ /** Its `attemptCompletedSignal` aborts, with the error that ended it, when the attempt ends. */
13
+ readonly request: SessionRequest;
14
+ /** See stop.ts. */
15
+ readonly stop: Stop;
16
+ /** The addon reads and writes the object state on it. A test gives `store` instead. */
17
+ readonly vm?: Vm;
18
+ /** The object's state in JavaScript, for an attempt without a VM (tests). */
19
+ readonly store?: Store;
20
+ /**
21
+ * The attempt's driver, on the VM: spans, and what the protocol adds beyond
22
+ * calls and sends (invocation state, signals, flush). A test's has none.
23
+ */
24
+ readonly driver?: AttemptDriver;
25
+ call(call: restate.GenericCall<unknown, unknown>): Promise<unknown> & { invocationId: Promise<string> };
26
+ send(send: restate.GenericSend<unknown>): void;
27
+ cancel(invocationId: string): void;
28
+ }
package/src/index.ts CHANGED
@@ -1,27 +1,10 @@
1
1
  // Session objects: Restate virtual objects whose state is a SQL database per
2
- // key. It is the Restate SDK, with `restate.sessionObject` beside its own
3
- // objects, services and workflows:
4
- //
5
- // import * as restate from '@restatedev/sessions';
6
- //
7
- // const notes = restate.sessionObject({
8
- // name: 'notes',
9
- // schema: ['CREATE TABLE notes (text TEXT NOT NULL)'],
10
- // handlers: {
11
- // add: async (ctx, text: string) => {
12
- // await ctx.db.execute('INSERT INTO notes (text) VALUES (?)', [text]);
13
- // },
14
- // },
15
- // views: {
16
- // list: async (ctx) => ctx.db.query<{ text: string }>('SELECT text FROM notes'),
17
- // },
18
- // });
19
- //
2
+ // key. This module is the Restate SDK (`import * as restate from
3
+ // '@restatedev/sessions'`) plus `restate.sessionObject` (example in object.ts).
20
4
  // See README.md.
21
5
 
22
- // The SDK, and what this module adds to it (or declares in its place: its
23
- // `Client`, `SendClient` and `Target` are a session object's, and `serve`
24
- // takes the services, with what they need beside them).
6
+ // The SDK, plus additions. `Client`, `SendClient`, `Target`, `serve` and
7
+ // `connect` replace the SDK exports of the same name.
25
8
  export * from '@restatedev/restate-sdk';
26
9
  export type { Database, DatabaseReader, DatabaseWriter, Row, SqlParam, SqlValue, Transaction } from './session.ts';
27
10
  export type { Step } from './schema.ts';
@@ -31,13 +14,10 @@ export {
31
14
  type Entry,
32
15
  type HandlerOptions,
33
16
  type SessionContext,
17
+ type SessionRequest,
34
18
  type ViewContext,
35
19
  } from './object.ts';
36
20
  export type { CallOptions, Client, Rpc, Send, SendClient, SendOptions, Target } from './calls.ts';
37
- // A handle on what another deployment serves: named and typed, not implemented here.
38
21
  export { remote } from './calls.ts';
39
- // In place of the SDK's: the services, on PORT, with what they need beside
40
- // them; `connect`, the same for Restate Cloud (the SDK's own leaves them out);
41
- // and `served`, the services with what they need, for an endpoint of your own
42
- // — which runs them on the VM too (`endpoint.ts`).
22
+ // See serve.ts.
43
23
  export { connect, serve, served } from './serve.ts';
package/src/internal.ts CHANGED
@@ -1,42 +1,31 @@
1
- // For tests: an attempt's session over a context of their own, the store's
2
- // fault injection, and a database over a store of their own. For this
3
- // repository's libraries: the schemas their tables are in,
4
- // databases of their own, and the Restate SDK as @restatedev/sessions runs it (its
5
- // own copy, so that a library's journaled handlers serve beside its objects).
1
+ // Internal exports. For tests: attempts and databases over their own hosts
2
+ // and stores. For the libraries in this repository: schemas, extra databases,
3
+ // keep-alive scopes, and the copy of the Restate SDK that @restatedev/sessions
4
+ // runs, so that journaled handlers of a library serve beside its objects.
6
5
  export * as sdk from '@restatedev/restate-sdk';
7
6
  export { ensureSchemas, Schema } from './schema.ts';
7
+ export { asDatabase, lazyDatabase, database, Attempt } from './session.ts';
8
8
  export {
9
- asDatabase,
10
- lazyDatabase,
11
- database,
12
- reset,
13
- deferSql,
14
- undeferSql,
15
- rideCommit,
16
- flushRiders,
17
- Attempt,
18
- withAttempt,
19
- } from './session.ts';
20
- export type { ObjectConfig, SqlHost } from './session.ts';
21
- export { Link } from './link.ts';
22
- export { ScopeKey } from './scope.ts';
23
- export { open, type Connection, type Store, type ConnectionTransaction, type Working } from './database.ts';
24
- // The attempt on the explicit recovery VM, for the tests that drive one.
25
- export { AttemptDriver, AttemptFailed, AttemptShutDown } from './driver.ts';
26
- export { Vm, isShutDown } from './vm.ts';
27
- export { serveSession, servedHere, type Stream } from './handler.ts';
28
- export { needing, served } from './serve.ts';
29
- export { invokeRoute, patchEndpoint } from './endpoint.ts';
30
- export {
31
- attach,
32
- cancelCalls,
33
- cancelled,
34
- configOf,
35
- contextOf,
36
- definitionOf,
37
- HEAD_KEY,
38
- invoke,
39
- start,
40
- withStoreWrapper,
41
- type AttemptContext,
42
- } from './object.ts';
9
+ open,
10
+ type Connection,
11
+ type Store,
12
+ type ConnectionTransaction,
13
+ type Stoppable,
14
+ type Suspendable,
15
+ type Working,
16
+ } from './database.ts';
17
+ // For tests that drive an attempt on the VM.
18
+ export { AttemptDriver, AttemptShutDown } from './driver.ts';
19
+ export type { AttemptHost } from './host.ts';
20
+ // For test attempts, and for integrations whose framework hooks hold scopes open (see stop.ts).
21
+ export { locateScopes, type Scope, Stop } from './stop.ts';
22
+ export { Vm } from './vm.ts';
23
+ export { served } from './serve.ts';
24
+ export { configOf, contextOf, HEAD_KEY, invoke, openScope, withAttempt } from './object.ts';
25
+ // The explicit recovery protocol: its content type, the discovery manifest
26
+ // this package serves, and the end of the attempts a process serves when it
27
+ // goes away (endpoint.ts).
28
+ export { goAway, CONTENT_TYPE } from './handler.ts';
29
+ export { manifestV6 } from './endpoint.ts';
30
+ // What the protocol adds beyond calls and sends, for libraries (provisional).
31
+ export { invocationState, readSignal, sendSignal, flush, type InvocationState } from './object.ts';
package/src/link.ts CHANGED
@@ -1,8 +1,7 @@
1
- // A private link on the objects this code makes: set once, as it makes one,
2
- // and read by its code alone (a database's session, a transaction's reset, a
3
- // definition's own). Not enumerable, so the object reads as its fields alone.
1
+ // A private link from an object this package makes to a value (the attempt
2
+ // behind a `ctx.db`, the stop of a context): set once at creation and read
3
+ // only by this package. Not enumerable, so the object shows only its fields.
4
4
 
5
- /** A link of one kind, on the objects that have one. */
6
5
  export class Link<T> {
7
6
  private readonly key: symbol;
8
7
 
@@ -10,7 +9,7 @@ export class Link<T> {
10
9
  this.key = Symbol(what);
11
10
  }
12
11
 
13
- /** `owner`, linked to `value`: once, as it is made (before it is frozen). */
12
+ /** Link `owner` to `value`, once, before it is frozen. */
14
13
  on<O extends object>(owner: O, value: T): O {
15
14
  return Object.defineProperty(owner, this.key, { value });
16
15
  }