@restatedev/sessions 0.11.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +330 -178
  2. package/dist/addon.d.ts +1 -0
  3. package/dist/addon.d.ts.map +1 -1
  4. package/dist/addon.js.map +1 -1
  5. package/dist/calls.d.ts +28 -28
  6. package/dist/calls.d.ts.map +1 -1
  7. package/dist/calls.js +25 -25
  8. package/dist/calls.js.map +1 -1
  9. package/dist/database.d.ts +90 -166
  10. package/dist/database.d.ts.map +1 -1
  11. package/dist/database.js +137 -249
  12. package/dist/database.js.map +1 -1
  13. package/dist/driver.d.ts +129 -126
  14. package/dist/driver.d.ts.map +1 -1
  15. package/dist/driver.js +337 -276
  16. package/dist/driver.js.map +1 -1
  17. package/dist/endpoint.d.ts +47 -5
  18. package/dist/endpoint.d.ts.map +1 -1
  19. package/dist/endpoint.js +175 -60
  20. package/dist/endpoint.js.map +1 -1
  21. package/dist/handler.d.ts +20 -17
  22. package/dist/handler.d.ts.map +1 -1
  23. package/dist/handler.js +161 -127
  24. package/dist/handler.js.map +1 -1
  25. package/dist/host.d.ts +29 -0
  26. package/dist/host.d.ts.map +1 -0
  27. package/dist/host.js +2 -0
  28. package/dist/host.js.map +1 -0
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +5 -26
  32. package/dist/index.js.map +1 -1
  33. package/dist/internal.d.ts +11 -11
  34. package/dist/internal.d.ts.map +1 -1
  35. package/dist/internal.js +20 -16
  36. package/dist/internal.js.map +1 -1
  37. package/dist/link.d.ts +1 -2
  38. package/dist/link.d.ts.map +1 -1
  39. package/dist/link.js +4 -5
  40. package/dist/link.js.map +1 -1
  41. package/dist/log.d.ts +14 -0
  42. package/dist/log.d.ts.map +1 -0
  43. package/dist/log.js +21 -0
  44. package/dist/log.js.map +1 -0
  45. package/dist/object.d.ts +217 -142
  46. package/dist/object.d.ts.map +1 -1
  47. package/dist/object.js +195 -241
  48. package/dist/object.js.map +1 -1
  49. package/dist/platform.d.ts +0 -1
  50. package/dist/platform.d.ts.map +1 -1
  51. package/dist/platform.js +4 -6
  52. package/dist/platform.js.map +1 -1
  53. package/dist/schema.d.ts +14 -22
  54. package/dist/schema.d.ts.map +1 -1
  55. package/dist/schema.js +31 -69
  56. package/dist/schema.js.map +1 -1
  57. package/dist/serve.d.ts +11 -17
  58. package/dist/serve.d.ts.map +1 -1
  59. package/dist/serve.js +21 -39
  60. package/dist/serve.js.map +1 -1
  61. package/dist/session.d.ts +58 -240
  62. package/dist/session.d.ts.map +1 -1
  63. package/dist/session.js +206 -532
  64. package/dist/session.js.map +1 -1
  65. package/dist/stop.d.ts +59 -0
  66. package/dist/stop.d.ts.map +1 -0
  67. package/dist/stop.js +220 -0
  68. package/dist/stop.js.map +1 -0
  69. package/dist/vm.d.ts +108 -29
  70. package/dist/vm.d.ts.map +1 -1
  71. package/dist/vm.js +43 -10
  72. package/dist/vm.js.map +1 -1
  73. package/package.json +4 -4
  74. package/src/addon.ts +1 -0
  75. package/src/calls.ts +51 -47
  76. package/src/database.ts +195 -339
  77. package/src/driver.ts +379 -315
  78. package/src/endpoint.ts +217 -62
  79. package/src/handler.ts +183 -164
  80. package/src/host.ts +28 -0
  81. package/src/index.ts +6 -26
  82. package/src/internal.ts +28 -39
  83. package/src/link.ts +4 -5
  84. package/src/log.ts +42 -0
  85. package/src/object.ts +379 -335
  86. package/src/platform.ts +4 -6
  87. package/src/schema.ts +37 -103
  88. package/src/serve.ts +20 -41
  89. package/src/session.ts +236 -629
  90. package/src/stop.ts +225 -0
  91. package/src/vm.ts +151 -55
  92. package/dist/scope.d.ts +0 -38
  93. package/dist/scope.d.ts.map +0 -1
  94. package/dist/scope.js +0 -55
  95. package/dist/scope.js.map +0 -1
  96. package/src/scope.ts +0 -78
package/src/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`).
191
- */
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.
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.
197
106
  */
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,123 +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
- /**
444
- * Write what is pending ({@link rideCommit}) in a transaction of its own, and resolve once it is stored. A
445
- * transaction under way that commits first writes it, and this commits nothing; one that rolls back leaves
446
- * it, and this writes it. Nothing, if nothing is pending.
447
- */
448
- export async function flushRiders(db: Database): Promise<void> {
449
- await ATTEMPT.of(db)?.flushRiders();
450
- }
451
-
452
- // A database's name (`database`).
453
249
  const DATABASE_NAME = /^[\w.-]{1,64}$/;
454
250
 
455
251
  /**
456
- * The database `name` of the key, apart from the object's own (`ctx.db`, of
457
- * the attempt whose session `db` is): for a library whose tables must be
458
- * alone in their database, such as OpenCode's. It opens on its first use,
459
- * and ends with the attempt, as `ctx.db` does. A name is 1 to 64 letters,
460
- * 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 `.`.
461
255
  */
462
256
  export function database(db: Database, name: string): Database {
463
257
  if (!DATABASE_NAME.test(name)) throw new TerminalError(`database: ${JSON.stringify(name)} is not a database name`);
@@ -466,45 +260,44 @@ export function database(db: Database, name: string): Database {
466
260
  return attempt.database(name);
467
261
  }
468
262
 
469
- /** 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. */
470
264
  class Sends {
471
- private readonly sends: Outgoing['sends'] = [];
265
+ private readonly sends: PendingSend[] = [];
472
266
  private open = true;
473
- readonly send: Send = sendOf((send) => {
474
- if (!this.open) throw new TerminalError('the transaction has ended: send from inside its body');
475
- this.sends.push(storedSend(send));
476
- });
267
+ readonly send: Send;
268
+
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
+ }
477
275
 
478
- /** The body ended: the transaction's sends, if it made any, their delays counted from now. */
479
- close(): Outgoing | undefined {
276
+ /** The body ended: the transaction's sends. */
277
+ close(): PendingSend[] {
480
278
  this.open = false;
481
- if (this.sends.length === 0) return undefined;
482
- const now = Date.now();
483
- for (const send of this.sends) if (send.delay !== undefined) send.due = now + send.delay;
484
- return { id: randomUUID(), sends: this.sends };
279
+ return this.sends;
485
280
  }
486
281
  }
487
282
 
488
283
  /**
489
- * One session of an attempt's database, from its open on. A failure ends it:
490
- * its open's, or a request's since. It closes as the attempt ends, unless the
491
- * 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.
492
286
  */
493
287
  class Session {
494
288
  readonly ready: Promise<Connection>;
495
- /** 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. */
496
290
  retired = false;
497
291
  private connection: Connection | undefined;
498
- /** Its connection, once its open settled. */
499
292
  get opened(): Connection | undefined {
500
293
  return this.connection;
501
294
  }
502
295
  private failed = false;
503
296
  private release: () => void = () => {};
504
297
 
505
- constructor(ready: Promise<Connection>, end: AttemptEnd) {
298
+ constructor(ready: Promise<Connection>, ended: AbortSignal) {
506
299
  this.ready = ready;
507
- void this.track(end);
300
+ void this.track(ended);
508
301
  }
509
302
 
510
303
  /** Whether a failure ended it. */
@@ -512,28 +305,25 @@ class Session {
512
305
  return this.failed || this.connection?.isUsable() === false;
513
306
  }
514
307
 
515
- /** 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. */
516
309
  async end(): Promise<Connection | undefined> {
517
310
  const db = await this.ready.catch(() => undefined);
518
311
  this.release();
519
312
  return db;
520
313
  }
521
314
 
522
- /** Close it now. */
523
315
  close(): void {
524
316
  void this.end()
525
317
  .then((db) => db?.close())
526
318
  .catch(() => {});
527
319
  }
528
320
 
529
- private async track(end: AttemptEnd) {
321
+ private async track(ended: AbortSignal) {
530
322
  try {
531
323
  const db = await this.ready;
532
324
  this.connection = db;
533
- // A handler still waiting for something else when the attempt ends (a
534
- // model request, say) keeps the session no longer: it closes once no
535
- // statement runs, and the handler's later calls fail.
536
- 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(() => {}));
537
327
  } catch {
538
328
  this.failed = true;
539
329
  }
@@ -541,155 +331,84 @@ class Session {
541
331
  }
542
332
 
543
333
  /**
544
- * An attempt's SQL session: opened on its first use, or as an exclusive
545
- * attempt starts ({@link openNow}), shared by everything the handler does,
546
- * and saved when the handler ends ({@link end}). With `name`, of the key's
547
- * database `name` ({@link database}), which has neither the object's schema
548
- * 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.
549
337
  */
550
338
  export class Attempt {
551
- /** `ctx.db`. */
552
339
  readonly db: Database;
553
- private readonly ctx: SqlHost;
554
- /** 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;
555
342
  private readonly config: ObjectConfig;
556
343
  private readonly name: string | undefined;
557
- /** Whether it is the object's own database of an exclusive handler: the one with an outbox. */
558
- private readonly hasOutbox: boolean;
559
- /** 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;
560
346
  private readonly databases = new Map<string, Attempt>();
561
- /** The session, from its first use on. */
562
347
  private session: Session | undefined;
563
- /** 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}. */
564
349
  private unhanded = 0;
565
- /** The ids of the outbox's transactions this attempt made the sends of. */
566
- private readonly made = new Set<string>();
567
- /** The writes that ride the next commit, by slot ({@link rideCommit}). */
568
- private readonly riders = new Map<string, Pending>();
569
- /** The transactions asked for and not finished: one that is under way writes the riders. */
570
- private active = 0;
571
- /** The macrotask at the end of which an urgent rider is written alone, if one is set. */
572
- private urgentTimer: NodeJS.Immediate | undefined;
573
- /** 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. */
574
351
  private readonly ensured = new Map<string, Schema>();
575
352
  private ended = false;
353
+ /** {@link end} began: the other databases are ending. */
354
+ private ending = false;
576
355
 
577
- constructor(ctx: SqlHost, config: ObjectConfig = {}, name?: string) {
578
- this.ctx = ctx;
356
+ constructor(host: AttemptHost, view: boolean, config: ObjectConfig = {}, name?: string) {
357
+ this.host = host;
358
+ this.view = view;
579
359
  this.config = config;
580
360
  this.name = name;
581
- this.hasOutbox = !ctx.shared && name === undefined;
361
+ this.sends = !view && name === undefined;
582
362
  const base = sqlOver(
583
363
  (sql, params) => this.askedNow(() => this.callNow((db) => db.queryColumnsNow(sql, params))),
584
364
  handlerError,
585
365
  );
586
366
  this.db = {
587
367
  ...base,
588
- // A write while a rider is pending is the transaction it rides.
589
- execute: (statement, params) =>
590
- this.riders.size > 0
591
- ? this.asked(() => this.transaction((tx) => tx.execute(statement, params)))
592
- : base.execute(statement, params),
593
368
  transaction: (body) => this.asked(() => this.transaction(body)),
594
369
  };
595
370
  ensuring(this.db, (schemas) => this.asked(() => this.call((db) => this.ensureSchemas(db, schemas))));
596
371
  ATTEMPT.on(this.db, this);
597
372
  }
598
373
 
599
- /** The key's database `name`, in this attempt: see {@link database}. */
374
+ /** See {@link database}. */
600
375
  database(name: string): Database {
601
- 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');
602
377
  let other = this.databases.get(name);
603
- 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)));
604
379
  return other.db;
605
380
  }
606
381
 
607
- /** {@link rideCommit}. */
608
- ride(slot: string, write: Rider | undefined, urgent: boolean): boolean {
609
- if (this.ctx.shared || this.ended) return false;
610
- if (write === undefined) this.riders.delete(slot);
611
- else {
612
- this.riders.set(slot, { write, urgent: urgent || (this.riders.get(slot)?.urgent ?? false) });
613
- this.arm();
614
- }
615
- return true;
616
- }
617
-
618
- /** Have the urgent riders written at the end of this macrotask, if any is pending and none is set. */
619
- private arm() {
620
- if (this.urgentTimer !== undefined || this.ended) return;
621
- if (![...this.riders.values()].some((r) => r.urgent)) return;
622
- this.urgentTimer = setImmediate(() => {
623
- this.urgentTimer = undefined;
624
- // A transaction under way writes them, or re-arms as it ends.
625
- if (this.ended || this.active > 0) return;
626
- // A failure leaves them pending, for the next commit or the flush, and is not tried again by a timer. After a
627
- // success, one that came while it committed (its own timer found it under way) is set now.
628
- this.transaction(async () => {}, false).then(
629
- () => this.arm(),
630
- () => {},
631
- );
632
- });
633
- }
634
-
635
- /** {@link flushRiders}, as a transaction of `db`: its commit writes them. */
636
- async flushRiders() {
637
- if (this.riders.size === 0) return;
638
- // Queued behind a transaction under way, which writes them as it commits: then there is nothing to write,
639
- // and this one rolls back, which commits nothing.
640
- let nothing = false;
641
- try {
642
- await this.db.transaction(async () => {
643
- if (this.riders.size > 0) return;
644
- nothing = true;
645
- throw new Error('no rider is pending');
646
- });
647
- } catch (error) {
648
- if (!nothing) throw error;
649
- }
650
- }
651
-
652
382
  /**
653
- * `call`, which the handler asked for, unless a cancellation is owed to
654
- * it: then the call fails with the cancellation, and does nothing.
655
- *
656
- * This is where the database delivers a cancellation, and the only place.
657
- * What the handler asks for passes through here; what the session does for
658
- * itself does not — the open, the object's schema, the sends a crashed
659
- * attempt left unmade, emptying the outbox after a commit — and a
660
- * cancellation that failed one of those would be delivered to nobody, or
661
- * would report a transaction as cancelled after it committed. And it is
662
- * before the call issues anything, so a call that fails with
663
- * `CancelledError` wrote nothing and sent nothing: a call already under way
664
- * when the cancellation arrives runs to its end, and the cancellation goes
665
- * 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.
666
387
  */
667
388
  private asked<T>(call: () => Promise<T>): Promise<T> {
668
- if (this.ctx.takeCancellation?.()) return Promise.reject(new CancelledError());
389
+ if (this.host.stop.take()) return Promise.reject(new CancelledError());
669
390
  return call();
670
391
  }
671
392
 
672
- /** {@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}). */
673
394
  private askedNow<T>(call: () => T | Promise<T>): T | Promise<T> {
674
- if (this.ctx.takeCancellation?.()) return Promise.reject(new CancelledError());
395
+ if (this.host.stop.take()) return Promise.reject(new CancelledError());
675
396
  return call();
676
397
  }
677
398
 
678
399
  /**
679
- * Open the session now, as the attempt starts, rather than on its first
680
- * call: the open makes the sends a crashed attempt committed and left
681
- * 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.
682
403
  */
683
404
  openNow() {
684
- if (this.hasOutbox && this.session === undefined) this.current().ready.catch(() => {});
405
+ if (this.sends && this.session === undefined) this.current().ready.catch(() => {});
685
406
  }
686
407
 
687
- /**
688
- * The handler ended with `outcome`: the key's other databases end, then
689
- * this one ({@link endSession}).
690
- */
408
+ /** The handler ended with `outcome`. The key's other databases end first, as the handler left them. */
691
409
  async end<T>(outcome: Outcome<T>): Promise<T> {
692
- // 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;
693
412
  const databases = await Promise.allSettled([...this.databases.values()].map((d) => d.end({ value: undefined })));
694
413
  const value = await this.endSession(outcome);
695
414
  const failed = databases.find((d) => d.status === 'rejected');
@@ -698,79 +417,48 @@ export class Attempt {
698
417
  }
699
418
 
700
419
  /**
701
- * `body` as one transaction. In the object's own database of an exclusive
702
- * handler, its sends commit with it, in the outbox, and are made with its
703
- * commit, right after its writes and before it waits for anything
704
- * (`withCommit`): Restate stores an attempt's commands in order, so they
705
- * are stored only if the commit is, and whatever fails the commit's wait
706
- * (the attempt's end, say) comes after them. A second commit empties the outbox
707
- * before `transaction` resolves: left until the handler's end, they would
708
- * be made again by an attempt that resumes a long wait (an approval), past
709
- * 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`).
710
422
  */
711
- private async transaction<T>(body: (tx: Transaction) => Promise<T>, rearm = true): Promise<T> {
712
- this.active++;
713
- try {
714
- return await this.transacted(body);
715
- } finally {
716
- this.active--;
717
- // What it left pending (it rolled back, or the rider came after it ran them) is for the end of this macrotask.
718
- if (rearm) this.arm();
719
- }
720
- }
721
-
722
- private async transacted<T>(body: (tx: Transaction) => Promise<T>): Promise<T> {
723
- let outgoing: Outgoing | undefined;
724
- // The riders this transaction wrote: pending until it has committed.
725
- let rode: [string, Pending][] = [];
726
- const value = await this.call((db) =>
423
+ private async transaction<T>(body: (tx: Transaction) => Promise<T>): Promise<T> {
424
+ return this.call((db) =>
727
425
  db.transaction(async (handle) => {
728
- const sends = this.hasOutbox ? new Sends() : undefined;
426
+ const sends = this.sends ? new Sends(this.config.serde) : undefined;
729
427
  const tx: Transaction = { ...forBody(handle), send: sends?.send ?? refusedSend };
730
- // A view's writes stay in its session: it has nothing to reset.
731
- DEFERRED.on(tx, handle);
732
- if (!this.ctx.shared) RESET.on(tx, () => this.reset(handle));
428
+ let made: PendingSend[] = [];
733
429
  let result: T;
734
430
  try {
735
431
  result = await body(tx);
736
432
  } finally {
737
- outgoing = sends?.close();
433
+ made = sends?.close() ?? [];
738
434
  }
739
- // After the body, which may have registered one (a transaction held open for more work), and before the commit.
740
- if (this.riders.size > 0) {
741
- rode = [...this.riders];
742
- for (const [, { write }] of rode) await write(tx);
743
- }
744
- if (this.hasOutbox) await this.commitOutbox(handle, outgoing);
435
+ if (this.sends) this.commitSends(handle, made);
745
436
  return result;
746
437
  }),
747
438
  );
748
- // One registered since is for the next commit.
749
- for (const [slot, pending] of rode) if (this.riders.get(slot) === pending) this.riders.delete(slot);
750
- if (outgoing !== undefined) await this.call((db) => this.flush(db));
751
- return value;
752
439
  }
753
440
 
754
- /**
755
- * Commit with `handle` the outbox as committed, but the sends stored since,
756
- * and with `outgoing`, which the commit makes. Unchanged, it is not
757
- * written again.
758
- */
759
- private async commitOutbox(handle: ConnectionTransaction, outgoing: Outgoing | undefined) {
760
- const outbox = await this.unstored(handle);
761
- if (outgoing !== undefined) {
762
- outbox.push(outgoing);
763
- 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;
764
449
  }
765
- 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
+ });
766
456
  }
767
457
 
768
458
  /**
769
- * `call` on the session, opening it on the first; its failure as the
770
- * handler fails with it. The call that fails on a session that a failure
771
- * ended is its last: the next opens another, which reads what is stored.
772
- * So the failure of an open made as the attempt started goes to the first
773
- * 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.
774
462
  */
775
463
  private async call<T>(call: (db: Connection) => Promise<T>): Promise<T> {
776
464
  const session = this.current();
@@ -793,11 +481,8 @@ export class Attempt {
793
481
  }
794
482
 
795
483
  /**
796
- * {@link call} for a call that answers with its value when it is ready: it
797
- * is the value, without a promise, which only this package takes so. That
798
- * is for a session that is open, and with no call before it still to reach
799
- * the connection (a call made before it, which waits for the session, must
800
- * 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.
801
486
  */
802
487
  private callNow<T>(call: (db: Connection) => T | Promise<T>): T | Promise<T> {
803
488
  const session = this.session;
@@ -805,7 +490,7 @@ export class Attempt {
805
490
  if (this.unhanded > 0 || session === undefined || db === undefined || session.retired || this.ended) {
806
491
  return this.call(async (connection) => call(connection));
807
492
  }
808
- // 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.
809
494
  const failure = (error: unknown): unknown => {
810
495
  if (session.ended) session.retired = true;
811
496
  return handlerError(error);
@@ -823,7 +508,7 @@ export class Attempt {
823
508
  : result;
824
509
  }
825
510
 
826
- /** 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. */
827
512
  private current(): Session {
828
513
  if (this.ended) throw new Error('the handler has ended: its SQL session is closed');
829
514
  if (this.session?.retired) this.session.close();
@@ -832,45 +517,34 @@ export class Attempt {
832
517
  }
833
518
 
834
519
  private open(): Session {
835
- const end = new AttemptEnd(this.ctx.invocationEndPromise.promise);
836
- 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);
837
524
  }
838
525
 
839
- private async start(end: AttemptEnd): Promise<Connection> {
840
- const ctx = this.ctx;
841
- // The page cache's: the key escaped, so that no key reads as another's
842
- // database (a name has no `/`).
843
- 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)}`;
844
530
  const namespace = this.name === undefined ? key : `${key}/${this.name}`;
845
- const wrap = this.config.wrapStore;
846
- // With a VM, the addon reads and writes the state itself and nothing of
847
- // the store crosses into JavaScript. A wrapper (fault injection, through
848
- // `withStoreWrapper`) would then have nothing to wrap, and using the
849
- // JavaScript store instead would quietly test the other path: the tests
850
- // that wrap give their attempts no VM, so this says so rather than
851
- // choosing for them.
852
- if (ctx.vm !== undefined && wrap !== undefined) {
853
- throw new TerminalError(
854
- 'withStoreWrapper wraps the store of an attempt served by the SDK; an attempt on the VM has none to wrap',
855
- );
856
- }
857
- const onVm = ctx.vm !== undefined;
858
- const object = onVm ? commitOnly() : objectStore(ctx, end, this.name);
859
- const db = onVm
860
- ? await openOnVm(namespace, object, ctx.vm, { name: this.name, reader: ctx.shared, working: ctx.working })
861
- : await open(namespace, wrap ? wrap(object) : object, { reader: ctx.shared });
862
- try {
863
- // A view writes nothing: a write fails, rather than vanish with the attempt.
864
- if (ctx.shared) await db.execute('PRAGMA query_only = 1');
865
- if (this.hasOutbox) {
866
- // What a crash left unmade; an open again in this attempt finds what
867
- // this attempt made, stored before it, as made.
868
- const left = decodeOutbox(await db.record(OUTBOX));
869
- for (const outgoing of left) if (!this.made.has(outgoing.id)) this.make(outgoing, true);
870
- // Emptied at once, as a transaction's own sends are (see `transaction`).
871
- 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;
872
540
  }
873
- // 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.
874
548
  const own = this.ownSchema();
875
549
  if (own) await this.ensureSchemas(db, [own]);
876
550
  } catch (error) {
@@ -881,16 +555,12 @@ export class Attempt {
881
555
  }
882
556
 
883
557
  /**
884
- * End the session, then settle as the handler did: an SQL error that
885
- * escaped it becomes terminal. The handler's error stands: what it
886
- * committed is stored, and an outbox left full is made by the next open.
887
- * A failure to end the session fails a handler that succeeded, which a
888
- * 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).
889
561
  */
890
562
  private async endSession<T>(outcome: Outcome<T>): Promise<T> {
891
563
  this.ended = true;
892
- if (this.urgentTimer !== undefined) clearImmediate(this.urgentTimer);
893
- this.urgentTimer = undefined;
894
564
  const failed = await this.close().then(
895
565
  () => undefined,
896
566
  (error: unknown) => ({ error }),
@@ -901,34 +571,20 @@ export class Attempt {
901
571
  }
902
572
 
903
573
  /**
904
- * Close the session as the attempt ends. A view's closes: it read the
905
- * snapshot it opened on, and one that outlived 16 commits failed its read
906
- * ("is gone"), which is retried. Another is saved, its outbox emptied. One
907
- * that a failure ended closes, and the object's own database is opened
908
- * again and saved: it may hold sends unmade (a crash left them, and this
909
- * attempt's open failed) or made and not emptied (the commit's wait
910
- * failed), and no attempt may follow this one (a cancelled invocation's),
911
- * 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.
912
576
  */
913
577
  private async close(): Promise<void> {
914
578
  if (this.session === undefined) return;
915
579
  const db = await this.session.end();
916
- if (this.ctx.shared) return db?.close();
580
+ if (this.view) return db?.close();
917
581
  if (db?.isUsable()) return this.save(db);
918
582
  await db?.close().catch(() => {});
919
- if (!this.hasOutbox) return;
920
- const again = this.open();
921
- try {
922
- await this.save(await again.ready);
923
- } finally {
924
- void again.end();
925
- }
926
583
  }
927
584
 
928
- /** Empty the outbox and save the session, which closes if that fails. */
585
+ /** Save the session. The session closes if that fails. */
929
586
  private async save(db: Connection) {
930
587
  try {
931
- if (this.hasOutbox) await this.flush(db);
932
588
  await db.save();
933
589
  } catch (error) {
934
590
  await db.close().catch(() => {});
@@ -936,65 +592,16 @@ export class Attempt {
936
592
  }
937
593
  }
938
594
 
939
- /** 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. */
940
596
  private ownSchema(): Schema | undefined {
941
597
  return this.name === undefined ? this.config.schema : undefined;
942
598
  }
943
599
 
944
- /** Empty the database in the transaction `handle` ({@link reset}), and apply the schemas this attempt applied again. */
945
- private async reset(handle: ConnectionTransaction) {
946
- const own = this.ownSchema();
947
- const schemas = [...(own ? [own] : []), ...[...this.ensured.values()].filter((s) => s !== own)];
948
- await dropAll(handle, schemas);
949
- }
950
-
951
- /** 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. */
952
601
  private async ensureSchemas(db: Connection, schemas: readonly Schema[]) {
953
602
  const lacking = schemas.filter((s) => !this.ensured.has(s.name));
954
603
  if (lacking.length === 0) return;
955
- await apply(db, lacking, { reader: this.ctx.shared });
604
+ await apply(db, lacking, { reader: this.view });
956
605
  for (const s of lacking) this.ensured.set(s.name, s);
957
606
  }
958
-
959
- /** 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. */
960
- private make({ id, sends }: Outgoing, again = false) {
961
- sends.forEach(({ parameter, due, delay, ...send }, index) => {
962
- this.ctx.genericSend({
963
- ...send,
964
- // Made again, a delayed send waits only what remains of its delay.
965
- ...(delay !== undefined ? { delay: again && due !== undefined ? Math.max(0, due - Date.now()) : delay } : {}),
966
- parameter: new Uint8Array(Buffer.from(parameter, 'base64')),
967
- inputSerde: serde.binary,
968
- idempotencyKey: send.idempotencyKey ?? `transaction/${id}/${index}`,
969
- });
970
- });
971
- this.made.add(id);
972
- }
973
-
974
- /** The outbox as committed, but the transactions this attempt made the sends of: a commit made after them stores them first. */
975
- private async unstored(db: Connection | ConnectionTransaction): Promise<Outgoing[]> {
976
- return decodeOutbox(await db.record(OUTBOX)).filter(({ id }) => !this.made.has(id));
977
- }
978
-
979
- /**
980
- * Empty the outbox, so that a later open does not make its sends again: a
981
- * commit after them, which stores them first.
982
- */
983
- private async flush(db: Connection) {
984
- if ((await db.record(OUTBOX)).length === 0) return;
985
- // Read in the transaction that writes it: one that committed sends since
986
- // the read above keeps them.
987
- await db.transaction(async (tx) => tx.setRecord(OUTBOX, encodeOutbox(await this.unstored(tx))));
988
- }
989
- }
990
-
991
- /** Run `handler`, then end `attempt`'s SQL session, if it opened one (see {@link Attempt.end}). */
992
- export async function withAttempt<T>(handler: () => Promise<T>, attempt: Attempt): Promise<T> {
993
- let outcome: Outcome<T>;
994
- try {
995
- outcome = { value: await handler() };
996
- } catch (error) {
997
- outcome = { error };
998
- }
999
- return attempt.end(outcome);
1000
607
  }