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