@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/dist/database.js CHANGED
@@ -1,49 +1,43 @@
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.js';
8
- import { STATE_WAIT_OVER } from './vm.js';
9
- import { AttemptShutDown } from './driver.js';
24
+ import { invalidInput, STATE_WAIT_OVER } from './vm.js';
25
+ import { AttemptShutDown, InvalidInput } from './driver.js';
10
26
  /**
11
- * A failure a retry would repeat: SQL the engine rejected (a syntax error, a
12
- * constraint, a missing table), which undid just that statement and leaves
13
- * the session usable; a parameter it cannot bind; or a call the session
14
- * refused, which may have ended it (a `COMMIT` in a transaction's body, a
15
- * transaction left open). A storage error, which ends the session, rejects
16
- * as it is.
27
+ * A failure a retry would repeat: rejected SQL (undoes only that statement),
28
+ * a parameter that cannot bind, or a refused call, which may end the session
29
+ * (a `COMMIT` in a transaction body). A storage error rejects unchanged.
17
30
  */
18
31
  export class SqlError extends Error {
19
32
  name = 'SqlError';
20
33
  }
21
- /**
22
- * What the addon refuses as a parameter before it runs a call (its conversion
23
- * of an SQL value): a failure here is the call's own, and nothing ran.
24
- */
25
- function checkParams(params) {
26
- for (const param of params ?? []) {
27
- const type = typeof param;
28
- if (type === 'bigint' && (param > 2n ** 63n - 1n || param < -(2n ** 63n))) {
29
- throw new Error('a bigint parameter exceeds 64 bits');
30
- }
31
- if (type === 'symbol' || type === 'function') {
32
- throw new Error(`unsupported SQL value: ${type === 'symbol' ? 'Symbol' : 'Function'}`);
33
- }
34
- if (type === 'object' && param !== null && !(param instanceof Uint8Array)) {
35
- throw new Error('unsupported SQL value: Object');
36
- }
37
- }
38
- }
39
- /** Nothing: what settles a queue's last call, and what `execute` resolves with. */
40
34
  const nothing = () => { };
41
- /** The rows of `result` as objects by column name; a column name twice is an {@link SqlError}. */
35
+ /** The rows as objects by column name. A repeated column name is an {@link SqlError}. */
42
36
  function objects({ columns, rows }) {
43
37
  const names = columns.length;
44
38
  let twice;
45
39
  for (let i = 1; i < names && twice === undefined; i++) {
46
- // A statement has a handful of columns: comparing them pairwise costs less than a Set.
40
+ // A statement has few columns: comparing pairs costs less than a Set.
47
41
  for (let j = 0; j < i; j++) {
48
42
  if (columns[j] === columns[i]) {
49
43
  twice = columns[i];
@@ -54,7 +48,7 @@ function objects({ columns, rows }) {
54
48
  if (twice !== undefined) {
55
49
  throw new SqlError(`the column ${twice} is named twice: alias one (AS), or read the rows with values()`);
56
50
  }
57
- // A column named `__proto__` is an own property of the row, as `Object.fromEntries` makes it;
51
+ // `Object.fromEntries` makes a column named `__proto__` an own property;
58
52
  // assignment would set the row's prototype instead.
59
53
  if (columns.includes('__proto__')) {
60
54
  return rows.map((row) => Object.fromEntries(columns.map((name, i) => [name, row[i]])));
@@ -68,7 +62,7 @@ function objects({ columns, rows }) {
68
62
  }
69
63
  return result;
70
64
  }
71
- // `result` mapped, as a promise: a result that is ready is mapped now, and a failure of the mapping is a rejection.
65
+ // A ready result is mapped now; a throw from `map` becomes a rejection.
72
66
  const mapped = (result, map) => {
73
67
  if (result instanceof Promise)
74
68
  return result.then(map);
@@ -79,15 +73,9 @@ const mapped = (result, map) => {
79
73
  return Promise.reject(error);
80
74
  }
81
75
  };
82
- /**
83
- * {@link DatabaseWriter} over `run`, which runs one call's SQL and returns
84
- * its rows with their columns, failing as `failure` makes its errors (as
85
- * `run` makes the engine's). `run` answers with the value itself when the
86
- * call was ready at once, which only this package sees: each call returns a
87
- * promise.
88
- */
76
+ /** A {@link DatabaseWriter} over `run`, which may answer synchronously; each method returns a promise. */
89
77
  export function sqlOver(run, failure = (error) => error) {
90
- // A `run` that throws is a rejection, as it was when each of these was an async function.
78
+ // A `run` that throws becomes a rejection, as in an async function.
91
79
  const start = (sql, params) => {
92
80
  try {
93
81
  return run(sql, params);
@@ -112,11 +100,7 @@ export function sqlOver(run, failure = (error) => error) {
112
100
  };
113
101
  }
114
102
  const addon = loaded;
115
- /**
116
- * Open the database of `namespace` over `store`. One process-wide page cache
117
- * serves every namespace. A `reader` reads beside the namespace's owner (a
118
- * shared handler), the state as of open, and writes nothing.
119
- */
103
+ /** Open the database of `namespace` over `store`. A `reader` (a view) reads the state as of the open. */
120
104
  export async function open(namespace, store, { reader = false } = {}) {
121
105
  const boundary = new Boundary(store);
122
106
  try {
@@ -127,37 +111,31 @@ export async function open(namespace, store, { reader = false } = {}) {
127
111
  }
128
112
  }
129
113
  /**
130
- * Open the database of `namespace` over the attempt's VM: the state is read
131
- * and written as the VM's own commands, in the addon, so none of it crosses
132
- * into JavaScript. `store` is called at one point only — its `sync`, which the
133
- * boundary uses to run what the committing transaction gave
134
- * {@link ConnectionTransaction.withCommit} — so its `get`, `set` and `clear`
135
- * are never reached. `name` names a database beside the object's own.
114
+ * Open the database of `namespace` over the attempt VM. The addon reads and
115
+ * writes the state as the VM's own actions and never calls a store; a commit
116
+ * is one atomic group, with what the transaction gave
117
+ * {@link ConnectionTransaction.commitWith}. `name` names a database beside the
118
+ * object database.
136
119
  */
137
- export async function openOnVm(namespace, store, vm, { name, reader = false, working } = {}) {
138
- const boundary = new Boundary(store, working);
120
+ export async function openOnVm(namespace, vm, { name, reader = false, keepAlive } = {}) {
121
+ const boundary = new Boundary(undefined, keepAlive);
139
122
  try {
140
- return new Connection(await boundary.alive(() => addon.openOnVm(namespace, boundary, vm, name, reader)), boundary);
123
+ return new Connection(await boundary.alive(() => addon.openOnVm(namespace, vm, name, reader)), boundary);
141
124
  }
142
125
  catch (error) {
143
- // The open reads the database's head. On this path that read waits in the
144
- // addon, so its failure arrives as text and `boundary.failed` is never
145
- // set: a cancellation here must still reach the handler as one.
126
+ // The open reads the head inside the addon, so `boundary.failed` is never
127
+ // set: the end of the attempt must still reach the handler as such.
146
128
  throw stateWaitFailure(error) ?? boundary.failed?.error ?? error;
147
129
  }
148
130
  }
149
131
  /**
150
- * The store as the addon calls it. An error of the store's crosses the addon
151
- * as text, which ends the session: the first is kept here, and the calls that
152
- * fail on the session it ended fail with it as it was thrown (the SDK's
153
- * CancelledError, say). And a commit's sync first runs what its transaction
154
- * gave {@link ConnectionTransaction.withCommit}: after the commit's writes,
155
- * before anything is awaited.
132
+ * The store as the addon calls it. A store error crosses the addon as text and
133
+ * ends the session, so the first one is kept for later calls to fail with. A
134
+ * commit sync first runs `withCommit`. On the VM the addon calls none of it.
156
135
  */
157
136
  class Boundary {
158
- /** The first error of the store's. */
159
137
  failed;
160
- /** What the next sync runs first: the committing transaction's. */
138
+ /** What the next sync runs first: the `withCommit` work of the committing transaction. */
161
139
  withSync;
162
140
  keys;
163
141
  store;
@@ -165,44 +143,45 @@ class Boundary {
165
143
  constructor(store, working) {
166
144
  this.store = store;
167
145
  this.working = working;
168
- // A store without keys keeps its garbage (see `Store.keys`).
169
- const keys = store.keys?.bind(store);
146
+ const keys = store?.keys?.bind(store);
170
147
  if (keys)
171
148
  this.keys = () => this.kept(keys);
172
149
  }
173
150
  get(key) {
174
- return this.kept(() => this.store.get(key));
151
+ return this.kept(() => this.stored().get(key));
175
152
  }
176
153
  set(key, value) {
177
- this.kept(() => this.store.set(key, value));
154
+ this.kept(() => this.stored().set(key, value));
178
155
  }
179
156
  clear(key) {
180
- this.kept(() => this.store.clear(key));
157
+ this.kept(() => this.stored().clear(key));
181
158
  }
182
159
  sync() {
183
160
  return this.kept(() => {
184
161
  const run = this.withSync;
185
162
  this.withSync = undefined;
186
163
  run?.();
187
- return this.store.sync();
164
+ return this.store === undefined ? Promise.resolve() : this.store.sync();
188
165
  });
189
166
  }
190
- /**
191
- * `call`'s value if it is ready (the addon answers at once): then no scope
192
- * is opened, as nothing waited; a promise runs on in the attempt's `working`
193
- * scope, which opens as the call returns it.
194
- */
167
+ /** On the VM, reaching here is a bug in the addon. */
168
+ stored() {
169
+ if (this.store === undefined)
170
+ throw new Error('@restatedev/sessions: the VM serves the state; the addon reads none here');
171
+ return this.store;
172
+ }
173
+ /** A synchronous answer needs no keep-alive; a promise runs in `Stop.keepAlive`. */
195
174
  aliveNow(call) {
196
175
  const result = call();
197
176
  if (!(result instanceof Promise))
198
177
  return result;
199
178
  return this.working === undefined ? result : this.working(() => result);
200
179
  }
201
- /** `call`, in the attempt's `working` scope if the database has one. */
180
+ /** `call`, in the attempt keep-alive if there is one (on the VM). */
202
181
  alive(call) {
203
182
  return this.working === undefined ? (async () => call())() : this.working(call);
204
183
  }
205
- /** `request`'s result, keeping its error, thrown at once or rejected. */
184
+ /** Run `request`, keeping the first error, whether thrown or rejected. */
206
185
  kept(request) {
207
186
  const keep = (error) => {
208
187
  this.failed ??= { error };
@@ -217,10 +196,7 @@ class Boundary {
217
196
  }
218
197
  }
219
198
  }
220
- /**
221
- * SQL on a session of the addon: {@link DatabaseWriter}'s `query` and `execute`
222
- * by way of its `queryColumnsNow`.
223
- */
199
+ /** {@link DatabaseWriter} on an addon session, built on `queryColumnsNow`. */
224
200
  class Sql {
225
201
  native;
226
202
  boundary;
@@ -230,10 +206,6 @@ class Sql {
230
206
  this.boundary = boundary;
231
207
  this.over = sqlOver((s, p) => this.queryColumnsNow(s, p));
232
208
  }
233
- queryColumns(sql, params) {
234
- const result = this.queryColumnsNow(sql, params);
235
- return result instanceof Promise ? result : Promise.resolve(result);
236
- }
237
209
  query(sql, params) {
238
210
  return this.over.query(sql, params);
239
211
  }
@@ -246,7 +218,7 @@ class Sql {
246
218
  execute(sql, params) {
247
219
  return this.over.execute(sql, params);
248
220
  }
249
- /** {@link request}, but the value itself if it is ready, and then without a scope or a promise. */
221
+ /** {@link request} that returns a ready value synchronously, with no keep-alive. */
250
222
  requestNow(call) {
251
223
  let result;
252
224
  try {
@@ -261,11 +233,7 @@ class Sql {
261
233
  throw this.failure(error);
262
234
  });
263
235
  }
264
- /**
265
- * `call`'s result, or its {@link failure}: `call` makes the request, as the
266
- * addon throws as it is called (arguments it cannot convert, and the error
267
- * of a call that answers at once).
268
- */
236
+ /** The result of `call`, or its {@link failure}, whether the addon throws or rejects. */
269
237
  request(call) {
270
238
  let alive;
271
239
  try {
@@ -279,56 +247,58 @@ class Sql {
279
247
  });
280
248
  }
281
249
  /**
282
- * A request's `error`: an {@link SqlError} if a retry would repeat it; the
283
- * store's own error if that ended the session.
250
+ * An {@link SqlError} if a retry would repeat `error`; the store error if
251
+ * that ended the session. `sends`: `error` failed the commit of a
252
+ * transaction that sends on the VM, the one call whose failure can be the
253
+ * VM's refusal of a send, or the attempt's end with the session usable.
284
254
  */
285
- failure(error) {
255
+ failure(error, { sends = false } = {}) {
286
256
  if (error instanceof SqlError)
287
257
  return error;
288
- // The state is read and written in the addon on the VM's path, so the
289
- // end of the attempt fails those waits there and its text is all that
290
- // crosses back. Give the handler the class the driver's own awaits fail
291
- // with.
292
- const stateWait = stateWaitFailure(error);
258
+ // On the VM the end of the attempt fails state waits inside the addon,
259
+ // and only its text crosses back. Use the class the driver fails with.
260
+ // Such a failure ends the session; an SQL error that merely names the
261
+ // text leaves it usable, and stays an SQL error. The commit of a
262
+ // transaction that sends is read so whatever the session says: a commit
263
+ // that wrote nothing makes its sends in a group of their own after the
264
+ // database's commit, and the attempt's end fails that wait with the
265
+ // session still usable until the end closes it.
266
+ const stateWait = this.native.isUsable() && !sends ? undefined : stateWaitFailure(error);
293
267
  if (stateWait !== undefined)
294
268
  return stateWait;
269
+ // A send of the commit that Restate would refuse (an empty idempotency
270
+ // key): the VM dropped the commit's group, and the handler gets a
271
+ // TerminalError (400), as from a send of its own. Only the commit's text
272
+ // is read so: any other call's is SQL's, which a trigger can make read so.
273
+ const refused = sends ? invalidInput(error) : undefined;
274
+ if (refused !== undefined)
275
+ return new InvalidInput(refused.message, { errorCode: refused.code });
295
276
  const failed = this.boundary.failed;
296
277
  if (failed !== undefined && !this.native.isUsable())
297
278
  return failed.error;
279
+ // `InvalidArg`: the addon's refusal of a call that may have ended the
280
+ // session, or an argument it cannot convert; a retry would repeat either.
298
281
  const repeats = error.code === REFUSED || this.native.isUsable();
299
282
  return repeats ? new SqlError(error.message, { cause: error }) : error;
300
283
  }
301
284
  }
302
- // The code of the addon's errors that a retry would repeat even though they
303
- // ended the session (its `Refused`), and of arguments it cannot convert.
285
+ /** The code of the addon's errors that a retry would repeat (its `Refused`, and arguments it cannot convert). */
304
286
  const REFUSED = 'InvalidArg';
305
- /**
306
- * The error of a call that failed because the attempt's state waits were
307
- * failed in the addon, at the end of the attempt. `undefined` for anything
308
- * else.
309
- */
287
+ /** `AttemptShutDown` for a call that failed because the attempt ended; else `undefined`. */
310
288
  function stateWaitFailure(error) {
311
- const message = error.message;
312
- if (typeof message !== 'string')
313
- return undefined;
314
- if (message.includes(STATE_WAIT_OVER))
315
- return new AttemptShutDown();
316
- return undefined;
289
+ const message = error?.message;
290
+ return typeof message === 'string' && message.includes(STATE_WAIT_OVER) ? new AttemptShutDown() : undefined;
317
291
  }
318
- /**
319
- * A session of a database: calls run one at a time, in call order, and a
320
- * transaction holds the session until it commits or rolls back. Calls made
321
- * meanwhile wait, but a call from inside the transaction's body is refused,
322
- * as it would wait for that body: the body uses its `tx`.
323
- */
292
+ /** A session of a database. Call ordering and the transaction guard: see the header. */
324
293
  export class Connection extends Sql {
325
- /** This session's transaction whose body is running, in that body's asynchronous context. */
294
+ /**
295
+ * The transaction guard: the open transaction, in the async context of its
296
+ * body. A call from a continuation created before the transaction, which
297
+ * the body then awaits, is not refused and deadlocks.
298
+ */
326
299
  running = new AsyncLocalStorage();
327
- /** Settles once the last call queued so far has: the next call runs after it. */
328
300
  queue = Promise.resolve();
329
- /** The last transaction queued, until it has committed or rolled back: a call queued behind it fires it. */
330
- tail;
331
- /** Calls queued and not settled: with none, a call that is ready runs at once, in order. */
301
+ /** Calls queued and not settled. With none, a call can take the fast path. */
332
302
  inflight = 0;
333
303
  release = () => {
334
304
  this.inflight--;
@@ -338,7 +308,7 @@ export class Connection extends Sql {
338
308
  const result = this.requestNow(() => this.native.queryColumns(sql, params));
339
309
  if (!(result instanceof Promise))
340
310
  return result;
341
- // Not ready: the calls after it queue behind it.
311
+ // Not ready: later calls queue behind it.
342
312
  this.inflight++;
343
313
  this.queue = result.then(this.release, this.release);
344
314
  return result;
@@ -346,53 +316,41 @@ export class Connection extends Sql {
346
316
  return this.serial(() => this.request(() => this.native.queryColumns(sql, params)));
347
317
  }
348
318
  /**
349
- * Run `body` as one SQL transaction: it commits when `body` resolves, with
350
- * the records it set, and rolls back when it rejects, with the body's own
351
- * error, once the calls it made have settled. A statement in it that ends
352
- * the transaction (`COMMIT`, `ROLLBACK`) ends the session. A failing
353
- * COMMIT rolls back.
319
+ * Run `body` as one SQL transaction: once its calls settle, commit with its
320
+ * records, or roll back if it rejects. A `COMMIT` or `ROLLBACK` statement
321
+ * in it ends the session.
354
322
  */
355
323
  transaction(body) {
356
- const gate = new Gate();
357
- return this.serial(async () => {
358
- try {
359
- return await this.run(gate, body);
360
- }
361
- finally {
362
- if (this.tail === gate)
363
- this.tail = undefined;
364
- }
365
- }, gate);
324
+ return this.serial(() => this.run(body));
366
325
  }
367
- async run(gate, body) {
326
+ async run(body) {
368
327
  await this.request(() => this.native.begin());
369
- const tx = new OpenTransaction(this.native, this.boundary, gate.promise);
328
+ const tx = new OpenTransaction(this.native, this.boundary);
370
329
  let result;
371
330
  try {
372
331
  result = await this.running.run(tx, () => body(tx));
373
- await tx.drain();
332
+ await tx.end();
374
333
  }
375
334
  catch (error) {
376
335
  await tx.end();
377
336
  await this.rollback();
378
337
  throw error;
379
338
  }
380
- const records = await tx.end();
381
- // Its commit's sync runs what the body gave `withCommit`; one that
382
- // wrote nothing synced nothing, and it runs after.
339
+ const records = tx.recordsSet();
340
+ // The commit sync runs the `withCommit` work; a commit with no writes has no sync, so it runs after.
341
+ // On the VM, what the body gave `commitWith` goes in the commit's atomic group instead.
383
342
  const runs = tx.commitRuns();
343
+ const withCommit = tx.vmCommit();
384
344
  this.boundary.withSync = runs;
385
345
  let unsynced;
386
346
  try {
387
- // Told whether there is work, the addon on the VM skips the call back
388
- // that would only run it.
389
- await this.boundary.alive(() => this.native.commit(records, runs !== undefined));
347
+ await this.boundary.alive(() => withCommit === undefined ? this.native.commit(records) : this.native.commit(records, withCommit));
390
348
  }
391
349
  catch (error) {
392
- // A COMMIT that fails (a deferred constraint) leaves the transaction
393
- // open: without the rollback, the calls after it would run inside it.
350
+ // A failed COMMIT (a deferred constraint) leaves the transaction open:
351
+ // without the rollback, later calls would run inside it.
394
352
  await this.rollback();
395
- throw this.failure(error);
353
+ throw this.failure(error, { sends: (withCommit?.sends.length ?? 0) > 0 });
396
354
  }
397
355
  finally {
398
356
  unsynced = this.boundary.withSync;
@@ -401,45 +359,33 @@ export class Connection extends Sql {
401
359
  unsynced?.();
402
360
  return result;
403
361
  }
404
- /**
405
- * The record `name`, as the last commit that set it left it (see
406
- * {@link ConnectionTransaction.setRecord}); empty if none did.
407
- */
362
+ /** The record `name` as last committed (see {@link ConnectionTransaction.setRecord}); empty if never set. */
408
363
  record(name) {
409
364
  return this.serial(async () => new Uint8Array(await this.request(() => this.native.record(name))));
410
365
  }
411
- /** Whether SQL can still run: an SQL error leaves the session usable, a storage error ends it. */
366
+ /** An SQL error leaves the session usable; a storage error ends it. */
412
367
  isUsable() {
413
368
  return this.native.isUsable();
414
369
  }
415
- /**
416
- * End the session after the calls before it, leaving its engine to the
417
- * next one. It rejects if they left a transaction open, or a failure ended
418
- * the session.
419
- */
370
+ /** End the session after earlier calls. Rejects if a transaction is left open or a failure ended it. */
420
371
  save() {
421
372
  return this.serial(() => this.request(() => this.native.save()));
422
373
  }
423
- /** End the session now, whatever its state: queued calls reject. */
374
+ /** End the session now, whatever its state. Queued calls reject. */
424
375
  close() {
425
376
  return this.native.close();
426
377
  }
427
- /** Run `call` once the calls before it have, unless it comes from the body of a transaction it would wait for. */
428
- serial(call, transaction) {
378
+ /** Queue `call` after earlier calls. Refused from the body of an open transaction (the guard). */
379
+ serial(call) {
429
380
  if (this.running.getStore()?.open) {
430
381
  return Promise.reject(new SqlError('inside a transaction, use the transaction handle its body gets'));
431
382
  }
432
- // A call queued behind the last transaction tells it so; a transaction
433
- // that is itself the last one queued from now on is told by the next.
434
- this.tail?.fire();
435
- if (transaction !== undefined)
436
- this.tail = transaction;
437
383
  this.inflight++;
438
384
  const result = this.queue.then(call);
439
385
  this.queue = result.then(this.release, this.release);
440
386
  return result;
441
387
  }
442
- /** Roll back, unless a storage error ended the session: the caller rethrows its own error, which says why. */
388
+ /** Roll back, ignoring errors: the caller rethrows its own error, which explains the failure. */
443
389
  async rollback() {
444
390
  try {
445
391
  await this.native.rollback();
@@ -447,73 +393,34 @@ export class Connection extends Sql {
447
393
  catch { }
448
394
  }
449
395
  }
450
- /** A promise that settles once {@link fire}d. */
451
- class Gate {
452
- promise;
453
- resolve;
454
- constructor() {
455
- this.promise = new Promise((resolve) => (this.resolve = resolve));
456
- }
457
- fire() {
458
- this.resolve();
459
- }
460
- }
461
- /**
462
- * A {@link ConnectionTransaction} of {@link Connection.transaction}, open until its body
463
- * settles. Its calls run one at a time, in call order, also when the body
464
- * awaits several together, or none: each call made while it is open runs
465
- * before its commit or rollback, so none outlives it.
466
- */
396
+ /** A {@link ConnectionTransaction}, open until its body settles. Its calls queue as the header says. */
467
397
  class OpenTransaction extends Sql {
468
- /** The records it sets, by name. */
469
398
  records = new Map();
470
- /** What runs with its commit (`withCommit`). */
471
399
  withCommits = [];
472
- /** Settles once the last call queued so far has: the next call runs after it. */
400
+ /** What commits with it on the VM (`commitWith`). */
401
+ committing;
473
402
  queue = Promise.resolve();
474
403
  inflight = 0;
475
404
  release = () => {
476
405
  this.inflight--;
477
406
  };
478
- /** SQL that runs with the next call made (`defer`). */
479
- deferred = [];
480
407
  ended = false;
481
- queued;
482
- constructor(native, boundary, queued) {
483
- super(native, boundary);
484
- this.queued = queued;
485
- }
486
- /** Whether it is open: its body runs, and holds its session. */
487
408
  get open() {
488
409
  return !this.ended;
489
410
  }
490
- /**
491
- * End it, refusing calls from now on, once the calls made before have
492
- * settled; then the records it set, as the addon's commit takes them.
493
- */
411
+ /** Refuse further calls; settles once earlier calls have. */
494
412
  async end() {
495
413
  this.ended = true;
496
414
  await this.queue;
415
+ }
416
+ recordsSet() {
497
417
  return Object.fromEntries(this.records);
498
418
  }
499
419
  queryColumnsNow(sql, params) {
500
420
  if (this.ended)
501
421
  return Promise.reject(new SqlError('the transaction has ended'));
502
- // The call fails before it runs anything if the addon cannot take its parameters: it must not have taken
503
- // the deferred statements, which no call would then run (the addon's conversion is checked here, as it
504
- // comes first there, and cannot be told from a failure of the SQL once it has run).
505
- if (this.deferred.length > 0) {
506
- try {
507
- checkParams(params);
508
- }
509
- catch (error) {
510
- return Promise.reject(this.failure(error));
511
- }
512
- }
513
- // Taken as the call is made, not as it runs: a call made before the deferral runs before it.
514
- const before = this.deferred.splice(0);
515
- const call = () => before.length === 0 ? this.native.queryColumns(sql, params) : this.native.queryColumnsAfter(before, sql, params);
516
- if (this.inflight === 0 && !this.ended) {
422
+ const call = () => this.native.queryColumns(sql, params);
423
+ if (this.inflight === 0) {
517
424
  const result = this.requestNow(call);
518
425
  if (!(result instanceof Promise))
519
426
  return result;
@@ -523,31 +430,6 @@ class OpenTransaction extends Sql {
523
430
  }
524
431
  return this.serial(() => this.request(call));
525
432
  }
526
- defer(sql) {
527
- if (this.ended || this.native.queryColumnsAfter === undefined)
528
- return false;
529
- this.deferred.push(sql);
530
- return true;
531
- }
532
- undefer(sql) {
533
- const at = this.deferred.lastIndexOf(sql);
534
- if (at < 0)
535
- return false;
536
- this.deferred.splice(at, 1);
537
- return true;
538
- }
539
- /**
540
- * Refuse calls from now on, and once those made have settled, run the SQL
541
- * that no call took (`defer`): the body has settled, and the commit
542
- * follows. Its failure fails the transaction, as the call that would have
543
- * run it would have.
544
- */
545
- async drain() {
546
- this.ended = true;
547
- await this.queue;
548
- for (const sql of this.deferred.splice(0))
549
- await this.request(() => this.native.queryColumns(sql));
550
- }
551
433
  setRecord(name, value) {
552
434
  this.refuseEnded();
553
435
  this.records.set(name, Buffer.from(value));
@@ -556,17 +438,23 @@ class OpenTransaction extends Sql {
556
438
  this.refuseEnded();
557
439
  this.withCommits.push(run);
558
440
  }
559
- /** What runs with its commit, once it ended: see {@link withCommit}. */
441
+ commitWith(commit) {
442
+ this.refuseEnded();
443
+ this.committing = commit;
444
+ }
445
+ /** What commits with it on the VM, once it ended: see {@link commitWith}. */
446
+ vmCommit() {
447
+ return this.committing;
448
+ }
560
449
  commitRuns() {
561
450
  const runs = this.withCommits;
562
451
  return runs.length === 0 ? undefined : () => runs.forEach((run) => run());
563
452
  }
564
453
  record(name) {
565
- // As set when it is called, in call order with `setRecord`.
454
+ // Read when called, so it is ordered with `setRecord`.
566
455
  const set = this.records.get(name);
567
456
  return this.serial(async () => new Uint8Array(set ?? (await this.request(() => this.native.record(name)))));
568
457
  }
569
- /** Run `call`, made while the transaction is open, once the calls before it have. */
570
458
  serial(call) {
571
459
  if (this.ended)
572
460
  return Promise.reject(new SqlError('the transaction has ended'));