@restatedev/sessions 0.0.0 → 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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +473 -2
  3. package/dist/calls.d.ts +72 -0
  4. package/dist/calls.d.ts.map +1 -0
  5. package/dist/calls.js +86 -0
  6. package/dist/calls.js.map +1 -0
  7. package/dist/database.d.ts +169 -0
  8. package/dist/database.d.ts.map +1 -0
  9. package/dist/database.js +264 -0
  10. package/dist/database.js.map +1 -0
  11. package/dist/index.d.ts +6 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +25 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/internal.d.ts +9 -0
  16. package/dist/internal.d.ts.map +1 -0
  17. package/dist/internal.js +12 -0
  18. package/dist/internal.js.map +1 -0
  19. package/dist/object.d.ts +162 -0
  20. package/dist/object.d.ts.map +1 -0
  21. package/dist/object.js +235 -0
  22. package/dist/object.js.map +1 -0
  23. package/dist/platform.d.ts +5 -0
  24. package/dist/platform.d.ts.map +1 -0
  25. package/dist/platform.js +15 -0
  26. package/dist/platform.js.map +1 -0
  27. package/dist/schema.d.ts +35 -0
  28. package/dist/schema.d.ts.map +1 -0
  29. package/dist/schema.js +118 -0
  30. package/dist/schema.js.map +1 -0
  31. package/dist/selector.d.ts +86 -0
  32. package/dist/selector.d.ts.map +1 -0
  33. package/dist/selector.js +196 -0
  34. package/dist/selector.js.map +1 -0
  35. package/dist/session.d.ts +167 -0
  36. package/dist/session.d.ts.map +1 -0
  37. package/dist/session.js +547 -0
  38. package/dist/session.js.map +1 -0
  39. package/package.json +40 -5
  40. package/src/calls.ts +197 -0
  41. package/src/database.ts +392 -0
  42. package/src/index.ts +35 -0
  43. package/src/internal.ts +13 -0
  44. package/src/object.ts +368 -0
  45. package/src/platform.ts +15 -0
  46. package/src/schema.ts +162 -0
  47. package/src/selector.ts +253 -0
  48. package/src/session.ts +663 -0
package/src/object.ts ADDED
@@ -0,0 +1,368 @@
1
+ // Session objects: Restate virtual objects whose state is a SQL database per
2
+ // key. Its handlers run one at a time per key, its views beside them; each
3
+ // gets a context of its own, made of the key, the request, the database and
4
+ // calls, and nothing else of the SDK's context:
5
+ //
6
+ // const notes = restate.sessionObject({
7
+ // name: 'notes',
8
+ // schema: ['CREATE TABLE notes (text TEXT NOT NULL)'],
9
+ // handlers: {
10
+ // add: async (ctx, text: string) => {
11
+ // await ctx.db.execute('INSERT INTO notes (text) VALUES (?)', [text]);
12
+ // },
13
+ // },
14
+ // views: {
15
+ // list: async (ctx) => ctx.db.query<{ text: string }>('SELECT text FROM notes'),
16
+ // },
17
+ // });
18
+ import * as restate from '@restatedev/restate-sdk';
19
+ import type { VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
20
+ import { type Rpc, rpcOf, type Send, sendOf } from './calls.ts';
21
+ import type { DatabaseReader } from './database.ts';
22
+ import { register, sessions, type Step } from './schema.ts';
23
+ import { hookSelector } from './selector.ts';
24
+ import { type Database, Attempt, type SqlHost, withAttempt } from './session.ts';
25
+
26
+ /**
27
+ * The context of a session object's handler. A handler runs in attempts:
28
+ * Restate starts a new one after a crash, a retryable error or a
29
+ * suspension, and each runs the handler from its first line, finding what
30
+ * the attempts before it committed. Its operations can be awaited together
31
+ * (`Promise.all`, `Promise.race`).
32
+ */
33
+ export interface SessionContext {
34
+ /** The session's key. */
35
+ readonly key: string;
36
+ /** The request: its id (the same on every attempt), headers, target, and the attempt's signal. */
37
+ readonly request: restate.Request;
38
+ /**
39
+ * The key's database. Each statement outside a transaction is its own
40
+ * commit, and `db.transaction` groups several; a commit is durable when
41
+ * its promise resolves. Calls run one at a time, in call order.
42
+ */
43
+ readonly db: Database;
44
+ /** Calls, typed (`ctx.rpc(object, key).handler(input)`) or literal. */
45
+ readonly rpc: Rpc;
46
+ /** Sends, made at once; a transaction's (`tx.send`) are made once it commits. */
47
+ readonly send: Send;
48
+ /** Cancel an invocation, by its id: see {@link Cancel}. */
49
+ readonly cancel: Cancel;
50
+ }
51
+
52
+ /**
53
+ * The context of a session object's view: it runs beside the handlers, and
54
+ * reads the database as committed when its invocation started, whatever they
55
+ * commit meanwhile. It writes nothing, and sends nothing, but it can cancel an
56
+ * invocation: a handler of its own object's, say, as a Stop button does.
57
+ */
58
+ export interface ViewContext {
59
+ readonly key: string;
60
+ readonly request: restate.Request;
61
+ readonly db: DatabaseReader;
62
+ readonly rpc: Rpc;
63
+ readonly cancel: Cancel;
64
+ }
65
+
66
+ /**
67
+ * Cancel invocation `invocationId` (such as `inv_1f…`), as Restate's admin
68
+ * API does: made at once, and not awaited. Cancelling an invocation that
69
+ * already ended does nothing, so a new attempt that cancels it again is
70
+ * harmless.
71
+ *
72
+ * ctx.cancel(turn.invocationId);
73
+ */
74
+ export type Cancel = (invocationId: string) => void;
75
+
76
+ /** A handler of `C`: its input, if any, annotated. */
77
+ // oxlint-disable-next-line typescript/no-explicit-any
78
+ type Fn<C> = (ctx: C, input: any) => Promise<unknown>;
79
+
80
+ /** The SDK's options of a handler (`input`, `output`, `description`, `ingressPrivate`, ...). */
81
+ // oxlint-disable-next-line typescript/no-explicit-any
82
+ export type HandlerOptions = restate.ObjectHandlerOpts<any, any>;
83
+
84
+ /** A handler or a view: a function, or one with options. */
85
+ export type Entry<C> = Fn<C> | ({ handler: Fn<C> } & HandlerOptions);
86
+
87
+ /** Each entry's function, as clients see it; none for entries left out (inferred as the constraint). */
88
+ type Functions<H> = string extends keyof H ? unknown : { [K in keyof H]: H[K] extends { handler: infer F } ? F : H[K] };
89
+
90
+ /**
91
+ * The key of the object database's head, its first read as it opens:
92
+ * `HEAD_KEY` in the addon's state format
93
+ * (`packages/sessions/native/src/state/format.rs`).
94
+ */
95
+ export const HEAD_KEY = 'v22/head';
96
+
97
+ /**
98
+ * The options every session object has: an invocation starts with the
99
+ * database's head only, not with every page. The rest of the database it
100
+ * reads as it needs it: its tail entries and packs change keys with each
101
+ * flush, so only the head can be named.
102
+ */
103
+ export const sqlOptions = { state: { preload: [HEAD_KEY] } } satisfies restate.ObjectOptions;
104
+
105
+ /**
106
+ * The metadata every session object has: Restate's UI hides the database
107
+ * from the journal view (its head, tail, manifests and packs in the object's
108
+ * state, `v22/...`; and the `sync` runs after its writes).
109
+ */
110
+ export const sqlMetadata = {
111
+ 'dev.restate.tooling.journal.hidden.names': 'sync',
112
+ 'dev.restate.tooling.journal.hidden.name.prefix': 'v22/',
113
+ };
114
+
115
+ // The handler options of every handler: explicit recovery, which runs a
116
+ // retried attempt from the start, since a later attempt makes different
117
+ // reads than a replayed journal would have.
118
+ export const recovery = () => restate.internal.explicitRecovery();
119
+
120
+ /** The SDK's runtime context, as far as the session needs it beyond its public type. */
121
+ type Runtime = { invocationEndPromise: SqlHost['invocationEndPromise']; defaultSerde: SqlHost['defaultSerde'] };
122
+
123
+ /** What an attempt needs of the SDK's context: a test's fake has these. */
124
+ export type AttemptContext = Pick<
125
+ restate.ObjectContext,
126
+ 'key' | 'request' | 'get' | 'set' | 'clear' | 'stateKeys' | 'run' | 'genericSend' | 'genericCall' | 'invocation'
127
+ > &
128
+ Runtime;
129
+
130
+ /** What an attempt's session needs of the SDK's context `ctx`. */
131
+ export function host(
132
+ ctx: restate.ObjectContext | restate.ObjectSharedContext | AttemptContext,
133
+ shared: boolean,
134
+ ): SqlHost {
135
+ const runtime = ctx as unknown as Runtime;
136
+ const exclusive = ctx as restate.ObjectContext;
137
+ return {
138
+ shared,
139
+ key: ctx.key,
140
+ invocationEndPromise: runtime.invocationEndPromise,
141
+ defaultSerde: runtime.defaultSerde,
142
+ request: () => ctx.request(),
143
+ get: (name, serde, entry) => ctx.get(name, serde, entry),
144
+ set: (name, value, serde, entry) => exclusive.set(name, value, serde, entry),
145
+ clear: (name, entry) => exclusive.clear(name, entry),
146
+ stateKeys: () => ctx.stateKeys(),
147
+ run: (name, action) => exclusive.run(name, action),
148
+ genericSend: (send) => ctx.genericSend(send),
149
+ };
150
+ }
151
+
152
+ /** The SDK's contexts behind the session objects' contexts, for @restatedev/sessions/internal. */
153
+ export const sdkContexts = new WeakMap<
154
+ SessionContext | ViewContext,
155
+ restate.ObjectContext | restate.ObjectSharedContext
156
+ >();
157
+
158
+ /** The reads of `db`, which apply a library's schema as `db` does (`Schema.ensure`). */
159
+ function readerOf(db: Database): DatabaseReader {
160
+ const reader: DatabaseReader = {
161
+ query: (sql, params) => db.query(sql, params),
162
+ get: (sql, params) => db.get(sql, params),
163
+ values: (sql, params) => db.values(sql, params),
164
+ };
165
+ const ensure = sessions.get(db);
166
+ if (ensure) sessions.set(reader, ensure);
167
+ return Object.freeze(reader);
168
+ }
169
+
170
+ /**
171
+ * The context of a handler (or, with `view`, of a view) over the SDK's
172
+ * context `ctx`, with the database `db`: what an attempt gets, and a test's
173
+ * over a context of its own. With `explicitCancellation`, a handler's with
174
+ * that option, which {@link cancelled} and {@link cancelCalls} take.
175
+ */
176
+ export function contextOf(ctx: AttemptContext, db: Database, options: { view: true }): ViewContext;
177
+ export function contextOf(
178
+ ctx: AttemptContext,
179
+ db: Database,
180
+ options?: { view?: false; explicitCancellation?: boolean },
181
+ ): SessionContext;
182
+ export function contextOf(
183
+ ctx: AttemptContext,
184
+ db: Database,
185
+ { view = false, explicitCancellation = false }: { view?: boolean; explicitCancellation?: boolean } = {},
186
+ ): SessionContext | ViewContext {
187
+ if (explicitCancellation) explicitlyCancelled.add(ctx);
188
+ const rpc = rpcOf(ctx);
189
+ const cancel = cancelOf(ctx);
190
+ const context: SessionContext | ViewContext = view
191
+ ? Object.freeze({ key: ctx.key, request: ctx.request(), db: readerOf(db), rpc, cancel })
192
+ : Object.freeze({
193
+ key: ctx.key,
194
+ request: ctx.request(),
195
+ db,
196
+ rpc,
197
+ send: sendOf((send) => void ctx.genericSend(send)),
198
+ cancel,
199
+ });
200
+ sdkContexts.set(context, ctx as unknown as restate.ObjectContext);
201
+ return context;
202
+ }
203
+
204
+ /** {@link Cancel} over the SDK's context `ctx`. */
205
+ const cancelOf =
206
+ (ctx: Pick<restate.ObjectContext, 'invocation'>): Cancel =>
207
+ (invocationId) => {
208
+ // Not an id (the SDK's parser checks no more): a retry would fail the same way.
209
+ if (!invocationId.startsWith('inv')) throw new restate.TerminalError(`not an invocation id: ${invocationId}`);
210
+ ctx.invocation(restate.InvocationIdParser.fromString(invocationId)).cancel();
211
+ };
212
+
213
+ /** One attempt of `fn` over `ctx`: its own context and session, which ends with it. */
214
+ function attempt(
215
+ fn: Fn<never>,
216
+ { view, explicit }: { view: boolean; explicit: boolean },
217
+ ctx: AttemptContext,
218
+ input: unknown,
219
+ ): Promise<unknown> {
220
+ const session = new Attempt(host(ctx, view));
221
+ session.openNow();
222
+ const context = view
223
+ ? contextOf(ctx, session.db, { view: true })
224
+ : contextOf(ctx, session.db, { explicitCancellation: explicit });
225
+ return withAttempt(() => fn(context as never, input as never), session);
226
+ }
227
+
228
+ /** `fn` as the SDK's handler: one loop drives each attempt's awaits (see selector.ts), until it ends. */
229
+ function wrap(fn: Fn<never>, view: boolean, explicit: boolean) {
230
+ return (ctx: restate.ObjectContext | restate.ObjectSharedContext, input: never) => {
231
+ const unhook = hookSelector(ctx);
232
+ const runtime = ctx as unknown as Runtime;
233
+ runtime.invocationEndPromise.promise.catch(unhook);
234
+ return attempt(fn, { view, explicit }, ctx as unknown as AttemptContext, input).finally(unhook);
235
+ };
236
+ }
237
+
238
+ /** Each session object's handlers and views, by name: for {@link invoke}. */
239
+ const entries = new WeakMap<object, Map<string, { fn: Fn<never>; view: boolean; explicit: boolean }>>();
240
+
241
+ /** The SDK's contexts of the handlers with `explicitCancellation: true`: for {@link cancelled}. */
242
+ const explicitlyCancelled = new WeakSet<object>();
243
+
244
+ /**
245
+ * Run handler or view `name` of `definition` for one attempt over `ctx`, a
246
+ * context of a test's own, without Restate: for tests.
247
+ */
248
+ export function invoke(definition: { name: string }, name: string, ctx: AttemptContext, input?: unknown) {
249
+ const entry = entries.get(definition)?.get(name);
250
+ if (entry === undefined) throw new Error(`${definition.name}.${name} is no handler or view of a session object`);
251
+ return attempt(entry.fn, entry, ctx, input);
252
+ }
253
+
254
+ /** Whether `value` is a handler of the SDK's already. */
255
+ const isSdkHandler = (value: object) => Object.getOwnPropertySymbols(value).some((s) => s.description === 'Handler');
256
+
257
+ /** The SDK's handler of entry `name` of `object`. */
258
+ function handlerOf(object: string, name: string, entry: unknown, view: boolean) {
259
+ const [fn, options] =
260
+ typeof entry === 'function'
261
+ ? [entry, {}]
262
+ : typeof entry === 'object' && entry !== null && typeof (entry as { handler?: unknown }).handler === 'function'
263
+ ? (() => {
264
+ const { handler, ...rest } = entry as { handler: Fn<never> } & HandlerOptions;
265
+ return [handler, rest] as const;
266
+ })()
267
+ : [undefined, undefined];
268
+ if (fn === undefined)
269
+ throw new TypeError(`${object}.${name} is not a handler: a function, or { handler, ...options }`);
270
+ if (isSdkHandler(fn)) {
271
+ throw new TypeError(
272
+ `${object}.${name} is an SDK handler: a session object's handlers are functions of its context. ` +
273
+ 'Put journaled work in a restate.object, service or workflow, and call it with ctx.rpc',
274
+ );
275
+ }
276
+ const opts = { ...options, ...recovery() } as HandlerOptions;
277
+ const explicit = (options as HandlerOptions).explicitCancellation === true;
278
+ const made = wrap(fn as Fn<never>, view, explicit) as never;
279
+ const handler = view ? restate.handlers.object.shared(opts, made) : restate.handlers.object.exclusive(opts, made);
280
+ return { handler, entry: { fn: fn as Fn<never>, view, explicit } };
281
+ }
282
+
283
+ /**
284
+ * A virtual object whose state is a SQL database per key.
285
+ *
286
+ * - `schema`: the steps that make each key's database, in order, applied
287
+ * once per key by the first handler that uses it. A step that ran never
288
+ * changes: a change is a step of its own.
289
+ * - `handlers`: they run one at a time per key, each with a
290
+ * {@link SessionContext}.
291
+ * - `views`: they run beside the handlers, each with a {@link ViewContext}:
292
+ * they read, and write nothing.
293
+ *
294
+ * Each is a function, or `{ handler, ...options }` with the SDK's handler
295
+ * options. A name is a handler or a view, not both. `description`,
296
+ * `metadata` and `options` are the SDK's object fields.
297
+ */
298
+ export function sessionObject<
299
+ P extends string,
300
+ // No defaults: a default stops each function's `ctx` from being inferred.
301
+ H extends Record<string, Entry<SessionContext>>,
302
+ V extends Record<string, Entry<ViewContext>>,
303
+ >(definition: {
304
+ name: P;
305
+ schema?: readonly Step[];
306
+ handlers?: H;
307
+ views?: V;
308
+ description?: string;
309
+ metadata?: Record<string, string>;
310
+ options?: restate.ObjectOptions;
311
+ }): VirtualObjectDefinition<P, Functions<H> & Functions<V>> {
312
+ const { name, schema, handlers = {}, views = {}, description, metadata, options } = definition;
313
+ const both = Object.keys(handlers).filter((key) => key in views);
314
+ if (both.length > 0) throw new Error(`${name}: ${both.join(', ')} is a handler and a view: name one otherwise`);
315
+ // Its state is its database's: which keys an invocation starts with is the session object's own.
316
+ if (options && ('state' in options || 'enableLazyState' in options)) {
317
+ throw new Error(`${name}: a session object sets its state options itself: leave out state and enableLazyState`);
318
+ }
319
+ if (schema) register(name, schema);
320
+ const sdkHandlers: Record<string, (ctx: restate.ObjectContext, input?: unknown) => Promise<unknown>> = {};
321
+ const own = new Map<string, { fn: Fn<never>; view: boolean; explicit: boolean }>();
322
+ for (const [view, map] of [
323
+ [false, handlers],
324
+ [true, views],
325
+ ] as const) {
326
+ for (const [key, value] of Object.entries(map)) {
327
+ const { handler, entry } = handlerOf(name, key, value, view);
328
+ sdkHandlers[key] = handler;
329
+ own.set(key, entry);
330
+ }
331
+ }
332
+ const made = restate.object({
333
+ name,
334
+ description,
335
+ handlers: sdkHandlers,
336
+ metadata: { ...sqlMetadata, ...metadata },
337
+ options: { ...sqlOptions, ...options },
338
+ });
339
+ entries.set(made, own);
340
+ return made;
341
+ }
342
+
343
+ /** The SDK's context behind `ctx`, a handler's with `explicitCancellation: true`. */
344
+ function explicitOf(ctx: SessionContext, of: string) {
345
+ const sdk = sdkContexts.get(ctx);
346
+ if (sdk === undefined) throw new restate.TerminalError(`${of} takes a session object's ctx`);
347
+ if (!explicitlyCancelled.has(sdk)) {
348
+ throw new restate.TerminalError(`${of} takes the ctx of a handler with explicitCancellation: true`);
349
+ }
350
+ return restate.internal.asInternal(sdk);
351
+ }
352
+
353
+ /**
354
+ * Resolves when Restate cancels the invocation of `ctx`, a handler's with
355
+ * `explicitCancellation: true`, whose awaits are left as they are: for a
356
+ * library that stops its own work then (a model's request, say).
357
+ */
358
+ export const cancelled = async (ctx: SessionContext): Promise<void> => {
359
+ await explicitOf(ctx, 'cancelled').cancellation();
360
+ };
361
+
362
+ /**
363
+ * Cancel the calls the attempt of `ctx` made, as a cancelled invocation's
364
+ * would be: a handler's with `explicitCancellation: true`.
365
+ */
366
+ export const cancelCalls = async (ctx: SessionContext): Promise<void> => {
367
+ await explicitOf(ctx, 'cancelCalls').cancelPreviousCalls();
368
+ };
@@ -0,0 +1,15 @@
1
+ // The platforms @restatedev/sessions ships its addon for, each a package of its
2
+ // own (npm/<platform>, `@restatedev/sessions-<platform>`) that @restatedev/sessions
3
+ // depends on optionally: a package manager installs the one of its machine
4
+ // alone (by the `os`, `cpu` and `libc` of each). The CI builds them
5
+ // (.github/workflows/packages.yml); `pnpm build` builds this machine's.
6
+
7
+ /** The platforms built, as their packages name them. */
8
+ export const PLATFORMS = ['linux-x64-gnu', 'linux-arm64-gnu', 'darwin-arm64'] as const;
9
+
10
+ /** This machine's platform, as a package of the addon would name it. */
11
+ export function platform(): string {
12
+ if (process.platform !== 'linux') return `${process.platform}-${process.arch}`;
13
+ const report = process.report.getReport() as { header?: { glibcVersionRuntime?: string } };
14
+ return `linux-${process.arch}-${report.header?.glibcVersionRuntime ? 'gnu' : 'musl'}`;
15
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,162 @@
1
+ // The schema of a session object's databases: each key's database is made by the
2
+ // same steps, in order, applied once per key, as its first exclusive attempt
3
+ // opens it. A database keeps how far each schema got in its record `schema` (beside
4
+ // its tables, in none of them), committed with the steps, so a step
5
+ // added later (a column, an index) runs on each key's database once, as that
6
+ // key is next opened:
7
+ //
8
+ // const notes = restate.sessionObject({
9
+ // name: 'notes',
10
+ // schema: ['CREATE TABLE notes (text TEXT NOT NULL)', 'ALTER TABLE notes ADD COLUMN at TEXT'],
11
+ // handlers: { ... },
12
+ // });
13
+ //
14
+ // A step is a statement, or an async function of the transaction (to move
15
+ // data, say). Steps are never changed or removed once they ran: a change is
16
+ // a step of its own.
17
+ //
18
+ // A view applies the steps its key's database lacks in its own session,
19
+ // which stores nothing, then reads: a key never written reads as
20
+ // empty tables. This repository's libraries (@restatedev/agents) keep their tables
21
+ // in a schema of their own name, which `schema.ensure(ctx.db)` applies where
22
+ // they use them, in any object: internal, from @restatedev/sessions/internal.
23
+ import type { Connection, DatabaseReader, DatabaseWriter, ConnectionTransaction } from './database.ts';
24
+
25
+ /**
26
+ * The database's record of its schemas: how many steps of each it has, by
27
+ * name. One record, so that `reset` clears all of them, a library's this
28
+ * process never loaded too.
29
+ */
30
+ const RECORD = 'schema';
31
+
32
+ /** How many steps of each schema the database has, by name. */
33
+ type Applied = Record<string, number>;
34
+
35
+ async function appliedIn(db: Connection | ConnectionTransaction): Promise<Applied> {
36
+ const record = await db.record(RECORD);
37
+ return record.length === 0 ? {} : (JSON.parse(new TextDecoder().decode(record)) as Applied);
38
+ }
39
+
40
+ /** A statement, or an async function of the transaction. */
41
+ export type Step = string | ((tx: DatabaseWriter) => Promise<void>);
42
+
43
+ /** A part of a database's schema: its `name`, and the `steps` that make it, in order. */
44
+ export class Schema {
45
+ readonly name: string;
46
+ readonly steps: readonly Step[];
47
+
48
+ constructor(name: string, steps: readonly Step[]) {
49
+ this.name = name;
50
+ this.steps = steps;
51
+ }
52
+
53
+ /**
54
+ * Apply the steps `db` lacks: a library's tables, where it uses them, in
55
+ * any object. On a handler's `ctx.db`, once per attempt, and a shared
56
+ * handler's are its own, vanishing with its session.
57
+ */
58
+ ensure(db: DatabaseReader | Connection): Promise<void> {
59
+ const session = sessions.get(db);
60
+ return session ? session([this]) : apply(db as Connection, [this]);
61
+ }
62
+ }
63
+
64
+ /** The handlers' sessions (`ctx.db`), each with how it applies schemas. */
65
+ export const sessions = new WeakMap<object, (schemas: readonly Schema[]) => Promise<void>>();
66
+
67
+ // The schema of each session object, by its name.
68
+ const objects = new Map<string, Schema>();
69
+
70
+ /** The session object `name`'s own schema: its steps, which each of its databases is made by. */
71
+ export const register = (name: string, steps: readonly Step[]) => void objects.set(name, new Schema(name, steps));
72
+
73
+ /** The session object `name`'s own schema, if it has one. */
74
+ export const ofObject = (name: string) => objects.get(name);
75
+
76
+ /** Apply the steps of `schemas` that `db` lacks, in one transaction, with how far each got. */
77
+ export async function apply(db: Connection, schemas: readonly Schema[], { reader = false } = {}) {
78
+ if (behind(await appliedIn(db), schemas).length === 0) return;
79
+ // Again in the transaction, which holds the session: a call before it may
80
+ // have applied them.
81
+ await db.transaction(async (tx) => {
82
+ if (!reader) return applyIn(tx, schemas);
83
+ // A reader's session is query-only, but for its schemas.
84
+ await tx.execute('PRAGMA query_only = 0');
85
+ try {
86
+ await applyIn(tx, schemas);
87
+ } finally {
88
+ await tx.execute('PRAGMA query_only = 1');
89
+ }
90
+ });
91
+ }
92
+
93
+ /** Apply the steps of `schemas` that the transaction `tx` lacks, and record how far each got. */
94
+ export async function applyIn(tx: ConnectionTransaction, schemas: readonly Schema[]) {
95
+ const applied = await appliedIn(tx);
96
+ const lacking = behind(applied, schemas);
97
+ if (lacking.length === 0) return;
98
+ for (const schema of lacking) {
99
+ for (const step of schema.steps.slice(applied[schema.name] ?? 0)) {
100
+ await (typeof step === 'string' ? tx.execute(step) : step(tx));
101
+ }
102
+ applied[schema.name] = schema.steps.length;
103
+ }
104
+ tx.setRecord(RECORD, new TextEncoder().encode(JSON.stringify(applied)));
105
+ }
106
+
107
+ /** The schemas of `schemas` that `applied` lacks steps of. */
108
+ const behind = (applied: Applied, schemas: readonly Schema[]) =>
109
+ schemas.filter((schema) => (applied[schema.name] ?? 0) < schema.steps.length);
110
+
111
+ /**
112
+ * Empty the database in the transaction `tx`: drop every table, view, index
113
+ * and trigger, and forget every schema, then apply `schemas` again. Its
114
+ * other records (the outbox) stay. It commits with `tx`: what `tx` writes
115
+ * after it are the new database's first rows.
116
+ */
117
+ export async function dropAll(tx: ConnectionTransaction, schemas: readonly Schema[]) {
118
+ const made = await tx.query<{ type: string; name: string }>(
119
+ "SELECT type, name FROM sqlite_schema WHERE substr(name, 1, 7) != 'sqlite_'",
120
+ );
121
+ // A trigger or view may name a table; an index goes with its table.
122
+ for (const type of ['trigger', 'view']) {
123
+ for (const { name } of made.filter((m) => m.type === type)) await drop(tx, type, name);
124
+ }
125
+ for (const name of await childrenFirst(
126
+ tx,
127
+ made.filter((m) => m.type === 'table').map((m) => m.name),
128
+ )) {
129
+ await drop(tx, 'table', name);
130
+ }
131
+ tx.setRecord(RECORD, new Uint8Array());
132
+ await applyIn(tx, schemas);
133
+ }
134
+
135
+ function drop(tx: ConnectionTransaction, type: string, name: string) {
136
+ return tx.execute(`DROP ${type.toUpperCase()} IF EXISTS "${name.replaceAll('"', '""')}"`);
137
+ }
138
+
139
+ /**
140
+ * `tables`, each after every table whose foreign keys name it: with foreign
141
+ * keys on, dropping a table deletes its rows, which a child's rows may not
142
+ * outlive. Tables in a cycle stay in their order.
143
+ */
144
+ async function childrenFirst(tx: ConnectionTransaction, tables: string[]): Promise<string[]> {
145
+ const parents = new Map<string, Set<string>>();
146
+ for (const name of tables) {
147
+ const keys = await tx.query<{ table: string }>('SELECT "table" FROM pragma_foreign_key_list(?)', [name]);
148
+ // SQL names are case-insensitive.
149
+ const own = name.toLowerCase();
150
+ parents.set(name, new Set(keys.map((k) => k.table.toLowerCase()).filter((t) => t !== own)));
151
+ }
152
+ const ordered: string[] = [];
153
+ let left = tables;
154
+ while (left.length > 0) {
155
+ const named = new Set(left.flatMap((name) => [...parents.get(name)!]));
156
+ const unnamed = left.filter((name) => !named.has(name.toLowerCase()));
157
+ const next = unnamed.length > 0 ? unnamed : left;
158
+ ordered.push(...next);
159
+ left = left.filter((name) => !next.includes(name));
160
+ }
161
+ return ordered;
162
+ }