@restatedev/sessions 0.11.2 → 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 -240
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +206 -532
- 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 -629
- 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
|
-
this.listeners.clear();
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* `promise`, or a rejection once the attempt ends: an attempt that is
|
|
33
|
-
* suspended or aborted never settles what it was waiting for.
|
|
34
|
-
*/
|
|
35
|
-
race(promise) {
|
|
36
|
-
if (this.ended)
|
|
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
|
+
});
|
|
54
22
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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);
|
|
31
|
+
}
|
|
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`).
|
|
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.
|
|
89
51
|
*/
|
|
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.
|
|
95
|
-
*/
|
|
96
|
-
function commitOnly() {
|
|
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
|
-
};
|
|
165
|
-
}
|
|
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
|
-
/**
|
|
169
|
-
* Have `sql` (one statement, no parameters) run just before the next call of
|
|
170
|
-
* the transaction `tx`, in the same crossing of the addon: the statement and
|
|
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;
|
|
98
|
+
return sqlOver((sql, params) => forHandlerNow(tx.queryColumnsNow(sql, params)), handlerError);
|
|
182
99
|
}
|
|
183
100
|
/**
|
|
184
|
-
* `connection
|
|
185
|
-
*
|
|
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,71 +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
|
-
/**
|
|
282
|
-
* Write what is pending ({@link rideCommit}) in a transaction of its own, and resolve once it is stored. A
|
|
283
|
-
* transaction under way that commits first writes it, and this commits nothing; one that rolls back leaves
|
|
284
|
-
* it, and this writes it. Nothing, if nothing is pending.
|
|
285
|
-
*/
|
|
286
|
-
export async function flushRiders(db) {
|
|
287
|
-
await ATTEMPT.of(db)?.flushRiders();
|
|
288
|
-
}
|
|
289
|
-
// A database's name (`database`).
|
|
290
163
|
const DATABASE_NAME = /^[\w.-]{1,64}$/;
|
|
291
164
|
/**
|
|
292
|
-
* The database `name
|
|
293
|
-
*
|
|
294
|
-
*
|
|
295
|
-
* and ends with the attempt, as `ctx.db` does. A name is 1 to 64 letters,
|
|
296
|
-
* 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 `.`.
|
|
297
168
|
*/
|
|
298
169
|
export function database(db, name) {
|
|
299
170
|
if (!DATABASE_NAME.test(name))
|
|
@@ -303,71 +174,63 @@ export function database(db, name) {
|
|
|
303
174
|
throw new TerminalError("database takes a handler's ctx.db");
|
|
304
175
|
return attempt.database(name);
|
|
305
176
|
}
|
|
306
|
-
/** The sends
|
|
177
|
+
/** The sends a transaction body makes (`tx.send`), until the body ends. */
|
|
307
178
|
class Sends {
|
|
308
179
|
sends = [];
|
|
309
180
|
open = true;
|
|
310
|
-
send
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
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. */
|
|
316
190
|
close() {
|
|
317
191
|
this.open = false;
|
|
318
|
-
|
|
319
|
-
return undefined;
|
|
320
|
-
const now = Date.now();
|
|
321
|
-
for (const send of this.sends)
|
|
322
|
-
if (send.delay !== undefined)
|
|
323
|
-
send.due = now + send.delay;
|
|
324
|
-
return { id: randomUUID(), sends: this.sends };
|
|
192
|
+
return this.sends;
|
|
325
193
|
}
|
|
326
194
|
}
|
|
327
195
|
/**
|
|
328
|
-
* One session of
|
|
329
|
-
*
|
|
330
|
-
* 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.
|
|
331
198
|
*/
|
|
332
199
|
class Session {
|
|
333
200
|
ready;
|
|
334
|
-
/**
|
|
201
|
+
/** Set by the call that fails on an ended session: the next call opens a new one. */
|
|
335
202
|
retired = false;
|
|
336
203
|
connection;
|
|
337
|
-
/** Its connection, once its open settled. */
|
|
338
204
|
get opened() {
|
|
339
205
|
return this.connection;
|
|
340
206
|
}
|
|
341
207
|
failed = false;
|
|
342
208
|
release = () => { };
|
|
343
|
-
constructor(ready,
|
|
209
|
+
constructor(ready, ended) {
|
|
344
210
|
this.ready = ready;
|
|
345
|
-
void this.track(
|
|
211
|
+
void this.track(ended);
|
|
346
212
|
}
|
|
347
213
|
/** Whether a failure ended it. */
|
|
348
214
|
get ended() {
|
|
349
215
|
return this.failed || this.connection?.isUsable() === false;
|
|
350
216
|
}
|
|
351
|
-
/**
|
|
217
|
+
/** The connection (none if the open failed). After this, the end of the attempt does not close it. */
|
|
352
218
|
async end() {
|
|
353
219
|
const db = await this.ready.catch(() => undefined);
|
|
354
220
|
this.release();
|
|
355
221
|
return db;
|
|
356
222
|
}
|
|
357
|
-
/** Close it now. */
|
|
358
223
|
close() {
|
|
359
224
|
void this.end()
|
|
360
225
|
.then((db) => db?.close())
|
|
361
226
|
.catch(() => { });
|
|
362
227
|
}
|
|
363
|
-
async track(
|
|
228
|
+
async track(ended) {
|
|
364
229
|
try {
|
|
365
230
|
const db = await this.ready;
|
|
366
231
|
this.connection = db;
|
|
367
|
-
//
|
|
368
|
-
|
|
369
|
-
// statement runs, and the handler's later calls fail.
|
|
370
|
-
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(() => { }));
|
|
371
234
|
}
|
|
372
235
|
catch {
|
|
373
236
|
this.failed = true;
|
|
@@ -375,153 +238,80 @@ class Session {
|
|
|
375
238
|
}
|
|
376
239
|
}
|
|
377
240
|
/**
|
|
378
|
-
*
|
|
379
|
-
*
|
|
380
|
-
*
|
|
381
|
-
* database `name` ({@link database}), which has neither the object's schema
|
|
382
|
-
* 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.
|
|
383
244
|
*/
|
|
384
245
|
export class Attempt {
|
|
385
|
-
/** `ctx.db`. */
|
|
386
246
|
db;
|
|
387
|
-
|
|
388
|
-
|
|
247
|
+
host;
|
|
248
|
+
view;
|
|
389
249
|
config;
|
|
390
250
|
name;
|
|
391
|
-
/**
|
|
392
|
-
|
|
393
|
-
/** 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;
|
|
394
253
|
databases = new Map();
|
|
395
|
-
/** The session, from its first use on. */
|
|
396
254
|
session;
|
|
397
|
-
/**
|
|
255
|
+
/** Calls that have not reached the connection yet: see {@link callNow}. */
|
|
398
256
|
unhanded = 0;
|
|
399
|
-
/**
|
|
400
|
-
made = new Set();
|
|
401
|
-
/** The writes that ride the next commit, by slot ({@link rideCommit}). */
|
|
402
|
-
riders = new Map();
|
|
403
|
-
/** The transactions asked for and not finished: one that is under way writes the riders. */
|
|
404
|
-
active = 0;
|
|
405
|
-
/** The macrotask at the end of which an urgent rider is written alone, if one is set. */
|
|
406
|
-
urgentTimer;
|
|
407
|
-
/** 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. */
|
|
408
258
|
ensured = new Map();
|
|
409
259
|
ended = false;
|
|
410
|
-
|
|
411
|
-
|
|
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;
|
|
412
265
|
this.config = config;
|
|
413
266
|
this.name = name;
|
|
414
|
-
this.
|
|
267
|
+
this.sends = !view && name === undefined;
|
|
415
268
|
const base = sqlOver((sql, params) => this.askedNow(() => this.callNow((db) => db.queryColumnsNow(sql, params))), handlerError);
|
|
416
269
|
this.db = {
|
|
417
270
|
...base,
|
|
418
|
-
// A write while a rider is pending is the transaction it rides.
|
|
419
|
-
execute: (statement, params) => this.riders.size > 0
|
|
420
|
-
? this.asked(() => this.transaction((tx) => tx.execute(statement, params)))
|
|
421
|
-
: base.execute(statement, params),
|
|
422
271
|
transaction: (body) => this.asked(() => this.transaction(body)),
|
|
423
272
|
};
|
|
424
273
|
ensuring(this.db, (schemas) => this.asked(() => this.call((db) => this.ensureSchemas(db, schemas))));
|
|
425
274
|
ATTEMPT.on(this.db, this);
|
|
426
275
|
}
|
|
427
|
-
/**
|
|
276
|
+
/** See {@link database}. */
|
|
428
277
|
database(name) {
|
|
429
|
-
if (this.ended)
|
|
278
|
+
if (this.ended || this.ending)
|
|
430
279
|
throw new Error('the handler has ended: its SQL session is closed');
|
|
431
280
|
let other = this.databases.get(name);
|
|
432
281
|
if (other === undefined)
|
|
433
|
-
this.databases.set(name, (other = new Attempt(this.
|
|
282
|
+
this.databases.set(name, (other = new Attempt(this.host, this.view, this.config, name)));
|
|
434
283
|
return other.db;
|
|
435
284
|
}
|
|
436
|
-
/** {@link rideCommit}. */
|
|
437
|
-
ride(slot, write, urgent) {
|
|
438
|
-
if (this.ctx.shared || this.ended)
|
|
439
|
-
return false;
|
|
440
|
-
if (write === undefined)
|
|
441
|
-
this.riders.delete(slot);
|
|
442
|
-
else {
|
|
443
|
-
this.riders.set(slot, { write, urgent: urgent || (this.riders.get(slot)?.urgent ?? false) });
|
|
444
|
-
this.arm();
|
|
445
|
-
}
|
|
446
|
-
return true;
|
|
447
|
-
}
|
|
448
|
-
/** Have the urgent riders written at the end of this macrotask, if any is pending and none is set. */
|
|
449
|
-
arm() {
|
|
450
|
-
if (this.urgentTimer !== undefined || this.ended)
|
|
451
|
-
return;
|
|
452
|
-
if (![...this.riders.values()].some((r) => r.urgent))
|
|
453
|
-
return;
|
|
454
|
-
this.urgentTimer = setImmediate(() => {
|
|
455
|
-
this.urgentTimer = undefined;
|
|
456
|
-
// A transaction under way writes them, or re-arms as it ends.
|
|
457
|
-
if (this.ended || this.active > 0)
|
|
458
|
-
return;
|
|
459
|
-
// A failure leaves them pending, for the next commit or the flush, and is not tried again by a timer. After a
|
|
460
|
-
// success, one that came while it committed (its own timer found it under way) is set now.
|
|
461
|
-
this.transaction(async () => { }, false).then(() => this.arm(), () => { });
|
|
462
|
-
});
|
|
463
|
-
}
|
|
464
|
-
/** {@link flushRiders}, as a transaction of `db`: its commit writes them. */
|
|
465
|
-
async flushRiders() {
|
|
466
|
-
if (this.riders.size === 0)
|
|
467
|
-
return;
|
|
468
|
-
// Queued behind a transaction under way, which writes them as it commits: then there is nothing to write,
|
|
469
|
-
// and this one rolls back, which commits nothing.
|
|
470
|
-
let nothing = false;
|
|
471
|
-
try {
|
|
472
|
-
await this.db.transaction(async () => {
|
|
473
|
-
if (this.riders.size > 0)
|
|
474
|
-
return;
|
|
475
|
-
nothing = true;
|
|
476
|
-
throw new Error('no rider is pending');
|
|
477
|
-
});
|
|
478
|
-
}
|
|
479
|
-
catch (error) {
|
|
480
|
-
if (!nothing)
|
|
481
|
-
throw error;
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
285
|
/**
|
|
485
|
-
*
|
|
486
|
-
*
|
|
487
|
-
*
|
|
488
|
-
*
|
|
489
|
-
* What the handler asks for passes through here; what the session does for
|
|
490
|
-
* itself does not — the open, the object's schema, the sends a crashed
|
|
491
|
-
* attempt left unmade, emptying the outbox after a commit — and a
|
|
492
|
-
* cancellation that failed one of those would be delivered to nobody, or
|
|
493
|
-
* would report a transaction as cancelled after it committed. And it is
|
|
494
|
-
* before the call issues anything, so a call that fails with
|
|
495
|
-
* `CancelledError` wrote nothing and sent nothing: a call already under way
|
|
496
|
-
* when the cancellation arrives runs to its end, and the cancellation goes
|
|
497
|
-
* 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.
|
|
498
290
|
*/
|
|
499
291
|
asked(call) {
|
|
500
|
-
if (this.
|
|
292
|
+
if (this.host.stop.take())
|
|
501
293
|
return Promise.reject(new CancelledError());
|
|
502
294
|
return call();
|
|
503
295
|
}
|
|
504
|
-
/** {@link asked} for a call that
|
|
296
|
+
/** {@link asked} for a call that may answer synchronously ({@link callNow}). */
|
|
505
297
|
askedNow(call) {
|
|
506
|
-
if (this.
|
|
298
|
+
if (this.host.stop.take())
|
|
507
299
|
return Promise.reject(new CancelledError());
|
|
508
300
|
return call();
|
|
509
301
|
}
|
|
510
302
|
/**
|
|
511
|
-
* Open the
|
|
512
|
-
* call:
|
|
513
|
-
*
|
|
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.
|
|
514
306
|
*/
|
|
515
307
|
openNow() {
|
|
516
|
-
if (this.
|
|
308
|
+
if (this.sends && this.session === undefined)
|
|
517
309
|
this.current().ready.catch(() => { });
|
|
518
310
|
}
|
|
519
|
-
/**
|
|
520
|
-
* The handler ended with `outcome`: the key's other databases end, then
|
|
521
|
-
* this one ({@link endSession}).
|
|
522
|
-
*/
|
|
311
|
+
/** The handler ended with `outcome`. The key's other databases end first, as the handler left them. */
|
|
523
312
|
async end(outcome) {
|
|
524
|
-
//
|
|
313
|
+
// None opens from here: nothing would end it.
|
|
314
|
+
this.ending = true;
|
|
525
315
|
const databases = await Promise.allSettled([...this.databases.values()].map((d) => d.end({ value: undefined })));
|
|
526
316
|
const value = await this.endSession(outcome);
|
|
527
317
|
const failed = databases.find((d) => d.status === 'rejected');
|
|
@@ -530,83 +320,47 @@ export class Attempt {
|
|
|
530
320
|
return value;
|
|
531
321
|
}
|
|
532
322
|
/**
|
|
533
|
-
* `body` as one transaction. In the object
|
|
534
|
-
* handler, its sends commit with it
|
|
535
|
-
* commit, right after its writes and before it waits for anything
|
|
536
|
-
* (`withCommit`): Restate stores an attempt's commands in order, so they
|
|
537
|
-
* are stored only if the commit is, and whatever fails the commit's wait
|
|
538
|
-
* (the attempt's end, say) comes after them. A second commit empties the outbox
|
|
539
|
-
* before `transaction` resolves: left until the handler's end, they would
|
|
540
|
-
* be made again by an attempt that resumes a long wait (an approval), past
|
|
541
|
-
* 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`).
|
|
542
325
|
*/
|
|
543
|
-
async transaction(body
|
|
544
|
-
this.
|
|
545
|
-
|
|
546
|
-
return await this.transacted(body);
|
|
547
|
-
}
|
|
548
|
-
finally {
|
|
549
|
-
this.active--;
|
|
550
|
-
// What it left pending (it rolled back, or the rider came after it ran them) is for the end of this macrotask.
|
|
551
|
-
if (rearm)
|
|
552
|
-
this.arm();
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
async transacted(body) {
|
|
556
|
-
let outgoing;
|
|
557
|
-
// The riders this transaction wrote: pending until it has committed.
|
|
558
|
-
let rode = [];
|
|
559
|
-
const value = await this.call((db) => db.transaction(async (handle) => {
|
|
560
|
-
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;
|
|
561
329
|
const tx = { ...forBody(handle), send: sends?.send ?? refusedSend };
|
|
562
|
-
|
|
563
|
-
DEFERRED.on(tx, handle);
|
|
564
|
-
if (!this.ctx.shared)
|
|
565
|
-
RESET.on(tx, () => this.reset(handle));
|
|
330
|
+
let made = [];
|
|
566
331
|
let result;
|
|
567
332
|
try {
|
|
568
333
|
result = await body(tx);
|
|
569
334
|
}
|
|
570
335
|
finally {
|
|
571
|
-
|
|
572
|
-
}
|
|
573
|
-
// After the body, which may have registered one (a transaction held open for more work), and before the commit.
|
|
574
|
-
if (this.riders.size > 0) {
|
|
575
|
-
rode = [...this.riders];
|
|
576
|
-
for (const [, { write }] of rode)
|
|
577
|
-
await write(tx);
|
|
336
|
+
made = sends?.close() ?? [];
|
|
578
337
|
}
|
|
579
|
-
if (this.
|
|
580
|
-
|
|
338
|
+
if (this.sends)
|
|
339
|
+
this.commitSends(handle, made);
|
|
581
340
|
return result;
|
|
582
341
|
}));
|
|
583
|
-
// One registered since is for the next commit.
|
|
584
|
-
for (const [slot, pending] of rode)
|
|
585
|
-
if (this.riders.get(slot) === pending)
|
|
586
|
-
this.riders.delete(slot);
|
|
587
|
-
if (outgoing !== undefined)
|
|
588
|
-
await this.call((db) => this.flush(db));
|
|
589
|
-
return value;
|
|
590
342
|
}
|
|
591
|
-
/**
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
outbox.push(outgoing);
|
|
600
|
-
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;
|
|
601
351
|
}
|
|
602
|
-
|
|
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
|
+
});
|
|
603
359
|
}
|
|
604
360
|
/**
|
|
605
|
-
* `call
|
|
606
|
-
*
|
|
607
|
-
*
|
|
608
|
-
* So the failure of an open made as the attempt started goes to the first
|
|
609
|
-
* 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.
|
|
610
364
|
*/
|
|
611
365
|
async call(call) {
|
|
612
366
|
const session = this.current();
|
|
@@ -631,11 +385,8 @@ export class Attempt {
|
|
|
631
385
|
}
|
|
632
386
|
}
|
|
633
387
|
/**
|
|
634
|
-
* {@link call}
|
|
635
|
-
*
|
|
636
|
-
* is for a session that is open, and with no call before it still to reach
|
|
637
|
-
* the connection (a call made before it, which waits for the session, must
|
|
638
|
-
* 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.
|
|
639
390
|
*/
|
|
640
391
|
callNow(call) {
|
|
641
392
|
const session = this.session;
|
|
@@ -643,7 +394,7 @@ export class Attempt {
|
|
|
643
394
|
if (this.unhanded > 0 || session === undefined || db === undefined || session.retired || this.ended) {
|
|
644
395
|
return this.call(async (connection) => call(connection));
|
|
645
396
|
}
|
|
646
|
-
// As `call
|
|
397
|
+
// As in `call`, the failing call retires a session that a failure ended.
|
|
647
398
|
const failure = (error) => {
|
|
648
399
|
if (session.ended)
|
|
649
400
|
session.retired = true;
|
|
@@ -662,7 +413,7 @@ export class Attempt {
|
|
|
662
413
|
})
|
|
663
414
|
: result;
|
|
664
415
|
}
|
|
665
|
-
/** The session, opening one if there is none
|
|
416
|
+
/** The session, opening a new one if there is none or it was retired. */
|
|
666
417
|
current() {
|
|
667
418
|
if (this.ended)
|
|
668
419
|
throw new Error('the handler has ended: its SQL session is closed');
|
|
@@ -673,46 +424,37 @@ export class Attempt {
|
|
|
673
424
|
return this.session;
|
|
674
425
|
}
|
|
675
426
|
open() {
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
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)}`;
|
|
684
436
|
const namespace = this.name === undefined ? key : `${key}/${this.name}`;
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
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
|
+
}
|
|
694
448
|
}
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
: 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');
|
|
700
453
|
try {
|
|
701
|
-
// A
|
|
702
|
-
if (
|
|
454
|
+
// A write in a view fails instead of vanishing with the attempt.
|
|
455
|
+
if (view)
|
|
703
456
|
await db.execute('PRAGMA query_only = 1');
|
|
704
|
-
|
|
705
|
-
// What a crash left unmade; an open again in this attempt finds what
|
|
706
|
-
// this attempt made, stored before it, as made.
|
|
707
|
-
const left = decodeOutbox(await db.record(OUTBOX));
|
|
708
|
-
for (const outgoing of left)
|
|
709
|
-
if (!this.made.has(outgoing.id))
|
|
710
|
-
this.make(outgoing, true);
|
|
711
|
-
// Emptied at once, as a transaction's own sends are (see `transaction`).
|
|
712
|
-
if (left.length > 0)
|
|
713
|
-
await this.flush(db);
|
|
714
|
-
}
|
|
715
|
-
// 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.
|
|
716
458
|
const own = this.ownSchema();
|
|
717
459
|
if (own)
|
|
718
460
|
await this.ensureSchemas(db, [own]);
|
|
@@ -724,17 +466,12 @@ export class Attempt {
|
|
|
724
466
|
return db;
|
|
725
467
|
}
|
|
726
468
|
/**
|
|
727
|
-
* End the session, then settle as the handler did
|
|
728
|
-
*
|
|
729
|
-
*
|
|
730
|
-
* A failure to end the session fails a handler that succeeded, which a
|
|
731
|
-
* 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).
|
|
732
472
|
*/
|
|
733
473
|
async endSession(outcome) {
|
|
734
474
|
this.ended = true;
|
|
735
|
-
if (this.urgentTimer !== undefined)
|
|
736
|
-
clearImmediate(this.urgentTimer);
|
|
737
|
-
this.urgentTimer = undefined;
|
|
738
475
|
const failed = await this.close().then(() => undefined, (error) => ({ error }));
|
|
739
476
|
if ('error' in outcome)
|
|
740
477
|
throw handlerError(outcome.error);
|
|
@@ -743,39 +480,22 @@ export class Attempt {
|
|
|
743
480
|
return outcome.value;
|
|
744
481
|
}
|
|
745
482
|
/**
|
|
746
|
-
* Close the session
|
|
747
|
-
*
|
|
748
|
-
* ("is gone"), which is retried. Another is saved, its outbox emptied. One
|
|
749
|
-
* that a failure ended closes, and the object's own database is opened
|
|
750
|
-
* again and saved: it may hold sends unmade (a crash left them, and this
|
|
751
|
-
* attempt's open failed) or made and not emptied (the commit's wait
|
|
752
|
-
* failed), and no attempt may follow this one (a cancelled invocation's),
|
|
753
|
-
* 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.
|
|
754
485
|
*/
|
|
755
486
|
async close() {
|
|
756
487
|
if (this.session === undefined)
|
|
757
488
|
return;
|
|
758
489
|
const db = await this.session.end();
|
|
759
|
-
if (this.
|
|
490
|
+
if (this.view)
|
|
760
491
|
return db?.close();
|
|
761
492
|
if (db?.isUsable())
|
|
762
493
|
return this.save(db);
|
|
763
494
|
await db?.close().catch(() => { });
|
|
764
|
-
if (!this.hasOutbox)
|
|
765
|
-
return;
|
|
766
|
-
const again = this.open();
|
|
767
|
-
try {
|
|
768
|
-
await this.save(await again.ready);
|
|
769
|
-
}
|
|
770
|
-
finally {
|
|
771
|
-
void again.end();
|
|
772
|
-
}
|
|
773
495
|
}
|
|
774
|
-
/**
|
|
496
|
+
/** Save the session. The session closes if that fails. */
|
|
775
497
|
async save(db) {
|
|
776
498
|
try {
|
|
777
|
-
if (this.hasOutbox)
|
|
778
|
-
await this.flush(db);
|
|
779
499
|
await db.save();
|
|
780
500
|
}
|
|
781
501
|
catch (error) {
|
|
@@ -783,64 +503,18 @@ export class Attempt {
|
|
|
783
503
|
throw error;
|
|
784
504
|
}
|
|
785
505
|
}
|
|
786
|
-
/** The object
|
|
506
|
+
/** The object schema. The key's other databases do not get it. */
|
|
787
507
|
ownSchema() {
|
|
788
508
|
return this.name === undefined ? this.config.schema : undefined;
|
|
789
509
|
}
|
|
790
|
-
/**
|
|
791
|
-
async reset(handle) {
|
|
792
|
-
const own = this.ownSchema();
|
|
793
|
-
const schemas = [...(own ? [own] : []), ...[...this.ensured.values()].filter((s) => s !== own)];
|
|
794
|
-
await dropAll(handle, schemas);
|
|
795
|
-
}
|
|
796
|
-
/** 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. */
|
|
797
511
|
async ensureSchemas(db, schemas) {
|
|
798
512
|
const lacking = schemas.filter((s) => !this.ensured.has(s.name));
|
|
799
513
|
if (lacking.length === 0)
|
|
800
514
|
return;
|
|
801
|
-
await apply(db, lacking, { reader: this.
|
|
515
|
+
await apply(db, lacking, { reader: this.view });
|
|
802
516
|
for (const s of lacking)
|
|
803
517
|
this.ensured.set(s.name, s);
|
|
804
518
|
}
|
|
805
|
-
/** 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. */
|
|
806
|
-
make({ id, sends }, again = false) {
|
|
807
|
-
sends.forEach(({ parameter, due, delay, ...send }, index) => {
|
|
808
|
-
this.ctx.genericSend({
|
|
809
|
-
...send,
|
|
810
|
-
// Made again, a delayed send waits only what remains of its delay.
|
|
811
|
-
...(delay !== undefined ? { delay: again && due !== undefined ? Math.max(0, due - Date.now()) : delay } : {}),
|
|
812
|
-
parameter: new Uint8Array(Buffer.from(parameter, 'base64')),
|
|
813
|
-
inputSerde: serde.binary,
|
|
814
|
-
idempotencyKey: send.idempotencyKey ?? `transaction/${id}/${index}`,
|
|
815
|
-
});
|
|
816
|
-
});
|
|
817
|
-
this.made.add(id);
|
|
818
|
-
}
|
|
819
|
-
/** The outbox as committed, but the transactions this attempt made the sends of: a commit made after them stores them first. */
|
|
820
|
-
async unstored(db) {
|
|
821
|
-
return decodeOutbox(await db.record(OUTBOX)).filter(({ id }) => !this.made.has(id));
|
|
822
|
-
}
|
|
823
|
-
/**
|
|
824
|
-
* Empty the outbox, so that a later open does not make its sends again: a
|
|
825
|
-
* commit after them, which stores them first.
|
|
826
|
-
*/
|
|
827
|
-
async flush(db) {
|
|
828
|
-
if ((await db.record(OUTBOX)).length === 0)
|
|
829
|
-
return;
|
|
830
|
-
// Read in the transaction that writes it: one that committed sends since
|
|
831
|
-
// the read above keeps them.
|
|
832
|
-
await db.transaction(async (tx) => tx.setRecord(OUTBOX, encodeOutbox(await this.unstored(tx))));
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
/** Run `handler`, then end `attempt`'s SQL session, if it opened one (see {@link Attempt.end}). */
|
|
836
|
-
export async function withAttempt(handler, attempt) {
|
|
837
|
-
let outcome;
|
|
838
|
-
try {
|
|
839
|
-
outcome = { value: await handler() };
|
|
840
|
-
}
|
|
841
|
-
catch (error) {
|
|
842
|
-
outcome = { error };
|
|
843
|
-
}
|
|
844
|
-
return attempt.end(outcome);
|
|
845
519
|
}
|
|
846
520
|
//# sourceMappingURL=session.js.map
|