@runeditrun/rer 0.2.16 → 0.2.18
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 +2 -0
- 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/output.mjs +7 -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/cli/stdio.mjs +12 -0
- package/global/CHANGELOG.md +12 -0
- package/global/output.mjs +1 -12
- 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 +25 -6
- package/modules/demo-host/capacity.mjs +27 -6
- package/modules/demo-host/container.mjs +37 -9
- package/modules/demo-host/entrypoint.sh +9 -0
- package/modules/demo-host/image.mjs +18 -0
- package/modules/demo-host/pages.mjs +7 -7
- package/modules/demo-host/plan.mjs +1 -1
- package/modules/demo-host/prepare.mjs +28 -0
- package/modules/demo-host/start-script.mjs +11 -4
- package/modules/demo-host/startup.mjs +25 -0
- package/modules/demo-host/template.mjs +71 -0
- package/modules/demo-host/worker.mjs +74 -31
- 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
|
@@ -24,24 +24,24 @@ ol.steps{display:none;list-style:none;margin:22px auto 0;padding:0;width:max-con
|
|
|
24
24
|
@media(min-width:600px) and (max-width:1023px){main{width:calc(100% - 64px);max-width:666px;margin:100px auto 48px}.card{padding:36px}h1{font-size:38px;line-height:46px}.intro{font-size:18px;line-height:27px}}
|
|
25
25
|
@media(max-width:599px){main,.ended main{width:calc(100% - 32px);margin:32px auto}.ended .card{padding:26px 22px}.ended h1{font-size:29px;line-height:36px}.ended .intro{font-size:17px;line-height:25px;margin-bottom:28px}.card{padding:26px 22px;border-radius:16px}.brand{font-size:16px}h1{font-size:34px;line-height:41px;letter-spacing:-.8px}.intro{font-size:17px;line-height:25px}ul{font-size:16px;line-height:25px;margin:22px 0 26px}li{padding-left:22px;margin-bottom:9px}li:before{left:2px;top:9px}.button{font-size:18px;margin-top:22px}.note{font-size:13px;line-height:20px}.steps{font-size:15px}.back{margin-top:24px;font-size:14px}}`;
|
|
26
26
|
|
|
27
|
-
function html(env, { page, title, body, status = 200, headers = {}, turnstile = false }) {
|
|
27
|
+
function html(env, { page, title, body, status = 200, headers = {}, turnstile = false, refresh = false }) {
|
|
28
28
|
const nonce = crypto.randomUUID().replaceAll('-', ''), site = new URL(env.DEMO_SITE);
|
|
29
29
|
const policy = `default-src 'none'; style-src 'nonce-${nonce}'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'${turnstile ? `; script-src 'nonce-${nonce}' https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com; connect-src 'self' https://challenges.cloudflare.com` : ''}`;
|
|
30
|
-
return new Response(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escape(title)}</title><style nonce="${nonce}">${STYLE}</style>${turnstile ? `<noscript><style nonce="${nonce}">#note{display:none}</style></noscript><script nonce="${nonce}">${START_SCRIPT}</script><script nonce="${nonce}" src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>` : ''}</head>
|
|
30
|
+
return new Response(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escape(title)}</title>${refresh ? '<noscript><meta http-equiv="refresh" content="2;url=/__demo/status"></noscript>' : ''}<style nonce="${nonce}">${STYLE}</style>${turnstile ? `<noscript><style nonce="${nonce}">#note{display:none}</style></noscript><script nonce="${nonce}">${START_SCRIPT}</script><script nonce="${nonce}" src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>` : ''}</head>
|
|
31
31
|
<body class="${page}"><main><section class="card" aria-labelledby="title"><div class="mark" aria-hidden="true"></div><p class="brand">${escape(env.DEMO_NAME)}</p>${body}</section><nav class="back" aria-label="Return"><a href="${escape(site.origin)}/">Back to ${escape(site.host)}</a></nav></main></body></html>`,
|
|
32
32
|
{ status, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': policy, 'referrer-policy': 'strict-origin', 'x-content-type-options': 'nosniff', ...headers } });
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
/** GET /: the visitor proves they are human and their demo starts. `notice` explains a refused start. */
|
|
36
|
-
export function startPage(env, { status = 200, notice, headers = {} } = {}) {
|
|
36
|
+
export function startPage(env, { status = 200, notice, pending = false, headers = {} } = {}) {
|
|
37
37
|
const name = escape(env.DEMO_NAME);
|
|
38
|
-
return html(env, { page: 'start', title: `Try ${env.DEMO_NAME}`, status, headers, turnstile: true, body: `<h1 id="title">Try ${name}</h1>
|
|
38
|
+
return html(env, { page: 'start', title: `Try ${env.DEMO_NAME}`, status, headers, turnstile: true, refresh: pending, body: `<h1 id="title">Try ${name}</h1>
|
|
39
39
|
<p class="intro">Your own copy of ${name}, signed in as its owner, with sample data.</p>
|
|
40
40
|
<ul><li>Nothing is sent: mail stays in an outbox.</li><li>It ends after an hour, or 15 idle minutes.</li><li>Then it is deleted. Nobody else can see it.</li></ul>
|
|
41
|
-
<p class="notice" id="notice" role="alert"${notice ? '' : ' hidden'}>${notice ? escape(notice) : ''}</p><form id="start" method="post" action="/__demo/start" data-auto="${notice ? '0' : '1'}"><div class="cf-turnstile" data-sitekey="${escape(env.TURNSTILE_SITE_KEY)}" data-size="flexible" data-callback="rerDemoVerified" data-before-interactive-callback="rerDemoInteractive" data-after-interactive-callback="rerDemoChecking" data-expired-callback="rerDemoExpired" data-error-callback="rerDemoCheckFailed"></div>
|
|
42
|
-
<button class="button" type="submit"><span class="spinner" aria-hidden="true"></span><span class="label"
|
|
41
|
+
<p class="notice" id="notice" role="alert"${notice ? '' : ' hidden'}>${notice ? escape(notice) : ''}</p><form id="start" method="post" action="/__demo/start" data-auto="${notice || pending ? '0' : '1'}"${pending ? ' data-resume="1" data-state="working"' : ''}><div class="cf-turnstile" data-sitekey="${escape(env.TURNSTILE_SITE_KEY)}" data-size="flexible" data-callback="rerDemoVerified" data-before-interactive-callback="rerDemoInteractive" data-after-interactive-callback="rerDemoChecking" data-expired-callback="rerDemoExpired" data-error-callback="rerDemoCheckFailed"></div>
|
|
42
|
+
<button class="button" type="submit"${pending ? ' disabled' : ''}><span class="spinner" aria-hidden="true"></span><span class="label">${pending ? 'Starting your demo…' : 'Start the demo'}</span></button>
|
|
43
43
|
<ol class="steps" aria-hidden="true"><li data-at="done">Checking you're human</li><li data-at="now">Starting a private copy</li><li data-at="next">Signing you in</li></ol>
|
|
44
|
-
<p class="note" id="note"
|
|
44
|
+
<p class="note" id="note">${pending ? 'Your demo will open automatically when ready.' : 'Complete the human check to start your demo.'}</p><noscript><p class="note">The human check needs JavaScript. Turn it on to start the demo.</p></noscript><p class="visually-hidden" id="status" role="status"></p></form>` });
|
|
45
45
|
}
|
|
46
46
|
|
|
47
47
|
/** A demo whose hour or idle time is up: its container and data are gone. */
|
|
@@ -9,7 +9,7 @@ import { siteDeclaration } from '../deploy-kit/site.mjs';
|
|
|
9
9
|
* running the seed's own image (`rer build --platform container`, workerd
|
|
10
10
|
* engine), deployed by `wrangler deploy` with the image beside it. */
|
|
11
11
|
|
|
12
|
-
export const DEMO_FILES = ['worker.mjs', 'container.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs'];
|
|
12
|
+
export const DEMO_FILES = ['worker.mjs', 'container.mjs', 'startup.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs'];
|
|
13
13
|
const FRONT_SET = /^(?:RER_.*|SESSION_SECRET|SETUP_TOKEN|OWNER_EMAIL)$/;
|
|
14
14
|
const SECRET = /SECRET|TOKEN|PASSWORD|_KEY$/;
|
|
15
15
|
// Cloudflare Containers' predefined instance types, smallest first (developers.cloudflare.com/containers/platform-details/limits).
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { mkdir, readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { workerEngine } from '../container/worker-engine.mjs';
|
|
4
|
+
import { sealTemplate } from './template.mjs';
|
|
5
|
+
|
|
6
|
+
/** Migrate with the packaged engine; never dispatch an app request or claim. */
|
|
7
|
+
export async function prepareTemplate({ root = '/app', data = '/template' } = {}) {
|
|
8
|
+
const manifest = JSON.parse(await readFile(join(root, 'container.json'), 'utf8'));
|
|
9
|
+
if (manifest.engine !== 'workerd') throw new Error('demo-template-requires-workerd');
|
|
10
|
+
await mkdir(data, { mode: 0o700 });
|
|
11
|
+
let engine;
|
|
12
|
+
try {
|
|
13
|
+
engine = await workerEngine({ root, data, manifest, settings: { RER_DEMO: '1' } });
|
|
14
|
+
} finally {
|
|
15
|
+
await engine?.close();
|
|
16
|
+
}
|
|
17
|
+
return sealTemplate(data, manifest);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (process.argv[1] === import.meta.filename) {
|
|
21
|
+
try { await prepareTemplate(); }
|
|
22
|
+
catch (error) {
|
|
23
|
+
// A failed engine constructor may still own workerd handles. The build must
|
|
24
|
+
// fail immediately; there is no usable template to keep alive or recover.
|
|
25
|
+
console.error('Demo template preparation failed:', error.name);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -24,14 +24,20 @@ function waiting(){
|
|
|
24
24
|
show('waiting',{label:'Waiting for the human check…',note:auto?'Your demo will open automatically when ready.':'Once the check passes, press Start the demo.'});
|
|
25
25
|
}
|
|
26
26
|
function stop(){timers.forEach(clearTimeout);timers=[]}
|
|
27
|
-
async function go(){
|
|
27
|
+
async function go(resume=false){
|
|
28
28
|
const p=el(),controller=attempt=new AbortController();
|
|
29
29
|
show('working',{label:'Starting your demo…',note:'Your demo will open automatically when ready.',live:'Check passed. Starting a private copy.',step:1,notice:''});
|
|
30
30
|
timers.push(setTimeout(()=>p.note.textContent='Taking a little longer than usual. Still starting…',LONG));
|
|
31
31
|
timers.push(setTimeout(()=>show('slow',{label:'Try again',note:'Still starting. It will open by itself if it finishes.',notice:'This is taking longer than it should. Keep waiting, or try again.'}),SLOW));
|
|
32
32
|
try{
|
|
33
|
-
|
|
34
|
-
|
|
33
|
+
let response=await fetch(resume?'/__demo/status':p.form.action,{...(resume?{}:{method:'POST',body:new URLSearchParams(new FormData(p.form))}),headers:{accept:'application/json'},signal:controller.signal});
|
|
34
|
+
let result=await response.json().catch(()=>({}));
|
|
35
|
+
while(response.status===202&&result.pending===true){
|
|
36
|
+
await new Promise(resolve=>setTimeout(resolve,500));
|
|
37
|
+
if(attempt!==controller)return;
|
|
38
|
+
response=await fetch('/__demo/status',{headers:{accept:'application/json'},signal:controller.signal});
|
|
39
|
+
result=await response.json().catch(()=>({}));
|
|
40
|
+
}
|
|
35
41
|
if(attempt!==controller)return;
|
|
36
42
|
stop();
|
|
37
43
|
if(response.ok&&typeof result.location==='string'){
|
|
@@ -60,7 +66,8 @@ window.rerDemoChecking=()=>checking()&&waiting();
|
|
|
60
66
|
window.rerDemoExpired=()=>checking()&&waiting();
|
|
61
67
|
window.rerDemoCheckFailed=()=>checking()&&show('failed',{label:'Try again',note:'',live:'',notice:'The human check did not load. Try again.'});
|
|
62
68
|
addEventListener('DOMContentLoaded',()=>{
|
|
63
|
-
if(
|
|
69
|
+
if(el().form.dataset.resume==='1')go(true);
|
|
70
|
+
else if(!el().form.dataset.state)waiting();
|
|
64
71
|
el().form.addEventListener('submit',event=>{
|
|
65
72
|
event.preventDefault();
|
|
66
73
|
const state=el().form.dataset.state;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { bounded, category, report } from './diagnostics.mjs';
|
|
2
|
+
import { fingerprint } from './capacity.mjs';
|
|
3
|
+
|
|
4
|
+
// Kept by the visitor's Durable Object while the front returns short progress
|
|
5
|
+
// responses. A dropped browser request cannot abandon cleanup or hold a place
|
|
6
|
+
// until the demo's hour expires.
|
|
7
|
+
export async function finishStart(demo, options) {
|
|
8
|
+
const { correlation, ends } = options, id = demo.ctx.id.toString();
|
|
9
|
+
try {
|
|
10
|
+
report(correlation, Date.now(), 'reservation', { heldId: await fingerprint(id) });
|
|
11
|
+
const result = await bounded(demo.start(options), demo.startTimeout + 1000);
|
|
12
|
+
if (!await bounded(demo.env.CAPACITY.get(demo.env.CAPACITY.idFromName('capacity')).extend(id, ends), 2000) || demo.stopped) throw new Error('start-reservation-expired');
|
|
13
|
+
await demo.ctx.storage.put('startup', { phase: 'ready', ...result });
|
|
14
|
+
await demo.ctx.storage.delete('startDeadline');
|
|
15
|
+
} catch (error) {
|
|
16
|
+
const failure = ['health-deadline', 'container-stopped', 'start-reservation-expired'].includes(error.message) ? error.message : category(error);
|
|
17
|
+
demo.record('failed', { error: failure });
|
|
18
|
+
try {
|
|
19
|
+
const diagnostic = await bounded(demo.diagnostic(), 3000);
|
|
20
|
+
await bounded(demo.env.CAPACITY.get(demo.env.CAPACITY.idFromName('diagnostics')).record(correlation, { ...diagnostic, failure }), 3000);
|
|
21
|
+
} catch (capture) { report(correlation, demo.started, 'diagnostic', { error: category(capture) }); }
|
|
22
|
+
await demo.ctx.storage.put('startup', { phase: 'failed' });
|
|
23
|
+
try { await demo.end(); } catch (cleanup) { report(correlation, demo.started, 'cleanup', { error: category(cleanup) }); }
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { cp, lstat, mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const descriptor = '.rer-demo-template.json';
|
|
6
|
+
const initialized = '.rer-demo-initialized.json';
|
|
7
|
+
const copying = '.rer-demo-initializing.json';
|
|
8
|
+
|
|
9
|
+
async function inventory(directory, prefix = '') {
|
|
10
|
+
const entries = [];
|
|
11
|
+
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
12
|
+
if (!entry.isFile() && !entry.isDirectory()) throw new Error('demo-template-invalid-entry');
|
|
13
|
+
const path = prefix + entry.name;
|
|
14
|
+
entries.push({ path, directory: entry.isDirectory() });
|
|
15
|
+
if (entry.isDirectory()) entries.push(...await inventory(join(directory, entry.name), path + '/'));
|
|
16
|
+
}
|
|
17
|
+
return entries;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Called only after the engine has closed its database and persistence files. */
|
|
21
|
+
export async function sealTemplate(template, manifest) {
|
|
22
|
+
const entries = await inventory(template);
|
|
23
|
+
if (entries.some(entry => ['host.lock', descriptor, initialized, copying].includes(entry.path))) throw new Error('demo-template-not-fresh');
|
|
24
|
+
const marker = { version: 1, manifest: createHash('sha256').update(JSON.stringify(manifest)).digest('hex'), entries };
|
|
25
|
+
await writeFile(join(template, descriptor), JSON.stringify(marker) + '\n', { flag: 'wx', mode: 0o600 });
|
|
26
|
+
return marker;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function present(directory, entries) {
|
|
30
|
+
for (const entry of entries) {
|
|
31
|
+
let stat;
|
|
32
|
+
try { stat = await lstat(join(directory, entry.path)); }
|
|
33
|
+
catch (error) { if (error.code === 'ENOENT') return false; throw error; }
|
|
34
|
+
if (entry.directory ? !stat.isDirectory() : !stat.isFile()) return false;
|
|
35
|
+
}
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Caller holds data/host.lock until the host exits. Never overlays live data. */
|
|
40
|
+
export async function copyTemplate(template, data) {
|
|
41
|
+
const raw = await readFile(join(template, descriptor), 'utf8'), marker = JSON.parse(raw);
|
|
42
|
+
if (marker.version !== 1 || !/^[a-f0-9]{64}$/.test(marker.manifest ?? '') || !Array.isArray(marker.entries)
|
|
43
|
+
|| marker.entries.some(entry => typeof entry.path !== 'string' || !entry.path || entry.path.startsWith('/')
|
|
44
|
+
|| entry.path.split('/').some(part => ['', '.', '..'].includes(part)) || typeof entry.directory !== 'boolean'
|
|
45
|
+
|| [descriptor, initialized, copying, 'host.lock'].includes(entry.path))) throw new Error('demo-template-invalid');
|
|
46
|
+
await mkdir(data, { recursive: true, mode: 0o700 });
|
|
47
|
+
const existing = await readdir(data);
|
|
48
|
+
if (existing.includes('host.lock') && !(await lstat(join(data, 'host.lock'))).isFile()) throw new Error('demo-volume-invalid-lock');
|
|
49
|
+
if (existing.includes(copying)) throw new Error('demo-volume-incomplete');
|
|
50
|
+
if (existing.includes(initialized)) {
|
|
51
|
+
if (!(await lstat(join(data, initialized))).isFile()) throw new Error('demo-volume-incomplete');
|
|
52
|
+
if (await readFile(join(data, initialized), 'utf8') !== raw) throw new Error('demo-volume-template-mismatch');
|
|
53
|
+
// SQLite may remove its transient WAL/SHM files after a later clean close.
|
|
54
|
+
if (!await present(data, marker.entries.filter(entry => !/-(wal|shm)$/.test(entry.path)))) throw new Error('demo-volume-incomplete');
|
|
55
|
+
return { copied: false };
|
|
56
|
+
}
|
|
57
|
+
if (existing.some(name => name !== 'host.lock')) throw new Error('demo-volume-not-fresh');
|
|
58
|
+
if (!await present(template, marker.entries)) throw new Error('demo-template-incomplete');
|
|
59
|
+
await writeFile(join(data, copying), raw, { flag: 'wx', mode: 0o600 });
|
|
60
|
+
for (const entry of marker.entries.filter(entry => !entry.path.includes('/'))) {
|
|
61
|
+
await cp(join(template, entry.path), join(data, entry.path), { recursive: true, force: false, errorOnExist: true });
|
|
62
|
+
}
|
|
63
|
+
if (!await present(data, marker.entries)) throw new Error('demo-volume-incomplete');
|
|
64
|
+
await rename(join(data, copying), join(data, initialized));
|
|
65
|
+
return { copied: true };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (process.argv[1] === import.meta.filename) {
|
|
69
|
+
try { await copyTemplate(process.argv[2] ?? '/template', process.argv[3] ?? '/data'); }
|
|
70
|
+
catch (error) { console.error('Demo volume initialization failed:', error.message); process.exitCode = 1; }
|
|
71
|
+
}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// container; nothing else on this host is reachable.
|
|
8
8
|
import { operatorPage } from './operator.mjs';
|
|
9
9
|
import { bounded, category, report } from './diagnostics.mjs';
|
|
10
|
-
import { startPage, demoCookie } from './pages.mjs';
|
|
10
|
+
import { startPage, demoCookie, clearCookie } from './pages.mjs';
|
|
11
11
|
|
|
12
12
|
export { DemoContainer } from './container.mjs';
|
|
13
13
|
export { DemoCapacity } from './capacity.mjs';
|
|
@@ -33,51 +33,94 @@ async function human(env, token, ip) {
|
|
|
33
33
|
if (typeof token !== 'string' || !token || token.length > 2048) return false;
|
|
34
34
|
const body = new URLSearchParams({ secret: env.TURNSTILE_SECRET_KEY, response: token });
|
|
35
35
|
if (ip) body.set('remoteip', ip);
|
|
36
|
-
const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', body });
|
|
36
|
+
const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', body, signal: AbortSignal.timeout(5000) });
|
|
37
37
|
const result = response.ok ? await response.json() : {};
|
|
38
38
|
if (result.success !== true) console.error('Turnstile refused a start:', response.status, JSON.stringify(result['error-codes'] ?? []));
|
|
39
39
|
return result.success === true;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
if (
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
42
|
+
const wantsJSON = request => request.headers.get('accept') === 'application/json';
|
|
43
|
+
function refusal(request, env, status, notice, headers = {}) {
|
|
44
|
+
return wantsJSON(request) ? Response.json({ notice }, { status, headers: { 'cache-control': 'no-store', ...headers } }) : startPage(env, { status, notice, headers });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function progress(request, env, id, state) {
|
|
48
|
+
const headers = new Headers({ 'cache-control': 'no-store' });
|
|
49
|
+
if (state.correlation) headers.set('x-rer-demo-correlation', state.correlation);
|
|
50
|
+
if (state.phase === 'failed') return refusal(request, env, 502, 'The demo did not start. Try again.', { ...Object.fromEntries(headers), 'set-cookie': clearCookie(env) });
|
|
51
|
+
headers.append('set-cookie', demoCookie(env, id.toString()));
|
|
52
|
+
if (state.phase === 'starting') {
|
|
53
|
+
headers.set('retry-after', '1');
|
|
54
|
+
if (wantsJSON(request)) return Response.json({ pending: true }, { status: 202, headers });
|
|
55
|
+
// A plain form keeps the same visitor reservation while the copy starts.
|
|
56
|
+
return startPage(env, { status: 202, pending: true, headers: Object.fromEntries(headers) });
|
|
53
57
|
}
|
|
54
|
-
const
|
|
58
|
+
for (const cookie of state.cookies) headers.append('set-cookie', cookie);
|
|
59
|
+
if (wantsJSON(request)) return Response.json({ location: state.location }, { headers });
|
|
60
|
+
headers.set('location', state.location);
|
|
61
|
+
return new Response(null, { status: 303, headers });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function status(request, env) {
|
|
65
|
+
const id = demoId(request, env);
|
|
66
|
+
if (!id) return refusal(request, env, 410, 'This demo has ended. Start a new demo.');
|
|
67
|
+
try { return progress(request, env, id, await bounded(env.DEMO.get(id).status(), 2000)); }
|
|
68
|
+
catch { return refusal(request, env, 503, 'The demo could not be reached. Try again.'); }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function start(request, env, ctx) {
|
|
72
|
+
const refuse = (status, notice, headers = {}) => refusal(request, env, status, notice, headers);
|
|
73
|
+
if (request.headers.get('origin') !== env.DEMO_ORIGIN) return refuse(403, 'Start the demo from this page.');
|
|
74
|
+
let demo, correlation;
|
|
75
|
+
const started = Date.now();
|
|
55
76
|
try {
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
if (
|
|
60
|
-
|
|
61
|
-
|
|
77
|
+
const ip = request.headers.get('cf-connecting-ip') ?? '';
|
|
78
|
+
if (!(await bounded(env.STARTS.limit({ key: ip }), 1000)).success) return refuse(429, 'Too many demos started from your network. Try again in a minute.');
|
|
79
|
+
const form = await bounded(request.formData(), 1000);
|
|
80
|
+
if (!await bounded(human(env, form.get('cf-turnstile-response'), ip), 5000)) return refuse(403, 'The check did not pass. Try again.');
|
|
81
|
+
// A retry while the original start is pending resumes that copy, not a
|
|
82
|
+
// second reservation that the visitor can never use.
|
|
83
|
+
const prior = demoId(request, env);
|
|
84
|
+
if (prior) {
|
|
85
|
+
const state = await bounded(env.DEMO.get(prior).status(), 1000);
|
|
86
|
+
if (state.phase === 'starting') return progress(request, env, prior, state);
|
|
87
|
+
}
|
|
88
|
+
const id = env.DEMO.newUniqueId(), ends = Date.now() + HOUR;
|
|
89
|
+
const capacity = env.CAPACITY.get(env.CAPACITY.idFromName('capacity'));
|
|
90
|
+
// A lost handoff occupies a place for at most a minute. The object extends
|
|
91
|
+
// it to the demo's end only after health and owner admission succeed.
|
|
92
|
+
if (!await bounded(capacity.acquire(id.toString(), Date.now() + 60_000, Number(env.DEMO_MAX_INSTANCES)), 2000)) {
|
|
93
|
+
return refuse(503, 'Every demo is in use right now. Try again in a few minutes.');
|
|
94
|
+
}
|
|
95
|
+
demo = env.DEMO.get(id); correlation = crypto.randomUUID();
|
|
96
|
+
const state = await bounded(demo.begin({ correlation, origin: env.DEMO_ORIGIN, originVar: env.DEMO_ORIGIN_VAR, ends, endsLocal: localTime(ends, request.cf?.timezone), settings: JSON.parse(env.DEMO_SETTINGS) }), 2000);
|
|
97
|
+
return progress(request, env, id, { ...state, correlation });
|
|
62
98
|
} catch (error) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
await bounded(env.CAPACITY.get(env.CAPACITY.idFromName('diagnostics')).record(correlation, diagnostic), 3000);
|
|
68
|
-
} catch (capture) { report(correlation, started, 'diagnostic', { error: category(capture) }); }
|
|
69
|
-
try { await bounded(demo.end(), 6000); } catch (cleanup) { report(correlation, started, 'cleanup', { error: category(cleanup) }); }
|
|
70
|
-
return refuse(502, 'The demo did not start. Try again.', { 'x-rer-demo-correlation': correlation });
|
|
99
|
+
report(correlation, started, 'failed', { error: category(error) });
|
|
100
|
+
// Cleanup runs independently of the response: retries never wait on it.
|
|
101
|
+
if (demo) ctx.waitUntil(bounded(demo.end(), 6000).catch(cleanup => report(correlation, started, 'cleanup', { error: category(cleanup) })));
|
|
102
|
+
return refuse(502, 'The demo did not start. Try again.', correlation ? { 'x-rer-demo-correlation': correlation } : {});
|
|
71
103
|
}
|
|
72
104
|
}
|
|
73
105
|
|
|
74
106
|
export default {
|
|
75
|
-
async fetch(request, env) {
|
|
107
|
+
async fetch(request, env, ctx) {
|
|
76
108
|
const url = new URL(request.url);
|
|
77
109
|
if (url.pathname.startsWith('/__demo/operator/')) return operatorPage(request, env, url.pathname.slice('/__demo/operator/'.length));
|
|
78
|
-
if (url.pathname === '/__demo/start') return request.method === 'POST' ? start(request, env) : home();
|
|
110
|
+
if (url.pathname === '/__demo/start') return request.method === 'POST' ? start(request, env, ctx) : home();
|
|
111
|
+
if (url.pathname === '/__demo/status') return request.method === 'GET' ? status(request, env) : home();
|
|
79
112
|
const id = demoId(request, env);
|
|
80
|
-
if (id)
|
|
113
|
+
if (id) {
|
|
114
|
+
// The JSON start leaves the browser on /. Reloading it must keep the
|
|
115
|
+
// pending copy on the progress page until health and owner claim finish.
|
|
116
|
+
if (url.pathname === '/' && ['GET', 'HEAD'].includes(request.method)) {
|
|
117
|
+
try {
|
|
118
|
+
const state = await bounded(env.DEMO.get(id).status(), 2000);
|
|
119
|
+
if (state.phase === 'starting') return progress(request, env, id, state);
|
|
120
|
+
} catch { return refusal(request, env, 503, 'The demo could not be reached. Try again.'); }
|
|
121
|
+
}
|
|
122
|
+
return env.DEMO.get(id).fetch(request);
|
|
123
|
+
}
|
|
81
124
|
if (!['GET', 'HEAD'].includes(request.method)) return new Response('Start a demo first.', { status: 403 });
|
|
82
125
|
if (url.pathname !== '/') return home();
|
|
83
126
|
return startPage(env);
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readinessWindow, readinessAPI } from './readiness-window.mjs';
|
|
2
|
+
import { uploadedWorker } from './uploaded-worker.mjs';
|
|
1
3
|
import { recordDeployFailure } from './diagnostics.mjs';
|
|
2
4
|
import { verifyServiceGrants } from './service-grants.mjs';
|
|
3
5
|
import { assert, hash, validatePlan } from './validation.mjs';
|
|
@@ -42,8 +44,11 @@ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,r
|
|
|
42
44
|
const migrations = [];
|
|
43
45
|
// A migration failure names its database, so the owner knows which one to inspect.
|
|
44
46
|
for (const item of plan.d1) migrations.push({binding:item.binding,...await migrate(api,resources.d1.find(x => x.binding === item.binding).id,item.migrations,{apply:!unchanged,upgrade:true}).catch(error => { error.resource ??= `d1:${item.name}`; throw error; })});
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
const window = readiness.window ?? readinessWindow({...(healthOptions.now ? {clock:healthOptions.now} : {}), ...(healthOptions.sleep ? {sleep:healthOptions.sleep} : {}), ...readiness});
|
|
48
|
+
let upload;
|
|
49
|
+
if (!unchanged) { window.start(); upload = await uploadWorker(api,{plan,artifact,bindings,secrets,migration,fingerprint}); }
|
|
50
|
+
if (!unchanged) api = readinessAPI(api, window);
|
|
51
|
+
const published = unchanged ? existing : await uploadedWorker({api,worker:plan.worker,upload,previous:existing,fingerprint,window}); assert(published,'missing-deployed-worker');
|
|
47
52
|
verifyBindings(published.settings.bindings,bindings);
|
|
48
53
|
verifyScheduledHandler(published,plan);
|
|
49
54
|
// Finish routing activation before applying schedules to this deployment.
|
|
@@ -61,7 +66,7 @@ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,r
|
|
|
61
66
|
const asset = publicAssetPaths(artifact.assets.map(x => x.path))[0];
|
|
62
67
|
try {
|
|
63
68
|
if (unchanged) await verifyHealth({...healthOptions,api,plan,receipt,fetch,asset});
|
|
64
|
-
else await firstHealth({api,plan,receipt,fetch,healthOptions,readiness,onHealth,asset});
|
|
69
|
+
else await firstHealth({api,plan,receipt,fetch,healthOptions,readiness:{...readiness,window,freshUpload:!existing},onHealth,asset});
|
|
65
70
|
} catch (error) { throw recordDeployFailure(error,{step:'health',...(error.code ? {code:error.code,output:error.message} : {})}); }
|
|
66
71
|
return receipt;
|
|
67
72
|
}
|
|
@@ -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. */
|