@serfab/quereus-plugin-sereus 1.20.0 → 1.22.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/src/app-schema.ts CHANGED
@@ -1,263 +1,397 @@
1
- import debug from 'debug';
2
- import { TransactionActiveError, type Database } from '@quereus/quereus';
3
- import type { Libp2p } from '@libp2p/interface';
4
- import { classifyCommitFailure } from '@optimystic/db-core';
5
- import { QueuedEntriesBlockSchemaChangeError, QueueDisposedError } from '@optimystic/quereus-plugin-optimystic/plugin';
6
- import type { StrandOfflineController, AppSchemaOutcome, AppSchemaWait } from './types.js';
7
-
8
- const log = debug('sereus:plugin:strand');
9
-
10
- /**
11
- * Step 7 of `composeStrand`: declare the sApp's schema as `App` and apply it — a
12
- * declarative diff against the catalog, so re-applying a schema that is already in place
13
- * emits nothing. The one site that applies an `App` schema: `composeStrand` calls it at
14
- * bring-up (through {@link applyAppSchemaOrDefer}, whose deferred retry shares its
15
- * declaration), and cadre-core's `StrandDatabase.attachAppSchema` calls it on a live storage
16
- * replica when an app claims the strand. The database must already be composed (optimystic
17
- * set as the default vtab), or the tables land in memory instead of the strand.
18
- *
19
- * Refuses a schema holding an item the Quereus parser skipped: it keeps any item whose leading
20
- * keyword it does not model (`create unique index …`, a misspelled `tabel`, `domain`) as an
21
- * opaque placeholder that apply ignores, so the app would otherwise run without that item.
22
- *
23
- * Refuses a schema holding a `seed` item: the apply runs on every node of the strand at every
24
- * connect, so seed inserts would put a network write on each bring-up and two nodes inserting
25
- * the same key at once would collide. Rows an app needs at birth are the founding app's to write.
26
- */
27
- export async function applyAppSchema(db: Database, schema: string): Promise<void> {
28
- await declareAppSchema(db, schema);
29
- await db.exec('apply schema App;');
30
- }
31
-
32
- /** Declare `schema` as `App`, refusing the items {@link applyAppSchema} refuses. Writes nothing to the strand. */
33
- async function declareAppSchema(db: Database, schema: string): Promise<void> {
34
- await db.exec(`
35
- declare schema App {
36
- ${schema}
37
- }
38
- `);
39
- assertNoIgnoredItems(db);
40
- assertNoSeedItems(db);
41
- }
42
-
43
- /** What {@link applyAppSchemaOrDefer} reports, in the shape `SereusPluginResult` carries it. */
44
- export interface AppSchemaApply {
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. */
49
- appSchemaDeferredBy?: readonly string[];
50
- }
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
-
64
- /**
65
- * Step 7 of `composeStrand`: {@link applyAppSchema}, except that an apply refused for a reason
66
- * that passes does not throw. Two such reasons:
67
- *
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, 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.
77
- *
78
- * Waiting before returning was rejected: that withholds the strand from the app right after an app
79
- * update, which is when a phone is most likely to be offline. So was refusing the connect: the queue
80
- * can drain only while the composition is alive.
81
- *
82
- * `released` is aborted when the composition shuts down; a retry not yet landed then settles
83
- * `cancelled`.
84
- *
85
- * A retry runs while the app is using `db`, so it is one atomic batch that refuses to run inside a
86
- * transaction another caller holds open, and waits for that transaction to end: run inside it, the
87
- * apply would be committed or rolled back with the app's rows, and a rollback leaves the index it
88
- * built holding entries for rows that are gone.
89
- */
90
- export async function applyAppSchemaOrDefer(
91
- db: Database,
92
- schema: string,
93
- waits: AppSchemaWaits,
94
- released: AbortSignal,
95
- ): Promise<AppSchemaApply> {
96
- try {
97
- await applyAppSchema(db, schema);
98
- log('sApp schema applied');
99
- return { appSchema: Promise.resolve({ state: 'applied' }) };
100
- } catch (err) {
101
- const deferral = deferralOf(err);
102
- if (!deferral) {
103
- throw err;
104
- }
105
- logDeferral('sApp schema apply', deferral);
106
- return {
107
- appSchema: retryDeferredAppSchema(db, schema, deferral, waits, released),
108
- appSchemaWaitingFor: deferral.wait,
109
- ...(deferral.wait === 'queue' && { appSchemaDeferredBy: deferral.transactionIds }),
110
- };
111
- }
112
- }
113
-
114
- async function retryDeferredAppSchema(
115
- db: Database,
116
- schema: string,
117
- first: Deferral,
118
- waits: AppSchemaWaits,
119
- released: AbortSignal,
120
- ): Promise<AppSchemaOutcome> {
121
- let deferral = first;
122
- let cohortRetries = 0;
123
- for (;;) {
124
- try {
125
- await nextChance(deferral, waits, cohortRetries, released);
126
- if (deferral.wait === 'cohort') {
127
- cohortRetries++;
128
- }
129
- if (released.aborted) {
130
- return { state: 'cancelled' };
131
- }
132
- await declareAppSchema(db, schema);
133
- await db.exec('apply schema App;', undefined, { transaction: true });
134
- log('Deferred sApp schema applied');
135
- return { state: 'applied', deferred: true };
136
- } catch (err) {
137
- if (released.aborted || err instanceof QueueDisposedError) {
138
- log('Deferred sApp schema apply cancelled by shutdown');
139
- return { state: 'cancelled' };
140
- }
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);
147
- if (!again) {
148
- log('Deferred sApp schema apply failed: %O', err);
149
- return { state: 'failed', error: err };
150
- }
151
- logDeferral('Deferred sApp schema apply', again);
152
- deferral = again;
153
- }
154
- }
155
- }
156
-
157
- /** Waits for whatever may get the retry past `deferral`. */
158
- async function nextChance(deferral: Deferral, waits: AppSchemaWaits, cohortRetries: number, released: AbortSignal): Promise<void> {
159
- if (deferral.wait === 'queue' && waits.queue) {
160
- // NOTE: this loops without a pause when `whenDrained` resolves at once while the refusal stands
161
- // (a segment left sealed with nothing queued, say). Upstream counts a removal still in progress
162
- // as undrained, so no such state is known; if one shows up as a busy loop, back off between tries.
163
- await waits.queue.whenDrained();
164
- return;
165
- }
166
- await nextCohortChance(waits.peers, cohortRetryDelay(cohortRetries), released);
167
- }
168
-
169
- /**
170
- * 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`.
172
- */
173
- function deferralOf(err: unknown): Deferral | undefined {
174
- for (let at = err; at instanceof Error; at = at.cause) {
175
- if (at instanceof QueuedEntriesBlockSchemaChangeError) {
176
- return { wait: 'queue', transactionIds: at.transactionIds };
177
- }
178
- if (classifyCommitFailure(at).kind === 'cohort-unreachable') {
179
- return { wait: 'cohort' };
180
- }
181
- }
182
- return undefined;
183
- }
184
-
185
- function logDeferral(what: string, deferral: Deferral): void {
186
- if (deferral.wait === 'queue') {
187
- log('%s refused by queued transactions %o; retrying once they settle', what, deferral.transactionIds);
188
- } else {
189
- log('%s could not reach the strand cohort; retrying when a peer connects', what);
190
- }
191
- }
192
-
193
- /**
194
- * Backoff for a retry waiting for the cohort, by how many came before it. A connect wakes the retry
195
- * sooner, so the backoff only bounds how long a missed or too-early connect leaves the schema behind.
196
- */
197
- const COHORT_RETRY_MS = [15_000, 30_000, 60_000, 120_000, 300_000] as const;
198
-
199
- function cohortRetryDelay(retriesBefore: number): number {
200
- return COHORT_RETRY_MS[Math.min(retriesBefore, COHORT_RETRY_MS.length - 1)]!;
201
- }
202
-
203
- /**
204
- * How long a retry woken by a connect waits first, so the peer is identified and in the ring before
205
- * the apply asks for its cohort; a retry that still finds it missing waits for the next chance.
206
- */
207
- const COHORT_CONNECT_SETTLE_MS = 2_000;
208
-
209
- /** Resolves {@link COHORT_CONNECT_SETTLE_MS} after the strand node's next peer connect, after `delayMs`, or when `signal` aborts. */
210
- async function nextCohortChance(peers: PeerConnectEvents | undefined, delayMs: number, signal: AbortSignal): Promise<void> {
211
- const byConnect = await new Promise<boolean>(resolve => {
212
- const done = (connected: boolean): void => {
213
- clearTimeout(timer);
214
- peers?.removeEventListener('peer:connect', onConnect);
215
- signal.removeEventListener('abort', onAbort);
216
- resolve(connected);
217
- };
218
- const onConnect = (): void => done(true);
219
- const onAbort = (): void => done(false);
220
- const timer = setTimeout(() => done(false), delayMs);
221
- peers?.addEventListener('peer:connect', onConnect);
222
- signal.addEventListener('abort', onAbort, { once: true });
223
- });
224
- if (byConnect) {
225
- await abortableDelay(COHORT_CONNECT_SETTLE_MS, signal);
226
- }
227
- }
228
-
229
- /** How long a deferred sApp schema apply waits before trying again while another caller's transaction is open. */
230
- const OPEN_TRANSACTION_RETRY_MS = 250;
231
-
232
- /** Resolves after `ms`, or as soon as `signal` aborts. */
233
- function abortableDelay(ms: number, signal: AbortSignal): Promise<void> {
234
- return new Promise(resolve => {
235
- const done = (): void => {
236
- clearTimeout(timer);
237
- signal.removeEventListener('abort', done);
238
- resolve();
239
- };
240
- const timer = setTimeout(done, ms);
241
- signal.addEventListener('abort', done, { once: true });
242
- });
243
- }
244
-
245
- function declaredAppItems(db: Database) {
246
- return db.declaredSchemaManager.getDeclaredSchema('App')?.items ?? [];
247
- }
248
-
249
- function assertNoIgnoredItems(db: Database): void {
250
- const ignored = declaredAppItems(db).filter(item => item.type === 'declareIgnored').length;
251
- if (ignored > 0) {
252
- // Only a count: Quereus leaves an ignored item's source text empty.
253
- 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\``);
254
- }
255
- }
256
-
257
- function assertNoSeedItems(db: Database): void {
258
- // Quereus refuses a second seed for one table at declare, so these names are distinct.
259
- const tables = declaredAppItems(db).flatMap(item => item.type === 'declaredSeed' ? [item.tableName] : []);
260
- if (tables.length > 0) {
261
- 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`);
262
- }
263
- }
1
+ import debug from 'debug';
2
+ import { QuereusError, StatusCode, TransactionActiveError, type Database } from '@quereus/quereus';
3
+ import type { Libp2p } from '@libp2p/interface';
4
+ import { classifyCommitFailure } from '@optimystic/db-core';
5
+ import { QueuedEntriesBlockSchemaChangeError, QueueDisposedError } from '@optimystic/quereus-plugin-optimystic/plugin';
6
+ import type { StrandOfflineController, AppSchemaOutcome, AppSchemaWait } from './types.js';
7
+
8
+ const log = debug('sereus:plugin:strand');
9
+
10
+ /**
11
+ * Step 7 of `composeStrand`: declare the sApp's schema as `App` and apply it — a
12
+ * declarative diff against the catalog, so re-applying a schema that is already in place
13
+ * emits nothing. The one site that applies an `App` schema: `composeStrand` calls it at
14
+ * bring-up (through {@link applyAppSchemaOrDefer}, whose deferred retry shares its
15
+ * declaration), and cadre-core's `StrandDatabase.attachAppSchema` calls it on a live storage
16
+ * replica when an app claims the strand. The database must already be composed (optimystic
17
+ * set as the default vtab), or the tables land in memory instead of the strand.
18
+ *
19
+ * Refuses a schema holding an item the Quereus parser skipped: it keeps any item whose leading
20
+ * keyword it does not model (`create unique index …`, a misspelled `tabel`, `domain`) as an
21
+ * opaque placeholder that apply ignores, so the app would otherwise run without that item.
22
+ *
23
+ * Refuses a schema holding a `seed` item: the apply runs on every node of the strand at every
24
+ * connect, so seed inserts would put a network write on each bring-up and two nodes inserting
25
+ * the same key at once would collide. Rows an app needs at birth are the founding app's to write.
26
+ *
27
+ * Every refusal decided by the schema itself, or by the schema against this node's tables and rows,
28
+ * throws {@link AppSchemaRefusedError}: retrying the same schema here fails the same way.
29
+ */
30
+ export async function applyAppSchema(db: Database, schema: string): Promise<void> {
31
+ try {
32
+ await declareAppSchema(db, schema);
33
+ await db.exec('apply schema App;');
34
+ } catch (err) {
35
+ throw asAppSchemaRefusal(err);
36
+ }
37
+ }
38
+
39
+ /** Declare `schema` as `App`, refusing the items {@link applyAppSchema} refuses. Writes nothing to the strand. */
40
+ async function declareAppSchema(db: Database, schema: string): Promise<void> {
41
+ await db.exec(`
42
+ declare schema App {
43
+ ${schema}
44
+ }
45
+ `);
46
+ assertNoIgnoredItems(db);
47
+ assertNoSeedItems(db);
48
+ }
49
+
50
+ /**
51
+ * An sApp schema refused for a reason that does not pass: the schema itself (a seed item, an item the
52
+ * parser skipped, a syntax error), or the schema against the tables and rows this node holds, such as a
53
+ * `not null` column with no default added to a table that has rows. Applying the same schema here again
54
+ * fails the same way, so a host should not retry it until the app supplies a different one. A storage
55
+ * or network fault is never this error.
56
+ *
57
+ * `cause` is the error Quereus raised, when it raised one.
58
+ */
59
+ export class AppSchemaRefusedError extends Error {
60
+ constructor(message: string, options?: ErrorOptions) {
61
+ super(message, options);
62
+ this.name = 'AppSchemaRefusedError';
63
+ }
64
+ }
65
+
66
+ /** The {@link AppSchemaRefusedError} `err` is or wraps, walking `cause`, so a wrapper added between the apply and the catch cannot hide it. */
67
+ export function appSchemaRefusalOf(err: unknown): AppSchemaRefusedError | undefined {
68
+ for (let at = err; at instanceof Error; at = at.cause) {
69
+ if (at instanceof AppSchemaRefusedError) {
70
+ return at;
71
+ }
72
+ }
73
+ return undefined;
74
+ }
75
+
76
+ /** What {@link applyAppSchemaOrDefer} reports, in the shape `SereusPluginResult` carries it. */
77
+ export interface AppSchemaApply {
78
+ appSchema: Promise<AppSchemaOutcome>;
79
+ /** What the connect-time apply waits for. Present only when it was deferred. */
80
+ appSchemaWaitingFor?: AppSchemaWait;
81
+ /** The queued transaction ids that refused the connect-time apply. Present only when the queue refused it. */
82
+ appSchemaDeferredBy?: readonly string[];
83
+ }
84
+
85
+ /** The strand node's peer events, which a retry waiting for the cohort wakes on. */
86
+ export type PeerConnectEvents = Pick<Libp2p, 'addEventListener' | 'removeEventListener'>;
87
+
88
+ /** Where a deferred apply waits: the offline queue, when there is one, and the strand node, when there is one. */
89
+ export interface AppSchemaWaits {
90
+ queue?: Pick<StrandOfflineController, 'whenDrained'>;
91
+ peers?: PeerConnectEvents;
92
+ }
93
+
94
+ /** Why an apply was refused, when it is a refusal a later retry can get past. */
95
+ type Deferral = { wait: 'queue'; transactionIds: readonly string[] } | { wait: 'cohort' };
96
+
97
+ /**
98
+ * Step 7 of `composeStrand`: {@link applyAppSchema}, except that an apply refused for a reason
99
+ * that passes does not throw. Two such reasons:
100
+ *
101
+ * - queued offline transactions wrote a table the apply changes (`QueuedEntriesBlockSchemaChangeError`);
102
+ * retried each time the queue drains;
103
+ * - the strand's cohort could not be reached (Optimystic's `classifyCommitFailure` says
104
+ * `cohort-unreachable`): an apply writes the strand's catalog, which needs the cohort, so a member
105
+ * alone after an app update would otherwise not open the strand at all (gotchoices/sereus#55).
106
+ * Retried when the strand node connects to a peer, and on a backoff ({@link COHORT_RETRY_MS}).
107
+ *
108
+ * Quereus unwinds a refused apply, whether a migration step or the closing catalog commit refused it,
109
+ * so `db` keeps the `App` schema it had, and `appSchema` settles with how the retries ended. Any other
110
+ * error from the first apply is thrown ({@link AppSchemaRefusedError} when the schema can never apply
111
+ * to these tables), and so is a refusal Quereus could not unwind that leaves a retry nothing to send
112
+ * ({@link retryableRefusalOf}). A retry that ends in such a refusal settles `failed` with it, typed the same way.
113
+ *
114
+ * Waiting before returning was rejected: that withholds the strand from the app right after an app
115
+ * update, which is when a phone is most likely to be offline. So was refusing the connect: the queue
116
+ * can drain only while the composition is alive.
117
+ *
118
+ * `released` is aborted when the composition shuts down; a retry not yet landed then settles
119
+ * `cancelled`.
120
+ *
121
+ * A retry runs while the app is using `db`, so it is one atomic batch that refuses to run inside a
122
+ * transaction another caller holds open, and waits for that transaction to end: run inside it, the
123
+ * apply would be committed or rolled back with the app's rows, and a rollback leaves the index it
124
+ * built holding entries for rows that are gone.
125
+ */
126
+ export async function applyAppSchemaOrDefer(
127
+ db: Database,
128
+ schema: string,
129
+ waits: AppSchemaWaits,
130
+ released: AbortSignal,
131
+ ): Promise<AppSchemaApply> {
132
+ try {
133
+ await applyAppSchema(db, schema);
134
+ log('sApp schema applied');
135
+ return { appSchema: Promise.resolve({ state: 'applied' }) };
136
+ } catch (err) {
137
+ const deferral = await retryableRefusalOf(db, err);
138
+ if (!deferral) {
139
+ throw err;
140
+ }
141
+ logDeferral('sApp schema apply', deferral);
142
+ return {
143
+ appSchema: retryDeferredAppSchema(db, schema, deferral, waits, released),
144
+ appSchemaWaitingFor: deferral.wait,
145
+ ...(deferral.wait === 'queue' && { appSchemaDeferredBy: deferral.transactionIds }),
146
+ };
147
+ }
148
+ }
149
+
150
+ async function retryDeferredAppSchema(
151
+ db: Database,
152
+ schema: string,
153
+ first: Deferral,
154
+ waits: AppSchemaWaits,
155
+ released: AbortSignal,
156
+ ): Promise<AppSchemaOutcome> {
157
+ let deferral = first;
158
+ let cohortRetries = 0;
159
+ for (;;) {
160
+ try {
161
+ await nextChance(deferral, waits, cohortRetries, released);
162
+ if (deferral.wait === 'cohort') {
163
+ cohortRetries++;
164
+ }
165
+ if (released.aborted) {
166
+ return { state: 'cancelled' };
167
+ }
168
+ await applyOutsideOpenTransaction(db, schema, released);
169
+ log('Deferred sApp schema applied');
170
+ return { state: 'applied', deferred: true };
171
+ } catch (err) {
172
+ if (released.aborted || err instanceof QueueDisposedError) {
173
+ log('Deferred sApp schema apply cancelled by shutdown');
174
+ return { state: 'cancelled' };
175
+ }
176
+ const again = await retryableRefusalOf(db, err);
177
+ if (!again) {
178
+ log('Deferred sApp schema apply failed: %O', err);
179
+ return { state: 'failed', error: asAppSchemaRefusal(err) };
180
+ }
181
+ logDeferral('Deferred sApp schema apply', again);
182
+ deferral = again;
183
+ }
184
+ }
185
+ }
186
+
187
+ /** One atomic apply, once no other caller holds a transaction open. Throws the open-transaction refusal when `released` aborts during the wait. */
188
+ async function applyOutsideOpenTransaction(db: Database, schema: string, released: AbortSignal): Promise<void> {
189
+ for (;;) {
190
+ await declareAppSchema(db, schema);
191
+ try {
192
+ await db.exec('apply schema App;', undefined, { transaction: true });
193
+ return;
194
+ } catch (err) {
195
+ if (!(err instanceof TransactionActiveError)) {
196
+ throw err;
197
+ }
198
+ log('Deferred sApp schema apply waiting for an open transaction to end');
199
+ await abortableDelay(OPEN_TRANSACTION_RETRY_MS, released);
200
+ if (released.aborted) {
201
+ throw err;
202
+ }
203
+ }
204
+ }
205
+ }
206
+
207
+ /** Waits for whatever may get the retry past `deferral`. */
208
+ async function nextChance(deferral: Deferral, waits: AppSchemaWaits, cohortRetries: number, released: AbortSignal): Promise<void> {
209
+ if (deferral.wait === 'queue' && waits.queue) {
210
+ // NOTE: this loops without a pause when `whenDrained` resolves at once while the refusal stands
211
+ // (a segment left sealed with nothing queued, say). Upstream counts a removal still in progress
212
+ // as undrained, so no such state is known; if one shows up as a busy loop, back off between tries.
213
+ await waits.queue.whenDrained();
214
+ return;
215
+ }
216
+ await nextCohortChance(waits.peers, cohortRetryDelay(cohortRetries), released);
217
+ }
218
+
219
+ /**
220
+ * The refusal `err` is or wraps, when retrying it would send something. An apply refused after a
221
+ * `drop table` or `drop column` cannot be unwound, so `db` can already hold the whole new schema while
222
+ * the store holds the old one. A retry would then diff clean and settle `applied` with nothing written,
223
+ * so that refusal counts as a failure: a restart plans the change again from the store.
224
+ */
225
+ async function retryableRefusalOf(db: Database, err: unknown): Promise<Deferral | undefined> {
226
+ const deferral = deferralOf(err);
227
+ if (!deferral) {
228
+ return undefined;
229
+ }
230
+ try {
231
+ if (await appSchemaHasPendingChanges(db)) {
232
+ return deferral;
233
+ }
234
+ log('sApp schema apply was refused, and the database already holds the new schema: %O', err);
235
+ } catch (diffError) {
236
+ log('Could not check what a refused sApp schema apply left to send: %O', diffError);
237
+ }
238
+ return undefined;
239
+ }
240
+
241
+ async function appSchemaHasPendingChanges(db: Database): Promise<boolean> {
242
+ for await (const _change of db.eval('diff schema App')) {
243
+ return true;
244
+ }
245
+ return false;
246
+ }
247
+
248
+ /**
249
+ * The refusal `err` is or wraps, when a later retry can get past it: Quereus rewraps an error out of
250
+ * a migration step, keeping it as `cause`.
251
+ *
252
+ * `classifyCommitFailure` refuses to walk `cause` itself, because a commit-phase shortfall nested
253
+ * there means the write is in doubt rather than unsent. Walking it here is safe: an apply is a
254
+ * declarative diff, so a retry after a write that did land changes nothing.
255
+ */
256
+ function deferralOf(err: unknown): Deferral | undefined {
257
+ for (let at = err; at instanceof Error; at = at.cause) {
258
+ if (at instanceof QueuedEntriesBlockSchemaChangeError) {
259
+ return { wait: 'queue', transactionIds: at.transactionIds };
260
+ }
261
+ if (classifyCommitFailure(at).kind === 'cohort-unreachable') {
262
+ return { wait: 'cohort' };
263
+ }
264
+ }
265
+ return undefined;
266
+ }
267
+
268
+ function logDeferral(what: string, deferral: Deferral): void {
269
+ if (deferral.wait === 'queue') {
270
+ log('%s refused by queued transactions %o; retrying once they settle', what, deferral.transactionIds);
271
+ } else {
272
+ log('%s could not reach the strand cohort; retrying when a peer connects', what);
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Backoff for a retry waiting for the cohort, by how many came before it. A connect wakes the retry
278
+ * sooner, so the backoff only bounds how long a missed or too-early connect leaves the schema behind.
279
+ */
280
+ const COHORT_RETRY_MS = [15_000, 30_000, 60_000, 120_000, 300_000] as const;
281
+
282
+ function cohortRetryDelay(retriesBefore: number): number {
283
+ return COHORT_RETRY_MS[Math.min(retriesBefore, COHORT_RETRY_MS.length - 1)]!;
284
+ }
285
+
286
+ /**
287
+ * How long a retry woken by a connect waits first, so the peer is identified and in the ring before
288
+ * the apply asks for its cohort; a retry that still finds it missing waits for the next chance.
289
+ */
290
+ const COHORT_CONNECT_SETTLE_MS = 2_000;
291
+
292
+ /**
293
+ * Resolves {@link COHORT_CONNECT_SETTLE_MS} after the strand node's next peer connect, after `delayMs`, or when `signal` aborts.
294
+ *
295
+ * NOTE: every connect wakes a retry, the relay's included, and a retry that reaches the cohort's
296
+ * refusal holds the database's statement lock while it waits for it. If that shows up as stalled app
297
+ * statements on a node with many connects, wake only on a connect to a strand member.
298
+ */
299
+ async function nextCohortChance(peers: PeerConnectEvents | undefined, delayMs: number, signal: AbortSignal): Promise<void> {
300
+ const byConnect = await new Promise<boolean>(resolve => {
301
+ const done = (connected: boolean): void => {
302
+ clearTimeout(timer);
303
+ peers?.removeEventListener('peer:connect', onConnect);
304
+ signal.removeEventListener('abort', onAbort);
305
+ resolve(connected);
306
+ };
307
+ const onConnect = (): void => done(true);
308
+ const onAbort = (): void => done(false);
309
+ const timer = setTimeout(() => done(false), delayMs);
310
+ peers?.addEventListener('peer:connect', onConnect);
311
+ signal.addEventListener('abort', onAbort, { once: true });
312
+ });
313
+ if (byConnect) {
314
+ await abortableDelay(COHORT_CONNECT_SETTLE_MS, signal);
315
+ }
316
+ }
317
+
318
+ /** How long a deferred sApp schema apply waits before trying again while another caller's transaction is open. */
319
+ const OPEN_TRANSACTION_RETRY_MS = 250;
320
+
321
+ /** Resolves after `ms`, or as soon as `signal` aborts. */
322
+ function abortableDelay(ms: number, signal: AbortSignal): Promise<void> {
323
+ return new Promise(resolve => {
324
+ const done = (): void => {
325
+ clearTimeout(timer);
326
+ signal.removeEventListener('abort', done);
327
+ resolve();
328
+ };
329
+ const timer = setTimeout(done, ms);
330
+ signal.addEventListener('abort', done, { once: true });
331
+ });
332
+ }
333
+
334
+ function declaredAppItems(db: Database) {
335
+ return db.declaredSchemaManager.getDeclaredSchema('App')?.items ?? [];
336
+ }
337
+
338
+ function assertNoIgnoredItems(db: Database): void {
339
+ const ignored = declaredAppItems(db).filter(item => item.type === 'declareIgnored').length;
340
+ if (ignored > 0) {
341
+ // Only a count: Quereus leaves an ignored item's source text empty.
342
+ throw new AppSchemaRefusedError(`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\``);
343
+ }
344
+ }
345
+
346
+ function assertNoSeedItems(db: Database): void {
347
+ // Quereus refuses a second seed for one table at declare, so these names are distinct.
348
+ const tables = declaredAppItems(db).flatMap(item => item.type === 'declaredSeed' ? [item.tableName] : []);
349
+ if (tables.length > 0) {
350
+ throw new AppSchemaRefusedError(`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`);
351
+ }
352
+ }
353
+
354
+ /** `err` typed as an {@link AppSchemaRefusedError} when {@link isSchemaRefusal} holds, else `err` unchanged. */
355
+ function asAppSchemaRefusal(err: unknown): unknown {
356
+ if (!isSchemaRefusal(err)) {
357
+ return err;
358
+ }
359
+ return new AppSchemaRefusedError(`sApp schema cannot be applied to this strand's tables: ${err.message}`, { cause: err });
360
+ }
361
+
362
+ /**
363
+ * Status codes Quereus raises for a refusal it decides from the schema and the catalog and rows it holds:
364
+ * a failed migration step is `ERROR` with the step's own error as `cause` (a backfill that breaks
365
+ * `not null` is `CONSTRAINT`, a key or type change it cannot make is `ERROR` or `UNSUPPORTED`).
366
+ * An allowlist rather than a list of fault codes, so a code Quereus adds later keeps today's retries.
367
+ */
368
+ const SCHEMA_REFUSAL_CODES: ReadonlySet<number> = new Set([
369
+ StatusCode.ERROR,
370
+ StatusCode.CONSTRAINT,
371
+ StatusCode.MISMATCH,
372
+ StatusCode.UNSUPPORTED,
373
+ StatusCode.SYNTAX,
374
+ StatusCode.SCHEMA,
375
+ StatusCode.RANGE,
376
+ ]);
377
+
378
+ /**
379
+ * Whether every link of `err`'s `cause` chain is a `QuereusError` with a {@link SCHEMA_REFUSAL_CODES} code.
380
+ * A storage or network fault anywhere in the chain is a plain `Error` (Optimystic's `PromiseShortfallError`,
381
+ * `BlockUnavailableError`) or carries `BUSY` or `MISUSE`, so it keeps the error untyped and retryable.
382
+ *
383
+ * NOTE: `ERROR` is broad, and one known `ERROR` with no `cause` is transient: Optimystic's "Committed read
384
+ * refused: storage is in a partially-committed state". An apply makes no committed reads (Quereus refuses
385
+ * them while a schema migrates), so it cannot reach this test. If a transient fault is ever seen typed as a
386
+ * refusal, have Optimystic give it a fault code or a `cause` rather than matching its message here.
387
+ */
388
+ function isSchemaRefusal(err: unknown): err is QuereusError {
389
+ let at = err;
390
+ do {
391
+ if (!(at instanceof QuereusError) || !SCHEMA_REFUSAL_CODES.has(at.code)) {
392
+ return false;
393
+ }
394
+ at = at.cause;
395
+ } while (at !== undefined);
396
+ return true;
397
+ }