@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
@@ -1,221 +0,0 @@
1
- import { DurableObject } from 'cloudflare:workers';
2
- import { claimKeys, signClaim } from './claim.mjs';
3
- import { bounded, boundedFetch, category, report } from './diagnostics.mjs';
4
- import { endedPage, clearCookie } from './pages.mjs';
5
- import { finishStart } from './startup.mjs';
6
- import { placeContainer } from './placement.mjs';
7
- import { fingerprint } from './capacity.mjs';
8
-
9
- // One visitor's demo: a Durable Object (newUniqueId) and its container, the
10
- // seed's image from `rer build --platform container` on the workerd engine.
11
- // The container starts with public internet in demo mode. withDemo simulates
12
- // external effects; the engine also refuses direct mail/SMS transports. The
13
- // front signs the owner in through the existing signed owner claim. The demo ends at its hour or after
14
- // 15 idle minutes: the alarm destroys the container and deletes everything.
15
- // Container lifetime is independent of the object's JS lifetime. Configure the
16
- // platform's inactivity grace on every object instance; persisted alarms and
17
- // request-time checks enforce the visitor's exact idle and absolute deadlines.
18
- const PORT = 8080, IDLE = 15 * 60_000, OWNER = 'owner@demo.invalid';
19
- // The container's port speaks plain HTTP; the app takes its public origin from RER_INGRESS_ORIGIN.
20
- const inside = url => `http://container${url.pathname}${url.search}`;
21
- const random = () => [...crypto.getRandomValues(new Uint8Array(32))].map(byte => byte.toString(16).padStart(2, '0')).join('');
22
-
23
- export class DemoContainer extends DurableObject {
24
- constructor(ctx, env) {
25
- super(ctx, env);
26
- ctx.blockConcurrencyWhile(async () => {
27
- const state = await ctx.storage.get(['correlation', 'started', 'startup']);
28
- this.correlation = state.get('correlation'); this.started = state.get('started');
29
- if (state.get('startup')?.phase === 'starting') {
30
- // An interrupted start has lost its private claim key and cannot be
31
- // resumed after object eviction. End it instead of polling forever.
32
- await ctx.storage.put('startup', { phase: 'starting', failure: state.get('startup').failure ?? { phase: 'failed' } });
33
- ctx.waitUntil(this.end().catch(cause => report(this.correlation, this.started, 'cleanup', { error: category(cause) })));
34
- } else if (this.container.running) {
35
- await this.container.setInactivityTimeout(this.idle);
36
- this.watch();
37
- }
38
- });
39
- }
40
- watch() {
41
- if (!this.watching) {
42
- this.watching = true;
43
- this.ctx.waitUntil(this.container.monitor().then(() => this.exited(), error => this.exited(error)));
44
- }
45
- }
46
- records = [];
47
- record(event, detail = {}) {
48
- const row = { event, at: new Date().toISOString(), elapsedMs: this.now() - this.started, ...detail };
49
- this.records.push(row); if (this.records.length > 8) this.records.shift();
50
- report(this.correlation, this.started, event, detail);
51
- }
52
- diagnostic() { return { correlation: this.correlation, tail: this.records, stdout: 'Provider container logs; not exposed by the lifecycle API.' }; }
53
- idle = IDLE;
54
- startTimeout = 45_000;
55
- placementTimeout = 90_000;
56
- probeTimeout = 5000;
57
- cleanupRetry = 30_000;
58
- now() { return Date.now(); }
59
- get container() { return this.ctx.container; }
60
- get owner() { return this.env.DEMO_OWNER_EMAIL || OWNER; }
61
- port() { return this.container.getTcpPort(PORT); }
62
-
63
- async begin(options) {
64
- if (!await this.ctx.storage.get('startup')) {
65
- await this.ctx.storage.put('startup', { phase: 'starting' });
66
- this.ctx.waitUntil(finishStart(this, options));
67
- }
68
- return this.status();
69
- }
70
-
71
- /** The start's state; `wait` holds a pending answer until it changes (at most 1.5 s), so the page learns of the sign-in without its own polling delay.
72
- * A poll can also reach a new copy before its slow begin has landed. */
73
- async status(wait = 0) {
74
- const until = Date.now() + Math.min(wait, 1500);
75
- let startup = await this.ctx.storage.get('startup');
76
- while ((!startup || (startup.phase === 'starting' && !startup.failure)) && Date.now() < until) {
77
- await new Promise(resolve => setTimeout(resolve, 100));
78
- startup = await this.ctx.storage.get('startup');
79
- }
80
- return { ...(startup ?? { phase: 'failed' }), correlation: this.correlation };
81
- }
82
-
83
- /** Start the container, wait for /health, claim the owner; returns the claim's 303. */
84
- async start({ origin, originVar, ends, endsLocal, settings, correlation }) {
85
- this.correlation = correlation; this.started = this.now(); this.stopped = false; this.cancelled = false;
86
- let deadline = this.started + this.startTimeout;
87
- const id = this.ctx.id.toString(), keys = await claimKeys(), now = this.now();
88
- await this.ctx.storage.put({ ends, seen: now, correlation, started: this.started, startDeadline: deadline });
89
- report(correlation, this.started, 'start');
90
- if (this.stopped) throw new Error('container-stopped');
91
- deadline = await placeContainer(this, { enableInternet: true, env: { ...settings, RER_DEMO: '1', [originVar]: origin, RER_INGRESS_ORIGIN: origin, RER_INGRESS_ORIGINS: JSON.stringify([origin, ...JSON.parse(this.env.DEMO_SECONDARY_ORIGINS ?? '[]')]),
92
- SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: this.owner, RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
93
- RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal } }, deadline);
94
- await this.container.setInactivityTimeout(this.idle);
95
- await this.ctx.storage.setAlarm(deadline);
96
- const token = await signClaim(keys, { origin, installationId: id, email: this.owner, now: this.now() });
97
- // Hold the place to the demo's end while the owner claim runs; a failed claim releases it in cleanup.
98
- const held = bounded(this.env.CAPACITY.get(this.env.CAPACITY.idFromName('capacity')).extend(id, ends), 2000).catch(() => false);
99
- const claimed = await boundedFetch(this.port(), 'http://container/auth/owner-claim', { method: 'POST', redirect: 'manual',
100
- headers: { origin, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ token }) }, Math.max(1, Math.min(10_000, deadline - this.now())));
101
- void claimed.body?.cancel().catch(() => {});
102
- this.record('claim', { status: claimed.status });
103
- if (this.stopped) throw new Error('container-stopped');
104
- if (claimed.status !== 303) throw new Error(`owner claim answered ${claimed.status}`);
105
- if (!await held) throw new Error('start-reservation-expired');
106
- await this.ctx.storage.put('seen', this.now());
107
- await this.ctx.storage.setAlarm(Math.min(ends, this.now() + this.idle));
108
- return { location: claimed.headers.get('location'), cookies: claimed.headers.getSetCookie() };
109
- }
110
-
111
- async healthy(deadline) {
112
- let attempt = 0;
113
- while (this.now() < deadline) {
114
- if (this.stopped) throw new Error('container-stopped');
115
- const probe = this.now();
116
- try {
117
- const response = await boundedFetch(this.port(), 'http://container/health', {}, Math.min(this.probeTimeout, deadline - this.now()));
118
- void response.body?.cancel().catch(() => {});
119
- this.record('health', { attempt: ++attempt, durationMs: this.now() - probe, status: response.status });
120
- if (response.ok && !this.stopped) return;
121
- } catch (error) {
122
- this.record('health', { attempt: ++attempt, durationMs: this.now() - probe, error: category(error) });
123
- }
124
- await new Promise(resolve => setTimeout(resolve, Math.min(100, Math.max(0, deadline - this.now()))));
125
- }
126
- throw new Error('health-deadline');
127
- }
128
-
129
- async exited(error) {
130
- this.watching = false;
131
- this.stopReason = error ? category(error) : 'container-stopped';
132
- this.stopped = true;
133
- this.record('exit', { outcome: error ? category(error) : 'exited', ...(Number.isInteger(error?.exitCode) ? { exitCode: error.exitCode } : {}) });
134
- if ((await this.ctx.storage.get('startup'))?.phase === 'starting') return;
135
- try { await this.end(); } catch (cause) { report(this.correlation, this.started, 'cleanup', { error: category(cause) }); }
136
- }
137
-
138
- /** Every request carrying this demo's cookie: proxied while the demo lives, else the ended page. */
139
- async fetch(request) {
140
- const state = await this.ctx.storage.get(['ends', 'seen']), now = this.now();
141
- if (!state.get('ends') || now >= Math.min(state.get('ends'), state.get('seen') + this.idle)) {
142
- try { await this.end(); }
143
- catch (cause) { report(this.correlation, this.started, 'cleanup', { error: category(cause) }); }
144
- return this.ended();
145
- }
146
- if (!this.container.running) return this.gone();
147
- await this.ctx.storage.put('seen', now);
148
- await this.ctx.storage.setAlarm(Math.min(state.get('ends'), now + this.idle));
149
- const forwarded = new Request(inside(new URL(request.url)), request);
150
- // The front admits only declared hosts. Never let a visitor choose the
151
- // container's public origin through a transport header.
152
- forwarded.headers.set('x-rer-ingress-origin', new URL(request.url).origin);
153
- try { return await this.port().fetch(forwarded); }
154
- catch (error) { if (this.container.running && !this.stopped) throw error; return this.gone(); }
155
- }
156
-
157
- ended() { return endedPage(this.env, { status: 410, headers: { 'set-cookie': clearCookie(this.env) } }); }
158
-
159
- /** A container the platform stopped while nothing watched it: end the demo (the alarm retries a failed cleanup). */
160
- async gone() {
161
- this.record('exit', { outcome: 'gone' });
162
- try { await this.end(); } catch (cause) { report(this.correlation, this.started, 'cleanup', { error: category(cause) }); }
163
- return this.ended();
164
- }
165
-
166
- async alarm() {
167
- const state = await this.ctx.storage.get(['ends', 'seen', 'startDeadline']), now = this.now();
168
- if (await this.ctx.storage.get('stopping')) return this.end();
169
- if (!state.get('ends')) return this.ctx.storage.deleteAll();
170
- const due = Math.min(state.get('ends'), state.get('seen') + this.idle, state.get('startDeadline') ?? Infinity);
171
- if (now >= due || !this.container.running) {
172
- if ((await this.ctx.storage.get('startup'))?.phase === 'starting') { this.stopped = true; return; }
173
- return this.end();
174
- }
175
- await this.ctx.storage.setAlarm(due);
176
- }
177
-
178
- /** Destroy the container and delete this demo's state and place; safe to repeat. */
179
- async end() {
180
- if (this.ending) return this.ending;
181
- this.ending = this.cleanup();
182
- try { await this.ending; } finally { this.ending = null; }
183
- }
184
-
185
- async cleanup() {
186
- this.cancelled = true; this.stopped = true;
187
- const startup = await this.ctx.storage.get('startup');
188
- const failure = startup?.failure ?? (startup?.phase === 'failed' ? startup : null);
189
- // A failed start has no live visitor. Release it even if destruction needs
190
- // another alarm; a live demo keeps its place until destruction succeeds.
191
- await this.ctx.storage.put('stopping', true);
192
- await this.ctx.storage.setAlarm(this.now() + this.cleanupRetry);
193
- if (failure) {
194
- await this.releasePlace();
195
- await this.ctx.storage.put('startup', failure);
196
- }
197
- if (this.container.running) {
198
- if (!failure) {
199
- try { await bounded(this.env.CAPACITY.get(this.env.CAPACITY.idFromName('capacity')).extend(this.ctx.id.toString(), this.now() + 60_000), 2000); }
200
- catch (cause) { report(this.correlation, this.started, 'cleanup-reservation', { error: category(cause) }); }
201
- }
202
- await bounded(this.container.destroy(), 5000);
203
- }
204
- if (!failure) await this.releasePlace();
205
- await this.ctx.storage.deleteAlarm();
206
- await this.ctx.storage.deleteAll();
207
- // Retain only the terminal answer briefly, so polling survives a fresh DO.
208
- if (failure) {
209
- await this.ctx.storage.put({ startup: failure, correlation: this.correlation, started: this.started });
210
- await this.ctx.storage.setAlarm(this.now() + 60_000);
211
- }
212
- report(this.correlation, this.started, 'ended');
213
- }
214
-
215
- async releasePlace() {
216
- const id = this.ctx.id.toString();
217
- if (await bounded(this.env.CAPACITY.get(this.env.CAPACITY.idFromName('capacity')).release(id), 2000)) {
218
- report(this.correlation, this.started, 'released', { releasedId: await fingerprint(id) });
219
- }
220
- }
221
- }
@@ -1,9 +0,0 @@
1
- #!/bin/sh
2
- set -eu
3
- umask 077
4
- mkdir -p /data
5
- # Keep this same lock inode held through template copying and the host lifetime.
6
- exec flock --nonblock --no-fork /data/host.lock sh -ec '
7
- node /runtime/modules/demo-host/template.mjs /template /data
8
- exec node /runtime/modules/container/host.mjs "$@"
9
- ' sh "$@"
@@ -1,18 +0,0 @@
1
- import { cp, mkdir, readFile, writeFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
-
4
- /** Add demo-only preparation to an ordinary workerd image build folder. */
5
- export async function prepareDemoImage(image) {
6
- const manifest = JSON.parse(await readFile(join(image, 'app/container.json'), 'utf8'));
7
- if (manifest.engine !== 'workerd') throw new Error('demo-template-requires-workerd');
8
- const path = join(image, 'Dockerfile'), dockerfile = await readFile(path, 'utf8');
9
- const entrypoint = 'ENTRYPOINT ["sh", "/runtime/modules/container/entrypoint.sh"]';
10
- if (!dockerfile.endsWith(entrypoint + '\n')) throw new Error('demo-image-entrypoint-changed');
11
- const runtime = join(image, 'runtime/modules/demo-host');
12
- await mkdir(runtime, { recursive: true });
13
- for (const file of ['prepare.mjs', 'template.mjs', 'entrypoint.sh']) await cp(new URL(file, import.meta.url), join(runtime, file));
14
- await writeFile(path, dockerfile.slice(0, -entrypoint.length - 1)
15
- + 'RUN --network=none node /runtime/modules/demo-host/prepare.mjs\n'
16
- + 'ENTRYPOINT ["sh", "/runtime/modules/demo-host/entrypoint.sh"]\n');
17
- return { output: image };
18
- }
@@ -1,37 +0,0 @@
1
- import { bounded } from './diagnostics.mjs';
2
-
3
- // Cloudflare keeps a small prepared pool per application (7 instances measured
4
- // on fresh hosts) and prepares more only on demand: a start beyond the pool
5
- // waits while Cloudflare places a new instance (16-37 s measured), then boots
6
- // normally. Keep this visitor's reservation through that wait. Only the
7
- // provider's explicit no-instance response permits another placement attempt,
8
- // and it renews the boot budget up to placementTimeout from the start; boot,
9
- // health and claim failures still terminate the start. Returns the deadline the
10
- // placed container must become healthy and claimed by.
11
- export async function placeContainer(demo, options, deadline) {
12
- const limit = demo.started + demo.placementTimeout, capacity = demo.env.CAPACITY.get(demo.env.CAPACITY.idFromName('capacity'));
13
- let attempt = 0;
14
- while (Date.now() < deadline && !demo.cancelled) {
15
- demo.stopped = false;
16
- demo.stopReason = undefined;
17
- demo.container.start(options);
18
- demo.watch();
19
- await demo.ctx.storage.setAlarm(deadline);
20
- try {
21
- await demo.healthy(deadline);
22
- return deadline;
23
- } catch (error) {
24
- if (demo.cancelled || demo.stopReason !== 'placement-unavailable') throw error;
25
- demo.record('placement', { attempt: ++attempt, outcome: 'waiting' });
26
- const renewed = Math.min(limit, Date.now() + demo.startTimeout);
27
- if (renewed > deadline) {
28
- // The reservation outlives the renewed budget, or the place is no longer this visitor's.
29
- if (!await bounded(capacity.extend(demo.ctx.id.toString(), renewed + 15_000), 2000)) throw new Error('start-reservation-expired');
30
- deadline = renewed;
31
- await demo.ctx.storage.put('startDeadline', deadline);
32
- }
33
- await new Promise(resolve => setTimeout(resolve, Math.min(1000, Math.max(0, deadline - Date.now()))));
34
- }
35
- }
36
- throw new Error(demo.cancelled ? 'container-stopped' : 'placement-unavailable');
37
- }
@@ -1,28 +0,0 @@
1
- import { mkdir, readFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
- import { workerEngine } from '../container/worker-engine.mjs';
4
- import { sealTemplate } from './template.mjs';
5
-
6
- /** Migrate with the packaged engine; never dispatch an app request or claim. */
7
- export async function prepareTemplate({ root = '/app', data = '/template' } = {}) {
8
- const manifest = JSON.parse(await readFile(join(root, 'container.json'), 'utf8'));
9
- if (manifest.engine !== 'workerd') throw new Error('demo-template-requires-workerd');
10
- await mkdir(data, { mode: 0o700 });
11
- let engine;
12
- try {
13
- engine = await workerEngine({ root, data, manifest, settings: { RER_DEMO: '1' } });
14
- } finally {
15
- await engine?.close();
16
- }
17
- return sealTemplate(data, manifest);
18
- }
19
-
20
- if (process.argv[1] === import.meta.filename) {
21
- try { await prepareTemplate(); }
22
- catch (error) {
23
- // A failed engine constructor may still own workerd handles. The build must
24
- // fail immediately; there is no usable template to keep alive or recover.
25
- console.error('Demo template preparation failed:', error.name);
26
- process.exit(1);
27
- }
28
- }
@@ -1,27 +0,0 @@
1
- import { bounded, category, report } from './diagnostics.mjs';
2
- import { fingerprint } from './capacity.mjs';
3
-
4
- // Kept by the visitor's Durable Object while the front returns short progress
5
- // responses. A dropped browser request cannot abandon cleanup or hold a place
6
- // until the demo's hour expires.
7
- export async function finishStart(demo, options) {
8
- const { correlation } = options, id = demo.ctx.id.toString();
9
- try {
10
- report(correlation, Date.now(), 'reservation', { heldId: await fingerprint(id) });
11
- const result = await bounded(demo.start(options), demo.placementTimeout + 1000);
12
- if (demo.stopped) throw new Error('container-stopped');
13
- await demo.ctx.storage.put('startup', { phase: 'ready', ...result });
14
- await demo.ctx.storage.delete('startDeadline');
15
- } catch (error) {
16
- const failure = ['health-deadline', 'container-stopped', 'start-reservation-expired'].includes(error.message) ? error.message : category(error);
17
- demo.record('failed', { error: failure });
18
- // Release before publishing the retry state, diagnostic capture or a slow
19
- // destruction retry. This copy never became a live visitor's demo.
20
- await demo.ctx.storage.put('startup', { phase: 'starting', failure: { phase: 'failed' } });
21
- try { await demo.end(); } catch (cleanup) { report(correlation, demo.started, 'cleanup', { error: category(cleanup) }); }
22
- try {
23
- const diagnostic = await bounded(demo.diagnostic(), 3000);
24
- await bounded(demo.env.CAPACITY.get(demo.env.CAPACITY.idFromName('diagnostics')).record(correlation, { ...diagnostic, failure }), 3000);
25
- } catch (capture) { report(correlation, demo.started, 'diagnostic', { error: category(capture) }); }
26
- }
27
- }
@@ -1,71 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { cp, lstat, mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
-
5
- const descriptor = '.rer-demo-template.json';
6
- const initialized = '.rer-demo-initialized.json';
7
- const copying = '.rer-demo-initializing.json';
8
-
9
- async function inventory(directory, prefix = '') {
10
- const entries = [];
11
- for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
12
- if (!entry.isFile() && !entry.isDirectory()) throw new Error('demo-template-invalid-entry');
13
- const path = prefix + entry.name;
14
- entries.push({ path, directory: entry.isDirectory() });
15
- if (entry.isDirectory()) entries.push(...await inventory(join(directory, entry.name), path + '/'));
16
- }
17
- return entries;
18
- }
19
-
20
- /** Called only after the engine has closed its database and persistence files. */
21
- export async function sealTemplate(template, manifest) {
22
- const entries = await inventory(template);
23
- if (entries.some(entry => ['host.lock', descriptor, initialized, copying].includes(entry.path))) throw new Error('demo-template-not-fresh');
24
- const marker = { version: 1, manifest: createHash('sha256').update(JSON.stringify(manifest)).digest('hex'), entries };
25
- await writeFile(join(template, descriptor), JSON.stringify(marker) + '\n', { flag: 'wx', mode: 0o600 });
26
- return marker;
27
- }
28
-
29
- async function present(directory, entries) {
30
- for (const entry of entries) {
31
- let stat;
32
- try { stat = await lstat(join(directory, entry.path)); }
33
- catch (error) { if (error.code === 'ENOENT') return false; throw error; }
34
- if (entry.directory ? !stat.isDirectory() : !stat.isFile()) return false;
35
- }
36
- return true;
37
- }
38
-
39
- /** Caller holds data/host.lock until the host exits. Never overlays live data. */
40
- export async function copyTemplate(template, data) {
41
- const raw = await readFile(join(template, descriptor), 'utf8'), marker = JSON.parse(raw);
42
- if (marker.version !== 1 || !/^[a-f0-9]{64}$/.test(marker.manifest ?? '') || !Array.isArray(marker.entries)
43
- || marker.entries.some(entry => typeof entry.path !== 'string' || !entry.path || entry.path.startsWith('/')
44
- || entry.path.split('/').some(part => ['', '.', '..'].includes(part)) || typeof entry.directory !== 'boolean'
45
- || [descriptor, initialized, copying, 'host.lock'].includes(entry.path))) throw new Error('demo-template-invalid');
46
- await mkdir(data, { recursive: true, mode: 0o700 });
47
- const existing = await readdir(data);
48
- if (existing.includes('host.lock') && !(await lstat(join(data, 'host.lock'))).isFile()) throw new Error('demo-volume-invalid-lock');
49
- if (existing.includes(copying)) throw new Error('demo-volume-incomplete');
50
- if (existing.includes(initialized)) {
51
- if (!(await lstat(join(data, initialized))).isFile()) throw new Error('demo-volume-incomplete');
52
- if (await readFile(join(data, initialized), 'utf8') !== raw) throw new Error('demo-volume-template-mismatch');
53
- // SQLite may remove its transient WAL/SHM files after a later clean close.
54
- if (!await present(data, marker.entries.filter(entry => !/-(wal|shm)$/.test(entry.path)))) throw new Error('demo-volume-incomplete');
55
- return { copied: false };
56
- }
57
- if (existing.some(name => name !== 'host.lock')) throw new Error('demo-volume-not-fresh');
58
- if (!await present(template, marker.entries)) throw new Error('demo-template-incomplete');
59
- await writeFile(join(data, copying), raw, { flag: 'wx', mode: 0o600 });
60
- for (const entry of marker.entries.filter(entry => !entry.path.includes('/'))) {
61
- await cp(join(template, entry.path), join(data, entry.path), { recursive: true, force: false, errorOnExist: true });
62
- }
63
- if (!await present(data, marker.entries)) throw new Error('demo-volume-incomplete');
64
- await rename(join(data, copying), join(data, initialized));
65
- return { copied: true };
66
- }
67
-
68
- if (process.argv[1] === import.meta.filename) {
69
- try { await copyTemplate(process.argv[2] ?? '/template', process.argv[3] ?? '/data'); }
70
- catch (error) { console.error('Demo volume initialization failed:', error.message); process.exitCode = 1; }
71
- }