@serfab/cadre-host 0.9.0 → 0.11.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 (213) hide show
  1. package/dist/auth/index.d.ts +2 -0
  2. package/dist/auth/index.js +1 -0
  3. package/dist/auth/index.js.map +1 -1
  4. package/dist/auth/self-label.d.ts +36 -0
  5. package/dist/auth/self-label.js +57 -0
  6. package/dist/auth/self-label.js.map +1 -0
  7. package/dist/auth/trust-circle.d.ts +32 -5
  8. package/dist/auth/trust-circle.js +31 -11
  9. package/dist/auth/trust-circle.js.map +1 -1
  10. package/dist/bin/host.js +41 -5
  11. package/dist/bin/host.js.map +1 -1
  12. package/dist/donation/__tests__/fake-orchestrator.d.ts +103 -0
  13. package/dist/donation/__tests__/fake-orchestrator.js +180 -0
  14. package/dist/donation/__tests__/fake-orchestrator.js.map +1 -0
  15. package/dist/donation/donation-service.d.ts +237 -12
  16. package/dist/donation/donation-service.js +491 -34
  17. package/dist/donation/donation-service.js.map +1 -1
  18. package/dist/donation/donation-store.d.ts +7 -0
  19. package/dist/donation/donation-store.js +7 -0
  20. package/dist/donation/donation-store.js.map +1 -1
  21. package/dist/donation/donation-supervisor.d.ts +167 -0
  22. package/dist/donation/donation-supervisor.js +341 -0
  23. package/dist/donation/donation-supervisor.js.map +1 -0
  24. package/dist/donation/index.d.ts +4 -2
  25. package/dist/donation/index.js +2 -1
  26. package/dist/donation/index.js.map +1 -1
  27. package/dist/donation/types.d.ts +26 -0
  28. package/dist/donation/types.js.map +1 -1
  29. package/dist/index.d.ts +3 -1
  30. package/dist/index.js +3 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/orchestrator/host-process-orchestrator.d.ts +109 -5
  33. package/dist/orchestrator/host-process-orchestrator.js +341 -98
  34. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  35. package/dist/orchestrator/node-identity.d.ts +26 -0
  36. package/dist/orchestrator/node-identity.js +36 -0
  37. package/dist/orchestrator/node-identity.js.map +1 -0
  38. package/dist/orchestrator/port-allocator.d.ts +14 -0
  39. package/dist/orchestrator/port-allocator.js +45 -0
  40. package/dist/orchestrator/port-allocator.js.map +1 -1
  41. package/dist/owner/owner-node-client.d.ts +20 -5
  42. package/dist/owner/owner-node-client.js +21 -4
  43. package/dist/owner/owner-node-client.js.map +1 -1
  44. package/dist/server/error-handler.d.ts +7 -1
  45. package/dist/server/error-handler.js +23 -1
  46. package/dist/server/error-handler.js.map +1 -1
  47. package/dist/server/events/types.d.ts +3 -0
  48. package/dist/server/index.d.ts +7 -0
  49. package/dist/server/index.js +9 -3
  50. package/dist/server/index.js.map +1 -1
  51. package/dist/server/routes/grants.js +22 -3
  52. package/dist/server/routes/grants.js.map +1 -1
  53. package/dist/server/routes/strands.d.ts +20 -0
  54. package/dist/server/routes/strands.js +38 -0
  55. package/dist/server/routes/strands.js.map +1 -0
  56. package/dist/server/static.js +38 -38
  57. package/dist/strands/index.d.ts +7 -0
  58. package/dist/strands/index.js +6 -0
  59. package/dist/strands/index.js.map +1 -0
  60. package/dist/strands/strand-service.d.ts +50 -0
  61. package/dist/strands/strand-service.js +103 -0
  62. package/dist/strands/strand-service.js.map +1 -0
  63. package/dist/strands/types.d.ts +93 -0
  64. package/dist/strands/types.js +23 -0
  65. package/dist/strands/types.js.map +1 -0
  66. package/dist/ui/assets/index-BVoqLjyX.css +1 -0
  67. package/dist/ui/assets/index-C-iks41M.js +17 -0
  68. package/dist/ui/assets/index-C-iks41M.js.map +1 -0
  69. package/dist/ui/index.html +14 -14
  70. package/dist/update/release-key.d.ts +1 -1
  71. package/dist/update/release-key.js +1 -1
  72. package/package.json +5 -5
  73. package/service/cadre-host.service.tmpl +16 -16
  74. package/service/com.serfab.cadre-host.plist.tmpl +35 -35
  75. package/service/install-service.ps1 +98 -98
  76. package/service/uninstall-service.ps1 +19 -19
  77. package/src/__tests__/build-targets.test.ts +26 -0
  78. package/src/__tests__/cli-invite.smoke.test.ts +192 -192
  79. package/src/__tests__/cli-nat.smoke.test.ts +212 -212
  80. package/src/__tests__/cli.smoke.test.ts +46 -46
  81. package/src/__tests__/global-setup.ts +51 -0
  82. package/src/__tests__/host-owner.smoke.test.ts +123 -123
  83. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -0
  84. package/src/__tests__/orchestrator-node-identity.test.ts +204 -0
  85. package/src/__tests__/orchestrator-owner.test.ts +198 -198
  86. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -153
  87. package/src/__tests__/orchestrator-push.test.ts +145 -145
  88. package/src/__tests__/orchestrator.test.ts +951 -570
  89. package/src/auth/__tests__/duration.test.ts +28 -28
  90. package/src/auth/__tests__/self-label.test.ts +85 -0
  91. package/src/auth/__tests__/trust-circle-integration.test.ts +152 -147
  92. package/src/auth/__tests__/trust-circle-store.test.ts +115 -115
  93. package/src/auth/__tests__/trust-circle.test.ts +445 -401
  94. package/src/auth/duration.ts +33 -33
  95. package/src/auth/index.ts +21 -19
  96. package/src/auth/self-label.ts +74 -0
  97. package/src/auth/trust-circle-store.ts +155 -155
  98. package/src/auth/trust-circle.ts +45 -13
  99. package/src/auth/types.ts +99 -99
  100. package/src/bin/host.ts +1299 -1258
  101. package/src/donation/__tests__/donation-service.test.ts +1068 -290
  102. package/src/donation/__tests__/donation-supervisor.test.ts +510 -0
  103. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -0
  104. package/src/donation/__tests__/fake-orchestrator.ts +225 -0
  105. package/src/donation/__tests__/grant-service.test.ts +213 -213
  106. package/src/donation/__tests__/grant-store.test.ts +113 -113
  107. package/src/donation/donation-service.ts +962 -392
  108. package/src/donation/donation-store.ts +171 -164
  109. package/src/donation/donation-supervisor.ts +388 -0
  110. package/src/donation/grant-service.ts +200 -200
  111. package/src/donation/grant-store.ts +152 -152
  112. package/src/donation/index.ts +64 -49
  113. package/src/donation/types.ts +243 -220
  114. package/src/index.ts +14 -0
  115. package/src/installer/__tests__/identity.test.ts +34 -34
  116. package/src/installer/__tests__/paths.test.ts +47 -47
  117. package/src/installer/__tests__/service-host.test.ts +62 -62
  118. package/src/installer/__tests__/wizard.test.ts +64 -64
  119. package/src/installer/identity.ts +49 -49
  120. package/src/installer/paths.ts +109 -109
  121. package/src/installer/platform.ts +27 -27
  122. package/src/installer/service-host/index.ts +21 -21
  123. package/src/installer/service-host/template.ts +21 -21
  124. package/src/installer/wizard.ts +103 -103
  125. package/src/nat/__tests__/address-resolver.test.ts +82 -82
  126. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -83
  127. package/src/nat/__tests__/ddns-updater.test.ts +253 -253
  128. package/src/nat/__tests__/external-ip.test.ts +124 -124
  129. package/src/nat/__tests__/nat-service.test.ts +497 -497
  130. package/src/nat/__tests__/nat-store.test.ts +93 -93
  131. package/src/nat/__tests__/port-mapper.test.ts +191 -191
  132. package/src/nat/__tests__/reachability.test.ts +24 -24
  133. package/src/nat/__tests__/secrets.test.ts +178 -178
  134. package/src/nat/address-resolver.ts +51 -51
  135. package/src/nat/ddns/duckdns.ts +76 -76
  136. package/src/nat/ddns/index.ts +55 -55
  137. package/src/nat/ddns/updater.ts +243 -243
  138. package/src/nat/external-ip.ts +154 -154
  139. package/src/nat/index.ts +71 -71
  140. package/src/nat/nat-service.ts +501 -501
  141. package/src/nat/nat-store.ts +154 -154
  142. package/src/nat/port-mapper.ts +329 -329
  143. package/src/nat/reachability.ts +34 -34
  144. package/src/nat/secrets/file-store.ts +130 -130
  145. package/src/nat/secrets/index.ts +112 -112
  146. package/src/nat/secrets/keytar-store.ts +67 -67
  147. package/src/nat/types.ts +159 -159
  148. package/src/orchestrator/__tests__/node-identity.test.ts +62 -0
  149. package/src/orchestrator/host-process-orchestrator.ts +1133 -894
  150. package/src/orchestrator/index.ts +10 -10
  151. package/src/orchestrator/log-rotator.ts +53 -53
  152. package/src/orchestrator/node-identity.ts +40 -0
  153. package/src/orchestrator/pid-liveness.ts +24 -24
  154. package/src/orchestrator/port-allocator.ts +91 -43
  155. package/src/orchestrator/state-store.ts +90 -90
  156. package/src/orchestrator/types.ts +141 -141
  157. package/src/owner/__tests__/owner-node-client.test.ts +194 -194
  158. package/src/owner/index.ts +12 -12
  159. package/src/owner/owner-node-client.ts +259 -233
  160. package/src/push/__tests__/push.test.ts +90 -90
  161. package/src/push/index.ts +146 -146
  162. package/src/server/__tests__/bus.test.ts +38 -38
  163. package/src/server/__tests__/error-handler.test.ts +118 -118
  164. package/src/server/__tests__/grants-admin-route.test.ts +73 -73
  165. package/src/server/__tests__/grants-route.test.ts +263 -189
  166. package/src/server/__tests__/nodes-route.test.ts +259 -259
  167. package/src/server/__tests__/origin-guard.test.ts +72 -72
  168. package/src/server/__tests__/publishers.test.ts +216 -216
  169. package/src/server/__tests__/server.smoke.test.ts +253 -253
  170. package/src/server/__tests__/settings-route.test.ts +194 -194
  171. package/src/server/__tests__/sse-route.test.ts +119 -119
  172. package/src/server/__tests__/static.test.ts +145 -145
  173. package/src/server/__tests__/status-route.test.ts +134 -134
  174. package/src/server/__tests__/strands-route.test.ts +233 -0
  175. package/src/server/error-handler.ts +178 -155
  176. package/src/server/events/bus.ts +42 -42
  177. package/src/server/events/sse-route.ts +81 -81
  178. package/src/server/events/types.ts +23 -22
  179. package/src/server/index.ts +267 -254
  180. package/src/server/origin-guard.ts +84 -84
  181. package/src/server/routes/grants-admin.ts +41 -41
  182. package/src/server/routes/grants.ts +210 -186
  183. package/src/server/routes/nat.ts +63 -63
  184. package/src/server/routes/nodes.ts +170 -170
  185. package/src/server/routes/settings.ts +123 -123
  186. package/src/server/routes/status.ts +118 -118
  187. package/src/server/routes/strands.ts +54 -0
  188. package/src/server/routes/trust-circle.ts +49 -49
  189. package/src/server/routes/update.ts +43 -43
  190. package/src/server/server.ts +122 -122
  191. package/src/server/settings-store.ts +37 -37
  192. package/src/server/static.ts +207 -207
  193. package/src/strands/__tests__/strand-service.test.ts +165 -0
  194. package/src/strands/index.ts +14 -0
  195. package/src/strands/strand-service.ts +135 -0
  196. package/src/strands/types.ts +102 -0
  197. package/src/update/__tests__/apply.test.ts +158 -158
  198. package/src/update/__tests__/manifest.test.ts +128 -128
  199. package/src/update/__tests__/release-key.test.ts +42 -42
  200. package/src/update/__tests__/sign.test.ts +78 -78
  201. package/src/update/__tests__/store.test.ts +81 -81
  202. package/src/update/__tests__/update-service.integration.test.ts +256 -256
  203. package/src/update/__tests__/version.test.ts +31 -31
  204. package/src/update/apply.ts +190 -190
  205. package/src/update/index.ts +341 -341
  206. package/src/update/release-key.ts +71 -71
  207. package/src/update/sign.ts +74 -74
  208. package/src/update/store.ts +101 -101
  209. package/src/update/types.ts +109 -109
  210. package/src/update/version.ts +80 -80
  211. package/dist/ui/assets/index-BlMXQPSw.js +0 -14
  212. package/dist/ui/assets/index-BlMXQPSw.js.map +0 -1
  213. package/dist/ui/assets/index-BwU5mJGF.css +0 -1
@@ -0,0 +1,510 @@
1
+ /**
2
+ * DonationSupervisor unit tests — the component that notices a donated node is
3
+ * no longer running and calls `DonationService.respawn`, backs off between
4
+ * attempts, and eventually gives up.
5
+ *
6
+ * Exercised against the shared `FakeOrchestrator` (no real child processes), a
7
+ * real on-disk `DonationStore`, and an injected clock — so backoff and the
8
+ * healthy-reset window are asserted without any wall-clock waiting.
9
+ *
10
+ * What is NOT covered here: that a really-respawned child rejoins the borrower's
11
+ * cadre. That needs the cross-package `cadre-host-node-donation` integration
12
+ * scenario.
13
+ */
14
+
15
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
16
+ import { mkdtempSync, rmSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+
20
+ import type { ManagedNodeInfo } from '../../orchestrator/types.js';
21
+ import { DonationService } from '../donation-service.js';
22
+ import { DonationStore } from '../donation-store.js';
23
+ import {
24
+ DonationSupervisor,
25
+ DONATION_RESPAWN_HEALTHY_MS,
26
+ DONATION_RESPAWN_MAX_ATTEMPTS,
27
+ } from '../donation-supervisor.js';
28
+ import { GrantService } from '../grant-service.js';
29
+ import { GrantStore } from '../grant-store.js';
30
+ import type { Donation, DonationView } from '../types.js';
31
+ import { DonationError } from '../types.js';
32
+ import { FakeOrchestrator } from './fake-orchestrator.js';
33
+
34
+ let tmpRoot: string;
35
+
36
+ /**
37
+ * A well-formed 32-byte base64url owner key. `DonationService.provision`
38
+ * shape-checks the pins at the boundary, so a placeholder string no longer stands
39
+ * in for one.
40
+ */
41
+ const OWNER_KEY = Buffer.alloc(32, 7).toString('base64url');
42
+
43
+ beforeEach(() => {
44
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-donation-sup-'));
45
+ });
46
+
47
+ afterEach(() => {
48
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
49
+ });
50
+
51
+ /** Everything one test needs, sharing a single mutable clock. */
52
+ interface Harness {
53
+ orch: FakeOrchestrator;
54
+ store: DonationStore;
55
+ service: DonationService;
56
+ supervisor: DonationSupervisor;
57
+ /** Move the shared clock forward. */
58
+ advance: (ms: number) => void;
59
+ nowMs: () => number;
60
+ /** Provision one donation. */
61
+ provision: () => Promise<DonationView>;
62
+ }
63
+
64
+ const START_MS = Date.parse('2026-01-01T00:00:00.000Z');
65
+
66
+ function makeHarness(): Harness {
67
+ let nowMs = START_MS;
68
+ const now = (): Date => new Date(nowMs);
69
+
70
+ const orch = new FakeOrchestrator();
71
+ const store = new DonationStore(join(tmpRoot, 'donations'));
72
+ const grants = new GrantService({ store: new GrantStore(join(tmpRoot, 'grants')) });
73
+ const token = grants.issue({ label: 'Alice', maxNodes: 10 }).token;
74
+ const service = new DonationService({ orchestrator: orch, grants, store, now });
75
+ const supervisor = new DonationSupervisor({ service, store, orchestrator: orch, now });
76
+
77
+ return {
78
+ orch,
79
+ store,
80
+ service,
81
+ supervisor,
82
+ advance: (ms) => { nowMs += ms; },
83
+ nowMs: () => nowMs,
84
+ provision: () => service.provision({
85
+ grantToken: token,
86
+ partyId: 'party-P',
87
+ bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
88
+ ownerKeys: [OWNER_KEY],
89
+ }),
90
+ };
91
+ }
92
+
93
+ /** Force a record's status without going through the (fetch-driven) seed path. */
94
+ function setStatus(store: DonationStore, id: string, status: Donation['status']): void {
95
+ store.put({ ...requireDonation(store, id), status });
96
+ }
97
+
98
+ function requireDonation(store: DonationStore, id: string): Donation {
99
+ const donation = store.get(id);
100
+ if (!donation) throw new Error(`no donation ${id}`);
101
+ return donation;
102
+ }
103
+
104
+ function dockerIdOf(donation: { dockerId?: string }): string {
105
+ if (!donation.dockerId) throw new Error('donation has no dockerId');
106
+ return donation.dockerId;
107
+ }
108
+
109
+ /** Let queued fire-and-forget passes run. */
110
+ function flush(): Promise<void> {
111
+ return new Promise((res) => setTimeout(res, 5));
112
+ }
113
+
114
+ /** A store whose every read fails — a malformed `donations.json` on disk. */
115
+ class UnreadableDonationStore extends DonationStore {
116
+ override list(): Donation[] {
117
+ throw new DonationError('storage_error', 'donations file is not valid JSON');
118
+ }
119
+ }
120
+
121
+ describe('DonationSupervisor.reconcile', () => {
122
+ it('respawns a seeded-but-stopped node, keeping its status and swapping its handle', async () => {
123
+ const h = makeHarness();
124
+ const view = await h.provision();
125
+ setStatus(h.store, view.id, 'seeded');
126
+ h.orch.crash(dockerIdOf(view));
127
+
128
+ const respawned = await h.supervisor.reconcile();
129
+
130
+ expect(respawned).toEqual([view.id]);
131
+ const stored = requireDonation(h.store, view.id);
132
+ expect(stored.dockerId).toBe('dock_2');
133
+ expect(stored.dockerId).not.toBe(view.dockerId);
134
+ // A seeded node needs no re-seeding — the loan is still live.
135
+ expect(stored.status).toBe('seeded');
136
+ // Fresh host↔node bearer for the new child.
137
+ expect(stored.seedToken).toBe('seed-token-2');
138
+ expect(h.orch.createCalls).toHaveLength(2);
139
+ });
140
+
141
+ it('leaves a running node alone', async () => {
142
+ const h = makeHarness();
143
+ const view = await h.provision();
144
+ setStatus(h.store, view.id, 'seeded');
145
+
146
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
147
+ expect(h.orch.createCalls).toHaveLength(1);
148
+ });
149
+
150
+ it('never respawns a terminated loan', async () => {
151
+ const h = makeHarness();
152
+ const view = await h.provision();
153
+ setStatus(h.store, view.id, 'seeded');
154
+ await h.service.terminate(view.id);
155
+
156
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
157
+ expect(h.orch.createCalls).toHaveLength(1);
158
+ expect(requireDonation(h.store, view.id).status).toBe('terminated');
159
+ });
160
+
161
+ it('respawns a stopped awaiting_seed node so the borrower can still seed it', async () => {
162
+ const h = makeHarness();
163
+ const view = await h.provision();
164
+ h.orch.crash(dockerIdOf(view));
165
+
166
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
167
+ const stored = requireDonation(h.store, view.id);
168
+ expect(stored.status).toBe('awaiting_seed');
169
+ expect(stored.seedEndpoint).toContain('9002');
170
+ });
171
+
172
+ it('honours the backoff window, then attempts again once the clock passes it', async () => {
173
+ const h = makeHarness();
174
+ const view = await h.provision();
175
+ setStatus(h.store, view.id, 'seeded');
176
+ h.orch.crash(dockerIdOf(view));
177
+ h.orch.failCreate = true;
178
+
179
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
180
+ expect(h.orch.createCalls).toHaveLength(2);
181
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(1);
182
+
183
+ // attempts = 1 → base * 2^1 = 10s. One second later is still too soon.
184
+ h.advance(1_000);
185
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
186
+ expect(h.orch.createCalls).toHaveLength(2);
187
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(1);
188
+
189
+ h.advance(10_000);
190
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
191
+ expect(h.orch.createCalls).toHaveLength(3);
192
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(2);
193
+ });
194
+
195
+ it('gives up after the attempt cap: record → error, child stopped but not reclaimed', async () => {
196
+ const h = makeHarness();
197
+ const view = await h.provision();
198
+ setStatus(h.store, view.id, 'seeded');
199
+ h.orch.crash(dockerIdOf(view));
200
+ h.orch.failCreate = true;
201
+
202
+ for (let i = 0; i < DONATION_RESPAWN_MAX_ATTEMPTS; i++) {
203
+ await h.supervisor.reconcile();
204
+ // Well past the longest backoff, so every pass gets to attempt.
205
+ h.advance(10 * 60_000);
206
+ }
207
+
208
+ const stored = requireDonation(h.store, view.id);
209
+ expect(stored.status).toBe('error');
210
+ expect(stored.respawn?.attempts).toBe(DONATION_RESPAWN_MAX_ATTEMPTS);
211
+ expect(stored.error).toContain(`${DONATION_RESPAWN_MAX_ATTEMPTS} attempts`);
212
+ expect(stored.error).toContain('spawn boom');
213
+ // The workdir holds the identity key the borrower's cadre approved — the
214
+ // give-up path stops the child but must never reclaim it.
215
+ //
216
+ // Doubles as the standing guard on `FakeOrchestrator`'s drop being
217
+ // success-only (mirroring `restoreDroppedHandles`): every create here fails,
218
+ // so a fake that dropped the prior handle regardless would leave `giveUp`
219
+ // with nothing to stop, and this line fails with
220
+ // `expected [] to include 'dock_1'`.
221
+ expect(h.orch.stopped).toContain(view.dockerId);
222
+ expect(h.orch.removed).toEqual([]);
223
+
224
+ // `error` is terminal: no further attempts, and the grant's quota is freed.
225
+ const createsAtGiveUp = h.orch.createCalls.length;
226
+ h.advance(10 * 60_000);
227
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
228
+ expect(h.orch.createCalls).toHaveLength(createsAtGiveUp);
229
+ expect(h.store.liveNodeCount(stored.grantToken)).toBe(0);
230
+ });
231
+
232
+ it('refills the attempt budget once a respawned node has stayed up', async () => {
233
+ const h = makeHarness();
234
+ const view = await h.provision();
235
+ const provisioned = requireDonation(h.store, view.id);
236
+ h.store.put({
237
+ ...provisioned,
238
+ status: 'seeded',
239
+ respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
240
+ });
241
+
242
+ // Still inside the healthy window — the crash loop's count stands.
243
+ h.advance(DONATION_RESPAWN_HEALTHY_MS - 1_000);
244
+ await h.supervisor.reconcile();
245
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(3);
246
+
247
+ h.advance(2_000);
248
+ await h.supervisor.reconcile();
249
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(0);
250
+ // A liveness observation is not borrower activity — the stale-awaiting_seed
251
+ // reap's clock must not be pushed forward by it.
252
+ expect(requireDonation(h.store, view.id).updatedAt).toBe(provisioned.updatedAt);
253
+ });
254
+
255
+ it('skips a record that predates persisted spawn inputs without ending the sweep', async () => {
256
+ const h = makeHarness();
257
+ // Written first, so a throw here would starve the respawnable record below.
258
+ h.store.put({
259
+ id: 'grn_legacy',
260
+ grantToken: 'tok-legacy',
261
+ partyId: 'party-old',
262
+ profile: 'storage',
263
+ status: 'seeded',
264
+ dockerId: 'dock_gone',
265
+ createdAt: new Date(START_MS).toISOString(),
266
+ updatedAt: new Date(START_MS).toISOString(),
267
+ });
268
+
269
+ const view = await h.provision();
270
+ setStatus(h.store, view.id, 'seeded');
271
+ h.orch.crash(dockerIdOf(view));
272
+
273
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
274
+ const legacy = requireDonation(h.store, 'grn_legacy');
275
+ expect(legacy.status).toBe('seeded');
276
+ expect(legacy.respawn).toBeUndefined();
277
+ });
278
+
279
+ it('leaves a still-provisioning record alone — provision owns that child', async () => {
280
+ const h = makeHarness();
281
+ // A handle written by a provision that has not yet flipped to awaiting_seed.
282
+ // Respawning it here would race that provision and strand the record.
283
+ h.store.put({
284
+ id: 'grn_inflight',
285
+ grantToken: 'tok',
286
+ partyId: 'party-P',
287
+ bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
288
+ ownerKeys: [OWNER_KEY],
289
+ profile: 'storage',
290
+ status: 'provisioning',
291
+ dockerId: 'dock_inflight',
292
+ createdAt: new Date(START_MS).toISOString(),
293
+ updatedAt: new Date(START_MS).toISOString(),
294
+ });
295
+
296
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
297
+ expect(h.orch.createCalls).toEqual([]);
298
+ expect(requireDonation(h.store, 'grn_inflight').status).toBe('provisioning');
299
+ });
300
+
301
+ it('skips a record that has no orchestrator handle yet', async () => {
302
+ const h = makeHarness();
303
+ h.store.put({
304
+ id: 'grn_nohandle',
305
+ grantToken: 'tok',
306
+ partyId: 'party-P',
307
+ bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
308
+ ownerKeys: [OWNER_KEY],
309
+ profile: 'storage',
310
+ status: 'awaiting_seed',
311
+ createdAt: new Date(START_MS).toISOString(),
312
+ updatedAt: new Date(START_MS).toISOString(),
313
+ });
314
+
315
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
316
+ expect(h.orch.createCalls).toEqual([]);
317
+ });
318
+
319
+ it('does not undo a seed that lands while the pass is mid-flight', async () => {
320
+ const h = makeHarness();
321
+ const view = await h.provision();
322
+ const provisioned = requireDonation(h.store, view.id);
323
+ h.store.put({
324
+ ...provisioned,
325
+ respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
326
+ });
327
+ h.advance(DONATION_RESPAWN_HEALTHY_MS + 1_000);
328
+
329
+ // The borrower's seed lands between the pass's store snapshot and the
330
+ // budget-refill write — the refill must merge, not replay a stale row.
331
+ h.orch.onIsRunning = () => {
332
+ h.orch.onIsRunning = undefined;
333
+ h.store.put({
334
+ ...requireDonation(h.store, view.id),
335
+ status: 'seeded',
336
+ updatedAt: new Date(h.nowMs()).toISOString(),
337
+ });
338
+ };
339
+
340
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
341
+ const stored = requireDonation(h.store, view.id);
342
+ expect(stored.status).toBe('seeded');
343
+ expect(stored.respawn?.attempts).toBe(0);
344
+ });
345
+
346
+ it('leaves a record that went terminal mid-attempt alone instead of marking it error', async () => {
347
+ const h = makeHarness();
348
+ const view = await h.provision();
349
+ h.store.put({
350
+ ...requireDonation(h.store, view.id),
351
+ status: 'seeded',
352
+ // Already at the cap, and long past the longest backoff — so the next
353
+ // failure lands straight in the give-up path.
354
+ respawn: {
355
+ attempts: DONATION_RESPAWN_MAX_ATTEMPTS,
356
+ lastAttemptAt: new Date(h.nowMs() - 10 * 60_000).toISOString(),
357
+ },
358
+ });
359
+ h.orch.crash(dockerIdOf(view));
360
+ h.orch.failCreate = true;
361
+ // The reap terminates the loan while the respawn's spawn is in flight.
362
+ h.orch.onCreate = () => {
363
+ h.store.put({ ...requireDonation(h.store, view.id), status: 'terminated' });
364
+ };
365
+
366
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
367
+
368
+ const stored = requireDonation(h.store, view.id);
369
+ // The borrower ended this loan — a host give-up must not rewrite that.
370
+ expect(stored.status).toBe('terminated');
371
+ expect(stored.error).toBeUndefined();
372
+ // The attempt counter is the one thing the failed attempt may still record.
373
+ expect(stored.respawn?.attempts).toBe(DONATION_RESPAWN_MAX_ATTEMPTS + 1);
374
+ expect(h.orch.stopped).toEqual([]);
375
+ });
376
+
377
+ it('does not count a respawn abandoned mid-spawn as a failed attempt', async () => {
378
+ const h = makeHarness();
379
+ const view = await h.provision();
380
+ h.store.put({
381
+ ...requireDonation(h.store, view.id),
382
+ status: 'seeded',
383
+ // Already at the cap and long past the longest backoff, so a *failed*
384
+ // attempt here would land straight in the give-up path.
385
+ respawn: {
386
+ attempts: DONATION_RESPAWN_MAX_ATTEMPTS,
387
+ lastAttemptAt: new Date(h.nowMs() - 10 * 60_000).toISOString(),
388
+ },
389
+ });
390
+ h.orch.crash(dockerIdOf(view));
391
+ // The borrower ends the loan while the respawn's spawn is in flight.
392
+ h.orch.createDelayMs = 20;
393
+ let terminated: Promise<void> | undefined;
394
+ h.orch.onCreate = () => { terminated ??= h.service.terminate(view.id); };
395
+
396
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
397
+ await terminated;
398
+
399
+ const stored = requireDonation(h.store, view.id);
400
+ // Nothing threw, so no attempt was persisted and give-up never ran.
401
+ expect(stored.status).toBe('terminated');
402
+ expect(stored.error).toBeUndefined();
403
+ expect(stored.respawn?.attempts).toBe(DONATION_RESPAWN_MAX_ATTEMPTS);
404
+ expect(stored.dockerId).toBe(view.dockerId);
405
+ // The abandoned child is stopped and reclaimed, not left holding ports.
406
+ expect(h.orch.stopped).toContain('dock_2');
407
+ expect(h.orch.removed).toContain('dock_2');
408
+ });
409
+
410
+ it('survives a pass over a store it cannot read', async () => {
411
+ const orch = new FakeOrchestrator();
412
+ const store = new UnreadableDonationStore(join(tmpRoot, 'donations'));
413
+ const grants = new GrantService({ store: new GrantStore(join(tmpRoot, 'grants')) });
414
+ const service = new DonationService({ orchestrator: orch, grants, store });
415
+ const supervisor = new DonationSupervisor({ service, store, orchestrator: orch });
416
+
417
+ await expect(supervisor.reconcile()).resolves.toEqual([]);
418
+ expect(orch.createCalls).toEqual([]);
419
+ });
420
+
421
+ it('serializes overlapping passes so one id is never double-spawned', async () => {
422
+ const h = makeHarness();
423
+ const view = await h.provision();
424
+ setStatus(h.store, view.id, 'seeded');
425
+ h.orch.crash(dockerIdOf(view));
426
+ h.orch.createDelayMs = 20;
427
+
428
+ const [first, second] = await Promise.all([
429
+ h.supervisor.reconcile(),
430
+ h.supervisor.reconcile(),
431
+ ]);
432
+
433
+ // Whichever pass wins the tail respawns; the other then finds it running.
434
+ expect([...first, ...second]).toEqual([view.id]);
435
+ // The original provision plus exactly one respawn.
436
+ expect(h.orch.createCalls).toHaveLength(2);
437
+ });
438
+ });
439
+
440
+ describe('DonationSupervisor start/stop', () => {
441
+ it('sweeps at startup and again on a donated child exit', async () => {
442
+ const h = makeHarness();
443
+ const view = await h.provision();
444
+ setStatus(h.store, view.id, 'seeded');
445
+ h.orch.crash(dockerIdOf(view));
446
+
447
+ h.supervisor.start();
448
+ try {
449
+ // Queued behind the startup pass, so awaiting it proves that pass ran.
450
+ await h.supervisor.reconcile();
451
+ expect(requireDonation(h.store, view.id).dockerId).toBe('dock_2');
452
+
453
+ // Now the exit-event trigger, with no manual reconcile in between.
454
+ h.advance(60_000);
455
+ h.orch.crash('dock_2');
456
+ await flush();
457
+ expect(requireDonation(h.store, view.id).dockerId).toBe('dock_3');
458
+ } finally {
459
+ h.supervisor.stop();
460
+ }
461
+ });
462
+
463
+ it('ignores owner-node exits — bin/host.ts owns re-spawning that one', async () => {
464
+ const h = makeHarness();
465
+ const view = await h.provision();
466
+ setStatus(h.store, view.id, 'seeded');
467
+
468
+ h.supervisor.start();
469
+ try {
470
+ await h.supervisor.reconcile(); // drain the startup pass (node is running)
471
+ // Take the node down WITHOUT an exit event, so the only event in play is
472
+ // the owner's.
473
+ await h.orch.stopContainer(dockerIdOf(view));
474
+
475
+ const ownerExit: ManagedNodeInfo = {
476
+ id: 'owner',
477
+ dockerId: 'dock_owner',
478
+ partyId: 'host-party',
479
+ profile: 'storage',
480
+ status: 'stopped',
481
+ spawnedAt: new Date(START_MS).toISOString(),
482
+ workdir: '/fake/owner',
483
+ ports: { health: 0, metrics: 0, p2p: 0, admin: 0 },
484
+ owner: true,
485
+ };
486
+ h.orch.emit(ownerExit);
487
+ await flush();
488
+
489
+ expect(h.orch.createCalls).toHaveLength(1);
490
+ expect(requireDonation(h.store, view.id).dockerId).toBe(view.dockerId);
491
+ } finally {
492
+ h.supervisor.stop();
493
+ }
494
+ });
495
+
496
+ it('stops reacting to exits after stop()', async () => {
497
+ const h = makeHarness();
498
+ const view = await h.provision();
499
+ setStatus(h.store, view.id, 'seeded');
500
+
501
+ h.supervisor.start();
502
+ await h.supervisor.reconcile();
503
+ h.supervisor.stop();
504
+
505
+ h.orch.crash(dockerIdOf(view));
506
+ await flush();
507
+ // The exit listener is gone, so the crash goes unnoticed until the next start.
508
+ expect(requireDonation(h.store, view.id).dockerId).toBe(view.dockerId);
509
+ });
510
+ });
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Contract tests for `FakeOrchestrator` itself — the handle lifecycle it borrows
3
+ * from `HostProcessOrchestrator`. The donation suites lean on these semantics to
4
+ * express races that only exist because the real class drops and rejects
5
+ * handles, so this file exists to stop a later relaxation of the fake from
6
+ * quietly turning one of those tests green. Each case names the real behaviour
7
+ * it mirrors.
8
+ */
9
+
10
+ import { describe, expect, it } from 'vitest';
11
+
12
+ import type { OrchestratorCreateRequest } from '@serfab/cadre-provider';
13
+
14
+ import { FakeOrchestrator } from './fake-orchestrator.js';
15
+
16
+ const request = (containerId: string): OrchestratorCreateRequest => ({
17
+ containerId,
18
+ partyId: 'party-P',
19
+ bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
20
+ profile: 'storage',
21
+ });
22
+
23
+ describe('FakeOrchestrator handle lifecycle', () => {
24
+ it('drops the prior handle when a re-spawn succeeds (mirrors dropStaleHandle)', async () => {
25
+ const orch = new FakeOrchestrator();
26
+ const first = await orch.createContainer(request('grn_1'));
27
+ const second = await orch.createContainer(request('grn_1'));
28
+
29
+ await expect(orch.stopContainer(first.dockerId)).rejects.toThrow(
30
+ `Container not found: ${first.dockerId}`,
31
+ );
32
+ // The rejected call left no trace: `stopped` records handles acted on, not
33
+ // calls attempted.
34
+ expect(orch.stopped).toEqual([]);
35
+ // …and the container now resolves only to the new spawn.
36
+ expect(orch.resolveDockerId('grn_1')).toBe(second.dockerId);
37
+
38
+ await orch.stopContainer(second.dockerId);
39
+ expect(orch.stopped).toEqual([second.dockerId]);
40
+ });
41
+
42
+ it('drops only the re-spawned container, leaving another container untouched', async () => {
43
+ const orch = new FakeOrchestrator();
44
+ const other = await orch.createContainer(request('grn_2'));
45
+ await orch.createContainer(request('grn_1'));
46
+ await orch.createContainer(request('grn_1'));
47
+
48
+ // The real drop filters on containerId; a fake that cleared the whole map
49
+ // would still pass every same-container case above.
50
+ await expect(orch.stopContainer(other.dockerId)).resolves.toBeUndefined();
51
+ expect(orch.resolveDockerId('grn_2')).toBe(other.dockerId);
52
+ });
53
+
54
+ it('keeps the prior handle live across the whole pre-drop await window', async () => {
55
+ const orch = new FakeOrchestrator();
56
+ const first = await orch.createContainer(request('grn_1'));
57
+
58
+ // The invariant the donation race tests rest on: a concurrent stop started
59
+ // from `onCreate` still finds the old handle. Deferring it onto a microtask
60
+ // puts it strictly after `onCreate` returns and strictly before the
61
+ // `createDelayMs` timer, so this one case pins the drop behind BOTH — with
62
+ // no dependence on wall-clock timing. The outcome is captured rather than
63
+ // rethrown so a regression fails this assertion instead of surfacing as an
64
+ // unhandled rejection.
65
+ orch.createDelayMs = 1;
66
+ let outcome: Promise<string> | undefined;
67
+ orch.onCreate = () => {
68
+ outcome ??= Promise.resolve()
69
+ .then(() => orch.stopContainer(first.dockerId))
70
+ .then(() => 'stopped', (err: Error) => `rejected: ${err.message}`);
71
+ };
72
+
73
+ const second = await orch.createContainer(request('grn_1'));
74
+
75
+ expect(await outcome).toBe('stopped');
76
+ expect(orch.stopped).toEqual([first.dockerId]);
77
+ expect(orch.resolveDockerId('grn_1')).toBe(second.dockerId);
78
+ });
79
+
80
+ it('leaves the prior handle in place when the re-spawn fails (mirrors restoreDroppedHandles)', async () => {
81
+ const orch = new FakeOrchestrator();
82
+ const first = await orch.createContainer(request('grn_1'));
83
+
84
+ orch.failCreate = true;
85
+ await expect(orch.createContainer(request('grn_1'))).rejects.toThrow('spawn boom');
86
+
87
+ // Host state is exactly as the failed attempt found it — which is what lets
88
+ // `DonationSupervisor.giveUp` still stop the child it knows about.
89
+ await expect(orch.stopContainer(first.dockerId)).resolves.toBeUndefined();
90
+ expect(orch.stopped).toEqual([first.dockerId]);
91
+ expect(orch.resolveDockerId('grn_1')).toBe(first.dockerId);
92
+ });
93
+
94
+ it('rejects a never-issued dockerId (mirrors requireHandle)', async () => {
95
+ const orch = new FakeOrchestrator();
96
+
97
+ await expect(orch.removeContainer('dock_nope')).rejects.toThrow(
98
+ 'Container not found: dock_nope',
99
+ );
100
+ expect(orch.removed).toEqual([]);
101
+ });
102
+
103
+ it('rejects a second call once a handle has been removed (mirrors removeContainer deleting it)', async () => {
104
+ const orch = new FakeOrchestrator();
105
+ const { dockerId } = await orch.createContainer(request('grn_1'));
106
+
107
+ await orch.removeContainer(dockerId);
108
+ expect(orch.removed).toEqual([dockerId]);
109
+
110
+ await expect(orch.stopContainer(dockerId)).rejects.toThrow(
111
+ `Container not found: ${dockerId}`,
112
+ );
113
+ expect(orch.stopped).toEqual([]);
114
+ });
115
+
116
+ it('fires onStop for a rejected stop, so a test can still observe the attempt', async () => {
117
+ const orch = new FakeOrchestrator();
118
+ const attempted: string[] = [];
119
+ orch.onStop = (id) => { attempted.push(id); };
120
+
121
+ await expect(orch.stopContainer('dock_nope')).rejects.toThrow('Container not found');
122
+ expect(attempted).toEqual(['dock_nope']);
123
+ expect(orch.stopped).toEqual([]);
124
+ });
125
+
126
+ it('refuses to reclaim the workdir of a container that still resolves (mirrors the live-handle guard)', async () => {
127
+ const orch = new FakeOrchestrator();
128
+ await orch.createContainer(request('grn_1'));
129
+
130
+ // A live handle owns that directory; only `removeContainer` — which stops
131
+ // the child first — may delete it.
132
+ expect(orch.reclaimWorkdir('grn_1')).toBe(false);
133
+ expect(orch.reclaimedWorkdirs).toEqual([]);
134
+ });
135
+
136
+ it('reclaims the workdir of a container no handle owns', async () => {
137
+ const orch = new FakeOrchestrator();
138
+
139
+ // Never spawned — the stuck-`provisioning` record whose host died before a
140
+ // handle ever existed.
141
+ expect(orch.reclaimWorkdir('grn_orphan')).toBe(true);
142
+ expect(orch.reclaimedWorkdirs).toEqual(['grn_orphan']);
143
+
144
+ // …and once the container's own handle is removed, its id becomes
145
+ // reclaimable too.
146
+ const { dockerId } = await orch.createContainer(request('grn_1'));
147
+ expect(orch.reclaimWorkdir('grn_1')).toBe(false);
148
+ await orch.removeContainer(dockerId);
149
+ expect(orch.reclaimWorkdir('grn_1')).toBe(true);
150
+ expect(orch.reclaimedWorkdirs).toEqual(['grn_orphan', 'grn_1']);
151
+ });
152
+
153
+ it('fires onSpawned after the drop, with the new handle live and the old one gone', async () => {
154
+ const orch = new FakeOrchestrator();
155
+ const first = await orch.createContainer(request('grn_1'));
156
+
157
+ let observed: { spawned: string; resolves: string | undefined } | undefined;
158
+ orch.onSpawned = (dockerId) => {
159
+ observed = { spawned: dockerId, resolves: orch.resolveDockerId('grn_1') };
160
+ };
161
+ const second = await orch.createContainer(request('grn_1'));
162
+
163
+ // The post-drop world: the container already resolves to the new handle, so
164
+ // work driven from here sees what `abandonRespawn`'s caller would see.
165
+ expect(observed).toEqual({ spawned: second.dockerId, resolves: second.dockerId });
166
+ expect(second.dockerId).not.toBe(first.dockerId);
167
+ });
168
+ });