@restatedev/sessions 0.2.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.
- 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 +4 -4
- 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/dist/session.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,OAAO,MAAM,yBAAyB,CAAC;AAExD,OAAO,EAA4B,KAAK,KAAK,EAAE,MAAM,8BAA8B,CAAC;AACpF,OAAO,EAEL,KAAK,GAAG,EAGR,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,KA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AC,KAAK,CAAS;IAEtB,YAAY,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,YAAiB,EAAE,IAAI,CAAC,EAAE,MAAM,EAWjE;IAED,wEAAwE;IACxE,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAK/B;IAED;;;;OAIG;IACH,OAAO,SAEN;IAED;;;OAGG;IACG,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAO5C;IAED;;;;;;;;;;OAUG;YACW,WAAW;IAsBzB;;;;OAIG;YACW,YAAY;IAS1B;;;;;;OAMG;YACW,IAAI;IAUlB,kFAAkF;IAClF,OAAO,CAAC,OAAO;IAOf,OAAO,CAAC,IAAI;YAKE,KAAK;IA8BnB;;;;;;OAMG;YACW,UAAU;IAWxB;;;;;;;;;OASG;YACW,KAAK;IAenB,yEAAyE;YAC3D,IAAI;IAUlB,yEAAyE;IACzE,OAAO,CAAC,SAAS;IAIjB,wHAAwH;YAC1G,KAAK;IAMnB,0FAA0F;YAC5E,aAAa;IAO3B,qJAAqJ;IACrJ,OAAO,CAAC,IAAI;IAcZ,gIAAgI;YAClH,QAAQ;IAItB;;;OAGG;YACW,KAAK;CAMpB;AAED,mGAAmG;AACnG,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,CAQ5F"}
|
package/dist/session.js
CHANGED
|
@@ -4,16 +4,12 @@
|
|
|
4
4
|
// each commits with (`tx.send`).
|
|
5
5
|
import { Buffer } from 'node:buffer';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
|
-
import {
|
|
7
|
+
import { serde, TerminalError } from '@restatedev/restate-sdk';
|
|
8
8
|
import { millisOrDurationToMillis } from '@restatedev/restate-sdk-core';
|
|
9
9
|
import { open, sqlOver, SqlError, } from './database.js';
|
|
10
|
-
import {
|
|
10
|
+
import { Link } from './link.js';
|
|
11
|
+
import { apply, dropAll, ensureOf, ensuring } from './schema.js';
|
|
11
12
|
import { sendOf } from './calls.js';
|
|
12
|
-
let wrapStore;
|
|
13
|
-
/** Wrap each object's store, such as for fault injection in tests. */
|
|
14
|
-
export function setStoreWrapper(wrap) {
|
|
15
|
-
wrapStore = wrap;
|
|
16
|
-
}
|
|
17
13
|
/** The end of an attempt, as `invocationEndPromise` rejects with it, for the requests that would otherwise wait for it. */
|
|
18
14
|
class AttemptEnd {
|
|
19
15
|
ended;
|
|
@@ -88,17 +84,12 @@ const unbeside = (name) => (key) => {
|
|
|
88
84
|
* stores in order; `sync` is an empty `ctx.run`, acknowledged after the
|
|
89
85
|
* commands before it. A `get` or `sync` the attempt's end leaves waiting
|
|
90
86
|
* rejects, so the session that made it ends instead of holding its lock for
|
|
91
|
-
* the life of the process.
|
|
87
|
+
* the life of the process. One the SDK cancels fails as any await does: the
|
|
88
|
+
* session it ends fails its calls with the CancelledError (see `open`).
|
|
92
89
|
*/
|
|
93
|
-
function objectStore(ctx, end, dbName
|
|
90
|
+
function objectStore(ctx, end, dbName) {
|
|
94
91
|
const keyOf = dbName === undefined ? (key) => key : beside(dbName);
|
|
95
|
-
|
|
96
|
-
// for the call that failed of it to fail with it (see `Attempt.call`).
|
|
97
|
-
const request = (promise) => end.race(promise).catch((error) => {
|
|
98
|
-
if (error instanceof CancelledError)
|
|
99
|
-
cancelled(error);
|
|
100
|
-
throw error;
|
|
101
|
-
});
|
|
92
|
+
const request = (promise) => end.race(promise);
|
|
102
93
|
// TODO: read with protocol v8's ephemeral get, left out of the journal, once
|
|
103
94
|
// a Restate release ships v8 and the SDK lets a library make one. Restate 1.8
|
|
104
95
|
// negotiates v7 at most: a journaled get.
|
|
@@ -160,11 +151,10 @@ export function asDatabase(connection) {
|
|
|
160
151
|
...sqlOver((sql, params) => connection.queryColumns(sql, params)),
|
|
161
152
|
transaction: (body) => connection.transaction((tx) => body({ ...forBody(tx), send: refusedSend })),
|
|
162
153
|
};
|
|
163
|
-
|
|
164
|
-
return db;
|
|
154
|
+
return ensuring(db, (schemas) => apply(connection, schemas));
|
|
165
155
|
}
|
|
166
|
-
|
|
167
|
-
const
|
|
156
|
+
/** How a transaction of `ctx.db` empties the database ({@link reset}). */
|
|
157
|
+
const RESET = new Link('reset');
|
|
168
158
|
/**
|
|
169
159
|
* Empty the key's database in `tx`, a transaction of an exclusive handler's
|
|
170
160
|
* `ctx.db`: every table, view, index and trigger is dropped, the schemas are
|
|
@@ -173,7 +163,7 @@ const resets = new WeakMap();
|
|
|
173
163
|
* new database's first rows, in the same commit.
|
|
174
164
|
*/
|
|
175
165
|
export function reset(tx) {
|
|
176
|
-
const of =
|
|
166
|
+
const of = RESET.of(tx);
|
|
177
167
|
if (of === undefined)
|
|
178
168
|
throw new TerminalError("reset takes a transaction of an exclusive handler's ctx.db");
|
|
179
169
|
return forHandler(of());
|
|
@@ -192,14 +182,13 @@ export function lazyDatabase(opener) {
|
|
|
192
182
|
execute: async (sql, params) => (await db()).execute(sql, params),
|
|
193
183
|
transaction: async (body) => (await db()).transaction(body),
|
|
194
184
|
};
|
|
195
|
-
|
|
185
|
+
return ensuring(lazy, async (schemas) => {
|
|
196
186
|
const inner = await db();
|
|
197
|
-
const ensure =
|
|
187
|
+
const ensure = ensureOf(inner);
|
|
198
188
|
if (ensure === undefined)
|
|
199
189
|
throw new TerminalError("lazyDatabase opens a handler's ctx.db, or a database of asDatabase");
|
|
200
190
|
await ensure(schemas);
|
|
201
191
|
});
|
|
202
|
-
return lazy;
|
|
203
192
|
}
|
|
204
193
|
/** The sends of a transaction that has no outbox: a shared handler's, or another database's. */
|
|
205
194
|
const refusedSend = () => {
|
|
@@ -222,13 +211,8 @@ function storedSend(send) {
|
|
|
222
211
|
parameter: Buffer.from((inputSerde ?? serde.binary).serialize(parameter)).toString('base64'),
|
|
223
212
|
};
|
|
224
213
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
throw outcome.error;
|
|
228
|
-
return outcome.value;
|
|
229
|
-
}
|
|
230
|
-
// The attempts, by their `ctx.db`: for `database`.
|
|
231
|
-
const attempts = new WeakMap();
|
|
214
|
+
/** The attempt of a `ctx.db`: for {@link database}. */
|
|
215
|
+
const ATTEMPT = new Link('database');
|
|
232
216
|
// A database's name (`database`).
|
|
233
217
|
const DATABASE_NAME = /^[\w.-]{1,64}$/;
|
|
234
218
|
/**
|
|
@@ -241,22 +225,94 @@ const DATABASE_NAME = /^[\w.-]{1,64}$/;
|
|
|
241
225
|
export function database(db, name) {
|
|
242
226
|
if (!DATABASE_NAME.test(name))
|
|
243
227
|
throw new TerminalError(`database: ${JSON.stringify(name)} is not a database name`);
|
|
244
|
-
const attempt =
|
|
228
|
+
const attempt = ATTEMPT.of(db);
|
|
245
229
|
if (attempt === undefined)
|
|
246
230
|
throw new TerminalError("database takes a handler's ctx.db");
|
|
247
231
|
return attempt.database(name);
|
|
248
232
|
}
|
|
233
|
+
/** The sends of one transaction, as its body makes them (`tx.send`), until it ends. */
|
|
234
|
+
class Sends {
|
|
235
|
+
sends = [];
|
|
236
|
+
open = true;
|
|
237
|
+
send = sendOf((send) => {
|
|
238
|
+
if (!this.open)
|
|
239
|
+
throw new TerminalError('the transaction has ended: send from inside its body');
|
|
240
|
+
this.sends.push(storedSend(send));
|
|
241
|
+
});
|
|
242
|
+
/** The body ended: the transaction's sends, if it made any, their delays counted from now. */
|
|
243
|
+
close() {
|
|
244
|
+
this.open = false;
|
|
245
|
+
if (this.sends.length === 0)
|
|
246
|
+
return undefined;
|
|
247
|
+
const now = Date.now();
|
|
248
|
+
for (const send of this.sends)
|
|
249
|
+
if (send.delay !== undefined)
|
|
250
|
+
send.due = now + send.delay;
|
|
251
|
+
return { id: randomUUID(), sends: this.sends };
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* One session of an attempt's database, from its open on. A failure ends it:
|
|
256
|
+
* its open's, or a request's since. It closes as the attempt ends, unless the
|
|
257
|
+
* attempt ends it first ({@link end}).
|
|
258
|
+
*/
|
|
259
|
+
class Session {
|
|
260
|
+
ready;
|
|
261
|
+
/** A call failed on it once a failure ended it: the next call opens another. */
|
|
262
|
+
retired = false;
|
|
263
|
+
connection;
|
|
264
|
+
failed = false;
|
|
265
|
+
release = () => { };
|
|
266
|
+
constructor(ready, end) {
|
|
267
|
+
this.ready = ready;
|
|
268
|
+
void this.track(end);
|
|
269
|
+
}
|
|
270
|
+
/** Whether a failure ended it. */
|
|
271
|
+
get ended() {
|
|
272
|
+
return this.failed || this.connection?.isUsable() === false;
|
|
273
|
+
}
|
|
274
|
+
/** Its connection, or none if the open failed; the attempt's end no longer closes it. */
|
|
275
|
+
async end() {
|
|
276
|
+
const db = await this.ready.catch(() => undefined);
|
|
277
|
+
this.release();
|
|
278
|
+
return db;
|
|
279
|
+
}
|
|
280
|
+
/** Close it now. */
|
|
281
|
+
close() {
|
|
282
|
+
void this.end()
|
|
283
|
+
.then((db) => db?.close())
|
|
284
|
+
.catch(() => { });
|
|
285
|
+
}
|
|
286
|
+
async track(end) {
|
|
287
|
+
try {
|
|
288
|
+
const db = await this.ready;
|
|
289
|
+
this.connection = db;
|
|
290
|
+
// A handler still waiting for something else when the attempt ends (a
|
|
291
|
+
// model request, say) keeps the session no longer: it closes once no
|
|
292
|
+
// statement runs, and the handler's later calls fail.
|
|
293
|
+
this.release = end.onEnd(() => void db.close().catch(() => { }));
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
this.failed = true;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
249
300
|
/**
|
|
250
301
|
* An attempt's SQL session: opened on its first use, or as an exclusive
|
|
251
302
|
* attempt starts ({@link openNow}), shared by everything the handler does,
|
|
252
|
-
* and saved when the handler ends ({@link end}). With `name`, of the key's
|
|
253
|
-
* ({@link database}), which has neither the object's schema
|
|
303
|
+
* and saved when the handler ends ({@link end}). With `name`, of the key's
|
|
304
|
+
* database `name` ({@link database}), which has neither the object's schema
|
|
305
|
+
* nor an outbox.
|
|
254
306
|
*/
|
|
255
307
|
export class Attempt {
|
|
256
308
|
/** `ctx.db`. */
|
|
257
309
|
db;
|
|
258
310
|
ctx;
|
|
311
|
+
/** Its object's: the key's other databases share its store's wrapper, and have none of its schema. */
|
|
312
|
+
config;
|
|
259
313
|
name;
|
|
314
|
+
/** Whether it is the object's own database of an exclusive handler: the one with an outbox. */
|
|
315
|
+
hasOutbox;
|
|
260
316
|
/** The key's other databases this attempt opened, by name. */
|
|
261
317
|
databases = new Map();
|
|
262
318
|
/** The session, from its first use on. */
|
|
@@ -266,37 +322,17 @@ export class Attempt {
|
|
|
266
322
|
/** The schemas this attempt's database has all the steps of. */
|
|
267
323
|
ensured = new Map();
|
|
268
324
|
ended = false;
|
|
269
|
-
|
|
270
|
-
unseenOpen = false;
|
|
271
|
-
/** Stops closing the session when the attempt ends. */
|
|
272
|
-
keepOpen = () => { };
|
|
273
|
-
/** The invocation's cancellation, once a request of the session failed of it. */
|
|
274
|
-
cancelled;
|
|
275
|
-
constructor(ctx, name) {
|
|
325
|
+
constructor(ctx, config = {}, name) {
|
|
276
326
|
this.ctx = ctx;
|
|
327
|
+
this.config = config;
|
|
277
328
|
this.name = name;
|
|
329
|
+
this.hasOutbox = !ctx.shared && name === undefined;
|
|
278
330
|
this.db = {
|
|
279
331
|
...sqlOver((sql, params) => this.call((db) => db.queryColumns(sql, params)), handlerError),
|
|
280
|
-
|
|
281
|
-
transaction: (body) => this.ctx.shared
|
|
282
|
-
? this.call((db) => db.transaction((tx) => body({ ...forBody(tx), send: refusedSend })))
|
|
283
|
-
: this.name !== undefined
|
|
284
|
-
? this.call((db) => db.transaction((handle) => {
|
|
285
|
-
const transaction = { ...forBody(handle), send: refusedSend };
|
|
286
|
-
resets.set(transaction, () => this.reset(handle));
|
|
287
|
-
return body(transaction);
|
|
288
|
-
}))
|
|
289
|
-
: this.withSends((tx, record, handle) => {
|
|
290
|
-
const transaction = { ...tx, send: sendOf(record) };
|
|
291
|
-
resets.set(transaction, () => this.reset(handle));
|
|
292
|
-
return body(transaction);
|
|
293
|
-
}),
|
|
332
|
+
transaction: (body) => this.transaction(body),
|
|
294
333
|
};
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
return this.opened().then((db) => this.ensureSchemas(db, schemas));
|
|
298
|
-
});
|
|
299
|
-
attempts.set(this.db, this);
|
|
334
|
+
ensuring(this.db, (schemas) => this.call((db) => this.ensureSchemas(db, schemas)));
|
|
335
|
+
ATTEMPT.on(this.db, this);
|
|
300
336
|
}
|
|
301
337
|
/** The key's database `name`, in this attempt: see {@link database}. */
|
|
302
338
|
database(name) {
|
|
@@ -304,110 +340,218 @@ export class Attempt {
|
|
|
304
340
|
throw new Error('the handler has ended: its SQL session is closed');
|
|
305
341
|
let other = this.databases.get(name);
|
|
306
342
|
if (other === undefined)
|
|
307
|
-
this.databases.set(name, (other = new Attempt(this.ctx, name)));
|
|
343
|
+
this.databases.set(name, (other = new Attempt(this.ctx, this.config, name)));
|
|
308
344
|
return other.db;
|
|
309
345
|
}
|
|
310
346
|
/**
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
*
|
|
347
|
+
* Open the session now, as the attempt starts, rather than on its first
|
|
348
|
+
* call: the open makes the sends a crashed attempt committed and left
|
|
349
|
+
* unmade, which must not wait for a handler that uses the database.
|
|
314
350
|
*/
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
351
|
+
openNow() {
|
|
352
|
+
if (this.hasOutbox && this.session === undefined)
|
|
353
|
+
this.current().ready.catch(() => { });
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* The handler ended with `outcome`: the key's other databases end, then
|
|
357
|
+
* this one ({@link endSession}).
|
|
358
|
+
*/
|
|
359
|
+
async end(outcome) {
|
|
360
|
+
// The key's other databases end first, as the handler left them.
|
|
361
|
+
const databases = await Promise.allSettled([...this.databases.values()].map((d) => d.end({ value: undefined })));
|
|
362
|
+
const value = await this.endSession(outcome);
|
|
363
|
+
const failed = databases.find((d) => d.status === 'rejected');
|
|
364
|
+
if (failed)
|
|
365
|
+
throw failed.reason;
|
|
366
|
+
return value;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* `body` as one transaction. In the object's own database of an exclusive
|
|
370
|
+
* handler, its sends commit with it, in the outbox, and are made with its
|
|
371
|
+
* commit, right after its writes and before it waits for anything
|
|
372
|
+
* (`withCommit`): Restate stores an attempt's commands in order, so they
|
|
373
|
+
* are stored only if the commit is, and whatever fails the commit's wait (a
|
|
374
|
+
* cancellation, say) comes after them. A second commit empties the outbox
|
|
375
|
+
* before `transaction` resolves: left until the handler's end, they would
|
|
376
|
+
* be made again by an attempt that resumes a long wait (an approval), past
|
|
377
|
+
* the idempotency retention that drops a repeat.
|
|
378
|
+
*/
|
|
379
|
+
async transaction(body) {
|
|
323
380
|
let outgoing;
|
|
324
381
|
const value = await this.call((db) => db.transaction(async (handle) => {
|
|
382
|
+
const sends = this.hasOutbox ? new Sends() : undefined;
|
|
383
|
+
const tx = { ...forBody(handle), send: sends?.send ?? refusedSend };
|
|
384
|
+
// A view's writes stay in its session: it has nothing to reset.
|
|
385
|
+
if (!this.ctx.shared)
|
|
386
|
+
RESET.on(tx, () => this.reset(handle));
|
|
325
387
|
let result;
|
|
326
388
|
try {
|
|
327
|
-
result = await body(
|
|
389
|
+
result = await body(tx);
|
|
328
390
|
}
|
|
329
391
|
finally {
|
|
330
|
-
|
|
392
|
+
outgoing = sends?.close();
|
|
331
393
|
}
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
const outbox = await this.unstored(handle);
|
|
335
|
-
if (sends.length > 0) {
|
|
336
|
-
// A delay counts from the commit: one made again waits what remains.
|
|
337
|
-
const now = Date.now();
|
|
338
|
-
for (const send of sends)
|
|
339
|
-
if (send.delay !== undefined)
|
|
340
|
-
send.due = now + send.delay;
|
|
341
|
-
outgoing = { id: randomUUID(), sends };
|
|
342
|
-
outbox.push(outgoing);
|
|
343
|
-
}
|
|
344
|
-
handle.setRecord(OUTBOX, encodeOutbox(outbox));
|
|
394
|
+
if (this.hasOutbox)
|
|
395
|
+
await this.commitOutbox(handle, outgoing);
|
|
345
396
|
return result;
|
|
346
397
|
}));
|
|
347
|
-
if (outgoing !== undefined)
|
|
348
|
-
this.make(outgoing);
|
|
349
|
-
// Emptied at once, by a commit after the sends, which Restate stores
|
|
350
|
-
// before it: left in the outbox until the handler's end, they would be
|
|
351
|
-
// made again by an attempt that resumes a long wait (an approval), past
|
|
352
|
-
// the idempotency retention that drops a repeat.
|
|
398
|
+
if (outgoing !== undefined)
|
|
353
399
|
await this.call((db) => this.flush(db));
|
|
354
|
-
}
|
|
355
400
|
return value;
|
|
356
401
|
}
|
|
357
402
|
/**
|
|
358
|
-
*
|
|
359
|
-
*
|
|
360
|
-
*
|
|
403
|
+
* Commit with `handle` the outbox as committed, but the sends stored since,
|
|
404
|
+
* and with `outgoing`, which the commit makes. Unchanged, it is not
|
|
405
|
+
* written again.
|
|
361
406
|
*/
|
|
362
|
-
async
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
return value;
|
|
407
|
+
async commitOutbox(handle, outgoing) {
|
|
408
|
+
const outbox = await this.unstored(handle);
|
|
409
|
+
if (outgoing !== undefined) {
|
|
410
|
+
outbox.push(outgoing);
|
|
411
|
+
handle.withCommit(() => this.make(outgoing));
|
|
412
|
+
}
|
|
413
|
+
handle.setRecord(OUTBOX, encodeOutbox(outbox));
|
|
370
414
|
}
|
|
371
415
|
/**
|
|
372
|
-
*
|
|
373
|
-
*
|
|
374
|
-
*
|
|
416
|
+
* `call` on the session, opening it on the first; its failure as the
|
|
417
|
+
* handler fails with it. The call that fails on a session that a failure
|
|
418
|
+
* ended is its last: the next opens another, which reads what is stored.
|
|
419
|
+
* So the failure of an open made as the attempt started goes to the first
|
|
420
|
+
* call, as it would had that call opened it.
|
|
375
421
|
*/
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
422
|
+
async call(call) {
|
|
423
|
+
const session = this.current();
|
|
424
|
+
try {
|
|
425
|
+
return await call(await session.ready);
|
|
426
|
+
}
|
|
427
|
+
catch (error) {
|
|
428
|
+
if (session.ended)
|
|
429
|
+
session.retired = true;
|
|
430
|
+
throw handlerError(error);
|
|
431
|
+
}
|
|
381
432
|
}
|
|
382
|
-
/**
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
433
|
+
/** The session, opening one if there is none, or the one there is was retired. */
|
|
434
|
+
current() {
|
|
435
|
+
if (this.ended)
|
|
436
|
+
throw new Error('the handler has ended: its SQL session is closed');
|
|
437
|
+
if (this.session?.retired)
|
|
438
|
+
this.session.close();
|
|
439
|
+
if (this.session === undefined || this.session.retired)
|
|
440
|
+
this.session = this.open();
|
|
441
|
+
return this.session;
|
|
442
|
+
}
|
|
443
|
+
open() {
|
|
444
|
+
const end = new AttemptEnd(this.ctx.invocationEndPromise.promise);
|
|
445
|
+
return new Session(this.start(end), end);
|
|
446
|
+
}
|
|
447
|
+
async start(end) {
|
|
448
|
+
const ctx = this.ctx;
|
|
449
|
+
// The page cache's: the key escaped, so that no key reads as another's
|
|
450
|
+
// database (a name has no `/`).
|
|
451
|
+
const key = `${ctx.request().target.service}/${encodeURIComponent(ctx.key)}`;
|
|
452
|
+
const namespace = this.name === undefined ? key : `${key}/${this.name}`;
|
|
453
|
+
const object = objectStore(ctx, end, this.name);
|
|
454
|
+
const wrap = this.config.wrapStore;
|
|
455
|
+
const db = await open(namespace, wrap ? wrap(object) : object, { reader: ctx.shared });
|
|
456
|
+
try {
|
|
457
|
+
// A view writes nothing: a write fails, rather than vanish with the attempt.
|
|
458
|
+
if (ctx.shared)
|
|
459
|
+
await db.execute('PRAGMA query_only = 1');
|
|
460
|
+
if (this.hasOutbox) {
|
|
461
|
+
// What a crash left unmade; an open again in this attempt finds what
|
|
462
|
+
// this attempt made, stored before it, as made.
|
|
463
|
+
const left = decodeOutbox(await db.record(OUTBOX));
|
|
464
|
+
for (const outgoing of left)
|
|
465
|
+
if (!this.made.has(outgoing.id))
|
|
466
|
+
this.make(outgoing, true);
|
|
467
|
+
// Emptied at once, as a transaction's own sends are (see `transaction`).
|
|
468
|
+
if (left.length > 0)
|
|
469
|
+
await this.flush(db);
|
|
470
|
+
}
|
|
471
|
+
// A view's too, whose writes are never stored: a key never written reads as empty tables.
|
|
472
|
+
const own = this.ownSchema();
|
|
473
|
+
if (own)
|
|
474
|
+
await this.ensureSchemas(db, [own]);
|
|
475
|
+
}
|
|
476
|
+
catch (error) {
|
|
477
|
+
await db.close();
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
return db;
|
|
388
481
|
}
|
|
389
482
|
/**
|
|
390
|
-
*
|
|
391
|
-
*
|
|
392
|
-
*
|
|
393
|
-
*
|
|
483
|
+
* End the session, then settle as the handler did: an SQL error that
|
|
484
|
+
* escaped it becomes terminal. The handler's error stands: what it
|
|
485
|
+
* committed is stored, and an outbox left full is made by the next open.
|
|
486
|
+
* A failure to end the session fails a handler that succeeded, which a
|
|
487
|
+
* retry then ends (a transaction it left open, say).
|
|
394
488
|
*/
|
|
395
|
-
async
|
|
396
|
-
this.
|
|
489
|
+
async endSession(outcome) {
|
|
490
|
+
this.ended = true;
|
|
491
|
+
const failed = await this.close().then(() => undefined, (error) => ({ error }));
|
|
492
|
+
if ('error' in outcome)
|
|
493
|
+
throw handlerError(outcome.error);
|
|
494
|
+
if (failed !== undefined)
|
|
495
|
+
throw handlerError(failed.error);
|
|
496
|
+
return outcome.value;
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Close the session as the attempt ends. A view's closes: it read the
|
|
500
|
+
* snapshot it opened on, and one that outlived 16 commits failed its read
|
|
501
|
+
* ("is gone"), which is retried. Another is saved, its outbox emptied. One
|
|
502
|
+
* that a failure ended closes, and the object's own database is opened
|
|
503
|
+
* again and saved: it may hold sends unmade (a crash left them, and this
|
|
504
|
+
* attempt's open failed) or made and not emptied (the commit's wait
|
|
505
|
+
* failed), and no attempt may follow this one (a cancelled invocation's),
|
|
506
|
+
* nor the key's next invocation come within the idempotency retention.
|
|
507
|
+
*/
|
|
508
|
+
async close() {
|
|
509
|
+
if (this.session === undefined)
|
|
510
|
+
return;
|
|
511
|
+
const db = await this.session.end();
|
|
512
|
+
if (this.ctx.shared)
|
|
513
|
+
return db?.close();
|
|
514
|
+
if (db?.isUsable())
|
|
515
|
+
return this.save(db);
|
|
516
|
+
await db?.close().catch(() => { });
|
|
517
|
+
if (!this.hasOutbox)
|
|
518
|
+
return;
|
|
519
|
+
const again = this.open();
|
|
397
520
|
try {
|
|
398
|
-
|
|
399
|
-
|
|
521
|
+
await this.save(await again.ready);
|
|
522
|
+
}
|
|
523
|
+
finally {
|
|
524
|
+
void again.end();
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
/** Empty the outbox and save the session, which closes if that fails. */
|
|
528
|
+
async save(db) {
|
|
529
|
+
try {
|
|
530
|
+
if (this.hasOutbox)
|
|
531
|
+
await this.flush(db);
|
|
532
|
+
await db.save();
|
|
400
533
|
}
|
|
401
534
|
catch (error) {
|
|
402
|
-
|
|
535
|
+
await db.close().catch(() => { });
|
|
536
|
+
throw error;
|
|
403
537
|
}
|
|
404
538
|
}
|
|
539
|
+
/** The object's schema, which the key's other databases have none of. */
|
|
540
|
+
ownSchema() {
|
|
541
|
+
return this.name === undefined ? this.config.schema : undefined;
|
|
542
|
+
}
|
|
543
|
+
/** Empty the database in the transaction `handle` ({@link reset}), and apply the schemas this attempt applied again. */
|
|
544
|
+
async reset(handle) {
|
|
545
|
+
const own = this.ownSchema();
|
|
546
|
+
const schemas = [...(own ? [own] : []), ...[...this.ensured.values()].filter((s) => s !== own)];
|
|
547
|
+
await dropAll(handle, schemas);
|
|
548
|
+
}
|
|
405
549
|
/** Apply the steps of `schemas` that the database lacks, each schema once per attempt. */
|
|
406
550
|
async ensureSchemas(db, schemas) {
|
|
407
551
|
const lacking = schemas.filter((s) => !this.ensured.has(s.name));
|
|
408
552
|
if (lacking.length === 0)
|
|
409
553
|
return;
|
|
410
|
-
await
|
|
554
|
+
await apply(db, lacking, { reader: this.ctx.shared });
|
|
411
555
|
for (const s of lacking)
|
|
412
556
|
this.ensured.set(s.name, s);
|
|
413
557
|
}
|
|
@@ -440,98 +584,6 @@ export class Attempt {
|
|
|
440
584
|
// the read above keeps them.
|
|
441
585
|
await db.transaction(async (tx) => tx.setRecord(OUTBOX, encodeOutbox(await this.unstored(tx))));
|
|
442
586
|
}
|
|
443
|
-
/** The session, opening it on the first call. */
|
|
444
|
-
opened() {
|
|
445
|
-
if (this.ended)
|
|
446
|
-
return Promise.reject(new Error('the handler has ended: its SQL session is closed'));
|
|
447
|
-
this.session ??= this.start();
|
|
448
|
-
return this.session;
|
|
449
|
-
}
|
|
450
|
-
async start() {
|
|
451
|
-
const ctx = this.ctx;
|
|
452
|
-
// The page cache's: the key escaped, so that no key reads as another's
|
|
453
|
-
// database (a name has no `/`).
|
|
454
|
-
const key = `${ctx.request().target.service}/${encodeURIComponent(ctx.key)}`;
|
|
455
|
-
const namespace = this.name === undefined ? key : `${key}/${this.name}`;
|
|
456
|
-
const end = new AttemptEnd(ctx.invocationEndPromise.promise);
|
|
457
|
-
const object = objectStore(ctx, end, this.name, (error) => (this.cancelled ??= error));
|
|
458
|
-
const db = await open(namespace, wrapStore ? wrapStore(object) : object, { reader: ctx.shared });
|
|
459
|
-
// A handler still waiting for something else when the attempt ends (a
|
|
460
|
-
// model request, say) keeps the session no longer: it closes once no
|
|
461
|
-
// statement runs, and the handler's later calls fail.
|
|
462
|
-
this.keepOpen = end.onEnd(() => void db.close().catch(() => { }));
|
|
463
|
-
// The object's schema: in a shared handler's session too, whose writes are never stored, so a
|
|
464
|
-
// key never written reads as empty tables.
|
|
465
|
-
const own = this.name === undefined ? ofObject(ctx.request().target.service) : undefined;
|
|
466
|
-
try {
|
|
467
|
-
// A view writes nothing: a write fails, rather than vanish with the attempt.
|
|
468
|
-
if (ctx.shared)
|
|
469
|
-
await db.execute('PRAGMA query_only = 1');
|
|
470
|
-
// What a crash may have left unmade.
|
|
471
|
-
if (!ctx.shared && this.name === undefined) {
|
|
472
|
-
const left = decodeOutbox(await db.record(OUTBOX));
|
|
473
|
-
left.forEach((outgoing) => this.make(outgoing, true));
|
|
474
|
-
// Emptied at once, as a transaction's own sends are (see `withSends`):
|
|
475
|
-
// kept until the handler's end, an attempt that resumes a long wait
|
|
476
|
-
// would make them again, past the idempotency retention.
|
|
477
|
-
if (left.length > 0)
|
|
478
|
-
await this.flush(db);
|
|
479
|
-
}
|
|
480
|
-
if (own)
|
|
481
|
-
await this.ensureSchemas(db, [own]);
|
|
482
|
-
}
|
|
483
|
-
catch (error) {
|
|
484
|
-
const failed = handlerError(error);
|
|
485
|
-
await db.close();
|
|
486
|
-
throw failed;
|
|
487
|
-
}
|
|
488
|
-
return db;
|
|
489
|
-
}
|
|
490
|
-
async endSession(outcome) {
|
|
491
|
-
this.ended = true;
|
|
492
|
-
const session = this.session;
|
|
493
|
-
if (session === undefined)
|
|
494
|
-
return settle(outcome);
|
|
495
|
-
let db;
|
|
496
|
-
try {
|
|
497
|
-
db = await session;
|
|
498
|
-
}
|
|
499
|
-
catch (error) {
|
|
500
|
-
// The open failed, and its error went to the call that made it; one
|
|
501
|
-
// made as the attempt started that no call saw fails the attempt, as
|
|
502
|
-
// its outbox is still to be made.
|
|
503
|
-
if (this.unseenOpen)
|
|
504
|
-
throw error;
|
|
505
|
-
return settle(outcome);
|
|
506
|
-
}
|
|
507
|
-
this.keepOpen();
|
|
508
|
-
if (this.ctx.shared) {
|
|
509
|
-
// It read the snapshot it opened on, whatever committed since; one that
|
|
510
|
-
// outlived 16 commits failed its read ("is gone"), and is retried.
|
|
511
|
-
const failed = 'error' in outcome ? handlerError(outcome.error) : undefined;
|
|
512
|
-
await db.close();
|
|
513
|
-
if ('error' in outcome)
|
|
514
|
-
throw failed;
|
|
515
|
-
return outcome.value;
|
|
516
|
-
}
|
|
517
|
-
if ('error' in outcome) {
|
|
518
|
-
const error = handlerError(outcome.error);
|
|
519
|
-
// The handler's error stands: what it committed is stored, and an
|
|
520
|
-
// outbox left full is made again by the next open.
|
|
521
|
-
await this.save(db).catch(() => db.close().catch(() => { }));
|
|
522
|
-
throw error;
|
|
523
|
-
}
|
|
524
|
-
// A transaction left open, say, which a retry would leave open again.
|
|
525
|
-
await forHandler(this.save(db));
|
|
526
|
-
return outcome.value;
|
|
527
|
-
}
|
|
528
|
-
/** Empty the outbox and save the session; one a storage error ended only closes. */
|
|
529
|
-
async save(db) {
|
|
530
|
-
if (!db.isUsable())
|
|
531
|
-
return db.close();
|
|
532
|
-
await this.flush(db);
|
|
533
|
-
await db.save();
|
|
534
|
-
}
|
|
535
587
|
}
|
|
536
588
|
/** Run `handler`, then end `attempt`'s SQL session, if it opened one (see {@link Attempt.end}). */
|
|
537
589
|
export async function withAttempt(handler, attempt) {
|