@restatedev/sessions 0.8.0 → 0.10.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 (62) hide show
  1. package/README.md +64 -31
  2. package/dist/addon.d.ts +9 -0
  3. package/dist/addon.d.ts.map +1 -0
  4. package/dist/addon.js +20 -0
  5. package/dist/addon.js.map +1 -0
  6. package/dist/database.d.ts +13 -0
  7. package/dist/database.d.ts.map +1 -1
  8. package/dist/database.js +44 -17
  9. package/dist/database.js.map +1 -1
  10. package/dist/driver.d.ts +186 -0
  11. package/dist/driver.d.ts.map +1 -0
  12. package/dist/driver.js +549 -0
  13. package/dist/driver.js.map +1 -0
  14. package/dist/endpoint.d.ts +13 -0
  15. package/dist/endpoint.d.ts.map +1 -0
  16. package/dist/endpoint.js +186 -0
  17. package/dist/endpoint.js.map +1 -0
  18. package/dist/handler.d.ts +35 -0
  19. package/dist/handler.d.ts.map +1 -0
  20. package/dist/handler.js +218 -0
  21. package/dist/handler.js.map +1 -0
  22. package/dist/index.d.ts +1 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +4 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/internal.d.ts +5 -3
  27. package/dist/internal.d.ts.map +1 -1
  28. package/dist/internal.js +8 -4
  29. package/dist/internal.js.map +1 -1
  30. package/dist/object.d.ts +15 -2
  31. package/dist/object.d.ts.map +1 -1
  32. package/dist/object.js +51 -12
  33. package/dist/object.js.map +1 -1
  34. package/dist/serve.d.ts +19 -26
  35. package/dist/serve.d.ts.map +1 -1
  36. package/dist/serve.js +21 -30
  37. package/dist/serve.js.map +1 -1
  38. package/dist/session.d.ts +32 -2
  39. package/dist/session.d.ts.map +1 -1
  40. package/dist/session.js +59 -9
  41. package/dist/session.js.map +1 -1
  42. package/dist/vm.d.ts +151 -0
  43. package/dist/vm.d.ts.map +1 -0
  44. package/dist/vm.js +28 -0
  45. package/dist/vm.js.map +1 -0
  46. package/package.json +4 -4
  47. package/src/addon.ts +29 -0
  48. package/src/database.ts +48 -19
  49. package/src/driver.ts +653 -0
  50. package/src/endpoint.ts +220 -0
  51. package/src/handler.ts +272 -0
  52. package/src/index.ts +4 -2
  53. package/src/internal.ts +8 -5
  54. package/src/object.ts +75 -13
  55. package/src/serve.ts +26 -39
  56. package/src/session.ts +77 -8
  57. package/src/vm.ts +195 -0
  58. package/dist/selector.d.ts +0 -129
  59. package/dist/selector.d.ts.map +0 -1
  60. package/dist/selector.js +0 -251
  61. package/dist/selector.js.map +0 -1
  62. package/src/selector.ts +0 -323
package/src/object.ts CHANGED
@@ -20,9 +20,9 @@ import type { Serde, VirtualObjectDefinition } from '@restatedev/restate-sdk-cor
20
20
  import { type CallOptions, type Rpc, rpcOf, type Send, sendOf, type Target } from './calls.ts';
21
21
  import type { DatabaseReader, Store } from './database.ts';
22
22
  import { ensureOf, ensuring, Schema, type Step } from './schema.ts';
23
+ import { patchEndpoint } from './endpoint.ts';
23
24
  import { Link } from './link.ts';
24
25
  import { holding, Scope, scopeOf } from './scope.ts';
25
- import { hookSelector } from './selector.ts';
26
26
  import { type Database, Attempt, type ObjectConfig, type SqlHost, withAttempt } from './session.ts';
27
27
 
28
28
  /**
@@ -147,6 +147,8 @@ export function host(
147
147
  clear: (name, entry) => exclusive.clear(name, entry),
148
148
  stateKeys: () => ctx.stateKeys(),
149
149
  run: (name, action) => exclusive.run(name, action),
150
+ vm: (ctx as { vm?: SqlHost['vm'] }).vm,
151
+ takeCancellation: (ctx as { takeCancellation?: SqlHost['takeCancellation'] }).takeCancellation,
150
152
  genericSend: (send) => ctx.genericSend(send),
151
153
  };
152
154
  }
@@ -157,14 +159,44 @@ interface ObjectState {
157
159
  definition?: object;
158
160
  }
159
161
 
160
- /** A handler or view of a session object: its function, kind, and object. */
162
+ /** A handler or view of a session object: its function, kind, serdes, and object. */
161
163
  interface HandlerEntry {
162
164
  fn: Fn<never>;
163
165
  view: boolean;
164
166
  explicit: boolean;
167
+ /** How its input and output are encoded, as its options set them; JSON by default. */
168
+ inputSerde: Serde<unknown>;
169
+ outputSerde: Serde<unknown>;
170
+ /** The handler option of the same name: which errors end the invocation rather than retrying. */
171
+ asTerminalError?: (error: unknown) => Error | undefined;
165
172
  object: ObjectState;
166
173
  }
167
174
 
175
+ /**
176
+ * The handler or view `name` of `definition`, if it is a session object's:
177
+ * what {@link serveSession} needs to run an attempt of it on the VM.
178
+ */
179
+ export function handlerEntry(
180
+ definition: object,
181
+ name: string,
182
+ ):
183
+ | {
184
+ view: boolean;
185
+ explicit: boolean;
186
+ inputSerde: Serde<unknown>;
187
+ outputSerde: Serde<unknown>;
188
+ asTerminalError?: (error: unknown) => Error | undefined;
189
+ }
190
+ | undefined {
191
+ const entry = OBJECT.of(definition)?.entries.get(name);
192
+ if (entry === undefined) return undefined;
193
+ const { view, explicit, inputSerde, outputSerde, asTerminalError } = entry;
194
+ return { view, explicit, inputSerde, outputSerde, asTerminalError };
195
+ }
196
+
197
+ /** Whether `definition` is a session object: it has handlers this package runs. */
198
+ export const isSessionObject = (definition: object): boolean => OBJECT.of(definition) !== undefined;
199
+
168
200
  /** A session object's own, on its definition: for {@link invoke} and {@link withStoreWrapper}. */
169
201
  const OBJECT = new Link<{ object: ObjectState; entries: Map<string, HandlerEntry> }>('a session object');
170
202
 
@@ -260,13 +292,26 @@ function attempt({ fn, view, explicit, object }: HandlerEntry, ctx: AttemptConte
260
292
  return withAttempt(() => fn(context as never, input as never), session);
261
293
  }
262
294
 
263
- /** `entry` as the SDK's handler: one loop drives each attempt's awaits (see selector.ts), until it ends. */
264
- function wrap(entry: HandlerEntry) {
265
- return (ctx: restate.ObjectContext | restate.ObjectSharedContext, input: never) => {
266
- const unhook = hookSelector(ctx);
267
- const runtime = ctx as unknown as Runtime;
268
- runtime.invocationEndPromise.promise.catch(unhook);
269
- return attempt(entry, ctx as unknown as AttemptContext, input).finally(unhook);
295
+ /**
296
+ * `entry` as the SDK's handler, which only a transport `endpoint.ts` does not
297
+ * reach can call: it routes a session object's invocation to the explicit
298
+ * recovery VM ahead of this, on every endpoint built from `NodeEndpoint` —
299
+ * `restate.endpoint()`, `restate.serve` and `connect`'s tunnel alike.
300
+ *
301
+ * Reaching here means the endpoint is one the patch does not cover, a fetch
302
+ * endpoint being the one that exists. A session object cannot run on the
303
+ * SDK's journaled VM: it is never replayed, and awaiting two things at once
304
+ * fails the attempt with `awaitNext already pending`. So it is refused, rather
305
+ * than half-served.
306
+ */
307
+ function wrap(objectName: string, name: string) {
308
+ return () => {
309
+ throw new restate.TerminalError(
310
+ `@restatedev/sessions: ${objectName}.${name} is a session object's handler, which runs on the explicit ` +
311
+ 'recovery VM. This endpoint does not route to it: serve the object from an endpoint built on the ' +
312
+ "SDK's node entry point (`restate.endpoint()`, `restate.serve` or `connect`). A fetch endpoint " +
313
+ 'cannot run one.',
314
+ );
270
315
  };
271
316
  }
272
317
 
@@ -304,8 +349,21 @@ function handlerOf(objectName: string, name: string, entry: unknown, view: boole
304
349
  }
305
350
  const opts = { ...options, ...recovery() } as HandlerOptions;
306
351
  const explicit = (options as HandlerOptions).explicitCancellation === true;
307
- const made: HandlerEntry = { fn: fn as Fn<never>, view, explicit, object };
308
- const sdk = wrap(made) as never;
352
+ const serdes = options as {
353
+ input?: Serde<unknown>;
354
+ output?: Serde<unknown>;
355
+ asTerminalError?: (error: unknown) => Error | undefined;
356
+ };
357
+ const made: HandlerEntry = {
358
+ fn: fn as Fn<never>,
359
+ view,
360
+ explicit,
361
+ inputSerde: serdes.input ?? (restate.serde.json as Serde<unknown>),
362
+ outputSerde: serdes.output ?? (restate.serde.json as Serde<unknown>),
363
+ asTerminalError: serdes.asTerminalError,
364
+ object,
365
+ };
366
+ const sdk = wrap(objectName, name) as never;
309
367
  const handler = view ? restate.handlers.object.shared(opts, sdk) : restate.handlers.object.exclusive(opts, sdk);
310
368
  return { handler, entry: made };
311
369
  }
@@ -339,6 +397,10 @@ export function sessionObject<
339
397
  metadata?: Record<string, string>;
340
398
  options?: restate.ObjectOptions;
341
399
  }): VirtualObjectDefinition<P, Functions<H> & Functions<V>> {
400
+ // Every way the SDK hands out a request handler now routes this object's
401
+ // invocations to the explicit recovery VM (`endpoint.ts`). Installed here
402
+ // rather than on import: the package declares `sideEffects: false`.
403
+ patchEndpoint();
342
404
  const { name, schema, handlers = {}, views = {}, description, metadata, options } = definition;
343
405
  const both = Object.keys(handlers).filter((key) => key in views);
344
406
  if (both.length > 0) throw new Error(`${name}: ${both.join(', ')} is a handler and a view: name one otherwise`);
@@ -436,8 +498,8 @@ function explicitOf(ctx: SessionContext, of: string) {
436
498
  *
437
499
  * It watches for the cancellation, and holds nothing: awaited alone, it does
438
500
  * not suspend the invocation, and Restate is not told that the handler waits
439
- * (see selector.ts: the attempt's journal has a run named `work` instead,
440
- * for the handler's own work). The cancel signal comes while Restate keeps
501
+ * (a heartbeat tells Restate the attempt makes progress instead, see
502
+ * `driver.ts`). The cancel signal comes while Restate keeps
441
503
  * the invocation's input open. Once Restate closed it (the handler sent and
442
504
  * got nothing for the inactivity timeout), a cancellation resolves this at
443
505
  * the handler's next await of Restate's, which suspends the invocation and
package/src/serve.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  // `serve`: the services of a program, on PORT, with what they need beside
2
2
  // them (a library's objects, such as each @restatedev/agents agent's companion).
3
+ //
4
+ // A session object's invocations run on the explicit recovery VM whichever of
5
+ // these serves them, and so does an endpoint built by hand: `endpoint.ts`
6
+ // wraps the SDK's endpoint class, which every transport builds its request
7
+ // handler from.
3
8
  import * as restate from '@restatedev/restate-sdk';
4
9
  import { isRemote } from './calls.ts';
5
10
 
@@ -17,51 +22,33 @@ export const needing = <D extends object>(definition: D, services: () => Service
17
22
  Object.defineProperty(definition, NEEDS, { value: services });
18
23
 
19
24
  /**
20
- * Serve `services`, with the services they need beside them, each once:
25
+ * Serve `services` on PORT (default 9080), with the services they need
26
+ * beside them, each once. RESTATE_SERVE_ONLY, names separated by commas
27
+ * (`triage,planner`), serves only those of them, each with what it needs
28
+ * beside it: one program (or image), deployed in parts.
21
29
  *
22
30
  * await restate.serve(notes, orders);
23
- *
24
- * On PORT (default 9080), for a Restate server that calls in. With
25
- * RESTATE_CONNECT_KEY set, it connects out to Restate Cloud instead, under
26
- * RESTATE_CONNECT_NAME (the deployment you register,
27
- * `connect://<name>`): the same program, deployed either way, with nothing
28
- * to change in it.
29
- *
30
- * RESTATE_SERVE_ONLY, names separated by commas (`triage,planner`), serves
31
- * only those of them, each with what it needs beside it: one program (or
32
- * image), deployed in parts.
33
31
  */
34
- export const serve = (...services: Service[]) => {
35
- const plan = serving(services);
36
- return plan.connect === undefined
37
- ? restate.serve({ services: plan.services, port: plan.port })
38
- : restate.connect({ services: plan.services, ...plan.connect });
39
- };
40
-
41
- /** What {@link serve} does with `services`, by the environment: see {@link serving}. */
42
- export interface Serving {
43
- /** The services it binds, each with what it needs beside it. */
44
- services: Service[];
45
- /** Set when it connects out: the deployment name to register, if the environment names one. */
46
- connect?: { name?: string };
47
- /** The port it listens on, when it does not connect out. */
48
- port?: number;
49
- }
32
+ export const serve = (...services: Service[]) =>
33
+ restate.serve({ services: served(services, process.env.RESTATE_SERVE_ONLY), port: Number(process.env.PORT ?? 9080) });
50
34
 
51
35
  /**
52
- * What {@link serve} does with `services` under `env`, decided and not done:
53
- * which services it binds, and whether it listens or connects out. A pure
54
- * function, so that a program (or a tool) can ask before anything is served.
36
+ * Connect out to Restate Cloud, rather than listening for it: the SDK's
37
+ * `connect`, with the services it needs beside them, each once (the SDK's
38
+ * own leaves them out, so an agent would run without its companion).
39
+ *
40
+ * restate.connect({ services: [notes, orders], name: 'notes-v1' });
41
+ *
42
+ * `name` is the deployment you register (`connect://notes-v1`); the key is
43
+ * RESTATE_CONNECT_KEY. RESTATE_SERVE_ONLY applies as it does to
44
+ * {@link serve}. It returns the SDK's `Connection` and does not wait for
45
+ * the handshake: `await restate.connect(…).ready` is what waits.
55
46
  */
56
- export function serving(services: Service[], env: Record<string, string | undefined> = process.env): Serving {
57
- const bound = served(services, env.RESTATE_SERVE_ONLY);
58
- // Blank counts as unset, as it does in the SDK (its `readEnv` maps '' to
59
- // undefined): `RESTATE_CONNECT_KEY=` in a .env, or `${RESTATE_CONNECT_KEY:-}`
60
- // in a compose file, would otherwise connect out and fail for want of a key.
61
- if (!env.RESTATE_CONNECT_KEY) return { services: bound, port: Number(env.PORT ?? 9080) };
62
- const name = env.RESTATE_CONNECT_NAME;
63
- return { services: bound, connect: name ? { name } : {} };
64
- }
47
+ export const connect = (options: ConnectOptions) =>
48
+ restate.connect({ ...options, services: served(options.services, process.env.RESTATE_SERVE_ONLY) });
49
+
50
+ /** {@link connect}'s options: the SDK's, whose `services` this module completes. */
51
+ type ConnectOptions = Omit<Parameters<typeof restate.connect>[0], 'services'> & { services: Service[] };
65
52
 
66
53
  /**
67
54
  * What {@link serve} serves of `services`: each with what it needs beside
package/src/session.ts CHANGED
@@ -5,10 +5,11 @@
5
5
  import { Buffer } from 'node:buffer';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import type * as restate from '@restatedev/restate-sdk';
8
- import { serde, TerminalError } from '@restatedev/restate-sdk';
8
+ import { CancelledError, serde, TerminalError } from '@restatedev/restate-sdk';
9
9
  import { millisOrDurationToMillis, type Serde } from '@restatedev/restate-sdk-core';
10
10
  import {
11
11
  open,
12
+ openOnVm,
12
13
  type Row,
13
14
  sqlOver,
14
15
  SqlError,
@@ -20,6 +21,7 @@ import {
20
21
  type Store,
21
22
  type ConnectionTransaction,
22
23
  } from './database.ts';
24
+ import type { Vm } from './vm.ts';
23
25
  import { Link } from './link.ts';
24
26
  import { apply, dropAll, ensureOf, ensuring, type Schema } from './schema.ts';
25
27
  import { type Send, sendOf } from './calls.ts';
@@ -69,6 +71,19 @@ export interface SqlHost {
69
71
  /** The object's state keys. */
70
72
  stateKeys(): PromiseLike<string[]>;
71
73
  run(name: string, action: () => void): PromiseLike<void>;
74
+ /**
75
+ * The attempt's VM, when it has one: the addon then reads and writes the
76
+ * object's state as the VM's own commands, and none of it crosses into
77
+ * JavaScript (see `openOnVm`).
78
+ */
79
+ readonly vm?: Vm;
80
+ /**
81
+ * Whether a cancellation is owed to the handler's next await, taking it:
82
+ * the attempt's driver has one when a cancellation arrived that failed
83
+ * nothing the handler awaits. Absent where the SDK's context serves the
84
+ * attempt, whose own awaits fail with it.
85
+ */
86
+ readonly takeCancellation?: () => boolean;
72
87
  genericSend(send: restate.GenericSend<Uint8Array>): unknown;
73
88
  }
74
89
 
@@ -161,6 +176,26 @@ const unbeside = (name: string) => (key: string) => {
161
176
  * the life of the process. One the SDK cancels fails as any await does: the
162
177
  * session it ends fails its calls with the CancelledError (see `open`).
163
178
  */
179
+ /**
180
+ * The store of a database the addon keeps on the VM: it reads and writes the
181
+ * state itself, and calls this only at a commit, through `sync`, where the
182
+ * boundary runs what the committing transaction gave `withCommit`. Reaching
183
+ * anything else is a bug in the addon, and says so rather than going quiet.
184
+ */
185
+ function commitOnly(): Store {
186
+ return {
187
+ get: servedByVm('get'),
188
+ set: servedByVm('set'),
189
+ clear: servedByVm('clear'),
190
+ sync: async () => {},
191
+ };
192
+ }
193
+
194
+ /** What a store the addon never calls does if it is called after all. */
195
+ const servedByVm = (op: string) => () => {
196
+ throw new Error(`@restatedev/sessions: the VM serves the state; the store's ${op} is not called`);
197
+ };
198
+
164
199
  function objectStore(ctx: SqlHost, end: AttemptEnd, dbName: string | undefined): Store {
165
200
  const keyOf = dbName === undefined ? (key: string) => key : beside(dbName);
166
201
  const request = <T>(promise: PromiseLike<T>) => end.race(promise);
@@ -444,10 +479,10 @@ export class Attempt {
444
479
  this.name = name;
445
480
  this.hasOutbox = !ctx.shared && name === undefined;
446
481
  this.db = {
447
- ...sqlOver((sql, params) => this.call((db) => db.queryColumns(sql, params)), handlerError),
448
- transaction: (body) => this.transaction(body),
482
+ ...sqlOver((sql, params) => this.asked(() => this.call((db) => db.queryColumns(sql, params))), handlerError),
483
+ transaction: (body) => this.asked(() => this.transaction(body)),
449
484
  };
450
- ensuring(this.db, (schemas) => this.call((db) => this.ensureSchemas(db, schemas)));
485
+ ensuring(this.db, (schemas) => this.asked(() => this.call((db) => this.ensureSchemas(db, schemas))));
451
486
  ATTEMPT.on(this.db, this);
452
487
  }
453
488
 
@@ -459,6 +494,26 @@ export class Attempt {
459
494
  return other.db;
460
495
  }
461
496
 
497
+ /**
498
+ * `call`, which the handler asked for, unless a cancellation is owed to
499
+ * it: then the call fails with the cancellation, and does nothing.
500
+ *
501
+ * This is where the database delivers a cancellation, and the only place.
502
+ * What the handler asks for passes through here; what the session does for
503
+ * itself does not — the open, the object's schema, the sends a crashed
504
+ * attempt left unmade, emptying the outbox after a commit — and a
505
+ * cancellation that failed one of those would be delivered to nobody, or
506
+ * would report a transaction as cancelled after it committed. And it is
507
+ * before the call issues anything, so a call that fails with
508
+ * `CancelledError` wrote nothing and sent nothing: a call already under way
509
+ * when the cancellation arrives runs to its end, and the cancellation goes
510
+ * to what the handler awaits next.
511
+ */
512
+ private asked<T>(call: () => Promise<T>): Promise<T> {
513
+ if (this.ctx.takeCancellation?.()) return Promise.reject(new CancelledError());
514
+ return call();
515
+ }
516
+
462
517
  /**
463
518
  * Open the session now, as the attempt starts, rather than on its first
464
519
  * call: the open makes the sends a crashed attempt committed and left
@@ -486,8 +541,8 @@ export class Attempt {
486
541
  * handler, its sends commit with it, in the outbox, and are made with its
487
542
  * commit, right after its writes and before it waits for anything
488
543
  * (`withCommit`): Restate stores an attempt's commands in order, so they
489
- * are stored only if the commit is, and whatever fails the commit's wait (a
490
- * cancellation, say) comes after them. A second commit empties the outbox
544
+ * are stored only if the commit is, and whatever fails the commit's wait
545
+ * (the attempt's end, say) comes after them. A second commit empties the outbox
491
546
  * before `transaction` resolves: left until the handler's end, they would
492
547
  * be made again by an attempt that resumes a long wait (an approval), past
493
548
  * the idempotency retention that drops a repeat.
@@ -564,9 +619,23 @@ export class Attempt {
564
619
  // database (a name has no `/`).
565
620
  const key = `${ctx.request().target.service}/${encodeURIComponent(ctx.key)}`;
566
621
  const namespace = this.name === undefined ? key : `${key}/${this.name}`;
567
- const object = objectStore(ctx, end, this.name);
568
622
  const wrap = this.config.wrapStore;
569
- const db = await open(namespace, wrap ? wrap(object) : object, { reader: ctx.shared });
623
+ // With a VM, the addon reads and writes the state itself and nothing of
624
+ // the store crosses into JavaScript. A wrapper (fault injection, through
625
+ // `withStoreWrapper`) would then have nothing to wrap, and using the
626
+ // JavaScript store instead would quietly test the other path: the tests
627
+ // that wrap give their attempts no VM, so this says so rather than
628
+ // choosing for them.
629
+ if (ctx.vm !== undefined && wrap !== undefined) {
630
+ throw new TerminalError(
631
+ 'withStoreWrapper wraps the store of an attempt served by the SDK; an attempt on the VM has none to wrap',
632
+ );
633
+ }
634
+ const onVm = ctx.vm !== undefined;
635
+ const object = onVm ? commitOnly() : objectStore(ctx, end, this.name);
636
+ const db = onVm
637
+ ? await openOnVm(namespace, object, ctx.vm, { name: this.name, reader: ctx.shared })
638
+ : await open(namespace, wrap ? wrap(object) : object, { reader: ctx.shared });
570
639
  try {
571
640
  // A view writes nothing: a write fails, rather than vanish with the attempt.
572
641
  if (ctx.shared) await db.execute('PRAGMA query_only = 1');
package/src/vm.ts ADDED
@@ -0,0 +1,195 @@
1
+ // The VM of a session object's attempt: shared-core's explicit recovery state
2
+ // machine, through the addon (`native/src/vm.rs`).
3
+ //
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.
10
+ //
11
+ // The VM is synchronous and does no I/O: every call only buffers output.
12
+ import { addon } from './addon.ts';
13
+
14
+ /** A header of the request, or of a call. */
15
+ export interface VmHeader {
16
+ key: string;
17
+ value: string;
18
+ }
19
+
20
+ /** A terminal failure: what a handler throws, and what a failed action completes with. */
21
+ export interface VmFailure {
22
+ code: number;
23
+ message: string;
24
+ metadata: VmHeader[];
25
+ }
26
+
27
+ /** The response's head: written before the body. */
28
+ export interface VmResponseHead {
29
+ statusCode: number;
30
+ headers: VmHeader[];
31
+ }
32
+
33
+ /** The invocation's input, once the VM is ready to execute. */
34
+ export interface VmInput {
35
+ invocationId: string;
36
+ key: string;
37
+ headers: VmHeader[];
38
+ input: Buffer;
39
+ scope?: string;
40
+ limitKey?: string;
41
+ idempotencyKey?: string;
42
+ }
43
+
44
+ /** The handles of a call: its invocation id, and its result. */
45
+ export interface VmCallHandle {
46
+ invocationId: number;
47
+ result: number;
48
+ }
49
+
50
+ /** A ready result: `kind` says which field holds it. */
51
+ export type VmNotification = { handle: number } & (
52
+ | { kind: 'void' }
53
+ | { kind: 'success'; bytes: Buffer }
54
+ | { kind: 'failure'; failure: VmFailure }
55
+ | { kind: 'stateKeys'; keys: string[] }
56
+ | { kind: 'invocationId'; id: string }
57
+ );
58
+
59
+ /** Where the attempt is: `starting` until the input is in, then `running`, then `closed`. */
60
+ export type VmState = 'starting' | 'running' | 'closed';
61
+
62
+ /**
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.
66
+ */
67
+ export interface Vm {
68
+ /**
69
+ * What the VM calls, on this thread, after the addon acts on it from the
70
+ * runtime's — the database's store reading or writing the object's state.
71
+ * It is the driver's tick: it writes the output and settles what completed.
72
+ */
73
+ setScheduler(scheduler: () => void): void;
74
+
75
+ getResponseHead(): VmResponseHead;
76
+
77
+ notifyInput(buffer: Uint8Array): void;
78
+ /** The runtime closed the input stream. While the handler runs, this shuts the attempt down. */
79
+ notifyInputClosed(): void;
80
+ /** The bytes buffered so far for the response body. */
81
+ takeOutput(): Buffer;
82
+
83
+ isReadyToExecute(): boolean;
84
+ input(): VmInput;
85
+
86
+ /**
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.
89
+ */
90
+ takeNotification(): VmNotification | null;
91
+
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,
101
+ buffer: Uint8Array,
102
+ key?: string,
103
+ idempotencyKey?: string,
104
+ headers?: VmHeader[],
105
+ name?: string,
106
+ ): VmCallHandle;
107
+ /** 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;
125
+
126
+ /** Tells Restate the attempt makes progress, delaying its shutdown. */
127
+ heartbeat(): void;
128
+ /** Whether the invocation was cancelled, in this attempt or an earlier one. */
129
+ isCancelled(): boolean;
130
+ /**
131
+ * 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.
134
+ */
135
+ endStateWaits(): void;
136
+ /**
137
+ * Let go of the scheduler. It holds the driver's tick, and so the driver and
138
+ * this VM: an attempt that kept it would never be freed.
139
+ */
140
+ clearScheduler(): void;
141
+ state(): VmState;
142
+
143
+ endSuccess(buffer: Uint8Array): void;
144
+ endFailure(failure: VmFailure): void;
145
+ /** Fails the attempt, for example with a retryable error of the handler. */
146
+ notifyError(message: string, stacktrace?: string, delayOverrideMs?: number): void;
147
+ }
148
+
149
+ interface VmConstructor {
150
+ /**
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.
154
+ */
155
+ new (headers: VmHeader[], bidirectional: boolean): Vm;
156
+ }
157
+
158
+ export const Vm = (addon as { Vm: VmConstructor }).Vm;
159
+
160
+ /**
161
+ * 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.
164
+ */
165
+ export interface Identity {
166
+ /**
167
+ * `null` if the headers carry a signature of `path` by one of the keys, and
168
+ * why not otherwise. It is `null` and not `undefined`: the addon answers
169
+ * `None`, which is how that crosses the boundary.
170
+ */
171
+ verify(path: string, headers: VmHeader[]): string | null;
172
+ }
173
+
174
+ interface IdentityConstructor {
175
+ /** The v1 public keys a deployment accepts (`publickeyv1_…`). */
176
+ new (keys: string[]): Identity;
177
+ }
178
+
179
+ export const Identity = (addon as { Identity: IdentityConstructor }).Identity;
180
+
181
+ /**
182
+ * What the database's store's waits fail with once the attempt is over, as
183
+ * the addon's errors carry it: the text crosses the boundary, the class does
184
+ * not (`native/src/vm.rs`).
185
+ */
186
+ export const STATE_WAIT_OVER = 'restate-sessions: the attempt is over';
187
+
188
+ /** The message of the error a closed attempt throws when Restate shut it down. */
189
+ const SHUT_DOWN = 'ATTEMPT_SHUT_DOWN';
190
+
191
+ /**
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.
194
+ */
195
+ export const isShutDown = (error: unknown): boolean => error instanceof Error && error.message.startsWith(SHUT_DOWN);