@runeditrun/rer 0.2.29 → 0.2.30

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 (48) hide show
  1. package/cli/contract.mjs +1 -1
  2. package/cli/demo-build.mjs +23 -0
  3. package/cli/demo-host.mjs +10 -70
  4. package/cli/demo-native.mjs +74 -0
  5. package/cli/lifecycle.mjs +1 -1
  6. package/cli/parse.mjs +1 -1
  7. package/global/CHANGELOG.md +13 -0
  8. package/modules/container/README.md +2 -15
  9. package/modules/container/host.mjs +1 -3
  10. package/modules/container/ingress.mjs +1 -15
  11. package/modules/container/worker-engine.mjs +2 -3
  12. package/modules/demo-host/README.md +23 -156
  13. package/modules/demo-host/build.mjs +49 -0
  14. package/modules/demo-host/capacity.mjs +8 -2
  15. package/modules/demo-host/claim.mjs +2 -2
  16. package/modules/demo-host/diagnostics.mjs +1 -18
  17. package/modules/demo-host/native/alarms.mjs +51 -0
  18. package/modules/demo-host/native/bindings.mjs +24 -0
  19. package/modules/demo-host/native/bridge.mjs +17 -0
  20. package/modules/demo-host/native/config.mjs +35 -0
  21. package/modules/demo-host/native/cron.mjs +31 -0
  22. package/modules/demo-host/native/d1.mjs +37 -0
  23. package/modules/demo-host/native/deploy-r2.mjs +43 -0
  24. package/modules/demo-host/native/isolate.mjs +36 -0
  25. package/modules/demo-host/native/loader.mjs +30 -0
  26. package/modules/demo-host/native/namespace.mjs +35 -0
  27. package/modules/demo-host/native/prepare.mjs +35 -0
  28. package/modules/demo-host/native/queues.mjs +62 -0
  29. package/modules/demo-host/native/r2-client.mjs +37 -0
  30. package/modules/demo-host/native/r2.mjs +43 -0
  31. package/modules/demo-host/native/resources.mjs +37 -0
  32. package/modules/demo-host/native/seed-object.mjs +22 -0
  33. package/modules/demo-host/native/sql.mjs +17 -0
  34. package/modules/demo-host/native/visitor.mjs +147 -0
  35. package/modules/demo-host/native/worker.mjs +22 -0
  36. package/modules/demo-host/pages.mjs +1 -1
  37. package/modules/demo-host/plan.mjs +9 -30
  38. package/modules/demo-host/remove.mjs +13 -23
  39. package/modules/demo-host/upgrade.mjs +41 -0
  40. package/modules/demo-host/worker.mjs +3 -4
  41. package/package.json +1 -1
  42. package/modules/demo-host/container.mjs +0 -221
  43. package/modules/demo-host/entrypoint.sh +0 -9
  44. package/modules/demo-host/image.mjs +0 -18
  45. package/modules/demo-host/placement.mjs +0 -37
  46. package/modules/demo-host/prepare.mjs +0 -28
  47. package/modules/demo-host/startup.mjs +0 -27
  48. package/modules/demo-host/template.mjs +0 -71
@@ -0,0 +1,22 @@
1
+ import { env } from 'cloudflare:workers';
2
+
3
+ // Facets have SQLite and WebSockets but no native alarms. Keep the seed's
4
+ // original context (including native methods) and replace only the alarm API.
5
+ export function seedObject(Original, binding) {
6
+ return class extends Original {
7
+ constructor(ctx, bindings) {
8
+ const call = (method, at) => env.RER_NATIVE_HOST.seedAlarm(binding, ctx.id.toString(), method, at);
9
+ ctx.storage.setAlarm = at => call('set', at instanceof Date ? at.getTime() : at);
10
+ ctx.storage.getAlarm = () => call('get');
11
+ ctx.storage.deleteAlarm = () => call('delete');
12
+ super(ctx, bindings);
13
+ }
14
+ async fetch(request) {
15
+ if (request.headers.get('x-rer-native-alarm-key') === env.RER_NATIVE_KEY) {
16
+ await super.alarm(JSON.parse(request.headers.get('x-rer-native-alarm-info')));
17
+ return new Response(null, { status: 204 });
18
+ }
19
+ return super.fetch(request);
20
+ }
21
+ };
22
+ }
@@ -0,0 +1,17 @@
1
+ export function sqlite(storage) {
2
+ let lastRowId = 0;
3
+ function query(query, args = []) {
4
+ const started = performance.now();
5
+ const read = /^\s*(?:SELECT|EXPLAIN)\b/i.test(query);
6
+ const before = read ? 0 : storage.sql.exec('SELECT total_changes() AS n').one().n;
7
+ const cursor = storage.sql.exec(query, ...args);
8
+ const columns = cursor.columnNames;
9
+ const rows = [...cursor.raw()].map(row => row.map(value => value instanceof ArrayBuffer ? [...new Uint8Array(value)] : value));
10
+ const after = read ? { n: 0, id: lastRowId } : storage.sql.exec('SELECT total_changes() AS n, last_insert_rowid() AS id').one();
11
+ lastRowId = after.id;
12
+ return { success: true, results: rows.map(row => Object.fromEntries(columns.map((column, index) => [column, row[index]]))), columns, rows,
13
+ meta: { duration: performance.now() - started, changes: after.n - before, last_row_id: after.id, changed_db: after.n !== before, rows_read: cursor.rowsRead, rows_written: cursor.rowsWritten } };
14
+ }
15
+ return { query, batch: statements => storage.transactionSync(() => statements.map(statement => query(statement.query, statement.args))),
16
+ exec(query) { const started = performance.now(); storage.sql.exec(query).toArray(); return { count: query.split('\n').filter(line => line.trim()).length, duration: performance.now() - started }; } };
17
+ }
@@ -0,0 +1,147 @@
1
+ import { DurableObject } from 'cloudflare:workers';
2
+ import { claimKeys, signClaim } from '../claim.mjs';
3
+ import { migrate } from '../../container/migrations.mjs';
4
+ import { DemoD1 } from './d1.mjs';
5
+ import { application, bundle } from './loader.mjs';
6
+ import { database, object, r2, eraseResources } from './resources.mjs';
7
+ import { enqueue, deliverQueues, nextQueue, queueMetrics } from './queues.mjs';
8
+ import { seedAlarm, nextSeedAlarm, deliverSeedAlarms } from './alarms.mjs';
9
+ import { cronMatches } from './cron.mjs';
10
+ import { endedPage, clearCookie } from '../pages.mjs';
11
+
12
+ const IDLE = 15 * 60_000;
13
+ const random = () => [...crypto.getRandomValues(new Uint8Array(32))].map(byte => byte.toString(16).padStart(2, '0')).join('');
14
+ export class NativeDemo extends DurableObject {
15
+ constructor(ctx, env) {
16
+ super(ctx, env);
17
+ ctx.blockConcurrencyWhile(async () => { this.state = await ctx.storage.get('visitor'); });
18
+ }
19
+ async save() { await this.ctx.storage.put('visitor', this.state); }
20
+ async begin(options) {
21
+ try { return await this.start(options); }
22
+ catch (error) {
23
+ await this.diagnostic(options.correlation, error);
24
+ await this.end();
25
+ return { phase: 'failed', correlation: options.correlation };
26
+ }
27
+ }
28
+ async diagnostic(correlation, error) {
29
+ await this.env.CAPACITY.get(this.env.CAPACITY.idFromName('diagnostics')).record(correlation, { failure: String(error.message).slice(0, 1000) });
30
+ }
31
+ async start({ origin, originVar, ends, endsLocal, settings, correlation, clientIp }) {
32
+ if (this.state) return this.status();
33
+ const id = this.ctx.id.toString(), keys = await claimKeys(), started = Date.now();
34
+ // Short TTLs are usable only on the guarded testing host.
35
+ if (/^[123]x0{31}AA$/.test(this.env.TURNSTILE_SECRET_KEY ?? '') && this.env.NATIVE_TEST_TTL_MS) ends = Math.min(ends, started + Number(this.env.NATIVE_TEST_TTL_MS));
36
+ const runtime = { ...bundle.vars, ...settings, RER_DEMO: '1', [originVar]: origin,
37
+ RER_NATIVE_KEY: random(), SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: this.env.DEMO_OWNER_EMAIL || 'owner@demo.invalid',
38
+ RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
39
+ RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal };
40
+ this.state = { phase: 'starting', runtime, ends, seen: started, savedSeen: started, lastCron: Math.floor(started / 60_000), correlation };
41
+ await this.save();
42
+ await this.ctx.storage.setAlarm(Math.min(ends, started + IDLE));
43
+ try {
44
+ const at = Date.now();
45
+ const app = application(this.env, this.ctx, id, runtime);
46
+ for (const binding of bundle.bindings.databases) {
47
+ const sql = { query: (...args) => this.database(binding, 'query', args), batch: (...args) => this.database(binding, 'batch', args), exec: (...args) => this.database(binding, 'exec', args) };
48
+ await migrate(new DemoD1(sql), bundle.migrations[binding] ?? []);
49
+ }
50
+ const migrated = Date.now();
51
+ const token = await signClaim(keys, { origin, installationId: id, email: runtime.OWNER_EMAIL, now: Date.now() });
52
+ const claimed = await app.fetch(new Request(origin + '/auth/owner-claim', { method: 'POST', redirect: 'manual', headers: { origin, 'cf-connecting-ip': clientIp, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ token }) }));
53
+ if (claimed.status !== 303) throw new Error(`owner-claim-${claimed.status}: ${(await claimed.text()).slice(0, 500)}`);
54
+ await claimed.body?.cancel();
55
+ const cookies = claimed.headers.getSetCookie();
56
+ const seeded = await app.fetch(new Request(origin + '/health', { headers: { cookie: cookies.map(cookie => cookie.split(';')[0]).join('; ') } }));
57
+ await seeded.arrayBuffer();
58
+ if (!seeded.ok) throw new Error(`demo-seed-${seeded.status}`);
59
+ if (this.state?.phase !== 'starting') throw new Error('demo-ended-during-start');
60
+ if (!await this.capacity().extend(id, ends)) throw new Error('start-reservation-expired');
61
+ this.state = { ...this.state, phase: 'ready', cookies, location: claimed.headers.get('location'), timing: { migrationsMs: migrated - at, claimAndSeedMs: Date.now() - migrated, totalMs: Date.now() - started } };
62
+ await this.save();
63
+ await this.schedule(await nextQueue(this));
64
+ return this.status();
65
+ } catch (error) {
66
+ console.error(JSON.stringify({ event: 'native-demo-start-failed', correlation, message: error.message }));
67
+ await this.diagnostic(correlation, error);
68
+ await this.end();
69
+ return { phase: 'failed', correlation };
70
+ }
71
+ }
72
+ capacity() { return this.env.CAPACITY.get(this.env.CAPACITY.idFromName('capacity')); }
73
+ async active() {
74
+ if (this.state?.phase === 'ending') throw new Error('demo-ended');
75
+ if (!this.state || this.state.ends <= Date.now() || this.state.seen + IDLE <= Date.now()) {
76
+ if (this.state) await this.end();
77
+ throw new Error('demo-ended');
78
+ }
79
+ }
80
+ async session() {
81
+ try { await this.active(); } catch { return null; }
82
+ if (this.state.phase !== 'ready') return null;
83
+ this.state.seen = Date.now();
84
+ if (this.state.seen - this.state.savedSeen >= 60_000) {
85
+ this.state.savedSeen = this.state.seen;
86
+ await this.save();
87
+ }
88
+ return this.state.runtime;
89
+ }
90
+ status() { return this.state && this.state.phase !== 'ending' ? { phase: this.state.phase, cookies: this.state.cookies ?? [], location: this.state.location, correlation: this.state.correlation, timing: this.state.timing } : { phase: 'failed' }; }
91
+ async fetch(request) {
92
+ if (this.state && request.headers.get('x-rer-native-key') === this.state.runtime.RER_NATIVE_KEY) {
93
+ const [binding, id] = (request.headers.get('x-rer-native-object') ?? '').split(':');
94
+ const headers = new Headers(request.headers);
95
+ headers.delete('x-rer-native-key'); headers.delete('x-rer-native-object');
96
+ return this.object(binding, id, 'fetch', [new Request(request, { headers })]);
97
+ }
98
+ const runtime = await this.session();
99
+ if (!runtime) return endedPage(this.env, { headers: { 'set-cookie': clearCookie(this.env) } });
100
+ return application(this.env, this.ctx, this.ctx.id.toString(), runtime).fetch(request);
101
+ }
102
+ database(binding, method, args) { return database(this, binding, method, args); }
103
+ object(binding, id, method, args) { return object(this, binding, id, method, args); }
104
+ r2(binding, method, args) { return r2(this, binding, method, args); }
105
+ queueMetrics(queue) { return queueMetrics(this, queue); }
106
+ enqueue(queue, messages) { return enqueue(this, queue, messages); }
107
+ seedAlarm(binding, id, method, at) { return seedAlarm(this, binding, id, method, at); }
108
+ async schedule(candidate = Infinity) {
109
+ if (!this.state || this.state.phase === 'ending') return;
110
+ const at = Math.max(Date.now() + 50, Math.min(candidate, await nextSeedAlarm(this), this.state.ends, this.state.seen + IDLE, (Math.floor(Date.now() / 60_000) + 1) * 60_000));
111
+ const current = await this.ctx.storage.getAlarm();
112
+ if (!current || current > at) await this.ctx.storage.setAlarm(at);
113
+ }
114
+ async alarm() {
115
+ if (this.state?.phase === 'ending') return this.end();
116
+ try { await this.active(); } catch { return; }
117
+ try {
118
+ if (this.state.phase === 'ready') {
119
+ const now = Date.now(), minute = Math.floor(now / 60_000);
120
+ if (minute > this.state.lastCron) {
121
+ this.state.lastCron = minute;
122
+ await this.save();
123
+ for (const cron of bundle.crons) if (cronMatches(cron, new Date(now))) {
124
+ await application(this.env, this.ctx, this.ctx.id.toString(), this.state.runtime).runScheduled(minute * 60_000, cron);
125
+ console.log(JSON.stringify({ event: 'native-demo-scheduled', correlation: this.state?.correlation, cron }));
126
+ }
127
+ }
128
+ await deliverSeedAlarms(this, now);
129
+ await deliverQueues(this, now);
130
+ }
131
+ } finally { await this.schedule(await nextQueue(this)); }
132
+ }
133
+ end() {
134
+ if (!this.ending) this.ending = this.erase().finally(() => { this.ending = undefined; });
135
+ return this.ending;
136
+ }
137
+ async erase() {
138
+ if (this.state) { this.state.phase = 'ending'; await this.save(); }
139
+ // Keep a retry alarm until external objects have actually been erased.
140
+ await this.ctx.storage.setAlarm(Date.now() + 10_000);
141
+ await eraseResources(this);
142
+ await this.ctx.storage.deleteAll();
143
+ await this.ctx.storage.deleteAlarm();
144
+ this.state = undefined;
145
+ await this.capacity().release(this.ctx.id.toString());
146
+ }
147
+ }
@@ -0,0 +1,22 @@
1
+ import front from '../worker.mjs';
2
+ import { bundle } from './loader.mjs';
3
+ export { HostBridge } from './bridge.mjs';
4
+ export { DemoAssets, DemoEgress } from './loader.mjs';
5
+ export { NativeDemo } from './visitor.mjs';
6
+ export { DemoCapacity } from '../capacity.mjs';
7
+
8
+ const assets = new Set(bundle.assetPaths);
9
+ export default {
10
+ async fetch(request, env, ctx) {
11
+ const url = new URL(request.url);
12
+ if (url.origin !== env.DEMO_ORIGIN && !JSON.parse(env.DEMO_SECONDARY_ORIGINS ?? '[]').includes(url.origin)) return new Response('Not found.', { status: 404 });
13
+ if (['GET', 'HEAD'].includes(request.method) && assets.has(url.pathname)) {
14
+ const response = await env.ASSETS.fetch(request);
15
+ const headers = new Headers(response.headers);
16
+ if (/^\/assets\/.*-[\w-]{8,}\.[\w]+$/.test(url.pathname)) headers.set('cache-control', 'public, max-age=31536000, immutable');
17
+ headers.set('x-rer-demo-assets', 'edge');
18
+ return new Response(response.body, { status: response.status, headers });
19
+ }
20
+ return front.fetch(request, env, ctx);
21
+ },
22
+ };
@@ -44,7 +44,7 @@ export function startPage(env, { status = 200, notice, pending = false, headers
44
44
  <p class="note" id="note">${pending ? 'Your demo will open automatically when ready.' : 'Complete the human check to start your demo.'}</p><noscript><p class="note">The human check needs JavaScript. Turn it on to start the demo.</p></noscript><p class="visually-hidden" id="status" role="status"></p></form>` });
45
45
  }
46
46
 
47
- /** A demo whose hour or idle time is up: its container and data are gone. */
47
+ /** A demo whose hour or idle time is up: its isolate and data are gone. */
48
48
  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>
@@ -3,46 +3,29 @@ import { assert, hash, resourceName } from '../deploy-kit/validation.mjs';
3
3
  import { ownerWorkerName } from '../deploy-kit/owner.mjs';
4
4
  import { siteDeclaration } from '../deploy-kit/site.mjs';
5
5
 
6
- /* A seed's hosted demo at demo.<domain>: the Worker `rer deploy --demo` builds
7
- * from deploy-demo.json, as `rer deploy --site` builds the run site from
8
- * deploy-site.json. It is this folder's front Worker plus a Container class
9
- * running the seed's own image (`rer build --platform container`, workerd
10
- * engine), deployed by `wrangler deploy` with the image beside it. */
11
-
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', 'measurement.mjs'];
6
+ // Native Loader front, admission and visitor session support.
7
+ export const DEMO_FILES = ['worker.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs', 'measurement.mjs'];
13
8
  const FRONT_SET = /^(?:RER_.*|SESSION_SECRET|SETUP_TOKEN|OWNER_EMAIL)$/;
14
9
  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'];
17
-
18
- /**
19
- * deploy-demo.json: `{ "version": 1, "domain": "run-lamp.com", "name": "Lamp" }`, plus optionally
20
- * `maxInstances` (concurrent demos, default 10), `instanceType` (one of INSTANCE_TYPES, default
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
- * 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.
25
- */
26
10
  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', 'ownerEmail', 'settings'].includes(key)), 'invalid-demo-declaration');
11
+ assert(value && typeof value === 'object' && !Array.isArray(value) && value.version === 1 && Object.keys(value).every(key => ['version', 'domain', 'name', 'maxInstances', 'ownerEmail', 'settings'].includes(key)), 'invalid-demo-declaration');
28
12
  siteDeclaration({ version: 1, domain: value.domain });
29
13
  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
14
  const maxInstances = value.maxInstances ?? 10;
31
15
  assert(Number.isSafeInteger(maxInstances) && maxInstances >= 1 && maxInstances <= 100, 'invalid-demo-max-instances');
32
- const instanceType = value.instanceType ?? 'basic';
33
- assert(INSTANCE_TYPES.includes(instanceType), 'invalid-demo-instance-type');
34
16
  const ownerEmail = value.ownerEmail;
35
17
  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');
36
18
  const settings = value.settings ?? {};
37
19
  assert(settings && typeof settings === 'object' && !Array.isArray(settings) && Object.entries(settings).every(([name, setting]) =>
38
20
  /^[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');
39
- return { domain: value.domain, name: value.name, maxInstances, instanceType, ownerEmail, settings };
21
+ return { domain: value.domain, name: value.name, maxInstances, ownerEmail, settings };
40
22
  }
41
23
 
42
24
  /** The demo Worker's name and its Wrangler configuration; no provider request. */
43
25
  export function demoPlan({ project, environment, compatibilityDate, originVar, hostVariables = [], declaration, turnstileSiteKey }) {
44
26
  assert(/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate ?? '') && /^[A-Z][A-Z0-9_]{0,63}$/.test(originVar ?? ''), 'invalid-plan');
45
- const { domain, name, maxInstances, instanceType, ownerEmail, settings } = demoDeclaration(declaration, originVar);
27
+ const { domain, name, maxInstances, ownerEmail, settings } = demoDeclaration(declaration, originVar);
28
+ // Keep the historical container name in the ownership hash for released hosts.
46
29
  const worker = `${ownerWorkerName(project, environment)}--demo`, hostname = `demo.${domain}`, container = worker.replace(/-+/g, '-');
47
30
  assert(resourceName(worker), 'owner-name-too-long');
48
31
  assert(Array.isArray(hostVariables) && hostVariables.every(variable => typeof variable === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(variable)), 'invalid-demo-host-variables');
@@ -63,15 +46,11 @@ export function demoPlan({ project, environment, compatibilityDate, originVar, h
63
46
  observability: { enabled: true, head_sampling_rate: 1, logs: { enabled: true, invocation_logs: false } },
64
47
  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}`)),
65
48
  ...(ownerEmail ? { DEMO_OWNER_EMAIL: ownerEmail } : {}), ...(turnstileSiteKey ? { TURNSTILE_SITE_KEY: turnstileSiteKey } : {}) },
66
- durable_objects: { bindings: [{ name: 'DEMO', class_name: 'DemoContainer' }, { name: 'CAPACITY', class_name: 'DemoCapacity' }] },
67
- migrations: [{ tag: 'v1', new_sqlite_classes: ['DemoContainer', 'DemoCapacity'] }],
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 }],
49
+ durable_objects: { bindings: [{ name: 'DEMO', class_name: 'NativeDemo' }, { name: 'CAPACITY', class_name: 'DemoCapacity' }] },
50
+ migrations: [{ tag: 'native-v2', new_sqlite_classes: ['NativeDemo', 'DemoCapacity'] }],
72
51
  ratelimits: [{ name: 'STARTS', namespace_id: namespace, simple: { limit: 3, period: 60 } }],
73
52
  };
74
- return { worker, hostname, hostnames, container, record: demoRecord({ worker, hostname, hostnames, container }), origin: `https://${hostname}`, maxInstances, instanceType, settings: Object.keys(settings), wrangler };
53
+ return { worker, hostname, hostnames, container, record: demoRecord({ worker, hostname, hostnames, container }), origin: `https://${hostname}`, maxInstances, settings: Object.keys(settings), wrangler };
75
54
  }
76
55
 
77
56
  /** The demo's record of what `rer deploy --demo` creates, kept on the provider so a
@@ -1,35 +1,25 @@
1
+ import { ownedBucket, removeBucket } from './native/deploy-r2.mjs';
1
2
  import { assert } from '../deploy-kit/validation.mjs';
2
3
  import { workerSettings } from '../deploy-kit/owner.mjs';
3
4
  import { servedVersion } from '../deploy-kit/site.mjs';
4
5
  import { deleteWorker } from '../deploy-kit/teardown.mjs';
5
6
 
6
- /* `rer deploy --demo --remove --yes`: remove the hosted demo `rer deploy --demo`
7
- * made for this environment, by exact provider ids, and nothing else. What the
8
- * deploy made: the front Worker (its Durable Object namespaces go with it), the
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
- * the Worker's DemoContainer namespace. It makes no D1, KV, R2, queue or DNS
12
- * record of its own: the domain's record is Cloudflare's, and goes with it.
13
- *
14
- * The Worker is the demo's own only while it serves the version carrying the
15
- * demo's record (plan.mjs `demoRecord`). The domain is the demo's only while it
16
- * routes to that Worker, the Container application only while it belongs to
17
- * that Worker's DemoContainer namespace. Anything else of those names, or
18
- * attached to that Worker, is refused before the first delete. The Worker goes
19
- * last, so a run cut short leaves the record for the next one; once everything
20
- * is gone a second run is a no-op. */
7
+ // Exact-id teardown and ownership inventory, shared by native upgrades.
8
+ // The Worker is deleted last so interrupted removal retains its ownership record.
21
9
 
22
10
  function refuse(code, resource) { const error = new Error(code); error.resource = resource; return error; }
23
11
  const rows = value => { assert(Array.isArray(value), 'provider-invalid-list'); return value; };
24
12
 
25
13
  /** What exists of the demo now, each with its exact id; refuses whatever is not provably the demo's. */
26
- async function inventory(api, plan) {
14
+ export async function demoInventory(api, plan) {
27
15
  const named = (await Promise.all(plan.hostnames.map(async hostname =>
28
16
  rows(await api.request(`/workers/domains?hostname=${hostname}`)).filter(row => row?.hostname === hostname)))).flat();
29
17
  const attached = rows(await api.request(`/workers/domains?service=${plan.worker}`)).filter(row => row?.service === plan.worker);
30
- const apps = rows(await api.request('/containers/applications')).filter(row => row?.name === plan.container);
31
18
  const namespaces = rows(await api.list('/workers/durable_objects/namespaces')).filter(row => row?.script === plan.worker);
32
- const worker = await workerSettings(api, plan.worker) !== null;
19
+ const settings = await workerSettings(api, plan.worker);
20
+ const worker = settings !== null;
21
+ const container = namespaces.find(row => row.class === 'DemoContainer')?.id;
22
+ const apps = container ? rows(await api.request('/containers/applications')).filter(row => row?.name === plan.container || row?.durable_objects?.namespace_id === container) : [];
33
23
  for (const row of named) if (row.service !== plan.worker) throw refuse('resource-name-collision', `domain:${row.hostname}`);
34
24
  if (worker) {
35
25
  const served = await servedVersion(api, plan.worker);
@@ -40,13 +30,12 @@ async function inventory(api, plan) {
40
30
  // Without the Worker nothing proves these are the demo's.
41
31
  throw refuse('uncertain-resource-create', named[0] || attached[0] ? `domain:${(named[0] ?? attached[0]).hostname}` : `container:${plan.container}`);
42
32
  }
43
- const container = namespaces.find(row => row.class === 'DemoContainer')?.id;
44
- for (const app of apps) if (!container || app.durable_objects?.namespace_id !== container) throw refuse('resource-name-collision', `container:${plan.container}`);
45
- return { worker, domains: named, apps };
33
+ for (const app of apps) if (app.name !== plan.container || !container || app.durable_objects?.namespace_id !== container) throw refuse('resource-name-collision', `container:${plan.container}`);
34
+ return { worker, settings, namespaces, domains: named, apps, bucket: worker ? await ownedBucket(api, plan, settings) : null };
46
35
  }
47
36
 
48
37
  export async function demoRemove({ api, plan, sleep }) {
49
- const found = await inventory(api, plan);
38
+ const found = await demoInventory(api, plan);
50
39
  if (!found.worker) return { worker: plan.worker, removed: [], remaining: [], alreadyRemoved: true };
51
40
  const removed = [];
52
41
  for (const domain of found.domains) {
@@ -54,6 +43,7 @@ export async function demoRemove({ api, plan, sleep }) {
54
43
  removed.push(`domain:${domain.hostname}`);
55
44
  }
56
45
  for (const app of found.apps) { await api.request(`/containers/applications/${app.id}`, { method: 'DELETE' }); removed.push(`container:${plan.container}`); }
46
+ if (found.bucket) { await removeBucket(api, found.bucket); removed.push(`r2:${found.bucket.name}`); }
57
47
  await deleteWorker({ api, worker: plan.worker, ...sleep ? { sleep } : {} });
58
48
  removed.push(`worker:${plan.worker}`);
59
49
  // Read back: nothing of the demo is listed any more.
@@ -62,7 +52,7 @@ export async function demoRemove({ api, plan, sleep }) {
62
52
  for (const row of rows(await api.list('/workers/durable_objects/namespaces'))) if (row?.script === plan.worker) remaining.push(`durable-object:${row.class}`);
63
53
  const domains = await Promise.all(plan.hostnames.map(async hostname => ({ hostname, rows: rows(await api.request(`/workers/domains?hostname=${hostname}`)) })));
64
54
  for (const { hostname, rows: listed } of domains) if (listed.some(row => row?.hostname === hostname)) remaining.push(`domain:${hostname}`);
65
- const apps = rows(await api.request('/containers/applications'));
55
+ const apps = found.apps.length ? rows(await api.request('/containers/applications')) : [];
66
56
  for (const app of found.apps) if (apps.some(row => row?.id === app.id)) remaining.push(`container:${plan.container}`);
67
57
  if (remaining.length) { const error = new Error('remove-incomplete'); error.remaining = remaining; error.removed = removed.filter(item => !remaining.includes(item)); throw error; }
68
58
  return { worker: plan.worker, removed, remaining: [] };
@@ -0,0 +1,41 @@
1
+ import { demoInventory } from './remove.mjs';
2
+
3
+ // Keep the Worker and custom domains throughout the transition. Container apps
4
+ // must go before deleting their backing class; Wrangler then applies the class
5
+ // migration atomically with the native code. A failed upload can be rerun.
6
+ export async function upgradeDemo({ api, plan }) {
7
+ const found = await demoInventory(api, plan);
8
+ const classes = found.namespaces.map(row => row.class);
9
+ const unknown = classes.filter(name => !['DemoContainer', 'NativeDemo', 'DemoCapacity'].includes(name));
10
+ if (unknown.length) throw new Error('demo-upgrade-unknown-class');
11
+ const service = found.worker ? await api.request(`/workers/services/${plan.worker}`) : null;
12
+ const tag = service?.default_environment?.script?.migration_tag;
13
+ if (found.worker && classes.length && !tag) throw new Error('demo-upgrade-missing-migration-tag');
14
+ const migration = { tag: 'native-v2' };
15
+ const added = ['NativeDemo', 'DemoCapacity'].filter(name => !classes.includes(name));
16
+ if (added.length) migration.new_sqlite_classes = added;
17
+ if (classes.includes('DemoContainer')) migration.deleted_classes = ['DemoContainer'];
18
+ if (tag === migration.tag && (added.length || migration.deleted_classes)) throw new Error('demo-upgrade-inconsistent-migration');
19
+ for (const app of found.apps) await api.request(`/containers/applications/${app.id}`, { method: 'DELETE' });
20
+ if (found.apps.length) {
21
+ const remaining = await api.request('/containers/applications');
22
+ if (remaining.some(row => found.apps.some(app => app.id === row.id))) throw new Error('demo-upgrade-container-remove-incomplete');
23
+ }
24
+ if (classes.includes('DemoContainer')) {
25
+ // The API checks the currently deployed bindings before class deletion.
26
+ // Detach the retired binding first; inherit every other value by name,
27
+ // including secrets, and retain the ownership annotation for a rerun.
28
+ const body = new FormData();
29
+ body.set('settings', new Blob([JSON.stringify({
30
+ annotations: { 'workers/message': plan.record },
31
+ bindings: found.settings.bindings.filter(binding => !(binding.type === 'durable_object_namespace' && binding.class_name === 'DemoContainer'))
32
+ .map(binding => ({ name: binding.name, type: 'inherit' })),
33
+ })], { type: 'application/json' }));
34
+ await api.request(`/workers/scripts/${plan.worker}/settings`, { method: 'PATCH', body });
35
+ }
36
+ // Wrangler validates the full declared history locally, even though only
37
+ // steps after the deployed tag are sent. Describe the existing classes in
38
+ // that historical step so a deletion resolves without shipping old code.
39
+ if (tag === migration.tag) return [{ tag, new_sqlite_classes: classes }];
40
+ return tag ? [{ tag, new_sqlite_classes: classes }, migration] : [migration];
41
+ }
@@ -1,16 +1,15 @@
1
1
  // A seed's hosted demo at demo.<domain>, generated by `rer deploy --demo`.
2
2
  // GET / shows the start page (a Turnstile managed widget that starts the demo by itself).
3
3
  // POST /__demo/start checks the visitor's IP rate limit, Turnstile and capacity,
4
- // then starts a container of their own, signs its owner in and sets the
4
+ // then starts a native isolate of their own, signs its owner in and sets the
5
5
  // rer_demo cookie. The page's script asks for JSON (Accept: application/json) to
6
6
  // show its progress and failures; a plain form post gets the 303 or the page. Every request with that cookie goes to the visitor's
7
- // container; nothing else on this host is reachable.
7
+ // isolate; nothing else on this host is reachable.
8
8
  import { operatorPage } from './operator.mjs';
9
9
  import { measured, testHost } from './measurement.mjs';
10
10
  import { bounded, category, report } from './diagnostics.mjs';
11
11
  import { startPage, demoCookie, clearCookie } from './pages.mjs';
12
12
 
13
- export { DemoContainer } from './container.mjs';
14
13
  export { DemoCapacity } from './capacity.mjs';
15
14
 
16
15
  const HOUR = 60 * 60_000;
@@ -106,7 +105,7 @@ async function start(request, env, ctx) {
106
105
  // Who holds the place: automated browsers pass Turnstile's testing keys.
107
106
  report(correlation, started, 'admitted', { agent: (request.headers.get('user-agent') ?? '').slice(0, 160), network: request.cf?.asOrganization ?? null });
108
107
  demo = env.DEMO.get(id);
109
- const begun = demo.begin({ correlation, origin: env.DEMO_ORIGIN, originVar: env.DEMO_ORIGIN_VAR, ends, endsLocal: localTime(ends, request.cf?.timezone), settings: JSON.parse(env.DEMO_SETTINGS) });
108
+ const begun = demo.begin({ correlation, clientIp: ip, origin: env.DEMO_ORIGIN, originVar: env.DEMO_ORIGIN_VAR, ends, endsLocal: localTime(ends, request.cf?.timezone), settings: JSON.parse(env.DEMO_SETTINGS) });
110
109
  // A new object can take seconds to answer. That is a slow start, not a
111
110
  // failed one: the page polls this copy, and a begin that later fails ends
112
111
  // it and releases its place.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.29",
3
+ "version": "0.2.30",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",