@restatedev/sessions 0.10.3 → 0.11.1
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 +36 -9
- package/dist/database.d.ts +71 -8
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +270 -57
- package/dist/database.js.map +1 -1
- package/dist/driver.d.ts +37 -2
- package/dist/driver.d.ts.map +1 -1
- package/dist/driver.js +90 -22
- package/dist/driver.js.map +1 -1
- package/dist/handler.d.ts.map +1 -1
- package/dist/handler.js +15 -2
- package/dist/handler.js.map +1 -1
- package/dist/internal.d.ts +2 -2
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +1 -1
- package/dist/internal.js.map +1 -1
- package/dist/object.d.ts +23 -6
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +10 -5
- package/dist/object.js.map +1 -1
- package/dist/session.d.ts +79 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +191 -13
- package/dist/session.js.map +1 -1
- package/package.json +4 -4
- package/src/database.ts +311 -58
- package/src/driver.ts +89 -22
- package/src/handler.ts +15 -2
- package/src/internal.ts +13 -2
- package/src/object.ts +29 -6
- package/src/session.ts +222 -13
package/src/handler.ts
CHANGED
|
@@ -78,6 +78,18 @@ export async function serveSession(
|
|
|
78
78
|
// addon; this is how it asks for the tick that writes what it sent.
|
|
79
79
|
vm.setScheduler(() => driver.scheduleTick());
|
|
80
80
|
|
|
81
|
+
// The response ends with the attempt, once the tick wrote its last words:
|
|
82
|
+
// not when the handler returns. Restate starts the next attempt only once
|
|
83
|
+
// it has, and a handler that Restate shut down at work of its own (outside
|
|
84
|
+
// `ctx.working`) runs on until that work is done, its actions throwing.
|
|
85
|
+
let closed = false;
|
|
86
|
+
const close = () => {
|
|
87
|
+
if (closed) return;
|
|
88
|
+
closed = true;
|
|
89
|
+
stream.close();
|
|
90
|
+
};
|
|
91
|
+
driver.whenEnded(() => setTimeout(close, 0));
|
|
92
|
+
|
|
81
93
|
// The input pump: the only reader of the request body. It runs until the
|
|
82
94
|
// body ends, beside the handler.
|
|
83
95
|
const ready = Promise.withResolvers<void>();
|
|
@@ -100,7 +112,6 @@ export async function serveSession(
|
|
|
100
112
|
try {
|
|
101
113
|
await ready.promise;
|
|
102
114
|
if (driver.over !== undefined || !driver.isReadyToExecute()) return;
|
|
103
|
-
driver.startHeartbeats();
|
|
104
115
|
// Input this handler cannot read will not read on the next attempt
|
|
105
116
|
// either: a terminal failure ends the invocation, where a retryable one
|
|
106
117
|
// would have Restate send the same bytes forever. The SDK's own handler
|
|
@@ -125,7 +136,7 @@ export async function serveSession(
|
|
|
125
136
|
await pump;
|
|
126
137
|
// The attempt's last words are buffered: a turn lets the tick write them.
|
|
127
138
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
128
|
-
|
|
139
|
+
close();
|
|
129
140
|
}
|
|
130
141
|
}
|
|
131
142
|
|
|
@@ -229,6 +240,8 @@ function contextOf(
|
|
|
229
240
|
// database takes before it issues anything (`session.ts`).
|
|
230
241
|
takeCancellation: () => driver.takeCarriedCancellation(),
|
|
231
242
|
cancelPreviousCalls: () => driver.cancelPreviousCalls(),
|
|
243
|
+
// What `ctx.working` keeps alive, and the database's own calls too (`session.ts`).
|
|
244
|
+
working: <T>(fn: () => T | Promise<T>) => driver.working(fn),
|
|
232
245
|
invocationEndPromise: { promise: ending.promise },
|
|
233
246
|
defaultSerde: restate.serde.json,
|
|
234
247
|
// The addon reads and writes the object's state on this, rather than
|
package/src/internal.ts
CHANGED
|
@@ -5,11 +5,22 @@
|
|
|
5
5
|
// own copy, so that a library's journaled handlers serve beside its objects).
|
|
6
6
|
export * as sdk from '@restatedev/restate-sdk';
|
|
7
7
|
export { ensureSchemas, Schema } from './schema.ts';
|
|
8
|
-
export {
|
|
8
|
+
export {
|
|
9
|
+
asDatabase,
|
|
10
|
+
lazyDatabase,
|
|
11
|
+
database,
|
|
12
|
+
reset,
|
|
13
|
+
deferSql,
|
|
14
|
+
undeferSql,
|
|
15
|
+
rideCommit,
|
|
16
|
+
flushRiders,
|
|
17
|
+
Attempt,
|
|
18
|
+
withAttempt,
|
|
19
|
+
} from './session.ts';
|
|
9
20
|
export type { ObjectConfig, SqlHost } from './session.ts';
|
|
10
21
|
export { Link } from './link.ts';
|
|
11
22
|
export { ScopeKey } from './scope.ts';
|
|
12
|
-
export { open, type Connection, type Store, type ConnectionTransaction } from './database.ts';
|
|
23
|
+
export { open, type Connection, type Store, type ConnectionTransaction, type Working } from './database.ts';
|
|
13
24
|
// The attempt on the explicit recovery VM, for the tests that drive one.
|
|
14
25
|
export { AttemptDriver, AttemptFailed, AttemptShutDown } from './driver.ts';
|
|
15
26
|
export { Vm, isShutDown } from './vm.ts';
|
package/src/object.ts
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import * as restate from '@restatedev/restate-sdk';
|
|
19
19
|
import type { Serde, VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
|
|
20
20
|
import { type CallOptions, type Rpc, rpcOf, type Send, sendOf, type Target } from './calls.ts';
|
|
21
|
-
import type { DatabaseReader, Store } from './database.ts';
|
|
21
|
+
import type { DatabaseReader, Store, Working } from './database.ts';
|
|
22
22
|
import { ensureOf, ensuring, Schema, type Step } from './schema.ts';
|
|
23
23
|
import { patchEndpoint } from './endpoint.ts';
|
|
24
24
|
import { Link } from './link.ts';
|
|
@@ -49,6 +49,23 @@ export interface SessionContext {
|
|
|
49
49
|
readonly send: Send;
|
|
50
50
|
/** Cancel an invocation, by its id: see {@link Cancel}. */
|
|
51
51
|
readonly cancel: Cancel;
|
|
52
|
+
/**
|
|
53
|
+
* Run `fn`, keeping the attempt alive while it runs: for work outside
|
|
54
|
+
* Restate that may outlast Restate's inactivity timeout (a minute, by
|
|
55
|
+
* default), such as a model's request.
|
|
56
|
+
*
|
|
57
|
+
* const reply = await ctx.working(() => model.generate(prompt));
|
|
58
|
+
*
|
|
59
|
+
* Outside it, an attempt Restate hears nothing from for that long is shut
|
|
60
|
+
* down: it suspends on the calls it waits for, and a new attempt runs the
|
|
61
|
+
* handler from the start when one answers (or at once, if it waits for
|
|
62
|
+
* none). So a wait of days holds no process, and work cut off that way is
|
|
63
|
+
* done again. Inside it, the attempt sends a heartbeat every 20 seconds
|
|
64
|
+
* (`RESTATE_SESSIONS_HEARTBEAT`, in milliseconds), whatever it waits for:
|
|
65
|
+
* keep a long wait on Restate (a call, a signal) out of it. The database's
|
|
66
|
+
* own calls keep the attempt alive by themselves.
|
|
67
|
+
*/
|
|
68
|
+
readonly working: Working;
|
|
52
69
|
}
|
|
53
70
|
|
|
54
71
|
/**
|
|
@@ -149,6 +166,7 @@ export function host(
|
|
|
149
166
|
run: (name, action) => exclusive.run(name, action),
|
|
150
167
|
vm: (ctx as { vm?: SqlHost['vm'] }).vm,
|
|
151
168
|
takeCancellation: (ctx as { takeCancellation?: SqlHost['takeCancellation'] }).takeCancellation,
|
|
169
|
+
working: workingOf(ctx),
|
|
152
170
|
genericSend: (send) => ctx.genericSend(send),
|
|
153
171
|
};
|
|
154
172
|
}
|
|
@@ -266,12 +284,17 @@ export function contextOf(
|
|
|
266
284
|
rpc,
|
|
267
285
|
send: sendOf((send) => void ctx.genericSend(send)),
|
|
268
286
|
cancel,
|
|
287
|
+
// An attempt the SDK serves (a test's) has nothing to keep alive.
|
|
288
|
+
working: workingOf(ctx) ?? ((fn) => (async () => fn())()),
|
|
269
289
|
},
|
|
270
290
|
scope,
|
|
271
291
|
);
|
|
272
292
|
return Object.freeze(context);
|
|
273
293
|
}
|
|
274
294
|
|
|
295
|
+
/** The `working` of an attempt on the VM's context `ctx` (`handler.ts`); none on the SDK's. */
|
|
296
|
+
const workingOf = (ctx: object): Working | undefined => (ctx as { working?: Working }).working;
|
|
297
|
+
|
|
275
298
|
/** {@link Cancel} over the SDK's context `ctx`. */
|
|
276
299
|
const cancelOf =
|
|
277
300
|
(ctx: Pick<restate.ObjectContext, 'invocation'>): Cancel =>
|
|
@@ -498,17 +521,17 @@ function explicitOf(ctx: SessionContext, of: string) {
|
|
|
498
521
|
*
|
|
499
522
|
* It watches for the cancellation, and holds nothing: awaited alone, it does
|
|
500
523
|
* not suspend the invocation, and Restate is not told that the handler waits
|
|
501
|
-
* (a heartbeat tells Restate the attempt makes progress
|
|
502
|
-
*
|
|
524
|
+
* (a heartbeat, in `ctx.working`, tells Restate the attempt makes progress
|
|
525
|
+
* instead). The cancel signal comes while Restate keeps
|
|
503
526
|
* the invocation's input open. Once Restate closed it (the handler sent and
|
|
504
527
|
* got nothing for the inactivity timeout), a cancellation resolves this at
|
|
505
528
|
* the handler's next await of Restate's, which suspends the invocation and
|
|
506
529
|
* resumes it at once, or not at all if it awaits nothing more.
|
|
507
530
|
*
|
|
508
531
|
* So it is not a way to park a handler until it is cancelled. One that
|
|
509
|
-
* awaits this and nothing else is not suspended: its attempt
|
|
510
|
-
* the inactivity timeout
|
|
511
|
-
*
|
|
532
|
+
* awaits this and nothing else is not suspended: its attempt is shut down at
|
|
533
|
+
* the inactivity timeout and started again at once, and so on until the
|
|
534
|
+
* cancellation comes.
|
|
512
535
|
*/
|
|
513
536
|
export const cancelled = async (ctx: SessionContext): Promise<void> => {
|
|
514
537
|
await explicitOf(ctx, 'cancelled').cancellation();
|
package/src/session.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
type SqlValue,
|
|
21
21
|
type Store,
|
|
22
22
|
type ConnectionTransaction,
|
|
23
|
+
type Working,
|
|
23
24
|
} from './database.ts';
|
|
24
25
|
import type { Vm } from './vm.ts';
|
|
25
26
|
import { Link } from './link.ts';
|
|
@@ -53,6 +54,13 @@ export interface Transaction extends DatabaseWriter {
|
|
|
53
54
|
* again is dropped.
|
|
54
55
|
*/
|
|
55
56
|
readonly send: Send;
|
|
57
|
+
/**
|
|
58
|
+
* Settles, and never rejects, once another call to `ctx.db` waits for this
|
|
59
|
+
* transaction to end. A body that keeps the transaction open for more work
|
|
60
|
+
* can return when it settles, so that the other call waits for one commit
|
|
61
|
+
* and no more.
|
|
62
|
+
*/
|
|
63
|
+
readonly queued: Promise<void>;
|
|
56
64
|
}
|
|
57
65
|
|
|
58
66
|
/** What the session needs of the handler's context. */
|
|
@@ -84,6 +92,11 @@ export interface SqlHost {
|
|
|
84
92
|
* attempt, whose own awaits fail with it.
|
|
85
93
|
*/
|
|
86
94
|
readonly takeCancellation?: () => boolean;
|
|
95
|
+
/**
|
|
96
|
+
* Keeps the attempt alive while a call of the database runs: the VM's
|
|
97
|
+
* attempt has it (`driver.ts`), the SDK's context does not.
|
|
98
|
+
*/
|
|
99
|
+
readonly working?: Working;
|
|
87
100
|
genericSend(send: restate.GenericSend<Uint8Array>): unknown;
|
|
88
101
|
}
|
|
89
102
|
|
|
@@ -237,17 +250,43 @@ function handlerError(error: unknown): unknown {
|
|
|
237
250
|
}
|
|
238
251
|
|
|
239
252
|
/** `call`'s result, or the error the handler fails with (see {@link handlerError}). */
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
return await call;
|
|
243
|
-
} catch (error) {
|
|
253
|
+
function forHandler<T>(call: Promise<T>): Promise<T> {
|
|
254
|
+
return call.catch((error: unknown) => {
|
|
244
255
|
throw handlerError(error);
|
|
245
|
-
}
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** {@link forHandler} of a call that answers with its value when it is ready: then it is the value, which only this package takes so. */
|
|
260
|
+
function forHandlerNow<T>(call: T | Promise<T>): T | Promise<T> {
|
|
261
|
+
return call instanceof Promise ? forHandler(call) : call;
|
|
246
262
|
}
|
|
247
263
|
|
|
248
264
|
/** The SQL of a transaction's body: `tx`'s, failing as {@link forHandler} does. */
|
|
249
|
-
function forBody(tx: ConnectionTransaction): DatabaseWriter {
|
|
250
|
-
return
|
|
265
|
+
function forBody(tx: ConnectionTransaction): DatabaseWriter & { readonly queued: Promise<void> } {
|
|
266
|
+
return {
|
|
267
|
+
...sqlOver((sql, params) => forHandlerNow(tx.queryColumnsNow(sql, params)), handlerError),
|
|
268
|
+
queued: tx.queued,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The connection's transaction behind a `tx` of a body, for the SQL it defers ({@link deferSql}). */
|
|
273
|
+
const DEFERRED = new Link<ConnectionTransaction>('deferred sql');
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Have `sql` (one statement, no parameters) run just before the next call of
|
|
277
|
+
* the transaction `tx`, in the same crossing of the addon: the statement and
|
|
278
|
+
* its order are those of a call made now, and what it spares is the call.
|
|
279
|
+
* Its failure is the next call's (or the commit's, if none comes). Returns
|
|
280
|
+
* false, queuing nothing, if the transaction cannot (a `tx` of another
|
|
281
|
+
* kind, or an addon without it): run the statement with `tx.execute`.
|
|
282
|
+
*/
|
|
283
|
+
export function deferSql(tx: Transaction, sql: string): boolean {
|
|
284
|
+
return DEFERRED.of(tx)?.defer(sql) ?? false;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Take back the last `sql` that {@link deferSql} queued on `tx` and no call has taken: it never runs. Whether it was taken back. */
|
|
288
|
+
export function undeferSql(tx: Transaction, sql: string): boolean {
|
|
289
|
+
return DEFERRED.of(tx)?.undefer(sql) ?? false;
|
|
251
290
|
}
|
|
252
291
|
|
|
253
292
|
/**
|
|
@@ -257,8 +296,8 @@ function forBody(tx: ConnectionTransaction): DatabaseWriter {
|
|
|
257
296
|
*/
|
|
258
297
|
export function asDatabase(connection: Connection): Database {
|
|
259
298
|
const db: Database = {
|
|
260
|
-
...sqlOver((sql, params) => connection.
|
|
261
|
-
transaction: (body) => connection.transaction((tx) => body({ ...forBody(tx), send: refusedSend })),
|
|
299
|
+
...sqlOver((sql, params) => connection.queryColumnsNow(sql, params)),
|
|
300
|
+
transaction: (body) => connection.transaction((tx) => body(DEFERRED.on({ ...forBody(tx), send: refusedSend }, tx))),
|
|
262
301
|
};
|
|
263
302
|
return ensuring(db, (schemas) => apply(connection, schemas));
|
|
264
303
|
}
|
|
@@ -360,6 +399,52 @@ type Outcome<T> = { value: T } | { error: unknown };
|
|
|
360
399
|
/** The attempt of a `ctx.db`: for {@link database}. */
|
|
361
400
|
const ATTEMPT = new Link<Attempt>('database');
|
|
362
401
|
|
|
402
|
+
/** A write that rides the next commit of a database, in that commit's transaction. */
|
|
403
|
+
type Rider = (tx: Transaction) => Promise<void>;
|
|
404
|
+
|
|
405
|
+
/** A pending {@link Rider}, and whether it may not wait for a commit that is not under way. */
|
|
406
|
+
interface Pending {
|
|
407
|
+
write: Rider;
|
|
408
|
+
urgent: boolean;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Have `write` run in the next transaction of `db` that commits, before its
|
|
413
|
+
* commit, rather than commit on its own: for bookkeeping that must be stored
|
|
414
|
+
* with the next write, not before it. A write by `db.execute` outside a
|
|
415
|
+
* transaction, made while a rider is pending, is that transaction; a read
|
|
416
|
+
* (`get`, `values`, `query`) is not, and writes nothing. A transaction that
|
|
417
|
+
* rolls back leaves the rider pending, and so does one that ends the handler
|
|
418
|
+
* before it commits: {@link flushRiders} writes what is left.
|
|
419
|
+
*
|
|
420
|
+
* A database has one rider per `slot`: a later one replaces the earlier, and
|
|
421
|
+
* `undefined` clears it. A rider registered while a commit that runs the
|
|
422
|
+
* earlier one is under way is for the commit after. Returns false, registering
|
|
423
|
+
* nothing, for a database that cannot (a view's, another kind of
|
|
424
|
+
* `Database`): the caller writes at once.
|
|
425
|
+
*
|
|
426
|
+
* An `urgent` rider waits only for a transaction that is under way: if none
|
|
427
|
+
* is at the end of the macrotask it was registered in (or of the one in which
|
|
428
|
+
* a transaction ended and left it pending), it is written in a transaction of
|
|
429
|
+
* its own. A transaction that is held open (a batch of commits) is under way,
|
|
430
|
+
* and writes it when it commits. A write of its own that fails is not
|
|
431
|
+
* retried and raises nothing: the rider stays pending for the next commit or
|
|
432
|
+
* {@link flushRiders}. A rider that replaces an urgent one stays urgent.
|
|
433
|
+
*/
|
|
434
|
+
export function rideCommit(
|
|
435
|
+
db: Database,
|
|
436
|
+
slot: string,
|
|
437
|
+
write: Rider | undefined,
|
|
438
|
+
{ urgent = false }: { urgent?: boolean } = {},
|
|
439
|
+
): boolean {
|
|
440
|
+
return ATTEMPT.of(db)?.ride(slot, write, urgent) ?? false;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** Write what is pending ({@link rideCommit}) in a transaction of its own: nothing, if nothing is. */
|
|
444
|
+
export async function flushRiders(db: Database): Promise<void> {
|
|
445
|
+
await ATTEMPT.of(db)?.flushRiders();
|
|
446
|
+
}
|
|
447
|
+
|
|
363
448
|
// A database's name (`database`).
|
|
364
449
|
const DATABASE_NAME = /^[\w.-]{1,64}$/;
|
|
365
450
|
|
|
@@ -406,6 +491,10 @@ class Session {
|
|
|
406
491
|
/** A call failed on it once a failure ended it: the next call opens another. */
|
|
407
492
|
retired = false;
|
|
408
493
|
private connection: Connection | undefined;
|
|
494
|
+
/** Its connection, once its open settled. */
|
|
495
|
+
get opened(): Connection | undefined {
|
|
496
|
+
return this.connection;
|
|
497
|
+
}
|
|
409
498
|
private failed = false;
|
|
410
499
|
private release: () => void = () => {};
|
|
411
500
|
|
|
@@ -467,8 +556,16 @@ export class Attempt {
|
|
|
467
556
|
private readonly databases = new Map<string, Attempt>();
|
|
468
557
|
/** The session, from its first use on. */
|
|
469
558
|
private session: Session | undefined;
|
|
559
|
+
/** The calls made on the session that have not reached its connection yet: see {@link call}. */
|
|
560
|
+
private unhanded = 0;
|
|
470
561
|
/** The ids of the outbox's transactions this attempt made the sends of. */
|
|
471
562
|
private readonly made = new Set<string>();
|
|
563
|
+
/** The writes that ride the next commit, by slot ({@link rideCommit}). */
|
|
564
|
+
private readonly riders = new Map<string, Pending>();
|
|
565
|
+
/** The transactions asked for and not finished: one that is under way writes the riders. */
|
|
566
|
+
private active = 0;
|
|
567
|
+
/** The macrotask at the end of which an urgent rider is written alone, if one is set. */
|
|
568
|
+
private urgentTimer: NodeJS.Immediate | undefined;
|
|
472
569
|
/** The schemas this attempt's database has all the steps of. */
|
|
473
570
|
private readonly ensured = new Map<string, Schema>();
|
|
474
571
|
private ended = false;
|
|
@@ -478,8 +575,17 @@ export class Attempt {
|
|
|
478
575
|
this.config = config;
|
|
479
576
|
this.name = name;
|
|
480
577
|
this.hasOutbox = !ctx.shared && name === undefined;
|
|
578
|
+
const base = sqlOver(
|
|
579
|
+
(sql, params) => this.askedNow(() => this.callNow((db) => db.queryColumnsNow(sql, params))),
|
|
580
|
+
handlerError,
|
|
581
|
+
);
|
|
481
582
|
this.db = {
|
|
482
|
-
...
|
|
583
|
+
...base,
|
|
584
|
+
// A write while a rider is pending is the transaction it rides.
|
|
585
|
+
execute: (statement, params) =>
|
|
586
|
+
this.riders.size > 0
|
|
587
|
+
? this.asked(() => this.transaction((tx) => tx.execute(statement, params)))
|
|
588
|
+
: base.execute(statement, params),
|
|
483
589
|
transaction: (body) => this.asked(() => this.transaction(body)),
|
|
484
590
|
};
|
|
485
591
|
ensuring(this.db, (schemas) => this.asked(() => this.call((db) => this.ensureSchemas(db, schemas))));
|
|
@@ -494,6 +600,39 @@ export class Attempt {
|
|
|
494
600
|
return other.db;
|
|
495
601
|
}
|
|
496
602
|
|
|
603
|
+
/** {@link rideCommit}. */
|
|
604
|
+
ride(slot: string, write: Rider | undefined, urgent: boolean): boolean {
|
|
605
|
+
if (this.ctx.shared || this.ended) return false;
|
|
606
|
+
if (write === undefined) this.riders.delete(slot);
|
|
607
|
+
else {
|
|
608
|
+
this.riders.set(slot, { write, urgent: urgent || (this.riders.get(slot)?.urgent ?? false) });
|
|
609
|
+
this.arm();
|
|
610
|
+
}
|
|
611
|
+
return true;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** Have the urgent riders written at the end of this macrotask, if any is pending and none is set. */
|
|
615
|
+
private arm() {
|
|
616
|
+
if (this.urgentTimer !== undefined || this.ended) return;
|
|
617
|
+
if (![...this.riders.values()].some((r) => r.urgent)) return;
|
|
618
|
+
this.urgentTimer = setImmediate(() => {
|
|
619
|
+
this.urgentTimer = undefined;
|
|
620
|
+
// A transaction under way writes them, or re-arms as it ends.
|
|
621
|
+
if (this.ended || this.active > 0) return;
|
|
622
|
+
// A failure leaves them pending, for the next commit or the flush, and is not tried again by a timer. After a
|
|
623
|
+
// success, one that came while it committed (its own timer found it under way) is set now.
|
|
624
|
+
this.transaction(async () => {}, false).then(
|
|
625
|
+
() => this.arm(),
|
|
626
|
+
() => {},
|
|
627
|
+
);
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** {@link flushRiders}, as a transaction of `db`: its commit writes them. */
|
|
632
|
+
async flushRiders() {
|
|
633
|
+
if (this.riders.size > 0) await this.db.transaction(async () => {});
|
|
634
|
+
}
|
|
635
|
+
|
|
497
636
|
/**
|
|
498
637
|
* `call`, which the handler asked for, unless a cancellation is owed to
|
|
499
638
|
* it: then the call fails with the cancellation, and does nothing.
|
|
@@ -514,6 +653,12 @@ export class Attempt {
|
|
|
514
653
|
return call();
|
|
515
654
|
}
|
|
516
655
|
|
|
656
|
+
/** {@link asked} for a call that answers with its value when it is ready ({@link callNow}). */
|
|
657
|
+
private askedNow<T>(call: () => T | Promise<T>): T | Promise<T> {
|
|
658
|
+
if (this.ctx.takeCancellation?.()) return Promise.reject(new CancelledError());
|
|
659
|
+
return call();
|
|
660
|
+
}
|
|
661
|
+
|
|
517
662
|
/**
|
|
518
663
|
* Open the session now, as the attempt starts, rather than on its first
|
|
519
664
|
* call: the open makes the sends a crashed attempt committed and left
|
|
@@ -547,13 +692,27 @@ export class Attempt {
|
|
|
547
692
|
* be made again by an attempt that resumes a long wait (an approval), past
|
|
548
693
|
* the idempotency retention that drops a repeat.
|
|
549
694
|
*/
|
|
550
|
-
private async transaction<T>(body: (tx: Transaction) => Promise<T
|
|
695
|
+
private async transaction<T>(body: (tx: Transaction) => Promise<T>, rearm = true): Promise<T> {
|
|
696
|
+
this.active++;
|
|
697
|
+
try {
|
|
698
|
+
return await this.transacted(body);
|
|
699
|
+
} finally {
|
|
700
|
+
this.active--;
|
|
701
|
+
// What it left pending (it rolled back, or the rider came after it ran them) is for the end of this macrotask.
|
|
702
|
+
if (rearm) this.arm();
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
private async transacted<T>(body: (tx: Transaction) => Promise<T>): Promise<T> {
|
|
551
707
|
let outgoing: Outgoing | undefined;
|
|
708
|
+
// The riders this transaction wrote: pending until it has committed.
|
|
709
|
+
let rode: [string, Pending][] = [];
|
|
552
710
|
const value = await this.call((db) =>
|
|
553
711
|
db.transaction(async (handle) => {
|
|
554
712
|
const sends = this.hasOutbox ? new Sends() : undefined;
|
|
555
713
|
const tx: Transaction = { ...forBody(handle), send: sends?.send ?? refusedSend };
|
|
556
714
|
// A view's writes stay in its session: it has nothing to reset.
|
|
715
|
+
DEFERRED.on(tx, handle);
|
|
557
716
|
if (!this.ctx.shared) RESET.on(tx, () => this.reset(handle));
|
|
558
717
|
let result: T;
|
|
559
718
|
try {
|
|
@@ -561,10 +720,17 @@ export class Attempt {
|
|
|
561
720
|
} finally {
|
|
562
721
|
outgoing = sends?.close();
|
|
563
722
|
}
|
|
723
|
+
// After the body, which may have registered one (a transaction held open for more work), and before the commit.
|
|
724
|
+
if (this.riders.size > 0) {
|
|
725
|
+
rode = [...this.riders];
|
|
726
|
+
for (const [, { write }] of rode) await write(tx);
|
|
727
|
+
}
|
|
564
728
|
if (this.hasOutbox) await this.commitOutbox(handle, outgoing);
|
|
565
729
|
return result;
|
|
566
730
|
}),
|
|
567
731
|
);
|
|
732
|
+
// One registered since is for the next commit.
|
|
733
|
+
for (const [slot, pending] of rode) if (this.riders.get(slot) === pending) this.riders.delete(slot);
|
|
568
734
|
if (outgoing !== undefined) await this.call((db) => this.flush(db));
|
|
569
735
|
return value;
|
|
570
736
|
}
|
|
@@ -592,14 +758,55 @@ export class Attempt {
|
|
|
592
758
|
*/
|
|
593
759
|
private async call<T>(call: (db: Connection) => Promise<T>): Promise<T> {
|
|
594
760
|
const session = this.current();
|
|
761
|
+
// Counted until it reaches the connection, which orders it from there on.
|
|
762
|
+
this.unhanded++;
|
|
763
|
+
let counted = true;
|
|
764
|
+
const handed = () => {
|
|
765
|
+
if (counted) this.unhanded--;
|
|
766
|
+
counted = false;
|
|
767
|
+
};
|
|
595
768
|
try {
|
|
596
|
-
|
|
769
|
+
const db = await session.ready;
|
|
770
|
+
handed();
|
|
771
|
+
return await call(db);
|
|
597
772
|
} catch (error) {
|
|
773
|
+
handed();
|
|
598
774
|
if (session.ended) session.retired = true;
|
|
599
775
|
throw handlerError(error);
|
|
600
776
|
}
|
|
601
777
|
}
|
|
602
778
|
|
|
779
|
+
/**
|
|
780
|
+
* {@link call} for a call that answers with its value when it is ready: it
|
|
781
|
+
* is the value, without a promise, which only this package takes so. That
|
|
782
|
+
* is for a session that is open, and with no call before it still to reach
|
|
783
|
+
* the connection (a call made before it, which waits for the session, must
|
|
784
|
+
* run first): anything else is {@link call}.
|
|
785
|
+
*/
|
|
786
|
+
private callNow<T>(call: (db: Connection) => T | Promise<T>): T | Promise<T> {
|
|
787
|
+
const session = this.session;
|
|
788
|
+
const db = session?.opened;
|
|
789
|
+
if (this.unhanded > 0 || session === undefined || db === undefined || session.retired || this.ended) {
|
|
790
|
+
return this.call(async (connection) => call(connection));
|
|
791
|
+
}
|
|
792
|
+
// As `call` fails: a session that a failure ended is retired by the call that fails on it.
|
|
793
|
+
const failure = (error: unknown): unknown => {
|
|
794
|
+
if (session.ended) session.retired = true;
|
|
795
|
+
return handlerError(error);
|
|
796
|
+
};
|
|
797
|
+
let result: T | Promise<T>;
|
|
798
|
+
try {
|
|
799
|
+
result = call(db);
|
|
800
|
+
} catch (error) {
|
|
801
|
+
return Promise.reject(failure(error));
|
|
802
|
+
}
|
|
803
|
+
return result instanceof Promise
|
|
804
|
+
? result.catch((error: unknown) => {
|
|
805
|
+
throw failure(error);
|
|
806
|
+
})
|
|
807
|
+
: result;
|
|
808
|
+
}
|
|
809
|
+
|
|
603
810
|
/** The session, opening one if there is none, or the one there is was retired. */
|
|
604
811
|
private current(): Session {
|
|
605
812
|
if (this.ended) throw new Error('the handler has ended: its SQL session is closed');
|
|
@@ -634,7 +841,7 @@ export class Attempt {
|
|
|
634
841
|
const onVm = ctx.vm !== undefined;
|
|
635
842
|
const object = onVm ? commitOnly() : objectStore(ctx, end, this.name);
|
|
636
843
|
const db = onVm
|
|
637
|
-
? await openOnVm(namespace, object, ctx.vm, { name: this.name, reader: ctx.shared })
|
|
844
|
+
? await openOnVm(namespace, object, ctx.vm, { name: this.name, reader: ctx.shared, working: ctx.working })
|
|
638
845
|
: await open(namespace, wrap ? wrap(object) : object, { reader: ctx.shared });
|
|
639
846
|
try {
|
|
640
847
|
// A view writes nothing: a write fails, rather than vanish with the attempt.
|
|
@@ -666,6 +873,8 @@ export class Attempt {
|
|
|
666
873
|
*/
|
|
667
874
|
private async endSession<T>(outcome: Outcome<T>): Promise<T> {
|
|
668
875
|
this.ended = true;
|
|
876
|
+
if (this.urgentTimer !== undefined) clearImmediate(this.urgentTimer);
|
|
877
|
+
this.urgentTimer = undefined;
|
|
669
878
|
const failed = await this.close().then(
|
|
670
879
|
() => undefined,
|
|
671
880
|
(error: unknown) => ({ error }),
|