@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/src/database.ts
CHANGED
|
@@ -1,12 +1,28 @@
|
|
|
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.ts';
|
|
8
|
-
import { STATE_WAIT_OVER, type Vm } from './vm.ts';
|
|
9
|
-
import { AttemptShutDown } from './driver.ts';
|
|
24
|
+
import { invalidInput, STATE_WAIT_OVER, type Vm, type VmCommit } from './vm.ts';
|
|
25
|
+
import { AttemptShutDown, InvalidInput } from './driver.ts';
|
|
10
26
|
|
|
11
27
|
/** An SQL value. Integers come back as numbers, or as bigints beyond 2^53. */
|
|
12
28
|
export type SqlValue = null | number | bigint | string | Uint8Array;
|
|
@@ -14,77 +30,52 @@ export type SqlValue = null | number | bigint | string | Uint8Array;
|
|
|
14
30
|
/** An SQL parameter: an `SqlValue`, or a boolean, stored as 0 or 1. */
|
|
15
31
|
export type SqlParam = SqlValue | boolean;
|
|
16
32
|
|
|
17
|
-
|
|
18
|
-
export interface SqlQueryResult {
|
|
33
|
+
interface SqlQueryResult {
|
|
19
34
|
columns: string[];
|
|
20
35
|
rows: SqlValue[][];
|
|
21
36
|
}
|
|
22
37
|
|
|
23
38
|
/**
|
|
24
|
-
* A failure a retry would repeat: SQL
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* refused, which may have ended it (a `COMMIT` in a transaction's body, a
|
|
28
|
-
* transaction left open). A storage error, which ends the session, rejects
|
|
29
|
-
* as it is.
|
|
39
|
+
* A failure a retry would repeat: rejected SQL (undoes only that statement),
|
|
40
|
+
* a parameter that cannot bind, or a refused call, which may end the session
|
|
41
|
+
* (a `COMMIT` in a transaction body). A storage error rejects unchanged.
|
|
30
42
|
*/
|
|
31
43
|
export class SqlError extends Error {
|
|
32
44
|
override name = 'SqlError';
|
|
33
45
|
}
|
|
34
46
|
|
|
35
|
-
/** A row as an object, by column name. */
|
|
36
47
|
export type Row = Record<string, SqlValue>;
|
|
37
48
|
|
|
38
|
-
/** Reads of a database, or of one
|
|
49
|
+
/** Reads of a database, or of one of its transactions. */
|
|
39
50
|
export interface DatabaseReader {
|
|
40
51
|
/**
|
|
41
|
-
* The rows of one statement, each an object by column name
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
52
|
+
* The rows of one statement, each an object by column name. `T` declares
|
|
53
|
+
* the row shape, unchecked: integers past 2^53 come back as bigints, and
|
|
54
|
+
* booleans as 0 or 1. Columns are named as SQL names them (an expression
|
|
55
|
+
* needs `AS`). Two columns with the same name are an SQL error (from
|
|
56
|
+
* `ctx.db`, a `TerminalError`): alias them, or use {@link values}.
|
|
46
57
|
*/
|
|
47
58
|
query<T = Row>(sql: string, params?: SqlParam[]): Promise<T[]>;
|
|
48
59
|
/** The first row of {@link query}, or `undefined` when there is none. */
|
|
49
60
|
get<T = Row>(sql: string, params?: SqlParam[]): Promise<T | undefined>;
|
|
50
|
-
/** The rows
|
|
61
|
+
/** The rows as arrays, in column order: for adapters, and for columns that share a name. */
|
|
51
62
|
values(sql: string, params?: SqlParam[]): Promise<SqlValue[][]>;
|
|
52
63
|
}
|
|
53
64
|
|
|
54
|
-
/** SQL
|
|
65
|
+
/** SQL on a database, or on one of its transactions. */
|
|
55
66
|
export interface DatabaseWriter extends DatabaseReader {
|
|
56
67
|
/** Run SQL (one or more statements), discarding rows; parameters only with a single statement. */
|
|
57
68
|
execute(sql: string, params?: SqlParam[]): Promise<void>;
|
|
58
69
|
}
|
|
59
70
|
|
|
60
|
-
/**
|
|
61
|
-
* What the addon refuses as a parameter before it runs a call (its conversion
|
|
62
|
-
* of an SQL value): a failure here is the call's own, and nothing ran.
|
|
63
|
-
*/
|
|
64
|
-
function checkParams(params: SqlParam[] | undefined): void {
|
|
65
|
-
for (const param of params ?? []) {
|
|
66
|
-
const type = typeof param;
|
|
67
|
-
if (type === 'bigint' && ((param as bigint) > 2n ** 63n - 1n || (param as bigint) < -(2n ** 63n))) {
|
|
68
|
-
throw new Error('a bigint parameter exceeds 64 bits');
|
|
69
|
-
}
|
|
70
|
-
if (type === 'symbol' || type === 'function') {
|
|
71
|
-
throw new Error(`unsupported SQL value: ${type === 'symbol' ? 'Symbol' : 'Function'}`);
|
|
72
|
-
}
|
|
73
|
-
if (type === 'object' && param !== null && !(param instanceof Uint8Array)) {
|
|
74
|
-
throw new Error('unsupported SQL value: Object');
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Nothing: what settles a queue's last call, and what `execute` resolves with. */
|
|
80
71
|
const nothing = (): void => {};
|
|
81
72
|
|
|
82
|
-
/** The rows
|
|
73
|
+
/** The rows as objects by column name. A repeated column name is an {@link SqlError}. */
|
|
83
74
|
function objects({ columns, rows }: SqlQueryResult): Row[] {
|
|
84
75
|
const names = columns.length;
|
|
85
76
|
let twice: string | undefined;
|
|
86
77
|
for (let i = 1; i < names && twice === undefined; i++) {
|
|
87
|
-
// A statement has
|
|
78
|
+
// A statement has few columns: comparing pairs costs less than a Set.
|
|
88
79
|
for (let j = 0; j < i; j++) {
|
|
89
80
|
if (columns[j] === columns[i]) {
|
|
90
81
|
twice = columns[i];
|
|
@@ -95,7 +86,7 @@ function objects({ columns, rows }: SqlQueryResult): Row[] {
|
|
|
95
86
|
if (twice !== undefined) {
|
|
96
87
|
throw new SqlError(`the column ${twice} is named twice: alias one (AS), or read the rows with values()`);
|
|
97
88
|
}
|
|
98
|
-
//
|
|
89
|
+
// `Object.fromEntries` makes a column named `__proto__` an own property;
|
|
99
90
|
// assignment would set the row's prototype instead.
|
|
100
91
|
if (columns.includes('__proto__')) {
|
|
101
92
|
return rows.map((row) => Object.fromEntries(columns.map((name, i) => [name, row[i]!])));
|
|
@@ -109,7 +100,7 @@ function objects({ columns, rows }: SqlQueryResult): Row[] {
|
|
|
109
100
|
return result;
|
|
110
101
|
}
|
|
111
102
|
|
|
112
|
-
//
|
|
103
|
+
// A ready result is mapped now; a throw from `map` becomes a rejection.
|
|
113
104
|
const mapped = <T>(result: Answer<SqlQueryResult>, map: (result: SqlQueryResult) => T): Promise<T> => {
|
|
114
105
|
if (result instanceof Promise) return result.then(map);
|
|
115
106
|
try {
|
|
@@ -119,18 +110,12 @@ const mapped = <T>(result: Answer<SqlQueryResult>, map: (result: SqlQueryResult)
|
|
|
119
110
|
}
|
|
120
111
|
};
|
|
121
112
|
|
|
122
|
-
/**
|
|
123
|
-
* {@link DatabaseWriter} over `run`, which runs one call's SQL and returns
|
|
124
|
-
* its rows with their columns, failing as `failure` makes its errors (as
|
|
125
|
-
* `run` makes the engine's). `run` answers with the value itself when the
|
|
126
|
-
* call was ready at once, which only this package sees: each call returns a
|
|
127
|
-
* promise.
|
|
128
|
-
*/
|
|
113
|
+
/** A {@link DatabaseWriter} over `run`, which may answer synchronously; each method returns a promise. */
|
|
129
114
|
export function sqlOver(
|
|
130
115
|
run: (sql: string, params?: SqlParam[]) => Answer<SqlQueryResult>,
|
|
131
116
|
failure: (error: unknown) => unknown = (error) => error,
|
|
132
117
|
): DatabaseWriter {
|
|
133
|
-
// A `run` that throws
|
|
118
|
+
// A `run` that throws becomes a rejection, as in an async function.
|
|
134
119
|
const start = (sql: string, params?: SqlParam[]): Answer<SqlQueryResult> => {
|
|
135
120
|
try {
|
|
136
121
|
return run(sql, params);
|
|
@@ -155,43 +140,28 @@ export function sqlOver(
|
|
|
155
140
|
}
|
|
156
141
|
|
|
157
142
|
/**
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
* since the last sync and loses the rest. `get` returns the stored value, or
|
|
162
|
-
* this request's own latest write; `undefined` or `null` when absent.
|
|
143
|
+
* The object state as a key/value store. `sync` resolves once every earlier
|
|
144
|
+
* write is stored. Writes are stored in order, so a crash keeps a prefix of
|
|
145
|
+
* them. `get` sees this request's own writes; absent is `undefined` or `null`.
|
|
163
146
|
*/
|
|
164
147
|
export interface Store {
|
|
165
148
|
get(key: string): Promise<Uint8Array | null | undefined>;
|
|
166
149
|
set(key: string, value: Uint8Array): void;
|
|
167
150
|
clear(key: string): void;
|
|
168
151
|
sync(): Promise<void>;
|
|
169
|
-
/**
|
|
170
|
-
* Every key, as `ctx.stateKeys()`: then a commit that checkpoints deletes
|
|
171
|
-
* the packs no checkpoint needs any more. A store without it keeps them.
|
|
172
|
-
*/
|
|
152
|
+
/** Every key. With it, a checkpoint deletes packs no checkpoint needs; without it they stay. */
|
|
173
153
|
keys?(): Promise<string[]>;
|
|
174
154
|
}
|
|
175
155
|
|
|
176
|
-
/**
|
|
177
|
-
interface
|
|
178
|
-
open(namespace: string, store: Store, reader: boolean): Promise<NativeSession>;
|
|
179
|
-
openOnVm(namespace: string, store: Store, vm: Vm, name: string | undefined, reader: boolean): Promise<NativeSession>;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* A session of the addon: one call at a time holds it. A transaction's body
|
|
184
|
-
* runs between `begin` and `commit` (or `rollback`). A call answers at once
|
|
185
|
-
* with its value (or throws) when it needs nothing from the store, such as
|
|
186
|
-
* SQL on cached pages, and with a promise when it waits for the store.
|
|
187
|
-
*/
|
|
188
|
-
interface NativeSession {
|
|
156
|
+
/** An addon session. A call that needs nothing from the store returns its value or throws. */
|
|
157
|
+
export interface NativeSession {
|
|
189
158
|
queryColumns(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
|
|
190
|
-
/** `queryColumns`, after `before`'s statements in the same call; absent in an addon without it. */
|
|
191
|
-
queryColumnsAfter?(before: string[], sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
|
|
192
159
|
begin(): Answer<void>;
|
|
193
|
-
/**
|
|
194
|
-
|
|
160
|
+
/**
|
|
161
|
+
* On the VM, `withCommit` is what commits with the transaction: its sends,
|
|
162
|
+
* inside the commit's atomic group (see {@link ConnectionTransaction.commitWith}).
|
|
163
|
+
*/
|
|
164
|
+
commit(records: Record<string, Buffer>, withCommit?: VmCommit): Answer<void>;
|
|
195
165
|
rollback(): Answer<void>;
|
|
196
166
|
record(name: string): Answer<Buffer>;
|
|
197
167
|
isUsable(): boolean;
|
|
@@ -199,23 +169,26 @@ interface NativeSession {
|
|
|
199
169
|
close(): Promise<void>;
|
|
200
170
|
}
|
|
201
171
|
|
|
202
|
-
/** A value, or a promise of it: `await` takes either. */
|
|
203
172
|
type Answer<T> = T | Promise<T>;
|
|
204
173
|
|
|
205
|
-
/**
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
export type Working = <T>(fn: () => T | Promise<T>) => Promise<T>;
|
|
174
|
+
/** The addon (`native/src/node.rs`). */
|
|
175
|
+
interface Addon {
|
|
176
|
+
open(namespace: string, store: Store, reader: boolean): Promise<NativeSession>;
|
|
177
|
+
openOnVm(namespace: string, vm: Vm, name: string | undefined, reader: boolean): Promise<NativeSession>;
|
|
178
|
+
}
|
|
211
179
|
|
|
212
180
|
const addon = loaded as unknown as Addon;
|
|
213
181
|
|
|
214
|
-
/**
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
182
|
+
/** `ctx.working` (see stop.ts). */
|
|
183
|
+
export type Working = <T>(fn: () => T | Promise<T>) => Promise<T>;
|
|
184
|
+
|
|
185
|
+
/** `ctx.stoppable` (see stop.ts). */
|
|
186
|
+
export type Stoppable = <T>(fn: (signal: AbortSignal) => T | Promise<T>) => Promise<T>;
|
|
187
|
+
|
|
188
|
+
/** `ctx.suspendable` (see stop.ts). */
|
|
189
|
+
export type Suspendable = <T>(fn: () => T | Promise<T>) => Promise<T>;
|
|
190
|
+
|
|
191
|
+
/** Open the database of `namespace` over `store`. A `reader` (a view) reads the state as of the open. */
|
|
219
192
|
export async function open(namespace: string, store: Store, { reader = false } = {}): Promise<Connection> {
|
|
220
193
|
const boundary = new Boundary(store);
|
|
221
194
|
try {
|
|
@@ -226,65 +199,57 @@ export async function open(namespace: string, store: Store, { reader = false } =
|
|
|
226
199
|
}
|
|
227
200
|
|
|
228
201
|
/**
|
|
229
|
-
* Open the database of `namespace` over the attempt
|
|
230
|
-
*
|
|
231
|
-
*
|
|
232
|
-
*
|
|
233
|
-
*
|
|
234
|
-
* are never reached. `name` names a database beside the object's own.
|
|
202
|
+
* Open the database of `namespace` over the attempt VM. The addon reads and
|
|
203
|
+
* writes the state as the VM's own actions and never calls a store; a commit
|
|
204
|
+
* is one atomic group, with what the transaction gave
|
|
205
|
+
* {@link ConnectionTransaction.commitWith}. `name` names a database beside the
|
|
206
|
+
* object database.
|
|
235
207
|
*/
|
|
236
208
|
export async function openOnVm(
|
|
237
209
|
namespace: string,
|
|
238
|
-
store: Store,
|
|
239
210
|
vm: Vm,
|
|
240
|
-
{ name, reader = false,
|
|
211
|
+
{ name, reader = false, keepAlive }: { name?: string; reader?: boolean; keepAlive?: Working } = {},
|
|
241
212
|
): Promise<Connection> {
|
|
242
|
-
const boundary = new Boundary(
|
|
213
|
+
const boundary = new Boundary(undefined, keepAlive);
|
|
243
214
|
try {
|
|
244
|
-
return new Connection(await boundary.alive(() => addon.openOnVm(namespace,
|
|
215
|
+
return new Connection(await boundary.alive(() => addon.openOnVm(namespace, vm, name, reader)), boundary);
|
|
245
216
|
} catch (error) {
|
|
246
|
-
// The open reads the
|
|
247
|
-
//
|
|
248
|
-
// set: a cancellation here must still reach the handler as one.
|
|
217
|
+
// The open reads the head inside the addon, so `boundary.failed` is never
|
|
218
|
+
// set: the end of the attempt must still reach the handler as such.
|
|
249
219
|
throw stateWaitFailure(error) ?? boundary.failed?.error ?? error;
|
|
250
220
|
}
|
|
251
221
|
}
|
|
252
222
|
|
|
253
223
|
/**
|
|
254
|
-
* The store as the addon calls it.
|
|
255
|
-
*
|
|
256
|
-
*
|
|
257
|
-
* CancelledError, say). And a commit's sync first runs what its transaction
|
|
258
|
-
* gave {@link ConnectionTransaction.withCommit}: after the commit's writes,
|
|
259
|
-
* before anything is awaited.
|
|
224
|
+
* The store as the addon calls it. A store error crosses the addon as text and
|
|
225
|
+
* ends the session, so the first one is kept for later calls to fail with. A
|
|
226
|
+
* commit sync first runs `withCommit`. On the VM the addon calls none of it.
|
|
260
227
|
*/
|
|
261
228
|
class Boundary implements Store {
|
|
262
|
-
/** The first error of the store's. */
|
|
263
229
|
failed: { error: unknown } | undefined;
|
|
264
|
-
/** What the next sync runs first: the committing transaction
|
|
230
|
+
/** What the next sync runs first: the `withCommit` work of the committing transaction. */
|
|
265
231
|
withSync: (() => void) | undefined;
|
|
266
232
|
readonly keys?: () => Promise<string[]>;
|
|
267
|
-
private readonly store: Store;
|
|
233
|
+
private readonly store: Store | undefined;
|
|
268
234
|
private readonly working: Working | undefined;
|
|
269
235
|
|
|
270
|
-
constructor(store: Store, working?: Working) {
|
|
236
|
+
constructor(store: Store | undefined, working?: Working) {
|
|
271
237
|
this.store = store;
|
|
272
238
|
this.working = working;
|
|
273
|
-
|
|
274
|
-
const keys = store.keys?.bind(store);
|
|
239
|
+
const keys = store?.keys?.bind(store);
|
|
275
240
|
if (keys) this.keys = () => this.kept(keys);
|
|
276
241
|
}
|
|
277
242
|
|
|
278
243
|
get(key: string) {
|
|
279
|
-
return this.kept(() => this.
|
|
244
|
+
return this.kept(() => this.stored().get(key));
|
|
280
245
|
}
|
|
281
246
|
|
|
282
247
|
set(key: string, value: Uint8Array) {
|
|
283
|
-
this.kept(() => this.
|
|
248
|
+
this.kept(() => this.stored().set(key, value));
|
|
284
249
|
}
|
|
285
250
|
|
|
286
251
|
clear(key: string) {
|
|
287
|
-
this.kept(() => this.
|
|
252
|
+
this.kept(() => this.stored().clear(key));
|
|
288
253
|
}
|
|
289
254
|
|
|
290
255
|
sync() {
|
|
@@ -292,27 +257,30 @@ class Boundary implements Store {
|
|
|
292
257
|
const run = this.withSync;
|
|
293
258
|
this.withSync = undefined;
|
|
294
259
|
run?.();
|
|
295
|
-
return this.store.sync();
|
|
260
|
+
return this.store === undefined ? Promise.resolve() : this.store.sync();
|
|
296
261
|
});
|
|
297
262
|
}
|
|
298
263
|
|
|
299
|
-
/**
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
264
|
+
/** On the VM, reaching here is a bug in the addon. */
|
|
265
|
+
private stored(): Store {
|
|
266
|
+
if (this.store === undefined)
|
|
267
|
+
throw new Error('@restatedev/sessions: the VM serves the state; the addon reads none here');
|
|
268
|
+
return this.store;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** A synchronous answer needs no keep-alive; a promise runs in `Stop.keepAlive`. */
|
|
304
272
|
aliveNow<T>(call: () => Answer<T>): Answer<T> {
|
|
305
273
|
const result = call();
|
|
306
274
|
if (!(result instanceof Promise)) return result;
|
|
307
275
|
return this.working === undefined ? result : this.working(() => result);
|
|
308
276
|
}
|
|
309
277
|
|
|
310
|
-
/** `call`, in the attempt
|
|
278
|
+
/** `call`, in the attempt keep-alive if there is one (on the VM). */
|
|
311
279
|
alive<T>(call: () => T | Promise<T>): Promise<T> {
|
|
312
280
|
return this.working === undefined ? (async () => call())() : this.working(call);
|
|
313
281
|
}
|
|
314
282
|
|
|
315
|
-
/** `request
|
|
283
|
+
/** Run `request`, keeping the first error, whether thrown or rejected. */
|
|
316
284
|
private kept<T>(request: () => T): T {
|
|
317
285
|
const keep = (error: unknown): never => {
|
|
318
286
|
this.failed ??= { error };
|
|
@@ -327,10 +295,7 @@ class Boundary implements Store {
|
|
|
327
295
|
}
|
|
328
296
|
}
|
|
329
297
|
|
|
330
|
-
/**
|
|
331
|
-
* SQL on a session of the addon: {@link DatabaseWriter}'s `query` and `execute`
|
|
332
|
-
* by way of its `queryColumnsNow`.
|
|
333
|
-
*/
|
|
298
|
+
/** {@link DatabaseWriter} on an addon session, built on `queryColumnsNow`. */
|
|
334
299
|
abstract class Sql implements DatabaseWriter {
|
|
335
300
|
protected readonly native: NativeSession;
|
|
336
301
|
protected readonly boundary: Boundary;
|
|
@@ -342,18 +307,9 @@ abstract class Sql implements DatabaseWriter {
|
|
|
342
307
|
this.over = sqlOver((s, p) => this.queryColumnsNow(s, p));
|
|
343
308
|
}
|
|
344
309
|
|
|
345
|
-
/**
|
|
346
|
-
* The rows of one statement with their column names: the value itself if
|
|
347
|
-
* the addon answered at once (only the package's own code takes it so), else
|
|
348
|
-
* a promise of it. A failure is a rejection.
|
|
349
|
-
*/
|
|
310
|
+
/** The rows of one statement with their columns; synchronous if the addon answered so. A failure rejects. */
|
|
350
311
|
abstract queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
|
|
351
312
|
|
|
352
|
-
queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult> {
|
|
353
|
-
const result = this.queryColumnsNow(sql, params);
|
|
354
|
-
return result instanceof Promise ? result : Promise.resolve(result);
|
|
355
|
-
}
|
|
356
|
-
|
|
357
313
|
query<T = Row>(sql: string, params?: SqlParam[]): Promise<T[]> {
|
|
358
314
|
return this.over.query<T>(sql, params);
|
|
359
315
|
}
|
|
@@ -370,7 +326,7 @@ abstract class Sql implements DatabaseWriter {
|
|
|
370
326
|
return this.over.execute(sql, params);
|
|
371
327
|
}
|
|
372
328
|
|
|
373
|
-
/** {@link request}
|
|
329
|
+
/** {@link request} that returns a ready value synchronously, with no keep-alive. */
|
|
374
330
|
protected requestNow<T>(call: () => Answer<T>): Answer<T> {
|
|
375
331
|
let result: Answer<T>;
|
|
376
332
|
try {
|
|
@@ -384,11 +340,7 @@ abstract class Sql implements DatabaseWriter {
|
|
|
384
340
|
});
|
|
385
341
|
}
|
|
386
342
|
|
|
387
|
-
/**
|
|
388
|
-
* `call`'s result, or its {@link failure}: `call` makes the request, as the
|
|
389
|
-
* addon throws as it is called (arguments it cannot convert, and the error
|
|
390
|
-
* of a call that answers at once).
|
|
391
|
-
*/
|
|
343
|
+
/** The result of `call`, or its {@link failure}, whether the addon throws or rejects. */
|
|
392
344
|
protected request<T>(call: () => Answer<T>): Promise<T> {
|
|
393
345
|
let alive: Promise<T>;
|
|
394
346
|
try {
|
|
@@ -402,54 +354,57 @@ abstract class Sql implements DatabaseWriter {
|
|
|
402
354
|
}
|
|
403
355
|
|
|
404
356
|
/**
|
|
405
|
-
*
|
|
406
|
-
*
|
|
357
|
+
* An {@link SqlError} if a retry would repeat `error`; the store error if
|
|
358
|
+
* that ended the session. `sends`: `error` failed the commit of a
|
|
359
|
+
* transaction that sends on the VM, the one call whose failure can be the
|
|
360
|
+
* VM's refusal of a send, or the attempt's end with the session usable.
|
|
407
361
|
*/
|
|
408
|
-
protected failure(error: unknown): unknown {
|
|
362
|
+
protected failure(error: unknown, { sends = false }: { sends?: boolean } = {}): unknown {
|
|
409
363
|
if (error instanceof SqlError) return error;
|
|
410
|
-
//
|
|
411
|
-
//
|
|
412
|
-
//
|
|
413
|
-
//
|
|
414
|
-
|
|
364
|
+
// On the VM the end of the attempt fails state waits inside the addon,
|
|
365
|
+
// and only its text crosses back. Use the class the driver fails with.
|
|
366
|
+
// Such a failure ends the session; an SQL error that merely names the
|
|
367
|
+
// text leaves it usable, and stays an SQL error. The commit of a
|
|
368
|
+
// transaction that sends is read so whatever the session says: a commit
|
|
369
|
+
// that wrote nothing makes its sends in a group of their own after the
|
|
370
|
+
// database's commit, and the attempt's end fails that wait with the
|
|
371
|
+
// session still usable until the end closes it.
|
|
372
|
+
const stateWait = this.native.isUsable() && !sends ? undefined : stateWaitFailure(error);
|
|
415
373
|
if (stateWait !== undefined) return stateWait;
|
|
374
|
+
// A send of the commit that Restate would refuse (an empty idempotency
|
|
375
|
+
// key): the VM dropped the commit's group, and the handler gets a
|
|
376
|
+
// TerminalError (400), as from a send of its own. Only the commit's text
|
|
377
|
+
// is read so: any other call's is SQL's, which a trigger can make read so.
|
|
378
|
+
const refused = sends ? invalidInput(error) : undefined;
|
|
379
|
+
if (refused !== undefined) return new InvalidInput(refused.message, { errorCode: refused.code });
|
|
416
380
|
const failed = this.boundary.failed;
|
|
417
381
|
if (failed !== undefined && !this.native.isUsable()) return failed.error;
|
|
382
|
+
// `InvalidArg`: the addon's refusal of a call that may have ended the
|
|
383
|
+
// session, or an argument it cannot convert; a retry would repeat either.
|
|
418
384
|
const repeats = (error as { code?: unknown }).code === REFUSED || this.native.isUsable();
|
|
419
385
|
return repeats ? new SqlError((error as Error).message, { cause: error }) : error;
|
|
420
386
|
}
|
|
421
387
|
}
|
|
422
388
|
|
|
423
|
-
|
|
424
|
-
// ended the session (its `Refused`), and of arguments it cannot convert.
|
|
389
|
+
/** The code of the addon's errors that a retry would repeat (its `Refused`, and arguments it cannot convert). */
|
|
425
390
|
const REFUSED = 'InvalidArg';
|
|
426
391
|
|
|
427
|
-
/**
|
|
428
|
-
* The error of a call that failed because the attempt's state waits were
|
|
429
|
-
* failed in the addon, at the end of the attempt. `undefined` for anything
|
|
430
|
-
* else.
|
|
431
|
-
*/
|
|
392
|
+
/** `AttemptShutDown` for a call that failed because the attempt ended; else `undefined`. */
|
|
432
393
|
function stateWaitFailure(error: unknown): unknown {
|
|
433
|
-
const message = (error as { message?: unknown })
|
|
434
|
-
|
|
435
|
-
if (message.includes(STATE_WAIT_OVER)) return new AttemptShutDown();
|
|
436
|
-
return undefined;
|
|
394
|
+
const message = (error as { message?: unknown } | undefined)?.message;
|
|
395
|
+
return typeof message === 'string' && message.includes(STATE_WAIT_OVER) ? new AttemptShutDown() : undefined;
|
|
437
396
|
}
|
|
438
397
|
|
|
439
|
-
/**
|
|
440
|
-
* A session of a database: calls run one at a time, in call order, and a
|
|
441
|
-
* transaction holds the session until it commits or rolls back. Calls made
|
|
442
|
-
* meanwhile wait, but a call from inside the transaction's body is refused,
|
|
443
|
-
* as it would wait for that body: the body uses its `tx`.
|
|
444
|
-
*/
|
|
398
|
+
/** A session of a database. Call ordering and the transaction guard: see the header. */
|
|
445
399
|
export class Connection extends Sql {
|
|
446
|
-
/**
|
|
400
|
+
/**
|
|
401
|
+
* The transaction guard: the open transaction, in the async context of its
|
|
402
|
+
* body. A call from a continuation created before the transaction, which
|
|
403
|
+
* the body then awaits, is not refused and deadlocks.
|
|
404
|
+
*/
|
|
447
405
|
private readonly running = new AsyncLocalStorage<OpenTransaction>();
|
|
448
|
-
/** Settles once the last call queued so far has: the next call runs after it. */
|
|
449
406
|
private queue: Promise<unknown> = Promise.resolve();
|
|
450
|
-
/**
|
|
451
|
-
private tail: Gate | undefined;
|
|
452
|
-
/** Calls queued and not settled: with none, a call that is ready runs at once, in order. */
|
|
407
|
+
/** Calls queued and not settled. With none, a call can take the fast path. */
|
|
453
408
|
private inflight = 0;
|
|
454
409
|
private readonly release = (): void => {
|
|
455
410
|
this.inflight--;
|
|
@@ -459,7 +414,7 @@ export class Connection extends Sql {
|
|
|
459
414
|
if (this.inflight === 0 && this.running.getStore()?.open !== true) {
|
|
460
415
|
const result = this.requestNow(() => this.native.queryColumns(sql, params));
|
|
461
416
|
if (!(result instanceof Promise)) return result;
|
|
462
|
-
// Not ready:
|
|
417
|
+
// Not ready: later calls queue behind it.
|
|
463
418
|
this.inflight++;
|
|
464
419
|
this.queue = result.then(this.release, this.release);
|
|
465
420
|
return result;
|
|
@@ -468,50 +423,42 @@ export class Connection extends Sql {
|
|
|
468
423
|
}
|
|
469
424
|
|
|
470
425
|
/**
|
|
471
|
-
* Run `body` as one SQL transaction:
|
|
472
|
-
*
|
|
473
|
-
*
|
|
474
|
-
* the transaction (`COMMIT`, `ROLLBACK`) ends the session. A failing
|
|
475
|
-
* COMMIT rolls back.
|
|
426
|
+
* Run `body` as one SQL transaction: once its calls settle, commit with its
|
|
427
|
+
* records, or roll back if it rejects. A `COMMIT` or `ROLLBACK` statement
|
|
428
|
+
* in it ends the session.
|
|
476
429
|
*/
|
|
477
430
|
transaction<T>(body: (tx: ConnectionTransaction) => Promise<T>): Promise<T> {
|
|
478
|
-
|
|
479
|
-
return this.serial(async () => {
|
|
480
|
-
try {
|
|
481
|
-
return await this.run(gate, body);
|
|
482
|
-
} finally {
|
|
483
|
-
if (this.tail === gate) this.tail = undefined;
|
|
484
|
-
}
|
|
485
|
-
}, gate);
|
|
431
|
+
return this.serial(() => this.run(body));
|
|
486
432
|
}
|
|
487
433
|
|
|
488
|
-
private async run<T>(
|
|
434
|
+
private async run<T>(body: (tx: ConnectionTransaction) => Promise<T>): Promise<T> {
|
|
489
435
|
await this.request(() => this.native.begin());
|
|
490
|
-
const tx = new OpenTransaction(this.native, this.boundary
|
|
436
|
+
const tx = new OpenTransaction(this.native, this.boundary);
|
|
491
437
|
let result: T;
|
|
492
438
|
try {
|
|
493
439
|
result = await this.running.run(tx, () => body(tx));
|
|
494
|
-
await tx.
|
|
440
|
+
await tx.end();
|
|
495
441
|
} catch (error) {
|
|
496
442
|
await tx.end();
|
|
497
443
|
await this.rollback();
|
|
498
444
|
throw error;
|
|
499
445
|
}
|
|
500
|
-
const records =
|
|
501
|
-
//
|
|
502
|
-
//
|
|
446
|
+
const records = tx.recordsSet();
|
|
447
|
+
// The commit sync runs the `withCommit` work; a commit with no writes has no sync, so it runs after.
|
|
448
|
+
// On the VM, what the body gave `commitWith` goes in the commit's atomic group instead.
|
|
503
449
|
const runs = tx.commitRuns();
|
|
450
|
+
const withCommit = tx.vmCommit();
|
|
504
451
|
this.boundary.withSync = runs;
|
|
505
452
|
let unsynced: (() => void) | undefined;
|
|
506
453
|
try {
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
454
|
+
await this.boundary.alive(() =>
|
|
455
|
+
withCommit === undefined ? this.native.commit(records) : this.native.commit(records, withCommit),
|
|
456
|
+
);
|
|
510
457
|
} catch (error) {
|
|
511
|
-
// A COMMIT
|
|
512
|
-
//
|
|
458
|
+
// A failed COMMIT (a deferred constraint) leaves the transaction open:
|
|
459
|
+
// without the rollback, later calls would run inside it.
|
|
513
460
|
await this.rollback();
|
|
514
|
-
throw this.failure(error);
|
|
461
|
+
throw this.failure(error, { sends: (withCommit?.sends.length ?? 0) > 0 });
|
|
515
462
|
} finally {
|
|
516
463
|
unsynced = this.boundary.withSync;
|
|
517
464
|
this.boundary.withSync = undefined;
|
|
@@ -520,49 +467,38 @@ export class Connection extends Sql {
|
|
|
520
467
|
return result;
|
|
521
468
|
}
|
|
522
469
|
|
|
523
|
-
/**
|
|
524
|
-
* The record `name`, as the last commit that set it left it (see
|
|
525
|
-
* {@link ConnectionTransaction.setRecord}); empty if none did.
|
|
526
|
-
*/
|
|
470
|
+
/** The record `name` as last committed (see {@link ConnectionTransaction.setRecord}); empty if never set. */
|
|
527
471
|
record(name: string): Promise<Uint8Array> {
|
|
528
472
|
return this.serial(async () => new Uint8Array(await this.request(() => this.native.record(name))));
|
|
529
473
|
}
|
|
530
474
|
|
|
531
|
-
/**
|
|
475
|
+
/** An SQL error leaves the session usable; a storage error ends it. */
|
|
532
476
|
isUsable(): boolean {
|
|
533
477
|
return this.native.isUsable();
|
|
534
478
|
}
|
|
535
479
|
|
|
536
|
-
/**
|
|
537
|
-
* End the session after the calls before it, leaving its engine to the
|
|
538
|
-
* next one. It rejects if they left a transaction open, or a failure ended
|
|
539
|
-
* the session.
|
|
540
|
-
*/
|
|
480
|
+
/** End the session after earlier calls. Rejects if a transaction is left open or a failure ended it. */
|
|
541
481
|
save(): Promise<void> {
|
|
542
482
|
return this.serial(() => this.request(() => this.native.save()));
|
|
543
483
|
}
|
|
544
484
|
|
|
545
|
-
/** End the session now, whatever its state
|
|
485
|
+
/** End the session now, whatever its state. Queued calls reject. */
|
|
546
486
|
close(): Promise<void> {
|
|
547
487
|
return this.native.close();
|
|
548
488
|
}
|
|
549
489
|
|
|
550
|
-
/**
|
|
551
|
-
private serial<T>(call: () => Promise<T
|
|
490
|
+
/** Queue `call` after earlier calls. Refused from the body of an open transaction (the guard). */
|
|
491
|
+
private serial<T>(call: () => Promise<T>): Promise<T> {
|
|
552
492
|
if (this.running.getStore()?.open) {
|
|
553
493
|
return Promise.reject(new SqlError('inside a transaction, use the transaction handle its body gets'));
|
|
554
494
|
}
|
|
555
|
-
// A call queued behind the last transaction tells it so; a transaction
|
|
556
|
-
// that is itself the last one queued from now on is told by the next.
|
|
557
|
-
this.tail?.fire();
|
|
558
|
-
if (transaction !== undefined) this.tail = transaction;
|
|
559
495
|
this.inflight++;
|
|
560
496
|
const result = this.queue.then(call);
|
|
561
497
|
this.queue = result.then(this.release, this.release);
|
|
562
498
|
return result;
|
|
563
499
|
}
|
|
564
500
|
|
|
565
|
-
/** Roll back,
|
|
501
|
+
/** Roll back, ignoring errors: the caller rethrows its own error, which explains the failure. */
|
|
566
502
|
private async rollback(): Promise<void> {
|
|
567
503
|
try {
|
|
568
504
|
await this.native.rollback();
|
|
@@ -570,128 +506,65 @@ export class Connection extends Sql {
|
|
|
570
506
|
}
|
|
571
507
|
}
|
|
572
508
|
|
|
573
|
-
/** SQL in one transaction
|
|
509
|
+
/** SQL in one transaction while its body runs, and the records it commits with. */
|
|
574
510
|
export interface ConnectionTransaction extends DatabaseWriter {
|
|
575
|
-
/** The rows of one statement
|
|
576
|
-
queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult>;
|
|
577
|
-
/** {@link queryColumns} for the package's own code: the value itself if the addon answered at once. */
|
|
511
|
+
/** The rows of one statement with their columns, synchronous if the addon answered so (package code only). */
|
|
578
512
|
queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
|
|
579
513
|
/**
|
|
580
|
-
* Set the record `name` to `value`
|
|
581
|
-
*
|
|
582
|
-
*
|
|
583
|
-
*
|
|
584
|
-
* name is at most 255 bytes, and not `db`; a value at most 16 MiB.
|
|
514
|
+
* Set the record `name` to `value` in this commit: a value kept outside the
|
|
515
|
+
* tables, stored exactly when the transaction is, even if no row changes.
|
|
516
|
+
* It stays until a later transaction sets it. An empty value reads as never
|
|
517
|
+
* set. A name is at most 255 bytes and not `db`; a value at most 16 MiB.
|
|
585
518
|
*/
|
|
586
519
|
setRecord(name: string, value: Uint8Array): void;
|
|
587
|
-
/** The record `name` as this transaction would commit it
|
|
520
|
+
/** The record `name` as this transaction would commit it. */
|
|
588
521
|
record(name: string): Promise<Uint8Array>;
|
|
589
522
|
/**
|
|
590
|
-
* Run `run`
|
|
591
|
-
*
|
|
592
|
-
*
|
|
593
|
-
* sends, which it stores in order with the writes). Never if the
|
|
594
|
-
* transaction rolls back.
|
|
523
|
+
* Run `run` right after the commit writes, before waiting for them: for a
|
|
524
|
+
* store in JavaScript (the sends of a test's transaction, session.ts).
|
|
525
|
+
* Never if the transaction rolls back. On the VM, {@link commitWith}.
|
|
595
526
|
*/
|
|
596
527
|
withCommit(run: () => void): void;
|
|
597
528
|
/**
|
|
598
|
-
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
* the crossing of a call. Returns false, and queues nothing, where the
|
|
603
|
-
* addon cannot (an addon without `queryColumnsAfter`): run the statement
|
|
604
|
-
* with {@link queryColumns}. One still queued as the body settles runs
|
|
605
|
-
* then, before the commit, and its failure fails the transaction.
|
|
606
|
-
*/
|
|
607
|
-
defer(sql: string): boolean;
|
|
608
|
-
/**
|
|
609
|
-
* Take back the last `sql` that {@link defer} queued if no call has taken
|
|
610
|
-
* it yet: it never runs. Whether it did.
|
|
529
|
+
* On the VM: commit `commit`'s sends with the transaction, inside its
|
|
530
|
+
* commit's atomic group, which is inside `commit.parentSpan`. A transaction
|
|
531
|
+
* that writes nothing makes them in a group of its own. A later call
|
|
532
|
+
* replaces it.
|
|
611
533
|
*/
|
|
612
|
-
|
|
613
|
-
/**
|
|
614
|
-
* Settles, and never rejects, once another call to the connection has
|
|
615
|
-
* queued behind this transaction: it is waiting for the body to settle.
|
|
616
|
-
* A body that holds the transaction open for more work can return on it,
|
|
617
|
-
* so that the call costs one commit rather than a stall. A call made
|
|
618
|
-
* before the transaction began does not settle it, and neither does one
|
|
619
|
-
* made from the body, which is refused.
|
|
620
|
-
*/
|
|
621
|
-
readonly queued: Promise<void>;
|
|
534
|
+
commitWith(commit: VmCommit): void;
|
|
622
535
|
}
|
|
623
536
|
|
|
624
|
-
/** A
|
|
625
|
-
class Gate {
|
|
626
|
-
readonly promise: Promise<void>;
|
|
627
|
-
private resolve!: () => void;
|
|
628
|
-
constructor() {
|
|
629
|
-
this.promise = new Promise<void>((resolve) => (this.resolve = resolve));
|
|
630
|
-
}
|
|
631
|
-
fire(): void {
|
|
632
|
-
this.resolve();
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
/**
|
|
637
|
-
* A {@link ConnectionTransaction} of {@link Connection.transaction}, open until its body
|
|
638
|
-
* settles. Its calls run one at a time, in call order, also when the body
|
|
639
|
-
* awaits several together, or none: each call made while it is open runs
|
|
640
|
-
* before its commit or rollback, so none outlives it.
|
|
641
|
-
*/
|
|
537
|
+
/** A {@link ConnectionTransaction}, open until its body settles. Its calls queue as the header says. */
|
|
642
538
|
class OpenTransaction extends Sql implements ConnectionTransaction {
|
|
643
|
-
/** The records it sets, by name. */
|
|
644
539
|
private readonly records = new Map<string, Buffer>();
|
|
645
|
-
/** What runs with its commit (`withCommit`). */
|
|
646
540
|
private readonly withCommits: (() => void)[] = [];
|
|
647
|
-
/**
|
|
541
|
+
/** What commits with it on the VM (`commitWith`). */
|
|
542
|
+
private committing: VmCommit | undefined;
|
|
648
543
|
private queue: Promise<unknown> = Promise.resolve();
|
|
649
544
|
private inflight = 0;
|
|
650
545
|
private readonly release = (): void => {
|
|
651
546
|
this.inflight--;
|
|
652
547
|
};
|
|
653
|
-
/** SQL that runs with the next call made (`defer`). */
|
|
654
|
-
private deferred: string[] = [];
|
|
655
548
|
private ended = false;
|
|
656
|
-
readonly queued: Promise<void>;
|
|
657
549
|
|
|
658
|
-
constructor(native: NativeSession, boundary: Boundary, queued: Promise<void>) {
|
|
659
|
-
super(native, boundary);
|
|
660
|
-
this.queued = queued;
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
/** Whether it is open: its body runs, and holds its session. */
|
|
664
550
|
get open(): boolean {
|
|
665
551
|
return !this.ended;
|
|
666
552
|
}
|
|
667
553
|
|
|
668
|
-
/**
|
|
669
|
-
|
|
670
|
-
* settled; then the records it set, as the addon's commit takes them.
|
|
671
|
-
*/
|
|
672
|
-
async end(): Promise<Record<string, Buffer>> {
|
|
554
|
+
/** Refuse further calls; settles once earlier calls have. */
|
|
555
|
+
async end(): Promise<void> {
|
|
673
556
|
this.ended = true;
|
|
674
557
|
await this.queue;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
recordsSet(): Record<string, Buffer> {
|
|
675
561
|
return Object.fromEntries(this.records);
|
|
676
562
|
}
|
|
677
563
|
|
|
678
564
|
queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult> {
|
|
679
565
|
if (this.ended) return Promise.reject(new SqlError('the transaction has ended'));
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
// comes first there, and cannot be told from a failure of the SQL once it has run).
|
|
683
|
-
if (this.deferred.length > 0) {
|
|
684
|
-
try {
|
|
685
|
-
checkParams(params);
|
|
686
|
-
} catch (error) {
|
|
687
|
-
return Promise.reject(this.failure(error));
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
// Taken as the call is made, not as it runs: a call made before the deferral runs before it.
|
|
691
|
-
const before = this.deferred.splice(0);
|
|
692
|
-
const call = () =>
|
|
693
|
-
before.length === 0 ? this.native.queryColumns(sql, params) : this.native.queryColumnsAfter!(before, sql, params);
|
|
694
|
-
if (this.inflight === 0 && !this.ended) {
|
|
566
|
+
const call = () => this.native.queryColumns(sql, params);
|
|
567
|
+
if (this.inflight === 0) {
|
|
695
568
|
const result = this.requestNow(call);
|
|
696
569
|
if (!(result instanceof Promise)) return result;
|
|
697
570
|
this.inflight++;
|
|
@@ -701,31 +574,6 @@ class OpenTransaction extends Sql implements ConnectionTransaction {
|
|
|
701
574
|
return this.serial(() => this.request(call));
|
|
702
575
|
}
|
|
703
576
|
|
|
704
|
-
defer(sql: string): boolean {
|
|
705
|
-
if (this.ended || this.native.queryColumnsAfter === undefined) return false;
|
|
706
|
-
this.deferred.push(sql);
|
|
707
|
-
return true;
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
undefer(sql: string): boolean {
|
|
711
|
-
const at = this.deferred.lastIndexOf(sql);
|
|
712
|
-
if (at < 0) return false;
|
|
713
|
-
this.deferred.splice(at, 1);
|
|
714
|
-
return true;
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
/**
|
|
718
|
-
* Refuse calls from now on, and once those made have settled, run the SQL
|
|
719
|
-
* that no call took (`defer`): the body has settled, and the commit
|
|
720
|
-
* follows. Its failure fails the transaction, as the call that would have
|
|
721
|
-
* run it would have.
|
|
722
|
-
*/
|
|
723
|
-
async drain(): Promise<void> {
|
|
724
|
-
this.ended = true;
|
|
725
|
-
await this.queue;
|
|
726
|
-
for (const sql of this.deferred.splice(0)) await this.request(() => this.native.queryColumns(sql));
|
|
727
|
-
}
|
|
728
|
-
|
|
729
577
|
setRecord(name: string, value: Uint8Array): void {
|
|
730
578
|
this.refuseEnded();
|
|
731
579
|
this.records.set(name, Buffer.from(value));
|
|
@@ -736,19 +584,27 @@ class OpenTransaction extends Sql implements ConnectionTransaction {
|
|
|
736
584
|
this.withCommits.push(run);
|
|
737
585
|
}
|
|
738
586
|
|
|
739
|
-
|
|
587
|
+
commitWith(commit: VmCommit): void {
|
|
588
|
+
this.refuseEnded();
|
|
589
|
+
this.committing = commit;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** What commits with it on the VM, once it ended: see {@link commitWith}. */
|
|
593
|
+
vmCommit(): VmCommit | undefined {
|
|
594
|
+
return this.committing;
|
|
595
|
+
}
|
|
596
|
+
|
|
740
597
|
commitRuns(): (() => void) | undefined {
|
|
741
598
|
const runs = this.withCommits;
|
|
742
599
|
return runs.length === 0 ? undefined : () => runs.forEach((run) => run());
|
|
743
600
|
}
|
|
744
601
|
|
|
745
602
|
record(name: string): Promise<Uint8Array> {
|
|
746
|
-
//
|
|
603
|
+
// Read when called, so it is ordered with `setRecord`.
|
|
747
604
|
const set = this.records.get(name);
|
|
748
605
|
return this.serial(async () => new Uint8Array(set ?? (await this.request(() => this.native.record(name)))));
|
|
749
606
|
}
|
|
750
607
|
|
|
751
|
-
/** Run `call`, made while the transaction is open, once the calls before it have. */
|
|
752
608
|
private serial<T>(call: () => Promise<T>): Promise<T> {
|
|
753
609
|
if (this.ended) return Promise.reject(new SqlError('the transaction has ended'));
|
|
754
610
|
this.inflight++;
|