@restatedev/sessions 0.11.1 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +330 -178
- package/dist/addon.d.ts +1 -0
- package/dist/addon.d.ts.map +1 -1
- package/dist/addon.js.map +1 -1
- package/dist/calls.d.ts +28 -28
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +25 -25
- package/dist/calls.js.map +1 -1
- package/dist/database.d.ts +90 -166
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +137 -249
- package/dist/database.js.map +1 -1
- package/dist/driver.d.ts +129 -126
- package/dist/driver.d.ts.map +1 -1
- package/dist/driver.js +337 -276
- package/dist/driver.js.map +1 -1
- package/dist/endpoint.d.ts +47 -5
- package/dist/endpoint.d.ts.map +1 -1
- package/dist/endpoint.js +175 -60
- package/dist/endpoint.js.map +1 -1
- package/dist/handler.d.ts +20 -17
- package/dist/handler.d.ts.map +1 -1
- package/dist/handler.js +161 -127
- package/dist/handler.js.map +1 -1
- package/dist/host.d.ts +29 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +2 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -26
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +11 -11
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +20 -16
- package/dist/internal.js.map +1 -1
- package/dist/link.d.ts +1 -2
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +4 -5
- package/dist/link.js.map +1 -1
- package/dist/log.d.ts +14 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +21 -0
- package/dist/log.js.map +1 -0
- package/dist/object.d.ts +217 -142
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +195 -241
- package/dist/object.js.map +1 -1
- package/dist/platform.d.ts +0 -1
- package/dist/platform.d.ts.map +1 -1
- package/dist/platform.js +4 -6
- package/dist/platform.js.map +1 -1
- package/dist/schema.d.ts +14 -22
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +31 -69
- package/dist/schema.js.map +1 -1
- package/dist/serve.d.ts +11 -17
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +21 -39
- package/dist/serve.js.map +1 -1
- package/dist/session.d.ts +58 -236
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +206 -513
- package/dist/session.js.map +1 -1
- package/dist/stop.d.ts +59 -0
- package/dist/stop.d.ts.map +1 -0
- package/dist/stop.js +220 -0
- package/dist/stop.js.map +1 -0
- package/dist/vm.d.ts +108 -29
- package/dist/vm.d.ts.map +1 -1
- package/dist/vm.js +43 -10
- package/dist/vm.js.map +1 -1
- package/package.json +4 -4
- package/src/addon.ts +1 -0
- package/src/calls.ts +51 -47
- package/src/database.ts +195 -339
- package/src/driver.ts +379 -315
- package/src/endpoint.ts +217 -62
- package/src/handler.ts +183 -164
- package/src/host.ts +28 -0
- package/src/index.ts +6 -26
- package/src/internal.ts +28 -39
- package/src/link.ts +4 -5
- package/src/log.ts +42 -0
- package/src/object.ts +379 -335
- package/src/platform.ts +4 -6
- package/src/schema.ts +37 -103
- package/src/serve.ts +20 -41
- package/src/session.ts +236 -613
- package/src/stop.ts +225 -0
- package/src/vm.ts +151 -55
- package/dist/scope.d.ts +0 -38
- package/dist/scope.d.ts.map +0 -1
- package/dist/scope.js +0 -55
- package/dist/scope.js.map +0 -1
- package/src/scope.ts +0 -78
package/dist/session.js
CHANGED
|
@@ -1,143 +1,81 @@
|
|
|
1
|
-
// An attempt's database: the session's database, kept in the object's state
|
|
2
|
-
// (database.ts), opened as an exclusive attempt starts (a view's on its first
|
|
3
|
-
// read) and saved when the handler ends; and its transactions, with the sends
|
|
4
|
-
// each commits with (`tx.send`).
|
|
5
|
-
import { Buffer } from 'node:buffer';
|
|
6
|
-
import { randomUUID } from 'node:crypto';
|
|
7
1
|
import { CancelledError, serde, TerminalError } from '@restatedev/restate-sdk';
|
|
8
2
|
import { millisOrDurationToMillis } from '@restatedev/restate-sdk-core';
|
|
9
3
|
import { open, openOnVm, sqlOver, SqlError, } from './database.js';
|
|
10
4
|
import { Link } from './link.js';
|
|
11
|
-
import { apply,
|
|
5
|
+
import { apply, ensureOf, ensuring } from './schema.js';
|
|
12
6
|
import { sendOf } from './calls.js';
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
return Promise.reject(this.ended);
|
|
38
|
-
return new Promise((resolve, reject) => {
|
|
39
|
-
this.waiting.add(reject);
|
|
40
|
-
void Promise.resolve(promise)
|
|
41
|
-
.finally(() => this.waiting.delete(reject))
|
|
42
|
-
.then(resolve, reject);
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
/** Call `listener` when the attempt ends; the returned function cancels it. */
|
|
46
|
-
onEnd(listener) {
|
|
47
|
-
if (this.ended) {
|
|
48
|
-
listener();
|
|
49
|
-
return () => { };
|
|
50
|
-
}
|
|
51
|
-
this.listeners.add(listener);
|
|
52
|
-
return () => this.listeners.delete(listener);
|
|
53
|
-
}
|
|
7
|
+
/**
|
|
8
|
+
* `promise`, or a rejection once the attempt ends. A suspended or aborted
|
|
9
|
+
* attempt never settles what it waits for, and a session left waiting would
|
|
10
|
+
* hold its lock for the life of the process.
|
|
11
|
+
*/
|
|
12
|
+
function raced(ended, promise) {
|
|
13
|
+
if (ended.aborted)
|
|
14
|
+
return Promise.reject(ended.reason);
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
const abort = () => reject(ended.reason);
|
|
17
|
+
ended.addEventListener('abort', abort, { once: true });
|
|
18
|
+
void Promise.resolve(promise)
|
|
19
|
+
.finally(() => ended.removeEventListener('abort', abort))
|
|
20
|
+
.then(resolve, reject);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/** Call `listener` when `ended` aborts (now, if it has). The returned function removes it. */
|
|
24
|
+
function onEnd(ended, listener) {
|
|
25
|
+
if (ended.aborted) {
|
|
26
|
+
listener();
|
|
27
|
+
return () => { };
|
|
28
|
+
}
|
|
29
|
+
ended.addEventListener('abort', listener, { once: true });
|
|
30
|
+
return () => ended.removeEventListener('abort', listener);
|
|
54
31
|
}
|
|
55
|
-
// A
|
|
56
|
-
// database's head, tail and packs by name (`dev.restate.tooling.journal.hidden.name.prefix`).
|
|
57
|
-
const named = (key) => ({ name: key });
|
|
58
|
-
// A shared handler's reader writes nothing.
|
|
32
|
+
// A view writes nothing.
|
|
59
33
|
const refusedWrite = () => {
|
|
60
34
|
throw new Error('a shared handler writes no state');
|
|
61
35
|
};
|
|
62
|
-
/**
|
|
63
|
-
* The keys of the database `name`, apart from the object's own: each of the
|
|
64
|
-
* format's keys (`v22/head`, `v22/tail/...`, `v22/manifest/...`,
|
|
65
|
-
* `v22/pack/...`) as `v22/db/<name>/head`, under the format's prefix still,
|
|
66
|
-
* which tooling hides, and under none of the object's database's.
|
|
67
|
-
*/
|
|
36
|
+
/** The state key of `key` in database `name`: `v22/head` becomes `v22/db/<name>/head`, still hidden by tooling. */
|
|
68
37
|
const beside = (name) => (key) => {
|
|
69
38
|
const at = key.indexOf('/') + 1;
|
|
70
39
|
return `${key.slice(0, at)}db/${name}/${key.slice(at)}`;
|
|
71
40
|
};
|
|
72
|
-
/**
|
|
73
|
-
* The format's key of a key of the database `name` (undoes {@link beside});
|
|
74
|
-
* `undefined` for any other key of the object.
|
|
75
|
-
*/
|
|
41
|
+
/** Undoes {@link beside}. `undefined` for a key of another database. */
|
|
76
42
|
const unbeside = (name) => (key) => {
|
|
77
43
|
const at = key.indexOf('/') + 1;
|
|
78
44
|
const prefix = `db/${name}/`;
|
|
79
45
|
return at > 0 && key.startsWith(prefix, at) ? key.slice(0, at) + key.slice(at + prefix.length) : undefined;
|
|
80
46
|
};
|
|
81
47
|
/**
|
|
82
|
-
* The object
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* commands before it. A `get` or `sync` the attempt's end leaves waiting
|
|
86
|
-
* rejects, so the session that made it ends instead of holding its lock for
|
|
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`).
|
|
89
|
-
*/
|
|
90
|
-
/**
|
|
91
|
-
* The store of a database the addon keeps on the VM: it reads and writes the
|
|
92
|
-
* state itself, and calls this only at a commit, through `sync`, where the
|
|
93
|
-
* boundary runs what the committing transaction gave `withCommit`. Reaching
|
|
94
|
-
* anything else is a bug in the addon, and says so rather than going quiet.
|
|
48
|
+
* The object state `store` of a test attempt, as database `dbName` sees it:
|
|
49
|
+
* keys named apart ({@link beside}), no writes in a `view`, and pending reads
|
|
50
|
+
* rejected when the attempt ends.
|
|
95
51
|
*/
|
|
96
|
-
function
|
|
97
|
-
return {
|
|
98
|
-
get: servedByVm('get'),
|
|
99
|
-
set: servedByVm('set'),
|
|
100
|
-
clear: servedByVm('clear'),
|
|
101
|
-
sync: async () => { },
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
/** What a store the addon never calls does if it is called after all. */
|
|
105
|
-
const servedByVm = (op) => () => {
|
|
106
|
-
throw new Error(`@restatedev/sessions: the VM serves the state; the store's ${op} is not called`);
|
|
107
|
-
};
|
|
108
|
-
function objectStore(ctx, end, dbName) {
|
|
52
|
+
function objectStore(store, ended, view, dbName) {
|
|
109
53
|
const keyOf = dbName === undefined ? (key) => key : beside(dbName);
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
// a Restate release ships v8 and the SDK lets a library make one. Restate 1.8
|
|
113
|
-
// negotiates v7 at most: a journaled get.
|
|
114
|
-
const get = async (key) => (await request(ctx.get(keyOf(key), serde.binary, named(keyOf(key))))) ?? undefined;
|
|
115
|
-
if (ctx.shared)
|
|
54
|
+
const get = (key) => raced(ended, store.get(keyOf(key)));
|
|
55
|
+
if (view)
|
|
116
56
|
return { get, set: refusedWrite, clear: refusedWrite, sync: async () => { } };
|
|
57
|
+
const keys = store.keys?.bind(store);
|
|
117
58
|
return {
|
|
118
59
|
get,
|
|
119
|
-
set: (key, value) =>
|
|
120
|
-
clear: (key) =>
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
},
|
|
60
|
+
set: (key, value) => store.set(keyOf(key), value),
|
|
61
|
+
clear: (key) => store.clear(keyOf(key)),
|
|
62
|
+
sync: () => raced(ended, store.sync()),
|
|
63
|
+
// For garbage collection.
|
|
64
|
+
...(keys && {
|
|
65
|
+
keys: async () => {
|
|
66
|
+
const all = await raced(ended, keys());
|
|
67
|
+
if (dbName === undefined)
|
|
68
|
+
return all;
|
|
69
|
+
const own = unbeside(dbName);
|
|
70
|
+
return all.flatMap((key) => own(key) ?? []);
|
|
71
|
+
},
|
|
72
|
+
}),
|
|
132
73
|
};
|
|
133
74
|
}
|
|
134
75
|
/**
|
|
135
|
-
*
|
|
136
|
-
* {@link
|
|
137
|
-
*
|
|
138
|
-
* any handler: a storage error, which ends the session, or the handler's own
|
|
139
|
-
* (a failed request to another service, say) is retried, unless it is a
|
|
140
|
-
* TerminalError itself.
|
|
76
|
+
* An {@link SqlError}, which a retry would repeat, becomes a
|
|
77
|
+
* {@link TerminalError} with the SQL error as `cause`. Other errors are
|
|
78
|
+
* retried as usual.
|
|
141
79
|
*/
|
|
142
80
|
function handlerError(error) {
|
|
143
81
|
if (!(error instanceof SqlError))
|
|
@@ -146,71 +84,31 @@ function handlerError(error) {
|
|
|
146
84
|
terminal.cause = error;
|
|
147
85
|
return terminal;
|
|
148
86
|
}
|
|
149
|
-
/** `call`'s result, or the error the handler fails with (see {@link handlerError}). */
|
|
150
87
|
function forHandler(call) {
|
|
151
88
|
return call.catch((error) => {
|
|
152
89
|
throw handlerError(error);
|
|
153
90
|
});
|
|
154
91
|
}
|
|
155
|
-
/** {@link forHandler}
|
|
92
|
+
/** {@link forHandler} for a call that may answer synchronously (only this package sees that). */
|
|
156
93
|
function forHandlerNow(call) {
|
|
157
94
|
return call instanceof Promise ? forHandler(call) : call;
|
|
158
95
|
}
|
|
159
|
-
/** The SQL of a transaction
|
|
96
|
+
/** The SQL of a transaction body over `tx`, failing as {@link forHandler} does. */
|
|
160
97
|
function forBody(tx) {
|
|
161
|
-
return
|
|
162
|
-
...sqlOver((sql, params) => forHandlerNow(tx.queryColumnsNow(sql, params)), handlerError),
|
|
163
|
-
queued: tx.queued,
|
|
164
|
-
};
|
|
98
|
+
return sqlOver((sql, params) => forHandlerNow(tx.queryColumnsNow(sql, params)), handlerError);
|
|
165
99
|
}
|
|
166
|
-
/** The connection's transaction behind a `tx` of a body, for the SQL it defers ({@link deferSql}). */
|
|
167
|
-
const DEFERRED = new Link('deferred sql');
|
|
168
100
|
/**
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
* its order are those of a call made now, and what it spares is the call.
|
|
172
|
-
* Its failure is the next call's (or the commit's, if none comes). Returns
|
|
173
|
-
* false, queuing nothing, if the transaction cannot (a `tx` of another
|
|
174
|
-
* kind, or an addon without it): run the statement with `tx.execute`.
|
|
175
|
-
*/
|
|
176
|
-
export function deferSql(tx, sql) {
|
|
177
|
-
return DEFERRED.of(tx)?.defer(sql) ?? false;
|
|
178
|
-
}
|
|
179
|
-
/** Take back the last `sql` that {@link deferSql} queued on `tx` and no call has taken: it never runs. Whether it was taken back. */
|
|
180
|
-
export function undeferSql(tx, sql) {
|
|
181
|
-
return DEFERRED.of(tx)?.undefer(sql) ?? false;
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* `connection`, opened without the SDK (`open`), as a handler's `ctx.db`:
|
|
185
|
-
* for a library's tests, and tools. Its transactions send nothing, and a
|
|
186
|
-
* library's schema applies to it (`Schema.ensure`).
|
|
101
|
+
* `connection` (opened without the SDK) as a `ctx.db`, for library tests and
|
|
102
|
+
* tools. Its transactions cannot send. `Schema.ensure` works on it.
|
|
187
103
|
*/
|
|
188
104
|
export function asDatabase(connection) {
|
|
189
105
|
const db = {
|
|
190
106
|
...sqlOver((sql, params) => connection.queryColumnsNow(sql, params)),
|
|
191
|
-
transaction: (body) => connection.transaction((tx) => body(
|
|
107
|
+
transaction: (body) => connection.transaction((tx) => body({ ...forBody(tx), send: refusedSend })),
|
|
192
108
|
};
|
|
193
109
|
return ensuring(db, (schemas) => apply(connection, schemas));
|
|
194
110
|
}
|
|
195
|
-
/**
|
|
196
|
-
const RESET = new Link('reset');
|
|
197
|
-
/**
|
|
198
|
-
* Empty the key's database in `tx`, a transaction of an exclusive handler's
|
|
199
|
-
* `ctx.db`: every table, view, index and trigger is dropped, the schemas are
|
|
200
|
-
* applied again (the object's, and the libraries' the attempt applied), and
|
|
201
|
-
* the outbox stays. It commits with `tx`: what `tx` writes after it are the
|
|
202
|
-
* new database's first rows, in the same commit.
|
|
203
|
-
*/
|
|
204
|
-
export function reset(tx) {
|
|
205
|
-
const of = RESET.of(tx);
|
|
206
|
-
if (of === undefined)
|
|
207
|
-
throw new TerminalError("reset takes a transaction of an exclusive handler's ctx.db");
|
|
208
|
-
return forHandler(of());
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* A database that `opener` opens on its first call, as a handler's `ctx.db`
|
|
212
|
-
* opens: for tests, which give each attempt one over the same state.
|
|
213
|
-
*/
|
|
111
|
+
/** A database that `opener` opens on first use, as `ctx.db` does: for tests. */
|
|
214
112
|
export function lazyDatabase(opener) {
|
|
215
113
|
let opened;
|
|
216
114
|
const db = () => (opened ??= opener());
|
|
@@ -229,67 +127,44 @@ export function lazyDatabase(opener) {
|
|
|
229
127
|
await ensure(schemas);
|
|
230
128
|
});
|
|
231
129
|
}
|
|
232
|
-
/**
|
|
130
|
+
/** `tx.send` where a transaction cannot send: in a view, or in a database other than the object database. */
|
|
233
131
|
const refusedSend = () => {
|
|
234
132
|
throw new TerminalError("a send of a transaction is an exclusive handler's, in the object's own database");
|
|
235
133
|
};
|
|
236
|
-
|
|
237
|
-
const
|
|
238
|
-
/** The outbox as its record: none is empty, as a record never set reads. */
|
|
239
|
-
function encodeOutbox(outbox) {
|
|
240
|
-
return outbox.length === 0 ? new Uint8Array() : new TextEncoder().encode(JSON.stringify(outbox));
|
|
241
|
-
}
|
|
242
|
-
function decodeOutbox(record) {
|
|
243
|
-
return record.length === 0 ? [] : JSON.parse(new TextDecoder().decode(record));
|
|
244
|
-
}
|
|
245
|
-
function storedSend(send) {
|
|
246
|
-
const { parameter, inputSerde, delay, ...rest } = send;
|
|
134
|
+
function pendingSend(send) {
|
|
135
|
+
const { service, method, key, parameter, inputSerde, delay, idempotencyKey, headers } = send;
|
|
247
136
|
return {
|
|
248
|
-
|
|
137
|
+
service,
|
|
138
|
+
handler: method,
|
|
139
|
+
...(key !== undefined ? { key } : {}),
|
|
140
|
+
parameter: (inputSerde ?? serde.binary).serialize(parameter),
|
|
249
141
|
...(delay !== undefined ? { delay: millisOrDurationToMillis(delay) } : {}),
|
|
250
|
-
|
|
142
|
+
...(idempotencyKey !== undefined ? { idempotencyKey } : {}),
|
|
143
|
+
...(headers !== undefined ? { headers } : {}),
|
|
251
144
|
};
|
|
252
145
|
}
|
|
253
|
-
/**
|
|
146
|
+
/** `send` as the commit's atomic group makes it. */
|
|
147
|
+
const groupSend = (send) => ({
|
|
148
|
+
target: {
|
|
149
|
+
service: send.service,
|
|
150
|
+
handler: send.handler,
|
|
151
|
+
...(send.key !== undefined ? { key: send.key } : {}),
|
|
152
|
+
...(send.idempotencyKey !== undefined ? { idempotencyKey: send.idempotencyKey } : {}),
|
|
153
|
+
...(send.headers !== undefined
|
|
154
|
+
? { headers: Object.entries(send.headers).map(([key, value]) => ({ key, value })) }
|
|
155
|
+
: {}),
|
|
156
|
+
},
|
|
157
|
+
input: send.parameter,
|
|
158
|
+
...(send.delay !== undefined ? { delay: send.delay } : {}),
|
|
159
|
+
name: `${send.service}/${send.handler}`,
|
|
160
|
+
});
|
|
161
|
+
/** The attempt behind a `ctx.db`, for {@link database}. */
|
|
254
162
|
const ATTEMPT = new Link('database');
|
|
255
|
-
/**
|
|
256
|
-
* Have `write` run in the next transaction of `db` that commits, before its
|
|
257
|
-
* commit, rather than commit on its own: for bookkeeping that must be stored
|
|
258
|
-
* with the next write, not before it. A write by `db.execute` outside a
|
|
259
|
-
* transaction, made while a rider is pending, is that transaction; a read
|
|
260
|
-
* (`get`, `values`, `query`) is not, and writes nothing. A transaction that
|
|
261
|
-
* rolls back leaves the rider pending, and so does one that ends the handler
|
|
262
|
-
* before it commits: {@link flushRiders} writes what is left.
|
|
263
|
-
*
|
|
264
|
-
* A database has one rider per `slot`: a later one replaces the earlier, and
|
|
265
|
-
* `undefined` clears it. A rider registered while a commit that runs the
|
|
266
|
-
* earlier one is under way is for the commit after. Returns false, registering
|
|
267
|
-
* nothing, for a database that cannot (a view's, another kind of
|
|
268
|
-
* `Database`): the caller writes at once.
|
|
269
|
-
*
|
|
270
|
-
* An `urgent` rider waits only for a transaction that is under way: if none
|
|
271
|
-
* is at the end of the macrotask it was registered in (or of the one in which
|
|
272
|
-
* a transaction ended and left it pending), it is written in a transaction of
|
|
273
|
-
* its own. A transaction that is held open (a batch of commits) is under way,
|
|
274
|
-
* and writes it when it commits. A write of its own that fails is not
|
|
275
|
-
* retried and raises nothing: the rider stays pending for the next commit or
|
|
276
|
-
* {@link flushRiders}. A rider that replaces an urgent one stays urgent.
|
|
277
|
-
*/
|
|
278
|
-
export function rideCommit(db, slot, write, { urgent = false } = {}) {
|
|
279
|
-
return ATTEMPT.of(db)?.ride(slot, write, urgent) ?? false;
|
|
280
|
-
}
|
|
281
|
-
/** Write what is pending ({@link rideCommit}) in a transaction of its own: nothing, if nothing is. */
|
|
282
|
-
export async function flushRiders(db) {
|
|
283
|
-
await ATTEMPT.of(db)?.flushRiders();
|
|
284
|
-
}
|
|
285
|
-
// A database's name (`database`).
|
|
286
163
|
const DATABASE_NAME = /^[\w.-]{1,64}$/;
|
|
287
164
|
/**
|
|
288
|
-
* The database `name
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
* and ends with the attempt, as `ctx.db` does. A name is 1 to 64 letters,
|
|
292
|
-
* digits, `_`, `-` or `.`.
|
|
165
|
+
* The key's database `name`, separate from `ctx.db` (`db`): for a library
|
|
166
|
+
* whose tables must be alone. It opens on first use and
|
|
167
|
+
* ends with the attempt. A name is 1 to 64 letters, digits, `_`, `-` or `.`.
|
|
293
168
|
*/
|
|
294
169
|
export function database(db, name) {
|
|
295
170
|
if (!DATABASE_NAME.test(name))
|
|
@@ -299,71 +174,63 @@ export function database(db, name) {
|
|
|
299
174
|
throw new TerminalError("database takes a handler's ctx.db");
|
|
300
175
|
return attempt.database(name);
|
|
301
176
|
}
|
|
302
|
-
/** The sends
|
|
177
|
+
/** The sends a transaction body makes (`tx.send`), until the body ends. */
|
|
303
178
|
class Sends {
|
|
304
179
|
sends = [];
|
|
305
180
|
open = true;
|
|
306
|
-
send
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
181
|
+
send;
|
|
182
|
+
constructor(fallback) {
|
|
183
|
+
this.send = sendOf((send) => {
|
|
184
|
+
if (!this.open)
|
|
185
|
+
throw new TerminalError('the transaction has ended: send from inside its body');
|
|
186
|
+
this.sends.push(pendingSend(send));
|
|
187
|
+
}, fallback);
|
|
188
|
+
}
|
|
189
|
+
/** The body ended: the transaction's sends. */
|
|
312
190
|
close() {
|
|
313
191
|
this.open = false;
|
|
314
|
-
|
|
315
|
-
return undefined;
|
|
316
|
-
const now = Date.now();
|
|
317
|
-
for (const send of this.sends)
|
|
318
|
-
if (send.delay !== undefined)
|
|
319
|
-
send.due = now + send.delay;
|
|
320
|
-
return { id: randomUUID(), sends: this.sends };
|
|
192
|
+
return this.sends;
|
|
321
193
|
}
|
|
322
194
|
}
|
|
323
195
|
/**
|
|
324
|
-
* One session of
|
|
325
|
-
*
|
|
326
|
-
* attempt ends it first ({@link end}).
|
|
196
|
+
* One session of the attempt database. A failed open or a failed request ends
|
|
197
|
+
* it. It closes when the attempt ends, unless {@link end} was called first.
|
|
327
198
|
*/
|
|
328
199
|
class Session {
|
|
329
200
|
ready;
|
|
330
|
-
/**
|
|
201
|
+
/** Set by the call that fails on an ended session: the next call opens a new one. */
|
|
331
202
|
retired = false;
|
|
332
203
|
connection;
|
|
333
|
-
/** Its connection, once its open settled. */
|
|
334
204
|
get opened() {
|
|
335
205
|
return this.connection;
|
|
336
206
|
}
|
|
337
207
|
failed = false;
|
|
338
208
|
release = () => { };
|
|
339
|
-
constructor(ready,
|
|
209
|
+
constructor(ready, ended) {
|
|
340
210
|
this.ready = ready;
|
|
341
|
-
void this.track(
|
|
211
|
+
void this.track(ended);
|
|
342
212
|
}
|
|
343
213
|
/** Whether a failure ended it. */
|
|
344
214
|
get ended() {
|
|
345
215
|
return this.failed || this.connection?.isUsable() === false;
|
|
346
216
|
}
|
|
347
|
-
/**
|
|
217
|
+
/** The connection (none if the open failed). After this, the end of the attempt does not close it. */
|
|
348
218
|
async end() {
|
|
349
219
|
const db = await this.ready.catch(() => undefined);
|
|
350
220
|
this.release();
|
|
351
221
|
return db;
|
|
352
222
|
}
|
|
353
|
-
/** Close it now. */
|
|
354
223
|
close() {
|
|
355
224
|
void this.end()
|
|
356
225
|
.then((db) => db?.close())
|
|
357
226
|
.catch(() => { });
|
|
358
227
|
}
|
|
359
|
-
async track(
|
|
228
|
+
async track(ended) {
|
|
360
229
|
try {
|
|
361
230
|
const db = await this.ready;
|
|
362
231
|
this.connection = db;
|
|
363
|
-
//
|
|
364
|
-
|
|
365
|
-
// statement runs, and the handler's later calls fail.
|
|
366
|
-
this.release = end.onEnd(() => void db.close().catch(() => { }));
|
|
232
|
+
// When the attempt ends, the session closes once no statement runs, and later calls fail.
|
|
233
|
+
this.release = onEnd(ended, () => void db.close().catch(() => { }));
|
|
367
234
|
}
|
|
368
235
|
catch {
|
|
369
236
|
this.failed = true;
|
|
@@ -371,138 +238,80 @@ class Session {
|
|
|
371
238
|
}
|
|
372
239
|
}
|
|
373
240
|
/**
|
|
374
|
-
*
|
|
375
|
-
*
|
|
376
|
-
*
|
|
377
|
-
* database `name` ({@link database}), which has neither the object's schema
|
|
378
|
-
* nor an outbox.
|
|
241
|
+
* The SQL session of an attempt, shared by everything the handler does. With
|
|
242
|
+
* `name`, it is the key's database `name` ({@link database}), which has no
|
|
243
|
+
* object schema and whose transactions cannot send.
|
|
379
244
|
*/
|
|
380
245
|
export class Attempt {
|
|
381
|
-
/** `ctx.db`. */
|
|
382
246
|
db;
|
|
383
|
-
|
|
384
|
-
|
|
247
|
+
host;
|
|
248
|
+
view;
|
|
385
249
|
config;
|
|
386
250
|
name;
|
|
387
|
-
/**
|
|
388
|
-
|
|
389
|
-
/** The key's other databases this attempt opened, by name. */
|
|
251
|
+
/** Only the object database of an exclusive handler has transactions that send. */
|
|
252
|
+
sends;
|
|
390
253
|
databases = new Map();
|
|
391
|
-
/** The session, from its first use on. */
|
|
392
254
|
session;
|
|
393
|
-
/**
|
|
255
|
+
/** Calls that have not reached the connection yet: see {@link callNow}. */
|
|
394
256
|
unhanded = 0;
|
|
395
|
-
/**
|
|
396
|
-
made = new Set();
|
|
397
|
-
/** The writes that ride the next commit, by slot ({@link rideCommit}). */
|
|
398
|
-
riders = new Map();
|
|
399
|
-
/** The transactions asked for and not finished: one that is under way writes the riders. */
|
|
400
|
-
active = 0;
|
|
401
|
-
/** The macrotask at the end of which an urgent rider is written alone, if one is set. */
|
|
402
|
-
urgentTimer;
|
|
403
|
-
/** The schemas this attempt's database has all the steps of. */
|
|
257
|
+
/** Schemas applied in this session. A view applies them only in its session. */
|
|
404
258
|
ensured = new Map();
|
|
405
259
|
ended = false;
|
|
406
|
-
|
|
407
|
-
|
|
260
|
+
/** {@link end} began: the other databases are ending. */
|
|
261
|
+
ending = false;
|
|
262
|
+
constructor(host, view, config = {}, name) {
|
|
263
|
+
this.host = host;
|
|
264
|
+
this.view = view;
|
|
408
265
|
this.config = config;
|
|
409
266
|
this.name = name;
|
|
410
|
-
this.
|
|
267
|
+
this.sends = !view && name === undefined;
|
|
411
268
|
const base = sqlOver((sql, params) => this.askedNow(() => this.callNow((db) => db.queryColumnsNow(sql, params))), handlerError);
|
|
412
269
|
this.db = {
|
|
413
270
|
...base,
|
|
414
|
-
// A write while a rider is pending is the transaction it rides.
|
|
415
|
-
execute: (statement, params) => this.riders.size > 0
|
|
416
|
-
? this.asked(() => this.transaction((tx) => tx.execute(statement, params)))
|
|
417
|
-
: base.execute(statement, params),
|
|
418
271
|
transaction: (body) => this.asked(() => this.transaction(body)),
|
|
419
272
|
};
|
|
420
273
|
ensuring(this.db, (schemas) => this.asked(() => this.call((db) => this.ensureSchemas(db, schemas))));
|
|
421
274
|
ATTEMPT.on(this.db, this);
|
|
422
275
|
}
|
|
423
|
-
/**
|
|
276
|
+
/** See {@link database}. */
|
|
424
277
|
database(name) {
|
|
425
|
-
if (this.ended)
|
|
278
|
+
if (this.ended || this.ending)
|
|
426
279
|
throw new Error('the handler has ended: its SQL session is closed');
|
|
427
280
|
let other = this.databases.get(name);
|
|
428
281
|
if (other === undefined)
|
|
429
|
-
this.databases.set(name, (other = new Attempt(this.
|
|
282
|
+
this.databases.set(name, (other = new Attempt(this.host, this.view, this.config, name)));
|
|
430
283
|
return other.db;
|
|
431
284
|
}
|
|
432
|
-
/** {@link rideCommit}. */
|
|
433
|
-
ride(slot, write, urgent) {
|
|
434
|
-
if (this.ctx.shared || this.ended)
|
|
435
|
-
return false;
|
|
436
|
-
if (write === undefined)
|
|
437
|
-
this.riders.delete(slot);
|
|
438
|
-
else {
|
|
439
|
-
this.riders.set(slot, { write, urgent: urgent || (this.riders.get(slot)?.urgent ?? false) });
|
|
440
|
-
this.arm();
|
|
441
|
-
}
|
|
442
|
-
return true;
|
|
443
|
-
}
|
|
444
|
-
/** Have the urgent riders written at the end of this macrotask, if any is pending and none is set. */
|
|
445
|
-
arm() {
|
|
446
|
-
if (this.urgentTimer !== undefined || this.ended)
|
|
447
|
-
return;
|
|
448
|
-
if (![...this.riders.values()].some((r) => r.urgent))
|
|
449
|
-
return;
|
|
450
|
-
this.urgentTimer = setImmediate(() => {
|
|
451
|
-
this.urgentTimer = undefined;
|
|
452
|
-
// A transaction under way writes them, or re-arms as it ends.
|
|
453
|
-
if (this.ended || this.active > 0)
|
|
454
|
-
return;
|
|
455
|
-
// A failure leaves them pending, for the next commit or the flush, and is not tried again by a timer. After a
|
|
456
|
-
// success, one that came while it committed (its own timer found it under way) is set now.
|
|
457
|
-
this.transaction(async () => { }, false).then(() => this.arm(), () => { });
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
/** {@link flushRiders}, as a transaction of `db`: its commit writes them. */
|
|
461
|
-
async flushRiders() {
|
|
462
|
-
if (this.riders.size > 0)
|
|
463
|
-
await this.db.transaction(async () => { });
|
|
464
|
-
}
|
|
465
285
|
/**
|
|
466
|
-
*
|
|
467
|
-
*
|
|
468
|
-
*
|
|
469
|
-
*
|
|
470
|
-
* What the handler asks for passes through here; what the session does for
|
|
471
|
-
* itself does not — the open, the object's schema, the sends a crashed
|
|
472
|
-
* attempt left unmade, emptying the outbox after a commit — and a
|
|
473
|
-
* cancellation that failed one of those would be delivered to nobody, or
|
|
474
|
-
* would report a transaction as cancelled after it committed. And it is
|
|
475
|
-
* before the call issues anything, so a call that fails with
|
|
476
|
-
* `CancelledError` wrote nothing and sent nothing: a call already under way
|
|
477
|
-
* when the cancellation arrives runs to its end, and the cancellation goes
|
|
478
|
-
* to what the handler awaits next.
|
|
286
|
+
* Fail with an owed cancellation before anything runs (see stop.ts). Only
|
|
287
|
+
* handler calls pass here: failing the session's own work (the open, the
|
|
288
|
+
* object's schema, the save) would deliver the cancellation to nobody, or
|
|
289
|
+
* report a committed transaction as cancelled.
|
|
479
290
|
*/
|
|
480
291
|
asked(call) {
|
|
481
|
-
if (this.
|
|
292
|
+
if (this.host.stop.take())
|
|
482
293
|
return Promise.reject(new CancelledError());
|
|
483
294
|
return call();
|
|
484
295
|
}
|
|
485
|
-
/** {@link asked} for a call that
|
|
296
|
+
/** {@link asked} for a call that may answer synchronously ({@link callNow}). */
|
|
486
297
|
askedNow(call) {
|
|
487
|
-
if (this.
|
|
298
|
+
if (this.host.stop.take())
|
|
488
299
|
return Promise.reject(new CancelledError());
|
|
489
300
|
return call();
|
|
490
301
|
}
|
|
491
302
|
/**
|
|
492
|
-
* Open the
|
|
493
|
-
* call:
|
|
494
|
-
*
|
|
303
|
+
* Open the object database as an exclusive attempt starts, rather than on
|
|
304
|
+
* its first call: its head is read and the object schema applied while the
|
|
305
|
+
* handler gets going.
|
|
495
306
|
*/
|
|
496
307
|
openNow() {
|
|
497
|
-
if (this.
|
|
308
|
+
if (this.sends && this.session === undefined)
|
|
498
309
|
this.current().ready.catch(() => { });
|
|
499
310
|
}
|
|
500
|
-
/**
|
|
501
|
-
* The handler ended with `outcome`: the key's other databases end, then
|
|
502
|
-
* this one ({@link endSession}).
|
|
503
|
-
*/
|
|
311
|
+
/** The handler ended with `outcome`. The key's other databases end first, as the handler left them. */
|
|
504
312
|
async end(outcome) {
|
|
505
|
-
//
|
|
313
|
+
// None opens from here: nothing would end it.
|
|
314
|
+
this.ending = true;
|
|
506
315
|
const databases = await Promise.allSettled([...this.databases.values()].map((d) => d.end({ value: undefined })));
|
|
507
316
|
const value = await this.endSession(outcome);
|
|
508
317
|
const failed = databases.find((d) => d.status === 'rejected');
|
|
@@ -511,83 +320,47 @@ export class Attempt {
|
|
|
511
320
|
return value;
|
|
512
321
|
}
|
|
513
322
|
/**
|
|
514
|
-
* `body` as one transaction. In the object
|
|
515
|
-
* handler, its sends commit with it
|
|
516
|
-
* commit, right after its writes and before it waits for anything
|
|
517
|
-
* (`withCommit`): Restate stores an attempt's commands in order, so they
|
|
518
|
-
* are stored only if the commit is, and whatever fails the commit's wait
|
|
519
|
-
* (the attempt's end, say) comes after them. A second commit empties the outbox
|
|
520
|
-
* before `transaction` resolves: left until the handler's end, they would
|
|
521
|
-
* be made again by an attempt that resumes a long wait (an approval), past
|
|
522
|
-
* the idempotency retention that drops a repeat.
|
|
323
|
+
* `body` as one transaction. In the object database of an exclusive
|
|
324
|
+
* handler, its sends commit with it (see the block above `PendingSend`).
|
|
523
325
|
*/
|
|
524
|
-
async transaction(body
|
|
525
|
-
this.
|
|
526
|
-
|
|
527
|
-
return await this.transacted(body);
|
|
528
|
-
}
|
|
529
|
-
finally {
|
|
530
|
-
this.active--;
|
|
531
|
-
// What it left pending (it rolled back, or the rider came after it ran them) is for the end of this macrotask.
|
|
532
|
-
if (rearm)
|
|
533
|
-
this.arm();
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
async transacted(body) {
|
|
537
|
-
let outgoing;
|
|
538
|
-
// The riders this transaction wrote: pending until it has committed.
|
|
539
|
-
let rode = [];
|
|
540
|
-
const value = await this.call((db) => db.transaction(async (handle) => {
|
|
541
|
-
const sends = this.hasOutbox ? new Sends() : undefined;
|
|
326
|
+
async transaction(body) {
|
|
327
|
+
return this.call((db) => db.transaction(async (handle) => {
|
|
328
|
+
const sends = this.sends ? new Sends(this.config.serde) : undefined;
|
|
542
329
|
const tx = { ...forBody(handle), send: sends?.send ?? refusedSend };
|
|
543
|
-
|
|
544
|
-
DEFERRED.on(tx, handle);
|
|
545
|
-
if (!this.ctx.shared)
|
|
546
|
-
RESET.on(tx, () => this.reset(handle));
|
|
330
|
+
let made = [];
|
|
547
331
|
let result;
|
|
548
332
|
try {
|
|
549
333
|
result = await body(tx);
|
|
550
334
|
}
|
|
551
335
|
finally {
|
|
552
|
-
|
|
553
|
-
}
|
|
554
|
-
// After the body, which may have registered one (a transaction held open for more work), and before the commit.
|
|
555
|
-
if (this.riders.size > 0) {
|
|
556
|
-
rode = [...this.riders];
|
|
557
|
-
for (const [, { write }] of rode)
|
|
558
|
-
await write(tx);
|
|
336
|
+
made = sends?.close() ?? [];
|
|
559
337
|
}
|
|
560
|
-
if (this.
|
|
561
|
-
|
|
338
|
+
if (this.sends)
|
|
339
|
+
this.commitSends(handle, made);
|
|
562
340
|
return result;
|
|
563
341
|
}));
|
|
564
|
-
// One registered since is for the next commit.
|
|
565
|
-
for (const [slot, pending] of rode)
|
|
566
|
-
if (this.riders.get(slot) === pending)
|
|
567
|
-
this.riders.delete(slot);
|
|
568
|
-
if (outgoing !== undefined)
|
|
569
|
-
await this.call((db) => this.flush(db));
|
|
570
|
-
return value;
|
|
571
342
|
}
|
|
572
|
-
/**
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
outbox.push(outgoing);
|
|
581
|
-
handle.withCommit(() => this.make(outgoing));
|
|
343
|
+
/** Have the commit of `handle` make `sends`: in its atomic group on the VM, else through the host. */
|
|
344
|
+
commitSends(handle, sends) {
|
|
345
|
+
const { host } = this;
|
|
346
|
+
if (host.vm !== undefined) {
|
|
347
|
+
// A transaction opens no span of its own: its group is inside the span the handler's code is in, if any.
|
|
348
|
+
const parentSpan = host.driver?.currentSpan;
|
|
349
|
+
handle.commitWith({ sends: sends.map(groupSend), ...(parentSpan !== undefined ? { parentSpan } : {}) });
|
|
350
|
+
return;
|
|
582
351
|
}
|
|
583
|
-
|
|
352
|
+
if (sends.length === 0)
|
|
353
|
+
return;
|
|
354
|
+
handle.withCommit(() => {
|
|
355
|
+
for (const { handler, parameter, ...send } of sends) {
|
|
356
|
+
host.send({ ...send, method: handler, parameter, inputSerde: serde.binary });
|
|
357
|
+
}
|
|
358
|
+
});
|
|
584
359
|
}
|
|
585
360
|
/**
|
|
586
|
-
* `call
|
|
587
|
-
*
|
|
588
|
-
*
|
|
589
|
-
* So the failure of an open made as the attempt started goes to the first
|
|
590
|
-
* call, as it would had that call opened it.
|
|
361
|
+
* Run `call`, opening the session on first use. A call that fails on an
|
|
362
|
+
* ended session retires it, and the next call opens a new one. So a failed
|
|
363
|
+
* open at attempt start fails the first call.
|
|
591
364
|
*/
|
|
592
365
|
async call(call) {
|
|
593
366
|
const session = this.current();
|
|
@@ -612,11 +385,8 @@ export class Attempt {
|
|
|
612
385
|
}
|
|
613
386
|
}
|
|
614
387
|
/**
|
|
615
|
-
* {@link call}
|
|
616
|
-
*
|
|
617
|
-
* is for a session that is open, and with no call before it still to reach
|
|
618
|
-
* the connection (a call made before it, which waits for the session, must
|
|
619
|
-
* run first): anything else is {@link call}.
|
|
388
|
+
* {@link call} that may return the value synchronously: only for an open
|
|
389
|
+
* session with no earlier call still waiting to reach the connection.
|
|
620
390
|
*/
|
|
621
391
|
callNow(call) {
|
|
622
392
|
const session = this.session;
|
|
@@ -624,7 +394,7 @@ export class Attempt {
|
|
|
624
394
|
if (this.unhanded > 0 || session === undefined || db === undefined || session.retired || this.ended) {
|
|
625
395
|
return this.call(async (connection) => call(connection));
|
|
626
396
|
}
|
|
627
|
-
// As `call
|
|
397
|
+
// As in `call`, the failing call retires a session that a failure ended.
|
|
628
398
|
const failure = (error) => {
|
|
629
399
|
if (session.ended)
|
|
630
400
|
session.retired = true;
|
|
@@ -643,7 +413,7 @@ export class Attempt {
|
|
|
643
413
|
})
|
|
644
414
|
: result;
|
|
645
415
|
}
|
|
646
|
-
/** The session, opening one if there is none
|
|
416
|
+
/** The session, opening a new one if there is none or it was retired. */
|
|
647
417
|
current() {
|
|
648
418
|
if (this.ended)
|
|
649
419
|
throw new Error('the handler has ended: its SQL session is closed');
|
|
@@ -654,46 +424,37 @@ export class Attempt {
|
|
|
654
424
|
return this.session;
|
|
655
425
|
}
|
|
656
426
|
open() {
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
427
|
+
// A view applies schema steps only in its session, so a new session lacks them.
|
|
428
|
+
this.ensured.clear();
|
|
429
|
+
const ended = this.host.request.attemptCompletedSignal;
|
|
430
|
+
return new Session(this.start(ended), ended);
|
|
431
|
+
}
|
|
432
|
+
async start(ended) {
|
|
433
|
+
const { host, view } = this;
|
|
434
|
+
// Escaped so that no key reads as another key's database (a name has no `/`).
|
|
435
|
+
const key = `${host.request.target.service}/${encodeURIComponent(host.key)}`;
|
|
665
436
|
const namespace = this.name === undefined ? key : `${key}/${this.name}`;
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
437
|
+
// With a VM, the addon reads and writes the state itself, and no store call crosses into JavaScript.
|
|
438
|
+
const keepAlive = (fn) => host.stop.keepAlive(fn);
|
|
439
|
+
let db;
|
|
440
|
+
if (host.vm !== undefined) {
|
|
441
|
+
try {
|
|
442
|
+
db = await openOnVm(namespace, host.vm, { name: this.name, reader: view, keepAlive });
|
|
443
|
+
}
|
|
444
|
+
catch (error) {
|
|
445
|
+
// The VM refuses the open of an attempt that is over: it fails as the attempt ended.
|
|
446
|
+
throw ended.aborted ? ended.reason : error;
|
|
447
|
+
}
|
|
675
448
|
}
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
: await open(namespace, wrap ? wrap(object) : object, { reader: ctx.shared });
|
|
449
|
+
else if (host.store !== undefined)
|
|
450
|
+
db = await open(namespace, objectStore(host.store, ended, view, this.name), { reader: view });
|
|
451
|
+
else
|
|
452
|
+
throw new Error('@restatedev/sessions: an attempt has a VM or a store');
|
|
681
453
|
try {
|
|
682
|
-
// A
|
|
683
|
-
if (
|
|
454
|
+
// A write in a view fails instead of vanishing with the attempt.
|
|
455
|
+
if (view)
|
|
684
456
|
await db.execute('PRAGMA query_only = 1');
|
|
685
|
-
|
|
686
|
-
// What a crash left unmade; an open again in this attempt finds what
|
|
687
|
-
// this attempt made, stored before it, as made.
|
|
688
|
-
const left = decodeOutbox(await db.record(OUTBOX));
|
|
689
|
-
for (const outgoing of left)
|
|
690
|
-
if (!this.made.has(outgoing.id))
|
|
691
|
-
this.make(outgoing, true);
|
|
692
|
-
// Emptied at once, as a transaction's own sends are (see `transaction`).
|
|
693
|
-
if (left.length > 0)
|
|
694
|
-
await this.flush(db);
|
|
695
|
-
}
|
|
696
|
-
// A view's too, whose writes are never stored: a key never written reads as empty tables.
|
|
457
|
+
// Also in a view, which never stores the steps: a key never written reads as empty tables.
|
|
697
458
|
const own = this.ownSchema();
|
|
698
459
|
if (own)
|
|
699
460
|
await this.ensureSchemas(db, [own]);
|
|
@@ -705,17 +466,12 @@ export class Attempt {
|
|
|
705
466
|
return db;
|
|
706
467
|
}
|
|
707
468
|
/**
|
|
708
|
-
* End the session, then settle as the handler did
|
|
709
|
-
*
|
|
710
|
-
*
|
|
711
|
-
* A failure to end the session fails a handler that succeeded, which a
|
|
712
|
-
* retry then ends (a transaction it left open, say).
|
|
469
|
+
* End the session, then settle as the handler did. The handler's error wins
|
|
470
|
+
* (its commits are stored). A failure to end the session fails a handler
|
|
471
|
+
* that succeeded (for example, one that left a transaction open).
|
|
713
472
|
*/
|
|
714
473
|
async endSession(outcome) {
|
|
715
474
|
this.ended = true;
|
|
716
|
-
if (this.urgentTimer !== undefined)
|
|
717
|
-
clearImmediate(this.urgentTimer);
|
|
718
|
-
this.urgentTimer = undefined;
|
|
719
475
|
const failed = await this.close().then(() => undefined, (error) => ({ error }));
|
|
720
476
|
if ('error' in outcome)
|
|
721
477
|
throw handlerError(outcome.error);
|
|
@@ -724,39 +480,22 @@ export class Attempt {
|
|
|
724
480
|
return outcome.value;
|
|
725
481
|
}
|
|
726
482
|
/**
|
|
727
|
-
* Close the session
|
|
728
|
-
*
|
|
729
|
-
* ("is gone"), which is retried. Another is saved, its outbox emptied. One
|
|
730
|
-
* that a failure ended closes, and the object's own database is opened
|
|
731
|
-
* again and saved: it may hold sends unmade (a crash left them, and this
|
|
732
|
-
* attempt's open failed) or made and not emptied (the commit's wait
|
|
733
|
-
* failed), and no attempt may follow this one (a cancelled invocation's),
|
|
734
|
-
* nor the key's next invocation come within the idempotency retention.
|
|
483
|
+
* Close the session. A view only closes. Otherwise the session is saved; one
|
|
484
|
+
* that a failure ended closes, and what it committed is stored as it was.
|
|
735
485
|
*/
|
|
736
486
|
async close() {
|
|
737
487
|
if (this.session === undefined)
|
|
738
488
|
return;
|
|
739
489
|
const db = await this.session.end();
|
|
740
|
-
if (this.
|
|
490
|
+
if (this.view)
|
|
741
491
|
return db?.close();
|
|
742
492
|
if (db?.isUsable())
|
|
743
493
|
return this.save(db);
|
|
744
494
|
await db?.close().catch(() => { });
|
|
745
|
-
if (!this.hasOutbox)
|
|
746
|
-
return;
|
|
747
|
-
const again = this.open();
|
|
748
|
-
try {
|
|
749
|
-
await this.save(await again.ready);
|
|
750
|
-
}
|
|
751
|
-
finally {
|
|
752
|
-
void again.end();
|
|
753
|
-
}
|
|
754
495
|
}
|
|
755
|
-
/**
|
|
496
|
+
/** Save the session. The session closes if that fails. */
|
|
756
497
|
async save(db) {
|
|
757
498
|
try {
|
|
758
|
-
if (this.hasOutbox)
|
|
759
|
-
await this.flush(db);
|
|
760
499
|
await db.save();
|
|
761
500
|
}
|
|
762
501
|
catch (error) {
|
|
@@ -764,64 +503,18 @@ export class Attempt {
|
|
|
764
503
|
throw error;
|
|
765
504
|
}
|
|
766
505
|
}
|
|
767
|
-
/** The object
|
|
506
|
+
/** The object schema. The key's other databases do not get it. */
|
|
768
507
|
ownSchema() {
|
|
769
508
|
return this.name === undefined ? this.config.schema : undefined;
|
|
770
509
|
}
|
|
771
|
-
/**
|
|
772
|
-
async reset(handle) {
|
|
773
|
-
const own = this.ownSchema();
|
|
774
|
-
const schemas = [...(own ? [own] : []), ...[...this.ensured.values()].filter((s) => s !== own)];
|
|
775
|
-
await dropAll(handle, schemas);
|
|
776
|
-
}
|
|
777
|
-
/** Apply the steps of `schemas` that the database lacks, each schema once per attempt. */
|
|
510
|
+
/** Apply the steps of `schemas` that the database lacks, each schema once per session. */
|
|
778
511
|
async ensureSchemas(db, schemas) {
|
|
779
512
|
const lacking = schemas.filter((s) => !this.ensured.has(s.name));
|
|
780
513
|
if (lacking.length === 0)
|
|
781
514
|
return;
|
|
782
|
-
await apply(db, lacking, { reader: this.
|
|
515
|
+
await apply(db, lacking, { reader: this.view });
|
|
783
516
|
for (const s of lacking)
|
|
784
517
|
this.ensured.set(s.name, s);
|
|
785
518
|
}
|
|
786
|
-
/** Make the sends of a committed transaction: each with an idempotency key of the transaction (or its own), so that making them again is dropped. */
|
|
787
|
-
make({ id, sends }, again = false) {
|
|
788
|
-
sends.forEach(({ parameter, due, delay, ...send }, index) => {
|
|
789
|
-
this.ctx.genericSend({
|
|
790
|
-
...send,
|
|
791
|
-
// Made again, a delayed send waits only what remains of its delay.
|
|
792
|
-
...(delay !== undefined ? { delay: again && due !== undefined ? Math.max(0, due - Date.now()) : delay } : {}),
|
|
793
|
-
parameter: new Uint8Array(Buffer.from(parameter, 'base64')),
|
|
794
|
-
inputSerde: serde.binary,
|
|
795
|
-
idempotencyKey: send.idempotencyKey ?? `transaction/${id}/${index}`,
|
|
796
|
-
});
|
|
797
|
-
});
|
|
798
|
-
this.made.add(id);
|
|
799
|
-
}
|
|
800
|
-
/** The outbox as committed, but the transactions this attempt made the sends of: a commit made after them stores them first. */
|
|
801
|
-
async unstored(db) {
|
|
802
|
-
return decodeOutbox(await db.record(OUTBOX)).filter(({ id }) => !this.made.has(id));
|
|
803
|
-
}
|
|
804
|
-
/**
|
|
805
|
-
* Empty the outbox, so that a later open does not make its sends again: a
|
|
806
|
-
* commit after them, which stores them first.
|
|
807
|
-
*/
|
|
808
|
-
async flush(db) {
|
|
809
|
-
if ((await db.record(OUTBOX)).length === 0)
|
|
810
|
-
return;
|
|
811
|
-
// Read in the transaction that writes it: one that committed sends since
|
|
812
|
-
// the read above keeps them.
|
|
813
|
-
await db.transaction(async (tx) => tx.setRecord(OUTBOX, encodeOutbox(await this.unstored(tx))));
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
/** Run `handler`, then end `attempt`'s SQL session, if it opened one (see {@link Attempt.end}). */
|
|
817
|
-
export async function withAttempt(handler, attempt) {
|
|
818
|
-
let outcome;
|
|
819
|
-
try {
|
|
820
|
-
outcome = { value: await handler() };
|
|
821
|
-
}
|
|
822
|
-
catch (error) {
|
|
823
|
-
outcome = { error };
|
|
824
|
-
}
|
|
825
|
-
return attempt.end(outcome);
|
|
826
519
|
}
|
|
827
520
|
//# sourceMappingURL=session.js.map
|