@serfab/cadre-core 1.22.0 → 1.23.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.
@@ -2,7 +2,7 @@ import debug from 'debug';
2
2
  import type { Libp2p, PrivateKey } from '@libp2p/interface';
3
3
  import type { ICohortReachability } from '@optimystic/db-core';
4
4
  import { createLibp2pNode, type IRawStorage } from '@optimystic/db-p2p';
5
- import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
5
+ import { wrapStorageWithCache, disposeStorageCache, checkAppSchema, appSchemaRefusalOf } from '@serfab/quereus-plugin-sereus';
6
6
  import { StrandDatabase, type StrandDatabaseOffline } from './strand-database.js';
7
7
  import type { StrandCommitDurability, StrandCommitHeld } from './strand-commit-durability.js';
8
8
  import type { StrandOfflineConfig, StrandOfflineListeners, StrandOfflineMode } from './strand-offline.js';
@@ -80,6 +80,17 @@ type StrandDatabaseBuild = 'built' | 'awaiting-seed' | 'released';
80
80
 
81
81
  const timing = debug('sereus:cadre:timing');
82
82
 
83
+ /**
84
+ * An sApp claim of a storage replica ({@link StrandInstanceManager.attachSApp}) that the retained
85
+ * launch config carries and that has not been applied to the strand yet.
86
+ */
87
+ interface UnappliedAttach {
88
+ /** The claiming sApp's config, as the retained launch config holds it. */
89
+ sAppConfig: SAppConfig;
90
+ /** The instance's latency hint before the claim, for a fallback to the replica to put back. */
91
+ latencyHint: LatencyHint;
92
+ }
93
+
83
94
  /** One caller blocked in {@link StrandInstanceManager.whenWritable}. */
84
95
  interface WritableWaiter {
85
96
  resolve: () => void;
@@ -638,6 +649,14 @@ export class StrandInstanceManager {
638
649
  * {@link releaseRuntime}, so a stop or a quiesce cancels it.
639
650
  */
640
651
  private unreachableJoinRetries: Map<string, unknown> = new Map();
652
+ /**
653
+ * Per strand id, the sApp claim ({@link attachSApp}) whose schema the retained launch config
654
+ * carries but no apply has landed yet: the claim found no live database, or its live apply failed
655
+ * for a reason that may pass. Lets a build that refuses that schema fall back to the replica
656
+ * ({@link revertRefusedAttach}). Deleted when a database applies the schema, by that fallback,
657
+ * and when {@link stopStrand} begins.
658
+ */
659
+ private unappliedAttaches: Map<string, UnappliedAttach> = new Map();
641
660
  /**
642
661
  * The offline mode set per strand id ({@link setOfflineMode}); a strand absent here runs in its
643
662
  * launch's `initialMode`. Never cleared: the mode belongs to the strand, not to one database, so
@@ -1288,6 +1307,7 @@ export class StrandInstanceManager {
1288
1307
  await strandDb.close();
1289
1308
  return 'released';
1290
1309
  }
1310
+ this.forgetAppliedAttach(strandId, config.sAppConfig, strandDb);
1291
1311
 
1292
1312
  // The first-sync write gate. A founder just wrote the Header in its bootstrap; any
1293
1313
  // other machine may commit only once it holds the Header — which it can only have
@@ -1461,7 +1481,8 @@ export class StrandInstanceManager {
1461
1481
  * runtime still attached. Skipped when the strand was stopped or released since — a quiesce
1462
1482
  * releases it and the resume after rebuilds the whole runtime — or already has a database.
1463
1483
  * A failure other than an unanswered seed releases the runtime and marks the strand
1464
- * `'error'`, as a failed resume does.
1484
+ * `'error'`, as a failed resume does, unless it is a refusal of a claim's schema the replica
1485
+ * can fall back from ({@link buildJoinDatabaseOrReplica}).
1465
1486
  */
1466
1487
  private async retryUnreachableJoin(instance: StrandInstance): Promise<void> {
1467
1488
  const strandId = instance.strandId;
@@ -1476,7 +1497,7 @@ export class StrandInstanceManager {
1476
1497
  try {
1477
1498
  // Tracked like any runtime build, so a wake, a quiesce or an sApp attach waits for it
1478
1499
  // rather than acting on a database that is still initializing.
1479
- build = await this.trackRuntimeBuild(strandId, this.buildStrandDatabase(instance, config, node));
1500
+ build = await this.trackRuntimeBuild(strandId, this.buildJoinDatabaseOrReplica(instance, config, node));
1480
1501
  } catch (error) {
1481
1502
  if (!this.isCurrentRuntime(instance, node)) {
1482
1503
  log('Strand %s: a database retry failed after its runtime was released: %o', strandId, error);
@@ -1495,6 +1516,39 @@ export class StrandInstanceManager {
1495
1516
  }
1496
1517
  }
1497
1518
 
1519
+ /**
1520
+ * A deferred join's database phase ({@link buildStrandDatabase}), run once more as the replica
1521
+ * when it fails on the schema of a claim that has not applied yet ({@link revertRefusedAttach}).
1522
+ * The failed attempt's database is closed first: a failure leaves it registered with its gate.
1523
+ * `'released'` when a stop began while it closed.
1524
+ */
1525
+ private async buildJoinDatabaseOrReplica(
1526
+ instance: StrandInstance,
1527
+ config: StartStrandConfig,
1528
+ node: Libp2pNodeWithRepo
1529
+ ): Promise<StrandDatabaseBuild> {
1530
+ try {
1531
+ return await this.buildStrandDatabase(instance, config, node);
1532
+ } catch (error) {
1533
+ const replicaConfig = this.isCurrentRuntime(instance, node)
1534
+ ? this.revertRefusedAttach(instance, config.sAppConfig, error)
1535
+ : undefined;
1536
+ if (!replicaConfig) {
1537
+ throw error;
1538
+ }
1539
+ const failedAttempt = this.firstSyncGates.get(instance.strandId);
1540
+ if (failedAttempt) {
1541
+ await this.discardDatabaseAttempt(instance.strandId, failedAttempt);
1542
+ }
1543
+ if (!this.isCurrentRuntime(instance, node) || instance.status === 'stopping') {
1544
+ // A stop that began while the failed attempt closed found no gate to release, so a
1545
+ // database built now would outlive the stop, open and unreleased.
1546
+ return 'released';
1547
+ }
1548
+ return await this.buildStrandDatabase(instance, replicaConfig, node);
1549
+ }
1550
+ }
1551
+
1498
1552
  /** Whether `instance` is still tracked, with `node` still its runtime's libp2p node. */
1499
1553
  private isCurrentRuntime(instance: StrandInstance, node: Libp2p): boolean {
1500
1554
  return !this.stopping && this.instances.get(instance.strandId) === instance && instance.libp2pNode === node;
@@ -2048,7 +2102,7 @@ export class StrandInstanceManager {
2048
2102
 
2049
2103
  instance.status = 'starting';
2050
2104
  try {
2051
- await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, resumeConfig));
2105
+ await this.trackRuntimeBuild(strandId, this.buildRuntimeOrReplica(instance, resumeConfig));
2052
2106
  timing('[resumeStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
2053
2107
  log('Strand %s resumed successfully', strandId);
2054
2108
  return instance;
@@ -2060,6 +2114,66 @@ export class StrandInstanceManager {
2060
2114
  }
2061
2115
  }
2062
2116
 
2117
+ /**
2118
+ * {@link buildStrandRuntime}, run once more as the replica when it fails on the schema of a
2119
+ * claim that has not applied yet ({@link revertRefusedAttach}). Safe to run twice: a failed
2120
+ * build releases both handles before it rejects.
2121
+ */
2122
+ private async buildRuntimeOrReplica(instance: StrandInstance, config: StartStrandConfig): Promise<void> {
2123
+ try {
2124
+ await this.buildStrandRuntime(instance, config);
2125
+ } catch (error) {
2126
+ const replicaConfig = this.revertRefusedAttach(instance, config.sAppConfig, error);
2127
+ if (!replicaConfig) {
2128
+ throw error;
2129
+ }
2130
+ await this.buildStrandRuntime(instance, replicaConfig);
2131
+ }
2132
+ }
2133
+
2134
+ /**
2135
+ * Undo a claim of a storage replica ({@link attachSApp}) after an apply of its schema was refused
2136
+ * (`AppSchemaRefusedError`): the retained launch config drops the sApp, so later rebuilds run the
2137
+ * replica, and the instance gets back the replica's unset `sAppInfo` and its latency hint. Only
2138
+ * when `error` is such a refusal, `refused` is the claim the strand has not applied yet, and the
2139
+ * retained config still carries it, so a config rewritten since is left alone.
2140
+ *
2141
+ * @returns the replica's launch config, or `undefined` when nothing was undone.
2142
+ */
2143
+ private revertRefusedAttach(
2144
+ instance: StrandInstance,
2145
+ refused: SAppConfig | undefined,
2146
+ error: unknown
2147
+ ): StartStrandConfig | undefined {
2148
+ const strandId = instance.strandId;
2149
+ const unapplied = this.unappliedAttaches.get(strandId);
2150
+ const config = this.launchConfigs.get(strandId);
2151
+ const refusal = appSchemaRefusalOf(error);
2152
+ if (!refusal || !unapplied || !config || this.stopping || this.instances.get(strandId) !== instance
2153
+ || refused !== unapplied.sAppConfig || config.sAppConfig !== refused) {
2154
+ return undefined;
2155
+ }
2156
+ this.unappliedAttaches.delete(strandId);
2157
+ const { sAppConfig: _refused, ...replicaConfig } = config;
2158
+ this.launchConfigs.set(strandId, replicaConfig);
2159
+ instance.sAppInfo = undefined;
2160
+ instance.latencyHint = unapplied.latencyHint;
2161
+ log('Strand %s: the schema of sApp %s, which claimed this storage replica, was refused here; ' +
2162
+ 'the strand runs as a replica again: %s', strandId, refused.id, refusal.message);
2163
+ return replicaConfig;
2164
+ }
2165
+
2166
+ /**
2167
+ * Forget the unapplied claim of `strandId` once `database`, given the claim's sApp config as
2168
+ * `applied`, has applied its schema. An apply still deferred keeps it, since its retry can still be
2169
+ * refused by the strand's rows.
2170
+ */
2171
+ private forgetAppliedAttach(strandId: string, applied: SAppConfig | undefined, database: StrandDatabase): void {
2172
+ if (applied && this.unappliedAttaches.get(strandId)?.sAppConfig === applied && database.appSchemaState() === 'applied') {
2173
+ this.unappliedAttaches.delete(strandId);
2174
+ }
2175
+ }
2176
+
2063
2177
  /**
2064
2178
  * Honor a founder request against an ALREADY-TRACKED strand — the seam that
2065
2179
  * closes the "whoever launches first decides whether the bootstrap runs" gap:
@@ -2132,19 +2246,24 @@ export class StrandInstanceManager {
2132
2246
  *
2133
2247
  * A runtime build in flight (the replica's launch, or a hibernation wake) is waited out
2134
2248
  * first, so the attach acts on the database that build produced. Then, in order: the
2135
- * schema signature is checked before anything changes; the retained launch config takes
2136
- * the sApp, so every later rebuild applies it through `composeStrand`; the live database —
2137
- * published, or still held by the first-sync gate — gets the schema; and only then does
2138
- * the instance record `sAppInfo` and the sApp's latency hint. An instance with no live
2139
- * database gets the config alone: a quiesced one applies the schema at its next resume, a
2140
- * launch waiting for a seed peer at its next database retry.
2249
+ * schema signature, and the refusals the schema's text alone decides (`checkAppSchema`: a
2250
+ * `seed` item, an item the parser skipped, a syntax error), are checked before anything
2251
+ * changes; the retained launch config takes the sApp, so every later rebuild applies it
2252
+ * through `composeStrand`; the live database — published, or still held by the first-sync
2253
+ * gate — gets the schema; and only then does the instance record `sAppInfo` and the sApp's
2254
+ * latency hint. An instance with no live database gets the config alone: a quiesced one
2255
+ * applies the schema at its next resume, a launch waiting for a seed peer at its next
2256
+ * database retry, and that build falls back to the replica if the strand's tables and rows
2257
+ * refuse the schema ({@link revertRefusedAttach}).
2141
2258
  *
2142
2259
  * @returns `'already-attached'` when the instance already runs an sApp — a DIFFERENT one
2143
2260
  * is logged and left as it is, as a second claim of a claimed strand always has been —
2144
2261
  * else `'attached'`.
2145
2262
  * @throws when the strand is not tracked (a caller bug, or a launch that failed while
2146
- * this waited on it); when the schema signature is refused, having changed nothing; and
2147
- * whatever the live apply throws (e.g. a quiesce closed the database mid-apply) — the
2263
+ * this waited on it); when the schema signature or the schema's text is refused, having
2264
+ * changed nothing; `AppSchemaRefusedError` when the live apply refuses the schema against
2265
+ * the replica's tables and rows, having put the retained config back to the replica's; and
2266
+ * whatever else the live apply throws (e.g. a quiesce closed the database mid-apply) — the
2148
2267
  * retained config then still carries the sApp and `sAppInfo` stays unset, so the next
2149
2268
  * claim retries the apply.
2150
2269
  *
@@ -2159,26 +2278,34 @@ export class StrandInstanceManager {
2159
2278
  options: { requireSignedSchemas?: boolean } = {}
2160
2279
  ): Promise<'attached' | 'already-attached'> {
2161
2280
  await this.settleRuntimeBuilds(strandId);
2162
- const instance = this.instances.get(strandId);
2163
- const config = this.launchConfigs.get(strandId);
2164
- if (!instance || !config) {
2165
- throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
2166
- }
2167
- if (instance.sAppInfo) {
2168
- if (instance.sAppInfo.id !== sAppConfig.id) {
2169
- log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored',
2170
- strandId, instance.sAppInfo.id, sAppConfig.id);
2171
- }
2281
+ if (this.claimTarget(strandId, sAppConfig) === 'already-attached') {
2172
2282
  return 'already-attached';
2173
2283
  }
2174
2284
  const sAppInfo = verifiedSAppInfo(strandId, sAppConfig, options.requireSignedSchemas);
2285
+ await checkAppSchema(sAppConfig.schema);
2286
+ // The check yielded, so a wake or another claim may have started meanwhile: wait out its build
2287
+ // and read the instance and config again, or the config written below would drop what a
2288
+ // resume just retained (its fresh `bootstrapNodes`).
2289
+ await this.settleRuntimeBuilds(strandId);
2290
+ const target = this.claimTarget(strandId, sAppConfig);
2291
+ if (target === 'already-attached') {
2292
+ return target;
2293
+ }
2294
+ const { instance, config } = target;
2175
2295
  // A fresh object rather than mutating in place: startStrand retains the CALLER'S
2176
2296
  // config object, which is not ours to rewrite.
2177
2297
  this.launchConfigs.set(strandId, { ...config, sAppConfig });
2298
+ this.unappliedAttaches.set(strandId, { sAppConfig, latencyHint: instance.latencyHint });
2178
2299
  const database = instance.database ?? this.firstSyncGates.get(strandId)?.database;
2179
2300
  if (database) {
2180
- await database.attachAppSchema(sAppConfig);
2301
+ await this.applyClaimedSchema(instance, database, sAppConfig);
2181
2302
  } else {
2303
+ // NOTE: accepted gap — this claim resolves `'attached'` before any apply, so the app learns of
2304
+ // a refusal by the strand's rows only from the log and from `sAppInfo` going back to unset when
2305
+ // the build falls back to the replica; `CadreNode.sAppConfigs` keeps the claim, so a restart's
2306
+ // launch with it is refused and suppressed (`suppressIfAppSchemaRefused`). Failing the claim
2307
+ // instead would mean waking a quiesced replica to apply now, and would still not cover a
2308
+ // launch waiting for a seed peer.
2182
2309
  log('attachSApp: strand %s has no live database — its next build applies the sApp schema', strandId);
2183
2310
  }
2184
2311
  instance.sAppInfo = sAppInfo;
@@ -2192,6 +2319,48 @@ export class StrandInstanceManager {
2192
2319
  return 'attached';
2193
2320
  }
2194
2321
 
2322
+ /**
2323
+ * The tracked instance and retained config an {@link attachSApp} claim acts on, or
2324
+ * `'already-attached'` when the instance already runs an sApp (a claim for a different one is
2325
+ * logged and ignored).
2326
+ *
2327
+ * @throws when the strand is not tracked.
2328
+ */
2329
+ private claimTarget(
2330
+ strandId: string,
2331
+ sAppConfig: SAppConfig
2332
+ ): { instance: StrandInstance; config: StartStrandConfig } | 'already-attached' {
2333
+ const instance = this.instances.get(strandId);
2334
+ const config = this.launchConfigs.get(strandId);
2335
+ if (!instance || !config) {
2336
+ throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
2337
+ }
2338
+ if (!instance.sAppInfo) {
2339
+ return { instance, config };
2340
+ }
2341
+ if (instance.sAppInfo.id !== sAppConfig.id) {
2342
+ log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored',
2343
+ strandId, instance.sAppInfo.id, sAppConfig.id);
2344
+ }
2345
+ return 'already-attached';
2346
+ }
2347
+
2348
+ /**
2349
+ * Apply a claim's schema to the replica's live database. A refusal by the replica's tables and
2350
+ * rows puts the retained config back to the replica's ({@link revertRefusedAttach}): the replica
2351
+ * holds no `App` schema, so the refused apply left nothing to drop. Any other failure leaves the
2352
+ * claim retained and unapplied, for the next claim or build to retry.
2353
+ */
2354
+ private async applyClaimedSchema(instance: StrandInstance, database: StrandDatabase, sAppConfig: SAppConfig): Promise<void> {
2355
+ try {
2356
+ await database.attachAppSchema(sAppConfig);
2357
+ } catch (error) {
2358
+ this.revertRefusedAttach(instance, sAppConfig, error);
2359
+ throw error;
2360
+ }
2361
+ this.forgetAppliedAttach(instance.strandId, sAppConfig, database);
2362
+ }
2363
+
2195
2364
  /**
2196
2365
  * Whether `strandId` is launched but still waiting for its first sync — a joiner whose
2197
2366
  * runtime is up while its database is withheld (status `'syncing'`, or `'idle'` after
@@ -2466,6 +2635,8 @@ export class StrandInstanceManager {
2466
2635
 
2467
2636
  log('Stopping strand instance: %s', strandId);
2468
2637
  instance.status = 'stopping';
2638
+ // Before the release awaits, so a build failing meanwhile does not rebuild as the replica.
2639
+ this.unappliedAttaches.delete(strandId);
2469
2640
  this.rejectWritableWaiters(strandId, 'was stopped');
2470
2641
 
2471
2642
  try {
package/src/types.ts CHANGED
@@ -2328,11 +2328,20 @@ export interface PendingPartyKeyRotation {
2328
2328
  superseded: string[];
2329
2329
  /**
2330
2330
  * Who can move the replacement forward from here, judged from this machine's view of the strand.
2331
- * - `another-party`: the strand runs here, the party holds no manager seat and `publicKey` is not a member, so another party's manager has to admit it: a fresh invitation to the strand redeemed on an owner device of this party, or the key admitted by hand.
2331
+ * - `another-party`: the strand runs here, the party holds no manager seat and `publicKey` is not a member, so another party's manager has to admit it: a fresh invitation to the strand redeemed on an owner device of this party the new key is sealed to (`sealedTo`), or the key admitted by hand.
2332
2332
  * - `sealed`: the strand has no managers at all and `publicKey` is not a member; nobody can admit it, and the removed machine stays a member until the strand is re-formed.
2333
- * - `owner-machine`: an owner device of this party that runs the strand finishes it (the strand does not run here, the party holds a manager seat, or `publicKey` is already a member), which this machine may or may not be. Also the answer when a read here fails.
2333
+ * - `owner-machine`: an owner device of this party the new key is sealed to (`sealedTo`) that runs the strand finishes it (the strand does not run here, the party holds a manager seat, or `publicKey` is already a member), which this machine may or may not be. Also the answer when a read here fails.
2334
2334
  */
2335
2335
  waitingOn: 'another-party' | 'sealed' | 'owner-machine';
2336
+ /**
2337
+ * The machines of this cadre the new key is sealed to: control peer ids, each a live machine
2338
+ * (`listMachines`) or this node, in no particular order. Only these can redeem the host's
2339
+ * invitation under the new key or finish the replacement, and only those of them that hold an
2340
+ * owner key. A machine admitted after the removal is never one. Empty when every machine it
2341
+ * was sealed to has left the cadre, or the row's envelope does not decode; removing a machine
2342
+ * then writes a replacement sealed to the machines present.
2343
+ */
2344
+ sealedTo: string[];
2336
2345
  }
2337
2346
 
2338
2347
  /** Why `CadreNode.removeOwner` refuses by name (`OwnerKeyRemovalRefusedError.code`). */