@runeditrun/rer 0.2.28 → 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 (70) hide show
  1. package/cli/contract.mjs +3 -3
  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/inspect.mjs +5 -1
  6. package/cli/lifecycle.mjs +1 -1
  7. package/cli/main.mjs +6 -1
  8. package/cli/parse.mjs +9 -2
  9. package/cli/placeholder-mark.mjs +46 -0
  10. package/cli/release.mjs +6 -2
  11. package/global/CHANGELOG.md +27 -0
  12. package/modules/container/README.md +2 -15
  13. package/modules/container/host.mjs +1 -3
  14. package/modules/container/ingress.mjs +1 -15
  15. package/modules/container/worker-engine.mjs +2 -3
  16. package/modules/demo-host/README.md +23 -156
  17. package/modules/demo-host/build.mjs +49 -0
  18. package/modules/demo-host/capacity.mjs +8 -2
  19. package/modules/demo-host/claim.mjs +2 -2
  20. package/modules/demo-host/diagnostics.mjs +1 -18
  21. package/modules/demo-host/native/alarms.mjs +51 -0
  22. package/modules/demo-host/native/bindings.mjs +24 -0
  23. package/modules/demo-host/native/bridge.mjs +17 -0
  24. package/modules/demo-host/native/config.mjs +35 -0
  25. package/modules/demo-host/native/cron.mjs +31 -0
  26. package/modules/demo-host/native/d1.mjs +37 -0
  27. package/modules/demo-host/native/deploy-r2.mjs +43 -0
  28. package/modules/demo-host/native/isolate.mjs +36 -0
  29. package/modules/demo-host/native/loader.mjs +30 -0
  30. package/modules/demo-host/native/namespace.mjs +35 -0
  31. package/modules/demo-host/native/prepare.mjs +35 -0
  32. package/modules/demo-host/native/queues.mjs +62 -0
  33. package/modules/demo-host/native/r2-client.mjs +37 -0
  34. package/modules/demo-host/native/r2.mjs +43 -0
  35. package/modules/demo-host/native/resources.mjs +37 -0
  36. package/modules/demo-host/native/seed-object.mjs +22 -0
  37. package/modules/demo-host/native/sql.mjs +17 -0
  38. package/modules/demo-host/native/visitor.mjs +147 -0
  39. package/modules/demo-host/native/worker.mjs +22 -0
  40. package/modules/demo-host/pages.mjs +1 -1
  41. package/modules/demo-host/plan.mjs +9 -30
  42. package/modules/demo-host/remove.mjs +13 -23
  43. package/modules/demo-host/upgrade.mjs +41 -0
  44. package/modules/demo-host/worker.mjs +3 -4
  45. package/modules/mail/README.md +18 -5
  46. package/modules/mail/src/adapters/rer/contract.mjs +5 -0
  47. package/modules/mail/src/adapters/rer/index.mjs +4 -2
  48. package/modules/mail/src/adapters/rer/list-headers.mjs +5 -0
  49. package/modules/mail/src/core/validation.mjs +7 -2
  50. package/modules/mail/src/development/index.d.mts +1 -0
  51. package/modules/operator-auth/README.md +11 -0
  52. package/modules/operator-auth/accounts/one-click.mjs +63 -0
  53. package/modules/operator-auth/accounts/store.mjs +3 -3
  54. package/modules/operator-auth/dev/index.mjs +26 -13
  55. package/modules/operator-auth/index.d.mts +5 -0
  56. package/modules/operator-auth/routes.mjs +20 -1
  57. package/modules/operator-auth/service.mjs +2 -0
  58. package/modules/operator-auth/signin/index.mjs +7 -0
  59. package/modules/operator-auth/signin/one-click.mjs +7 -0
  60. package/modules/portability/catalogue.mjs +3 -3
  61. package/modules/release/produce.mjs +8 -1
  62. package/onboarding/README.md +4 -0
  63. package/package.json +1 -1
  64. package/modules/demo-host/container.mjs +0 -221
  65. package/modules/demo-host/entrypoint.sh +0 -9
  66. package/modules/demo-host/image.mjs +0 -18
  67. package/modules/demo-host/placement.mjs +0 -37
  68. package/modules/demo-host/prepare.mjs +0 -28
  69. package/modules/demo-host/startup.mjs +0 -27
  70. package/modules/demo-host/template.mjs +0 -71
@@ -1,156 +1,23 @@
1
- # Hosted demo
2
-
3
- The front Worker `rer deploy --demo` deploys at `demo.<domain>` for a seed
4
- that adopted demo mode (`withDemo`, export/DEMO.md). `plan.mjs` turns `deploy-demo.json`
5
- (optionally `instanceType`, one of Cloudflare's predefined Container instance
6
- types, `basic` unless set, and `ownerEmail`, the address the demo's owner signs
7
- in as, `owner@demo.invalid` unless set) into the Worker's Wrangler configuration; the CLI (`cli/demo-host.mjs`) writes
8
- it with these files and the seed's container image folder (workerd engine) to
9
- `.rer/demo-host/` and runs `wrangler deploy` there. Declared
10
- `container.hostVariables` resolve from demo settings to the primary hostname or
11
- its descendants (for example `page.demo.<domain>`); each gets a custom-domain
12
- route to the same front. The visitor cookie covers these hosts, while the
13
- primary host's `__Host` owner session stays host-only. The front supplies a
14
- validated public origin to the container ingress, so secondary page routing
15
- sees the requested host. Anonymous secondary requests return to the primary
16
- start page.
17
-
18
- - `worker.mjs`: `GET /` is the start page; `POST /__demo/start` checks the
19
- exact Origin, the `STARTS` rate limit (3 per IP per 60 s), Turnstile's
20
- siteverify and capacity, then starts the visitor's demo. It answers with
21
- 202 progress and a `rer_demo` cookie; `GET /__demo/status` polls that same
22
- copy until it can relay the owner claim's 303 (JSON `{ location }` for the
23
- page script) and session cookie. Every external admission step is bounded:
24
- the start answers within 12 seconds. A new copy that takes over two seconds
25
- to answer is still a pending start, not a failure. Each status request is
26
- held (at most 1.5 seconds) until the start changes, so the page learns of the
27
- sign-in at once; a slow status read answers pending. Each admission logs
28
- `demo_admitted` with the request's user agent and network owner, so a held
29
- place can be joined to whoever started it. On Turnstile's testing secret (a
30
- test host) a start must also carry the deploy's measurement token
31
- (`measurement.mjs`: cookie `rer_demo_measure` or header
32
- `x-rer-demo-measurement`), since automated browsers pass those keys; a
33
- test host without a token admits nobody. A request
34
- with that cookie goes to the visitor's Durable Object; nothing else reaches
35
- a container.
36
- - `container.mjs`: `DemoContainer`, one per visitor (`newUniqueId`, checked
37
- with `idFromString`). It starts the container with public internet enabled,
38
- `RER_DEMO=1`, the fixed origin (`RER_INGRESS_ORIGIN` and the seed's origin
39
- variable), fresh `SESSION_SECRET` and `SETUP_TOKEN`,
40
- `OWNER_EMAIL` (`DEMO_OWNER_EMAIL`, else `owner@demo.invalid`) and the owner claim's issuer, installation
41
- id and public key; waits for `/health`; and posts a five-minute ES256 claim
42
- (`claim.mjs`) to `/auth/owner-claim`. Its alarm ends the demo at its hour or
43
- after 15 idle minutes: `destroy()`, `deleteAll()` and the place released. A
44
- container that stops by itself ends its demo too.
45
- Public internet reads and checks run against real services. The app's demo
46
- guard simulates effects on people and third-party accounts, while the
47
- container egress independently refuses direct mail/SMS provider transports
48
- and SMTP ports. Public-address filtering and TLS remain enforced.
49
- The platform inactivity timeout is set after start and reapplied when an
50
- object recovers an already-running container. Persisted alarms enforce the
51
- exact idle/absolute deadline without keeping a timer in flight. Requests
52
- check both deadlines before refreshing activity. A container found stopped
53
- ends the demo and answers the ended page (410).
54
- - `certificate.mjs`: after `wrangler deploy`, the CLI waits for each demo
55
- hostname's certificate, a TLS handshake that verifies for that name at the
56
- address public DNS over HTTPS gives (10 minutes at most), and logs each
57
- attempt. A failed or unverified handshake never counts as active.
58
- - `capacity.mjs`: `DemoCapacity` counts unexpired reservation rows inside a
59
- storage transaction, excluding diagnostics and expired rows. A lost start
60
- handoff expires after one minute; a successful claim extends the reservation
61
- to the demo's end. Refusals log the held ids as SHA-256 fingerprints (also
62
- logged with each start's correlation), never visitor bearer cookies. The
63
- refusal's response correlation also identifies that held-place snapshot.
64
- - `image.mjs`, `prepare.mjs`, `template.mjs`, `entrypoint.sh`: the demo image
65
- build migrates fresh workerd persistence with the packaged engine and closes
66
- it into `/template`, with no network and no app requests. The entrypoint
67
- copies that state into a fresh `/data` under the host's existing flock;
68
- partial or foreign volumes are refused. Startup validates the existing
69
- migration hashes instead of replaying SQL. Owners, sessions and the seed's
70
- owner-dependent sample data are still created separately for each visitor.
71
- - `pages.mjs`: the start and ended pages (12ui designs), strict CSP.
72
- `start-script.mjs` is the start page's script: once Turnstile passes it
73
- posts the form with `Accept: application/json` (the Worker then answers
74
- 202 `{ pending: true }`, `{ location }` with the cookies, or `{ notice }`
75
- with the refusal's status)
76
- and shows each step: the check, the private copy starting, the sign-in. A
77
- refusal, a network failure or a start past 25 seconds is shown with Try
78
- again, which first destroys the abandoned copy and releases its place through
79
- `POST /__demo/cancel`, then runs a new check; progress is announced through a
80
- `role="status"` region and failures through `role="alert"`. Without
81
- JavaScript the form posts as before and gets the 303 or the page.
82
- - `remove.mjs`: `rer deploy --demo --remove --yes`. The deploy passes the
83
- demo's record (`plan.record`) to `wrangler deploy --message`; removal takes
84
- the Worker for the demo's only while it serves that version, the Custom
85
- Domain only while it routes to that Worker and the Container application
86
- only while it belongs to that Worker's DemoContainer namespace, refuses
87
- anything else before the first delete, deletes by exact id (the Worker
88
- last) and reads back that each is gone (export/DEMO.md "Removing a hosted
89
- demo"). `cli/demo-remove.test.mjs` runs it through the CLI against a fake
90
- Cloudflare account (`tests/demo-account.mjs`).
91
-
92
- `node --test modules/demo-host/tests/*.test.mjs` runs the Worker in workerd
93
- with its real Durable Objects and rate limit; Turnstile and the container
94
- platform are the only fakes. `start-page.test.mjs` drives the start page in
95
- Chromium (default-seed's Playwright) through waiting, failure, Try again,
96
- working and the signed-in landing. The end-to-end proof (`wrangler dev` with Docker)
97
- is in DEMO.md.
98
-
99
- Startup has a 45-second boot budget, with a separate five-second HTTP probe
100
- limit; waiting for Cloudflare to place the container renews it, up to 90
101
- seconds from the start (see placement below).
102
- The Durable Object owns that work and cleanup while the page polls; a browser
103
- that leaves cannot abandon it. Retrying a pending copy resumes the same
104
- 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
105
- the container. Destruction retries for failed starts never extend or reclaim the
106
- released place. Each release logs the id's SHA-256 fingerprint with the start's
107
- correlation. Every attempt logs its timestamp, elapsed time, duration and
108
- HTTP status or fixed error category, including successful probes. Exit records
109
- include the numeric platform exit code when supplied. A separate random
110
- `x-rer-demo-correlation` response header joins these events without disclosing
111
- the visitor's bearer cookie. Early refusals, including capacity, rate-limit,
112
- Origin and human-check refusals, also carry a correlation and log their status.
113
- Worker observability also enables the platform's
114
- private Container stdout/stderr logs; historical stdout is not exposed by the
115
- Container lifecycle API. Read those logs with an account principal granted
116
- Workers Observability Write, and filter by the application and boot interval.
117
-
118
- Optionally set a separate random `RER_DEMO_OPERATOR_TOKEN` (32–512 characters)
119
- when running `rer deploy --demo`. It becomes a Worker secret. A host operator
120
- can request `GET /__demo/operator/<correlation>` with
121
- `Authorization: Bearer <RER_DEMO_OPERATOR_TOKEN>` to see the existing start page
122
- with a bounded, redacted diagnostic line for a failed start. It retains the
123
- last eight probe/exit records, for at most 15 minutes and 32 failed starts.
124
- Unauthenticated requests, demo owner sessions and correlation IDs alone grant
125
- no access. The token never belongs in a URL. Ordinary visitors keep the generic
126
- failure page. No raw error text, health body, cookies or environment values are
127
- included in this diagnostic.
128
-
129
- Failed destruction retains its alarm for cleanup. A live visitor's demo also
130
- retains its capacity reservation until destruction is confirmed (or the
131
- container is already stopped); a terminal start failure releases it immediately.
132
- A cleanup failure is logged separately and cannot replace the startup failure
133
- shown to the visitor.
134
-
135
- Cloudflare keeps a small prepared pool per application (7 instances on fresh
136
- test hosts, measured in October 2026, whatever `max_instances` is) and places a
137
- new instance only on demand: a start beyond the pool gets "no container instance
138
- that can be provided" until Cloudflare has placed one (16 to 37 seconds
139
- measured, after which boot was normal). `placement.mjs` keeps the same
140
- reservation and launch options, requests placement again only for that specific
141
- provider response, and renews the 45-second boot budget after each wait, up to
142
- 90 seconds from the start, extending the reservation to match. Boot, health
143
- and claim errors are not retried. Placement exhaustion answers with the normal
144
- failed-start retry state and releases the reservation; the capacity notice is
145
- reserved for actual reservation exhaustion. Cleanup keeps only that terminal
146
- answer and correlation for one minute, so a status poll after object recovery
147
- still receives the right answer; its alarm then deletes the remaining metadata.
148
-
149
- `DemoCapacity` alone admits visitors (`maxInstances` live demos). The Container
150
- application's own `max_instances` is twice that, so instances Cloudflare still
151
- counts after a demo ends or a start fails never refuse a place admission gave.
152
- Its `rollout_active_grace_period` is an hour, a demo's longest life: a redeploy
153
- that rolls the application out (a new image, instance type or limit) replaces
154
- idle prepared instances at once and leaves every live demo running until it
155
- ends. With no grace period a rollout replaced live demos' containers within two
156
- minutes, and their visitors saw "This demo has ended".
1
+ # Native hosted demos
2
+
3
+ `rer deploy --demo` builds the seed's production Worker for a Worker Loader
4
+ host. See [adoption and deployment](../../export/DEMO.md#hosting-the-demo).
5
+
6
+ - `build.mjs`: ordinary Vite output, declared SQL and public configuration,
7
+ using the shared container migration-inventory and image-variable checks.
8
+ - `native/`: bundle preparation, per-visitor D1/seed-DO facets, prefixed R2,
9
+ durable queue delivery, seed-DO alarms and declared UTC crons.
10
+ A narrow bridge exposes only visitor resource operations to the seed; own-host
11
+ outbound requests return to the same visitor, including declared secondary hosts.
12
+ - `worker.mjs`, `pages.mjs`, `start-script.mjs`: Turnstile start, progress,
13
+ cancellation and visitor routing. Static assets are served at the edge.
14
+ - `capacity.mjs`: concurrent visitor admission and operator diagnostics. This
15
+ is used by the native host as well as retained during legacy upgrades.
16
+ - `upgrade.mjs`: verifies ownership, removes the old Container application and
17
+ derives the class migration from deployed namespaces and migration tag.
18
+ - `remove.mjs`: exact-id teardown, ownership collision checks and absence reads.
19
+
20
+ The historical resource-name hash remains stable so released container demos
21
+ can upgrade and be removed from a fresh checkout. Portable container hosting
22
+ remains separate from the native hosted-demo runtime.
23
+ `rer demo` remains the local Vite/Workers demo, with its own temporary state.
@@ -0,0 +1,49 @@
1
+ import { readFile, writeFile, realpath, cp, mkdir, rm } from 'node:fs/promises';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { containerMigrationInventory as demoMigrationInventory } from '../container/migration-inventory.mjs';
6
+ import { checkImageVariables as checkBuildVariables } from '../container/image-variables.mjs';
7
+ import { nativeBindings } from './native/config.mjs';
8
+ import { readMigrationRewrites, withRewrites } from '../deploy-kit/migrations.mjs';
9
+
10
+ // The seed's ordinary production Worker output, with the declared SQL inventory.
11
+ // No image, runtime emulator or dependency installation belongs in this bundle.
12
+ export async function buildDemo(root, output, declaration) {
13
+ const require = createRequire(join(root, 'package.json'));
14
+ const vite = await import(pathToFileURL(require.resolve('vite')));
15
+ const loaded = await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, undefined, root);
16
+ if (!loaded) throw new Error('Vite configuration missing');
17
+ const emitted = new Set(), entryExports = new Map();
18
+ const config = { ...loaded.config, root, configFile: false, plugins: [...(loaded.config.plugins ?? []), {
19
+ name: 'rer-demo-output',
20
+ async writeBundle(output, bundle) {
21
+ const directory = resolve(root, output.dir ?? dirname(output.file));
22
+ for (const chunk of Object.values(bundle)) if (chunk.type === 'chunk') {
23
+ const path = await realpath(join(directory, chunk.fileName)); emitted.add(path);
24
+ if (chunk.isEntry) entryExports.set(path, new Set(chunk.exports));
25
+ }
26
+ },
27
+ }] };
28
+ await (await vite.createBuilder(config)).buildApp();
29
+ await (await import('../../cli/dev-identity.mjs')).refuseDevLayerOutput(root);
30
+ const workerConfig = JSON.parse(await readFile(join(root, 'dist/server/wrangler.json'), 'utf8'));
31
+ const entry = await realpath(resolve(root, 'dist/server', workerConfig.main));
32
+ const bindings = nativeBindings(workerConfig);
33
+ for (const binding of bindings.objects) if (!entryExports.get(entry)?.has(binding.class_name)) throw new Error(`Loader demo cannot bind ${binding.name}: missing Durable Object export ${binding.class_name}`);
34
+ if (!emitted.has(entry)) throw new Error('Demo Worker entry was not emitted by this build');
35
+ await checkBuildVariables(root, workerConfig.vars ?? {}, declaration.secrets ?? []);
36
+ const { unstable_splitSqlQuery: split } = require('wrangler');
37
+ const migrations = Object.fromEntries((workerConfig.d1_databases ?? []).map(db => [db.binding, []]));
38
+ const inventory = withRewrites(await demoMigrationInventory(root, { config: workerConfig, configFile: 'dist/server/wrangler.json' }), await readMigrationRewrites(root));
39
+ for (const { binding, ...migration } of inventory) migrations[binding].push({ ...migration, statements: split(migration.sql) });
40
+ await rm(output, { recursive: true, force: true });
41
+ await mkdir(join(output, 'app'), { recursive: true });
42
+ await cp(join(root, 'dist'), join(output, 'app/dist'), { recursive: true });
43
+ await writeFile(join(output, 'app/demo.json'), JSON.stringify({ config: workerConfig, migrations }) + '\n');
44
+ }
45
+
46
+ if (process.argv[1] === import.meta.filename) {
47
+ try { await buildDemo(resolve(process.argv[2]), resolve(process.argv[3]), JSON.parse(process.argv[4])); }
48
+ catch (error) { console.error(error.message); process.exitCode = 1; }
49
+ }
@@ -22,9 +22,15 @@ export class DemoCapacity extends DurableObject {
22
22
  return this.ctx.storage.transaction(async storage => {
23
23
  const now = Date.now(), places = [...await storage.list()]
24
24
  .filter(([key, until]) => /^[0-9a-f]{64}$/.test(key) && typeof until === 'number');
25
- const expired = places.filter(([, until]) => until <= now).map(([key]) => key);
25
+ // A class migration retires visitor ids from the old namespace. Release
26
+ // those reservations on the first native start rather than holding a
27
+ // full legacy host closed until its former visitors' hour expires.
28
+ const expired = places.filter(([key, until]) => {
29
+ if (until <= now) return true;
30
+ try { this.env.DEMO.idFromString(key); return false; } catch { return true; }
31
+ }).map(([key]) => key);
26
32
  if (expired.length) await storage.delete(expired);
27
- const held = places.filter(([key, until]) => key !== id && until > now);
33
+ const held = places.filter(([key]) => key !== id && !expired.includes(key));
28
34
  if (held.length >= max) {
29
35
  // Fingerprints identify held reservations without logging bearer cookies.
30
36
  const heldIds = await Promise.all(held.map(async ([key, until]) => ({ id: await fingerprint(key), ends: until })));
@@ -1,6 +1,6 @@
1
1
  // The signed owner claim (modules/owner-claim) a demo's front Worker makes for
2
- // its container: one ES256 key pair per container, its public JWK given to the
3
- // container at start, and one five-minute claim signed with the private key,
2
+ // its isolate: one ES256 key pair per isolate, its public JWK given to the
3
+ // isolate at start, and one five-minute claim signed with the private key,
4
4
  // which is never stored.
5
5
  const base64url = bytes => btoa(String.fromCharCode(...new Uint8Array(bytes))).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
6
6
  const segment = value => base64url(new TextEncoder().encode(JSON.stringify(value)));
@@ -1,31 +1,14 @@
1
1
  // Only fixed categories and numeric metadata enter provider logs. No request,
2
- // container response body, cookie, environment value or raw error is retained.
2
+ // isolate 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';
6
5
  if (error?.name === 'TimeoutError' || error?.name === 'AbortError') return 'probe-timeout';
7
- if (/connection refused|not listening|port.*not.*ready/i.test(message)) return 'port-not-ready';
8
- if (/container.*not.*running|container.*stopped/i.test(message)) return 'container-stopped';
9
6
  if (/disconnect|connection reset|network connection lost/i.test(message)) return 'connection-lost';
10
7
  return error instanceof TypeError ? 'transport-type-error' : 'platform-error';
11
8
  }
12
9
  export function report(correlation, started, event, detail = {}) {
13
10
  console.log(JSON.stringify({ event: `demo_${event}`, correlation, at: new Date().toISOString(), elapsedMs: Date.now() - started, ...detail }));
14
11
  }
15
- export async function boundedFetch(port, url, init, milliseconds) {
16
- const controller = new AbortController();
17
- let timer;
18
- const timeout = new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new DOMException('probe deadline', 'TimeoutError')); }, milliseconds); });
19
- try {
20
- const request = port.fetch(url, { ...init, signal: controller.signal }).then(response => {
21
- if (controller.signal.aborted) void response.body?.cancel().catch(() => {});
22
- return response;
23
- });
24
- return await Promise.race([request, timeout]);
25
- }
26
- finally { clearTimeout(timer); }
27
- }
28
-
29
12
  export async function bounded(operation, milliseconds) {
30
13
  let timer;
31
14
  try {
@@ -0,0 +1,51 @@
1
+ import { bundle } from './loader.mjs';
2
+
3
+ export async function seedAlarm(host, binding, id, method, at) {
4
+ await host.active();
5
+ if (!bundle.bindings.objects.some(item => item.name === binding) || !/^[a-f0-9]{64}$/.test(id)) throw new Error(`Unknown Durable Object binding or id: ${binding}`);
6
+ const key = `alarm:${binding}:${id}`;
7
+ if (method === 'get') {
8
+ const record = await host.ctx.storage.get(key);
9
+ return record && !record.firing ? record.at : null;
10
+ }
11
+ if (method === 'delete') { await host.ctx.storage.delete(key); return; }
12
+ if (method !== 'set' || !Number.isFinite(at) || at <= 0) throw new TypeError('Invalid Durable Object alarm time');
13
+ await host.ctx.storage.put(key, { binding, id, at: Math.max(Date.now(), at), token: crypto.randomUUID(), attempts: 0 });
14
+ await host.schedule(at);
15
+ }
16
+ export async function nextSeedAlarm(host) {
17
+ return Math.min(Infinity, ...[...(await host.ctx.storage.list({ prefix: 'alarm:' })).values()].map(item => item.at));
18
+ }
19
+ export async function deliverSeedAlarms(host, now) {
20
+ const records = await host.ctx.storage.list({ prefix: 'alarm:' });
21
+ for (const [key, record] of records) {
22
+ if (record.at > now) continue;
23
+ const claimed = await host.ctx.storage.transaction(async txn => {
24
+ const current = await txn.get(key);
25
+ if (current?.token !== record.token) return false;
26
+ // Persist a retry before invoking the seed, so an interrupted delivery is
27
+ // retried too. A seed's set/delete during delivery supersedes this token.
28
+ await txn.put(key, { ...record, firing: true, at: Date.now() + 2000 * 2 ** record.attempts, attempts: record.attempts + 1 });
29
+ return true;
30
+ });
31
+ if (!claimed) continue;
32
+ let failed = false;
33
+ try {
34
+ const response = await host.object(record.binding, record.id, 'fetch', [new Request('https://native.invalid/alarm', { headers: {
35
+ 'x-rer-native-alarm-key': host.state.runtime.RER_NATIVE_KEY,
36
+ 'x-rer-native-alarm-info': JSON.stringify({ retryCount: record.attempts, isRetry: record.attempts > 0 }),
37
+ } })]);
38
+ if (response.status !== 204) throw new Error(`Seed alarm refused: ${response.status}`);
39
+ }
40
+ catch (error) {
41
+ failed = true;
42
+ console.error(JSON.stringify({ event: 'native-demo-seed-alarm-failed', binding: record.binding, message: String(error.message) }));
43
+ }
44
+ await host.ctx.storage.transaction(async txn => {
45
+ const current = await txn.get(key);
46
+ if (current?.token !== record.token) return;
47
+ if (failed && current.attempts <= 6) await txn.put(key, { ...current, firing: false });
48
+ else await txn.delete(key);
49
+ });
50
+ }
51
+ }
@@ -0,0 +1,24 @@
1
+ import { env } from 'cloudflare:workers';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { DemoD1 } from './d1.js';
4
+ import { DemoR2 } from './r2-client.js';
5
+ import { DemoNamespace } from './namespace.js';
6
+
7
+ // Seed DOs use RPC rather than another object's SQL storage handle.
8
+ export const localSQL = new AsyncLocalStorage();
9
+ const config = env.RER_NATIVE_CONFIG;
10
+ for (const binding of config.databases) {
11
+ const call = (method, ...args) => {
12
+ const sql = localSQL.getStore();
13
+ return sql && binding === config.databases[0]
14
+ ? sql[method](...args) : env.RER_NATIVE_HOST.database(binding, method, args);
15
+ };
16
+ env[binding] = new DemoD1({ query: (...args) => call('query', ...args), batch: (...args) => call('batch', ...args), exec: (...args) => call('exec', ...args) });
17
+ }
18
+ for (const binding of config.buckets) env[binding] = new DemoR2(env.RER_NATIVE_HOST, binding);
19
+ for (const { binding, queue } of config.queues.producers) env[binding] = {
20
+ metrics: () => env.RER_NATIVE_HOST.queueMetrics(queue),
21
+ send: (body, options = {}) => env.RER_NATIVE_HOST.enqueue(queue, [{ body, ...options }]),
22
+ sendBatch: (messages, options = {}) => env.RER_NATIVE_HOST.enqueue(queue, Array.from(messages).map(message => ({ ...options, ...message }))),
23
+ };
24
+ for (const { name } of config.objects) env[name] = new DemoNamespace(env.RER_NATIVE_HOST, name, env.RER_NATIVE_KEY);
@@ -0,0 +1,17 @@
1
+ import { WorkerEntrypoint } from 'cloudflare:workers';
2
+
3
+ // Only visitor-local resource operations cross into the loaded seed.
4
+ export class HostBridge extends WorkerEntrypoint {
5
+ #host() { return this.env.DEMO.get(this.env.DEMO.idFromString(this.ctx.props.id)); }
6
+ database(binding, method, args) { return this.#host().database(binding, method, args); }
7
+ object(binding, id, method, args) { return this.#host().object(binding, id, method, args); }
8
+ r2(binding, method, args) { return this.#host().r2(binding, method, args); }
9
+ enqueue(queue, messages) { return this.#host().enqueue(queue, messages); }
10
+ queueMetrics(queue) { return this.#host().queueMetrics(queue); }
11
+ seedAlarm(binding, id, method, at) { return this.#host().seedAlarm(binding, id, method, at); }
12
+ fetch(request) {
13
+ // The host validates the visitor key and removes the routing headers.
14
+ if (!request.headers.has('x-rer-native-object') || request.headers.get('x-rer-native-key') !== this.ctx.props.key) return new Response('Not found.', { status: 404 });
15
+ return this.#host().fetch(request);
16
+ }
17
+ }
@@ -0,0 +1,35 @@
1
+ import { parseCron } from './cron.mjs';
2
+
3
+ export const RUNTIME_FILES = ['config', 'worker', 'visitor', 'loader', 'd1', 'sql', 'r2', 'queues', 'resources', 'cron', 'bridge', 'alarms'];
4
+ export const ISOLATE_FILES = ['bindings', 'namespace', 'r2-client', 'd1', 'sql', 'seed-object'];
5
+ export function nativeBindings(config) {
6
+ for (const kind of ['kv_namespaces', 'services', 'workflows', 'ai', 'vectorize', 'hyperdrive', 'analytics_engine_datasets', 'browser', 'images', 'send_email', 'dispatch_namespaces', 'mtls_certificates', 'pipelines', 'secrets_store_secrets', 'unsafe', 'vpc_services', 'vpc_networks', 'ratelimits', 'worker_loaders', 'containers', 'ai_search_namespaces', 'ai_search', 'agent_memory', 'connect', 'artifacts', 'unsafe_hello_world', 'flagship', 'logfwdr', 'version_metadata']) {
7
+ const value = config[kind];
8
+ if (!value || (Array.isArray(value) && !value.length)) continue;
9
+ const entries = Array.isArray(value) ? value : value.bindings ?? [value];
10
+ for (const item of entries) throw new Error(`Loader demo cannot bind ${kind}: ${item.binding ?? item.name ?? kind}`);
11
+ }
12
+ const databases = (config.d1_databases ?? []).map(item => item.binding);
13
+ const buckets = (config.r2_buckets ?? []).map(item => item.binding);
14
+ const objects = config.durable_objects?.bindings ?? [];
15
+ for (const item of objects) {
16
+ if (item.script_name || item.environment) throw new Error(`Loader demo cannot bind external Durable Object: ${item.name}`);
17
+ if (!/^[A-Za-z_$][\w$]*$/.test(item.class_name) || ['DemoApp', 'DemoDatabase'].includes(item.class_name)) throw new Error(`Loader demo cannot export Durable Object: ${item.name} (${item.class_name})`);
18
+ }
19
+ const queues = { producers: config.queues?.producers ?? [], consumers: config.queues?.consumers ?? [] };
20
+ for (const consumer of queues.consumers) {
21
+ if (consumer.type && consumer.type !== 'worker') throw new Error(`Loader demo cannot bind pull queue: ${consumer.queue}`);
22
+ }
23
+ for (const cron of config.triggers?.crons ?? []) {
24
+ try { parseCron(cron); } catch { throw new Error(`Loader demo cannot schedule cron: ${cron}`); }
25
+ }
26
+ const names = [...databases, ...buckets, ...objects.map(item => item.name), ...queues.producers.map(item => item.binding)];
27
+ for (const name of names) if (!/^[A-Za-z_][\w]*$/.test(name) || name.startsWith('RER_NATIVE_')) throw new Error(`Loader demo cannot bind reserved or invalid name: ${name}`);
28
+ if (new Set(names).size !== names.length) throw new Error('Loader demo has duplicate binding names');
29
+ return { databases, buckets, objects, queues, assets: config.assets?.binding ?? 'ASSETS' };
30
+ }
31
+
32
+ // Export one wrapper per binding, including when several bindings share a class.
33
+ export const objectClass = binding => `RerSeed_${binding}`;
34
+ export const objectExports = bindings => (bindings.objects.length ? "\nimport { seedObject } from './seed-object.js';" : '') + bindings.objects.map(({ name, class_name }) =>
35
+ `\nexport const ${objectClass(name)} = seedObject(application[${JSON.stringify(class_name)}], ${JSON.stringify(name)});`).join('');
@@ -0,0 +1,31 @@
1
+ const fields = [[0, 59], [0, 23], [1, 31], [1, 12], [1, 7]];
2
+
3
+ function field(text, [low, high]) {
4
+ const values = new Set();
5
+ for (const part of text.split(',')) {
6
+ const match = /^(?:(\*)|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part);
7
+ if (!match) throw new Error(`Unsupported cron field "${text}"`);
8
+ const step = match[4] === undefined ? 1 : Number(match[4]);
9
+ const start = match[1] ? low : Number(match[2]), end = match[1] ? high : match[3] === undefined ? (match[4] === undefined ? start : high) : Number(match[3]);
10
+ if (!step || start < low || end > high || start > end) throw new Error(`Cron field "${text}" is out of range`);
11
+ for (let value = start; value <= end; value += step) values.add(value);
12
+ }
13
+ return values;
14
+ }
15
+
16
+ // Same grammar the deploy kit accepts: five numeric fields with lists, ranges and
17
+ // steps, in UTC. Day of week counts 1 (Sunday) to 7 (Saturday), as Cloudflare does.
18
+ export function parseCron(expression) {
19
+ const parts = expression.trim().split(/\s+/);
20
+ if (parts.length !== 5) throw new Error(`Cron "${expression}" needs five fields`);
21
+ const [minute, hour, day, month, weekday] = parts.map((part, index) => field(part, fields[index]));
22
+ return { minute, hour, day, month, weekday, dayRestricted: parts[2] !== '*', weekdayRestricted: parts[4] !== '*' };
23
+ }
24
+
25
+ export function cronMatches(cron, date) {
26
+ const parsed = typeof cron === 'string' ? parseCron(cron) : cron;
27
+ const day = parsed.day.has(date.getUTCDate()), weekday = parsed.weekday.has(date.getUTCDay() + 1);
28
+ const days = parsed.dayRestricted && parsed.weekdayRestricted ? day || weekday : day && weekday;
29
+ return parsed.minute.has(date.getUTCMinutes()) && parsed.hour.has(date.getUTCHours()) && parsed.month.has(date.getUTCMonth() + 1) && days;
30
+ }
31
+
@@ -0,0 +1,37 @@
1
+ // The synchronous D1 statement builder stays inside the app isolate. Only SQL
2
+ // and bound values cross RPC; a batch remains one SQLite transaction.
3
+ export class DemoD1 {
4
+ constructor(sql) { this.sql = sql; }
5
+ prepare(query) { return new Statement(this, query); }
6
+ async batch(statements) {
7
+ if (statements.some(statement => statement.db !== this)) throw new Error('Foreign D1 statement');
8
+ return (await this.sql.batch(statements.map(({ query, args }) => ({ query, args })))).map(result);
9
+ }
10
+ exec(query) { return this.sql.exec(query); }
11
+ }
12
+ const result = value => ({ success: value.success, results: value.results, meta: value.meta });
13
+ class Statement {
14
+ constructor(db, query, args = []) { this.db = db; this.query = query; this.args = args; }
15
+ bind(...args) {
16
+ return new Statement(this.db, this.query, args.map(value => {
17
+ if (typeof value === 'boolean') return Number(value);
18
+ if (value === null || typeof value === 'string' || typeof value === 'number' || value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return value;
19
+ if (Array.isArray(value) && value.every(byte => Number.isInteger(byte) && byte >= 0 && byte <= 255)) return new Uint8Array(value);
20
+ throw new TypeError('D1_TYPE_ERROR: unsupported bound value');
21
+ }));
22
+ }
23
+ execute() { return this.db.sql.query(this.query, this.args); }
24
+ async all() { return result(await this.execute()); }
25
+ run() { return this.all(); }
26
+ async first(column) {
27
+ const row = (await this.execute()).results[0];
28
+ if (!row) return null;
29
+ if (column === undefined) return row;
30
+ if (!Object.hasOwn(row, column)) throw new Error(`D1_COLUMN_NOTFOUND: ${column}`);
31
+ return row[column];
32
+ }
33
+ async raw({ columnNames = false } = {}) {
34
+ const { columns, rows } = await this.execute();
35
+ return columnNames ? [columns, ...rows] : rows;
36
+ }
37
+ }
@@ -0,0 +1,43 @@
1
+ import { workerSettings } from '../../deploy-kit/owner.mjs';
2
+ import { servedVersion } from '../../deploy-kit/site.mjs';
3
+ import { r2ObjectPages, r2ObjectPath } from '../../deploy-kit/r2-objects.mjs';
4
+
5
+ export const demoBucketName = worker => `${worker.replace(/-+/g, '-').slice(0, 48)}-objects`;
6
+ const missing = async (api, name) => {
7
+ try { return await api.request(`/r2/buckets/${name}`); }
8
+ catch (error) { if (error.status === 404) return null; throw error; }
9
+ };
10
+ export async function prepareBucket(api, plan, pending) {
11
+ const name = demoBucketName(plan.worker), bucket = await missing(api, name), settings = await workerSettings(api, plan.worker);
12
+ if (!bucket && settings?.bindings?.some(item => item.name === 'NATIVE_BUCKET')) throw new Error(`Demo R2 bucket is missing: ${name}`);
13
+ if (bucket) {
14
+ const version = settings && await servedVersion(api, plan.worker);
15
+ if (!settings && pending?.record === plan.record && pending.bucket?.name === name && pending.bucket.creation_date === bucket.creation_date) return bucket;
16
+ if (!version?.current || version.annotation !== plan.record || !ownsBucket(settings, bucket)) throw new Error(`Demo R2 bucket ownership is unproven: ${name}`);
17
+ return bucket;
18
+ }
19
+ return api.request('/r2/buckets', { method: 'POST', body: { name } });
20
+ }
21
+ function ownsBucket(settings, bucket) {
22
+ return settings?.bindings?.some(item => item.type === 'r2_bucket' && item.name === 'NATIVE_BUCKET' && item.bucket_name === bucket.name)
23
+ && settings.bindings.some(item => item.name === 'NATIVE_BUCKET_CREATED' && item.text === bucket.creation_date);
24
+ }
25
+ export async function ownedBucket(api, plan, settings) {
26
+ const binding = settings?.bindings?.find(item => item.name === 'NATIVE_BUCKET' && item.type === 'r2_bucket');
27
+ if (!binding) return null;
28
+ if (binding.bucket_name !== demoBucketName(plan.worker)) throw new Error('demo-r2-name-collision');
29
+ const bucket = await missing(api, binding.bucket_name);
30
+ if (bucket && !ownsBucket(settings, bucket)) throw new Error('demo-r2-replaced');
31
+ return bucket;
32
+ }
33
+ export async function removeBucket(api, bucket) {
34
+ const check = async () => {
35
+ const current = await missing(api, bucket.name);
36
+ if (!current || current.creation_date !== bucket.creation_date) throw new Error('demo-r2-replaced');
37
+ };
38
+ for await (const page of r2ObjectPages(api, bucket.name)) for (const { key } of page) {
39
+ await check(); await api.request(r2ObjectPath(bucket.name, key), { method: 'DELETE' });
40
+ }
41
+ await check(); await api.request(`/r2/buckets/${bucket.name}`, { method: 'DELETE' });
42
+ if (await missing(api, bucket.name)) throw new Error('demo-r2-remove-incomplete');
43
+ }
@@ -0,0 +1,36 @@
1
+ // Bindings must exist before evaluating the seed's cloudflare:workers imports.
2
+ import { localSQL } from './bindings.js';
3
+ import { env, DurableObject } from 'cloudflare:workers';
4
+ import * as application from '__RER_APP_ENTRY__';
5
+ import { sqlite } from './sql.js';
6
+
7
+ export class DemoDatabase extends DurableObject {
8
+ constructor(ctx, bindings) { super(ctx, bindings); this.sql = sqlite(ctx.storage); }
9
+ query(query, args) { return this.sql.query(query, args); }
10
+ batch(statements) { return this.sql.batch(statements); }
11
+ exec(query) { return this.sql.exec(query); }
12
+ }
13
+ export class DemoApp extends DemoDatabase {
14
+ async fetch(request) { return localSQL.run(this.sql, () => application.default.fetch(request, env, this.ctx)); }
15
+ async runScheduled(scheduledTime, cron) {
16
+ if (application.default.scheduled) await localSQL.run(this.sql, () => application.default.scheduled({ scheduledTime, cron, noRetry() {} }, env, this.ctx));
17
+ }
18
+ async runQueue(queue, messages) {
19
+ if (!application.default.queue) throw new Error(`Seed has no queue() handler for ${queue}`);
20
+ const outcomes = new Map(), waits = [];
21
+ const settle = (id, retry, options = {}) => { if (!outcomes.has(id)) outcomes.set(id, { id, retry, delaySeconds: options.delaySeconds }); };
22
+ const batch = { queue, messages: messages.map(message => ({ ...message, timestamp: new Date(message.timestamp),
23
+ ack: () => settle(message.id, false), retry: options => settle(message.id, true, options) })),
24
+ ackAll: () => messages.forEach(message => settle(message.id, false)),
25
+ retryAll: options => messages.forEach(message => settle(message.id, true, options)),
26
+ };
27
+ let failed = false;
28
+ try {
29
+ await localSQL.run(this.sql, async () => {
30
+ await application.default.queue(batch, env, { waitUntil: promise => waits.push(promise), passThroughOnException() {} });
31
+ await Promise.all(waits);
32
+ });
33
+ } catch { failed = true; }
34
+ return messages.map(message => outcomes.get(message.id) ?? { id: message.id, retry: failed });
35
+ }
36
+ }
@@ -0,0 +1,30 @@
1
+ import { WorkerEntrypoint } from 'cloudflare:workers';
2
+ import demoEgress from '../../container/demo-egress.mjs';
3
+ import bundle from './bundle.mjs';
4
+
5
+ export function loaded(env, ctx, id, runtime) {
6
+ return env.LOADER.get(`${bundle.digest}:${id}`, () => ({
7
+ compatibilityDate: bundle.compatibilityDate, compatibilityFlags: bundle.compatibilityFlags,
8
+ mainModule: '_rer/isolate.js', modules: bundle.modules,
9
+ globalOutbound: ctx.exports.DemoEgress({ props: { id } }),
10
+ env: { ...runtime, RER_NATIVE_CONFIG: bundle.bindings, RER_NATIVE_HOST: ctx.exports.HostBridge({ props: { id, key: runtime.RER_NATIVE_KEY } }), [bundle.bindings.assets]: ctx.exports.DemoAssets({}) },
11
+ }));
12
+ }
13
+ export function application(env, ctx, id, runtime) {
14
+ return ctx.facets.get('app', () => ({ class: loaded(env, ctx, id, runtime).getDurableObjectClass('DemoApp') }));
15
+ }
16
+ export class DemoAssets extends WorkerEntrypoint {
17
+ fetch(request) { return this.env.ASSETS.fetch(request); }
18
+ }
19
+ export { bundle };
20
+
21
+ export class DemoEgress extends WorkerEntrypoint {
22
+ fetch(request) {
23
+ return demoEgress.fetch(request, {
24
+ RER_DEMO: '1',
25
+ RER_DEMO_ORIGINS: JSON.stringify([this.env.DEMO_ORIGIN, ...JSON.parse(this.env.DEMO_SECONDARY_ORIGINS ?? '[]')]),
26
+ SELF: { fetch: request => this.env.DEMO.get(this.env.DEMO.idFromString(this.ctx.props.id)).fetch(request) },
27
+ NETWORK: { fetch: request => fetch(request) },
28
+ });
29
+ }
30
+ }