@runeditrun/rer 0.2.22 → 0.2.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/cli/README.md +19 -0
  2. package/cli/bounded.mjs +5 -1
  3. package/cli/delivery-declarations.mjs +2 -2
  4. package/cli/demo-host.mjs +1 -1
  5. package/cli/deploy-command.mjs +7 -5
  6. package/cli/deploy-inputs.mjs +4 -1
  7. package/cli/deploy-observation.mjs +20 -2
  8. package/cli/deploy-owner.mjs +12 -7
  9. package/cli/deploy.mjs +9 -6
  10. package/cli/deployment-record.mjs +52 -0
  11. package/cli/local.mjs +11 -3
  12. package/cli/managed-server.mjs +2 -1
  13. package/cli/output.mjs +1 -1
  14. package/cli/production-auth.mjs +7 -27
  15. package/cli/production-mail.mjs +72 -0
  16. package/cli/signin.mjs +11 -6
  17. package/cli/site.mjs +2 -2
  18. package/global/CHANGELOG.md +25 -0
  19. package/modules/container/README.md +8 -3
  20. package/modules/container/adapters/d1.mjs +1 -1
  21. package/modules/container/build.mjs +1 -1
  22. package/modules/container/host.mjs +7 -4
  23. package/modules/container/transfer.mjs +0 -1
  24. package/modules/container/websockets.mjs +54 -0
  25. package/modules/container/worker-engine.mjs +3 -3
  26. package/modules/demo/README.md +4 -0
  27. package/modules/demo/label.mjs +7 -4
  28. package/modules/demo/responses.mjs +1 -1
  29. package/modules/demo-host/README.md +34 -9
  30. package/modules/demo-host/capacity.mjs +2 -2
  31. package/modules/demo-host/container.mjs +19 -7
  32. package/modules/demo-host/placement.mjs +19 -5
  33. package/modules/demo-host/plan.mjs +11 -6
  34. package/modules/demo-host/start-script.mjs +2 -1
  35. package/modules/demo-host/startup.mjs +3 -3
  36. package/modules/demo-host/worker.mjs +36 -13
  37. package/modules/deploy-kit/README.md +35 -2
  38. package/modules/deploy-kit/diagnostics.mjs +16 -1
  39. package/modules/deploy-kit/owner-cli.mjs +3 -3
  40. package/modules/deploy-kit/owner-remove.mjs +23 -5
  41. package/modules/deploy-kit/owner-signin.mjs +1 -1
  42. package/modules/deploy-kit/pagination.mjs +99 -0
  43. package/modules/deploy-kit/provider.mjs +30 -70
  44. package/modules/deploy-kit/r2-objects.mjs +6 -17
  45. package/modules/deploy-kit/site-readback.mjs +67 -0
  46. package/modules/deploy-kit/site.mjs +17 -31
  47. package/modules/deploy-kit/uploaded-worker.mjs +9 -3
  48. package/modules/erasure/queue.mjs +0 -2
  49. package/modules/job-queue/cli.mjs +1 -1
  50. package/modules/mail/README.md +14 -5
  51. package/modules/mail/src/adapters/rer/contract.mjs +33 -5
  52. package/modules/mail/src/adapters/rer/index.mjs +4 -1
  53. package/modules/mail/src/core/transport.mjs +9 -3
  54. package/modules/operator-auth/README.md +5 -0
  55. package/modules/operator-auth/identity/email-link/index.mjs +5 -0
  56. package/modules/operator-auth/identity/oidc/jwt.mjs +1 -1
  57. package/modules/portability/bridge.mjs +3 -3
  58. package/modules/portability/catalogue.mjs +1 -1
  59. package/modules/portability/cli-options.mjs +1 -1
  60. package/modules/portability/legacy-files.mjs +1 -1
  61. package/modules/portability/legacy-safety.mjs +3 -3
  62. package/modules/portability/payloads.mjs +1 -1
  63. package/modules/release/source.mjs +1 -1
  64. package/onboarding/local/operation.mjs +4 -2
  65. package/onboarding/local/owner.mjs +9 -3
  66. package/onboarding/local/state-files.mjs +17 -0
  67. package/onboarding/process-diagnostics.mjs +25 -5
  68. package/package.json +1 -1
  69. package/scripts/publish-check/README.md +5 -2
  70. package/scripts/publish-check/content_identities.py +1 -1
  71. package/scripts/publish-check/json_identity.py +10 -1
  72. package/scripts/publish-check/public_hygiene.py +30 -4
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.24
4
+
5
+ - Hosted demos stay up through redeploys. The demo's Container application keeps a live demo's instance for an hour (`rollout_active_grace_period`), so a deploy that changes the image, instance type or limit no longer ends idle visitors' demos ("This demo has ended" within two minutes before).
6
+ - Hosted demos wait out Cloudflare placement. A fresh application keeps 7 prepared instances; the eighth concurrent demo waited 16-37 s for Cloudflare to place another. Placement waits now renew the 45-second boot budget up to 90 seconds and keep the visitor's reservation. The application's own `max_instances` is twice `maxInstances`, so instances Cloudflare still counts after demos end never refuse an admitted visitor; admission still holds at `maxInstances`.
7
+ - A new demo copy that takes over two seconds to answer is a pending start instead of a 502, and a slow status read stays pending instead of a 503.
8
+ - The start page signs in about half a second sooner: each status poll is held until the start changes, and the reservation is extended alongside the owner claim.
9
+ - `deploy-demo.json` takes an optional `ownerEmail`, the address the demo's owner signs in as and seed screens show (`owner@demo.invalid` unless set).
10
+ - Each demo admission logs `demo_admitted` with the user agent and network, so a held place can be joined to whoever started it. On test hosts, automated browsers pass Turnstile's always-pass testing keys and hold real places.
11
+ - Run-site deploys wait through Cloudflare propagation after a fresh upload, within a 90-second window, and name the serving and newest versions on a timeout.
12
+ - Every Cloudflare list read shares one pagination reader; an incomplete list stops with `provider-incomplete-pagination` instead of treating a resource as absent. Environment removal detaches queue consumers before deleting queues and confirms their absence.
13
+
14
+ ### Upgrade notes
15
+
16
+ - Redeploy the hosted demo (`rer deploy --demo`) once to apply the hour-long rollout grace and the doubled provider limit. The deploy that first sets the grace may itself still replace live demos, so run it when no visitor is mid-demo.
17
+ - Add `"ownerEmail"` to `deploy-demo.json` for a plausible owner address on demo screens.
18
+
19
+ ## 0.2.23
20
+
21
+ - Managed mail (`rer` provider) works from Cloudflare Workers. Mail transport always fetches with `redirect: 'manual'`, because Workers reject `redirect: 'error'`, which made every relay send end as `transport_uncertain` without a request. A relay 3xx is never followed and is reported as `rejected` (`provider_redirected`).
22
+ - The `rer` relay adapter accepts `Auto-Submitted: auto-generated`, which Base's sign-in and invitation mail sets, and does not transmit it: the platform relay sets it on every message. It maps `List-Unsubscribe` and one-click `List-Unsubscribe-Post` to the relay's `listUnsubscribe` and `listUnsubscribePost` fields. Values the relay would refuse are refused before sending, and every other header is still refused.
23
+
24
+ ### Upgrade notes
25
+
26
+ - Mail transport now passes `redirect: 'manual'` to an injected `fetch`. A seed that wrapped fetch for the `rer` relay to get around the Workers redirect error must remove that wrapper when it refreshes `modules/mail` or pins 0.2.23. A wrapper that insists on `redirect: 'error'` (as Spool's `src/auth/mail-fetch.server.mjs` does) would turn every send into `uncertain`. A seed that dropped `Auto-Submitted` for the relay can send it again.
27
+
3
28
  ## 0.2.21
4
29
 
5
30
  - Demo removal retries transient Cloudflare provider failures while preserving the resource ownership checks.
@@ -27,9 +27,14 @@ Other Cloudflare modules have no admitted host adapters; raw sockets would also
27
27
  bypass the host's routed fetch egress. Native `email()` has no configured host
28
28
  delivery, `caches.default` has no declared container cache contract, and the host
29
29
  disables request CF metadata (`cf: false`). The module import rule admits native
30
- ES module loading, not arbitrary calls carrying module strings. Admitting
31
- `WebSocketPair` does not add HTTP upgrade transport or qualify a complete live
32
- WebSocket flow through the container host.
30
+ ES module loading, not arbitrary calls carrying module strings.
31
+
32
+ The host forwards WebSocket upgrades through the same ingress and app session
33
+ checks as HTTP. An app response with status 101 and a `WebSocketPair` is bridged
34
+ in both directions, preserving text and binary messages, selected protocols,
35
+ cookies and close codes. Refused upgrades retain their HTTP response; other
36
+ upgrade protocols receive 400. Hosted demo routing selects the visitor's own
37
+ container before forwarding the upgrade, including on declared secondary hosts.
33
38
 
34
39
  The workerd source boundary permits Durable Object definitions, including export
35
40
  aliases and indirect inheritance. Unbound definitions create no namespace. The
@@ -14,7 +14,7 @@ export class D1 {
14
14
  if(message.started){pending.timer=setTimeout(()=>{void this.worker.terminate();this.fail(new Error('D1_ERROR: query timed out: SQLITE_INTERRUPT'));},30000);return;}
15
15
  clearTimeout(pending.timer);this.pending.delete(message.id);message.error?pending.reject(new Error(message.error)):pending.resolve(message.result);
16
16
  });
17
- this.worker.on('error',cause=>this.fail(cause));this.worker.on('exit',code=>{this.worker=null;if(this.pending.size)this.fail(new Error('D1_ERROR: database worker stopped'));});
17
+ this.worker.on('error',cause=>this.fail(cause));this.worker.on('exit',()=>{this.worker=null;if(this.pending.size)this.fail(new Error('D1_ERROR: database worker stopped'));});
18
18
  }
19
19
  fail(cause){for(const pending of this.pending.values()){clearTimeout(pending.timer);pending.reject(cause);}this.pending.clear();}
20
20
  call(operation,statements,sql){if(!this.worker)this.start();const id=++this.next;return new Promise((resolve,reject)=>{this.pending.set(id,{resolve,reject});this.worker.postMessage({id,operation,statements,sql});});}
@@ -85,7 +85,7 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
85
85
  }
86
86
  const base = resolve(import.meta.dirname,'../..');
87
87
  for (const path of ['modules/container','modules/portability','modules/d1-transport','modules/deploy-kit','cli/scheduled.mjs','cli/jsonc.mjs','modules/integrations/core/public-address.ts']) { await mkdir(join(output,'runtime',path,'..'),{recursive:true}); await cp(join(base,path),join(output,'runtime',path),{recursive:true,filter:path => !path.includes('/tests/')}); }
88
- const dependencies = engine === 'workerd' ? { miniflare:'5.20260907.0-alpha' } : {};
88
+ const dependencies = { ws:'8.21.0', ...(engine === 'workerd' ? { miniflare:'5.20260907.0-alpha' } : {}) };
89
89
  await writeFile(join(output,'runtime/package.json'),JSON.stringify({private:true,type:'module',dependencies}));
90
90
  await writeFile(join(output,'Dockerfile'),`FROM node:26.8.1-bookworm-slim\nRUN apt-get update && apt-get install -y --no-install-recommends util-linux ca-certificates && apt-get clean\nRUN mkdir -p /private /archive\nWORKDIR /runtime\nCOPY runtime/package.json ./package.json\nRUN npm install --omit=dev --no-audit --no-fund\nCOPY runtime/ /runtime/\nCOPY app/ /app/\nENV NODE_ENV=production PORT=8080 WRANGLER_SEND_METRICS=false\nEXPOSE 8080\nVOLUME /data\nENTRYPOINT ["sh", "/runtime/modules/container/entrypoint.sh"]\n`);
91
91
  return { output,manifest };
@@ -3,13 +3,14 @@ import { readFile, mkdir } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { recordVolumeOwner } from './lock.mjs';
5
5
  import { incoming, outgoing } from './ingress.mjs';
6
+ import { attachWebSockets } from './websockets.mjs';
6
7
  import { parseCron, cronMatches } from '../../cli/scheduled.mjs';
7
8
  import { superviseRunner } from './runner.mjs';
8
9
  export async function startHost({ root = '/app', data = '/data', settings = process.env, port = Number(process.env.PORT ?? 8080), edge, engineVersion = process.version, automaticTicks=true, runnerEnabled=true } = {}) {
9
10
  await mkdir(data, { recursive:true });
10
11
  const manifest = JSON.parse(await readFile(join(root, 'container.json'), 'utf8'));
11
12
  const release = await recordVolumeOwner(data);
12
- let engine, server, timer, idleTimer, runner, closing, lastMinute = -1, lastRequest=Date.now();
13
+ let engine, server, timer, idleTimer, runner, closing, closeWebSockets, lastMinute = -1, lastRequest=Date.now();
13
14
  try {
14
15
  const origins = settings.RER_INGRESS_ORIGINS === undefined ? undefined : JSON.parse(settings.RER_INGRESS_ORIGINS);
15
16
  if (origins !== undefined && (!Array.isArray(origins) || origins.some(value => { try { const url = new URL(value); return typeof value !== 'string' || url.protocol !== 'https:' || url.origin !== value; } catch { return true; } }))) throw new Error('Invalid ingress origins');
@@ -17,10 +18,11 @@ export async function startHost({ root = '/app', data = '/data', settings = proc
17
18
  engine = await create({ root,data,manifest,settings,edge });
18
19
  const schedules = (manifest.config.triggers?.crons ?? []).map(cron => [cron,parseCron(cron)]);
19
20
  const tick = async time => { for (const [cron, expression] of schedules) if (cronMatches(expression, new Date(time))) await engine.scheduled({ cron,scheduledTime:time }); await engine.drain(); };
21
+ const requestFrom = req => incoming(req, { trustedProxy:settings.TRUSTED_PROXY, origin:settings.RER_INGRESS_ORIGIN, origins, maxRequestBytes:manifest.maxRequestBytes });
20
22
  server = createServer(async (req, res) => {
21
23
  try {
22
24
  lastRequest=Date.now();
23
- const request = await incoming(req, { trustedProxy:settings.TRUSTED_PROXY, origin:settings.RER_INGRESS_ORIGIN, origins, maxRequestBytes:manifest.maxRequestBytes });
25
+ const request = await requestFrom(req);
24
26
  let response = await engine.fetch(request);
25
27
  if (new URL(request.url).pathname === '/health' && response.ok) {
26
28
  const body = await response.json(); const deadJobs = engine.dead();
@@ -29,14 +31,15 @@ export async function startHost({ root = '/app', data = '/data', settings = proc
29
31
  outgoing(response, res);
30
32
  } catch (cause) { res.statusCode = cause.status ?? 500; res.end('Container request failed'); console.error('Container request failed:', cause.name); }
31
33
  });
34
+ closeWebSockets = attachWebSockets(server, { engine, incoming:requestFrom, activity:() => { lastRequest=Date.now(); } });
32
35
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port,'0.0.0.0',resolve); });
33
36
  let ticking=false;
34
37
  if(automaticTicks){timer = setInterval(async () => { if(ticking)return;ticking=true;const minute = Math.floor(Date.now()/60000); try { if (minute !== lastMinute) { lastMinute = minute; await tick(minute * 60000); } else await engine.drain(); } catch { console.error('Container scheduled event failed'); }finally{ticking=false;} },1000); timer.unref();}
35
- const close = () => closing ??= (async () => { clearInterval(timer); clearInterval(idleTimer); await runner?.close(); await new Promise(resolve => server.close(resolve)); await engine.close(); await release(); })();
38
+ const close = () => closing ??= (async () => { clearInterval(timer); clearInterval(idleTimer); await runner?.close(); closeWebSockets(); await new Promise(resolve => server.close(resolve)); await engine.close(); await release(); })();
36
39
  const idle=Number(settings.RER_CONTAINER_IDLE_SECONDS);if(Number.isFinite(idle)&&idle>0){idleTimer=setInterval(()=>{if(Date.now()-lastRequest>=idle*1000)void close();},Math.min(1000,idle*1000));idleTimer.unref();}
37
40
  if(runnerEnabled)runner=superviseRunner({root,manifest,settings,failed(){console.error('Required container runner stopped');void close().finally(()=>{process.exitCode=1;});}});
38
41
  return { engine,manifest,server,tick,close };
39
- } catch (cause) { clearInterval(timer); clearInterval(idleTimer); await runner?.close(); server?.close(); await engine?.close(); await release(); throw cause; }
42
+ } catch (cause) { clearInterval(timer); clearInterval(idleTimer); await runner?.close(); closeWebSockets?.(); server?.close(); await engine?.close(); await release(); throw cause; }
40
43
  }
41
44
  if (process.argv[1] === import.meta.filename) {
42
45
  let host;
@@ -1,5 +1,4 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
2
  import { DatabaseSync } from 'node:sqlite';
4
3
  import { D1 } from './adapters/d1.mjs';
5
4
  import { Objects } from './adapters/objects.mjs';
@@ -0,0 +1,54 @@
1
+ import { ServerResponse } from 'node:http';
2
+ import { WebSocketServer } from 'ws';
3
+ import { outgoing } from './ingress.mjs';
4
+
5
+ // Keep the Worker response's cookies and selected protocol. ws owns the wire
6
+ // handshake (including key validation) and never negotiates compression here.
7
+ const handshakeHeaders = new Set(['connection', 'upgrade', 'sec-websocket-accept', 'sec-websocket-extensions', 'content-length', 'transfer-encoding']);
8
+ export function attachWebSockets(server, { engine, incoming, activity }) {
9
+ const responses = new WeakMap(), sockets = new Set();
10
+ const bridge = new WebSocketServer({ noServer:true, handleProtocols:() => false });
11
+ bridge.on('headers', (headers, req) => {
12
+ const response = responses.get(req); responses.delete(req);
13
+ for (const [name, value] of response.headers) if (!handshakeHeaders.has(name) && name !== 'set-cookie') headers.push(`${name}: ${value}`);
14
+ for (const cookie of response.headers.getSetCookie()) headers.push(`set-cookie: ${cookie}`);
15
+ });
16
+ const refuse = (req, socket, response) => {
17
+ const res = new ServerResponse(req); res.assignSocket(socket);
18
+ res.shouldKeepAlive = false;
19
+ const headers = new Headers(response.headers); headers.set('connection', 'close');
20
+ outgoing(new Response(response.body, { status:response.status, headers }), res);
21
+ };
22
+ server.on('upgrade', async (req, socket, head) => {
23
+ sockets.add(socket); socket.once('close', () => sockets.delete(socket));
24
+ // A peer may disappear while ingress or the Worker is still dispatching.
25
+ socket.on('error', () => socket.destroy());
26
+ let pair, coupled = false;
27
+ const abandon = () => { if (pair && !coupled) { try { pair.accept(); pair.close(1001, 'Client disconnected'); } catch {} } };
28
+ socket.once('close', abandon);
29
+ try {
30
+ activity();
31
+ if (req.headers.upgrade?.toLowerCase() !== 'websocket') return refuse(req, socket, new Response('Unsupported upgrade', { status:400 }));
32
+ const request = await incoming(req); request.headers.set('upgrade', 'websocket');
33
+ const response = await engine.fetch(request);
34
+ pair = response.webSocket;
35
+ if (socket.destroyed) { abandon(); return; }
36
+ if (response.status !== 101) return refuse(req, socket, response);
37
+ if (!pair || !engine.coupleWebSocket) return refuse(req, socket, new Response('Invalid WebSocket response', { status:502 }));
38
+ responses.set(req, response);
39
+ bridge.handleUpgrade(req, socket, head, ws => {
40
+ coupled = true;
41
+ ws.on('message', activity); ws.on('ping', activity); ws.on('pong', activity);
42
+ pair.addEventListener('message', activity);
43
+ // Miniflare's coupling preserves text/binary messages, queued app sends,
44
+ // close codes and abrupt disconnects on its returned WebSocketPair.
45
+ engine.coupleWebSocket(ws, pair).catch(() => { ws.terminate(); try { pair.close(1011, 'Bridge failed'); } catch {} });
46
+ });
47
+ } catch (cause) {
48
+ abandon();
49
+ if (!socket.destroyed) refuse(req, socket, new Response('Container upgrade failed', { status:cause.status ?? 500 }));
50
+ console.error('Container upgrade failed:', cause.name);
51
+ }
52
+ });
53
+ return () => { for (const socket of sockets) socket.destroy(); bridge.close(); };
54
+ }
@@ -1,6 +1,6 @@
1
- import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
1
+ import { Miniflare, convertV4MiniflareOptions, coupleWebSocket } from 'miniflare';
2
2
  import { readdir } from 'node:fs/promises';
3
- import { join, relative } from 'node:path';
3
+ import { join } from 'node:path';
4
4
  import { rootCertificates } from 'node:tls';
5
5
  import { ensurePortabilitySchema } from './portability-schema.mjs';
6
6
  import { migrate } from './migrations.mjs';
@@ -27,7 +27,7 @@ export async function workerEngine({ root, data, manifest, settings, edge }) {
27
27
  for (const [binding, plan] of Object.entries(manifest.migrations)) { const db = await mf.getD1Database(binding, 'app'); databases[binding] = db; await migrate(db, plan); await ensurePortabilitySchema(db, manifest.portabilityMigrations); }
28
28
  for (const bucket of config.r2_buckets ?? []) objects[bucket.binding] = await mf.getR2Bucket(bucket.binding, 'app');
29
29
  const worker = await mf.getWorker('app');
30
- return { mf, databases, objects, app:worker,
30
+ return { mf, databases, objects, app:worker, coupleWebSocket,
31
31
  fetch(request) { const headers = new Headers(request.headers); headers.set('x-rer-original-url', request.url); return mf.dispatchFetch(request.url, { method:request.method,headers,body:request.body,duplex:'half',redirect:'manual' }); },
32
32
  scheduled:event => worker.scheduled(event), async drain() {}, dead:() => 0, close:() => mf.dispose(),
33
33
  };
@@ -18,6 +18,10 @@ Production build/deploy refuses that setting; ordinary builds keep real effects.
18
18
  provider response should supply its own exact success shape this way.
19
19
  - Mail in local dev and demo is silently suppressed. There is no outbox or
20
20
  blocked-send UI. Logs contain only the mocked request's method and host.
21
+ - The configured owner's authenticated session supplies step-up proof inside
22
+ its own demo, including owner invitations and role changes. The demo guard
23
+ must be active; ordinary hosted instances still require real proof. Each
24
+ visitor's separate session secret and store reject other visitors' cookies.
21
25
  - `seed(env, { ownerEmail, now })` runs once after the owner exists and must
22
26
  be idempotent. Its only table is the demo's throwaway `rer_demo` marker.
23
27
  - Base adds ` Demo` to the document title, including client-side navigation.
@@ -1,23 +1,26 @@
1
1
  import { allow, sha256 } from '../operator-auth/csp.mjs';
2
2
 
3
3
  // CSS leaves React's text alone during hydration. The title observer handles
4
- // client-side route changes, whose head manager writes a fresh title.
4
+ // client-side route changes, whose head manager writes a fresh title. The script
5
+ // is one constant text (so one constant CSP hash); the suffix reaches it as data
6
+ // on the label's style element, never as code.
7
+ const SCRIPT = "(()=>{const suffix=document.querySelector('style[data-rer-label]').dataset.rerLabel,update=()=>{const title=document.title.replace(/ (?:Demo|Dev)$/,'')+' '+suffix;if(document.title!==title)document.title=title};update();new MutationObserver(update).observe(document.head,{childList:true,subtree:true,characterData:true})})()";
8
+
5
9
  export async function decorateLabel(response, mode) {
6
10
  if (!response.body || !response.headers.get('content-type')?.toLowerCase().startsWith('text/html')) return response;
7
11
  const suffix = mode === 'Demo' ? 'Demo' : 'Dev';
8
12
  const style = `[data-rer-name]::after{content:" ${suffix}"}`;
9
- const script = `(()=>{const suffix=${JSON.stringify(suffix)},update=()=>{const title=document.title.replace(/ (?:Demo|Dev)$/,'')+' '+suffix;if(document.title!==title)document.title=title};update();new MutationObserver(update).observe(document.head,{childList:true,subtree:true,characterData:true})})()`;
10
13
  const html = await response.text();
11
14
  if (html.includes('data-rer-label=')) return new Response(html, response);
12
15
  const headers = new Headers(response.headers);
13
16
  let policy = headers.get('content-security-policy');
14
17
  if (policy) {
15
18
  policy = allow(policy, 'style-src', await sha256(style));
16
- headers.set('content-security-policy', allow(policy, 'script-src', await sha256(script)));
19
+ headers.set('content-security-policy', allow(policy, 'script-src', await sha256(SCRIPT)));
17
20
  }
18
21
  headers.delete('content-length');
19
22
  headers.delete('etag');
20
- const addition = `<style data-rer-label="${suffix}">${style}</style><script>${script}</script>`;
23
+ const addition = `<style data-rer-label="${suffix}">${style}</style><script>${SCRIPT}</script>`;
21
24
  const titled = html.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title>)/i, (_, open, title, close) => `${open}${title.replace(/ (?:Demo|Dev)$/, '')} ${suffix}${close}`);
22
25
  const body = /<\/head\s*>/i.test(titled) ? titled.replace(/<\/head\s*>/i, `${addition}</head>`) : addition + titled;
23
26
  return new Response(body, { status: response.status, statusText: response.statusText, headers });
@@ -7,7 +7,7 @@ export async function effectSuccess(request) {
7
7
  if (host === 'api.resend.com') return json({ id });
8
8
  if (host === 'api.twilio.com') return json({ sid: `SM${crypto.randomUUID().replaceAll('-', '')}`, status: 'queued', error_code: null, error_message: null }, 201);
9
9
  if (host === 'api.postmarkapp.com') return json({ ErrorCode: 0, Message: 'OK', MessageID: id, SubmittedAt: new Date().toISOString() });
10
- if (host.endsWith('mailgun.net')) return json({ id: `<${id}@demo.invalid>`, message: 'Queued. Thank you.' });
10
+ if (host === 'mailgun.net' || host.endsWith('.mailgun.net')) return json({ id: `<${id}@demo.invalid>`, message: 'Queued. Thank you.' });
11
11
  if (host === 'slack.com') return json({ ok: true, channel: 'demo', ts: `${Math.floor(Date.now() / 1000)}.000001`, message: { type: 'message', text: 'Message sent' } });
12
12
  if (host === 'hooks.slack.com' || host.endsWith('.webhook.office.com') || host.endsWith('.logic.azure.com')) return new Response(host === 'hooks.slack.com' ? 'ok' : '1');
13
13
  if (host === 'api.stripe.com') {
@@ -3,7 +3,8 @@
3
3
  The front Worker `rer deploy --demo` deploys at `demo.<domain>` for a seed
4
4
  that adopted demo mode (`withDemo`, export/DEMO.md). `plan.mjs` turns `deploy-demo.json`
5
5
  (optionally `instanceType`, one of Cloudflare's predefined Container instance
6
- types, `basic` unless set) into the Worker's Wrangler configuration; the CLI (`cli/demo-host.mjs`) writes
6
+ types, `basic` unless set, and `ownerEmail`, the address the demo's owner signs
7
+ in as, `owner@demo.invalid` unless set) into the Worker's Wrangler configuration; the CLI (`cli/demo-host.mjs`) writes
7
8
  it with these files and the seed's container image folder (workerd engine) to
8
9
  `.rer/demo-host/` and runs `wrangler deploy` there. Declared
9
10
  `container.hostVariables` resolve from demo settings to the primary hostname or
@@ -20,14 +21,20 @@ start page.
20
21
  202 progress and a `rer_demo` cookie; `GET /__demo/status` polls that same
21
22
  copy until it can relay the owner claim's 303 (JSON `{ location }` for the
22
23
  page script) and session cookie. Every external admission step is bounded:
23
- the start answers within 12 seconds, and status within two seconds. A request
24
+ the start answers within 12 seconds. A new copy that takes over two seconds
25
+ to answer is still a pending start, not a failure. Each status request is
26
+ held (at most 1.5 seconds) until the start changes, so the page learns of the
27
+ sign-in at once; a slow status read answers pending. Each admission logs
28
+ `demo_admitted` with the request's user agent and network owner, so a held
29
+ place can be joined to whoever started it (automated browsers pass
30
+ Turnstile's always-pass testing keys on test hosts). A request
24
31
  with that cookie goes to the visitor's Durable Object; nothing else reaches
25
32
  a container.
26
33
  - `container.mjs`: `DemoContainer`, one per visitor (`newUniqueId`, checked
27
34
  with `idFromString`). It starts the container with public internet enabled,
28
35
  `RER_DEMO=1`, the fixed origin (`RER_INGRESS_ORIGIN` and the seed's origin
29
36
  variable), fresh `SESSION_SECRET` and `SETUP_TOKEN`,
30
- `OWNER_EMAIL=owner@demo.invalid` and the owner claim's issuer, installation
37
+ `OWNER_EMAIL` (`DEMO_OWNER_EMAIL`, else `owner@demo.invalid`) and the owner claim's issuer, installation
31
38
  id and public key; waits for `/health`; and posts a five-minute ES256 claim
32
39
  (`claim.mjs`) to `/auth/owner-claim`. Its alarm ends the demo at its hour or
33
40
  after 15 idle minutes: `destroy()`, `deleteAll()` and the place released. A
@@ -45,7 +52,8 @@ start page.
45
52
  storage transaction, excluding diagnostics and expired rows. A lost start
46
53
  handoff expires after one minute; a successful claim extends the reservation
47
54
  to the demo's end. Refusals log the held ids as SHA-256 fingerprints (also
48
- logged with each start's correlation), never visitor bearer cookies.
55
+ logged with each start's correlation), never visitor bearer cookies. The
56
+ refusal's response correlation also identifies that held-place snapshot.
49
57
  - `image.mjs`, `prepare.mjs`, `template.mjs`, `entrypoint.sh`: the demo image
50
58
  build migrates fresh workerd persistence with the packaged engine and closes
51
59
  it into `/template`, with no network and no app requests. The entrypoint
@@ -81,7 +89,9 @@ Chromium (default-seed's Playwright) through waiting, failure, Try again,
81
89
  working and the signed-in landing. The end-to-end proof (`wrangler dev` with Docker)
82
90
  is in DEMO.md.
83
91
 
84
- Startup has a 45-second budget, with a separate five-second HTTP probe limit.
92
+ Startup has a 45-second boot budget, with a separate five-second HTTP probe
93
+ limit; waiting for Cloudflare to place the container renews it, up to 90
94
+ seconds from the start (see placement below).
85
95
  The Durable Object owns that work and cleanup while the page polls; a browser
86
96
  that leaves cannot abandon it. Retrying a pending copy resumes the same
87
97
  reservation; an explicit Try again cancels it before creating a replacement. Failed starts release their place before returning the retry state, retain the bounded operator diagnostic and destroy
@@ -91,7 +101,9 @@ correlation. Every attempt logs its timestamp, elapsed time, duration and
91
101
  HTTP status or fixed error category, including successful probes. Exit records
92
102
  include the numeric platform exit code when supplied. A separate random
93
103
  `x-rer-demo-correlation` response header joins these events without disclosing
94
- the visitor's bearer cookie. Worker observability also enables the platform's
104
+ the visitor's bearer cookie. Early refusals, including capacity, rate-limit,
105
+ Origin and human-check refusals, also carry a correlation and log their status.
106
+ Worker observability also enables the platform's
95
107
  private Container stdout/stderr logs; historical stdout is not exposed by the
96
108
  Container lifecycle API. Read those logs with an account principal granted
97
109
  Workers Observability Write, and filter by the application and boot interval.
@@ -113,12 +125,25 @@ container is already stopped); a terminal start failure releases it immediately.
113
125
  A cleanup failure is logged separately and cannot replace the startup failure
114
126
  shown to the visitor.
115
127
 
116
- Cloudflare may briefly report that it has no prepared container instance even
117
- when the application is below `max_instances`. `placement.mjs` keeps the same
128
+ Cloudflare keeps a small prepared pool per application (7 instances on fresh
129
+ test hosts, measured in October 2026, whatever `max_instances` is) and places a
130
+ new instance only on demand: a start beyond the pool gets "no container instance
131
+ that can be provided" until Cloudflare has placed one (16 to 37 seconds
132
+ measured, after which boot was normal). `placement.mjs` keeps the same
118
133
  reservation and launch options, requests placement again only for that specific
119
- provider response, and stays within the original startup deadline. Boot, health
134
+ provider response, and renews the 45-second boot budget after each wait, up to
135
+ 90 seconds from the start, extending the reservation to match. Boot, health
120
136
  and claim errors are not retried. Placement exhaustion answers with the normal
121
137
  failed-start retry state and releases the reservation; the capacity notice is
122
138
  reserved for actual reservation exhaustion. Cleanup keeps only that terminal
123
139
  answer and correlation for one minute, so a status poll after object recovery
124
140
  still receives the right answer; its alarm then deletes the remaining metadata.
141
+
142
+ `DemoCapacity` alone admits visitors (`maxInstances` live demos). The Container
143
+ application's own `max_instances` is twice that, so instances Cloudflare still
144
+ counts after a demo ends or a start fails never refuse a place admission gave.
145
+ Its `rollout_active_grace_period` is an hour, a demo's longest life: a redeploy
146
+ that rolls the application out (a new image, instance type or limit) replaces
147
+ idle prepared instances at once and leaves every live demo running until it
148
+ ends. With no grace period a rollout replaced live demos' containers within two
149
+ minutes, and their visitors saw "This demo has ended".
@@ -18,7 +18,7 @@ export class DemoCapacity extends DurableObject {
18
18
  }
19
19
  async alarm() { await this.ctx.storage.deleteAll(); }
20
20
 
21
- async acquire(id, ends, max) {
21
+ async acquire(id, ends, max, correlation) {
22
22
  return this.ctx.storage.transaction(async storage => {
23
23
  const now = Date.now(), places = [...await storage.list()]
24
24
  .filter(([key, until]) => /^[0-9a-f]{64}$/.test(key) && typeof until === 'number');
@@ -28,7 +28,7 @@ export class DemoCapacity extends DurableObject {
28
28
  if (held.length >= max) {
29
29
  // Fingerprints identify held reservations without logging bearer cookies.
30
30
  const heldIds = await Promise.all(held.map(async ([key, until]) => ({ id: await fingerprint(key), ends: until })));
31
- console.log(JSON.stringify({ event: 'demo_capacity_refused', max, held: heldIds }));
31
+ console.log(JSON.stringify({ event: 'demo_capacity_refused', correlation, max, held: heldIds }));
32
32
  return false;
33
33
  }
34
34
  await storage.put(id, ends);
@@ -52,10 +52,12 @@ export class DemoContainer extends DurableObject {
52
52
  diagnostic() { return { correlation: this.correlation, tail: this.records, stdout: 'Provider container logs; not exposed by the lifecycle API.' }; }
53
53
  idle = IDLE;
54
54
  startTimeout = 45_000;
55
+ placementTimeout = 90_000;
55
56
  probeTimeout = 5000;
56
57
  cleanupRetry = 30_000;
57
58
  now() { return Date.now(); }
58
59
  get container() { return this.ctx.container; }
60
+ get owner() { return this.env.DEMO_OWNER_EMAIL || OWNER; }
59
61
  port() { return this.container.getTcpPort(PORT); }
60
62
 
61
63
  async begin(options) {
@@ -66,31 +68,41 @@ export class DemoContainer extends DurableObject {
66
68
  return this.status();
67
69
  }
68
70
 
69
- async status() {
70
- const startup = await this.ctx.storage.get('startup');
71
+ /** The start's state; `wait` holds a pending answer until it changes (at most 1.5 s), so the page learns of the sign-in without its own polling delay.
72
+ * A poll can also reach a new copy before its slow begin has landed. */
73
+ async status(wait = 0) {
74
+ const until = Date.now() + Math.min(wait, 1500);
75
+ let startup = await this.ctx.storage.get('startup');
76
+ while ((!startup || (startup.phase === 'starting' && !startup.failure)) && Date.now() < until) {
77
+ await new Promise(resolve => setTimeout(resolve, 100));
78
+ startup = await this.ctx.storage.get('startup');
79
+ }
71
80
  return { ...(startup ?? { phase: 'failed' }), correlation: this.correlation };
72
81
  }
73
82
 
74
83
  /** Start the container, wait for /health, claim the owner; returns the claim's 303. */
75
84
  async start({ origin, originVar, ends, endsLocal, settings, correlation }) {
76
85
  this.correlation = correlation; this.started = this.now(); this.stopped = false; this.cancelled = false;
77
- const deadline = this.started + this.startTimeout;
86
+ let deadline = this.started + this.startTimeout;
78
87
  const id = this.ctx.id.toString(), keys = await claimKeys(), now = this.now();
79
88
  await this.ctx.storage.put({ ends, seen: now, correlation, started: this.started, startDeadline: deadline });
80
89
  report(correlation, this.started, 'start');
81
90
  if (this.stopped) throw new Error('container-stopped');
82
- await placeContainer(this, { enableInternet: true, env: { ...settings, RER_DEMO: '1', [originVar]: origin, RER_INGRESS_ORIGIN: origin, RER_INGRESS_ORIGINS: JSON.stringify([origin, ...JSON.parse(this.env.DEMO_SECONDARY_ORIGINS ?? '[]')]),
83
- SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: OWNER, RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
91
+ deadline = await placeContainer(this, { enableInternet: true, env: { ...settings, RER_DEMO: '1', [originVar]: origin, RER_INGRESS_ORIGIN: origin, RER_INGRESS_ORIGINS: JSON.stringify([origin, ...JSON.parse(this.env.DEMO_SECONDARY_ORIGINS ?? '[]')]),
92
+ SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: this.owner, RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
84
93
  RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal } }, deadline);
85
94
  await this.container.setInactivityTimeout(this.idle);
86
95
  await this.ctx.storage.setAlarm(deadline);
87
- const token = await signClaim(keys, { origin, installationId: id, email: OWNER, now: this.now() });
96
+ const token = await signClaim(keys, { origin, installationId: id, email: this.owner, now: this.now() });
97
+ // Hold the place to the demo's end while the owner claim runs; a failed claim releases it in cleanup.
98
+ const held = bounded(this.env.CAPACITY.get(this.env.CAPACITY.idFromName('capacity')).extend(id, ends), 2000).catch(() => false);
88
99
  const claimed = await boundedFetch(this.port(), 'http://container/auth/owner-claim', { method: 'POST', redirect: 'manual',
89
100
  headers: { origin, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ token }) }, Math.max(1, Math.min(10_000, deadline - this.now())));
90
101
  void claimed.body?.cancel().catch(() => {});
91
102
  this.record('claim', { status: claimed.status });
92
103
  if (this.stopped) throw new Error('container-stopped');
93
104
  if (claimed.status !== 303) throw new Error(`owner claim answered ${claimed.status}`);
105
+ if (!await held) throw new Error('start-reservation-expired');
94
106
  await this.ctx.storage.put('seen', this.now());
95
107
  await this.ctx.storage.setAlarm(Math.min(ends, this.now() + this.idle));
96
108
  return { location: claimed.headers.get('location'), cookies: claimed.headers.getSetCookie() };
@@ -109,7 +121,7 @@ export class DemoContainer extends DurableObject {
109
121
  } catch (error) {
110
122
  this.record('health', { attempt: ++attempt, durationMs: this.now() - probe, error: category(error) });
111
123
  }
112
- await new Promise(resolve => setTimeout(resolve, Math.min(250, Math.max(0, deadline - this.now()))));
124
+ await new Promise(resolve => setTimeout(resolve, Math.min(100, Math.max(0, deadline - this.now()))));
113
125
  }
114
126
  throw new Error('health-deadline');
115
127
  }
@@ -1,8 +1,15 @@
1
- // Cloudflare can exhaust its prepared instances before reaching max_instances.
2
- // Keep this visitor's reservation while that pool grows. Only the provider's
3
- // explicit no-instance response permits another placement attempt; boot, health
4
- // and claim failures still terminate the start.
1
+ import { bounded } from './diagnostics.mjs';
2
+
3
+ // Cloudflare keeps a small prepared pool per application (7 instances measured
4
+ // on fresh hosts) and prepares more only on demand: a start beyond the pool
5
+ // waits while Cloudflare places a new instance (16-37 s measured), then boots
6
+ // normally. Keep this visitor's reservation through that wait. Only the
7
+ // provider's explicit no-instance response permits another placement attempt,
8
+ // and it renews the boot budget up to placementTimeout from the start; boot,
9
+ // health and claim failures still terminate the start. Returns the deadline the
10
+ // placed container must become healthy and claimed by.
5
11
  export async function placeContainer(demo, options, deadline) {
12
+ const limit = demo.started + demo.placementTimeout, capacity = demo.env.CAPACITY.get(demo.env.CAPACITY.idFromName('capacity'));
6
13
  let attempt = 0;
7
14
  while (Date.now() < deadline && !demo.cancelled) {
8
15
  demo.stopped = false;
@@ -12,10 +19,17 @@ export async function placeContainer(demo, options, deadline) {
12
19
  await demo.ctx.storage.setAlarm(deadline);
13
20
  try {
14
21
  await demo.healthy(deadline);
15
- return;
22
+ return deadline;
16
23
  } catch (error) {
17
24
  if (demo.cancelled || demo.stopReason !== 'placement-unavailable') throw error;
18
25
  demo.record('placement', { attempt: ++attempt, outcome: 'waiting' });
26
+ const renewed = Math.min(limit, Date.now() + demo.startTimeout);
27
+ if (renewed > deadline) {
28
+ // The reservation outlives the renewed budget, or the place is no longer this visitor's.
29
+ if (!await bounded(capacity.extend(demo.ctx.id.toString(), renewed + 15_000), 2000)) throw new Error('start-reservation-expired');
30
+ deadline = renewed;
31
+ await demo.ctx.storage.put('startDeadline', deadline);
32
+ }
19
33
  await new Promise(resolve => setTimeout(resolve, Math.min(1000, Math.max(0, deadline - Date.now()))));
20
34
  }
21
35
  }
@@ -18,29 +18,31 @@ export const INSTANCE_TYPES = ['lite', 'basic', 'standard-1', 'standard-2', 'sta
18
18
  /**
19
19
  * deploy-demo.json: `{ "version": 1, "domain": "run-lamp.com", "name": "Lamp" }`, plus optionally
20
20
  * `maxInstances` (concurrent demos, default 10), `instanceType` (one of INSTANCE_TYPES, default
21
- * "basic") and `settings`, the seed's plain demo settings (such as MAIL_PROVIDER: "development").
21
+ * "basic"), `ownerEmail` (the address the demo's owner signs in as, default owner@demo.invalid) and `settings`, the seed's plain demo settings (such as MAIL_PROVIDER: "development").
22
22
  * Settings never carry secrets or what the front sets. The app declaration's
23
23
  * container.hostVariables select hostname settings: the primary demo hostname
24
24
  * or its descendants, routed through the same visitor isolation.
25
25
  */
26
26
  export function demoDeclaration(value, originVar) {
27
- assert(value && typeof value === 'object' && !Array.isArray(value) && value.version === 1 && Object.keys(value).every(key => ['version', 'domain', 'name', 'maxInstances', 'instanceType', 'settings'].includes(key)), 'invalid-demo-declaration');
27
+ assert(value && typeof value === 'object' && !Array.isArray(value) && value.version === 1 && Object.keys(value).every(key => ['version', 'domain', 'name', 'maxInstances', 'instanceType', 'ownerEmail', 'settings'].includes(key)), 'invalid-demo-declaration');
28
28
  siteDeclaration({ version: 1, domain: value.domain });
29
29
  assert(typeof value.name === 'string' && value.name.trim() === value.name && value.name.length > 0 && value.name.length <= 60 && !/[\p{Cc}\p{Cf}]/u.test(value.name), 'invalid-demo-name');
30
30
  const maxInstances = value.maxInstances ?? 10;
31
31
  assert(Number.isSafeInteger(maxInstances) && maxInstances >= 1 && maxInstances <= 100, 'invalid-demo-max-instances');
32
32
  const instanceType = value.instanceType ?? 'basic';
33
33
  assert(INSTANCE_TYPES.includes(instanceType), 'invalid-demo-instance-type');
34
+ const ownerEmail = value.ownerEmail;
35
+ assert(ownerEmail === undefined || (typeof ownerEmail === 'string' && ownerEmail.length <= 254 && /^[^\s@<>"]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i.test(ownerEmail)), 'invalid-demo-owner-email');
34
36
  const settings = value.settings ?? {};
35
37
  assert(settings && typeof settings === 'object' && !Array.isArray(settings) && Object.entries(settings).every(([name, setting]) =>
36
38
  /^[A-Z][A-Z0-9_]{0,63}$/.test(name) && !FRONT_SET.test(name) && !SECRET.test(name) && name !== originVar && typeof setting === 'string' && setting.length <= 1024), 'invalid-demo-settings');
37
- return { domain: value.domain, name: value.name, maxInstances, instanceType, settings };
39
+ return { domain: value.domain, name: value.name, maxInstances, instanceType, ownerEmail, settings };
38
40
  }
39
41
 
40
42
  /** The demo Worker's name and its Wrangler configuration; no provider request. */
41
43
  export function demoPlan({ project, environment, compatibilityDate, originVar, hostVariables = [], declaration, turnstileSiteKey }) {
42
44
  assert(/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate ?? '') && /^[A-Z][A-Z0-9_]{0,63}$/.test(originVar ?? ''), 'invalid-plan');
43
- const { domain, name, maxInstances, instanceType, settings } = demoDeclaration(declaration, originVar);
45
+ const { domain, name, maxInstances, instanceType, ownerEmail, settings } = demoDeclaration(declaration, originVar);
44
46
  const worker = `${ownerWorkerName(project, environment)}--demo`, hostname = `demo.${domain}`, container = worker.replace(/-+/g, '-');
45
47
  assert(resourceName(worker), 'owner-name-too-long');
46
48
  assert(Array.isArray(hostVariables) && hostVariables.every(variable => typeof variable === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(variable)), 'invalid-demo-host-variables');
@@ -60,10 +62,13 @@ export function demoPlan({ project, environment, compatibilityDate, originVar, h
60
62
  routes: hostnames.map(pattern => ({ pattern, custom_domain: true })),
61
63
  observability: { enabled: true, head_sampling_rate: 1, logs: { enabled: true, invocation_logs: false } },
62
64
  vars: { DEMO_ORIGIN: `https://${hostname}`, DEMO_SITE: `https://${domain}`, DEMO_NAME: name, DEMO_ORIGIN_VAR: originVar, DEMO_MAX_INSTANCES: String(maxInstances), DEMO_SETTINGS: JSON.stringify(settings), DEMO_SECONDARY_ORIGINS: JSON.stringify(secondaryHosts.map(host => `https://${host}`)),
63
- ...(turnstileSiteKey ? { TURNSTILE_SITE_KEY: turnstileSiteKey } : {}) },
65
+ ...(ownerEmail ? { DEMO_OWNER_EMAIL: ownerEmail } : {}), ...(turnstileSiteKey ? { TURNSTILE_SITE_KEY: turnstileSiteKey } : {}) },
64
66
  durable_objects: { bindings: [{ name: 'DEMO', class_name: 'DemoContainer' }, { name: 'CAPACITY', class_name: 'DemoCapacity' }] },
65
67
  migrations: [{ tag: 'v1', new_sqlite_classes: ['DemoContainer', 'DemoCapacity'] }],
66
- containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type: instanceType }],
68
+ // Admission (DemoCapacity) holds live demos at maxInstances. The provider's
69
+ // own limit keeps headroom for instances it still counts after a demo ends
70
+ // or a start fails, and rollouts leave a live demo (at most an hour old) alone.
71
+ containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances * 2, instance_type: instanceType, rollout_active_grace_period: 3600 }],
67
72
  ratelimits: [{ name: 'STARTS', namespace_id: namespace, simple: { limit: 3, period: 60 } }],
68
73
  };
69
74
  return { worker, hostname, hostnames, container, record: demoRecord({ worker, hostname, hostnames, container }), origin: `https://${hostname}`, maxInstances, instanceType, settings: Object.keys(settings), wrangler };
@@ -33,7 +33,8 @@ async function go(resume=false){
33
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
34
  let result=await response.json().catch(()=>({}));
35
35
  while(response.status===202&&result.pending===true){
36
- await new Promise(resolve=>setTimeout(resolve,500));
36
+ // The server holds each pending answer until the start changes.
37
+ await new Promise(resolve=>setTimeout(resolve,100));
37
38
  if(attempt!==controller)return;
38
39
  response=await fetch('/__demo/status',{headers:{accept:'application/json'},signal:controller.signal});
39
40
  result=await response.json().catch(()=>({}));
@@ -5,11 +5,11 @@ import { fingerprint } from './capacity.mjs';
5
5
  // responses. A dropped browser request cannot abandon cleanup or hold a place
6
6
  // until the demo's hour expires.
7
7
  export async function finishStart(demo, options) {
8
- const { correlation, ends } = options, id = demo.ctx.id.toString();
8
+ const { correlation } = options, id = demo.ctx.id.toString();
9
9
  try {
10
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');
11
+ const result = await bounded(demo.start(options), demo.placementTimeout + 1000);
12
+ if (demo.stopped) throw new Error('container-stopped');
13
13
  await demo.ctx.storage.put('startup', { phase: 'ready', ...result });
14
14
  await demo.ctx.storage.delete('startDeadline');
15
15
  } catch (error) {