@runeditrun/rer 0.2.15 → 0.2.17
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.
- package/cli/demo-host.mjs +4 -4
- package/cli/deploy-claim-request.mjs +32 -0
- package/cli/deploy-command.mjs +22 -8
- package/cli/deploy-hook.mjs +11 -3
- package/cli/deploy-observation.mjs +7 -4
- package/cli/deploy-owner.mjs +5 -4
- package/cli/deploy.mjs +4 -4
- package/cli/door.mjs +4 -3
- package/cli/local.mjs +5 -3
- package/cli/pnpm-probe.mjs +19 -10
- package/cli/port.mjs +17 -10
- package/cli/project-pnpm.mjs +4 -2
- package/cli/site-diagnostics.mjs +35 -0
- package/cli/site-render.mjs +4 -1
- package/cli/site.mjs +5 -0
- package/global/CHANGELOG.md +21 -0
- package/modules/container/boundary.mjs +70 -34
- package/modules/container/build.mjs +20 -3
- package/modules/container/import-graph.mjs +233 -0
- package/modules/demo-host/README.md +8 -1
- package/modules/demo-host/container.mjs +25 -6
- package/modules/demo-host/plan.mjs +12 -7
- package/modules/deploy-kit/deploy.mjs +8 -3
- package/modules/deploy-kit/health-request.mjs +14 -11
- package/modules/deploy-kit/health.mjs +16 -6
- package/modules/deploy-kit/owner-cli.mjs +24 -4
- package/modules/deploy-kit/owner.mjs +6 -3
- package/modules/deploy-kit/provider.mjs +6 -2
- package/modules/deploy-kit/readiness-window.mjs +32 -0
- package/modules/deploy-kit/uploaded-worker.mjs +22 -0
- package/modules/deploy-kit/worker.mjs +1 -1
- package/onboarding/adapter.mjs +13 -4
- package/onboarding/process-diagnostics.mjs +142 -36
- package/package.json +1 -1
|
@@ -6,17 +6,17 @@ import { assert } from './validation.mjs';
|
|
|
6
6
|
const decodePrefix = bytes => new StringDecoder('utf8').write(bytes.subarray(0,256));
|
|
7
7
|
|
|
8
8
|
async function bodyPrefix(response) {
|
|
9
|
-
if (!response.body) return '';
|
|
10
|
-
const reader = response.body.getReader(); let bytes = Buffer.alloc(0);
|
|
9
|
+
if (!response.body) return {body:'',complete:true};
|
|
10
|
+
const reader = response.body.getReader(); let bytes = Buffer.alloc(0), complete = false;
|
|
11
11
|
try {
|
|
12
12
|
while (bytes.length < 256) {
|
|
13
13
|
const {done,value} = await reader.read();
|
|
14
|
-
if (done) break;
|
|
14
|
+
if (done) { complete = true; break; }
|
|
15
15
|
bytes = Buffer.concat([bytes,value.subarray(0,256-bytes.length)]);
|
|
16
16
|
}
|
|
17
17
|
} catch { /* HTTP status remains authoritative if its diagnostic body breaks. */ }
|
|
18
18
|
finally { await reader.cancel().catch(() => {}); }
|
|
19
|
-
return decodePrefix(bytes);
|
|
19
|
+
return {body:decodePrefix(bytes),complete};
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
/** One credential-free, bounded request. Retain only bounded response evidence. */
|
|
@@ -34,9 +34,10 @@ export async function healthRequest({origin, expected, request, timeoutMs, offse
|
|
|
34
34
|
attempt.cfRay = response.headers.get('cf-ray')?.slice(0,256) ?? null;
|
|
35
35
|
attempt.contentType = response.headers.get('content-type')?.slice(0,256) ?? null;
|
|
36
36
|
if (response.status !== 200 || response.redirected) {
|
|
37
|
-
|
|
37
|
+
const prefix = await bodyPrefix(response);
|
|
38
|
+
attempt.body = prefix.body;
|
|
38
39
|
attempt.errorClass = 'health-http-failed';
|
|
39
|
-
return {attempt,transient:!response.redirected && (response.status === 404 || response.status >= 500 && response.status <= 599)};
|
|
40
|
+
return {attempt,routePropagation:!response.redirected && response.status === 404 && prefix.complete && prefix.body.trim() === 'error code: 1042',transient:!response.redirected && (response.status === 404 || response.status >= 500 && response.status <= 599)};
|
|
40
41
|
}
|
|
41
42
|
let bytes = Buffer.alloc(0);
|
|
42
43
|
try {
|
|
@@ -76,18 +77,20 @@ const MIN_DELAY_MS = 2000, MAX_DELAY_MS = 10000;
|
|
|
76
77
|
|
|
77
78
|
/** The total bound includes requests, body reads and backoff; no request starts at the deadline.
|
|
78
79
|
* Only a transient outcome is retried. Every attempt is recorded, in order, whatever the end. */
|
|
79
|
-
export async function waitHealth({origin,receipt,versionId,expected={sourceSha:receipt.source.sha,fingerprint:receipt.fingerprint,versionId},request,timeoutMs=30000,totalMs=90000,clock=()=>performance.now(),sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)),onAttempt=()=>{},single=false}) {
|
|
80
|
+
export async function waitHealth({origin,receipt,versionId,expected={sourceSha:receipt.source.sha,fingerprint:receipt.fingerprint,versionId},request,timeoutMs=30000,totalMs=90000,clock=()=>performance.now(),sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)),onAttempt=()=>{},single=false,freshUpload=false,window}) {
|
|
80
81
|
assert(Number.isFinite(totalMs) && totalMs > 0 && totalMs <= 90000 && Number.isFinite(timeoutMs) && timeoutMs > 0,'invalid-health-bound');
|
|
81
82
|
const start = clock(); const attempts = []; let delay = 1000;
|
|
82
83
|
while (true) {
|
|
83
|
-
const remaining = totalMs - (clock()-start);
|
|
84
|
+
const remaining = Math.min(totalMs - (clock()-start), window?.remaining() ?? Infinity);
|
|
84
85
|
if (remaining <= 0) break;
|
|
85
86
|
const result = await healthRequest({origin,expected,request,timeoutMs:Math.max(1,Math.ceil(Math.min(timeoutMs,remaining))),offsetMs:Math.round(clock()-start)});
|
|
86
87
|
attempts.push(result.attempt); await onAttempt(result.attempt,attempts);
|
|
87
88
|
if (!result.attempt.errorClass) return {ok:true,versionId,attempts};
|
|
88
|
-
//
|
|
89
|
-
|
|
90
|
-
const
|
|
89
|
+
// A newly uploaded workers.dev route can briefly disappear even after its
|
|
90
|
+
// first healthy answer. Only the observed edge 1042 response gets this exception.
|
|
91
|
+
const routePropagation = freshUpload && new URL(origin).protocol === 'https:' && new URL(origin).hostname.endsWith('.workers.dev') && result.routePropagation;
|
|
92
|
+
if (!result.transient || single && result.attempt.errorClass !== 'health-identity-mismatch' && !routePropagation) break;
|
|
93
|
+
const rest = Math.min(totalMs - (clock()-start), window?.remaining() ?? Infinity);
|
|
91
94
|
if (rest <= 0) break;
|
|
92
95
|
await sleep(Math.min(Math.max(delay,MIN_DELAY_MS),rest)); delay = Math.min(delay*2,MAX_DELAY_MS);
|
|
93
96
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readinessAPI } from './readiness-window.mjs';
|
|
1
2
|
import { verifyServiceGrants } from './service-grants.mjs';
|
|
2
3
|
import { assert, stable } from './validation.mjs';
|
|
3
4
|
import { boundedJSON } from './provider.mjs';
|
|
@@ -49,11 +50,13 @@ export async function waitForDeploymentHealth(url, {
|
|
|
49
50
|
/** An unauthenticated GET of a built file; anything but 200 means the browser gets no assets.
|
|
50
51
|
* After an upload (`windowMs`), an edge still serving the previous version answers 404 for
|
|
51
52
|
* the new build's hashed files: 404, 5xx and transport failures are retried within the window. */
|
|
52
|
-
async function servedAsset(origin, path, request, timeoutMs, {windowMs = 0, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
|
|
53
|
+
async function servedAsset(origin, path, request, timeoutMs, {window, windowMs = 0, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
|
|
53
54
|
const start = clock();
|
|
54
55
|
for (;;) {
|
|
55
56
|
let response, failure;
|
|
56
|
-
|
|
57
|
+
const remaining = window?.remaining() ?? timeoutMs;
|
|
58
|
+
assert(remaining > 0, 'asset-readiness-timeout');
|
|
59
|
+
try { response = await request(`${origin}/${path.split('/').map(encodeURIComponent).join('/')}`,{redirect:'manual',signal:AbortSignal.timeout(Math.max(1, Math.ceil(Math.min(timeoutMs,remaining)))),headers:{'Cache-Control':'no-cache'}}); }
|
|
57
60
|
catch { failure = 'asset-transport-failed'; }
|
|
58
61
|
if (response) {
|
|
59
62
|
await response.body?.cancel().catch(() => {});
|
|
@@ -62,7 +65,7 @@ async function servedAsset(origin, path, request, timeoutMs, {windowMs = 0, cloc
|
|
|
62
65
|
if (response.redirected || response.status !== 404 && response.status < 500) throw new Error(failure);
|
|
63
66
|
}
|
|
64
67
|
if (clock() - start + 2000 > windowMs) throw new Error(failure);
|
|
65
|
-
await sleep(2000);
|
|
68
|
+
await sleep(Math.min(2000,window?.remaining() ?? 2000));
|
|
66
69
|
}
|
|
67
70
|
}
|
|
68
71
|
|
|
@@ -71,6 +74,7 @@ async function servedAsset(origin, path, request, timeoutMs, {windowMs = 0, cloc
|
|
|
71
74
|
* With `readiness` (deploy after an upload) it gets the recorded 90-second wait of health-request.mjs.
|
|
72
75
|
* `asset`, a built file's path, is then requested once and must answer 200. */
|
|
73
76
|
export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fetch,timeoutMs=30000,intervalMs=2000,now,sleep,readiness,asset}) {
|
|
77
|
+
if (readiness?.window) api = readinessAPI(api, readiness.window);
|
|
74
78
|
assert(receipt?.version === 1 && receipt.accountId === api.accountId && receipt.worker === plan.worker,'receipt-target-mismatch');
|
|
75
79
|
await verifyServiceGrants(api, plan);
|
|
76
80
|
const current = await activeWorker(api,plan.worker);
|
|
@@ -85,8 +89,14 @@ export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fe
|
|
|
85
89
|
const namespaces = await durableNamespaces(api,plan,{requireAll:true});
|
|
86
90
|
assert(stable(namespaces) === stable(receipt.durableObjects),'durable-object-identity-drift');
|
|
87
91
|
for (const item of plan.d1) await migrate(api,resources.d1.find(x => x.binding === item.binding).id,item.migrations,{apply:false});
|
|
88
|
-
|
|
89
|
-
|
|
92
|
+
for (;;) {
|
|
93
|
+
assert(!readiness?.window || readiness.window.remaining() > 0, 'missing-deployed-secret');
|
|
94
|
+
const secrets = await api.request(`/workers/scripts/${plan.worker}/secrets`);
|
|
95
|
+
assert(Array.isArray(secrets) && secrets.every(row => typeof row?.name === 'string' && row.type === 'secret_text'), 'invalid-secret-list');
|
|
96
|
+
if (plan.secrets.every(x => secrets.some(y => y.name === x.binding && y.type === 'secret_text'))) break;
|
|
97
|
+
assert(readiness?.freshUpload && readiness.window?.remaining() > 0, 'missing-deployed-secret');
|
|
98
|
+
await readiness.window.pause();
|
|
99
|
+
}
|
|
90
100
|
let health;
|
|
91
101
|
// A Worker without a public route (reached only through service bindings) has no /health to request.
|
|
92
102
|
if (plan.workersDev === false) health = {ok:true,versionId:current.versionId,route:'none'};
|
|
@@ -111,7 +121,7 @@ export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fe
|
|
|
111
121
|
assert(body?.ok === true && body.deployment?.sourceSha === receipt.source.sha && body.deployment?.fingerprint === receipt.fingerprint && body.deployment?.versionId === current.versionId,'health-identity-mismatch');
|
|
112
122
|
health = {ok:true,versionId:current.versionId};
|
|
113
123
|
}
|
|
114
|
-
if (asset && origin) health.asset = await servedAsset(origin,asset,request,timeoutMs,readiness ? {windowMs:60000,...(readiness.clock ? {clock:readiness.clock} : {}),...(readiness.sleep ? {sleep:readiness.sleep} : {})} : {});
|
|
124
|
+
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} : {})} : {});
|
|
115
125
|
const after = await activeWorker(api,plan.worker);
|
|
116
126
|
assert(after.versionId === current.versionId && after.deploymentId === current.deploymentId && after.etag === current.etag,'deployment-changed-during-health');
|
|
117
127
|
await verifyServiceGrants(api, plan);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readinessWindow, rememberReadiness } from './readiness-window.mjs';
|
|
1
2
|
import { deploymentDiagnostics, deployDiagnostic } from './diagnostics.mjs';
|
|
2
3
|
import { execFileSync } from 'node:child_process';
|
|
3
4
|
import { resolve, join } from 'node:path';
|
|
@@ -25,7 +26,7 @@ async function ownerArtifact(root, product) {
|
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
/** Inputs: CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN, plus the secrets the declaration names on first deploy. */
|
|
28
|
-
export async function main(argv = process.argv.slice(2), env = process.env, {fetch = globalThis.fetch, cwd = process.cwd(), healthOptions, settle, localOnlyKeys = [], notice = line => console.error(line), onCreated} = {}) {
|
|
29
|
+
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} = {}) {
|
|
29
30
|
let parsed;
|
|
30
31
|
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'},unset:{type:'string'},outcome:{type:'string'}}}); }
|
|
31
32
|
catch { throw new Error('usage'); }
|
|
@@ -44,6 +45,15 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
|
|
|
44
45
|
assert(typeof declaration?.project === 'string','missing-owner-project');
|
|
45
46
|
// Removal reads identity before each object DELETE and may span many pages.
|
|
46
47
|
// Bound each response, not the owner's bucket size; failures retain ownership.
|
|
48
|
+
let requestWindow = propagation?.freshUpload ? propagation.window : undefined;
|
|
49
|
+
const request = fetch;
|
|
50
|
+
fetch = (input, init = {}) => {
|
|
51
|
+
if (!requestWindow?.active) return request(input, init);
|
|
52
|
+
const remaining = requestWindow.remaining();
|
|
53
|
+
assert(remaining > 0, 'deployment-readiness-timeout');
|
|
54
|
+
const deadline = AbortSignal.timeout(Math.max(1, Math.ceil(remaining)));
|
|
55
|
+
return request(input, {...init,signal:init.signal ? AbortSignal.any([init.signal,deadline]) : deadline});
|
|
56
|
+
};
|
|
47
57
|
const api = deploymentDiagnostics(cloudflare({accountId:env.CLOUDFLARE_ACCOUNT_ID,token:env.CLOUDFLARE_API_TOKEN,fetch,...(command === 'remove' ? {maxRequests:Infinity} : {})}),{onCreated});
|
|
48
58
|
const target = await ownerTarget(api,{project:declaration.project,environment:values.environment});
|
|
49
59
|
const statePath = values.state ? resolve(root,values.state) : join(root,'.rer','deploy',`${target.environment}.json`);
|
|
@@ -79,18 +89,28 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
|
|
|
79
89
|
const artifact = await ownerArtifact(root,values.product);
|
|
80
90
|
const plan = ownerPlan(target,current,artifact,{localOnlyKeys});
|
|
81
91
|
if (command === 'health') {
|
|
82
|
-
|
|
92
|
+
const readiness = {...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}),
|
|
93
|
+
...healthOptions?.readiness,single:true,totalMs:30000,
|
|
94
|
+
...(propagation ? {window:propagation.window,freshUpload:propagation.freshUpload && propagation.versionId === state.receipt?.provider.versionId} : {})};
|
|
95
|
+
await ownerHealth({api,target,plan,statePath,fetch,healthOptions:{...healthOptions,readiness}}).catch(error=>{throw api.annotateFailure(error,'health');});
|
|
83
96
|
return {ok:true,worker:target.worker,origin:target.origin};
|
|
84
97
|
}
|
|
85
98
|
// Dispatch is the provider's: on some accounts a new Cron starts only at the account scheduler's next refresh.
|
|
86
99
|
if (plan.crons.length) notice(cronNotice);
|
|
87
100
|
// The fingerprint names every declared secret, retired ones too: an untouched repeat after the claim is a no-op.
|
|
88
101
|
const declaredSecrets = current === declaration ? plan.secrets : ownerPlan(target,declaration,artifact,{localOnlyKeys}).secrets;
|
|
89
|
-
const
|
|
102
|
+
const window = readinessWindow({...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}), ...healthOptions?.readiness});
|
|
103
|
+
requestWindow = window;
|
|
104
|
+
const {receipt,created,sentSecrets,freshUpload} = await ownerDeploy({api,target,plan,artifact,statePath,env,fetch,healthOptions,readiness:{...healthOptions?.readiness,window},settle,declaredSecrets}).catch(error => {
|
|
90
105
|
api.annotateFailure(error,error.message.startsWith('missing-secret-') ? 'secrets' : undefined);
|
|
91
106
|
throw error;
|
|
92
107
|
});
|
|
93
|
-
|
|
108
|
+
const result = {ok:true,changed:receipt.changed,worker:target.worker,origin:receipt.origin,versionId:receipt.provider.versionId,created,sentSecrets,retiredSecrets,...(state.ownerClaim ? {ownerClaim:state.ownerClaim} : {}),state:statePath};
|
|
109
|
+
const sentTokens = new Map(sentSecrets.map(binding => [binding,env[declaration.secrets.find(item => item.binding === binding)?.environment]]));
|
|
110
|
+
Object.defineProperty(result, 'propagation', {value: {window,freshUpload,sentSecrets,versionId:receipt.provider.versionId,
|
|
111
|
+
matchesToken:(binding,token) => sentTokens.has(binding) && sentTokens.get(binding) === token}});
|
|
112
|
+
rememberReadiness(result);
|
|
113
|
+
return result;
|
|
94
114
|
}
|
|
95
115
|
|
|
96
116
|
/** Prints refusal codes and resource names only; never inputs, tokens or provider bodies. */
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readinessWindow } from './readiness-window.mjs';
|
|
2
|
+
import { uploadedWorker } from './uploaded-worker.mjs';
|
|
1
3
|
import { ingressBindings } from './container-config.mjs';
|
|
2
4
|
import { mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
5
|
import { dirname } from 'node:path';
|
|
@@ -373,6 +375,8 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
|
|
|
373
375
|
await listedAfterCreate(api,kind,item,settle);
|
|
374
376
|
}
|
|
375
377
|
if (!exists && !state.owned.worker) { state.owned.worker = {status:'pending'}; await save(); }
|
|
378
|
+
const window = readiness.window ?? readinessWindow({...(healthOptions.now ? {clock:healthOptions.now} : {}), ...(healthOptions.sleep ? {sleep:healthOptions.sleep} : {}), ...readiness});
|
|
379
|
+
readiness = {...readiness,window};
|
|
376
380
|
const upload = `/workers/scripts/${plan.worker}?bindings_inherit=strict`;
|
|
377
381
|
const observed = {...api, async request(path, options) {
|
|
378
382
|
const sending = path === upload && options?.method === 'PUT';
|
|
@@ -387,8 +391,7 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
|
|
|
387
391
|
// A successful upload creates a Worker only when ownership preflight found
|
|
388
392
|
// it absent. Record it before readback, which can fail after creation.
|
|
389
393
|
if (!exists) api.recordCreated?.(`Worker:${plan.worker}`);
|
|
390
|
-
const active = await
|
|
391
|
-
assert(active && deployedFingerprint(active.settings) === state.pendingUpload.fingerprint, 'uploaded-worker-drift');
|
|
394
|
+
const active = await uploadedWorker({api,worker:plan.worker,upload:result,previous:priorWorker,fingerprint:state.pendingUpload.fingerprint,window});
|
|
392
395
|
state.pendingUpload.provider = {versionId:active.versionId,deploymentId:active.deploymentId,etag:active.etag};
|
|
393
396
|
state.owned.worker = {status:'created'}; await save();
|
|
394
397
|
}
|
|
@@ -399,7 +402,7 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
|
|
|
399
402
|
onReceipt: async candidate => { if (candidate.changed || !state.receipt) { state.receipt = candidate; delete state.pendingUpload; delete state.pendingSecret; await save(); } },
|
|
400
403
|
// Keep each first-health attempt beside the identity it belongs to.
|
|
401
404
|
onHealth: async candidate => { if (candidate.changed) { state.receipt = candidate; await save(); } }});
|
|
402
|
-
return {receipt, created:create.map(({kind,item}) => `${kind}:${item.name}`), sentSecrets};
|
|
405
|
+
return {receipt, created:create.map(({kind,item}) => `${kind}:${item.name}`), sentSecrets, freshUpload:!exists && receipt.changed};
|
|
403
406
|
}
|
|
404
407
|
|
|
405
408
|
/** Independent read-only health of the last owner deployment recorded in the state file. */
|
|
@@ -37,7 +37,7 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
|
|
|
37
37
|
assert(typeof token === 'string' && token.trim() && !/[\r\n]/.test(token), 'invalid-cloudflare-api-token');
|
|
38
38
|
let requests = 0;
|
|
39
39
|
// `zone` scope: the zone-level API (/zones/...), for a run site's zone lookup and redirect rule.
|
|
40
|
-
async function envelope(path, { method = 'GET', body, assetToken, zone = false } = {}) {
|
|
40
|
+
async function envelope(path, { method = 'GET', body, assetToken, zone = false, signal: callerSignal } = {}) {
|
|
41
41
|
assert(typeof path === 'string' && (isR2ObjectDelete(path, method) || /^\/[a-z0-9/_?=&.,%-]+$/i.test(path) && !path.includes('..') && !path.split('?')[0].includes('%')), 'invalid-provider-path');
|
|
42
42
|
assert(!zone || /^\/zones(?:[/?]|$)/.test(path), 'invalid-provider-path');
|
|
43
43
|
assert(++requests <= maxRequests, 'provider-request-budget');
|
|
@@ -46,13 +46,17 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
|
|
|
46
46
|
// Preserve complete text for the CLI's remaining redaction before truncation.
|
|
47
47
|
const redactAuth = text => /\/r2\/buckets\/[^/]+\/objects(?:[/?]|$)/.test(path) ? '[R2 object details omitted]' : /\/d1\/database\/[^/]+\/import$/.test(path) ? '[D1 import details omitted]' : [accountId,token,assetToken].filter(Boolean).flatMap(value=>[value,encodeURIComponent(value),JSON.stringify(value).slice(1,-1)]).sort((a,b)=>b.length-a.length).reduce((value,secret)=>value.split(secret).join('[REDACTED]'),text);
|
|
48
48
|
const transportFailure = cause => recordDeployFailure(new Error('provider-transport-failed'),{output:redactAuth(transportOutput(cause))});
|
|
49
|
-
const
|
|
49
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
50
|
+
const signal = callerSignal ? AbortSignal.any([callerSignal,timeout]) : timeout;
|
|
50
51
|
let response;
|
|
51
52
|
try { response = isR2ObjectDelete(path, method) ? await objectDelete(`/client/v4/accounts/${accountId}${path}`, {headers:{Authorization:`Bearer ${token}`},signal}) : await request(zone ? `https://api.cloudflare.com/client/v4${path}` : `https://api.cloudflare.com/client/v4/accounts/${accountId}${path}`, {
|
|
52
53
|
method, redirect: 'error', signal, headers: { Authorization: `Bearer ${assetToken ?? token}`, ...(body && !(body instanceof FormData) ? { 'Content-Type':'application/json' } : {}) },
|
|
53
54
|
...(body === undefined ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }),
|
|
54
55
|
}); } catch (cause) { throw transportFailure(cause); }
|
|
55
56
|
const output = response.body ? await boundedText(response,undefined,transportFailure) : '';
|
|
57
|
+
// A successful DELETE may have no response body (including HTTP 200).
|
|
58
|
+
// Nonempty replies and all other methods still require the API envelope.
|
|
59
|
+
if (method === 'DELETE' && response.ok && output === '') return { success: true, result: null };
|
|
56
60
|
let payload;
|
|
57
61
|
try { payload = JSON.parse(output); } catch { if (response.ok) throw new Error('malformed-response'); }
|
|
58
62
|
if (!response.ok || payload?.success === false) {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { assert } from './validation.mjs';
|
|
3
|
+
|
|
4
|
+
// A single, in-memory deadline travels with this upload. It is deliberately not
|
|
5
|
+
// persisted: an old receipt is not evidence of a fresh propagation window.
|
|
6
|
+
export function readinessWindow({ totalMs = 90000, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) } = {}) {
|
|
7
|
+
assert(Number.isFinite(totalMs) && totalMs > 0 && totalMs <= 90000, 'invalid-health-bound');
|
|
8
|
+
let start;
|
|
9
|
+
return {
|
|
10
|
+
clock, sleep,
|
|
11
|
+
get active() { return start !== undefined; },
|
|
12
|
+
start() { start ??= clock(); },
|
|
13
|
+
remaining() { return start === undefined ? totalMs : Math.max(0, totalMs - (clock() - start)); },
|
|
14
|
+
async pause() { const left = this.remaining(); if (left > 0) await sleep(Math.min(2000, left)); },
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Custom deploy hooks can claim before returning their result. Keep the proof
|
|
19
|
+
// inside their current observation scope, never in a process-global cache.
|
|
20
|
+
const observations = new AsyncLocalStorage();
|
|
21
|
+
export const observeReadiness = run => observations.getStore() ? run() : observations.run(new Map(), run);
|
|
22
|
+
export const rememberReadiness = deployed => observations.getStore()?.set(deployed.origin, deployed);
|
|
23
|
+
export const observedReadiness = origin => observations.getStore()?.get(origin);
|
|
24
|
+
|
|
25
|
+
export function readinessAPI(api, window, failure = 'deployment-readiness-timeout') {
|
|
26
|
+
return {...api, request(path, options = {}) {
|
|
27
|
+
const remaining = window.remaining();
|
|
28
|
+
assert(remaining > 0, failure);
|
|
29
|
+
const deadline = AbortSignal.timeout(Math.max(1, Math.ceil(remaining)));
|
|
30
|
+
return api.request(path, {...options, signal:options.signal ? AbortSignal.any([options.signal,deadline]) : deadline});
|
|
31
|
+
}};
|
|
32
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { readinessAPI } from './readiness-window.mjs';
|
|
2
|
+
import { activeWorker, deployedFingerprint } from './worker.mjs';
|
|
3
|
+
import { assert, uuid } from './validation.mjs';
|
|
4
|
+
|
|
5
|
+
// Poll only the missing fresh Worker or the exact pre-upload version. A new
|
|
6
|
+
// unrelated version is drift, even during propagation; provider errors fail.
|
|
7
|
+
export async function uploadedWorker({ api, worker, upload, previous, fingerprint, window }) {
|
|
8
|
+
const rawVersion = typeof upload?.deployment_id === 'string' ? upload.deployment_id.toLowerCase() : upload?.deployment_id;
|
|
9
|
+
// The legacy upload API also returns the UUID without separators (Wrangler
|
|
10
|
+
// normalizes this field before treating it as its uploaded version ID).
|
|
11
|
+
const versionId = typeof rawVersion === 'string' && /^[a-f0-9]{32}$/i.test(rawVersion) ? rawVersion.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5').toLowerCase() : rawVersion;
|
|
12
|
+
if (versionId !== undefined) assert(uuid(versionId), 'invalid-upload-version');
|
|
13
|
+
const bounded = readinessAPI(api, window, 'uploaded-worker-timeout');
|
|
14
|
+
while (window.remaining() > 0) {
|
|
15
|
+
const current = await activeWorker(bounded, worker);
|
|
16
|
+
if (current && (!versionId || current.versionId === versionId) && deployedFingerprint(current.settings) === fingerprint) return current;
|
|
17
|
+
const prior = previous && current?.versionId === previous.versionId && current.deploymentId === previous.deploymentId && current.etag === previous.etag;
|
|
18
|
+
assert(!current || prior || current.versionId === versionId, 'uploaded-worker-drift');
|
|
19
|
+
await window.pause();
|
|
20
|
+
}
|
|
21
|
+
throw new Error('uploaded-worker-timeout');
|
|
22
|
+
}
|
|
@@ -85,7 +85,7 @@ export async function uploadWorker(api, {plan,artifact,bindings,secrets,migratio
|
|
|
85
85
|
if (artifact.assets.length) { metadata.assets = {jwt:await uploadAssets(api,plan.worker,artifact.assets),config:{run_worker_first:RUN_WORKER_FIRST}}; }
|
|
86
86
|
data.set('metadata',new Blob([JSON.stringify(metadata)],{type:'application/json'}));
|
|
87
87
|
for (const file of artifact.modules) data.set(file.path,new Blob([Buffer.from(file.base64,'base64')],{type:moduleType(file.path)}),file.path);
|
|
88
|
-
|
|
88
|
+
return api.request(`/workers/scripts/${plan.worker}?bindings_inherit=strict`,{method:'PUT',body:data});
|
|
89
89
|
}
|
|
90
90
|
/** The workers.dev origin, enabling it when allowed. With `workersDev: false` the route is kept
|
|
91
91
|
* off (a Worker reached only through service bindings) and there is no origin. */
|
package/onboarding/adapter.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { credentialValues } from './redaction.mjs';
|
|
|
10
10
|
import { dependencyEnvironment } from './dependency-environment.mjs';
|
|
11
11
|
import { labels } from './adapter-labels.mjs';
|
|
12
12
|
import { chooseOrigin, prepareSettings, readSettings } from './adapter-settings.mjs';
|
|
13
|
-
import {listenerPorts} from './process-diagnostics.mjs';
|
|
13
|
+
import {listenerPorts,listenerOwnership} from './process-diagnostics.mjs';
|
|
14
14
|
import { appFetch } from './app-fetch.mjs';
|
|
15
15
|
import { owner, signIn } from './adapter-auth.mjs';
|
|
16
16
|
import { installerDevKey } from './dev-identity.mjs';
|
|
@@ -214,11 +214,15 @@ async function start(context, hooks) {
|
|
|
214
214
|
const url = new URL(health, context.origin).href;
|
|
215
215
|
const expectedPort=context.runtimePort??Number(new URL(context.origin).port||80);
|
|
216
216
|
const readinessLabel=`${labels.start} (expected internal port ${expectedPort})`;
|
|
217
|
+
const ownedPorts=async()=>{
|
|
218
|
+
try{return await listenerPorts(child.pid);}
|
|
219
|
+
catch(error){throw installationFailure('command_failed',{step:'start',diagnostic:error});}
|
|
220
|
+
};
|
|
217
221
|
try {
|
|
218
222
|
await store.waitForReady(readinessLabel, child, ready ? probeSignal => ready(url, probeSignal, context) : probeSignal => (hooks.health ?? defaultHealth)(url, probeSignal, context), { signal, timeoutMs: ['dev','preview'].includes(context.verb)?Math.min(timeoutMs??60000,120000):(timeoutMs??900000), ...(softAfterMs ? { softAfterMs } : {}), ...(intervalMs ? { intervalMs } : {}) });
|
|
219
223
|
} catch (error) {
|
|
220
224
|
if (signal?.aborted) throw error;
|
|
221
|
-
const ports=await
|
|
225
|
+
const ports=await ownedPorts();
|
|
222
226
|
if(ports.length){
|
|
223
227
|
const message=store.redact(`Application listened on port ${ports.join(', ')}; readiness failed for expected internal port ${expectedPort}. Check application health and the runtime target's port binding.`);
|
|
224
228
|
store.report(message);const prior=approvedFailure(error);error=commandFailure(`${prior?.message??readinessLabel}\n${message}`,prior??{});
|
|
@@ -228,8 +232,13 @@ async function start(context, hooks) {
|
|
|
228
232
|
// Another app can take the loopback port between the port check and the bind;
|
|
229
233
|
// its /health would pass. Claim and sign in only against the process this
|
|
230
234
|
// setup started.
|
|
231
|
-
|
|
232
|
-
|
|
235
|
+
let ownership;
|
|
236
|
+
try { ownership=await listenerOwnership(child.pid,expectedPort,context.runtimePort?'127.0.0.1':new URL(url).hostname); }
|
|
237
|
+
catch(error){throw installationFailure('command_failed',{step:'start',diagnostic:error});}
|
|
238
|
+
if (ownership.status !== 'owned') {
|
|
239
|
+
const message = (store.redact??(value=>value))(ownership.status==='other'
|
|
240
|
+
? `Another process answered on port ${expectedPort}; the application did not bind it. Listener PID ${ownership.pid}. Nothing was sent. Stop that process or choose another port, then run setup again.`
|
|
241
|
+
: `The application did not bind expected internal port ${expectedPort}; completed inspection found no listener on the health address. Nothing was sent. Check the application binding, then run setup again.`);
|
|
233
242
|
store.report?.(message);
|
|
234
243
|
throw installationFailure('command_failed', { step: 'start', diagnostic: commandFailure(message, {}) });
|
|
235
244
|
}
|
|
@@ -1,75 +1,175 @@
|
|
|
1
1
|
import {execFile} from 'node:child_process';
|
|
2
2
|
import {promisify} from 'node:util';
|
|
3
|
-
import {realpath,readFile,readdir,readlink} from 'node:fs/promises';
|
|
3
|
+
import {lstat,realpath,readFile,readdir,readlink} from 'node:fs/promises';
|
|
4
4
|
import {basename,join} from 'node:path';
|
|
5
|
+
import {homedir} from 'node:os';
|
|
6
|
+
import {isIP} from 'node:net';
|
|
7
|
+
import {commandFailure} from './failures.mjs';
|
|
5
8
|
const exec=promisify(execFile);
|
|
6
9
|
// macOS supplies lsof in /usr/sbin, which a command PATH may omit.
|
|
7
10
|
// Diagnose sockets with the system utility even when that PATH is constrained.
|
|
8
11
|
const lsof=process.platform==='darwin'?'/usr/sbin/lsof':'lsof';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
// One monotonic budget covers every command in an ownership decision.
|
|
13
|
+
export const inspectionContext=()=>({deadline:performance.now()+15000});
|
|
14
|
+
const run=async(command,args,context=inspectionContext(),{maxBuffer=1024*1024,noMatch=false}={})=>{
|
|
15
|
+
const invocation=[command,...args].join(' ').replaceAll(homedir(),'~');
|
|
16
|
+
let failure;
|
|
17
|
+
for(let attempt=0;attempt<2;attempt++){
|
|
18
|
+
const remaining=Math.floor(context.deadline-performance.now());
|
|
19
|
+
if(remaining<=0)break;
|
|
20
|
+
const timeout=attempt===0?Math.min(3000,remaining):remaining;
|
|
21
|
+
try{return (await exec(command,args,{timeout,maxBuffer})).stdout;}
|
|
22
|
+
catch(error){
|
|
23
|
+
// A quiet lsof exit 1 means no match, including a selected PID exiting
|
|
24
|
+
// while other selected PIDs still return records. Diagnostic output instead
|
|
25
|
+
// means inspection failed, even if lsof also returned partial records.
|
|
26
|
+
if((command===lsof||noMatch)&&error.code===1&&!error.killed&&!error.signal&&typeof error.stdout==='string'&&typeof error.stderr==='string'&&!error.stderr.trim())return error.stdout;
|
|
27
|
+
failure=error.killed ? `timed out after ${timeout} ms` : `failed (${error.code??error.signal??'unknown error'}${typeof error.stderr==='string'&&error.stderr.trim()?'; diagnostic output':''}; attempt bound ${timeout} ms)`;
|
|
28
|
+
}
|
|
15
29
|
}
|
|
30
|
+
throw commandFailure(`ownership-unchecked: Listener ownership could not be checked: ${invocation} ${failure??'total inspection deadline exhausted'} (at most 2 attempts; shared total bound 15000 ms). Launch refused; no ownership conclusion was made.`,{});
|
|
16
31
|
};
|
|
17
|
-
|
|
32
|
+
|
|
33
|
+
export async function processName(pid,context=inspectionContext()){
|
|
34
|
+
try{process.kill(pid,0);}catch(error){if(error.code==='ESRCH')return 'process';}
|
|
18
35
|
if(process.platform==='linux'){const name=await readFile(`/proc/${pid}/comm`,'utf8').catch(()=>'');if(name)return name.trim().replace(/[^a-zA-Z0-9._-]/g,'').slice(0,80)||'process';}
|
|
19
|
-
|
|
36
|
+
// A completed quiet ps exit 1 means the PID has exited. Its display label
|
|
37
|
+
// is optional; this does not prove listener ownership or process liveness.
|
|
38
|
+
const text=await run('/bin/ps',['-p',String(pid),'-o','comm='],context,{noMatch:true});
|
|
20
39
|
return basename(text.trim()).replace(/[^a-zA-Z0-9._-]/g,'').slice(0,80)||'process';
|
|
21
40
|
}
|
|
22
|
-
function records(text
|
|
23
|
-
|
|
41
|
+
function records(text,socketTypes=false){
|
|
42
|
+
let record,family;const rows=[];
|
|
43
|
+
for(const line of text.split('\n')){
|
|
44
|
+
if(line[0]==='p'){record={pid:Number(line.slice(1)),names:[],...(socketTypes?{sockets:[]}: {})};family=undefined;rows.push(record);}
|
|
45
|
+
else if(line[0]==='f')family=undefined;
|
|
46
|
+
else if(line[0]==='t')family=['IPv4','IPv6'].includes(line.slice(1))?line.slice(1):undefined;
|
|
47
|
+
else if(line[0]==='n'&&record){const name=line.slice(1);record.names.push(name);if(socketTypes)record.sockets.push({name,family});}
|
|
48
|
+
}
|
|
49
|
+
return rows;
|
|
50
|
+
}
|
|
51
|
+
export async function listeners(pids,context=inspectionContext(),port){
|
|
24
52
|
// -a is essential: otherwise lsof ORs the PID and network selections and
|
|
25
53
|
// still walks every process's sockets. Read only the owned tree on failure.
|
|
26
|
-
if(
|
|
54
|
+
if(!pids&&!port&&context.allListeners)return context.allListeners;
|
|
55
|
+
if(process.platform!=='linux'){
|
|
56
|
+
// lsof renders both IPv4 and IPv6 wildcards as '*'. Keep the type of
|
|
57
|
+
// each file descriptor: a process may hold sockets of both families.
|
|
58
|
+
// -b avoids unrelated mount stat/readlink calls that can block even a PID
|
|
59
|
+
// query on macOS. -w suppresses the expected warnings for skipped filesystem
|
|
60
|
+
// metadata; neither that metadata nor pathname selection is used here.
|
|
61
|
+
const rows=records(await run(lsof,['-nP','-b','-w',...(pids?['-a','-p',pids.join(',')]:[]),port?`-iTCP:${port}`:'-iTCP','-sTCP:LISTEN','-Fpftn'],context),true);
|
|
62
|
+
if(!pids&&!port)context.allListeners=rows;
|
|
63
|
+
return rows;
|
|
64
|
+
}
|
|
27
65
|
const sockets=new Map();
|
|
28
66
|
for(const file of ['tcp','tcp6'])for(const line of (await readFile('/proc/net/'+file,'utf8').catch(()=>'' )).trim().split('\n').slice(1)){
|
|
29
|
-
const parts=line.trim().split(/\s+/);if(parts[3]==='0A'
|
|
67
|
+
const parts=line.trim().split(/\s+/);if(parts[3]==='0A'&&(!port||parseInt(parts[1].split(':')[1],16)===port))sockets.set(parts[9],{name:linuxAddress(parts[1]),family:file==='tcp'?'IPv4':'IPv6'});
|
|
30
68
|
}
|
|
31
69
|
const found=[];
|
|
32
70
|
for(const pid of pids??await linuxPids()){
|
|
33
|
-
const
|
|
34
|
-
if(
|
|
35
|
-
}
|
|
71
|
+
const held=[];for(const target of await descriptors(pid)){const inode=/^socket:\[(\d+)\]$/.exec(target)?.[1];if(sockets.has(inode))held.push(sockets.get(inode));}
|
|
72
|
+
if(held.length)found.push({pid,names:held.map(socket=>socket.name),sockets:held});
|
|
73
|
+
}
|
|
74
|
+
if(!pids&&!port)context.allListeners=found;
|
|
75
|
+
return found;
|
|
76
|
+
}
|
|
77
|
+
// /proc encodes each 32-bit address word in host byte order.
|
|
78
|
+
function linuxAddress(local){
|
|
79
|
+
const [hex,port]=local.split(':');
|
|
80
|
+
const bytes=hex.match(/.{8}/g).map(word=>Buffer.from(word.match(/../g).reverse().join(''),'hex'));
|
|
81
|
+
const address=Buffer.concat(bytes);
|
|
82
|
+
const host=address.every(byte=>byte===0)?'*':hex.length===8?[...address].join('.'):
|
|
83
|
+
address.subarray(0,10).every(byte=>byte===0)&&address[10]===255&&address[11]===255?'::ffff:'+([...address.subarray(12)].join('.')):
|
|
84
|
+
[...Array(8)].map((_,i)=>address.readUInt16BE(i*2).toString(16)).join(':').replace(/(^|:)0(?::0)+(?=:|$)/,':').replace(/^:([^:])/, '::$1').replace(/([^:]):$/, '$1::');
|
|
85
|
+
return `${host.includes(':')?'['+host+']':host}:${parseInt(port,16)}`;
|
|
36
86
|
}
|
|
37
87
|
async function linuxPids(){return (await readdir('/proc')).filter(name=>/^\d+$/.test(name)).map(Number);}
|
|
38
88
|
async function descriptors(pid){return Promise.all((await readdir(`/proc/${pid}/fd`).catch(()=>[])).map(fd=>readlink(`/proc/${pid}/fd/${fd}`).catch(()=>'')));}
|
|
39
89
|
|
|
40
90
|
const portOf=name=>Number(/:(\d+)$/.exec(name)?.[1]);
|
|
41
|
-
export async function processCwd(pid){
|
|
91
|
+
export async function processCwd(pid,context=inspectionContext()){
|
|
42
92
|
if(process.platform==='linux')return readlink(`/proc/${pid}/cwd`).catch(()=>undefined);
|
|
43
|
-
return records(await run(lsof,['-a','-p',String(pid),'-d','cwd','-Fpn'])).flatMap(row=>row.names)[0];
|
|
93
|
+
return records(await run(lsof,['-nP','-b','-w','-a','-p',String(pid),'-d','cwd','-Fpn'],context)).flatMap(row=>row.names)[0];
|
|
44
94
|
}
|
|
45
95
|
// Every TCP port some process listens on, on any address: a wildcard listener
|
|
46
96
|
// does not stop a bind to 127.0.0.1, yet it still serves that port's traffic.
|
|
47
|
-
export async function listeningPorts(){return new Set((await listeners()).flatMap(row=>row.names.map(portOf)).filter(Number.isInteger));}
|
|
97
|
+
export async function listeningPorts(context=inspectionContext()){return new Set((await listeners(undefined,context)).flatMap(row=>row.names.map(portOf)).filter(Number.isInteger));}
|
|
48
98
|
// The process that listens on a port on the given host's address or on every
|
|
49
99
|
// address, with its command and working directory.
|
|
50
|
-
|
|
51
|
-
const bare=
|
|
52
|
-
|
|
53
|
-
|
|
100
|
+
function normalizedAddress(address){
|
|
101
|
+
const bare=address.replace(/^\[|\]$/g,'');
|
|
102
|
+
if(bare.toLowerCase()==='localhost')return 'localhost';
|
|
103
|
+
if(isIP(bare)!==6)return bare;
|
|
104
|
+
const [ip,zone]=bare.split('%');
|
|
105
|
+
const normalized=new URL(`http://[${ip}]/`).hostname.slice(1,-1)+(zone?'%'+zone:'');
|
|
106
|
+
const mapped=/^::ffff:([\da-f]+):([\da-f]+)$/i.exec(normalized);
|
|
107
|
+
return mapped?mapped.slice(1).flatMap(word=>[parseInt(word,16)>>>8,parseInt(word,16)&255]).join('.'):normalized;
|
|
54
108
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
109
|
+
// undefined means the inspection cannot prove whether this socket serves the
|
|
110
|
+
// address. In particular, an IPv6 wildcard does not reveal IPV6_V6ONLY.
|
|
111
|
+
function serves({name,family},port,host){
|
|
112
|
+
if(portOf(name)!==port)return false;
|
|
113
|
+
if(!host)return true;
|
|
114
|
+
const address=normalizedAddress(name.slice(0,name.lastIndexOf(':'))),target=normalizedAddress(host);
|
|
115
|
+
if(target==='localhost'){
|
|
116
|
+
const matches=['127.0.0.1','::1'].map(loopback=>serves({name,family},port,loopback));
|
|
117
|
+
return matches.includes(true)?true:matches.includes(undefined)?undefined:false;
|
|
118
|
+
}
|
|
119
|
+
if(address!=='*'&&address!=='0.0.0.0'&&address!=='::')return address===target;
|
|
120
|
+
const socketFamily=family??(address==='0.0.0.0'?'IPv4':address==='::'?'IPv6':undefined);
|
|
121
|
+
if(socketFamily==='IPv4')return isIP(target)===4;
|
|
122
|
+
if(socketFamily==='IPv6'&&isIP(target)===6)return true;
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
function matchingListener(rows,port,host){
|
|
126
|
+
const row=rows.find(row=>row.sockets.some(socket=>serves(socket,port,host)===true));
|
|
127
|
+
if(row)return row;
|
|
128
|
+
if(rows.some(row=>row.sockets.some(socket=>serves(socket,port,host)===undefined))){
|
|
129
|
+
throw commandFailure(`ownership-unchecked: Listener inspection found a wildcard socket on port ${port} whose address family does not prove it serves ${host}. No ownership conclusion was made. Bind the application to the health address explicitly, then retry.`,{});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
export async function portListener(port,host,context=inspectionContext()){
|
|
133
|
+
const row=matchingListener(await listeners(undefined,context,port),port,host);
|
|
134
|
+
return row&&{pid:row.pid,command:await processName(row.pid,context),cwd:await processCwd(row.pid,context)};
|
|
135
|
+
}
|
|
136
|
+
async function descendants(pid,context){
|
|
137
|
+
const rows=(await run('/bin/ps',['-axo','pid=,ppid='],context)).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number));
|
|
59
138
|
const owned=new Set([pid]);for(let changed=true;changed;){changed=false;for(const [child,parent]of rows)if(owned.has(parent)&&!owned.has(child)){owned.add(child);changed=true;}}
|
|
60
|
-
return
|
|
139
|
+
return owned;
|
|
140
|
+
}
|
|
141
|
+
export async function listenerPorts(pid,context=inspectionContext()){
|
|
142
|
+
const owned=await descendants(pid,context);
|
|
143
|
+
return [...new Set((await listeners([...owned],context)).filter(row=>owned.has(row.pid)).flatMap(row=>row.names.map(portOf)).filter(port=>Number.isInteger(port)&&port>0&&port<=65535))].sort((a,b)=>a-b);
|
|
144
|
+
}
|
|
145
|
+
// An exact health address can use positive own-tree evidence. localhost can
|
|
146
|
+
// reach either loopback family, so it also needs a completed inspection with
|
|
147
|
+
// no foreign listener on either address before owner/sign-in can proceed.
|
|
148
|
+
export async function listenerOwnership(pid,port,host,context=inspectionContext()){
|
|
149
|
+
const owned=await descendants(pid,context);
|
|
150
|
+
const ownRows=await listeners([...owned],context);
|
|
151
|
+
const own=ownRows.find(row=>owned.has(row.pid)&&row.sockets.some(socket=>serves(socket,port,host)===true));
|
|
152
|
+
const localhost=host&&normalizedAddress(host)==='localhost';
|
|
153
|
+
if(own&&!localhost)return {status:'owned',pid:own.pid};
|
|
154
|
+
const rows=await listeners(undefined,context,port);
|
|
155
|
+
if(localhost){
|
|
156
|
+
const foreign=matchingListener(rows.filter(row=>!owned.has(row.pid)),port,host);
|
|
157
|
+
if(foreign)return {status:'other',pid:foreign.pid};
|
|
158
|
+
}
|
|
159
|
+
const row=matchingListener(rows,port,host);
|
|
160
|
+
return row?{status:owned.has(row.pid)?'owned':'other',pid:row.pid}:{status:'none'};
|
|
61
161
|
}
|
|
62
162
|
// The caller and the chain that launched it (an installer server running setup,
|
|
63
163
|
// pnpm, a shell) act for this command, never against it.
|
|
64
|
-
async function callerLineage(){
|
|
65
|
-
const parents=new Map((await run('/bin/ps',['-axo','pid=,ppid='])).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number)));
|
|
164
|
+
async function callerLineage(context){
|
|
165
|
+
const parents=new Map((await run('/bin/ps',['-axo','pid=,ppid='],context)).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number)));
|
|
66
166
|
const lineage=new Set([process.pid,process.ppid]);
|
|
67
167
|
for(let pid=process.ppid;pid>1&&parents.has(pid);){pid=parents.get(pid);if(lineage.has(pid))break;lineage.add(pid);}
|
|
68
168
|
return lineage;
|
|
69
169
|
}
|
|
70
|
-
export async function localProcessConflict(root,savedOrigin){
|
|
71
|
-
root=await realpath(root);const all=await listeners(),lineage=await callerLineage();
|
|
72
|
-
const cwdRecords=process.platform!=='linux'&&all.length?records(await run(lsof,['-a','-p',all.map(row=>row.pid).join(','),'-d','cwd','-Fpn'])):[];
|
|
170
|
+
export async function localProcessConflict(root,savedOrigin,context=inspectionContext()){
|
|
171
|
+
root=await realpath(root);const all=await listeners(undefined,context),lineage=await callerLineage(context);
|
|
172
|
+
const cwdRecords=process.platform!=='linux'&&all.length?records(await run(lsof,['-nP','-b','-w','-a','-p',all.map(row=>row.pid).join(','),'-d','cwd','-Fpn'],context)):[];
|
|
73
173
|
let port;try{const url=new URL(savedOrigin);port=Number(url.port||80);}catch{}
|
|
74
174
|
for(const row of all){
|
|
75
175
|
if(lineage.has(row.pid))continue;
|
|
@@ -79,13 +179,19 @@ export async function localProcessConflict(root,savedOrigin){
|
|
|
79
179
|
// A listener running somewhere else is another program's or another checkout's
|
|
80
180
|
// server: it does not use this checkout's state, so it only blocks the port.
|
|
81
181
|
if(onSavedPort&&places.length&&!places.some(place=>place===root||place.startsWith(root+'/')))continue;
|
|
82
|
-
if(onSavedPort||inCheckout)return {pid:row.pid,command:await processName(row.pid),reason:onSavedPort?`saved local port ${port}`:'this checkout'};
|
|
182
|
+
if(onSavedPort||inCheckout)return {pid:row.pid,command:await processName(row.pid,context),reason:onSavedPort?`saved local port ${port}`:'this checkout'};
|
|
83
183
|
}
|
|
84
184
|
// A process may hold the canonical database without listening. Inspect only
|
|
85
185
|
// actual state files, never broad checkout contents or a process environment.
|
|
86
186
|
const state=join(root,'.wrangler/state');
|
|
187
|
+
try{await lstat(state);}catch(error){if(error.code==='ENOENT')return;throw error;}
|
|
87
188
|
let held;
|
|
88
189
|
if(process.platform==='linux'){for(const pid of await linuxPids())if(!lineage.has(pid)&&(await descriptors(pid)).some(path=>path.startsWith(state+'/'))){held={pid};break;}}
|
|
89
|
-
else
|
|
90
|
-
|
|
190
|
+
else {
|
|
191
|
+
// +D requires blocking pathname metadata even for a narrow directory. Read
|
|
192
|
+
// kernel-provided open paths instead, then match only canonical state files.
|
|
193
|
+
// This preflight protects data held by processes outside the app's tree.
|
|
194
|
+
held=records(await run(lsof,['-nP','-b','-w','-Fpn'],context,{maxBuffer:16*1024*1024})).find(row=>!lineage.has(row.pid)&&row.names.some(path=>path.startsWith(state+'/')));
|
|
195
|
+
}
|
|
196
|
+
if(held)return {pid:held.pid,command:await processName(held.pid,context),reason:'the canonical local state'};
|
|
91
197
|
}
|