@serfab/quereus-plugin-sereus 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -274,6 +274,10 @@ on shutdown.
274
274
 
275
275
  The result's `onCommitDurability(listener)` is called after every commit that wrote something, before the commit returns, with who holds what it wrote; `onCommitFullyHeld(listener)` is called once when a commit reported `followed` below full replication becomes held by its whole cohort. Both pass through from `@optimystic/quereus-plugin-optimystic`, whose README explains the report ([A commit's durability](https://github.com/gotchoices/optimystic/blob/main/packages/quereus-plugin-optimystic/README.md#a-commits-durability--pluginoncommitdurabilitylistener)); the `SqlCommitDurability` and `CommitFullyHeld` types are re-exported here. A cadre app reads the same reports through `@serfab/cadre-core` ([strands.md → A commit's durability](../../docs/strands.md#a-commits-durability)).
276
276
 
277
+ ### Offline mode
278
+
279
+ With `offline` given, the result's `offline` is the queue's controller (`enter()`, `exit()`, `whenDrained()`, `onStatus(listener)`, `entries()`, …), passed through from `@optimystic/quereus-plugin-optimystic` ([Offline mode](https://github.com/gotchoices/optimystic/blob/main/packages/quereus-plugin-optimystic/README.md#offline-mode--pluginoffline)); `offlineControllerOf(db)` finds it from the `Database`, and the status, state and error types are re-exported here. The `Strand` tables are always acknowledged by the network, and an `App` schema apply that queued transactions refuse is retried once they drain rather than failing the connect: the result's `appSchema` settles with how it ended, `appSchemaWaitingFor` is `'queue'`, and `appSchemaDeferredBy` names the transactions that refused it. An apply that cannot reach the strand's cohort is deferred the same way, offline mode or not (`appSchemaWaitingFor: 'cohort'`). Both, and where the queue is saved, are in [strands.md → Offline mode](../../docs/strands.md#offline-mode).
280
+
277
281
  ### Founding a strand: `createEmptyCollections()`
278
282
 
279
283
  A table nobody has written has no collection, so no single machine can show it empty: every read of it asks the other members, and fails while they are offline. The result's `createEmptyCollections(except?)` commits an empty collection for every table the `Strand` and `App` schemas declare that has none yet, and resolves to how many it committed. `except` lists qualified tables (`'Strand.Header'`) the caller is about to write: their inserts create their collections, so every tree of those tables is left out, and a name matching no declared table throws. The founder calls it once, before its founding write, while no other machine can have written to the strand; cadre-core's founder bootstrap does this, leaving out the tables its founding transaction writes ([strands.md → Joining](../../docs/strands.md#joining-no-writes-before-the-first-sync)). Call it only while nothing else writes through the `Database`: it commits whatever is staged in those collections outside any SQL transaction.
@@ -301,6 +305,7 @@ The same step is exported on its own as `createEmptyCollections(db, bridge, sche
301
305
  | `coordinatedRepo` | IRepo | — | Required when `libp2pNode` is provided |
302
306
  | `transactor` | `'local' \| 'network' \| 'test'` | `'network'` | Storage engine transactions go through. `'network'`: the strand's libp2p cohort, which a lone node coordinates for itself — the only value an application should use. `'local'`: this process's raw storage directly, no peers consulted (in-process tests and tooling). `'test'`: Optimystic's in-memory fake; no libp2p node is created unless one is injected (unit tests) |
303
307
  | `storage` | IRawStorage | — | Persistent raw storage. Borrowed — not closed on `shutdown()` |
308
+ | `offline` | `StrandOfflineOptions` | — | Turn on Optimystic's offline queue: the plugin's `offline` block less `journalLabel`, which is derived from the strand id. Programmatic only; no plugin setting carries it. See [Offline mode](#offline-mode) |
304
309
 
305
310
  ### Plugin settings (plugin-loader / Quoomb)
306
311
 
@@ -0,0 +1,63 @@
1
+ import { type Database } from '@quereus/quereus';
2
+ import type { Libp2p } from '@libp2p/interface';
3
+ import type { StrandOfflineController, AppSchemaOutcome, AppSchemaWait } from './types.js';
4
+ /**
5
+ * Step 7 of `composeStrand`: declare the sApp's schema as `App` and apply it — a
6
+ * declarative diff against the catalog, so re-applying a schema that is already in place
7
+ * emits nothing. The one site that applies an `App` schema: `composeStrand` calls it at
8
+ * bring-up (through {@link applyAppSchemaOrDefer}, whose deferred retry shares its
9
+ * declaration), and cadre-core's `StrandDatabase.attachAppSchema` calls it on a live storage
10
+ * replica when an app claims the strand. The database must already be composed (optimystic
11
+ * set as the default vtab), or the tables land in memory instead of the strand.
12
+ *
13
+ * Refuses a schema holding an item the Quereus parser skipped: it keeps any item whose leading
14
+ * keyword it does not model (`create unique index …`, a misspelled `tabel`, `domain`) as an
15
+ * opaque placeholder that apply ignores, so the app would otherwise run without that item.
16
+ *
17
+ * Refuses a schema holding a `seed` item: the apply runs on every node of the strand at every
18
+ * connect, so seed inserts would put a network write on each bring-up and two nodes inserting
19
+ * the same key at once would collide. Rows an app needs at birth are the founding app's to write.
20
+ */
21
+ export declare function applyAppSchema(db: Database, schema: string): Promise<void>;
22
+ /** What {@link applyAppSchemaOrDefer} reports, in the shape `SereusPluginResult` carries it. */
23
+ export interface AppSchemaApply {
24
+ appSchema: Promise<AppSchemaOutcome>;
25
+ /** What the connect-time apply waits for. Present only when it was deferred. */
26
+ appSchemaWaitingFor?: AppSchemaWait;
27
+ /** The queued transaction ids that refused the connect-time apply. Present only when the queue refused it. */
28
+ appSchemaDeferredBy?: readonly string[];
29
+ }
30
+ /** The strand node's peer events, which a retry waiting for the cohort wakes on. */
31
+ export type PeerConnectEvents = Pick<Libp2p, 'addEventListener' | 'removeEventListener'>;
32
+ /** Where a deferred apply waits: the offline queue, when there is one, and the strand node, when there is one. */
33
+ export interface AppSchemaWaits {
34
+ queue?: Pick<StrandOfflineController, 'whenDrained'>;
35
+ peers?: PeerConnectEvents;
36
+ }
37
+ /**
38
+ * Step 7 of `composeStrand`: {@link applyAppSchema}, except that an apply refused for a reason
39
+ * that passes does not throw. Two such reasons:
40
+ *
41
+ * - queued offline transactions wrote a table the apply changes (`QueuedEntriesBlockSchemaChangeError`);
42
+ * retried each time the queue drains;
43
+ * - the strand's cohort could not be reached (Optimystic's `classifyCommitFailure` says
44
+ * `cohort-unreachable`): an apply writes the strand's catalog, which needs the cohort, so a member
45
+ * alone after an app update would otherwise not open the strand at all (gotchoices/sereus#55).
46
+ * Retried when the strand node connects to a peer, and on a backoff ({@link COHORT_RETRY_MS}).
47
+ *
48
+ * Quereus unwinds a refused apply, so `db` keeps the `App` schema it had, and `appSchema` settles
49
+ * with how the retries ended. Any other error from the first apply is thrown.
50
+ *
51
+ * Waiting before returning was rejected: that withholds the strand from the app right after an app
52
+ * update, which is when a phone is most likely to be offline. So was refusing the connect: the queue
53
+ * can drain only while the composition is alive.
54
+ *
55
+ * `released` is aborted when the composition shuts down; a retry not yet landed then settles
56
+ * `cancelled`.
57
+ *
58
+ * A retry runs while the app is using `db`, so it is one atomic batch that refuses to run inside a
59
+ * transaction another caller holds open, and waits for that transaction to end: run inside it, the
60
+ * apply would be committed or rolled back with the app's rows, and a rollback leaves the index it
61
+ * built holding entries for rows that are gone.
62
+ */
63
+ export declare function applyAppSchemaOrDefer(db: Database, schema: string, waits: AppSchemaWaits, released: AbortSignal): Promise<AppSchemaApply>;
@@ -0,0 +1,216 @@
1
+ import debug from 'debug';
2
+ import { TransactionActiveError } from '@quereus/quereus';
3
+ import { classifyCommitFailure } from '@optimystic/db-core';
4
+ import { QueuedEntriesBlockSchemaChangeError, QueueDisposedError } from '@optimystic/quereus-plugin-optimystic/plugin';
5
+ const log = debug('sereus:plugin:strand');
6
+ /**
7
+ * Step 7 of `composeStrand`: declare the sApp's schema as `App` and apply it — a
8
+ * declarative diff against the catalog, so re-applying a schema that is already in place
9
+ * emits nothing. The one site that applies an `App` schema: `composeStrand` calls it at
10
+ * bring-up (through {@link applyAppSchemaOrDefer}, whose deferred retry shares its
11
+ * declaration), and cadre-core's `StrandDatabase.attachAppSchema` calls it on a live storage
12
+ * replica when an app claims the strand. The database must already be composed (optimystic
13
+ * set as the default vtab), or the tables land in memory instead of the strand.
14
+ *
15
+ * Refuses a schema holding an item the Quereus parser skipped: it keeps any item whose leading
16
+ * keyword it does not model (`create unique index …`, a misspelled `tabel`, `domain`) as an
17
+ * opaque placeholder that apply ignores, so the app would otherwise run without that item.
18
+ *
19
+ * Refuses a schema holding a `seed` item: the apply runs on every node of the strand at every
20
+ * connect, so seed inserts would put a network write on each bring-up and two nodes inserting
21
+ * the same key at once would collide. Rows an app needs at birth are the founding app's to write.
22
+ */
23
+ export async function applyAppSchema(db, schema) {
24
+ await declareAppSchema(db, schema);
25
+ await db.exec('apply schema App;');
26
+ }
27
+ /** Declare `schema` as `App`, refusing the items {@link applyAppSchema} refuses. Writes nothing to the strand. */
28
+ async function declareAppSchema(db, schema) {
29
+ await db.exec(`
30
+ declare schema App {
31
+ ${schema}
32
+ }
33
+ `);
34
+ assertNoIgnoredItems(db);
35
+ assertNoSeedItems(db);
36
+ }
37
+ /**
38
+ * Step 7 of `composeStrand`: {@link applyAppSchema}, except that an apply refused for a reason
39
+ * that passes does not throw. Two such reasons:
40
+ *
41
+ * - queued offline transactions wrote a table the apply changes (`QueuedEntriesBlockSchemaChangeError`);
42
+ * retried each time the queue drains;
43
+ * - the strand's cohort could not be reached (Optimystic's `classifyCommitFailure` says
44
+ * `cohort-unreachable`): an apply writes the strand's catalog, which needs the cohort, so a member
45
+ * alone after an app update would otherwise not open the strand at all (gotchoices/sereus#55).
46
+ * Retried when the strand node connects to a peer, and on a backoff ({@link COHORT_RETRY_MS}).
47
+ *
48
+ * Quereus unwinds a refused apply, so `db` keeps the `App` schema it had, and `appSchema` settles
49
+ * with how the retries ended. Any other error from the first apply is thrown.
50
+ *
51
+ * Waiting before returning was rejected: that withholds the strand from the app right after an app
52
+ * update, which is when a phone is most likely to be offline. So was refusing the connect: the queue
53
+ * can drain only while the composition is alive.
54
+ *
55
+ * `released` is aborted when the composition shuts down; a retry not yet landed then settles
56
+ * `cancelled`.
57
+ *
58
+ * A retry runs while the app is using `db`, so it is one atomic batch that refuses to run inside a
59
+ * transaction another caller holds open, and waits for that transaction to end: run inside it, the
60
+ * apply would be committed or rolled back with the app's rows, and a rollback leaves the index it
61
+ * built holding entries for rows that are gone.
62
+ */
63
+ export async function applyAppSchemaOrDefer(db, schema, waits, released) {
64
+ try {
65
+ await applyAppSchema(db, schema);
66
+ log('sApp schema applied');
67
+ return { appSchema: Promise.resolve({ state: 'applied' }) };
68
+ }
69
+ catch (err) {
70
+ const deferral = deferralOf(err);
71
+ if (!deferral) {
72
+ throw err;
73
+ }
74
+ logDeferral('sApp schema apply', deferral);
75
+ return {
76
+ appSchema: retryDeferredAppSchema(db, schema, deferral, waits, released),
77
+ appSchemaWaitingFor: deferral.wait,
78
+ ...(deferral.wait === 'queue' && { appSchemaDeferredBy: deferral.transactionIds }),
79
+ };
80
+ }
81
+ }
82
+ async function retryDeferredAppSchema(db, schema, first, waits, released) {
83
+ let deferral = first;
84
+ let cohortRetries = 0;
85
+ for (;;) {
86
+ try {
87
+ await nextChance(deferral, waits, cohortRetries, released);
88
+ if (deferral.wait === 'cohort') {
89
+ cohortRetries++;
90
+ }
91
+ if (released.aborted) {
92
+ return { state: 'cancelled' };
93
+ }
94
+ await declareAppSchema(db, schema);
95
+ await db.exec('apply schema App;', undefined, { transaction: true });
96
+ log('Deferred sApp schema applied');
97
+ return { state: 'applied', deferred: true };
98
+ }
99
+ catch (err) {
100
+ if (released.aborted || err instanceof QueueDisposedError) {
101
+ log('Deferred sApp schema apply cancelled by shutdown');
102
+ return { state: 'cancelled' };
103
+ }
104
+ if (err instanceof TransactionActiveError) {
105
+ log('Deferred sApp schema apply waiting for an open transaction to end');
106
+ await abortableDelay(OPEN_TRANSACTION_RETRY_MS, released);
107
+ continue;
108
+ }
109
+ const again = deferralOf(err);
110
+ if (!again) {
111
+ log('Deferred sApp schema apply failed: %O', err);
112
+ return { state: 'failed', error: err };
113
+ }
114
+ logDeferral('Deferred sApp schema apply', again);
115
+ deferral = again;
116
+ }
117
+ }
118
+ }
119
+ /** Waits for whatever may get the retry past `deferral`. */
120
+ async function nextChance(deferral, waits, cohortRetries, released) {
121
+ if (deferral.wait === 'queue' && waits.queue) {
122
+ // NOTE: this loops without a pause when `whenDrained` resolves at once while the refusal stands
123
+ // (a segment left sealed with nothing queued, say). Upstream counts a removal still in progress
124
+ // as undrained, so no such state is known; if one shows up as a busy loop, back off between tries.
125
+ await waits.queue.whenDrained();
126
+ return;
127
+ }
128
+ await nextCohortChance(waits.peers, cohortRetryDelay(cohortRetries), released);
129
+ }
130
+ /**
131
+ * The refusal `err` is or wraps, when a later retry can get past it: Quereus rewraps an error out of
132
+ * `apply schema`, keeping it as `cause`.
133
+ */
134
+ function deferralOf(err) {
135
+ for (let at = err; at instanceof Error; at = at.cause) {
136
+ if (at instanceof QueuedEntriesBlockSchemaChangeError) {
137
+ return { wait: 'queue', transactionIds: at.transactionIds };
138
+ }
139
+ if (classifyCommitFailure(at).kind === 'cohort-unreachable') {
140
+ return { wait: 'cohort' };
141
+ }
142
+ }
143
+ return undefined;
144
+ }
145
+ function logDeferral(what, deferral) {
146
+ if (deferral.wait === 'queue') {
147
+ log('%s refused by queued transactions %o; retrying once they settle', what, deferral.transactionIds);
148
+ }
149
+ else {
150
+ log('%s could not reach the strand cohort; retrying when a peer connects', what);
151
+ }
152
+ }
153
+ /**
154
+ * Backoff for a retry waiting for the cohort, by how many came before it. A connect wakes the retry
155
+ * sooner, so the backoff only bounds how long a missed or too-early connect leaves the schema behind.
156
+ */
157
+ const COHORT_RETRY_MS = [15000, 30000, 60000, 120000, 300000];
158
+ function cohortRetryDelay(retriesBefore) {
159
+ return COHORT_RETRY_MS[Math.min(retriesBefore, COHORT_RETRY_MS.length - 1)];
160
+ }
161
+ /**
162
+ * How long a retry woken by a connect waits first, so the peer is identified and in the ring before
163
+ * the apply asks for its cohort; a retry that still finds it missing waits for the next chance.
164
+ */
165
+ const COHORT_CONNECT_SETTLE_MS = 2000;
166
+ /** Resolves {@link COHORT_CONNECT_SETTLE_MS} after the strand node's next peer connect, after `delayMs`, or when `signal` aborts. */
167
+ async function nextCohortChance(peers, delayMs, signal) {
168
+ const byConnect = await new Promise(resolve => {
169
+ const done = (connected) => {
170
+ clearTimeout(timer);
171
+ peers?.removeEventListener('peer:connect', onConnect);
172
+ signal.removeEventListener('abort', onAbort);
173
+ resolve(connected);
174
+ };
175
+ const onConnect = () => done(true);
176
+ const onAbort = () => done(false);
177
+ const timer = setTimeout(() => done(false), delayMs);
178
+ peers?.addEventListener('peer:connect', onConnect);
179
+ signal.addEventListener('abort', onAbort, { once: true });
180
+ });
181
+ if (byConnect) {
182
+ await abortableDelay(COHORT_CONNECT_SETTLE_MS, signal);
183
+ }
184
+ }
185
+ /** How long a deferred sApp schema apply waits before trying again while another caller's transaction is open. */
186
+ const OPEN_TRANSACTION_RETRY_MS = 250;
187
+ /** Resolves after `ms`, or as soon as `signal` aborts. */
188
+ function abortableDelay(ms, signal) {
189
+ return new Promise(resolve => {
190
+ const done = () => {
191
+ clearTimeout(timer);
192
+ signal.removeEventListener('abort', done);
193
+ resolve();
194
+ };
195
+ const timer = setTimeout(done, ms);
196
+ signal.addEventListener('abort', done, { once: true });
197
+ });
198
+ }
199
+ function declaredAppItems(db) {
200
+ return db.declaredSchemaManager.getDeclaredSchema('App')?.items ?? [];
201
+ }
202
+ function assertNoIgnoredItems(db) {
203
+ const ignored = declaredAppItems(db).filter(item => item.type === 'declareIgnored').length;
204
+ if (ignored > 0) {
205
+ // Only a count: Quereus leaves an ignored item's source text empty.
206
+ 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\``);
207
+ }
208
+ }
209
+ function assertNoSeedItems(db) {
210
+ // Quereus refuses a second seed for one table at declare, so these names are distinct.
211
+ const tables = declaredAppItems(db).flatMap(item => item.type === 'declaredSeed' ? [item.tableName] : []);
212
+ if (tables.length > 0) {
213
+ 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`);
214
+ }
215
+ }
216
+ //# sourceMappingURL=app-schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app-schema.js","sourceRoot":"","sources":["../src/app-schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,sBAAsB,EAAiB,MAAM,kBAAkB,CAAC;AAEzE,OAAO,EAAE,qBA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,KAAK,gBAAgB,CAAC,CAAC,MAAM,CAAC;IAC3F,IAAI,OAAO,GAAG,CAAC,EAAE,CAAC;QACjB,oEAAoE;QACpE,MAAM,IAAI,KAAK,CAAC,mBAAmB,OAAO,oNAAoN,CAAC,CAAC;IACjQ,CAAC;AACF,CAAC;AAED,SAAS,iBAAiB,CAAC,EAAY;IACtC,uFAAuF;IACvF,MAAM,MAAM,GAAG,gBAAgB,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,cAAc,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1G,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,6CAA6C,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,8HAA8H,CAAC,CAAC;IAC/M,CAAC;AACF,CAAC"}
@@ -29,7 +29,9 @@
29
29
  * backend, which is the invariant's other half.
30
30
  *
31
31
  * `MemoryRawStorage` is returned unwrapped on upstream's own guidance: the backend
32
- * is already in-memory, so the cache adds bookkeeping with nothing to save.
32
+ * is already in-memory, so the cache adds bookkeeping with nothing to save. So is a
33
+ * storage that reports `readCached` with a cache of its own (React Native's
34
+ * `LevelDBRawStorage`), which upstream refuses to have wrapped again.
33
35
  *
34
36
  * **{@link wrapStorageWithCache} and {@link disposeStorageCache} are a matched pair
35
37
  * with a holder count between them.** Every wrap that hands back a cache this module
@@ -29,7 +29,9 @@
29
29
  * backend, which is the invariant's other half.
30
30
  *
31
31
  * `MemoryRawStorage` is returned unwrapped on upstream's own guidance: the backend
32
- * is already in-memory, so the cache adds bookkeeping with nothing to save.
32
+ * is already in-memory, so the cache adds bookkeeping with nothing to save. So is a
33
+ * storage that reports `readCached` with a cache of its own (React Native's
34
+ * `LevelDBRawStorage`), which upstream refuses to have wrapped again.
33
35
  *
34
36
  * **{@link wrapStorageWithCache} and {@link disposeStorageCache} are a matched pair
35
37
  * with a holder count between them.** Every wrap that hands back a cache this module
@@ -86,6 +88,14 @@ function addHolder(wrapped) {
86
88
  claim.holders += 1;
87
89
  }
88
90
  }
91
+ /**
92
+ * A storage that carries its own read cache and is not one of this module's wrappers, such as
93
+ * the React Native `LevelDBRawStorage`. Upstream refuses a second cache over it
94
+ * (`redundant read cache`), and it stays its creator's to close.
95
+ */
96
+ function isOwnReadCache(storage) {
97
+ return storage.readCached === true && !(storage instanceof CachedRawStorage);
98
+ }
89
99
  /**
90
100
  * The cached view of `storage`, memoized per instance, with one holder claim taken for
91
101
  * this caller — release it with {@link disposeStorageCache} when this caller's scope
@@ -94,7 +104,7 @@ function addHolder(wrapped) {
94
104
  * one backend is the failure that matters and a stale pool label is not.
95
105
  */
96
106
  export function wrapStorageWithCache(storage, label) {
97
- if (storage instanceof MemoryRawStorage) {
107
+ if (storage instanceof MemoryRawStorage || isOwnReadCache(storage)) {
98
108
  return storage;
99
109
  }
100
110
  if (storage instanceof CachedRawStorage) {
@@ -1 +1 @@
1
- {"version":3,"file":"cached-storage.js","sourceRoot":"","sources":["../src/cached-storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqEG;AAEH,6EAA6E;AAC7E,gFAAgF;AAChF,4EAA4E;AAC5E,kEAAkE;AAClE,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAoB,MAAM,uBAAuB,CAAC;AAE7F,MAAM,KAAK,GAAG,IAAI,OAAO,EAAiC,CAAC;AAmB3D,MAAM,MAAM,GAAG,IAAI,OAAO,EAAgC,CAAC;AAE3D;;;;GAIG;AACH,SAAS,SAAS,CAAC,OAAyB;IAC3C,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAClC,IAAI,KAAK,EAAE,CAAC;QACX,KAAK,CAAC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C;IAC1B,MAAM,OAAO,CAAC,OAAO,EAAE,CAAC;AACzB,CAAC"}
@@ -1,7 +1,13 @@
1
1
  import type { Database, VTablePluginInfo, FunctionPluginInfo, CollationPluginInfo } from '@quereus/quereus';
2
2
  import type { Libp2p } from '@libp2p/interface';
3
- import type { IRawStorage, NodeOptions } from '@optimystic/db-p2p';
4
- import type { StrandConnectionOptions, SereusPluginResult, StrandTransactor } from './types.js';
3
+ import type { IKVStore, IRawStorage, NodeOptions } from '@optimystic/db-p2p';
4
+ import type { StrandConnectionOptions, SereusPluginResult, StrandTransactor, StrandOfflineController } from './types.js';
5
+ /**
6
+ * The offline controller of the live strand composition over `db`, or `undefined` when it was
7
+ * composed without `offline`, has shut down, or `db` is no strand composition. For Sereus's own
8
+ * writers, which are handed a bare `Database` and must see whether its queue holds transactions.
9
+ */
10
+ export declare function offlineControllerOf(db: Database): StrandOfflineController | undefined;
5
11
  /** Registration shape shared by the crypto and optimystic plugin results. */
6
12
  interface PluginRegistrations {
7
13
  vtables?: VTablePluginInfo[];
@@ -71,6 +77,13 @@ export interface StrandPlatform {
71
77
  * default to IndexedDB so a reload survives.
72
78
  */
73
79
  resolveStorage?(ctx: ResolveStorageContext): Promise<IRawStorage | undefined> | IRawStorage | undefined;
80
+ /**
81
+ * The store to journal offline transactions in when `options.offline` names no `journal`.
82
+ * Called after {@link resolveStorage}, only when `options.offline` is given. Optional — when
83
+ * omitted, or when it answers `undefined`, the queue lives in memory (Node). The browser answers
84
+ * a store over the IndexedDB database it defaulted the strand's storage to.
85
+ */
86
+ defaultOfflineJournal?(): IKVStore | undefined;
74
87
  /**
75
88
  * Create a libp2p node. Called only when no node is injected and the
76
89
  * transactor needs one. Node creates a TCP node via `@optimystic/db-p2p`;
@@ -90,21 +103,4 @@ export interface StrandPlatform {
90
103
  * vtab, hydrate the catalog, then apply the sApp schema.
91
104
  */
92
105
  export declare function composeStrand(db: Database, options: StrandConnectionOptions, platform: StrandPlatform): Promise<SereusPluginResult>;
93
- /**
94
- * Step 7 of {@link composeStrand}: declare the sApp's schema as `App` and apply it — a
95
- * declarative diff against the catalog, so re-applying a schema that is already in place
96
- * emits nothing. The one site that applies an `App` schema: `composeStrand` calls it at
97
- * bring-up, and cadre-core's `StrandDatabase.attachAppSchema` calls it on a live storage
98
- * replica when an app claims the strand. The database must already be composed (optimystic
99
- * set as the default vtab), or the tables land in memory instead of the strand.
100
- *
101
- * Refuses a schema holding an item the Quereus parser skipped: it keeps any item whose leading
102
- * keyword it does not model (`create unique index …`, a misspelled `tabel`, `domain`) as an
103
- * opaque placeholder that apply ignores, so the app would otherwise run without that item.
104
- *
105
- * Refuses a schema holding a `seed` item: the apply runs on every node of the strand at every
106
- * connect, so seed inserts would put a network write on each bring-up and two nodes inserting
107
- * the same key at once would collide. Rows an app needs at birth are the founding app's to write.
108
- */
109
- export declare function applyAppSchema(db: Database, schema: string): Promise<void>;
110
106
  export {};
@@ -1,5 +1,6 @@
1
1
  import debug from 'debug';
2
2
  import optimysticPlugin from '@optimystic/quereus-plugin-optimystic/plugin';
3
+ import { applyAppSchemaOrDefer } from './app-schema.js';
3
4
  import { STRAND_SCHEMA } from './strand-schema.js';
4
5
  import { resolveStrandClusterSize, STRAND_CLUSTER_POLICY } from './cluster-size.js';
5
6
  import { wrapStorageWithCache, disposeStorageCache } from './cached-storage.js';
@@ -8,18 +9,33 @@ const log = debug('sereus:plugin:strand');
8
9
  const timing = debug('sereus:plugin:strand:timing');
9
10
  /** The schemas whose tables a strand founder gives a collection: strand membership, then the sApp's. */
10
11
  const FOUNDED_SCHEMAS = ['Strand', 'App'];
12
+ /** The offline controller of each live strand composition composed with `offline`, by its `Database`. */
13
+ const offlineControllers = new WeakMap();
11
14
  /**
12
- * Release a composition's hold on the optimystic plugin. The transaction bridge goes first: its
13
- * durability follower subscribes to the node's `StorageRepo`, and cadre-core keeps a strand's node
14
- * across a database rebuild, so a bridge never disposed stays subscribed once per rebuild. Then the
15
- * collection factory: a node the composition created is stopped with it; an injected node is left
16
- * running, because it belongs to the caller — cadre-core keeps a strand's node up across a failed
17
- * database build and retries the build on it.
15
+ * The offline controller of the live strand composition over `db`, or `undefined` when it was
16
+ * composed without `offline`, has shut down, or `db` is no strand composition. For Sereus's own
17
+ * writers, which are handed a bare `Database` and must see whether its queue holds transactions.
18
+ */
19
+ export function offlineControllerOf(db) {
20
+ return offlineControllers.get(db);
21
+ }
22
+ /**
23
+ * Release a composition's hold on the optimystic plugin. The offline queue goes first: its drain
24
+ * keeps timers and may have a submission in flight, which reports its commit through the bridge's
25
+ * follower, so the bridge must outlive it (the plugin's own `dispose()` orders them the same way).
26
+ * A queue `hydrate` restored before a failed composition is stopped here too. Then the transaction
27
+ * bridge: its durability follower subscribes to the node's `StorageRepo`, and cadre-core keeps a
28
+ * strand's node across a database rebuild, so a bridge never disposed stays subscribed once per
29
+ * rebuild. Then the collection factory: a node the composition created is stopped with it; an
30
+ * injected node is left running, because it belongs to the caller — cadre-core keeps a strand's
31
+ * node up across a failed database build and retries the build on it.
18
32
  *
19
- * Disposes the bridge itself rather than calling the plugin's `dispose()`, which would release the
20
- * factory a second time on the created-node path (`shutdown()` ends with the same `dispose()`).
33
+ * Disposes the queue and bridge itself rather than calling the plugin's `dispose()`, which would
34
+ * release the factory a second time on the created-node path (`shutdown()` ends with the same
35
+ * `dispose()`).
21
36
  */
22
37
  async function releaseOptimysticPlugin(plugin, createdNode) {
38
+ await plugin.offline.dispose();
23
39
  // NOTE: the bridge's follower re-subscribes at the start of any transaction, so a write begun on
24
40
  // this `Database` after release (before its owner closes it) subscribes again and nothing
25
41
  // releases it. cadre-core stops its own writers before releasing; if an app write in flight at
@@ -119,6 +135,7 @@ export async function composeStrand(db, options, platform) {
119
135
  networkName,
120
136
  enableCache,
121
137
  storage,
138
+ offline: options.offline && strandOfflineConfig(strandId, options.offline, platform),
122
139
  });
123
140
  }
124
141
  catch (err) {
@@ -126,7 +143,16 @@ export async function composeStrand(db, options, platform) {
126
143
  throw err;
127
144
  }
128
145
  const { collectionFactory } = pluginResult;
146
+ const offline = options.offline && pluginResult.offline;
147
+ if (offline) {
148
+ offlineControllers.set(db, offline);
149
+ }
150
+ // Aborted by `shutdown`, so a deferred sApp schema apply still waiting settles `cancelled`.
151
+ const released = new AbortController();
152
+ let appSchemaApply;
129
153
  let createdNode = null;
154
+ // The strand node, when there is one: a deferred sApp schema apply waiting for the cohort wakes on its connects.
155
+ let peers;
130
156
  let hydrated;
131
157
  try {
132
158
  // 3. Acquire the libp2p node. Skip only when this is the unit-test fake
@@ -162,6 +188,7 @@ export async function composeStrand(db, options, platform) {
162
188
  coordinatedRepo = repo;
163
189
  log('Created libp2p node (port: %d, fretProfile: %s, storage=%s)', port, fretProfile, !!storage);
164
190
  }
191
+ peers = node;
165
192
  collectionFactory.registerLibp2pNode(networkName, node, coordinatedRepo);
166
193
  log('Registered libp2p node with collection factory');
167
194
  }
@@ -194,6 +221,13 @@ export async function composeStrand(db, options, platform) {
194
221
  // nothing here writes membership rows. Founder bootstrap (Header, founding
195
222
  // Manager/Member, invite/peer flows) is owned by the lifecycle ticket
196
223
  // `strand-membership-lifecycle-population`.
224
+ //
225
+ // NOTE: unlike step 7, this apply is not deferred behind the offline queue. Every `Strand`
226
+ // table is tagged `"optimystic.offline" = 'network'`, so the only queued transactions that
227
+ // write one are network-acknowledged commits waiting behind app transactions, and the only
228
+ // change this schema has made since is a tag, which the queue does not refuse. If a
229
+ // later strand schema changes how a table's rows are stored (an index, a column), this apply
230
+ // can be refused by `QueuedEntriesBlockSchemaChangeError` the same way and needs step 7's path.
197
231
  log('Applying Strand membership schema for strand %s', strandId);
198
232
  await db.exec(`
199
233
  declare schema Strand {
@@ -218,14 +252,19 @@ export async function composeStrand(db, options, platform) {
218
252
  // differ: once one has run, any later step that fails leaves the schema partially
219
253
  // migrated instead of restored. No schema in this repo evolves that way, so this
220
254
  // is a note for whoever first ships a migration that does.
255
+ //
256
+ // The exception: an apply refused by queued offline transactions, or because the strand's
257
+ // cohort could not be reached, does not fail the connect. The strand comes up on the `App`
258
+ // schema it had, and the apply is retried as the queue drains or when a peer connects (see
259
+ // `applyAppSchemaOrDefer`).
221
260
  if (schema) {
222
261
  log('Applying sApp schema for strand %s', strandId);
223
- await applyAppSchema(db, schema);
224
- log('sApp schema applied');
262
+ appSchemaApply = await applyAppSchemaOrDefer(db, schema, { queue: pluginResult.offline, peers }, released.signal);
225
263
  }
226
264
  }
227
265
  catch (err) {
228
266
  // Clean up resources if setup fails after partial initialization.
267
+ offlineControllers.delete(db);
229
268
  await releaseOptimysticPlugin(pluginResult, createdNode);
230
269
  await releaseStorageCache();
231
270
  throw err;
@@ -242,8 +281,15 @@ export async function composeStrand(db, options, platform) {
242
281
  onCommitDurability: listener => pluginResult.onCommitDurability(listener),
243
282
  onCommitFullyHeld: listener => pluginResult.onCommitFullyHeld(listener),
244
283
  createEmptyCollections: except => createEmptyCollections(db, pluginResult.txnBridge, FOUNDED_SCHEMAS, except),
284
+ ...(offline && { offline }),
285
+ ...appSchemaApply,
245
286
  async shutdown() {
246
287
  log('Shutting down strand connection %s', strandId);
288
+ // NOTE: a deferred sApp schema apply already running is not awaited: it runs on against the
289
+ // released plugin, Quereus unwinds it when it fails, and `appSchema` settles `cancelled`. If
290
+ // that ever leaves a catalog write landing after close, await `appSchema` here first.
291
+ released.abort();
292
+ offlineControllers.delete(db);
247
293
  await releaseOptimysticPlugin(pluginResult, createdNode);
248
294
  await releaseStorageCache();
249
295
  log('Strand connection %s shut down', strandId);
@@ -251,47 +297,22 @@ export async function composeStrand(db, options, platform) {
251
297
  };
252
298
  }
253
299
  /**
254
- * Step 7 of {@link composeStrand}: declare the sApp's schema as `App` and apply it — a
255
- * declarative diff against the catalog, so re-applying a schema that is already in place
256
- * emits nothing. The one site that applies an `App` schema: `composeStrand` calls it at
257
- * bring-up, and cadre-core's `StrandDatabase.attachAppSchema` calls it on a live storage
258
- * replica when an app claims the strand. The database must already be composed (optimystic
259
- * set as the default vtab), or the tables land in memory instead of the strand.
260
- *
261
- * Refuses a schema holding an item the Quereus parser skipped: it keeps any item whose leading
262
- * keyword it does not model (`create unique index …`, a misspelled `tabel`, `domain`) as an
263
- * opaque placeholder that apply ignores, so the app would otherwise run without that item.
264
- *
265
- * Refuses a schema holding a `seed` item: the apply runs on every node of the strand at every
266
- * connect, so seed inserts would put a network write on each bring-up and two nodes inserting
267
- * the same key at once would collide. Rows an app needs at birth are the founding app's to write.
300
+ * The Optimystic plugin's `offline` block for this strand: the caller's options, the platform's
301
+ * journal when the caller named none, and the journal label, which the plugin refuses without one.
268
302
  */
269
- export async function applyAppSchema(db, schema) {
270
- await db.exec(`
271
- declare schema App {
272
- ${schema}
273
- }
274
- `);
275
- assertNoIgnoredItems(db);
276
- assertNoSeedItems(db);
277
- await db.exec('apply schema App;');
303
+ function strandOfflineConfig(strandId, offline, platform) {
304
+ const journal = offline.journal ?? platform.defaultOfflineJournal?.();
305
+ return journal === undefined
306
+ ? { ...offline }
307
+ : { ...offline, journal, journalLabel: strandJournalLabel(strandId) };
278
308
  }
279
- function declaredAppItems(db) {
280
- return db.declaredSchemaManager.getDeclaredSchema('App')?.items ?? [];
281
- }
282
- function assertNoIgnoredItems(db) {
283
- const ignored = declaredAppItems(db).filter(item => item.type === 'declareIgnored').length;
284
- if (ignored > 0) {
285
- // Only a count: Quereus leaves an ignored item's source text empty.
286
- 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\``);
287
- }
288
- }
289
- function assertNoSeedItems(db) {
290
- // Quereus refuses a second seed for one table at declare, so these names are distinct.
291
- const tables = declaredAppItems(db).flatMap(item => item.type === 'declaredSeed' ? [item.tableName] : []);
292
- if (tables.length > 0) {
293
- 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`);
294
- }
309
+ /**
310
+ * The offline journal label for a strand. A label is `[a-z0-9_-]` and a strand id `[a-z0-9._-]`, so
311
+ * `_` becomes `__` and `.` becomes `_d`: no two strand ids share a label, and two strands journaling
312
+ * into one store keep their records apart.
313
+ */
314
+ function strandJournalLabel(strandId) {
315
+ return `strand-${strandId.replaceAll('_', '__').replaceAll('.', '_d')}`;
295
316
  }
296
317
  /**
297
318
  * Steps 1-2 of {@link composeStrand}: register the crypto plugin, then the optimystic
@@ -313,9 +334,16 @@ async function registerStrandPlugins(db, platform, strand) {
313
334
  const storage = strand.storage;
314
335
  pluginConfig.rawStorageFactory = () => storage;
315
336
  }
337
+ // NOTE: `networkCommitTimeoutMs` is left at upstream's default (five minutes); nothing was
338
+ // measured to choose another. A network-acknowledged commit made while transactions are queued
339
+ // (any `Strand` write, all of them tagged 'network') waits that long behind them holding
340
+ // Quereus's execution lock. If that ever shows up as a frozen app, lower it for strands here.
341
+ if (strand.offline) {
342
+ pluginConfig.offline = strand.offline;
343
+ }
316
344
  // The plugin's published signature is `Record<string, SqlValue>` but it also reads
317
- // `rawStorageFactory` (a function reference) from the same map. Cast through unknown
318
- // rather than widen the public type.
345
+ // `rawStorageFactory` (a function reference) and `offline` (an object) from the same
346
+ // map. Cast through unknown rather than widen the public type.
319
347
  const pluginResult = optimysticPlugin(db, pluginConfig);
320
348
  applyRegistrations(db, pluginResult);
321
349
  log('Registered optimystic vtables and functions');