@restatedev/sessions 0.1.0 → 0.3.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 (47) hide show
  1. package/README.md +54 -8
  2. package/dist/database.d.ts +41 -2
  3. package/dist/database.d.ts.map +1 -1
  4. package/dist/database.js +99 -20
  5. package/dist/database.js.map +1 -1
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +4 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/internal.d.ts +6 -3
  11. package/dist/internal.d.ts.map +1 -1
  12. package/dist/internal.js +5 -2
  13. package/dist/internal.js.map +1 -1
  14. package/dist/link.d.ts +10 -0
  15. package/dist/link.d.ts.map +1 -0
  16. package/dist/link.js +19 -0
  17. package/dist/link.js.map +1 -0
  18. package/dist/object.d.ts +17 -4
  19. package/dist/object.d.ts.map +1 -1
  20. package/dist/object.js +61 -46
  21. package/dist/object.js.map +1 -1
  22. package/dist/schema.d.ts +7 -6
  23. package/dist/schema.d.ts.map +1 -1
  24. package/dist/schema.js +9 -10
  25. package/dist/schema.js.map +1 -1
  26. package/dist/scope.d.ts +38 -0
  27. package/dist/scope.d.ts.map +1 -0
  28. package/dist/scope.js +55 -0
  29. package/dist/scope.js.map +1 -0
  30. package/dist/serve.d.ts +21 -0
  31. package/dist/serve.d.ts.map +1 -0
  32. package/dist/serve.js +49 -0
  33. package/dist/serve.js.map +1 -0
  34. package/dist/session.d.ts +70 -34
  35. package/dist/session.d.ts.map +1 -1
  36. package/dist/session.js +273 -221
  37. package/dist/session.js.map +1 -1
  38. package/package.json +4 -4
  39. package/src/database.ts +111 -22
  40. package/src/index.ts +4 -1
  41. package/src/internal.ts +16 -3
  42. package/src/link.ts +22 -0
  43. package/src/object.ts +94 -63
  44. package/src/schema.ts +11 -10
  45. package/src/scope.ts +78 -0
  46. package/src/serve.ts +54 -0
  47. package/src/session.ts +273 -230
package/src/session.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { Buffer } from 'node:buffer';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import type * as restate from '@restatedev/restate-sdk';
8
- import { CancelledError, serde, TerminalError } from '@restatedev/restate-sdk';
8
+ import { serde, TerminalError } from '@restatedev/restate-sdk';
9
9
  import { millisOrDurationToMillis, type Serde } from '@restatedev/restate-sdk-core';
10
10
  import {
11
11
  open,
@@ -20,7 +20,8 @@ import {
20
20
  type Store,
21
21
  type ConnectionTransaction,
22
22
  } from './database.ts';
23
- import { apply, dropAll, ofObject, type Schema, sessions } from './schema.ts';
23
+ import { Link } from './link.ts';
24
+ import { apply, dropAll, ensureOf, ensuring, type Schema } from './schema.ts';
24
25
  import { type Send, sendOf } from './calls.ts';
25
26
 
26
27
  export type { DatabaseReader, DatabaseWriter, Row, SqlParam, SqlValue };
@@ -71,12 +72,11 @@ export interface SqlHost {
71
72
  genericSend(send: restate.GenericSend<Uint8Array>): unknown;
72
73
  }
73
74
 
74
- type Wrap = (store: Store) => Store;
75
- let wrapStore: Wrap | undefined;
76
-
77
- /** Wrap each object's store, such as for fault injection in tests. */
78
- export function setStoreWrapper(wrap: Wrap) {
79
- wrapStore = wrap;
75
+ /** What a session object gives its attempts: its schema, and a wrapper of its store (fault injection, in tests). */
76
+ export interface ObjectConfig {
77
+ /** The object's own schema, which each of its databases is made by. */
78
+ readonly schema?: Schema;
79
+ wrapStore?: (store: Store) => Store;
80
80
  }
81
81
 
82
82
  /** The end of an attempt, as `invocationEndPromise` rejects with it, for the requests that would otherwise wait for it. */
@@ -158,22 +158,12 @@ const unbeside = (name: string) => (key: string) => {
158
158
  * stores in order; `sync` is an empty `ctx.run`, acknowledged after the
159
159
  * commands before it. A `get` or `sync` the attempt's end leaves waiting
160
160
  * rejects, so the session that made it ends instead of holding its lock for
161
- * the life of the process.
161
+ * the life of the process. One the SDK cancels fails as any await does: the
162
+ * session it ends fails its calls with the CancelledError (see `open`).
162
163
  */
163
- function objectStore(
164
- ctx: SqlHost,
165
- end: AttemptEnd,
166
- dbName: string | undefined,
167
- cancelled: (error: CancelledError) => void,
168
- ): Store {
164
+ function objectStore(ctx: SqlHost, end: AttemptEnd, dbName: string | undefined): Store {
169
165
  const keyOf = dbName === undefined ? (key: string) => key : beside(dbName);
170
- // The addon gets a request's failure as text: a cancellation is kept here,
171
- // for the call that failed of it to fail with it (see `Attempt.call`).
172
- const request = <T>(promise: PromiseLike<T>) =>
173
- end.race(promise).catch((error: unknown) => {
174
- if (error instanceof CancelledError) cancelled(error);
175
- throw error;
176
- });
166
+ const request = <T>(promise: PromiseLike<T>) => end.race(promise);
177
167
  // TODO: read with protocol v8's ephemeral get, left out of the journal, once
178
168
  // a Restate release ships v8 and the SDK lets a library make one. Restate 1.8
179
169
  // negotiates v7 at most: a journaled get.
@@ -235,12 +225,11 @@ export function asDatabase(connection: Connection): Database {
235
225
  ...sqlOver((sql, params) => connection.queryColumns(sql, params)),
236
226
  transaction: (body) => connection.transaction((tx) => body({ ...forBody(tx), send: refusedSend })),
237
227
  };
238
- sessions.set(db, (schemas) => apply(connection, schemas));
239
- return db;
228
+ return ensuring(db, (schemas) => apply(connection, schemas));
240
229
  }
241
230
 
242
- // The transactions of `ctx.db`, each with how it empties the database (`reset`).
243
- const resets = new WeakMap<Transaction, () => Promise<void>>();
231
+ /** How a transaction of `ctx.db` empties the database ({@link reset}). */
232
+ const RESET = new Link<() => Promise<void>>('reset');
244
233
 
245
234
  /**
246
235
  * Empty the key's database in `tx`, a transaction of an exclusive handler's
@@ -250,7 +239,7 @@ const resets = new WeakMap<Transaction, () => Promise<void>>();
250
239
  * new database's first rows, in the same commit.
251
240
  */
252
241
  export function reset(tx: Transaction): Promise<void> {
253
- const of = resets.get(tx);
242
+ const of = RESET.of(tx);
254
243
  if (of === undefined) throw new TerminalError("reset takes a transaction of an exclusive handler's ctx.db");
255
244
  return forHandler(of());
256
245
  }
@@ -269,14 +258,13 @@ export function lazyDatabase(opener: () => Promise<Database>): Database {
269
258
  execute: async (sql, params) => (await db()).execute(sql, params),
270
259
  transaction: async (body) => (await db()).transaction(body),
271
260
  };
272
- sessions.set(lazy, async (schemas) => {
261
+ return ensuring(lazy, async (schemas) => {
273
262
  const inner = await db();
274
- const ensure = sessions.get(inner);
263
+ const ensure = ensureOf(inner);
275
264
  if (ensure === undefined)
276
265
  throw new TerminalError("lazyDatabase opens a handler's ctx.db, or a database of asDatabase");
277
266
  await ensure(schemas);
278
267
  });
279
- return lazy;
280
268
  }
281
269
 
282
270
  /** The sends of a transaction that has no outbox: a shared handler's, or another database's. */
@@ -286,8 +274,8 @@ const refusedSend: Send = () => {
286
274
 
287
275
  // A transaction's sends commit with it, in the database's record `outbox`
288
276
  // (beside its tables, in none of them), which holds each committed
289
- // transaction's sends until they are stored. They are made once the
290
- // transaction commits; a later open makes again those still in the outbox,
277
+ // transaction's sends until they are stored. They are made with its commit
278
+ // (see `Attempt.transaction`); a later open makes again those still in the outbox,
291
279
  // with the same idempotency keys (`transaction/<id>/<index>`, with a random
292
280
  // id of the transaction), so making them again is dropped. Restate keeps an attempt's commands in the
293
281
  // order they were made, so a send made before a commit is stored whenever the
@@ -334,13 +322,8 @@ function storedSend(send: restate.GenericSend<unknown>): Outgoing['sends'][numbe
334
322
  /** How a handler ended. */
335
323
  type Outcome<T> = { value: T } | { error: unknown };
336
324
 
337
- function settle<T>(outcome: Outcome<T>): T {
338
- if ('error' in outcome) throw outcome.error;
339
- return outcome.value;
340
- }
341
-
342
- // The attempts, by their `ctx.db`: for `database`.
343
- const attempts = new WeakMap<object, Attempt>();
325
+ /** The attempt of a `ctx.db`: for {@link database}. */
326
+ const ATTEMPT = new Link<Attempt>('database');
344
327
 
345
328
  // A database's name (`database`).
346
329
  const DATABASE_NAME = /^[\w.-]{1,64}$/;
@@ -354,182 +337,328 @@ const DATABASE_NAME = /^[\w.-]{1,64}$/;
354
337
  */
355
338
  export function database(db: Database, name: string): Database {
356
339
  if (!DATABASE_NAME.test(name)) throw new TerminalError(`database: ${JSON.stringify(name)} is not a database name`);
357
- const attempt = attempts.get(db);
340
+ const attempt = ATTEMPT.of(db);
358
341
  if (attempt === undefined) throw new TerminalError("database takes a handler's ctx.db");
359
342
  return attempt.database(name);
360
343
  }
361
344
 
345
+ /** The sends of one transaction, as its body makes them (`tx.send`), until it ends. */
346
+ class Sends {
347
+ private readonly sends: Outgoing['sends'] = [];
348
+ private open = true;
349
+ readonly send: Send = sendOf((send) => {
350
+ if (!this.open) throw new TerminalError('the transaction has ended: send from inside its body');
351
+ this.sends.push(storedSend(send));
352
+ });
353
+
354
+ /** The body ended: the transaction's sends, if it made any, their delays counted from now. */
355
+ close(): Outgoing | undefined {
356
+ this.open = false;
357
+ if (this.sends.length === 0) return undefined;
358
+ const now = Date.now();
359
+ for (const send of this.sends) if (send.delay !== undefined) send.due = now + send.delay;
360
+ return { id: randomUUID(), sends: this.sends };
361
+ }
362
+ }
363
+
364
+ /**
365
+ * One session of an attempt's database, from its open on. A failure ends it:
366
+ * its open's, or a request's since. It closes as the attempt ends, unless the
367
+ * attempt ends it first ({@link end}).
368
+ */
369
+ class Session {
370
+ readonly ready: Promise<Connection>;
371
+ /** A call failed on it once a failure ended it: the next call opens another. */
372
+ retired = false;
373
+ private connection: Connection | undefined;
374
+ private failed = false;
375
+ private release: () => void = () => {};
376
+
377
+ constructor(ready: Promise<Connection>, end: AttemptEnd) {
378
+ this.ready = ready;
379
+ void this.track(end);
380
+ }
381
+
382
+ /** Whether a failure ended it. */
383
+ get ended(): boolean {
384
+ return this.failed || this.connection?.isUsable() === false;
385
+ }
386
+
387
+ /** Its connection, or none if the open failed; the attempt's end no longer closes it. */
388
+ async end(): Promise<Connection | undefined> {
389
+ const db = await this.ready.catch(() => undefined);
390
+ this.release();
391
+ return db;
392
+ }
393
+
394
+ /** Close it now. */
395
+ close(): void {
396
+ void this.end()
397
+ .then((db) => db?.close())
398
+ .catch(() => {});
399
+ }
400
+
401
+ private async track(end: AttemptEnd) {
402
+ try {
403
+ const db = await this.ready;
404
+ this.connection = db;
405
+ // A handler still waiting for something else when the attempt ends (a
406
+ // model request, say) keeps the session no longer: it closes once no
407
+ // statement runs, and the handler's later calls fail.
408
+ this.release = end.onEnd(() => void db.close().catch(() => {}));
409
+ } catch {
410
+ this.failed = true;
411
+ }
412
+ }
413
+ }
414
+
362
415
  /**
363
416
  * An attempt's SQL session: opened on its first use, or as an exclusive
364
417
  * attempt starts ({@link openNow}), shared by everything the handler does,
365
- * and saved when the handler ends ({@link end}). With `name`, of the key's database `name`
366
- * ({@link database}), which has neither the object's schema nor an outbox.
418
+ * and saved when the handler ends ({@link end}). With `name`, of the key's
419
+ * database `name` ({@link database}), which has neither the object's schema
420
+ * nor an outbox.
367
421
  */
368
422
  export class Attempt {
369
423
  /** `ctx.db`. */
370
424
  readonly db: Database;
371
425
  private readonly ctx: SqlHost;
426
+ /** Its object's: the key's other databases share its store's wrapper, and have none of its schema. */
427
+ private readonly config: ObjectConfig;
372
428
  private readonly name: string | undefined;
429
+ /** Whether it is the object's own database of an exclusive handler: the one with an outbox. */
430
+ private readonly hasOutbox: boolean;
373
431
  /** The key's other databases this attempt opened, by name. */
374
432
  private readonly databases = new Map<string, Attempt>();
375
433
  /** The session, from its first use on. */
376
- private session: Promise<Connection> | undefined;
434
+ private session: Session | undefined;
377
435
  /** The ids of the outbox's transactions this attempt made the sends of. */
378
436
  private readonly made = new Set<string>();
379
437
  /** The schemas this attempt's database has all the steps of. */
380
438
  private readonly ensured = new Map<string, Schema>();
381
439
  private ended = false;
382
- /** Opened when the attempt started ({@link openNow}), and no call has seen how it went yet. */
383
- private unseenOpen = false;
384
- /** Stops closing the session when the attempt ends. */
385
- private keepOpen: () => void = () => {};
386
- /** The invocation's cancellation, once a request of the session failed of it. */
387
- private cancelled: CancelledError | undefined;
388
-
389
- constructor(ctx: SqlHost, name?: string) {
440
+
441
+ constructor(ctx: SqlHost, config: ObjectConfig = {}, name?: string) {
390
442
  this.ctx = ctx;
443
+ this.config = config;
391
444
  this.name = name;
445
+ this.hasOutbox = !ctx.shared && name === undefined;
392
446
  this.db = {
393
447
  ...sqlOver((sql, params) => this.call((db) => db.queryColumns(sql, params)), handlerError),
394
- // A shared handler's writes stay in its session: it has no outbox.
395
- transaction: <T>(body: (tx: Transaction) => Promise<T>) =>
396
- this.ctx.shared
397
- ? this.call((db) => db.transaction((tx) => body({ ...forBody(tx), send: refusedSend })))
398
- : this.name !== undefined
399
- ? this.call((db) =>
400
- db.transaction((handle) => {
401
- const transaction: Transaction = { ...forBody(handle), send: refusedSend };
402
- resets.set(transaction, () => this.reset(handle));
403
- return body(transaction);
404
- }),
405
- )
406
- : this.withSends((tx, record, handle) => {
407
- const transaction: Transaction = { ...tx, send: sendOf(record) };
408
- resets.set(transaction, () => this.reset(handle));
409
- return body(transaction);
410
- }),
448
+ transaction: (body) => this.transaction(body),
411
449
  };
412
- sessions.set(this.db, (schemas) => {
413
- this.unseenOpen = false;
414
- return this.opened().then((db) => this.ensureSchemas(db, schemas));
415
- });
416
- attempts.set(this.db, this);
450
+ ensuring(this.db, (schemas) => this.call((db) => this.ensureSchemas(db, schemas)));
451
+ ATTEMPT.on(this.db, this);
417
452
  }
418
453
 
419
454
  /** The key's database `name`, in this attempt: see {@link database}. */
420
455
  database(name: string): Database {
421
456
  if (this.ended) throw new Error('the handler has ended: its SQL session is closed');
422
457
  let other = this.databases.get(name);
423
- if (other === undefined) this.databases.set(name, (other = new Attempt(this.ctx, name)));
458
+ if (other === undefined) this.databases.set(name, (other = new Attempt(this.ctx, this.config, name)));
424
459
  return other.db;
425
460
  }
426
461
 
427
462
  /**
428
- * One transaction of the session, whose sends are made once it commits,
429
- * and kept in the outbox until they are stored: `body` gets its SQL, and
430
- * `record`, which records a send.
463
+ * Open the session now, as the attempt starts, rather than on its first
464
+ * call: the open makes the sends a crashed attempt committed and left
465
+ * unmade, which must not wait for a handler that uses the database.
431
466
  */
432
- private async withSends<T>(
433
- body: (
434
- db: DatabaseWriter,
435
- record: (send: restate.GenericSend<unknown>) => void,
436
- handle: ConnectionTransaction,
437
- ) => Promise<T>,
438
- ): Promise<T> {
439
- const sends: Outgoing['sends'] = [];
440
- let recording = true;
441
- const record = (send: restate.GenericSend<unknown>) => {
442
- if (!recording) throw new TerminalError('the transaction has ended: send from inside its body');
443
- sends.push(storedSend(send));
444
- };
467
+ openNow() {
468
+ if (this.hasOutbox && this.session === undefined) this.current().ready.catch(() => {});
469
+ }
470
+
471
+ /**
472
+ * The handler ended with `outcome`: the key's other databases end, then
473
+ * this one ({@link endSession}).
474
+ */
475
+ async end<T>(outcome: Outcome<T>): Promise<T> {
476
+ // The key's other databases end first, as the handler left them.
477
+ const databases = await Promise.allSettled([...this.databases.values()].map((d) => d.end({ value: undefined })));
478
+ const value = await this.endSession(outcome);
479
+ const failed = databases.find((d) => d.status === 'rejected');
480
+ if (failed) throw failed.reason;
481
+ return value;
482
+ }
483
+
484
+ /**
485
+ * `body` as one transaction. In the object's own database of an exclusive
486
+ * handler, its sends commit with it, in the outbox, and are made with its
487
+ * commit, right after its writes and before it waits for anything
488
+ * (`withCommit`): Restate stores an attempt's commands in order, so they
489
+ * are stored only if the commit is, and whatever fails the commit's wait (a
490
+ * cancellation, say) comes after them. A second commit empties the outbox
491
+ * before `transaction` resolves: left until the handler's end, they would
492
+ * be made again by an attempt that resumes a long wait (an approval), past
493
+ * the idempotency retention that drops a repeat.
494
+ */
495
+ private async transaction<T>(body: (tx: Transaction) => Promise<T>): Promise<T> {
445
496
  let outgoing: Outgoing | undefined;
446
497
  const value = await this.call((db) =>
447
498
  db.transaction(async (handle) => {
499
+ const sends = this.hasOutbox ? new Sends() : undefined;
500
+ const tx: Transaction = { ...forBody(handle), send: sends?.send ?? refusedSend };
501
+ // A view's writes stay in its session: it has nothing to reset.
502
+ if (!this.ctx.shared) RESET.on(tx, () => this.reset(handle));
448
503
  let result: T;
449
504
  try {
450
- result = await body(forBody(handle), record, handle);
505
+ result = await body(tx);
451
506
  } finally {
452
- recording = false;
453
- }
454
- // The outbox as committed, but the sends stored since, and this
455
- // transaction's: unchanged, it is not written again.
456
- const outbox = await this.unstored(handle);
457
- if (sends.length > 0) {
458
- // A delay counts from the commit: one made again waits what remains.
459
- const now = Date.now();
460
- for (const send of sends) if (send.delay !== undefined) send.due = now + send.delay;
461
- outgoing = { id: randomUUID(), sends };
462
- outbox.push(outgoing);
507
+ outgoing = sends?.close();
463
508
  }
464
- handle.setRecord(OUTBOX, encodeOutbox(outbox));
509
+ if (this.hasOutbox) await this.commitOutbox(handle, outgoing);
465
510
  return result;
466
511
  }),
467
512
  );
468
- if (outgoing !== undefined) {
469
- this.make(outgoing);
470
- // Emptied at once, by a commit after the sends, which Restate stores
471
- // before it: left in the outbox until the handler's end, they would be
472
- // made again by an attempt that resumes a long wait (an approval), past
473
- // the idempotency retention that drops a repeat.
474
- await this.call((db) => this.flush(db));
475
- }
513
+ if (outgoing !== undefined) await this.call((db) => this.flush(db));
476
514
  return value;
477
515
  }
478
516
 
479
517
  /**
480
- * The handler ended with `outcome`: an SQL error that escaped it becomes
481
- * terminal, then the outbox is emptied, and the session is saved. One that
482
- * a storage error ended closes now, rather than when it is collected.
518
+ * Commit with `handle` the outbox as committed, but the sends stored since,
519
+ * and with `outgoing`, which the commit makes. Unchanged, it is not
520
+ * written again.
483
521
  */
484
- async end<T>(outcome: Outcome<T>): Promise<T> {
485
- // The key's other databases end first, as the handler left them.
486
- const databases = await Promise.allSettled([...this.databases.values()].map((d) => d.end({ value: undefined })));
487
- const value = await this.endSession(outcome);
488
- const failed = databases.find((d) => d.status === 'rejected');
489
- if (failed) throw failed.reason;
490
- return value;
522
+ private async commitOutbox(handle: ConnectionTransaction, outgoing: Outgoing | undefined) {
523
+ const outbox = await this.unstored(handle);
524
+ if (outgoing !== undefined) {
525
+ outbox.push(outgoing);
526
+ handle.withCommit(() => this.make(outgoing));
527
+ }
528
+ handle.setRecord(OUTBOX, encodeOutbox(outbox));
491
529
  }
492
530
 
493
531
  /**
494
- * Open the session now, as the attempt starts, rather than on its first
495
- * call: the open makes the sends a crashed attempt committed and left
496
- * unmade, which must not wait for a handler that uses the database.
532
+ * `call` on the session, opening it on the first; its failure as the
533
+ * handler fails with it. The call that fails on a session that a failure
534
+ * ended is its last: the next opens another, which reads what is stored.
535
+ * So the failure of an open made as the attempt started goes to the first
536
+ * call, as it would had that call opened it.
497
537
  */
498
- openNow() {
499
- if (this.ctx.shared || this.name !== undefined || this.session !== undefined) return;
500
- this.unseenOpen = true;
501
- this.opened().catch(() => {});
538
+ private async call<T>(call: (db: Connection) => Promise<T>): Promise<T> {
539
+ const session = this.current();
540
+ try {
541
+ return await call(await session.ready);
542
+ } catch (error) {
543
+ if (session.ended) session.retired = true;
544
+ throw handlerError(error);
545
+ }
502
546
  }
503
547
 
504
- /** Empty the database in the transaction `handle` ({@link reset}), and apply the schemas this attempt applied again. */
505
- private async reset(handle: ConnectionTransaction) {
506
- // Another database of the key has none of the object's schema.
507
- const own = this.name === undefined ? ofObject(this.ctx.request().target.service) : undefined;
508
- const schemas = [...(own ? [own] : []), ...[...this.ensured.values()].filter((s) => s !== own)];
509
- await dropAll(handle, schemas);
548
+ /** The session, opening one if there is none, or the one there is was retired. */
549
+ private current(): Session {
550
+ if (this.ended) throw new Error('the handler has ended: its SQL session is closed');
551
+ if (this.session?.retired) this.session.close();
552
+ if (this.session === undefined || this.session.retired) this.session = this.open();
553
+ return this.session;
554
+ }
555
+
556
+ private open(): Session {
557
+ const end = new AttemptEnd(this.ctx.invocationEndPromise.promise);
558
+ return new Session(this.start(end), end);
559
+ }
560
+
561
+ private async start(end: AttemptEnd): Promise<Connection> {
562
+ const ctx = this.ctx;
563
+ // The page cache's: the key escaped, so that no key reads as another's
564
+ // database (a name has no `/`).
565
+ const key = `${ctx.request().target.service}/${encodeURIComponent(ctx.key)}`;
566
+ const namespace = this.name === undefined ? key : `${key}/${this.name}`;
567
+ const object = objectStore(ctx, end, this.name);
568
+ const wrap = this.config.wrapStore;
569
+ const db = await open(namespace, wrap ? wrap(object) : object, { reader: ctx.shared });
570
+ try {
571
+ // A view writes nothing: a write fails, rather than vanish with the attempt.
572
+ if (ctx.shared) await db.execute('PRAGMA query_only = 1');
573
+ if (this.hasOutbox) {
574
+ // What a crash left unmade; an open again in this attempt finds what
575
+ // this attempt made, stored before it, as made.
576
+ const left = decodeOutbox(await db.record(OUTBOX));
577
+ for (const outgoing of left) if (!this.made.has(outgoing.id)) this.make(outgoing, true);
578
+ // Emptied at once, as a transaction's own sends are (see `transaction`).
579
+ if (left.length > 0) await this.flush(db);
580
+ }
581
+ // A view's too, whose writes are never stored: a key never written reads as empty tables.
582
+ const own = this.ownSchema();
583
+ if (own) await this.ensureSchemas(db, [own]);
584
+ } catch (error) {
585
+ await db.close();
586
+ throw error;
587
+ }
588
+ return db;
510
589
  }
511
590
 
512
591
  /**
513
- * `call` on the session, opening it on the first; its failure as the
514
- * handler fails with it, or the invocation's cancellation, if a request of
515
- * the session failed of it: a call it ended fails with a CancelledError,
516
- * as any of the handler's awaits does.
592
+ * End the session, then settle as the handler did: an SQL error that
593
+ * escaped it becomes terminal. The handler's error stands: what it
594
+ * committed is stored, and an outbox left full is made by the next open.
595
+ * A failure to end the session fails a handler that succeeded, which a
596
+ * retry then ends (a transaction it left open, say).
517
597
  */
518
- private async call<T>(call: (db: Connection) => Promise<T>): Promise<T> {
519
- this.unseenOpen = false;
598
+ private async endSession<T>(outcome: Outcome<T>): Promise<T> {
599
+ this.ended = true;
600
+ const failed = await this.close().then(
601
+ () => undefined,
602
+ (error: unknown) => ({ error }),
603
+ );
604
+ if ('error' in outcome) throw handlerError(outcome.error);
605
+ if (failed !== undefined) throw handlerError(failed.error);
606
+ return outcome.value;
607
+ }
608
+
609
+ /**
610
+ * Close the session as the attempt ends. A view's closes: it read the
611
+ * snapshot it opened on, and one that outlived 16 commits failed its read
612
+ * ("is gone"), which is retried. Another is saved, its outbox emptied. One
613
+ * that a failure ended closes, and the object's own database is opened
614
+ * again and saved: it may hold sends unmade (a crash left them, and this
615
+ * attempt's open failed) or made and not emptied (the commit's wait
616
+ * failed), and no attempt may follow this one (a cancelled invocation's),
617
+ * nor the key's next invocation come within the idempotency retention.
618
+ */
619
+ private async close(): Promise<void> {
620
+ if (this.session === undefined) return;
621
+ const db = await this.session.end();
622
+ if (this.ctx.shared) return db?.close();
623
+ if (db?.isUsable()) return this.save(db);
624
+ await db?.close().catch(() => {});
625
+ if (!this.hasOutbox) return;
626
+ const again = this.open();
520
627
  try {
521
- const db = await this.opened();
522
- return await forHandler(call(db));
628
+ await this.save(await again.ready);
629
+ } finally {
630
+ void again.end();
631
+ }
632
+ }
633
+
634
+ /** Empty the outbox and save the session, which closes if that fails. */
635
+ private async save(db: Connection) {
636
+ try {
637
+ if (this.hasOutbox) await this.flush(db);
638
+ await db.save();
523
639
  } catch (error) {
524
- throw this.cancelled ?? error;
640
+ await db.close().catch(() => {});
641
+ throw error;
525
642
  }
526
643
  }
527
644
 
645
+ /** The object's schema, which the key's other databases have none of. */
646
+ private ownSchema(): Schema | undefined {
647
+ return this.name === undefined ? this.config.schema : undefined;
648
+ }
649
+
650
+ /** Empty the database in the transaction `handle` ({@link reset}), and apply the schemas this attempt applied again. */
651
+ private async reset(handle: ConnectionTransaction) {
652
+ const own = this.ownSchema();
653
+ const schemas = [...(own ? [own] : []), ...[...this.ensured.values()].filter((s) => s !== own)];
654
+ await dropAll(handle, schemas);
655
+ }
656
+
528
657
  /** Apply the steps of `schemas` that the database lacks, each schema once per attempt. */
529
658
  private async ensureSchemas(db: Connection, schemas: readonly Schema[]) {
530
659
  const lacking = schemas.filter((s) => !this.ensured.has(s.name));
531
660
  if (lacking.length === 0) return;
532
- await forHandler(apply(db, lacking, { reader: this.ctx.shared }));
661
+ await apply(db, lacking, { reader: this.ctx.shared });
533
662
  for (const s of lacking) this.ensured.set(s.name, s);
534
663
  }
535
664
 
@@ -563,92 +692,6 @@ export class Attempt {
563
692
  // the read above keeps them.
564
693
  await db.transaction(async (tx) => tx.setRecord(OUTBOX, encodeOutbox(await this.unstored(tx))));
565
694
  }
566
-
567
- /** The session, opening it on the first call. */
568
- private opened(): Promise<Connection> {
569
- if (this.ended) return Promise.reject(new Error('the handler has ended: its SQL session is closed'));
570
- this.session ??= this.start();
571
- return this.session;
572
- }
573
-
574
- private async start(): Promise<Connection> {
575
- const ctx = this.ctx;
576
- // The page cache's: the key escaped, so that no key reads as another's
577
- // database (a name has no `/`).
578
- const key = `${ctx.request().target.service}/${encodeURIComponent(ctx.key)}`;
579
- const namespace = this.name === undefined ? key : `${key}/${this.name}`;
580
- const end = new AttemptEnd(ctx.invocationEndPromise.promise);
581
- const object = objectStore(ctx, end, this.name, (error) => (this.cancelled ??= error));
582
- const db = await open(namespace, wrapStore ? wrapStore(object) : object, { reader: ctx.shared });
583
- // A handler still waiting for something else when the attempt ends (a
584
- // model request, say) keeps the session no longer: it closes once no
585
- // statement runs, and the handler's later calls fail.
586
- this.keepOpen = end.onEnd(() => void db.close().catch(() => {}));
587
- // The object's schema: in a shared handler's session too, whose writes are never stored, so a
588
- // key never written reads as empty tables.
589
- const own = this.name === undefined ? ofObject(ctx.request().target.service) : undefined;
590
- try {
591
- // A view writes nothing: a write fails, rather than vanish with the attempt.
592
- if (ctx.shared) await db.execute('PRAGMA query_only = 1');
593
- // What a crash may have left unmade.
594
- if (!ctx.shared && this.name === undefined) {
595
- const left = decodeOutbox(await db.record(OUTBOX));
596
- left.forEach((outgoing) => this.make(outgoing, true));
597
- // Emptied at once, as a transaction's own sends are (see `withSends`):
598
- // kept until the handler's end, an attempt that resumes a long wait
599
- // would make them again, past the idempotency retention.
600
- if (left.length > 0) await this.flush(db);
601
- }
602
- if (own) await this.ensureSchemas(db, [own]);
603
- } catch (error) {
604
- const failed = handlerError(error);
605
- await db.close();
606
- throw failed;
607
- }
608
- return db;
609
- }
610
-
611
- private async endSession<T>(outcome: Outcome<T>): Promise<T> {
612
- this.ended = true;
613
- const session = this.session;
614
- if (session === undefined) return settle(outcome);
615
- let db: Connection;
616
- try {
617
- db = await session;
618
- } catch (error) {
619
- // The open failed, and its error went to the call that made it; one
620
- // made as the attempt started that no call saw fails the attempt, as
621
- // its outbox is still to be made.
622
- if (this.unseenOpen) throw error;
623
- return settle(outcome);
624
- }
625
- this.keepOpen();
626
- if (this.ctx.shared) {
627
- // It read the snapshot it opened on, whatever committed since; one that
628
- // outlived 16 commits failed its read ("is gone"), and is retried.
629
- const failed = 'error' in outcome ? handlerError(outcome.error) : undefined;
630
- await db.close();
631
- if ('error' in outcome) throw failed;
632
- return outcome.value;
633
- }
634
- if ('error' in outcome) {
635
- const error = handlerError(outcome.error);
636
- // The handler's error stands: what it committed is stored, and an
637
- // outbox left full is made again by the next open.
638
- await this.save(db).catch(() => db.close().catch(() => {}));
639
- throw error;
640
- }
641
- // A transaction left open, say, which a retry would leave open again.
642
- await forHandler(this.save(db));
643
- return outcome.value;
644
- }
645
-
646
- /** Empty the outbox and save the session; one a storage error ended only closes. */
647
- private async save(db: Connection) {
648
- if (!db.isUsable()) return db.close();
649
- await this.flush(db);
650
- await db.save();
651
- }
652
695
  }
653
696
 
654
697
  /** Run `handler`, then end `attempt`'s SQL session, if it opened one (see {@link Attempt.end}). */