@nowcrew/daemon 0.6.60 → 0.6.64

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 (47) hide show
  1. package/README.md +9 -8
  2. package/dist/agent-ability/materializer.js +1 -20
  3. package/dist/automatic-install-target.js +10 -15
  4. package/dist/computer-cli.js +1 -10
  5. package/dist/computer-service.js +1 -41
  6. package/dist/config.js +0 -35
  7. package/dist/daemon-migration-controller.js +18 -16
  8. package/dist/execution-runner.js +13 -35
  9. package/dist/local-executor.js +1 -44
  10. package/dist/machine-info.js +2 -3
  11. package/dist/main.js +0 -83
  12. package/dist/managed-service-lifecycle.js +2 -47
  13. package/dist/managed-service-startup.js +0 -2
  14. package/dist/profile-layout.js +4 -10
  15. package/dist/runner.js +0 -1
  16. package/dist/serve.js +3 -64
  17. package/dist/workspace.js +1 -24
  18. package/package.json +10 -9
  19. package/dist/local-memory/index-budget.js +0 -74
  20. package/dist/local-memory/pending.js +0 -111
  21. package/dist/local-memory/runtime.js +0 -87
  22. package/dist/local-memory/types.js +0 -1
  23. package/dist/local-memory/write.js +0 -448
  24. package/dist/storage-config.js +0 -175
  25. package/dist/storage-control.js +0 -131
  26. package/dist/storage-copy.js +0 -444
  27. package/dist/storage-credential-guard.js +0 -21
  28. package/dist/storage-doctor.js +0 -175
  29. package/dist/storage-identity.js +0 -29
  30. package/dist/storage-layout.js +0 -143
  31. package/dist/storage-manifest.js +0 -440
  32. package/dist/storage-migration-controller.js +0 -417
  33. package/dist/storage-migration-manifest.js +0 -105
  34. package/dist/storage-migration-policy.js +0 -100
  35. package/dist/storage-runtime-controller.js +0 -313
  36. package/dist/storage-runtime-readiness.js +0 -184
  37. package/dist/storage-runtime.js +0 -39
  38. package/dist/storage-safe-fs.js +0 -293
  39. package/dist/storage-serve-adapter.js +0 -65
  40. package/dist/storage-status-delivery.js +0 -201
  41. package/dist/storage-status-replay.js +0 -125
  42. package/dist/storage-target-confirmation.js +0 -129
  43. package/dist/storage-worker-command.js +0 -27
  44. package/dist/storage-worker-executor.js +0 -383
  45. package/dist/storage-worker-handoff.js +0 -151
  46. package/dist/storage-worker-operation.js +0 -283
  47. package/dist/storage-worker-status.js +0 -105
@@ -1,129 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { isAbsolute, join } from "node:path";
3
- import { z } from "zod";
4
- import { atomicPrivateWrite } from "./atomic-private-write.js";
5
- import { readStorageMigrationReceipt } from "./storage-migration-controller.js";
6
- const FingerprintSchema = z.string().regex(/^sha256:[0-9a-f]{64}$/u);
7
- const IdentitySchema = z.object({
8
- type: z.literal("daemon:storage-migration-confirmed"),
9
- migrationId: z.string().uuid(),
10
- environment: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,31}$/u),
11
- workspaceId: z.string().uuid(),
12
- profile: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u),
13
- manifestDigest: z.string().regex(/^[0-9a-f]{64}$/u),
14
- targetStorageFingerprint: FingerprintSchema,
15
- }).strict();
16
- const AcknowledgementSchema = IdentitySchema.omit({ type: true }).extend({
17
- version: z.literal(1),
18
- confirmedAt: z.string().datetime({ offset: true }),
19
- }).strict();
20
- const delay = (milliseconds) => new Promise((resolvePromise) => {
21
- setTimeout(resolvePromise, milliseconds);
22
- });
23
- export function storageMigrationAcknowledgementPath(backupsRoot, migrationId) {
24
- if (!isAbsolute(backupsRoot))
25
- throw new Error("storage migration backups root must be absolute");
26
- return join(backupsRoot, z.string().uuid().parse(migrationId), "hello-confirmed.json");
27
- }
28
- export async function waitForStorageMigrationAcknowledgement(input) {
29
- const expected = IdentitySchema.omit({ type: true }).parse({
30
- migrationId: input.migrationId,
31
- environment: input.environment,
32
- workspaceId: input.workspaceId,
33
- profile: input.profile,
34
- manifestDigest: input.manifestDigest,
35
- targetStorageFingerprint: input.targetStorageFingerprint,
36
- });
37
- const timeoutMs = z.number().int().min(10).max(600_000).parse(input.timeoutMs ?? 120_000);
38
- const pollIntervalMs = z.number().int().min(1).max(5_000).parse(input.pollIntervalMs ?? 250);
39
- const path = storageMigrationAcknowledgementPath(input.backupsRoot, expected.migrationId);
40
- const deadline = Date.now() + timeoutMs;
41
- while (Date.now() <= deadline) {
42
- try {
43
- const acknowledgement = AcknowledgementSchema.parse(JSON.parse(await readFile(path, "utf8")));
44
- const { version: _version, confirmedAt: _confirmedAt, ...identity } = acknowledgement;
45
- if (JSON.stringify(identity) !== JSON.stringify(expected)) {
46
- throw new Error("storage migration acknowledgement identity mismatch");
47
- }
48
- return;
49
- }
50
- catch (error) {
51
- if (error.code !== "ENOENT")
52
- throw error;
53
- }
54
- await delay(pollIntervalMs);
55
- }
56
- throw new Error("storage migration hello confirmation timeout");
57
- }
58
- export function createStorageTargetConfirmationHandler(input) {
59
- const profile = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u).parse(input.profile);
60
- const completionTimeoutMs = z.number().int().min(10).max(600_000).parse(input.completionTimeoutMs ?? 120_000);
61
- const pollIntervalMs = z.number().int().min(1).max(5_000).parse(input.pollIntervalMs ?? 250);
62
- if (input.identity.storageMigrationId === undefined) {
63
- throw new Error("storage target confirmation requires a migration identity");
64
- }
65
- let active = null;
66
- const handle = async (raw, send) => {
67
- const rawType = typeof raw === "object" && raw !== null && "type" in raw ? raw.type : undefined;
68
- if (rawType !== "daemon:storage-migration-confirmed")
69
- return false;
70
- const confirmation = IdentitySchema.parse(raw);
71
- if (confirmation.migrationId !== input.identity.storageMigrationId
72
- || confirmation.environment !== input.identity.storageEnvironment
73
- || confirmation.workspaceId !== input.identity.storageWorkspaceId
74
- || confirmation.profile !== profile
75
- || confirmation.targetStorageFingerprint !== input.identity.storageIdFingerprint) {
76
- throw new Error("storage migration confirmation identity mismatch");
77
- }
78
- const key = JSON.stringify(confirmation);
79
- if (active !== null) {
80
- if (active.key !== key)
81
- throw new Error("storage migration confirmation changed while processing");
82
- return active.promise;
83
- }
84
- const processConfirmation = async () => {
85
- const receipt = await readStorageMigrationReceipt(input.backupsRoot, confirmation.migrationId);
86
- if (receipt === null || receipt.status !== "service_switched"
87
- || receipt.environment !== confirmation.environment
88
- || receipt.workspaceId !== confirmation.workspaceId
89
- || receipt.profile !== confirmation.profile
90
- || receipt.manifestDigest !== confirmation.manifestDigest) {
91
- throw new Error("storage migration confirmation receipt identity mismatch");
92
- }
93
- const { type: _type, ...confirmationIdentity } = confirmation;
94
- await atomicPrivateWrite(storageMigrationAcknowledgementPath(input.backupsRoot, confirmation.migrationId), `${JSON.stringify(AcknowledgementSchema.parse({
95
- version: 1,
96
- ...confirmationIdentity,
97
- confirmedAt: new Date().toISOString(),
98
- }), null, 2)}\n`);
99
- const deadline = Date.now() + completionTimeoutMs;
100
- while (Date.now() <= deadline) {
101
- const current = await readStorageMigrationReceipt(input.backupsRoot, confirmation.migrationId);
102
- if (current?.status === "completed") {
103
- send({
104
- type: "daemon:storage-migration-status",
105
- migrationId: confirmation.migrationId,
106
- status: "completed",
107
- environment: confirmation.environment,
108
- workspaceId: confirmation.workspaceId,
109
- profile: confirmation.profile,
110
- });
111
- return true;
112
- }
113
- if (current !== null && ["failed", "rolled_back", "rollback_failed"].includes(current.status)) {
114
- throw new Error(`storage migration ended before completion: ${current.status}`);
115
- }
116
- await delay(pollIntervalMs);
117
- }
118
- throw new Error("storage migration worker completion timeout");
119
- };
120
- const promise = processConfirmation();
121
- active = { key, promise };
122
- void promise.catch(() => {
123
- if (active?.key === key)
124
- active = null;
125
- });
126
- return promise;
127
- };
128
- return Object.freeze({ handle });
129
- }
@@ -1,27 +0,0 @@
1
- import { posix, win32 } from "node:path";
2
- import { executeStorageMigrationWorker, recoverStorageMigrationWorker, } from "./storage-worker-executor.js";
3
- import { completeStorageMigrationWorkerServiceForHandoff } from "./storage-worker-handoff.js";
4
- import { startStorageWorkerHeartbeat, writeStorageWorkerFailureStatus, } from "./storage-worker-status.js";
5
- export async function runStorageWorkerCommand(args, execute = executeStorageMigrationWorker, writeFailure = writeStorageWorkerFailureStatus, startHeartbeat = startStorageWorkerHeartbeat, completeService = completeStorageMigrationWorkerServiceForHandoff, recover = recoverStorageMigrationWorker) {
6
- const command = args[0];
7
- if (command !== "storage-migration-worker" && command !== "storage-migration-recover")
8
- return null;
9
- const path = args[1] === "--job" ? args[2] : undefined;
10
- if (args.length !== 3 || path === undefined || path.length === 0
11
- || /[\0\r\n]/u.test(path) || (!posix.isAbsolute(path) && !win32.isAbsolute(path))) {
12
- throw new Error("Invalid storage migration worker command");
13
- }
14
- const stopHeartbeat = await startHeartbeat(path);
15
- try {
16
- await (command === "storage-migration-recover" ? recover(path) : execute(path));
17
- }
18
- catch (error) {
19
- await writeFailure(path, error).catch(() => undefined);
20
- throw error;
21
- }
22
- finally {
23
- await stopHeartbeat().catch(() => undefined);
24
- await completeService(path);
25
- }
26
- return 0;
27
- }
@@ -1,383 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { realpathSync } from "node:fs";
3
- import { buildServiceSpec, captureExactService, serviceAction, systemCommandRunner, } from "./computer-service.js";
4
- import { listProfiles, loadProfile, removeProfile, saveProfile, } from "./computer-profile.js";
5
- import { assertManagedServiceIdentity, installManagedService, uninstallManagedService, uninstallUnregisteredManagedService, } from "./managed-service-lifecycle.js";
6
- import { readManagedServiceRegistry, normalizeManagedServiceRecord, serviceDescriptorSha256, } from "./managed-service-registry.js";
7
- import { readInstallations, writeInstallations, } from "./storage-config.js";
8
- import { runStorageDoctor } from "./storage-doctor.js";
9
- import { readStorageMigrationReceipt, recoverStorageMigration, runStorageMigration, StorageMigrationFailure, } from "./storage-migration-controller.js";
10
- import { readStorageWorkerHandoff } from "./storage-worker-handoff.js";
11
- import { readStorageWorkerOperation } from "./storage-worker-operation.js";
12
- import { storageIdFingerprint } from "./storage-identity.js";
13
- import { waitForStorageMigrationAcknowledgement } from "./storage-target-confirmation.js";
14
- const defaultServiceDependencies = () => ({
15
- assertManagedServiceIdentity,
16
- serviceAction,
17
- uninstallManagedService,
18
- uninstallUnregisteredManagedService,
19
- installManagedService,
20
- captureExactService,
21
- readManagedServices: readManagedServiceRegistry,
22
- listProfiles,
23
- loadProfile,
24
- saveProfile,
25
- removeProfile,
26
- readInstallations,
27
- writeInstallations,
28
- });
29
- function serviceSpec(operation, record, profileHome) {
30
- return buildServiceSpec({
31
- platform: operation.service.platform,
32
- profile: operation.profile,
33
- userHome: realpathSync.native(operation.service.userHome),
34
- uid: operation.service.uid,
35
- nodePath: record.nodePath,
36
- entryPath: record.entryPath,
37
- profileHome,
38
- ...(operation.service.serviceEnvironment === undefined
39
- ? {}
40
- : { environment: operation.service.serviceEnvironment }),
41
- });
42
- }
43
- function assertRecordMatchesSpec(record, spec) {
44
- const normalizedDescriptorPath = spec.descriptorPath === null
45
- ? null
46
- : normalizeManagedServiceRecord({ ...record, descriptorPath: spec.descriptorPath }).descriptorPath;
47
- const mismatches = [
48
- spec.descriptor === null ? "descriptor" : null,
49
- spec.descriptorPath === null ? "descriptorPath" : null,
50
- record.platform !== spec.platform ? "platform" : null,
51
- record.serviceId !== spec.id ? "serviceId" : null,
52
- record.profile !== spec.profile ? "profile" : null,
53
- record.descriptorPath !== normalizedDescriptorPath ? "descriptorPath" : null,
54
- spec.descriptor !== null && record.descriptorSha256 !== serviceDescriptorSha256(spec.descriptor)
55
- ? "descriptorSha256"
56
- : null,
57
- ].filter((value) => value !== null);
58
- if (mismatches.length > 0) {
59
- throw new Error(`Managed service record does not match operation service '${record.serviceId}': ${mismatches.join(", ")}`);
60
- }
61
- }
62
- function sameRecord(left, right) {
63
- return JSON.stringify(left) === JSON.stringify(right);
64
- }
65
- function sameInstallation(left, right) {
66
- return JSON.stringify(left) === JSON.stringify(right);
67
- }
68
- function sameProfile(left, right) {
69
- return JSON.stringify(left) === JSON.stringify(right);
70
- }
71
- function canonicalServerUrl(value) {
72
- return value.replace(/\/+$/u, "");
73
- }
74
- export function createStorageWorkerServiceLifecycle(operation, injected = {}) {
75
- const dependencies = { ...defaultServiceDependencies(), ...injected };
76
- const registry = { userHome: operation.service.userHome };
77
- const sourceRecord = operation.service.sourceRecord;
78
- const targetRecord = operation.service.targetRecord;
79
- const sourceSpec = serviceSpec(operation, sourceRecord, operation.migration.sourceRoots["daemon-home"]);
80
- const targetSpec = serviceSpec(operation, targetRecord, operation.installation.configRoot);
81
- assertRecordMatchesSpec(sourceRecord, sourceSpec);
82
- assertRecordMatchesSpec(targetRecord, targetSpec);
83
- let sourceProfile = null;
84
- let savedTargetProfile = null;
85
- let baselineInstallations = null;
86
- let targetProfileCreated = false;
87
- let targetInstallationWritten = false;
88
- const assertSourceIdentity = () => dependencies.assertManagedServiceIdentity({
89
- spec: sourceSpec,
90
- record: sourceRecord,
91
- registry,
92
- });
93
- const readTargetInstallations = () => dependencies.readInstallations({
94
- configRoot: operation.installation.configRoot,
95
- });
96
- const assertTargetMetadataUnchanged = async () => {
97
- const profiles = await dependencies.listProfiles(operation.installation.configRoot);
98
- if (profiles.includes(operation.profile))
99
- throw new Error(`Target profile '${operation.profile}' already exists`);
100
- const current = await readTargetInstallations();
101
- if (baselineInstallations !== null && JSON.stringify(current) !== JSON.stringify(baselineInstallations)) {
102
- throw new Error("Target installation registry changed after worker preflight");
103
- }
104
- if (current.some((record) => record.profile === operation.profile
105
- || record.installationId === operation.installation.target.installationId)) {
106
- throw new Error("Target installation identity already exists");
107
- }
108
- return current;
109
- };
110
- const preflight = async () => {
111
- await assertSourceIdentity();
112
- const source = await dependencies.captureExactService(sourceSpec, systemCommandRunner);
113
- if (!source.installed || !source.exact || source.running !== operation.service.sourceWasRunning) {
114
- throw new Error("Source service state does not match worker operation");
115
- }
116
- const target = await dependencies.captureExactService(targetSpec, systemCommandRunner);
117
- if (target.installed)
118
- throw new Error(`Target service '${targetSpec.id}' already exists`);
119
- sourceProfile = await dependencies.loadProfile(operation.profile, sourceRecord.daemonHome);
120
- if (sourceProfile.name !== operation.profile
121
- || canonicalServerUrl(sourceProfile.serverUrl) !== canonicalServerUrl(operation.installation.target.serverUrl)) {
122
- throw new Error("Source profile does not match target installation identity");
123
- }
124
- baselineInstallations = await assertTargetMetadataUnchanged();
125
- };
126
- const stopSourceService = async () => {
127
- await dependencies.serviceAction(sourceSpec, "stop", systemCommandRunner);
128
- const stopped = await dependencies.captureExactService(sourceSpec, systemCommandRunner);
129
- if (!stopped.installed || !stopped.exact || stopped.running) {
130
- throw new Error(`Source service '${sourceSpec.id}' did not stop exactly`);
131
- }
132
- };
133
- const installTargetService = async () => {
134
- if (sourceProfile === null || baselineInstallations === null)
135
- throw new Error("Worker service preflight is required");
136
- const installations = await assertTargetMetadataUnchanged();
137
- await assertSourceIdentity();
138
- await dependencies.uninstallManagedService({
139
- spec: sourceSpec,
140
- record: sourceRecord,
141
- runner: systemCommandRunner,
142
- registry,
143
- });
144
- const { version: _version, ...profile } = sourceProfile;
145
- savedTargetProfile = await dependencies.saveProfile({
146
- ...profile,
147
- agentsRoot: targetRecord.agentsRoot,
148
- }, operation.installation.configRoot);
149
- targetProfileCreated = true;
150
- await dependencies.writeInstallations([...installations, operation.installation.target].sort((left, right) => left.profile.localeCompare(right.profile)), { configRoot: operation.installation.configRoot });
151
- targetInstallationWritten = true;
152
- await dependencies.installManagedService({
153
- spec: targetSpec,
154
- record: targetRecord,
155
- runner: systemCommandRunner,
156
- registry,
157
- });
158
- const target = await dependencies.captureExactService(targetSpec, systemCommandRunner);
159
- if (!target.installed || !target.exact || target.running) {
160
- throw new Error(`Target service '${targetSpec.id}' was not installed exactly in stopped state`);
161
- }
162
- };
163
- const startTargetService = async () => {
164
- await dependencies.serviceAction(targetSpec, "start", systemCommandRunner);
165
- const target = await dependencies.captureExactService(targetSpec, systemCommandRunner);
166
- if (!target.installed || !target.exact || !target.running) {
167
- throw new Error(`Target service '${targetSpec.id}' did not start exactly`);
168
- }
169
- };
170
- const removeTargetService = async () => {
171
- const records = await dependencies.readManagedServices(registry);
172
- const registered = records.find((record) => record.serviceId === targetRecord.serviceId
173
- || (record.profile === targetRecord.profile && record.daemonHome === targetRecord.daemonHome));
174
- if (registered !== undefined && !sameRecord(registered, targetRecord)) {
175
- throw new Error(`Target service '${targetSpec.id}' identity changed before rollback`);
176
- }
177
- if (registered !== undefined) {
178
- await dependencies.uninstallManagedService({
179
- spec: targetSpec,
180
- record: targetRecord,
181
- runner: systemCommandRunner,
182
- registry,
183
- });
184
- }
185
- else {
186
- const target = await dependencies.captureExactService(targetSpec, systemCommandRunner);
187
- if (target.installed && !target.exact)
188
- throw new Error(`Target service '${targetSpec.id}' changed before rollback`);
189
- if (target.installed) {
190
- await dependencies.uninstallUnregisteredManagedService({
191
- spec: targetSpec,
192
- daemonHome: targetRecord.daemonHome,
193
- npmPrefix: targetRecord.npmPrefix,
194
- runner: systemCommandRunner,
195
- registry,
196
- });
197
- }
198
- }
199
- const installations = await readTargetInstallations();
200
- const targetInstallation = installations.find((record) => record.profile === operation.profile
201
- || record.installationId === operation.installation.target.installationId);
202
- if (targetInstallation !== undefined) {
203
- if (!sameInstallation(targetInstallation, operation.installation.target)) {
204
- throw new Error("Target installation identity changed before rollback");
205
- }
206
- await dependencies.writeInstallations(installations.filter((record) => !sameInstallation(record, operation.installation.target)), { configRoot: operation.installation.configRoot });
207
- targetInstallationWritten = false;
208
- }
209
- const profiles = await dependencies.listProfiles(operation.installation.configRoot);
210
- if (profiles.includes(operation.profile)) {
211
- const current = await dependencies.loadProfile(operation.profile, operation.installation.configRoot);
212
- const original = sourceProfile
213
- ?? await dependencies.loadProfile(operation.profile, sourceRecord.daemonHome);
214
- const { version: _version, ...profile } = original;
215
- const expected = savedTargetProfile ?? { version: 1, ...profile, agentsRoot: targetRecord.agentsRoot };
216
- if (!sameProfile(current, expected)) {
217
- throw new Error("Target profile identity changed before rollback");
218
- }
219
- await dependencies.removeProfile(operation.profile, operation.installation.configRoot);
220
- targetProfileCreated = false;
221
- }
222
- };
223
- const restoreSourceService = async () => {
224
- const current = await dependencies.captureExactService(sourceSpec, systemCommandRunner);
225
- if (current.installed && !current.exact) {
226
- throw new Error(`Source service '${sourceSpec.id}' changed before rollback`);
227
- }
228
- if (!current.installed) {
229
- await dependencies.installManagedService({
230
- spec: sourceSpec,
231
- record: sourceRecord,
232
- runner: systemCommandRunner,
233
- registry,
234
- });
235
- }
236
- const afterInstall = current.installed
237
- ? current
238
- : await dependencies.captureExactService(sourceSpec, systemCommandRunner);
239
- if (operation.service.sourceWasRunning && !afterInstall.running) {
240
- await dependencies.serviceAction(sourceSpec, "start", systemCommandRunner);
241
- }
242
- else if (!operation.service.sourceWasRunning && afterInstall.running) {
243
- await dependencies.serviceAction(sourceSpec, "stop", systemCommandRunner);
244
- }
245
- const restored = await dependencies.captureExactService(sourceSpec, systemCommandRunner);
246
- if (!restored.installed || !restored.exact || restored.running !== operation.service.sourceWasRunning) {
247
- throw new Error(`Source service '${sourceSpec.id}' was not restored exactly`);
248
- }
249
- };
250
- return Object.freeze({
251
- preflight,
252
- assertServiceIdentity: assertSourceIdentity,
253
- isBusy: () => false,
254
- quiesceExecutions: async () => undefined,
255
- waitForIdle: async () => undefined,
256
- flushLocalState: async () => undefined,
257
- stopSourceService,
258
- installTargetService,
259
- startTargetService,
260
- removeTargetService,
261
- restoreSourceService,
262
- confirmHello: (receipt) => waitForStorageMigrationAcknowledgement({
263
- backupsRoot: operation.migration.backupsRoot,
264
- migrationId: operation.migrationId,
265
- environment: operation.environment,
266
- workspaceId: operation.workspaceId,
267
- profile: operation.profile,
268
- manifestDigest: receipt.manifestDigest,
269
- targetStorageFingerprint: storageIdFingerprint(operation.installation.target.storageId),
270
- }),
271
- });
272
- }
273
- function validateFreshDoctor(operation, doctor) {
274
- if (!doctor.applyAllowed
275
- || doctor.manifestDigest !== operation.expectedManifestDigest
276
- || doctor.manifest.migrationId !== operation.migrationId
277
- || doctor.environment !== operation.environment
278
- || doctor.workspaceId !== operation.workspaceId
279
- || doctor.profile !== operation.profile
280
- || doctor.manifest.targetWorkspaceRoot !== operation.migration.targetWorkspaceRoot) {
281
- throw new StorageMigrationFailure("worker_doctor_mismatch", "fresh worker doctor digest or identity does not match the approved operation");
282
- }
283
- }
284
- function workerDoctorInput(operation, generatedAt = operation.doctorInput.generatedAt) {
285
- const { freeSpaceMultiplier, ...input } = operation.doctorInput;
286
- return {
287
- ...input,
288
- generatedAt,
289
- ...(freeSpaceMultiplier === undefined ? {} : { freeSpaceMultiplier }),
290
- };
291
- }
292
- function workerSourceRoots(operation) {
293
- return Object.fromEntries(Object.entries(operation.migration.sourceRoots)
294
- .filter((entry) => entry[1] !== undefined));
295
- }
296
- export async function executeStorageMigrationWorker(handoffPath, injected = {}) {
297
- const dependencies = {
298
- runDoctor: (input) => runStorageDoctor(input),
299
- runMigration: runStorageMigration,
300
- recoverMigration: recoverStorageMigration,
301
- readReceipt: readStorageMigrationReceipt,
302
- createServiceLifecycle: (operation) => createStorageWorkerServiceLifecycle(operation),
303
- now: () => new Date(),
304
- ...injected,
305
- };
306
- const handoff = await readStorageWorkerHandoff(handoffPath);
307
- const operation = await readStorageWorkerOperation(handoff.operationPath, handoff.operationSha256);
308
- if (handoff.migrationId !== operation.migrationId || handoff.profile !== operation.profile) {
309
- throw new StorageMigrationFailure("worker_handoff_mismatch", "worker handoff does not match operation identity");
310
- }
311
- const lifecycle = dependencies.createServiceLifecycle(operation);
312
- const existing = await dependencies.readReceipt(operation.migration.backupsRoot, operation.migrationId);
313
- if (existing !== null) {
314
- if (existing.environment !== operation.environment || existing.workspaceId !== operation.workspaceId
315
- || existing.profile !== operation.profile) {
316
- throw new StorageMigrationFailure("worker_receipt_mismatch", "worker receipt does not match operation identity");
317
- }
318
- if (existing.status === "completed" || existing.status === "rolled_back")
319
- return existing;
320
- return dependencies.recoverMigration({
321
- backupsRoot: operation.migration.backupsRoot,
322
- migrationId: operation.migrationId,
323
- }, { ...lifecycle, now: dependencies.now });
324
- }
325
- await lifecycle.preflight();
326
- const doctor = await dependencies.runDoctor(workerDoctorInput(operation));
327
- validateFreshDoctor(operation, doctor);
328
- return dependencies.runMigration({
329
- doctor,
330
- sourceRoots: workerSourceRoots(operation),
331
- stagingWorkspaceRoot: operation.migration.stagingWorkspaceRoot,
332
- targetWorkspaceRoot: operation.migration.targetWorkspaceRoot,
333
- backupsRoot: operation.migration.backupsRoot,
334
- backupArtifacts: operation.migration.backupArtifacts,
335
- acceptedWarnings: operation.migration.acceptedWarnings,
336
- }, {
337
- ...lifecycle,
338
- now: dependencies.now,
339
- refreshDoctor: async () => {
340
- const refreshed = await dependencies.runDoctor(workerDoctorInput(operation, dependencies.now().toISOString()));
341
- if (refreshed.manifest.migrationId !== operation.migrationId
342
- || refreshed.environment !== operation.environment
343
- || refreshed.workspaceId !== operation.workspaceId
344
- || refreshed.profile !== operation.profile) {
345
- throw new StorageMigrationFailure("final_doctor_failed", "final worker doctor identity changed");
346
- }
347
- return refreshed;
348
- },
349
- });
350
- }
351
- export async function recoverStorageMigrationWorker(handoffPath, injected = {}) {
352
- const dependencies = {
353
- runDoctor: (input) => runStorageDoctor(input),
354
- runMigration: runStorageMigration,
355
- recoverMigration: recoverStorageMigration,
356
- readReceipt: readStorageMigrationReceipt,
357
- createServiceLifecycle: (operation) => createStorageWorkerServiceLifecycle(operation),
358
- now: () => new Date(),
359
- ...injected,
360
- };
361
- const handoff = await readStorageWorkerHandoff(handoffPath);
362
- const operation = await readStorageWorkerOperation(handoff.operationPath, handoff.operationSha256);
363
- if (handoff.migrationId !== operation.migrationId || handoff.profile !== operation.profile) {
364
- throw new StorageMigrationFailure("worker_handoff_mismatch", "worker handoff does not match operation identity");
365
- }
366
- const receipt = await dependencies.readReceipt(operation.migration.backupsRoot, operation.migrationId);
367
- if (receipt === null) {
368
- throw new StorageMigrationFailure("migration_receipt_missing", "explicit rollback requires an existing migration receipt");
369
- }
370
- if (receipt.environment !== operation.environment || receipt.workspaceId !== operation.workspaceId
371
- || receipt.profile !== operation.profile) {
372
- throw new StorageMigrationFailure("worker_receipt_mismatch", "worker receipt does not match operation identity");
373
- }
374
- if (receipt.status === "completed" || receipt.status === "rolled_back")
375
- return receipt;
376
- return dependencies.recoverMigration({
377
- backupsRoot: operation.migration.backupsRoot,
378
- migrationId: operation.migrationId,
379
- }, { ...dependencies.createServiceLifecycle(operation), now: dependencies.now });
380
- }
381
- export function storageWorkerOperationDigest(operation) {
382
- return createHash("sha256").update(`${JSON.stringify(operation, null, 2)}\n`).digest("hex");
383
- }