@runeditrun/rer 0.2.23 → 0.2.25

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 (77) hide show
  1. package/README.md +16 -7
  2. package/cli/browser-runtime.mjs +65 -0
  3. package/cli/demo-host.mjs +1 -1
  4. package/cli/deploy-claim-request.mjs +5 -4
  5. package/cli/deploy-command.mjs +7 -5
  6. package/cli/deploy-inputs.mjs +2 -1
  7. package/cli/deploy-observation.mjs +20 -2
  8. package/cli/deploy-owner.mjs +12 -7
  9. package/cli/deploy.mjs +19 -6
  10. package/cli/export.mjs +1 -1
  11. package/cli/hydration/browser.mjs +3 -9
  12. package/cli/inspect.mjs +3 -1
  13. package/cli/lifecycle.mjs +4 -1
  14. package/cli/site.mjs +2 -2
  15. package/global/CHANGELOG.md +37 -0
  16. package/global/README.md +16 -7
  17. package/global/browser-runtime.mjs +45 -0
  18. package/global/cli/layout.mjs +8 -4
  19. package/global/main.mjs +13 -3
  20. package/install.sh +56 -3
  21. package/modules/container/README.md +6 -0
  22. package/modules/container/adapters/d1.mjs +1 -1
  23. package/modules/container/build.mjs +2 -1
  24. package/modules/container/image-variables.mjs +27 -0
  25. package/modules/container/transfer.mjs +0 -1
  26. package/modules/container/worker-engine.mjs +1 -1
  27. package/modules/delivery-producer/declarations.mjs +6 -1
  28. package/modules/delivery-producer/mail.mjs +66 -0
  29. package/modules/demo/label.mjs +5 -2
  30. package/modules/demo-host/README.md +29 -7
  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 +27 -8
  37. package/modules/deploy-kit/README.md +41 -6
  38. package/modules/deploy-kit/asset-health.mjs +28 -0
  39. package/modules/deploy-kit/d1-import.mjs +22 -4
  40. package/modules/deploy-kit/diagnostics.mjs +46 -1
  41. package/modules/deploy-kit/health.mjs +2 -23
  42. package/modules/deploy-kit/migration-ledger.mjs +6 -2
  43. package/modules/deploy-kit/migration-retry.mjs +91 -0
  44. package/modules/deploy-kit/migrations.mjs +9 -5
  45. package/modules/deploy-kit/owner-cli.mjs +9 -6
  46. package/modules/deploy-kit/owner-remove.mjs +104 -64
  47. package/modules/deploy-kit/pagination.mjs +99 -0
  48. package/modules/deploy-kit/provider-transport.mjs +28 -5
  49. package/modules/deploy-kit/provider.mjs +38 -75
  50. package/modules/deploy-kit/r2-objects.mjs +6 -17
  51. package/modules/deploy-kit/site-readback.mjs +67 -0
  52. package/modules/deploy-kit/site.mjs +17 -31
  53. package/modules/deploy-kit/uploaded-worker.mjs +9 -3
  54. package/modules/deploy-kit/worker.mjs +5 -2
  55. package/modules/erasure/queue.mjs +0 -2
  56. package/modules/job-queue/cli.mjs +1 -1
  57. package/modules/operator-auth/README.md +10 -2
  58. package/modules/operator-auth/config.mjs +1 -0
  59. package/modules/operator-auth/conformance/presentation.mjs +2 -2
  60. package/modules/operator-auth/identity/email-link/confirmation.mjs +2 -1
  61. package/modules/operator-auth/identity/email-link/expiry.mjs +8 -0
  62. package/modules/operator-auth/identity/email-link/index.mjs +2 -1
  63. package/modules/operator-auth/identity/email-link/message.mjs +3 -2
  64. package/modules/operator-auth/identity/oidc/jwt.mjs +1 -1
  65. package/modules/operator-auth/index.d.mts +2 -0
  66. package/modules/portability/README.md +7 -2
  67. package/modules/portability/bridge.mjs +3 -3
  68. package/modules/portability/catalogue.mjs +1 -1
  69. package/modules/portability/cli-options.mjs +1 -1
  70. package/modules/portability/import-staging.mjs +45 -0
  71. package/modules/portability/import.mjs +8 -8
  72. package/modules/portability/legacy-files.mjs +1 -1
  73. package/modules/portability/legacy-safety.mjs +3 -3
  74. package/modules/portability/payloads.mjs +1 -1
  75. package/modules/portability/storage.mjs +5 -2
  76. package/modules/release/source.mjs +1 -1
  77. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  // Where a user install lives. Data: ${XDG_DATA_HOME:-$HOME/.local/share}/rer,
2
2
  // as immutable versions/<version>-<digest8> directories and a `current` link.
3
- // Launcher: $HOME/.local/bin/rer, a POSIX sh script that runs node from PATH.
3
+ // Launcher: $HOME/.local/bin/rer, using the installer's private Node when present.
4
4
  import { readFile, lstat } from 'node:fs/promises';
5
5
  import { homedir } from 'node:os';
6
6
  import { join } from 'node:path';
@@ -15,14 +15,18 @@ export function layout(env = process.env) {
15
15
  const marker = '# rer launcher, written by `rer cli install` (@runeditrun/rer). Do not edit.';
16
16
  const quote = value => `'${value.replaceAll("'", `'\\''`)}'`;
17
17
 
18
- // No absolute Node path is baked in, so a Node upgrade never breaks it.
18
+ // The managed runtime stays inside the install root; npx installs use PATH.
19
19
  export function launcherScript(data) {
20
20
  return `#!/bin/sh
21
21
  ${marker}
22
- # It runs the installed version with the node on PATH.
22
+ # It uses the installer's private Node when present, otherwise Node on PATH.
23
23
  root=${quote(data)}
24
+ if [ -x "$root/node/bin/node" ]; then
25
+ PATH="$root/node/bin:$PATH"
26
+ export PATH
27
+ fi
24
28
  if ! command -v node >/dev/null 2>&1; then
25
- echo "rer: node is not on PATH. Install Node 22 or later, then run rer again." >&2
29
+ echo "rer: Node is missing. Run: curl -fsSL https://runeditrun.com/install.sh | sh" >&2
26
30
  exit 127
27
31
  fi
28
32
  exec node "$root/current/global/rer.mjs" "$@"
package/global/main.mjs CHANGED
@@ -36,7 +36,7 @@ import, doctor, describe, check, release. Run rer VERB --help in a checkout for
36
36
 
37
37
  // The checkout verbs that install the pinned package before they run when
38
38
  // node_modules holds another version or none (dev installs it in its launch).
39
- const installsFirst = new Set([...Object.keys(verbs), 'signin', 'release'].filter(verb => verb !== 'dev'));
39
+ const installsFirst = new Set([...Object.keys(verbs), 'signin', 'release'].filter(verb => !['dev', 'doctor'].includes(verb)));
40
40
 
41
41
  export async function main(argv) {
42
42
  handleBrokenPipes();
@@ -51,7 +51,7 @@ export async function main(argv) {
51
51
  delete process.env[localDefaults];
52
52
  if (verb === 'update') return (await import('./update/command.mjs')).update(argv.slice(1));
53
53
  const notice = await import('./update/notice.mjs');
54
- if (notice.wantsNotice(argv)) await notice.updateNotice();
54
+ if (verb !== 'doctor' && notice.wantsNotice(argv)) await notice.updateNotice();
55
55
  if (!verb || verb === '--help' || verb === '-h' || verb === 'help') { process.stdout.write(help); return 0; }
56
56
  if (verb === 'cli') return (await import('./cli/command.mjs')).cliCommand(argv.slice(1));
57
57
  if (verb === 'list') return (await import('./list.mjs')).listCommand(argv.slice(1));
@@ -65,6 +65,13 @@ export async function main(argv) {
65
65
  const { jobsDirectory } = await import('../modules/job-queue/config.mjs');
66
66
  process.env.RER_SERVERS_DIR = serversDirectory(process.env);
67
67
  process.env.RER_JOBS_DIR = jobsDirectory(process.env);
68
+ if ((mode !== 'bundled' || pinnedPackage(target.root)) && verb === 'doctor' && !argv.includes('--help')) {
69
+ const { parse } = await import('../cli/parse.mjs');
70
+ try { parse(target.args, target.root); }
71
+ catch (error) { process.stderr.write(error.message + '\n'); return error.exitCode ?? 2; }
72
+ const code = await (await import('./browser-runtime.mjs')).browserPreflight(target.root, target.args);
73
+ if (code !== undefined) return code;
74
+ }
68
75
  const bootstrap = pinnedPackage(target.root)?.ready === false && installsFirst.has(verb);
69
76
  if ((bootstrap || ['install', 'setup', 'dev', 'preview', 'build', 'verify'].includes(verb)) && !argv.includes('--help') && !argv.includes('--stop')) {
70
77
  const { parse } = await import('../cli/parse.mjs');
@@ -98,9 +105,12 @@ export async function main(argv) {
98
105
  const { installPinned } = await import('./launch/install-pinned.mjs'), { LaunchFailure } = await import('./launch/failure.mjs');
99
106
  try { await installPinned(target.root); }
100
107
  catch (failure) { if (!(failure instanceof LaunchFailure)) throw failure; process.stderr.write(failure.message + '\n'); return failure.exitCode; }
101
- return delegate(target, target.args);
102
108
  }
103
109
  if (mode === 'package' && installsFirst.has(verb)) await (await import('./launch/install-pinned.mjs')).settledPin(target.root);
110
+ if (first && dispatcher(target.root).mode !== 'bundled' && ['install', 'verify'].includes(verb) && !argv.includes('--help') && !argv.includes('--site')) {
111
+ const code = await (await import('./browser-runtime.mjs')).browserPreflight(target.root, target.args);
112
+ if (code !== undefined) return code;
113
+ }
104
114
  if (verb === 'dev' && mode && mode !== 'package' && !argv.includes('--help')) return (await import('./launch/dev.mjs')).launchDev(target);
105
115
  // Every other server start or queued job on a vendored pin gets the person
106
116
  // defaults too (a pinned package applies its own).
package/install.sh CHANGED
@@ -12,8 +12,8 @@
12
12
  # `npx -y @runeditrun/rer cli install`. A failure leaves any previous install
13
13
  # selected and working. It never edits shell profiles.
14
14
  #
15
- # Needs curl, tar and Node (the package's minimum). macOS or Linux on x64 or
16
- # arm64; on Windows, run it inside WSL2.
15
+ # Needs curl and tar. If Node 22 or later is absent, installs the pinned official
16
+ # Node release in rer's own data directory. macOS/Linux x64/arm64; Windows: WSL2.
17
17
 
18
18
  # Everything runs from main, so a partly downloaded script does nothing.
19
19
  main() {
@@ -29,7 +29,7 @@ main() {
29
29
  x86_64 | amd64 | arm64 | aarch64) ;;
30
30
  *) fail "this processor ($(uname -m)) is not supported; rer runs on x64 and arm64." ;;
31
31
  esac
32
- for tool in curl tar node; do
32
+ for tool in curl tar; do
33
33
  command -v "$tool" >/dev/null 2>&1 || fail "$tool is required. Install it, then run this again."
34
34
  done
35
35
 
@@ -39,6 +39,11 @@ main() {
39
39
  trap 'rm -rf "$work"' EXIT
40
40
  trap 'exit 130' INT TERM
41
41
 
42
+ # Bootstrap before reading npm metadata; no npm global install or PATH links.
43
+ if ! command -v node >/dev/null 2>&1 || ! node -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 22 ? 0 : 1)' >/dev/null 2>&1; then
44
+ install_node
45
+ fi
46
+
42
47
  curl -fsSL --proto '=http,https' -H 'Accept: application/json' "$registry/@runeditrun%2frer" -o "$work/metadata.json" \
43
48
  || fail "could not read $package from $registry."
44
49
  # Writes version, tarball URL, integrity, file count and unpacked size, one per line.
@@ -136,6 +141,54 @@ NODE
136
141
  || fail "rer cli install failed; any previous install is still selected."
137
142
  }
138
143
 
144
+ install_node() {
145
+ node_version=22.20.0
146
+ case "$(uname -s)" in Darwin) node_os=darwin ;; Linux) node_os=linux ;; esac
147
+ case "$(uname -m)" in x86_64 | amd64) node_arch=x64 ;; arm64 | aarch64) node_arch=arm64 ;; esac
148
+ node_name="node-v$node_version-$node_os-$node_arch"
149
+ data="${XDG_DATA_HOME:-$HOME/.local/share}/rer"
150
+ node_home="$data/runtimes/$node_name"
151
+ if [ ! -x "$node_home/bin/node" ] || [ "$("$node_home/bin/node" --version 2>/dev/null)" != "v$node_version" ]; then
152
+ printf 'Installing Node %s in %s from the checksum-verified nodejs.org release.\n' "$node_version" "$node_home"
153
+ archive="$node_name.tar.gz"
154
+ release="https://nodejs.org/dist/v$node_version"
155
+ curl -fsSL --proto '=https' "$release/SHASUMS256.txt" -o "$work/SHASUMS256.txt" \
156
+ || fail "could not download Node $node_version checksums from nodejs.org."
157
+ curl -fL --proto '=https' "$release/$archive" -o "$work/$archive" \
158
+ || fail "could not download Node $node_version from nodejs.org."
159
+ expected=$(awk -v file="$archive" '$2 == file { print $1 }' "$work/SHASUMS256.txt")
160
+ [ "${#expected}" -eq 64 ] || fail "nodejs.org gives no unique SHA-256 for $archive."
161
+ case "$expected" in *[!0-9a-f]*) fail "nodejs.org gives an invalid SHA-256 for $archive." ;; esac
162
+ if command -v shasum >/dev/null 2>&1; then
163
+ actual=$(shasum -a 256 "$work/$archive")
164
+ elif command -v sha256sum >/dev/null 2>&1; then
165
+ actual=$(sha256sum "$work/$archive")
166
+ else
167
+ fail 'SHA-256 verification needs shasum or sha256sum. Install one, then run this again.'
168
+ fi
169
+ [ "${actual%% *}" = "$expected" ] || fail "Node $node_version does not match nodejs.org's SHA-256; nothing was installed."
170
+ mkdir "$work/node"
171
+ tar -xzf "$work/$archive" -C "$work/node" || fail "could not unpack Node $node_version."
172
+ [ "$("$work/node/$node_name/bin/node" --version)" = "v$node_version" ] || fail "Node $node_version cannot run on this system."
173
+ mkdir -p "$data/runtimes"
174
+ # Move only into our prefix, and never overlay an existing runtime.
175
+ [ ! -e "$node_home" ] || fail "the private Node runtime at $node_home is damaged; remove that directory and run this again."
176
+ mv "$work/node/$node_name" "$node_home"
177
+ fi
178
+ # A private link lets future launchers and updates find the managed runtime.
179
+ # Node's rename replaces an existing symlink atomically on macOS and Linux.
180
+ "$node_home/bin/node" - "$data" "$node_name" <<'NODE' || exit 1
181
+ var fs = require('fs'), path = require('path');
182
+ var root = process.argv[2], temporary = path.join(root, '.node-' + process.pid);
183
+ try {
184
+ fs.symlinkSync(path.join('runtimes', process.argv[3]), temporary);
185
+ fs.renameSync(temporary, path.join(root, 'node'));
186
+ } finally { try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; } }
187
+ NODE
188
+ PATH="$node_home/bin:$PATH"
189
+ export PATH
190
+ }
191
+
139
192
  fail() {
140
193
  printf 'rer install: %s\n' "$*" >&2
141
194
  exit 1
@@ -68,6 +68,12 @@ SQLite stays on the Docker host's local filesystem; host-shared checkout mounts
68
68
  are not used for database storage. Back up with export before deleting a volume. Build
69
69
  uses the ordinary private-file custody and command admission boundary. Secrets
70
70
  are provided at runtime, never baked into the image or transferred in archives.
71
+ Managed mail's `MAIL_PROVIDER` and `MAIL_FROM` are public configuration. Keep
72
+ them in the mail spec's public variables and Wrangler `vars`, and remove them
73
+ from `deploy.json` secrets. For migration, the image builder accepts those two
74
+ legacy secret declarations when the managed-mail spec declares them public,
75
+ and prints that correction. Demo runtime settings override their image defaults.
76
+ API keys, tokens and other secrets in image variables remain refused.
71
77
 
72
78
  `rer deploy --platform container --host ssh://user@host --env-file FILE` uses
73
79
  strict SSH host-key checking and a Linux host with Python 3 and Docker. FILE must
@@ -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});});}
@@ -8,6 +8,7 @@ import { checkBoundary } from './boundary.mjs';
8
8
  import { localDurableObjects } from './durable-objects.mjs';
9
9
  import { readMigrationRewrites, withRewrites } from '../deploy-kit/migrations.mjs';
10
10
  import { containerMigrationInventory } from './migration-inventory.mjs';
11
+ import { checkImageVariables } from './image-variables.mjs';
11
12
  export async function buildContainer(root, options={}) {
12
13
  const previous=process.cwd();process.chdir(root);
13
14
  try{return await buildImage(root,options);}finally{process.chdir(previous);}
@@ -74,7 +75,7 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
74
75
  const entry = engine === 'workerd' ? 'dist/server/'+workerConfig.main : 'dist/server/index.mjs';
75
76
  await readFile(join(root,entry));
76
77
  if (engine === 'node' && workerConfig.kv_namespaces?.length) throw new Error('Node container does not support KV');
77
- for (const secret of declaration.secrets ?? []) if (Object.hasOwn(workerConfig.vars ?? {},secret.binding)) throw new Error('Secret declared as an image variable: '+secret.binding);
78
+ await checkImageVariables(root,workerConfig.vars ?? {},declaration.secrets ?? []);
78
79
  const manifest = { version:1,engine,entry,cacheContract,runner,config:workerConfig,migrations,portabilityMigrations:await portabilityPlan(split),maxRequestBytes:25*1024*1024 };
79
80
  await rm(output,{recursive:true,force:true}); await mkdir(join(output,'app'),{recursive:true});
80
81
  await cp(join(root,'dist'),join(output,'app/dist'),{recursive:true}); await writeFile(join(output,'app/container.json'),JSON.stringify(manifest,null,2)+'\n');
@@ -0,0 +1,27 @@
1
+ import {readFile} from 'node:fs/promises';
2
+ import {deliveryDeclarationSources} from '../../cli/delivery-declarations.mjs';
3
+ import {sourcePath} from '../delivery-producer/migrations.mjs';
4
+ import {usesManagedMail,validateMailSpec} from '../delivery-producer/mail.mjs';
5
+
6
+ /** Admit only the managed-mail contract's public config through legacy secret declarations. */
7
+ export async function checkImageVariables(root,vars,secrets) {
8
+ const overlaps=secrets.filter(secret=>Object.hasOwn(vars,secret.binding));
9
+ if (!overlaps.length) return;
10
+ const publicMail=new Set(),privateNames=new Set();
11
+ for (const [candidate,select] of deliveryDeclarationSources) {
12
+ const path=await sourcePath(root,candidate,{optional:true});
13
+ if (!path) continue;
14
+ const spec=select(JSON.parse(await readFile(path,'utf8')));
15
+ if (!spec) continue;
16
+ for (const name of [...(spec.secretNames ?? []),...(spec.optionalSecretNames ?? [])]) privateNames.add(name);
17
+ if (!usesManagedMail(spec.mail)) continue;
18
+ const names=spec.publicVariableNames ?? Object.keys(spec.publicVariables ?? {});
19
+ const publicVariables=Object.fromEntries(Object.entries(vars).filter(([name])=>names.includes(name)));
20
+ validateMailSpec({...spec,publicVariables,secretNames:spec.secretNames ?? []});
21
+ for (const name of ['MAIL_PROVIDER','MAIL_FROM']) if (typeof publicVariables[name] === 'string') publicMail.add(name);
22
+ }
23
+ for (const {binding} of overlaps) if (!publicMail.has(binding) || privateNames.has(binding)) {
24
+ throw new Error('Secret declared as an image variable: '+binding);
25
+ }
26
+ console.warn(overlaps.map(secret=>secret.binding).join(', ')+' are public mail configuration, not secrets. Remove these bindings from deploy.json secrets; keep them in the mail spec public variables and Wrangler vars. Accepting the legacy declaration; runtime demo settings override the image defaults.');
27
+ }
@@ -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';
@@ -1,6 +1,6 @@
1
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';
@@ -1,6 +1,10 @@
1
1
  import {array, bindingPattern, keys, string, strings} from './bindings.mjs';
2
2
 
3
3
  const pathPattern = /^\/[A-Za-z0-9/_.~-]*$/;
4
+ const validSignIn = value => value && typeof value === 'object' && !Array.isArray(value)
5
+ && Object.keys(value).every(key => ['path','loginHint'].includes(key))
6
+ && typeof value.path === 'string' && /^\/(?!\/)[a-zA-Z0-9/_-]*$/.test(value.path)
7
+ && typeof value.loginHint === 'boolean';
4
8
  const status = (value, label) => {
5
9
  if (!Number.isInteger(value) || value < 100 || value > 599) throw Error(`Invalid ${label}`);
6
10
  };
@@ -15,8 +19,9 @@ export function validateDeclarations(spec) {
15
19
  if (!spec.surfaces.app) throw Error('Surfaces require an app');
16
20
  const origins = new Map();
17
21
  for (const [name, surface] of Object.entries(spec.surfaces)) {
18
- keys(surface, ['path','hostnameVariable','originVariable','readiness'], 'surface');
22
+ keys(surface, ['path','hostnameVariable','originVariable','readiness','signIn'], 'surface');
19
23
  string(surface.path, 'surface path', pathPattern);
24
+ if (surface.signIn !== undefined && (name !== 'app' || !validSignIn(surface.signIn))) throw Error('Invalid project sign-in declaration');
20
25
  if (surface.hostnameVariable !== undefined && surface.originVariable !== undefined) throw Error('Surface must choose one address variable');
21
26
  for (const field of ['hostnameVariable','originVariable']) if (surface[field] !== undefined) string(surface[field], field, bindingPattern);
22
27
  if (surface.originVariable !== undefined) {
@@ -0,0 +1,66 @@
1
+ import {keys, strings} from './bindings.mjs';
2
+
3
+ const publicNames = ['MAIL_PROVIDER', 'MAIL_FROM', 'MAIL_RELAY_URL'];
4
+ const providerLabels = {rer: 'RER managed mail', resend: 'Resend', sendgrid: 'SendGrid', cloudflare: 'Cloudflare Email Sending'};
5
+
6
+ /** Managed mail is an explicit capability, independent of direct provider adapters. */
7
+ export function usesManagedMail(mail) {
8
+ if (mail === undefined) return false;
9
+ keys(mail, ['providers'], 'mail');
10
+ const providers = strings(mail.providers, 'mail providers', /^(rer|resend|sendgrid|cloudflare)$/);
11
+ if (!providers.length) throw Error('Mail requires at least one provider');
12
+ return providers.includes('rer');
13
+ }
14
+
15
+ /** Compose these fields into the seed's committed setup manifest before packaging. */
16
+ export function generateMailSetupFields(mail) {
17
+ usesManagedMail(mail);
18
+ if (!mail) throw Error('Mail setup requires a provider declaration');
19
+ const condition = provider => ({field: 'MAIL_PROVIDER', equals: provider});
20
+ const presentations = mail.providers.map(provider => ({when: condition(provider), required: true}));
21
+ return [
22
+ {name: 'MAIL_PROVIDER', label: 'Mail provider', kind: 'select', required: true, default: mail.providers[0],
23
+ options: mail.providers.map(value => ({value, label: providerLabels[value]}))},
24
+ {name: 'MAIL_FROM', label: 'Sender address', kind: 'text', required: false, presentations},
25
+ ...(mail.providers.includes('rer') ? [
26
+ {name: 'MAIL_RELAY_URL', label: 'Managed mail relay URL', kind: 'url', required: true, when: condition('rer')}
27
+ ] : []),
28
+ {name: 'MAIL_API_KEY', label: 'Mail API key', kind: 'secret', input: 'entered', ownerVisible: true,
29
+ required: false, presentations: structuredClone(presentations)},
30
+ ...(mail.providers.includes('cloudflare') ? [
31
+ {name: 'MAIL_ACCOUNT_ID', label: 'Cloudflare account ID', kind: 'text', required: true, when: condition('cloudflare')}
32
+ ] : [])
33
+ ];
34
+ }
35
+
36
+ export function validateMailSpec(spec) {
37
+ if (!usesManagedMail(spec.mail)) return;
38
+ for (const name of publicNames) {
39
+ if (!Object.hasOwn(spec.publicVariables, name)) throw Error(`Managed mail requires public ${name}`);
40
+ }
41
+ if (![...spec.secretNames, ...(spec.optionalSecretNames ?? [])].includes('MAIL_API_KEY')) {
42
+ throw Error('Managed mail requires secret MAIL_API_KEY');
43
+ }
44
+ }
45
+
46
+ /** Check the selected installer's effective fields for RER's assigned provider. */
47
+ export function validateMailSetup(mail, manifest) {
48
+ if (!usesManagedMail(mail) || !manifest) return;
49
+ const provider = manifest.fields.find(field => field.name === 'MAIL_PROVIDER');
50
+ if (provider?.kind !== 'select' || !provider.options.some(option => option.value === 'rer')) {
51
+ throw Error('Managed mail setup requires a MAIL_PROVIDER select with the rer option');
52
+ }
53
+ const matches = condition => condition.field === 'MAIL_PROVIDER'
54
+ && (condition.nonEmpty === true || condition.equals === 'rer');
55
+ for (const name of [...publicNames, 'MAIL_API_KEY']) {
56
+ const field = manifest.fields.find(item => item.name === name);
57
+ if (!field || (name === 'MAIL_API_KEY' ? field.kind !== 'secret' : field.kind === 'secret')) {
58
+ throw Error(`Managed mail setup requires ${name === 'MAIL_API_KEY' ? 'secret' : 'public'} ${name}`);
59
+ }
60
+ const presentation = field.presentations?.find(item => matches(item.when));
61
+ if ((field.when && !matches(field.when)) || (field.presentations && !presentation)
62
+ || (presentation?.required ?? field.required) !== true) {
63
+ throw Error(`Managed mail setup requires ${name} with provider rer`);
64
+ }
65
+ }
66
+ }
@@ -4,7 +4,7 @@ import { allow, sha256 } from '../operator-auth/csp.mjs';
4
4
  // client-side route changes, whose head manager writes a fresh title. The script
5
5
  // is one constant text (so one constant CSP hash); the suffix reaches it as data
6
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})})()";
7
+ const SCRIPT = "(()=>{const suffix=document.querySelector('style[data-rer-label]').dataset.rerLabel,update=()=>{const base=document.title.replace(/\\s*(?:Demo|Dev)$/,''),title=(base?base+' ':'')+suffix;if(document.title!==title)document.title=title};update();new MutationObserver(update).observe(document.head,{childList:true,subtree:true,characterData:true})})()";
8
8
 
9
9
  export async function decorateLabel(response, mode) {
10
10
  if (!response.body || !response.headers.get('content-type')?.toLowerCase().startsWith('text/html')) return response;
@@ -21,7 +21,10 @@ export async function decorateLabel(response, mode) {
21
21
  headers.delete('content-length');
22
22
  headers.delete('etag');
23
23
  const addition = `<style data-rer-label="${suffix}">${style}</style><script>${SCRIPT}</script>`;
24
- const titled = html.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title>)/i, (_, open, title, close) => `${open}${title.replace(/ (?:Demo|Dev)$/, '')} ${suffix}${close}`);
24
+ const titled = html.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title>)/i, (_, open, title, close) => {
25
+ const base = title.replace(/\s*(?:Demo|Dev)$/, '');
26
+ return `${open}${base ? `${base} ` : ''}${suffix}${close}`;
27
+ });
25
28
  const body = /<\/head\s*>/i.test(titled) ? titled.replace(/<\/head\s*>/i, `${addition}</head>`) : addition + titled;
26
29
  return new Response(body, { status: response.status, statusText: response.statusText, headers });
27
30
  }
@@ -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
@@ -82,7 +89,9 @@ Chromium (default-seed's Playwright) through waiting, failure, Try again,
82
89
  working and the signed-in landing. The end-to-end proof (`wrangler dev` with Docker)
83
90
  is in DEMO.md.
84
91
 
85
- 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).
86
95
  The Durable Object owns that work and cleanup while the page polls; a browser
87
96
  that leaves cannot abandon it. Retrying a pending copy resumes the same
88
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
@@ -116,12 +125,25 @@ container is already stopped); a terminal start failure releases it immediately.
116
125
  A cleanup failure is logged separately and cannot replace the startup failure
117
126
  shown to the visitor.
118
127
 
119
- Cloudflare may briefly report that it has no prepared container instance even
120
- 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
121
133
  reservation and launch options, requests placement again only for that specific
122
- 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
123
136
  and claim errors are not retried. Placement exhaustion answers with the normal
124
137
  failed-start retry state and releases the reservation; the capacity notice is
125
138
  reserved for actual reservation exhaustion. Cleanup keeps only that terminal
126
139
  answer and correlation for one minute, so a status poll after object recovery
127
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".
@@ -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(()=>({}));