@runeditrun/rer 0.2.15 → 0.2.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/demo-host.mjs CHANGED
@@ -4,7 +4,7 @@ import { dirname, join } from 'node:path';
4
4
  import { contained } from './project.mjs';
5
5
  import { invalid, missing, refuse, RerError } from './errors.mjs';
6
6
  import { imageFolder } from './container.mjs';
7
- import { DEMO_FILES, demoPlan } from '../modules/demo-host/plan.mjs';
7
+ import { DEMO_FILES, INSTANCE_TYPES, demoPlan } from '../modules/demo-host/plan.mjs';
8
8
 
9
9
  // `rer deploy --demo [--dry-run]`: the seed's hosted demo at demo.<domain>
10
10
  // (modules/demo-host), from deploy-demo.json. It writes .rer/demo-host/: the
@@ -19,7 +19,7 @@ export async function demoHostCommand(project, options, store, signal, out, oper
19
19
  if (!(app.platforms ?? ['workers']).includes('container')) throw refuse('A hosted demo runs the seed\'s container image: declare "container" in deploy.json platforms first.');
20
20
  let plan;
21
21
  try { plan = demoPlan({ project: app.project, environment: options.environment ?? 'production', compatibilityDate: app.compatibilityDate, originVar: app.originVar, declaration, turnstileSiteKey: process.env.TURNSTILE_SITE_KEY?.trim() }); }
22
- catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds {"version": 1, "domain": "<run site apex>", "name": "<product name>"}, optionally "maxInstances" and plain "settings".`); }
22
+ catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds {"version": 1, "domain": "<run site apex>", "name": "<product name>"}, optionally "maxInstances", "instanceType" (${INSTANCE_TYPES.join(', ')}; default basic) and plain "settings".`); }
23
23
  if (options.remove) return removeDemo(plan, store);
24
24
  if (process.env.RER_DEMO_OPERATOR_TOKEN && (process.env.RER_DEMO_OPERATOR_TOKEN.length < 32 || process.env.RER_DEMO_OPERATOR_TOKEN.length > 512)) throw invalid('RER_DEMO_OPERATOR_TOKEN must contain 32 to 512 characters.');
25
25
  const folder = join(project.root, '.rer', 'demo-host');
@@ -29,9 +29,9 @@ export async function demoHostCommand(project, options, store, signal, out, oper
29
29
  await imageFolder(project, operation, { ...app, secrets: [...(app.secrets ?? []), { binding: 'RER_DEMO_OPERATOR_TOKEN' }, { binding: 'TURNSTILE_SECRET_KEY' }] }, { output: join(folder, 'image'), engine: 'workerd' });
30
30
  for (const file of DEMO_FILES) await cp(new URL(`../modules/demo-host/${file}`, import.meta.url), join(folder, file));
31
31
  await writeFile(join(folder, 'wrangler.json'), JSON.stringify(plan.wrangler, null, 2) + '\n');
32
- const summary = { worker: plan.worker, origin: plan.origin, hostname: plan.hostname, folder: '.rer/demo-host', maxInstances: plan.maxInstances, settings: plan.settings, instanceType: 'basic', startsPerIpPerMinute: 3, minutes: 60, idleMinutes: 15, enableInternet: false };
32
+ const summary = { worker: plan.worker, origin: plan.origin, hostname: plan.hostname, folder: '.rer/demo-host', maxInstances: plan.maxInstances, settings: plan.settings, instanceType: plan.instanceType, startsPerIpPerMinute: 3, minutes: 60, idleMinutes: 15, enableInternet: false };
33
33
  const human = [`Demo plan: Worker ${summary.worker} on ${summary.hostname} (custom domain; workers.dev off), written to ${summary.folder}`,
34
- ` one container per visitor (basic, at most ${summary.maxInstances} at once, no internet, RER_DEMO=1), 3 starts per IP per minute behind Turnstile`,
34
+ ` one container per visitor (${summary.instanceType}, at most ${summary.maxInstances} at once, no internet, RER_DEMO=1), 3 starts per IP per minute behind Turnstile`,
35
35
  ` each demo ends after 60 minutes or 15 idle minutes; its container is destroyed and its state deleted`];
36
36
  if (options.dryRun) {
37
37
  if (options.json) out.event('demo', summary); else for (const line of human) out.human(line);
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.16
4
+
5
+ - A hosted demo's container stays up until the visitor's 15 idle minutes or the demo's hour, however long the visitor goes without a request. Before, the platform stopped it about three minutes after the last request, the next request got a Cloudflare 500, and its place stayed held. A container that is gone anyway (stopped by the platform, or failing once stopped) now ends its demo, frees its place at once and answers the ended page (410, with "Start a new demo").
6
+ - `deploy-demo.json` takes an optional `instanceType`, one of Cloudflare Containers' predefined types (`lite`, `basic`, `standard-1` to `standard-4`); `basic` unless set, so existing demos are unchanged. `rer deploy --demo --dry-run` prints the planned type and refuses any other value. DEMO.md notes what a larger type costs.
7
+
8
+ ### Upgrade notes
9
+
10
+ - Update the exact rer package pin and redeploy hosted demos (`rer deploy --demo`, or run-demo) to receive the keepalive. Demos already running end as before. Set `instanceType` (for example `standard-1`) only where a faster start is worth the cost.
11
+
3
12
  ## 0.2.15
4
13
 
5
14
  - Demo pages show a slim strip pinned to the top, collapsed by default. Captured mail and blocked-send details open in a popover without moving the page.
@@ -2,7 +2,8 @@
2
2
 
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
- into the Worker's Wrangler configuration; the CLI (`cli/demo-host.mjs`) writes
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
7
  it with these files and the seed's container image folder (workerd engine) to
7
8
  `.rer/demo-host/` and runs `wrangler deploy` there.
8
9
 
@@ -21,6 +22,12 @@ it with these files and the seed's container image folder (workerd engine) to
21
22
  (`claim.mjs`) to `/auth/owner-claim`. Its alarm ends the demo at its hour or
22
23
  after 15 idle minutes: `destroy()`, `deleteAll()` and the place released. A
23
24
  container that stops by itself ends its demo too.
25
+ The platform stops a container about two minutes after its Durable Object's
26
+ last event, when it evicts the object (and the object's exit watcher with
27
+ it). So the alarm stays in flight until the demo's next check, at most three
28
+ minutes, and arms the next at once, as the Containers class keeps its own
29
+ object alive. A request or alarm that finds the container gone ends the demo
30
+ and answers the ended page (410), never a 5xx.
24
31
  - `capacity.mjs`: `DemoCapacity` admits at most `max_instances` live demos.
25
32
  - `pages.mjs`: the start and ended pages (12ui designs), strict CSP.
26
33
  `start-script.mjs` is the start page's script: once Turnstile passes it
@@ -9,6 +9,11 @@ import { endedPage, clearCookie } from './pages.mjs';
9
9
  // engine's egress worker refuse every send. The front signs the owner in
10
10
  // through the existing signed owner claim. The demo ends at its hour or after
11
11
  // 15 idle minutes: the alarm destroys the container and deletes everything.
12
+ // The platform stops a container about two minutes after its Durable Object's
13
+ // last event, when the object is evicted, and the exit watcher goes with it.
14
+ // So the alarm stays in flight until the demo's next check and then arms the
15
+ // next at once, as the Containers class keeps its object alive; a container
16
+ // that is gone anyway answers the ended page and frees its place.
12
17
  const PORT = 8080, IDLE = 15 * 60_000, OWNER = 'owner@demo.invalid';
13
18
  // The container's port speaks plain HTTP; the app takes its public origin from RER_INGRESS_ORIGIN.
14
19
  const inside = url => `http://container${url.pathname}${url.search}`;
@@ -40,6 +45,7 @@ export class DemoContainer extends DurableObject {
40
45
  startTimeout = 120_000;
41
46
  probeTimeout = 5000;
42
47
  cleanupRetry = 30_000;
48
+ hold = 3 * 60_000;
43
49
  get container() { return this.ctx.container; }
44
50
  port() { return this.container.getTcpPort(PORT); }
45
51
 
@@ -49,13 +55,13 @@ export class DemoContainer extends DurableObject {
49
55
  const deadline = this.started + this.startTimeout;
50
56
  const id = this.ctx.id.toString(), keys = await claimKeys(), now = Date.now();
51
57
  await this.ctx.storage.put({ ends, seen: now, correlation, started: this.started });
52
- await this.ctx.storage.setAlarm(Math.min(ends, now + this.idle));
53
58
  report(correlation, this.started, 'start');
54
59
  this.container.start({ enableInternet: false, env: { ...settings, RER_DEMO: '1', [originVar]: origin, RER_INGRESS_ORIGIN: origin,
55
60
  SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: OWNER, RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
56
61
  RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal } });
57
62
  // A container that stops by itself ends the demo too.
58
63
  this.watch();
64
+ await this.ctx.storage.setAlarm(Date.now());
59
65
  await this.healthy(deadline);
60
66
  const token = await signClaim(keys, { origin, installationId: id, email: OWNER, now: Date.now() });
61
67
  const claimed = await boundedFetch(this.port(), 'http://container/auth/owner-claim', { method: 'POST', redirect: 'manual',
@@ -94,17 +100,30 @@ export class DemoContainer extends DurableObject {
94
100
  /** Every request carrying this demo's cookie: proxied while the demo lives, else the ended page. */
95
101
  async fetch(request) {
96
102
  const state = await this.ctx.storage.get(['ends', 'seen']), now = Date.now();
97
- if (!(state.get('ends') > now)) return endedPage(this.env, { status: 410, headers: { 'set-cookie': clearCookie(this.env) } });
103
+ if (!(state.get('ends') > now)) return this.ended();
104
+ if (!this.container.running) return this.gone();
98
105
  if (now - state.get('seen') > 60_000) await this.ctx.storage.put('seen', now);
99
- return this.port().fetch(new Request(inside(new URL(request.url)), request));
106
+ try { return await this.port().fetch(new Request(inside(new URL(request.url)), request)); }
107
+ catch (error) { if (this.container.running && !this.stopped) throw error; return this.gone(); }
108
+ }
109
+
110
+ ended() { return endedPage(this.env, { status: 410, headers: { 'set-cookie': clearCookie(this.env) } }); }
111
+
112
+ /** A container the platform stopped while nothing watched it: end the demo (the alarm retries a failed cleanup). */
113
+ async gone() {
114
+ this.record('exit', { outcome: 'gone' });
115
+ try { await this.end(); } catch (cause) { report(this.correlation, this.started, 'cleanup', { error: category(cause) }); }
116
+ return this.ended();
100
117
  }
101
118
 
102
119
  async alarm() {
103
120
  const state = await this.ctx.storage.get(['ends', 'seen']), now = Date.now();
104
121
  if (await this.ctx.storage.get('stopping')) return this.end();
105
122
  if (!state.get('ends')) return;
106
- if (now >= state.get('ends') || now - state.get('seen') >= this.idle) return this.end();
107
- await this.ctx.storage.setAlarm(Math.min(state.get('ends'), state.get('seen') + this.idle));
123
+ const due = Math.min(state.get('ends'), state.get('seen') + this.idle);
124
+ if (now >= due || !this.container.running) return this.end();
125
+ await new Promise(resolve => { this.wake = resolve; setTimeout(resolve, Math.min(due - now, this.hold)); });
126
+ if (!this.stopped) await this.ctx.storage.setAlarm(Date.now());
108
127
  }
109
128
 
110
129
  /** Destroy the container and delete this demo's state and place; safe to repeat. */
@@ -115,7 +134,7 @@ export class DemoContainer extends DurableObject {
115
134
  }
116
135
 
117
136
  async cleanup() {
118
- this.stopped = true;
137
+ this.stopped = true; this.wake?.();
119
138
  // Keep the alarm and capacity reservation if destruction fails; retry cleanup.
120
139
  await this.ctx.storage.put('stopping', true);
121
140
  await this.ctx.storage.setAlarm(Date.now() + this.cleanupRetry);
@@ -12,28 +12,33 @@ import { siteDeclaration } from '../deploy-kit/site.mjs';
12
12
  export const DEMO_FILES = ['worker.mjs', 'container.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
+ // Cloudflare Containers' predefined instance types, smallest first (developers.cloudflare.com/containers/platform-details/limits).
16
+ export const INSTANCE_TYPES = ['lite', 'basic', 'standard-1', 'standard-2', 'standard-3', 'standard-4'];
15
17
 
16
18
  /**
17
19
  * deploy-demo.json: `{ "version": 1, "domain": "run-lamp.com", "name": "Lamp" }`, plus optionally
18
- * `maxInstances` (concurrent demos, default 10) and `settings`, the seed's plain demo settings
19
- * (such as MAIL_PROVIDER: "development"). Settings never carry secrets or what the front sets.
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").
22
+ * Settings never carry secrets or what the front sets.
20
23
  */
21
24
  export function demoDeclaration(value, originVar) {
22
- assert(value && typeof value === 'object' && !Array.isArray(value) && value.version === 1 && Object.keys(value).every(key => ['version', 'domain', 'name', 'maxInstances', 'settings'].includes(key)), 'invalid-demo-declaration');
25
+ 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');
23
26
  siteDeclaration({ version: 1, domain: value.domain });
24
27
  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');
25
28
  const maxInstances = value.maxInstances ?? 10;
26
29
  assert(Number.isSafeInteger(maxInstances) && maxInstances >= 1 && maxInstances <= 100, 'invalid-demo-max-instances');
30
+ const instanceType = value.instanceType ?? 'basic';
31
+ assert(INSTANCE_TYPES.includes(instanceType), 'invalid-demo-instance-type');
27
32
  const settings = value.settings ?? {};
28
33
  assert(settings && typeof settings === 'object' && !Array.isArray(settings) && Object.entries(settings).every(([name, setting]) =>
29
34
  /^[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');
30
- return { domain: value.domain, name: value.name, maxInstances, settings };
35
+ return { domain: value.domain, name: value.name, maxInstances, instanceType, settings };
31
36
  }
32
37
 
33
38
  /** The demo Worker's name and its Wrangler configuration; no provider request. */
34
39
  export function demoPlan({ project, environment, compatibilityDate, originVar, declaration, turnstileSiteKey }) {
35
40
  assert(/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate ?? '') && /^[A-Z][A-Z0-9_]{0,63}$/.test(originVar ?? ''), 'invalid-plan');
36
- const { domain, name, maxInstances, settings } = demoDeclaration(declaration, originVar);
41
+ const { domain, name, maxInstances, instanceType, settings } = demoDeclaration(declaration, originVar);
37
42
  const worker = `${ownerWorkerName(project, environment)}--demo`, hostname = `demo.${domain}`, container = worker.replace(/-+/g, '-');
38
43
  assert(resourceName(worker), 'owner-name-too-long');
39
44
  // Rate limit namespaces are account-wide integers: one per demo Worker.
@@ -46,10 +51,10 @@ export function demoPlan({ project, environment, compatibilityDate, originVar, d
46
51
  ...(turnstileSiteKey ? { TURNSTILE_SITE_KEY: turnstileSiteKey } : {}) },
47
52
  durable_objects: { bindings: [{ name: 'DEMO', class_name: 'DemoContainer' }, { name: 'CAPACITY', class_name: 'DemoCapacity' }] },
48
53
  migrations: [{ tag: 'v1', new_sqlite_classes: ['DemoContainer', 'DemoCapacity'] }],
49
- containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type: 'basic' }],
54
+ containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type: instanceType }],
50
55
  ratelimits: [{ name: 'STARTS', namespace_id: namespace, simple: { limit: 3, period: 60 } }],
51
56
  };
52
- return { worker, hostname, container, record: demoRecord({ worker, hostname, container }), origin: `https://${hostname}`, maxInstances, settings: Object.keys(settings), wrangler };
57
+ return { worker, hostname, container, record: demoRecord({ worker, hostname, container }), origin: `https://${hostname}`, maxInstances, instanceType, settings: Object.keys(settings), wrangler };
53
58
  }
54
59
 
55
60
  /** The demo's record of what `rer deploy --demo` creates, kept on the provider so a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.15",
3
+ "version": "0.2.16",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",