@runeditrun/rer 0.2.120 → 0.2.122

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 (152) hide show
  1. package/cli/README.md +173 -5
  2. package/cli/archive.mjs +1 -1
  3. package/cli/authoring.mjs +1 -1
  4. package/cli/browser-runtime.mjs +33 -18
  5. package/cli/business/agent-help.mjs +11 -11
  6. package/cli/business/agent-verbs.mjs +9 -8
  7. package/cli/business/api.mjs +11 -7
  8. package/cli/business/carry.mjs +4 -3
  9. package/cli/business/choices.mjs +1 -1
  10. package/cli/business/command.mjs +33 -11
  11. package/cli/business/connect.mjs +4 -4
  12. package/cli/business/credential-file.mjs +102 -0
  13. package/cli/business/errors.mjs +5 -2
  14. package/cli/business/invocation.mjs +7 -4
  15. package/cli/business/keychain.mjs +6 -2
  16. package/cli/business/local-commands.mjs +9 -3
  17. package/cli/business/mcp-bridge.mjs +2 -1
  18. package/cli/business/questions.mjs +1 -1
  19. package/cli/business/run-child.mjs +5 -5
  20. package/cli/business/run-grant.mjs +27 -8
  21. package/cli/business/run-mask.mjs +8 -1
  22. package/cli/business/scan-command.mjs +1 -1
  23. package/cli/business/service.mjs +4 -2
  24. package/cli/business/state.mjs +2 -2
  25. package/cli/checkout-folders.mjs +1 -1
  26. package/cli/checkout-preparation.mjs +4 -4
  27. package/cli/command-guidance.mjs +9 -0
  28. package/cli/companion/command.mjs +4 -3
  29. package/cli/companion/providers/sandbox.mjs +1 -1
  30. package/cli/companion/setup.mjs +4 -4
  31. package/cli/contract.mjs +8 -8
  32. package/cli/demo.mjs +1 -1
  33. package/cli/deploy-command.mjs +10 -5
  34. package/cli/deploy-hook.mjs +3 -2
  35. package/cli/deploy-inputs.mjs +20 -3
  36. package/cli/deploy-owner-input.mjs +2 -2
  37. package/cli/deploy-settings.mjs +14 -0
  38. package/cli/deploy-source.mjs +1 -1
  39. package/cli/deploy-variables.mjs +7 -1
  40. package/cli/deploy.mjs +6 -4
  41. package/cli/deployment-record.mjs +1 -1
  42. package/cli/dev-identity.mjs +4 -4
  43. package/cli/door-clauses.mjs +2 -2
  44. package/cli/door-mode.mjs +7 -7
  45. package/cli/door.mjs +7 -7
  46. package/cli/errors.mjs +15 -1
  47. package/cli/export-summary.mjs +1 -1
  48. package/cli/export.mjs +1 -1
  49. package/cli/hosted-export.mjs +1 -1
  50. package/cli/hosted-output.mjs +2 -2
  51. package/cli/human-error.mjs +8 -2
  52. package/cli/hydration/browser.mjs +1 -1
  53. package/cli/hydration/check.mjs +1 -1
  54. package/cli/import-summary.mjs +2 -2
  55. package/cli/inspect.mjs +9 -4
  56. package/cli/lifecycle.mjs +10 -10
  57. package/cli/listen.mjs +1 -1
  58. package/cli/listing.mjs +1 -1
  59. package/cli/local-env.mjs +1 -1
  60. package/cli/local.mjs +4 -4
  61. package/cli/managed-server.mjs +36 -13
  62. package/cli/output.mjs +2 -1
  63. package/cli/owner-entry-ready.mjs +92 -0
  64. package/cli/parse.mjs +19 -9
  65. package/cli/port.mjs +3 -3
  66. package/cli/portability-runtime.mjs +16 -0
  67. package/cli/portability.mjs +4 -4
  68. package/cli/production-auth.mjs +4 -2
  69. package/cli/production-mail.mjs +1 -1
  70. package/cli/project.mjs +2 -0
  71. package/cli/rehearse/options.mjs +3 -3
  72. package/cli/release-candidate.mjs +2 -2
  73. package/cli/release.mjs +5 -5
  74. package/cli/server-registry.mjs +3 -3
  75. package/cli/server-resources.mjs +1 -1
  76. package/cli/setup-input.mjs +6 -6
  77. package/cli/signin.mjs +11 -10
  78. package/cli/site-render.mjs +1 -1
  79. package/cli/size/schema.mjs +1 -1
  80. package/cli/size/verify-step.mjs +1 -1
  81. package/cli/transfers.mjs +4 -4
  82. package/edition-authoring/api-source.mjs +121 -0
  83. package/edition-authoring/archive-source.mjs +1 -86
  84. package/edition-authoring/base-copies.mjs +5 -3
  85. package/global/CHANGELOG.md +47 -0
  86. package/global/browser-runtime.mjs +9 -5
  87. package/global/cli/command.mjs +6 -5
  88. package/global/cli/install.mjs +6 -3
  89. package/global/cli/path-link.mjs +11 -22
  90. package/global/cli/repo-command.mjs +4 -3
  91. package/global/cli/repository-contract.mjs +3 -3
  92. package/global/door/command.mjs +39 -38
  93. package/global/door/control.mjs +3 -3
  94. package/global/door/pages.mjs +6 -5
  95. package/global/door/server.mjs +8 -5
  96. package/global/door/sites.mjs +14 -13
  97. package/global/launch/capacity.mjs +2 -2
  98. package/global/launch/dev.mjs +6 -6
  99. package/global/launch/door.mjs +1 -1
  100. package/global/launch/facts.mjs +2 -2
  101. package/global/launch/failure.mjs +1 -1
  102. package/global/launch/prepare.mjs +3 -3
  103. package/global/launch/render.mjs +3 -2
  104. package/global/launch/worker.mjs +1 -1
  105. package/global/list.mjs +4 -4
  106. package/global/main.mjs +32 -31
  107. package/global/registry.mjs +1 -1
  108. package/global/run.mjs +5 -5
  109. package/global/update/command.mjs +5 -5
  110. package/global/update/notice.mjs +1 -1
  111. package/global/version.mjs +1 -1
  112. package/install.sh +17 -4
  113. package/modules/deploy-kit/README.md +11 -3
  114. package/modules/deploy-kit/asset-health.mjs +6 -4
  115. package/modules/deploy-kit/cancellation.mjs +26 -0
  116. package/modules/deploy-kit/d1-import-diagnostics.mjs +3 -2
  117. package/modules/deploy-kit/deploy.mjs +8 -3
  118. package/modules/deploy-kit/diagnostics.mjs +11 -4
  119. package/modules/deploy-kit/health-request.mjs +16 -9
  120. package/modules/deploy-kit/health.mjs +14 -11
  121. package/modules/deploy-kit/owner-cli.mjs +55 -25
  122. package/modules/deploy-kit/owner-remove.mjs +7 -6
  123. package/modules/deploy-kit/owner-secret-copy.mjs +2 -1
  124. package/modules/deploy-kit/owner-secret.mjs +8 -5
  125. package/modules/deploy-kit/owner.mjs +49 -30
  126. package/modules/deploy-kit/provider-transport.mjs +2 -0
  127. package/modules/deploy-kit/provider.mjs +10 -9
  128. package/modules/deploy-kit/readiness-window.mjs +5 -3
  129. package/modules/deploy-kit/site.mjs +1 -1
  130. package/modules/deploy-kit/teardown.mjs +5 -4
  131. package/modules/deploy-kit/validation.mjs +1 -0
  132. package/modules/deploy-kit/worker.mjs +1 -0
  133. package/modules/operator-auth/dev/index.mjs +4 -3
  134. package/modules/operator-auth/dev/sign-in-as.mjs +2 -1
  135. package/modules/operator-auth/dev-gate.mjs +3 -2
  136. package/modules/operator-auth/routes.mjs +2 -1
  137. package/modules/operator-auth/terminal-guidance.mjs +3 -0
  138. package/onboarding/adapter-settings.mjs +1 -0
  139. package/onboarding/adapter.mjs +3 -3
  140. package/onboarding/agent-handoff.mjs +1 -1
  141. package/onboarding/busy.mjs +1 -1
  142. package/onboarding/launcher.mjs +1 -1
  143. package/onboarding/local/environment.mjs +1 -1
  144. package/onboarding/local/operation.mjs +12 -4
  145. package/onboarding/local/owner.mjs +2 -2
  146. package/onboarding/operator-installer.mjs +4 -3
  147. package/onboarding/operator-migrations.mjs +1 -1
  148. package/onboarding/operator-prerequisites.mjs +26 -14
  149. package/onboarding/operator-settings.mjs +28 -0
  150. package/onboarding/process-diagnostics.mjs +2 -2
  151. package/onboarding/project-vite.mjs +1 -1
  152. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { pause, combinedSignal } from './cancellation.mjs';
1
2
  import { servedAsset } from './asset-health.mjs';
2
3
  import { readinessAPI } from './readiness-window.mjs';
3
4
  import { verifyServiceGrants } from './service-grants.mjs';
@@ -23,15 +24,17 @@ export async function waitForDeploymentHealth(url, {
23
24
  headers,
24
25
  fetchImpl = globalThis.fetch,
25
26
  now = Date.now,
26
- sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
27
+ sleep, signal,
27
28
  } = {}) {
28
29
  const deadline = now() + timeoutMs;
29
30
  let lastResult = 'no response';
30
31
  while (now() < deadline) {
32
+ signal?.throwIfAborted();
31
33
  let response;
32
34
  try {
33
- response = await fetchImpl(url, { redirect: 'manual', signal: AbortSignal.timeout(Math.max(1, Math.min(attemptTimeoutMs, deadline - now()))), ...(headers ? { headers } : {}) });
35
+ response = await fetchImpl(url, { redirect: 'manual', signal: combinedSignal(signal,AbortSignal.timeout(Math.max(1, Math.min(attemptTimeoutMs, deadline - now())))), ...(headers ? { headers } : {}) });
34
36
  } catch {
37
+ signal?.throwIfAborted();
35
38
  lastResult = 'network error';
36
39
  }
37
40
  if (response) {
@@ -43,7 +46,7 @@ export async function waitForDeploymentHealth(url, {
43
46
  }
44
47
  }
45
48
  const remaining = deadline - now();
46
- if (remaining > 0) await sleep(Math.min(intervalMs, remaining));
49
+ if (remaining > 0) await pause(Math.min(intervalMs, remaining),signal,sleep);
47
50
  }
48
51
  throw healthError(`Deployment did not become healthy at ${url} within ${timeoutMs}ms; last result: ${lastResult}.`, lastResult === 'network error' ? 'health-transport-failed' : 'health-http-failed', lastResult);
49
52
  }
@@ -52,7 +55,7 @@ export async function waitForDeploymentHealth(url, {
52
55
  * Without `readiness`, /health gets the single bounded window of waitForDeploymentHealth.
53
56
  * With `readiness` (deploy after an upload) it gets the recorded 90-second wait of health-request.mjs.
54
57
  * `asset`, a built file's path, must answer 200 after at most one transient replay. */
55
- export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fetch,timeoutMs=30000,intervalMs=2000,now,sleep,readiness,asset}) {
58
+ export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fetch,timeoutMs=30000,intervalMs=2000,now,sleep,readiness,asset,signal}) {
56
59
  if (readiness?.window) api = readinessAPI(api, readiness.window);
57
60
  assert(receipt?.version === 1 && receipt.accountId === api.accountId && receipt.worker === plan.worker,'receipt-target-mismatch');
58
61
  await verifyServiceGrants(api, plan);
@@ -79,28 +82,28 @@ export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fe
79
82
  let health;
80
83
  // A Worker without a public route (reached only through service bindings) has no /health to request.
81
84
  if (plan.workersDev === false) health = {ok:true,versionId:current.versionId,route:'none'};
82
- else if (readiness) health = await waitHealth({origin,receipt,versionId:current.versionId,request,timeoutMs,...readiness});
85
+ else if (readiness) health = await waitHealth({origin,receipt,versionId:current.versionId,request,timeoutMs,signal,...readiness});
83
86
  else {
84
87
  // A secret change makes a new version of the same build; until it reaches
85
88
  // every edge, a healthy answer can still name the previous version. Ask again
86
89
  // within the window; any other wrong identity fails at once.
87
- const clock = now ?? Date.now, wait = sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))), start = clock();
90
+ const clock = now ?? Date.now, start = clock();
88
91
  let body;
89
92
  for (;;) {
90
93
  let response;
91
94
  try {
92
- response = await waitForDeploymentHealth(`${origin}/health`,{timeoutMs,intervalMs,attemptTimeoutMs:timeoutMs,headers:{'Cache-Control':'no-cache','Accept':'application/json'},fetchImpl:request,...(now ? {now} : {}),...(sleep ? {sleep} : {})});
93
- } catch (error) { throw new Error(error.code ?? 'health-transport-failed'); }
95
+ response = await waitForDeploymentHealth(`${origin}/health`,{timeoutMs,intervalMs,attemptTimeoutMs:timeoutMs,headers:{'Cache-Control':'no-cache','Accept':'application/json'},fetchImpl:request,signal,...(now ? {now} : {}),...(sleep ? {sleep} : {})});
96
+ } catch (error) { signal?.throwIfAborted(); throw new Error(error.code ?? 'health-transport-failed'); }
94
97
  assert(response.ok && response.status === 200 && !response.redirected,'health-http-failed');
95
- body = await boundedJSON(response,65536);
98
+ body = await boundedJSON(response,65536,signal);
96
99
  const other = body?.ok === true && typeof body.deployment?.versionId === 'string' && body.deployment.versionId !== current.versionId;
97
100
  if (!other || clock() - start + intervalMs > timeoutMs) break;
98
- await wait(intervalMs);
101
+ await pause(intervalMs,signal,sleep);
99
102
  }
100
103
  assert(body?.ok === true && body.deployment?.sourceSha === receipt.source.sha && body.deployment?.fingerprint === receipt.fingerprint && body.deployment?.versionId === current.versionId,'health-identity-mismatch');
101
104
  health = {ok:true,versionId:current.versionId};
102
105
  }
103
- if (asset && origin) health.asset = await servedAsset(origin,asset,request,timeoutMs,readiness ? {window:readiness.window,windowMs:60000,...(readiness.clock ? {clock:readiness.clock} : {}),...(readiness.sleep ? {sleep:readiness.sleep} : {})} : {});
106
+ if (asset && origin) health.asset = await servedAsset(origin,asset,request,timeoutMs,readiness ? {signal,window:readiness.window,windowMs:60000,...(readiness.clock ? {clock:readiness.clock} : {}),...(readiness.sleep ? {sleep:readiness.sleep} : {})} : {signal});
104
107
  const after = await activeWorker(api,plan.worker);
105
108
  assert(after.versionId === current.versionId && after.deploymentId === current.deploymentId && after.etag === current.etag,'deployment-changed-during-health');
106
109
  await verifyServiceGrants(api, plan);
@@ -1,6 +1,8 @@
1
1
  import { readinessWindow, rememberReadiness } from './readiness-window.mjs';
2
2
  import { deploymentDiagnostics, deployDiagnostic } from './diagnostics.mjs';
3
- import { execFileSync } from 'node:child_process';
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+ import { combinedSignal } from './cancellation.mjs';
4
6
  import { resolve, join } from 'node:path';
5
7
  import { pathToFileURL } from 'node:url';
6
8
  import { parseArgs } from 'node:util';
@@ -9,7 +11,7 @@ import { assert, hexId } from './validation.mjs';
9
11
  import { regularBytes } from './artifact.mjs';
10
12
  import { packageBuild } from './prepare.mjs';
11
13
  import { cloudflare } from './provider.mjs';
12
- import { ownerTarget, recordedOwnerTarget, ownerWorkerName, ownerPlan, ownerDeploy, ownerHealth, settleOwnerState, sameDeployment, localOnlyBinding, withStateLock, readOwnerState, writeOwnerState, workerSettings, withScopeHints } from './owner.mjs';
14
+ import { ownerTarget, ownerStateTarget, recordedOwnerTarget, ownerWorkerName, ownerPlan, ownerDeploy, ownerHealth, settleOwnerState, sameDeployment, localOnlyBinding, withStateLock, readOwnerState, writeOwnerState, workerSettings, withScopeHints } from './owner.mjs';
13
15
  import { activeWorker, secretBindings } from './worker.mjs';
14
16
  import { ownerSecret } from './owner-secret.mjs';
15
17
  import { ownerRemove } from './owner-remove.mjs';
@@ -18,6 +20,7 @@ import { ownerRekey } from './owner-rekey.mjs';
18
20
  import { refuseLocalModels } from './local-only.mjs';
19
21
  import { validateMigrations } from './migrations.mjs';
20
22
  import { publicOrigin } from './public-origin.mjs';
23
+ import { switchableDefaults } from '../../cli/deploy-settings.mjs';
21
24
 
22
25
  export const cronNotice = 'This Worker has a Cron Trigger. Cloudflare may take up to about two hours to start its first scheduled run on some accounts.';
23
26
  const usage = 'usage: owner-cli.mjs deploy|dry-run|local-plan|health|remove|inspect|record-owner|signin|rekey|settle --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME [--set NAME]|--unset NAME [--unset NAME]';
@@ -25,18 +28,41 @@ const usage = 'usage: owner-cli.mjs deploy|dry-run|local-plan|health|remove|insp
25
28
  // The public offline command also contains legacy hooks that call kit dry-run.
26
29
  // Keep their plan local without changing direct kit callers or real deploys.
27
30
  const localPlans = new AsyncLocalStorage();
31
+ const ownerSignals = new AsyncLocalStorage();
32
+ export const withOwnerDeploySignal = (signal, run) => ownerSignals.run(signal, run);
33
+ const execute = promisify(execFile);
28
34
  export const withLocalDeployPlan = run => localPlans.run(true, run);
29
35
 
30
36
  /** The owner's committed source and existing local build. Run the seed's build first. */
31
- async function ownerArtifact(root, product) {
32
- const git = (...args) => { try { return execFileSync('git',args,{cwd:root,encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim(); } catch { throw new Error('owner-source-not-a-git-checkout'); } };
33
- const source = {sha:git('rev-parse','HEAD'),tree:git('rev-parse','HEAD^{tree}')};
34
- assert(!git('status','--porcelain','--untracked-files=no'),'owner-source-not-committed');
37
+ async function ownerArtifact(root, product, signal) {
38
+ const git = async (...args) => {
39
+ signal?.throwIfAborted();
40
+ const grouped = process.platform !== 'win32';
41
+ const pending = execute('git',args,{cwd:root,encoding:'utf8',stdio:['ignore','pipe','pipe'],detached:grouped});
42
+ // Git may invoke a configured helper. End this invocation's entire process
43
+ // group, and await execFile's close callback before returning cancellation.
44
+ const abort = () => {
45
+ if (!pending.child.pid) return;
46
+ try { process.kill(grouped ? -pending.child.pid : pending.child.pid,'SIGKILL'); }
47
+ catch (error) { if (error.code !== 'ESRCH') pending.child.kill('SIGKILL'); }
48
+ };
49
+ signal?.addEventListener('abort',abort,{once:true});
50
+ if (signal?.aborted) abort();
51
+ try { const result = await pending; signal?.throwIfAborted(); return result.stdout.trim(); }
52
+ catch { signal?.throwIfAborted(); throw new Error('owner-source-not-a-git-checkout'); }
53
+ finally { signal?.removeEventListener('abort',abort); }
54
+ };
55
+ const source = {sha:await git('rev-parse','HEAD'),tree:await git('rev-parse','HEAD^{tree}')};
56
+ assert(!await git('status','--porcelain','--untracked-files=no'),'owner-source-not-committed');
57
+ signal?.throwIfAborted();
35
58
  return packageBuild({root,source,runIdentity:{id:'0',attempt:'1'},productDirectory:product});
36
59
  }
37
60
 
38
61
  /** Inputs: CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN, plus the secrets the declaration names on first deploy. */
39
- export async function main(argv = process.argv.slice(2), env = process.env, {fetch = globalThis.fetch, cwd = process.cwd(), healthOptions, propagation, settle, localOnlyKeys = [], notice = line => console.error(line), onCreated} = {}) {
62
+ export async function main(argv = process.argv.slice(2), env = process.env, {fetch = globalThis.fetch, cwd = process.cwd(), healthOptions, propagation, settle, signal = ownerSignals.getStore(), localOnlyKeys = [], notice = line => console.error(line), onCreated} = {}) {
63
+ signal?.throwIfAborted();
64
+ healthOptions = {...healthOptions,signal,...(healthOptions?.readiness ? {readiness:{...healthOptions.readiness,signal}} : {})};
65
+ settle = {...settle,signal};
40
66
  let parsed;
41
67
  try { parsed = parseArgs({args:argv,allowPositionals:true,strict:true,options:{declaration:{type:'string'},environment:{type:'string'},product:{type:'string',default:''},state:{type:'string'},set:{type:'string',multiple:true},unset:{type:'string',multiple:true},outcome:{type:'string'}}}); }
42
68
  catch { throw new Error('usage'); }
@@ -59,11 +85,12 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
59
85
  assert(typeof declaration?.project === 'string','missing-owner-project');
60
86
  // Validate even direct kit invocations before any provider request or write.
61
87
  publicOrigin(declaration, env);
88
+ const publicDefaults = await switchableDefaults(declaration);
62
89
  let artifact;
63
90
  if (command === 'dry-run' || command === 'local-plan') {
64
91
  artifact = await packageBuild({root,source:{sha:'0'.repeat(40),tree:'0'.repeat(40)},runIdentity:{id:'0',attempt:'1'},productDirectory:values.product});
65
92
  const worker = ownerWorkerName(declaration.project,values.environment);
66
- const plan = ownerPlan({project:declaration.project,environment:values.environment,worker,origin:`https://${worker}.example.invalid`},declaration,artifact,{localOnlyKeys,env});
93
+ const plan = ownerPlan({project:declaration.project,environment:values.environment,worker,origin:`https://${worker}.example.invalid`},declaration,artifact,{localOnlyKeys,env,publicDefaults});
67
94
  if (command === 'local-plan') for (const item of plan.d1) validateMigrations(item.migrations);
68
95
  // Print names only: configuration values and migration SQL stay local.
69
96
  // Return before constructing a provider client or resolving an account.
@@ -80,40 +107,43 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
80
107
  let requestWindow = propagation?.uploaded ? propagation.window : undefined;
81
108
  const request = fetch;
82
109
  const guardedRequest = (input, init = {}) => {
110
+ signal?.throwIfAborted();
83
111
  init.signal?.throwIfAborted();
84
112
  // The window clock can expire before its shared abort timer fires.
85
113
  assert(!requestWindow?.active || requestWindow.remaining() > 0, 'deployment-readiness-timeout');
86
114
  return request(input, init);
87
115
  };
88
116
  const requestSignal = () => {
89
- if (!requestWindow?.active) return undefined;
117
+ signal?.throwIfAborted();
118
+ if (!requestWindow?.active) return signal;
90
119
  const remaining = requestWindow.remaining();
91
120
  assert(remaining > 0, 'deployment-readiness-timeout');
92
- return requestWindow.timeout(Math.max(1, Math.ceil(remaining)));
121
+ return combinedSignal(signal, requestWindow.timeout(Math.max(1, Math.ceil(remaining))));
93
122
  };
94
123
  fetch = (input, init = {}) => {
95
- const deadline = requestSignal();
96
- return request(input, {...init,...(deadline ? {signal:init.signal ? AbortSignal.any([init.signal,deadline]) : deadline} : {})});
124
+ const requestAbort = combinedSignal(init.signal, requestSignal());
125
+ requestAbort?.throwIfAborted();
126
+ return request(input, {...init,signal:requestAbort});
97
127
  };
98
128
  // Transport must see the same outer signal when deciding whether to retry.
99
129
  const api = deploymentDiagnostics(cloudflare({accountId:env.CLOUDFLARE_ACCOUNT_ID,token:env.CLOUDFLARE_API_TOKEN,fetch:guardedRequest,requestSignal,budgetMigrations:command === 'deploy',...(command === 'remove' ? {maxRequests:Infinity,removal:true} : {})}),{onCreated});
100
130
  const statePath = values.state ? resolve(root,values.state) : join(root,'.rer','deploy',`${values.environment}.json`);
101
- // Signin uses only the selected app record; never discover a sibling page Worker.
102
- // Removal needs the recorded account/name identity, not a workers.dev route.
131
+ // Every follow-up uses the app record's resolved name, including native
132
+ // uploaders' prefixes. Removal needs no routable origin or completed receipt.
103
133
  const target = command === 'signin'
104
134
  ? await recordedOwnerTarget(api,{project:declaration.project,environment:values.environment,statePath})
105
135
  : command === 'remove'
106
- ? {accountId:api.accountId,project:declaration.project,environment:values.environment,worker:ownerWorkerName(declaration.project,values.environment)}
107
- : await ownerTarget(api,{project:declaration.project,environment:values.environment});
108
- if (command === 'remove') return {ok:true,...await ownerRemove({api,target,statePath}).catch(error => { throw api.annotateFailure(error,'remove'); })};
136
+ ? await ownerStateTarget(api,{project:declaration.project,environment:values.environment,statePath})
137
+ : await ownerTarget(api,{project:declaration.project,environment:values.environment,statePath});
138
+ if (command === 'remove') return {ok:true,...await ownerRemove({api,target,statePath,signal}).catch(error => { throw api.annotateFailure(error,'remove'); })};
109
139
  if (command === 'rekey') return ownerRekey({api,target,statePath,declaration,env,notice});
110
140
  if (command === 'secret') {
111
141
  // Every named secret is changed in one Worker version, or none is.
112
142
  const named = [...new Set(values.set ?? values.unset)], declared = Array.isArray(declaration.secrets) ? declaration.secrets : [];
113
143
  const undeclared = named.filter(binding => !declared.some(entry => entry?.binding === binding));
114
144
  if (undeclared.length) { const error = new Error('undeclared-secret'); error.resource = undeclared.map(binding => `secret:${binding}`).join(', '); throw error; }
115
- const changes = named.map(binding => ({binding, value:values.set === undefined ? undefined : env[declared.find(entry => entry?.binding === binding).environment]}));
116
- return {ok:true,...await ownerSecret({api,target,statePath,changes,fetch,healthOptions,settle}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
145
+ const changes = named.map(binding => ({binding, value:values.set === undefined ? undefined : env[declared.find(entry => entry?.binding === binding).environment], ...(values.unset !== undefined && Object.hasOwn(publicDefaults,binding) ? {publicDefault:publicDefaults[binding]} : {})}));
146
+ return {ok:true,...await ownerSecret({api,target,statePath,changes,fetch,healthOptions,settle,signal}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
117
147
  }
118
148
  // A secret rer retired (the spent setup token) is no longer part of the plan.
119
149
  // A dry run only reads state: settling an interrupted change may write it.
@@ -144,8 +174,8 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
144
174
  return {ok:true, origin:state.receipt.origin ?? target.origin, versionId:live.versionId, retiredSecrets, ownerClaim:state.ownerClaim, liveSecrets:rows.map(row => row.name)};
145
175
  }
146
176
  const current = retiredSecrets.length && Array.isArray(declaration.secrets) ? {...declaration,secrets:declaration.secrets.filter(item => !retiredSecrets.includes(item?.binding))} : declaration;
147
- artifact ??= await ownerArtifact(root,values.product);
148
- const plan = ownerPlan(target,current,artifact,{localOnlyKeys,env});
177
+ artifact ??= await ownerArtifact(root,values.product,signal);
178
+ const plan = ownerPlan(target,current,artifact,{localOnlyKeys,env,publicDefaults});
149
179
  if (command === 'dry-run') {
150
180
  const checked = withScopeHints(api);
151
181
  const exists = await workerSettings(checked,target.worker) !== null;
@@ -154,7 +184,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
154
184
  }
155
185
  if (command === 'health') {
156
186
  const readiness = {...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}),
157
- ...healthOptions?.readiness,single:true,totalMs:30000,
187
+ ...healthOptions?.readiness,signal,single:true,totalMs:30000,
158
188
  ...(propagation ? {window:propagation.window,freshUpload:propagation.uploaded && propagation.versionId === state.receipt?.provider.versionId} : {})};
159
189
  await ownerHealth({api,target,plan,statePath,fetch,healthOptions:{...healthOptions,readiness}}).catch(error=>{throw api.annotateFailure(error,'health');});
160
190
  return {ok:true,worker:target.worker,origin:target.origin};
@@ -162,10 +192,10 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
162
192
  // Dispatch is the provider's: on some accounts a new Cron starts only at the account scheduler's next refresh.
163
193
  if (plan.crons.length) notice(cronNotice);
164
194
  // The fingerprint names every declared secret, retired ones too: an untouched repeat after the claim is a no-op.
165
- const declaredSecrets = current === declaration ? plan.secrets : ownerPlan(target,declaration,artifact,{localOnlyKeys,env}).secrets;
166
- const window = readinessWindow({...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}), ...healthOptions?.readiness});
195
+ const declaredSecrets = current === declaration ? plan.secrets : ownerPlan(target,declaration,artifact,{localOnlyKeys,env,publicDefaults}).secrets;
196
+ const window = readinessWindow({...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}), ...healthOptions?.readiness,signal});
167
197
  requestWindow = window;
168
- const {receipt,created,sentSecrets,unsetSecrets,freshUpload} = await ownerDeploy({api,target,plan,artifact,statePath,env,fetch,healthOptions,readiness:{...healthOptions?.readiness,window},settle,declaredSecrets}).catch(error => {
198
+ const {receipt,created,sentSecrets,unsetSecrets,freshUpload} = await ownerDeploy({api,target,plan,artifact,statePath,env,fetch,healthOptions,readiness:{...healthOptions?.readiness,window,signal},settle,declaredSecrets}).catch(error => {
169
199
  api.annotateFailure(error,error.message.startsWith('missing-secret-') ? 'secrets' : undefined);
170
200
  throw error;
171
201
  });
@@ -1,3 +1,4 @@
1
+ import { pause } from './cancellation.mjs';
1
2
  import { r2ObjectPages, r2ObjectPath } from './r2-objects.mjs';
2
3
  import { rm } from 'node:fs/promises';
3
4
  import { assert, hexId } from './validation.mjs';
@@ -38,8 +39,8 @@ async function confirmEmpty(api, worker, kind, name, id) {
38
39
  * everything before the first delete; a replaced or uncertain resource refuses it all,
39
40
  * except an uncertain one confirmed empty (see confirmEmpty). R2 object purges
40
41
  * additionally require the saved creation timestamp and recheck it before each delete. */
41
- export async function ownerRemove({api: provider, target, statePath, clock, sleep}) {
42
- const api = withSettledLists(withScopeHints(provider));
42
+ export async function ownerRemove({api: provider, target, statePath, clock, sleep, signal}) {
43
+ const api = withSettledLists(withScopeHints(provider),{signal});
43
44
  return withStateLock(statePath, async () => {
44
45
  const state = await readOwnerState(statePath, target);
45
46
  const remaining = new Set([...(state.owned.worker ? [`worker:${target.worker}`] : []), ...KINDS.flatMap(kind => Object.keys(state.owned[kind]).map(name => `${kind}:${name}`))]);
@@ -80,13 +81,13 @@ export async function ownerRemove({api: provider, target, statePath, clock, slee
80
81
  await api.request(`/queues/${queue.id}/consumers/${consumer.consumer_id}`, {method:'DELETE'});
81
82
  }
82
83
  }
83
- if (worker) { await deleteWorker({api, worker, ...(clock ? {clock} : {}), ...(sleep ? {sleep} : {})}); removed.push(`worker:${worker}`); }
84
+ if (worker) { await deleteWorker({api, worker, signal, ...(clock ? {clock} : {}), ...(sleep ? {sleep} : {})}); removed.push(`worker:${worker}`); }
84
85
  for (const item of doomed) {
85
86
  try {
86
87
  if (item.kind === 'r2') await removeBucket(api, item);
87
88
  else {
88
89
  await remove[item.kind](api, item.id, item.name);
89
- if (item.kind === 'queues') await waitForQueueRemoval(api,item,{clock,sleep});
90
+ if (item.kind === 'queues') await waitForQueueRemoval(api,item,{clock,sleep,signal});
90
91
  }
91
92
  removed.push(`${item.kind}:${item.name}`);
92
93
  }
@@ -165,7 +166,7 @@ async function removeBucket(api, {name, entry}) {
165
166
 
166
167
  // Queue deletion and its account listing can settle separately. Finish the
167
168
  // readback within this removal invocation, without replaying the DELETE.
168
- async function waitForQueueRemoval(api, item, {clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve,ms))}) {
169
+ async function waitForQueueRemoval(api, item, {clock = () => performance.now(), sleep, signal}) {
169
170
  const start = clock();
170
171
  for (;;) {
171
172
  if (!(await resourceKinds.queues.list(api)).some(row => row.queue_id === item.id)) return;
@@ -174,6 +175,6 @@ async function waitForQueueRemoval(api, item, {clock = () => performance.now(),
174
175
  error.providerCall = {operation:'GET /queues',reason:'Cloudflare still lists the deleted queue after 60 seconds'};
175
176
  throw error;
176
177
  }
177
- await sleep(500);
178
+ await pause(500,signal,sleep);
178
179
  }
179
180
  }
@@ -17,7 +17,8 @@ export async function uploadSecretCopy(api, worker, live, {changes, marker}) {
17
17
  const named = new Set(changes.map(change => change.binding));
18
18
  const metadata = {main_module:entry, compatibility_date:runtime.compatibility_date, compatibility_flags:runtime.compatibility_flags ?? [],
19
19
  bindings:[...bindings.filter(row => !named.has(row.name)).map(row => ({type:'inherit',name:row.name})),
20
- ...changes.filter(change => change.value !== undefined).map(change => ({type:'secret_text',name:change.binding,text:change.value}))],
20
+ ...changes.flatMap(change => change.value !== undefined ? [{type:'secret_text',name:change.binding,text:change.value}]
21
+ : change.publicDefault !== undefined ? [{type:'plain_text',name:change.binding,text:change.publicDefault}] : [])],
21
22
  keep_assets:true, annotations:{'workers/message':copyMessage(marker)}};
22
23
  const data = new FormData();
23
24
  data.set('metadata', new Blob([JSON.stringify(metadata)], {type:'application/json'}));
@@ -1,3 +1,4 @@
1
+ import { pause } from './cancellation.mjs';
1
2
  import { randomBytes } from 'node:crypto';
2
3
  import { assert, identifier } from './validation.mjs';
3
4
  import { activeWorker } from './worker.mjs';
@@ -20,8 +21,8 @@ import { uploadSecretCopy, deploySecretCopy } from './owner-secret-copy.mjs';
20
21
  * deployment is still live. An ambiguous one-secret rotation
21
22
  * re-PUTs the value before accepting its successor as proof of the rotation.
22
23
  * A removed declared secret is retired: later plans omit it until it is set again. */
23
- export async function ownerSecret({api: provider, target, statePath, changes, fetch = globalThis.fetch, healthOptions = {}, settle = {}, windowMs = 30000, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))}) {
24
- const api = withSettledLists(withScopeHints(provider),settle);
24
+ export async function ownerSecret({api: provider, target, statePath, changes, fetch = globalThis.fetch, healthOptions = {}, settle = {}, windowMs = 30000, clock = () => performance.now(), sleep, signal}) {
25
+ const api = withSettledLists(withScopeHints(provider),{...settle,signal});
25
26
  const bindings = changes.map(change => change.binding), present = changes[0]?.value !== undefined;
26
27
  assert(bindings.length && bindings.every(identifier) && validSecretNames(bindings), 'invalid-secret-name');
27
28
  assert(changes.every(change => (change.value !== undefined) === present), 'mixed-secret-change');
@@ -41,7 +42,7 @@ export async function ownerSecret({api: provider, target, statePath, changes, fe
41
42
  assert(names, 'invalid-secret-list');
42
43
  // Removing secrets the Worker does not hold changes nothing; the rest of a removal still runs.
43
44
  const writes = present ? changes : changes.filter(change => names.includes(change.binding));
44
- const existed = writes.some(change => names.includes(change.binding)), changed = writes.length > 0, copy = writes.length > 1;
45
+ const existed = writes.some(change => names.includes(change.binding)), changed = writes.length > 0, copy = writes.length > 1 || writes.some(change => change.publicDefault !== undefined);
45
46
  state.pendingSecret = {bindings, present, versionId:state.receipt.provider.versionId, names:names.filter(name => !bindings.includes(name)).sort(), ...(copy ? {copy:randomBytes(16).toString('hex')} : {})};
46
47
  await writeOwnerState(statePath, state);
47
48
  let failure, unchanged = false, confirming = false, uploaded = false;
@@ -59,11 +60,12 @@ export async function ownerSecret({api: provider, target, statePath, changes, fe
59
60
  // pending: the same command deploys it next time, as this change and no other.
60
61
  if (definiteProviderRefusal(error) && !uploaded) { delete state.pendingSecret; await writeOwnerState(statePath, state); throw error; }
61
62
  if (definiteProviderRefusal(error)) { await writeOwnerState(statePath, state); throw error; }
63
+ signal?.throwIfAborted();
62
64
  failure = error;
63
65
  }
64
66
  try {
65
67
  if (!changed) recordSecretChange(state, live, state.pendingSecret);
66
- else for (const start = clock(); ; await sleep(2000)) {
68
+ else for (const start = clock(); ; await pause(2000,signal,sleep)) {
67
69
  try {
68
70
  if (await settlePendingSecret(api, target.worker, state, {
69
71
  observe: current => { unchanged = sameDeployment(current, state.receipt.provider); },
@@ -79,6 +81,7 @@ export async function ownerSecret({api: provider, target, statePath, changes, fe
79
81
  })) break;
80
82
  }
81
83
  catch (error) {
84
+ signal?.throwIfAborted();
82
85
  unchanged = false;
83
86
  // Another ambiguous PUT cannot prove a rotation by presence either.
84
87
  // Keep both starting versions for recovery; do not report it done.
@@ -101,7 +104,7 @@ export async function ownerSecret({api: provider, target, statePath, changes, fe
101
104
  if (state.receipt.origin) await waitHealth({
102
105
  origin:state.receipt.origin, receipt:state.receipt, versionId:result.versionId, request:fetch,
103
106
  timeoutMs:healthOptions.timeoutMs,
104
- clock:healthOptions.now, sleep:healthOptions.sleep, ...healthOptions.readiness,
107
+ clock:healthOptions.now, sleep:healthOptions.sleep, signal, ...healthOptions.readiness,
105
108
  });
106
109
  const after = await activeWorker(api, target.worker);
107
110
  assert(after && sameDeployment(after, state.receipt.provider), 'deployment-changed-during-health');
@@ -1,7 +1,9 @@
1
+ import { pause } from './cancellation.mjs';
2
+ import { shared } from '../../cli/shared.mjs';
1
3
  import { readinessWindow } from './readiness-window.mjs';
2
4
  import { uploadedWorker } from './uploaded-worker.mjs';
3
5
  import { ingressBindings } from './container-config.mjs';
4
- import { mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
6
+ import { mkdir, rename, writeFile } from 'node:fs/promises';
5
7
  import { dirname } from 'node:path';
6
8
  import { assert, hash, identifier, resourceName, uuid, validatePlan } from './validation.mjs';
7
9
  import { definiteProviderRefusal } from './provider.mjs';
@@ -71,15 +73,16 @@ export const LIST_WINDOW_MS = 120000;
71
73
  const settleable = error => ['provider-partial-list','provider-pagination-changed'].includes(error.message);
72
74
  /** Owner mode replays a list read, and a GET of a path the provider reads as a list (a Worker's
73
75
  * deployments or versions), until a complete snapshot arrives or the window closes. */
74
- export function withSettledLists(api, {windowMs = LIST_WINDOW_MS, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
76
+ export function withSettledLists(api, {windowMs = LIST_WINDOW_MS, clock = () => performance.now(), sleep, signal} = {}) {
75
77
  if (api.settledLists) return api;
76
78
  const settled = read => async (...args) => {
77
79
  const start = clock();
78
80
  for (let delay = 500; ; delay = Math.min(delay * 2, 4000)) {
81
+ signal?.throwIfAborted();
79
82
  try { return await read(...args); }
80
83
  catch (error) {
81
84
  if (!settleable(error) || clock() - start + delay > windowMs) throw error;
82
- await sleep(delay);
85
+ await pause(delay,signal,sleep);
83
86
  }
84
87
  }
85
88
  };
@@ -90,13 +93,14 @@ export function withSettledLists(api, {windowMs = LIST_WINDOW_MS, clock = () =>
90
93
  }
91
94
  /** Waits until the account's listing shows a resource this run just created, so no later
92
95
  * read mistakes it for a missing or replaced one. One that never appears is named. */
93
- async function listedAfterCreate(api, kind, item, {windowMs = LIST_WINDOW_MS, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
96
+ async function listedAfterCreate(api, kind, item, {windowMs = LIST_WINDOW_MS, clock = () => performance.now(), sleep, signal} = {}) {
94
97
  const start = clock();
95
98
  for (let delay = 500; ; delay = Math.min(delay * 2, 4000)) {
99
+ signal?.throwIfAborted();
96
100
  try { if (findResource(await resourceKinds[kind].list(api.unsettled ?? api),kind,item.name)) return; }
97
101
  catch (error) { if (!settleable(error)) throw error; }
98
102
  if (clock() - start + delay > windowMs) throw refuse('resource-not-listed',kind,item.name);
99
- await sleep(delay);
103
+ await pause(delay,signal,sleep);
100
104
  }
101
105
  }
102
106
  /** Reads the account's workers.dev subdomain; no other provider request. */
@@ -109,21 +113,36 @@ async function workerOrigin(provider, worker) {
109
113
  assert(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(result.subdomain),'invalid-account-subdomain');
110
114
  return `https://${worker}.${result.subdomain}.workers.dev`;
111
115
  }
112
- export async function ownerTarget(api, {project, environment}) {
113
- const worker = ownerWorkerName(project, environment);
114
- return {accountId:api.accountId,project,environment,worker,origin:await workerOrigin(api,worker)};
116
+ export async function ownerTarget(api, {project, environment, statePath}) {
117
+ const target = await ownerStateTarget(api,{project,environment,statePath});
118
+ return {...target,origin:target.origin ?? await workerOrigin(api,target.worker)};
115
119
  }
116
120
 
117
- /** Signin follows the selected app record, including native uploaders' custom names.
118
- * The caller still supplies the account, project and environment to validate it.
119
- * Later state reads and the live provider check must corroborate this identity. */
120
- export async function recordedOwnerTarget(api, {project, environment, statePath}) {
121
- ownerWorkerName(project, environment); // Validate the caller's project and environment as usual.
121
+ /** Native uploaders record their resolved Worker name. Follow it only within the
122
+ * caller's account, project and environment. An absent record keeps the original
123
+ * derived name; partial records remain usable for recovery and removal. */
124
+ export async function ownerStateTarget(api, {project, environment, statePath}) {
125
+ const worker = ownerWorkerName(project, environment);
126
+ const target = {accountId:api.accountId,project,environment,worker};
127
+ if (statePath === undefined) return target;
122
128
  let recorded;
123
129
  try { recorded = JSON.parse(await regularBytes(statePath, 4 * 1024 * 1024)); }
124
- catch (error) { throw new Error(error.code === 'ENOENT' ? 'missing-owner-receipt' : 'invalid-owner-state'); }
130
+ catch (error) { if (error.code === 'ENOENT') return target; throw new Error('invalid-owner-state'); }
125
131
  assert(resourceName(recorded?.worker), 'invalid-owner-state');
126
- const target = {accountId:api.accountId,project,environment,worker:recorded.worker};
132
+ const selected = {...target,worker:recorded.worker};
133
+ let state;
134
+ try { state = await readOwnerState(statePath,selected); }
135
+ catch (error) {
136
+ if (error.message === 'owner-state-target-mismatch') error.ownerTargetMismatch.requestedWorker = worker;
137
+ throw error;
138
+ }
139
+ return {...selected,...(state.receipt?.origin ? {origin:state.receipt.origin} : {})};
140
+ }
141
+
142
+ /** Signin requires a completed record and never discovers a sibling Worker. */
143
+ export async function recordedOwnerTarget(api, options) {
144
+ const target = await ownerStateTarget(api,options);
145
+ const {statePath} = options;
127
146
  const state = await readOwnerState(statePath,target);
128
147
  assert(state.receipt, 'missing-owner-receipt');
129
148
  return {...target,origin:state.receipt.origin ?? await workerOrigin(api,target.worker)};
@@ -144,7 +163,7 @@ export function localOnlyBinding(declaration, localOnlyKeys = []) {
144
163
  return names.find(name => refused.has(name)) ?? null;
145
164
  }
146
165
  /** A seed declares bindings, never names. Migrations come from the packaged artifact. */
147
- export function ownerPlan(target, declaration, artifact, { localOnlyKeys = [], env = {} } = {}) {
166
+ export function ownerPlan(target, declaration, artifact, { localOnlyKeys = [], env = {}, publicDefaults = {} } = {}) {
148
167
  assert(declaration?.version === 1 && typeof declaration === 'object' && Object.keys(declaration).every(key => DECLARATION_KEYS.includes(key)), 'invalid-owner-declaration');
149
168
  assert(declaration.publicSettings === undefined || Array.isArray(declaration.publicSettings) && new Set(declaration.publicSettings).size === declaration.publicSettings.length && declaration.publicSettings.every(name => typeof name === 'string' && /^[A-Z][A-Z0-9_]*$/.test(name)), 'invalid-public-settings');
150
169
  ownerPlatforms(declaration);
@@ -165,6 +184,7 @@ export function ownerPlan(target, declaration, artifact, { localOnlyKeys = [], e
165
184
  const queues = entries(declaration,'queues');
166
185
  for (const item of queues) assert(item.deadLetterQueue === undefined || queues.some(other => other.binding === item.deadLetterQueue), 'invalid-dead-letter-queue');
167
186
  const vars = {...(declaration.vars ?? {})};
187
+ for (const name of Object.keys(publicDefaults)) if (declaration.secrets?.some(item => item.binding === name)) delete vars[name];
168
188
  const origin = publicOrigin(declaration, env);
169
189
  if (declaration.originVar !== undefined) {
170
190
  assert(identifier(declaration.originVar) && !Object.hasOwn(vars,declaration.originVar), 'invalid-owner-origin-variable');
@@ -183,7 +203,7 @@ export function ownerPlan(target, declaration, artifact, { localOnlyKeys = [], e
183
203
  durableObjects:entries(declaration,'durableObjects').map(item => ({...item})),
184
204
  // verifyStandIn is only `rer verify`'s hosted-check value: never planned, sent or stored.
185
205
  // An optional secret (`"optional": true`, an integration's credential) may stay unset: it is bound only once supplied.
186
- secrets:entries(declaration,'secrets').map(({verifyStandIn,...item}) => { assert(verifyStandIn === undefined || typeof verifyStandIn === 'string' && verifyStandIn.length > 0 && verifyStandIn.length <= 1024, 'invalid-verify-stand-in'); return item; }),
206
+ secrets:entries(declaration,'secrets').map(({verifyStandIn,...item}) => { assert(verifyStandIn === undefined || typeof verifyStandIn === 'string' && verifyStandIn.length > 0 && verifyStandIn.length <= 1024, 'invalid-verify-stand-in'); return Object.hasOwn(publicDefaults,item.binding) ? {...item,publicDefault:publicDefaults[item.binding]} : item; }),
187
207
  crons:[...(declaration.crons ?? [])],vars,
188
208
  // Only declarations using these add the keys, so earlier plans and fingerprints are unchanged.
189
209
  ...(services.length ? {services} : {}),...(declaration.workersDev === false ? {workersDev:false} : {})});
@@ -217,7 +237,11 @@ export async function readOwnerState(path, target) {
217
237
  && (pending.names === undefined || validSecretNames(pending.names) && !pending.names.some(name => pending.bindings.includes(name))), 'invalid-owner-state');
218
238
  assert(state.ownerClaim === undefined || ['claimed','kept'].includes(state.ownerClaim?.outcome), 'invalid-owner-state');
219
239
  assert(state.retiredSecrets === undefined || Array.isArray(state.retiredSecrets) && state.retiredSecrets.every(identifier), 'invalid-owner-state');
220
- assert(state.accountId === target.accountId && state.project === target.project && state.environment === target.environment && state.worker === target.worker, 'owner-state-target-mismatch');
240
+ if (state.accountId !== target.accountId || state.project !== target.project || state.environment !== target.environment || state.worker !== target.worker) {
241
+ const error = new Error('owner-state-target-mismatch');
242
+ error.ownerTargetMismatch = {recordedWorker:state.worker,requestedWorker:target.worker};
243
+ throw error;
244
+ }
221
245
  return state;
222
246
  }
223
247
  export async function writeOwnerState(path, state) {
@@ -372,18 +396,13 @@ async function checkOwnedWorker(api, plan, state, save) {
372
396
  return checkWorkerIdentity(api, plan, state, save);
373
397
  }
374
398
 
375
- /** One deploy at a time per state file: an exclusive lock file for the whole run. */
399
+ /** One deploy per state file. A killed writer's lock is reclaimed only after
400
+ * its PID/start identity is dead, using the local operation's exclusive takeover. */
376
401
  export async function withStateLock(path, run) {
377
402
  await mkdir(dirname(path),{recursive:true,mode:0o700});
378
- const lock = `${path}.lock`;
379
- let handle;
380
- try { handle = await open(lock,'wx',0o600); }
381
- catch (error) { throw error.code === 'EEXIST' ? new Error('owner-state-locked') : error; }
382
- try {
383
- await handle.writeFile(`${process.pid}\n`);
384
- await handle.close();
385
- return await run();
386
- } finally { try { await handle.close(); } finally { await rm(lock,{force:true}); } }
403
+ const { fileOperation } = await shared('local/operation.mjs');
404
+ const lock = await fileOperation(`${path}.lock`, undefined, () => new Error('owner-state-locked'));
405
+ try { return await run(); } finally { await lock.release(); }
387
406
  }
388
407
 
389
408
  /** Find or create every declared resource under the owner's account, migrate, upload and check health.
@@ -445,7 +464,7 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
445
464
  }
446
465
  return result;
447
466
  }};
448
- const receipt = await deploy({api:observed, plan, artifact, artifactSha256:hash(artifact), previousReceipt:state.receipt ?? undefined,
467
+ const receipt = await deploy({api:observed, plan, artifact, artifactSha256:hash(artifact), previousReceipt:state.receipt ?? undefined, pendingUpload:state.pendingUpload,
449
468
  // Migrations run inside this run's state lock: no other deploy of this install is running.
450
469
  createResources:false, uploadWithoutReceipt:true, locked:true, env, fetch, healthOptions, readiness, declaredSecrets,
451
470
  onReceipt: async candidate => { if (candidate.changed || !state.receipt) { state.receipt = candidate; delete state.pendingUpload; delete state.pendingSecret; await save(); } },
@@ -456,7 +475,7 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
456
475
 
457
476
  /** Independent read-only health of the last owner deployment recorded in the state file. */
458
477
  export async function ownerHealth({api: provider, target, plan, statePath, fetch = globalThis.fetch, healthOptions = {}}) {
459
- const api = withSettledLists(withScopeHints(provider));
478
+ const api = withSettledLists(withScopeHints(provider),{signal:healthOptions.signal});
460
479
  validatePlan(plan); assertOwnerNames(target, plan);
461
480
  const state = await readOwnerState(statePath, target);
462
481
  assert(state.receipt, 'missing-owner-receipt');
@@ -27,7 +27,9 @@ export async function providerResponse({send, method, timeoutMs, callerSignal, r
27
27
  const attemptSignal = firstRead ? AbortSignal.any([signal, firstRead.signal]) : signal;
28
28
  let readingBody = false, response;
29
29
  try {
30
+ attemptSignal.throwIfAborted();
30
31
  response = await send(attemptSignal);
32
+ attemptSignal.throwIfAborted();
31
33
  clearTimeout(timer);
32
34
  // A retried delete can observe the first attempt's committed deletion.
33
35
  if (removalReplay && method === 'DELETE' && attempt > 1 && response.status === 404) {