@restatedev/sessions 0.2.0 → 0.4.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.
- package/README.md +47 -8
- package/dist/database.d.ts +41 -2
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +99 -20
- package/dist/database.js.map +1 -1
- package/dist/internal.d.ts +5 -3
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +4 -2
- package/dist/internal.js.map +1 -1
- package/dist/link.d.ts +10 -0
- package/dist/link.d.ts.map +1 -0
- package/dist/link.js +19 -0
- package/dist/link.js.map +1 -0
- package/dist/object.d.ts +17 -4
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +61 -46
- package/dist/object.js.map +1 -1
- package/dist/schema.d.ts +7 -6
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +9 -10
- package/dist/schema.js.map +1 -1
- package/dist/scope.d.ts +38 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +55 -0
- package/dist/scope.js.map +1 -0
- package/dist/session.d.ts +70 -34
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +273 -221
- package/dist/session.js.map +1 -1
- package/package.json +5 -5
- package/src/database.ts +111 -22
- package/src/internal.ts +15 -3
- package/src/link.ts +22 -0
- package/src/object.ts +94 -63
- package/src/schema.ts +11 -10
- package/src/scope.ts +78 -0
- 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 {
|
|
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 {
|
|
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
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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
|
-
|
|
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
|
-
|
|
239
|
-
return db;
|
|
228
|
+
return ensuring(db, (schemas) => apply(connection, schemas));
|
|
240
229
|
}
|
|
241
230
|
|
|
242
|
-
|
|
243
|
-
const
|
|
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 =
|
|
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
|
-
|
|
261
|
+
return ensuring(lazy, async (schemas) => {
|
|
273
262
|
const inner = await db();
|
|
274
|
-
const ensure =
|
|
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
|
|
290
|
-
// transaction
|
|
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
|
-
|
|
338
|
-
|
|
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 =
|
|
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
|
|
366
|
-
* ({@link database}), which has neither the object's schema
|
|
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:
|
|
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
|
-
|
|
383
|
-
|
|
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
|
-
|
|
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
|
-
|
|
413
|
-
|
|
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
|
-
*
|
|
429
|
-
*
|
|
430
|
-
*
|
|
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
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
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(
|
|
505
|
+
result = await body(tx);
|
|
451
506
|
} finally {
|
|
452
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
481
|
-
*
|
|
482
|
-
*
|
|
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
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
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
|
-
*
|
|
495
|
-
*
|
|
496
|
-
*
|
|
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
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
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
|
-
/**
|
|
505
|
-
private
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
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
|
-
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
516
|
-
*
|
|
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
|
|
519
|
-
this.
|
|
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
|
-
|
|
522
|
-
|
|
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
|
-
|
|
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
|
|
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}). */
|