@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/database.ts CHANGED
@@ -1,12 +1,28 @@
1
- // A session's database, through the addon (`native/`): SQLite-compatible
2
- // SQL, kept in the object's state. The addon reads and writes the state through a
3
- // store (`objectStore` in session.ts), in the order it makes its requests
4
- // (`native/src/node.rs`); this module orders the calls and runs transactions.
1
+ // A session database through the addon (`native/`): SQLite-compatible SQL
2
+ // kept in the object state. On the VM the addon reads and writes the state
3
+ // itself as the VM's own actions, and a commit is one atomic group with what
4
+ // the transaction gave `commitWith` (`openOnVm`). Without a VM (tests) it
5
+ // calls a JavaScript `Store` (`open`), in the order it makes its requests.
6
+ //
7
+ // Call ordering. A `Connection` runs calls one at a time, in call order,
8
+ // through a promise queue (`serial`). A transaction holds the connection from
9
+ // `begin` to `commit` or `rollback`, and calls made meanwhile queue behind it.
10
+ // Inside the body, an `OpenTransaction` has its own queue, so every call the
11
+ // body makes runs before the commit, even one it does not await.
12
+ //
13
+ // The transaction guard refuses a `ctx.db` call from inside a transaction
14
+ // body with `SqlError`, because that call would wait for the body forever
15
+ // (see `Connection.running`).
16
+ //
17
+ // Fast paths. When nothing is queued, a call runs immediately, and if the
18
+ // addon answers synchronously (SQL on cached pages) the value is returned
19
+ // without a promise. Only this package sees such values (`...Now` methods);
20
+ // the public methods always return promises.
5
21
  import { AsyncLocalStorage } from 'node:async_hooks';
6
22
  import { Buffer } from 'node:buffer';
7
23
  import { addon as loaded } from './addon.ts';
8
- import { STATE_WAIT_OVER, type Vm } from './vm.ts';
9
- import { AttemptShutDown } from './driver.ts';
24
+ import { invalidInput, STATE_WAIT_OVER, type Vm, type VmCommit } from './vm.ts';
25
+ import { AttemptShutDown, InvalidInput } from './driver.ts';
10
26
 
11
27
  /** An SQL value. Integers come back as numbers, or as bigints beyond 2^53. */
12
28
  export type SqlValue = null | number | bigint | string | Uint8Array;
@@ -14,77 +30,52 @@ export type SqlValue = null | number | bigint | string | Uint8Array;
14
30
  /** An SQL parameter: an `SqlValue`, or a boolean, stored as 0 or 1. */
15
31
  export type SqlParam = SqlValue | boolean;
16
32
 
17
- /** The rows of a statement, with its column names. */
18
- export interface SqlQueryResult {
33
+ interface SqlQueryResult {
19
34
  columns: string[];
20
35
  rows: SqlValue[][];
21
36
  }
22
37
 
23
38
  /**
24
- * A failure a retry would repeat: SQL the engine rejected (a syntax error, a
25
- * constraint, a missing table), which undid just that statement and leaves
26
- * the session usable; a parameter it cannot bind; or a call the session
27
- * refused, which may have ended it (a `COMMIT` in a transaction's body, a
28
- * transaction left open). A storage error, which ends the session, rejects
29
- * as it is.
39
+ * A failure a retry would repeat: rejected SQL (undoes only that statement),
40
+ * a parameter that cannot bind, or a refused call, which may end the session
41
+ * (a `COMMIT` in a transaction body). A storage error rejects unchanged.
30
42
  */
31
43
  export class SqlError extends Error {
32
44
  override name = 'SqlError';
33
45
  }
34
46
 
35
- /** A row as an object, by column name. */
36
47
  export type Row = Record<string, SqlValue>;
37
48
 
38
- /** Reads of a database, or of one transaction of it. */
49
+ /** Reads of a database, or of one of its transactions. */
39
50
  export interface DatabaseReader {
40
51
  /**
41
- * The rows of one statement, each an object by column name; parameters
42
- * bind to a single statement. `T` declares the row's shape, unchecked:
43
- * integers past 2^53 come back as bigints, and booleans as 0 or 1. Columns
44
- * are named as SQL names them (an expression needs `AS`), and two of the
45
- * same name are an {@link SqlError}: alias them, or use {@link values}.
52
+ * The rows of one statement, each an object by column name. `T` declares
53
+ * the row shape, unchecked: integers past 2^53 come back as bigints, and
54
+ * booleans as 0 or 1. Columns are named as SQL names them (an expression
55
+ * needs `AS`). Two columns with the same name are an SQL error (from
56
+ * `ctx.db`, a `TerminalError`): alias them, or use {@link values}.
46
57
  */
47
58
  query<T = Row>(sql: string, params?: SqlParam[]): Promise<T[]>;
48
59
  /** The first row of {@link query}, or `undefined` when there is none. */
49
60
  get<T = Row>(sql: string, params?: SqlParam[]): Promise<T | undefined>;
50
- /** The rows of one statement as arrays, in column order: for adapters, and for columns that share a name. */
61
+ /** The rows as arrays, in column order: for adapters, and for columns that share a name. */
51
62
  values(sql: string, params?: SqlParam[]): Promise<SqlValue[][]>;
52
63
  }
53
64
 
54
- /** SQL: a database, or one transaction of it. */
65
+ /** SQL on a database, or on one of its transactions. */
55
66
  export interface DatabaseWriter extends DatabaseReader {
56
67
  /** Run SQL (one or more statements), discarding rows; parameters only with a single statement. */
57
68
  execute(sql: string, params?: SqlParam[]): Promise<void>;
58
69
  }
59
70
 
60
- /**
61
- * What the addon refuses as a parameter before it runs a call (its conversion
62
- * of an SQL value): a failure here is the call's own, and nothing ran.
63
- */
64
- function checkParams(params: SqlParam[] | undefined): void {
65
- for (const param of params ?? []) {
66
- const type = typeof param;
67
- if (type === 'bigint' && ((param as bigint) > 2n ** 63n - 1n || (param as bigint) < -(2n ** 63n))) {
68
- throw new Error('a bigint parameter exceeds 64 bits');
69
- }
70
- if (type === 'symbol' || type === 'function') {
71
- throw new Error(`unsupported SQL value: ${type === 'symbol' ? 'Symbol' : 'Function'}`);
72
- }
73
- if (type === 'object' && param !== null && !(param instanceof Uint8Array)) {
74
- throw new Error('unsupported SQL value: Object');
75
- }
76
- }
77
- }
78
-
79
- /** Nothing: what settles a queue's last call, and what `execute` resolves with. */
80
71
  const nothing = (): void => {};
81
72
 
82
- /** The rows of `result` as objects by column name; a column name twice is an {@link SqlError}. */
73
+ /** The rows as objects by column name. A repeated column name is an {@link SqlError}. */
83
74
  function objects({ columns, rows }: SqlQueryResult): Row[] {
84
75
  const names = columns.length;
85
76
  let twice: string | undefined;
86
77
  for (let i = 1; i < names && twice === undefined; i++) {
87
- // A statement has a handful of columns: comparing them pairwise costs less than a Set.
78
+ // A statement has few columns: comparing pairs costs less than a Set.
88
79
  for (let j = 0; j < i; j++) {
89
80
  if (columns[j] === columns[i]) {
90
81
  twice = columns[i];
@@ -95,7 +86,7 @@ function objects({ columns, rows }: SqlQueryResult): Row[] {
95
86
  if (twice !== undefined) {
96
87
  throw new SqlError(`the column ${twice} is named twice: alias one (AS), or read the rows with values()`);
97
88
  }
98
- // A column named `__proto__` is an own property of the row, as `Object.fromEntries` makes it;
89
+ // `Object.fromEntries` makes a column named `__proto__` an own property;
99
90
  // assignment would set the row's prototype instead.
100
91
  if (columns.includes('__proto__')) {
101
92
  return rows.map((row) => Object.fromEntries(columns.map((name, i) => [name, row[i]!])));
@@ -109,7 +100,7 @@ function objects({ columns, rows }: SqlQueryResult): Row[] {
109
100
  return result;
110
101
  }
111
102
 
112
- // `result` mapped, as a promise: a result that is ready is mapped now, and a failure of the mapping is a rejection.
103
+ // A ready result is mapped now; a throw from `map` becomes a rejection.
113
104
  const mapped = <T>(result: Answer<SqlQueryResult>, map: (result: SqlQueryResult) => T): Promise<T> => {
114
105
  if (result instanceof Promise) return result.then(map);
115
106
  try {
@@ -119,18 +110,12 @@ const mapped = <T>(result: Answer<SqlQueryResult>, map: (result: SqlQueryResult)
119
110
  }
120
111
  };
121
112
 
122
- /**
123
- * {@link DatabaseWriter} over `run`, which runs one call's SQL and returns
124
- * its rows with their columns, failing as `failure` makes its errors (as
125
- * `run` makes the engine's). `run` answers with the value itself when the
126
- * call was ready at once, which only this package sees: each call returns a
127
- * promise.
128
- */
113
+ /** A {@link DatabaseWriter} over `run`, which may answer synchronously; each method returns a promise. */
129
114
  export function sqlOver(
130
115
  run: (sql: string, params?: SqlParam[]) => Answer<SqlQueryResult>,
131
116
  failure: (error: unknown) => unknown = (error) => error,
132
117
  ): DatabaseWriter {
133
- // A `run` that throws is a rejection, as it was when each of these was an async function.
118
+ // A `run` that throws becomes a rejection, as in an async function.
134
119
  const start = (sql: string, params?: SqlParam[]): Answer<SqlQueryResult> => {
135
120
  try {
136
121
  return run(sql, params);
@@ -155,43 +140,28 @@ export function sqlOver(
155
140
  }
156
141
 
157
142
  /**
158
- * A key/value store, the object's state: `set` and `clear` return at once,
159
- * and `sync` resolves once every write before it is stored. Writes are
160
- * stored in the order they were made: a crash keeps a prefix of the writes
161
- * since the last sync and loses the rest. `get` returns the stored value, or
162
- * this request's own latest write; `undefined` or `null` when absent.
143
+ * The object state as a key/value store. `sync` resolves once every earlier
144
+ * write is stored. Writes are stored in order, so a crash keeps a prefix of
145
+ * them. `get` sees this request's own writes; absent is `undefined` or `null`.
163
146
  */
164
147
  export interface Store {
165
148
  get(key: string): Promise<Uint8Array | null | undefined>;
166
149
  set(key: string, value: Uint8Array): void;
167
150
  clear(key: string): void;
168
151
  sync(): Promise<void>;
169
- /**
170
- * Every key, as `ctx.stateKeys()`: then a commit that checkpoints deletes
171
- * the packs no checkpoint needs any more. A store without it keeps them.
172
- */
152
+ /** Every key. With it, a checkpoint deletes packs no checkpoint needs; without it they stay. */
173
153
  keys?(): Promise<string[]>;
174
154
  }
175
155
 
176
- /** The addon (`native/src/node.rs`). */
177
- interface Addon {
178
- open(namespace: string, store: Store, reader: boolean): Promise<NativeSession>;
179
- openOnVm(namespace: string, store: Store, vm: Vm, name: string | undefined, reader: boolean): Promise<NativeSession>;
180
- }
181
-
182
- /**
183
- * A session of the addon: one call at a time holds it. A transaction's body
184
- * runs between `begin` and `commit` (or `rollback`). A call answers at once
185
- * with its value (or throws) when it needs nothing from the store, such as
186
- * SQL on cached pages, and with a promise when it waits for the store.
187
- */
188
- interface NativeSession {
156
+ /** An addon session. A call that needs nothing from the store returns its value or throws. */
157
+ export interface NativeSession {
189
158
  queryColumns(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
190
- /** `queryColumns`, after `before`'s statements in the same call; absent in an addon without it. */
191
- queryColumnsAfter?(before: string[], sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
192
159
  begin(): Answer<void>;
193
- /** `withCommit`: whether the transaction has work to run at the commit's sync (see `Boundary.sync`). */
194
- commit(records: Record<string, Buffer>, withCommit?: boolean): Answer<void>;
160
+ /**
161
+ * On the VM, `withCommit` is what commits with the transaction: its sends,
162
+ * inside the commit's atomic group (see {@link ConnectionTransaction.commitWith}).
163
+ */
164
+ commit(records: Record<string, Buffer>, withCommit?: VmCommit): Answer<void>;
195
165
  rollback(): Answer<void>;
196
166
  record(name: string): Answer<Buffer>;
197
167
  isUsable(): boolean;
@@ -199,23 +169,26 @@ interface NativeSession {
199
169
  close(): Promise<void>;
200
170
  }
201
171
 
202
- /** A value, or a promise of it: `await` takes either. */
203
172
  type Answer<T> = T | Promise<T>;
204
173
 
205
- /**
206
- * Run `fn`, keeping the attempt alive meanwhile: the attempt's `working`
207
- * (see `driver.ts`). The database's calls run in it, being local work that
208
- * never waits on Restate for long.
209
- */
210
- export type Working = <T>(fn: () => T | Promise<T>) => Promise<T>;
174
+ /** The addon (`native/src/node.rs`). */
175
+ interface Addon {
176
+ open(namespace: string, store: Store, reader: boolean): Promise<NativeSession>;
177
+ openOnVm(namespace: string, vm: Vm, name: string | undefined, reader: boolean): Promise<NativeSession>;
178
+ }
211
179
 
212
180
  const addon = loaded as unknown as Addon;
213
181
 
214
- /**
215
- * Open the database of `namespace` over `store`. One process-wide page cache
216
- * serves every namespace. A `reader` reads beside the namespace's owner (a
217
- * shared handler), the state as of open, and writes nothing.
218
- */
182
+ /** `ctx.working` (see stop.ts). */
183
+ export type Working = <T>(fn: () => T | Promise<T>) => Promise<T>;
184
+
185
+ /** `ctx.stoppable` (see stop.ts). */
186
+ export type Stoppable = <T>(fn: (signal: AbortSignal) => T | Promise<T>) => Promise<T>;
187
+
188
+ /** `ctx.suspendable` (see stop.ts). */
189
+ export type Suspendable = <T>(fn: () => T | Promise<T>) => Promise<T>;
190
+
191
+ /** Open the database of `namespace` over `store`. A `reader` (a view) reads the state as of the open. */
219
192
  export async function open(namespace: string, store: Store, { reader = false } = {}): Promise<Connection> {
220
193
  const boundary = new Boundary(store);
221
194
  try {
@@ -226,65 +199,57 @@ export async function open(namespace: string, store: Store, { reader = false } =
226
199
  }
227
200
 
228
201
  /**
229
- * Open the database of `namespace` over the attempt's VM: the state is read
230
- * and written as the VM's own commands, in the addon, so none of it crosses
231
- * into JavaScript. `store` is called at one point only — its `sync`, which the
232
- * boundary uses to run what the committing transaction gave
233
- * {@link ConnectionTransaction.withCommit} — so its `get`, `set` and `clear`
234
- * are never reached. `name` names a database beside the object's own.
202
+ * Open the database of `namespace` over the attempt VM. The addon reads and
203
+ * writes the state as the VM's own actions and never calls a store; a commit
204
+ * is one atomic group, with what the transaction gave
205
+ * {@link ConnectionTransaction.commitWith}. `name` names a database beside the
206
+ * object database.
235
207
  */
236
208
  export async function openOnVm(
237
209
  namespace: string,
238
- store: Store,
239
210
  vm: Vm,
240
- { name, reader = false, working }: { name?: string; reader?: boolean; working?: Working } = {},
211
+ { name, reader = false, keepAlive }: { name?: string; reader?: boolean; keepAlive?: Working } = {},
241
212
  ): Promise<Connection> {
242
- const boundary = new Boundary(store, working);
213
+ const boundary = new Boundary(undefined, keepAlive);
243
214
  try {
244
- return new Connection(await boundary.alive(() => addon.openOnVm(namespace, boundary, vm, name, reader)), boundary);
215
+ return new Connection(await boundary.alive(() => addon.openOnVm(namespace, vm, name, reader)), boundary);
245
216
  } catch (error) {
246
- // The open reads the database's head. On this path that read waits in the
247
- // addon, so its failure arrives as text and `boundary.failed` is never
248
- // set: a cancellation here must still reach the handler as one.
217
+ // The open reads the head inside the addon, so `boundary.failed` is never
218
+ // set: the end of the attempt must still reach the handler as such.
249
219
  throw stateWaitFailure(error) ?? boundary.failed?.error ?? error;
250
220
  }
251
221
  }
252
222
 
253
223
  /**
254
- * The store as the addon calls it. An error of the store's crosses the addon
255
- * as text, which ends the session: the first is kept here, and the calls that
256
- * fail on the session it ended fail with it as it was thrown (the SDK's
257
- * CancelledError, say). And a commit's sync first runs what its transaction
258
- * gave {@link ConnectionTransaction.withCommit}: after the commit's writes,
259
- * before anything is awaited.
224
+ * The store as the addon calls it. A store error crosses the addon as text and
225
+ * ends the session, so the first one is kept for later calls to fail with. A
226
+ * commit sync first runs `withCommit`. On the VM the addon calls none of it.
260
227
  */
261
228
  class Boundary implements Store {
262
- /** The first error of the store's. */
263
229
  failed: { error: unknown } | undefined;
264
- /** What the next sync runs first: the committing transaction's. */
230
+ /** What the next sync runs first: the `withCommit` work of the committing transaction. */
265
231
  withSync: (() => void) | undefined;
266
232
  readonly keys?: () => Promise<string[]>;
267
- private readonly store: Store;
233
+ private readonly store: Store | undefined;
268
234
  private readonly working: Working | undefined;
269
235
 
270
- constructor(store: Store, working?: Working) {
236
+ constructor(store: Store | undefined, working?: Working) {
271
237
  this.store = store;
272
238
  this.working = working;
273
- // A store without keys keeps its garbage (see `Store.keys`).
274
- const keys = store.keys?.bind(store);
239
+ const keys = store?.keys?.bind(store);
275
240
  if (keys) this.keys = () => this.kept(keys);
276
241
  }
277
242
 
278
243
  get(key: string) {
279
- return this.kept(() => this.store.get(key));
244
+ return this.kept(() => this.stored().get(key));
280
245
  }
281
246
 
282
247
  set(key: string, value: Uint8Array) {
283
- this.kept(() => this.store.set(key, value));
248
+ this.kept(() => this.stored().set(key, value));
284
249
  }
285
250
 
286
251
  clear(key: string) {
287
- this.kept(() => this.store.clear(key));
252
+ this.kept(() => this.stored().clear(key));
288
253
  }
289
254
 
290
255
  sync() {
@@ -292,27 +257,30 @@ class Boundary implements Store {
292
257
  const run = this.withSync;
293
258
  this.withSync = undefined;
294
259
  run?.();
295
- return this.store.sync();
260
+ return this.store === undefined ? Promise.resolve() : this.store.sync();
296
261
  });
297
262
  }
298
263
 
299
- /**
300
- * `call`'s value if it is ready (the addon answers at once): then no scope
301
- * is opened, as nothing waited; a promise runs on in the attempt's `working`
302
- * scope, which opens as the call returns it.
303
- */
264
+ /** On the VM, reaching here is a bug in the addon. */
265
+ private stored(): Store {
266
+ if (this.store === undefined)
267
+ throw new Error('@restatedev/sessions: the VM serves the state; the addon reads none here');
268
+ return this.store;
269
+ }
270
+
271
+ /** A synchronous answer needs no keep-alive; a promise runs in `Stop.keepAlive`. */
304
272
  aliveNow<T>(call: () => Answer<T>): Answer<T> {
305
273
  const result = call();
306
274
  if (!(result instanceof Promise)) return result;
307
275
  return this.working === undefined ? result : this.working(() => result);
308
276
  }
309
277
 
310
- /** `call`, in the attempt's `working` scope if the database has one. */
278
+ /** `call`, in the attempt keep-alive if there is one (on the VM). */
311
279
  alive<T>(call: () => T | Promise<T>): Promise<T> {
312
280
  return this.working === undefined ? (async () => call())() : this.working(call);
313
281
  }
314
282
 
315
- /** `request`'s result, keeping its error, thrown at once or rejected. */
283
+ /** Run `request`, keeping the first error, whether thrown or rejected. */
316
284
  private kept<T>(request: () => T): T {
317
285
  const keep = (error: unknown): never => {
318
286
  this.failed ??= { error };
@@ -327,10 +295,7 @@ class Boundary implements Store {
327
295
  }
328
296
  }
329
297
 
330
- /**
331
- * SQL on a session of the addon: {@link DatabaseWriter}'s `query` and `execute`
332
- * by way of its `queryColumnsNow`.
333
- */
298
+ /** {@link DatabaseWriter} on an addon session, built on `queryColumnsNow`. */
334
299
  abstract class Sql implements DatabaseWriter {
335
300
  protected readonly native: NativeSession;
336
301
  protected readonly boundary: Boundary;
@@ -342,18 +307,9 @@ abstract class Sql implements DatabaseWriter {
342
307
  this.over = sqlOver((s, p) => this.queryColumnsNow(s, p));
343
308
  }
344
309
 
345
- /**
346
- * The rows of one statement with their column names: the value itself if
347
- * the addon answered at once (only the package's own code takes it so), else
348
- * a promise of it. A failure is a rejection.
349
- */
310
+ /** The rows of one statement with their columns; synchronous if the addon answered so. A failure rejects. */
350
311
  abstract queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
351
312
 
352
- queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult> {
353
- const result = this.queryColumnsNow(sql, params);
354
- return result instanceof Promise ? result : Promise.resolve(result);
355
- }
356
-
357
313
  query<T = Row>(sql: string, params?: SqlParam[]): Promise<T[]> {
358
314
  return this.over.query<T>(sql, params);
359
315
  }
@@ -370,7 +326,7 @@ abstract class Sql implements DatabaseWriter {
370
326
  return this.over.execute(sql, params);
371
327
  }
372
328
 
373
- /** {@link request}, but the value itself if it is ready, and then without a scope or a promise. */
329
+ /** {@link request} that returns a ready value synchronously, with no keep-alive. */
374
330
  protected requestNow<T>(call: () => Answer<T>): Answer<T> {
375
331
  let result: Answer<T>;
376
332
  try {
@@ -384,11 +340,7 @@ abstract class Sql implements DatabaseWriter {
384
340
  });
385
341
  }
386
342
 
387
- /**
388
- * `call`'s result, or its {@link failure}: `call` makes the request, as the
389
- * addon throws as it is called (arguments it cannot convert, and the error
390
- * of a call that answers at once).
391
- */
343
+ /** The result of `call`, or its {@link failure}, whether the addon throws or rejects. */
392
344
  protected request<T>(call: () => Answer<T>): Promise<T> {
393
345
  let alive: Promise<T>;
394
346
  try {
@@ -402,54 +354,57 @@ abstract class Sql implements DatabaseWriter {
402
354
  }
403
355
 
404
356
  /**
405
- * A request's `error`: an {@link SqlError} if a retry would repeat it; the
406
- * store's own error if that ended the session.
357
+ * An {@link SqlError} if a retry would repeat `error`; the store error if
358
+ * that ended the session. `sends`: `error` failed the commit of a
359
+ * transaction that sends on the VM, the one call whose failure can be the
360
+ * VM's refusal of a send, or the attempt's end with the session usable.
407
361
  */
408
- protected failure(error: unknown): unknown {
362
+ protected failure(error: unknown, { sends = false }: { sends?: boolean } = {}): unknown {
409
363
  if (error instanceof SqlError) return error;
410
- // The state is read and written in the addon on the VM's path, so the
411
- // end of the attempt fails those waits there and its text is all that
412
- // crosses back. Give the handler the class the driver's own awaits fail
413
- // with.
414
- const stateWait = stateWaitFailure(error);
364
+ // On the VM the end of the attempt fails state waits inside the addon,
365
+ // and only its text crosses back. Use the class the driver fails with.
366
+ // Such a failure ends the session; an SQL error that merely names the
367
+ // text leaves it usable, and stays an SQL error. The commit of a
368
+ // transaction that sends is read so whatever the session says: a commit
369
+ // that wrote nothing makes its sends in a group of their own after the
370
+ // database's commit, and the attempt's end fails that wait with the
371
+ // session still usable until the end closes it.
372
+ const stateWait = this.native.isUsable() && !sends ? undefined : stateWaitFailure(error);
415
373
  if (stateWait !== undefined) return stateWait;
374
+ // A send of the commit that Restate would refuse (an empty idempotency
375
+ // key): the VM dropped the commit's group, and the handler gets a
376
+ // TerminalError (400), as from a send of its own. Only the commit's text
377
+ // is read so: any other call's is SQL's, which a trigger can make read so.
378
+ const refused = sends ? invalidInput(error) : undefined;
379
+ if (refused !== undefined) return new InvalidInput(refused.message, { errorCode: refused.code });
416
380
  const failed = this.boundary.failed;
417
381
  if (failed !== undefined && !this.native.isUsable()) return failed.error;
382
+ // `InvalidArg`: the addon's refusal of a call that may have ended the
383
+ // session, or an argument it cannot convert; a retry would repeat either.
418
384
  const repeats = (error as { code?: unknown }).code === REFUSED || this.native.isUsable();
419
385
  return repeats ? new SqlError((error as Error).message, { cause: error }) : error;
420
386
  }
421
387
  }
422
388
 
423
- // The code of the addon's errors that a retry would repeat even though they
424
- // ended the session (its `Refused`), and of arguments it cannot convert.
389
+ /** The code of the addon's errors that a retry would repeat (its `Refused`, and arguments it cannot convert). */
425
390
  const REFUSED = 'InvalidArg';
426
391
 
427
- /**
428
- * The error of a call that failed because the attempt's state waits were
429
- * failed in the addon, at the end of the attempt. `undefined` for anything
430
- * else.
431
- */
392
+ /** `AttemptShutDown` for a call that failed because the attempt ended; else `undefined`. */
432
393
  function stateWaitFailure(error: unknown): unknown {
433
- const message = (error as { message?: unknown }).message;
434
- if (typeof message !== 'string') return undefined;
435
- if (message.includes(STATE_WAIT_OVER)) return new AttemptShutDown();
436
- return undefined;
394
+ const message = (error as { message?: unknown } | undefined)?.message;
395
+ return typeof message === 'string' && message.includes(STATE_WAIT_OVER) ? new AttemptShutDown() : undefined;
437
396
  }
438
397
 
439
- /**
440
- * A session of a database: calls run one at a time, in call order, and a
441
- * transaction holds the session until it commits or rolls back. Calls made
442
- * meanwhile wait, but a call from inside the transaction's body is refused,
443
- * as it would wait for that body: the body uses its `tx`.
444
- */
398
+ /** A session of a database. Call ordering and the transaction guard: see the header. */
445
399
  export class Connection extends Sql {
446
- /** This session's transaction whose body is running, in that body's asynchronous context. */
400
+ /**
401
+ * The transaction guard: the open transaction, in the async context of its
402
+ * body. A call from a continuation created before the transaction, which
403
+ * the body then awaits, is not refused and deadlocks.
404
+ */
447
405
  private readonly running = new AsyncLocalStorage<OpenTransaction>();
448
- /** Settles once the last call queued so far has: the next call runs after it. */
449
406
  private queue: Promise<unknown> = Promise.resolve();
450
- /** The last transaction queued, until it has committed or rolled back: a call queued behind it fires it. */
451
- private tail: Gate | undefined;
452
- /** Calls queued and not settled: with none, a call that is ready runs at once, in order. */
407
+ /** Calls queued and not settled. With none, a call can take the fast path. */
453
408
  private inflight = 0;
454
409
  private readonly release = (): void => {
455
410
  this.inflight--;
@@ -459,7 +414,7 @@ export class Connection extends Sql {
459
414
  if (this.inflight === 0 && this.running.getStore()?.open !== true) {
460
415
  const result = this.requestNow(() => this.native.queryColumns(sql, params));
461
416
  if (!(result instanceof Promise)) return result;
462
- // Not ready: the calls after it queue behind it.
417
+ // Not ready: later calls queue behind it.
463
418
  this.inflight++;
464
419
  this.queue = result.then(this.release, this.release);
465
420
  return result;
@@ -468,50 +423,42 @@ export class Connection extends Sql {
468
423
  }
469
424
 
470
425
  /**
471
- * Run `body` as one SQL transaction: it commits when `body` resolves, with
472
- * the records it set, and rolls back when it rejects, with the body's own
473
- * error, once the calls it made have settled. A statement in it that ends
474
- * the transaction (`COMMIT`, `ROLLBACK`) ends the session. A failing
475
- * COMMIT rolls back.
426
+ * Run `body` as one SQL transaction: once its calls settle, commit with its
427
+ * records, or roll back if it rejects. A `COMMIT` or `ROLLBACK` statement
428
+ * in it ends the session.
476
429
  */
477
430
  transaction<T>(body: (tx: ConnectionTransaction) => Promise<T>): Promise<T> {
478
- const gate = new Gate();
479
- return this.serial(async () => {
480
- try {
481
- return await this.run(gate, body);
482
- } finally {
483
- if (this.tail === gate) this.tail = undefined;
484
- }
485
- }, gate);
431
+ return this.serial(() => this.run(body));
486
432
  }
487
433
 
488
- private async run<T>(gate: Gate, body: (tx: ConnectionTransaction) => Promise<T>): Promise<T> {
434
+ private async run<T>(body: (tx: ConnectionTransaction) => Promise<T>): Promise<T> {
489
435
  await this.request(() => this.native.begin());
490
- const tx = new OpenTransaction(this.native, this.boundary, gate.promise);
436
+ const tx = new OpenTransaction(this.native, this.boundary);
491
437
  let result: T;
492
438
  try {
493
439
  result = await this.running.run(tx, () => body(tx));
494
- await tx.drain();
440
+ await tx.end();
495
441
  } catch (error) {
496
442
  await tx.end();
497
443
  await this.rollback();
498
444
  throw error;
499
445
  }
500
- const records = await tx.end();
501
- // Its commit's sync runs what the body gave `withCommit`; one that
502
- // wrote nothing synced nothing, and it runs after.
446
+ const records = tx.recordsSet();
447
+ // The commit sync runs the `withCommit` work; a commit with no writes has no sync, so it runs after.
448
+ // On the VM, what the body gave `commitWith` goes in the commit's atomic group instead.
503
449
  const runs = tx.commitRuns();
450
+ const withCommit = tx.vmCommit();
504
451
  this.boundary.withSync = runs;
505
452
  let unsynced: (() => void) | undefined;
506
453
  try {
507
- // Told whether there is work, the addon on the VM skips the call back
508
- // that would only run it.
509
- await this.boundary.alive(() => this.native.commit(records, runs !== undefined));
454
+ await this.boundary.alive(() =>
455
+ withCommit === undefined ? this.native.commit(records) : this.native.commit(records, withCommit),
456
+ );
510
457
  } catch (error) {
511
- // A COMMIT that fails (a deferred constraint) leaves the transaction
512
- // open: without the rollback, the calls after it would run inside it.
458
+ // A failed COMMIT (a deferred constraint) leaves the transaction open:
459
+ // without the rollback, later calls would run inside it.
513
460
  await this.rollback();
514
- throw this.failure(error);
461
+ throw this.failure(error, { sends: (withCommit?.sends.length ?? 0) > 0 });
515
462
  } finally {
516
463
  unsynced = this.boundary.withSync;
517
464
  this.boundary.withSync = undefined;
@@ -520,49 +467,38 @@ export class Connection extends Sql {
520
467
  return result;
521
468
  }
522
469
 
523
- /**
524
- * The record `name`, as the last commit that set it left it (see
525
- * {@link ConnectionTransaction.setRecord}); empty if none did.
526
- */
470
+ /** The record `name` as last committed (see {@link ConnectionTransaction.setRecord}); empty if never set. */
527
471
  record(name: string): Promise<Uint8Array> {
528
472
  return this.serial(async () => new Uint8Array(await this.request(() => this.native.record(name))));
529
473
  }
530
474
 
531
- /** Whether SQL can still run: an SQL error leaves the session usable, a storage error ends it. */
475
+ /** An SQL error leaves the session usable; a storage error ends it. */
532
476
  isUsable(): boolean {
533
477
  return this.native.isUsable();
534
478
  }
535
479
 
536
- /**
537
- * End the session after the calls before it, leaving its engine to the
538
- * next one. It rejects if they left a transaction open, or a failure ended
539
- * the session.
540
- */
480
+ /** End the session after earlier calls. Rejects if a transaction is left open or a failure ended it. */
541
481
  save(): Promise<void> {
542
482
  return this.serial(() => this.request(() => this.native.save()));
543
483
  }
544
484
 
545
- /** End the session now, whatever its state: queued calls reject. */
485
+ /** End the session now, whatever its state. Queued calls reject. */
546
486
  close(): Promise<void> {
547
487
  return this.native.close();
548
488
  }
549
489
 
550
- /** Run `call` once the calls before it have, unless it comes from the body of a transaction it would wait for. */
551
- private serial<T>(call: () => Promise<T>, transaction?: Gate): Promise<T> {
490
+ /** Queue `call` after earlier calls. Refused from the body of an open transaction (the guard). */
491
+ private serial<T>(call: () => Promise<T>): Promise<T> {
552
492
  if (this.running.getStore()?.open) {
553
493
  return Promise.reject(new SqlError('inside a transaction, use the transaction handle its body gets'));
554
494
  }
555
- // A call queued behind the last transaction tells it so; a transaction
556
- // that is itself the last one queued from now on is told by the next.
557
- this.tail?.fire();
558
- if (transaction !== undefined) this.tail = transaction;
559
495
  this.inflight++;
560
496
  const result = this.queue.then(call);
561
497
  this.queue = result.then(this.release, this.release);
562
498
  return result;
563
499
  }
564
500
 
565
- /** Roll back, unless a storage error ended the session: the caller rethrows its own error, which says why. */
501
+ /** Roll back, ignoring errors: the caller rethrows its own error, which explains the failure. */
566
502
  private async rollback(): Promise<void> {
567
503
  try {
568
504
  await this.native.rollback();
@@ -570,128 +506,65 @@ export class Connection extends Sql {
570
506
  }
571
507
  }
572
508
 
573
- /** SQL in one transaction, while its body runs, and the records it commits with. */
509
+ /** SQL in one transaction while its body runs, and the records it commits with. */
574
510
  export interface ConnectionTransaction extends DatabaseWriter {
575
- /** The rows of one statement, with their column names. */
576
- queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult>;
577
- /** {@link queryColumns} for the package's own code: the value itself if the addon answered at once. */
511
+ /** The rows of one statement with their columns, synchronous if the addon answered so (package code only). */
578
512
  queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
579
513
  /**
580
- * Set the record `name` to `value` with this transaction, in the same
581
- * write: a whole value kept beside the SQL, in no table, stored exactly
582
- * when the transaction is, even if it changes no row. It stays until a
583
- * later transaction sets it again; an empty value reads as never set. A
584
- * name is at most 255 bytes, and not `db`; a value at most 16 MiB.
514
+ * Set the record `name` to `value` in this commit: a value kept outside the
515
+ * tables, stored exactly when the transaction is, even if no row changes.
516
+ * It stays until a later transaction sets it. An empty value reads as never
517
+ * set. A name is at most 255 bytes and not `db`; a value at most 16 MiB.
585
518
  */
586
519
  setRecord(name: string, value: Uint8Array): void;
587
- /** The record `name` as this transaction would commit it: as it set it, or as committed. */
520
+ /** The record `name` as this transaction would commit it. */
588
521
  record(name: string): Promise<Uint8Array>;
589
522
  /**
590
- * Run `run` with the commit, right after its writes and before it waits
591
- * for them to be stored: the store's host gets what `run` makes after the
592
- * writes, and before anything that fails the commit's wait (Restate's
593
- * sends, which it stores in order with the writes). Never if the
594
- * transaction rolls back.
523
+ * Run `run` right after the commit writes, before waiting for them: for a
524
+ * store in JavaScript (the sends of a test's transaction, session.ts).
525
+ * Never if the transaction rolls back. On the VM, {@link commitWith}.
595
526
  */
596
527
  withCommit(run: () => void): void;
597
528
  /**
598
- * Have `sql` (one statement, no parameters) run just before the next call
599
- * of this transaction, in the same call to the addon: the statements are
600
- * the ones a call of their own would run, in the order the calls are made,
601
- * and the call fails with the error of the first that fails. It spares
602
- * the crossing of a call. Returns false, and queues nothing, where the
603
- * addon cannot (an addon without `queryColumnsAfter`): run the statement
604
- * with {@link queryColumns}. One still queued as the body settles runs
605
- * then, before the commit, and its failure fails the transaction.
606
- */
607
- defer(sql: string): boolean;
608
- /**
609
- * Take back the last `sql` that {@link defer} queued if no call has taken
610
- * it yet: it never runs. Whether it did.
529
+ * On the VM: commit `commit`'s sends with the transaction, inside its
530
+ * commit's atomic group, which is inside `commit.parentSpan`. A transaction
531
+ * that writes nothing makes them in a group of its own. A later call
532
+ * replaces it.
611
533
  */
612
- undefer(sql: string): boolean;
613
- /**
614
- * Settles, and never rejects, once another call to the connection has
615
- * queued behind this transaction: it is waiting for the body to settle.
616
- * A body that holds the transaction open for more work can return on it,
617
- * so that the call costs one commit rather than a stall. A call made
618
- * before the transaction began does not settle it, and neither does one
619
- * made from the body, which is refused.
620
- */
621
- readonly queued: Promise<void>;
534
+ commitWith(commit: VmCommit): void;
622
535
  }
623
536
 
624
- /** A promise that settles once {@link fire}d. */
625
- class Gate {
626
- readonly promise: Promise<void>;
627
- private resolve!: () => void;
628
- constructor() {
629
- this.promise = new Promise<void>((resolve) => (this.resolve = resolve));
630
- }
631
- fire(): void {
632
- this.resolve();
633
- }
634
- }
635
-
636
- /**
637
- * A {@link ConnectionTransaction} of {@link Connection.transaction}, open until its body
638
- * settles. Its calls run one at a time, in call order, also when the body
639
- * awaits several together, or none: each call made while it is open runs
640
- * before its commit or rollback, so none outlives it.
641
- */
537
+ /** A {@link ConnectionTransaction}, open until its body settles. Its calls queue as the header says. */
642
538
  class OpenTransaction extends Sql implements ConnectionTransaction {
643
- /** The records it sets, by name. */
644
539
  private readonly records = new Map<string, Buffer>();
645
- /** What runs with its commit (`withCommit`). */
646
540
  private readonly withCommits: (() => void)[] = [];
647
- /** Settles once the last call queued so far has: the next call runs after it. */
541
+ /** What commits with it on the VM (`commitWith`). */
542
+ private committing: VmCommit | undefined;
648
543
  private queue: Promise<unknown> = Promise.resolve();
649
544
  private inflight = 0;
650
545
  private readonly release = (): void => {
651
546
  this.inflight--;
652
547
  };
653
- /** SQL that runs with the next call made (`defer`). */
654
- private deferred: string[] = [];
655
548
  private ended = false;
656
- readonly queued: Promise<void>;
657
549
 
658
- constructor(native: NativeSession, boundary: Boundary, queued: Promise<void>) {
659
- super(native, boundary);
660
- this.queued = queued;
661
- }
662
-
663
- /** Whether it is open: its body runs, and holds its session. */
664
550
  get open(): boolean {
665
551
  return !this.ended;
666
552
  }
667
553
 
668
- /**
669
- * End it, refusing calls from now on, once the calls made before have
670
- * settled; then the records it set, as the addon's commit takes them.
671
- */
672
- async end(): Promise<Record<string, Buffer>> {
554
+ /** Refuse further calls; settles once earlier calls have. */
555
+ async end(): Promise<void> {
673
556
  this.ended = true;
674
557
  await this.queue;
558
+ }
559
+
560
+ recordsSet(): Record<string, Buffer> {
675
561
  return Object.fromEntries(this.records);
676
562
  }
677
563
 
678
564
  queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult> {
679
565
  if (this.ended) return Promise.reject(new SqlError('the transaction has ended'));
680
- // The call fails before it runs anything if the addon cannot take its parameters: it must not have taken
681
- // the deferred statements, which no call would then run (the addon's conversion is checked here, as it
682
- // comes first there, and cannot be told from a failure of the SQL once it has run).
683
- if (this.deferred.length > 0) {
684
- try {
685
- checkParams(params);
686
- } catch (error) {
687
- return Promise.reject(this.failure(error));
688
- }
689
- }
690
- // Taken as the call is made, not as it runs: a call made before the deferral runs before it.
691
- const before = this.deferred.splice(0);
692
- const call = () =>
693
- before.length === 0 ? this.native.queryColumns(sql, params) : this.native.queryColumnsAfter!(before, sql, params);
694
- if (this.inflight === 0 && !this.ended) {
566
+ const call = () => this.native.queryColumns(sql, params);
567
+ if (this.inflight === 0) {
695
568
  const result = this.requestNow(call);
696
569
  if (!(result instanceof Promise)) return result;
697
570
  this.inflight++;
@@ -701,31 +574,6 @@ class OpenTransaction extends Sql implements ConnectionTransaction {
701
574
  return this.serial(() => this.request(call));
702
575
  }
703
576
 
704
- defer(sql: string): boolean {
705
- if (this.ended || this.native.queryColumnsAfter === undefined) return false;
706
- this.deferred.push(sql);
707
- return true;
708
- }
709
-
710
- undefer(sql: string): boolean {
711
- const at = this.deferred.lastIndexOf(sql);
712
- if (at < 0) return false;
713
- this.deferred.splice(at, 1);
714
- return true;
715
- }
716
-
717
- /**
718
- * Refuse calls from now on, and once those made have settled, run the SQL
719
- * that no call took (`defer`): the body has settled, and the commit
720
- * follows. Its failure fails the transaction, as the call that would have
721
- * run it would have.
722
- */
723
- async drain(): Promise<void> {
724
- this.ended = true;
725
- await this.queue;
726
- for (const sql of this.deferred.splice(0)) await this.request(() => this.native.queryColumns(sql));
727
- }
728
-
729
577
  setRecord(name: string, value: Uint8Array): void {
730
578
  this.refuseEnded();
731
579
  this.records.set(name, Buffer.from(value));
@@ -736,19 +584,27 @@ class OpenTransaction extends Sql implements ConnectionTransaction {
736
584
  this.withCommits.push(run);
737
585
  }
738
586
 
739
- /** What runs with its commit, once it ended: see {@link withCommit}. */
587
+ commitWith(commit: VmCommit): void {
588
+ this.refuseEnded();
589
+ this.committing = commit;
590
+ }
591
+
592
+ /** What commits with it on the VM, once it ended: see {@link commitWith}. */
593
+ vmCommit(): VmCommit | undefined {
594
+ return this.committing;
595
+ }
596
+
740
597
  commitRuns(): (() => void) | undefined {
741
598
  const runs = this.withCommits;
742
599
  return runs.length === 0 ? undefined : () => runs.forEach((run) => run());
743
600
  }
744
601
 
745
602
  record(name: string): Promise<Uint8Array> {
746
- // As set when it is called, in call order with `setRecord`.
603
+ // Read when called, so it is ordered with `setRecord`.
747
604
  const set = this.records.get(name);
748
605
  return this.serial(async () => new Uint8Array(set ?? (await this.request(() => this.native.record(name)))));
749
606
  }
750
607
 
751
- /** Run `call`, made while the transaction is open, once the calls before it have. */
752
608
  private serial<T>(call: () => Promise<T>): Promise<T> {
753
609
  if (this.ended) return Promise.reject(new SqlError('the transaction has ended'));
754
610
  this.inflight++;