@serfab/cadre-core 0.13.0 → 1.1.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 +20 -6
- 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 +558 -80
- package/dist/cadre-node.js +1060 -170
- 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 +299 -44
- package/dist/control-database.js +469 -69
- 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 +103 -19
- package/dist/control-schema.js.map +1 -1
- package/dist/control-write-retry.d.ts +80 -11
- package/dist/control-write-retry.js +176 -29
- package/dist/control-write-retry.js.map +1 -1
- package/dist/enrolled-machine-store.js +2 -2
- package/dist/index.d.ts +14 -7
- package/dist/index.js +33 -6
- package/dist/index.js.map +1 -1
- package/dist/node-local-snapshot.d.ts +15 -7
- package/dist/node-local-snapshot.js +23 -8
- 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/relay-addrs.d.ts +90 -52
- package/dist/relay-addrs.js +91 -59
- 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 +34 -16
- package/dist/strand-database.js +38 -24
- 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 +87 -5
- package/dist/strand-formation-manager.js +109 -5
- package/dist/strand-formation-manager.js.map +1 -1
- package/dist/strand-formation-protocol.d.ts +21 -1
- package/dist/strand-formation-protocol.js +30 -0
- package/dist/strand-formation-protocol.js.map +1 -1
- package/dist/strand-instance-manager.d.ts +243 -6
- package/dist/strand-instance-manager.js +470 -37
- 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 +131 -11
- package/dist/strand-membership-writer.js +396 -134
- package/dist/strand-membership-writer.js.map +1 -1
- package/dist/strand-network-config.d.ts +46 -14
- package/dist/strand-network-config.js +79 -23
- package/dist/strand-network-config.js.map +1 -1
- package/dist/strand-solicitation.d.ts +10 -1
- package/dist/strand-solicitation.js +5 -0
- 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 +6 -0
- 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 +262 -30
- package/dist/types.js.map +1 -1
- package/package.json +8 -8
- package/src/bootstrap-peer-store-file.ts +2 -2
- package/src/bootstrap-peer-store.ts +69 -27
- package/src/cadre-node.ts +7301 -6353
- package/src/control-authorization.ts +2 -1
- package/src/control-cohort.ts +122 -130
- package/src/control-database.ts +537 -69
- package/src/control-read-retry.ts +202 -167
- package/src/control-retry.ts +297 -190
- package/src/control-schema.ts +103 -19
- package/src/control-write-retry.ts +533 -383
- package/src/enrolled-machine-store.ts +2 -2
- package/src/index.ts +83 -6
- package/src/node-local-snapshot.ts +25 -8
- package/src/peer-dial.ts +215 -0
- package/src/relay-addrs.ts +458 -436
- 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 +50 -27
- package/src/strand-first-sync-gate.ts +258 -0
- package/src/strand-formation-manager.ts +140 -5
- package/src/strand-formation-protocol.ts +43 -1
- package/src/strand-instance-manager.ts +577 -37
- 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 +527 -189
- package/src/strand-network-config.ts +102 -24
- package/src/strand-solicitation.ts +16 -1
- package/src/strand-wake-protocol.ts +21 -66
- package/src/strand-watcher.ts +6 -0
- package/src/timed-step.ts +28 -0
- package/src/timeout-scheduler.ts +28 -0
- package/src/types.ts +1789 -1554
package/dist/control-database.js
CHANGED
|
@@ -9,7 +9,7 @@ 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
13
|
import { chainMessages } from './control-retry.js';
|
|
14
14
|
const log = debug('sereus:cadre:control-db');
|
|
15
15
|
const timing = debug('sereus:cadre:timing');
|
|
@@ -209,6 +209,7 @@ const GUARDED_KEY_COLUMN = {
|
|
|
209
209
|
CadrePeer: 'PeerId',
|
|
210
210
|
ValidationKey: 'Key',
|
|
211
211
|
Strand: 'Id',
|
|
212
|
+
StrandPartyKey: 'Id',
|
|
212
213
|
DeviceToken: 'PeerId',
|
|
213
214
|
};
|
|
214
215
|
/**
|
|
@@ -236,19 +237,43 @@ const STRAND_ID_CONFLICT = /UNIQUE constraint failed: Strand\.Id\b/i;
|
|
|
236
237
|
* reword reddens there.
|
|
237
238
|
*/
|
|
238
239
|
export function isStrandIdConflict(error) {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
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));
|
|
243
268
|
}
|
|
244
269
|
/**
|
|
245
270
|
* Guarded tables a node may reap locally once their tombstone has committed — the
|
|
246
271
|
* tables whose `AuthorizedDelete` carries the REAP branch (see the constraint comment on
|
|
247
|
-
* `CadrePeer.AuthorizedDelete` in the schema). `Strand`
|
|
248
|
-
*
|
|
249
|
-
* nowhere else (tickets/backlog/debt-strand-tombstone-reap.md owns any
|
|
250
|
-
* `OwnerKey` has no production removal path and `MinOneOwner` makes an
|
|
251
|
-
* 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.
|
|
252
277
|
*/
|
|
253
278
|
export const REAPABLE_TABLES = ['CadrePeer', 'DeviceToken', 'ValidationKey'];
|
|
254
279
|
/**
|
|
@@ -271,8 +296,16 @@ export class ControlDatabase {
|
|
|
271
296
|
this.initialized = false;
|
|
272
297
|
this.membershipListener = null;
|
|
273
298
|
this.guardedDeleteListener = null;
|
|
299
|
+
this.controlWriteAbandonedListener = null;
|
|
274
300
|
/** Tail of the local-write chain — see {@link withWriteLock}. */
|
|
275
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;
|
|
276
309
|
/**
|
|
277
310
|
* Pacing seams for {@link lockedWithRetry}. Production leaves this empty (real backoff,
|
|
278
311
|
* real clock); specs inject a recorded `sleep` / fake `now` so no test waits out a real
|
|
@@ -355,8 +388,8 @@ export class ControlDatabase {
|
|
|
355
388
|
// NOTE: this is where a slow launch is felt. Duration is (raw-storage operations
|
|
356
389
|
// issued) × per-operation storage latency: ~1ms/op on an idle machine, but
|
|
357
390
|
// 50-90ms/op on a loaded disk or a phone's flash under launch contention. A cold
|
|
358
|
-
// start now reaches the backend
|
|
359
|
-
// — 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
|
|
360
393
|
// wraps every embedder storage in `@optimystic/db-p2p`'s write-through cache
|
|
361
394
|
// (@serfab/quereus-plugin-sereus's cached-storage.ts). Uncached the same start issued ~2000 operations — the
|
|
362
395
|
// upstream re-read amplification measured in
|
|
@@ -469,11 +502,33 @@ export class ControlDatabase {
|
|
|
469
502
|
* opted in, `control-write-degraded-cohort-member` could no longer observe a sibling
|
|
470
503
|
* publishing its own `CadrePeer` row and failed at suite setup on two runs out of two.
|
|
471
504
|
*
|
|
472
|
-
*
|
|
473
|
-
*
|
|
474
|
-
*
|
|
475
|
-
*
|
|
476
|
-
*
|
|
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).
|
|
477
532
|
*
|
|
478
533
|
* What a committed read gives up is observing a write that has not finished
|
|
479
534
|
* committing, and that is safe for every caller here: an AWAITED write is committed by
|
|
@@ -481,15 +536,23 @@ export class ControlDatabase {
|
|
|
481
536
|
* open explicit transaction and stays serialized, so it still sees its own
|
|
482
537
|
* transaction's rows. A read after an UNAWAITED write on this database would be wrong
|
|
483
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.
|
|
484
547
|
*/
|
|
485
|
-
async readRowsOnce(sql, params) {
|
|
548
|
+
async readRowsOnce(sql, params, underWriteLock) {
|
|
486
549
|
let iterator;
|
|
487
|
-
if (this.
|
|
488
|
-
|
|
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' });
|
|
489
553
|
}
|
|
490
554
|
else {
|
|
491
|
-
|
|
492
|
-
iterator = this.db.eval(sql, params, { readConcurrency: 'committed' });
|
|
555
|
+
iterator = this.db.eval(sql, params);
|
|
493
556
|
}
|
|
494
557
|
const rows = [];
|
|
495
558
|
for await (const row of iterator) {
|
|
@@ -497,6 +560,19 @@ export class ControlDatabase {
|
|
|
497
560
|
}
|
|
498
561
|
return rows;
|
|
499
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
|
+
}
|
|
500
576
|
/**
|
|
501
577
|
* {@link readRowsOnce} plus the bounded transient-failure retry
|
|
502
578
|
* ({@link retryControlRead}) — the funnel every UNLOCKED control read goes through, so a
|
|
@@ -512,8 +588,8 @@ export class ControlDatabase {
|
|
|
512
588
|
* primary-key lookup or a `count(1)`); nothing streams.
|
|
513
589
|
*
|
|
514
590
|
* Each ATTEMPT is a fresh {@link readRowsOnce} call, so the committed-read opt-in
|
|
515
|
-
* (
|
|
516
|
-
* 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.
|
|
517
593
|
*
|
|
518
594
|
* The retry's budget ({@link CONTROL_READ_RETRY_BUDGET_MS}, 1.5 s) is deliberately far
|
|
519
595
|
* under the write funnel's: the tightest caller deadline over a control read is the
|
|
@@ -541,12 +617,19 @@ export class ControlDatabase {
|
|
|
541
617
|
* under-lock callback seam is ever added, audit its read graph the same way.
|
|
542
618
|
*/
|
|
543
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.
|
|
544
627
|
if (!retry) {
|
|
545
|
-
return this.readRowsOnce(sql, params);
|
|
628
|
+
return this.readRowsOnce(sql, params, true);
|
|
546
629
|
}
|
|
547
630
|
// The label lands LAST so the call site's name survives the spec-injected pacing —
|
|
548
631
|
// it changes log attribution only, never behaviour (same layering as lockedWithRetry).
|
|
549
|
-
return retryControlRead(() => this.readRowsOnce(sql, params), { ...this.controlReadRetryPacing, label });
|
|
632
|
+
return retryControlRead(() => this.readRowsOnce(sql, params, false), { ...this.controlReadRetryPacing, label });
|
|
550
633
|
}
|
|
551
634
|
/**
|
|
552
635
|
* Query all strands from the control database
|
|
@@ -664,10 +747,12 @@ export class ControlDatabase {
|
|
|
664
747
|
* {@link queryRevokedStamps} rather than inlining the SQL, so tests can interpose on
|
|
665
748
|
* that seam to model the replicated live-row-plus-tombstone merge state.
|
|
666
749
|
*
|
|
667
|
-
* NOTE: runs a second query (the retired-stamp set) per call,
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
*
|
|
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.
|
|
671
756
|
*
|
|
672
757
|
* NOTE: this filter is HAND-MIRRORED by the gate suites' fake control databases
|
|
673
758
|
* (`test/membership-gate-helpers.ts` and `test/cadre-node-authorized-surface.spec.ts`),
|
|
@@ -776,6 +861,24 @@ export class ControlDatabase {
|
|
|
776
861
|
queryStrandStampId(strandId) {
|
|
777
862
|
return this.queryStampId('Strand', strandId);
|
|
778
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
|
+
}
|
|
779
882
|
/** `ValidationKey` stamp nonce — bound into {@link deleteValidationKey}'s remove digest. */
|
|
780
883
|
queryValidationKeyStampId(key) {
|
|
781
884
|
return this.queryStampId('ValidationKey', key);
|
|
@@ -792,9 +895,18 @@ export class ControlDatabase {
|
|
|
792
895
|
* ({@link queryCadrePeers}, {@link queryPeerRecord},
|
|
793
896
|
* {@link CadreNode.resolveDeviceToken}) drop any row whose stamp appears here.
|
|
794
897
|
*
|
|
795
|
-
* NOTE:
|
|
796
|
-
*
|
|
797
|
-
*
|
|
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}.
|
|
798
910
|
*
|
|
799
911
|
* `retry: false` is forwarded by {@link queryCadrePeers} for the one caller that reads
|
|
800
912
|
* under the write lock — see that method's note.
|
|
@@ -802,23 +914,76 @@ export class ControlDatabase {
|
|
|
802
914
|
async queryRevokedStamps(tableName, retry = true) {
|
|
803
915
|
this.ensureInitialized();
|
|
804
916
|
const stamps = new Set();
|
|
805
|
-
for (const row of await this.
|
|
917
|
+
for (const row of await this.readRevokedStampRows(tableName, retry)) {
|
|
806
918
|
stamps.add(row.StampId);
|
|
807
919
|
}
|
|
808
920
|
return stamps;
|
|
809
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
|
+
}
|
|
810
967
|
/**
|
|
811
968
|
* Every locally-held `CadreControl.Revocation` tombstone — identity triple plus its
|
|
812
969
|
* `ReissuedAt` counter. Consumed by the cohort-growth re-issue sweep, which
|
|
813
970
|
* enumerates what this node holds before {@link reissueRevocations} re-broadcasts
|
|
814
|
-
* it. Plain scan with no `where`, so
|
|
815
|
-
* (see the statement comment in
|
|
816
|
-
* 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'`.
|
|
817
979
|
*/
|
|
818
980
|
async queryRevocations() {
|
|
819
981
|
this.ensureInitialized();
|
|
820
982
|
const rows = [];
|
|
821
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
|
+
}
|
|
822
987
|
rows.push({
|
|
823
988
|
tableName: row.TableName,
|
|
824
989
|
rowKey: row.RowKey,
|
|
@@ -1024,11 +1189,126 @@ export class ControlDatabase {
|
|
|
1024
1189
|
* The remove digest binds only (Id, StampId) — not Type/MemberPrivateKey — so this
|
|
1025
1190
|
* works identically for open and closed strands.
|
|
1026
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
|
+
*
|
|
1027
1201
|
* A no-op (no throw, no tombstone) when the row does not exist — `false` then, `true`
|
|
1028
1202
|
* when a row was actually removed.
|
|
1029
1203
|
*/
|
|
1030
1204
|
deleteStrand(strandId, ownerKey, signMessage) {
|
|
1031
|
-
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');
|
|
1032
1312
|
}
|
|
1033
1313
|
/**
|
|
1034
1314
|
* Insert a validation key into the control database using an owner signature.
|
|
@@ -1309,16 +1589,26 @@ export class ControlDatabase {
|
|
|
1309
1589
|
`, [ownerKey, revocationSignature, table, keyValue, stampId]);
|
|
1310
1590
|
});
|
|
1311
1591
|
log('%s deleted: %s (stamp retired)', table, keyValue);
|
|
1312
|
-
|
|
1313
|
-
try {
|
|
1314
|
-
this.guardedDeleteListener({ tableName: table, rowKey: keyValue, stampId });
|
|
1315
|
-
}
|
|
1316
|
-
catch (error) {
|
|
1317
|
-
log('guarded-delete listener threw (committed delete unaffected): %o', error);
|
|
1318
|
-
}
|
|
1319
|
-
}
|
|
1592
|
+
this.notifyGuardedDelete({ tableName: table, rowKey: keyValue, stampId });
|
|
1320
1593
|
return true;
|
|
1321
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
|
+
}
|
|
1322
1612
|
/**
|
|
1323
1613
|
* Delete one guarded row that an ALREADY-COMMITTED `Revocation` tombstone retires —
|
|
1324
1614
|
* the local catch-up for a node that converged on a removal's tombstone while still
|
|
@@ -1427,8 +1717,9 @@ export class ControlDatabase {
|
|
|
1427
1717
|
*
|
|
1428
1718
|
* Two rows are deliberately left alone:
|
|
1429
1719
|
*
|
|
1430
|
-
* - **Tables outside {@link REAPABLE_TABLES}** (`Strand`, `OwnerKey`)
|
|
1431
|
-
* 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.
|
|
1432
1723
|
* - **This node's OWN `CadrePeer` / `DeviceToken` row** (`selfPeerId`). Reaping it would
|
|
1433
1724
|
* fight this node's own re-registration: `registerSelf` / `retouchSelfDeviceToken` run
|
|
1434
1725
|
* on the heartbeat and the growth drain, and after a self-reap their insert-if-absent
|
|
@@ -1448,8 +1739,11 @@ export class ControlDatabase {
|
|
|
1448
1739
|
* skip-self rule is exercisable without one.
|
|
1449
1740
|
*
|
|
1450
1741
|
* NOTE: cost is O(tombstones), not O(live rows) — one {@link queryRevocations} scan plus
|
|
1451
|
-
* one {@link queryStampId} point lookup per tombstone, and the empty
|
|
1452
|
-
*
|
|
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.
|
|
1453
1747
|
* But `Revocation` is append-only and unbounded, so this is O(all tombstones ever) point
|
|
1454
1748
|
* lookups on every reconcile tick. Fine while revocations stay rare for a cadre-sized
|
|
1455
1749
|
* party; if the table ever grows, persist a node-local high-water mark of what has
|
|
@@ -1556,6 +1850,74 @@ export class ControlDatabase {
|
|
|
1556
1850
|
return executed;
|
|
1557
1851
|
}, {}, 'revocation-reissue');
|
|
1558
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
|
+
}
|
|
1559
1921
|
/**
|
|
1560
1922
|
* Run `body` between `beginTransaction` and `commit`, rolling back on failure.
|
|
1561
1923
|
*
|
|
@@ -1616,6 +1978,19 @@ export class ControlDatabase {
|
|
|
1616
1978
|
setGuardedDeleteListener(listener) {
|
|
1617
1979
|
this.guardedDeleteListener = listener;
|
|
1618
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
|
+
}
|
|
1619
1994
|
/**
|
|
1620
1995
|
* Run a `CadrePeer` row mutation and notify the membership listener once it has
|
|
1621
1996
|
* COMMITTED.
|
|
@@ -1700,10 +2075,26 @@ export class ControlDatabase {
|
|
|
1700
2075
|
async withWriteLock(fn) {
|
|
1701
2076
|
// Chain behind the current tail regardless of how it settled, then park a
|
|
1702
2077
|
// swallowed copy as the new tail so one failed write never poisons the queue.
|
|
1703
|
-
const
|
|
2078
|
+
const body = () => this.runWriteBody(fn);
|
|
2079
|
+
const run = this.writeQueue.then(body, body);
|
|
1704
2080
|
this.writeQueue = run.then(() => undefined, () => undefined);
|
|
1705
2081
|
return run;
|
|
1706
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
|
+
}
|
|
1707
2098
|
/**
|
|
1708
2099
|
* {@link withWriteLock} plus the bounded transient-failure retry
|
|
1709
2100
|
* ({@link retryControlWrite}) — the wrapper the whole public write surface goes
|
|
@@ -1727,12 +2118,24 @@ export class ControlDatabase {
|
|
|
1727
2118
|
* `label` names the operation in this loop's debug lines and nothing else
|
|
1728
2119
|
* ({@link ControlWriteRetryOptions.label}). Every call site in this class supplies one:
|
|
1729
2120
|
* several writes retry CONCURRENTLY in a real party, so an unlabelled line cannot be
|
|
1730
|
-
* 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.
|
|
1731
2127
|
*/
|
|
1732
2128
|
lockedWithRetry(fn, policy = {}, label) {
|
|
1733
2129
|
// The label lands LAST so a call site's own name survives both the policy and the
|
|
1734
2130
|
// spec-injected pacing; it changes log attribution only, never behaviour.
|
|
1735
|
-
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
|
+
});
|
|
1736
2139
|
}
|
|
1737
2140
|
/**
|
|
1738
2141
|
* One-statement local write, serialized by {@link withWriteLock} and retried on a
|
|
@@ -2096,22 +2499,19 @@ export class ControlDatabase {
|
|
|
2096
2499
|
/**
|
|
2097
2500
|
* Count `FormationUsage` rows recorded against a token (uses consumed so far).
|
|
2098
2501
|
*
|
|
2099
|
-
*
|
|
2100
|
-
* the
|
|
2101
|
-
*
|
|
2102
|
-
*
|
|
2103
|
-
*
|
|
2104
|
-
*
|
|
2105
|
-
*
|
|
2106
|
-
*
|
|
2107
|
-
*
|
|
2108
|
-
*
|
|
2109
|
-
*
|
|
2110
|
-
*
|
|
2111
|
-
*
|
|
2112
|
-
* `schemas/control.qsql`, and the engine defect in
|
|
2113
|
-
* `blocked/secondary-index-seek-blind-to-sibling-rows`. Do NOT re-declare the index to
|
|
2114
|
-
* 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.
|
|
2115
2515
|
*
|
|
2116
2516
|
* `retry: false` is passed only by {@link assertSeatRemains}, which runs INSIDE a
|
|
2117
2517
|
* locked write body — same per-call opt-out, and for the same reason, as
|