@restatedev/sessions 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 -236
  62. package/dist/session.d.ts.map +1 -1
  63. package/dist/session.js +206 -513
  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 -613
  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/session.ts CHANGED
@@ -1,12 +1,10 @@
1
- // An attempt's database: the session's database, kept in the object's state
2
- // (database.ts), opened as an exclusive attempt starts (a view's on its first
3
- // read) and saved when the handler ends; and its transactions, with the sends
4
- // each commits with (`tx.send`).
5
- import { Buffer } from 'node:buffer';
6
- import { randomUUID } from 'node:crypto';
1
+ // The database of one attempt (`ctx.db`, over database.ts): opened when an
2
+ // exclusive attempt starts (a view opens it on first read) and saved when the
3
+ // handler ends. Also transactions and their sends (`tx.send`), which commit
4
+ // with them: on the VM, inside the commit's atomic group.
7
5
  import type * as restate from '@restatedev/restate-sdk';
8
6
  import { CancelledError, serde, TerminalError } from '@restatedev/restate-sdk';
9
- import { millisOrDurationToMillis, type Serde } from '@restatedev/restate-sdk-core';
7
+ import { millisOrDurationToMillis } from '@restatedev/restate-sdk-core';
10
8
  import {
11
9
  open,
12
10
  openOnVm,
@@ -20,27 +18,22 @@ import {
20
18
  type SqlValue,
21
19
  type Store,
22
20
  type ConnectionTransaction,
23
- type Working,
24
21
  } from './database.ts';
25
- import type { Vm } from './vm.ts';
22
+ import type { AttemptHost } from './host.ts';
23
+ import type { VmGroupSend } from './vm.ts';
26
24
  import { Link } from './link.ts';
27
- import { apply, dropAll, ensureOf, ensuring, type Schema } from './schema.ts';
25
+ import { apply, ensureOf, ensuring, type Schema } from './schema.ts';
28
26
  import { type Send, sendOf } from './calls.ts';
29
27
 
30
28
  export type { DatabaseReader, DatabaseWriter, Row, SqlParam, SqlValue };
31
29
 
32
- /**
33
- * The session's database, `ctx.db`, for the whole handler: each statement
34
- * outside {@link transaction} is its own transaction. Calls run one at a
35
- * time, in call order.
36
- */
30
+ /** `ctx.db`. Each statement outside {@link transaction} is its own transaction. Calls run in call order. */
37
31
  export interface Database extends DatabaseWriter {
38
32
  /**
39
33
  * Run `body` as one transaction: it commits when `body` resolves, and rolls
40
- * back when it rejects. It holds the database: other calls wait until it
41
- * ends, and a call to the database from inside `body` is refused, as it
42
- * would wait for `body`. So `body` uses the `tx` it gets, which is invalid
43
- * once `body` settles.
34
+ * back when it rejects. Other calls wait until it ends. A call to `ctx.db`
35
+ * from inside `body` is refused, because it would wait for `body`: use the
36
+ * `tx` that `body` gets, which is invalid once `body` settles.
44
37
  */
45
38
  transaction<T>(body: (tx: Transaction) => Promise<T>): Promise<T>;
46
39
  }
@@ -48,132 +41,58 @@ export interface Database extends DatabaseWriter {
48
41
  /** One transaction of a {@link Database}: its SQL, and the sends it commits with. */
49
42
  export interface Transaction extends DatabaseWriter {
50
43
  /**
51
- * Sends made right after the transaction commits, and never if it rolls
52
- * back. Each has the idempotency key it is given, or else one of the
53
- * transaction (`transaction/<id>/<index>`), so a send an attempt makes
54
- * again is dropped.
44
+ * Sends that commit with the transaction, and never if it rolls back: on
45
+ * Restate, in the commit's atomic group, so the rows and the sends are
46
+ * stored together or not at all. A delay counts from the commit.
55
47
  */
56
48
  readonly send: Send;
57
- /**
58
- * Settles, and never rejects, once another call to `ctx.db` waits for this
59
- * transaction to end. A body that keeps the transaction open for more work
60
- * can return when it settles, so that the other call waits for one commit
61
- * and no more.
62
- */
63
- readonly queued: Promise<void>;
64
49
  }
65
50
 
66
- /** What the session needs of the handler's context. */
67
- export interface SqlHost {
68
- /** A shared handler's: it reads beside the exclusive one, and stores nothing. */
69
- readonly shared: boolean;
70
- readonly key: string;
71
- /** Rejects when the attempt ends (suspended, or aborted). */
72
- readonly invocationEndPromise: { readonly promise: Promise<unknown> };
73
- // oxlint-disable-next-line typescript/no-explicit-any
74
- readonly defaultSerde: Serde<any>;
75
- request(): { readonly id: string; readonly target: { readonly service: string } };
76
- get(name: string, serde: Serde<Uint8Array>, options: restate.EntryOptions): PromiseLike<Uint8Array | null>;
77
- set(name: string, value: Uint8Array, serde: Serde<Uint8Array>, options: restate.EntryOptions): void;
78
- clear(name: string, options: restate.EntryOptions): void;
79
- /** The object's state keys. */
80
- stateKeys(): PromiseLike<string[]>;
81
- run(name: string, action: () => void): PromiseLike<void>;
82
- /**
83
- * The attempt's VM, when it has one: the addon then reads and writes the
84
- * object's state as the VM's own commands, and none of it crosses into
85
- * JavaScript (see `openOnVm`).
86
- */
87
- readonly vm?: Vm;
88
- /**
89
- * Whether a cancellation is owed to the handler's next await, taking it:
90
- * the attempt's driver has one when a cancellation arrived that failed
91
- * nothing the handler awaits. Absent where the SDK's context serves the
92
- * attempt, whose own awaits fail with it.
93
- */
94
- readonly takeCancellation?: () => boolean;
95
- /**
96
- * Keeps the attempt alive while a call of the database runs: the VM's
97
- * attempt has it (`driver.ts`), the SDK's context does not.
98
- */
99
- readonly working?: Working;
100
- genericSend(send: restate.GenericSend<Uint8Array>): unknown;
101
- }
102
-
103
- /** What a session object gives its attempts: its schema, and a wrapper of its store (fault injection, in tests). */
51
+ /** What a session object gives its attempts. */
104
52
  export interface ObjectConfig {
105
- /** The object's own schema, which each of its databases is made by. */
106
53
  readonly schema?: Schema;
107
- wrapStore?: (store: Store) => Store;
54
+ /** The serde of a typed client's `tx.send` to a handler that declares none: the `serde` option, JSON by default. */
55
+ readonly serde?: restate.Serde<unknown>;
108
56
  }
109
57
 
110
- /** The end of an attempt, as `invocationEndPromise` rejects with it, for the requests that would otherwise wait for it. */
111
- class AttemptEnd {
112
- private ended: Error | undefined;
113
- /** The rejections of the requests waiting. */
114
- private readonly waiting = new Set<(error: Error) => void>();
115
- private readonly listeners = new Set<() => void>();
116
-
117
- constructor(end: Promise<unknown>) {
118
- end.catch((error: unknown) => {
119
- const ended = error instanceof Error ? error : new Error(String(error));
120
- this.ended = ended;
121
- for (const reject of this.waiting) reject(ended);
122
- this.waiting.clear();
123
- for (const listener of this.listeners) listener();
124
- this.listeners.clear();
125
- });
126
- }
127
-
128
- /**
129
- * `promise`, or a rejection once the attempt ends: an attempt that is
130
- * suspended or aborted never settles what it was waiting for.
131
- */
132
- race<T>(promise: PromiseLike<T>): Promise<T> {
133
- if (this.ended) return Promise.reject(this.ended);
134
- return new Promise<T>((resolve, reject) => {
135
- this.waiting.add(reject);
136
- void Promise.resolve(promise)
137
- .finally(() => this.waiting.delete(reject))
138
- .then(resolve, reject);
139
- });
140
- }
58
+ /**
59
+ * `promise`, or a rejection once the attempt ends. A suspended or aborted
60
+ * attempt never settles what it waits for, and a session left waiting would
61
+ * hold its lock for the life of the process.
62
+ */
63
+ function raced<T>(ended: AbortSignal, promise: PromiseLike<T>): Promise<T> {
64
+ if (ended.aborted) return Promise.reject(ended.reason as Error);
65
+ return new Promise<T>((resolve, reject) => {
66
+ const abort = () => reject(ended.reason as Error);
67
+ ended.addEventListener('abort', abort, { once: true });
68
+ void Promise.resolve(promise)
69
+ .finally(() => ended.removeEventListener('abort', abort))
70
+ .then(resolve, reject);
71
+ });
72
+ }
141
73
 
142
- /** Call `listener` when the attempt ends; the returned function cancels it. */
143
- onEnd(listener: () => void): () => void {
144
- if (this.ended) {
145
- listener();
146
- return () => {};
147
- }
148
- this.listeners.add(listener);
149
- return () => this.listeners.delete(listener);
74
+ /** Call `listener` when `ended` aborts (now, if it has). The returned function removes it. */
75
+ function onEnd(ended: AbortSignal, listener: () => void): () => void {
76
+ if (ended.aborted) {
77
+ listener();
78
+ return () => {};
150
79
  }
80
+ ended.addEventListener('abort', listener, { once: true });
81
+ return () => ended.removeEventListener('abort', listener);
151
82
  }
152
83
 
153
- // A state command is named after its key, so that tooling can hide the
154
- // database's head, tail and packs by name (`dev.restate.tooling.journal.hidden.name.prefix`).
155
- const named = (key: string): restate.EntryOptions => ({ name: key });
156
-
157
- // A shared handler's reader writes nothing.
84
+ // A view writes nothing.
158
85
  const refusedWrite = () => {
159
86
  throw new Error('a shared handler writes no state');
160
87
  };
161
88
 
162
- /**
163
- * The keys of the database `name`, apart from the object's own: each of the
164
- * format's keys (`v22/head`, `v22/tail/...`, `v22/manifest/...`,
165
- * `v22/pack/...`) as `v22/db/<name>/head`, under the format's prefix still,
166
- * which tooling hides, and under none of the object's database's.
167
- */
89
+ /** The state key of `key` in database `name`: `v22/head` becomes `v22/db/<name>/head`, still hidden by tooling. */
168
90
  const beside = (name: string) => (key: string) => {
169
91
  const at = key.indexOf('/') + 1;
170
92
  return `${key.slice(0, at)}db/${name}/${key.slice(at)}`;
171
93
  };
172
94
 
173
- /**
174
- * The format's key of a key of the database `name` (undoes {@link beside});
175
- * `undefined` for any other key of the object.
176
- */
95
+ /** Undoes {@link beside}. `undefined` for a key of another database. */
177
96
  const unbeside = (name: string) => (key: string) => {
178
97
  const at = key.indexOf('/') + 1;
179
98
  const prefix = `db/${name}/`;
@@ -181,66 +100,36 @@ const unbeside = (name: string) => (key: string) => {
181
100
  };
182
101
 
183
102
  /**
184
- * The object's state as an ordered store: `get` is a state get, `set` and
185
- * `clear` are state writes, which return at once and which the runtime
186
- * stores in order; `sync` is an empty `ctx.run`, acknowledged after the
187
- * commands before it. A `get` or `sync` the attempt's end leaves waiting
188
- * rejects, so the session that made it ends instead of holding its lock for
189
- * the life of the process. One the SDK cancels fails as any await does: the
190
- * session it ends fails its calls with the CancelledError (see `open`).
103
+ * The object state `store` of a test attempt, as database `dbName` sees it:
104
+ * keys named apart ({@link beside}), no writes in a `view`, and pending reads
105
+ * rejected when the attempt ends.
191
106
  */
192
- /**
193
- * The store of a database the addon keeps on the VM: it reads and writes the
194
- * state itself, and calls this only at a commit, through `sync`, where the
195
- * boundary runs what the committing transaction gave `withCommit`. Reaching
196
- * anything else is a bug in the addon, and says so rather than going quiet.
197
- */
198
- function commitOnly(): Store {
199
- return {
200
- get: servedByVm('get'),
201
- set: servedByVm('set'),
202
- clear: servedByVm('clear'),
203
- sync: async () => {},
204
- };
205
- }
206
-
207
- /** What a store the addon never calls does if it is called after all. */
208
- const servedByVm = (op: string) => () => {
209
- throw new Error(`@restatedev/sessions: the VM serves the state; the store's ${op} is not called`);
210
- };
211
-
212
- function objectStore(ctx: SqlHost, end: AttemptEnd, dbName: string | undefined): Store {
107
+ function objectStore(store: Store, ended: AbortSignal, view: boolean, dbName: string | undefined): Store {
213
108
  const keyOf = dbName === undefined ? (key: string) => key : beside(dbName);
214
- const request = <T>(promise: PromiseLike<T>) => end.race(promise);
215
- // TODO: read with protocol v8's ephemeral get, left out of the journal, once
216
- // a Restate release ships v8 and the SDK lets a library make one. Restate 1.8
217
- // negotiates v7 at most: a journaled get.
218
- const get = async (key: string) => (await request(ctx.get(keyOf(key), serde.binary, named(keyOf(key))))) ?? undefined;
219
- if (ctx.shared) return { get, set: refusedWrite, clear: refusedWrite, sync: async () => {} };
109
+ const get = (key: string) => raced(ended, store.get(keyOf(key)));
110
+ if (view) return { get, set: refusedWrite, clear: refusedWrite, sync: async () => {} };
111
+ const keys = store.keys?.bind(store);
220
112
  return {
221
113
  get,
222
- set: (key, value) => ctx.set(keyOf(key), value, serde.binary, named(keyOf(key))),
223
- clear: (key) => ctx.clear(keyOf(key), named(keyOf(key))),
224
- // The database's keys, for a garbage collection.
225
- keys: async () => {
226
- const keys = await request(ctx.stateKeys());
227
- if (dbName === undefined) return keys;
228
- const own = unbeside(dbName);
229
- return keys.flatMap((key) => own(key) ?? []);
230
- },
231
- sync: async () => {
232
- await request(ctx.run('sync', () => {}));
233
- },
114
+ set: (key, value) => store.set(keyOf(key), value),
115
+ clear: (key) => store.clear(keyOf(key)),
116
+ sync: () => raced(ended, store.sync()),
117
+ // For garbage collection.
118
+ ...(keys && {
119
+ keys: async () => {
120
+ const all = await raced(ended, keys());
121
+ if (dbName === undefined) return all;
122
+ const own = unbeside(dbName);
123
+ return all.flatMap((key) => own(key) ?? []);
124
+ },
125
+ }),
234
126
  };
235
127
  }
236
128
 
237
129
  /**
238
- * What a failed call to the session fails the handler with: an
239
- * {@link SqlError}, which a retry would repeat, becomes a
240
- * {@link TerminalError}, its `cause` the SQL error. Anything else is as for
241
- * any handler: a storage error, which ends the session, or the handler's own
242
- * (a failed request to another service, say) is retried, unless it is a
243
- * TerminalError itself.
130
+ * An {@link SqlError}, which a retry would repeat, becomes a
131
+ * {@link TerminalError} with the SQL error as `cause`. Other errors are
132
+ * retried as usual.
244
133
  */
245
134
  function handlerError(error: unknown): unknown {
246
135
  if (!(error instanceof SqlError)) return error;
@@ -249,79 +138,35 @@ function handlerError(error: unknown): unknown {
249
138
  return terminal;
250
139
  }
251
140
 
252
- /** `call`'s result, or the error the handler fails with (see {@link handlerError}). */
253
141
  function forHandler<T>(call: Promise<T>): Promise<T> {
254
142
  return call.catch((error: unknown) => {
255
143
  throw handlerError(error);
256
144
  });
257
145
  }
258
146
 
259
- /** {@link forHandler} of a call that answers with its value when it is ready: then it is the value, which only this package takes so. */
147
+ /** {@link forHandler} for a call that may answer synchronously (only this package sees that). */
260
148
  function forHandlerNow<T>(call: T | Promise<T>): T | Promise<T> {
261
149
  return call instanceof Promise ? forHandler(call) : call;
262
150
  }
263
151
 
264
- /** The SQL of a transaction's body: `tx`'s, failing as {@link forHandler} does. */
265
- function forBody(tx: ConnectionTransaction): DatabaseWriter & { readonly queued: Promise<void> } {
266
- return {
267
- ...sqlOver((sql, params) => forHandlerNow(tx.queryColumnsNow(sql, params)), handlerError),
268
- queued: tx.queued,
269
- };
270
- }
271
-
272
- /** The connection's transaction behind a `tx` of a body, for the SQL it defers ({@link deferSql}). */
273
- const DEFERRED = new Link<ConnectionTransaction>('deferred sql');
274
-
275
- /**
276
- * Have `sql` (one statement, no parameters) run just before the next call of
277
- * the transaction `tx`, in the same crossing of the addon: the statement and
278
- * its order are those of a call made now, and what it spares is the call.
279
- * Its failure is the next call's (or the commit's, if none comes). Returns
280
- * false, queuing nothing, if the transaction cannot (a `tx` of another
281
- * kind, or an addon without it): run the statement with `tx.execute`.
282
- */
283
- export function deferSql(tx: Transaction, sql: string): boolean {
284
- return DEFERRED.of(tx)?.defer(sql) ?? false;
285
- }
286
-
287
- /** Take back the last `sql` that {@link deferSql} queued on `tx` and no call has taken: it never runs. Whether it was taken back. */
288
- export function undeferSql(tx: Transaction, sql: string): boolean {
289
- return DEFERRED.of(tx)?.undefer(sql) ?? false;
152
+ /** The SQL of a transaction body over `tx`, failing as {@link forHandler} does. */
153
+ function forBody(tx: ConnectionTransaction): DatabaseWriter {
154
+ return sqlOver((sql, params) => forHandlerNow(tx.queryColumnsNow(sql, params)), handlerError);
290
155
  }
291
156
 
292
157
  /**
293
- * `connection`, opened without the SDK (`open`), as a handler's `ctx.db`:
294
- * for a library's tests, and tools. Its transactions send nothing, and a
295
- * library's schema applies to it (`Schema.ensure`).
158
+ * `connection` (opened without the SDK) as a `ctx.db`, for library tests and
159
+ * tools. Its transactions cannot send. `Schema.ensure` works on it.
296
160
  */
297
161
  export function asDatabase(connection: Connection): Database {
298
162
  const db: Database = {
299
163
  ...sqlOver((sql, params) => connection.queryColumnsNow(sql, params)),
300
- transaction: (body) => connection.transaction((tx) => body(DEFERRED.on({ ...forBody(tx), send: refusedSend }, tx))),
164
+ transaction: (body) => connection.transaction((tx) => body({ ...forBody(tx), send: refusedSend })),
301
165
  };
302
166
  return ensuring(db, (schemas) => apply(connection, schemas));
303
167
  }
304
168
 
305
- /** How a transaction of `ctx.db` empties the database ({@link reset}). */
306
- const RESET = new Link<() => Promise<void>>('reset');
307
-
308
- /**
309
- * Empty the key's database in `tx`, a transaction of an exclusive handler's
310
- * `ctx.db`: every table, view, index and trigger is dropped, the schemas are
311
- * applied again (the object's, and the libraries' the attempt applied), and
312
- * the outbox stays. It commits with `tx`: what `tx` writes after it are the
313
- * new database's first rows, in the same commit.
314
- */
315
- export function reset(tx: Transaction): Promise<void> {
316
- const of = RESET.of(tx);
317
- if (of === undefined) throw new TerminalError("reset takes a transaction of an exclusive handler's ctx.db");
318
- return forHandler(of());
319
- }
320
-
321
- /**
322
- * A database that `opener` opens on its first call, as a handler's `ctx.db`
323
- * opens: for tests, which give each attempt one over the same state.
324
- */
169
+ /** A database that `opener` opens on first use, as `ctx.db` does: for tests. */
325
170
  export function lazyDatabase(opener: () => Promise<Database>): Database {
326
171
  let opened: Promise<Database> | undefined;
327
172
  const db = () => (opened ??= opener());
@@ -341,119 +186,72 @@ export function lazyDatabase(opener: () => Promise<Database>): Database {
341
186
  });
342
187
  }
343
188
 
344
- /** The sends of a transaction that has no outbox: a shared handler's, or another database's. */
189
+ /** `tx.send` where a transaction cannot send: in a view, or in a database other than the object database. */
345
190
  const refusedSend: Send = () => {
346
191
  throw new TerminalError("a send of a transaction is an exclusive handler's, in the object's own database");
347
192
  };
348
193
 
349
- // A transaction's sends commit with it, in the database's record `outbox`
350
- // (beside its tables, in none of them), which holds each committed
351
- // transaction's sends until they are stored. They are made with its commit
352
- // (see `Attempt.transaction`); a later open makes again those still in the outbox,
353
- // with the same idempotency keys (`transaction/<id>/<index>`, with a random
354
- // id of the transaction), so making them again is dropped. Restate keeps an attempt's commands in the
355
- // order they were made, so a send made before a commit is stored whenever the
356
- // commit is: the next commit leaves the sends this attempt made out of the
357
- // outbox, and so does the end of the attempt.
358
-
359
- /** A send, but its parameter, as it is stored. */
360
- type StoredSend = Omit<restate.GenericSend<unknown>, 'parameter' | 'inputSerde' | 'delay'> & {
361
- /** Its delay, in milliseconds. */
194
+ // A transaction's sends commit with it. On the VM they go in the commit's
195
+ // atomic group, after its writes (`commitWith`): Restate applies the rows and
196
+ // the sends together, or neither, so nothing has to remember them across a
197
+ // crash. A transaction that wrote nothing sends in a group of its own, and
198
+ // resolves once that is applied. Without the VM (a test's store), they are
199
+ // made through the host right after the commit's writes, before its sync
200
+ // (`withCommit`).
201
+
202
+ /** A send of a transaction, its parameter serialized. */
203
+ interface PendingSend {
204
+ service: string;
205
+ handler: string;
206
+ key?: string;
207
+ parameter: Uint8Array;
208
+ /** In milliseconds. */
362
209
  delay?: number;
363
- /** When a delayed send is due (epoch ms): one made again waits only what remains. */
364
- due?: number;
365
- };
366
-
367
- /** The sends of a committed transaction, in the outbox. */
368
- interface Outgoing {
369
- /** The transaction's random id. */
370
- id: string;
371
- /** Each send, its parameter in base64. */
372
- sends: (StoredSend & { parameter: string })[];
373
- }
374
-
375
- /** The database's record of the outbox. */
376
- const OUTBOX = 'outbox';
377
-
378
- /** The outbox as its record: none is empty, as a record never set reads. */
379
- function encodeOutbox(outbox: Outgoing[]): Uint8Array {
380
- return outbox.length === 0 ? new Uint8Array() : new TextEncoder().encode(JSON.stringify(outbox));
381
- }
382
-
383
- function decodeOutbox(record: Uint8Array): Outgoing[] {
384
- return record.length === 0 ? [] : (JSON.parse(new TextDecoder().decode(record)) as Outgoing[]);
210
+ idempotencyKey?: string;
211
+ headers?: Record<string, string>;
385
212
  }
386
213
 
387
- function storedSend(send: restate.GenericSend<unknown>): Outgoing['sends'][number] {
388
- const { parameter, inputSerde, delay, ...rest } = send;
214
+ function pendingSend(send: restate.GenericSend<unknown>): PendingSend {
215
+ const { service, method, key, parameter, inputSerde, delay, idempotencyKey, headers } = send;
389
216
  return {
390
- ...rest,
217
+ service,
218
+ handler: method,
219
+ ...(key !== undefined ? { key } : {}),
220
+ parameter: (inputSerde ?? serde.binary).serialize(parameter),
391
221
  ...(delay !== undefined ? { delay: millisOrDurationToMillis(delay) } : {}),
392
- parameter: Buffer.from((inputSerde ?? serde.binary).serialize(parameter)).toString('base64'),
222
+ ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),
223
+ ...(headers !== undefined ? { headers } : {}),
393
224
  };
394
225
  }
395
226
 
227
+ /** `send` as the commit's atomic group makes it. */
228
+ const groupSend = (send: PendingSend): VmGroupSend => ({
229
+ target: {
230
+ service: send.service,
231
+ handler: send.handler,
232
+ ...(send.key !== undefined ? { key: send.key } : {}),
233
+ ...(send.idempotencyKey !== undefined ? { idempotencyKey: send.idempotencyKey } : {}),
234
+ ...(send.headers !== undefined
235
+ ? { headers: Object.entries(send.headers).map(([key, value]) => ({ key, value })) }
236
+ : {}),
237
+ },
238
+ input: send.parameter,
239
+ ...(send.delay !== undefined ? { delay: send.delay } : {}),
240
+ name: `${send.service}/${send.handler}`,
241
+ });
242
+
396
243
  /** How a handler ended. */
397
244
  type Outcome<T> = { value: T } | { error: unknown };
398
245
 
399
- /** The attempt of a `ctx.db`: for {@link database}. */
246
+ /** The attempt behind a `ctx.db`, for {@link database}. */
400
247
  const ATTEMPT = new Link<Attempt>('database');
401
248
 
402
- /** A write that rides the next commit of a database, in that commit's transaction. */
403
- type Rider = (tx: Transaction) => Promise<void>;
404
-
405
- /** A pending {@link Rider}, and whether it may not wait for a commit that is not under way. */
406
- interface Pending {
407
- write: Rider;
408
- urgent: boolean;
409
- }
410
-
411
- /**
412
- * Have `write` run in the next transaction of `db` that commits, before its
413
- * commit, rather than commit on its own: for bookkeeping that must be stored
414
- * with the next write, not before it. A write by `db.execute` outside a
415
- * transaction, made while a rider is pending, is that transaction; a read
416
- * (`get`, `values`, `query`) is not, and writes nothing. A transaction that
417
- * rolls back leaves the rider pending, and so does one that ends the handler
418
- * before it commits: {@link flushRiders} writes what is left.
419
- *
420
- * A database has one rider per `slot`: a later one replaces the earlier, and
421
- * `undefined` clears it. A rider registered while a commit that runs the
422
- * earlier one is under way is for the commit after. Returns false, registering
423
- * nothing, for a database that cannot (a view's, another kind of
424
- * `Database`): the caller writes at once.
425
- *
426
- * An `urgent` rider waits only for a transaction that is under way: if none
427
- * is at the end of the macrotask it was registered in (or of the one in which
428
- * a transaction ended and left it pending), it is written in a transaction of
429
- * its own. A transaction that is held open (a batch of commits) is under way,
430
- * and writes it when it commits. A write of its own that fails is not
431
- * retried and raises nothing: the rider stays pending for the next commit or
432
- * {@link flushRiders}. A rider that replaces an urgent one stays urgent.
433
- */
434
- export function rideCommit(
435
- db: Database,
436
- slot: string,
437
- write: Rider | undefined,
438
- { urgent = false }: { urgent?: boolean } = {},
439
- ): boolean {
440
- return ATTEMPT.of(db)?.ride(slot, write, urgent) ?? false;
441
- }
442
-
443
- /** Write what is pending ({@link rideCommit}) in a transaction of its own: nothing, if nothing is. */
444
- export async function flushRiders(db: Database): Promise<void> {
445
- await ATTEMPT.of(db)?.flushRiders();
446
- }
447
-
448
- // A database's name (`database`).
449
249
  const DATABASE_NAME = /^[\w.-]{1,64}$/;
450
250
 
451
251
  /**
452
- * The database `name` of the key, apart from the object's own (`ctx.db`, of
453
- * the attempt whose session `db` is): for a library whose tables must be
454
- * alone in their database, such as OpenCode's. It opens on its first use,
455
- * and ends with the attempt, as `ctx.db` does. A name is 1 to 64 letters,
456
- * digits, `_`, `-` or `.`.
252
+ * The key's database `name`, separate from `ctx.db` (`db`): for a library
253
+ * whose tables must be alone. It opens on first use and
254
+ * ends with the attempt. A name is 1 to 64 letters, digits, `_`, `-` or `.`.
457
255
  */
458
256
  export function database(db: Database, name: string): Database {
459
257
  if (!DATABASE_NAME.test(name)) throw new TerminalError(`database: ${JSON.stringify(name)} is not a database name`);
@@ -462,45 +260,44 @@ export function database(db: Database, name: string): Database {
462
260
  return attempt.database(name);
463
261
  }
464
262
 
465
- /** The sends of one transaction, as its body makes them (`tx.send`), until it ends. */
263
+ /** The sends a transaction body makes (`tx.send`), until the body ends. */
466
264
  class Sends {
467
- private readonly sends: Outgoing['sends'] = [];
265
+ private readonly sends: PendingSend[] = [];
468
266
  private open = true;
469
- readonly send: Send = sendOf((send) => {
470
- if (!this.open) throw new TerminalError('the transaction has ended: send from inside its body');
471
- this.sends.push(storedSend(send));
472
- });
267
+ readonly send: Send;
473
268
 
474
- /** The body ended: the transaction's sends, if it made any, their delays counted from now. */
475
- close(): Outgoing | undefined {
269
+ constructor(fallback?: restate.Serde<unknown>) {
270
+ this.send = sendOf((send) => {
271
+ if (!this.open) throw new TerminalError('the transaction has ended: send from inside its body');
272
+ this.sends.push(pendingSend(send));
273
+ }, fallback);
274
+ }
275
+
276
+ /** The body ended: the transaction's sends. */
277
+ close(): PendingSend[] {
476
278
  this.open = false;
477
- if (this.sends.length === 0) return undefined;
478
- const now = Date.now();
479
- for (const send of this.sends) if (send.delay !== undefined) send.due = now + send.delay;
480
- return { id: randomUUID(), sends: this.sends };
279
+ return this.sends;
481
280
  }
482
281
  }
483
282
 
484
283
  /**
485
- * One session of an attempt's database, from its open on. A failure ends it:
486
- * its open's, or a request's since. It closes as the attempt ends, unless the
487
- * attempt ends it first ({@link end}).
284
+ * One session of the attempt database. A failed open or a failed request ends
285
+ * it. It closes when the attempt ends, unless {@link end} was called first.
488
286
  */
489
287
  class Session {
490
288
  readonly ready: Promise<Connection>;
491
- /** A call failed on it once a failure ended it: the next call opens another. */
289
+ /** Set by the call that fails on an ended session: the next call opens a new one. */
492
290
  retired = false;
493
291
  private connection: Connection | undefined;
494
- /** Its connection, once its open settled. */
495
292
  get opened(): Connection | undefined {
496
293
  return this.connection;
497
294
  }
498
295
  private failed = false;
499
296
  private release: () => void = () => {};
500
297
 
501
- constructor(ready: Promise<Connection>, end: AttemptEnd) {
298
+ constructor(ready: Promise<Connection>, ended: AbortSignal) {
502
299
  this.ready = ready;
503
- void this.track(end);
300
+ void this.track(ended);
504
301
  }
505
302
 
506
303
  /** Whether a failure ended it. */
@@ -508,28 +305,25 @@ class Session {
508
305
  return this.failed || this.connection?.isUsable() === false;
509
306
  }
510
307
 
511
- /** Its connection, or none if the open failed; the attempt's end no longer closes it. */
308
+ /** The connection (none if the open failed). After this, the end of the attempt does not close it. */
512
309
  async end(): Promise<Connection | undefined> {
513
310
  const db = await this.ready.catch(() => undefined);
514
311
  this.release();
515
312
  return db;
516
313
  }
517
314
 
518
- /** Close it now. */
519
315
  close(): void {
520
316
  void this.end()
521
317
  .then((db) => db?.close())
522
318
  .catch(() => {});
523
319
  }
524
320
 
525
- private async track(end: AttemptEnd) {
321
+ private async track(ended: AbortSignal) {
526
322
  try {
527
323
  const db = await this.ready;
528
324
  this.connection = db;
529
- // A handler still waiting for something else when the attempt ends (a
530
- // model request, say) keeps the session no longer: it closes once no
531
- // statement runs, and the handler's later calls fail.
532
- this.release = end.onEnd(() => void db.close().catch(() => {}));
325
+ // When the attempt ends, the session closes once no statement runs, and later calls fail.
326
+ this.release = onEnd(ended, () => void db.close().catch(() => {}));
533
327
  } catch {
534
328
  this.failed = true;
535
329
  }
@@ -537,143 +331,84 @@ class Session {
537
331
  }
538
332
 
539
333
  /**
540
- * An attempt's SQL session: opened on its first use, or as an exclusive
541
- * attempt starts ({@link openNow}), shared by everything the handler does,
542
- * and saved when the handler ends ({@link end}). With `name`, of the key's
543
- * database `name` ({@link database}), which has neither the object's schema
544
- * nor an outbox.
334
+ * The SQL session of an attempt, shared by everything the handler does. With
335
+ * `name`, it is the key's database `name` ({@link database}), which has no
336
+ * object schema and whose transactions cannot send.
545
337
  */
546
338
  export class Attempt {
547
- /** `ctx.db`. */
548
339
  readonly db: Database;
549
- private readonly ctx: SqlHost;
550
- /** Its object's: the key's other databases share its store's wrapper, and have none of its schema. */
340
+ private readonly host: AttemptHost;
341
+ private readonly view: boolean;
551
342
  private readonly config: ObjectConfig;
552
343
  private readonly name: string | undefined;
553
- /** Whether it is the object's own database of an exclusive handler: the one with an outbox. */
554
- private readonly hasOutbox: boolean;
555
- /** The key's other databases this attempt opened, by name. */
344
+ /** Only the object database of an exclusive handler has transactions that send. */
345
+ private readonly sends: boolean;
556
346
  private readonly databases = new Map<string, Attempt>();
557
- /** The session, from its first use on. */
558
347
  private session: Session | undefined;
559
- /** The calls made on the session that have not reached its connection yet: see {@link call}. */
348
+ /** Calls that have not reached the connection yet: see {@link callNow}. */
560
349
  private unhanded = 0;
561
- /** The ids of the outbox's transactions this attempt made the sends of. */
562
- private readonly made = new Set<string>();
563
- /** The writes that ride the next commit, by slot ({@link rideCommit}). */
564
- private readonly riders = new Map<string, Pending>();
565
- /** The transactions asked for and not finished: one that is under way writes the riders. */
566
- private active = 0;
567
- /** The macrotask at the end of which an urgent rider is written alone, if one is set. */
568
- private urgentTimer: NodeJS.Immediate | undefined;
569
- /** The schemas this attempt's database has all the steps of. */
350
+ /** Schemas applied in this session. A view applies them only in its session. */
570
351
  private readonly ensured = new Map<string, Schema>();
571
352
  private ended = false;
353
+ /** {@link end} began: the other databases are ending. */
354
+ private ending = false;
572
355
 
573
- constructor(ctx: SqlHost, config: ObjectConfig = {}, name?: string) {
574
- this.ctx = ctx;
356
+ constructor(host: AttemptHost, view: boolean, config: ObjectConfig = {}, name?: string) {
357
+ this.host = host;
358
+ this.view = view;
575
359
  this.config = config;
576
360
  this.name = name;
577
- this.hasOutbox = !ctx.shared && name === undefined;
361
+ this.sends = !view && name === undefined;
578
362
  const base = sqlOver(
579
363
  (sql, params) => this.askedNow(() => this.callNow((db) => db.queryColumnsNow(sql, params))),
580
364
  handlerError,
581
365
  );
582
366
  this.db = {
583
367
  ...base,
584
- // A write while a rider is pending is the transaction it rides.
585
- execute: (statement, params) =>
586
- this.riders.size > 0
587
- ? this.asked(() => this.transaction((tx) => tx.execute(statement, params)))
588
- : base.execute(statement, params),
589
368
  transaction: (body) => this.asked(() => this.transaction(body)),
590
369
  };
591
370
  ensuring(this.db, (schemas) => this.asked(() => this.call((db) => this.ensureSchemas(db, schemas))));
592
371
  ATTEMPT.on(this.db, this);
593
372
  }
594
373
 
595
- /** The key's database `name`, in this attempt: see {@link database}. */
374
+ /** See {@link database}. */
596
375
  database(name: string): Database {
597
- if (this.ended) throw new Error('the handler has ended: its SQL session is closed');
376
+ if (this.ended || this.ending) throw new Error('the handler has ended: its SQL session is closed');
598
377
  let other = this.databases.get(name);
599
- if (other === undefined) this.databases.set(name, (other = new Attempt(this.ctx, this.config, name)));
378
+ if (other === undefined) this.databases.set(name, (other = new Attempt(this.host, this.view, this.config, name)));
600
379
  return other.db;
601
380
  }
602
381
 
603
- /** {@link rideCommit}. */
604
- ride(slot: string, write: Rider | undefined, urgent: boolean): boolean {
605
- if (this.ctx.shared || this.ended) return false;
606
- if (write === undefined) this.riders.delete(slot);
607
- else {
608
- this.riders.set(slot, { write, urgent: urgent || (this.riders.get(slot)?.urgent ?? false) });
609
- this.arm();
610
- }
611
- return true;
612
- }
613
-
614
- /** Have the urgent riders written at the end of this macrotask, if any is pending and none is set. */
615
- private arm() {
616
- if (this.urgentTimer !== undefined || this.ended) return;
617
- if (![...this.riders.values()].some((r) => r.urgent)) return;
618
- this.urgentTimer = setImmediate(() => {
619
- this.urgentTimer = undefined;
620
- // A transaction under way writes them, or re-arms as it ends.
621
- if (this.ended || this.active > 0) return;
622
- // A failure leaves them pending, for the next commit or the flush, and is not tried again by a timer. After a
623
- // success, one that came while it committed (its own timer found it under way) is set now.
624
- this.transaction(async () => {}, false).then(
625
- () => this.arm(),
626
- () => {},
627
- );
628
- });
629
- }
630
-
631
- /** {@link flushRiders}, as a transaction of `db`: its commit writes them. */
632
- async flushRiders() {
633
- if (this.riders.size > 0) await this.db.transaction(async () => {});
634
- }
635
-
636
382
  /**
637
- * `call`, which the handler asked for, unless a cancellation is owed to
638
- * it: then the call fails with the cancellation, and does nothing.
639
- *
640
- * This is where the database delivers a cancellation, and the only place.
641
- * What the handler asks for passes through here; what the session does for
642
- * itself does not — the open, the object's schema, the sends a crashed
643
- * attempt left unmade, emptying the outbox after a commit — and a
644
- * cancellation that failed one of those would be delivered to nobody, or
645
- * would report a transaction as cancelled after it committed. And it is
646
- * before the call issues anything, so a call that fails with
647
- * `CancelledError` wrote nothing and sent nothing: a call already under way
648
- * when the cancellation arrives runs to its end, and the cancellation goes
649
- * to what the handler awaits next.
383
+ * Fail with an owed cancellation before anything runs (see stop.ts). Only
384
+ * handler calls pass here: failing the session's own work (the open, the
385
+ * object's schema, the save) would deliver the cancellation to nobody, or
386
+ * report a committed transaction as cancelled.
650
387
  */
651
388
  private asked<T>(call: () => Promise<T>): Promise<T> {
652
- if (this.ctx.takeCancellation?.()) return Promise.reject(new CancelledError());
389
+ if (this.host.stop.take()) return Promise.reject(new CancelledError());
653
390
  return call();
654
391
  }
655
392
 
656
- /** {@link asked} for a call that answers with its value when it is ready ({@link callNow}). */
393
+ /** {@link asked} for a call that may answer synchronously ({@link callNow}). */
657
394
  private askedNow<T>(call: () => T | Promise<T>): T | Promise<T> {
658
- if (this.ctx.takeCancellation?.()) return Promise.reject(new CancelledError());
395
+ if (this.host.stop.take()) return Promise.reject(new CancelledError());
659
396
  return call();
660
397
  }
661
398
 
662
399
  /**
663
- * Open the session now, as the attempt starts, rather than on its first
664
- * call: the open makes the sends a crashed attempt committed and left
665
- * unmade, which must not wait for a handler that uses the database.
400
+ * Open the object database as an exclusive attempt starts, rather than on
401
+ * its first call: its head is read and the object schema applied while the
402
+ * handler gets going.
666
403
  */
667
404
  openNow() {
668
- if (this.hasOutbox && this.session === undefined) this.current().ready.catch(() => {});
405
+ if (this.sends && this.session === undefined) this.current().ready.catch(() => {});
669
406
  }
670
407
 
671
- /**
672
- * The handler ended with `outcome`: the key's other databases end, then
673
- * this one ({@link endSession}).
674
- */
408
+ /** The handler ended with `outcome`. The key's other databases end first, as the handler left them. */
675
409
  async end<T>(outcome: Outcome<T>): Promise<T> {
676
- // The key's other databases end first, as the handler left them.
410
+ // None opens from here: nothing would end it.
411
+ this.ending = true;
677
412
  const databases = await Promise.allSettled([...this.databases.values()].map((d) => d.end({ value: undefined })));
678
413
  const value = await this.endSession(outcome);
679
414
  const failed = databases.find((d) => d.status === 'rejected');
@@ -682,79 +417,48 @@ export class Attempt {
682
417
  }
683
418
 
684
419
  /**
685
- * `body` as one transaction. In the object's own database of an exclusive
686
- * handler, its sends commit with it, in the outbox, and are made with its
687
- * commit, right after its writes and before it waits for anything
688
- * (`withCommit`): Restate stores an attempt's commands in order, so they
689
- * are stored only if the commit is, and whatever fails the commit's wait
690
- * (the attempt's end, say) comes after them. A second commit empties the outbox
691
- * before `transaction` resolves: left until the handler's end, they would
692
- * be made again by an attempt that resumes a long wait (an approval), past
693
- * the idempotency retention that drops a repeat.
420
+ * `body` as one transaction. In the object database of an exclusive
421
+ * handler, its sends commit with it (see the block above `PendingSend`).
694
422
  */
695
- private async transaction<T>(body: (tx: Transaction) => Promise<T>, rearm = true): Promise<T> {
696
- this.active++;
697
- try {
698
- return await this.transacted(body);
699
- } finally {
700
- this.active--;
701
- // What it left pending (it rolled back, or the rider came after it ran them) is for the end of this macrotask.
702
- if (rearm) this.arm();
703
- }
704
- }
705
-
706
- private async transacted<T>(body: (tx: Transaction) => Promise<T>): Promise<T> {
707
- let outgoing: Outgoing | undefined;
708
- // The riders this transaction wrote: pending until it has committed.
709
- let rode: [string, Pending][] = [];
710
- const value = await this.call((db) =>
423
+ private async transaction<T>(body: (tx: Transaction) => Promise<T>): Promise<T> {
424
+ return this.call((db) =>
711
425
  db.transaction(async (handle) => {
712
- const sends = this.hasOutbox ? new Sends() : undefined;
426
+ const sends = this.sends ? new Sends(this.config.serde) : undefined;
713
427
  const tx: Transaction = { ...forBody(handle), send: sends?.send ?? refusedSend };
714
- // A view's writes stay in its session: it has nothing to reset.
715
- DEFERRED.on(tx, handle);
716
- if (!this.ctx.shared) RESET.on(tx, () => this.reset(handle));
428
+ let made: PendingSend[] = [];
717
429
  let result: T;
718
430
  try {
719
431
  result = await body(tx);
720
432
  } finally {
721
- outgoing = sends?.close();
722
- }
723
- // After the body, which may have registered one (a transaction held open for more work), and before the commit.
724
- if (this.riders.size > 0) {
725
- rode = [...this.riders];
726
- for (const [, { write }] of rode) await write(tx);
433
+ made = sends?.close() ?? [];
727
434
  }
728
- if (this.hasOutbox) await this.commitOutbox(handle, outgoing);
435
+ if (this.sends) this.commitSends(handle, made);
729
436
  return result;
730
437
  }),
731
438
  );
732
- // One registered since is for the next commit.
733
- for (const [slot, pending] of rode) if (this.riders.get(slot) === pending) this.riders.delete(slot);
734
- if (outgoing !== undefined) await this.call((db) => this.flush(db));
735
- return value;
736
439
  }
737
440
 
738
- /**
739
- * Commit with `handle` the outbox as committed, but the sends stored since,
740
- * and with `outgoing`, which the commit makes. Unchanged, it is not
741
- * written again.
742
- */
743
- private async commitOutbox(handle: ConnectionTransaction, outgoing: Outgoing | undefined) {
744
- const outbox = await this.unstored(handle);
745
- if (outgoing !== undefined) {
746
- outbox.push(outgoing);
747
- handle.withCommit(() => this.make(outgoing));
441
+ /** Have the commit of `handle` make `sends`: in its atomic group on the VM, else through the host. */
442
+ private commitSends(handle: ConnectionTransaction, sends: PendingSend[]) {
443
+ const { host } = this;
444
+ if (host.vm !== undefined) {
445
+ // A transaction opens no span of its own: its group is inside the span the handler's code is in, if any.
446
+ const parentSpan = host.driver?.currentSpan;
447
+ handle.commitWith({ sends: sends.map(groupSend), ...(parentSpan !== undefined ? { parentSpan } : {}) });
448
+ return;
748
449
  }
749
- handle.setRecord(OUTBOX, encodeOutbox(outbox));
450
+ if (sends.length === 0) return;
451
+ handle.withCommit(() => {
452
+ for (const { handler, parameter, ...send } of sends) {
453
+ host.send({ ...send, method: handler, parameter, inputSerde: serde.binary });
454
+ }
455
+ });
750
456
  }
751
457
 
752
458
  /**
753
- * `call` on the session, opening it on the first; its failure as the
754
- * handler fails with it. The call that fails on a session that a failure
755
- * ended is its last: the next opens another, which reads what is stored.
756
- * So the failure of an open made as the attempt started goes to the first
757
- * call, as it would had that call opened it.
459
+ * Run `call`, opening the session on first use. A call that fails on an
460
+ * ended session retires it, and the next call opens a new one. So a failed
461
+ * open at attempt start fails the first call.
758
462
  */
759
463
  private async call<T>(call: (db: Connection) => Promise<T>): Promise<T> {
760
464
  const session = this.current();
@@ -777,11 +481,8 @@ export class Attempt {
777
481
  }
778
482
 
779
483
  /**
780
- * {@link call} for a call that answers with its value when it is ready: it
781
- * is the value, without a promise, which only this package takes so. That
782
- * is for a session that is open, and with no call before it still to reach
783
- * the connection (a call made before it, which waits for the session, must
784
- * run first): anything else is {@link call}.
484
+ * {@link call} that may return the value synchronously: only for an open
485
+ * session with no earlier call still waiting to reach the connection.
785
486
  */
786
487
  private callNow<T>(call: (db: Connection) => T | Promise<T>): T | Promise<T> {
787
488
  const session = this.session;
@@ -789,7 +490,7 @@ export class Attempt {
789
490
  if (this.unhanded > 0 || session === undefined || db === undefined || session.retired || this.ended) {
790
491
  return this.call(async (connection) => call(connection));
791
492
  }
792
- // As `call` fails: a session that a failure ended is retired by the call that fails on it.
493
+ // As in `call`, the failing call retires a session that a failure ended.
793
494
  const failure = (error: unknown): unknown => {
794
495
  if (session.ended) session.retired = true;
795
496
  return handlerError(error);
@@ -807,7 +508,7 @@ export class Attempt {
807
508
  : result;
808
509
  }
809
510
 
810
- /** The session, opening one if there is none, or the one there is was retired. */
511
+ /** The session, opening a new one if there is none or it was retired. */
811
512
  private current(): Session {
812
513
  if (this.ended) throw new Error('the handler has ended: its SQL session is closed');
813
514
  if (this.session?.retired) this.session.close();
@@ -816,45 +517,34 @@ export class Attempt {
816
517
  }
817
518
 
818
519
  private open(): Session {
819
- const end = new AttemptEnd(this.ctx.invocationEndPromise.promise);
820
- return new Session(this.start(end), end);
520
+ // A view applies schema steps only in its session, so a new session lacks them.
521
+ this.ensured.clear();
522
+ const ended = this.host.request.attemptCompletedSignal;
523
+ return new Session(this.start(ended), ended);
821
524
  }
822
525
 
823
- private async start(end: AttemptEnd): Promise<Connection> {
824
- const ctx = this.ctx;
825
- // The page cache's: the key escaped, so that no key reads as another's
826
- // database (a name has no `/`).
827
- const key = `${ctx.request().target.service}/${encodeURIComponent(ctx.key)}`;
526
+ private async start(ended: AbortSignal): Promise<Connection> {
527
+ const { host, view } = this;
528
+ // Escaped so that no key reads as another key's database (a name has no `/`).
529
+ const key = `${host.request.target.service}/${encodeURIComponent(host.key)}`;
828
530
  const namespace = this.name === undefined ? key : `${key}/${this.name}`;
829
- const wrap = this.config.wrapStore;
830
- // With a VM, the addon reads and writes the state itself and nothing of
831
- // the store crosses into JavaScript. A wrapper (fault injection, through
832
- // `withStoreWrapper`) would then have nothing to wrap, and using the
833
- // JavaScript store instead would quietly test the other path: the tests
834
- // that wrap give their attempts no VM, so this says so rather than
835
- // choosing for them.
836
- if (ctx.vm !== undefined && wrap !== undefined) {
837
- throw new TerminalError(
838
- 'withStoreWrapper wraps the store of an attempt served by the SDK; an attempt on the VM has none to wrap',
839
- );
840
- }
841
- const onVm = ctx.vm !== undefined;
842
- const object = onVm ? commitOnly() : objectStore(ctx, end, this.name);
843
- const db = onVm
844
- ? await openOnVm(namespace, object, ctx.vm, { name: this.name, reader: ctx.shared, working: ctx.working })
845
- : await open(namespace, wrap ? wrap(object) : object, { reader: ctx.shared });
846
- try {
847
- // A view writes nothing: a write fails, rather than vanish with the attempt.
848
- if (ctx.shared) await db.execute('PRAGMA query_only = 1');
849
- if (this.hasOutbox) {
850
- // What a crash left unmade; an open again in this attempt finds what
851
- // this attempt made, stored before it, as made.
852
- const left = decodeOutbox(await db.record(OUTBOX));
853
- for (const outgoing of left) if (!this.made.has(outgoing.id)) this.make(outgoing, true);
854
- // Emptied at once, as a transaction's own sends are (see `transaction`).
855
- if (left.length > 0) await this.flush(db);
531
+ // With a VM, the addon reads and writes the state itself, and no store call crosses into JavaScript.
532
+ const keepAlive = <T>(fn: () => T | Promise<T>) => host.stop.keepAlive(fn);
533
+ let db: Connection;
534
+ if (host.vm !== undefined) {
535
+ try {
536
+ db = await openOnVm(namespace, host.vm, { name: this.name, reader: view, keepAlive });
537
+ } catch (error) {
538
+ // The VM refuses the open of an attempt that is over: it fails as the attempt ended.
539
+ throw ended.aborted ? (ended.reason as Error) : error;
856
540
  }
857
- // A view's too, whose writes are never stored: a key never written reads as empty tables.
541
+ } else if (host.store !== undefined)
542
+ db = await open(namespace, objectStore(host.store, ended, view, this.name), { reader: view });
543
+ else throw new Error('@restatedev/sessions: an attempt has a VM or a store');
544
+ try {
545
+ // A write in a view fails instead of vanishing with the attempt.
546
+ if (view) await db.execute('PRAGMA query_only = 1');
547
+ // Also in a view, which never stores the steps: a key never written reads as empty tables.
858
548
  const own = this.ownSchema();
859
549
  if (own) await this.ensureSchemas(db, [own]);
860
550
  } catch (error) {
@@ -865,16 +555,12 @@ export class Attempt {
865
555
  }
866
556
 
867
557
  /**
868
- * End the session, then settle as the handler did: an SQL error that
869
- * escaped it becomes terminal. The handler's error stands: what it
870
- * committed is stored, and an outbox left full is made by the next open.
871
- * A failure to end the session fails a handler that succeeded, which a
872
- * retry then ends (a transaction it left open, say).
558
+ * End the session, then settle as the handler did. The handler's error wins
559
+ * (its commits are stored). A failure to end the session fails a handler
560
+ * that succeeded (for example, one that left a transaction open).
873
561
  */
874
562
  private async endSession<T>(outcome: Outcome<T>): Promise<T> {
875
563
  this.ended = true;
876
- if (this.urgentTimer !== undefined) clearImmediate(this.urgentTimer);
877
- this.urgentTimer = undefined;
878
564
  const failed = await this.close().then(
879
565
  () => undefined,
880
566
  (error: unknown) => ({ error }),
@@ -885,34 +571,20 @@ export class Attempt {
885
571
  }
886
572
 
887
573
  /**
888
- * Close the session as the attempt ends. A view's closes: it read the
889
- * snapshot it opened on, and one that outlived 16 commits failed its read
890
- * ("is gone"), which is retried. Another is saved, its outbox emptied. One
891
- * that a failure ended closes, and the object's own database is opened
892
- * again and saved: it may hold sends unmade (a crash left them, and this
893
- * attempt's open failed) or made and not emptied (the commit's wait
894
- * failed), and no attempt may follow this one (a cancelled invocation's),
895
- * nor the key's next invocation come within the idempotency retention.
574
+ * Close the session. A view only closes. Otherwise the session is saved; one
575
+ * that a failure ended closes, and what it committed is stored as it was.
896
576
  */
897
577
  private async close(): Promise<void> {
898
578
  if (this.session === undefined) return;
899
579
  const db = await this.session.end();
900
- if (this.ctx.shared) return db?.close();
580
+ if (this.view) return db?.close();
901
581
  if (db?.isUsable()) return this.save(db);
902
582
  await db?.close().catch(() => {});
903
- if (!this.hasOutbox) return;
904
- const again = this.open();
905
- try {
906
- await this.save(await again.ready);
907
- } finally {
908
- void again.end();
909
- }
910
583
  }
911
584
 
912
- /** Empty the outbox and save the session, which closes if that fails. */
585
+ /** Save the session. The session closes if that fails. */
913
586
  private async save(db: Connection) {
914
587
  try {
915
- if (this.hasOutbox) await this.flush(db);
916
588
  await db.save();
917
589
  } catch (error) {
918
590
  await db.close().catch(() => {});
@@ -920,65 +592,16 @@ export class Attempt {
920
592
  }
921
593
  }
922
594
 
923
- /** The object's schema, which the key's other databases have none of. */
595
+ /** The object schema. The key's other databases do not get it. */
924
596
  private ownSchema(): Schema | undefined {
925
597
  return this.name === undefined ? this.config.schema : undefined;
926
598
  }
927
599
 
928
- /** Empty the database in the transaction `handle` ({@link reset}), and apply the schemas this attempt applied again. */
929
- private async reset(handle: ConnectionTransaction) {
930
- const own = this.ownSchema();
931
- const schemas = [...(own ? [own] : []), ...[...this.ensured.values()].filter((s) => s !== own)];
932
- await dropAll(handle, schemas);
933
- }
934
-
935
- /** Apply the steps of `schemas` that the database lacks, each schema once per attempt. */
600
+ /** Apply the steps of `schemas` that the database lacks, each schema once per session. */
936
601
  private async ensureSchemas(db: Connection, schemas: readonly Schema[]) {
937
602
  const lacking = schemas.filter((s) => !this.ensured.has(s.name));
938
603
  if (lacking.length === 0) return;
939
- await apply(db, lacking, { reader: this.ctx.shared });
604
+ await apply(db, lacking, { reader: this.view });
940
605
  for (const s of lacking) this.ensured.set(s.name, s);
941
606
  }
942
-
943
- /** Make the sends of a committed transaction: each with an idempotency key of the transaction (or its own), so that making them again is dropped. */
944
- private make({ id, sends }: Outgoing, again = false) {
945
- sends.forEach(({ parameter, due, delay, ...send }, index) => {
946
- this.ctx.genericSend({
947
- ...send,
948
- // Made again, a delayed send waits only what remains of its delay.
949
- ...(delay !== undefined ? { delay: again && due !== undefined ? Math.max(0, due - Date.now()) : delay } : {}),
950
- parameter: new Uint8Array(Buffer.from(parameter, 'base64')),
951
- inputSerde: serde.binary,
952
- idempotencyKey: send.idempotencyKey ?? `transaction/${id}/${index}`,
953
- });
954
- });
955
- this.made.add(id);
956
- }
957
-
958
- /** The outbox as committed, but the transactions this attempt made the sends of: a commit made after them stores them first. */
959
- private async unstored(db: Connection | ConnectionTransaction): Promise<Outgoing[]> {
960
- return decodeOutbox(await db.record(OUTBOX)).filter(({ id }) => !this.made.has(id));
961
- }
962
-
963
- /**
964
- * Empty the outbox, so that a later open does not make its sends again: a
965
- * commit after them, which stores them first.
966
- */
967
- private async flush(db: Connection) {
968
- if ((await db.record(OUTBOX)).length === 0) return;
969
- // Read in the transaction that writes it: one that committed sends since
970
- // the read above keeps them.
971
- await db.transaction(async (tx) => tx.setRecord(OUTBOX, encodeOutbox(await this.unstored(tx))));
972
- }
973
- }
974
-
975
- /** Run `handler`, then end `attempt`'s SQL session, if it opened one (see {@link Attempt.end}). */
976
- export async function withAttempt<T>(handler: () => Promise<T>, attempt: Attempt): Promise<T> {
977
- let outcome: Outcome<T>;
978
- try {
979
- outcome = { value: await handler() };
980
- } catch (error) {
981
- outcome = { error };
982
- }
983
- return attempt.end(outcome);
984
607
  }