@serfab/cadre-core 0.12.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -8
- package/dist/bootstrap-peer-store-file.js +2 -2
- package/dist/bootstrap-peer-store.d.ts +32 -12
- package/dist/bootstrap-peer-store.js +41 -15
- package/dist/bootstrap-peer-store.js.map +1 -1
- package/dist/cadre-node.d.ts +883 -102
- package/dist/cadre-node.js +1800 -209
- package/dist/cadre-node.js.map +1 -1
- package/dist/control-authorization.d.ts +2 -2
- package/dist/control-authorization.js +1 -0
- package/dist/control-authorization.js.map +1 -1
- package/dist/control-cohort.d.ts +13 -26
- package/dist/control-cohort.js +0 -26
- package/dist/control-cohort.js.map +1 -1
- package/dist/control-database.d.ts +318 -44
- package/dist/control-database.js +516 -74
- package/dist/control-database.js.map +1 -1
- package/dist/control-read-retry.d.ts +40 -11
- package/dist/control-read-retry.js +48 -15
- package/dist/control-read-retry.js.map +1 -1
- package/dist/control-retry.d.ts +58 -3
- package/dist/control-retry.js +58 -3
- package/dist/control-retry.js.map +1 -1
- package/dist/control-schema.d.ts +1 -1
- package/dist/control-schema.js +133 -21
- package/dist/control-schema.js.map +1 -1
- package/dist/control-write-retry.d.ts +80 -11
- package/dist/control-write-retry.js +168 -29
- package/dist/control-write-retry.js.map +1 -1
- package/dist/enrolled-machine-store-file.d.ts +13 -0
- package/dist/enrolled-machine-store-file.js +41 -0
- package/dist/enrolled-machine-store-file.js.map +1 -0
- package/dist/enrolled-machine-store.d.ts +81 -0
- package/dist/enrolled-machine-store.js +225 -0
- package/dist/enrolled-machine-store.js.map +1 -0
- package/dist/file-durable-slot.js +5 -3
- package/dist/file-durable-slot.js.map +1 -1
- package/dist/index.d.ts +17 -8
- package/dist/index.js +54 -9
- package/dist/index.js.map +1 -1
- package/dist/membership-connection-gater.d.ts +15 -1
- package/dist/membership-connection-gater.js +9 -3
- package/dist/membership-connection-gater.js.map +1 -1
- package/dist/node-local-snapshot.d.ts +21 -7
- package/dist/node-local-snapshot.js +30 -9
- package/dist/node-local-snapshot.js.map +1 -1
- package/dist/peer-dial.d.ts +143 -0
- package/dist/peer-dial.js +176 -0
- package/dist/peer-dial.js.map +1 -0
- package/dist/{strand-backfill.d.ts → peer-join-backfill.d.ts} +49 -20
- package/dist/{strand-backfill.js → peer-join-backfill.js} +133 -52
- package/dist/peer-join-backfill.js.map +1 -0
- package/dist/relay-addrs.d.ts +160 -49
- package/dist/relay-addrs.js +287 -60
- package/dist/relay-addrs.js.map +1 -1
- package/dist/relay-reservation.d.ts +71 -3
- package/dist/relay-reservation.js +116 -8
- package/dist/relay-reservation.js.map +1 -1
- package/dist/seed-bootstrap.d.ts +30 -1
- package/dist/seed-bootstrap.js +62 -17
- package/dist/seed-bootstrap.js.map +1 -1
- package/dist/storage-scope.d.ts +62 -0
- package/dist/storage-scope.js +75 -0
- package/dist/storage-scope.js.map +1 -0
- package/dist/strand-database.d.ts +41 -11
- package/dist/strand-database.js +48 -18
- package/dist/strand-database.js.map +1 -1
- package/dist/strand-first-sync-gate.d.ts +152 -0
- package/dist/strand-first-sync-gate.js +208 -0
- package/dist/strand-first-sync-gate.js.map +1 -0
- package/dist/strand-formation-manager.d.ts +99 -5
- package/dist/strand-formation-manager.js +119 -8
- package/dist/strand-formation-manager.js.map +1 -1
- package/dist/strand-formation-protocol.d.ts +97 -3
- package/dist/strand-formation-protocol.js +108 -2
- package/dist/strand-formation-protocol.js.map +1 -1
- package/dist/strand-instance-manager.d.ts +389 -19
- package/dist/strand-instance-manager.js +678 -65
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-member-key.d.ts +20 -12
- package/dist/strand-member-key.js +20 -12
- package/dist/strand-member-key.js.map +1 -1
- package/dist/strand-member-registry.js +3 -0
- package/dist/strand-member-registry.js.map +1 -1
- package/dist/strand-membership-reconciler.d.ts +361 -0
- package/dist/strand-membership-reconciler.js +548 -0
- package/dist/strand-membership-reconciler.js.map +1 -0
- package/dist/strand-membership-writer.d.ts +143 -11
- package/dist/strand-membership-writer.js +419 -135
- package/dist/strand-membership-writer.js.map +1 -1
- package/dist/strand-network-config.d.ts +116 -0
- package/dist/strand-network-config.js +192 -0
- package/dist/strand-network-config.js.map +1 -0
- package/dist/strand-revocation-enforcer.d.ts +392 -0
- package/dist/strand-revocation-enforcer.js +533 -0
- package/dist/strand-revocation-enforcer.js.map +1 -0
- package/dist/strand-solicitation.d.ts +17 -1
- package/dist/strand-solicitation.js +13 -2
- package/dist/strand-solicitation.js.map +1 -1
- package/dist/strand-wake-protocol.d.ts +11 -7
- package/dist/strand-wake-protocol.js +20 -52
- package/dist/strand-wake-protocol.js.map +1 -1
- package/dist/strand-watcher.js +12 -1
- package/dist/strand-watcher.js.map +1 -1
- package/dist/timed-step.d.ts +12 -0
- package/dist/timed-step.js +28 -0
- package/dist/timed-step.js.map +1 -0
- package/dist/timeout-scheduler.d.ts +19 -0
- package/dist/timeout-scheduler.js +22 -0
- package/dist/timeout-scheduler.js.map +1 -0
- package/dist/types.d.ts +472 -46
- package/dist/types.js +7 -1
- package/dist/types.js.map +1 -1
- package/package.json +16 -8
- package/src/bootstrap-peer-store-file.ts +2 -2
- package/src/bootstrap-peer-store.ts +69 -27
- package/src/cadre-node.ts +1926 -228
- package/src/control-authorization.ts +2 -1
- package/src/control-cohort.ts +122 -130
- package/src/control-database.ts +586 -74
- package/src/control-read-retry.ts +202 -167
- package/src/control-retry.ts +297 -190
- package/src/control-schema.ts +133 -21
- package/src/control-write-retry.ts +525 -383
- package/src/enrolled-machine-store-file.ts +43 -0
- package/src/enrolled-machine-store.ts +280 -0
- package/src/file-durable-slot.ts +5 -3
- package/src/index.ts +134 -15
- package/src/membership-connection-gater.ts +9 -3
- package/src/node-local-snapshot.ts +38 -9
- package/src/peer-addr-book.ts +251 -250
- package/src/peer-dial.ts +215 -0
- package/src/{strand-backfill.ts → peer-join-backfill.ts} +478 -389
- package/src/relay-addrs.ts +458 -218
- package/src/relay-reservation.ts +951 -828
- package/src/seed-bootstrap.ts +76 -18
- package/src/storage-scope.ts +78 -0
- package/src/strand-database.ts +61 -21
- package/src/strand-first-sync-gate.ts +258 -0
- package/src/strand-formation-manager.ts +162 -8
- package/src/strand-formation-protocol.ts +850 -692
- package/src/strand-instance-manager.ts +877 -74
- package/src/strand-member-key.ts +20 -12
- package/src/strand-member-registry.ts +3 -0
- package/src/strand-membership-reconciler.ts +680 -0
- package/src/strand-membership-writer.ts +550 -190
- package/src/strand-network-config.ts +250 -0
- package/src/strand-revocation-enforcer.ts +653 -0
- package/src/strand-solicitation.ts +499 -471
- package/src/strand-wake-protocol.ts +21 -66
- package/src/strand-watcher.ts +325 -314
- package/src/timed-step.ts +28 -0
- package/src/timeout-scheduler.ts +28 -0
- package/src/types.ts +487 -52
- package/dist/strand-backfill.js.map +0 -1
package/dist/control-database.js
CHANGED
|
@@ -9,7 +9,8 @@ import { canonicalDatetime } from './canonical-datetime.js';
|
|
|
9
9
|
import { controlAuthorizationFields, CONTROL_TABLES } from './control-authorization.js';
|
|
10
10
|
import { requireEd25519PublicKeyB64 } from './ed25519-key.js';
|
|
11
11
|
import { retryControlWrite, SCHEMA_INIT_RETRY_POLICY } from './control-write-retry.js';
|
|
12
|
-
import { retryControlRead } from './control-read-retry.js';
|
|
12
|
+
import { isCohortUnreachableRead, retryControlRead } from './control-read-retry.js';
|
|
13
|
+
import { chainMessages } from './control-retry.js';
|
|
13
14
|
const log = debug('sereus:cadre:control-db');
|
|
14
15
|
const timing = debug('sereus:cadre:timing');
|
|
15
16
|
/**
|
|
@@ -208,16 +209,71 @@ const GUARDED_KEY_COLUMN = {
|
|
|
208
209
|
CadrePeer: 'PeerId',
|
|
209
210
|
ValidationKey: 'Key',
|
|
210
211
|
Strand: 'Id',
|
|
212
|
+
StrandPartyKey: 'Id',
|
|
211
213
|
DeviceToken: 'PeerId',
|
|
212
214
|
};
|
|
215
|
+
/**
|
|
216
|
+
* The rejection a second insert of an already-seated strand id produces, as the optimystic
|
|
217
|
+
* vtab words it (`uniqueConstraintMessage`, qualified by table name only — no schema
|
|
218
|
+
* prefix, matching `test/control-constraint-helpers.ts`'s `expectUniqueViolation`).
|
|
219
|
+
*
|
|
220
|
+
* `Strand.StampId` is unique too, but a fresh stamp is minted per insert attempt, so only
|
|
221
|
+
* the primary key can collide on a repeat publish. Matching the column explicitly keeps
|
|
222
|
+
* any OTHER uniqueness failure out of the idempotency branch.
|
|
223
|
+
*/
|
|
224
|
+
const STRAND_ID_CONFLICT = /UNIQUE constraint failed: Strand\.Id\b/i;
|
|
225
|
+
/**
|
|
226
|
+
* Did this write fail because the strand id is already seated?
|
|
227
|
+
*
|
|
228
|
+
* {@link CadreNode.publishStrand} uses this to tell "my own earlier publish already
|
|
229
|
+
* landed" (re-read, and no-op when the row matches) apart from every other rejection —
|
|
230
|
+
* an unauthorized signer, a retired stamp — which must keep surfacing.
|
|
231
|
+
*
|
|
232
|
+
* Matched by TEXT, not by type: the typed engine error does not survive the trip out of
|
|
233
|
+
* optimystic (same constraint the retry classifiers in `control-write-retry.ts` document).
|
|
234
|
+
* Fails CLOSED — a rewording upstream turns the idempotent branch back into the raw
|
|
235
|
+
* uniqueness error the caller saw before, never into a silent overwrite. The
|
|
236
|
+
* `publish-strand.spec.ts` repeat-publish cases assert against the live engine error, so a
|
|
237
|
+
* reword reddens there.
|
|
238
|
+
*/
|
|
239
|
+
export function isStrandIdConflict(error) {
|
|
240
|
+
return errorChainMatches(error, STRAND_ID_CONFLICT);
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* The one `CadreControl.Revocation` row that retires nothing, filed once by an owner
|
|
244
|
+
* ({@link ControlDatabase.openRevocationLedger}) so the table is never a never-written
|
|
245
|
+
* block. The schema's table comment says why that matters and why the row can never read
|
|
246
|
+
* as a retirement; `RowIsGone` pins this exact triple.
|
|
247
|
+
*/
|
|
248
|
+
export const REVOCATION_LEDGER_MARKER = {
|
|
249
|
+
tableName: 'Revocation',
|
|
250
|
+
rowKey: 'ledger',
|
|
251
|
+
stampId: 'opened',
|
|
252
|
+
};
|
|
253
|
+
/**
|
|
254
|
+
* The rejection a second insert of the ledger marker produces: the optimystic vtab's
|
|
255
|
+
* primary-key wording (see {@link STRAND_ID_CONFLICT}), naming both columns of
|
|
256
|
+
* `Revocation`'s composite key. Applied only to the marker's own insert, whose key
|
|
257
|
+
* ('Revocation', 'opened') no row but the marker can hold (`RowIsGone`), and `Revocation`
|
|
258
|
+
* has no other unique constraint.
|
|
259
|
+
*/
|
|
260
|
+
const REVOCATION_LEDGER_CONFLICT = /UNIQUE constraint failed: Revocation\.TableName, Revocation\.StampId\b/i;
|
|
261
|
+
/** Did the ledger marker's insert fail because the marker is already filed? Text-matched, failing closed, like {@link isStrandIdConflict}. */
|
|
262
|
+
function isRevocationLedgerConflict(error) {
|
|
263
|
+
return errorChainMatches(error, REVOCATION_LEDGER_CONFLICT);
|
|
264
|
+
}
|
|
265
|
+
/** Whether any message in `error`'s cause chain matches `pattern`; false for a non-`Error`. */
|
|
266
|
+
function errorChainMatches(error, pattern) {
|
|
267
|
+
return error instanceof Error && chainMessages(error).some(message => pattern.test(message));
|
|
268
|
+
}
|
|
213
269
|
/**
|
|
214
270
|
* Guarded tables a node may reap locally once their tombstone has committed — the
|
|
215
271
|
* tables whose `AuthorizedDelete` carries the REAP branch (see the constraint comment on
|
|
216
|
-
* `CadrePeer.AuthorizedDelete` in the schema). `Strand`
|
|
217
|
-
*
|
|
218
|
-
* nowhere else (tickets/backlog/debt-strand-tombstone-reap.md owns any
|
|
219
|
-
* `OwnerKey` has no production removal path and `MinOneOwner` makes an
|
|
220
|
-
* owner-key reap a party-bricking hazard.
|
|
272
|
+
* `CadrePeer.AuthorizedDelete` in the schema). `Strand` and `StrandPartyKey` are
|
|
273
|
+
* deliberately absent: their rows carry `MemberPrivateKey` / `PrivateKey` — party
|
|
274
|
+
* secrets stored nowhere else (tickets/backlog/debt-strand-tombstone-reap.md owns any
|
|
275
|
+
* future change). `OwnerKey` has no production removal path and `MinOneOwner` makes an
|
|
276
|
+
* automated owner-key reap a party-bricking hazard.
|
|
221
277
|
*/
|
|
222
278
|
export const REAPABLE_TABLES = ['CadrePeer', 'DeviceToken', 'ValidationKey'];
|
|
223
279
|
/**
|
|
@@ -240,8 +296,16 @@ export class ControlDatabase {
|
|
|
240
296
|
this.initialized = false;
|
|
241
297
|
this.membershipListener = null;
|
|
242
298
|
this.guardedDeleteListener = null;
|
|
299
|
+
this.controlWriteAbandonedListener = null;
|
|
243
300
|
/** Tail of the local-write chain — see {@link withWriteLock}. */
|
|
244
301
|
this.writeQueue = Promise.resolve();
|
|
302
|
+
/**
|
|
303
|
+
* Locked write bodies currently running (see {@link runWriteBody}); what
|
|
304
|
+
* {@link readRowsOnce} consults to route an unlocked read around a write that has
|
|
305
|
+
* started but not yet opened its transaction. At most 1 while every writer takes the
|
|
306
|
+
* lock — a count rather than a flag so it stays truthful if that ever stops holding.
|
|
307
|
+
*/
|
|
308
|
+
this.runningWriteBodies = 0;
|
|
245
309
|
/**
|
|
246
310
|
* Pacing seams for {@link lockedWithRetry}. Production leaves this empty (real backoff,
|
|
247
311
|
* real clock); specs inject a recorded `sleep` / fake `now` so no test waits out a real
|
|
@@ -324,8 +388,8 @@ export class ControlDatabase {
|
|
|
324
388
|
// NOTE: this is where a slow launch is felt. Duration is (raw-storage operations
|
|
325
389
|
// issued) × per-operation storage latency: ~1ms/op on an idle machine, but
|
|
326
390
|
// 50-90ms/op on a loaded disk or a phone's flash under launch contention. A cold
|
|
327
|
-
// start now reaches the backend
|
|
328
|
-
// — dominated by its
|
|
391
|
+
// start now reaches the backend 45 times (9 tables + 1 index, 20 distinct blocks
|
|
392
|
+
// — dominated by its genuine writes), a warm restart 13, because cadre-core
|
|
329
393
|
// wraps every embedder storage in `@optimystic/db-p2p`'s write-through cache
|
|
330
394
|
// (@serfab/quereus-plugin-sereus's cached-storage.ts). Uncached the same start issued ~2000 operations — the
|
|
331
395
|
// upstream re-read amplification measured in
|
|
@@ -438,11 +502,33 @@ export class ControlDatabase {
|
|
|
438
502
|
* opted in, `control-write-degraded-cohort-member` could no longer observe a sibling
|
|
439
503
|
* publishing its own `CadrePeer` row and failed at suite setup on two runs out of two.
|
|
440
504
|
*
|
|
441
|
-
*
|
|
442
|
-
*
|
|
443
|
-
*
|
|
444
|
-
*
|
|
445
|
-
*
|
|
505
|
+
* "A write is in flight" is {@link writeInFlight}, and it needs TWO signals because a
|
|
506
|
+
* write is invisible to `getAutocommit()` for part of its life. `Database.exec` takes
|
|
507
|
+
* the exec mutex first; the implicit transaction — the moment `getAutocommit()` turns
|
|
508
|
+
* false — opens only after the write has acquired the mutex, planned the statement,
|
|
509
|
+
* and awaited `begin()` on every connection. While the write WAITS for the mutex (a
|
|
510
|
+
* serialized read holds it, say) it still reports autocommit, so a read routed on
|
|
511
|
+
* `getAutocommit()` alone queued behind the write and answered only after its whole
|
|
512
|
+
* commit — tens of seconds against a slow cohort member, which is what timed out the
|
|
513
|
+
* degraded-cohort scenario's `isMember` read (verified against the engine directly;
|
|
514
|
+
* `complete/control-read-queues-behind-a-write-waiting-for-the-database`). So an
|
|
515
|
+
* UNLOCKED read also takes the committed path while any locked write body is running
|
|
516
|
+
* ({@link runningWriteBodies}), which covers that queued window and everything else a
|
|
517
|
+
* body does before its transaction opens. A read issued INSIDE a locked body
|
|
518
|
+
* (`underWriteLock`) must not: that body is the one being counted, and its guard reads
|
|
519
|
+
* need the refreshing path — so it keeps the transaction-only test.
|
|
520
|
+
*
|
|
521
|
+
* Both signals are sampled synchronously just before `eval`, which claims its place
|
|
522
|
+
* on the mutex in that same tick, so the only race left is a body starting or ending
|
|
523
|
+
* in between: a body that starts after the sample queues its statements BEHIND this
|
|
524
|
+
* read, and one that ended before it has nothing left to queue behind.
|
|
525
|
+
*
|
|
526
|
+
* Residual gaps, both of which still queue a read behind a write:
|
|
527
|
+
* - an EXPLICIT transaction ({@link inTransaction}) disqualifies the committed path in
|
|
528
|
+
* Quereus itself, so a read overlapping such a body's `COMMIT` falls back to the
|
|
529
|
+
* serialized path and waits for it;
|
|
530
|
+
* - a writer that bypasses {@link withWriteLock} is not counted (in this repo only
|
|
531
|
+
* `reference-app-web`'s deliberately-rejected diagnostics insert does).
|
|
446
532
|
*
|
|
447
533
|
* What a committed read gives up is observing a write that has not finished
|
|
448
534
|
* committing, and that is safe for every caller here: an AWAITED write is committed by
|
|
@@ -450,15 +536,23 @@ export class ControlDatabase {
|
|
|
450
536
|
* open explicit transaction and stays serialized, so it still sees its own
|
|
451
537
|
* transaction's rows. A read after an UNAWAITED write on this database would be wrong
|
|
452
538
|
* — no such caller exists, and {@link withWriteLock} is what keeps it that way.
|
|
539
|
+
*
|
|
540
|
+
* NOTE: counting whole bodies widens the stale (non-refreshing) window from "a
|
|
541
|
+
* transaction is open" to "a locked body is running", which adds a body's pre-transaction
|
|
542
|
+
* work and its post-commit tail (a `CadrePeer` write's membership-listener read). The
|
|
543
|
+
* slow part of a write against a degraded cohort is its commit, already inside the old
|
|
544
|
+
* window, so the added time is short; if a poller for replicated rows ever starves
|
|
545
|
+
* behind back-to-back local writes, narrow the count to the span from a body's first
|
|
546
|
+
* statement to its transaction opening.
|
|
453
547
|
*/
|
|
454
|
-
async readRowsOnce(sql, params) {
|
|
548
|
+
async readRowsOnce(sql, params, underWriteLock) {
|
|
455
549
|
let iterator;
|
|
456
|
-
if (this.
|
|
457
|
-
|
|
550
|
+
if (this.writeInFlight(underWriteLock)) {
|
|
551
|
+
log('read-eval: a write is in flight (%s), asking for a committed read: %s', this.db.getAutocommit() ? 'locked body running, no transaction open yet' : 'transaction open', sql);
|
|
552
|
+
iterator = this.db.eval(sql, params, { readConcurrency: 'committed' });
|
|
458
553
|
}
|
|
459
554
|
else {
|
|
460
|
-
|
|
461
|
-
iterator = this.db.eval(sql, params, { readConcurrency: 'committed' });
|
|
555
|
+
iterator = this.db.eval(sql, params);
|
|
462
556
|
}
|
|
463
557
|
const rows = [];
|
|
464
558
|
for await (const row of iterator) {
|
|
@@ -466,6 +560,19 @@ export class ControlDatabase {
|
|
|
466
560
|
}
|
|
467
561
|
return rows;
|
|
468
562
|
}
|
|
563
|
+
/**
|
|
564
|
+
* Whether a control read should ask for a committed read — see {@link readRowsOnce}.
|
|
565
|
+
* `getAutocommit()` reports the whole `Database` (the property
|
|
566
|
+
* {@link assertCommitBoundary} leans on), so false means some writer's transaction is
|
|
567
|
+
* open. An unlocked read also counts a running locked body that has not opened its
|
|
568
|
+
* transaction yet; a read inside such a body does not, since it is that body.
|
|
569
|
+
*/
|
|
570
|
+
writeInFlight(underWriteLock) {
|
|
571
|
+
if (!this.db.getAutocommit()) {
|
|
572
|
+
return true;
|
|
573
|
+
}
|
|
574
|
+
return !underWriteLock && this.runningWriteBodies > 0;
|
|
575
|
+
}
|
|
469
576
|
/**
|
|
470
577
|
* {@link readRowsOnce} plus the bounded transient-failure retry
|
|
471
578
|
* ({@link retryControlRead}) — the funnel every UNLOCKED control read goes through, so a
|
|
@@ -481,8 +588,8 @@ export class ControlDatabase {
|
|
|
481
588
|
* primary-key lookup or a `count(1)`); nothing streams.
|
|
482
589
|
*
|
|
483
590
|
* Each ATTEMPT is a fresh {@link readRowsOnce} call, so the committed-read opt-in
|
|
484
|
-
* (
|
|
485
|
-
* and change the right answer.
|
|
591
|
+
* ({@link writeInFlight}) is re-evaluated per attempt — a write can finish between
|
|
592
|
+
* attempts and change the right answer.
|
|
486
593
|
*
|
|
487
594
|
* The retry's budget ({@link CONTROL_READ_RETRY_BUDGET_MS}, 1.5 s) is deliberately far
|
|
488
595
|
* under the write funnel's: the tightest caller deadline over a control read is the
|
|
@@ -510,12 +617,19 @@ export class ControlDatabase {
|
|
|
510
617
|
* under-lock callback seam is ever added, audit its read graph the same way.
|
|
511
618
|
*/
|
|
512
619
|
readRows(sql, params, label, retry = true) {
|
|
620
|
+
// `retry: false` marks the reads that may run inside a locked write body, which is
|
|
621
|
+
// also what readRowsOnce's committed-read routing must know (see writeInFlight).
|
|
622
|
+
// NOTE: the membership-gate refresh passes it on EVERY trigger, including the
|
|
623
|
+
// unlocked ones (start, reconcile, seed-applied), so those keep the transaction-only
|
|
624
|
+
// routing and can still queue behind a write waiting for the exec mutex (as before this
|
|
625
|
+
// routing existed). Tolerable while its awaiting callers (reconcile, applySeed) carry no
|
|
626
|
+
// tight deadline; if one ever does, pass the locked/unlocked distinction through instead.
|
|
513
627
|
if (!retry) {
|
|
514
|
-
return this.readRowsOnce(sql, params);
|
|
628
|
+
return this.readRowsOnce(sql, params, true);
|
|
515
629
|
}
|
|
516
630
|
// The label lands LAST so the call site's name survives the spec-injected pacing —
|
|
517
631
|
// it changes log attribution only, never behaviour (same layering as lockedWithRetry).
|
|
518
|
-
return retryControlRead(() => this.readRowsOnce(sql, params), { ...this.controlReadRetryPacing, label });
|
|
632
|
+
return retryControlRead(() => this.readRowsOnce(sql, params, false), { ...this.controlReadRetryPacing, label });
|
|
519
633
|
}
|
|
520
634
|
/**
|
|
521
635
|
* Query all strands from the control database
|
|
@@ -523,11 +637,12 @@ export class ControlDatabase {
|
|
|
523
637
|
async queryStrands() {
|
|
524
638
|
this.ensureInitialized();
|
|
525
639
|
const results = [];
|
|
526
|
-
for (const row of await this.readRows('select Id, MemberPrivateKey, Type from CadreControl.Strand', undefined, 'strands')) {
|
|
640
|
+
for (const row of await this.readRows('select Id, MemberPrivateKey, Type, FounderOwnerKey from CadreControl.Strand', undefined, 'strands')) {
|
|
527
641
|
results.push({
|
|
528
642
|
Id: row.Id,
|
|
529
643
|
MemberPrivateKey: row.MemberPrivateKey,
|
|
530
644
|
Type: row.Type,
|
|
645
|
+
FounderOwnerKey: row.FounderOwnerKey,
|
|
531
646
|
});
|
|
532
647
|
}
|
|
533
648
|
return results;
|
|
@@ -540,11 +655,12 @@ export class ControlDatabase {
|
|
|
540
655
|
*/
|
|
541
656
|
async queryStrand(strandId) {
|
|
542
657
|
this.ensureInitialized();
|
|
543
|
-
for (const row of await this.readRows('select Id, MemberPrivateKey, Type from CadreControl.Strand where Id = ?', [strandId], 'strand')) {
|
|
658
|
+
for (const row of await this.readRows('select Id, MemberPrivateKey, Type, FounderOwnerKey from CadreControl.Strand where Id = ?', [strandId], 'strand')) {
|
|
544
659
|
return {
|
|
545
660
|
Id: row.Id,
|
|
546
661
|
MemberPrivateKey: row.MemberPrivateKey,
|
|
547
662
|
Type: row.Type,
|
|
663
|
+
FounderOwnerKey: row.FounderOwnerKey,
|
|
548
664
|
};
|
|
549
665
|
}
|
|
550
666
|
return null;
|
|
@@ -631,10 +747,12 @@ export class ControlDatabase {
|
|
|
631
747
|
* {@link queryRevokedStamps} rather than inlining the SQL, so tests can interpose on
|
|
632
748
|
* that seam to model the replicated live-row-plus-tombstone merge state.
|
|
633
749
|
*
|
|
634
|
-
* NOTE: runs a second query (the retired-stamp set) per call,
|
|
635
|
-
*
|
|
636
|
-
*
|
|
637
|
-
*
|
|
750
|
+
* NOTE: runs a second query (the retired-stamp set) per call, on the membership-gate
|
|
751
|
+
* refresh path. Its cost is storage consults, not rows (see {@link queryRevokedStamps}):
|
|
752
|
+
* while `Revocation` has never been written every call consults the cohort about it, and
|
|
753
|
+
* the ledger marker ({@link openRevocationLedger}) is what makes it a held block. Folding
|
|
754
|
+
* the exclusion into one statement would not help (it reads the same block), and caching
|
|
755
|
+
* the set would hide a tombstone arriving by replication.
|
|
638
756
|
*
|
|
639
757
|
* NOTE: this filter is HAND-MIRRORED by the gate suites' fake control databases
|
|
640
758
|
* (`test/membership-gate-helpers.ts` and `test/cadre-node-authorized-surface.spec.ts`),
|
|
@@ -743,6 +861,24 @@ export class ControlDatabase {
|
|
|
743
861
|
queryStrandStampId(strandId) {
|
|
744
862
|
return this.queryStampId('Strand', strandId);
|
|
745
863
|
}
|
|
864
|
+
/** `StrandPartyKey` stamp nonce — bound into {@link deleteStrandPartyKey}'s remove digest. */
|
|
865
|
+
queryStrandPartyKeyStampId(strandId) {
|
|
866
|
+
return this.queryStampId('StrandPartyKey', strandId);
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Read THIS party's own strand membership private key (base64 protobuf; decode with
|
|
870
|
+
* `strandMemberKeyPair`) for one strand, or null when no `StrandPartyKey` row exists.
|
|
871
|
+
* The identity source the closed-strand founder bootstrap derives its `Member.Key` /
|
|
872
|
+
* `Manager.MemberKey` from — deliberately NOT `Strand.MemberPrivateKey`, the
|
|
873
|
+
* strand-wide read secret every joining party receives.
|
|
874
|
+
*/
|
|
875
|
+
async queryStrandPartyKey(strandId) {
|
|
876
|
+
this.ensureInitialized();
|
|
877
|
+
for (const row of await this.readRows('select PrivateKey from CadreControl.StrandPartyKey where Id = ?', [strandId], 'strand-party-key')) {
|
|
878
|
+
return row.PrivateKey ?? null;
|
|
879
|
+
}
|
|
880
|
+
return null;
|
|
881
|
+
}
|
|
746
882
|
/** `ValidationKey` stamp nonce — bound into {@link deleteValidationKey}'s remove digest. */
|
|
747
883
|
queryValidationKeyStampId(key) {
|
|
748
884
|
return this.queryStampId('ValidationKey', key);
|
|
@@ -759,9 +895,18 @@ export class ControlDatabase {
|
|
|
759
895
|
* ({@link queryCadrePeers}, {@link queryPeerRecord},
|
|
760
896
|
* {@link CadreNode.resolveDeviceToken}) drop any row whose stamp appears here.
|
|
761
897
|
*
|
|
762
|
-
* NOTE:
|
|
763
|
-
*
|
|
764
|
-
*
|
|
898
|
+
* NOTE: the per-call cost that matters is the storage layer's, not the row count. While
|
|
899
|
+
* `Revocation` has never been written, this node does not hold its block, and Optimystic
|
|
900
|
+
* consults a block's cohort on every read of a block it does not hold: 1 consult per
|
|
901
|
+
* call (measured), each a round trip to every other member on a multi-machine party. The
|
|
902
|
+
* ledger marker ({@link openRevocationLedger}) ends that — a held block is re-consulted
|
|
903
|
+
* at most once per read-repair window (10 s). Do not cache the set instead: a cache
|
|
904
|
+
* cannot see a tombstone arriving by replication, so it would delay a revocation. The
|
|
905
|
+
* row count only grows (append-only) but stays small while removals are rare; revisit if
|
|
906
|
+
* removals become routine and the scan itself shows up in a profile.
|
|
907
|
+
*
|
|
908
|
+
* An isolated node that has never received the `Revocation` block reads it as holding no
|
|
909
|
+
* revocations instead of throwing — see {@link readRevokedStampRows}.
|
|
765
910
|
*
|
|
766
911
|
* `retry: false` is forwarded by {@link queryCadrePeers} for the one caller that reads
|
|
767
912
|
* under the write lock — see that method's note.
|
|
@@ -769,23 +914,76 @@ export class ControlDatabase {
|
|
|
769
914
|
async queryRevokedStamps(tableName, retry = true) {
|
|
770
915
|
this.ensureInitialized();
|
|
771
916
|
const stamps = new Set();
|
|
772
|
-
for (const row of await this.
|
|
917
|
+
for (const row of await this.readRevokedStampRows(tableName, retry)) {
|
|
773
918
|
stamps.add(row.StampId);
|
|
774
919
|
}
|
|
775
920
|
return stamps;
|
|
776
921
|
}
|
|
922
|
+
/**
|
|
923
|
+
* The `Revocation` scan behind {@link queryRevokedStamps}, answering NO ROWS when the read
|
|
924
|
+
* fails `cohort-unreachable` ({@link isCohortUnreachableRead}): this node does not hold
|
|
925
|
+
* the block and could ask no other cohort member about it. Every other failure rethrows.
|
|
926
|
+
* The retry in {@link readRows} runs first, so a node whose connectivity returns within
|
|
927
|
+
* the read budget still gets the real answer.
|
|
928
|
+
*
|
|
929
|
+
* Without this, a machine cut off from every other machine in its party before it ever
|
|
930
|
+
* received the block — the block does not exist anywhere until the owner files the
|
|
931
|
+
* ledger marker ({@link openRevocationLedger}) on a connected reconcile pass — cannot
|
|
932
|
+
* answer ANY membership, peer-record or device-token lookup, although it holds those
|
|
933
|
+
* rows locally.
|
|
934
|
+
*
|
|
935
|
+
* NOTE: accepted tradeoff — `cohort-unreachable` on THIS read, and only this read, is
|
|
936
|
+
* treated as "no revocations known". It adds no fail-open that does not already exist:
|
|
937
|
+
* an isolated node holding a stale `Revocation` block is served it silently (the consult
|
|
938
|
+
* reaches nobody, so no doubt is raised), and a revocation authored elsewhere is invisible
|
|
939
|
+
* to it either way until connectivity returns. The other reasons still throw:
|
|
940
|
+
* `peers-unreachable` means part of the cohort answered, and `claimed-elsewhere` /
|
|
941
|
+
* `unmaterializable` mean the block exists, so an empty answer could admit a revoked
|
|
942
|
+
* member. Do not move this into {@link readRows}: an empty answer is known-safe only for
|
|
943
|
+
* a table whose empty state is its never-written state; decide any other table in its
|
|
944
|
+
* own reader. Revisit if optimystic starts reporting a held-but-stale block distinctly
|
|
945
|
+
* (the equivalence above then breaks), or if revocation enforcement must fail closed
|
|
946
|
+
* under partition.
|
|
947
|
+
*
|
|
948
|
+
* NOTE: an isolated node pays the whole read retry (up to
|
|
949
|
+
* `CONTROL_READ_RETRY_BUDGET_MS`, plus the slow attempt that exhausted it) before this
|
|
950
|
+
* answers, and {@link queryPeerRecord} then issues its row scan on top. If an isolated
|
|
951
|
+
* node's lookups are seen exceeding the admission gate's 2 s deadline
|
|
952
|
+
* (`ADMISSION_DECISION_TIMEOUT_MS`), skip the retry for this read when the first attempt
|
|
953
|
+
* fails `cohort-unreachable`.
|
|
954
|
+
*/
|
|
955
|
+
async readRevokedStampRows(tableName, retry) {
|
|
956
|
+
try {
|
|
957
|
+
return await this.readRows('select StampId from CadreControl.Revocation where TableName = ?', [tableName], 'revoked-stamps', retry);
|
|
958
|
+
}
|
|
959
|
+
catch (error) {
|
|
960
|
+
if (!isCohortUnreachableRead(error)) {
|
|
961
|
+
throw error;
|
|
962
|
+
}
|
|
963
|
+
log('revoked-stamps(%s): no cohort member reachable and the Revocation block is not held here; reading as no revocations known: %s', tableName, error);
|
|
964
|
+
return [];
|
|
965
|
+
}
|
|
966
|
+
}
|
|
777
967
|
/**
|
|
778
968
|
* Every locally-held `CadreControl.Revocation` tombstone — identity triple plus its
|
|
779
969
|
* `ReissuedAt` counter. Consumed by the cohort-growth re-issue sweep, which
|
|
780
970
|
* enumerates what this node holds before {@link reissueRevocations} re-broadcasts
|
|
781
|
-
* it. Plain scan with no `where`, so
|
|
782
|
-
* (see the statement comment in
|
|
783
|
-
* like every other read.
|
|
971
|
+
* it, and by the reap sweep ({@link reapRevokedRows}). Plain scan with no `where`, so
|
|
972
|
+
* the composite-primary-key point-lookup hazard (see the statement comment in
|
|
973
|
+
* {@link reissueRevocations}) does not arise. Unlocked, like every other read.
|
|
974
|
+
*
|
|
975
|
+
* Skips the ledger marker ({@link REVOCATION_LEDGER_MARKER}): it retires nothing, so
|
|
976
|
+
* neither sweep may reap or re-sign it, and skipping it keeps `RevocationRow.tableName`
|
|
977
|
+
* a {@link RevocableTable}. Filtered on `TableName` alone, in TypeScript: `RowIsGone`
|
|
978
|
+
* admits no other row under `'Revocation'`.
|
|
784
979
|
*/
|
|
785
980
|
async queryRevocations() {
|
|
786
981
|
this.ensureInitialized();
|
|
787
982
|
const rows = [];
|
|
788
983
|
for (const row of await this.readRows('select TableName, RowKey, StampId, ReissuedAt from CadreControl.Revocation', undefined, 'revocations')) {
|
|
984
|
+
if (row.TableName === REVOCATION_LEDGER_MARKER.tableName) {
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
789
987
|
rows.push({
|
|
790
988
|
tableName: row.TableName,
|
|
791
989
|
rowKey: row.RowKey,
|
|
@@ -939,6 +1137,10 @@ export class ControlDatabase {
|
|
|
939
1137
|
/**
|
|
940
1138
|
* Insert a strand into the control database using an owner signature.
|
|
941
1139
|
*
|
|
1140
|
+
* Fails with a `Strand.Id` uniqueness violation when the id is already seated — the
|
|
1141
|
+
* caller decides whether that is a duplicate of its own earlier write (idempotent) or a
|
|
1142
|
+
* genuine conflict; see {@link isStrandIdConflict} and `CadreNode.publishStrand`.
|
|
1143
|
+
*
|
|
942
1144
|
* The owner signs the canonical row-bound authorization message (see
|
|
943
1145
|
* {@link buildAuthorizationMessage}) — NOT a bare stamp — so the signature is bound to
|
|
944
1146
|
* this strand's contents and cannot be transplanted onto an attacker-chosen row. The
|
|
@@ -958,15 +1160,18 @@ export class ControlDatabase {
|
|
|
958
1160
|
const peerId = this.config.libp2pNode.peerId.toString();
|
|
959
1161
|
const stampId = generateStampId(peerId);
|
|
960
1162
|
// Field order MUST match the schema's Strand `AuthorizedInsert` verify:
|
|
961
|
-
// Id, Type, MemberPrivateKey ('' when null), StampId.
|
|
1163
|
+
// Id, Type, MemberPrivateKey ('' when null), StampId. FounderOwnerKey is
|
|
1164
|
+
// deliberately NOT in the digest — the schema binds it by equality to the
|
|
1165
|
+
// verified context.OwnerKey instead (see the constraint's comment).
|
|
962
1166
|
const message = buildAuthorizationMessage('CadreControl.Strand', 'add', [strandId, type, memberPrivateKey ?? '', stampId]);
|
|
963
1167
|
const signature = signMessage(message);
|
|
964
1168
|
// StampId is a real, unique column (single-use anti-replay), no longer a context value.
|
|
1169
|
+
// FounderOwnerKey must equal the signing owner or the constraint rejects the row.
|
|
965
1170
|
await this.execWrite(`
|
|
966
|
-
insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId)
|
|
1171
|
+
insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId, FounderOwnerKey)
|
|
967
1172
|
with context OwnerKey = ?, Signature = ?
|
|
968
|
-
values (?, ?, ?, ?)
|
|
969
|
-
`, [ownerKey, signature, strandId, type, memberPrivateKey ?? null, stampId], 'strand-insert');
|
|
1173
|
+
values (?, ?, ?, ?, ?)
|
|
1174
|
+
`, [ownerKey, signature, strandId, type, memberPrivateKey ?? null, stampId, ownerKey], 'strand-insert');
|
|
970
1175
|
log('Strand inserted: %s', strandId);
|
|
971
1176
|
}
|
|
972
1177
|
/**
|
|
@@ -984,11 +1189,126 @@ export class ControlDatabase {
|
|
|
984
1189
|
* The remove digest binds only (Id, StampId) — not Type/MemberPrivateKey — so this
|
|
985
1190
|
* works identically for open and closed strands.
|
|
986
1191
|
*
|
|
1192
|
+
* When the strand has a `StrandPartyKey` row (this party's own membership identity for
|
|
1193
|
+
* the strand — minted at publish for closed strands), it is deleted IN THE SAME
|
|
1194
|
+
* transaction, with its own `'remove'`-tagged signature and its own `Revocation`
|
|
1195
|
+
* tombstone, so a re-published strand always mints fresh identity and no crash window
|
|
1196
|
+
* can orphan the key row. The party-key delete happens ONLY alongside an actual strand
|
|
1197
|
+
* row delete: a `StrandPartyKey` row with no local `Strand` row is a JOINER's identity
|
|
1198
|
+
* (the joiner never holds the strand row) and is not this method's to destroy — that
|
|
1199
|
+
* is {@link deleteStrandPartyKey}'s.
|
|
1200
|
+
*
|
|
987
1201
|
* A no-op (no throw, no tombstone) when the row does not exist — `false` then, `true`
|
|
988
1202
|
* when a row was actually removed.
|
|
989
1203
|
*/
|
|
990
1204
|
deleteStrand(strandId, ownerKey, signMessage) {
|
|
991
|
-
return this.lockedWithRetry(() => this.
|
|
1205
|
+
return this.lockedWithRetry(() => this.deleteStrandAndPartyKey(strandId, ownerKey, signMessage), {}, 'strand-delete');
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* The locked body of {@link deleteStrand}: the `Strand` delete + tombstone, plus — when
|
|
1209
|
+
* one exists — the strand's `StrandPartyKey` delete + tombstone, all in ONE
|
|
1210
|
+
* transaction. A two-table sibling of {@link deleteGuardedRow} (see that method for the
|
|
1211
|
+
* per-clause security rationale: stamp read inside the locked body, `'remove'`-tagged
|
|
1212
|
+
* digests, mandatory same-transaction tombstones); kept separate rather than
|
|
1213
|
+
* generalizing the shared body because no other guarded table has a companion row.
|
|
1214
|
+
*
|
|
1215
|
+
* NOTE: that duplication is a drift risk, not a correctness one — a future tightening of
|
|
1216
|
+
* {@link deleteGuardedRow}'s discipline (an extra precondition, a different digest shape)
|
|
1217
|
+
* will NOT reach this body. Grep for both when you change either; if a second guarded
|
|
1218
|
+
* table ever gains a companion row, generalize instead of copying this a third time.
|
|
1219
|
+
*
|
|
1220
|
+
* Not wrapped in {@link withWriteLock} — the caller holds the (non-re-entrant) lock.
|
|
1221
|
+
*/
|
|
1222
|
+
async deleteStrandAndPartyKey(strandId, ownerKey, signMessage) {
|
|
1223
|
+
this.ensureInitialized();
|
|
1224
|
+
// retry: false — these reads run inside the locked write body (see queryStampId's NOTE).
|
|
1225
|
+
const strandStamp = await this.queryStampId('Strand', strandId, false);
|
|
1226
|
+
if (strandStamp === null) {
|
|
1227
|
+
log('delete Strand: no row for %s (already absent)', strandId);
|
|
1228
|
+
return false;
|
|
1229
|
+
}
|
|
1230
|
+
const partyKeyStamp = await this.queryStampId('StrandPartyKey', strandId, false);
|
|
1231
|
+
const strandSignature = signMessage(buildAuthorizationMessage('CadreControl.Strand', 'remove', [strandId, strandStamp]));
|
|
1232
|
+
const strandRevocationSignature = signMessage(buildAuthorizationMessage('CadreControl.Revocation', 'remove', ['Strand', strandId, strandStamp]));
|
|
1233
|
+
const partyKeySignature = partyKeyStamp === null ? null : signMessage(buildAuthorizationMessage('CadreControl.StrandPartyKey', 'remove', [strandId, partyKeyStamp]));
|
|
1234
|
+
const partyKeyRevocationSignature = partyKeyStamp === null ? null : signMessage(buildAuthorizationMessage('CadreControl.Revocation', 'remove', ['StrandPartyKey', strandId, partyKeyStamp]));
|
|
1235
|
+
await this.inTransaction('delete Strand', async () => {
|
|
1236
|
+
await this.db.exec(`
|
|
1237
|
+
delete from CadreControl.Strand
|
|
1238
|
+
with context OwnerKey = ?, Signature = ?
|
|
1239
|
+
where Id = ?
|
|
1240
|
+
`, [ownerKey, strandSignature, strandId]);
|
|
1241
|
+
await this.db.exec(`
|
|
1242
|
+
insert into CadreControl.Revocation (TableName, RowKey, StampId, ReissuedAt)
|
|
1243
|
+
with context OwnerKey = ?, Signature = ?
|
|
1244
|
+
values ('Strand', ?, ?, 0)
|
|
1245
|
+
`, [ownerKey, strandRevocationSignature, strandId, strandStamp]);
|
|
1246
|
+
if (partyKeyStamp !== null) {
|
|
1247
|
+
await this.db.exec(`
|
|
1248
|
+
delete from CadreControl.StrandPartyKey
|
|
1249
|
+
with context OwnerKey = ?, Signature = ?
|
|
1250
|
+
where Id = ?
|
|
1251
|
+
`, [ownerKey, partyKeySignature, strandId]);
|
|
1252
|
+
await this.db.exec(`
|
|
1253
|
+
insert into CadreControl.Revocation (TableName, RowKey, StampId, ReissuedAt)
|
|
1254
|
+
with context OwnerKey = ?, Signature = ?
|
|
1255
|
+
values ('StrandPartyKey', ?, ?, 0)
|
|
1256
|
+
`, [ownerKey, partyKeyRevocationSignature, strandId, partyKeyStamp]);
|
|
1257
|
+
}
|
|
1258
|
+
});
|
|
1259
|
+
log('Strand deleted: %s (stamp retired%s)', strandId, partyKeyStamp === null ? '' : '; party key deleted, stamp retired');
|
|
1260
|
+
this.notifyGuardedDelete({ tableName: 'Strand', rowKey: strandId, stampId: strandStamp });
|
|
1261
|
+
if (partyKeyStamp !== null) {
|
|
1262
|
+
this.notifyGuardedDelete({ tableName: 'StrandPartyKey', rowKey: strandId, stampId: partyKeyStamp });
|
|
1263
|
+
}
|
|
1264
|
+
return true;
|
|
1265
|
+
}
|
|
1266
|
+
/**
|
|
1267
|
+
* Insert this party's own strand membership identity key (`StrandPartyKey` row) using
|
|
1268
|
+
* an owner signature.
|
|
1269
|
+
*
|
|
1270
|
+
* Mirrors {@link insertStrand}: the owner signs the canonical row-bound authorization
|
|
1271
|
+
* message over (Id, PrivateKey, StampId) — binding the key material means a captured
|
|
1272
|
+
* approval can only ever reproduce the exact key it approved — and the StampId is
|
|
1273
|
+
* persisted as a unique column for single-use anti-replay.
|
|
1274
|
+
*
|
|
1275
|
+
* @param strandId - The strand this key is the party's identity for.
|
|
1276
|
+
* @param privateKey - The party's ed25519 strand member private key, base64 protobuf
|
|
1277
|
+
* (same encoding as `Strand.MemberPrivateKey`; mint with `generateStrandMemberKey`).
|
|
1278
|
+
* @param ownerKey - Public key of the authorizing owner.
|
|
1279
|
+
* @param signMessage - Function that ed25519-signs the raw message bytes (no pre-hash)
|
|
1280
|
+
* with the owner's private key, returning a base64url signature.
|
|
1281
|
+
*/
|
|
1282
|
+
async insertStrandPartyKey(strandId, privateKey, ownerKey, signMessage) {
|
|
1283
|
+
this.ensureInitialized();
|
|
1284
|
+
log('Inserting strand party key for strand: %s', strandId);
|
|
1285
|
+
const peerId = this.config.libp2pNode.peerId.toString();
|
|
1286
|
+
const stampId = generateStampId(peerId);
|
|
1287
|
+
// Field order MUST match the schema's StrandPartyKey `AuthorizedInsert` verify:
|
|
1288
|
+
// Id, PrivateKey, StampId.
|
|
1289
|
+
const message = buildAuthorizationMessage('CadreControl.StrandPartyKey', 'add', [strandId, privateKey, stampId]);
|
|
1290
|
+
const signature = signMessage(message);
|
|
1291
|
+
await this.execWrite(`
|
|
1292
|
+
insert into CadreControl.StrandPartyKey (Id, PrivateKey, StampId)
|
|
1293
|
+
with context OwnerKey = ?, Signature = ?
|
|
1294
|
+
values (?, ?, ?)
|
|
1295
|
+
`, [ownerKey, signature, strandId, privateKey, stampId], 'strand-party-key-insert');
|
|
1296
|
+
log('Strand party key inserted for strand: %s', strandId);
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
* Owner-signed removal of one `StrandPartyKey` row — the party's own membership
|
|
1300
|
+
* identity for that strand, stored nowhere else, so this is as destructive as
|
|
1301
|
+
* {@link deleteStrand} on a closed strand. {@link deleteStrand} already removes the
|
|
1302
|
+
* founder's row alongside the `Strand` row in one transaction; this standalone form
|
|
1303
|
+
* exists for a party-key row with NO local `Strand` row (a joiner's identity — the
|
|
1304
|
+
* shape the formation tickets build on).
|
|
1305
|
+
*
|
|
1306
|
+
* Mirrors {@link deleteValidationKey}: `'remove'`-tagged digest over (Id, StampId),
|
|
1307
|
+
* `Revocation` tombstone in the same transaction. A no-op (no throw, no tombstone)
|
|
1308
|
+
* when the row does not exist — `false` then, `true` when a row was actually removed.
|
|
1309
|
+
*/
|
|
1310
|
+
deleteStrandPartyKey(strandId, ownerKey, signMessage) {
|
|
1311
|
+
return this.lockedWithRetry(() => this.deleteGuardedRow('StrandPartyKey', strandId, ownerKey, signMessage), {}, 'strand-party-key-delete');
|
|
992
1312
|
}
|
|
993
1313
|
/**
|
|
994
1314
|
* Insert a validation key into the control database using an owner signature.
|
|
@@ -1269,16 +1589,26 @@ export class ControlDatabase {
|
|
|
1269
1589
|
`, [ownerKey, revocationSignature, table, keyValue, stampId]);
|
|
1270
1590
|
});
|
|
1271
1591
|
log('%s deleted: %s (stamp retired)', table, keyValue);
|
|
1272
|
-
|
|
1273
|
-
try {
|
|
1274
|
-
this.guardedDeleteListener({ tableName: table, rowKey: keyValue, stampId });
|
|
1275
|
-
}
|
|
1276
|
-
catch (error) {
|
|
1277
|
-
log('guarded-delete listener threw (committed delete unaffected): %o', error);
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1592
|
+
this.notifyGuardedDelete({ tableName: table, rowKey: keyValue, stampId });
|
|
1280
1593
|
return true;
|
|
1281
1594
|
}
|
|
1595
|
+
/**
|
|
1596
|
+
* Fire the guarded-delete listener for one committed tombstone, swallowing (and
|
|
1597
|
+
* logging) a listener throw — a committed delete never fails because bookkeeping did.
|
|
1598
|
+
* Shared by {@link deleteGuardedRow} and {@link deleteStrandAndPartyKey} (which files
|
|
1599
|
+
* up to two tombstones per transaction).
|
|
1600
|
+
*/
|
|
1601
|
+
notifyGuardedDelete(revocation) {
|
|
1602
|
+
if (!this.guardedDeleteListener) {
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
try {
|
|
1606
|
+
this.guardedDeleteListener(revocation);
|
|
1607
|
+
}
|
|
1608
|
+
catch (error) {
|
|
1609
|
+
log('guarded-delete listener threw (committed delete unaffected): %o', error);
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1282
1612
|
/**
|
|
1283
1613
|
* Delete one guarded row that an ALREADY-COMMITTED `Revocation` tombstone retires —
|
|
1284
1614
|
* the local catch-up for a node that converged on a removal's tombstone while still
|
|
@@ -1387,8 +1717,9 @@ export class ControlDatabase {
|
|
|
1387
1717
|
*
|
|
1388
1718
|
* Two rows are deliberately left alone:
|
|
1389
1719
|
*
|
|
1390
|
-
* - **Tables outside {@link REAPABLE_TABLES}** (`Strand`, `OwnerKey`)
|
|
1391
|
-
* exists on their `AuthorizedDelete`, so the delete would throw
|
|
1720
|
+
* - **Tables outside {@link REAPABLE_TABLES}** (`Strand`, `StrandPartyKey`, `OwnerKey`)
|
|
1721
|
+
* — no reap branch exists on their `AuthorizedDelete`, so the delete would throw
|
|
1722
|
+
* rather than no-op.
|
|
1392
1723
|
* - **This node's OWN `CadrePeer` / `DeviceToken` row** (`selfPeerId`). Reaping it would
|
|
1393
1724
|
* fight this node's own re-registration: `registerSelf` / `retouchSelfDeviceToken` run
|
|
1394
1725
|
* on the heartbeat and the growth drain, and after a self-reap their insert-if-absent
|
|
@@ -1408,8 +1739,11 @@ export class ControlDatabase {
|
|
|
1408
1739
|
* skip-self rule is exercisable without one.
|
|
1409
1740
|
*
|
|
1410
1741
|
* NOTE: cost is O(tombstones), not O(live rows) — one {@link queryRevocations} scan plus
|
|
1411
|
-
* one {@link queryStampId} point lookup per tombstone, and the empty
|
|
1412
|
-
*
|
|
1742
|
+
* one {@link queryStampId} point lookup per tombstone, and the empty early return makes
|
|
1743
|
+
* the common case (a party that has never revoked anyone; {@link queryRevocations} skips
|
|
1744
|
+
* the ledger marker) a single scan per pass. That scan consults the cohort on every pass
|
|
1745
|
+
* only while `Revocation` has never been written; the ledger marker
|
|
1746
|
+
* ({@link openRevocationLedger}), filed by the same connected pass, makes it a held block.
|
|
1413
1747
|
* But `Revocation` is append-only and unbounded, so this is O(all tombstones ever) point
|
|
1414
1748
|
* lookups on every reconcile tick. Fine while revocations stay rare for a cadre-sized
|
|
1415
1749
|
* party; if the table ever grows, persist a node-local high-water mark of what has
|
|
@@ -1516,6 +1850,74 @@ export class ControlDatabase {
|
|
|
1516
1850
|
return executed;
|
|
1517
1851
|
}, {}, 'revocation-reissue');
|
|
1518
1852
|
}
|
|
1853
|
+
/**
|
|
1854
|
+
* Owner-signed filing of the singleton `Revocation` ledger marker
|
|
1855
|
+
* ({@link REVOCATION_LEDGER_MARKER}), the one row in that table that retires nothing.
|
|
1856
|
+
*
|
|
1857
|
+
* Why it exists: while `Revocation` has never been written, this node does not hold its
|
|
1858
|
+
* block, and Optimystic consults a block's cohort on EVERY read of a block it does not
|
|
1859
|
+
* hold — and every membership lookup, and every guarded insert's `NotRevoked` check,
|
|
1860
|
+
* reads this table. Once any row exists the block is held and re-checked at most once per
|
|
1861
|
+
* read-repair window, like every other populated table. The schema's table comment says
|
|
1862
|
+
* why the row can never read as a retirement.
|
|
1863
|
+
*
|
|
1864
|
+
* Insert-if-absent, shaped like {@link reissueRevocations}: the signature is minted
|
|
1865
|
+
* OUTSIDE the locked body so a retried attempt re-presents the same one, and the guard
|
|
1866
|
+
* runs INSIDE it so it sees a concurrent local writer's committed row. The guard scans
|
|
1867
|
+
* the `'Revocation'` rows and compares the stamp in TypeScript rather than seeking the
|
|
1868
|
+
* full composite primary key, which is served as a point lookup that can miss an existing
|
|
1869
|
+
* row on a networked database (tickets/backlog/debt-composite-pk-point-lookup-unreliable-untracked).
|
|
1870
|
+
*
|
|
1871
|
+
* Two owners filing at once: the loser either sees the marker in its guard or is refused
|
|
1872
|
+
* on the primary key, and both answer `'already-open'`.
|
|
1873
|
+
*
|
|
1874
|
+
* The caller decides WHEN. A marker committed while the node is alone is local-only and
|
|
1875
|
+
* can fork the collection, so {@link CadreNode} files it only while connected; this
|
|
1876
|
+
* method does not look at connectivity.
|
|
1877
|
+
*
|
|
1878
|
+
* @param ownerKey - owner public key for the write context (`Revocation.Authorized`).
|
|
1879
|
+
* @param signMessage - ed25519-signs the raw message bytes (no pre-hash) with that owner's
|
|
1880
|
+
* private key, returning a base64url signature.
|
|
1881
|
+
* @returns `'opened'` when this call filed the marker, `'already-open'` when it was
|
|
1882
|
+
* already there.
|
|
1883
|
+
*/
|
|
1884
|
+
async openRevocationLedger(ownerKey, signMessage) {
|
|
1885
|
+
this.ensureInitialized();
|
|
1886
|
+
const { tableName, rowKey, stampId } = REVOCATION_LEDGER_MARKER;
|
|
1887
|
+
const signature = signMessage(buildAuthorizationMessage('CadreControl.Revocation', 'remove', [tableName, rowKey, stampId]));
|
|
1888
|
+
try {
|
|
1889
|
+
return await this.lockedWithRetry(async () => {
|
|
1890
|
+
if (await this.revocationLedgerFiled()) {
|
|
1891
|
+
return 'already-open';
|
|
1892
|
+
}
|
|
1893
|
+
// Bare `exec`: already inside the write lock, which is NOT re-entrant.
|
|
1894
|
+
await this.db.exec(`
|
|
1895
|
+
insert into CadreControl.Revocation (TableName, RowKey, StampId)
|
|
1896
|
+
with context OwnerKey = ?, Signature = ?
|
|
1897
|
+
values (?, ?, ?)
|
|
1898
|
+
`, [ownerKey, signature, tableName, rowKey, stampId]);
|
|
1899
|
+
log('Revocation ledger marker filed');
|
|
1900
|
+
return 'opened';
|
|
1901
|
+
}, {}, 'revocation-ledger-open');
|
|
1902
|
+
}
|
|
1903
|
+
catch (error) {
|
|
1904
|
+
if (!isRevocationLedgerConflict(error)) {
|
|
1905
|
+
throw error;
|
|
1906
|
+
}
|
|
1907
|
+
log('Revocation ledger marker already filed (refused on the primary key, most likely by another owner filing first): %s', error);
|
|
1908
|
+
return 'already-open';
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
/**
|
|
1912
|
+
* Whether the ledger marker is present locally: a scan of the `'Revocation'` rows with the
|
|
1913
|
+
* stamp compared in TypeScript (see {@link openRevocationLedger} for why not a seek).
|
|
1914
|
+
* Called only inside the locked write body, so never retried (see queryStampId's NOTE).
|
|
1915
|
+
*/
|
|
1916
|
+
async revocationLedgerFiled() {
|
|
1917
|
+
const { tableName, stampId } = REVOCATION_LEDGER_MARKER;
|
|
1918
|
+
const rows = await this.readRows('select StampId from CadreControl.Revocation where TableName = ?', [tableName], 'revocation-ledger', false);
|
|
1919
|
+
return rows.some(row => row.StampId === stampId);
|
|
1920
|
+
}
|
|
1519
1921
|
/**
|
|
1520
1922
|
* Run `body` between `beginTransaction` and `commit`, rolling back on failure.
|
|
1521
1923
|
*
|
|
@@ -1576,6 +1978,19 @@ export class ControlDatabase {
|
|
|
1576
1978
|
setGuardedDeleteListener(listener) {
|
|
1577
1979
|
this.guardedDeleteListener = listener;
|
|
1578
1980
|
}
|
|
1981
|
+
/**
|
|
1982
|
+
* Wire (or clear, with null) the single listener notified when {@link lockedWithRetry}
|
|
1983
|
+
* ABANDONS a control write. Same ownership contract as
|
|
1984
|
+
* {@link setMembershipChangeListener}: one CadreNode, wired in `start()` and cleared on
|
|
1985
|
+
* teardown, and a second call replaces the first rather than fanning out.
|
|
1986
|
+
*
|
|
1987
|
+
* Covers every write that reaches the funnel, foreground and background alike. A
|
|
1988
|
+
* foreground caller also sees the rethrown error; a background one often does not, which
|
|
1989
|
+
* is the whole reason this exists.
|
|
1990
|
+
*/
|
|
1991
|
+
setControlWriteAbandonedListener(listener) {
|
|
1992
|
+
this.controlWriteAbandonedListener = listener;
|
|
1993
|
+
}
|
|
1579
1994
|
/**
|
|
1580
1995
|
* Run a `CadrePeer` row mutation and notify the membership listener once it has
|
|
1581
1996
|
* COMMITTED.
|
|
@@ -1660,10 +2075,26 @@ export class ControlDatabase {
|
|
|
1660
2075
|
async withWriteLock(fn) {
|
|
1661
2076
|
// Chain behind the current tail regardless of how it settled, then park a
|
|
1662
2077
|
// swallowed copy as the new tail so one failed write never poisons the queue.
|
|
1663
|
-
const
|
|
2078
|
+
const body = () => this.runWriteBody(fn);
|
|
2079
|
+
const run = this.writeQueue.then(body, body);
|
|
1664
2080
|
this.writeQueue = run.then(() => undefined, () => undefined);
|
|
1665
2081
|
return run;
|
|
1666
2082
|
}
|
|
2083
|
+
/**
|
|
2084
|
+
* Run one locked body, counted in {@link runningWriteBodies} from the moment it takes
|
|
2085
|
+
* the lock until it settles — so an unlocked read routes around it even while its
|
|
2086
|
+
* first statement is still waiting for the database's exec mutex, before
|
|
2087
|
+
* `getAutocommit()` can show it (see {@link readRowsOnce}).
|
|
2088
|
+
*/
|
|
2089
|
+
async runWriteBody(fn) {
|
|
2090
|
+
this.runningWriteBodies++;
|
|
2091
|
+
try {
|
|
2092
|
+
return await fn();
|
|
2093
|
+
}
|
|
2094
|
+
finally {
|
|
2095
|
+
this.runningWriteBodies--;
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
1667
2098
|
/**
|
|
1668
2099
|
* {@link withWriteLock} plus the bounded transient-failure retry
|
|
1669
2100
|
* ({@link retryControlWrite}) — the wrapper the whole public write surface goes
|
|
@@ -1687,12 +2118,24 @@ export class ControlDatabase {
|
|
|
1687
2118
|
* `label` names the operation in this loop's debug lines and nothing else
|
|
1688
2119
|
* ({@link ControlWriteRetryOptions.label}). Every call site in this class supplies one:
|
|
1689
2120
|
* several writes retry CONCURRENTLY in a real party, so an unlabelled line cannot be
|
|
1690
|
-
* attributed to a write — keep new call sites labelled.
|
|
2121
|
+
* attributed to a write — keep new call sites labelled. It is also the only thing that
|
|
2122
|
+
* attributes an abandonment reported through {@link setControlWriteAbandonedListener}.
|
|
2123
|
+
*
|
|
2124
|
+
* The abandonment observer lands LAST, after both the policy and the spec-injected
|
|
2125
|
+
* pacing, so this class's single listener is the one seam for it — a caller that
|
|
2126
|
+
* smuggled its own in through `policy` would be displaced here rather than fanning out.
|
|
1691
2127
|
*/
|
|
1692
2128
|
lockedWithRetry(fn, policy = {}, label) {
|
|
1693
2129
|
// The label lands LAST so a call site's own name survives both the policy and the
|
|
1694
2130
|
// spec-injected pacing; it changes log attribution only, never behaviour.
|
|
1695
|
-
return retryControlWrite(() => this.withWriteLock(fn), {
|
|
2131
|
+
return retryControlWrite(() => this.withWriteLock(fn), {
|
|
2132
|
+
...policy,
|
|
2133
|
+
...this.controlWriteRetryPacing,
|
|
2134
|
+
...(label !== undefined ? { label } : {}),
|
|
2135
|
+
// Read through the field, not captured: a listener wired (or cleared) while a write
|
|
2136
|
+
// is already in backoff still governs that write's abandonment.
|
|
2137
|
+
onAbandon: (abandonment) => this.controlWriteAbandonedListener?.(abandonment)
|
|
2138
|
+
});
|
|
1696
2139
|
}
|
|
1697
2140
|
/**
|
|
1698
2141
|
* One-statement local write, serialized by {@link withWriteLock} and retried on a
|
|
@@ -1893,11 +2336,13 @@ export class ControlDatabase {
|
|
|
1893
2336
|
await this.inTransaction('redemption', async () => {
|
|
1894
2337
|
// 1. Strand row — authorised by the FormationUsage branch (no owner sig),
|
|
1895
2338
|
// still carrying a fresh unique StampId for the anti-replay column.
|
|
1896
|
-
// Hard-coded open + keyless
|
|
2339
|
+
// Hard-coded open + keyless + explicit null FounderOwnerKey: the
|
|
2340
|
+
// consent branch admits no other shape (no signature means no
|
|
2341
|
+
// trustworthy founder machine to record — see the schema's NOTE).
|
|
1897
2342
|
await this.db.exec(`
|
|
1898
|
-
insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId)
|
|
2343
|
+
insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId, FounderOwnerKey)
|
|
1899
2344
|
with context OwnerKey = null, Signature = null
|
|
1900
|
-
values (?, 'o', null,
|
|
2345
|
+
values (?, 'o', null, ?, null)
|
|
1901
2346
|
`, [strandId, strandStampId]);
|
|
1902
2347
|
// 2. FormationUsage row — authorised by the matching FormationInvite, and
|
|
1903
2348
|
// carrying the strand's stamp so it authorizes THIS row and no other.
|
|
@@ -2054,22 +2499,19 @@ export class ControlDatabase {
|
|
|
2054
2499
|
/**
|
|
2055
2500
|
* Count `FormationUsage` rows recorded against a token (uses consumed so far).
|
|
2056
2501
|
*
|
|
2057
|
-
*
|
|
2058
|
-
* the
|
|
2059
|
-
*
|
|
2060
|
-
*
|
|
2061
|
-
*
|
|
2062
|
-
*
|
|
2063
|
-
*
|
|
2064
|
-
*
|
|
2065
|
-
*
|
|
2066
|
-
*
|
|
2067
|
-
*
|
|
2068
|
-
*
|
|
2069
|
-
*
|
|
2070
|
-
* `schemas/control.qsql`, and the engine defect in
|
|
2071
|
-
* `blocked/secondary-index-seek-blind-to-sibling-rows`. Do NOT re-declare the index to
|
|
2072
|
-
* speed this up while that ticket is open.
|
|
2502
|
+
* Served by a seek through the `FormationUsageByToken` index rather than a full scan of
|
|
2503
|
+
* the table, which is append-only and grows for the life of the party.
|
|
2504
|
+
*
|
|
2505
|
+
* NOTE: this count IS the seat cap (`enforceFormationUseCap`), so an under-report admits a
|
|
2506
|
+
* seat the invitation never paid for — and reading it through a secondary index makes the
|
|
2507
|
+
* cap depend on that index converging across machines. It did not, from 2026-08-04 to
|
|
2508
|
+
* 2026-08-25: a descent on a second machine returned only the rows that machine had
|
|
2509
|
+
* written, and the index was removed until the engine was fixed upstream (re-measured
|
|
2510
|
+
* 2026-09-17, `complete/restore-formation-usage-token-index`). The live guard is the
|
|
2511
|
+
* integration-tests scenario `strand-formation-concurrent-redemption`, which asserts both
|
|
2512
|
+
* machines' views of a raced redemption. If it fails on BOTH views again, index
|
|
2513
|
+
* convergence has regressed — fix the engine or take this read off the index, and do not
|
|
2514
|
+
* weaken that scenario's assertions to get a green run.
|
|
2073
2515
|
*
|
|
2074
2516
|
* `retry: false` is passed only by {@link assertSeatRemains}, which runs INSIDE a
|
|
2075
2517
|
* locked write body — same per-call opt-out, and for the same reason, as
|