@serfab/cadre-core 1.6.0 → 1.8.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 (179) hide show
  1. package/README.md +8 -6
  2. package/dist/cadre-node.d.ts +548 -137
  3. package/dist/cadre-node.js +1208 -383
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +2 -2
  6. package/dist/control-authorization.js +1 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-cohort.d.ts +6 -0
  9. package/dist/control-cohort.js +6 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +46 -8
  12. package/dist/control-database.js +97 -18
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +37 -14
  15. package/dist/control-formation-recorder.js +60 -10
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +13 -12
  18. package/dist/control-read-retry.js +14 -12
  19. package/dist/control-read-retry.js.map +1 -1
  20. package/dist/control-schema.d.ts +1 -1
  21. package/dist/control-schema.js +67 -5
  22. package/dist/control-schema.js.map +1 -1
  23. package/dist/control-stream.d.ts +9 -1
  24. package/dist/control-stream.js +24 -1
  25. package/dist/control-stream.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +12 -2
  27. package/dist/control-write-retry.js +13 -2
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +11 -8
  30. package/dist/delegate-admission.js +19 -11
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/diagnostics/connection-path.d.ts +0 -7
  33. package/dist/diagnostics/connection-path.js +0 -7
  34. package/dist/diagnostics/connection-path.js.map +1 -1
  35. package/dist/formation-approval.d.ts +7 -0
  36. package/dist/formation-approval.js +9 -3
  37. package/dist/formation-approval.js.map +1 -1
  38. package/dist/fs-atomic.d.ts +11 -2
  39. package/dist/fs-atomic.js +13 -3
  40. package/dist/fs-atomic.js.map +1 -1
  41. package/dist/hibernation-manager.d.ts +111 -8
  42. package/dist/hibernation-manager.js +234 -49
  43. package/dist/hibernation-manager.js.map +1 -1
  44. package/dist/index.d.ts +13 -6
  45. package/dist/index.js +27 -5
  46. package/dist/index.js.map +1 -1
  47. package/dist/joined-strand-store.d.ts +177 -0
  48. package/dist/joined-strand-store.js +431 -0
  49. package/dist/joined-strand-store.js.map +1 -0
  50. package/dist/key-store-file.js +14 -5
  51. package/dist/key-store-file.js.map +1 -1
  52. package/dist/key-store.d.ts +6 -0
  53. package/dist/key-store.js.map +1 -1
  54. package/dist/link-budget.d.ts +367 -69
  55. package/dist/link-budget.js +375 -72
  56. package/dist/link-budget.js.map +1 -1
  57. package/dist/membership-connection-gater.d.ts +30 -43
  58. package/dist/membership-connection-gater.js +31 -42
  59. package/dist/membership-connection-gater.js.map +1 -1
  60. package/dist/node-local-snapshot.d.ts +5 -4
  61. package/dist/node-local-snapshot.js +6 -3
  62. package/dist/node-local-snapshot.js.map +1 -1
  63. package/dist/peer-dial.d.ts +24 -4
  64. package/dist/peer-dial.js +74 -5
  65. package/dist/peer-dial.js.map +1 -1
  66. package/dist/peer-join-backfill.d.ts +35 -15
  67. package/dist/peer-join-backfill.js +115 -55
  68. package/dist/peer-join-backfill.js.map +1 -1
  69. package/dist/push-fanout.d.ts +6 -0
  70. package/dist/push-fanout.js +6 -0
  71. package/dist/push-fanout.js.map +1 -1
  72. package/dist/relay-reservation.d.ts +3 -1
  73. package/dist/relay-reservation.js +3 -1
  74. package/dist/relay-reservation.js.map +1 -1
  75. package/dist/relay-server.d.ts +79 -0
  76. package/dist/relay-server.js +74 -0
  77. package/dist/relay-server.js.map +1 -0
  78. package/dist/seed-bootstrap.d.ts +57 -4
  79. package/dist/seed-bootstrap.js +107 -83
  80. package/dist/seed-bootstrap.js.map +1 -1
  81. package/dist/storage-scope.d.ts +33 -17
  82. package/dist/storage-scope.js +44 -23
  83. package/dist/storage-scope.js.map +1 -1
  84. package/dist/strand-addr-protocol.d.ts +58 -21
  85. package/dist/strand-addr-protocol.js +133 -85
  86. package/dist/strand-addr-protocol.js.map +1 -1
  87. package/dist/strand-database.d.ts +20 -2
  88. package/dist/strand-database.js +42 -5
  89. package/dist/strand-database.js.map +1 -1
  90. package/dist/strand-first-sync-gate.d.ts +59 -21
  91. package/dist/strand-first-sync-gate.js +58 -19
  92. package/dist/strand-first-sync-gate.js.map +1 -1
  93. package/dist/strand-formation-deadlines.d.ts +151 -0
  94. package/dist/strand-formation-deadlines.js +171 -0
  95. package/dist/strand-formation-deadlines.js.map +1 -0
  96. package/dist/strand-formation-manager.d.ts +63 -30
  97. package/dist/strand-formation-manager.js +67 -41
  98. package/dist/strand-formation-manager.js.map +1 -1
  99. package/dist/strand-formation-protocol.d.ts +45 -35
  100. package/dist/strand-formation-protocol.js +59 -122
  101. package/dist/strand-formation-protocol.js.map +1 -1
  102. package/dist/strand-instance-manager.d.ts +152 -6
  103. package/dist/strand-instance-manager.js +331 -42
  104. package/dist/strand-instance-manager.js.map +1 -1
  105. package/dist/strand-membership-writer.d.ts +6 -0
  106. package/dist/strand-membership-writer.js +11 -0
  107. package/dist/strand-membership-writer.js.map +1 -1
  108. package/dist/strand-peer-book-file.d.ts +12 -0
  109. package/dist/strand-peer-book-file.js +37 -0
  110. package/dist/strand-peer-book-file.js.map +1 -0
  111. package/dist/strand-peer-book-protocol.d.ts +168 -0
  112. package/dist/strand-peer-book-protocol.js +356 -0
  113. package/dist/strand-peer-book-protocol.js.map +1 -0
  114. package/dist/strand-peer-book-swap.d.ts +104 -0
  115. package/dist/strand-peer-book-swap.js +284 -0
  116. package/dist/strand-peer-book-swap.js.map +1 -0
  117. package/dist/strand-peer-book.d.ts +159 -0
  118. package/dist/strand-peer-book.js +361 -0
  119. package/dist/strand-peer-book.js.map +1 -0
  120. package/dist/strand-peer-observer.d.ts +88 -0
  121. package/dist/strand-peer-observer.js +180 -0
  122. package/dist/strand-peer-observer.js.map +1 -0
  123. package/dist/strand-revocation-enforcer.js +2 -1
  124. package/dist/strand-revocation-enforcer.js.map +1 -1
  125. package/dist/strand-solicitation.d.ts +36 -20
  126. package/dist/strand-solicitation.js +4 -4
  127. package/dist/strand-solicitation.js.map +1 -1
  128. package/dist/strand-wake-protocol.d.ts +80 -23
  129. package/dist/strand-wake-protocol.js +89 -64
  130. package/dist/strand-wake-protocol.js.map +1 -1
  131. package/dist/types.d.ts +181 -33
  132. package/dist/types.js +4 -3
  133. package/dist/types.js.map +1 -1
  134. package/package.json +11 -7
  135. package/src/cadre-node.ts +1316 -398
  136. package/src/control-authorization.ts +2 -1
  137. package/src/control-cohort.ts +6 -0
  138. package/src/control-database.ts +122 -18
  139. package/src/control-formation-recorder.ts +354 -305
  140. package/src/control-read-retry.ts +14 -12
  141. package/src/control-schema.ts +67 -5
  142. package/src/control-stream.ts +25 -1
  143. package/src/control-write-retry.ts +13 -2
  144. package/src/delegate-admission.ts +23 -13
  145. package/src/diagnostics/connection-path.ts +0 -7
  146. package/src/formation-approval.ts +610 -604
  147. package/src/fs-atomic.ts +14 -4
  148. package/src/hibernation-manager.ts +638 -437
  149. package/src/index.ts +91 -6
  150. package/src/joined-strand-store.ts +498 -0
  151. package/src/key-store-file.ts +14 -5
  152. package/src/key-store.ts +6 -0
  153. package/src/link-budget.ts +393 -74
  154. package/src/membership-connection-gater.ts +31 -45
  155. package/src/node-local-snapshot.ts +293 -289
  156. package/src/peer-dial.ts +81 -7
  157. package/src/peer-join-backfill.ts +120 -57
  158. package/src/push-fanout.ts +6 -0
  159. package/src/relay-reservation.ts +3 -1
  160. package/src/relay-server.ts +98 -0
  161. package/src/seed-bootstrap.ts +133 -91
  162. package/src/storage-scope.ts +44 -23
  163. package/src/strand-addr-protocol.ts +547 -458
  164. package/src/strand-database.ts +287 -242
  165. package/src/strand-first-sync-gate.ts +58 -19
  166. package/src/strand-formation-deadlines.ts +227 -0
  167. package/src/strand-formation-manager.ts +700 -647
  168. package/src/strand-formation-protocol.ts +103 -150
  169. package/src/strand-instance-manager.ts +387 -45
  170. package/src/strand-membership-writer.ts +12 -0
  171. package/src/strand-peer-book-file.ts +39 -0
  172. package/src/strand-peer-book-protocol.ts +466 -0
  173. package/src/strand-peer-book-swap.ts +338 -0
  174. package/src/strand-peer-book.ts +475 -0
  175. package/src/strand-peer-observer.ts +235 -0
  176. package/src/strand-revocation-enforcer.ts +2 -1
  177. package/src/strand-solicitation.ts +519 -500
  178. package/src/strand-wake-protocol.ts +401 -355
  179. package/src/types.ts +185 -33
@@ -0,0 +1,235 @@
1
+ /**
2
+ * The strand peer book's OBSERVATION writer: on one strand libp2p node, every peer
3
+ * whose identify result names this strand's block-transfer protocol — a strand peer,
4
+ * never the circuit relay or a bootstrap node ({@link speaksBlockTransfer}, the
5
+ * same gate `PeerJoinBackfill` schedules on) — is reported with its dialable
6
+ * addresses, so `CadreNode` can merge an unsigned book entry for it
7
+ * (`strand-peer-book.ts`). That is what lets a restarted machine dial the peers it
8
+ * was talking to, instead of only the ones a formation once carried back.
9
+ *
10
+ * Dialable addresses are the peer's announced `listenAddrs` from the identify
11
+ * result, plus the open connection's `remoteAddr` when it is relayed
12
+ * (`/p2p-circuit`) — a relay-only peer announces its circuit listener, but the
13
+ * address this node actually reached it on is the one proven to work. Every
14
+ * address is bound to the peer id (`withTrailingPeerId`), ordered signaling-first
15
+ * and capped like a formation's list, so the book files it under the right peer.
16
+ *
17
+ * Throttled to one report per peer per {@link STRAND_PEER_OBSERVE_THROTTLE_MS}
18
+ * unless the address set changed, so a flapping relayed connection — identify
19
+ * fires on every reconnect, every 16 s at worst — does not rewrite the node-local
20
+ * slot each time. Best-effort throughout: nothing here throws into a libp2p event
21
+ * handler.
22
+ *
23
+ * Lifecycle: one observer per running strand, armed in
24
+ * `StrandInstanceManager.buildStrandRuntime` right after the libp2p node exists
25
+ * (the bootstrap dials that follow `libp2p.start()` are exactly the peers worth
26
+ * observing) and stopped in `releaseRuntime`, so a hibernation wake re-arms it on
27
+ * the rebuilt node. `start` also walks the peers already connected, because
28
+ * identify may have completed for an early peer before this object existed.
29
+ */
30
+ import debug from 'debug';
31
+ import type { Connection, IdentifyResult, Libp2p, PeerId } from '@libp2p/interface';
32
+ import { multiaddr } from '@multiformats/multiaddr';
33
+ import { speaksBlockTransfer } from './peer-join-backfill.js';
34
+ import { isSignalingAddr, orderSignalingFirst, withTrailingPeerId } from './peer-record.js';
35
+ import { MAX_STRAND_ADDRS } from './strand-formation-protocol.js';
36
+
37
+ const log = debug('sereus:cadre:strand-peer-observer');
38
+
39
+ /** Minimum gap between two reports of ONE peer with an unchanged address set. */
40
+ export const STRAND_PEER_OBSERVE_THROTTLE_MS = 10 * 60 * 1000;
41
+
42
+ /** One strand peer seen live: its strand transport peer id and the addresses it is dialable at. */
43
+ export interface StrandPeerObservation {
44
+ peerId: string;
45
+ /** Bound to `peerId`, signaling-first, at most `MAX_STRAND_ADDRS`. */
46
+ addrs: string[];
47
+ }
48
+
49
+ export interface StrandPeerObserverDeps {
50
+ /** For logs (the strand id). */
51
+ label: string;
52
+ /** The strand's libp2p node. */
53
+ libp2p: Libp2p;
54
+ /** This strand network's `/optimystic/<networkName>` prefix — the block-transfer gate. */
55
+ protocolPrefix: string;
56
+ /** Called for every (throttled) observation; must not throw. */
57
+ onObserved: (observation: StrandPeerObservation) => void;
58
+ }
59
+
60
+ export interface StrandPeerObserverOptions {
61
+ /** Default {@link STRAND_PEER_OBSERVE_THROTTLE_MS}. */
62
+ throttleMs?: number;
63
+ /** Clock, for tests. Default `Date.now`. */
64
+ now?: () => number;
65
+ }
66
+
67
+ interface LastReport {
68
+ at: number;
69
+ /** The address set reported, canonicalised for comparison. */
70
+ key: string;
71
+ }
72
+
73
+ /**
74
+ * Anything that prints as a multiaddr. libp2p's identify result and peer store hand
75
+ * back its nested `@multiformats/multiaddr` copy, a structurally different type from
76
+ * this package's, so addresses are taken by their string form and re-parsed here.
77
+ */
78
+ export interface AddrLike {
79
+ toString(): string;
80
+ }
81
+
82
+ /** One connected peer as the peer store knows it: what identify recorded, plus its open connections. */
83
+ export interface ConnectedIdentifiedPeer {
84
+ peerId: PeerId;
85
+ protocols: string[];
86
+ /** The stored addresses: identify-announced, plus whatever else was merged in. */
87
+ addrs: AddrLike[];
88
+ connections: Connection[];
89
+ }
90
+
91
+ /**
92
+ * Every peer `libp2p` holds a connection to AND has already identified (it is in the
93
+ * peer store), grouped per peer. A connected peer whose identify has not finished is
94
+ * left out: its `peer:identify` event is still to come, and every listener that walks
95
+ * this list at start subscribes to that event too. Shared by the peer-book observer
96
+ * and the book swap (`strand-peer-book-swap.ts`), which both arm right after the
97
+ * node exists and may already have missed an early peer's identify.
98
+ */
99
+ export async function connectedIdentifiedPeers(libp2p: Libp2p, label: string): Promise<ConnectedIdentifiedPeer[]> {
100
+ const byPeer = new Map<string, { peerId: PeerId; connections: Connection[] }>();
101
+ for (const connection of libp2p.getConnections()) {
102
+ const key = connection.remotePeer.toString();
103
+ const group = byPeer.get(key) ?? { peerId: connection.remotePeer, connections: [] };
104
+ group.connections.push(connection);
105
+ byPeer.set(key, group);
106
+ }
107
+ const identified = await Promise.all([...byPeer.values()].map(async ({ peerId, connections }): Promise<ConnectedIdentifiedPeer | undefined> => {
108
+ try {
109
+ const peer = await libp2p.peerStore.get(peerId);
110
+ return { peerId, protocols: peer.protocols, addrs: peer.addresses.map((a) => a.multiaddr), connections };
111
+ } catch (error) {
112
+ // NotFoundError: identify has not finished; the event handler will see it.
113
+ if ((error as Error).name !== 'NotFoundError') {
114
+ log('[%s] peer store read for %s failed — skipping it: %o', label, peerId.toString(), error);
115
+ }
116
+ return undefined;
117
+ }
118
+ }));
119
+ return identified.filter((peer): peer is ConnectedIdentifiedPeer => peer !== undefined);
120
+ }
121
+
122
+ export class StrandPeerObserver {
123
+ private readonly throttleMs: number;
124
+ private readonly now: () => number;
125
+ private readonly lastReports = new Map<string, LastReport>();
126
+ private readonly onPeerIdentify: (evt: CustomEvent<IdentifyResult>) => void;
127
+ private started = false;
128
+ private stopped = false;
129
+
130
+ constructor(private readonly deps: StrandPeerObserverDeps, options?: StrandPeerObserverOptions) {
131
+ this.throttleMs = options?.throttleMs ?? STRAND_PEER_OBSERVE_THROTTLE_MS;
132
+ this.now = options?.now ?? Date.now;
133
+ this.onPeerIdentify = (evt) => {
134
+ const { peerId, protocols, listenAddrs, connection } = evt.detail;
135
+ if (speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
136
+ this.observe(peerId, listenAddrs, [connection]);
137
+ }
138
+ };
139
+ }
140
+
141
+ /** Subscribe to `peer:identify` and report the peers already connected and identified. */
142
+ start(): void {
143
+ if (this.started || this.stopped) return;
144
+ this.started = true;
145
+ this.deps.libp2p.addEventListener('peer:identify', this.onPeerIdentify);
146
+ void this.observeConnectedPeers().then((seen) => {
147
+ log('[%s] started (%d peer(s) already connected)', this.deps.label, seen);
148
+ });
149
+ }
150
+
151
+ /** Unsubscribe; later identify results are ignored. */
152
+ stop(): void {
153
+ if (this.stopped) return;
154
+ this.stopped = true;
155
+ if (this.started) {
156
+ this.deps.libp2p.removeEventListener('peer:identify', this.onPeerIdentify);
157
+ }
158
+ this.lastReports.clear();
159
+ log('[%s] stopped', this.deps.label);
160
+ }
161
+
162
+ /**
163
+ * Report every connected peer the peer store already knows speaks this strand's
164
+ * protocol, with its stored addresses. A peer not yet in the store (identify has
165
+ * not finished) is left to the `peer:identify` handler. Returns the number of
166
+ * identified peers considered.
167
+ *
168
+ * NOTE: the stored addresses include what `CadreNode.mergeStrandPeerAddrs` merged
169
+ * INTO the peer store from the book, so this walk can re-vouch a dead address the
170
+ * book already held, until the peer's next `peer:identify` replaces the set with
171
+ * what it announces now. Bounded by the address cap; if a dead address ever shows
172
+ * up surviving across resumes, read only the peer store's identify-sourced
173
+ * addresses here rather than shortening the age.
174
+ */
175
+ private async observeConnectedPeers(): Promise<number> {
176
+ const peers = await connectedIdentifiedPeers(this.deps.libp2p, this.deps.label);
177
+ for (const { peerId, protocols, addrs, connections } of peers) {
178
+ if (!this.stopped && speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
179
+ this.observe(peerId, addrs, connections);
180
+ }
181
+ }
182
+ return peers.length;
183
+ }
184
+
185
+ /** Shape, throttle and report one peer. Never throws. */
186
+ private observe(peerId: PeerId, listenAddrs: AddrLike[], connections: Connection[]): void {
187
+ if (this.stopped) return;
188
+ const id = peerId.toString();
189
+ // Identify is about remotes, so self never arrives here; belt and braces, since
190
+ // a node must never file its own addresses as a peer to dial.
191
+ if (id === this.deps.libp2p.peerId.toString()) return;
192
+ try {
193
+ const addrs = dialableAddrs(id, listenAddrs, connections);
194
+ if (!this.shouldReport(id, addrs)) return;
195
+ log('[%s] observed strand peer %s at %d addr(s)', this.deps.label, id, addrs.length);
196
+ this.deps.onObserved({ peerId: id, addrs });
197
+ } catch (error) {
198
+ log('[%s] observing %s failed (ignored): %o', this.deps.label, id, error);
199
+ }
200
+ }
201
+
202
+ /** One report per peer per throttle window, unless the address set changed. */
203
+ private shouldReport(peerId: string, addrs: string[]): boolean {
204
+ const now = this.now();
205
+ const key = [...addrs].sort().join('\n');
206
+ const last = this.lastReports.get(peerId);
207
+ if (last && last.key === key && now - last.at < this.throttleMs) {
208
+ return false;
209
+ }
210
+ this.lastReports.set(peerId, { at: now, key });
211
+ return true;
212
+ }
213
+ }
214
+
215
+ /**
216
+ * The addresses to file for `peerId`: its announced listen addrs plus every relayed
217
+ * connection addr, each bound to `peerId`, de-duplicated, signaling-first, capped.
218
+ * Re-parsed through this package's own `multiaddr` (see {@link AddrLike}).
219
+ */
220
+ export function dialableAddrs(peerId: string, listenAddrs: AddrLike[], connections: Connection[]): string[] {
221
+ const candidates = [
222
+ ...listenAddrs.map((ma) => ma.toString()),
223
+ ...connections.map((c) => c.remoteAddr.toString()).filter(isSignalingAddr)
224
+ ];
225
+ const bound = new Set<string>();
226
+ for (const candidate of candidates) {
227
+ const addr = withTrailingPeerId(multiaddr(candidate), peerId);
228
+ if (addr === null) {
229
+ log('dropping addr %s — it names a peer other than %s', candidate, peerId);
230
+ continue;
231
+ }
232
+ bound.add(addr.toString());
233
+ }
234
+ return orderSignalingFirst([...bound]).slice(0, MAX_STRAND_ADDRS);
235
+ }
@@ -118,7 +118,8 @@
118
118
  import debug from 'debug';
119
119
  import type { ConnectionGater, PeerId, MultiaddrConnection } from '@libp2p/interface';
120
120
  import type { Database } from '@quereus/quereus';
121
- import { ADMISSION_DECISION_TIMEOUT_MS, decideWithinDeadline } from './membership-connection-gater.js';
121
+ import { decideWithinDeadline } from './membership-connection-gater.js';
122
+ import { ADMISSION_DECISION_TIMEOUT_MS } from './link-budget.js';
122
123
 
123
124
  const log = debug('sereus:cadre:strand-revocation');
124
125