@runeditrun/rer 0.2.20 → 0.2.22

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 (51) hide show
  1. package/cli/README.md +7 -0
  2. package/cli/demo-host.mjs +9 -8
  3. package/cli/demo-removal-provider.mjs +24 -0
  4. package/cli/deploy-command.mjs +10 -7
  5. package/cli/deploy-hook.mjs +10 -14
  6. package/cli/deploy.mjs +3 -1
  7. package/cli/export.mjs +1 -1
  8. package/cli/managed-server.mjs +5 -2
  9. package/cli/production-auth.mjs +19 -5
  10. package/global/CHANGELOG.md +7 -1
  11. package/modules/container/README.md +10 -0
  12. package/modules/container/build.mjs +10 -12
  13. package/modules/container/host.mjs +3 -1
  14. package/modules/container/ingress.mjs +15 -4
  15. package/modules/container/migration-inventory.mjs +33 -0
  16. package/modules/container/migrations.mjs +16 -2
  17. package/modules/delivery-producer/migrations.mjs +61 -0
  18. package/modules/demo/effects.mjs +4 -0
  19. package/modules/demo-host/README.md +34 -15
  20. package/modules/demo-host/capacity.mjs +1 -1
  21. package/modules/demo-host/container.mjs +73 -39
  22. package/modules/demo-host/diagnostics.mjs +1 -0
  23. package/modules/demo-host/pages.mjs +1 -1
  24. package/modules/demo-host/placement.mjs +23 -0
  25. package/modules/demo-host/plan.mjs +20 -7
  26. package/modules/demo-host/remove.mjs +9 -7
  27. package/modules/demo-host/start-script.mjs +10 -1
  28. package/modules/demo-host/startup.mjs +4 -2
  29. package/modules/demo-host/worker.mjs +18 -1
  30. package/modules/dependencies/approval.mjs +3 -2
  31. package/modules/dependencies/index.mjs +2 -2
  32. package/modules/deploy-kit/README.md +16 -2
  33. package/modules/deploy-kit/diagnostics.mjs +9 -0
  34. package/modules/deploy-kit/health-request.mjs +7 -5
  35. package/modules/deploy-kit/provider-transport.mjs +56 -0
  36. package/modules/deploy-kit/provider.mjs +22 -20
  37. package/modules/operator-auth/README.md +4 -0
  38. package/modules/operator-auth/accounts/credentials.mjs +2 -2
  39. package/modules/operator-auth/accounts/email-change.mjs +2 -2
  40. package/modules/operator-auth/accounts/provider-control.mjs +3 -3
  41. package/modules/operator-auth/accounts/store.mjs +9 -8
  42. package/modules/operator-auth/dev/cli-session.mjs +5 -4
  43. package/modules/operator-auth/dev/index.mjs +5 -5
  44. package/modules/operator-auth/dev-gate.mjs +4 -2
  45. package/modules/operator-auth/identity/email-link/index.mjs +2 -1
  46. package/modules/operator-auth/signin/index.mjs +10 -2
  47. package/onboarding/adapter.mjs +11 -3
  48. package/onboarding/operator-installer.mjs +2 -2
  49. package/onboarding/operator-migrations.mjs +48 -0
  50. package/onboarding/process-table.mjs +45 -19
  51. package/package.json +1 -1
@@ -5,7 +5,14 @@ that adopted demo mode (`withDemo`, export/DEMO.md). `plan.mjs` turns `deploy-de
5
5
  (optionally `instanceType`, one of Cloudflare's predefined Container instance
6
6
  types, `basic` unless set) into the Worker's Wrangler configuration; the CLI (`cli/demo-host.mjs`) writes
7
7
  it with these files and the seed's container image folder (workerd engine) to
8
- `.rer/demo-host/` and runs `wrangler deploy` there.
8
+ `.rer/demo-host/` and runs `wrangler deploy` there. Declared
9
+ `container.hostVariables` resolve from demo settings to the primary hostname or
10
+ its descendants (for example `page.demo.<domain>`); each gets a custom-domain
11
+ route to the same front. The visitor cookie covers these hosts, while the
12
+ primary host's `__Host` owner session stays host-only. The front supplies a
13
+ validated public origin to the container ingress, so secondary page routing
14
+ sees the requested host. Anonymous secondary requests return to the primary
15
+ start page.
9
16
 
10
17
  - `worker.mjs`: `GET /` is the start page; `POST /__demo/start` checks the
11
18
  exact Origin, the `STARTS` rate limit (3 per IP per 60 s), Turnstile's
@@ -29,12 +36,11 @@ it with these files and the seed's container image folder (workerd engine) to
29
36
  guard simulates effects on people and third-party accounts, while the
30
37
  container egress independently refuses direct mail/SMS provider transports
31
38
  and SMTP ports. Public-address filtering and TLS remain enforced.
32
- The platform stops a container about two minutes after its Durable Object's
33
- last event, when it evicts the object (and the object's exit watcher with
34
- it). So the alarm stays in flight until the demo's next check, at most three
35
- minutes, and arms the next at once, as the Containers class keeps its own
36
- object alive. A request or alarm that finds the container gone ends the demo
37
- and answers the ended page (410), never a 5xx.
39
+ The platform inactivity timeout is set after start and reapplied when an
40
+ object recovers an already-running container. Persisted alarms enforce the
41
+ exact idle/absolute deadline without keeping a timer in flight. Requests
42
+ check both deadlines before refreshing activity. A container found stopped
43
+ ends the demo and answers the ended page (410).
38
44
  - `capacity.mjs`: `DemoCapacity` counts unexpired reservation rows inside a
39
45
  storage transaction, excluding diagnostics and expired rows. A lost start
40
46
  handoff expires after one minute; a successful claim extends the reservation
@@ -54,7 +60,8 @@ it with these files and the seed's container image folder (workerd engine) to
54
60
  with the refusal's status)
55
61
  and shows each step: the check, the private copy starting, the sign-in. A
56
62
  refusal, a network failure or a start past 25 seconds is shown with Try
57
- again, which runs a new check; progress is announced through a
63
+ again, which first destroys the abandoned copy and releases its place through
64
+ `POST /__demo/cancel`, then runs a new check; progress is announced through a
58
65
  `role="status"` region and failures through `role="alert"`. Without
59
66
  JavaScript the form posts as before and gets the 303 or the page.
60
67
  - `remove.mjs`: `rer deploy --demo --remove --yes`. The deploy passes the
@@ -77,9 +84,10 @@ is in DEMO.md.
77
84
  Startup has a 45-second budget, with a separate five-second HTTP probe limit.
78
85
  The Durable Object owns that work and cleanup while the page polls; a browser
79
86
  that leaves cannot abandon it. Retrying a pending copy resumes the same
80
- reservation. Failed starts retain the bounded operator diagnostic and destroy
81
- the container; cleanup retries keep a reservation only while destruction is
82
- unconfirmed. Every attempt logs its timestamp, elapsed time, duration and
87
+ 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
88
+ the container. Destruction retries for failed starts never extend or reclaim the
89
+ released place. Each release logs the id's SHA-256 fingerprint with the start's
90
+ correlation. Every attempt logs its timestamp, elapsed time, duration and
83
91
  HTTP status or fixed error category, including successful probes. Exit records
84
92
  include the numeric platform exit code when supplied. A separate random
85
93
  `x-rer-demo-correlation` response header joins these events without disclosing
@@ -99,7 +107,18 @@ no access. The token never belongs in a URL. Ordinary visitors keep the generic
99
107
  failure page. No raw error text, health body, cookies or environment values are
100
108
  included in this diagnostic.
101
109
 
102
- Failed destruction retains its alarm and capacity reservation for cleanup;
103
- only confirmed destruction (or an already-stopped container) releases the
104
- place. A cleanup failure is logged separately and cannot replace the startup
105
- failure shown to the visitor.
110
+ Failed destruction retains its alarm for cleanup. A live visitor's demo also
111
+ retains its capacity reservation until destruction is confirmed (or the
112
+ container is already stopped); a terminal start failure releases it immediately.
113
+ A cleanup failure is logged separately and cannot replace the startup failure
114
+ shown to the visitor.
115
+
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
118
+ reservation and launch options, requests placement again only for that specific
119
+ provider response, and stays within the original startup deadline. Boot, health
120
+ and claim errors are not retried. Placement exhaustion answers with the normal
121
+ failed-start retry state and releases the reservation; the capacity notice is
122
+ reserved for actual reservation exhaustion. Cleanup keeps only that terminal
123
+ answer and correlation for one minute, so a status poll after object recovery
124
+ still receives the right answer; its alarm then deletes the remaining metadata.
@@ -45,7 +45,7 @@ export class DemoCapacity extends DurableObject {
45
45
  }
46
46
 
47
47
  async release(id) {
48
- await this.ctx.storage.delete(id);
48
+ return this.ctx.storage.delete(id);
49
49
  }
50
50
  }
51
51
 
@@ -3,6 +3,8 @@ import { claimKeys, signClaim } from './claim.mjs';
3
3
  import { bounded, boundedFetch, category, report } from './diagnostics.mjs';
4
4
  import { endedPage, clearCookie } from './pages.mjs';
5
5
  import { finishStart } from './startup.mjs';
6
+ import { placeContainer } from './placement.mjs';
7
+ import { fingerprint } from './capacity.mjs';
6
8
 
7
9
  // One visitor's demo: a Durable Object (newUniqueId) and its container, the
8
10
  // seed's image from `rer build --platform container` on the workerd engine.
@@ -10,11 +12,9 @@ import { finishStart } from './startup.mjs';
10
12
  // external effects; the engine also refuses direct mail/SMS transports. The
11
13
  // front signs the owner in through the existing signed owner claim. The demo ends at its hour or after
12
14
  // 15 idle minutes: the alarm destroys the container and deletes everything.
13
- // The platform stops a container about two minutes after its Durable Object's
14
- // last event, when the object is evicted, and the exit watcher goes with it.
15
- // So the alarm stays in flight until the demo's next check and then arms the
16
- // next at once, as the Containers class keeps its object alive; a container
17
- // that is gone anyway answers the ended page and frees its place.
15
+ // Container lifetime is independent of the object's JS lifetime. Configure the
16
+ // platform's inactivity grace on every object instance; persisted alarms and
17
+ // request-time checks enforce the visitor's exact idle and absolute deadlines.
18
18
  const PORT = 8080, IDLE = 15 * 60_000, OWNER = 'owner@demo.invalid';
19
19
  // The container's port speaks plain HTTP; the app takes its public origin from RER_INGRESS_ORIGIN.
20
20
  const inside = url => `http://container${url.pathname}${url.search}`;
@@ -29,9 +29,12 @@ export class DemoContainer extends DurableObject {
29
29
  if (state.get('startup')?.phase === 'starting') {
30
30
  // An interrupted start has lost its private claim key and cannot be
31
31
  // resumed after object eviction. End it instead of polling forever.
32
- await ctx.storage.put('startup', { phase: 'failed' });
32
+ await ctx.storage.put('startup', { phase: 'starting', failure: state.get('startup').failure ?? { phase: 'failed' } });
33
33
  ctx.waitUntil(this.end().catch(cause => report(this.correlation, this.started, 'cleanup', { error: category(cause) })));
34
- } else if (this.container.running) this.watch();
34
+ } else if (this.container.running) {
35
+ await this.container.setInactivityTimeout(this.idle);
36
+ this.watch();
37
+ }
35
38
  });
36
39
  }
37
40
  watch() {
@@ -42,7 +45,7 @@ export class DemoContainer extends DurableObject {
42
45
  }
43
46
  records = [];
44
47
  record(event, detail = {}) {
45
- const row = { event, at: new Date().toISOString(), elapsedMs: Date.now() - this.started, ...detail };
48
+ const row = { event, at: new Date().toISOString(), elapsedMs: this.now() - this.started, ...detail };
46
49
  this.records.push(row); if (this.records.length > 8) this.records.shift();
47
50
  report(this.correlation, this.started, event, detail);
48
51
  }
@@ -51,7 +54,7 @@ export class DemoContainer extends DurableObject {
51
54
  startTimeout = 45_000;
52
55
  probeTimeout = 5000;
53
56
  cleanupRetry = 30_000;
54
- hold = 3 * 60_000;
57
+ now() { return Date.now(); }
55
58
  get container() { return this.ctx.container; }
56
59
  port() { return this.container.getTcpPort(PORT); }
57
60
 
@@ -70,48 +73,50 @@ export class DemoContainer extends DurableObject {
70
73
 
71
74
  /** Start the container, wait for /health, claim the owner; returns the claim's 303. */
72
75
  async start({ origin, originVar, ends, endsLocal, settings, correlation }) {
73
- this.correlation = correlation; this.started = Date.now(); this.stopped = false;
76
+ this.correlation = correlation; this.started = this.now(); this.stopped = false; this.cancelled = false;
74
77
  const deadline = this.started + this.startTimeout;
75
- const id = this.ctx.id.toString(), keys = await claimKeys(), now = Date.now();
78
+ const id = this.ctx.id.toString(), keys = await claimKeys(), now = this.now();
76
79
  await this.ctx.storage.put({ ends, seen: now, correlation, started: this.started, startDeadline: deadline });
77
80
  report(correlation, this.started, 'start');
78
81
  if (this.stopped) throw new Error('container-stopped');
79
- this.container.start({ enableInternet: true, env: { ...settings, RER_DEMO: '1', [originVar]: origin, RER_INGRESS_ORIGIN: origin,
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 ?? '[]')]),
80
83
  SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: OWNER, RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
81
- RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal } });
82
- // A container that stops by itself ends the demo too.
83
- this.watch();
84
- await this.ctx.storage.setAlarm(Date.now());
85
- await this.healthy(deadline);
86
- const token = await signClaim(keys, { origin, installationId: id, email: OWNER, now: Date.now() });
84
+ RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal } }, deadline);
85
+ await this.container.setInactivityTimeout(this.idle);
86
+ await this.ctx.storage.setAlarm(deadline);
87
+ const token = await signClaim(keys, { origin, installationId: id, email: OWNER, now: this.now() });
87
88
  const claimed = await boundedFetch(this.port(), 'http://container/auth/owner-claim', { method: 'POST', redirect: 'manual',
88
- headers: { origin, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ token }) }, Math.max(1, Math.min(10_000, deadline - Date.now())));
89
+ headers: { origin, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ token }) }, Math.max(1, Math.min(10_000, deadline - this.now())));
89
90
  void claimed.body?.cancel().catch(() => {});
90
91
  this.record('claim', { status: claimed.status });
91
92
  if (this.stopped) throw new Error('container-stopped');
92
93
  if (claimed.status !== 303) throw new Error(`owner claim answered ${claimed.status}`);
94
+ await this.ctx.storage.put('seen', this.now());
95
+ await this.ctx.storage.setAlarm(Math.min(ends, this.now() + this.idle));
93
96
  return { location: claimed.headers.get('location'), cookies: claimed.headers.getSetCookie() };
94
97
  }
95
98
 
96
99
  async healthy(deadline) {
97
100
  let attempt = 0;
98
- while (Date.now() < deadline) {
101
+ while (this.now() < deadline) {
99
102
  if (this.stopped) throw new Error('container-stopped');
100
- const probe = Date.now();
103
+ const probe = this.now();
101
104
  try {
102
- const response = await boundedFetch(this.port(), 'http://container/health', {}, Math.min(this.probeTimeout, deadline - Date.now()));
105
+ const response = await boundedFetch(this.port(), 'http://container/health', {}, Math.min(this.probeTimeout, deadline - this.now()));
103
106
  void response.body?.cancel().catch(() => {});
104
- this.record('health', { attempt: ++attempt, durationMs: Date.now() - probe, status: response.status });
107
+ this.record('health', { attempt: ++attempt, durationMs: this.now() - probe, status: response.status });
105
108
  if (response.ok && !this.stopped) return;
106
109
  } catch (error) {
107
- this.record('health', { attempt: ++attempt, durationMs: Date.now() - probe, error: category(error) });
110
+ this.record('health', { attempt: ++attempt, durationMs: this.now() - probe, error: category(error) });
108
111
  }
109
- await new Promise(resolve => setTimeout(resolve, Math.min(250, Math.max(0, deadline - Date.now()))));
112
+ await new Promise(resolve => setTimeout(resolve, Math.min(250, Math.max(0, deadline - this.now()))));
110
113
  }
111
114
  throw new Error('health-deadline');
112
115
  }
113
116
 
114
117
  async exited(error) {
118
+ this.watching = false;
119
+ this.stopReason = error ? category(error) : 'container-stopped';
115
120
  this.stopped = true;
116
121
  this.record('exit', { outcome: error ? category(error) : 'exited', ...(Number.isInteger(error?.exitCode) ? { exitCode: error.exitCode } : {}) });
117
122
  if ((await this.ctx.storage.get('startup'))?.phase === 'starting') return;
@@ -120,11 +125,20 @@ export class DemoContainer extends DurableObject {
120
125
 
121
126
  /** Every request carrying this demo's cookie: proxied while the demo lives, else the ended page. */
122
127
  async fetch(request) {
123
- const state = await this.ctx.storage.get(['ends', 'seen']), now = Date.now();
124
- if (!(state.get('ends') > now)) return this.ended();
128
+ const state = await this.ctx.storage.get(['ends', 'seen']), now = this.now();
129
+ if (!state.get('ends') || now >= Math.min(state.get('ends'), state.get('seen') + this.idle)) {
130
+ try { await this.end(); }
131
+ catch (cause) { report(this.correlation, this.started, 'cleanup', { error: category(cause) }); }
132
+ return this.ended();
133
+ }
125
134
  if (!this.container.running) return this.gone();
126
- if (now - state.get('seen') > 60_000) await this.ctx.storage.put('seen', now);
127
- try { return await this.port().fetch(new Request(inside(new URL(request.url)), request)); }
135
+ await this.ctx.storage.put('seen', now);
136
+ await this.ctx.storage.setAlarm(Math.min(state.get('ends'), now + this.idle));
137
+ const forwarded = new Request(inside(new URL(request.url)), request);
138
+ // The front admits only declared hosts. Never let a visitor choose the
139
+ // container's public origin through a transport header.
140
+ forwarded.headers.set('x-rer-ingress-origin', new URL(request.url).origin);
141
+ try { return await this.port().fetch(forwarded); }
128
142
  catch (error) { if (this.container.running && !this.stopped) throw error; return this.gone(); }
129
143
  }
130
144
 
@@ -138,16 +152,15 @@ export class DemoContainer extends DurableObject {
138
152
  }
139
153
 
140
154
  async alarm() {
141
- const state = await this.ctx.storage.get(['ends', 'seen', 'startDeadline']), now = Date.now();
155
+ const state = await this.ctx.storage.get(['ends', 'seen', 'startDeadline']), now = this.now();
142
156
  if (await this.ctx.storage.get('stopping')) return this.end();
143
- if (!state.get('ends')) return;
157
+ if (!state.get('ends')) return this.ctx.storage.deleteAll();
144
158
  const due = Math.min(state.get('ends'), state.get('seen') + this.idle, state.get('startDeadline') ?? Infinity);
145
159
  if (now >= due || !this.container.running) {
146
160
  if ((await this.ctx.storage.get('startup'))?.phase === 'starting') { this.stopped = true; return; }
147
161
  return this.end();
148
162
  }
149
- await new Promise(resolve => { this.wake = resolve; setTimeout(resolve, Math.min(due - now, this.hold)); });
150
- if (!this.stopped) await this.ctx.storage.setAlarm(Date.now());
163
+ await this.ctx.storage.setAlarm(due);
151
164
  }
152
165
 
153
166
  /** Destroy the container and delete this demo's state and place; safe to repeat. */
@@ -158,18 +171,39 @@ export class DemoContainer extends DurableObject {
158
171
  }
159
172
 
160
173
  async cleanup() {
161
- this.stopped = true; this.wake?.();
162
- // Keep the alarm and capacity reservation if destruction fails; retry cleanup.
174
+ this.cancelled = true; this.stopped = true;
175
+ const startup = await this.ctx.storage.get('startup');
176
+ const failure = startup?.failure ?? (startup?.phase === 'failed' ? startup : null);
177
+ // A failed start has no live visitor. Release it even if destruction needs
178
+ // another alarm; a live demo keeps its place until destruction succeeds.
163
179
  await this.ctx.storage.put('stopping', true);
164
- await this.ctx.storage.setAlarm(Date.now() + this.cleanupRetry);
180
+ await this.ctx.storage.setAlarm(this.now() + this.cleanupRetry);
181
+ if (failure) {
182
+ await this.releasePlace();
183
+ await this.ctx.storage.put('startup', failure);
184
+ }
165
185
  if (this.container.running) {
166
- try { await bounded(this.env.CAPACITY.get(this.env.CAPACITY.idFromName('capacity')).extend(this.ctx.id.toString(), Date.now() + 60_000), 2000); }
167
- catch (cause) { report(this.correlation, this.started, 'cleanup-reservation', { error: category(cause) }); }
186
+ if (!failure) {
187
+ try { await bounded(this.env.CAPACITY.get(this.env.CAPACITY.idFromName('capacity')).extend(this.ctx.id.toString(), this.now() + 60_000), 2000); }
188
+ catch (cause) { report(this.correlation, this.started, 'cleanup-reservation', { error: category(cause) }); }
189
+ }
168
190
  await bounded(this.container.destroy(), 5000);
169
191
  }
170
- await bounded(this.env.CAPACITY.get(this.env.CAPACITY.idFromName('capacity')).release(this.ctx.id.toString()), 2000);
192
+ if (!failure) await this.releasePlace();
171
193
  await this.ctx.storage.deleteAlarm();
172
194
  await this.ctx.storage.deleteAll();
195
+ // Retain only the terminal answer briefly, so polling survives a fresh DO.
196
+ if (failure) {
197
+ await this.ctx.storage.put({ startup: failure, correlation: this.correlation, started: this.started });
198
+ await this.ctx.storage.setAlarm(this.now() + 60_000);
199
+ }
173
200
  report(this.correlation, this.started, 'ended');
174
201
  }
202
+
203
+ async releasePlace() {
204
+ const id = this.ctx.id.toString();
205
+ if (await bounded(this.env.CAPACITY.get(this.env.CAPACITY.idFromName('capacity')).release(id), 2000)) {
206
+ report(this.correlation, this.started, 'released', { releasedId: await fingerprint(id) });
207
+ }
208
+ }
175
209
  }
@@ -2,6 +2,7 @@
2
2
  // container response body, cookie, environment value or raw error is retained.
3
3
  export function category(error) {
4
4
  const message = String(error?.message ?? '');
5
+ if (message === 'placement-unavailable' || /there is no container instance that can be provided to this Durable Object, try again later/i.test(message)) return 'placement-unavailable';
5
6
  if (error?.name === 'TimeoutError' || error?.name === 'AbortError') return 'probe-timeout';
6
7
  if (/connection refused|not listening|port.*not.*ready/i.test(message)) return 'port-not-ready';
7
8
  if (/container.*not.*running|container.*stopped/i.test(message)) return 'container-stopped';
@@ -49,7 +49,7 @@ export function endedPage(env, { status = 410, headers = {} } = {}) {
49
49
  const name = escape(env.DEMO_NAME);
50
50
  return html(env, { page: 'ended', title: 'This demo has ended', status, headers, body: `<h1 id="title">This demo has ended</h1>
51
51
  <p class="intro">Demos last an hour, or until 15 minutes pass with nothing happening. Its copy of ${name} and everything in it have been deleted.</p>
52
- <a class="button" href="/">Start a new demo</a><p class="secondary"><a href="${escape(new URL(env.DEMO_SITE).origin)}/run">Run ${name} yourself</a></p>` });
52
+ <a class="button" href="${escape(env.DEMO_ORIGIN)}/">Start a new demo</a><p class="secondary"><a href="${escape(new URL(env.DEMO_SITE).origin)}/run">Run ${name} yourself</a></p>` });
53
53
  }
54
54
 
55
55
  const cookie = (env, value, seconds) => `rer_demo=${value}; Domain=${new URL(env.DEMO_ORIGIN).hostname}; Path=/; Max-Age=${seconds}; HttpOnly; Secure; SameSite=Lax`;
@@ -0,0 +1,23 @@
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.
5
+ export async function placeContainer(demo, options, deadline) {
6
+ let attempt = 0;
7
+ while (Date.now() < deadline && !demo.cancelled) {
8
+ demo.stopped = false;
9
+ demo.stopReason = undefined;
10
+ demo.container.start(options);
11
+ demo.watch();
12
+ await demo.ctx.storage.setAlarm(deadline);
13
+ try {
14
+ await demo.healthy(deadline);
15
+ return;
16
+ } catch (error) {
17
+ if (demo.cancelled || demo.stopReason !== 'placement-unavailable') throw error;
18
+ demo.record('placement', { attempt: ++attempt, outcome: 'waiting' });
19
+ await new Promise(resolve => setTimeout(resolve, Math.min(1000, Math.max(0, deadline - Date.now()))));
20
+ }
21
+ }
22
+ throw new Error(demo.cancelled ? 'container-stopped' : 'placement-unavailable');
23
+ }
@@ -9,7 +9,7 @@ import { siteDeclaration } from '../deploy-kit/site.mjs';
9
9
  * running the seed's own image (`rer build --platform container`, workerd
10
10
  * engine), deployed by `wrangler deploy` with the image beside it. */
11
11
 
12
- export const DEMO_FILES = ['worker.mjs', 'container.mjs', 'startup.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs'];
12
+ export const DEMO_FILES = ['worker.mjs', 'container.mjs', 'startup.mjs', 'placement.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs'];
13
13
  const FRONT_SET = /^(?:RER_.*|SESSION_SECRET|SETUP_TOKEN|OWNER_EMAIL)$/;
14
14
  const SECRET = /SECRET|TOKEN|PASSWORD|_KEY$/;
15
15
  // Cloudflare Containers' predefined instance types, smallest first (developers.cloudflare.com/containers/platform-details/limits).
@@ -19,7 +19,9 @@ export const INSTANCE_TYPES = ['lite', 'basic', 'standard-1', 'standard-2', 'sta
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
21
  * "basic") and `settings`, the seed's plain demo settings (such as MAIL_PROVIDER: "development").
22
- * Settings never carry secrets or what the front sets.
22
+ * Settings never carry secrets or what the front sets. The app declaration's
23
+ * container.hostVariables select hostname settings: the primary demo hostname
24
+ * or its descendants, routed through the same visitor isolation.
23
25
  */
24
26
  export function demoDeclaration(value, originVar) {
25
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');
@@ -36,28 +38,39 @@ export function demoDeclaration(value, originVar) {
36
38
  }
37
39
 
38
40
  /** The demo Worker's name and its Wrangler configuration; no provider request. */
39
- export function demoPlan({ project, environment, compatibilityDate, originVar, declaration, turnstileSiteKey }) {
41
+ export function demoPlan({ project, environment, compatibilityDate, originVar, hostVariables = [], declaration, turnstileSiteKey }) {
40
42
  assert(/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate ?? '') && /^[A-Z][A-Z0-9_]{0,63}$/.test(originVar ?? ''), 'invalid-plan');
41
43
  const { domain, name, maxInstances, instanceType, settings } = demoDeclaration(declaration, originVar);
42
44
  const worker = `${ownerWorkerName(project, environment)}--demo`, hostname = `demo.${domain}`, container = worker.replace(/-+/g, '-');
43
45
  assert(resourceName(worker), 'owner-name-too-long');
46
+ assert(Array.isArray(hostVariables) && hostVariables.every(variable => typeof variable === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(variable)), 'invalid-demo-host-variables');
47
+ const declaredHosts = hostVariables.map(variable => {
48
+ const host = settings[variable];
49
+ assert(Object.hasOwn(settings, variable) && typeof host === 'string' && host.length <= 253 &&
50
+ /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(host) &&
51
+ (host === hostname || host.endsWith(`.${hostname}`)), 'invalid-demo-host-setting');
52
+ return host;
53
+ });
54
+ const secondaryHosts = [...new Set(declaredHosts)].filter(host => host !== hostname).sort();
55
+ const hostnames = [hostname, ...secondaryHosts];
44
56
  // Rate limit namespaces are account-wide integers: one per demo Worker.
45
57
  const namespace = String(1000 + parseInt(createHash('sha256').update(worker).digest('hex').slice(0, 8), 16) % 1_000_000_000);
46
58
  const wrangler = {
47
59
  name: worker, main: 'worker.mjs', compatibility_date: compatibilityDate, workers_dev: false, preview_urls: false,
48
- routes: [{ pattern: hostname, custom_domain: true }],
60
+ routes: hostnames.map(pattern => ({ pattern, custom_domain: true })),
49
61
  observability: { enabled: true, head_sampling_rate: 1, logs: { enabled: true, invocation_logs: false } },
50
- 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),
62
+ 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}`)),
51
63
  ...(turnstileSiteKey ? { TURNSTILE_SITE_KEY: turnstileSiteKey } : {}) },
52
64
  durable_objects: { bindings: [{ name: 'DEMO', class_name: 'DemoContainer' }, { name: 'CAPACITY', class_name: 'DemoCapacity' }] },
53
65
  migrations: [{ tag: 'v1', new_sqlite_classes: ['DemoContainer', 'DemoCapacity'] }],
54
66
  containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type: instanceType }],
55
67
  ratelimits: [{ name: 'STARTS', namespace_id: namespace, simple: { limit: 3, period: 60 } }],
56
68
  };
57
- return { worker, hostname, container, record: demoRecord({ worker, hostname, container }), origin: `https://${hostname}`, maxInstances, instanceType, settings: Object.keys(settings), wrangler };
69
+ return { worker, hostname, hostnames, container, record: demoRecord({ worker, hostname, hostnames, container }), origin: `https://${hostname}`, maxInstances, instanceType, settings: Object.keys(settings), wrangler };
58
70
  }
59
71
 
60
72
  /** The demo's record of what `rer deploy --demo` creates, kept on the provider so a
61
73
  * fresh checkout (a CI runner) can remove it: the deploy writes it as the Worker
62
74
  * version's message, and only a Worker serving it is taken for the demo's own. */
63
- export const demoRecord = ({ worker, hostname, container }) => `rer-demo:${hash({ worker, hostname, container })}`;
75
+ export const demoRecord = ({ worker, hostname, hostnames = [hostname], container }) =>
76
+ `rer-demo:${hash({ worker, hostname, container, ...(hostnames.length > 1 ? { hostnames } : {}) })}`;
@@ -6,8 +6,8 @@ import { deleteWorker } from '../deploy-kit/teardown.mjs';
6
6
  /* `rer deploy --demo --remove --yes`: remove the hosted demo `rer deploy --demo`
7
7
  * made for this environment, by exact provider ids, and nothing else. What the
8
8
  * deploy made: the front Worker (its Durable Object namespaces go with it), the
9
- * Workers Custom Domain demo.<domain> (Cloudflare adds and removes its DNS
10
- * record with it) and the Container application `wrangler deploy` created for
9
+ * Workers Custom Domains on the primary demo hostname and declared descendants
10
+ * (Cloudflare adds and removes their DNS records with them), and the Container application `wrangler deploy` created for
11
11
  * the Worker's DemoContainer namespace. It makes no D1, KV, R2, queue or DNS
12
12
  * record of its own: the domain's record is Cloudflare's, and goes with it.
13
13
  *
@@ -24,17 +24,18 @@ const rows = value => { assert(Array.isArray(value), 'provider-invalid-list'); r
24
24
 
25
25
  /** What exists of the demo now, each with its exact id; refuses whatever is not provably the demo's. */
26
26
  async function inventory(api, plan) {
27
- const named = rows(await api.request(`/workers/domains?hostname=${plan.hostname}`)).filter(row => row?.hostname === plan.hostname);
27
+ const named = (await Promise.all(plan.hostnames.map(async hostname =>
28
+ rows(await api.request(`/workers/domains?hostname=${hostname}`)).filter(row => row?.hostname === hostname)))).flat();
28
29
  const attached = rows(await api.request(`/workers/domains?service=${plan.worker}`)).filter(row => row?.service === plan.worker);
29
30
  const apps = rows(await api.request('/containers/applications')).filter(row => row?.name === plan.container);
30
31
  const namespaces = rows(await api.list('/workers/durable_objects/namespaces')).filter(row => row?.script === plan.worker);
31
32
  const worker = await workerSettings(api, plan.worker) !== null;
32
- for (const row of named) if (row.service !== plan.worker) throw refuse('resource-name-collision', `domain:${plan.hostname}`);
33
+ for (const row of named) if (row.service !== plan.worker) throw refuse('resource-name-collision', `domain:${row.hostname}`);
33
34
  if (worker) {
34
35
  const served = await servedVersion(api, plan.worker);
35
36
  if (served.annotation !== plan.record) throw refuse('resource-name-collision', `worker:${plan.worker}`);
36
37
  if (!served.current) throw refuse('owned-resource-replaced', `worker:${plan.worker}`);
37
- for (const row of attached) if (row.hostname !== plan.hostname) throw refuse('resource-not-in-record', `domain:${row.hostname}`);
38
+ for (const row of attached) if (!plan.hostnames.includes(row.hostname)) throw refuse('resource-not-in-record', `domain:${row.hostname}`);
38
39
  } else if (named.length || attached.length || apps.length) {
39
40
  // Without the Worker nothing proves these are the demo's.
40
41
  throw refuse('uncertain-resource-create', named[0] || attached[0] ? `domain:${(named[0] ?? attached[0]).hostname}` : `container:${plan.container}`);
@@ -50,7 +51,7 @@ export async function demoRemove({ api, plan, sleep }) {
50
51
  const removed = [];
51
52
  for (const domain of found.domains) {
52
53
  await api.request(`/workers/domains/${domain.id}`, { method: 'DELETE' });
53
- removed.push(`domain:${plan.hostname}`);
54
+ removed.push(`domain:${domain.hostname}`);
54
55
  }
55
56
  for (const app of found.apps) { await api.request(`/containers/applications/${app.id}`, { method: 'DELETE' }); removed.push(`container:${plan.container}`); }
56
57
  await deleteWorker({ api, worker: plan.worker, ...sleep ? { sleep } : {} });
@@ -59,7 +60,8 @@ export async function demoRemove({ api, plan, sleep }) {
59
60
  const remaining = [];
60
61
  if (await workerSettings(api, plan.worker) !== null) remaining.push(`worker:${plan.worker}`);
61
62
  for (const row of rows(await api.list('/workers/durable_objects/namespaces'))) if (row?.script === plan.worker) remaining.push(`durable-object:${row.class}`);
62
- if (rows(await api.request(`/workers/domains?hostname=${plan.hostname}`)).some(row => row?.hostname === plan.hostname)) remaining.push(`domain:${plan.hostname}`);
63
+ const domains = await Promise.all(plan.hostnames.map(async hostname => ({ hostname, rows: rows(await api.request(`/workers/domains?hostname=${hostname}`)) })));
64
+ for (const { hostname, rows: listed } of domains) if (listed.some(row => row?.hostname === hostname)) remaining.push(`domain:${hostname}`);
63
65
  const apps = rows(await api.request('/containers/applications'));
64
66
  for (const app of found.apps) if (apps.some(row => row?.id === app.id)) remaining.push(`container:${plan.container}`);
65
67
  if (remaining.length) { const error = new Error('remove-incomplete'); error.remaining = remaining; error.removed = removed.filter(item => !remaining.includes(item)); throw error; }
@@ -52,8 +52,17 @@ async function go(resume=false){
52
52
  show('failed',{label:'Try again',note:'',live:'',notice:'The demo could not be reached. Check your connection, then try again.'});
53
53
  }
54
54
  }
55
- function again(){
55
+ async function again(){
56
56
  attempt?.abort();attempt=null;stop();
57
+ el().auto=false;
58
+ show('working',{label:'Trying again…',note:'Your new demo will start after the human check.',live:'Trying again.',notice:''});
59
+ try{
60
+ const response=await fetch('/__demo/cancel',{method:'POST',headers:{accept:'application/json'},signal:AbortSignal.timeout(8000)});
61
+ if(!response.ok)throw new Error('cancel-failed');
62
+ }catch{
63
+ show('failed',{label:'Try again',note:'',live:'',notice:'The previous demo could not be ended. Try again.'});
64
+ return;
65
+ }
57
66
  el().auto=true;
58
67
  show('waiting',{label:'Waiting for the human check…',note:'Running the check again. The demo starts by itself once it passes.',live:'Running the human check again.',notice:''});
59
68
  turnstile.reset(el().form.querySelector('.cf-turnstile'));
@@ -15,11 +15,13 @@ export async function finishStart(demo, options) {
15
15
  } catch (error) {
16
16
  const failure = ['health-deadline', 'container-stopped', 'start-reservation-expired'].includes(error.message) ? error.message : category(error);
17
17
  demo.record('failed', { error: failure });
18
+ // Release before publishing the retry state, diagnostic capture or a slow
19
+ // destruction retry. This copy never became a live visitor's demo.
20
+ await demo.ctx.storage.put('startup', { phase: 'starting', failure: { phase: 'failed' } });
21
+ try { await demo.end(); } catch (cleanup) { report(correlation, demo.started, 'cleanup', { error: category(cleanup) }); }
18
22
  try {
19
23
  const diagnostic = await bounded(demo.diagnostic(), 3000);
20
24
  await bounded(demo.env.CAPACITY.get(demo.env.CAPACITY.idFromName('diagnostics')).record(correlation, { ...diagnostic, failure }), 3000);
21
25
  } catch (capture) { report(correlation, demo.started, 'diagnostic', { error: category(capture) }); }
22
- await demo.ctx.storage.put('startup', { phase: 'failed' });
23
- try { await demo.end(); } catch (cleanup) { report(correlation, demo.started, 'cleanup', { error: category(cleanup) }); }
24
26
  }
25
27
  }
@@ -103,17 +103,33 @@ async function start(request, env, ctx) {
103
103
  }
104
104
  }
105
105
 
106
+ // The visitor explicitly abandons this copy before running a fresh human check.
107
+ // Wait for destruction and place release; a failed cleanup must retain the cookie
108
+ // so another click can finish it instead of silently leaking a reservation.
109
+ async function cancel(request, env) {
110
+ if (request.headers.get('origin') !== env.DEMO_ORIGIN) return refusal(request, env, 403, 'Start the demo from this page.');
111
+ const id = demoId(request, env);
112
+ try { if (id) await bounded(env.DEMO.get(id).end(), 6000); }
113
+ catch { return refusal(request, env, 503, 'The previous demo could not be ended. Try again.'); }
114
+ return new Response(null, { status: 204, headers: { 'cache-control': 'no-store', 'set-cookie': clearCookie(env) } });
115
+ }
116
+
106
117
  export default {
107
118
  async fetch(request, env, ctx) {
108
119
  const url = new URL(request.url);
120
+ const primary = url.origin === env.DEMO_ORIGIN;
121
+ const secondary = JSON.parse(env.DEMO_SECONDARY_ORIGINS ?? '[]').includes(url.origin);
122
+ if (!primary && !secondary) return new Response('Not found.', { status: 404 });
123
+ if (!primary && url.pathname.startsWith('/__demo/')) return new Response('Start the demo on its primary host.', { status: 403 });
109
124
  if (url.pathname.startsWith('/__demo/operator/')) return operatorPage(request, env, url.pathname.slice('/__demo/operator/'.length));
110
125
  if (url.pathname === '/__demo/start') return request.method === 'POST' ? start(request, env, ctx) : home();
111
126
  if (url.pathname === '/__demo/status') return request.method === 'GET' ? status(request, env) : home();
127
+ if (url.pathname === '/__demo/cancel') return request.method === 'POST' ? cancel(request, env) : home();
112
128
  const id = demoId(request, env);
113
129
  if (id) {
114
130
  // The JSON start leaves the browser on /. Reloading it must keep the
115
131
  // pending copy on the progress page until health and owner claim finish.
116
- if (url.pathname === '/' && ['GET', 'HEAD'].includes(request.method)) {
132
+ if (primary && url.pathname === '/' && ['GET', 'HEAD'].includes(request.method)) {
117
133
  try {
118
134
  const state = await bounded(env.DEMO.get(id).status(), 2000);
119
135
  if (state.phase === 'starting') return progress(request, env, id, state);
@@ -122,6 +138,7 @@ export default {
122
138
  return env.DEMO.get(id).fetch(request);
123
139
  }
124
140
  if (!['GET', 'HEAD'].includes(request.method)) return new Response('Start a demo first.', { status: 403 });
141
+ if (!primary) return new Response(null, { status: 303, headers: { location: env.DEMO_ORIGIN + '/' } });
125
142
  if (url.pathname !== '/') return home();
126
143
  return startPage(env);
127
144
  },
@@ -17,8 +17,9 @@ export async function approveSetup({db,auth,request,input,contract,callbacks,clo
17
17
  }
18
18
  export async function approveOwner({store,actor,input,contract,callbacks,clock,native}) {
19
19
  const fence=native?await native.ownerFence(actor,clock()):ownerFence(actor,clock());
20
- const approval=await store.run(`INSERT INTO rer_dependency_pending(interface,issuer,approved_by,expires_at,approved_session,approved_version,callbacks,attempt_id) SELECT ?,?,?,?,?,?,?,? WHERE ${fence.sql} ON CONFLICT(interface) DO UPDATE SET issuer=excluded.issuer,approved_by=excluded.approved_by,expires_at=excluded.expires_at,approved_session=excluded.approved_session,approved_version=excluded.approved_version,callbacks=excluded.callbacks,attempt_id=excluded.attempt_id`,contract,input.issuer,actor.operator.id,clock()+600000,actor.id,actor.operator.version,callbacks,crypto.randomUUID(),...fence.args);
21
- insist(approval.meta.changes===1,'authority_changed',409);
20
+ const attempt=crypto.randomUUID();
21
+ const approval=await store.first(`INSERT INTO rer_dependency_pending(interface,issuer,approved_by,expires_at,approved_session,approved_version,callbacks,attempt_id) SELECT ?,?,?,?,?,?,?,? WHERE ${fence.sql} ON CONFLICT(interface) DO UPDATE SET issuer=excluded.issuer,approved_by=excluded.approved_by,expires_at=excluded.expires_at,approved_session=excluded.approved_session,approved_version=excluded.approved_version,callbacks=excluded.callbacks,attempt_id=excluded.attempt_id RETURNING interface,attempt_id`,contract,input.issuer,actor.operator.id,clock()+600000,actor.id,actor.operator.version,callbacks,attempt,...fence.args);
22
+ insist(approval?.interface===contract && approval.attempt_id===attempt,'authority_changed',409);
22
23
  }
23
24
  // Snapshot the attempt before network I/O. Every authority and exact attempt
24
25
  // predicate is executed again in the transaction that installs the link.
@@ -36,8 +36,8 @@ export function createDependencies({db,origin,name,provider,interfaces=[{interfa
36
36
  insist(await store.first(`SELECT 1 WHERE ${initialApproval.sql}`,...initialApproval.args),'local_owner_proof_required',403);
37
37
  const metadata=await providerMetadata(expected,fetcher,contract),installation=await store.installation(contract);
38
38
  const codeDigest=await digest(expected+'\0'+data.code);
39
- const consumed=await store.run('INSERT INTO rer_dependency_codes(digest,created_at) VALUES(?,?) ON CONFLICT DO NOTHING',codeDigest,clock());
40
- insist(consumed.meta.changes===1,'link_code_used',409);
39
+ const consumed=await store.first('INSERT INTO rer_dependency_codes(digest,created_at) VALUES(?,?) ON CONFLICT DO NOTHING RETURNING digest',codeDigest,clock());
40
+ insist(consumed?.digest===codeDigest,'link_code_used',409);
41
41
  const now=Math.floor(clock()/1000), proof=await assertion(installation.key,{iss:origin,sub:origin,aud:metadata.link.redeem,iat:now,exp:now+60,jti:crypto.randomUUID(),code:data.code,interface:contract,sector_id:installation.sector_id,callback:origin+CALLBACK});
42
42
  const result=await readJson(fetcher,metadata.link.redeem,NETWORK,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({code:data.code,interface:contract,origin,callback:origin+CALLBACK,client_assertion_type:'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',client_assertion:proof})});
43
43
  insist(result.issuer===expected && result.interface===contract && result.sector_id===installation.sector_id && result.origin===origin && result.callback===origin+CALLBACK && typeof result.client_id==='string' && result.client_id.length>0 && result.client_id.length<=512,'invalid_link_grant',403);