@serfab/cadre-host 1.12.0 → 1.14.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 (337) hide show
  1. package/README.md +332 -423
  2. package/dist/bin/host.d.ts +6 -3
  3. package/dist/bin/host.js +301 -505
  4. package/dist/bin/host.js.map +1 -1
  5. package/dist/bin/join-output.d.ts +56 -0
  6. package/dist/bin/join-output.js +92 -0
  7. package/dist/bin/join-output.js.map +1 -0
  8. package/dist/bin/nat-output.d.ts +49 -0
  9. package/dist/bin/nat-output.js +127 -0
  10. package/dist/bin/nat-output.js.map +1 -0
  11. package/dist/hosted/claim-details.d.ts +44 -0
  12. package/dist/hosted/claim-details.js +66 -0
  13. package/dist/hosted/claim-details.js.map +1 -0
  14. package/dist/hosted/hosted-node-service.d.ts +318 -0
  15. package/dist/hosted/hosted-node-service.js +666 -0
  16. package/dist/hosted/hosted-node-service.js.map +1 -0
  17. package/dist/hosted/hosted-node-store.d.ts +40 -0
  18. package/dist/hosted/hosted-node-store.js +126 -0
  19. package/dist/hosted/hosted-node-store.js.map +1 -0
  20. package/dist/{donation/donation-supervisor.d.ts → hosted/hosted-node-supervisor.d.ts} +70 -53
  21. package/dist/hosted/hosted-node-supervisor.js +396 -0
  22. package/dist/hosted/hosted-node-supervisor.js.map +1 -0
  23. package/dist/hosted/hosted-node-watcher.d.ts +83 -0
  24. package/dist/hosted/hosted-node-watcher.js +224 -0
  25. package/dist/hosted/hosted-node-watcher.js.map +1 -0
  26. package/dist/hosted/index.d.ts +16 -0
  27. package/dist/hosted/index.js +13 -0
  28. package/dist/hosted/index.js.map +1 -0
  29. package/dist/hosted/node-status.d.ts +35 -0
  30. package/dist/hosted/node-status.js +61 -0
  31. package/dist/hosted/node-status.js.map +1 -0
  32. package/dist/hosted/types.d.ts +134 -0
  33. package/dist/hosted/types.js +22 -0
  34. package/dist/hosted/types.js.map +1 -0
  35. package/dist/index.d.ts +12 -24
  36. package/dist/index.js +9 -19
  37. package/dist/index.js.map +1 -1
  38. package/dist/installer/config.d.ts +4 -34
  39. package/dist/installer/config.js +3 -18
  40. package/dist/installer/config.js.map +1 -1
  41. package/dist/installer/index.d.ts +7 -19
  42. package/dist/installer/index.js +14 -69
  43. package/dist/installer/index.js.map +1 -1
  44. package/dist/installer/paths.d.ts +0 -2
  45. package/dist/installer/paths.js +0 -4
  46. package/dist/installer/paths.js.map +1 -1
  47. package/dist/installer/wizard.d.ts +0 -7
  48. package/dist/installer/wizard.js +1 -8
  49. package/dist/installer/wizard.js.map +1 -1
  50. package/dist/nat/address-resolver.d.ts +18 -17
  51. package/dist/nat/address-resolver.js +79 -25
  52. package/dist/nat/address-resolver.js.map +1 -1
  53. package/dist/nat/address-watch.d.ts +37 -0
  54. package/dist/nat/address-watch.js +84 -0
  55. package/dist/nat/address-watch.js.map +1 -0
  56. package/dist/nat/ddns/duckdns.d.ts +2 -1
  57. package/dist/nat/ddns/duckdns.js +5 -1
  58. package/dist/nat/ddns/duckdns.js.map +1 -1
  59. package/dist/nat/ddns/index.d.ts +6 -0
  60. package/dist/nat/ddns/index.js.map +1 -1
  61. package/dist/nat/index.d.ts +12 -9
  62. package/dist/nat/index.js +6 -5
  63. package/dist/nat/index.js.map +1 -1
  64. package/dist/nat/nat-service.d.ts +203 -77
  65. package/dist/nat/nat-service.js +602 -237
  66. package/dist/nat/nat-service.js.map +1 -1
  67. package/dist/nat/nat-store.d.ts +12 -5
  68. package/dist/nat/nat-store.js +114 -30
  69. package/dist/nat/nat-store.js.map +1 -1
  70. package/dist/nat/port-mapper.d.ts +83 -79
  71. package/dist/nat/port-mapper.js +148 -189
  72. package/dist/nat/port-mapper.js.map +1 -1
  73. package/dist/nat/reachability.d.ts +31 -15
  74. package/dist/nat/reachability.js +97 -22
  75. package/dist/nat/reachability.js.map +1 -1
  76. package/dist/nat/types.d.ts +78 -27
  77. package/dist/nat/types.js +8 -5
  78. package/dist/nat/types.js.map +1 -1
  79. package/dist/orchestrator/host-process-orchestrator.d.ts +29 -71
  80. package/dist/orchestrator/host-process-orchestrator.js +78 -218
  81. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  82. package/dist/{installer/identity.d.ts → orchestrator/identity-file.d.ts} +5 -5
  83. package/dist/{installer/identity.js → orchestrator/identity-file.js} +6 -6
  84. package/dist/orchestrator/identity-file.js.map +1 -0
  85. package/dist/orchestrator/index.d.ts +2 -3
  86. package/dist/orchestrator/index.js +1 -1
  87. package/dist/orchestrator/index.js.map +1 -1
  88. package/dist/orchestrator/node-identity.d.ts +6 -6
  89. package/dist/orchestrator/node-identity.js +7 -7
  90. package/dist/orchestrator/node-identity.js.map +1 -1
  91. package/dist/orchestrator/port-allocator.d.ts +5 -6
  92. package/dist/orchestrator/port-allocator.js +9 -11
  93. package/dist/orchestrator/port-allocator.js.map +1 -1
  94. package/dist/orchestrator/state-store.d.ts +3 -5
  95. package/dist/orchestrator/state-store.js +2 -10
  96. package/dist/orchestrator/state-store.js.map +1 -1
  97. package/dist/orchestrator/types.d.ts +33 -22
  98. package/dist/orchestrator/types.js.map +1 -1
  99. package/dist/server/error-handler.d.ts +5 -25
  100. package/dist/server/error-handler.js +11 -74
  101. package/dist/server/error-handler.js.map +1 -1
  102. package/dist/server/events/types.d.ts +7 -11
  103. package/dist/server/events/types.js +2 -1
  104. package/dist/server/events/types.js.map +1 -1
  105. package/dist/server/index.d.ts +11 -37
  106. package/dist/server/index.js +30 -48
  107. package/dist/server/index.js.map +1 -1
  108. package/dist/server/routes/hosted-nodes.d.ts +28 -0
  109. package/dist/server/routes/hosted-nodes.js +68 -0
  110. package/dist/server/routes/hosted-nodes.js.map +1 -0
  111. package/dist/server/routes/nat.d.ts +4 -1
  112. package/dist/server/routes/nat.js +13 -2
  113. package/dist/server/routes/nat.js.map +1 -1
  114. package/dist/server/routes/nodes.d.ts +6 -20
  115. package/dist/server/routes/nodes.js +7 -86
  116. package/dist/server/routes/nodes.js.map +1 -1
  117. package/dist/server/routes/settings.d.ts +2 -7
  118. package/dist/server/routes/settings.js +3 -7
  119. package/dist/server/routes/settings.js.map +1 -1
  120. package/dist/server/routes/status.d.ts +2 -25
  121. package/dist/server/routes/status.js +1 -11
  122. package/dist/server/routes/status.js.map +1 -1
  123. package/dist/server/server.js +8 -8
  124. package/dist/server/settings-store.d.ts +2 -2
  125. package/dist/server/settings-store.js +2 -2
  126. package/dist/server/static.js +1 -2
  127. package/dist/server/static.js.map +1 -1
  128. package/dist/ui/assets/index-4FWuU8ye.js +19 -0
  129. package/dist/ui/assets/index-4FWuU8ye.js.map +1 -0
  130. package/dist/ui/assets/index-Di9Q4d01.css +1 -0
  131. package/dist/ui/index.html +2 -2
  132. package/dist/update/index.d.ts +2 -2
  133. package/dist/update/index.js +2 -2
  134. package/dist/update/store.d.ts +1 -1
  135. package/dist/update/store.js +1 -1
  136. package/dist/update/types.d.ts +1 -1
  137. package/dist/update/types.js +1 -1
  138. package/package.json +5 -6
  139. package/src/__tests__/cli-nat.smoke.test.ts +219 -212
  140. package/src/__tests__/cli.smoke.test.ts +1 -1
  141. package/src/__tests__/global-setup.ts +2 -3
  142. package/src/__tests__/orchestrator-claim-secret.test.ts +112 -0
  143. package/src/__tests__/orchestrator-handle-contract.ts +134 -134
  144. package/src/__tests__/orchestrator-node-identity.test.ts +182 -203
  145. package/src/__tests__/orchestrator-ports.test.ts +124 -143
  146. package/src/__tests__/orchestrator-push.test.ts +138 -146
  147. package/src/__tests__/orchestrator.test.ts +1019 -1063
  148. package/src/bin/host.ts +368 -553
  149. package/src/bin/join-output.ts +120 -0
  150. package/src/bin/nat-output.ts +177 -0
  151. package/src/{donation → hosted}/__tests__/fake-orchestrator.test.ts +173 -173
  152. package/src/{donation → hosted}/__tests__/fake-orchestrator.ts +265 -243
  153. package/src/hosted/__tests__/hosted-node-service.test.ts +609 -0
  154. package/src/hosted/__tests__/hosted-node-supervisor.test.ts +474 -0
  155. package/src/hosted/__tests__/test-invitation.ts +33 -0
  156. package/src/hosted/claim-details.ts +96 -0
  157. package/src/hosted/hosted-node-service.ts +795 -0
  158. package/src/hosted/hosted-node-store.ts +144 -0
  159. package/src/hosted/hosted-node-supervisor.ts +439 -0
  160. package/src/hosted/hosted-node-watcher.ts +250 -0
  161. package/src/hosted/index.ts +53 -0
  162. package/src/hosted/node-status.ts +71 -0
  163. package/src/hosted/types.ts +153 -0
  164. package/src/index.ts +72 -91
  165. package/src/installer/__tests__/config.test.ts +15 -40
  166. package/src/installer/__tests__/installer.smoke.test.ts +5 -86
  167. package/src/installer/__tests__/wizard.test.ts +56 -64
  168. package/src/installer/config.ts +135 -175
  169. package/src/installer/index.ts +15 -83
  170. package/src/installer/paths.ts +104 -109
  171. package/src/installer/wizard.ts +87 -103
  172. package/src/nat/__tests__/address-resolver.test.ts +107 -82
  173. package/src/nat/__tests__/nat-service.test.ts +433 -408
  174. package/src/nat/__tests__/nat-store.test.ts +127 -93
  175. package/src/nat/__tests__/port-mapper.test.ts +30 -191
  176. package/src/nat/__tests__/reachability.test.ts +96 -13
  177. package/src/nat/address-resolver.ts +94 -52
  178. package/src/nat/address-watch.ts +92 -0
  179. package/src/nat/ddns/duckdns.ts +5 -1
  180. package/src/nat/ddns/index.ts +6 -0
  181. package/src/nat/index.ts +87 -71
  182. package/src/nat/nat-service.ts +889 -501
  183. package/src/nat/nat-store.ts +237 -154
  184. package/src/nat/port-mapper.ts +241 -329
  185. package/src/nat/reachability.ts +134 -25
  186. package/src/nat/types.ts +209 -159
  187. package/src/{installer/__tests__/identity.test.ts → orchestrator/__tests__/identity-file.test.ts} +34 -34
  188. package/src/orchestrator/__tests__/node-identity.test.ts +62 -62
  189. package/src/orchestrator/host-process-orchestrator.ts +81 -243
  190. package/src/{installer/identity.ts → orchestrator/identity-file.ts} +56 -56
  191. package/src/orchestrator/index.ts +9 -10
  192. package/src/orchestrator/node-identity.ts +41 -41
  193. package/src/orchestrator/port-allocator.ts +71 -73
  194. package/src/orchestrator/state-store.ts +76 -90
  195. package/src/orchestrator/types.ts +34 -23
  196. package/src/server/__tests__/bus.test.ts +38 -38
  197. package/src/server/__tests__/error-handler.test.ts +81 -118
  198. package/src/server/__tests__/fakes.ts +40 -44
  199. package/src/server/__tests__/hosted-nodes-route.test.ts +160 -0
  200. package/src/server/__tests__/nodes-route.test.ts +114 -283
  201. package/src/server/__tests__/publishers.test.ts +193 -180
  202. package/src/server/__tests__/server.smoke.test.ts +134 -223
  203. package/src/server/__tests__/settings-route.test.ts +179 -195
  204. package/src/server/__tests__/sse-route.test.ts +119 -119
  205. package/src/server/__tests__/status-route.test.ts +82 -121
  206. package/src/server/error-handler.ts +112 -178
  207. package/src/server/events/types.ts +20 -24
  208. package/src/server/index.ts +223 -267
  209. package/src/server/routes/hosted-nodes.ts +83 -0
  210. package/src/server/routes/nat.ts +75 -63
  211. package/src/server/routes/nodes.ts +96 -188
  212. package/src/server/routes/settings.ts +115 -123
  213. package/src/server/routes/status.ts +102 -134
  214. package/src/server/server.ts +8 -8
  215. package/src/server/settings-store.ts +2 -2
  216. package/src/server/static.ts +1 -2
  217. package/src/update/index.ts +2 -2
  218. package/src/update/store.ts +1 -1
  219. package/src/update/types.ts +1 -1
  220. package/dist/auth/duration.d.ts +0 -1
  221. package/dist/auth/duration.js +0 -32
  222. package/dist/auth/duration.js.map +0 -1
  223. package/dist/auth/index.d.ts +0 -11
  224. package/dist/auth/index.js +0 -9
  225. package/dist/auth/index.js.map +0 -1
  226. package/dist/auth/self-label.d.ts +0 -36
  227. package/dist/auth/self-label.js +0 -57
  228. package/dist/auth/self-label.js.map +0 -1
  229. package/dist/auth/trust-circle-store.d.ts +0 -26
  230. package/dist/auth/trust-circle-store.js +0 -129
  231. package/dist/auth/trust-circle-store.js.map +0 -1
  232. package/dist/auth/trust-circle.d.ts +0 -156
  233. package/dist/auth/trust-circle.js +0 -307
  234. package/dist/auth/trust-circle.js.map +0 -1
  235. package/dist/auth/types.d.ts +0 -84
  236. package/dist/auth/types.js +0 -24
  237. package/dist/auth/types.js.map +0 -1
  238. package/dist/donation/donation-service.d.ts +0 -389
  239. package/dist/donation/donation-service.js +0 -828
  240. package/dist/donation/donation-service.js.map +0 -1
  241. package/dist/donation/donation-store.d.ts +0 -51
  242. package/dist/donation/donation-store.js +0 -152
  243. package/dist/donation/donation-store.js.map +0 -1
  244. package/dist/donation/donation-supervisor.js +0 -364
  245. package/dist/donation/donation-supervisor.js.map +0 -1
  246. package/dist/donation/grant-service.d.ts +0 -80
  247. package/dist/donation/grant-service.js +0 -210
  248. package/dist/donation/grant-service.js.map +0 -1
  249. package/dist/donation/grant-store.d.ts +0 -38
  250. package/dist/donation/grant-store.js +0 -135
  251. package/dist/donation/grant-store.js.map +0 -1
  252. package/dist/donation/index.d.ts +0 -20
  253. package/dist/donation/index.js +0 -17
  254. package/dist/donation/index.js.map +0 -1
  255. package/dist/donation/types.d.ts +0 -224
  256. package/dist/donation/types.js +0 -40
  257. package/dist/donation/types.js.map +0 -1
  258. package/dist/installer/identity.js.map +0 -1
  259. package/dist/owner/index.d.ts +0 -11
  260. package/dist/owner/index.js +0 -11
  261. package/dist/owner/index.js.map +0 -1
  262. package/dist/owner/owner-node-client.d.ts +0 -110
  263. package/dist/owner/owner-node-client.js +0 -184
  264. package/dist/owner/owner-node-client.js.map +0 -1
  265. package/dist/server/routes/bootstrap-node-validation.d.ts +0 -115
  266. package/dist/server/routes/bootstrap-node-validation.js +0 -197
  267. package/dist/server/routes/bootstrap-node-validation.js.map +0 -1
  268. package/dist/server/routes/grants-admin.d.ts +0 -29
  269. package/dist/server/routes/grants-admin.js +0 -58
  270. package/dist/server/routes/grants-admin.js.map +0 -1
  271. package/dist/server/routes/grants.d.ts +0 -28
  272. package/dist/server/routes/grants.js +0 -165
  273. package/dist/server/routes/grants.js.map +0 -1
  274. package/dist/server/routes/provision-request-validation.d.ts +0 -45
  275. package/dist/server/routes/provision-request-validation.js +0 -97
  276. package/dist/server/routes/provision-request-validation.js.map +0 -1
  277. package/dist/server/routes/strands.d.ts +0 -20
  278. package/dist/server/routes/strands.js +0 -38
  279. package/dist/server/routes/strands.js.map +0 -1
  280. package/dist/server/routes/trust-circle.d.ts +0 -17
  281. package/dist/server/routes/trust-circle.js +0 -35
  282. package/dist/server/routes/trust-circle.js.map +0 -1
  283. package/dist/strands/index.d.ts +0 -7
  284. package/dist/strands/index.js +0 -6
  285. package/dist/strands/index.js.map +0 -1
  286. package/dist/strands/strand-service.d.ts +0 -50
  287. package/dist/strands/strand-service.js +0 -103
  288. package/dist/strands/strand-service.js.map +0 -1
  289. package/dist/strands/types.d.ts +0 -93
  290. package/dist/strands/types.js +0 -23
  291. package/dist/strands/types.js.map +0 -1
  292. package/dist/ui/assets/index-C6nELNfC.js +0 -23
  293. package/dist/ui/assets/index-C6nELNfC.js.map +0 -1
  294. package/dist/ui/assets/index-TtIYSeZO.css +0 -1
  295. package/src/__tests__/cli-invite.smoke.test.ts +0 -192
  296. package/src/__tests__/host-owner.smoke.test.ts +0 -123
  297. package/src/__tests__/orchestrator-owner.test.ts +0 -234
  298. package/src/__tests__/orchestrator-pin-keys.test.ts +0 -152
  299. package/src/auth/__tests__/duration.test.ts +0 -28
  300. package/src/auth/__tests__/self-label.test.ts +0 -85
  301. package/src/auth/__tests__/trust-circle-integration.test.ts +0 -152
  302. package/src/auth/__tests__/trust-circle-store.test.ts +0 -115
  303. package/src/auth/__tests__/trust-circle.test.ts +0 -445
  304. package/src/auth/duration.ts +0 -33
  305. package/src/auth/index.ts +0 -21
  306. package/src/auth/self-label.ts +0 -74
  307. package/src/auth/trust-circle-store.ts +0 -155
  308. package/src/auth/trust-circle.ts +0 -395
  309. package/src/auth/types.ts +0 -99
  310. package/src/donation/__tests__/donation-service.test.ts +0 -1193
  311. package/src/donation/__tests__/donation-supervisor.test.ts +0 -548
  312. package/src/donation/__tests__/grant-service.test.ts +0 -213
  313. package/src/donation/__tests__/grant-store.test.ts +0 -113
  314. package/src/donation/donation-service.ts +0 -1033
  315. package/src/donation/donation-store.ts +0 -176
  316. package/src/donation/donation-supervisor.ts +0 -411
  317. package/src/donation/grant-service.ts +0 -252
  318. package/src/donation/grant-store.ts +0 -152
  319. package/src/donation/index.ts +0 -65
  320. package/src/donation/types.ts +0 -260
  321. package/src/owner/__tests__/owner-node-client.test.ts +0 -194
  322. package/src/owner/index.ts +0 -12
  323. package/src/owner/owner-node-client.ts +0 -259
  324. package/src/server/__tests__/bootstrap-node-validation.test.ts +0 -138
  325. package/src/server/__tests__/grants-admin-route.test.ts +0 -171
  326. package/src/server/__tests__/grants-route.test.ts +0 -394
  327. package/src/server/__tests__/strands-route.test.ts +0 -234
  328. package/src/server/routes/bootstrap-node-validation.ts +0 -206
  329. package/src/server/routes/grants-admin.ts +0 -74
  330. package/src/server/routes/grants.ts +0 -193
  331. package/src/server/routes/provision-request-validation.ts +0 -105
  332. package/src/server/routes/strands.ts +0 -54
  333. package/src/server/routes/trust-circle.ts +0 -49
  334. package/src/strands/__tests__/strand-service.test.ts +0 -165
  335. package/src/strands/index.ts +0 -14
  336. package/src/strands/strand-service.ts +0 -135
  337. package/src/strands/types.ts +0 -102
@@ -0,0 +1,666 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import debug from 'debug';
3
+ import { CLAIM_SECRET_BYTES, decodeCadreInvitation } from '@serfab/cadre-core';
4
+ import { buildClaimDetails } from './claim-details.js';
5
+ import { HostedNodeWatcher } from './hosted-node-watcher.js';
6
+ import { PLACEHOLDER_PARTY, errorMessage, readNodeStatus, statusUrlFor } from './node-status.js';
7
+ import { HostedNodeError } from './types.js';
8
+ const log = debug('cadre:host:hosted-node-service');
9
+ /**
10
+ * The only statuses a node may come back from. An allowlist, not a terminal
11
+ * denylist: `error` is a node the host gave up on, and `spawning` is a join still
12
+ * in flight — replaying its spawn would race that join and strand the record in
13
+ * `spawning`, which only the stuck-`spawning` reap collects.
14
+ *
15
+ * Checked twice in {@link HostedNodeService.respawn} — once on entry, once after
16
+ * the spawn — so the "may this node come back" rule is stated exactly once.
17
+ */
18
+ const RESPAWNABLE_STATUSES = new Set([
19
+ 'unclaimed',
20
+ 'joining',
21
+ 'joined',
22
+ ]);
23
+ /**
24
+ * Age after which a record still stuck in `spawning` is marked `error` and its
25
+ * child, if any, reclaimed: the host wrote the row before starting the child, and
26
+ * a crash/kill in that window (or during the spawn itself) leaves nothing to
27
+ * advance it across a restart. A real spawn (identity key read/gen, port
28
+ * allocation, process spawn) completes in well under a second normally, so 5
29
+ * minutes is generously past "any plausible spawn" without risking a false reap
30
+ * of one still genuinely in flight under heavy load.
31
+ */
32
+ export const HOSTED_NODE_SPAWNING_TTL_MS = 5 * 60 * 1000;
33
+ /** How often the stuck-`spawning` reap runs while cadre-host is up. 5 minutes. */
34
+ export const HOSTED_NODE_REAP_SWEEP_MS = 5 * 60 * 1000;
35
+ /**
36
+ * HostedNodeService — the host's one action, "Join a cadre", and what follows from it.
37
+ *
38
+ * `join` starts a child waiting to be claimed, or one that redeems a cadre invitation;
39
+ * `claimDetails` reads a waiting node's addresses and builds the QR payload; the status
40
+ * watcher ({@link startWatching}) notices the claim or the redemption's outcome, and the
41
+ * node's liveness; `respawn` brings a dead child back as the same node with the same
42
+ * secret and ports; `retry` starts an invitation node again after no member could be
43
+ * reached; `remove` and `reset` end it. The host contributes capacity only: it never
44
+ * holds an owner key.
45
+ *
46
+ * **An ending that lands mid-operation wins.** Spawning a child takes seconds, and
47
+ * a `remove` can land inside that window. `hosted-nodes.json` is written a whole row
48
+ * at a time, so every long operation re-reads the record after its wait, decides
49
+ * against what is actually stored, and merges forward only the fields it itself
50
+ * produced — never the entry-time copy.
51
+ *
52
+ * **Respawns run one at a time** ({@link serializeRespawns}): the supervisor's passes and
53
+ * restarts and `retry` share one queue, since two overlapping respawns of one id both spawn
54
+ * a child and the second drops the first's orchestrator handle.
55
+ */
56
+ export class HostedNodeService {
57
+ constructor(opts) {
58
+ this.listeners = new Set();
59
+ /** Serialization tail for `join`, so two joins at once cannot interleave their store writes. */
60
+ this.joinTail = Promise.resolve();
61
+ /** Serialization tail for every respawn — see {@link serializeRespawns}. */
62
+ this.respawnTail = Promise.resolve();
63
+ this.orchestrator = opts.orchestrator;
64
+ this.store = opts.store;
65
+ this.addresses = opts.addresses;
66
+ this.now = opts.now ?? (() => new Date());
67
+ this.watcher = new HostedNodeWatcher({
68
+ store: this.store,
69
+ orchestrator: this.orchestrator,
70
+ now: this.now,
71
+ emit: (change) => this.emit(change),
72
+ });
73
+ log('HostedNodeService initialized');
74
+ }
75
+ /** Register a change listener (the server publishes each change as an SSE event). Returns an unsubscribe fn. */
76
+ onChange(listener) {
77
+ this.listeners.add(listener);
78
+ return () => { this.listeners.delete(listener); };
79
+ }
80
+ /**
81
+ * Report a change to the listeners. Public for the supervisor's give-up, which
82
+ * writes the record itself; a listener that throws is logged, never propagated.
83
+ */
84
+ emit(change) {
85
+ for (const listener of this.listeners) {
86
+ try {
87
+ listener(change);
88
+ }
89
+ catch (err) {
90
+ log('change listener threw for %s: %s', change.id, errorMessage(err));
91
+ }
92
+ }
93
+ }
94
+ /** Start following every node's `/status` (claims and liveness). Idempotent. */
95
+ startWatching() {
96
+ this.watcher.start();
97
+ }
98
+ stopWatching() {
99
+ this.watcher.stop();
100
+ }
101
+ /** One status pass now, awaited — for tests and callers that need the result before going on. */
102
+ pollStatuses() {
103
+ return this.watcher.poll();
104
+ }
105
+ /**
106
+ * Start a node: write the record, spawn the child, and record its handles. Without an
107
+ * invitation the node waits to be claimed — a fresh claim secret, the placeholder
108
+ * party, `unclaimed`. With one it redeems the invitation — the invitation's party,
109
+ * `joining` — and an invitation that does not decode is `invalid_request` before
110
+ * anything is written. On any orchestrator failure the reserved resources are
111
+ * reclaimed and the record is marked `error`. Resolves once the child is spawned; its
112
+ * `/status` may take a few seconds more, which `claimDetails` reports as
113
+ * `node_unavailable`.
114
+ */
115
+ async join(opts = {}) {
116
+ const invitation = opts.invitation === undefined ? undefined : decodeInvitation(opts.invitation);
117
+ return this.serializeJoin(() => this.joinLocked(invitation));
118
+ }
119
+ async joinLocked(invitation) {
120
+ const id = generateHostedNodeId();
121
+ const nowIso = this.now().toISOString();
122
+ const join = invitation
123
+ ? { kind: 'invitation', encoded: invitation.encoded }
124
+ : { kind: 'claim', secret: generateClaimSecret() };
125
+ const record = {
126
+ id,
127
+ join,
128
+ partyId: invitation ? invitation.decoded.partyId : PLACEHOLDER_PARTY,
129
+ profile: 'storage',
130
+ status: 'spawning',
131
+ createdAt: nowIso,
132
+ updatedAt: nowIso,
133
+ };
134
+ this.store.put(record);
135
+ // The spawn is the only step that can fail before anything is allocated, so
136
+ // it gets a `try` of its own — a wider one would swallow the abandon decision
137
+ // below and mark a removal as a host-side `error`.
138
+ let result;
139
+ try {
140
+ result = await this.orchestrator.createContainer(spawnRequestFor(record));
141
+ }
142
+ catch (err) {
143
+ const message = errorMessage(err);
144
+ log('spawn of hosted node %s failed: %s', id, message);
145
+ this.markSpawnFailed(id, message);
146
+ throw new HostedNodeError('orchestrator_error', `Failed to start hosted node: ${message}`);
147
+ }
148
+ // Re-read: `record` predates the orchestrator round-trip (seconds of wall
149
+ // clock) and `store.put` replaces the whole row, so writing that copy back
150
+ // would resurrect a node removed while the spawn was in flight. The store is
151
+ // synchronous, so this read-decide-write is atomic against the event loop
152
+ // only as long as no `await` sneaks in between.
153
+ const current = this.store.get(id);
154
+ if (!current || current.status !== 'spawning') {
155
+ // The removal cleaned up nothing: the record named no `dockerId` yet, so
156
+ // `remove`'s stop-and-reclaim never ran and this child is the only thing
157
+ // holding the spawn's ports and workdir. Reclaim (not merely stop) — the
158
+ // workdir was created by this very spawn, so there is nothing to preserve.
159
+ log('hosted node %s went %s during its spawn — abandoning new child %s', id, current?.status ?? 'missing', result.dockerId);
160
+ await this.safeReclaim(result.dockerId);
161
+ throw current
162
+ ? new HostedNodeError('invalid_state', `Hosted node ${id} was ${current.status} before it finished starting`)
163
+ : new HostedNodeError('not_found', `No such hosted node: ${id}`);
164
+ }
165
+ const started = {
166
+ ...current,
167
+ ...handlesOf(result),
168
+ status: invitation ? 'joining' : 'unclaimed',
169
+ updatedAt: this.now().toISOString(),
170
+ };
171
+ try {
172
+ this.store.put(started);
173
+ }
174
+ catch (err) {
175
+ const message = errorMessage(err);
176
+ log('recording hosted node %s failed: %s', id, message);
177
+ await this.safeReclaim(result.dockerId);
178
+ this.markSpawnFailed(id, message);
179
+ throw new HostedNodeError('orchestrator_error', `Failed to start hosted node: ${message}`);
180
+ }
181
+ log(invitation ? 'hosted node %s is up and redeeming its invitation' : 'hosted node %s is up and waiting to be claimed', id);
182
+ this.emit({ kind: 'added', id });
183
+ this.watcher.poke(id);
184
+ return redact(started);
185
+ }
186
+ /**
187
+ * Mark a still-`spawning` record as failed — and ONLY such a record. A row that
188
+ * was removed while the spawn was in flight must not be recreated.
189
+ *
190
+ * Best-effort (mirroring {@link storeRespawnAttempt}): we are already unwinding a
191
+ * spawn failure, and a store error here must not mask the error being reported
192
+ * to the caller.
193
+ */
194
+ markSpawnFailed(id, message) {
195
+ try {
196
+ const current = this.store.get(id);
197
+ if (current?.status !== 'spawning')
198
+ return;
199
+ this.store.put({ ...current, status: 'error', error: message, updatedAt: this.now().toISOString() });
200
+ this.emit({ kind: 'changed', id });
201
+ }
202
+ catch (err) {
203
+ log('failed to mark hosted node %s as errored: %s', id, errorMessage(err));
204
+ }
205
+ }
206
+ /**
207
+ * What the QR code carries for a node waiting to be claimed: its peer id, the
208
+ * addresses a phone may dial it at, and its claim secret — the only place the
209
+ * secret ever leaves the host. `409 invalid_state` unless the node is `unclaimed`;
210
+ * `503 node_unavailable` until the child's `/status` answers (callers poll).
211
+ */
212
+ async claimDetails(id) {
213
+ const node = this.requireNode(id);
214
+ if (node.status !== 'unclaimed' || node.join.kind !== 'claim') {
215
+ throw new HostedNodeError('invalid_state', `Hosted node ${id} is ${node.status}; only a node waiting to be claimed has claim details`);
216
+ }
217
+ if (!node.statusEndpoint) {
218
+ throw new HostedNodeError('node_unavailable', `Hosted node ${id} has no status endpoint yet`);
219
+ }
220
+ const { secret } = node.join;
221
+ const status = await readNodeStatus(node.statusEndpoint);
222
+ this.recordPeerId(id, status.peerId);
223
+ return buildClaimDetails({ id, secret, status, ports: this.orchestrator.getNode?.(id)?.ports, addresses: this.addresses });
224
+ }
225
+ /** Cache the peer id on the record, once. Best-effort: the claim details do not depend on it. */
226
+ recordPeerId(id, peerId) {
227
+ try {
228
+ // Re-read: the entry-time copy predates the `/status` round-trip.
229
+ const current = this.store.get(id);
230
+ if (!current || current.peerId === peerId)
231
+ return;
232
+ this.store.put({ ...current, peerId });
233
+ }
234
+ catch (err) {
235
+ log('failed to record peer id of hosted node %s: %s', id, errorMessage(err));
236
+ }
237
+ }
238
+ /**
239
+ * Re-spawn a node that is no longer running, replaying the record's party and
240
+ * claim secret, or its invitation while it is still `joining`. The node keeps its
241
+ * workdir — and with it its identity key and node-local stores — and comes back on
242
+ * the same ports, so it is the *same* peer at the same addresses: a QR code already
243
+ * shown stays valid, and a joined node's cadre finds it where it was. Keeping the
244
+ * secret after the claim is deliberate: `cadre-cli` honours `claim.json` and, with the
245
+ * secret still set, answers a rival `already-claimed`. A joined invitation node comes
246
+ * back without its invitation ({@link spawnRequestFor} says why).
247
+ *
248
+ * **Status is deliberately unchanged.** A `joined` node stays `joined`; an
249
+ * `unclaimed` one keeps waiting, a `joining` one redeems again. `connected` is
250
+ * dropped until the watcher reads the new child.
251
+ *
252
+ * **An ending that lands mid-spawn wins.** The record is re-read after the
253
+ * orchestrator returns; if it was removed (or went `error`) while the child was
254
+ * starting, that write stands and the new child is abandoned — see
255
+ * {@link abandonRespawn}. An abandoned respawn is a skip, not a failure, so a
256
+ * sweep over the store keeps going. Orchestrator failures DO throw; the caller
257
+ * owns backoff/give-up.
258
+ *
259
+ * Not serialized itself: callers run it on {@link serializeRespawns}. Two overlapping
260
+ * calls for the same id both spawn a child, and the second spawn drops the first's
261
+ * orchestrator handle — leaving an unmanaged process.
262
+ */
263
+ async respawn(id, opts = {}) {
264
+ const node = this.requireNode(id);
265
+ // Callers filter for this already; the guard is here so no future one can
266
+ // resurrect or double-spawn a node by omission.
267
+ if (!RESPAWNABLE_STATUSES.has(node.status)) {
268
+ throw new HostedNodeError('invalid_state', `Hosted node ${id} cannot be respawned in status ${node.status}`);
269
+ }
270
+ // Just the counters, never a whole row copy: both exits below merge these
271
+ // onto whatever the store holds *after* the spawn, and an entry-time record
272
+ // in scope is a standing invitation to write the stale row back.
273
+ const attempt = opts.countAttempt === false
274
+ ? undefined
275
+ : { attempts: (node.respawn?.attempts ?? 0) + 1, lastAttemptAt: this.now().toISOString() };
276
+ let spawned;
277
+ try {
278
+ const result = await this.orchestrator.createContainer(spawnRequestFor(node));
279
+ spawned = handlesOf(result);
280
+ // Re-read: see `joinLocked`. A removal or a give-up that landed while the
281
+ // spawn was in flight must stand.
282
+ const current = this.store.get(id);
283
+ if (!current || !RESPAWNABLE_STATUSES.has(current.status)) {
284
+ return this.abandonRespawn(id, spawned, current);
285
+ }
286
+ const { connected: _connected, ...rest } = current;
287
+ const respawned = {
288
+ ...rest,
289
+ ...(attempt ? { respawn: attempt, updatedAt: this.now().toISOString() } : {}),
290
+ ...spawned,
291
+ };
292
+ this.store.put(respawned);
293
+ log('respawned hosted node %s → %s (status %s)', id, result.dockerId, respawned.status);
294
+ this.emit({ kind: 'changed', id });
295
+ this.watcher.poke(id);
296
+ return { outcome: 'respawned', node: redact(respawned) };
297
+ }
298
+ catch (err) {
299
+ const message = errorMessage(err);
300
+ log('respawn of hosted node %s failed: %s', id, message);
301
+ // Stop — never reclaim — a child we spawned but failed to record:
302
+ // `removeContainer` deletes the workdir, which holds the identity key and
303
+ // node-local stores that are the whole reason a respawn is the same node.
304
+ // The new handles go onto the record below, so it names the child that
305
+ // actually exists and a later `remove()` reclaims that one.
306
+ if (spawned)
307
+ await this.safeStop(spawned.dockerId);
308
+ this.storeRespawnAttempt(id, attempt, spawned);
309
+ throw new HostedNodeError('orchestrator_error', `Failed to respawn hosted node: ${message}`);
310
+ }
311
+ }
312
+ /**
313
+ * Start an invitation node again after no member of its cadre could be reached: the
314
+ * `error` record goes back to `joining` and is respawned with its invitation, without
315
+ * spending a respawn attempt. On the respawn queue, so it never overlaps the
316
+ * supervisor's handling of the same node. `409 invalid_state` unless the node is `error`
317
+ * with `retryable` — a refused invitation stays refused, and the supervisor's give-up and
318
+ * the other failures are a reset's.
319
+ */
320
+ retry(id) {
321
+ return this.serializeRespawns(() => this.retryLocked(id));
322
+ }
323
+ async retryLocked(id) {
324
+ const node = this.requireNode(id);
325
+ if (node.status !== 'error' || node.retryable !== true) {
326
+ throw new HostedNodeError('invalid_state', `Hosted node ${id} is ${node.status}${node.status === 'error' ? ' and not retryable' : ''}; only an invitation no member could be reached for can be retried`);
327
+ }
328
+ // The watcher stops a child whose redemption failed; one still running (that stop
329
+ // failed, or a host restart re-attached it) would make the spawn below refuse.
330
+ if (node.dockerId && await this.orchestrator.isRunning(node.dockerId))
331
+ await this.safeStop(node.dockerId);
332
+ // Re-read: the stop is an await, and a removal may have landed in it.
333
+ const current = this.store.get(id);
334
+ if (current?.status !== 'error') {
335
+ throw current
336
+ ? new HostedNodeError('invalid_state', `Hosted node ${id} went ${current.status} before its retry started`)
337
+ : new HostedNodeError('not_found', `No such hosted node: ${id}`);
338
+ }
339
+ const { error: _error, retryable: _retryable, ...rest } = current;
340
+ this.store.put({ ...rest, status: 'joining', updatedAt: this.now().toISOString() });
341
+ log('retrying the invitation of hosted node %s', id);
342
+ this.emit({ kind: 'changed', id });
343
+ // A respawn that throws leaves the record `joining` with no child, which the
344
+ // supervisor's next pass respawns, counting the attempt.
345
+ const result = await this.respawn(id, { countAttempt: false });
346
+ if (result.outcome === 'abandoned') {
347
+ throw result.status
348
+ ? new HostedNodeError('invalid_state', `Hosted node ${id} went ${result.status} while its retry was starting`)
349
+ : new HostedNodeError('not_found', `No such hosted node: ${id}`);
350
+ }
351
+ return result.node;
352
+ }
353
+ /**
354
+ * Give up on a respawn whose record ended while the child was starting: stop
355
+ * the new child and, unless the record went `error`, reclaim it.
356
+ *
357
+ * Reclaim, not merely stop. The removal's own cleanup already ran and found
358
+ * nothing: `HostProcessOrchestrator.createContainer` calls `dropStaleHandle`
359
+ * *while* spawning, so by the time the concurrent `remove` reached its
360
+ * stop/reclaim the old handle was gone and both calls were swallowed as
361
+ * best-effort no-ops. The new handle is now the only thing holding that
362
+ * spawn's ports and workdir, so stopping alone would leak both.
363
+ *
364
+ * `error` is the deliberate exception: `removeContainer` deletes the workdir,
365
+ * and `HostedNodeSupervisor.giveUp` keeps it on purpose so the identity key the
366
+ * node's cadre approved survives. Since both spawns share one workdir
367
+ * (`<rootDir>/<containerId>`), reclaiming here would delete exactly what
368
+ * `giveUp` meant to keep.
369
+ *
370
+ * The `error` record is then pointed at the new child, the one that exists, so a
371
+ * later `remove` reclaims its ports and workdir. `giveUp` runs on the respawn queue
372
+ * and cannot overlap a respawn; the watcher's write of a failed invitation can, when
373
+ * a poll of the old child answers while the new one is starting.
374
+ */
375
+ async abandonRespawn(id, spawned, current) {
376
+ const status = current?.status;
377
+ log('hosted node %s went %s during respawn — abandoning new child %s', id, status ?? 'missing', spawned.dockerId);
378
+ await this.safeStop(spawned.dockerId);
379
+ if (status === 'error')
380
+ this.storeRespawnAttempt(id, undefined, spawned);
381
+ else
382
+ await this.safeReclaim(spawned.dockerId);
383
+ return status ? { outcome: 'abandoned', status } : { outcome: 'abandoned' };
384
+ }
385
+ /**
386
+ * Remove a hosted node: delete the row FIRST, then stop and reclaim the child
387
+ * (its workdir, identity key and data go with it). The node's cadre keeps the
388
+ * node's row until its owner removes it there.
389
+ *
390
+ * Order matters: stopping the child fires the orchestrator's `onStateChange`,
391
+ * and the supervisor's exit-triggered pass must find no record — otherwise it
392
+ * observes "node gone, record still `joined`" and brings back a node the admin
393
+ * just removed. The tradeoff: a crash between the delete and the stop leaves a
394
+ * running child no record names, which `remove` on its id still reclaims (below).
395
+ *
396
+ * A handle no record names — `hosted-nodes.json` lost, or a handle an older
397
+ * build persisted — is removed the same way, so `/api/nodes` cannot list a node
398
+ * for good that nothing can end.
399
+ */
400
+ async remove(id) {
401
+ const node = this.store.get(id);
402
+ if (!node) {
403
+ await this.removeOrphanHandle(id);
404
+ return;
405
+ }
406
+ this.store.remove(id);
407
+ if (node.dockerId) {
408
+ await this.safeStop(node.dockerId);
409
+ await this.safeReclaim(node.dockerId);
410
+ }
411
+ else {
412
+ // No `dockerId` — the spawn never got far enough to produce one, so the
413
+ // stop-and-reclaim above has nothing to aim at and the node's working
414
+ // directory would be stranded on disk with nothing able to name it.
415
+ //
416
+ // NOTE: this can race an in-flight `join` for the same record — the delete
417
+ // may land between that spawn's `mkdirSync` and its `spawn`. The end state
418
+ // is still correct (`joinLocked`'s post-spawn re-read sees no record and
419
+ // reclaims the new child, which deletes the workdir anyway); the interim
420
+ // delete can only make that child fail to start noisily, which is strictly
421
+ // better than a permanent strand.
422
+ this.safeReclaimWorkdir(id);
423
+ }
424
+ log('hosted node %s removed', id);
425
+ this.emit({ kind: 'removed', id });
426
+ }
427
+ async removeOrphanHandle(id) {
428
+ const dockerId = this.orchestrator.resolveDockerId?.(id);
429
+ if (!dockerId)
430
+ throw new HostedNodeError('not_found', `No such hosted node: ${id}`);
431
+ log('hosted node %s has a handle but no record — removing the handle', id);
432
+ await this.safeStop(dockerId);
433
+ await this.safeReclaim(dockerId);
434
+ this.emit({ kind: 'removed', id });
435
+ }
436
+ /**
437
+ * Remove a node and start a fresh one waiting to be claimed, with a new secret and
438
+ * identity. For the case where someone else photographed the QR code and claimed the
439
+ * node first, and for an `error` node the admin wants to try again. An invitation node
440
+ * is replaced by one waiting to be claimed too: its invitation may be spent, and the
441
+ * admin can join with a fresh one instead.
442
+ */
443
+ async reset(id) {
444
+ await this.remove(id);
445
+ return this.join();
446
+ }
447
+ /**
448
+ * Mark records stuck in `spawning` past `ttlMs` as `error` and reclaim whatever
449
+ * the orchestrator can still find for them — the record is written before the
450
+ * child spawn starts, so a host crash/kill anywhere in that window (including
451
+ * mid-spawn) leaves nothing to advance it across a restart. Run once at
452
+ * startup and on a periodic sweep. Age is measured from `updatedAt`, which for
453
+ * a genuinely-stuck row equals `createdAt` — `joinLocked` never touches a
454
+ * `spawning` record again except to advance it out of this predicate.
455
+ * Best-effort per record: a failed reap is logged and the sweep continues.
456
+ * Returns the reaped ids.
457
+ */
458
+ async reapStuckSpawning(ttlMs = HOSTED_NODE_SPAWNING_TTL_MS) {
459
+ const cutoff = this.now().getTime() - ttlMs;
460
+ const stale = this.store.list().filter((n) => isStuckSpawning(n, cutoff));
461
+ const reaped = [];
462
+ for (const node of stale) {
463
+ try {
464
+ // Re-read: an in-flight (same-process) `joinLocked` call can still
465
+ // advance this exact record between the snapshot above and now.
466
+ const current = this.store.get(node.id);
467
+ if (!current || !isStuckSpawning(current, cutoff))
468
+ continue;
469
+ await this.reclaimStuckSpawning(current);
470
+ reaped.push(node.id);
471
+ log('reaped stuck spawning hosted node %s (age > %dms)', node.id, ttlMs);
472
+ }
473
+ catch (err) {
474
+ log('failed to reap stuck spawning hosted node %s: %s', node.id, errorMessage(err));
475
+ }
476
+ }
477
+ return reaped;
478
+ }
479
+ /**
480
+ * Terminalize a stuck-`spawning` record as `error` and reclaim any child the
481
+ * orchestrator can still find for it. Status is written FIRST (same ordering
482
+ * rule as {@link remove}): reclaiming fires `onStateChange`, and anything
483
+ * listening must already see a terminal record.
484
+ *
485
+ * NOTE: the stop only reaches a child the orchestrator has a handle for.
486
+ * `HostProcessOrchestrator.launchChild` spawns the process and persists the
487
+ * handle in the same synchronous step, so the only child this misses is one
488
+ * whose host died between the OS spawn and that write — an orphan *process*
489
+ * this reap terminalizes the record for but cannot kill (its ports stay held
490
+ * until a reboot). Its working directory is reclaimed by container name when
491
+ * no handle resolves, which also covers the far commoner case of a host that
492
+ * died before any child existed at all.
493
+ */
494
+ async reclaimStuckSpawning(node) {
495
+ this.store.put({
496
+ ...node,
497
+ status: 'error',
498
+ error: 'stuck starting past its deadline — the host likely restarted mid-spawn',
499
+ updatedAt: this.now().toISOString(),
500
+ });
501
+ this.emit({ kind: 'changed', id: node.id });
502
+ const dockerId = this.orchestrator.resolveDockerId?.(node.id);
503
+ if (dockerId) {
504
+ await this.safeStop(dockerId);
505
+ await this.safeReclaim(dockerId);
506
+ }
507
+ else {
508
+ this.safeReclaimWorkdir(node.id);
509
+ }
510
+ }
511
+ /** One node (secret stripped), or undefined when unknown. */
512
+ get(id) {
513
+ const node = this.store.get(id);
514
+ return node ? redact(node) : undefined;
515
+ }
516
+ /** Every node (secret stripped). */
517
+ list() {
518
+ return this.store.list().map(redact);
519
+ }
520
+ requireNode(id) {
521
+ const node = this.store.get(id);
522
+ if (!node)
523
+ throw new HostedNodeError('not_found', `No such hosted node: ${id}`);
524
+ return node;
525
+ }
526
+ /** Best-effort stop; logs but never throws (cleanup path). */
527
+ async safeStop(dockerId) {
528
+ try {
529
+ await this.orchestrator.stopContainer(dockerId);
530
+ }
531
+ catch (err) {
532
+ log('failed to stop container %s: %s', dockerId, errorMessage(err));
533
+ }
534
+ }
535
+ /**
536
+ * Persist a failed respawn's attempt counters (none for an uncounted restart) —
537
+ * plus, when the spawn itself succeeded and it was the record write that failed,
538
+ * the new child's handles. Merged onto whatever is on disk now, never written
539
+ * wholesale: the caller's copy predates the orchestrator round-trip.
540
+ *
541
+ * `status` and `updatedAt` are deliberately untouched — the attempt did not succeed.
542
+ *
543
+ * Recording `spawned` is what keeps the record pointing at the child that
544
+ * actually exists: `createContainer` already dropped the handle the record
545
+ * previously named, so leaving the old `dockerId` there would send every later
546
+ * stop/reclaim at an id the orchestrator cannot resolve — stranding the node's
547
+ * workdir on disk forever.
548
+ *
549
+ * Best-effort: we are already unwinding a respawn failure, and a store error
550
+ * here must not mask it. Losing the write costs the caller one extra attempt
551
+ * before backoff; the supervisor's next pass re-reads the record, finds the
552
+ * named child not running, and respawns again — which drops whatever handle is
553
+ * current, so the ports self-heal either way.
554
+ */
555
+ storeRespawnAttempt(id, respawn, spawned) {
556
+ if (!respawn && !spawned)
557
+ return;
558
+ try {
559
+ // A row that vanished (a removal) must not be recreated.
560
+ const current = this.store.get(id);
561
+ if (!current)
562
+ return;
563
+ this.store.put({ ...current, ...(respawn ? { respawn } : {}), ...spawned });
564
+ }
565
+ catch (err) {
566
+ log('failed to record respawn attempt for %s: %s', id, errorMessage(err));
567
+ }
568
+ }
569
+ /** Best-effort remove; logs but never throws (cleanup path). */
570
+ async safeReclaim(dockerId) {
571
+ try {
572
+ await this.orchestrator.removeContainer(dockerId);
573
+ }
574
+ catch (err) {
575
+ log('failed to reclaim container %s: %s', dockerId, errorMessage(err));
576
+ }
577
+ }
578
+ /**
579
+ * Best-effort removal of the working directory of a node whose spawn never
580
+ * produced a `dockerId`; logs but never throws (cleanup path). A no-op on an
581
+ * orchestrator without the capability, and on one that refuses because a live
582
+ * handle still owns the directory.
583
+ */
584
+ safeReclaimWorkdir(id) {
585
+ try {
586
+ if (this.orchestrator.reclaimWorkdir?.(id)) {
587
+ log('reclaimed orphaned workdir for hosted node %s', id);
588
+ }
589
+ }
590
+ catch (err) {
591
+ log('failed to reclaim workdir for hosted node %s: %s', id, errorMessage(err));
592
+ }
593
+ }
594
+ /** Run `fn` after any in-flight join. */
595
+ serializeJoin(fn) {
596
+ const run = this.joinTail.then(fn, fn);
597
+ // The stored tail swallows outcomes — a rejected join must not reject the
598
+ // next caller's wait, only defer it.
599
+ this.joinTail = run.then(() => undefined, () => undefined);
600
+ return run;
601
+ }
602
+ /**
603
+ * Run `fn` after every respawn already queued. Every caller of {@link respawn} goes
604
+ * through here: the supervisor's reconcile passes and restarts, and {@link retry}.
605
+ */
606
+ serializeRespawns(fn) {
607
+ const run = this.respawnTail.then(fn, fn);
608
+ // As in `serializeJoin`: a failed pass only sequences the next one, never rejects it.
609
+ this.respawnTail = run.then(() => undefined, () => undefined);
610
+ return run;
611
+ }
612
+ }
613
+ /** `hn_<high-entropy base64url>` — also the node's orchestrator containerId and workdir name. */
614
+ function generateHostedNodeId() {
615
+ return `hn_${randomBytes(12).toString('base64url')}`;
616
+ }
617
+ function generateClaimSecret() {
618
+ return randomBytes(CLAIM_SECRET_BYTES).toString('base64url');
619
+ }
620
+ /** Decode a pasted invitation; one that does not decode is `invalid_request` with the decoder's reason. */
621
+ function decodeInvitation(encoded) {
622
+ const trimmed = encoded.trim();
623
+ try {
624
+ return { encoded: trimmed, decoded: decodeCadreInvitation(trimmed) };
625
+ }
626
+ catch (err) {
627
+ throw new HostedNodeError('invalid_request', `The invitation does not decode: ${errorMessage(err)}`);
628
+ }
629
+ }
630
+ /**
631
+ * The spawn a record describes: its party, profile, and how it gets into its cadre. Used
632
+ * by `join` and `respawn` alike.
633
+ *
634
+ * An invitation is passed until the node has joined, and never after: a joined node is a
635
+ * member whose rows are in its own control database, and an invitation that expired
636
+ * meanwhile must not turn a healthy member's restart into a refusal.
637
+ */
638
+ function spawnRequestFor(node) {
639
+ const base = {
640
+ containerId: node.id,
641
+ partyId: node.partyId,
642
+ bootstrapNodes: [],
643
+ profile: node.profile,
644
+ };
645
+ if (node.join.kind === 'claim')
646
+ return { ...base, claimSecret: node.join.secret };
647
+ return node.status === 'joined' ? base : { ...base, invitation: node.join.encoded };
648
+ }
649
+ /** The record fields a spawn result lands. `seedToken` and `seedEndpoint` are the provider's shape; cadre-host ignores both. */
650
+ function handlesOf(result) {
651
+ return { dockerId: result.dockerId, statusEndpoint: statusUrlFor(result.healthEndpoint) };
652
+ }
653
+ /** Strip the claim secret or the invitation. */
654
+ function redact(node) {
655
+ const { join, ...rest } = node;
656
+ return { ...rest, join: { kind: join.kind } };
657
+ }
658
+ /**
659
+ * Whether a record is still a stuck-`spawning` reap candidate. Stated once and
660
+ * applied twice in {@link HostedNodeService.reapStuckSpawning} — on the sweep's
661
+ * candidate list, and again per record before the terminal write.
662
+ */
663
+ function isStuckSpawning(node, cutoff) {
664
+ return node?.status === 'spawning' && Date.parse(node.updatedAt) < cutoff;
665
+ }
666
+ //# sourceMappingURL=hosted-node-service.js.map