@restatedev/sessions 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +474 -2
- package/dist/calls.d.ts +72 -0
- package/dist/calls.d.ts.map +1 -0
- package/dist/calls.js +86 -0
- package/dist/calls.js.map +1 -0
- package/dist/database.d.ts +169 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +264 -0
- package/dist/database.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -0
- package/dist/internal.d.ts +9 -0
- package/dist/internal.d.ts.map +1 -0
- package/dist/internal.js +12 -0
- package/dist/internal.js.map +1 -0
- package/dist/object.d.ts +162 -0
- package/dist/object.d.ts.map +1 -0
- package/dist/object.js +235 -0
- package/dist/object.js.map +1 -0
- package/dist/platform.d.ts +5 -0
- package/dist/platform.d.ts.map +1 -0
- package/dist/platform.js +15 -0
- package/dist/platform.js.map +1 -0
- package/dist/schema.d.ts +35 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +118 -0
- package/dist/schema.js.map +1 -0
- package/dist/selector.d.ts +86 -0
- package/dist/selector.d.ts.map +1 -0
- package/dist/selector.js +196 -0
- package/dist/selector.js.map +1 -0
- package/dist/session.d.ts +167 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +547 -0
- package/dist/session.js.map +1 -0
- package/package.json +46 -3
- package/src/calls.ts +197 -0
- package/src/database.ts +392 -0
- package/src/index.ts +35 -0
- package/src/internal.ts +13 -0
- package/src/object.ts +368 -0
- package/src/platform.ts +15 -0
- package/src/schema.ts +162 -0
- package/src/selector.ts +253 -0
- package/src/session.ts +663 -0
package/src/session.ts
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
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
|
+
import type * as restate from '@restatedev/restate-sdk';
|
|
8
|
+
import { CancelledError, serde, TerminalError } from '@restatedev/restate-sdk';
|
|
9
|
+
import { millisOrDurationToMillis, type Serde } from '@restatedev/restate-sdk-core';
|
|
10
|
+
import {
|
|
11
|
+
open,
|
|
12
|
+
type Row,
|
|
13
|
+
sqlOver,
|
|
14
|
+
SqlError,
|
|
15
|
+
type Connection,
|
|
16
|
+
type DatabaseWriter,
|
|
17
|
+
type SqlParam,
|
|
18
|
+
type DatabaseReader,
|
|
19
|
+
type SqlValue,
|
|
20
|
+
type Store,
|
|
21
|
+
type ConnectionTransaction,
|
|
22
|
+
} from './database.ts';
|
|
23
|
+
import { apply, dropAll, ofObject, type Schema, sessions } from './schema.ts';
|
|
24
|
+
import { type Send, sendOf } from './calls.ts';
|
|
25
|
+
|
|
26
|
+
export type { DatabaseReader, DatabaseWriter, Row, SqlParam, SqlValue };
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The session's database, `ctx.db`, for the whole handler: each statement
|
|
30
|
+
* outside {@link transaction} is its own transaction. Calls run one at a
|
|
31
|
+
* time, in call order.
|
|
32
|
+
*/
|
|
33
|
+
export interface Database extends DatabaseWriter {
|
|
34
|
+
/**
|
|
35
|
+
* Run `body` as one transaction: it commits when `body` resolves, and rolls
|
|
36
|
+
* back when it rejects. It holds the database: other calls wait until it
|
|
37
|
+
* ends, and a call to the database from inside `body` is refused, as it
|
|
38
|
+
* would wait for `body`. So `body` uses the `tx` it gets, which is invalid
|
|
39
|
+
* once `body` settles.
|
|
40
|
+
*/
|
|
41
|
+
transaction<T>(body: (tx: Transaction) => Promise<T>): Promise<T>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** One transaction of a {@link Database}: its SQL, and the sends it commits with. */
|
|
45
|
+
export interface Transaction extends DatabaseWriter {
|
|
46
|
+
/**
|
|
47
|
+
* Sends made right after the transaction commits, and never if it rolls
|
|
48
|
+
* back. Each has the idempotency key it is given, or else one of the
|
|
49
|
+
* transaction (`transaction/<id>/<index>`), so a send an attempt makes
|
|
50
|
+
* again is dropped.
|
|
51
|
+
*/
|
|
52
|
+
readonly send: Send;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** What the session needs of the handler's context. */
|
|
56
|
+
export interface SqlHost {
|
|
57
|
+
/** A shared handler's: it reads beside the exclusive one, and stores nothing. */
|
|
58
|
+
readonly shared: boolean;
|
|
59
|
+
readonly key: string;
|
|
60
|
+
/** Rejects when the attempt ends (suspended, or aborted). */
|
|
61
|
+
readonly invocationEndPromise: { readonly promise: Promise<unknown> };
|
|
62
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
63
|
+
readonly defaultSerde: Serde<any>;
|
|
64
|
+
request(): { readonly id: string; readonly target: { readonly service: string } };
|
|
65
|
+
get(name: string, serde: Serde<Uint8Array>, options: restate.EntryOptions): PromiseLike<Uint8Array | null>;
|
|
66
|
+
set(name: string, value: Uint8Array, serde: Serde<Uint8Array>, options: restate.EntryOptions): void;
|
|
67
|
+
clear(name: string, options: restate.EntryOptions): void;
|
|
68
|
+
/** The object's state keys. */
|
|
69
|
+
stateKeys(): PromiseLike<string[]>;
|
|
70
|
+
run(name: string, action: () => void): PromiseLike<void>;
|
|
71
|
+
genericSend(send: restate.GenericSend<Uint8Array>): unknown;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
type Wrap = (store: Store) => Store;
|
|
75
|
+
let wrapStore: Wrap | undefined;
|
|
76
|
+
|
|
77
|
+
/** Wrap each object's store, such as for fault injection in tests. */
|
|
78
|
+
export function setStoreWrapper(wrap: Wrap) {
|
|
79
|
+
wrapStore = wrap;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The end of an attempt, as `invocationEndPromise` rejects with it, for the requests that would otherwise wait for it. */
|
|
83
|
+
class AttemptEnd {
|
|
84
|
+
private ended: Error | undefined;
|
|
85
|
+
/** The rejections of the requests waiting. */
|
|
86
|
+
private readonly waiting = new Set<(error: Error) => void>();
|
|
87
|
+
private readonly listeners = new Set<() => void>();
|
|
88
|
+
|
|
89
|
+
constructor(end: Promise<unknown>) {
|
|
90
|
+
end.catch((error: unknown) => {
|
|
91
|
+
const ended = error instanceof Error ? error : new Error(String(error));
|
|
92
|
+
this.ended = ended;
|
|
93
|
+
for (const reject of this.waiting) reject(ended);
|
|
94
|
+
this.waiting.clear();
|
|
95
|
+
for (const listener of this.listeners) listener();
|
|
96
|
+
this.listeners.clear();
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* `promise`, or a rejection once the attempt ends: an attempt that is
|
|
102
|
+
* suspended or aborted never settles what it was waiting for.
|
|
103
|
+
*/
|
|
104
|
+
race<T>(promise: PromiseLike<T>): Promise<T> {
|
|
105
|
+
if (this.ended) return Promise.reject(this.ended);
|
|
106
|
+
return new Promise<T>((resolve, reject) => {
|
|
107
|
+
this.waiting.add(reject);
|
|
108
|
+
void Promise.resolve(promise)
|
|
109
|
+
.finally(() => this.waiting.delete(reject))
|
|
110
|
+
.then(resolve, reject);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Call `listener` when the attempt ends; the returned function cancels it. */
|
|
115
|
+
onEnd(listener: () => void): () => void {
|
|
116
|
+
if (this.ended) {
|
|
117
|
+
listener();
|
|
118
|
+
return () => {};
|
|
119
|
+
}
|
|
120
|
+
this.listeners.add(listener);
|
|
121
|
+
return () => this.listeners.delete(listener);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// A state command is named after its key, so that tooling can hide the
|
|
126
|
+
// database's head, tail and packs by name (`dev.restate.tooling.journal.hidden.name.prefix`).
|
|
127
|
+
const named = (key: string): restate.EntryOptions => ({ name: key });
|
|
128
|
+
|
|
129
|
+
// A shared handler's reader writes nothing.
|
|
130
|
+
const refusedWrite = () => {
|
|
131
|
+
throw new Error('a shared handler writes no state');
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The keys of the database `name`, apart from the object's own: each of the
|
|
136
|
+
* format's keys (`v22/head`, `v22/tail/...`, `v22/manifest/...`,
|
|
137
|
+
* `v22/pack/...`) as `v22/db/<name>/head`, under the format's prefix still,
|
|
138
|
+
* which tooling hides, and under none of the object's database's.
|
|
139
|
+
*/
|
|
140
|
+
const beside = (name: string) => (key: string) => {
|
|
141
|
+
const at = key.indexOf('/') + 1;
|
|
142
|
+
return `${key.slice(0, at)}db/${name}/${key.slice(at)}`;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The format's key of a key of the database `name` (undoes {@link beside});
|
|
147
|
+
* `undefined` for any other key of the object.
|
|
148
|
+
*/
|
|
149
|
+
const unbeside = (name: string) => (key: string) => {
|
|
150
|
+
const at = key.indexOf('/') + 1;
|
|
151
|
+
const prefix = `db/${name}/`;
|
|
152
|
+
return at > 0 && key.startsWith(prefix, at) ? key.slice(0, at) + key.slice(at + prefix.length) : undefined;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The object's state as an ordered store: `get` is a state get, `set` and
|
|
157
|
+
* `clear` are state writes, which return at once and which the runtime
|
|
158
|
+
* stores in order; `sync` is an empty `ctx.run`, acknowledged after the
|
|
159
|
+
* commands before it. A `get` or `sync` the attempt's end leaves waiting
|
|
160
|
+
* rejects, so the session that made it ends instead of holding its lock for
|
|
161
|
+
* the life of the process.
|
|
162
|
+
*/
|
|
163
|
+
function objectStore(
|
|
164
|
+
ctx: SqlHost,
|
|
165
|
+
end: AttemptEnd,
|
|
166
|
+
dbName: string | undefined,
|
|
167
|
+
cancelled: (error: CancelledError) => void,
|
|
168
|
+
): Store {
|
|
169
|
+
const keyOf = dbName === undefined ? (key: string) => key : beside(dbName);
|
|
170
|
+
// The addon gets a request's failure as text: a cancellation is kept here,
|
|
171
|
+
// for the call that failed of it to fail with it (see `Attempt.call`).
|
|
172
|
+
const request = <T>(promise: PromiseLike<T>) =>
|
|
173
|
+
end.race(promise).catch((error: unknown) => {
|
|
174
|
+
if (error instanceof CancelledError) cancelled(error);
|
|
175
|
+
throw error;
|
|
176
|
+
});
|
|
177
|
+
// TODO: read with protocol v8's ephemeral get, left out of the journal, once
|
|
178
|
+
// a Restate release ships v8 and the SDK lets a library make one. Restate 1.8
|
|
179
|
+
// negotiates v7 at most: a journaled get.
|
|
180
|
+
const get = async (key: string) => (await request(ctx.get(keyOf(key), serde.binary, named(keyOf(key))))) ?? undefined;
|
|
181
|
+
if (ctx.shared) return { get, set: refusedWrite, clear: refusedWrite, sync: async () => {} };
|
|
182
|
+
return {
|
|
183
|
+
get,
|
|
184
|
+
set: (key, value) => ctx.set(keyOf(key), value, serde.binary, named(keyOf(key))),
|
|
185
|
+
clear: (key) => ctx.clear(keyOf(key), named(keyOf(key))),
|
|
186
|
+
// The database's keys, for a garbage collection.
|
|
187
|
+
keys: async () => {
|
|
188
|
+
const keys = await request(ctx.stateKeys());
|
|
189
|
+
if (dbName === undefined) return keys;
|
|
190
|
+
const own = unbeside(dbName);
|
|
191
|
+
return keys.flatMap((key) => own(key) ?? []);
|
|
192
|
+
},
|
|
193
|
+
sync: async () => {
|
|
194
|
+
await request(ctx.run('sync', () => {}));
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* What a failed call to the session fails the handler with: an
|
|
201
|
+
* {@link SqlError}, which a retry would repeat, becomes a
|
|
202
|
+
* {@link TerminalError}, its `cause` the SQL error. Anything else is as for
|
|
203
|
+
* any handler: a storage error, which ends the session, or the handler's own
|
|
204
|
+
* (a failed request to another service, say) is retried, unless it is a
|
|
205
|
+
* TerminalError itself.
|
|
206
|
+
*/
|
|
207
|
+
function handlerError(error: unknown): unknown {
|
|
208
|
+
if (!(error instanceof SqlError)) return error;
|
|
209
|
+
const terminal = new TerminalError(error.message);
|
|
210
|
+
terminal.cause = error;
|
|
211
|
+
return terminal;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** `call`'s result, or the error the handler fails with (see {@link handlerError}). */
|
|
215
|
+
async function forHandler<T>(call: Promise<T>): Promise<T> {
|
|
216
|
+
try {
|
|
217
|
+
return await call;
|
|
218
|
+
} catch (error) {
|
|
219
|
+
throw handlerError(error);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The SQL of a transaction's body: `tx`'s, failing as {@link forHandler} does. */
|
|
224
|
+
function forBody(tx: ConnectionTransaction): DatabaseWriter {
|
|
225
|
+
return sqlOver((sql, params) => forHandler(tx.queryColumns(sql, params)), handlerError);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* `connection`, opened without the SDK (`open`), as a handler's `ctx.db`:
|
|
230
|
+
* for a library's tests, and tools. Its transactions send nothing, and a
|
|
231
|
+
* library's schema applies to it (`Schema.ensure`).
|
|
232
|
+
*/
|
|
233
|
+
export function asDatabase(connection: Connection): Database {
|
|
234
|
+
const db: Database = {
|
|
235
|
+
...sqlOver((sql, params) => connection.queryColumns(sql, params)),
|
|
236
|
+
transaction: (body) => connection.transaction((tx) => body({ ...forBody(tx), send: refusedSend })),
|
|
237
|
+
};
|
|
238
|
+
sessions.set(db, (schemas) => apply(connection, schemas));
|
|
239
|
+
return db;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// The transactions of `ctx.db`, each with how it empties the database (`reset`).
|
|
243
|
+
const resets = new WeakMap<Transaction, () => Promise<void>>();
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Empty the key's database in `tx`, a transaction of an exclusive handler's
|
|
247
|
+
* `ctx.db`: every table, view, index and trigger is dropped, the schemas are
|
|
248
|
+
* applied again (the object's, and the libraries' the attempt applied), and
|
|
249
|
+
* the outbox stays. It commits with `tx`: what `tx` writes after it are the
|
|
250
|
+
* new database's first rows, in the same commit.
|
|
251
|
+
*/
|
|
252
|
+
export function reset(tx: Transaction): Promise<void> {
|
|
253
|
+
const of = resets.get(tx);
|
|
254
|
+
if (of === undefined) throw new TerminalError("reset takes a transaction of an exclusive handler's ctx.db");
|
|
255
|
+
return forHandler(of());
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* A database that `opener` opens on its first call, as a handler's `ctx.db`
|
|
260
|
+
* opens: for tests, which give each attempt one over the same state.
|
|
261
|
+
*/
|
|
262
|
+
export function lazyDatabase(opener: () => Promise<Database>): Database {
|
|
263
|
+
let opened: Promise<Database> | undefined;
|
|
264
|
+
const db = () => (opened ??= opener());
|
|
265
|
+
const lazy: Database = {
|
|
266
|
+
query: async (sql, params) => (await db()).query(sql, params),
|
|
267
|
+
get: async (sql, params) => (await db()).get(sql, params),
|
|
268
|
+
values: async (sql, params) => (await db()).values(sql, params),
|
|
269
|
+
execute: async (sql, params) => (await db()).execute(sql, params),
|
|
270
|
+
transaction: async (body) => (await db()).transaction(body),
|
|
271
|
+
};
|
|
272
|
+
sessions.set(lazy, async (schemas) => {
|
|
273
|
+
const inner = await db();
|
|
274
|
+
const ensure = sessions.get(inner);
|
|
275
|
+
if (ensure === undefined)
|
|
276
|
+
throw new TerminalError("lazyDatabase opens a handler's ctx.db, or a database of asDatabase");
|
|
277
|
+
await ensure(schemas);
|
|
278
|
+
});
|
|
279
|
+
return lazy;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** The sends of a transaction that has no outbox: a shared handler's, or another database's. */
|
|
283
|
+
const refusedSend: Send = () => {
|
|
284
|
+
throw new TerminalError("a send of a transaction is an exclusive handler's, in the object's own database");
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
// A transaction's sends commit with it, in the database's record `outbox`
|
|
288
|
+
// (beside its tables, in none of them), which holds each committed
|
|
289
|
+
// transaction's sends until they are stored. They are made once the
|
|
290
|
+
// transaction commits; a later open makes again those still in the outbox,
|
|
291
|
+
// with the same idempotency keys (`transaction/<id>/<index>`, with a random
|
|
292
|
+
// id of the transaction), so making them again is dropped. Restate keeps an attempt's commands in the
|
|
293
|
+
// order they were made, so a send made before a commit is stored whenever the
|
|
294
|
+
// commit is: the next commit leaves the sends this attempt made out of the
|
|
295
|
+
// outbox, and so does the end of the attempt.
|
|
296
|
+
|
|
297
|
+
/** A send, but its parameter, as it is stored. */
|
|
298
|
+
type StoredSend = Omit<restate.GenericSend<unknown>, 'parameter' | 'inputSerde' | 'delay'> & {
|
|
299
|
+
/** Its delay, in milliseconds. */
|
|
300
|
+
delay?: number;
|
|
301
|
+
/** When a delayed send is due (epoch ms): one made again waits only what remains. */
|
|
302
|
+
due?: number;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
/** The sends of a committed transaction, in the outbox. */
|
|
306
|
+
interface Outgoing {
|
|
307
|
+
/** The transaction's random id. */
|
|
308
|
+
id: string;
|
|
309
|
+
/** Each send, its parameter in base64. */
|
|
310
|
+
sends: (StoredSend & { parameter: string })[];
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The database's record of the outbox. */
|
|
314
|
+
const OUTBOX = 'outbox';
|
|
315
|
+
|
|
316
|
+
/** The outbox as its record: none is empty, as a record never set reads. */
|
|
317
|
+
function encodeOutbox(outbox: Outgoing[]): Uint8Array {
|
|
318
|
+
return outbox.length === 0 ? new Uint8Array() : new TextEncoder().encode(JSON.stringify(outbox));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function decodeOutbox(record: Uint8Array): Outgoing[] {
|
|
322
|
+
return record.length === 0 ? [] : (JSON.parse(new TextDecoder().decode(record)) as Outgoing[]);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function storedSend(send: restate.GenericSend<unknown>): Outgoing['sends'][number] {
|
|
326
|
+
const { parameter, inputSerde, delay, ...rest } = send;
|
|
327
|
+
return {
|
|
328
|
+
...rest,
|
|
329
|
+
...(delay !== undefined ? { delay: millisOrDurationToMillis(delay) } : {}),
|
|
330
|
+
parameter: Buffer.from((inputSerde ?? serde.binary).serialize(parameter)).toString('base64'),
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** How a handler ended. */
|
|
335
|
+
type Outcome<T> = { value: T } | { error: unknown };
|
|
336
|
+
|
|
337
|
+
function settle<T>(outcome: Outcome<T>): T {
|
|
338
|
+
if ('error' in outcome) throw outcome.error;
|
|
339
|
+
return outcome.value;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// The attempts, by their `ctx.db`: for `database`.
|
|
343
|
+
const attempts = new WeakMap<object, Attempt>();
|
|
344
|
+
|
|
345
|
+
// A database's name (`database`).
|
|
346
|
+
const DATABASE_NAME = /^[\w.-]{1,64}$/;
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* The database `name` of the key, apart from the object's own (`ctx.db`, of
|
|
350
|
+
* the attempt whose session `db` is): for a library whose tables must be
|
|
351
|
+
* alone in their database, such as OpenCode's. It opens on its first use,
|
|
352
|
+
* and ends with the attempt, as `ctx.db` does. A name is 1 to 64 letters,
|
|
353
|
+
* digits, `_`, `-` or `.`.
|
|
354
|
+
*/
|
|
355
|
+
export function database(db: Database, name: string): Database {
|
|
356
|
+
if (!DATABASE_NAME.test(name)) throw new TerminalError(`database: ${JSON.stringify(name)} is not a database name`);
|
|
357
|
+
const attempt = attempts.get(db);
|
|
358
|
+
if (attempt === undefined) throw new TerminalError("database takes a handler's ctx.db");
|
|
359
|
+
return attempt.database(name);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* An attempt's SQL session: opened on its first use, or as an exclusive
|
|
364
|
+
* attempt starts ({@link openNow}), shared by everything the handler does,
|
|
365
|
+
* and saved when the handler ends ({@link end}). With `name`, of the key's database `name`
|
|
366
|
+
* ({@link database}), which has neither the object's schema nor an outbox.
|
|
367
|
+
*/
|
|
368
|
+
export class Attempt {
|
|
369
|
+
/** `ctx.db`. */
|
|
370
|
+
readonly db: Database;
|
|
371
|
+
private readonly ctx: SqlHost;
|
|
372
|
+
private readonly name: string | undefined;
|
|
373
|
+
/** The key's other databases this attempt opened, by name. */
|
|
374
|
+
private readonly databases = new Map<string, Attempt>();
|
|
375
|
+
/** The session, from its first use on. */
|
|
376
|
+
private session: Promise<Connection> | undefined;
|
|
377
|
+
/** The ids of the outbox's transactions this attempt made the sends of. */
|
|
378
|
+
private readonly made = new Set<string>();
|
|
379
|
+
/** The schemas this attempt's database has all the steps of. */
|
|
380
|
+
private readonly ensured = new Map<string, Schema>();
|
|
381
|
+
private ended = false;
|
|
382
|
+
/** Opened when the attempt started ({@link openNow}), and no call has seen how it went yet. */
|
|
383
|
+
private unseenOpen = false;
|
|
384
|
+
/** Stops closing the session when the attempt ends. */
|
|
385
|
+
private keepOpen: () => void = () => {};
|
|
386
|
+
/** The invocation's cancellation, once a request of the session failed of it. */
|
|
387
|
+
private cancelled: CancelledError | undefined;
|
|
388
|
+
|
|
389
|
+
constructor(ctx: SqlHost, name?: string) {
|
|
390
|
+
this.ctx = ctx;
|
|
391
|
+
this.name = name;
|
|
392
|
+
this.db = {
|
|
393
|
+
...sqlOver((sql, params) => this.call((db) => db.queryColumns(sql, params)), handlerError),
|
|
394
|
+
// A shared handler's writes stay in its session: it has no outbox.
|
|
395
|
+
transaction: <T>(body: (tx: Transaction) => Promise<T>) =>
|
|
396
|
+
this.ctx.shared
|
|
397
|
+
? this.call((db) => db.transaction((tx) => body({ ...forBody(tx), send: refusedSend })))
|
|
398
|
+
: this.name !== undefined
|
|
399
|
+
? this.call((db) =>
|
|
400
|
+
db.transaction((handle) => {
|
|
401
|
+
const transaction: Transaction = { ...forBody(handle), send: refusedSend };
|
|
402
|
+
resets.set(transaction, () => this.reset(handle));
|
|
403
|
+
return body(transaction);
|
|
404
|
+
}),
|
|
405
|
+
)
|
|
406
|
+
: this.withSends((tx, record, handle) => {
|
|
407
|
+
const transaction: Transaction = { ...tx, send: sendOf(record) };
|
|
408
|
+
resets.set(transaction, () => this.reset(handle));
|
|
409
|
+
return body(transaction);
|
|
410
|
+
}),
|
|
411
|
+
};
|
|
412
|
+
sessions.set(this.db, (schemas) => {
|
|
413
|
+
this.unseenOpen = false;
|
|
414
|
+
return this.opened().then((db) => this.ensureSchemas(db, schemas));
|
|
415
|
+
});
|
|
416
|
+
attempts.set(this.db, this);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** The key's database `name`, in this attempt: see {@link database}. */
|
|
420
|
+
database(name: string): Database {
|
|
421
|
+
if (this.ended) throw new Error('the handler has ended: its SQL session is closed');
|
|
422
|
+
let other = this.databases.get(name);
|
|
423
|
+
if (other === undefined) this.databases.set(name, (other = new Attempt(this.ctx, name)));
|
|
424
|
+
return other.db;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* One transaction of the session, whose sends are made once it commits,
|
|
429
|
+
* and kept in the outbox until they are stored: `body` gets its SQL, and
|
|
430
|
+
* `record`, which records a send.
|
|
431
|
+
*/
|
|
432
|
+
private async withSends<T>(
|
|
433
|
+
body: (
|
|
434
|
+
db: DatabaseWriter,
|
|
435
|
+
record: (send: restate.GenericSend<unknown>) => void,
|
|
436
|
+
handle: ConnectionTransaction,
|
|
437
|
+
) => Promise<T>,
|
|
438
|
+
): Promise<T> {
|
|
439
|
+
const sends: Outgoing['sends'] = [];
|
|
440
|
+
let recording = true;
|
|
441
|
+
const record = (send: restate.GenericSend<unknown>) => {
|
|
442
|
+
if (!recording) throw new TerminalError('the transaction has ended: send from inside its body');
|
|
443
|
+
sends.push(storedSend(send));
|
|
444
|
+
};
|
|
445
|
+
let outgoing: Outgoing | undefined;
|
|
446
|
+
const value = await this.call((db) =>
|
|
447
|
+
db.transaction(async (handle) => {
|
|
448
|
+
let result: T;
|
|
449
|
+
try {
|
|
450
|
+
result = await body(forBody(handle), record, handle);
|
|
451
|
+
} finally {
|
|
452
|
+
recording = false;
|
|
453
|
+
}
|
|
454
|
+
// The outbox as committed, but the sends stored since, and this
|
|
455
|
+
// transaction's: unchanged, it is not written again.
|
|
456
|
+
const outbox = await this.unstored(handle);
|
|
457
|
+
if (sends.length > 0) {
|
|
458
|
+
// A delay counts from the commit: one made again waits what remains.
|
|
459
|
+
const now = Date.now();
|
|
460
|
+
for (const send of sends) if (send.delay !== undefined) send.due = now + send.delay;
|
|
461
|
+
outgoing = { id: randomUUID(), sends };
|
|
462
|
+
outbox.push(outgoing);
|
|
463
|
+
}
|
|
464
|
+
handle.setRecord(OUTBOX, encodeOutbox(outbox));
|
|
465
|
+
return result;
|
|
466
|
+
}),
|
|
467
|
+
);
|
|
468
|
+
if (outgoing !== undefined) {
|
|
469
|
+
this.make(outgoing);
|
|
470
|
+
// Emptied at once, by a commit after the sends, which Restate stores
|
|
471
|
+
// before it: left in the outbox until the handler's end, they would be
|
|
472
|
+
// made again by an attempt that resumes a long wait (an approval), past
|
|
473
|
+
// the idempotency retention that drops a repeat.
|
|
474
|
+
await this.call((db) => this.flush(db));
|
|
475
|
+
}
|
|
476
|
+
return value;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* The handler ended with `outcome`: an SQL error that escaped it becomes
|
|
481
|
+
* terminal, then the outbox is emptied, and the session is saved. One that
|
|
482
|
+
* a storage error ended closes now, rather than when it is collected.
|
|
483
|
+
*/
|
|
484
|
+
async end<T>(outcome: Outcome<T>): Promise<T> {
|
|
485
|
+
// The key's other databases end first, as the handler left them.
|
|
486
|
+
const databases = await Promise.allSettled([...this.databases.values()].map((d) => d.end({ value: undefined })));
|
|
487
|
+
const value = await this.endSession(outcome);
|
|
488
|
+
const failed = databases.find((d) => d.status === 'rejected');
|
|
489
|
+
if (failed) throw failed.reason;
|
|
490
|
+
return value;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Open the session now, as the attempt starts, rather than on its first
|
|
495
|
+
* call: the open makes the sends a crashed attempt committed and left
|
|
496
|
+
* unmade, which must not wait for a handler that uses the database.
|
|
497
|
+
*/
|
|
498
|
+
openNow() {
|
|
499
|
+
if (this.ctx.shared || this.name !== undefined || this.session !== undefined) return;
|
|
500
|
+
this.unseenOpen = true;
|
|
501
|
+
this.opened().catch(() => {});
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Empty the database in the transaction `handle` ({@link reset}), and apply the schemas this attempt applied again. */
|
|
505
|
+
private async reset(handle: ConnectionTransaction) {
|
|
506
|
+
// Another database of the key has none of the object's schema.
|
|
507
|
+
const own = this.name === undefined ? ofObject(this.ctx.request().target.service) : undefined;
|
|
508
|
+
const schemas = [...(own ? [own] : []), ...[...this.ensured.values()].filter((s) => s !== own)];
|
|
509
|
+
await dropAll(handle, schemas);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* `call` on the session, opening it on the first; its failure as the
|
|
514
|
+
* handler fails with it, or the invocation's cancellation, if a request of
|
|
515
|
+
* the session failed of it: a call it ended fails with a CancelledError,
|
|
516
|
+
* as any of the handler's awaits does.
|
|
517
|
+
*/
|
|
518
|
+
private async call<T>(call: (db: Connection) => Promise<T>): Promise<T> {
|
|
519
|
+
this.unseenOpen = false;
|
|
520
|
+
try {
|
|
521
|
+
const db = await this.opened();
|
|
522
|
+
return await forHandler(call(db));
|
|
523
|
+
} catch (error) {
|
|
524
|
+
throw this.cancelled ?? error;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** Apply the steps of `schemas` that the database lacks, each schema once per attempt. */
|
|
529
|
+
private async ensureSchemas(db: Connection, schemas: readonly Schema[]) {
|
|
530
|
+
const lacking = schemas.filter((s) => !this.ensured.has(s.name));
|
|
531
|
+
if (lacking.length === 0) return;
|
|
532
|
+
await forHandler(apply(db, lacking, { reader: this.ctx.shared }));
|
|
533
|
+
for (const s of lacking) this.ensured.set(s.name, s);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** 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. */
|
|
537
|
+
private make({ id, sends }: Outgoing, again = false) {
|
|
538
|
+
sends.forEach(({ parameter, due, delay, ...send }, index) => {
|
|
539
|
+
this.ctx.genericSend({
|
|
540
|
+
...send,
|
|
541
|
+
// Made again, a delayed send waits only what remains of its delay.
|
|
542
|
+
...(delay !== undefined ? { delay: again && due !== undefined ? Math.max(0, due - Date.now()) : delay } : {}),
|
|
543
|
+
parameter: new Uint8Array(Buffer.from(parameter, 'base64')),
|
|
544
|
+
inputSerde: serde.binary,
|
|
545
|
+
idempotencyKey: send.idempotencyKey ?? `transaction/${id}/${index}`,
|
|
546
|
+
});
|
|
547
|
+
});
|
|
548
|
+
this.made.add(id);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** The outbox as committed, but the transactions this attempt made the sends of: a commit made after them stores them first. */
|
|
552
|
+
private async unstored(db: Connection | ConnectionTransaction): Promise<Outgoing[]> {
|
|
553
|
+
return decodeOutbox(await db.record(OUTBOX)).filter(({ id }) => !this.made.has(id));
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* Empty the outbox, so that a later open does not make its sends again: a
|
|
558
|
+
* commit after them, which stores them first.
|
|
559
|
+
*/
|
|
560
|
+
private async flush(db: Connection) {
|
|
561
|
+
if ((await db.record(OUTBOX)).length === 0) return;
|
|
562
|
+
// Read in the transaction that writes it: one that committed sends since
|
|
563
|
+
// the read above keeps them.
|
|
564
|
+
await db.transaction(async (tx) => tx.setRecord(OUTBOX, encodeOutbox(await this.unstored(tx))));
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** The session, opening it on the first call. */
|
|
568
|
+
private opened(): Promise<Connection> {
|
|
569
|
+
if (this.ended) return Promise.reject(new Error('the handler has ended: its SQL session is closed'));
|
|
570
|
+
this.session ??= this.start();
|
|
571
|
+
return this.session;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
private async start(): Promise<Connection> {
|
|
575
|
+
const ctx = this.ctx;
|
|
576
|
+
// The page cache's: the key escaped, so that no key reads as another's
|
|
577
|
+
// database (a name has no `/`).
|
|
578
|
+
const key = `${ctx.request().target.service}/${encodeURIComponent(ctx.key)}`;
|
|
579
|
+
const namespace = this.name === undefined ? key : `${key}/${this.name}`;
|
|
580
|
+
const end = new AttemptEnd(ctx.invocationEndPromise.promise);
|
|
581
|
+
const object = objectStore(ctx, end, this.name, (error) => (this.cancelled ??= error));
|
|
582
|
+
const db = await open(namespace, wrapStore ? wrapStore(object) : object, { reader: ctx.shared });
|
|
583
|
+
// A handler still waiting for something else when the attempt ends (a
|
|
584
|
+
// model request, say) keeps the session no longer: it closes once no
|
|
585
|
+
// statement runs, and the handler's later calls fail.
|
|
586
|
+
this.keepOpen = end.onEnd(() => void db.close().catch(() => {}));
|
|
587
|
+
// The object's schema: in a shared handler's session too, whose writes are never stored, so a
|
|
588
|
+
// key never written reads as empty tables.
|
|
589
|
+
const own = this.name === undefined ? ofObject(ctx.request().target.service) : undefined;
|
|
590
|
+
try {
|
|
591
|
+
// A view writes nothing: a write fails, rather than vanish with the attempt.
|
|
592
|
+
if (ctx.shared) await db.execute('PRAGMA query_only = 1');
|
|
593
|
+
// What a crash may have left unmade.
|
|
594
|
+
if (!ctx.shared && this.name === undefined) {
|
|
595
|
+
const left = decodeOutbox(await db.record(OUTBOX));
|
|
596
|
+
left.forEach((outgoing) => this.make(outgoing, true));
|
|
597
|
+
// Emptied at once, as a transaction's own sends are (see `withSends`):
|
|
598
|
+
// kept until the handler's end, an attempt that resumes a long wait
|
|
599
|
+
// would make them again, past the idempotency retention.
|
|
600
|
+
if (left.length > 0) await this.flush(db);
|
|
601
|
+
}
|
|
602
|
+
if (own) await this.ensureSchemas(db, [own]);
|
|
603
|
+
} catch (error) {
|
|
604
|
+
const failed = handlerError(error);
|
|
605
|
+
await db.close();
|
|
606
|
+
throw failed;
|
|
607
|
+
}
|
|
608
|
+
return db;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
private async endSession<T>(outcome: Outcome<T>): Promise<T> {
|
|
612
|
+
this.ended = true;
|
|
613
|
+
const session = this.session;
|
|
614
|
+
if (session === undefined) return settle(outcome);
|
|
615
|
+
let db: Connection;
|
|
616
|
+
try {
|
|
617
|
+
db = await session;
|
|
618
|
+
} catch (error) {
|
|
619
|
+
// The open failed, and its error went to the call that made it; one
|
|
620
|
+
// made as the attempt started that no call saw fails the attempt, as
|
|
621
|
+
// its outbox is still to be made.
|
|
622
|
+
if (this.unseenOpen) throw error;
|
|
623
|
+
return settle(outcome);
|
|
624
|
+
}
|
|
625
|
+
this.keepOpen();
|
|
626
|
+
if (this.ctx.shared) {
|
|
627
|
+
// It read the snapshot it opened on, whatever committed since; one that
|
|
628
|
+
// outlived 16 commits failed its read ("is gone"), and is retried.
|
|
629
|
+
const failed = 'error' in outcome ? handlerError(outcome.error) : undefined;
|
|
630
|
+
await db.close();
|
|
631
|
+
if ('error' in outcome) throw failed;
|
|
632
|
+
return outcome.value;
|
|
633
|
+
}
|
|
634
|
+
if ('error' in outcome) {
|
|
635
|
+
const error = handlerError(outcome.error);
|
|
636
|
+
// The handler's error stands: what it committed is stored, and an
|
|
637
|
+
// outbox left full is made again by the next open.
|
|
638
|
+
await this.save(db).catch(() => db.close().catch(() => {}));
|
|
639
|
+
throw error;
|
|
640
|
+
}
|
|
641
|
+
// A transaction left open, say, which a retry would leave open again.
|
|
642
|
+
await forHandler(this.save(db));
|
|
643
|
+
return outcome.value;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Empty the outbox and save the session; one a storage error ended only closes. */
|
|
647
|
+
private async save(db: Connection) {
|
|
648
|
+
if (!db.isUsable()) return db.close();
|
|
649
|
+
await this.flush(db);
|
|
650
|
+
await db.save();
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/** Run `handler`, then end `attempt`'s SQL session, if it opened one (see {@link Attempt.end}). */
|
|
655
|
+
export async function withAttempt<T>(handler: () => Promise<T>, attempt: Attempt): Promise<T> {
|
|
656
|
+
let outcome: Outcome<T>;
|
|
657
|
+
try {
|
|
658
|
+
outcome = { value: await handler() };
|
|
659
|
+
} catch (error) {
|
|
660
|
+
outcome = { error };
|
|
661
|
+
}
|
|
662
|
+
return attempt.end(outcome);
|
|
663
|
+
}
|