@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,394 +1,406 @@
1
- /**
2
- * Control-network push-wake transport.
3
- *
4
- * Lets a same-cadre peer — typically an always-on server that participates in a
5
- * strand and sees new activity — signal a hibernating cadre peer to bring that
6
- * strand online, pull pending activity, and re-hibernate. Push-wake travels the
7
- * **control network** (the per-party network connecting this party's own cadre
8
- * nodes), which is the only network a hibernating peer keeps connected.
9
- *
10
- * Modeled directly on `seed-bootstrap.ts`: a dedicated libp2p protocol id,
11
- * 4-byte big-endian length-prefixed JSON frames, `node.handle` for the receiver,
12
- * `node.dialProtocol` for the sender, and the shared `ControlStream` primitives
13
- * from `control-stream.ts`. The exchange is a single request → single ack on one
14
- * stream (like seed delivery), so each side reads to EOF (under a read timeout)
15
- * and decodes one frame via the shared {@link decodeLengthPrefixedFrame} guard.
16
- *
17
- * **Authorization (v1):** a wake is low-risk — it only causes the receiver to
18
- * spend resources coming online for a strand it already participates in — so the
19
- * request carries no signature. Membership is checked before this handler runs, by
20
- * the control node's protocol guard (`control-protocol-guard.ts`, the `members`
21
- * class: `CadreNode.isAuthorizedMember`, under which the sender's `CadrePeer` row
22
- * must carry a voucher that verifies against an owner key in the receiver's
23
- * node-local trusted-owner anchor), so a peer that merely published rows into the
24
- * replicated control DB gets its stream reset and never reaches this module.
25
- */
26
-
27
- import debug from 'debug';
28
- import type { Libp2p, Connection } from '@libp2p/interface';
29
- import type { Multiaddr } from '@multiformats/multiaddr';
30
- import type { StrandInstance, WakeRequest, WakeAck } from './types.js';
31
- import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
32
- import { type ControlStream, exchangeFrame, readStreamToEnd, replyAndClose } from './control-stream.js';
33
- import { dialAddr, tryAddrsInTurn } from './peer-dial.js';
34
- import { relayedRequestBudgetMs } from './link-budget.js';
35
-
36
- const log = debug('sereus:cadre:strand-wake');
37
-
38
- /** Protocol id for control-network push-wake (parallel to `/sereus/seed/1.0.0`). */
39
- export const WAKE_PROTOCOL = '/sereus/strand-wake/1.0.0';
40
-
41
- /**
42
- * Maximum wake frame size. Wake messages are tiny (a strand id + short reason),
43
- * so this is a defensive cap — far below the 1MB seed ceiling — that bounds the
44
- * bytes a peer can make the receiver buffer per stream.
45
- */
46
- const MAX_WAKE_SIZE = 64 * 1024;
47
-
48
- /**
49
- * Default deadline for ONE wake attempt — dial, request, ack — at the default declared link
50
- * (ms): `relayedRequestBudgetMs` in `link-budget.ts`, because the target may be reachable
51
- * only through a relay and the attempt has to open that connection before the exchange.
52
- * {@link dialWake} derives it from {@link DialWakeOptions.linkRoundTripMs} instead when given.
53
- *
54
- * It holds only link work because the receiver acks as soon as it has DECIDED, before the
55
- * wake itself runs ({@link StrandWakeService.processWakeRequest}).
56
- *
57
- * NOTE: the receiver's membership check (two live control reads, in its protocol guard) runs
58
- * inside this deadline and is not counted. In steady state those reads touch only held blocks and do not consult the
59
- * cohort. If a wake or address request is seen timing out while the receiver's membership read
60
- * is consulting, count one membership decision in this deadline or answer the check from the
61
- * materialized authorized-peer snapshot. See docs/cadre-consistency.md → "Deadlines Over
62
- * Optimystic's Reads and Commits".
63
- */
64
- export const DEFAULT_WAKE_TIMEOUT_MS = relayedRequestBudgetMs();
65
-
66
- /**
67
- * Whole attempts one {@link dialWake} call budgets for: a stale signaling address, then the
68
- * direct address that works.
69
- */
70
- export const WAKE_DIAL_ATTEMPTS = 2;
71
-
72
- /**
73
- * Default budget for a WHOLE {@link dialWake} call at the default declared link, in ms —
74
- * every candidate address together, not each one: {@link WAKE_DIAL_ATTEMPTS} attempt
75
- * deadlines.
76
- *
77
- * Without it the cost of a wake is (candidate count × {@link
78
- * DEFAULT_WAKE_TIMEOUT_MS}), a number nothing chooses or bounds. That is not
79
- * hypothetical: an address behind a dropped NAT mapping, or any host that
80
- * blackholes rather than sending a RST, burns its full attempt timeout instead
81
- * of failing in milliseconds, so a five-address peer would cost five attempts.
82
- *
83
- * This makes the TARGET PEER the unit rather than the address — the same
84
- * decision, for the same reason, as
85
- * `DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS` in `peer-dial.ts`, though not the same
86
- * count: that one is sized to fit several dead addresses ahead of a working one,
87
- * while a wake target is expected to be awake and reachable on its first or second
88
- * address. Two whole attempts so a reachable peer whose signaling address is stale
89
- * still gets a genuine try at its direct one; a peer needing longer than that is
90
- * not "asleep and reachable", which is the only case a wake is for. The last
91
- * attempt inside the budget gets whatever remains of it, so the call returns at
92
- * the budget, not past it.
93
- *
94
- * Override per call with {@link DialWakeOptions.budgetMs} — tests that drive
95
- * dead addresses on purpose set it low so a dial's duration is a chosen number
96
- * rather than a transitive libp2p default stretched by machine load.
97
- */
98
- export const DEFAULT_WAKE_DIAL_BUDGET_MS = WAKE_DIAL_ATTEMPTS * DEFAULT_WAKE_TIMEOUT_MS;
99
-
100
- /** Default time the receiver waits for an inbound wake frame before aborting (ms). */
101
- // eslint-disable-next-line no-restricted-syntax -- link-independent: a receiver cap on one small request frame on a stream the peer already opened; it bounds a peer that opens a stream and never sends, not the dial
102
- const DEFAULT_WAKE_READ_TIMEOUT_MS = 10_000;
103
-
104
- /** Default cap on concurrent inbound wake streams a single peer can pin open. */
105
- const DEFAULT_MAX_CONCURRENT_WAKES = 100;
106
-
107
- /**
108
- * Read a libp2p stream to EOF and decode the single length-prefixed JSON frame
109
- * it carries. Bounded by `timeoutMs` (a never-half-closing peer is aborted, not
110
- * awaited forever) and capped at {@link MAX_WAKE_SIZE}, reusing the shared
111
- * {@link decodeLengthPrefixedFrame} guard for the prefix/length checks.
112
- */
113
- async function readFrame<T>(stream: ControlStream, timeoutMs: number): Promise<T> {
114
- const data = await readStreamToEnd(stream, { maxBytes: MAX_WAKE_SIZE, timeoutMs, label: 'Wake' });
115
- const body = decodeLengthPrefixedFrame(data, MAX_WAKE_SIZE);
116
- return JSON.parse(new TextDecoder().decode(body)) as T;
117
- }
118
-
119
- /**
120
- * Dependencies the {@link StrandWakeService} receiver needs from its host
121
- * (`CadreNode`), injected so the service is testable without a full node.
122
- */
123
- export interface StrandWakeServiceOptions {
124
- /** Look up a local strand instance by id (undefined if not participated in). */
125
- getStrand(strandId: string): StrandInstance | undefined;
126
- /**
127
- * Trigger the local wake path for a hibernating/idle strand. Wired to
128
- * `CadreNode.wakeStrand` (→ `HibernationManager` → `resumeStrand`); `resumeStrand`
129
- * joins any resume already in flight, so a push-wake racing a check-in shares its
130
- * runtime build.
131
- *
132
- * Started, not awaited: the ack goes back before the strand is up, and a wake
133
- * that fails afterwards is logged here rather than reported to the sender.
134
- */
135
- wake(strandId: string): Promise<void>;
136
- /**
137
- * Time to wait for the inbound wake frame before aborting the read (ms).
138
- * Defaults to {@link DEFAULT_WAKE_READ_TIMEOUT_MS}. Bounds a buggy/compromised
139
- * own-cadre node that opens a stream and never half-closes its write end.
140
- */
141
- readTimeoutMs?: number;
142
- /**
143
- * Cap on concurrent inbound wake streams (defaults to
144
- * {@link DEFAULT_MAX_CONCURRENT_WAKES}). Over the cap, a non-accepting ack is
145
- * returned without invoking the wake path.
146
- *
147
- * It counts streams, not wakes: a wake started after its ack is no longer
148
- * counted. Those are bounded by the strands this node participates in instead,
149
- * since an unknown strand is refused before any wake starts and the wake path
150
- * coalesces per strand.
151
- */
152
- maxConcurrent?: number;
153
- }
154
-
155
- /**
156
- * Receiver side of the push-wake protocol. Registers a `WAKE_PROTOCOL` handler
157
- * on the control node and, for each inbound {@link WakeRequest} (from a peer the
158
- * protocol guard has already admitted as an authorized member), replies with a
159
- * {@link WakeAck} and starts resuming the named strand if it is hibernating/idle
160
- * and we participate in it.
161
- */
162
- export class StrandWakeService {
163
- private readonly options: StrandWakeServiceOptions;
164
- private readonly readTimeoutMs: number;
165
- private readonly maxConcurrent: number;
166
- private node: Libp2p | null = null;
167
- /** In-flight inbound wake streams, used to enforce {@link maxConcurrent}. */
168
- private activeStreams = 0;
169
-
170
- constructor(options: StrandWakeServiceOptions) {
171
- this.options = options;
172
- this.readTimeoutMs = options.readTimeoutMs ?? DEFAULT_WAKE_READ_TIMEOUT_MS;
173
- this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT_WAKES;
174
- }
175
-
176
- /** Number of in-flight inbound wake streams. */
177
- get activeCount(): number {
178
- return this.activeStreams;
179
- }
180
-
181
- /**
182
- * Register the wake protocol handler on the control node. Rejects when libp2p
183
- * refuses the registration; the node reference is kept only once the handler
184
- * is in place.
185
- */
186
- async initialize(node: Libp2p): Promise<void> {
187
- // `runOnLimitedConnection: true` is REQUIRED for the relay path: a NAT'd
188
- // receiver is reached over a circuit-relay connection, which libp2p marks
189
- // "limited" (the relay caps its data/duration). Without this the receiver
190
- // would refuse the inbound wake stream on exactly the connection the
191
- // protocol is designed to use (see the relay note on `dialWake`).
192
- await node.handle(WAKE_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
193
- const remotePeerId = (rawConnection as Connection).remotePeer.toString();
194
- await this.handleStream(rawStream as ControlStream, remotePeerId);
195
- }, { runOnLimitedConnection: true });
196
- this.node = node;
197
- log('StrandWakeService registered handler: %s', WAKE_PROTOCOL);
198
- }
199
-
200
- /** Unregister the handler and release the node reference. */
201
- async shutdown(): Promise<void> {
202
- if (this.node) {
203
- await this.node.unhandle(WAKE_PROTOCOL);
204
- this.node = null;
205
- log('StrandWakeService shutdown');
206
- }
207
- }
208
-
209
- /**
210
- * Read the inbound request, decide the wake, and write the ack.
211
- *
212
- * Three hardening layers, all reported as a non-accepting ack rather than a
213
- * dropped/hung stream: a concurrency cap (over {@link maxConcurrent}, reply
214
- * without touching the wake path), a read timeout (a peer that never
215
- * half-closes is aborted inside {@link readFrame}/`readStreamToEnd`), and the
216
- * existing malformed/oversized-frame guard.
217
- */
218
- private async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
219
- log('Incoming wake request from: %s', remotePeerId);
220
-
221
- if (this.activeStreams >= this.maxConcurrent) {
222
- log('Rejecting wake from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrent);
223
- await replyAndClose(stream, { accepted: false, reason: 'Too many concurrent wake requests' } satisfies WakeAck, 'Wake');
224
- return;
225
- }
226
-
227
- this.activeStreams++;
228
- try {
229
- await replyAndClose(stream, await this.answerStream(stream, remotePeerId), 'Wake');
230
- } finally {
231
- this.activeStreams--;
232
- }
233
- }
234
-
235
- /** Read and decide one inbound request; any failure becomes a non-accepting ack. */
236
- private async answerStream(stream: ControlStream, remotePeerId: string): Promise<WakeAck> {
237
- try {
238
- const request = await readFrame<WakeRequest>(stream, this.readTimeoutMs);
239
- return await this.processWakeRequest(request, remotePeerId);
240
- } catch (err) {
241
- log('Error handling wake request from %s: %o', remotePeerId, err);
242
- return { accepted: false, reason: err instanceof Error ? err.message : 'Unknown error' };
243
- }
244
- }
245
-
246
- /**
247
- * Decide the wake for a decoded request and start it. Exposed (not private) so
248
- * the decision matrix can be unit-tested directly.
249
- *
250
- * - Unknown / not-participated strand → rejected (`accepted: false`).
251
- * - Hibernating or idle strand → `accepted` with that status, and a wake started.
252
- * - Already-live strand → no-op, `accepted` with current status.
253
- *
254
- * The wake is not awaited, so the ack means "a wake was started", not "the
255
- * strand is up". Awaiting it would put the whole resume — a sibling address
256
- * collection, a strand node build, a relay reservation drive — inside the
257
- * sender's attempt deadline, coupling that deadline to this node's own budgets.
258
- */
259
- async processWakeRequest(request: WakeRequest, remotePeerId: string): Promise<WakeAck> {
260
- const instance = this.options.getStrand(request.strandId);
261
- if (!instance) {
262
- log('Rejecting wake for unknown/unparticipated strand %s', request.strandId);
263
- return { accepted: false, reason: 'Strand not found or not participated in' };
264
- }
265
-
266
- // Read before the wake starts: the wake path mutates the shared instance.
267
- const status = instance.status;
268
- if (status === 'hibernating' || status === 'idle') {
269
- log('Waking strand %s on push from %s (reason=%s)', request.strandId, remotePeerId, request.reason ?? 'unspecified');
270
- this.startWake(request.strandId);
271
- } else {
272
- log('Strand %s already %s; push-wake is a no-op', request.strandId, status);
273
- }
274
-
275
- return { accepted: true, status };
276
- }
277
-
278
- /**
279
- * Start a wake without awaiting it — the same fire-and-forget an activity-driven
280
- * local wake uses (`HibernationManager`), which also coalesces the two.
281
- */
282
- private startWake(strandId: string): void {
283
- void this.options.wake(strandId).catch((err: unknown) => {
284
- log('Push-wake of strand %s failed after it was accepted: %o', strandId, err);
285
- });
286
- }
287
- }
288
-
289
- /** Options for {@link dialWake}. */
290
- export interface DialWakeOptions {
291
- /**
292
- * The sender's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
293
- * both deadlines below are derived when not given. Unset means the declared default.
294
- */
295
- linkRoundTripMs?: number;
296
- /** Per-ATTEMPT timeout in ms (default: derived as {@link DEFAULT_WAKE_TIMEOUT_MS} is). */
297
- timeoutMs?: number;
298
- /**
299
- * Budget for the whole call — every candidate together (default:
300
- * {@link WAKE_DIAL_ATTEMPTS} × the per-attempt timeout, as {@link DEFAULT_WAKE_DIAL_BUDGET_MS}).
301
- */
302
- budgetMs?: number;
303
- /** Override the protocol id (defaults to {@link WAKE_PROTOCOL}). */
304
- protocolId?: string;
305
- }
306
-
307
- /**
308
- * Sender side: dial a target's control-network address(es), send a
309
- * {@link WakeRequest} over `WAKE_PROTOCOL`, and return the peer's {@link WakeAck}.
310
- *
311
- * Tries each candidate address in order (signaling/relay first, as produced by
312
- * `CadreNode.resolvePeerAddrs`) until one dials, so a NAT'd peer is reachable via
313
- * its circuit-relay address. Each attempt is bounded by `timeoutMs` and the call
314
- * as a whole by `budgetMs` (see {@link DEFAULT_WAKE_DIAL_BUDGET_MS}); a candidate
315
- * the budget leaves no room for is reported as untried rather than silently
316
- * dropped.
317
- *
318
- * Throws if no address is dialable — with an error naming EVERY candidate and
319
- * why it failed, not merely the last one ({@link tryAddrsInTurn}). That
320
- * distinction is not cosmetic: with only the last candidate's message the
321
- * failure that mattered (usually the signaling address, tried first) is
322
- * invisible outside a debug log, and the surfaced message points at whichever
323
- * address happened to be tried last.
324
- *
325
- * The candidate loop is deliberately explicit rather than one
326
- * `dialProtocol(addrs)` call. libp2p sorts any multi-address dial with
327
- * `defaultAddressSorter`, whose `circuitRelayAddressesLast` pass would demote
328
- * exactly the signaling address this ordering puts first — silently inverting
329
- * it, with no per-dial sorter override to opt out of. For the same reason this
330
- * does not use `dialPeerAddrs`, which puts relayed addresses last.
331
- *
332
- * NOTE: unlike `dialPeerAddrs`, this does not drop addresses that relay through this node, so a
333
- * relay waking a peer that holds a reservation on it tries that address and gets `Can not dial
334
- * self` (fast, then the next candidate). If wakes are ever sent from a relay to its own
335
- * reservation holders routinely, share `dialPeerAddrs`'s filter here.
336
- */
337
- export async function dialWake(
338
- node: Libp2p,
339
- addrs: Multiaddr[],
340
- request: WakeRequest,
341
- options: DialWakeOptions = {}
342
- ): Promise<WakeAck> {
343
- if (addrs.length === 0) {
344
- throw new Error('No dialable address for wake target');
345
- }
346
- const protocolId = options.protocolId ?? WAKE_PROTOCOL;
347
- const perAddressMs = options.timeoutMs ?? relayedRequestBudgetMs(options.linkRoundTripMs);
348
- const budget = {
349
- perAddressMs,
350
- totalMs: options.budgetMs ?? WAKE_DIAL_ATTEMPTS * perAddressMs,
351
- };
352
- // The attempt's signal aborts the in-flight dialProtocol and resets the live
353
- // stream, so neither the connect nor the ack-read leaks.
354
- return await tryAddrsInTurn(addrs, budget, 'Wake dial', (addr, signal, attemptMs) =>
355
- sendWake(node, addr, protocolId, request, attemptMs, signal));
356
- }
357
-
358
- /**
359
- * Dial one address, open one stream, send the request, half-close, and read the ack.
360
- *
361
- * The address is dialed outside libp2p's dial queue (`dialAddr`), so another dial of
362
- * the target in flight cannot capture this attempt; an open connection is still reused.
363
- *
364
- * `signal` is the per-attempt deadline from {@link dialWake}: it goes to the dial so a
365
- * timeout during connect aborts it, and into {@link exchangeFrame} so a timeout after
366
- * the stream is open resets it — releasing the otherwise unbounded ack-read.
367
- */
368
- async function sendWake(
369
- node: Libp2p,
370
- addr: Multiaddr,
371
- protocolId: string,
372
- request: WakeRequest,
373
- timeoutMs: number,
374
- signal: AbortSignal,
375
- ): Promise<WakeAck> {
376
- const connection = await dialAddr(node, addr, signal, 'Wake dial');
377
- // `runOnLimitedConnection: true`: the target may be reachable only over a
378
- // circuit-relay connection (the signaling-first addr), which libp2p marks
379
- // "limited". The wake exchange is a single tiny request→ack well within the
380
- // relay's data/duration cap, so opening it on the limited connection is safe
381
- // and is the whole point of dialing the relay address.
382
- const rawStream = await connection.newStream(protocolId, { runOnLimitedConnection: true, signal });
383
-
384
- const ack = await exchangeFrame(
385
- rawStream as unknown as ControlStream,
386
- signal,
387
- request,
388
- (stream) => readFrame<WakeAck>(stream, timeoutMs),
389
- 'Wake dial aborted by timeout',
390
- );
391
-
392
- log('Wake ack from %s: accepted=%s status=%s', addr.toString(), ack.accepted, ack.status ?? '-');
393
- return ack;
394
- }
1
+ /**
2
+ * Control-network push-wake transport.
3
+ *
4
+ * Lets a same-cadre peer — typically an always-on server that participates in a
5
+ * strand and sees new activity — signal a hibernating cadre peer to bring that
6
+ * strand online, pull pending activity, and re-hibernate. Push-wake travels the
7
+ * **control network** (the per-party network connecting this party's own cadre
8
+ * nodes), which is the only network a hibernating peer keeps connected.
9
+ *
10
+ * Modeled directly on `seed-bootstrap.ts`: a dedicated libp2p protocol id,
11
+ * 4-byte big-endian length-prefixed JSON frames, `node.handle` for the receiver,
12
+ * `node.dialProtocol` for the sender, and the shared `ControlStream` primitives
13
+ * from `control-stream.ts`. The exchange is a single request → single ack on one
14
+ * stream (like seed delivery), so each side reads to EOF (under a read timeout)
15
+ * and decodes one frame via the shared {@link decodeLengthPrefixedFrame} guard.
16
+ *
17
+ * **Authorization (v1):** a wake is low-risk — it only causes the receiver to
18
+ * spend resources coming online for a strand it already participates in — so the
19
+ * request carries no signature. Membership is checked before this handler runs, by
20
+ * the control node's protocol guard (`control-protocol-guard.ts`, the `members`
21
+ * class: `CadreNode.isAuthorizedMember`, under which the sender's `CadrePeer` row
22
+ * must carry a voucher that verifies against an owner key in the receiver's
23
+ * node-local trusted-owner anchor), so a peer that merely published rows into the
24
+ * replicated control DB gets its stream reset and never reaches this module.
25
+ */
26
+
27
+ import debug from 'debug';
28
+ import type { Libp2p, Connection } from '@libp2p/interface';
29
+ import type { Multiaddr } from '@multiformats/multiaddr';
30
+ import type { StrandInstance, WakeRequest, WakeAck } from './types.js';
31
+ import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
32
+ import { type ControlStream, exchangeFrame, readStreamToEnd, replyAndClose } from './control-stream.js';
33
+ import { dialAddr, tryAddrsInTurn, webrtcLast } from './peer-dial.js';
34
+ import { relayedRequestBudgetMs } from './link-budget.js';
35
+
36
+ const log = debug('sereus:cadre:strand-wake');
37
+
38
+ /** Protocol id for control-network push-wake (parallel to `/sereus/seed/1.0.0`). */
39
+ export const WAKE_PROTOCOL = '/sereus/strand-wake/1.0.0';
40
+
41
+ /**
42
+ * Maximum wake frame size. Wake messages are tiny (a strand id + short reason),
43
+ * so this is a defensive cap — far below the 1MB seed ceiling — that bounds the
44
+ * bytes a peer can make the receiver buffer per stream.
45
+ */
46
+ const MAX_WAKE_SIZE = 64 * 1024;
47
+
48
+ /**
49
+ * Default deadline for ONE wake attempt — dial, request, ack — at the default declared link
50
+ * (ms): `relayedRequestBudgetMs` in `link-budget.ts`, because the target may be reachable
51
+ * only through a relay and the attempt has to open that connection before the exchange.
52
+ * {@link dialWake} derives it from {@link DialWakeOptions.linkRoundTripMs} instead when given.
53
+ *
54
+ * It holds only link work because the receiver acks as soon as it has DECIDED, before the
55
+ * wake itself runs ({@link StrandWakeService.processWakeRequest}).
56
+ *
57
+ * NOTE: the receiver's membership check (two live control reads, in its protocol guard) runs
58
+ * inside this deadline and is not counted. In steady state those reads touch only held blocks and do not consult the
59
+ * cohort. If a wake or address request is seen timing out while the receiver's membership read
60
+ * is consulting, count one membership decision in this deadline or answer the check from the
61
+ * materialized authorized-peer snapshot. See docs/network/deadlines.md → "Deadlines over
62
+ * Optimystic's reads and commits".
63
+ */
64
+ export const DEFAULT_WAKE_TIMEOUT_MS = relayedRequestBudgetMs();
65
+
66
+ /**
67
+ * Whole attempts one {@link dialWake} call budgets for: a stale relayed address, then the
68
+ * direct address that works.
69
+ *
70
+ * Two RELAYED OR DIRECT attempts. {@link dialWake} moves every address that needs ICE after its
71
+ * relay hop behind them ({@link webrtcLast}), because such an address answers nothing for about
72
+ * 23 s when ICE cannot connect — so without that ordering one of these two attempts could be
73
+ * spent on an address nothing is waiting for, and a target whose first relay reservation has
74
+ * rotated would never be reached at its second relay.
75
+ */
76
+ export const WAKE_DIAL_ATTEMPTS = 2;
77
+
78
+ /**
79
+ * Default budget for a WHOLE {@link dialWake} call at the default declared link, in ms —
80
+ * every candidate address together, not each one: {@link WAKE_DIAL_ATTEMPTS} attempt
81
+ * deadlines.
82
+ *
83
+ * Without it the cost of a wake is (candidate count × {@link
84
+ * DEFAULT_WAKE_TIMEOUT_MS}), a number nothing chooses or bounds. That is not
85
+ * hypothetical: an address behind a dropped NAT mapping, or any host that
86
+ * blackholes rather than sending a RST, burns its full attempt timeout instead
87
+ * of failing in milliseconds, so a five-address peer would cost five attempts.
88
+ *
89
+ * This makes the TARGET PEER the unit rather than the address — the same
90
+ * decision, for the same reason, as
91
+ * `DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS` in `peer-dial.ts`, though not the same
92
+ * count: that one is sized to fit several dead addresses ahead of a working one,
93
+ * while a wake target is expected to be awake and reachable on its first or second
94
+ * address. Two whole attempts so a reachable peer whose relayed address is stale
95
+ * still gets a genuine try at its direct one; a peer needing longer than that is
96
+ * not "asleep and reachable", which is the only case a wake is for. The last
97
+ * attempt inside the budget gets whatever remains of it, so the call returns at
98
+ * the budget, not past it.
99
+ *
100
+ * Override per call with {@link DialWakeOptions.budgetMs} — tests that drive
101
+ * dead addresses on purpose set it low so a dial's duration is a chosen number
102
+ * rather than a transitive libp2p default stretched by machine load.
103
+ */
104
+ export const DEFAULT_WAKE_DIAL_BUDGET_MS = WAKE_DIAL_ATTEMPTS * DEFAULT_WAKE_TIMEOUT_MS;
105
+
106
+ /** Default time the receiver waits for an inbound wake frame before aborting (ms). */
107
+ // eslint-disable-next-line no-restricted-syntax -- link-independent: a receiver cap on one small request frame on a stream the peer already opened; it bounds a peer that opens a stream and never sends, not the dial
108
+ const DEFAULT_WAKE_READ_TIMEOUT_MS = 10_000;
109
+
110
+ /** Default cap on concurrent inbound wake streams a single peer can pin open. */
111
+ const DEFAULT_MAX_CONCURRENT_WAKES = 100;
112
+
113
+ /**
114
+ * Read a libp2p stream to EOF and decode the single length-prefixed JSON frame
115
+ * it carries. Bounded by `timeoutMs` (a never-half-closing peer is aborted, not
116
+ * awaited forever) and capped at {@link MAX_WAKE_SIZE}, reusing the shared
117
+ * {@link decodeLengthPrefixedFrame} guard for the prefix/length checks.
118
+ */
119
+ async function readFrame<T>(stream: ControlStream, timeoutMs: number): Promise<T> {
120
+ const data = await readStreamToEnd(stream, { maxBytes: MAX_WAKE_SIZE, timeoutMs, label: 'Wake' });
121
+ const body = decodeLengthPrefixedFrame(data, MAX_WAKE_SIZE);
122
+ return JSON.parse(new TextDecoder().decode(body)) as T;
123
+ }
124
+
125
+ /**
126
+ * Dependencies the {@link StrandWakeService} receiver needs from its host
127
+ * (`CadreNode`), injected so the service is testable without a full node.
128
+ */
129
+ export interface StrandWakeServiceOptions {
130
+ /** Look up a local strand instance by id (undefined if not participated in). */
131
+ getStrand(strandId: string): StrandInstance | undefined;
132
+ /**
133
+ * Trigger the local wake path for a hibernating/idle strand. Wired to
134
+ * `CadreNode.wakeStrand` (→ `HibernationManager` → `resumeStrand`); `resumeStrand`
135
+ * joins any resume already in flight, so a push-wake racing a check-in shares its
136
+ * runtime build.
137
+ *
138
+ * Started, not awaited: the ack goes back before the strand is up, and a wake
139
+ * that fails afterwards is logged here rather than reported to the sender.
140
+ */
141
+ wake(strandId: string): Promise<void>;
142
+ /**
143
+ * Time to wait for the inbound wake frame before aborting the read (ms).
144
+ * Defaults to {@link DEFAULT_WAKE_READ_TIMEOUT_MS}. Bounds a buggy/compromised
145
+ * own-cadre node that opens a stream and never half-closes its write end.
146
+ */
147
+ readTimeoutMs?: number;
148
+ /**
149
+ * Cap on concurrent inbound wake streams (defaults to
150
+ * {@link DEFAULT_MAX_CONCURRENT_WAKES}). Over the cap, a non-accepting ack is
151
+ * returned without invoking the wake path.
152
+ *
153
+ * It counts streams, not wakes: a wake started after its ack is no longer
154
+ * counted. Those are bounded by the strands this node participates in instead,
155
+ * since an unknown strand is refused before any wake starts and the wake path
156
+ * coalesces per strand.
157
+ */
158
+ maxConcurrent?: number;
159
+ }
160
+
161
+ /**
162
+ * Receiver side of the push-wake protocol. Registers a `WAKE_PROTOCOL` handler
163
+ * on the control node and, for each inbound {@link WakeRequest} (from a peer the
164
+ * protocol guard has already admitted as an authorized member), replies with a
165
+ * {@link WakeAck} and starts resuming the named strand if it is hibernating/idle
166
+ * and we participate in it.
167
+ */
168
+ export class StrandWakeService {
169
+ private readonly options: StrandWakeServiceOptions;
170
+ private readonly readTimeoutMs: number;
171
+ private readonly maxConcurrent: number;
172
+ private node: Libp2p | null = null;
173
+ /** In-flight inbound wake streams, used to enforce {@link maxConcurrent}. */
174
+ private activeStreams = 0;
175
+
176
+ constructor(options: StrandWakeServiceOptions) {
177
+ this.options = options;
178
+ this.readTimeoutMs = options.readTimeoutMs ?? DEFAULT_WAKE_READ_TIMEOUT_MS;
179
+ this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT_WAKES;
180
+ }
181
+
182
+ /** Number of in-flight inbound wake streams. */
183
+ get activeCount(): number {
184
+ return this.activeStreams;
185
+ }
186
+
187
+ /**
188
+ * Register the wake protocol handler on the control node. Rejects when libp2p
189
+ * refuses the registration; the node reference is kept only once the handler
190
+ * is in place.
191
+ */
192
+ async initialize(node: Libp2p): Promise<void> {
193
+ // `runOnLimitedConnection: true` is REQUIRED for the relay path: a NAT'd
194
+ // receiver is reached over a circuit-relay connection, which libp2p marks
195
+ // "limited" (the relay caps its data/duration). Without this the receiver
196
+ // would refuse the inbound wake stream on exactly the connection the
197
+ // protocol is designed to use (see the relay note on `dialWake`).
198
+ await node.handle(WAKE_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
199
+ const remotePeerId = (rawConnection as Connection).remotePeer.toString();
200
+ await this.handleStream(rawStream as ControlStream, remotePeerId);
201
+ }, { runOnLimitedConnection: true });
202
+ this.node = node;
203
+ log('StrandWakeService registered handler: %s', WAKE_PROTOCOL);
204
+ }
205
+
206
+ /** Unregister the handler and release the node reference. */
207
+ async shutdown(): Promise<void> {
208
+ if (this.node) {
209
+ await this.node.unhandle(WAKE_PROTOCOL);
210
+ this.node = null;
211
+ log('StrandWakeService shutdown');
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Read the inbound request, decide the wake, and write the ack.
217
+ *
218
+ * Three hardening layers, all reported as a non-accepting ack rather than a
219
+ * dropped/hung stream: a concurrency cap (over {@link maxConcurrent}, reply
220
+ * without touching the wake path), a read timeout (a peer that never
221
+ * half-closes is aborted inside {@link readFrame}/`readStreamToEnd`), and the
222
+ * existing malformed/oversized-frame guard.
223
+ */
224
+ private async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
225
+ log('Incoming wake request from: %s', remotePeerId);
226
+
227
+ if (this.activeStreams >= this.maxConcurrent) {
228
+ log('Rejecting wake from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrent);
229
+ await replyAndClose(stream, { accepted: false, reason: 'Too many concurrent wake requests' } satisfies WakeAck, 'Wake');
230
+ return;
231
+ }
232
+
233
+ this.activeStreams++;
234
+ try {
235
+ await replyAndClose(stream, await this.answerStream(stream, remotePeerId), 'Wake');
236
+ } finally {
237
+ this.activeStreams--;
238
+ }
239
+ }
240
+
241
+ /** Read and decide one inbound request; any failure becomes a non-accepting ack. */
242
+ private async answerStream(stream: ControlStream, remotePeerId: string): Promise<WakeAck> {
243
+ try {
244
+ const request = await readFrame<WakeRequest>(stream, this.readTimeoutMs);
245
+ return await this.processWakeRequest(request, remotePeerId);
246
+ } catch (err) {
247
+ log('Error handling wake request from %s: %o', remotePeerId, err);
248
+ return { accepted: false, reason: err instanceof Error ? err.message : 'Unknown error' };
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Decide the wake for a decoded request and start it. Exposed (not private) so
254
+ * the decision matrix can be unit-tested directly.
255
+ *
256
+ * - Unknown / not-participated strand → rejected (`accepted: false`).
257
+ * - Hibernating or idle strand → `accepted` with that status, and a wake started.
258
+ * - Already-live strand → no-op, `accepted` with current status.
259
+ *
260
+ * The wake is not awaited, so the ack means "a wake was started", not "the
261
+ * strand is up". Awaiting it would put the whole resume — a sibling address
262
+ * collection, a strand node build, a relay reservation drive — inside the
263
+ * sender's attempt deadline, coupling that deadline to this node's own budgets.
264
+ */
265
+ async processWakeRequest(request: WakeRequest, remotePeerId: string): Promise<WakeAck> {
266
+ const instance = this.options.getStrand(request.strandId);
267
+ if (!instance) {
268
+ log('Rejecting wake for unknown/unparticipated strand %s', request.strandId);
269
+ return { accepted: false, reason: 'Strand not found or not participated in' };
270
+ }
271
+
272
+ // Read before the wake starts: the wake path mutates the shared instance.
273
+ const status = instance.status;
274
+ if (status === 'hibernating' || status === 'idle') {
275
+ log('Waking strand %s on push from %s (reason=%s)', request.strandId, remotePeerId, request.reason ?? 'unspecified');
276
+ this.startWake(request.strandId);
277
+ } else {
278
+ log('Strand %s already %s; push-wake is a no-op', request.strandId, status);
279
+ }
280
+
281
+ return { accepted: true, status };
282
+ }
283
+
284
+ /**
285
+ * Start a wake without awaiting it — the same fire-and-forget an activity-driven
286
+ * local wake uses (`HibernationManager`), which also coalesces the two.
287
+ */
288
+ private startWake(strandId: string): void {
289
+ void this.options.wake(strandId).catch((err: unknown) => {
290
+ log('Push-wake of strand %s failed after it was accepted: %o', strandId, err);
291
+ });
292
+ }
293
+ }
294
+
295
+ /** Options for {@link dialWake}. */
296
+ export interface DialWakeOptions {
297
+ /**
298
+ * The sender's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
299
+ * both deadlines below are derived when not given. Unset means the declared default.
300
+ */
301
+ linkRoundTripMs?: number;
302
+ /** Per-ATTEMPT timeout in ms (default: derived as {@link DEFAULT_WAKE_TIMEOUT_MS} is). */
303
+ timeoutMs?: number;
304
+ /**
305
+ * Budget for the whole call — every candidate together (default:
306
+ * {@link WAKE_DIAL_ATTEMPTS} × the per-attempt timeout, as {@link DEFAULT_WAKE_DIAL_BUDGET_MS}).
307
+ */
308
+ budgetMs?: number;
309
+ /** Override the protocol id (defaults to {@link WAKE_PROTOCOL}). */
310
+ protocolId?: string;
311
+ }
312
+
313
+ /**
314
+ * Sender side: dial a target's control-network address(es), send a
315
+ * {@link WakeRequest} over `WAKE_PROTOCOL`, and return the peer's {@link WakeAck}.
316
+ *
317
+ * Tries each candidate address in order (relayed first, as produced by
318
+ * `CadreNode.resolvePeerAddrs`) until one dials, so a NAT'd peer is reachable via
319
+ * its circuit-relay address. Each attempt is bounded by `timeoutMs` and the call
320
+ * as a whole by `budgetMs` (see {@link DEFAULT_WAKE_DIAL_BUDGET_MS}); a candidate
321
+ * the budget leaves no room for is reported as untried rather than silently
322
+ * dropped.
323
+ *
324
+ * The caller's order is kept but for one rule enforced here, at the site that owns the budget:
325
+ * an address that needs ICE after its relay hop goes last ({@link webrtcLast}), whatever order
326
+ * the caller gave. Only that rule is applied — unlike `dialPeerAddrs`, this does NOT hoist
327
+ * direct addresses ahead of relayed ones, because a hibernating machine is usually reachable
328
+ * only through its relay and its direct addresses blackhole.
329
+ *
330
+ * Throws if no address is dialable — with an error naming EVERY candidate and
331
+ * why it failed, not merely the last one ({@link tryAddrsInTurn}). That
332
+ * distinction is not cosmetic: with only the last candidate's message the
333
+ * failure that mattered (usually the relayed address, tried first) is
334
+ * invisible outside a debug log, and the surfaced message points at whichever
335
+ * address happened to be tried last.
336
+ *
337
+ * The candidate loop is deliberately explicit rather than one
338
+ * `dialProtocol(addrs)` call. libp2p sorts any multi-address dial with
339
+ * `defaultAddressSorter`, whose `circuitRelayAddressesLast` pass would demote
340
+ * exactly the relayed address this ordering puts first — silently inverting
341
+ * it, with no per-dial sorter override to opt out of. For the same reason this
342
+ * does not use `dialPeerAddrs`, which puts relayed addresses last.
343
+ *
344
+ * NOTE: unlike `dialPeerAddrs`, this does not drop addresses that relay through this node, so a
345
+ * relay waking a peer that holds a reservation on it tries that address and gets `Can not dial
346
+ * self` (fast, then the next candidate). If wakes are ever sent from a relay to its own
347
+ * reservation holders routinely, share `dialPeerAddrs`'s filter here.
348
+ */
349
+ export async function dialWake(
350
+ node: Libp2p,
351
+ addrs: Multiaddr[],
352
+ request: WakeRequest,
353
+ options: DialWakeOptions = {}
354
+ ): Promise<WakeAck> {
355
+ if (addrs.length === 0) {
356
+ throw new Error('No dialable address for wake target');
357
+ }
358
+ const protocolId = options.protocolId ?? WAKE_PROTOCOL;
359
+ const perAddressMs = options.timeoutMs ?? relayedRequestBudgetMs(options.linkRoundTripMs);
360
+ const budget = {
361
+ perAddressMs,
362
+ totalMs: options.budgetMs ?? WAKE_DIAL_ATTEMPTS * perAddressMs,
363
+ };
364
+ // The attempt's signal aborts the in-flight dialProtocol and resets the live
365
+ // stream, so neither the connect nor the ack-read leaks.
366
+ return await tryAddrsInTurn(webrtcLast(addrs), budget, 'Wake dial', (addr, signal, attemptMs) =>
367
+ sendWake(node, addr, protocolId, request, attemptMs, signal));
368
+ }
369
+
370
+ /**
371
+ * Dial one address, open one stream, send the request, half-close, and read the ack.
372
+ *
373
+ * The address is dialed outside libp2p's dial queue (`dialAddr`), so another dial of
374
+ * the target in flight cannot capture this attempt; an open connection is still reused.
375
+ *
376
+ * `signal` is the per-attempt deadline from {@link dialWake}: it goes to the dial so a
377
+ * timeout during connect aborts it, and into {@link exchangeFrame} so a timeout after
378
+ * the stream is open resets it — releasing the otherwise unbounded ack-read.
379
+ */
380
+ async function sendWake(
381
+ node: Libp2p,
382
+ addr: Multiaddr,
383
+ protocolId: string,
384
+ request: WakeRequest,
385
+ timeoutMs: number,
386
+ signal: AbortSignal,
387
+ ): Promise<WakeAck> {
388
+ const connection = await dialAddr(node, addr, signal, 'Wake dial');
389
+ // `runOnLimitedConnection: true`: the target may be reachable only over a
390
+ // circuit-relay connection (the relayed addr tried first), which libp2p marks
391
+ // "limited". The wake exchange is a single tiny request→ack well within the
392
+ // relay's data/duration cap, so opening it on the limited connection is safe
393
+ // and is the whole point of dialing the relay address.
394
+ const rawStream = await connection.newStream(protocolId, { runOnLimitedConnection: true, signal });
395
+
396
+ const ack = await exchangeFrame(
397
+ rawStream as unknown as ControlStream,
398
+ signal,
399
+ request,
400
+ (stream) => readFrame<WakeAck>(stream, timeoutMs),
401
+ 'Wake dial aborted by timeout',
402
+ );
403
+
404
+ log('Wake ack from %s: accepted=%s status=%s', addr.toString(), ack.accepted, ack.status ?? '-');
405
+ return ack;
406
+ }