@runeditrun/rer 0.2.29 → 0.2.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/cli/README.md +17 -0
- package/cli/business/command.mjs +27 -0
- package/cli/business/detector.mjs +42 -0
- package/cli/business/parsers-config.mjs +91 -0
- package/cli/business/parsers-infrastructure.mjs +68 -0
- package/cli/business/parsers-packages.mjs +84 -0
- package/cli/business/parsers-pulumi.mjs +64 -0
- package/cli/business/parsers-syntax.mjs +113 -0
- package/cli/business/parsers-terraform.mjs +53 -0
- package/cli/business/parsers.mjs +62 -0
- package/cli/business/policy.mjs +46 -0
- package/cli/business/scan.mjs +67 -0
- package/cli/contract.mjs +2 -2
- package/cli/demo-build.mjs +23 -0
- package/cli/demo-host.mjs +10 -70
- package/cli/demo-native.mjs +74 -0
- package/cli/lifecycle.mjs +1 -1
- package/cli/main.mjs +1 -0
- package/cli/parse.mjs +1 -1
- package/cli/release.mjs +5 -2
- package/global/CHANGELOG.md +30 -0
- package/global/README.md +16 -0
- package/global/main.mjs +3 -0
- package/modules/container/README.md +2 -15
- package/modules/container/host.mjs +1 -3
- package/modules/container/ingress.mjs +1 -15
- package/modules/container/worker-engine.mjs +2 -3
- package/modules/demo-host/README.md +23 -156
- package/modules/demo-host/build.mjs +49 -0
- package/modules/demo-host/capacity.mjs +8 -2
- package/modules/demo-host/claim.mjs +2 -2
- package/modules/demo-host/diagnostics.mjs +1 -18
- package/modules/demo-host/native/alarms.mjs +51 -0
- package/modules/demo-host/native/bindings.mjs +24 -0
- package/modules/demo-host/native/bridge.mjs +17 -0
- package/modules/demo-host/native/config.mjs +35 -0
- package/modules/demo-host/native/cron.mjs +31 -0
- package/modules/demo-host/native/d1.mjs +37 -0
- package/modules/demo-host/native/deploy-r2.mjs +43 -0
- package/modules/demo-host/native/isolate.mjs +36 -0
- package/modules/demo-host/native/loader.mjs +30 -0
- package/modules/demo-host/native/namespace.mjs +35 -0
- package/modules/demo-host/native/prepare.mjs +35 -0
- package/modules/demo-host/native/queues.mjs +62 -0
- package/modules/demo-host/native/r2-client.mjs +37 -0
- package/modules/demo-host/native/r2.mjs +43 -0
- package/modules/demo-host/native/resources.mjs +37 -0
- package/modules/demo-host/native/seed-object.mjs +22 -0
- package/modules/demo-host/native/sql.mjs +17 -0
- package/modules/demo-host/native/visitor.mjs +147 -0
- package/modules/demo-host/native/worker.mjs +22 -0
- package/modules/demo-host/pages.mjs +1 -1
- package/modules/demo-host/plan.mjs +9 -30
- package/modules/demo-host/remove.mjs +13 -23
- package/modules/demo-host/upgrade.mjs +41 -0
- package/modules/demo-host/worker.mjs +3 -4
- package/modules/owner-claim/verify.d.mts +5 -0
- package/modules/release/README.md +11 -1
- package/modules/release/github-verify.mjs +30 -26
- package/modules/release/produce.mjs +2 -2
- package/modules/release/source-verification.mjs +2 -2
- package/modules/release/verify-workflow.mjs +23 -0
- package/package.json +1 -1
- package/modules/demo-host/container.mjs +0 -221
- package/modules/demo-host/entrypoint.sh +0 -9
- package/modules/demo-host/image.mjs +0 -18
- package/modules/demo-host/placement.mjs +0 -37
- package/modules/demo-host/prepare.mjs +0 -28
- package/modules/demo-host/startup.mjs +0 -27
- package/modules/demo-host/template.mjs +0 -71
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
class Id {
|
|
4
|
+
constructor(value, name) { this.value = value; this.name = name; }
|
|
5
|
+
toString() { return this.value; }
|
|
6
|
+
equals(other) { return this.value === other.toString(); }
|
|
7
|
+
}
|
|
8
|
+
export class DemoNamespace {
|
|
9
|
+
constructor(host, binding, key) { this.host = host; this.binding = binding; this.key = key; }
|
|
10
|
+
idFromName(name) { return new Id(createHash('sha256').update(`${this.binding}:${name}`).digest('hex'), name); }
|
|
11
|
+
idFromString(value) {
|
|
12
|
+
if (!/^[a-f0-9]{64}$/i.test(value)) throw new TypeError('Invalid Durable Object id');
|
|
13
|
+
return new Id(value.toLowerCase());
|
|
14
|
+
}
|
|
15
|
+
newUniqueId() { return new Id([...crypto.getRandomValues(new Uint8Array(32))].map(byte => byte.toString(16).padStart(2, '0')).join('')); }
|
|
16
|
+
jurisdiction() { return this; }
|
|
17
|
+
getByName(name, options) { return this.get(this.idFromName(name), options); }
|
|
18
|
+
get(id) {
|
|
19
|
+
const host = this.host, binding = this.binding, key = this.key, value = this.idFromString(id.toString());
|
|
20
|
+
return new Proxy({ id, name: id.name }, { get(target, method) {
|
|
21
|
+
if (method in target) return target[method];
|
|
22
|
+
if (method === 'then' || typeof method === 'symbol') return undefined;
|
|
23
|
+
return async (...args) => {
|
|
24
|
+
if (method === 'fetch') {
|
|
25
|
+
const request = args[0] instanceof Request ? args[0] : new Request(...args);
|
|
26
|
+
const headers = new Headers(request.headers);
|
|
27
|
+
headers.set('x-rer-native-object', `${binding}:${value}`);
|
|
28
|
+
headers.set('x-rer-native-key', key);
|
|
29
|
+
return host.fetch(new Request(request, { headers }));
|
|
30
|
+
}
|
|
31
|
+
return host.object(binding, value.toString(), method, args);
|
|
32
|
+
};
|
|
33
|
+
} });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { readFile, writeFile, cp } from 'node:fs/promises';
|
|
2
|
+
import { resolve, join, relative } from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { collectBuildModules } from '../../deploy-kit/build-modules.mjs';
|
|
5
|
+
import { collectFiles } from '../../deploy-kit/artifact.mjs';
|
|
6
|
+
import { nativeBindings, ISOLATE_FILES, objectExports } from './config.mjs';
|
|
7
|
+
|
|
8
|
+
// Reuse the normal production build and its migration inventory, without
|
|
9
|
+
// building or running a container. The bundle is stored once in the front.
|
|
10
|
+
export async function prepareNative(folder) {
|
|
11
|
+
const app = join(folder, 'bundle/app');
|
|
12
|
+
const manifest = JSON.parse(await readFile(join(app, 'demo.json'), 'utf8'));
|
|
13
|
+
const config = manifest.config, root = join(app, 'dist/server');
|
|
14
|
+
const bindings = nativeBindings(config);
|
|
15
|
+
const main = relative(root, resolve(root, config.main));
|
|
16
|
+
const modules = {};
|
|
17
|
+
for (const file of await collectBuildModules(root, config, main)) {
|
|
18
|
+
const source = Buffer.from(file.base64, 'base64');
|
|
19
|
+
if (/\.(m?js)$/.test(file.path)) modules[`app/${file.path}`] = { js: source.toString('utf8') };
|
|
20
|
+
else if (/\.(txt|html|sql)$/.test(file.path)) modules[`app/${file.path}`] = { text: source.toString('utf8') };
|
|
21
|
+
else throw new Error(`Loader demo does not implement module type: ${file.path}`);
|
|
22
|
+
}
|
|
23
|
+
const entry = `../app/${main}`;
|
|
24
|
+
modules['_rer/isolate.js'] = { js: (await readFile(new URL('./isolate.mjs', import.meta.url), 'utf8')).replace('__RER_APP_ENTRY__', entry)
|
|
25
|
+
+ objectExports(bindings) };
|
|
26
|
+
for (const file of ISOLATE_FILES) modules[`_rer/${file}.js`] = { js: await readFile(new URL(`./${file}.mjs`, import.meta.url), 'utf8') };
|
|
27
|
+
const assets = await collectFiles(join(app, 'dist/client'));
|
|
28
|
+
const bundle = { compatibilityDate: config.compatibility_date, compatibilityFlags: [...new Set([...(config.compatibility_flags ?? []), 'nodejs_compat'])], modules,
|
|
29
|
+
bindings, migrations: manifest.migrations, vars: config.vars ?? {}, crons: config.triggers?.crons ?? [],
|
|
30
|
+
assetPaths: assets.filter(file => !file.path.split('/').some(part => part.startsWith('.'))).map(file => '/' + file.path) };
|
|
31
|
+
bundle.digest = createHash('sha256').update(JSON.stringify(bundle)).digest('hex');
|
|
32
|
+
await cp(join(app, 'dist/client'), join(folder, 'assets'), { recursive: true });
|
|
33
|
+
await writeFile(join(folder, 'modules/demo-host/native/bundle.mjs'), `export default ${JSON.stringify(bundle)};\n`);
|
|
34
|
+
return bundle;
|
|
35
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { application, bundle } from './loader.mjs';
|
|
2
|
+
const consumerFor = queue => bundle.bindings.queues.consumers.find(item => item.queue === queue);
|
|
3
|
+
export async function enqueue(host, queue, messages) {
|
|
4
|
+
await host.active();
|
|
5
|
+
if (!bundle.bindings.queues.producers.some(item => item.queue === queue)) throw new Error(`Unknown queue: ${queue}`);
|
|
6
|
+
if (!Array.isArray(messages) || !messages.length || messages.length > 100) throw new Error('Queue batch must contain 1–100 messages');
|
|
7
|
+
const now = Date.now(), records = {};
|
|
8
|
+
for (const message of messages) {
|
|
9
|
+
const type = message.contentType ?? 'json';
|
|
10
|
+
if (!['json', 'text', 'bytes', 'v8'].includes(type)) throw new TypeError('Unknown queue contentType');
|
|
11
|
+
const body = type === 'json' ? JSON.parse(JSON.stringify(message.body)) : message.body;
|
|
12
|
+
if (type === 'text' && typeof body !== 'string') throw new TypeError('Queue text body must be a string');
|
|
13
|
+
const delay = message.delaySeconds ?? consumerFor(queue)?.delivery_delay ?? 0;
|
|
14
|
+
if (!Number.isInteger(delay) || delay < 0 || delay > 43200) throw new TypeError('Invalid queue delaySeconds');
|
|
15
|
+
const id = crypto.randomUUID();
|
|
16
|
+
records[`queue:${id}`] = { id, queue, body, timestamp: now, attempts: 0, at: now + Math.max(delay * 1000, Math.min(1000, (consumerFor(queue)?.max_batch_timeout ?? 1) * 1000)) };
|
|
17
|
+
}
|
|
18
|
+
await host.ctx.storage.put(records);
|
|
19
|
+
await host.schedule(Math.min(...Object.values(records).map(item => item.at)));
|
|
20
|
+
return { metadata: { metrics: await queueMetrics(host, queue) } };
|
|
21
|
+
}
|
|
22
|
+
export async function deliverQueues(host, now) {
|
|
23
|
+
const records = await host.ctx.storage.list({ prefix: 'queue:' });
|
|
24
|
+
const groups = new Map();
|
|
25
|
+
for (const message of records.values()) if (message.at <= now) {
|
|
26
|
+
if (!groups.has(message.queue)) groups.set(message.queue, []);
|
|
27
|
+
groups.get(message.queue).push(message);
|
|
28
|
+
}
|
|
29
|
+
for (const [queue, pending] of groups) {
|
|
30
|
+
const consumer = consumerFor(queue) ?? {}, size = consumer.max_batch_size ?? 10;
|
|
31
|
+
// Bound alarm work. Undelivered batches retain their original durable records.
|
|
32
|
+
const messages = pending.slice(0, size).map(message => ({ ...message, attempts: message.attempts + 1 }));
|
|
33
|
+
let outcomes;
|
|
34
|
+
try { outcomes = await application(host.env, host.ctx, host.ctx.id.toString(), host.state.runtime).runQueue(queue, messages); }
|
|
35
|
+
catch { outcomes = messages.map(message => ({ id: message.id, retry: true })); }
|
|
36
|
+
console.log(JSON.stringify({ event: 'native-demo-queue', correlation: host.state?.correlation, queue, messages: messages.length, acknowledged: outcomes.filter(item => !item.retry).length }));
|
|
37
|
+
for (const message of messages) {
|
|
38
|
+
if (!host.state || host.state.phase !== 'ready') return;
|
|
39
|
+
const result = outcomes.find(item => item.id === message.id);
|
|
40
|
+
if (result && !result.retry) await host.ctx.storage.delete(`queue:${message.id}`);
|
|
41
|
+
else if (message.attempts <= (consumer.max_retries ?? 3)) {
|
|
42
|
+
message.at = Date.now() + (result?.delaySeconds ?? consumer.retry_delay ?? Math.min(60, 2 ** message.attempts)) * 1000;
|
|
43
|
+
await host.ctx.storage.put(`queue:${message.id}`, message);
|
|
44
|
+
} else if (consumer.dead_letter_queue) {
|
|
45
|
+
const target = consumer.dead_letter_queue;
|
|
46
|
+
await host.ctx.storage.put(`queue:${message.id}`, { ...message, queue: target, attempts: 0, at: consumerFor(target) ? Date.now() : Number.MAX_SAFE_INTEGER });
|
|
47
|
+
} else await host.ctx.storage.delete(`queue:${message.id}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export async function nextQueue(host) {
|
|
52
|
+
return Math.min(Infinity, ...[...(await host.ctx.storage.list({ prefix: 'queue:' })).values()].map(item => item.at));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function queueMetrics(host, queue) {
|
|
56
|
+
await host.active();
|
|
57
|
+
if (!bundle.bindings.queues.producers.some(item => item.queue === queue)) throw new Error(`Unknown queue: ${queue}`);
|
|
58
|
+
const messages = [...(await host.ctx.storage.list({ prefix: 'queue:' })).values()].filter(item => item.queue === queue);
|
|
59
|
+
const bytes = body => body instanceof ArrayBuffer || ArrayBuffer.isView(body) ? body.byteLength : new TextEncoder().encode(typeof body === 'string' ? body : JSON.stringify(body)).byteLength;
|
|
60
|
+
return { backlogCount: messages.length, backlogBytes: messages.reduce((sum, item) => sum + bytes(item.body), 0),
|
|
61
|
+
...(messages.length ? { oldestMessageTimestamp: new Date(Math.min(...messages.map(item => item.timestamp))) } : {}) };
|
|
62
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
function object(value) {
|
|
2
|
+
if (!value) return value;
|
|
3
|
+
value.writeHttpMetadata = headers => {
|
|
4
|
+
for (const [key, content] of Object.entries(value.httpMetadata ?? {})) {
|
|
5
|
+
const header = { contentType: 'content-type', contentLanguage: 'content-language', contentDisposition: 'content-disposition', contentEncoding: 'content-encoding', cacheControl: 'cache-control', cacheExpiry: 'expires' }[key];
|
|
6
|
+
if (header) headers.set(header, content instanceof Date ? content.toUTCString() : content);
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
if (value.body) {
|
|
10
|
+
const response = new Response(value.body);
|
|
11
|
+
Object.defineProperty(value, 'bodyUsed', { get: () => response.bodyUsed });
|
|
12
|
+
for (const method of ['arrayBuffer', 'text', 'json', 'blob']) value[method] = () => response[method]();
|
|
13
|
+
value.bytes = async () => new Uint8Array(await response.arrayBuffer());
|
|
14
|
+
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
// RPC does not preserve a stream's known byte length, which R2 requires.
|
|
18
|
+
// Seed upload limits keep these demo bodies bounded; multipart parts are
|
|
19
|
+
// buffered separately rather than collecting the complete multipart object.
|
|
20
|
+
const bytes = value => value instanceof Blob ? value.arrayBuffer() : value instanceof ReadableStream ? new Response(value).arrayBuffer() : value;
|
|
21
|
+
export class DemoR2 {
|
|
22
|
+
constructor(host, binding) { this.host = host; this.binding = binding; }
|
|
23
|
+
call(method, ...args) { return this.host.r2(this.binding, method, args); }
|
|
24
|
+
async get(key, options) { return object(await this.call('get', key, options)); }
|
|
25
|
+
async head(key) { return object(await this.call('head', key)); }
|
|
26
|
+
async put(key, body, options) { return object(await this.call('put', key, await bytes(body), options)); }
|
|
27
|
+
delete(keys) { return this.call('delete', keys); }
|
|
28
|
+
async list(options) { const page = await this.call('list', options); page.objects = page.objects.map(object); return page; }
|
|
29
|
+
async createMultipartUpload(key, options) { return this.resumeMultipartUpload(key, await this.call('createMultipartUpload', key, options)); }
|
|
30
|
+
resumeMultipartUpload(key, uploadId) {
|
|
31
|
+
return { key, uploadId,
|
|
32
|
+
uploadPart: async (part, body, options) => this.call('uploadPart', key, uploadId, part, await bytes(body), options),
|
|
33
|
+
abort: () => this.call('abort', key, uploadId),
|
|
34
|
+
complete: async parts => object(await this.call('complete', key, uploadId, parts)),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export const prefixFor = (id, binding) => `${id}/${binding}/`;
|
|
2
|
+
function metadata(value, prefix) {
|
|
3
|
+
if (!value) return value;
|
|
4
|
+
const result = {};
|
|
5
|
+
for (const key of ['key', 'version', 'size', 'etag', 'httpEtag', 'uploaded', 'httpMetadata', 'customMetadata', 'range', 'storageClass', 'body']) {
|
|
6
|
+
if (value[key] !== undefined) result[key] = value[key];
|
|
7
|
+
}
|
|
8
|
+
result.key = result.key.slice(prefix.length);
|
|
9
|
+
if (value.checksums) result.checksums = Object.fromEntries(['md5', 'sha1', 'sha256', 'sha384', 'sha512'].filter(key => value.checksums[key]).map(key => [key, value.checksums[key]]));
|
|
10
|
+
return result;
|
|
11
|
+
}
|
|
12
|
+
export async function r2Call(bucket, storage, id, binding, method, args) {
|
|
13
|
+
const prefix = prefixFor(id, binding), key = value => prefix + String(value);
|
|
14
|
+
if (method === 'list') {
|
|
15
|
+
const options = args[0] ?? {};
|
|
16
|
+
const page = await bucket.list({ ...options, prefix: key(options.prefix ?? ''), ...(options.startAfter ? { startAfter: key(options.startAfter) } : {}) });
|
|
17
|
+
return { ...page, objects: page.objects.map(value => metadata(value, prefix)), delimitedPrefixes: page.delimitedPrefixes.map(value => value.slice(prefix.length)) };
|
|
18
|
+
}
|
|
19
|
+
if (method === 'delete') return bucket.delete(Array.isArray(args[0]) ? args[0].map(key) : key(args[0]));
|
|
20
|
+
if (['get', 'head', 'put'].includes(method)) return metadata(await bucket[method](key(args[0]), ...args.slice(1)), prefix);
|
|
21
|
+
if (method === 'createMultipartUpload') {
|
|
22
|
+
const upload = await bucket.createMultipartUpload(key(args[0]), args[1]);
|
|
23
|
+
try { await storage.put(`upload:${upload.uploadId}`, { key: key(args[0]), uploadId: upload.uploadId }); }
|
|
24
|
+
catch (error) { await upload.abort(); throw error; }
|
|
25
|
+
return upload.uploadId;
|
|
26
|
+
}
|
|
27
|
+
if (['uploadPart', 'abort', 'complete'].includes(method)) {
|
|
28
|
+
const upload = bucket.resumeMultipartUpload(key(args[0]), args[1]);
|
|
29
|
+
const result = await upload[method](...args.slice(2));
|
|
30
|
+
if (method !== 'uploadPart') await storage.delete(`upload:${args[1]}`);
|
|
31
|
+
return method === 'complete' ? metadata(result, prefix) : result;
|
|
32
|
+
}
|
|
33
|
+
throw new Error(`Unsupported R2 method: ${method}`);
|
|
34
|
+
}
|
|
35
|
+
export async function eraseR2(bucket, storage, id) {
|
|
36
|
+
if (!bucket) return;
|
|
37
|
+
for (const { key, uploadId } of (await storage.list({ prefix: 'upload:' })).values()) await bucket.resumeMultipartUpload(key, uploadId).abort();
|
|
38
|
+
for (;;) {
|
|
39
|
+
const page = await bucket.list({ prefix: `${id}/`, limit: 1000 });
|
|
40
|
+
if (!page.objects.length) break;
|
|
41
|
+
await bucket.delete(page.objects.map(value => value.key));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { objectClass } from './config.mjs';
|
|
2
|
+
import { application, loaded, bundle } from './loader.mjs';
|
|
3
|
+
import { r2Call, eraseR2 } from './r2.mjs';
|
|
4
|
+
|
|
5
|
+
export async function database(host, binding, method, args) {
|
|
6
|
+
await host.active();
|
|
7
|
+
if (!bundle.bindings.databases.includes(binding) || !['query', 'batch', 'exec'].includes(method)) throw new Error(`Unknown D1 binding or method: ${binding}.${method}`);
|
|
8
|
+
const { ctx, env, state } = host, id = ctx.id.toString();
|
|
9
|
+
const stub = binding === bundle.bindings.databases[0] ? application(env, ctx, id, state.runtime)
|
|
10
|
+
: ctx.facets.get(`database:${binding}`, () => ({ class: loaded(env, ctx, id, state.runtime).getDurableObjectClass('DemoDatabase') }));
|
|
11
|
+
return stub[method](...args);
|
|
12
|
+
}
|
|
13
|
+
export async function object(host, binding, id, method, args) {
|
|
14
|
+
await host.active();
|
|
15
|
+
const declared = bundle.bindings.objects.find(item => item.name === binding);
|
|
16
|
+
if (!declared || !/^[a-f0-9]{64}$/.test(id)) throw new Error(`Unknown Durable Object binding or id: ${binding}`);
|
|
17
|
+
const state = host.state, name = `object:${binding}:${id}`;
|
|
18
|
+
await host.ctx.storage.put(`facet:${name}`, true);
|
|
19
|
+
if (host.state !== state || state.phase === 'ending') throw new Error('demo-ended');
|
|
20
|
+
const stub = host.ctx.facets.get(name, () => ({ class: loaded(host.env, host.ctx, host.ctx.id.toString(), host.state.runtime).getDurableObjectClass(objectClass(binding)), id }));
|
|
21
|
+
if (['constructor', 'then'].includes(method) || method.startsWith('_')) throw new Error('Invalid Durable Object method');
|
|
22
|
+
return stub[method](...args);
|
|
23
|
+
}
|
|
24
|
+
export async function r2(host, binding, method, args) {
|
|
25
|
+
await host.active();
|
|
26
|
+
if (!bundle.bindings.buckets.includes(binding)) throw new Error(`Unknown R2 binding: ${binding}`);
|
|
27
|
+
const operation = r2Call(host.env.NATIVE_BUCKET, host.ctx.storage, host.ctx.id.toString(), binding, method, args);
|
|
28
|
+
host.r2Pending ??= new Set(); host.r2Pending.add(operation);
|
|
29
|
+
try { return await operation; } finally { host.r2Pending.delete(operation); }
|
|
30
|
+
}
|
|
31
|
+
export async function eraseResources(host) {
|
|
32
|
+
host.ctx.facets.delete('app');
|
|
33
|
+
for (const binding of bundle.bindings.databases.slice(1)) host.ctx.facets.delete(`database:${binding}`);
|
|
34
|
+
for (const key of (await host.ctx.storage.list({ prefix: 'facet:' })).keys()) host.ctx.facets.delete(key.slice(6));
|
|
35
|
+
await Promise.allSettled(host.r2Pending ?? []);
|
|
36
|
+
await eraseR2(host.env.NATIVE_BUCKET, host.ctx.storage, host.ctx.id.toString());
|
|
37
|
+
}
|
|
@@ -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
|
|
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
|
-
|
|
7
|
-
|
|
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', '
|
|
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,
|
|
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,
|
|
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: '
|
|
67
|
-
migrations: [{ tag: '
|
|
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,
|
|
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
|