@serfab/quereus-plugin-sereus 1.20.0 → 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,6 +90,8 @@ 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
  *
@@ -99,8 +101,6 @@ export type StrandOfflineController = Pick<OfflineMode, 'enter' | 'exit' | 'isEn
99
101
  * before.
100
102
  * - `cancelled` — the connection shut down before a deferred retry landed.
101
103
  */
102
- /** What a deferred sApp schema apply waits for (see {@link SereusPluginResult.appSchemaWaitingFor}). */
103
- export type AppSchemaWait = 'queue' | 'cohort';
104
104
  export type AppSchemaOutcome = {
105
105
  state: 'applied';
106
106
  deferred?: true;
@@ -166,8 +166,8 @@ export interface SereusPluginResult {
166
166
  * Present when {@link StrandConnectionOptions.schema} was given; never rejects. Resolves
167
167
  * `{ state: 'applied' }` at once when the apply succeeded at connect. When queued offline
168
168
  * transactions refused it, or the strand's cohort could not be reached, the connection comes up
169
- * on the `App` schema it already had and retries ({@link appSchemaWaitingFor}); this settles when
170
- * a retry lands, fails otherwise, or {@link shutdown} runs first.
169
+ * anyway and retries ({@link appSchemaWaitingFor}); this settles when a retry lands, fails
170
+ * otherwise, or {@link shutdown} runs first.
171
171
  */
172
172
  appSchema?: Promise<AppSchemaOutcome>;
173
173
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serfab/quereus-plugin-sereus",
3
- "version": "1.20.0",
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.23.0",
72
- "@optimystic/db-p2p": "^1.23.0",
73
- "@optimystic/db-p2p-storage-fs": "^1.23.0",
74
- "@optimystic/db-p2p-storage-web": "^1.23.0",
75
- "@optimystic/quereus-plugin-crypto": "^1.23.0",
76
- "@optimystic/quereus-plugin-optimystic": "^1.23.0",
77
- "@quereus/quereus": "^4.23.0",
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
@@ -72,8 +72,10 @@ type Deferral = { wait: 'queue'; transactionIds: readonly string[] } | { wait: '
72
72
  * alone after an app update would otherwise not open the strand at all (gotchoices/sereus#55).
73
73
  * Retried when the strand node connects to a peer, and on a backoff ({@link COHORT_RETRY_MS}).
74
74
  *
75
- * Quereus unwinds a refused apply, so `db` keeps the `App` schema it had, and `appSchema` settles
76
- * with how the retries ended. Any other error from the first apply is thrown.
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}).
77
79
  *
78
80
  * Waiting before returning was rejected: that withholds the strand from the app right after an app
79
81
  * update, which is when a phone is most likely to be offline. So was refusing the connect: the queue
@@ -98,7 +100,7 @@ export async function applyAppSchemaOrDefer(
98
100
  log('sApp schema applied');
99
101
  return { appSchema: Promise.resolve({ state: 'applied' }) };
100
102
  } catch (err) {
101
- const deferral = deferralOf(err);
103
+ const deferral = await retryableRefusalOf(db, err);
102
104
  if (!deferral) {
103
105
  throw err;
104
106
  }
@@ -129,8 +131,7 @@ async function retryDeferredAppSchema(
129
131
  if (released.aborted) {
130
132
  return { state: 'cancelled' };
131
133
  }
132
- await declareAppSchema(db, schema);
133
- await db.exec('apply schema App;', undefined, { transaction: true });
134
+ await applyOutsideOpenTransaction(db, schema, released);
134
135
  log('Deferred sApp schema applied');
135
136
  return { state: 'applied', deferred: true };
136
137
  } catch (err) {
@@ -138,12 +139,7 @@ async function retryDeferredAppSchema(
138
139
  log('Deferred sApp schema apply cancelled by shutdown');
139
140
  return { state: 'cancelled' };
140
141
  }
141
- if (err instanceof TransactionActiveError) {
142
- log('Deferred sApp schema apply waiting for an open transaction to end');
143
- await abortableDelay(OPEN_TRANSACTION_RETRY_MS, released);
144
- continue;
145
- }
146
- const again = deferralOf(err);
142
+ const again = await retryableRefusalOf(db, err);
147
143
  if (!again) {
148
144
  log('Deferred sApp schema apply failed: %O', err);
149
145
  return { state: 'failed', error: err };
@@ -154,6 +150,26 @@ async function retryDeferredAppSchema(
154
150
  }
155
151
  }
156
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
+ }
169
+ }
170
+ }
171
+ }
172
+
157
173
  /** Waits for whatever may get the retry past `deferral`. */
158
174
  async function nextChance(deferral: Deferral, waits: AppSchemaWaits, cohortRetries: number, released: AbortSignal): Promise<void> {
159
175
  if (deferral.wait === 'queue' && waits.queue) {
@@ -166,9 +182,42 @@ async function nextChance(deferral: Deferral, waits: AppSchemaWaits, cohortRetri
166
182
  await nextCohortChance(waits.peers, cohortRetryDelay(cohortRetries), released);
167
183
  }
168
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
+
169
214
  /**
170
215
  * The refusal `err` is or wraps, when a later retry can get past it: Quereus rewraps an error out of
171
- * `apply schema`, keeping it as `cause`.
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.
172
221
  */
173
222
  function deferralOf(err: unknown): Deferral | undefined {
174
223
  for (let at = err; at instanceof Error; at = at.cause) {
@@ -206,7 +255,13 @@ function cohortRetryDelay(retriesBefore: number): number {
206
255
  */
207
256
  const COHORT_CONNECT_SETTLE_MS = 2_000;
208
257
 
209
- /** Resolves {@link COHORT_CONNECT_SETTLE_MS} after the strand node's next peer connect, after `delayMs`, or when `signal` aborts. */
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
+ */
210
265
  async function nextCohortChance(peers: PeerConnectEvents | undefined, delayMs: number, signal: AbortSignal): Promise<void> {
211
266
  const byConnect = await new Promise<boolean>(resolve => {
212
267
  const done = (connected: boolean): void => {
@@ -421,9 +421,8 @@ export async function composeStrand(
421
421
  // is a note for whoever first ships a migration that does.
422
422
  //
423
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. The strand comes up on the `App`
425
- // schema it had, and the apply is retried as the queue drains or when a peer connects (see
426
- // `applyAppSchemaOrDefer`).
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.
427
426
  if (schema) {
428
427
  log('Applying sApp schema for strand %s', strandId);
429
428
  appSchemaApply = await applyAppSchemaOrDefer(db, schema, { queue: pluginResult.offline, peers }, released.signal);
@@ -515,6 +514,9 @@ async function registerStrandPlugins(
515
514
  const storage = strand.storage;
516
515
  pluginConfig.rawStorageFactory = () => storage;
517
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.
518
520
  // NOTE: `networkCommitTimeoutMs` is left at upstream's default (five minutes); nothing was
519
521
  // measured to choose another. A network-acknowledged commit made while transactions are queued
520
522
  // (any `Strand` write, all of them tagged 'network') waits that long behind them holding
package/src/types.ts CHANGED
@@ -97,6 +97,9 @@ 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
  *
@@ -106,9 +109,6 @@ export type StrandOfflineController = Pick<OfflineMode,
106
109
  * before.
107
110
  * - `cancelled` — the connection shut down before a deferred retry landed.
108
111
  */
109
- /** What a deferred sApp schema apply waits for (see {@link SereusPluginResult.appSchemaWaitingFor}). */
110
- export type AppSchemaWait = 'queue' | 'cohort';
111
-
112
112
  export type AppSchemaOutcome =
113
113
  | { state: 'applied'; deferred?: true }
114
114
  | { state: 'failed'; error: unknown }
@@ -167,8 +167,8 @@ export interface SereusPluginResult {
167
167
  * Present when {@link StrandConnectionOptions.schema} was given; never rejects. Resolves
168
168
  * `{ state: 'applied' }` at once when the apply succeeded at connect. When queued offline
169
169
  * transactions refused it, or the strand's cohort could not be reached, the connection comes up
170
- * on the `App` schema it already had and retries ({@link appSchemaWaitingFor}); this settles when
171
- * a retry lands, fails otherwise, or {@link shutdown} runs first.
170
+ * anyway and retries ({@link appSchemaWaitingFor}); this settles when a retry lands, fails
171
+ * otherwise, or {@link shutdown} runs first.
172
172
  */
173
173
  appSchema?: Promise<AppSchemaOutcome>;
174
174
  /**