@serfab/cadre-host 1.13.0 → 1.15.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 (352) hide show
  1. package/README.md +347 -423
  2. package/dist/bin/host.d.ts +6 -3
  3. package/dist/bin/host.js +332 -524
  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 +54 -0
  9. package/dist/bin/nat-output.js +138 -0
  10. package/dist/bin/nat-output.js.map +1 -0
  11. package/dist/bin/ui-access.d.ts +22 -0
  12. package/dist/bin/ui-access.js +44 -0
  13. package/dist/bin/ui-access.js.map +1 -0
  14. package/dist/hosted/claim-details.d.ts +66 -0
  15. package/dist/hosted/claim-details.js +60 -0
  16. package/dist/hosted/claim-details.js.map +1 -0
  17. package/dist/hosted/hosted-node-service.d.ts +325 -0
  18. package/dist/hosted/hosted-node-service.js +678 -0
  19. package/dist/hosted/hosted-node-service.js.map +1 -0
  20. package/dist/hosted/hosted-node-store.d.ts +40 -0
  21. package/dist/hosted/hosted-node-store.js +126 -0
  22. package/dist/hosted/hosted-node-store.js.map +1 -0
  23. package/dist/{donation/donation-supervisor.d.ts → hosted/hosted-node-supervisor.d.ts} +70 -53
  24. package/dist/hosted/hosted-node-supervisor.js +396 -0
  25. package/dist/hosted/hosted-node-supervisor.js.map +1 -0
  26. package/dist/hosted/hosted-node-watcher.d.ts +95 -0
  27. package/dist/hosted/hosted-node-watcher.js +260 -0
  28. package/dist/hosted/hosted-node-watcher.js.map +1 -0
  29. package/dist/hosted/index.d.ts +16 -0
  30. package/dist/hosted/index.js +13 -0
  31. package/dist/hosted/index.js.map +1 -0
  32. package/dist/hosted/node-status.d.ts +51 -0
  33. package/dist/hosted/node-status.js +77 -0
  34. package/dist/hosted/node-status.js.map +1 -0
  35. package/dist/hosted/types.d.ts +141 -0
  36. package/dist/hosted/types.js +22 -0
  37. package/dist/hosted/types.js.map +1 -0
  38. package/dist/index.d.ts +12 -24
  39. package/dist/index.js +9 -19
  40. package/dist/index.js.map +1 -1
  41. package/dist/installer/config.d.ts +27 -34
  42. package/dist/installer/config.js +46 -15
  43. package/dist/installer/config.js.map +1 -1
  44. package/dist/installer/index.d.ts +9 -19
  45. package/dist/installer/index.js +21 -85
  46. package/dist/installer/index.js.map +1 -1
  47. package/dist/installer/paths.d.ts +0 -2
  48. package/dist/installer/paths.js +0 -4
  49. package/dist/installer/paths.js.map +1 -1
  50. package/dist/installer/wizard.d.ts +12 -9
  51. package/dist/installer/wizard.js +15 -14
  52. package/dist/installer/wizard.js.map +1 -1
  53. package/dist/nat/address-resolver.d.ts +18 -17
  54. package/dist/nat/address-resolver.js +79 -25
  55. package/dist/nat/address-resolver.js.map +1 -1
  56. package/dist/nat/address-watch.d.ts +37 -0
  57. package/dist/nat/address-watch.js +84 -0
  58. package/dist/nat/address-watch.js.map +1 -0
  59. package/dist/nat/ddns/duckdns.d.ts +2 -1
  60. package/dist/nat/ddns/duckdns.js +5 -1
  61. package/dist/nat/ddns/duckdns.js.map +1 -1
  62. package/dist/nat/ddns/index.d.ts +6 -0
  63. package/dist/nat/ddns/index.js.map +1 -1
  64. package/dist/nat/index.d.ts +13 -9
  65. package/dist/nat/index.js +7 -5
  66. package/dist/nat/index.js.map +1 -1
  67. package/dist/nat/nat-service.d.ts +220 -77
  68. package/dist/nat/nat-service.js +653 -239
  69. package/dist/nat/nat-service.js.map +1 -1
  70. package/dist/nat/nat-store.d.ts +12 -5
  71. package/dist/nat/nat-store.js +124 -29
  72. package/dist/nat/nat-store.js.map +1 -1
  73. package/dist/nat/network-mode.d.ts +19 -0
  74. package/dist/nat/network-mode.js +32 -0
  75. package/dist/nat/network-mode.js.map +1 -0
  76. package/dist/nat/port-mapper.d.ts +83 -79
  77. package/dist/nat/port-mapper.js +148 -189
  78. package/dist/nat/port-mapper.js.map +1 -1
  79. package/dist/nat/reachability.d.ts +32 -15
  80. package/dist/nat/reachability.js +110 -22
  81. package/dist/nat/reachability.js.map +1 -1
  82. package/dist/nat/types.d.ts +98 -27
  83. package/dist/nat/types.js +8 -5
  84. package/dist/nat/types.js.map +1 -1
  85. package/dist/orchestrator/host-process-orchestrator.d.ts +32 -74
  86. package/dist/orchestrator/host-process-orchestrator.js +84 -233
  87. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  88. package/dist/{installer/identity.d.ts → orchestrator/identity-file.d.ts} +5 -5
  89. package/dist/{installer/identity.js → orchestrator/identity-file.js} +6 -6
  90. package/dist/orchestrator/identity-file.js.map +1 -0
  91. package/dist/orchestrator/index.d.ts +2 -3
  92. package/dist/orchestrator/index.js +1 -1
  93. package/dist/orchestrator/index.js.map +1 -1
  94. package/dist/orchestrator/node-identity.d.ts +6 -6
  95. package/dist/orchestrator/node-identity.js +7 -7
  96. package/dist/orchestrator/node-identity.js.map +1 -1
  97. package/dist/orchestrator/port-allocator.d.ts +5 -6
  98. package/dist/orchestrator/port-allocator.js +9 -11
  99. package/dist/orchestrator/port-allocator.js.map +1 -1
  100. package/dist/orchestrator/state-store.d.ts +3 -5
  101. package/dist/orchestrator/state-store.js +2 -10
  102. package/dist/orchestrator/state-store.js.map +1 -1
  103. package/dist/orchestrator/types.d.ts +33 -22
  104. package/dist/orchestrator/types.js.map +1 -1
  105. package/dist/package-version.d.ts +1 -0
  106. package/dist/package-version.js +4 -0
  107. package/dist/package-version.js.map +1 -0
  108. package/dist/server/error-handler.d.ts +5 -25
  109. package/dist/server/error-handler.js +11 -74
  110. package/dist/server/error-handler.js.map +1 -1
  111. package/dist/server/events/types.d.ts +7 -11
  112. package/dist/server/events/types.js +2 -1
  113. package/dist/server/events/types.js.map +1 -1
  114. package/dist/server/index.d.ts +11 -37
  115. package/dist/server/index.js +30 -48
  116. package/dist/server/index.js.map +1 -1
  117. package/dist/server/routes/hosted-nodes.d.ts +28 -0
  118. package/dist/server/routes/hosted-nodes.js +68 -0
  119. package/dist/server/routes/hosted-nodes.js.map +1 -0
  120. package/dist/server/routes/nat.d.ts +4 -1
  121. package/dist/server/routes/nat.js +13 -2
  122. package/dist/server/routes/nat.js.map +1 -1
  123. package/dist/server/routes/nodes.d.ts +6 -20
  124. package/dist/server/routes/nodes.js +7 -86
  125. package/dist/server/routes/nodes.js.map +1 -1
  126. package/dist/server/routes/settings.d.ts +3 -7
  127. package/dist/server/routes/settings.js +18 -8
  128. package/dist/server/routes/settings.js.map +1 -1
  129. package/dist/server/routes/status.d.ts +2 -25
  130. package/dist/server/routes/status.js +3 -43
  131. package/dist/server/routes/status.js.map +1 -1
  132. package/dist/server/server.js +8 -8
  133. package/dist/server/settings-store.d.ts +2 -2
  134. package/dist/server/settings-store.js +2 -2
  135. package/dist/server/static.js +1 -2
  136. package/dist/server/static.js.map +1 -1
  137. package/dist/ui/assets/index-BHd8CWZA.css +1 -0
  138. package/dist/ui/assets/index-Ccr2GjPT.js +23 -0
  139. package/dist/ui/assets/index-Ccr2GjPT.js.map +1 -0
  140. package/dist/ui/index.html +2 -2
  141. package/dist/update/index.d.ts +2 -2
  142. package/dist/update/index.js +2 -2
  143. package/dist/update/store.d.ts +1 -1
  144. package/dist/update/store.js +1 -1
  145. package/dist/update/types.d.ts +1 -1
  146. package/dist/update/types.js +1 -1
  147. package/package.json +5 -7
  148. package/src/__tests__/cli-nat.smoke.test.ts +219 -212
  149. package/src/__tests__/cli.smoke.test.ts +2 -2
  150. package/src/__tests__/global-setup.ts +2 -3
  151. package/src/__tests__/orchestrator-claim-secret.test.ts +111 -0
  152. package/src/__tests__/orchestrator-env-scrub.test.ts +160 -163
  153. package/src/__tests__/orchestrator-handle-contract.ts +134 -134
  154. package/src/__tests__/orchestrator-node-identity.test.ts +177 -203
  155. package/src/__tests__/orchestrator-ports.test.ts +124 -143
  156. package/src/__tests__/orchestrator-push.test.ts +138 -146
  157. package/src/__tests__/orchestrator.test.ts +1017 -1063
  158. package/src/__tests__/ui-access.test.ts +30 -0
  159. package/src/bin/host.ts +397 -572
  160. package/src/bin/join-output.ts +120 -0
  161. package/src/bin/nat-output.ts +188 -0
  162. package/src/bin/ui-access.ts +50 -0
  163. package/src/{donation → hosted}/__tests__/fake-orchestrator.test.ts +172 -173
  164. package/src/{donation → hosted}/__tests__/fake-orchestrator.ts +43 -23
  165. package/src/hosted/__tests__/hosted-node-service.test.ts +708 -0
  166. package/src/hosted/__tests__/hosted-node-supervisor.test.ts +475 -0
  167. package/src/hosted/__tests__/test-invitation.ts +33 -0
  168. package/src/hosted/claim-details.ts +103 -0
  169. package/src/hosted/hosted-node-service.ts +814 -0
  170. package/src/hosted/hosted-node-store.ts +144 -0
  171. package/src/hosted/hosted-node-supervisor.ts +439 -0
  172. package/src/hosted/hosted-node-watcher.ts +288 -0
  173. package/src/hosted/index.ts +53 -0
  174. package/src/hosted/node-status.ts +97 -0
  175. package/src/hosted/types.ts +160 -0
  176. package/src/index.ts +72 -91
  177. package/src/installer/__tests__/config.test.ts +15 -40
  178. package/src/installer/__tests__/installer.smoke.test.ts +184 -263
  179. package/src/installer/__tests__/wizard.test.ts +25 -13
  180. package/src/installer/config.ts +201 -175
  181. package/src/installer/index.ts +252 -327
  182. package/src/installer/paths.ts +104 -109
  183. package/src/installer/wizard.ts +24 -26
  184. package/src/nat/__tests__/address-resolver.test.ts +107 -82
  185. package/src/nat/__tests__/nat-service.test.ts +608 -515
  186. package/src/nat/__tests__/nat-store.test.ts +49 -12
  187. package/src/nat/__tests__/network-mode.test.ts +38 -0
  188. package/src/nat/__tests__/port-mapper.test.ts +30 -191
  189. package/src/nat/__tests__/reachability.test.ts +96 -13
  190. package/src/nat/address-resolver.ts +94 -52
  191. package/src/nat/address-watch.ts +92 -0
  192. package/src/nat/ddns/duckdns.ts +5 -1
  193. package/src/nat/ddns/index.ts +6 -0
  194. package/src/nat/index.ts +33 -13
  195. package/src/nat/nat-service.ts +942 -501
  196. package/src/nat/nat-store.ts +126 -31
  197. package/src/nat/network-mode.ts +36 -0
  198. package/src/nat/port-mapper.ts +241 -329
  199. package/src/nat/reachability.ts +155 -34
  200. package/src/nat/types.ts +110 -37
  201. package/src/{installer/__tests__/identity.test.ts → orchestrator/__tests__/identity-file.test.ts} +34 -34
  202. package/src/orchestrator/__tests__/node-identity.test.ts +62 -62
  203. package/src/orchestrator/host-process-orchestrator.ts +1089 -1260
  204. package/src/{installer/identity.ts → orchestrator/identity-file.ts} +56 -56
  205. package/src/orchestrator/index.ts +9 -10
  206. package/src/orchestrator/node-identity.ts +41 -41
  207. package/src/orchestrator/port-allocator.ts +71 -73
  208. package/src/orchestrator/state-store.ts +76 -90
  209. package/src/orchestrator/types.ts +34 -23
  210. package/src/package-version.ts +4 -0
  211. package/src/server/__tests__/bus.test.ts +38 -38
  212. package/src/server/__tests__/error-handler.test.ts +81 -118
  213. package/src/server/__tests__/fakes.ts +15 -18
  214. package/src/server/__tests__/hosted-nodes-route.test.ts +161 -0
  215. package/src/server/__tests__/nodes-route.test.ts +114 -283
  216. package/src/server/__tests__/publishers.test.ts +193 -180
  217. package/src/server/__tests__/server.smoke.test.ts +134 -223
  218. package/src/server/__tests__/settings-route.test.ts +210 -195
  219. package/src/server/__tests__/sse-route.test.ts +119 -119
  220. package/src/server/__tests__/status-route.test.ts +82 -121
  221. package/src/server/error-handler.ts +112 -178
  222. package/src/server/events/types.ts +20 -24
  223. package/src/server/index.ts +223 -267
  224. package/src/server/routes/hosted-nodes.ts +83 -0
  225. package/src/server/routes/nat.ts +75 -63
  226. package/src/server/routes/nodes.ts +96 -188
  227. package/src/server/routes/settings.ts +20 -15
  228. package/src/server/routes/status.ts +5 -67
  229. package/src/server/server.ts +8 -8
  230. package/src/server/settings-store.ts +2 -2
  231. package/src/server/static.ts +1 -2
  232. package/src/update/index.ts +2 -2
  233. package/src/update/store.ts +1 -1
  234. package/src/update/types.ts +1 -1
  235. package/dist/auth/duration.d.ts +0 -1
  236. package/dist/auth/duration.js +0 -32
  237. package/dist/auth/duration.js.map +0 -1
  238. package/dist/auth/index.d.ts +0 -11
  239. package/dist/auth/index.js +0 -9
  240. package/dist/auth/index.js.map +0 -1
  241. package/dist/auth/self-label.d.ts +0 -36
  242. package/dist/auth/self-label.js +0 -57
  243. package/dist/auth/self-label.js.map +0 -1
  244. package/dist/auth/trust-circle-store.d.ts +0 -26
  245. package/dist/auth/trust-circle-store.js +0 -129
  246. package/dist/auth/trust-circle-store.js.map +0 -1
  247. package/dist/auth/trust-circle.d.ts +0 -156
  248. package/dist/auth/trust-circle.js +0 -307
  249. package/dist/auth/trust-circle.js.map +0 -1
  250. package/dist/auth/types.d.ts +0 -84
  251. package/dist/auth/types.js +0 -24
  252. package/dist/auth/types.js.map +0 -1
  253. package/dist/donation/donation-service.d.ts +0 -389
  254. package/dist/donation/donation-service.js +0 -828
  255. package/dist/donation/donation-service.js.map +0 -1
  256. package/dist/donation/donation-store.d.ts +0 -51
  257. package/dist/donation/donation-store.js +0 -152
  258. package/dist/donation/donation-store.js.map +0 -1
  259. package/dist/donation/donation-supervisor.js +0 -364
  260. package/dist/donation/donation-supervisor.js.map +0 -1
  261. package/dist/donation/grant-service.d.ts +0 -80
  262. package/dist/donation/grant-service.js +0 -210
  263. package/dist/donation/grant-service.js.map +0 -1
  264. package/dist/donation/grant-store.d.ts +0 -38
  265. package/dist/donation/grant-store.js +0 -135
  266. package/dist/donation/grant-store.js.map +0 -1
  267. package/dist/donation/index.d.ts +0 -20
  268. package/dist/donation/index.js +0 -17
  269. package/dist/donation/index.js.map +0 -1
  270. package/dist/donation/types.d.ts +0 -224
  271. package/dist/donation/types.js +0 -40
  272. package/dist/donation/types.js.map +0 -1
  273. package/dist/installer/identity.js.map +0 -1
  274. package/dist/owner/index.d.ts +0 -11
  275. package/dist/owner/index.js +0 -11
  276. package/dist/owner/index.js.map +0 -1
  277. package/dist/owner/owner-node-client.d.ts +0 -110
  278. package/dist/owner/owner-node-client.js +0 -184
  279. package/dist/owner/owner-node-client.js.map +0 -1
  280. package/dist/server/routes/bootstrap-node-validation.d.ts +0 -115
  281. package/dist/server/routes/bootstrap-node-validation.js +0 -197
  282. package/dist/server/routes/bootstrap-node-validation.js.map +0 -1
  283. package/dist/server/routes/grants-admin.d.ts +0 -29
  284. package/dist/server/routes/grants-admin.js +0 -58
  285. package/dist/server/routes/grants-admin.js.map +0 -1
  286. package/dist/server/routes/grants.d.ts +0 -28
  287. package/dist/server/routes/grants.js +0 -165
  288. package/dist/server/routes/grants.js.map +0 -1
  289. package/dist/server/routes/provision-request-validation.d.ts +0 -45
  290. package/dist/server/routes/provision-request-validation.js +0 -97
  291. package/dist/server/routes/provision-request-validation.js.map +0 -1
  292. package/dist/server/routes/strands.d.ts +0 -20
  293. package/dist/server/routes/strands.js +0 -38
  294. package/dist/server/routes/strands.js.map +0 -1
  295. package/dist/server/routes/trust-circle.d.ts +0 -17
  296. package/dist/server/routes/trust-circle.js +0 -35
  297. package/dist/server/routes/trust-circle.js.map +0 -1
  298. package/dist/strands/index.d.ts +0 -7
  299. package/dist/strands/index.js +0 -6
  300. package/dist/strands/index.js.map +0 -1
  301. package/dist/strands/strand-service.d.ts +0 -50
  302. package/dist/strands/strand-service.js +0 -103
  303. package/dist/strands/strand-service.js.map +0 -1
  304. package/dist/strands/types.d.ts +0 -93
  305. package/dist/strands/types.js +0 -23
  306. package/dist/strands/types.js.map +0 -1
  307. package/dist/ui/assets/index-C6nELNfC.js +0 -23
  308. package/dist/ui/assets/index-C6nELNfC.js.map +0 -1
  309. package/dist/ui/assets/index-TtIYSeZO.css +0 -1
  310. package/src/__tests__/cli-invite.smoke.test.ts +0 -192
  311. package/src/__tests__/host-owner.smoke.test.ts +0 -123
  312. package/src/__tests__/orchestrator-owner.test.ts +0 -234
  313. package/src/__tests__/orchestrator-pin-keys.test.ts +0 -152
  314. package/src/auth/__tests__/duration.test.ts +0 -28
  315. package/src/auth/__tests__/self-label.test.ts +0 -85
  316. package/src/auth/__tests__/trust-circle-integration.test.ts +0 -152
  317. package/src/auth/__tests__/trust-circle-store.test.ts +0 -115
  318. package/src/auth/__tests__/trust-circle.test.ts +0 -445
  319. package/src/auth/duration.ts +0 -33
  320. package/src/auth/index.ts +0 -21
  321. package/src/auth/self-label.ts +0 -74
  322. package/src/auth/trust-circle-store.ts +0 -155
  323. package/src/auth/trust-circle.ts +0 -395
  324. package/src/auth/types.ts +0 -99
  325. package/src/donation/__tests__/donation-service.test.ts +0 -1193
  326. package/src/donation/__tests__/donation-supervisor.test.ts +0 -548
  327. package/src/donation/__tests__/grant-service.test.ts +0 -213
  328. package/src/donation/__tests__/grant-store.test.ts +0 -113
  329. package/src/donation/donation-service.ts +0 -1033
  330. package/src/donation/donation-store.ts +0 -176
  331. package/src/donation/donation-supervisor.ts +0 -411
  332. package/src/donation/grant-service.ts +0 -252
  333. package/src/donation/grant-store.ts +0 -152
  334. package/src/donation/index.ts +0 -65
  335. package/src/donation/types.ts +0 -260
  336. package/src/owner/__tests__/owner-node-client.test.ts +0 -194
  337. package/src/owner/index.ts +0 -12
  338. package/src/owner/owner-node-client.ts +0 -259
  339. package/src/server/__tests__/bootstrap-node-validation.test.ts +0 -138
  340. package/src/server/__tests__/grants-admin-route.test.ts +0 -171
  341. package/src/server/__tests__/grants-route.test.ts +0 -394
  342. package/src/server/__tests__/strands-route.test.ts +0 -234
  343. package/src/server/routes/bootstrap-node-validation.ts +0 -206
  344. package/src/server/routes/grants-admin.ts +0 -74
  345. package/src/server/routes/grants.ts +0 -193
  346. package/src/server/routes/provision-request-validation.ts +0 -105
  347. package/src/server/routes/strands.ts +0 -54
  348. package/src/server/routes/trust-circle.ts +0 -49
  349. package/src/strands/__tests__/strand-service.test.ts +0 -165
  350. package/src/strands/index.ts +0 -14
  351. package/src/strands/strand-service.ts +0 -135
  352. package/src/strands/types.ts +0 -102
@@ -0,0 +1,288 @@
1
+ import debug from 'debug';
2
+
3
+ import { decodeCadreInvitation } from '@serfab/cadre-core';
4
+
5
+ import type { NodeStateListener } from '../orchestrator/types.js';
6
+ import type { HostedNodeStore } from './hosted-node-store.js';
7
+ import { errorMessage, readWatchedNodeStatus, reportsClaim, reportsRemoval, type NodeStatus, type RemovedNodeStatus } from './node-status.js';
8
+ import type { HostedNode, HostedNodeChange, HostedNodeStatus } from './types.js';
9
+
10
+ const log = debug('cadre:host:hosted-node-watcher');
11
+
12
+ /** How often an unclaimed node's `/status` is read for the claim, and a joining node's for its redemption. */
13
+ export const HOSTED_NODE_CLAIM_POLL_MS = 2_000;
14
+
15
+ /** How often a joined node's `/status` is read for its connection count. */
16
+ export const HOSTED_NODE_CONNECTED_POLL_MS = 15_000;
17
+
18
+ /** The `error` a node an owner removed from its cadre is recorded with. */
19
+ const REMOVED_BY_OWNER_ERROR = 'Removed from its cadre by an owner';
20
+
21
+ /**
22
+ * The orchestrator surface the watcher needs: the exit/start signal, when the orchestrator
23
+ * has one, and the stop of a node whose invitation failed or that an owner removed.
24
+ */
25
+ export interface WatchedOrchestrator {
26
+ onStateChange?(listener: NodeStateListener): () => void;
27
+ stopContainer(dockerId: string): Promise<void>;
28
+ }
29
+
30
+ /** Statuses the watcher reads every tick: a node still on its way into its cadre. */
31
+ const PENDING_STATUSES: ReadonlySet<HostedNodeStatus> = new Set<HostedNodeStatus>(['unclaimed', 'joining']);
32
+
33
+ export interface HostedNodeWatcherOptions {
34
+ store: HostedNodeStore;
35
+ orchestrator: WatchedOrchestrator;
36
+ now: () => Date;
37
+ /** Where a claim or a liveness change is reported (`HostedNodeService.emit`). */
38
+ emit: (change: HostedNodeChange) => void;
39
+ }
40
+
41
+ /**
42
+ * Follows each hosted node's `/status`: an `unclaimed` record becomes `joined` when
43
+ * the node reports a finished claim; a `joining` record becomes `joined` when a member
44
+ * accepted its invitation, or `error` when the redemption failed; a `joined`
45
+ * record's `connected` follows the node's control-connection count; and any of them
46
+ * becomes `error` when the node reports that an owner removed it from its cadre.
47
+ * Best-effort: a poll that fails is retried on the next tick, and nothing here throws
48
+ * out of the timer.
49
+ *
50
+ * One timer at the claim cadence drives all three: every tick polls every unclaimed and
51
+ * joining node, and each joined node every {@link HOSTED_NODE_CONNECTED_POLL_MS}, or at once when it
52
+ * was poked — the orchestrator's state change on a respawn pokes the node, and the
53
+ * poke stands until a poll succeeds, so a respawned child is noticed on its first
54
+ * answer rather than at the next 15 s mark. Polls are serialized on one promise
55
+ * tail so a timer pass and a poked pass cannot both write one record.
56
+ *
57
+ * NOTE: the 2 s timer ticks while nothing is unclaimed (one cached store read, no
58
+ * I/O per tick); if it ever shows up in a profile, stop it when no record is
59
+ * unclaimed and restart it from `poke`.
60
+ */
61
+ export class HostedNodeWatcher {
62
+ private readonly store: HostedNodeStore;
63
+ private readonly orchestrator: WatchedOrchestrator;
64
+ private readonly now: () => Date;
65
+ private readonly emit: (change: HostedNodeChange) => void;
66
+
67
+ private tail: Promise<void> = Promise.resolve();
68
+ private timer?: ReturnType<typeof setInterval>;
69
+ private unsubscribe?: () => void;
70
+ /** When each joined node's `/status` last answered (ms since epoch). */
71
+ private readonly lastPolledAt = new Map<string, number>();
72
+ /** Joined nodes to poll on the next pass regardless of cadence. */
73
+ private readonly due = new Set<string>();
74
+
75
+ constructor(opts: HostedNodeWatcherOptions) {
76
+ this.store = opts.store;
77
+ this.orchestrator = opts.orchestrator;
78
+ this.now = opts.now;
79
+ this.emit = opts.emit;
80
+ }
81
+
82
+ /** Start the timer and the state-change subscription, and poll once. Idempotent. */
83
+ start(): void {
84
+ if (this.timer) return;
85
+ this.unsubscribe = this.orchestrator.onStateChange?.((info) => { this.poke(info.id); });
86
+ this.timer = setInterval(() => { this.poke(); }, HOSTED_NODE_CLAIM_POLL_MS);
87
+ this.timer.unref();
88
+ this.poke();
89
+ }
90
+
91
+ stop(): void {
92
+ if (this.timer) {
93
+ clearInterval(this.timer);
94
+ this.timer = undefined;
95
+ }
96
+ this.unsubscribe?.();
97
+ this.unsubscribe = undefined;
98
+ }
99
+
100
+ /** Ask for a pass now; `id` names a joined node to poll ahead of its cadence. Fire-and-forget. */
101
+ poke(id?: string): void {
102
+ if (id) this.due.add(id);
103
+ void this.poll().catch((err) => { log('status poll failed: %s', errorMessage(err)); });
104
+ }
105
+
106
+ /** One pass over every unclaimed, joining and due joined record, serialized against the others. */
107
+ poll(): Promise<void> {
108
+ const next = this.tail.then(() => this.pollOnce(), () => this.pollOnce());
109
+ this.tail = next.then(() => undefined, () => undefined);
110
+ return next;
111
+ }
112
+
113
+ private async pollOnce(): Promise<void> {
114
+ let records: HostedNode[];
115
+ try {
116
+ records = this.store.list().filter((n) => PENDING_STATUSES.has(n.status) || n.status === 'joined');
117
+ } catch (err) {
118
+ // A malformed hosted-nodes.json throws on every load; log rather than let it escape the timer.
119
+ log('poll could not list hosted nodes: %s', errorMessage(err));
120
+ return;
121
+ }
122
+ this.forgetRemoved(new Set(records.map((r) => r.id)));
123
+ for (const record of records) {
124
+ if (this.shouldPoll(record)) await this.pollOne(record);
125
+ }
126
+ }
127
+
128
+ /** Drop the cadence and poke bookkeeping of nodes no longer on record, so neither map grows with removals. */
129
+ private forgetRemoved(live: Set<string>): void {
130
+ for (const id of this.lastPolledAt.keys()) if (!live.has(id)) this.lastPolledAt.delete(id);
131
+ for (const id of this.due) if (!live.has(id)) this.due.delete(id);
132
+ }
133
+
134
+ private shouldPoll(record: HostedNode): boolean {
135
+ if (PENDING_STATUSES.has(record.status) || this.due.has(record.id)) return true;
136
+ const last = this.lastPolledAt.get(record.id);
137
+ return last === undefined || this.now().getTime() - last >= HOSTED_NODE_CONNECTED_POLL_MS;
138
+ }
139
+
140
+ private async pollOne(record: HostedNode): Promise<void> {
141
+ if (!record.statusEndpoint) return;
142
+ let status: NodeStatus | RemovedNodeStatus;
143
+ try {
144
+ status = await readWatchedNodeStatus(record.statusEndpoint);
145
+ } catch (err) {
146
+ log('hosted node %s did not answer /status (retried next tick): %s', record.id, errorMessage(err));
147
+ return;
148
+ }
149
+ this.lastPolledAt.set(record.id, this.now().getTime());
150
+ this.due.delete(record.id);
151
+
152
+ // Re-read: `record` predates the round-trip and `store.put` replaces the whole
153
+ // row, so writing that copy back would resurrect a node removed meanwhile, or
154
+ // undo a respawn's new handles. The store is synchronous, so this read-decide-
155
+ // write is atomic against the event loop as long as no `await` sneaks in.
156
+ const current = this.store.get(record.id);
157
+ if (!current || current.status !== record.status) return;
158
+ if (reportsRemoval(status)) {
159
+ await this.applyRemoved(current, status);
160
+ } else if (current.status === 'unclaimed') {
161
+ this.applyUnclaimed(current, status);
162
+ } else if (current.status === 'joining') {
163
+ await this.applyJoining(current, status);
164
+ } else {
165
+ this.applyJoined(current, status);
166
+ }
167
+ }
168
+
169
+ /** An unclaimed node that reports a finished claim is `joined`, with the party and owner the claim named. */
170
+ private applyUnclaimed(current: HostedNode, status: NodeStatus): void {
171
+ if (!reportsClaim(status)) return;
172
+ this.store.put({
173
+ ...current,
174
+ status: 'joined',
175
+ partyId: status.node.partyId,
176
+ ownerKey: status.node.claimedBy,
177
+ peerId: current.peerId ?? status.peerId,
178
+ connected: status.node.connectionPaths.total > 0,
179
+ updatedAt: this.now().toISOString(),
180
+ });
181
+ log('hosted node %s was claimed by owner %s into cadre %s', current.id, status.node.claimedBy.slice(0, 8), status.node.partyId);
182
+ this.emit({ kind: 'claimed', id: current.id });
183
+ }
184
+
185
+ /**
186
+ * A joining node whose redemption settled: `joined` with the member that admitted it and
187
+ * the invitation's issuer as its owner, or `error` with the reason and whether Retry may
188
+ * help. A failed node's child is stopped after the write, as a give-up's is, and kept
189
+ * with its workdir for Retry; the write comes first so the exit the stop raises finds
190
+ * a record the supervisor leaves alone. Still `pending`: nothing.
191
+ */
192
+ private async applyJoining(current: HostedNode, status: NodeStatus): Promise<void> {
193
+ const invitation = status.node.invitation;
194
+ if (invitation?.state === 'accepted') {
195
+ const ownerKey = issuerOf(current);
196
+ this.store.put({
197
+ ...current,
198
+ status: 'joined',
199
+ ...(ownerKey ? { ownerKey } : {}),
200
+ ...(invitation.memberPeerId ? { memberPeerId: invitation.memberPeerId } : {}),
201
+ peerId: current.peerId ?? status.peerId,
202
+ connected: status.node.connectionPaths.total > 0,
203
+ updatedAt: this.now().toISOString(),
204
+ });
205
+ log('hosted node %s joined cadre %s at member %s', current.id, current.partyId, invitation.memberPeerId ?? '(unnamed)');
206
+ this.emit({ kind: 'joined', id: current.id });
207
+ return;
208
+ }
209
+ if (invitation?.state !== 'failed') return;
210
+ const error = invitation.error ?? 'the invitation could not be redeemed';
211
+ this.store.put({
212
+ ...current,
213
+ status: 'error',
214
+ error,
215
+ retryable: invitation.retryable === true,
216
+ peerId: current.peerId ?? status.peerId,
217
+ updatedAt: this.now().toISOString(),
218
+ });
219
+ log('hosted node %s could not join cadre %s (%s): %s', current.id, current.partyId, invitation.retryable ? 'retryable' : 'final', error);
220
+ this.emit({ kind: 'changed', id: current.id });
221
+ await this.stopChild(current, 'its invitation failed');
222
+ }
223
+
224
+ /**
225
+ * A node that reports an owner removed it from its cadre: `error`, not retryable, its child
226
+ * stopped after the write as a failed invitation's is, and its workdir kept for Remove (or a
227
+ * claim node's Reset). The child had already stopped its node, and stays up only to report
228
+ * the removal, so stopping it loses nothing. The party and owner come from the report, for an
229
+ * `unclaimed` record whose claim this watcher never saw: its own party is the placeholder.
230
+ */
231
+ private async applyRemoved(current: HostedNode, status: RemovedNodeStatus): Promise<void> {
232
+ const partyId = status.node.partyId || current.partyId;
233
+ const ownerKey = current.ownerKey ?? status.node.claimedBy;
234
+ this.store.put({
235
+ ...current,
236
+ status: 'error',
237
+ partyId,
238
+ ...(ownerKey ? { ownerKey } : {}),
239
+ error: REMOVED_BY_OWNER_ERROR,
240
+ retryable: false,
241
+ removedByOwner: true,
242
+ updatedAt: this.now().toISOString(),
243
+ });
244
+ log('hosted node %s was removed from cadre %s by an owner', current.id, partyId);
245
+ this.emit({ kind: 'changed', id: current.id });
246
+ await this.stopChild(current, 'an owner removed it');
247
+ }
248
+
249
+ /** Stop a node's child after its record went `error`; a failed stop is logged, the record stands. */
250
+ private async stopChild(current: HostedNode, why: string): Promise<void> {
251
+ if (!current.dockerId) return;
252
+ try {
253
+ await this.orchestrator.stopContainer(current.dockerId);
254
+ } catch (err) {
255
+ log('failed to stop hosted node %s after %s: %s', current.id, why, errorMessage(err));
256
+ }
257
+ }
258
+
259
+ /**
260
+ * A joined node's `connected` follows its control-connection count; published only on a
261
+ * change. Its `/status` keeps reporting the invitation for as long as the child that
262
+ * redeemed it runs, and whatever it says there is ignored: the node is a member, and the
263
+ * record says so.
264
+ */
265
+ private applyJoined(current: HostedNode, status: NodeStatus): void {
266
+ const connected = status.node.connectionPaths.total > 0;
267
+ if (current.connected === connected) return;
268
+ this.store.put({ ...current, connected, updatedAt: this.now().toISOString() });
269
+ log('hosted node %s is now %s', current.id, connected ? 'connected' : 'disconnected');
270
+ this.emit({ kind: 'changed', id: current.id });
271
+ }
272
+ }
273
+
274
+ /**
275
+ * The owner a joined invitation node is shown under: the issuer of its invitation. The
276
+ * record's bundle decoded at `join`, so this fails only on a hand-edited
277
+ * `hosted-nodes.json` or on a record written before invitations carried their
278
+ * `sereus-invite:1.` prefix; the node is a member either way, so the record says so without one.
279
+ */
280
+ function issuerOf(node: HostedNode): string | undefined {
281
+ if (node.join.kind !== 'invitation') return undefined;
282
+ try {
283
+ return decodeCadreInvitation(node.join.encoded).invite.issuerKey;
284
+ } catch (err) {
285
+ log('hosted node %s carries an invitation that no longer decodes: %s', node.id, errorMessage(err));
286
+ return undefined;
287
+ }
288
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Hosted nodes: the host's "Join a cadre" action and what follows from it. See
3
+ * ./types.ts for the record, ./hosted-node-service.ts for the lifecycle,
4
+ * ./hosted-node-watcher.ts for following each node's `/status`, ./claim-details.ts for
5
+ * the QR payload, and ./hosted-node-supervisor.ts for the respawn invariant.
6
+ */
7
+
8
+ export { HostedNodeStore } from './hosted-node-store.js';
9
+ export {
10
+ HostedNodeService,
11
+ HOSTED_NODE_SPAWNING_TTL_MS,
12
+ HOSTED_NODE_REAP_SWEEP_MS,
13
+ } from './hosted-node-service.js';
14
+ export type {
15
+ HostedNodeOrchestrator,
16
+ HostedNodeServiceOptions,
17
+ JoinOptions,
18
+ RespawnOptions,
19
+ RespawnResult,
20
+ } from './hosted-node-service.js';
21
+ export type { ClaimDetails, HostedNodeAddressSource } from './claim-details.js';
22
+ export {
23
+ HOSTED_NODE_CLAIM_POLL_MS,
24
+ HOSTED_NODE_CONNECTED_POLL_MS,
25
+ } from './hosted-node-watcher.js';
26
+ export {
27
+ HostedNodeSupervisor,
28
+ HOSTED_NODE_RESPAWN_BACKOFF_BASE_MS,
29
+ HOSTED_NODE_RESPAWN_BACKOFF_MAX_MS,
30
+ HOSTED_NODE_RESPAWN_MAX_ATTEMPTS,
31
+ HOSTED_NODE_RESPAWN_HEALTHY_MS,
32
+ HOSTED_NODE_RESPAWN_SWEEP_MS,
33
+ } from './hosted-node-supervisor.js';
34
+ export type {
35
+ HostedNodeSupervisorOptions,
36
+ SupervisedOrchestrator,
37
+ } from './hosted-node-supervisor.js';
38
+ export { PLACEHOLDER_PARTY } from './node-status.js';
39
+ export { HostedNodeError } from './types.js';
40
+ export type {
41
+ HostedNode,
42
+ HostedNodeChange,
43
+ HostedNodeChangeKind,
44
+ HostedNodeChangeListener,
45
+ HostedNodeErrorCode,
46
+ HostedNodeClaimJoin,
47
+ HostedNodeFile,
48
+ HostedNodeInvitationJoin,
49
+ HostedNodeJoin,
50
+ HostedNodeJoinView,
51
+ HostedNodeStatus,
52
+ HostedNodeView,
53
+ } from './types.js';
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Reading a hosted child's `/status` — the one window the host has onto a node it
3
+ * runs: its peer id and addresses before the claim, the claim itself, the party
4
+ * and the owner key after it, and its removal by an owner. Shared by
5
+ * `HostedNodeService.claimDetails` and the status watcher.
6
+ */
7
+
8
+ // The child's `/status` is typed against the CLI's own answer, so a field the CLI
9
+ // renames is a compile error here rather than a watcher that never sees a claim.
10
+ import type { HealthStatus } from '@serfab/cadre-cli';
11
+
12
+ import { HostedNodeError } from './types.js';
13
+
14
+ /** The party an unclaimed child's config names; the claim replaces it. */
15
+ export const PLACEHOLDER_PARTY = 'unclaimed';
16
+
17
+ /** The `/status` URL for a spawn's `/health` URL (same server and port). */
18
+ export function statusUrlFor(healthEndpoint: string): string {
19
+ const url = new URL(healthEndpoint);
20
+ url.pathname = '/status';
21
+ return url.toString();
22
+ }
23
+
24
+ /** A `/status` answer from a node that has its peer identity. */
25
+ export type NodeStatus = HealthStatus & { peerId: string };
26
+
27
+ /**
28
+ * A `/status` answer from a child an owner removed from its cadre. The child stopped its node
29
+ * and stays up only to report this, so it has no peer identity.
30
+ */
31
+ export type RemovedNodeStatus = HealthStatus & { node: { removed: NonNullable<HealthStatus['node']['removed']> } };
32
+
33
+ /**
34
+ * The child's `/status`, fresh every call. Throws `node_unavailable` while the child
35
+ * does not answer, answers with an error, or has no peer identity yet — every one of
36
+ * which a caller retries.
37
+ */
38
+ export async function readNodeStatus(statusEndpoint: string): Promise<NodeStatus> {
39
+ return requirePeerIdentity(await fetchNodeStatus(statusEndpoint));
40
+ }
41
+
42
+ /**
43
+ * {@link readNodeStatus} for the watcher, which also has to hear a removal: a child reporting
44
+ * one is answered as it is rather than refused for having no peer identity.
45
+ */
46
+ export async function readWatchedNodeStatus(statusEndpoint: string): Promise<NodeStatus | RemovedNodeStatus> {
47
+ const status = await fetchNodeStatus(statusEndpoint);
48
+ return reportsRemoval(status) ? status : requirePeerIdentity(status);
49
+ }
50
+
51
+ /** Whether the child reports that an owner removed it from its cadre. */
52
+ export function reportsRemoval(status: HealthStatus): status is RemovedNodeStatus {
53
+ return Boolean(status.node.removed);
54
+ }
55
+
56
+ async function fetchNodeStatus(statusEndpoint: string): Promise<HealthStatus> {
57
+ let res: Response;
58
+ try {
59
+ res = await fetch(statusEndpoint);
60
+ } catch (err) {
61
+ throw new HostedNodeError('node_unavailable', `Hosted node unreachable: ${errorMessage(err)}`);
62
+ }
63
+ if (!res.ok) {
64
+ throw new HostedNodeError('node_unavailable', `Hosted node /status returned ${res.status}`);
65
+ }
66
+ try {
67
+ return (await res.json()) as HealthStatus;
68
+ } catch (err) {
69
+ throw new HostedNodeError('node_unavailable', `Hosted node /status is not JSON: ${errorMessage(err)}`);
70
+ }
71
+ }
72
+
73
+ function requirePeerIdentity(status: HealthStatus): NodeStatus {
74
+ if (!status.peerId || !status.multiaddrs?.length) {
75
+ throw new HostedNodeError('node_unavailable', 'Hosted node has no peer identity yet');
76
+ }
77
+ return status as NodeStatus;
78
+ }
79
+
80
+ /**
81
+ * Whether `/status` reports a finished claim: a claim on record AND the party it
82
+ * named. `claim` flips to `claimed` the moment the node records the claim, but the
83
+ * node then restarts in-process into the claimed party, and until that restart
84
+ * finishes `partyId` is still the placeholder (or empty while the node object is
85
+ * being rebuilt). Writing `joined` on the flag alone would record the placeholder
86
+ * as the node's cadre.
87
+ */
88
+ export function reportsClaim(status: NodeStatus): status is NodeStatus & { node: { claimedBy: string } } {
89
+ return status.node.claim === 'claimed'
90
+ && status.node.claimedBy !== undefined
91
+ && status.node.partyId !== ''
92
+ && status.node.partyId !== PLACEHOLDER_PARTY;
93
+ }
94
+
95
+ export function errorMessage(err: unknown): string {
96
+ return err instanceof Error ? err.message : String(err);
97
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Hosted-node types for cadre-host.
3
+ *
4
+ * A **hosted node** is a child process the host runs for some cadre. It gets into its
5
+ * cadre one of two ways: the host starts it waiting to be claimed and shows its addresses
6
+ * and claim secret as a QR code, which the owner's phone scans to claim the node
7
+ * (`CadreNode.claimNode`); or the host starts it with a cadre invitation the owner's app
8
+ * minted, which the node redeems at a member of the cadre. Either way the host holds no
9
+ * owner key and is not an owner of any cadre its nodes serve.
10
+ *
11
+ * Records live in `<dataDir>/hosted-nodes.json` (`HostedNodeStore`). A record's id is also
12
+ * its orchestrator container id and the name of its working directory.
13
+ */
14
+
15
+ /**
16
+ * Lifecycle of one hosted node:
17
+ * spawning → the record is written, the child not yet spawned.
18
+ * unclaimed → (claim) the child is up with a claim secret, waiting for a phone to claim it.
19
+ * joining → (invitation) the child is up, its redemption of the invitation not yet settled.
20
+ * joined → in its cadre: claimed, or the invitation accepted by a member.
21
+ * error → the supervisor gave up on it, the stuck-`spawning` reap found it, the
22
+ * invitation was refused or no member could be reached (`retryable` says which),
23
+ * or an owner removed it from its cadre (`removedByOwner`).
24
+ *
25
+ * Removal deletes the row; there is no terminal "removed" status, and a node an owner removed
26
+ * from its cadre is, to the host, a node that failed and waits for the admin. An `error`
27
+ * record keeps its working directory (its identity key) until it is removed or reset.
28
+ */
29
+ export type HostedNodeStatus = 'spawning' | 'unclaimed' | 'joining' | 'joined' | 'error';
30
+
31
+ /**
32
+ * The node was started with a claim secret and waits for a phone to present it.
33
+ */
34
+ export interface HostedNodeClaimJoin {
35
+ kind: 'claim';
36
+ /** The node's one-time claim secret, base64url. Only `claimDetails` ever returns it. */
37
+ secret: string;
38
+ }
39
+
40
+ /**
41
+ * The node was started with a cadre invitation and redeems it at a member of the cadre.
42
+ * Kept for a respawn while `joining`: the child redeems again, and a member answers a node
43
+ * that already got in as accepted.
44
+ */
45
+ export interface HostedNodeInvitationJoin {
46
+ kind: 'invitation';
47
+ /**
48
+ * The bundle as the owner's app encoded it (`encodeCadreInvitation`). It carries the
49
+ * invitation's private key, so it is redacted like the claim secret.
50
+ *
51
+ * NOTE: kept on disk after the node joins, though nothing reads it then (a joined node is
52
+ * respawned without it). An invitation with uses left admits whoever reads it; if
53
+ * multi-use invitations get pasted into hosts, drop it at the watcher's `joined` write.
54
+ */
55
+ encoded: string;
56
+ }
57
+
58
+ /** How a node gets into its cadre. */
59
+ export type HostedNodeJoin = HostedNodeClaimJoin | HostedNodeInvitationJoin;
60
+
61
+ /** One hosted node, as persisted in `hosted-nodes.json`. */
62
+ export interface HostedNode {
63
+ /** `hn_<base64url of 12 random bytes>` — also the orchestrator container id and workdir name. */
64
+ id: string;
65
+ join: HostedNodeJoin;
66
+ /**
67
+ * A claim node: `unclaimed` (the placeholder party the child's config names) until the
68
+ * claim reports the party; the claimant's party after. An invitation node: the
69
+ * invitation's party from the start.
70
+ */
71
+ partyId: string;
72
+ /** Hosted nodes run the `storage` profile: they participate in strands and are dialable. */
73
+ profile: 'storage';
74
+ status: HostedNodeStatus;
75
+ /** Orchestrator handle (opaque `pid:token`), set once the child is spawned. */
76
+ dockerId?: string;
77
+ /** The child's loopback `/status` URL, from the spawn result. */
78
+ statusEndpoint?: string;
79
+ /** Read once from `/status`; the claim details need it before the claim. */
80
+ peerId?: string;
81
+ /**
82
+ * Set when the node joins: `/status.node.claimedBy` for a claim, the invitation's issuer
83
+ * key for an invitation. The UI shows its first 8 characters.
84
+ */
85
+ ownerKey?: string;
86
+ /** An invitation node, once joined: the member that admitted it, when its address named one. */
87
+ memberPeerId?: string;
88
+ /** From the last status poll: the node holds at least one control connection. */
89
+ connected?: boolean;
90
+ /**
91
+ * Respawn bookkeeping, owned by the supervisor's backoff. Absent until the first
92
+ * respawn attempt. Not secret — it rides along in `HostedNodeView`.
93
+ */
94
+ respawn?: { attempts: number; lastAttemptAt: string };
95
+ createdAt: string;
96
+ updatedAt: string;
97
+ /** Failure detail when `status === 'error'`. */
98
+ error?: string;
99
+ /**
100
+ * Set with `error` when an invitation failed: whether Retry may start the node again with
101
+ * the same invitation (no member could be reached), or the invitation itself was refused.
102
+ * False on a node an owner removed; absent on every other `error`.
103
+ */
104
+ retryable?: boolean;
105
+ /**
106
+ * Set with `error` when the node reported that an owner removed it from its cadre, so the
107
+ * UI words it as a removal rather than a failure to join or to stay up.
108
+ */
109
+ removedByOwner?: true;
110
+ }
111
+
112
+ /** `join` without its secret: what `list`, `get`, the routes and the events carry. */
113
+ export type HostedNodeJoinView = { kind: HostedNodeJoin['kind'] };
114
+
115
+ /** The wire shape of a hosted node: the record with the claim secret or the invitation stripped. */
116
+ export interface HostedNodeView extends Omit<HostedNode, 'join'> {
117
+ join: HostedNodeJoinView;
118
+ }
119
+
120
+ /** On-disk shape of `hosted-nodes.json`. Keyed by node id. */
121
+ export interface HostedNodeFile {
122
+ version: 1;
123
+ nodes: Record<string, Omit<HostedNode, 'id'>>;
124
+ }
125
+
126
+ /** Error codes thrown by the hosted-node service, mapped to HTTP status by `server/error-handler.ts`. */
127
+ export type HostedNodeErrorCode =
128
+ | 'not_found' // 404 — no such hosted node
129
+ | 'invalid_state' // 409 — the operation does not apply to the node's current status
130
+ | 'invalid_request' // 400 — malformed input
131
+ | 'node_unavailable' // 503 — the child's /status does not answer yet
132
+ | 'orchestrator_error' // 500 — spawn / stop failure
133
+ | 'storage_error'; // 500 — hosted-nodes.json read/write failure
134
+
135
+ /** Typed hosted-node error carrying a stable `code` for HTTP mapping. */
136
+ export class HostedNodeError extends Error {
137
+ readonly code: HostedNodeErrorCode;
138
+
139
+ constructor(code: HostedNodeErrorCode, message: string) {
140
+ super(message);
141
+ this.name = 'HostedNodeError';
142
+ this.code = code;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * What changed about a hosted node: `added` (a join started the node), `claimed` (the
148
+ * watcher saw the claim), `joined` (the watcher saw a member accept the invitation),
149
+ * `removed`, or `changed` (anything else: a respawn, a liveness change, a refused
150
+ * invitation, a retry, a give-up). The server publishes each as the `hosted-nodes-changed`
151
+ * SSE event.
152
+ */
153
+ export type HostedNodeChangeKind = 'added' | 'claimed' | 'joined' | 'removed' | 'changed';
154
+
155
+ export interface HostedNodeChange {
156
+ kind: HostedNodeChangeKind;
157
+ id: string;
158
+ }
159
+
160
+ export type HostedNodeChangeListener = (change: HostedNodeChange) => void;