@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/database.js
CHANGED
|
@@ -1,49 +1,43 @@
|
|
|
1
|
-
// A session
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// (`
|
|
1
|
+
// A session database through the addon (`native/`): SQLite-compatible SQL
|
|
2
|
+
// kept in the object state. On the VM the addon reads and writes the state
|
|
3
|
+
// itself as the VM's own actions, and a commit is one atomic group with what
|
|
4
|
+
// the transaction gave `commitWith` (`openOnVm`). Without a VM (tests) it
|
|
5
|
+
// calls a JavaScript `Store` (`open`), in the order it makes its requests.
|
|
6
|
+
//
|
|
7
|
+
// Call ordering. A `Connection` runs calls one at a time, in call order,
|
|
8
|
+
// through a promise queue (`serial`). A transaction holds the connection from
|
|
9
|
+
// `begin` to `commit` or `rollback`, and calls made meanwhile queue behind it.
|
|
10
|
+
// Inside the body, an `OpenTransaction` has its own queue, so every call the
|
|
11
|
+
// body makes runs before the commit, even one it does not await.
|
|
12
|
+
//
|
|
13
|
+
// The transaction guard refuses a `ctx.db` call from inside a transaction
|
|
14
|
+
// body with `SqlError`, because that call would wait for the body forever
|
|
15
|
+
// (see `Connection.running`).
|
|
16
|
+
//
|
|
17
|
+
// Fast paths. When nothing is queued, a call runs immediately, and if the
|
|
18
|
+
// addon answers synchronously (SQL on cached pages) the value is returned
|
|
19
|
+
// without a promise. Only this package sees such values (`...Now` methods);
|
|
20
|
+
// the public methods always return promises.
|
|
5
21
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
6
22
|
import { Buffer } from 'node:buffer';
|
|
7
23
|
import { addon as loaded } from './addon.js';
|
|
8
|
-
import { STATE_WAIT_OVER } from './vm.js';
|
|
9
|
-
import { AttemptShutDown } from './driver.js';
|
|
24
|
+
import { invalidInput, STATE_WAIT_OVER } from './vm.js';
|
|
25
|
+
import { AttemptShutDown, InvalidInput } from './driver.js';
|
|
10
26
|
/**
|
|
11
|
-
* A failure a retry would repeat: SQL
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* refused, which may have ended it (a `COMMIT` in a transaction's body, a
|
|
15
|
-
* transaction left open). A storage error, which ends the session, rejects
|
|
16
|
-
* as it is.
|
|
27
|
+
* A failure a retry would repeat: rejected SQL (undoes only that statement),
|
|
28
|
+
* a parameter that cannot bind, or a refused call, which may end the session
|
|
29
|
+
* (a `COMMIT` in a transaction body). A storage error rejects unchanged.
|
|
17
30
|
*/
|
|
18
31
|
export class SqlError extends Error {
|
|
19
32
|
name = 'SqlError';
|
|
20
33
|
}
|
|
21
|
-
/**
|
|
22
|
-
* What the addon refuses as a parameter before it runs a call (its conversion
|
|
23
|
-
* of an SQL value): a failure here is the call's own, and nothing ran.
|
|
24
|
-
*/
|
|
25
|
-
function checkParams(params) {
|
|
26
|
-
for (const param of params ?? []) {
|
|
27
|
-
const type = typeof param;
|
|
28
|
-
if (type === 'bigint' && (param > 2n ** 63n - 1n || param < -(2n ** 63n))) {
|
|
29
|
-
throw new Error('a bigint parameter exceeds 64 bits');
|
|
30
|
-
}
|
|
31
|
-
if (type === 'symbol' || type === 'function') {
|
|
32
|
-
throw new Error(`unsupported SQL value: ${type === 'symbol' ? 'Symbol' : 'Function'}`);
|
|
33
|
-
}
|
|
34
|
-
if (type === 'object' && param !== null && !(param instanceof Uint8Array)) {
|
|
35
|
-
throw new Error('unsupported SQL value: Object');
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
/** Nothing: what settles a queue's last call, and what `execute` resolves with. */
|
|
40
34
|
const nothing = () => { };
|
|
41
|
-
/** The rows
|
|
35
|
+
/** The rows as objects by column name. A repeated column name is an {@link SqlError}. */
|
|
42
36
|
function objects({ columns, rows }) {
|
|
43
37
|
const names = columns.length;
|
|
44
38
|
let twice;
|
|
45
39
|
for (let i = 1; i < names && twice === undefined; i++) {
|
|
46
|
-
// A statement has
|
|
40
|
+
// A statement has few columns: comparing pairs costs less than a Set.
|
|
47
41
|
for (let j = 0; j < i; j++) {
|
|
48
42
|
if (columns[j] === columns[i]) {
|
|
49
43
|
twice = columns[i];
|
|
@@ -54,7 +48,7 @@ function objects({ columns, rows }) {
|
|
|
54
48
|
if (twice !== undefined) {
|
|
55
49
|
throw new SqlError(`the column ${twice} is named twice: alias one (AS), or read the rows with values()`);
|
|
56
50
|
}
|
|
57
|
-
//
|
|
51
|
+
// `Object.fromEntries` makes a column named `__proto__` an own property;
|
|
58
52
|
// assignment would set the row's prototype instead.
|
|
59
53
|
if (columns.includes('__proto__')) {
|
|
60
54
|
return rows.map((row) => Object.fromEntries(columns.map((name, i) => [name, row[i]])));
|
|
@@ -68,7 +62,7 @@ function objects({ columns, rows }) {
|
|
|
68
62
|
}
|
|
69
63
|
return result;
|
|
70
64
|
}
|
|
71
|
-
//
|
|
65
|
+
// A ready result is mapped now; a throw from `map` becomes a rejection.
|
|
72
66
|
const mapped = (result, map) => {
|
|
73
67
|
if (result instanceof Promise)
|
|
74
68
|
return result.then(map);
|
|
@@ -79,15 +73,9 @@ const mapped = (result, map) => {
|
|
|
79
73
|
return Promise.reject(error);
|
|
80
74
|
}
|
|
81
75
|
};
|
|
82
|
-
/**
|
|
83
|
-
* {@link DatabaseWriter} over `run`, which runs one call's SQL and returns
|
|
84
|
-
* its rows with their columns, failing as `failure` makes its errors (as
|
|
85
|
-
* `run` makes the engine's). `run` answers with the value itself when the
|
|
86
|
-
* call was ready at once, which only this package sees: each call returns a
|
|
87
|
-
* promise.
|
|
88
|
-
*/
|
|
76
|
+
/** A {@link DatabaseWriter} over `run`, which may answer synchronously; each method returns a promise. */
|
|
89
77
|
export function sqlOver(run, failure = (error) => error) {
|
|
90
|
-
// A `run` that throws
|
|
78
|
+
// A `run` that throws becomes a rejection, as in an async function.
|
|
91
79
|
const start = (sql, params) => {
|
|
92
80
|
try {
|
|
93
81
|
return run(sql, params);
|
|
@@ -112,11 +100,7 @@ export function sqlOver(run, failure = (error) => error) {
|
|
|
112
100
|
};
|
|
113
101
|
}
|
|
114
102
|
const addon = loaded;
|
|
115
|
-
/**
|
|
116
|
-
* Open the database of `namespace` over `store`. One process-wide page cache
|
|
117
|
-
* serves every namespace. A `reader` reads beside the namespace's owner (a
|
|
118
|
-
* shared handler), the state as of open, and writes nothing.
|
|
119
|
-
*/
|
|
103
|
+
/** Open the database of `namespace` over `store`. A `reader` (a view) reads the state as of the open. */
|
|
120
104
|
export async function open(namespace, store, { reader = false } = {}) {
|
|
121
105
|
const boundary = new Boundary(store);
|
|
122
106
|
try {
|
|
@@ -127,37 +111,31 @@ export async function open(namespace, store, { reader = false } = {}) {
|
|
|
127
111
|
}
|
|
128
112
|
}
|
|
129
113
|
/**
|
|
130
|
-
* Open the database of `namespace` over the attempt
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
* are never reached. `name` names a database beside the object's own.
|
|
114
|
+
* Open the database of `namespace` over the attempt VM. The addon reads and
|
|
115
|
+
* writes the state as the VM's own actions and never calls a store; a commit
|
|
116
|
+
* is one atomic group, with what the transaction gave
|
|
117
|
+
* {@link ConnectionTransaction.commitWith}. `name` names a database beside the
|
|
118
|
+
* object database.
|
|
136
119
|
*/
|
|
137
|
-
export async function openOnVm(namespace,
|
|
138
|
-
const boundary = new Boundary(
|
|
120
|
+
export async function openOnVm(namespace, vm, { name, reader = false, keepAlive } = {}) {
|
|
121
|
+
const boundary = new Boundary(undefined, keepAlive);
|
|
139
122
|
try {
|
|
140
|
-
return new Connection(await boundary.alive(() => addon.openOnVm(namespace,
|
|
123
|
+
return new Connection(await boundary.alive(() => addon.openOnVm(namespace, vm, name, reader)), boundary);
|
|
141
124
|
}
|
|
142
125
|
catch (error) {
|
|
143
|
-
// The open reads the
|
|
144
|
-
//
|
|
145
|
-
// set: a cancellation here must still reach the handler as one.
|
|
126
|
+
// The open reads the head inside the addon, so `boundary.failed` is never
|
|
127
|
+
// set: the end of the attempt must still reach the handler as such.
|
|
146
128
|
throw stateWaitFailure(error) ?? boundary.failed?.error ?? error;
|
|
147
129
|
}
|
|
148
130
|
}
|
|
149
131
|
/**
|
|
150
|
-
* The store as the addon calls it.
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
* CancelledError, say). And a commit's sync first runs what its transaction
|
|
154
|
-
* gave {@link ConnectionTransaction.withCommit}: after the commit's writes,
|
|
155
|
-
* before anything is awaited.
|
|
132
|
+
* The store as the addon calls it. A store error crosses the addon as text and
|
|
133
|
+
* ends the session, so the first one is kept for later calls to fail with. A
|
|
134
|
+
* commit sync first runs `withCommit`. On the VM the addon calls none of it.
|
|
156
135
|
*/
|
|
157
136
|
class Boundary {
|
|
158
|
-
/** The first error of the store's. */
|
|
159
137
|
failed;
|
|
160
|
-
/** What the next sync runs first: the committing transaction
|
|
138
|
+
/** What the next sync runs first: the `withCommit` work of the committing transaction. */
|
|
161
139
|
withSync;
|
|
162
140
|
keys;
|
|
163
141
|
store;
|
|
@@ -165,44 +143,45 @@ class Boundary {
|
|
|
165
143
|
constructor(store, working) {
|
|
166
144
|
this.store = store;
|
|
167
145
|
this.working = working;
|
|
168
|
-
|
|
169
|
-
const keys = store.keys?.bind(store);
|
|
146
|
+
const keys = store?.keys?.bind(store);
|
|
170
147
|
if (keys)
|
|
171
148
|
this.keys = () => this.kept(keys);
|
|
172
149
|
}
|
|
173
150
|
get(key) {
|
|
174
|
-
return this.kept(() => this.
|
|
151
|
+
return this.kept(() => this.stored().get(key));
|
|
175
152
|
}
|
|
176
153
|
set(key, value) {
|
|
177
|
-
this.kept(() => this.
|
|
154
|
+
this.kept(() => this.stored().set(key, value));
|
|
178
155
|
}
|
|
179
156
|
clear(key) {
|
|
180
|
-
this.kept(() => this.
|
|
157
|
+
this.kept(() => this.stored().clear(key));
|
|
181
158
|
}
|
|
182
159
|
sync() {
|
|
183
160
|
return this.kept(() => {
|
|
184
161
|
const run = this.withSync;
|
|
185
162
|
this.withSync = undefined;
|
|
186
163
|
run?.();
|
|
187
|
-
return this.store.sync();
|
|
164
|
+
return this.store === undefined ? Promise.resolve() : this.store.sync();
|
|
188
165
|
});
|
|
189
166
|
}
|
|
190
|
-
/**
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
167
|
+
/** On the VM, reaching here is a bug in the addon. */
|
|
168
|
+
stored() {
|
|
169
|
+
if (this.store === undefined)
|
|
170
|
+
throw new Error('@restatedev/sessions: the VM serves the state; the addon reads none here');
|
|
171
|
+
return this.store;
|
|
172
|
+
}
|
|
173
|
+
/** A synchronous answer needs no keep-alive; a promise runs in `Stop.keepAlive`. */
|
|
195
174
|
aliveNow(call) {
|
|
196
175
|
const result = call();
|
|
197
176
|
if (!(result instanceof Promise))
|
|
198
177
|
return result;
|
|
199
178
|
return this.working === undefined ? result : this.working(() => result);
|
|
200
179
|
}
|
|
201
|
-
/** `call`, in the attempt
|
|
180
|
+
/** `call`, in the attempt keep-alive if there is one (on the VM). */
|
|
202
181
|
alive(call) {
|
|
203
182
|
return this.working === undefined ? (async () => call())() : this.working(call);
|
|
204
183
|
}
|
|
205
|
-
/** `request
|
|
184
|
+
/** Run `request`, keeping the first error, whether thrown or rejected. */
|
|
206
185
|
kept(request) {
|
|
207
186
|
const keep = (error) => {
|
|
208
187
|
this.failed ??= { error };
|
|
@@ -217,10 +196,7 @@ class Boundary {
|
|
|
217
196
|
}
|
|
218
197
|
}
|
|
219
198
|
}
|
|
220
|
-
/**
|
|
221
|
-
* SQL on a session of the addon: {@link DatabaseWriter}'s `query` and `execute`
|
|
222
|
-
* by way of its `queryColumnsNow`.
|
|
223
|
-
*/
|
|
199
|
+
/** {@link DatabaseWriter} on an addon session, built on `queryColumnsNow`. */
|
|
224
200
|
class Sql {
|
|
225
201
|
native;
|
|
226
202
|
boundary;
|
|
@@ -230,10 +206,6 @@ class Sql {
|
|
|
230
206
|
this.boundary = boundary;
|
|
231
207
|
this.over = sqlOver((s, p) => this.queryColumnsNow(s, p));
|
|
232
208
|
}
|
|
233
|
-
queryColumns(sql, params) {
|
|
234
|
-
const result = this.queryColumnsNow(sql, params);
|
|
235
|
-
return result instanceof Promise ? result : Promise.resolve(result);
|
|
236
|
-
}
|
|
237
209
|
query(sql, params) {
|
|
238
210
|
return this.over.query(sql, params);
|
|
239
211
|
}
|
|
@@ -246,7 +218,7 @@ class Sql {
|
|
|
246
218
|
execute(sql, params) {
|
|
247
219
|
return this.over.execute(sql, params);
|
|
248
220
|
}
|
|
249
|
-
/** {@link request}
|
|
221
|
+
/** {@link request} that returns a ready value synchronously, with no keep-alive. */
|
|
250
222
|
requestNow(call) {
|
|
251
223
|
let result;
|
|
252
224
|
try {
|
|
@@ -261,11 +233,7 @@ class Sql {
|
|
|
261
233
|
throw this.failure(error);
|
|
262
234
|
});
|
|
263
235
|
}
|
|
264
|
-
/**
|
|
265
|
-
* `call`'s result, or its {@link failure}: `call` makes the request, as the
|
|
266
|
-
* addon throws as it is called (arguments it cannot convert, and the error
|
|
267
|
-
* of a call that answers at once).
|
|
268
|
-
*/
|
|
236
|
+
/** The result of `call`, or its {@link failure}, whether the addon throws or rejects. */
|
|
269
237
|
request(call) {
|
|
270
238
|
let alive;
|
|
271
239
|
try {
|
|
@@ -279,56 +247,58 @@ class Sql {
|
|
|
279
247
|
});
|
|
280
248
|
}
|
|
281
249
|
/**
|
|
282
|
-
*
|
|
283
|
-
*
|
|
250
|
+
* An {@link SqlError} if a retry would repeat `error`; the store error if
|
|
251
|
+
* that ended the session. `sends`: `error` failed the commit of a
|
|
252
|
+
* transaction that sends on the VM, the one call whose failure can be the
|
|
253
|
+
* VM's refusal of a send, or the attempt's end with the session usable.
|
|
284
254
|
*/
|
|
285
|
-
failure(error) {
|
|
255
|
+
failure(error, { sends = false } = {}) {
|
|
286
256
|
if (error instanceof SqlError)
|
|
287
257
|
return error;
|
|
288
|
-
//
|
|
289
|
-
//
|
|
290
|
-
//
|
|
291
|
-
//
|
|
292
|
-
|
|
258
|
+
// On the VM the end of the attempt fails state waits inside the addon,
|
|
259
|
+
// and only its text crosses back. Use the class the driver fails with.
|
|
260
|
+
// Such a failure ends the session; an SQL error that merely names the
|
|
261
|
+
// text leaves it usable, and stays an SQL error. The commit of a
|
|
262
|
+
// transaction that sends is read so whatever the session says: a commit
|
|
263
|
+
// that wrote nothing makes its sends in a group of their own after the
|
|
264
|
+
// database's commit, and the attempt's end fails that wait with the
|
|
265
|
+
// session still usable until the end closes it.
|
|
266
|
+
const stateWait = this.native.isUsable() && !sends ? undefined : stateWaitFailure(error);
|
|
293
267
|
if (stateWait !== undefined)
|
|
294
268
|
return stateWait;
|
|
269
|
+
// A send of the commit that Restate would refuse (an empty idempotency
|
|
270
|
+
// key): the VM dropped the commit's group, and the handler gets a
|
|
271
|
+
// TerminalError (400), as from a send of its own. Only the commit's text
|
|
272
|
+
// is read so: any other call's is SQL's, which a trigger can make read so.
|
|
273
|
+
const refused = sends ? invalidInput(error) : undefined;
|
|
274
|
+
if (refused !== undefined)
|
|
275
|
+
return new InvalidInput(refused.message, { errorCode: refused.code });
|
|
295
276
|
const failed = this.boundary.failed;
|
|
296
277
|
if (failed !== undefined && !this.native.isUsable())
|
|
297
278
|
return failed.error;
|
|
279
|
+
// `InvalidArg`: the addon's refusal of a call that may have ended the
|
|
280
|
+
// session, or an argument it cannot convert; a retry would repeat either.
|
|
298
281
|
const repeats = error.code === REFUSED || this.native.isUsable();
|
|
299
282
|
return repeats ? new SqlError(error.message, { cause: error }) : error;
|
|
300
283
|
}
|
|
301
284
|
}
|
|
302
|
-
|
|
303
|
-
// ended the session (its `Refused`), and of arguments it cannot convert.
|
|
285
|
+
/** The code of the addon's errors that a retry would repeat (its `Refused`, and arguments it cannot convert). */
|
|
304
286
|
const REFUSED = 'InvalidArg';
|
|
305
|
-
/**
|
|
306
|
-
* The error of a call that failed because the attempt's state waits were
|
|
307
|
-
* failed in the addon, at the end of the attempt. `undefined` for anything
|
|
308
|
-
* else.
|
|
309
|
-
*/
|
|
287
|
+
/** `AttemptShutDown` for a call that failed because the attempt ended; else `undefined`. */
|
|
310
288
|
function stateWaitFailure(error) {
|
|
311
|
-
const message = error
|
|
312
|
-
|
|
313
|
-
return undefined;
|
|
314
|
-
if (message.includes(STATE_WAIT_OVER))
|
|
315
|
-
return new AttemptShutDown();
|
|
316
|
-
return undefined;
|
|
289
|
+
const message = error?.message;
|
|
290
|
+
return typeof message === 'string' && message.includes(STATE_WAIT_OVER) ? new AttemptShutDown() : undefined;
|
|
317
291
|
}
|
|
318
|
-
/**
|
|
319
|
-
* A session of a database: calls run one at a time, in call order, and a
|
|
320
|
-
* transaction holds the session until it commits or rolls back. Calls made
|
|
321
|
-
* meanwhile wait, but a call from inside the transaction's body is refused,
|
|
322
|
-
* as it would wait for that body: the body uses its `tx`.
|
|
323
|
-
*/
|
|
292
|
+
/** A session of a database. Call ordering and the transaction guard: see the header. */
|
|
324
293
|
export class Connection extends Sql {
|
|
325
|
-
/**
|
|
294
|
+
/**
|
|
295
|
+
* The transaction guard: the open transaction, in the async context of its
|
|
296
|
+
* body. A call from a continuation created before the transaction, which
|
|
297
|
+
* the body then awaits, is not refused and deadlocks.
|
|
298
|
+
*/
|
|
326
299
|
running = new AsyncLocalStorage();
|
|
327
|
-
/** Settles once the last call queued so far has: the next call runs after it. */
|
|
328
300
|
queue = Promise.resolve();
|
|
329
|
-
/**
|
|
330
|
-
tail;
|
|
331
|
-
/** Calls queued and not settled: with none, a call that is ready runs at once, in order. */
|
|
301
|
+
/** Calls queued and not settled. With none, a call can take the fast path. */
|
|
332
302
|
inflight = 0;
|
|
333
303
|
release = () => {
|
|
334
304
|
this.inflight--;
|
|
@@ -338,7 +308,7 @@ export class Connection extends Sql {
|
|
|
338
308
|
const result = this.requestNow(() => this.native.queryColumns(sql, params));
|
|
339
309
|
if (!(result instanceof Promise))
|
|
340
310
|
return result;
|
|
341
|
-
// Not ready:
|
|
311
|
+
// Not ready: later calls queue behind it.
|
|
342
312
|
this.inflight++;
|
|
343
313
|
this.queue = result.then(this.release, this.release);
|
|
344
314
|
return result;
|
|
@@ -346,53 +316,41 @@ export class Connection extends Sql {
|
|
|
346
316
|
return this.serial(() => this.request(() => this.native.queryColumns(sql, params)));
|
|
347
317
|
}
|
|
348
318
|
/**
|
|
349
|
-
* Run `body` as one SQL transaction:
|
|
350
|
-
*
|
|
351
|
-
*
|
|
352
|
-
* the transaction (`COMMIT`, `ROLLBACK`) ends the session. A failing
|
|
353
|
-
* COMMIT rolls back.
|
|
319
|
+
* Run `body` as one SQL transaction: once its calls settle, commit with its
|
|
320
|
+
* records, or roll back if it rejects. A `COMMIT` or `ROLLBACK` statement
|
|
321
|
+
* in it ends the session.
|
|
354
322
|
*/
|
|
355
323
|
transaction(body) {
|
|
356
|
-
|
|
357
|
-
return this.serial(async () => {
|
|
358
|
-
try {
|
|
359
|
-
return await this.run(gate, body);
|
|
360
|
-
}
|
|
361
|
-
finally {
|
|
362
|
-
if (this.tail === gate)
|
|
363
|
-
this.tail = undefined;
|
|
364
|
-
}
|
|
365
|
-
}, gate);
|
|
324
|
+
return this.serial(() => this.run(body));
|
|
366
325
|
}
|
|
367
|
-
async run(
|
|
326
|
+
async run(body) {
|
|
368
327
|
await this.request(() => this.native.begin());
|
|
369
|
-
const tx = new OpenTransaction(this.native, this.boundary
|
|
328
|
+
const tx = new OpenTransaction(this.native, this.boundary);
|
|
370
329
|
let result;
|
|
371
330
|
try {
|
|
372
331
|
result = await this.running.run(tx, () => body(tx));
|
|
373
|
-
await tx.
|
|
332
|
+
await tx.end();
|
|
374
333
|
}
|
|
375
334
|
catch (error) {
|
|
376
335
|
await tx.end();
|
|
377
336
|
await this.rollback();
|
|
378
337
|
throw error;
|
|
379
338
|
}
|
|
380
|
-
const records =
|
|
381
|
-
//
|
|
382
|
-
//
|
|
339
|
+
const records = tx.recordsSet();
|
|
340
|
+
// The commit sync runs the `withCommit` work; a commit with no writes has no sync, so it runs after.
|
|
341
|
+
// On the VM, what the body gave `commitWith` goes in the commit's atomic group instead.
|
|
383
342
|
const runs = tx.commitRuns();
|
|
343
|
+
const withCommit = tx.vmCommit();
|
|
384
344
|
this.boundary.withSync = runs;
|
|
385
345
|
let unsynced;
|
|
386
346
|
try {
|
|
387
|
-
|
|
388
|
-
// that would only run it.
|
|
389
|
-
await this.boundary.alive(() => this.native.commit(records, runs !== undefined));
|
|
347
|
+
await this.boundary.alive(() => withCommit === undefined ? this.native.commit(records) : this.native.commit(records, withCommit));
|
|
390
348
|
}
|
|
391
349
|
catch (error) {
|
|
392
|
-
// A COMMIT
|
|
393
|
-
//
|
|
350
|
+
// A failed COMMIT (a deferred constraint) leaves the transaction open:
|
|
351
|
+
// without the rollback, later calls would run inside it.
|
|
394
352
|
await this.rollback();
|
|
395
|
-
throw this.failure(error);
|
|
353
|
+
throw this.failure(error, { sends: (withCommit?.sends.length ?? 0) > 0 });
|
|
396
354
|
}
|
|
397
355
|
finally {
|
|
398
356
|
unsynced = this.boundary.withSync;
|
|
@@ -401,45 +359,33 @@ export class Connection extends Sql {
|
|
|
401
359
|
unsynced?.();
|
|
402
360
|
return result;
|
|
403
361
|
}
|
|
404
|
-
/**
|
|
405
|
-
* The record `name`, as the last commit that set it left it (see
|
|
406
|
-
* {@link ConnectionTransaction.setRecord}); empty if none did.
|
|
407
|
-
*/
|
|
362
|
+
/** The record `name` as last committed (see {@link ConnectionTransaction.setRecord}); empty if never set. */
|
|
408
363
|
record(name) {
|
|
409
364
|
return this.serial(async () => new Uint8Array(await this.request(() => this.native.record(name))));
|
|
410
365
|
}
|
|
411
|
-
/**
|
|
366
|
+
/** An SQL error leaves the session usable; a storage error ends it. */
|
|
412
367
|
isUsable() {
|
|
413
368
|
return this.native.isUsable();
|
|
414
369
|
}
|
|
415
|
-
/**
|
|
416
|
-
* End the session after the calls before it, leaving its engine to the
|
|
417
|
-
* next one. It rejects if they left a transaction open, or a failure ended
|
|
418
|
-
* the session.
|
|
419
|
-
*/
|
|
370
|
+
/** End the session after earlier calls. Rejects if a transaction is left open or a failure ended it. */
|
|
420
371
|
save() {
|
|
421
372
|
return this.serial(() => this.request(() => this.native.save()));
|
|
422
373
|
}
|
|
423
|
-
/** End the session now, whatever its state
|
|
374
|
+
/** End the session now, whatever its state. Queued calls reject. */
|
|
424
375
|
close() {
|
|
425
376
|
return this.native.close();
|
|
426
377
|
}
|
|
427
|
-
/**
|
|
428
|
-
serial(call
|
|
378
|
+
/** Queue `call` after earlier calls. Refused from the body of an open transaction (the guard). */
|
|
379
|
+
serial(call) {
|
|
429
380
|
if (this.running.getStore()?.open) {
|
|
430
381
|
return Promise.reject(new SqlError('inside a transaction, use the transaction handle its body gets'));
|
|
431
382
|
}
|
|
432
|
-
// A call queued behind the last transaction tells it so; a transaction
|
|
433
|
-
// that is itself the last one queued from now on is told by the next.
|
|
434
|
-
this.tail?.fire();
|
|
435
|
-
if (transaction !== undefined)
|
|
436
|
-
this.tail = transaction;
|
|
437
383
|
this.inflight++;
|
|
438
384
|
const result = this.queue.then(call);
|
|
439
385
|
this.queue = result.then(this.release, this.release);
|
|
440
386
|
return result;
|
|
441
387
|
}
|
|
442
|
-
/** Roll back,
|
|
388
|
+
/** Roll back, ignoring errors: the caller rethrows its own error, which explains the failure. */
|
|
443
389
|
async rollback() {
|
|
444
390
|
try {
|
|
445
391
|
await this.native.rollback();
|
|
@@ -447,73 +393,34 @@ export class Connection extends Sql {
|
|
|
447
393
|
catch { }
|
|
448
394
|
}
|
|
449
395
|
}
|
|
450
|
-
/** A
|
|
451
|
-
class Gate {
|
|
452
|
-
promise;
|
|
453
|
-
resolve;
|
|
454
|
-
constructor() {
|
|
455
|
-
this.promise = new Promise((resolve) => (this.resolve = resolve));
|
|
456
|
-
}
|
|
457
|
-
fire() {
|
|
458
|
-
this.resolve();
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
/**
|
|
462
|
-
* A {@link ConnectionTransaction} of {@link Connection.transaction}, open until its body
|
|
463
|
-
* settles. Its calls run one at a time, in call order, also when the body
|
|
464
|
-
* awaits several together, or none: each call made while it is open runs
|
|
465
|
-
* before its commit or rollback, so none outlives it.
|
|
466
|
-
*/
|
|
396
|
+
/** A {@link ConnectionTransaction}, open until its body settles. Its calls queue as the header says. */
|
|
467
397
|
class OpenTransaction extends Sql {
|
|
468
|
-
/** The records it sets, by name. */
|
|
469
398
|
records = new Map();
|
|
470
|
-
/** What runs with its commit (`withCommit`). */
|
|
471
399
|
withCommits = [];
|
|
472
|
-
/**
|
|
400
|
+
/** What commits with it on the VM (`commitWith`). */
|
|
401
|
+
committing;
|
|
473
402
|
queue = Promise.resolve();
|
|
474
403
|
inflight = 0;
|
|
475
404
|
release = () => {
|
|
476
405
|
this.inflight--;
|
|
477
406
|
};
|
|
478
|
-
/** SQL that runs with the next call made (`defer`). */
|
|
479
|
-
deferred = [];
|
|
480
407
|
ended = false;
|
|
481
|
-
queued;
|
|
482
|
-
constructor(native, boundary, queued) {
|
|
483
|
-
super(native, boundary);
|
|
484
|
-
this.queued = queued;
|
|
485
|
-
}
|
|
486
|
-
/** Whether it is open: its body runs, and holds its session. */
|
|
487
408
|
get open() {
|
|
488
409
|
return !this.ended;
|
|
489
410
|
}
|
|
490
|
-
/**
|
|
491
|
-
* End it, refusing calls from now on, once the calls made before have
|
|
492
|
-
* settled; then the records it set, as the addon's commit takes them.
|
|
493
|
-
*/
|
|
411
|
+
/** Refuse further calls; settles once earlier calls have. */
|
|
494
412
|
async end() {
|
|
495
413
|
this.ended = true;
|
|
496
414
|
await this.queue;
|
|
415
|
+
}
|
|
416
|
+
recordsSet() {
|
|
497
417
|
return Object.fromEntries(this.records);
|
|
498
418
|
}
|
|
499
419
|
queryColumnsNow(sql, params) {
|
|
500
420
|
if (this.ended)
|
|
501
421
|
return Promise.reject(new SqlError('the transaction has ended'));
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
// comes first there, and cannot be told from a failure of the SQL once it has run).
|
|
505
|
-
if (this.deferred.length > 0) {
|
|
506
|
-
try {
|
|
507
|
-
checkParams(params);
|
|
508
|
-
}
|
|
509
|
-
catch (error) {
|
|
510
|
-
return Promise.reject(this.failure(error));
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
// Taken as the call is made, not as it runs: a call made before the deferral runs before it.
|
|
514
|
-
const before = this.deferred.splice(0);
|
|
515
|
-
const call = () => before.length === 0 ? this.native.queryColumns(sql, params) : this.native.queryColumnsAfter(before, sql, params);
|
|
516
|
-
if (this.inflight === 0 && !this.ended) {
|
|
422
|
+
const call = () => this.native.queryColumns(sql, params);
|
|
423
|
+
if (this.inflight === 0) {
|
|
517
424
|
const result = this.requestNow(call);
|
|
518
425
|
if (!(result instanceof Promise))
|
|
519
426
|
return result;
|
|
@@ -523,31 +430,6 @@ class OpenTransaction extends Sql {
|
|
|
523
430
|
}
|
|
524
431
|
return this.serial(() => this.request(call));
|
|
525
432
|
}
|
|
526
|
-
defer(sql) {
|
|
527
|
-
if (this.ended || this.native.queryColumnsAfter === undefined)
|
|
528
|
-
return false;
|
|
529
|
-
this.deferred.push(sql);
|
|
530
|
-
return true;
|
|
531
|
-
}
|
|
532
|
-
undefer(sql) {
|
|
533
|
-
const at = this.deferred.lastIndexOf(sql);
|
|
534
|
-
if (at < 0)
|
|
535
|
-
return false;
|
|
536
|
-
this.deferred.splice(at, 1);
|
|
537
|
-
return true;
|
|
538
|
-
}
|
|
539
|
-
/**
|
|
540
|
-
* Refuse calls from now on, and once those made have settled, run the SQL
|
|
541
|
-
* that no call took (`defer`): the body has settled, and the commit
|
|
542
|
-
* follows. Its failure fails the transaction, as the call that would have
|
|
543
|
-
* run it would have.
|
|
544
|
-
*/
|
|
545
|
-
async drain() {
|
|
546
|
-
this.ended = true;
|
|
547
|
-
await this.queue;
|
|
548
|
-
for (const sql of this.deferred.splice(0))
|
|
549
|
-
await this.request(() => this.native.queryColumns(sql));
|
|
550
|
-
}
|
|
551
433
|
setRecord(name, value) {
|
|
552
434
|
this.refuseEnded();
|
|
553
435
|
this.records.set(name, Buffer.from(value));
|
|
@@ -556,17 +438,23 @@ class OpenTransaction extends Sql {
|
|
|
556
438
|
this.refuseEnded();
|
|
557
439
|
this.withCommits.push(run);
|
|
558
440
|
}
|
|
559
|
-
|
|
441
|
+
commitWith(commit) {
|
|
442
|
+
this.refuseEnded();
|
|
443
|
+
this.committing = commit;
|
|
444
|
+
}
|
|
445
|
+
/** What commits with it on the VM, once it ended: see {@link commitWith}. */
|
|
446
|
+
vmCommit() {
|
|
447
|
+
return this.committing;
|
|
448
|
+
}
|
|
560
449
|
commitRuns() {
|
|
561
450
|
const runs = this.withCommits;
|
|
562
451
|
return runs.length === 0 ? undefined : () => runs.forEach((run) => run());
|
|
563
452
|
}
|
|
564
453
|
record(name) {
|
|
565
|
-
//
|
|
454
|
+
// Read when called, so it is ordered with `setRecord`.
|
|
566
455
|
const set = this.records.get(name);
|
|
567
456
|
return this.serial(async () => new Uint8Array(set ?? (await this.request(() => this.native.record(name)))));
|
|
568
457
|
}
|
|
569
|
-
/** Run `call`, made while the transaction is open, once the calls before it have. */
|
|
570
458
|
serial(call) {
|
|
571
459
|
if (this.ended)
|
|
572
460
|
return Promise.reject(new SqlError('the transaction has ended'));
|