@serfab/quereus-plugin-sereus 1.17.0 → 1.18.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.
@@ -1,491 +1,494 @@
1
- import debug from 'debug';
2
- import type { Database, VTablePluginInfo, FunctionPluginInfo, CollationPluginInfo } from '@quereus/quereus';
3
- import optimysticPlugin from '@optimystic/quereus-plugin-optimystic/plugin';
4
- import type { SqlCommitDurabilityListener, CommitFullyHeldListener } from '@optimystic/quereus-plugin-optimystic/plugin';
5
- import type { Libp2p } from '@libp2p/interface';
6
- import type { IRepo } from '@optimystic/db-core';
7
- import type { IRawStorage, NodeOptions } from '@optimystic/db-p2p';
8
- import type { StrandConnectionOptions, SereusPluginResult, StrandTransactor, Libp2pNodeWithRepo } from './types.js';
9
- import { STRAND_SCHEMA } from './strand-schema.js';
10
- import { resolveStrandClusterSize, STRAND_CLUSTER_POLICY } from './cluster-size.js';
11
- import { wrapStorageWithCache, disposeStorageCache } from './cached-storage.js';
12
- import { createEmptyCollections, type CollectionRegistrySource } from './empty-collections.js';
13
-
14
- const log = debug('sereus:plugin:strand');
15
- const timing = debug('sereus:plugin:strand:timing');
16
-
17
- /**
18
- * Minimal interface for the CollectionFactory returned by the optimystic plugin.
19
- * We only need the methods this composition actually uses.
20
- */
21
- interface CollectionFactory {
22
- registerLibp2pNode(networkName: string, node: Libp2p, coordinatedRepo: IRepo): void;
23
- /** Releases the read caches and network watches; leaves every registered node running. */
24
- dispose(): Promise<void>;
25
- /** {@link dispose}, after stopping every registered node. */
26
- shutdown(): Promise<void>;
27
- }
28
-
29
- /**
30
- * Release a composition's hold on the optimystic plugin. The transaction bridge goes first: its
31
- * durability follower subscribes to the node's `StorageRepo`, and cadre-core keeps a strand's node
32
- * across a database rebuild, so a bridge never disposed stays subscribed once per rebuild. Then the
33
- * collection factory: a node the composition created is stopped with it; an injected node is left
34
- * running, because it belongs to the caller — cadre-core keeps a strand's node up across a failed
35
- * database build and retries the build on it.
36
- *
37
- * Disposes the bridge itself rather than calling the plugin's `dispose()`, which would release the
38
- * factory a second time on the created-node path (`shutdown()` ends with the same `dispose()`).
39
- */
40
- async function releaseOptimysticPlugin(plugin: OptimysticPluginResult, createdNode: Libp2p | null): Promise<void> {
41
- // NOTE: the bridge's follower re-subscribes at the start of any transaction, so a write begun on
42
- // this `Database` after release (before its owner closes it) subscribes again and nothing
43
- // releases it. cadre-core stops its own writers before releasing; if an app write in flight at
44
- // close ever shows up as a leaked subscription, close the `Database` before releasing.
45
- plugin.txnBridge.dispose();
46
- const { collectionFactory } = plugin;
47
- if (!createdNode) {
48
- await collectionFactory.dispose();
49
- return;
50
- }
51
- await collectionFactory.shutdown();
52
- // Stopped again for a node created but not yet registered (a missing `coordinatedRepo`);
53
- // a second stop of a registered one is a no-op.
54
- await createdNode.stop();
55
- }
56
-
57
- /**
58
- * Result of registering the optimystic plugin. The published plugin signature
59
- * does not surface `collectionFactory` / `hydrate`, so this is the local shim
60
- * over what `@optimystic/quereus-plugin-optimystic/plugin` actually returns
61
- * (see its `plugin.ts` — `hydrate` delegates to `optimysticModule.hydrateCatalog`).
62
- */
63
- interface OptimysticPluginResult {
64
- collectionFactory: CollectionFactory;
65
- vtables: VTablePluginInfo[];
66
- functions: FunctionPluginInfo[];
67
- collations?: CollationPluginInfo[];
68
- /**
69
- * Hydrate Quereus's in-memory catalog from persisted optimystic vtab schemas.
70
- * Must run BEFORE `apply schema App;` on a warm restart so the declarative
71
- * diff sees the existing tables and skips re-emitting CREATE TABLE / CREATE
72
- * INDEX for each persisted object. Idempotent; `{ tables: 0, indexes: 0 }`
73
- * on cold start.
74
- */
75
- hydrate: (db: Database) => Promise<{ tables: number; indexes: number }>;
76
- onCommitDurability: (listener: SqlCommitDurabilityListener) => () => void;
77
- onCommitFullyHeld: (listener: CommitFullyHeldListener) => () => void;
78
- /**
79
- * Holds the durability follower's subscription to the node's `StorageRepo` (see
80
- * {@link releaseOptimysticPlugin}) and the registry of every collection a table opened (see
81
- * {@link createEmptyCollections}).
82
- */
83
- txnBridge: { dispose(): void } & CollectionRegistrySource;
84
- [key: string]: unknown;
85
- }
86
-
87
- /** Registration shape shared by the crypto and optimystic plugin results. */
88
- interface PluginRegistrations {
89
- vtables?: VTablePluginInfo[];
90
- functions?: FunctionPluginInfo[];
91
- collations?: CollationPluginInfo[];
92
- }
93
-
94
- /**
95
- * Inline equivalent of `@quereus/quereus`'s `registerPlugin` for plugins that
96
- * only return functions/vtables/collations. Used directly for the optimystic
97
- * result (so the composition can read `collectionFactory` off the same object),
98
- * and by the browser crypto strategy to keep the browser bundle from pulling a
99
- * duplicate `@quereus/quereus` next to the host's instance.
100
- */
101
- export function applyRegistrations(db: Database, result: PluginRegistrations): void {
102
- for (const vtable of result.vtables ?? []) {
103
- db.registerModule(vtable.name, vtable.module, vtable.auxData);
104
- }
105
- for (const func of result.functions ?? []) {
106
- db.registerFunction(func.schema);
107
- }
108
- for (const collation of result.collations ?? []) {
109
- db.registerCollation(collation.name, collation.func, collation.normalizer);
110
- }
111
- }
112
-
113
- /** Context passed to the platform's node-creation strategy. */
114
- export interface CreateNodeContext {
115
- networkName: string;
116
- bootstrapNodes: string[];
117
- fretProfile: 'edge' | 'core';
118
- /** libp2p listening port (Node TCP). Browser transports ignore it. */
119
- port: number;
120
- /**
121
- * Resolved replication cluster size. Already defaulted — pass it to
122
- * `createLibp2pNode` verbatim; omitting it falls back to Optimystic's own
123
- * default of 10, which gates writes on any smaller party.
124
- */
125
- clusterSize: number;
126
- /**
127
- * The strand cluster policy, resolved here so no platform has to remember it.
128
- * Pass it to `createLibp2pNode` verbatim.
129
- *
130
- * Omitting it does NOT fall back to something equivalent: Optimystic then computes
131
- * its read-repair corroboration floor against `clusterSize` instead of against
132
- * {@link STRAND_CLUSTER_POLICY}'s `assumedClusterSize`, which is a stricter demand
133
- * than a two-machine strand can meet — so repair of a damaged block gives up where
134
- * it would otherwise succeed. That is the same defect class that took the *control*
135
- * network's e2e suite down before `42cd12c`; see `cluster-size.ts` for the reasoning
136
- * written out in full.
137
- */
138
- clusterPolicy: NonNullable<NodeOptions['clusterPolicy']>;
139
- /** Resolved persistent storage to back the node, if any. */
140
- storage?: IRawStorage;
141
- }
142
-
143
- /** Context passed to the platform's storage-resolution strategy. */
144
- export interface ResolveStorageContext {
145
- strandId: string;
146
- resolvedTransactor: StrandTransactor;
147
- /** The storage the caller passed in `options.storage`, if any. */
148
- requestedStorage?: IRawStorage;
149
- }
150
-
151
- /**
152
- * Platform-specific seams the shared composition delegates to. Everything else
153
- * (transactor resolution, plugin config, registration, default vtab, hydrate,
154
- * schema apply, cleanup/shutdown) is identical across Node and browser and lives
155
- * in {@link composeStrand}.
156
- */
157
- export interface StrandPlatform {
158
- /**
159
- * Register the crypto plugin against `db`. Node uses `@quereus/quereus`'s
160
- * `registerPlugin`; the browser inlines `applyRegistrations` to avoid bundling
161
- * a second `@quereus/quereus`.
162
- */
163
- registerCrypto(db: Database): void | Promise<void>;
164
- /**
165
- * Resolve the persistent storage to use. Optional — when omitted the caller's
166
- * `options.storage` is used verbatim (Node). The browser supplies this to
167
- * default to IndexedDB so a reload survives.
168
- */
169
- resolveStorage?(ctx: ResolveStorageContext): Promise<IRawStorage | undefined> | IRawStorage | undefined;
170
- /**
171
- * Create a libp2p node. Called only when no node is injected and the
172
- * transactor needs one. Node creates a TCP node via `@optimystic/db-p2p`;
173
- * the browser creates a WebSockets + circuit-relay node via the `/rn` entry.
174
- * Returns the created node (its `coordinatedRepo` is read by the composition).
175
- */
176
- createNode(ctx: CreateNodeContext): Promise<Libp2p>;
177
- }
178
-
179
- /**
180
- * Connect a Quereus `Database` to a Sereus strand. This is the single shared
181
- * SQL-surface composition: `connectToStrand` (Node), `connectToStrandBrowser`
182
- * (browser), and `cadre-core`'s `StrandDatabase` all flow through here, so the
183
- * hydrate-before-apply fix and any future schema wiring land in one place.
184
- *
185
- * Steps: resolve transactor + storage, register crypto + optimystic plugins,
186
- * acquire (inject or create) the libp2p node, set optimystic as the default
187
- * vtab, hydrate the catalog, then apply the sApp schema.
188
- */
189
- export async function composeStrand(
190
- db: Database,
191
- options: StrandConnectionOptions,
192
- platform: StrandPlatform,
193
- ): Promise<SereusPluginResult> {
194
- const {
195
- strandId,
196
- bootstrapNodes = [],
197
- schema,
198
- port = 0,
199
- enableCache = true,
200
- fretProfile = 'edge',
201
- transactor = 'network',
202
- } = options;
203
-
204
- // Resolve (and validate) up front so a nonsense value fails before any plugin
205
- // registration or node creation has happened.
206
- const clusterSize = resolveStrandClusterSize(options.clusterSize);
207
-
208
- // The storage engine every write and read below goes through — see
209
- // `StrandConnectionOptions.transactor`. Named separately from the option so
210
- // the default is applied exactly once and reported on the result.
211
- const resolvedTransactor: StrandTransactor = transactor;
212
-
213
- const networkName = `strand-${strandId}`;
214
- log('Connecting to strand %s (network: %s, transactor=%s)',
215
- strandId, networkName, resolvedTransactor);
216
-
217
- // Resolve storage. Node passes `options.storage` through; the browser
218
- // defaults to IndexedDB. The resolved instance feeds BOTH the local
219
- // transactor's `rawStorageFactory` and node creation, so it must be decided
220
- // up front (before pluginConfig is built). Wrapped in the write-through
221
- // raw-storage cache (cached-storage.ts) — idempotent, so a caller that
222
- // already wrapped (cadre-core's seams) passes through unchanged, with this
223
- // composition counted as one more holder of that same cache.
224
- const resolvedStorage = platform.resolveStorage
225
- ? await platform.resolveStorage({ strandId, resolvedTransactor, requestedStorage: options.storage })
226
- : options.storage;
227
- const storage = resolvedStorage ? wrapStorageWithCache(resolvedStorage, strandId) : resolvedStorage;
228
-
229
- /**
230
- * Release THIS composition's claim on the storage cache — the matching half of the
231
- * wrap above, which took one. `wrapStorageWithCache` counts holders, so this is
232
- * unconditionally correct whoever created the wrapper: the cache stays live while
233
- * cadre-core (or any other seam over the same store) still holds a claim, and is
234
- * emptied and unregistered from the shared cache pool when the last one goes. Holding
235
- * a claim past the strand's life is not free — the registration claims the backing
236
- * store in the pool, and a claim outliving its strand makes the next connect over that
237
- * same directory throw.
238
- *
239
- * Latched, so a caller that calls `shutdown()` twice releases one claim, not two — a
240
- * second release would consume another scope's claim.
241
- */
242
- let storageCacheReleased = false;
243
- const releaseStorageCache = async (): Promise<void> => {
244
- if (storageCacheReleased || !storage) {
245
- return;
246
- }
247
- storageCacheReleased = true;
248
- await disposeStorageCache(storage);
249
- };
250
-
251
- // 1-2. Register the crypto and optimystic plugins. Guarded on its own, because the
252
- // wrap above has ALREADY taken a holder claim: a registration that throws must release
253
- // it, or the claim — and the backing store's registration in the shared cache pool —
254
- // outlives the failed connect for the process lifetime, and no other scope can retire
255
- // the cache. Separate from the larger try below, which has a collection factory and
256
- // possibly a node to tear down as well; neither exists yet here.
257
- let pluginResult: OptimysticPluginResult;
258
- try {
259
- pluginResult = await registerStrandPlugins(db, platform, {
260
- resolvedTransactor,
261
- networkName,
262
- enableCache,
263
- storage,
264
- });
265
- } catch (err) {
266
- await releaseStorageCache();
267
- throw err;
268
- }
269
-
270
- const { collectionFactory } = pluginResult;
271
-
272
- let createdNode: Libp2p | null = null;
273
- let hydrated: { tables: number; indexes: number } | undefined;
274
-
275
- try {
276
- // 3. Acquire the libp2p node. Skip only when this is the unit-test fake
277
- // transactor with no injected node — every real path needs a node.
278
- if (resolvedTransactor !== 'test' || options.libp2pNode) {
279
- let node: Libp2p;
280
- let coordinatedRepo: IRepo;
281
-
282
- if (options.libp2pNode) {
283
- node = options.libp2pNode;
284
- if (!options.coordinatedRepo) {
285
- throw new Error('coordinatedRepo is required when libp2pNode is provided');
286
- }
287
- coordinatedRepo = options.coordinatedRepo;
288
- log('Using injected libp2p node');
289
- } else {
290
- // NOTE: this path takes the frozen policy whole, so it takes COHORT_READ_DEADLINE_MS
291
- // with no way to override it — `StrandConnectionOptions` has no counterpart to
292
- // cadre-core's `NetworkConfig.cohortQueryTimeoutMs` or `linkRoundTripMs`. Fine
293
- // today: every production strand comes up through cadre-core, which does thread
294
- // both, and this path is the plugin's own connect/e2e route, where the constant —
295
- // two link round trips at cadre's default declared link — is the right answer
296
- // anyway. If a plugin embedder ever needs a different deadline,
297
- // `strandClusterPolicy(clusterSize, { cohortQueryTimeoutMs: <ms> })` is the call to
298
- // reach for here.
299
- const created = await platform.createNode({ networkName, bootstrapNodes, fretProfile, port, clusterSize, clusterPolicy: STRAND_CLUSTER_POLICY, storage });
300
- createdNode = created;
301
- node = created;
302
- const repo = (created as Libp2pNodeWithRepo).coordinatedRepo;
303
- if (!repo) {
304
- throw new Error('coordinatedRepo not available on created libp2p node');
305
- }
306
- coordinatedRepo = repo;
307
- log('Created libp2p node (port: %d, fretProfile: %s, storage=%s)', port, fretProfile, !!storage);
308
- }
309
-
310
- collectionFactory.registerLibp2pNode(networkName, node, coordinatedRepo);
311
- log('Registered libp2p node with collection factory');
312
- }
313
-
314
- // 4. Set optimystic as default vtab so `declare schema` tables use it.
315
- db.setDefaultVtabName('optimystic');
316
- db.setDefaultVtabArgs({
317
- networkName,
318
- transactor: resolvedTransactor,
319
- keyNetwork: 'libp2p',
320
- });
321
- log('Set default vtab to optimystic (networkName=%s, transactor=%s)', networkName, resolvedTransactor);
322
-
323
- // 5. Hydrate Quereus's catalog from persisted optimystic vtab schemas
324
- // BEFORE applying the sApp schema. Without this, a warm restart diffs the
325
- // wrapped DDL against an empty catalog and re-emits CREATE TABLE / CREATE
326
- // INDEX for every persisted object — each round-tripping through optimystic
327
- // storage (the measured ~160s warm-start regression). No-op on first launch.
328
- const t0 = performance.now();
329
- hydrated = await pluginResult.hydrate(db);
330
- timing('[strand:%s] hydrate: %dms (tables=%d, indexes=%d)',
331
- strandId, Math.round(performance.now() - t0), hydrated.tables, hydrated.indexes);
332
- log('Hydrated catalog for strand %s (tables=%d, indexes=%d)', strandId, hydrated.tables, hydrated.indexes);
333
-
334
- // 6. Apply the strand membership/RBAC schema (`schemas/strand.qsql`,
335
- // embedded as STRAND_SCHEMA) UNCONDITIONALLY — every strand has membership
336
- // semantics whether or not an sApp schema is supplied. There are no
337
- // cross-schema references between `Strand` and `App`, so order is
338
- // irrelevant; apply `Strand` first for clarity. Because this runs AFTER
339
- // hydrate, a warm restart diffs the membership DDL against the already-
340
- // hydrated catalog and re-emits nothing (same fix as the sApp apply).
341
- //
342
- // This ticket only makes the tables present and their constraints active;
343
- // nothing here writes membership rows. Founder bootstrap (Header, founding
344
- // Manager/Member, invite/peer flows) is owned by the lifecycle ticket
345
- // `strand-membership-lifecycle-population`.
346
- log('Applying Strand membership schema for strand %s', strandId);
347
- await db.exec(`
348
- declare schema Strand {
349
- ${STRAND_SCHEMA}
350
- }
351
- apply schema Strand;
352
- `);
353
- log('Strand membership schema applied');
354
-
355
- // 7. Apply the sApp schema, if provided.
356
- //
357
- // SEAM: this and the Strand apply above are the single composition point
358
- // where strand-level declarative DDL is applied. Keep new schema wiring
359
- // here so it stays a one-location edit across Node, browser, and cadre-core.
360
- //
361
- // NOTE: neither apply is retried here — a failure releases this composition and throws,
362
- // and a later connect builds a fresh `Database` and re-hydrates from storage. A
363
- // failed apply is normally taken back whole (Quereus unwinds its migration steps
364
- // and verifies the catalog against a pre-apply fingerprint), so the next connect
365
- // diffs against the state the apply started from. The sApp schema is the one
366
- // supplied by the EMBEDDER, and the steps that DISCARD data — dropping a table,
367
- // dropping a column, narrowing a column's type — are irreversible to Quereus's
368
- // differ: once one has run, any later step that fails leaves the schema partially
369
- // migrated instead of restored. No schema in this repo evolves that way, so this
370
- // is a note for whoever first ships a migration that does.
371
- if (schema) {
372
- log('Applying sApp schema for strand %s', strandId);
373
- await applyAppSchema(db, schema);
374
- log('sApp schema applied');
375
- }
376
- } catch (err) {
377
- // Clean up resources if setup fails after partial initialization.
378
- await releaseOptimysticPlugin(pluginResult, createdNode);
379
- await releaseStorageCache();
380
- throw err;
381
- }
382
-
383
- // 8. Return result with hydrate counts, the commit-durability listeners, the founder's
384
- // empty-collection step + shutdown handler.
385
- // `shutdown` releases the plugin and stops the node only if this composition created it.
386
- return {
387
- vtables: [],
388
- functions: [],
389
- collations: [],
390
- hydrated,
391
- transactor: resolvedTransactor,
392
- onCommitDurability: listener => pluginResult.onCommitDurability(listener),
393
- onCommitFullyHeld: listener => pluginResult.onCommitFullyHeld(listener),
394
- createEmptyCollections: () => createEmptyCollections(db, pluginResult.txnBridge),
395
- async shutdown() {
396
- log('Shutting down strand connection %s', strandId);
397
- await releaseOptimysticPlugin(pluginResult, createdNode);
398
- await releaseStorageCache();
399
- log('Strand connection %s shut down', strandId);
400
- },
401
- };
402
- }
403
-
404
- /**
405
- * Step 7 of {@link composeStrand}: declare the sApp's schema as `App` and apply it — a
406
- * declarative diff against the catalog, so re-applying a schema that is already in place
407
- * emits nothing. The one site that applies an `App` schema: `composeStrand` calls it at
408
- * bring-up, and cadre-core's `StrandDatabase.attachAppSchema` calls it on a live storage
409
- * replica when an app claims the strand. The database must already be composed (optimystic
410
- * set as the default vtab), or the tables land in memory instead of the strand.
411
- *
412
- * Refuses a schema holding an item the Quereus parser skipped: it keeps any item whose leading
413
- * keyword it does not model (`create unique index …`, a misspelled `tabel`, `domain`) as an
414
- * opaque placeholder that apply ignores, so the app would otherwise run without that item.
415
- *
416
- * Refuses a schema holding a `seed` item: the apply runs on every node of the strand at every
417
- * connect, so seed inserts would put a network write on each bring-up and two nodes inserting
418
- * the same key at once would collide. Rows an app needs at birth are the founding app's to write.
419
- */
420
- export async function applyAppSchema(db: Database, schema: string): Promise<void> {
421
- await db.exec(`
422
- declare schema App {
423
- ${schema}
424
- }
425
- `);
426
- assertNoIgnoredItems(db);
427
- assertNoSeedItems(db);
428
- await db.exec('apply schema App;');
429
- }
430
-
431
- function declaredAppItems(db: Database) {
432
- return db.declaredSchemaManager.getDeclaredSchema('App')?.items ?? [];
433
- }
434
-
435
- function assertNoIgnoredItems(db: Database): void {
436
- const ignored = declaredAppItems(db).filter(item => item.type === 'declareIgnored').length;
437
- if (ignored > 0) {
438
- // Only a count: Quereus leaves an ignored item's source text empty.
439
- throw new Error(`sApp schema has ${ignored} item(s) the parser does not recognize (a \`create …\` prefix or a misspelled item keyword such as \`tabel\`); items are \`table\`, \`index\`, \`unique index\`, \`view\`, \`materialized view\` and \`assertion\``);
440
- }
441
- }
442
-
443
- function assertNoSeedItems(db: Database): void {
444
- // Quereus refuses a second seed for one table at declare, so these names are distinct.
445
- const tables = declaredAppItems(db).flatMap(item => item.type === 'declaredSeed' ? [item.tableName] : []);
446
- if (tables.length > 0) {
447
- throw new Error(`sApp schema has seed item(s) for table(s) ${tables.join(', ')}; Sereus does not apply seed rows to a strand — insert the rows an app needs at birth from the app when it founds the strand`);
448
- }
449
- }
450
-
451
- /**
452
- * Steps 1-2 of {@link composeStrand}: register the crypto plugin, then the optimystic
453
- * plugin carrying this strand's transactor defaults. Split out so the composition can
454
- * guard the pair against the storage-cache claim it has already taken.
455
- */
456
- async function registerStrandPlugins(
457
- db: Database,
458
- platform: StrandPlatform,
459
- strand: {
460
- resolvedTransactor: StrandTransactor;
461
- networkName: string;
462
- enableCache: boolean;
463
- storage: IRawStorage | undefined;
464
- },
465
- ): Promise<OptimysticPluginResult> {
466
- await platform.registerCrypto(db);
467
- log('Registered crypto plugin');
468
-
469
- // On the local transactor with persistent storage, hand the same instance to the
470
- // plugin so DML persists on the host backend (not in-memory).
471
- const pluginConfig: Record<string, unknown> = {
472
- default_transactor: strand.resolvedTransactor,
473
- default_key_network: 'libp2p',
474
- default_network_name: strand.networkName,
475
- enable_cache: strand.enableCache,
476
- };
477
- if (strand.resolvedTransactor === 'local' && strand.storage) {
478
- const storage = strand.storage;
479
- pluginConfig.rawStorageFactory = () => storage;
480
- }
481
- // The plugin's published signature is `Record<string, SqlValue>` but it also reads
482
- // `rawStorageFactory` (a function reference) from the same map. Cast through unknown
483
- // rather than widen the public type.
484
- const pluginResult = optimysticPlugin(
485
- db,
486
- pluginConfig as unknown as Parameters<typeof optimysticPlugin>[1],
487
- ) as unknown as OptimysticPluginResult;
488
- applyRegistrations(db, pluginResult);
489
- log('Registered optimystic vtables and functions');
490
- return pluginResult;
491
- }
1
+ import debug from 'debug';
2
+ import type { Database, VTablePluginInfo, FunctionPluginInfo, CollationPluginInfo } from '@quereus/quereus';
3
+ import optimysticPlugin from '@optimystic/quereus-plugin-optimystic/plugin';
4
+ import type { SqlCommitDurabilityListener, CommitFullyHeldListener } from '@optimystic/quereus-plugin-optimystic/plugin';
5
+ import type { Libp2p } from '@libp2p/interface';
6
+ import type { IRepo } from '@optimystic/db-core';
7
+ import type { IRawStorage, NodeOptions } from '@optimystic/db-p2p';
8
+ import type { StrandConnectionOptions, SereusPluginResult, StrandTransactor, Libp2pNodeWithRepo } from './types.js';
9
+ import { STRAND_SCHEMA } from './strand-schema.js';
10
+ import { resolveStrandClusterSize, STRAND_CLUSTER_POLICY } from './cluster-size.js';
11
+ import { wrapStorageWithCache, disposeStorageCache } from './cached-storage.js';
12
+ import { createEmptyCollections, type CollectionRegistrySource } from './empty-collections.js';
13
+
14
+ const log = debug('sereus:plugin:strand');
15
+ const timing = debug('sereus:plugin:strand:timing');
16
+
17
+ /** The schemas whose tables a strand founder gives a collection: strand membership, then the sApp's. */
18
+ const FOUNDED_SCHEMAS = ['Strand', 'App'] as const;
19
+
20
+ /**
21
+ * Minimal interface for the CollectionFactory returned by the optimystic plugin.
22
+ * We only need the methods this composition actually uses.
23
+ */
24
+ interface CollectionFactory {
25
+ registerLibp2pNode(networkName: string, node: Libp2p, coordinatedRepo: IRepo): void;
26
+ /** Releases the read caches and network watches; leaves every registered node running. */
27
+ dispose(): Promise<void>;
28
+ /** {@link dispose}, after stopping every registered node. */
29
+ shutdown(): Promise<void>;
30
+ }
31
+
32
+ /**
33
+ * Release a composition's hold on the optimystic plugin. The transaction bridge goes first: its
34
+ * durability follower subscribes to the node's `StorageRepo`, and cadre-core keeps a strand's node
35
+ * across a database rebuild, so a bridge never disposed stays subscribed once per rebuild. Then the
36
+ * collection factory: a node the composition created is stopped with it; an injected node is left
37
+ * running, because it belongs to the caller — cadre-core keeps a strand's node up across a failed
38
+ * database build and retries the build on it.
39
+ *
40
+ * Disposes the bridge itself rather than calling the plugin's `dispose()`, which would release the
41
+ * factory a second time on the created-node path (`shutdown()` ends with the same `dispose()`).
42
+ */
43
+ async function releaseOptimysticPlugin(plugin: OptimysticPluginResult, createdNode: Libp2p | null): Promise<void> {
44
+ // NOTE: the bridge's follower re-subscribes at the start of any transaction, so a write begun on
45
+ // this `Database` after release (before its owner closes it) subscribes again and nothing
46
+ // releases it. cadre-core stops its own writers before releasing; if an app write in flight at
47
+ // close ever shows up as a leaked subscription, close the `Database` before releasing.
48
+ plugin.txnBridge.dispose();
49
+ const { collectionFactory } = plugin;
50
+ if (!createdNode) {
51
+ await collectionFactory.dispose();
52
+ return;
53
+ }
54
+ await collectionFactory.shutdown();
55
+ // Stopped again for a node created but not yet registered (a missing `coordinatedRepo`);
56
+ // a second stop of a registered one is a no-op.
57
+ await createdNode.stop();
58
+ }
59
+
60
+ /**
61
+ * Result of registering the optimystic plugin. The published plugin signature
62
+ * does not surface `collectionFactory` / `hydrate`, so this is the local shim
63
+ * over what `@optimystic/quereus-plugin-optimystic/plugin` actually returns
64
+ * (see its `plugin.ts` — `hydrate` delegates to `optimysticModule.hydrateCatalog`).
65
+ */
66
+ interface OptimysticPluginResult {
67
+ collectionFactory: CollectionFactory;
68
+ vtables: VTablePluginInfo[];
69
+ functions: FunctionPluginInfo[];
70
+ collations?: CollationPluginInfo[];
71
+ /**
72
+ * Hydrate Quereus's in-memory catalog from persisted optimystic vtab schemas.
73
+ * Must run BEFORE `apply schema App;` on a warm restart so the declarative
74
+ * diff sees the existing tables and skips re-emitting CREATE TABLE / CREATE
75
+ * INDEX for each persisted object. Idempotent; `{ tables: 0, indexes: 0 }`
76
+ * on cold start.
77
+ */
78
+ hydrate: (db: Database) => Promise<{ tables: number; indexes: number }>;
79
+ onCommitDurability: (listener: SqlCommitDurabilityListener) => () => void;
80
+ onCommitFullyHeld: (listener: CommitFullyHeldListener) => () => void;
81
+ /**
82
+ * Holds the durability follower's subscription to the node's `StorageRepo` (see
83
+ * {@link releaseOptimysticPlugin}) and the registry of every collection a table opened (see
84
+ * {@link createEmptyCollections}).
85
+ */
86
+ txnBridge: { dispose(): void } & CollectionRegistrySource;
87
+ [key: string]: unknown;
88
+ }
89
+
90
+ /** Registration shape shared by the crypto and optimystic plugin results. */
91
+ interface PluginRegistrations {
92
+ vtables?: VTablePluginInfo[];
93
+ functions?: FunctionPluginInfo[];
94
+ collations?: CollationPluginInfo[];
95
+ }
96
+
97
+ /**
98
+ * Inline equivalent of `@quereus/quereus`'s `registerPlugin` for plugins that
99
+ * only return functions/vtables/collations. Used directly for the optimystic
100
+ * result (so the composition can read `collectionFactory` off the same object),
101
+ * and by the browser crypto strategy to keep the browser bundle from pulling a
102
+ * duplicate `@quereus/quereus` next to the host's instance.
103
+ */
104
+ export function applyRegistrations(db: Database, result: PluginRegistrations): void {
105
+ for (const vtable of result.vtables ?? []) {
106
+ db.registerModule(vtable.name, vtable.module, vtable.auxData);
107
+ }
108
+ for (const func of result.functions ?? []) {
109
+ db.registerFunction(func.schema);
110
+ }
111
+ for (const collation of result.collations ?? []) {
112
+ db.registerCollation(collation.name, collation.func, collation.normalizer);
113
+ }
114
+ }
115
+
116
+ /** Context passed to the platform's node-creation strategy. */
117
+ export interface CreateNodeContext {
118
+ networkName: string;
119
+ bootstrapNodes: string[];
120
+ fretProfile: 'edge' | 'core';
121
+ /** libp2p listening port (Node TCP). Browser transports ignore it. */
122
+ port: number;
123
+ /**
124
+ * Resolved replication cluster size. Already defaulted — pass it to
125
+ * `createLibp2pNode` verbatim; omitting it falls back to Optimystic's own
126
+ * default of 10, which gates writes on any smaller party.
127
+ */
128
+ clusterSize: number;
129
+ /**
130
+ * The strand cluster policy, resolved here so no platform has to remember it.
131
+ * Pass it to `createLibp2pNode` verbatim.
132
+ *
133
+ * Omitting it does NOT fall back to something equivalent: Optimystic then computes
134
+ * its read-repair corroboration floor against `clusterSize` instead of against
135
+ * {@link STRAND_CLUSTER_POLICY}'s `assumedClusterSize`, which is a stricter demand
136
+ * than a two-machine strand can meet — so repair of a damaged block gives up where
137
+ * it would otherwise succeed. That is the same defect class that took the *control*
138
+ * network's e2e suite down before `42cd12c`; see `cluster-size.ts` for the reasoning
139
+ * written out in full.
140
+ */
141
+ clusterPolicy: NonNullable<NodeOptions['clusterPolicy']>;
142
+ /** Resolved persistent storage to back the node, if any. */
143
+ storage?: IRawStorage;
144
+ }
145
+
146
+ /** Context passed to the platform's storage-resolution strategy. */
147
+ export interface ResolveStorageContext {
148
+ strandId: string;
149
+ resolvedTransactor: StrandTransactor;
150
+ /** The storage the caller passed in `options.storage`, if any. */
151
+ requestedStorage?: IRawStorage;
152
+ }
153
+
154
+ /**
155
+ * Platform-specific seams the shared composition delegates to. Everything else
156
+ * (transactor resolution, plugin config, registration, default vtab, hydrate,
157
+ * schema apply, cleanup/shutdown) is identical across Node and browser and lives
158
+ * in {@link composeStrand}.
159
+ */
160
+ export interface StrandPlatform {
161
+ /**
162
+ * Register the crypto plugin against `db`. Node uses `@quereus/quereus`'s
163
+ * `registerPlugin`; the browser inlines `applyRegistrations` to avoid bundling
164
+ * a second `@quereus/quereus`.
165
+ */
166
+ registerCrypto(db: Database): void | Promise<void>;
167
+ /**
168
+ * Resolve the persistent storage to use. Optional — when omitted the caller's
169
+ * `options.storage` is used verbatim (Node). The browser supplies this to
170
+ * default to IndexedDB so a reload survives.
171
+ */
172
+ resolveStorage?(ctx: ResolveStorageContext): Promise<IRawStorage | undefined> | IRawStorage | undefined;
173
+ /**
174
+ * Create a libp2p node. Called only when no node is injected and the
175
+ * transactor needs one. Node creates a TCP node via `@optimystic/db-p2p`;
176
+ * the browser creates a WebSockets + circuit-relay node via the `/rn` entry.
177
+ * Returns the created node (its `coordinatedRepo` is read by the composition).
178
+ */
179
+ createNode(ctx: CreateNodeContext): Promise<Libp2p>;
180
+ }
181
+
182
+ /**
183
+ * Connect a Quereus `Database` to a Sereus strand. This is the single shared
184
+ * SQL-surface composition: `connectToStrand` (Node), `connectToStrandBrowser`
185
+ * (browser), and `cadre-core`'s `StrandDatabase` all flow through here, so the
186
+ * hydrate-before-apply fix and any future schema wiring land in one place.
187
+ *
188
+ * Steps: resolve transactor + storage, register crypto + optimystic plugins,
189
+ * acquire (inject or create) the libp2p node, set optimystic as the default
190
+ * vtab, hydrate the catalog, then apply the sApp schema.
191
+ */
192
+ export async function composeStrand(
193
+ db: Database,
194
+ options: StrandConnectionOptions,
195
+ platform: StrandPlatform,
196
+ ): Promise<SereusPluginResult> {
197
+ const {
198
+ strandId,
199
+ bootstrapNodes = [],
200
+ schema,
201
+ port = 0,
202
+ enableCache = true,
203
+ fretProfile = 'edge',
204
+ transactor = 'network',
205
+ } = options;
206
+
207
+ // Resolve (and validate) up front so a nonsense value fails before any plugin
208
+ // registration or node creation has happened.
209
+ const clusterSize = resolveStrandClusterSize(options.clusterSize);
210
+
211
+ // The storage engine every write and read below goes through — see
212
+ // `StrandConnectionOptions.transactor`. Named separately from the option so
213
+ // the default is applied exactly once and reported on the result.
214
+ const resolvedTransactor: StrandTransactor = transactor;
215
+
216
+ const networkName = `strand-${strandId}`;
217
+ log('Connecting to strand %s (network: %s, transactor=%s)',
218
+ strandId, networkName, resolvedTransactor);
219
+
220
+ // Resolve storage. Node passes `options.storage` through; the browser
221
+ // defaults to IndexedDB. The resolved instance feeds BOTH the local
222
+ // transactor's `rawStorageFactory` and node creation, so it must be decided
223
+ // up front (before pluginConfig is built). Wrapped in the write-through
224
+ // raw-storage cache (cached-storage.ts) — idempotent, so a caller that
225
+ // already wrapped (cadre-core's seams) passes through unchanged, with this
226
+ // composition counted as one more holder of that same cache.
227
+ const resolvedStorage = platform.resolveStorage
228
+ ? await platform.resolveStorage({ strandId, resolvedTransactor, requestedStorage: options.storage })
229
+ : options.storage;
230
+ const storage = resolvedStorage ? wrapStorageWithCache(resolvedStorage, strandId) : resolvedStorage;
231
+
232
+ /**
233
+ * Release THIS composition's claim on the storage cache — the matching half of the
234
+ * wrap above, which took one. `wrapStorageWithCache` counts holders, so this is
235
+ * unconditionally correct whoever created the wrapper: the cache stays live while
236
+ * cadre-core (or any other seam over the same store) still holds a claim, and is
237
+ * emptied and unregistered from the shared cache pool when the last one goes. Holding
238
+ * a claim past the strand's life is not free — the registration claims the backing
239
+ * store in the pool, and a claim outliving its strand makes the next connect over that
240
+ * same directory throw.
241
+ *
242
+ * Latched, so a caller that calls `shutdown()` twice releases one claim, not two — a
243
+ * second release would consume another scope's claim.
244
+ */
245
+ let storageCacheReleased = false;
246
+ const releaseStorageCache = async (): Promise<void> => {
247
+ if (storageCacheReleased || !storage) {
248
+ return;
249
+ }
250
+ storageCacheReleased = true;
251
+ await disposeStorageCache(storage);
252
+ };
253
+
254
+ // 1-2. Register the crypto and optimystic plugins. Guarded on its own, because the
255
+ // wrap above has ALREADY taken a holder claim: a registration that throws must release
256
+ // it, or the claim — and the backing store's registration in the shared cache pool —
257
+ // outlives the failed connect for the process lifetime, and no other scope can retire
258
+ // the cache. Separate from the larger try below, which has a collection factory and
259
+ // possibly a node to tear down as well; neither exists yet here.
260
+ let pluginResult: OptimysticPluginResult;
261
+ try {
262
+ pluginResult = await registerStrandPlugins(db, platform, {
263
+ resolvedTransactor,
264
+ networkName,
265
+ enableCache,
266
+ storage,
267
+ });
268
+ } catch (err) {
269
+ await releaseStorageCache();
270
+ throw err;
271
+ }
272
+
273
+ const { collectionFactory } = pluginResult;
274
+
275
+ let createdNode: Libp2p | null = null;
276
+ let hydrated: { tables: number; indexes: number } | undefined;
277
+
278
+ try {
279
+ // 3. Acquire the libp2p node. Skip only when this is the unit-test fake
280
+ // transactor with no injected node — every real path needs a node.
281
+ if (resolvedTransactor !== 'test' || options.libp2pNode) {
282
+ let node: Libp2p;
283
+ let coordinatedRepo: IRepo;
284
+
285
+ if (options.libp2pNode) {
286
+ node = options.libp2pNode;
287
+ if (!options.coordinatedRepo) {
288
+ throw new Error('coordinatedRepo is required when libp2pNode is provided');
289
+ }
290
+ coordinatedRepo = options.coordinatedRepo;
291
+ log('Using injected libp2p node');
292
+ } else {
293
+ // NOTE: this path takes the frozen policy whole, so it takes COHORT_READ_DEADLINE_MS
294
+ // with no way to override it — `StrandConnectionOptions` has no counterpart to
295
+ // cadre-core's `NetworkConfig.cohortQueryTimeoutMs` or `linkRoundTripMs`. Fine
296
+ // today: every production strand comes up through cadre-core, which does thread
297
+ // both, and this path is the plugin's own connect/e2e route, where the constant —
298
+ // two link round trips at cadre's default declared link — is the right answer
299
+ // anyway. If a plugin embedder ever needs a different deadline,
300
+ // `strandClusterPolicy(clusterSize, { cohortQueryTimeoutMs: <ms> })` is the call to
301
+ // reach for here.
302
+ const created = await platform.createNode({ networkName, bootstrapNodes, fretProfile, port, clusterSize, clusterPolicy: STRAND_CLUSTER_POLICY, storage });
303
+ createdNode = created;
304
+ node = created;
305
+ const repo = (created as Libp2pNodeWithRepo).coordinatedRepo;
306
+ if (!repo) {
307
+ throw new Error('coordinatedRepo not available on created libp2p node');
308
+ }
309
+ coordinatedRepo = repo;
310
+ log('Created libp2p node (port: %d, fretProfile: %s, storage=%s)', port, fretProfile, !!storage);
311
+ }
312
+
313
+ collectionFactory.registerLibp2pNode(networkName, node, coordinatedRepo);
314
+ log('Registered libp2p node with collection factory');
315
+ }
316
+
317
+ // 4. Set optimystic as default vtab so `declare schema` tables use it.
318
+ db.setDefaultVtabName('optimystic');
319
+ db.setDefaultVtabArgs({
320
+ networkName,
321
+ transactor: resolvedTransactor,
322
+ keyNetwork: 'libp2p',
323
+ });
324
+ log('Set default vtab to optimystic (networkName=%s, transactor=%s)', networkName, resolvedTransactor);
325
+
326
+ // 5. Hydrate Quereus's catalog from persisted optimystic vtab schemas
327
+ // BEFORE applying the sApp schema. Without this, a warm restart diffs the
328
+ // wrapped DDL against an empty catalog and re-emits CREATE TABLE / CREATE
329
+ // INDEX for every persisted object — each round-tripping through optimystic
330
+ // storage (the measured ~160s warm-start regression). No-op on first launch.
331
+ const t0 = performance.now();
332
+ hydrated = await pluginResult.hydrate(db);
333
+ timing('[strand:%s] hydrate: %dms (tables=%d, indexes=%d)',
334
+ strandId, Math.round(performance.now() - t0), hydrated.tables, hydrated.indexes);
335
+ log('Hydrated catalog for strand %s (tables=%d, indexes=%d)', strandId, hydrated.tables, hydrated.indexes);
336
+
337
+ // 6. Apply the strand membership/RBAC schema (`schemas/strand.qsql`,
338
+ // embedded as STRAND_SCHEMA) UNCONDITIONALLY — every strand has membership
339
+ // semantics whether or not an sApp schema is supplied. There are no
340
+ // cross-schema references between `Strand` and `App`, so order is
341
+ // irrelevant; apply `Strand` first for clarity. Because this runs AFTER
342
+ // hydrate, a warm restart diffs the membership DDL against the already-
343
+ // hydrated catalog and re-emits nothing (same fix as the sApp apply).
344
+ //
345
+ // This ticket only makes the tables present and their constraints active;
346
+ // nothing here writes membership rows. Founder bootstrap (Header, founding
347
+ // Manager/Member, invite/peer flows) is owned by the lifecycle ticket
348
+ // `strand-membership-lifecycle-population`.
349
+ log('Applying Strand membership schema for strand %s', strandId);
350
+ await db.exec(`
351
+ declare schema Strand {
352
+ ${STRAND_SCHEMA}
353
+ }
354
+ apply schema Strand;
355
+ `);
356
+ log('Strand membership schema applied');
357
+
358
+ // 7. Apply the sApp schema, if provided.
359
+ //
360
+ // SEAM: this and the Strand apply above are the single composition point
361
+ // where strand-level declarative DDL is applied. Keep new schema wiring
362
+ // here so it stays a one-location edit across Node, browser, and cadre-core.
363
+ //
364
+ // NOTE: neither apply is retried here — a failure releases this composition and throws,
365
+ // and a later connect builds a fresh `Database` and re-hydrates from storage. A
366
+ // failed apply is normally taken back whole (Quereus unwinds its migration steps
367
+ // and verifies the catalog against a pre-apply fingerprint), so the next connect
368
+ // diffs against the state the apply started from. The sApp schema is the one
369
+ // supplied by the EMBEDDER, and the steps that DISCARD data — dropping a table,
370
+ // dropping a column, narrowing a column's type — are irreversible to Quereus's
371
+ // differ: once one has run, any later step that fails leaves the schema partially
372
+ // migrated instead of restored. No schema in this repo evolves that way, so this
373
+ // is a note for whoever first ships a migration that does.
374
+ if (schema) {
375
+ log('Applying sApp schema for strand %s', strandId);
376
+ await applyAppSchema(db, schema);
377
+ log('sApp schema applied');
378
+ }
379
+ } catch (err) {
380
+ // Clean up resources if setup fails after partial initialization.
381
+ await releaseOptimysticPlugin(pluginResult, createdNode);
382
+ await releaseStorageCache();
383
+ throw err;
384
+ }
385
+
386
+ // 8. Return result with hydrate counts, the commit-durability listeners, the founder's
387
+ // empty-collection step + shutdown handler.
388
+ // `shutdown` releases the plugin and stops the node only if this composition created it.
389
+ return {
390
+ vtables: [],
391
+ functions: [],
392
+ collations: [],
393
+ hydrated,
394
+ transactor: resolvedTransactor,
395
+ onCommitDurability: listener => pluginResult.onCommitDurability(listener),
396
+ onCommitFullyHeld: listener => pluginResult.onCommitFullyHeld(listener),
397
+ createEmptyCollections: except => createEmptyCollections(db, pluginResult.txnBridge, FOUNDED_SCHEMAS, except),
398
+ async shutdown() {
399
+ log('Shutting down strand connection %s', strandId);
400
+ await releaseOptimysticPlugin(pluginResult, createdNode);
401
+ await releaseStorageCache();
402
+ log('Strand connection %s shut down', strandId);
403
+ },
404
+ };
405
+ }
406
+
407
+ /**
408
+ * Step 7 of {@link composeStrand}: declare the sApp's schema as `App` and apply it — a
409
+ * declarative diff against the catalog, so re-applying a schema that is already in place
410
+ * emits nothing. The one site that applies an `App` schema: `composeStrand` calls it at
411
+ * bring-up, and cadre-core's `StrandDatabase.attachAppSchema` calls it on a live storage
412
+ * replica when an app claims the strand. The database must already be composed (optimystic
413
+ * set as the default vtab), or the tables land in memory instead of the strand.
414
+ *
415
+ * Refuses a schema holding an item the Quereus parser skipped: it keeps any item whose leading
416
+ * keyword it does not model (`create unique index …`, a misspelled `tabel`, `domain`) as an
417
+ * opaque placeholder that apply ignores, so the app would otherwise run without that item.
418
+ *
419
+ * Refuses a schema holding a `seed` item: the apply runs on every node of the strand at every
420
+ * connect, so seed inserts would put a network write on each bring-up and two nodes inserting
421
+ * the same key at once would collide. Rows an app needs at birth are the founding app's to write.
422
+ */
423
+ export async function applyAppSchema(db: Database, schema: string): Promise<void> {
424
+ await db.exec(`
425
+ declare schema App {
426
+ ${schema}
427
+ }
428
+ `);
429
+ assertNoIgnoredItems(db);
430
+ assertNoSeedItems(db);
431
+ await db.exec('apply schema App;');
432
+ }
433
+
434
+ function declaredAppItems(db: Database) {
435
+ return db.declaredSchemaManager.getDeclaredSchema('App')?.items ?? [];
436
+ }
437
+
438
+ function assertNoIgnoredItems(db: Database): void {
439
+ const ignored = declaredAppItems(db).filter(item => item.type === 'declareIgnored').length;
440
+ if (ignored > 0) {
441
+ // Only a count: Quereus leaves an ignored item's source text empty.
442
+ throw new Error(`sApp schema has ${ignored} item(s) the parser does not recognize (a \`create …\` prefix or a misspelled item keyword such as \`tabel\`); items are \`table\`, \`index\`, \`unique index\`, \`view\`, \`materialized view\` and \`assertion\``);
443
+ }
444
+ }
445
+
446
+ function assertNoSeedItems(db: Database): void {
447
+ // Quereus refuses a second seed for one table at declare, so these names are distinct.
448
+ const tables = declaredAppItems(db).flatMap(item => item.type === 'declaredSeed' ? [item.tableName] : []);
449
+ if (tables.length > 0) {
450
+ throw new Error(`sApp schema has seed item(s) for table(s) ${tables.join(', ')}; Sereus does not apply seed rows to a strand — insert the rows an app needs at birth from the app when it founds the strand`);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Steps 1-2 of {@link composeStrand}: register the crypto plugin, then the optimystic
456
+ * plugin carrying this strand's transactor defaults. Split out so the composition can
457
+ * guard the pair against the storage-cache claim it has already taken.
458
+ */
459
+ async function registerStrandPlugins(
460
+ db: Database,
461
+ platform: StrandPlatform,
462
+ strand: {
463
+ resolvedTransactor: StrandTransactor;
464
+ networkName: string;
465
+ enableCache: boolean;
466
+ storage: IRawStorage | undefined;
467
+ },
468
+ ): Promise<OptimysticPluginResult> {
469
+ await platform.registerCrypto(db);
470
+ log('Registered crypto plugin');
471
+
472
+ // On the local transactor with persistent storage, hand the same instance to the
473
+ // plugin so DML persists on the host backend (not in-memory).
474
+ const pluginConfig: Record<string, unknown> = {
475
+ default_transactor: strand.resolvedTransactor,
476
+ default_key_network: 'libp2p',
477
+ default_network_name: strand.networkName,
478
+ enable_cache: strand.enableCache,
479
+ };
480
+ if (strand.resolvedTransactor === 'local' && strand.storage) {
481
+ const storage = strand.storage;
482
+ pluginConfig.rawStorageFactory = () => storage;
483
+ }
484
+ // The plugin's published signature is `Record<string, SqlValue>` but it also reads
485
+ // `rawStorageFactory` (a function reference) from the same map. Cast through unknown
486
+ // rather than widen the public type.
487
+ const pluginResult = optimysticPlugin(
488
+ db,
489
+ pluginConfig as unknown as Parameters<typeof optimysticPlugin>[1],
490
+ ) as unknown as OptimysticPluginResult;
491
+ applyRegistrations(db, pluginResult);
492
+ log('Registered optimystic vtables and functions');
493
+ return pluginResult;
494
+ }