@serfab/cadre-core 1.22.0 → 1.24.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.
Files changed (314) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +159 -53
  8. package/dist/cadre-node.js +276 -89
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +6 -3
  82. package/dist/membership-view.js.map +1 -1
  83. package/dist/node-claim-payload.d.ts +15 -7
  84. package/dist/node-claim-payload.js +25 -9
  85. package/dist/node-claim-payload.js.map +1 -1
  86. package/dist/node-class.d.ts +36 -0
  87. package/dist/node-class.js +26 -0
  88. package/dist/node-class.js.map +1 -0
  89. package/dist/node-default-transports.d.ts +50 -3
  90. package/dist/node-default-transports.js +48 -3
  91. package/dist/node-default-transports.js.map +1 -1
  92. package/dist/node-roles.d.ts +118 -0
  93. package/dist/node-roles.js +142 -0
  94. package/dist/node-roles.js.map +1 -0
  95. package/dist/node-transports.d.ts +6 -2
  96. package/dist/node-transports.js +39 -7
  97. package/dist/node-transports.js.map +1 -1
  98. package/dist/owner-anchor-sync.js +1 -1
  99. package/dist/owner-key-export.js +1 -1
  100. package/dist/owner-key-flows.d.ts +1 -1
  101. package/dist/owner-key-store.js +1 -1
  102. package/dist/owner-signer.js +1 -1
  103. package/dist/peer-authorization.d.ts +3 -1
  104. package/dist/peer-authorization.js +3 -1
  105. package/dist/peer-authorization.js.map +1 -1
  106. package/dist/peer-dial.d.ts +74 -10
  107. package/dist/peer-dial.js +89 -17
  108. package/dist/peer-dial.js.map +1 -1
  109. package/dist/peer-join-backfill.js +4 -4
  110. package/dist/peer-join-backfill.js.map +1 -1
  111. package/dist/peer-record.d.ts +34 -9
  112. package/dist/peer-record.js +66 -13
  113. package/dist/peer-record.js.map +1 -1
  114. package/dist/pending-join-runner.d.ts +1 -1
  115. package/dist/pending-join-runner.js +1 -1
  116. package/dist/provider/client.d.ts +6 -5
  117. package/dist/provider/client.js +3 -3
  118. package/dist/provider/client.js.map +1 -1
  119. package/dist/provider/descriptor.d.ts +1 -1
  120. package/dist/provider/descriptor.js +1 -1
  121. package/dist/provider/oauth.d.ts +1 -1
  122. package/dist/provider/oauth.js +1 -1
  123. package/dist/provider/rent-node.d.ts +4 -3
  124. package/dist/provider/rent-node.js +3 -3
  125. package/dist/provider/rent-node.js.map +1 -1
  126. package/dist/relay-addrs.d.ts +62 -7
  127. package/dist/relay-addrs.js +74 -11
  128. package/dist/relay-addrs.js.map +1 -1
  129. package/dist/relay-reservation.d.ts +1 -1
  130. package/dist/relay-reservation.js +1 -1
  131. package/dist/relay-server.d.ts +6 -5
  132. package/dist/relay-server.js +5 -5
  133. package/dist/relay-server.js.map +1 -1
  134. package/dist/schema-verification.d.ts +13 -10
  135. package/dist/schema-verification.js +32 -24
  136. package/dist/schema-verification.js.map +1 -1
  137. package/dist/sealed-party-key.js +1 -1
  138. package/dist/seed-bootstrap.d.ts +4 -3
  139. package/dist/seed-bootstrap.js +6 -7
  140. package/dist/seed-bootstrap.js.map +1 -1
  141. package/dist/strand-addr-protocol.d.ts +8 -6
  142. package/dist/strand-addr-protocol.js +12 -10
  143. package/dist/strand-addr-protocol.js.map +1 -1
  144. package/dist/strand-app-schema-report.d.ts +16 -2
  145. package/dist/strand-app-schema-report.js +15 -0
  146. package/dist/strand-app-schema-report.js.map +1 -1
  147. package/dist/strand-cohort.d.ts +1 -4
  148. package/dist/strand-cohort.js.map +1 -1
  149. package/dist/strand-commit-durability.d.ts +1 -1
  150. package/dist/strand-database.d.ts +13 -6
  151. package/dist/strand-database.js +17 -9
  152. package/dist/strand-database.js.map +1 -1
  153. package/dist/strand-first-sync-gate.d.ts +3 -2
  154. package/dist/strand-first-sync-gate.js +3 -2
  155. package/dist/strand-first-sync-gate.js.map +1 -1
  156. package/dist/strand-formation-deadlines.d.ts +2 -2
  157. package/dist/strand-formation-deadlines.js +2 -2
  158. package/dist/strand-formation-protocol.d.ts +1 -1
  159. package/dist/strand-formation-protocol.js +51 -16
  160. package/dist/strand-formation-protocol.js.map +1 -1
  161. package/dist/strand-instance-manager.d.ts +134 -42
  162. package/dist/strand-instance-manager.js +331 -76
  163. package/dist/strand-instance-manager.js.map +1 -1
  164. package/dist/strand-membership-reconciler.d.ts +8 -3
  165. package/dist/strand-membership-reconciler.js +8 -3
  166. package/dist/strand-membership-reconciler.js.map +1 -1
  167. package/dist/strand-membership-writer.d.ts +2 -2
  168. package/dist/strand-membership-writer.js +41 -39
  169. package/dist/strand-membership-writer.js.map +1 -1
  170. package/dist/strand-move.js +1 -1
  171. package/dist/strand-network-config.d.ts +15 -5
  172. package/dist/strand-network-config.js +7 -6
  173. package/dist/strand-network-config.js.map +1 -1
  174. package/dist/strand-party-key-rotation.d.ts +7 -3
  175. package/dist/strand-party-key-rotation.js +7 -3
  176. package/dist/strand-party-key-rotation.js.map +1 -1
  177. package/dist/strand-party-machines.d.ts +19 -8
  178. package/dist/strand-party-machines.js +26 -11
  179. package/dist/strand-party-machines.js.map +1 -1
  180. package/dist/strand-party-peers.d.ts +36 -14
  181. package/dist/strand-party-peers.js +24 -15
  182. package/dist/strand-party-peers.js.map +1 -1
  183. package/dist/strand-peer-redial.d.ts +1 -1
  184. package/dist/strand-peer-redial.js +1 -1
  185. package/dist/strand-reactivity.d.ts +20 -17
  186. package/dist/strand-reactivity.js +31 -18
  187. package/dist/strand-reactivity.js.map +1 -1
  188. package/dist/strand-revocation-enforcer.d.ts +3 -3
  189. package/dist/strand-revocation-enforcer.js +3 -3
  190. package/dist/strand-wake-protocol.d.ts +19 -7
  191. package/dist/strand-wake-protocol.js +22 -10
  192. package/dist/strand-wake-protocol.js.map +1 -1
  193. package/dist/strand-watcher.d.ts +1 -1
  194. package/dist/strand-watcher.js +1 -1
  195. package/dist/table-change-watch.js +1 -1
  196. package/dist/types.d.ts +127 -57
  197. package/dist/types.js.map +1 -1
  198. package/dist/webrtc-upgrade.d.ts +254 -0
  199. package/dist/webrtc-upgrade.js +355 -0
  200. package/dist/webrtc-upgrade.js.map +1 -0
  201. package/package.json +9 -9
  202. package/src/announce-addrs.ts +93 -93
  203. package/src/arachnode-stub.ts +18 -10
  204. package/src/bootstrap-peer-store-file.ts +44 -44
  205. package/src/bootstrap-peer-store.ts +214 -214
  206. package/src/cadre-invite-protocol.ts +741 -740
  207. package/src/cadre-node.ts +12462 -12252
  208. package/src/claim-proof.ts +147 -147
  209. package/src/control-authorization.ts +290 -276
  210. package/src/control-cohort.ts +223 -204
  211. package/src/control-database.ts +72 -28
  212. package/src/control-formation-recorder.ts +359 -359
  213. package/src/control-protocol-guard.ts +370 -366
  214. package/src/control-read-retry.ts +222 -180
  215. package/src/control-retry.ts +36 -4
  216. package/src/control-schema-version.ts +301 -301
  217. package/src/control-schema.ts +1108 -1087
  218. package/src/control-write-retry.ts +639 -669
  219. package/src/delegate-admission.ts +351 -351
  220. package/src/describe-thrown.ts +60 -60
  221. package/src/ed25519-key.ts +185 -185
  222. package/src/edge-node/config.ts +13 -10
  223. package/src/edge-node/dissolve.ts +252 -252
  224. package/src/edge-node/edge-join.ts +320 -320
  225. package/src/edge-node/edge-node.ts +1095 -1095
  226. package/src/edge-node/index.ts +60 -59
  227. package/src/edge-node/join-credential.ts +16 -16
  228. package/src/edge-node/lazy-raw-storage.ts +194 -178
  229. package/src/edge-node/listen-addrs.ts +26 -0
  230. package/src/edge-node/node-local.ts +84 -84
  231. package/src/edge-node/options.ts +195 -195
  232. package/src/edge-node/owner-grant.ts +63 -63
  233. package/src/edge-node/platform.ts +5 -4
  234. package/src/edge-node/strand-move.ts +266 -266
  235. package/src/edge-node/strands.ts +27 -12
  236. package/src/enrolled-machine-store-file.ts +43 -43
  237. package/src/enrolled-machine-store.ts +280 -280
  238. package/src/fetch-impl.ts +23 -23
  239. package/src/file-durable-slot.ts +64 -64
  240. package/src/file-safe-name.ts +32 -32
  241. package/src/formation-approval.ts +604 -604
  242. package/src/formation-token.ts +63 -63
  243. package/src/fs-atomic.ts +92 -92
  244. package/src/index.ts +987 -957
  245. package/src/invitation-bootstrap.ts +152 -118
  246. package/src/joined-strand-store.ts +553 -553
  247. package/src/key-store-file.ts +142 -142
  248. package/src/link-budget.ts +61 -5
  249. package/src/machine-removal.ts +211 -210
  250. package/src/member-redemption.ts +643 -643
  251. package/src/membership-connection-gater.ts +650 -650
  252. package/src/membership-view.ts +147 -144
  253. package/src/node-claim-payload.ts +34 -12
  254. package/src/node-class.ts +47 -0
  255. package/src/node-default-transports.ts +65 -3
  256. package/src/node-roles.ts +220 -0
  257. package/src/node-transports.ts +86 -49
  258. package/src/owner-anchor-sync.ts +172 -172
  259. package/src/owner-grant-protocol.ts +547 -547
  260. package/src/owner-key-export.ts +348 -348
  261. package/src/owner-key-flows.ts +109 -109
  262. package/src/owner-key-store.ts +1 -1
  263. package/src/owner-keys.ts +179 -179
  264. package/src/owner-signer.ts +92 -92
  265. package/src/peer-addr-book.ts +252 -252
  266. package/src/peer-authorization.ts +584 -582
  267. package/src/peer-dial.ts +698 -605
  268. package/src/peer-join-backfill.ts +961 -961
  269. package/src/peer-record.ts +71 -16
  270. package/src/pending-join-runner.ts +798 -798
  271. package/src/primary-lan-address.ts +47 -47
  272. package/src/provider/client.ts +327 -326
  273. package/src/provider/descriptor.ts +129 -129
  274. package/src/provider/index.ts +59 -59
  275. package/src/provider/oauth.ts +285 -285
  276. package/src/provider/rent-node.ts +276 -275
  277. package/src/relay-addrs.ts +90 -12
  278. package/src/relay-reservation.ts +1 -1
  279. package/src/relay-server.ts +99 -98
  280. package/src/schema-verification.ts +38 -23
  281. package/src/sealed-party-key.ts +190 -190
  282. package/src/seed-bootstrap.ts +8 -11
  283. package/src/seed-trust-policy.ts +353 -353
  284. package/src/self-address-update.ts +19 -19
  285. package/src/strand-addr-protocol.ts +17 -14
  286. package/src/strand-app-schema-report.ts +147 -122
  287. package/src/strand-cohort.ts +1 -5
  288. package/src/strand-commit-durability.ts +165 -165
  289. package/src/strand-database.ts +522 -510
  290. package/src/strand-first-sync-gate.ts +3 -2
  291. package/src/strand-formation-deadlines.ts +227 -227
  292. package/src/strand-formation-manager.ts +731 -731
  293. package/src/strand-formation-protocol.ts +1174 -1138
  294. package/src/strand-fret-addrs.ts +179 -179
  295. package/src/strand-instance-manager.ts +381 -85
  296. package/src/strand-membership-reconciler.ts +1315 -1310
  297. package/src/strand-membership-writer.ts +2152 -2150
  298. package/src/strand-move.ts +1 -1
  299. package/src/strand-network-config.ts +16 -6
  300. package/src/strand-offline.ts +178 -178
  301. package/src/strand-party-key-rotation.ts +440 -436
  302. package/src/strand-party-machines.ts +308 -293
  303. package/src/strand-party-peers.ts +151 -129
  304. package/src/strand-peer-redial.ts +1 -1
  305. package/src/strand-reactivity.ts +36 -19
  306. package/src/strand-revocation-enforcer.ts +758 -758
  307. package/src/strand-wake-protocol.ts +406 -394
  308. package/src/strand-watcher.ts +1 -1
  309. package/src/table-change-watch.ts +285 -285
  310. package/src/timed-step.ts +28 -28
  311. package/src/timeout-scheduler.ts +29 -29
  312. package/src/trusted-owner-store.ts +242 -242
  313. package/src/types.ts +3182 -3112
  314. package/src/webrtc-upgrade.ts +439 -0
@@ -1,510 +1,522 @@
1
- import debug from 'debug';
2
- import { Database } from '@quereus/quereus';
3
- import { applyAppSchema, connectToStrand } from '@serfab/quereus-plugin-sereus';
4
- import type { SereusPluginResult, StrandOfflineController } from '@serfab/quereus-plugin-sereus';
5
- import type { Libp2p } from '@libp2p/interface';
6
- import type { ICohortReachability, IRepo } from '@optimystic/db-core';
7
- import type { IKVStore } from '@optimystic/db-p2p';
8
- import type { SAppConfig } from './types.js';
9
- import type { PartyStrandPeer } from './strand-party-peers.js';
10
- import { bootstrapFounderMembership } from './strand-membership-writer.js';
11
- import { strandMemberKeyPair } from './strand-member-key.js';
12
- import { StrandCommitRecord } from './strand-commit-durability.js';
13
- import type { StrandCommitDurability, StrandCommitListeners } from './strand-commit-durability.js';
14
- import { TableWatchRegistry } from './table-change-watch.js';
15
- import type { TableChangeWatch, TableChangeWatchOptions } from './table-change-watch.js';
16
- import { discardQueued, StrandOfflineReport } from './strand-offline.js';
17
- import type { StrandOfflineListeners, StrandOfflineMode, StrandOfflineQueue } from './strand-offline.js';
18
- import { StrandAppSchemaReport, type StrandAppSchemaListeners, type StrandAppSchemaState } from './strand-app-schema-report.js';
19
-
20
- const log = debug('sereus:cadre:strand-db');
21
- const timing = debug('sereus:cadre:timing');
22
-
23
- export interface StrandDatabaseConfig extends StrandCommitListeners {
24
- /** The strand ID */
25
- strandId: string;
26
- /**
27
- * sApp configuration containing the schema. Absent for a storage replica — a strand
28
- * this node stores and serves without the app installed: only the `Strand` membership
29
- * schema is applied, and such a database can never found (see {@link founderSApp}).
30
- */
31
- sAppConfig?: SAppConfig;
32
- /** Libp2p node for the strand network */
33
- libp2pNode: Libp2p;
34
- /** Coordinated repo from the libp2p node */
35
- coordinatedRepo: IRepo;
36
- /**
37
- * Strand type (`'o'` open / `'c'` closed) from the control-network strand row.
38
- * Drives the founder bootstrap: open strands get a `Header` only; closed strands
39
- * also get the founding `Member`+`Manager`.
40
- */
41
- strandType: 'o' | 'c';
42
- /**
43
- * The closed-strand `MemberPrivateKey` (base64 protobuf) from the strand row —
44
- * the strand-wide read secret every joining party receives. Carried for the
45
- * strand's read-gating story only; it derives NOBODY's identity (that used to be
46
- * this key's second job, which let any joiner sign as the founding manager —
47
- * gotchoices/sereus#4). Absent for open strands.
48
- */
49
- memberPrivateKey?: string;
50
- /**
51
- * THIS party's own strand membership private key (base64 protobuf), from the
52
- * control-layer `StrandPartyKey` row (or supplied explicitly at attach). Required
53
- * when `founder` is true and `strandType` is `'c'` — it derives the founding
54
- * `Member.Key`/`Manager.MemberKey`. Never shared outside the party; absent for
55
- * open strands and for joiners that have not yet persisted one.
56
- */
57
- partyMemberPrivateKey?: string;
58
- /**
59
- * Whether this node founds the strand. When true, {@link initialize} runs the
60
- * one-time founder membership bootstrap after the schema is applied. Joiners
61
- * leave this false and write nothing (rows arrive via sync). Defaults to false.
62
- */
63
- founder?: boolean;
64
- /**
65
- * Whether a closed strand's founder bootstrap also writes this machine's `Strand.MemberPeer`
66
- * binding (for `libp2pNode`'s peer id) in the founding transaction. That binding is the
67
- * membership reconciler's job; the founding run that seats the founding `Member` writes it
68
- * too, which saves the reconciler's commit. False whenever the reconciler is disarmed, so a
69
- * fixture that hand-drives the membership writers sees only the rows it wrote. Defaults to false.
70
- */
71
- bindFounderPeer?: boolean;
72
- /**
73
- * Turn on the connection's offline queue (docs/strands.md → "Offline mode"). Absent: no queue,
74
- * and {@link StrandDatabase.offline} is undefined.
75
- */
76
- offline?: StrandDatabaseOffline;
77
- /** Where to report the `App` schema apply when it is held back (docs/strands.md → "An app schema upgrade waits for the queue or the cohort"). */
78
- appSchema?: StrandAppSchemaListeners;
79
- /**
80
- * The party's other machines known to hold the strand (`StrandPartyMachines.machines`), named in
81
- * each commit's {@link StrandCommitDurability.awaitedMachines}. Absent on a node offering no
82
- * offline mode, which does not track them.
83
- */
84
- partyMachines?: () => readonly PartyStrandPeer[];
85
- }
86
-
87
- /** {@link StrandDatabaseConfig.offline}: one build's journal, the strand's mode, and where to report. */
88
- export interface StrandDatabaseOffline extends StrandOfflineListeners {
89
- /**
90
- * This build's journal, resolved by {@link StrandDatabase.initialize}, so a launch released while
91
- * it resolves is caught like one released during the rest of the build. A throw fails initialize.
92
- */
93
- journal: () => IKVStore | Promise<IKVStore>;
94
- /**
95
- * The strand's mode, read at the end of {@link StrandDatabase.initialize} and at every
96
- * {@link StrandDatabase.applyOfflineMode}, never captured, so the newest choice wins.
97
- */
98
- mode: () => StrandOfflineMode;
99
- /**
100
- * The gate the queue and offline live reads ask in place of the strand node's own: the node's
101
- * gate closed also while the party has machines holding the strand that this node is not in a
102
- * cohort with (`strand-party-machines.ts`). Absent on a node whose strand node offers no gate.
103
- */
104
- cohortReachability?: ICohortReachability;
105
- }
106
-
107
- /**
108
- * StrandDatabase manages the sApp schema for a strand using Quereus with the
109
- * Optimystic backend. Each strand instance has its own isolated database with
110
- * the sApp's schema applied.
111
- *
112
- * This class owns the `Database` lifecycle (creation, `getDatabase()`, `close()`)
113
- * but delegates the actual SQL-surface composition — plugin registration, node
114
- * wiring, catalog hydration, schema apply — to `connectToStrand` from
115
- * `@serfab/quereus-plugin-sereus`, the single shared composition. The libp2p
116
- * node is injected here, so `connectToStrand` neither creates nor stops it:
117
- * `StrandInstanceManager` owns the node lifecycle, and a failed or closed
118
- * database leaves the node running.
119
- *
120
- * One instance is one attempt: a failed {@link initialize} is closed and a new
121
- * instance built for the next attempt.
122
- */
123
- export class StrandDatabase {
124
- private db: Database | null = null;
125
- private shutdownStrand: SereusPluginResult['shutdown'] | null = null;
126
- private resolvedTransactor: SereusPluginResult['transactor'] | null = null;
127
- private createEmptyCollections: SereusPluginResult['createEmptyCollections'] | null = null;
128
- private readonly config: StrandDatabaseConfig;
129
- private initialized = false;
130
- private readonly commits: StrandCommitRecord;
131
- private unsubscribeCommits: (() => void) | null = null;
132
- private offlineQueue: StrandOfflineController | null = null;
133
- private offlineReport: StrandOfflineReport | null = null;
134
- private appSchemaReport: StrandAppSchemaReport | null = null;
135
- /** Subscriptions handed out by {@link watchTables}. */
136
- private readonly tableWatches = new TableWatchRegistry();
137
-
138
- constructor(config: StrandDatabaseConfig) {
139
- this.config = config;
140
- this.commits = new StrandCommitRecord(config.strandId, config, config.partyMachines);
141
- }
142
-
143
- /**
144
- * Initialize the database — create the `Database` and delegate the strand
145
- * SQL-surface composition (plugins, node wiring, hydrate, schema apply) to
146
- * `connectToStrand` with the injected libp2p node.
147
- */
148
- async initialize(): Promise<void> {
149
- if (this.initialized) {
150
- log('StrandDatabase for strand %s already initialized', this.config.strandId);
151
- return;
152
- }
153
-
154
- const sid = this.config.strandId;
155
- const { sAppConfig } = this.config;
156
- if (this.config.founder === true) {
157
- // Before composing anything: a founder that cannot write its Header must not
158
- // leave a half-built connection behind.
159
- this.founderSApp();
160
- }
161
- log('Initializing StrandDatabase for strand: %s (%s)', sid,
162
- sAppConfig ? `sApp: ${sAppConfig.id} v${sAppConfig.version}` : 'storage replica');
163
-
164
- const offline = this.config.offline && { journal: await this.config.offline.journal() };
165
- const cohortReachability = this.config.offline?.cohortReachability;
166
- this.db = new Database();
167
-
168
- // Delegate to the shared composition. The node is injected, so:
169
- // - `connectToStrand` never creates or stops a node; `StrandInstanceManager`
170
- // owns the node lifecycle;
171
- // - no `storage` is passed: the plugin consumes it only to build a local
172
- // transactor's raw-storage factory or to create a node it was not given,
173
- // and cadre-core always injects the node and runs the network transactor.
174
- // (The plugin keeps its `storage` option for the browser entry point.)
175
- const t0 = performance.now();
176
- //
177
- // A storage replica passes no schema, so no `App` tables are declared. A warm restart's
178
- // hydrate may still load `App` table definitions persisted in the replicated store into
179
- // the catalog — declarative metadata, nothing the app supplied runs — and the first-sync
180
- // probe then reads those tables once from blocks this node holds.
181
- const result = await connectToStrand(this.db, {
182
- strandId: sid,
183
- schema: sAppConfig?.schema,
184
- libp2pNode: this.config.libp2pNode,
185
- coordinatedRepo: this.config.coordinatedRepo,
186
- enableCache: true,
187
- offline,
188
- ...(cohortReachability && { cohortReachability }),
189
- });
190
- this.shutdownStrand = result.shutdown;
191
- this.resolvedTransactor = result.transactor;
192
- this.createEmptyCollections = result.createEmptyCollections;
193
- // Before the founder bootstrap, so its commits are reported like any other.
194
- this.subscribeToCommits(result);
195
- this.followOffline(result);
196
- this.appSchemaReport = new StrandAppSchemaReport(sid, this.config.appSchema ?? {}, result);
197
- timing('[strandDb:%s] connectToStrand: %dms (hydrated tables=%d, indexes=%d)',
198
- sid, Math.round(performance.now() - t0),
199
- result.hydrated?.tables ?? 0, result.hydrated?.indexes ?? 0);
200
-
201
- // Founder-only: write the one-time membership bootstrap now that the schema is
202
- // applied (connectToStrand has returned). A throw here propagates out of
203
- // initialize(), and the caller closes this half-built database (close() runs the
204
- // composition's shutdown). Joiners skip this — their rows arrive via sync.
205
- // NOTE: a bootstrap with rows to write while `hydrate` restored queued transactions is refused
206
- // (`StrandOfflineQueueBusyError`), failing every build, so that queue could never drain. Not
207
- // reachable today: rows are written only while the founding is incomplete (Member empty, or no
208
- // Manager and none retired), and an incomplete founding fails the build before the database is
209
- // ever published for the app to queue in. If a founder is ever published with its founding
210
- // incomplete, skip the bootstrap here while the queue is non-empty and run it once the queue drains.
211
- if (this.config.founder === true) {
212
- await this.bootstrapFounder();
213
- }
214
-
215
- // After `hydrate` restored the queue and after the founder bootstrap (its `Strand` writes are
216
- // network-acknowledged in either mode); before the first-sync probe, so in offline mode a read
217
- // the cohort cannot answer is served from this machine's copy there as it is to the app.
218
- this.applyOfflineMode();
219
- this.initialized = true;
220
- log('StrandDatabase for strand %s initialized successfully', sid);
221
- }
222
-
223
- private subscribeToCommits(result: SereusPluginResult): void {
224
- const unsubscribeDurability = result.onCommitDurability(report => this.commits.reportCommit(report));
225
- const unsubscribeHeld = result.onCommitFullyHeld(event => this.commits.reportHeld(event));
226
- this.unsubscribeCommits = () => {
227
- unsubscribeDurability();
228
- unsubscribeHeld();
229
- };
230
- }
231
-
232
- private followOffline(result: SereusPluginResult): void {
233
- const { offline } = this.config;
234
- if (!offline) {
235
- return;
236
- }
237
- this.offlineQueue = result.offline ?? null;
238
- this.offlineReport = new StrandOfflineReport(this.config.strandId, offline, result.offline);
239
- }
240
-
241
- /**
242
- * Put the queue in the strand's current mode ({@link StrandDatabaseOffline.mode}). It sets the
243
- * acknowledgement of transactions begun from now on; an open one keeps the one it began with.
244
- * No-op without a queue, and before {@link initialize} has composed one (it applies the mode itself).
245
- */
246
- applyOfflineMode(): void {
247
- const queue = this.offlineQueue;
248
- if (!queue || !this.config.offline) {
249
- return;
250
- }
251
- if (this.config.offline.mode() === 'offline') {
252
- queue.enter();
253
- } else {
254
- queue.exit();
255
- }
256
- }
257
-
258
- /**
259
- * The database was handed to the app (`StrandInstanceManager.publishDatabase`): report the
260
- * queue's state, since restored transactions' `queued` statuses were delivered before anything
261
- * subscribed, and an `App` schema apply still held back.
262
- */
263
- reportPublished(): void {
264
- this.offlineReport?.published();
265
- this.appSchemaReport?.published();
266
- }
267
-
268
- /**
269
- * Run the founder membership bootstrap against the freshly-composed strand DB.
270
- *
271
- * Derives the founding keypair from this PARTY's own `partyMemberPrivateKey` (the
272
- * `Member.Key`/`Manager.MemberKey` are its public key) — deliberately NOT from the
273
- * strand row's shared `MemberPrivateKey`, which every joining party receives and could
274
- * therefore use to forge the founder's identity. A closed strand with no
275
- * `partyMemberPrivateKey` throws, because it could never seat a founding manager.
276
- * The shared key's public half IS passed, but only so the bootstrap can refuse a strand
277
- * founded under it before the split (`PreSplitStrandIdentityError`). The strand node's
278
- * peer id is passed under {@link StrandDatabaseConfig.bindFounderPeer}: the same node, so
279
- * the same id, the membership reconciler binds. Open strands derive no keypair (Header
280
- * only). Idempotent — see {@link bootstrapFounderMembership}.
281
- */
282
- private async bootstrapFounder(): Promise<void> {
283
- const { strandId, strandType, memberPrivateKey, partyMemberPrivateKey, libp2pNode, bindFounderPeer } = this.config;
284
- const closed = strandType === 'c';
285
- await bootstrapFounderMembership(this.db!, {
286
- strandId,
287
- type: strandType,
288
- sApp: this.founderSApp(),
289
- founderKeyPair: closed ? this.deriveFounderKeyPair(strandId, partyMemberPrivateKey) : undefined,
290
- sharedMemberPublicKey: closed && memberPrivateKey
291
- ? strandMemberKeyPair(memberPrivateKey).publicKeyB64
292
- : undefined,
293
- founderPeerId: closed && bindFounderPeer === true ? libp2pNode.peerId.toString() : undefined,
294
- createEmptyCollections: this.createEmptyCollections!,
295
- });
296
- }
297
-
298
- /**
299
- * The sApp a founder bootstrap records in the `Strand.Header`. Throws for a storage
300
- * replica (no sApp config): its Header's sApp columns would have nothing to say.
301
- * `CadreNode` always launches a replica as a joiner, so this guards a future caller.
302
- */
303
- private founderSApp(): SAppConfig {
304
- const { sAppConfig, strandId } = this.config;
305
- if (!sAppConfig) {
306
- throw new Error(
307
- `Cannot found strand ${strandId} as a storage replica: the founder bootstrap writes ` +
308
- 'the sApp id and version into Strand.Header, and a replica has no sApp config.',
309
- );
310
- }
311
- return sAppConfig;
312
- }
313
-
314
- /**
315
- * Derive the founding keypair for a closed strand from the party's own
316
- * `partyMemberPrivateKey`, failing loudly when the key is absent (a closed strand
317
- * with no founding Manager can never admit anyone).
318
- */
319
- private deriveFounderKeyPair(strandId: string, partyMemberPrivateKey: string | undefined) {
320
- if (!partyMemberPrivateKey) {
321
- throw new Error(
322
- `Cannot found closed strand ${strandId}: this party has no StrandPartyKey for it. ` +
323
- 'A closed strand needs a founding Member/Manager derived from the party\'s own ' +
324
- 'membership key (minted when the strand is published, or at the founder launch for ' +
325
- 'a closed row stored without one) — the shared MemberPrivateKey deliberately ' +
326
- 'no longer derives anyone\'s identity.',
327
- );
328
- }
329
- return strandMemberKeyPair(partyMemberPrivateKey);
330
- }
331
-
332
- /**
333
- * Run the founder membership bootstrap against an ALREADY-LIVE database — the
334
- * seam {@link StrandInstanceManager.foundExistingStrand} uses when a founder
335
- * request arrives for an instance that was first launched as a joiner.
336
- * Idempotent: every bootstrap write is insert-if-absent
337
- * ({@link bootstrapFounderMembership}), so calling it on an instance that
338
- * already founded writes nothing. On success also flips the captured config's
339
- * `founder`, so this object's own record of how it was launched stays coherent
340
- * with what actually ran (a construction-time `founder: false` is a statement
341
- * about the launch, not a permanent identity); a refused bootstrap leaves it a joiner.
342
- *
343
- * @param partyMemberPrivateKey - The party's own membership key, for a closed strand
344
- * whose original (joiner) launch resolved none — e.g. the `StrandPartyKey` row had
345
- * not been written or replicated yet. The captured config's key wins when both
346
- * exist: it is the identity this instance launched under.
347
- */
348
- async ensureFounderBootstrap(partyMemberPrivateKey?: string): Promise<void> {
349
- this.ensureInitialized();
350
- this.config.partyMemberPrivateKey ??= partyMemberPrivateKey;
351
- await this.bootstrapFounder();
352
- this.config.founder = true;
353
- }
354
-
355
- /**
356
- * Give a live storage replica the app's schema: apply `App` to the already-composed
357
- * database — same libp2p node, same store, so the new tables read the blocks this node
358
- * already holds — and record the sApp, so a later {@link ensureFounderBootstrap} has it
359
- * for the `Header`. Idempotent: the apply is a declarative diff, so re-applying the same
360
- * schema emits nothing. A failed apply records nothing.
361
- */
362
- async attachAppSchema(sAppConfig: SAppConfig): Promise<void> {
363
- this.ensureInitialized();
364
- // NOTE: unlike the connect-time apply (`applyAppSchemaAfterQueue`), this is not deferred behind
365
- // the offline queue: a replica writes no app transactions, so no queued transaction wrote an
366
- // `App` table and `QueuedEntriesBlockSchemaChangeError` cannot refuse it. If a replica ever
367
- // writes app rows offline, route this through the deferral instead of throwing.
368
- await applyAppSchema(this.db!, sAppConfig.schema);
369
- this.config.sAppConfig = sAppConfig;
370
- log('StrandDatabase for strand %s attached sApp %s v%s', this.config.strandId, sAppConfig.id, sAppConfig.version);
371
- }
372
-
373
- /**
374
- * Get the underlying database for queries
375
- */
376
- getDatabase(): Database {
377
- this.ensureInitialized();
378
- return this.db!;
379
- }
380
-
381
- /**
382
- * Subscribe `onChange` to changes in this strand's tables (`'Strand.Member'`, …): commits
383
- * made here and changes replicated into this node's storage alike, on the single-flight
384
- * schedule `table-change-watch.ts` describes. {@link close} disposes every subscription
385
- * still live; a hibernated strand's database is closed and rebuilt on wake, so a consumer
386
- * subscribes again on the new instance.
387
- */
388
- watchTables(tables: readonly string[], onChange: () => Promise<void>, options: TableChangeWatchOptions): TableChangeWatch {
389
- this.ensureInitialized();
390
- return this.tableWatches.watch(this.db!, tables, onChange, options);
391
- }
392
-
393
- /**
394
- * The durability of a recent commit on this database, by its `StampId()` — the id a single
395
- * `insert … returning StampId() as Tx` statement returns. Read it after that statement
396
- * resolves: the plugin reports the commit before the statement returns, and a commit already
397
- * held everywhere is marked held by then too. `undefined` for a commit that wrote nothing, one
398
- * made before this database was built, or one more than 256 commits back. Each value is a
399
- * snapshot: read again after `strand:commit-held` to see the change.
400
- */
401
- commitDurability(transactionId: string): StrandCommitDurability | undefined {
402
- this.ensureInitialized();
403
- return this.commits.get(transactionId);
404
- }
405
-
406
- /**
407
- * The strand connection's offline queue (docs/strands.md → "Offline mode"), or `undefined` on a
408
- * node without `strandOffline`. The mode is set through `CadreNode.setStrandOfflineMode`, which
409
- * outlives this database; listeners taken here die with it, as {@link watchTables} subscriptions do.
410
- */
411
- get offline(): StrandOfflineQueue | undefined {
412
- this.ensureInitialized();
413
- return this.offlineQueue ?? undefined;
414
- }
415
-
416
- /**
417
- * Whether this database runs the `App` schema its launch was given. `'waiting-for-queue'` or
418
- * `'waiting-for-cohort'` while the apply is held back, so `StrandInstance.sAppInfo` names a version
419
- * whose new tables or columns may not be usable yet; check this before relying on them.
420
- */
421
- appSchemaState(): StrandAppSchemaState {
422
- this.ensureInitialized();
423
- return this.appSchemaReport?.appSchemaState() ?? 'applied';
424
- }
425
-
426
- /**
427
- * The transaction ids the offline queue lists (`entries()`, the ones a restore has not put back
428
- * yet included), or `undefined` with no queue: none configured, not composed yet, or closed.
429
- * Unlike {@link offline} it does not require {@link initialize} to have finished, so the manager
430
- * can read a database still being built or about to close.
431
- */
432
- queuedTransactionIds(): readonly string[] | undefined {
433
- return this.offlineQueue?.entries().map((entry) => entry.transactionId);
434
- }
435
-
436
- /** {@link discardQueued} on this database's queue; `undefined` with no queue, as {@link queuedTransactionIds}. */
437
- discardQueuedTransactions(): readonly string[] | undefined {
438
- return this.offlineQueue ? discardQueued(this.offlineQueue) : undefined;
439
- }
440
-
441
- /**
442
- * The Optimystic transactor this strand's connection resolved to — always
443
- * `'network'` here, since cadre-core passes no `transactor` option and takes
444
- * the plugin's default. Exposed so a spec measuring or asserting the network
445
- * path (`strand-solo-write-budget.spec.ts`) can pin the engine it ran on
446
- * rather than assume it.
447
- */
448
- getTransactor(): SereusPluginResult['transactor'] {
449
- this.ensureInitialized();
450
- return this.resolvedTransactor!;
451
- }
452
-
453
- /**
454
- * Close the database and cleanup resources. Closes the Quereus `Database` and waits for it
455
- * (it stops every running statement and open iterator and resolves once nothing reads or
456
- * writes), then runs the strand-connection shutdown (collection-factory teardown; the
457
- * injected node keeps running), so no statement reaches released storage. Safe on an
458
- * instance whose {@link initialize} failed part-way.
459
- *
460
- * The handle stays set across the awaits, so a second, concurrent close (a build released
461
- * part-way closes its database again) awaits the same Quereus teardown rather than skipping
462
- * ahead to the strand shutdown, which is safe to run twice (each release it makes is
463
- * idempotent, and the storage-cache release is latched). A rejected Quereus close is logged and the
464
- * teardown goes on, because callers stop the strand's node once this resolves.
465
- *
466
- * NOTE: this makes `close()` wait on a statement in a network wait, bounded by Optimystic's
467
- * RPC deadlines; the strand shutdown aborts no in-flight request, so closing it first never
468
- * cut that wait short. Revisit (abort in-flight collection work before closing Quereus) if
469
- * strand stops show up slow.
470
- *
471
- * NOTE: the plugin raises the commit-durability and commit-held reports from inside the
472
- * committing statement, but through listeners nobody awaits, so an app handler that starts
473
- * `stopStrand` does not make the statement wait for this close. If a delivery path ever
474
- * awaits its listeners, a stop started from one waits for itself and never resolves.
475
- */
476
- async close(): Promise<void> {
477
- // First, so an event from the closing connection reaches no app handler or table watch.
478
- this.unsubscribeCommits?.();
479
- this.unsubscribeCommits = null;
480
- this.offlineReport?.release();
481
- this.offlineReport = null;
482
- this.appSchemaReport?.release();
483
- this.appSchemaReport = null;
484
- this.offlineQueue = null;
485
- this.tableWatches.disposeAll();
486
- if (this.db) {
487
- try {
488
- await this.db.close();
489
- } catch (err) {
490
- log('Closing the Quereus database for strand %s failed; shutting the strand connection down anyway: %O', this.config.strandId, err);
491
- }
492
- }
493
- if (this.shutdownStrand) {
494
- await this.shutdownStrand();
495
- this.shutdownStrand = null;
496
- }
497
- // Again: a subscription taken during the awaits above would keep its timers past close.
498
- this.tableWatches.disposeAll();
499
- this.db = null;
500
- this.resolvedTransactor = null;
501
- this.initialized = false;
502
- log('StrandDatabase for strand %s closed', this.config.strandId);
503
- }
504
-
505
- private ensureInitialized(): void {
506
- if (!this.initialized || !this.db) {
507
- throw new Error(`StrandDatabase for strand ${this.config.strandId} not initialized. Call initialize() first.`);
508
- }
509
- }
510
- }
1
+ import debug from 'debug';
2
+ import { Database } from '@quereus/quereus';
3
+ import { connectToStrand } from '@serfab/quereus-plugin-sereus';
4
+ import type { SereusPluginResult, StrandOfflineController } from '@serfab/quereus-plugin-sereus';
5
+ import type { Libp2p } from '@libp2p/interface';
6
+ import type { ICohortReachability, IRepo } from '@optimystic/db-core';
7
+ import type { IKVStore } from '@optimystic/db-p2p';
8
+ import type { SAppConfig } from './types.js';
9
+ import type { PartyStrandPeer } from './strand-party-peers.js';
10
+ import { bootstrapFounderMembership } from './strand-membership-writer.js';
11
+ import { strandMemberKeyPair } from './strand-member-key.js';
12
+ import { StrandCommitRecord } from './strand-commit-durability.js';
13
+ import type { StrandCommitDurability, StrandCommitListeners } from './strand-commit-durability.js';
14
+ import { TableWatchRegistry } from './table-change-watch.js';
15
+ import type { TableChangeWatch, TableChangeWatchOptions } from './table-change-watch.js';
16
+ import { discardQueued, StrandOfflineReport } from './strand-offline.js';
17
+ import type { StrandOfflineListeners, StrandOfflineMode, StrandOfflineQueue } from './strand-offline.js';
18
+ import { StrandAppSchemaReport, type StrandAppSchemaListeners, type StrandAppSchemaState } from './strand-app-schema-report.js';
19
+
20
+ const log = debug('sereus:cadre:strand-db');
21
+ const timing = debug('sereus:cadre:timing');
22
+
23
+ export interface StrandDatabaseConfig extends StrandCommitListeners {
24
+ /** The strand ID */
25
+ strandId: string;
26
+ /**
27
+ * sApp configuration containing the schema. Absent for a storage replica — a strand
28
+ * this node stores and serves without the app installed: only the `Strand` membership
29
+ * schema is applied, and such a database can never found (see {@link founderSApp}).
30
+ */
31
+ sAppConfig?: SAppConfig;
32
+ /** Libp2p node for the strand network */
33
+ libp2pNode: Libp2p;
34
+ /**
35
+ * Coordinated repo from the libp2p node. Absent for a client node (`servesBlocks: false`),
36
+ * which stores no blocks and so coordinates no writes; the composition then builds a
37
+ * transactor that sends every read and write to a remote coordinator.
38
+ */
39
+ coordinatedRepo?: IRepo;
40
+ /**
41
+ * Strand type (`'o'` open / `'c'` closed) from the control-network strand row.
42
+ * Drives the founder bootstrap: open strands get a `Header` only; closed strands
43
+ * also get the founding `Member`+`Manager`.
44
+ */
45
+ strandType: 'o' | 'c';
46
+ /**
47
+ * The closed-strand `MemberPrivateKey` (base64 protobuf) from the strand row —
48
+ * the strand-wide read secret every joining party receives. Carried for the
49
+ * strand's read-gating story only; it derives NOBODY's identity (that used to be
50
+ * this key's second job, which let any joiner sign as the founding manager —
51
+ * gotchoices/sereus#4). Absent for open strands.
52
+ */
53
+ memberPrivateKey?: string;
54
+ /**
55
+ * THIS party's own strand membership private key (base64 protobuf), from the
56
+ * control-layer `StrandPartyKey` row (or supplied explicitly at attach). Required
57
+ * when `founder` is true and `strandType` is `'c'` — it derives the founding
58
+ * `Member.Key`/`Manager.MemberKey`. Never shared outside the party; absent for
59
+ * open strands and for joiners that have not yet persisted one.
60
+ */
61
+ partyMemberPrivateKey?: string;
62
+ /**
63
+ * Whether this node founds the strand. When true, {@link initialize} runs the
64
+ * one-time founder membership bootstrap after the schema is applied. Joiners
65
+ * leave this false and write nothing (rows arrive via sync). Defaults to false.
66
+ */
67
+ founder?: boolean;
68
+ /**
69
+ * Whether a closed strand's founder bootstrap also writes this machine's `Strand.MemberPeer`
70
+ * binding (for `libp2pNode`'s peer id) in the founding transaction. That binding is the
71
+ * membership reconciler's job; the founding run that seats the founding `Member` writes it
72
+ * too, which saves the reconciler's commit. False whenever the reconciler is disarmed, so a
73
+ * fixture that hand-drives the membership writers sees only the rows it wrote. Defaults to false.
74
+ */
75
+ bindFounderPeer?: boolean;
76
+ /**
77
+ * Turn on the connection's offline queue (docs/strands/writes.md → "Offline mode"). Absent: no queue,
78
+ * and {@link StrandDatabase.offline} is undefined.
79
+ */
80
+ offline?: StrandDatabaseOffline;
81
+ /** Where to report the `App` schema apply when it is held back (docs/strands/app-schema.md → "An app schema upgrade waits for the queue or the cohort"). */
82
+ appSchema?: StrandAppSchemaListeners;
83
+ /**
84
+ * The party's other machines known to hold the strand (`StrandPartyMachines.machines`), named in
85
+ * each commit's {@link StrandCommitDurability.awaitedMachines}. Absent on a node offering no
86
+ * offline mode, which does not track them.
87
+ */
88
+ partyMachines?: () => readonly PartyStrandPeer[];
89
+ }
90
+
91
+ /** {@link StrandDatabaseConfig.offline}: one build's journal, the strand's mode, and where to report. */
92
+ export interface StrandDatabaseOffline extends StrandOfflineListeners {
93
+ /**
94
+ * This build's journal, resolved by {@link StrandDatabase.initialize}, so a launch released while
95
+ * it resolves is caught like one released during the rest of the build. A throw fails initialize.
96
+ */
97
+ journal: () => IKVStore | Promise<IKVStore>;
98
+ /**
99
+ * The strand's mode, read at the end of {@link StrandDatabase.initialize} and at every
100
+ * {@link StrandDatabase.applyOfflineMode}, never captured, so the newest choice wins.
101
+ */
102
+ mode: () => StrandOfflineMode;
103
+ /**
104
+ * The gate the queue and offline live reads ask in place of the strand node's own: the node's
105
+ * gate closed also while the party has machines holding the strand that this node is not in a
106
+ * cohort with (`strand-party-machines.ts`). Absent on a node whose strand node offers no gate.
107
+ */
108
+ cohortReachability?: ICohortReachability;
109
+ }
110
+
111
+ /**
112
+ * StrandDatabase manages the sApp schema for a strand using Quereus with the
113
+ * Optimystic backend. Each strand instance has its own isolated database with
114
+ * the sApp's schema applied.
115
+ *
116
+ * This class owns the `Database` lifecycle (creation, `getDatabase()`, `close()`)
117
+ * but delegates the actual SQL-surface composition — plugin registration, node
118
+ * wiring, catalog hydration, schema apply — to `connectToStrand` from
119
+ * `@serfab/quereus-plugin-sereus`, the single shared composition. The libp2p
120
+ * node is injected here, so `connectToStrand` neither creates nor stops it:
121
+ * `StrandInstanceManager` owns the node lifecycle, and a failed or closed
122
+ * database leaves the node running.
123
+ *
124
+ * One instance is one attempt: a failed {@link initialize} is closed and a new
125
+ * instance built for the next attempt.
126
+ */
127
+ export class StrandDatabase {
128
+ private db: Database | null = null;
129
+ private shutdownStrand: SereusPluginResult['shutdown'] | null = null;
130
+ private resolvedTransactor: SereusPluginResult['transactor'] | null = null;
131
+ private createEmptyCollections: SereusPluginResult['createEmptyCollections'] | null = null;
132
+ private applyLiveAppSchema: SereusPluginResult['applyAppSchema'] | null = null;
133
+ private readonly config: StrandDatabaseConfig;
134
+ private initialized = false;
135
+ private readonly commits: StrandCommitRecord;
136
+ private unsubscribeCommits: (() => void) | null = null;
137
+ private offlineQueue: StrandOfflineController | null = null;
138
+ private offlineReport: StrandOfflineReport | null = null;
139
+ private appSchemaReport: StrandAppSchemaReport | null = null;
140
+ /** Subscriptions handed out by {@link watchTables}. */
141
+ private readonly tableWatches = new TableWatchRegistry();
142
+
143
+ constructor(config: StrandDatabaseConfig) {
144
+ this.config = config;
145
+ this.commits = new StrandCommitRecord(config.strandId, config, config.partyMachines);
146
+ }
147
+
148
+ /**
149
+ * Initialize the database — create the `Database` and delegate the strand
150
+ * SQL-surface composition (plugins, node wiring, hydrate, schema apply) to
151
+ * `connectToStrand` with the injected libp2p node.
152
+ */
153
+ async initialize(): Promise<void> {
154
+ if (this.initialized) {
155
+ log('StrandDatabase for strand %s already initialized', this.config.strandId);
156
+ return;
157
+ }
158
+
159
+ const sid = this.config.strandId;
160
+ const { sAppConfig } = this.config;
161
+ if (this.config.founder === true) {
162
+ // Before composing anything: a founder that cannot write its Header must not
163
+ // leave a half-built connection behind.
164
+ this.founderSApp();
165
+ }
166
+ log('Initializing StrandDatabase for strand: %s (%s)', sid,
167
+ sAppConfig ? `sApp: ${sAppConfig.id} v${sAppConfig.version}` : 'storage replica');
168
+
169
+ const offline = this.config.offline && { journal: await this.config.offline.journal() };
170
+ const cohortReachability = this.config.offline?.cohortReachability;
171
+ this.db = new Database();
172
+
173
+ // Delegate to the shared composition. The node is injected, so:
174
+ // - `connectToStrand` never creates or stops a node; `StrandInstanceManager`
175
+ // owns the node lifecycle;
176
+ // - no `storage` is passed: the plugin consumes it only to build a local
177
+ // transactor's raw-storage factory or to create a node it was not given,
178
+ // and cadre-core always injects the node and runs the network transactor.
179
+ // (The plugin keeps its `storage` option for the browser entry point.)
180
+ const t0 = performance.now();
181
+ //
182
+ // A storage replica passes no schema, so no `App` tables are declared. A warm restart's
183
+ // hydrate may still load `App` table definitions persisted in the replicated store into
184
+ // the catalog — declarative metadata, nothing the app supplied runs — and the first-sync
185
+ // probe then reads those tables once from blocks this node holds.
186
+ const connection = {
187
+ strandId: sid,
188
+ libp2pNode: this.config.libp2pNode,
189
+ // Only when the node has one: the composition refuses a repo offered with a client node.
190
+ ...(this.config.coordinatedRepo && { coordinatedRepo: this.config.coordinatedRepo }),
191
+ enableCache: true,
192
+ offline,
193
+ ...(cohortReachability && { cohortReachability }),
194
+ };
195
+ const result = await connectToStrand(this.db, sAppConfig
196
+ ? { ...connection, schema: sAppConfig.schema, schemaVersion: sAppConfig.schemaVersion }
197
+ : connection);
198
+ this.shutdownStrand = result.shutdown;
199
+ this.resolvedTransactor = result.transactor;
200
+ this.createEmptyCollections = result.createEmptyCollections;
201
+ this.applyLiveAppSchema = result.applyAppSchema;
202
+ // Before the founder bootstrap, so its commits are reported like any other.
203
+ this.subscribeToCommits(result);
204
+ this.followOffline(result);
205
+ this.appSchemaReport = new StrandAppSchemaReport(sid, this.config.appSchema ?? {}, result);
206
+ timing('[strandDb:%s] connectToStrand: %dms (hydrated tables=%d, indexes=%d)',
207
+ sid, Math.round(performance.now() - t0),
208
+ result.hydrated?.tables ?? 0, result.hydrated?.indexes ?? 0);
209
+
210
+ // Founder-only: write the one-time membership bootstrap now that the schema is
211
+ // applied (connectToStrand has returned). A throw here propagates out of
212
+ // initialize(), and the caller closes this half-built database (close() runs the
213
+ // composition's shutdown). Joiners skip this — their rows arrive via sync.
214
+ // NOTE: a bootstrap with rows to write while `hydrate` restored queued transactions is refused
215
+ // (`StrandOfflineQueueBusyError`), failing every build, so that queue could never drain. Not
216
+ // reachable today: rows are written only while the founding is incomplete (Member empty, or no
217
+ // Manager and none retired), and an incomplete founding fails the build before the database is
218
+ // ever published for the app to queue in. If a founder is ever published with its founding
219
+ // incomplete, skip the bootstrap here while the queue is non-empty and run it once the queue drains.
220
+ if (this.config.founder === true) {
221
+ await this.bootstrapFounder();
222
+ }
223
+
224
+ // After `hydrate` restored the queue and after the founder bootstrap (its `Strand` writes are
225
+ // network-acknowledged in either mode); before the first-sync probe, so in offline mode a read
226
+ // the cohort cannot answer is served from this machine's copy there as it is to the app.
227
+ this.applyOfflineMode();
228
+ this.initialized = true;
229
+ log('StrandDatabase for strand %s initialized successfully', sid);
230
+ }
231
+
232
+ private subscribeToCommits(result: SereusPluginResult): void {
233
+ const unsubscribeDurability = result.onCommitDurability(report => this.commits.reportCommit(report));
234
+ const unsubscribeHeld = result.onCommitFullyHeld(event => this.commits.reportHeld(event));
235
+ this.unsubscribeCommits = () => {
236
+ unsubscribeDurability();
237
+ unsubscribeHeld();
238
+ };
239
+ }
240
+
241
+ private followOffline(result: SereusPluginResult): void {
242
+ const { offline } = this.config;
243
+ if (!offline) {
244
+ return;
245
+ }
246
+ this.offlineQueue = result.offline ?? null;
247
+ this.offlineReport = new StrandOfflineReport(this.config.strandId, offline, result.offline);
248
+ }
249
+
250
+ /**
251
+ * Put the queue in the strand's current mode ({@link StrandDatabaseOffline.mode}). It sets the
252
+ * acknowledgement of transactions begun from now on; an open one keeps the one it began with.
253
+ * No-op without a queue, and before {@link initialize} has composed one (it applies the mode itself).
254
+ */
255
+ applyOfflineMode(): void {
256
+ const queue = this.offlineQueue;
257
+ if (!queue || !this.config.offline) {
258
+ return;
259
+ }
260
+ if (this.config.offline.mode() === 'offline') {
261
+ queue.enter();
262
+ } else {
263
+ queue.exit();
264
+ }
265
+ }
266
+
267
+ /**
268
+ * The database was handed to the app (`StrandInstanceManager.publishDatabase`): report the
269
+ * queue's state, since restored transactions' `queued` statuses were delivered before anything
270
+ * subscribed, and an `App` schema apply still held back.
271
+ */
272
+ reportPublished(): void {
273
+ this.offlineReport?.published();
274
+ this.appSchemaReport?.published();
275
+ }
276
+
277
+ /**
278
+ * Run the founder membership bootstrap against the freshly-composed strand DB.
279
+ *
280
+ * Derives the founding keypair from this PARTY's own `partyMemberPrivateKey` (the
281
+ * `Member.Key`/`Manager.MemberKey` are its public key) — deliberately NOT from the
282
+ * strand row's shared `MemberPrivateKey`, which every joining party receives and could
283
+ * therefore use to forge the founder's identity. A closed strand with no
284
+ * `partyMemberPrivateKey` throws, because it could never seat a founding manager.
285
+ * The shared key's public half IS passed, but only so the bootstrap can refuse a strand
286
+ * founded under it before the split (`PreSplitStrandIdentityError`). The strand node's
287
+ * peer id is passed under {@link StrandDatabaseConfig.bindFounderPeer}: the same node, so
288
+ * the same id, the membership reconciler binds. Open strands derive no keypair (Header
289
+ * only). Idempotent — see {@link bootstrapFounderMembership}.
290
+ */
291
+ private async bootstrapFounder(): Promise<void> {
292
+ const { strandId, strandType, memberPrivateKey, partyMemberPrivateKey, libp2pNode, bindFounderPeer } = this.config;
293
+ const closed = strandType === 'c';
294
+ await bootstrapFounderMembership(this.db!, {
295
+ strandId,
296
+ type: strandType,
297
+ sApp: this.founderSApp(),
298
+ founderKeyPair: closed ? this.deriveFounderKeyPair(strandId, partyMemberPrivateKey) : undefined,
299
+ sharedMemberPublicKey: closed && memberPrivateKey
300
+ ? strandMemberKeyPair(memberPrivateKey).publicKeyB64
301
+ : undefined,
302
+ founderPeerId: closed && bindFounderPeer === true ? libp2pNode.peerId.toString() : undefined,
303
+ createEmptyCollections: this.createEmptyCollections!,
304
+ });
305
+ }
306
+
307
+ /**
308
+ * The sApp a founder bootstrap records in the `Strand.Header`. Throws for a storage
309
+ * replica (no sApp config): its Header's sApp columns would have nothing to say.
310
+ * `CadreNode` always launches a replica as a joiner, so this guards a future caller.
311
+ */
312
+ private founderSApp(): SAppConfig {
313
+ const { sAppConfig, strandId } = this.config;
314
+ if (!sAppConfig) {
315
+ throw new Error(
316
+ `Cannot found strand ${strandId} as a storage replica: the founder bootstrap writes ` +
317
+ 'the sApp id and version into Strand.Header, and a replica has no sApp config.',
318
+ );
319
+ }
320
+ return sAppConfig;
321
+ }
322
+
323
+ /**
324
+ * Derive the founding keypair for a closed strand from the party's own
325
+ * `partyMemberPrivateKey`, failing loudly when the key is absent (a closed strand
326
+ * with no founding Manager can never admit anyone).
327
+ */
328
+ private deriveFounderKeyPair(strandId: string, partyMemberPrivateKey: string | undefined) {
329
+ if (!partyMemberPrivateKey) {
330
+ throw new Error(
331
+ `Cannot found closed strand ${strandId}: this party has no StrandPartyKey for it. ` +
332
+ 'A closed strand needs a founding Member/Manager derived from the party\'s own ' +
333
+ 'membership key (minted when the strand is published, or at the founder launch for ' +
334
+ 'a closed row stored without one) — the shared MemberPrivateKey deliberately ' +
335
+ 'no longer derives anyone\'s identity.',
336
+ );
337
+ }
338
+ return strandMemberKeyPair(partyMemberPrivateKey);
339
+ }
340
+
341
+ /**
342
+ * Run the founder membership bootstrap against an ALREADY-LIVE database — the
343
+ * seam {@link StrandInstanceManager.foundExistingStrand} uses when a founder
344
+ * request arrives for an instance that was first launched as a joiner.
345
+ * Idempotent: every bootstrap write is insert-if-absent
346
+ * ({@link bootstrapFounderMembership}), so calling it on an instance that
347
+ * already founded writes nothing. On success also flips the captured config's
348
+ * `founder`, so this object's own record of how it was launched stays coherent
349
+ * with what actually ran (a construction-time `founder: false` is a statement
350
+ * about the launch, not a permanent identity); a refused bootstrap leaves it a joiner.
351
+ *
352
+ * @param partyMemberPrivateKey - The party's own membership key, for a closed strand
353
+ * whose original (joiner) launch resolved none — e.g. the `StrandPartyKey` row had
354
+ * not been written or replicated yet. The captured config's key wins when both
355
+ * exist: it is the identity this instance launched under.
356
+ */
357
+ async ensureFounderBootstrap(partyMemberPrivateKey?: string): Promise<void> {
358
+ this.ensureInitialized();
359
+ this.config.partyMemberPrivateKey ??= partyMemberPrivateKey;
360
+ await this.bootstrapFounder();
361
+ this.config.founder = true;
362
+ }
363
+
364
+ /**
365
+ * Give a live storage replica the app's schema: apply `App` to the already-composed
366
+ * database — same libp2p node, same store, so the new tables read the blocks this node
367
+ * already holds — and record the sApp, so a later {@link ensureFounderBootstrap} has it
368
+ * for the `Header`. Idempotent: the apply is a declarative diff, so re-applying the same
369
+ * schema emits nothing. A failed apply records nothing. Once it lands, the connection checks the
370
+ * strand's App schema version as a connect-time apply does, reporting a higher one through
371
+ * {@link StrandDatabaseConfig.appSchema}'s `onAppSchemaSuperseded`.
372
+ */
373
+ async attachAppSchema(sAppConfig: SAppConfig): Promise<void> {
374
+ this.ensureInitialized();
375
+ // NOTE: unlike the connect-time apply (`applyAppSchemaOrDefer`), this is not deferred behind
376
+ // the offline queue: a replica writes no app transactions, so no queued transaction wrote an
377
+ // `App` table and `QueuedEntriesBlockSchemaChangeError` cannot refuse it. If a replica ever
378
+ // writes app rows offline, route this through the deferral instead of throwing.
379
+ await this.applyLiveAppSchema!(sAppConfig);
380
+ this.config.sAppConfig = sAppConfig;
381
+ log('StrandDatabase for strand %s attached sApp %s v%s', this.config.strandId, sAppConfig.id, sAppConfig.version);
382
+ }
383
+
384
+ /**
385
+ * Get the underlying database for queries
386
+ */
387
+ getDatabase(): Database {
388
+ this.ensureInitialized();
389
+ return this.db!;
390
+ }
391
+
392
+ /**
393
+ * Subscribe `onChange` to changes in this strand's tables (`'Strand.Member'`, …): commits
394
+ * made here and changes replicated into this node's storage alike, on the single-flight
395
+ * schedule `table-change-watch.ts` describes. {@link close} disposes every subscription
396
+ * still live; a hibernated strand's database is closed and rebuilt on wake, so a consumer
397
+ * subscribes again on the new instance.
398
+ */
399
+ watchTables(tables: readonly string[], onChange: () => Promise<void>, options: TableChangeWatchOptions): TableChangeWatch {
400
+ this.ensureInitialized();
401
+ return this.tableWatches.watch(this.db!, tables, onChange, options);
402
+ }
403
+
404
+ /**
405
+ * The durability of a recent commit on this database, by its `StampId()` — the id a single
406
+ * `insert … returning StampId() as Tx` statement returns. Read it after that statement
407
+ * resolves: the plugin reports the commit before the statement returns, and a commit already
408
+ * held everywhere is marked held by then too. `undefined` for a commit that wrote nothing, one
409
+ * made before this database was built, or one more than 256 commits back. Each value is a
410
+ * snapshot: read again after `strand:commit-held` to see the change.
411
+ */
412
+ commitDurability(transactionId: string): StrandCommitDurability | undefined {
413
+ this.ensureInitialized();
414
+ return this.commits.get(transactionId);
415
+ }
416
+
417
+ /**
418
+ * The strand connection's offline queue (docs/strands/writes.md → "Offline mode"), or `undefined` on a
419
+ * node without `strandOffline`. The mode is set through `CadreNode.setStrandOfflineMode`, which
420
+ * outlives this database; listeners taken here die with it, as {@link watchTables} subscriptions do.
421
+ */
422
+ get offline(): StrandOfflineQueue | undefined {
423
+ this.ensureInitialized();
424
+ return this.offlineQueue ?? undefined;
425
+ }
426
+
427
+ /**
428
+ * Whether this database runs the `App` schema its launch was given. `'waiting-for-queue'` or
429
+ * `'waiting-for-cohort'` while the apply is held back, so `StrandInstance.sAppInfo` names a version
430
+ * whose new tables or columns may not be usable yet; check this before relying on them.
431
+ */
432
+ appSchemaState(): StrandAppSchemaState {
433
+ this.ensureInitialized();
434
+ return this.appSchemaReport?.appSchemaState() ?? 'applied';
435
+ }
436
+
437
+ /**
438
+ * The transaction ids the offline queue lists (`entries()`, the ones a restore has not put back
439
+ * yet included), or `undefined` with no queue: none configured, not composed yet, or closed.
440
+ * Unlike {@link offline} it does not require {@link initialize} to have finished, so the manager
441
+ * can read a database still being built or about to close.
442
+ */
443
+ queuedTransactionIds(): readonly string[] | undefined {
444
+ return this.offlineQueue?.entries().map((entry) => entry.transactionId);
445
+ }
446
+
447
+ /** {@link discardQueued} on this database's queue; `undefined` with no queue, as {@link queuedTransactionIds}. */
448
+ discardQueuedTransactions(): readonly string[] | undefined {
449
+ return this.offlineQueue ? discardQueued(this.offlineQueue) : undefined;
450
+ }
451
+
452
+ /**
453
+ * The Optimystic transactor this strand's connection resolved to — always
454
+ * `'network'` here, since cadre-core passes no `transactor` option and takes
455
+ * the plugin's default. Exposed so a spec measuring or asserting the network
456
+ * path (`strand-solo-write-budget.spec.ts`) can pin the engine it ran on
457
+ * rather than assume it.
458
+ */
459
+ getTransactor(): SereusPluginResult['transactor'] {
460
+ this.ensureInitialized();
461
+ return this.resolvedTransactor!;
462
+ }
463
+
464
+ /**
465
+ * Close the database and cleanup resources. Closes the Quereus `Database` and waits for it
466
+ * (it stops every running statement and open iterator and resolves once nothing reads or
467
+ * writes), then runs the strand-connection shutdown (collection-factory teardown; the
468
+ * injected node keeps running), so no statement reaches released storage. Safe on an
469
+ * instance whose {@link initialize} failed part-way.
470
+ *
471
+ * The handle stays set across the awaits, so a second, concurrent close (a build released
472
+ * part-way closes its database again) awaits the same Quereus teardown rather than skipping
473
+ * ahead to the strand shutdown, which is safe to run twice (each release it makes is
474
+ * idempotent, and the storage-cache release is latched). A rejected Quereus close is logged and the
475
+ * teardown goes on, because callers stop the strand's node once this resolves.
476
+ *
477
+ * NOTE: this makes `close()` wait on a statement in a network wait, bounded by Optimystic's
478
+ * RPC deadlines; the strand shutdown aborts no in-flight request, so closing it first never
479
+ * cut that wait short. Revisit (abort in-flight collection work before closing Quereus) if
480
+ * strand stops show up slow.
481
+ *
482
+ * NOTE: the plugin raises the commit-durability and commit-held reports from inside the
483
+ * committing statement, but through listeners nobody awaits, so an app handler that starts
484
+ * `stopStrand` does not make the statement wait for this close. If a delivery path ever
485
+ * awaits its listeners, a stop started from one waits for itself and never resolves.
486
+ */
487
+ async close(): Promise<void> {
488
+ // First, so an event from the closing connection reaches no app handler or table watch.
489
+ this.unsubscribeCommits?.();
490
+ this.unsubscribeCommits = null;
491
+ this.offlineReport?.release();
492
+ this.offlineReport = null;
493
+ this.appSchemaReport?.release();
494
+ this.appSchemaReport = null;
495
+ this.offlineQueue = null;
496
+ this.tableWatches.disposeAll();
497
+ if (this.db) {
498
+ try {
499
+ await this.db.close();
500
+ } catch (err) {
501
+ log('Closing the Quereus database for strand %s failed; shutting the strand connection down anyway: %O', this.config.strandId, err);
502
+ }
503
+ }
504
+ if (this.shutdownStrand) {
505
+ await this.shutdownStrand();
506
+ this.shutdownStrand = null;
507
+ }
508
+ // Again: a subscription taken during the awaits above would keep its timers past close.
509
+ this.tableWatches.disposeAll();
510
+ this.db = null;
511
+ this.resolvedTransactor = null;
512
+ this.applyLiveAppSchema = null;
513
+ this.initialized = false;
514
+ log('StrandDatabase for strand %s closed', this.config.strandId);
515
+ }
516
+
517
+ private ensureInitialized(): void {
518
+ if (!this.initialized || !this.db) {
519
+ throw new Error(`StrandDatabase for strand ${this.config.strandId} not initialized. Call initialize() first.`);
520
+ }
521
+ }
522
+ }