@serfab/quereus-plugin-sereus 1.19.1 → 1.21.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/dist/types.d.ts CHANGED
@@ -90,13 +90,15 @@ export type StrandOfflineOptions = Omit<OfflineConfig, 'journalLabel'>;
90
90
  * `OfflineMode` an app calls. The class's other public methods are the plugin's internals.
91
91
  */
92
92
  export type StrandOfflineController = Pick<OfflineMode, 'enter' | 'exit' | 'isEntered' | 'whenDrained' | 'onStatus' | 'onQueueState' | 'queueState' | 'entries' | 'status' | 'discard' | 'outcomes' | 'acknowledge'>;
93
+ /** What a deferred sApp schema apply waits for (see {@link SereusPluginResult.appSchemaWaitingFor}). */
94
+ export type AppSchemaWait = 'queue' | 'cohort';
93
95
  /**
94
96
  * How a connection's sApp schema apply ended (see {@link SereusPluginResult.appSchema}):
95
97
  *
96
- * - `applied` — the schema is in place. `deferred` when queued offline transactions refused the
97
- * first apply and a later one, once they had settled, landed.
98
- * - `failed` — a deferred retry failed for a reason other than the queue; the connection keeps the
99
- * schema it had before.
98
+ * - `applied` — the schema is in place. `deferred` when the first apply was refused (by queued
99
+ * offline transactions, or because the strand's cohort could not be reached) and a later one landed.
100
+ * - `failed` — a deferred retry failed for another reason; the connection keeps the schema it had
101
+ * before.
100
102
  * - `cancelled` — the connection shut down before a deferred retry landed.
101
103
  */
102
104
  export type AppSchemaOutcome = {
@@ -163,12 +165,18 @@ export interface SereusPluginResult {
163
165
  /**
164
166
  * Present when {@link StrandConnectionOptions.schema} was given; never rejects. Resolves
165
167
  * `{ state: 'applied' }` at once when the apply succeeded at connect. When queued offline
166
- * transactions refused it, the connection comes up on the `App` schema it already had and
167
- * retries each time the queue drains; this settles when a retry lands, fails otherwise, or
168
- * {@link shutdown} runs first.
168
+ * transactions refused it, or the strand's cohort could not be reached, the connection comes up
169
+ * anyway and retries ({@link appSchemaWaitingFor}); this settles when a retry lands, fails
170
+ * otherwise, or {@link shutdown} runs first.
169
171
  */
170
172
  appSchema?: Promise<AppSchemaOutcome>;
171
- /** The queued transaction ids that refused the connect-time apply. Present only when it was deferred. */
173
+ /**
174
+ * What the connect-time apply waits for: `'queue'`, queued offline transactions (retried each time
175
+ * the queue drains), or `'cohort'`, the strand's members (retried when the strand node connects to
176
+ * a peer, and on a backoff). Present only when it was deferred.
177
+ */
178
+ appSchemaWaitingFor?: AppSchemaWait;
179
+ /** The queued transaction ids that refused the connect-time apply. Present only when the queue refused it. */
172
180
  appSchemaDeferredBy?: readonly string[];
173
181
  /** Shuts down the libp2p node and collection factory. Call when done. */
174
182
  shutdown: () => Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serfab/quereus-plugin-sereus",
3
- "version": "1.19.1",
3
+ "version": "1.21.0",
4
4
  "type": "module",
5
5
  "description": "Quereus plugin that connects to a Sereus strand for SQL access",
6
6
  "main": "dist/index.js",
@@ -68,13 +68,13 @@
68
68
  "@libp2p/circuit-relay-v2": "^4.2.13",
69
69
  "@libp2p/interface": "^3.3.0",
70
70
  "@libp2p/websockets": "^10.1.21",
71
- "@optimystic/db-core": "^1.20.1",
72
- "@optimystic/db-p2p": "^1.20.1",
73
- "@optimystic/db-p2p-storage-fs": "^1.20.1",
74
- "@optimystic/db-p2p-storage-web": "^1.20.1",
75
- "@optimystic/quereus-plugin-crypto": "^1.20.1",
76
- "@optimystic/quereus-plugin-optimystic": "^1.20.1",
77
- "@quereus/quereus": "^4.21.1",
71
+ "@optimystic/db-core": "^1.25.0",
72
+ "@optimystic/db-p2p": "^1.25.0",
73
+ "@optimystic/db-p2p-storage-fs": "^1.25.0",
74
+ "@optimystic/db-p2p-storage-web": "^1.25.0",
75
+ "@optimystic/quereus-plugin-crypto": "^1.25.0",
76
+ "@optimystic/quereus-plugin-optimystic": "^1.25.0",
77
+ "@quereus/quereus": "^4.25.0",
78
78
  "debug": "^4.4.3"
79
79
  },
80
80
  "quereus": {
package/src/app-schema.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import debug from 'debug';
2
2
  import { TransactionActiveError, type Database } from '@quereus/quereus';
3
+ import type { Libp2p } from '@libp2p/interface';
4
+ import { classifyCommitFailure } from '@optimystic/db-core';
3
5
  import { QueuedEntriesBlockSchemaChangeError, QueueDisposedError } from '@optimystic/quereus-plugin-optimystic/plugin';
4
- import type { StrandOfflineController, AppSchemaOutcome } from './types.js';
6
+ import type { StrandOfflineController, AppSchemaOutcome, AppSchemaWait } from './types.js';
5
7
 
6
8
  const log = debug('sereus:plugin:strand');
7
9
 
@@ -9,7 +11,7 @@ const log = debug('sereus:plugin:strand');
9
11
  * Step 7 of `composeStrand`: declare the sApp's schema as `App` and apply it — a
10
12
  * declarative diff against the catalog, so re-applying a schema that is already in place
11
13
  * emits nothing. The one site that applies an `App` schema: `composeStrand` calls it at
12
- * bring-up (through {@link applyAppSchemaAfterQueue}, whose deferred retry shares its
14
+ * bring-up (through {@link applyAppSchemaOrDefer}, whose deferred retry shares its
13
15
  * declaration), and cadre-core's `StrandDatabase.attachAppSchema` calls it on a live storage
14
16
  * replica when an app claims the strand. The database must already be composed (optimystic
15
17
  * set as the default vtab), or the tables land in memory instead of the strand.
@@ -38,22 +40,46 @@ async function declareAppSchema(db: Database, schema: string): Promise<void> {
38
40
  assertNoSeedItems(db);
39
41
  }
40
42
 
41
- /** What {@link applyAppSchemaAfterQueue} reports, in the shape `SereusPluginResult` carries it. */
43
+ /** What {@link applyAppSchemaOrDefer} reports, in the shape `SereusPluginResult` carries it. */
42
44
  export interface AppSchemaApply {
43
45
  appSchema: Promise<AppSchemaOutcome>;
46
+ /** What the connect-time apply waits for. Present only when it was deferred. */
47
+ appSchemaWaitingFor?: AppSchemaWait;
48
+ /** The queued transaction ids that refused the connect-time apply. Present only when the queue refused it. */
44
49
  appSchemaDeferredBy?: readonly string[];
45
50
  }
46
51
 
52
+ /** The strand node's peer events, which a retry waiting for the cohort wakes on. */
53
+ export type PeerConnectEvents = Pick<Libp2p, 'addEventListener' | 'removeEventListener'>;
54
+
55
+ /** Where a deferred apply waits: the offline queue, when there is one, and the strand node, when there is one. */
56
+ export interface AppSchemaWaits {
57
+ queue?: Pick<StrandOfflineController, 'whenDrained'>;
58
+ peers?: PeerConnectEvents;
59
+ }
60
+
61
+ /** Why an apply was refused, when it is a refusal a later retry can get past. */
62
+ type Deferral = { wait: 'queue'; transactionIds: readonly string[] } | { wait: 'cohort' };
63
+
47
64
  /**
48
- * Step 7 of `composeStrand`: {@link applyAppSchema}, except that an apply refused by queued
49
- * offline transactions (`QueuedEntriesBlockSchemaChangeError` on the error's `cause` chain) does not
50
- * throw. Quereus unwinds the refused apply, so `db` keeps the `App` schema it had; the apply is
51
- * retried in the background each time `queue` drains, for as long as the queue is what refuses it,
52
- * and `appSchema` settles with how that ended. Any other error from the first apply is thrown.
65
+ * Step 7 of `composeStrand`: {@link applyAppSchema}, except that an apply refused for a reason
66
+ * that passes does not throw. Two such reasons:
53
67
  *
54
- * Waiting for the queue before returning was rejected: offline, that withholds the strand from the
55
- * app right after an app update, which is when offline mode matters. So was refusing the connect:
56
- * the queue can drain only while the composition is alive.
68
+ * - queued offline transactions wrote a table the apply changes (`QueuedEntriesBlockSchemaChangeError`);
69
+ * retried each time the queue drains;
70
+ * - the strand's cohort could not be reached (Optimystic's `classifyCommitFailure` says
71
+ * `cohort-unreachable`): an apply writes the strand's catalog, which needs the cohort, so a member
72
+ * alone after an app update would otherwise not open the strand at all (gotchoices/sereus#55).
73
+ * Retried when the strand node connects to a peer, and on a backoff ({@link COHORT_RETRY_MS}).
74
+ *
75
+ * Quereus unwinds a refused apply, whether a migration step or the closing catalog commit refused it,
76
+ * so `db` keeps the `App` schema it had, and `appSchema` settles with how the retries ended. Any other
77
+ * error from the first apply is thrown, and so is a refusal Quereus could not unwind that leaves a
78
+ * retry nothing to send ({@link retryableRefusalOf}).
79
+ *
80
+ * Waiting before returning was rejected: that withholds the strand from the app right after an app
81
+ * update, which is when a phone is most likely to be offline. So was refusing the connect: the queue
82
+ * can drain only while the composition is alive.
57
83
  *
58
84
  * `released` is aborted when the composition shuts down; a retry not yet landed then settles
59
85
  * `cancelled`.
@@ -63,10 +89,10 @@ export interface AppSchemaApply {
63
89
  * apply would be committed or rolled back with the app's rows, and a rollback leaves the index it
64
90
  * built holding entries for rows that are gone.
65
91
  */
66
- export async function applyAppSchemaAfterQueue(
92
+ export async function applyAppSchemaOrDefer(
67
93
  db: Database,
68
94
  schema: string,
69
- queue: Pick<StrandOfflineController, 'whenDrained'>,
95
+ waits: AppSchemaWaits,
70
96
  released: AbortSignal,
71
97
  ): Promise<AppSchemaApply> {
72
98
  try {
@@ -74,35 +100,38 @@ export async function applyAppSchemaAfterQueue(
74
100
  log('sApp schema applied');
75
101
  return { appSchema: Promise.resolve({ state: 'applied' }) };
76
102
  } catch (err) {
77
- const refusal = queueRefusalIn(err);
78
- if (!refusal) {
103
+ const deferral = await retryableRefusalOf(db, err);
104
+ if (!deferral) {
79
105
  throw err;
80
106
  }
81
- log('sApp schema apply refused by queued transactions %o; retrying once they settle', refusal.transactionIds);
107
+ logDeferral('sApp schema apply', deferral);
82
108
  return {
83
- appSchema: retryAppSchemaAfterDrain(db, schema, queue, released),
84
- appSchemaDeferredBy: refusal.transactionIds,
109
+ appSchema: retryDeferredAppSchema(db, schema, deferral, waits, released),
110
+ appSchemaWaitingFor: deferral.wait,
111
+ ...(deferral.wait === 'queue' && { appSchemaDeferredBy: deferral.transactionIds }),
85
112
  };
86
113
  }
87
114
  }
88
115
 
89
- async function retryAppSchemaAfterDrain(
116
+ async function retryDeferredAppSchema(
90
117
  db: Database,
91
118
  schema: string,
92
- queue: Pick<StrandOfflineController, 'whenDrained'>,
119
+ first: Deferral,
120
+ waits: AppSchemaWaits,
93
121
  released: AbortSignal,
94
122
  ): Promise<AppSchemaOutcome> {
95
- // NOTE: this loops without a pause when `whenDrained` resolves at once while the refusal stands
96
- // (a segment left sealed with nothing queued, say). Upstream counts a removal still in progress
97
- // as undrained, so no such state is known; if one shows up as a busy loop, back off between tries.
123
+ let deferral = first;
124
+ let cohortRetries = 0;
98
125
  for (;;) {
99
126
  try {
100
- await queue.whenDrained();
127
+ await nextChance(deferral, waits, cohortRetries, released);
128
+ if (deferral.wait === 'cohort') {
129
+ cohortRetries++;
130
+ }
101
131
  if (released.aborted) {
102
132
  return { state: 'cancelled' };
103
133
  }
104
- await declareAppSchema(db, schema);
105
- await db.exec('apply schema App;', undefined, { transaction: true });
134
+ await applyOutsideOpenTransaction(db, schema, released);
106
135
  log('Deferred sApp schema applied');
107
136
  return { state: 'applied', deferred: true };
108
137
  } catch (err) {
@@ -110,31 +139,148 @@ async function retryAppSchemaAfterDrain(
110
139
  log('Deferred sApp schema apply cancelled by shutdown');
111
140
  return { state: 'cancelled' };
112
141
  }
113
- if (err instanceof TransactionActiveError) {
114
- log('Deferred sApp schema apply waiting for an open transaction to end');
115
- await abortableDelay(OPEN_TRANSACTION_RETRY_MS, released);
116
- continue;
117
- }
118
- const refusal = queueRefusalIn(err);
119
- if (!refusal) {
142
+ const again = await retryableRefusalOf(db, err);
143
+ if (!again) {
120
144
  log('Deferred sApp schema apply failed: %O', err);
121
145
  return { state: 'failed', error: err };
122
146
  }
123
- log('sApp schema apply refused again by queued transactions %o', refusal.transactionIds);
147
+ logDeferral('Deferred sApp schema apply', again);
148
+ deferral = again;
149
+ }
150
+ }
151
+ }
152
+
153
+ /** One atomic apply, once no other caller holds a transaction open. Throws the open-transaction refusal when `released` aborts during the wait. */
154
+ async function applyOutsideOpenTransaction(db: Database, schema: string, released: AbortSignal): Promise<void> {
155
+ for (;;) {
156
+ await declareAppSchema(db, schema);
157
+ try {
158
+ await db.exec('apply schema App;', undefined, { transaction: true });
159
+ return;
160
+ } catch (err) {
161
+ if (!(err instanceof TransactionActiveError)) {
162
+ throw err;
163
+ }
164
+ log('Deferred sApp schema apply waiting for an open transaction to end');
165
+ await abortableDelay(OPEN_TRANSACTION_RETRY_MS, released);
166
+ if (released.aborted) {
167
+ throw err;
168
+ }
124
169
  }
125
170
  }
126
171
  }
127
172
 
128
- /** The offline queue's refusal `err` is or wraps: Quereus rewraps it out of `apply schema`, keeping it as `cause`. */
129
- function queueRefusalIn(err: unknown): QueuedEntriesBlockSchemaChangeError | undefined {
173
+ /** Waits for whatever may get the retry past `deferral`. */
174
+ async function nextChance(deferral: Deferral, waits: AppSchemaWaits, cohortRetries: number, released: AbortSignal): Promise<void> {
175
+ if (deferral.wait === 'queue' && waits.queue) {
176
+ // NOTE: this loops without a pause when `whenDrained` resolves at once while the refusal stands
177
+ // (a segment left sealed with nothing queued, say). Upstream counts a removal still in progress
178
+ // as undrained, so no such state is known; if one shows up as a busy loop, back off between tries.
179
+ await waits.queue.whenDrained();
180
+ return;
181
+ }
182
+ await nextCohortChance(waits.peers, cohortRetryDelay(cohortRetries), released);
183
+ }
184
+
185
+ /**
186
+ * The refusal `err` is or wraps, when retrying it would send something. An apply refused after a
187
+ * `drop table` or `drop column` cannot be unwound, so `db` can already hold the whole new schema while
188
+ * the store holds the old one. A retry would then diff clean and settle `applied` with nothing written,
189
+ * so that refusal counts as a failure: a restart plans the change again from the store.
190
+ */
191
+ async function retryableRefusalOf(db: Database, err: unknown): Promise<Deferral | undefined> {
192
+ const deferral = deferralOf(err);
193
+ if (!deferral) {
194
+ return undefined;
195
+ }
196
+ try {
197
+ if (await appSchemaHasPendingChanges(db)) {
198
+ return deferral;
199
+ }
200
+ log('sApp schema apply was refused, and the database already holds the new schema: %O', err);
201
+ } catch (diffError) {
202
+ log('Could not check what a refused sApp schema apply left to send: %O', diffError);
203
+ }
204
+ return undefined;
205
+ }
206
+
207
+ async function appSchemaHasPendingChanges(db: Database): Promise<boolean> {
208
+ for await (const _change of db.eval('diff schema App')) {
209
+ return true;
210
+ }
211
+ return false;
212
+ }
213
+
214
+ /**
215
+ * The refusal `err` is or wraps, when a later retry can get past it: Quereus rewraps an error out of
216
+ * a migration step, keeping it as `cause`.
217
+ *
218
+ * `classifyCommitFailure` refuses to walk `cause` itself, because a commit-phase shortfall nested
219
+ * there means the write is in doubt rather than unsent. Walking it here is safe: an apply is a
220
+ * declarative diff, so a retry after a write that did land changes nothing.
221
+ */
222
+ function deferralOf(err: unknown): Deferral | undefined {
130
223
  for (let at = err; at instanceof Error; at = at.cause) {
131
224
  if (at instanceof QueuedEntriesBlockSchemaChangeError) {
132
- return at;
225
+ return { wait: 'queue', transactionIds: at.transactionIds };
226
+ }
227
+ if (classifyCommitFailure(at).kind === 'cohort-unreachable') {
228
+ return { wait: 'cohort' };
133
229
  }
134
230
  }
135
231
  return undefined;
136
232
  }
137
233
 
234
+ function logDeferral(what: string, deferral: Deferral): void {
235
+ if (deferral.wait === 'queue') {
236
+ log('%s refused by queued transactions %o; retrying once they settle', what, deferral.transactionIds);
237
+ } else {
238
+ log('%s could not reach the strand cohort; retrying when a peer connects', what);
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Backoff for a retry waiting for the cohort, by how many came before it. A connect wakes the retry
244
+ * sooner, so the backoff only bounds how long a missed or too-early connect leaves the schema behind.
245
+ */
246
+ const COHORT_RETRY_MS = [15_000, 30_000, 60_000, 120_000, 300_000] as const;
247
+
248
+ function cohortRetryDelay(retriesBefore: number): number {
249
+ return COHORT_RETRY_MS[Math.min(retriesBefore, COHORT_RETRY_MS.length - 1)]!;
250
+ }
251
+
252
+ /**
253
+ * How long a retry woken by a connect waits first, so the peer is identified and in the ring before
254
+ * the apply asks for its cohort; a retry that still finds it missing waits for the next chance.
255
+ */
256
+ const COHORT_CONNECT_SETTLE_MS = 2_000;
257
+
258
+ /**
259
+ * Resolves {@link COHORT_CONNECT_SETTLE_MS} after the strand node's next peer connect, after `delayMs`, or when `signal` aborts.
260
+ *
261
+ * NOTE: every connect wakes a retry, the relay's included, and a retry that reaches the cohort's
262
+ * refusal holds the database's statement lock while it waits for it. If that shows up as stalled app
263
+ * statements on a node with many connects, wake only on a connect to a strand member.
264
+ */
265
+ async function nextCohortChance(peers: PeerConnectEvents | undefined, delayMs: number, signal: AbortSignal): Promise<void> {
266
+ const byConnect = await new Promise<boolean>(resolve => {
267
+ const done = (connected: boolean): void => {
268
+ clearTimeout(timer);
269
+ peers?.removeEventListener('peer:connect', onConnect);
270
+ signal.removeEventListener('abort', onAbort);
271
+ resolve(connected);
272
+ };
273
+ const onConnect = (): void => done(true);
274
+ const onAbort = (): void => done(false);
275
+ const timer = setTimeout(() => done(false), delayMs);
276
+ peers?.addEventListener('peer:connect', onConnect);
277
+ signal.addEventListener('abort', onAbort, { once: true });
278
+ });
279
+ if (byConnect) {
280
+ await abortableDelay(COHORT_CONNECT_SETTLE_MS, signal);
281
+ }
282
+ }
283
+
138
284
  /** How long a deferred sApp schema apply waits before trying again while another caller's transaction is open. */
139
285
  const OPEN_TRANSACTION_RETRY_MS = 250;
140
286
 
@@ -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
@@ -108,6 +110,15 @@ function addHolder(wrapped: CachedRawStorage): void {
108
110
  }
109
111
  }
110
112
 
113
+ /**
114
+ * A storage that carries its own read cache and is not one of this module's wrappers, such as
115
+ * the React Native `LevelDBRawStorage`. Upstream refuses a second cache over it
116
+ * (`redundant read cache`), and it stays its creator's to close.
117
+ */
118
+ function isOwnReadCache(storage: IRawStorage): boolean {
119
+ return storage.readCached === true && !(storage instanceof CachedRawStorage);
120
+ }
121
+
111
122
  /**
112
123
  * The cached view of `storage`, memoized per instance, with one holder claim taken for
113
124
  * this caller — release it with {@link disposeStorageCache} when this caller's scope
@@ -116,7 +127,7 @@ function addHolder(wrapped: CachedRawStorage): void {
116
127
  * one backend is the failure that matters and a stale pool label is not.
117
128
  */
118
129
  export function wrapStorageWithCache(storage: IRawStorage, label: string): IRawStorage {
119
- if (storage instanceof MemoryRawStorage) {
130
+ if (storage instanceof MemoryRawStorage || isOwnReadCache(storage)) {
120
131
  return storage;
121
132
  }
122
133
  if (storage instanceof CachedRawStorage) {
@@ -9,7 +9,7 @@ import type {
9
9
  StrandConnectionOptions, SereusPluginResult, StrandTransactor, Libp2pNodeWithRepo,
10
10
  StrandOfflineOptions, StrandOfflineController,
11
11
  } from './types.js';
12
- import { applyAppSchemaAfterQueue, type AppSchemaApply } from './app-schema.js';
12
+ import { applyAppSchemaOrDefer, type AppSchemaApply, type PeerConnectEvents } from './app-schema.js';
13
13
  import { STRAND_SCHEMA } from './strand-schema.js';
14
14
  import { resolveStrandClusterSize, STRAND_CLUSTER_POLICY } from './cluster-size.js';
15
15
  import { wrapStorageWithCache, disposeStorageCache } from './cached-storage.js';
@@ -311,6 +311,8 @@ export async function composeStrand(
311
311
  let appSchemaApply: AppSchemaApply | undefined;
312
312
 
313
313
  let createdNode: Libp2p | null = null;
314
+ // The strand node, when there is one: a deferred sApp schema apply waiting for the cohort wakes on its connects.
315
+ let peers: PeerConnectEvents | undefined;
314
316
  let hydrated: { tables: number; indexes: number } | undefined;
315
317
 
316
318
  try {
@@ -347,6 +349,7 @@ export async function composeStrand(
347
349
  coordinatedRepo = repo;
348
350
  log('Created libp2p node (port: %d, fretProfile: %s, storage=%s)', port, fretProfile, !!storage);
349
351
  }
352
+ peers = node;
350
353
 
351
354
  collectionFactory.registerLibp2pNode(networkName, node, coordinatedRepo);
352
355
  log('Registered libp2p node with collection factory');
@@ -417,12 +420,12 @@ export async function composeStrand(
417
420
  // migrated instead of restored. No schema in this repo evolves that way, so this
418
421
  // is a note for whoever first ships a migration that does.
419
422
  //
420
- // The one exception: an apply refused by queued offline transactions does not fail the
421
- // connect. The strand comes up on the `App` schema it had, and the apply is retried as the
422
- // queue drains (see `applyAppSchemaAfterQueue`).
423
+ // The exception: an apply refused by queued offline transactions, or because the strand's
424
+ // cohort could not be reached, does not fail the connect, and is retried as the queue drains
425
+ // or when a peer connects. See `applyAppSchemaOrDefer`, including what `db` holds meanwhile.
423
426
  if (schema) {
424
427
  log('Applying sApp schema for strand %s', strandId);
425
- appSchemaApply = await applyAppSchemaAfterQueue(db, schema, pluginResult.offline, released.signal);
428
+ appSchemaApply = await applyAppSchemaOrDefer(db, schema, { queue: pluginResult.offline, peers }, released.signal);
426
429
  }
427
430
  } catch (err) {
428
431
  // Clean up resources if setup fails after partial initialization.
@@ -511,6 +514,9 @@ async function registerStrandPlugins(
511
514
  const storage = strand.storage;
512
515
  pluginConfig.rawStorageFactory = () => storage;
513
516
  }
517
+ // NOTE: `cost_profile` is left at upstream's default, `distributed` on the network transactor. A
518
+ // strand keeps each block on `DEFAULT_STRAND_CLUSTER_SIZE` machines, so in a larger party a read
519
+ // can leave the machine; a smaller one pays planner overhead, never a wrong result.
514
520
  // NOTE: `networkCommitTimeoutMs` is left at upstream's default (five minutes); nothing was
515
521
  // measured to choose another. A network-acknowledged commit made while transactions are queued
516
522
  // (any `Strand` write, all of them tagged 'network') waits that long behind them holding
package/src/index.ts CHANGED
@@ -16,7 +16,7 @@ export {
16
16
  } from './cluster-size.js';
17
17
  export { wrapStorageWithCache, disposeStorageCache } from './cached-storage.js';
18
18
  export type {
19
- StrandConnectionOptions, SereusPluginResult, StrandTransactor, StrandOfflineOptions, StrandOfflineController, AppSchemaOutcome,
19
+ StrandConnectionOptions, SereusPluginResult, StrandTransactor, StrandOfflineOptions, StrandOfflineController, AppSchemaOutcome, AppSchemaWait,
20
20
  } from './types.js';
21
21
  export type { SqlCommitDurability, CommitFullyHeld } from '@optimystic/quereus-plugin-optimystic/plugin';
22
22
  export {
package/src/types.ts CHANGED
@@ -97,13 +97,16 @@ export type StrandOfflineController = Pick<OfflineMode,
97
97
  'enter' | 'exit' | 'isEntered' | 'whenDrained' | 'onStatus' | 'onQueueState' | 'queueState'
98
98
  | 'entries' | 'status' | 'discard' | 'outcomes' | 'acknowledge'>;
99
99
 
100
+ /** What a deferred sApp schema apply waits for (see {@link SereusPluginResult.appSchemaWaitingFor}). */
101
+ export type AppSchemaWait = 'queue' | 'cohort';
102
+
100
103
  /**
101
104
  * How a connection's sApp schema apply ended (see {@link SereusPluginResult.appSchema}):
102
105
  *
103
- * - `applied` — the schema is in place. `deferred` when queued offline transactions refused the
104
- * first apply and a later one, once they had settled, landed.
105
- * - `failed` — a deferred retry failed for a reason other than the queue; the connection keeps the
106
- * schema it had before.
106
+ * - `applied` — the schema is in place. `deferred` when the first apply was refused (by queued
107
+ * offline transactions, or because the strand's cohort could not be reached) and a later one landed.
108
+ * - `failed` — a deferred retry failed for another reason; the connection keeps the schema it had
109
+ * before.
107
110
  * - `cancelled` — the connection shut down before a deferred retry landed.
108
111
  */
109
112
  export type AppSchemaOutcome =
@@ -163,12 +166,18 @@ export interface SereusPluginResult {
163
166
  /**
164
167
  * Present when {@link StrandConnectionOptions.schema} was given; never rejects. Resolves
165
168
  * `{ state: 'applied' }` at once when the apply succeeded at connect. When queued offline
166
- * transactions refused it, the connection comes up on the `App` schema it already had and
167
- * retries each time the queue drains; this settles when a retry lands, fails otherwise, or
168
- * {@link shutdown} runs first.
169
+ * transactions refused it, or the strand's cohort could not be reached, the connection comes up
170
+ * anyway and retries ({@link appSchemaWaitingFor}); this settles when a retry lands, fails
171
+ * otherwise, or {@link shutdown} runs first.
169
172
  */
170
173
  appSchema?: Promise<AppSchemaOutcome>;
171
- /** The queued transaction ids that refused the connect-time apply. Present only when it was deferred. */
174
+ /**
175
+ * What the connect-time apply waits for: `'queue'`, queued offline transactions (retried each time
176
+ * the queue drains), or `'cohort'`, the strand's members (retried when the strand node connects to
177
+ * a peer, and on a backoff). Present only when it was deferred.
178
+ */
179
+ appSchemaWaitingFor?: AppSchemaWait;
180
+ /** The queued transaction ids that refused the connect-time apply. Present only when the queue refused it. */
172
181
  appSchemaDeferredBy?: readonly string[];
173
182
  /** Shuts down the libp2p node and collection factory. Call when done. */
174
183
  shutdown: () => Promise<void>;