@runeditrun/rer 0.2.21 → 0.2.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/README.md +26 -0
- package/cli/bounded.mjs +5 -1
- package/cli/delivery-declarations.mjs +2 -2
- package/cli/demo-host.mjs +5 -5
- package/cli/deploy-command.mjs +2 -2
- package/cli/deploy-inputs.mjs +4 -1
- package/cli/deploy.mjs +7 -3
- package/cli/deployment-record.mjs +52 -0
- package/cli/export.mjs +1 -1
- package/cli/local.mjs +11 -3
- package/cli/managed-server.mjs +7 -3
- package/cli/output.mjs +1 -1
- package/cli/production-auth.mjs +7 -13
- package/cli/production-mail.mjs +72 -0
- package/cli/signin.mjs +11 -6
- package/global/CHANGELOG.md +9 -0
- package/modules/container/README.md +18 -3
- package/modules/container/build.mjs +8 -12
- package/modules/container/host.mjs +9 -4
- package/modules/container/ingress.mjs +15 -4
- package/modules/container/migration-inventory.mjs +33 -0
- package/modules/container/migrations.mjs +16 -2
- package/modules/container/websockets.mjs +54 -0
- package/modules/container/worker-engine.mjs +2 -2
- package/modules/delivery-producer/migrations.mjs +61 -0
- package/modules/demo/README.md +4 -0
- package/modules/demo/effects.mjs +4 -0
- package/modules/demo/label.mjs +7 -4
- package/modules/demo/responses.mjs +1 -1
- package/modules/demo-host/README.md +32 -19
- package/modules/demo-host/capacity.mjs +3 -3
- package/modules/demo-host/container.mjs +65 -37
- package/modules/demo-host/pages.mjs +1 -1
- package/modules/demo-host/plan.mjs +19 -6
- package/modules/demo-host/remove.mjs +9 -7
- package/modules/demo-host/start-script.mjs +10 -1
- package/modules/demo-host/startup.mjs +4 -2
- package/modules/demo-host/worker.mjs +28 -7
- package/modules/dependencies/approval.mjs +3 -2
- package/modules/dependencies/index.mjs +2 -2
- package/modules/deploy-kit/README.md +4 -2
- package/modules/deploy-kit/diagnostics.mjs +9 -0
- package/modules/deploy-kit/owner-signin.mjs +1 -1
- package/modules/deploy-kit/provider-transport.mjs +56 -0
- package/modules/deploy-kit/provider.mjs +22 -20
- package/modules/mail/README.md +14 -5
- package/modules/mail/src/adapters/rer/contract.mjs +33 -5
- package/modules/mail/src/adapters/rer/index.mjs +4 -1
- package/modules/mail/src/core/transport.mjs +9 -3
- package/modules/operator-auth/README.md +9 -0
- package/modules/operator-auth/accounts/credentials.mjs +2 -2
- package/modules/operator-auth/accounts/email-change.mjs +2 -2
- package/modules/operator-auth/accounts/provider-control.mjs +3 -3
- package/modules/operator-auth/accounts/store.mjs +9 -8
- package/modules/operator-auth/dev/cli-session.mjs +5 -4
- package/modules/operator-auth/dev/index.mjs +5 -5
- package/modules/operator-auth/dev-gate.mjs +4 -2
- package/modules/operator-auth/identity/email-link/index.mjs +7 -1
- package/modules/operator-auth/signin/index.mjs +10 -2
- package/onboarding/adapter.mjs +11 -3
- package/onboarding/local/operation.mjs +4 -2
- package/onboarding/local/owner.mjs +9 -3
- package/onboarding/local/state-files.mjs +17 -0
- package/onboarding/operator-installer.mjs +2 -2
- package/onboarding/operator-migrations.mjs +48 -0
- package/onboarding/process-diagnostics.mjs +25 -5
- package/onboarding/process-table.mjs +45 -19
- package/package.json +1 -1
- package/scripts/publish-check/README.md +5 -2
- package/scripts/publish-check/content_identities.py +1 -1
- package/scripts/publish-check/json_identity.py +10 -1
- package/scripts/publish-check/public_hygiene.py +30 -4
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import { readFile, writeFile,
|
|
1
|
+
import { readFile, writeFile, realpath, cp, mkdir, rm } from 'node:fs/promises';
|
|
2
2
|
import { dirname, join, resolve, sep } from 'node:path';
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { pathToFileURL } from 'node:url';
|
|
5
|
-
import { createHash } from 'node:crypto';
|
|
6
5
|
import { parseJsonc } from '../../cli/jsonc.mjs';
|
|
7
6
|
import { portabilityPlan } from './portability-schema.mjs';
|
|
8
7
|
import { checkBoundary } from './boundary.mjs';
|
|
9
8
|
import { localDurableObjects } from './durable-objects.mjs';
|
|
10
9
|
import { readMigrationRewrites, withRewrites } from '../deploy-kit/migrations.mjs';
|
|
11
|
-
|
|
10
|
+
import { containerMigrationInventory } from './migration-inventory.mjs';
|
|
12
11
|
export async function buildContainer(root, options={}) {
|
|
13
12
|
const previous=process.cwd();process.chdir(root);
|
|
14
13
|
try{return await buildImage(root,options);}finally{process.chdir(previous);}
|
|
@@ -67,14 +66,11 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
|
|
|
67
66
|
if (!freshServerFiles.has(serverEntry)) throw new Error('Container server entry was not emitted by this build');
|
|
68
67
|
await checkBoundary(root,{engine,cacheContract,entries:[serverEntry],emittedFiles:freshServerFiles,outputRoot:serverOutput});
|
|
69
68
|
const { unstable_splitSqlQuery:split } = require('wrangler');
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
for (const name of (await readdir(directory)).filter(name => name.endsWith('.sql')).sort()) { const sql = await readFile(join(directory,name),'utf8'); migrations[db.binding].push({ name,sql,sha256:hash(sql),statements:split(sql) }); }
|
|
76
|
-
migrations[db.binding] = withRewrites(migrations[db.binding], rewrites, { partial:true });
|
|
77
|
-
}
|
|
69
|
+
const configFile = engine === 'workerd' ? 'dist/server/wrangler.json' : 'wrangler.jsonc';
|
|
70
|
+
const rewrites = await readMigrationRewrites(root);
|
|
71
|
+
const inventory = withRewrites(await containerMigrationInventory(root,{config:workerConfig,configFile}),rewrites);
|
|
72
|
+
const migrations = Object.fromEntries((workerConfig.d1_databases ?? []).map(db => [db.binding,[]]));
|
|
73
|
+
for (const {binding,...migration} of inventory) migrations[binding].push({...migration,statements:split(migration.sql)});
|
|
78
74
|
const entry = engine === 'workerd' ? 'dist/server/'+workerConfig.main : 'dist/server/index.mjs';
|
|
79
75
|
await readFile(join(root,entry));
|
|
80
76
|
if (engine === 'node' && workerConfig.kv_namespaces?.length) throw new Error('Node container does not support KV');
|
|
@@ -89,7 +85,7 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
|
|
|
89
85
|
}
|
|
90
86
|
const base = resolve(import.meta.dirname,'../..');
|
|
91
87
|
for (const path of ['modules/container','modules/portability','modules/d1-transport','modules/deploy-kit','cli/scheduled.mjs','cli/jsonc.mjs','modules/integrations/core/public-address.ts']) { await mkdir(join(output,'runtime',path,'..'),{recursive:true}); await cp(join(base,path),join(output,'runtime',path),{recursive:true,filter:path => !path.includes('/tests/')}); }
|
|
92
|
-
const dependencies = engine === 'workerd' ? { miniflare:'5.20260907.0-alpha' } : {};
|
|
88
|
+
const dependencies = { ws:'8.21.0', ...(engine === 'workerd' ? { miniflare:'5.20260907.0-alpha' } : {}) };
|
|
93
89
|
await writeFile(join(output,'runtime/package.json'),JSON.stringify({private:true,type:'module',dependencies}));
|
|
94
90
|
await writeFile(join(output,'Dockerfile'),`FROM node:26.8.1-bookworm-slim\nRUN apt-get update && apt-get install -y --no-install-recommends util-linux ca-certificates && apt-get clean\nRUN mkdir -p /private /archive\nWORKDIR /runtime\nCOPY runtime/package.json ./package.json\nRUN npm install --omit=dev --no-audit --no-fund\nCOPY runtime/ /runtime/\nCOPY app/ /app/\nENV NODE_ENV=production PORT=8080 WRANGLER_SEND_METRICS=false\nEXPOSE 8080\nVOLUME /data\nENTRYPOINT ["sh", "/runtime/modules/container/entrypoint.sh"]\n`);
|
|
95
91
|
return { output,manifest };
|
|
@@ -3,22 +3,26 @@ import { readFile, mkdir } from 'node:fs/promises';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { recordVolumeOwner } from './lock.mjs';
|
|
5
5
|
import { incoming, outgoing } from './ingress.mjs';
|
|
6
|
+
import { attachWebSockets } from './websockets.mjs';
|
|
6
7
|
import { parseCron, cronMatches } from '../../cli/scheduled.mjs';
|
|
7
8
|
import { superviseRunner } from './runner.mjs';
|
|
8
9
|
export async function startHost({ root = '/app', data = '/data', settings = process.env, port = Number(process.env.PORT ?? 8080), edge, engineVersion = process.version, automaticTicks=true, runnerEnabled=true } = {}) {
|
|
9
10
|
await mkdir(data, { recursive:true });
|
|
10
11
|
const manifest = JSON.parse(await readFile(join(root, 'container.json'), 'utf8'));
|
|
11
12
|
const release = await recordVolumeOwner(data);
|
|
12
|
-
let engine, server, timer, idleTimer, runner, closing, lastMinute = -1, lastRequest=Date.now();
|
|
13
|
+
let engine, server, timer, idleTimer, runner, closing, closeWebSockets, lastMinute = -1, lastRequest=Date.now();
|
|
13
14
|
try {
|
|
15
|
+
const origins = settings.RER_INGRESS_ORIGINS === undefined ? undefined : JSON.parse(settings.RER_INGRESS_ORIGINS);
|
|
16
|
+
if (origins !== undefined && (!Array.isArray(origins) || origins.some(value => { try { const url = new URL(value); return typeof value !== 'string' || url.protocol !== 'https:' || url.origin !== value; } catch { return true; } }))) throw new Error('Invalid ingress origins');
|
|
14
17
|
const create = manifest.engine === 'node' ? (await import('./node-engine.mjs')).nodeEngine : (await import('./worker-engine.mjs')).workerEngine;
|
|
15
18
|
engine = await create({ root,data,manifest,settings,edge });
|
|
16
19
|
const schedules = (manifest.config.triggers?.crons ?? []).map(cron => [cron,parseCron(cron)]);
|
|
17
20
|
const tick = async time => { for (const [cron, expression] of schedules) if (cronMatches(expression, new Date(time))) await engine.scheduled({ cron,scheduledTime:time }); await engine.drain(); };
|
|
21
|
+
const requestFrom = req => incoming(req, { trustedProxy:settings.TRUSTED_PROXY, origin:settings.RER_INGRESS_ORIGIN, origins, maxRequestBytes:manifest.maxRequestBytes });
|
|
18
22
|
server = createServer(async (req, res) => {
|
|
19
23
|
try {
|
|
20
24
|
lastRequest=Date.now();
|
|
21
|
-
const request = await
|
|
25
|
+
const request = await requestFrom(req);
|
|
22
26
|
let response = await engine.fetch(request);
|
|
23
27
|
if (new URL(request.url).pathname === '/health' && response.ok) {
|
|
24
28
|
const body = await response.json(); const deadJobs = engine.dead();
|
|
@@ -27,14 +31,15 @@ export async function startHost({ root = '/app', data = '/data', settings = proc
|
|
|
27
31
|
outgoing(response, res);
|
|
28
32
|
} catch (cause) { res.statusCode = cause.status ?? 500; res.end('Container request failed'); console.error('Container request failed:', cause.name); }
|
|
29
33
|
});
|
|
34
|
+
closeWebSockets = attachWebSockets(server, { engine, incoming:requestFrom, activity:() => { lastRequest=Date.now(); } });
|
|
30
35
|
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port,'0.0.0.0',resolve); });
|
|
31
36
|
let ticking=false;
|
|
32
37
|
if(automaticTicks){timer = setInterval(async () => { if(ticking)return;ticking=true;const minute = Math.floor(Date.now()/60000); try { if (minute !== lastMinute) { lastMinute = minute; await tick(minute * 60000); } else await engine.drain(); } catch { console.error('Container scheduled event failed'); }finally{ticking=false;} },1000); timer.unref();}
|
|
33
|
-
const close = () => closing ??= (async () => { clearInterval(timer); clearInterval(idleTimer); await runner?.close(); await new Promise(resolve => server.close(resolve)); await engine.close(); await release(); })();
|
|
38
|
+
const close = () => closing ??= (async () => { clearInterval(timer); clearInterval(idleTimer); await runner?.close(); closeWebSockets(); await new Promise(resolve => server.close(resolve)); await engine.close(); await release(); })();
|
|
34
39
|
const idle=Number(settings.RER_CONTAINER_IDLE_SECONDS);if(Number.isFinite(idle)&&idle>0){idleTimer=setInterval(()=>{if(Date.now()-lastRequest>=idle*1000)void close();},Math.min(1000,idle*1000));idleTimer.unref();}
|
|
35
40
|
if(runnerEnabled)runner=superviseRunner({root,manifest,settings,failed(){console.error('Required container runner stopped');void close().finally(()=>{process.exitCode=1;});}});
|
|
36
41
|
return { engine,manifest,server,tick,close };
|
|
37
|
-
} catch (cause) { clearInterval(timer); clearInterval(idleTimer); await runner?.close(); server?.close(); await engine?.close(); await release(); throw cause; }
|
|
42
|
+
} catch (cause) { clearInterval(timer); clearInterval(idleTimer); await runner?.close(); closeWebSockets?.(); server?.close(); await engine?.close(); await release(); throw cause; }
|
|
38
43
|
}
|
|
39
44
|
if (process.argv[1] === import.meta.filename) {
|
|
40
45
|
let host;
|
|
@@ -2,15 +2,26 @@ import { Readable } from 'node:stream';
|
|
|
2
2
|
import { lookup } from 'node:dns/promises';
|
|
3
3
|
import { isIP } from 'node:net';
|
|
4
4
|
// `origin` (RER_INGRESS_ORIGIN) fixes the public origin for a container whose only
|
|
5
|
-
// peer is its own front, such as a hosted demo's Durable Object.
|
|
6
|
-
|
|
5
|
+
// peer is its own front, such as a hosted demo's Durable Object. That front can
|
|
6
|
+
// select another explicitly allowed HTTPS origin with x-rer-ingress-origin.
|
|
7
|
+
export async function incoming(req, { trustedProxy, origin, origins, maxRequestBytes = 25 * 1024 * 1024 } = {}) {
|
|
7
8
|
const headers = new Headers(); for (const [name, value] of Object.entries(req.headers)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(',') : value);
|
|
8
9
|
const peer = req.socket.remoteAddress?.replace('::ffff:', '') ?? '';
|
|
9
10
|
const trusted = trustedProxy && (isIP(trustedProxy) ? peer===trustedProxy : (await lookup(trustedProxy,{all:true})).some(item=>item.address.replace('::ffff:','')===peer));
|
|
10
11
|
let host = req.headers.host, proto = 'http', address = peer;
|
|
11
12
|
if (trusted) { host = req.headers['x-forwarded-host'] ?? host; proto = req.headers['x-forwarded-proto'] ?? proto; address = req.headers['x-forwarded-for']?.split(',').at(-1)?.trim() ?? peer; }
|
|
12
|
-
if (origin) {
|
|
13
|
-
|
|
13
|
+
if (origin) {
|
|
14
|
+
const requested = req.headers['x-rer-ingress-origin'];
|
|
15
|
+
let fixed = new URL(origin);
|
|
16
|
+
if (requested !== undefined) {
|
|
17
|
+
let selected;
|
|
18
|
+
try { selected = new URL(requested); } catch {}
|
|
19
|
+
if (!Array.isArray(origins) || !origins.includes(requested) || selected?.protocol !== 'https:' || selected.origin !== requested) throw Object.assign(new Error('Invalid ingress origin'), { status: 400 });
|
|
20
|
+
fixed = selected;
|
|
21
|
+
}
|
|
22
|
+
host = fixed.host; proto = fixed.protocol.slice(0, -1);
|
|
23
|
+
}
|
|
24
|
+
for (const name of ['cf-connecting-ip','x-forwarded-host','x-forwarded-proto','x-forwarded-for','forwarded','x-rer-original-url','x-rer-ingress-origin']) headers.delete(name);
|
|
14
25
|
if (!['http', 'https'].includes(proto) || typeof host !== 'string' || !/^(?:[a-zA-Z0-9.-]+|\[[0-9a-fA-F:]+\])(?::[0-9]+)?$/.test(host)) throw new Error('Invalid ingress origin');
|
|
15
26
|
headers.set('cf-connecting-ip', address); headers.set('host', host);
|
|
16
27
|
const url = `${proto}://${host}${req.url}`;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {readFile} from 'node:fs/promises';
|
|
2
|
+
import {dirname, resolve} from 'node:path';
|
|
3
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
4
|
+
import {collectMigrations, sourcePath} from '../delivery-producer/migrations.mjs';
|
|
5
|
+
|
|
6
|
+
// These are the producer's source policy and exported policy locations. Never
|
|
7
|
+
// infer extra directories from a seed name or scan undeclared SQL trees.
|
|
8
|
+
const packagingFiles = ['packaging.json','rer-packaging.json','scripts/delivery/base/packaging.json'];
|
|
9
|
+
async function migrationPolicy(root) {
|
|
10
|
+
const policies = [];
|
|
11
|
+
for (const candidate of packagingFiles) {
|
|
12
|
+
const file = await sourcePath(root,candidate,{optional:true});
|
|
13
|
+
if (!file) continue;
|
|
14
|
+
const packaging = JSON.parse(await readFile(file,'utf8'));
|
|
15
|
+
const inputs = packaging.artifact?.specInputs;
|
|
16
|
+
if (!inputs || typeof inputs !== 'object' || Array.isArray(inputs)) throw new Error('Invalid container migration packaging policy');
|
|
17
|
+
policies.push({migrationPrefix:inputs.migrationPrefix === undefined ? '' : inputs.migrationPrefix,extraMigrationDirectories:inputs.extraMigrationDirectories === undefined ? [] : inputs.extraMigrationDirectories,...(inputs.wranglerFile === undefined ? {} : {wranglerFile:inputs.wranglerFile})});
|
|
18
|
+
}
|
|
19
|
+
if (policies.some(policy => !isDeepStrictEqual(policy,policies[0]))) throw new Error('Conflicting container migration packaging policies');
|
|
20
|
+
return policies[0] ?? {migrationPrefix:'',extraMigrationDirectories:[]};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function containerMigrationInventory(root,{config,configFile}) {
|
|
24
|
+
const policy = await migrationPolicy(root);
|
|
25
|
+
const file = await sourcePath(root,policy.wranglerFile ?? configFile);
|
|
26
|
+
const migrationConfig = policy.wranglerFile === undefined ? config : JSON.parse(await readFile(file,'utf8'));
|
|
27
|
+
const resources = (config.d1_databases ?? []).map(db => ({kind:'d1',binding:db.binding}));
|
|
28
|
+
const directories = (migrationConfig.d1_databases ?? []).map(db => {
|
|
29
|
+
if (typeof db.migrations_dir !== 'string' || !db.migrations_dir.trim()) throw new Error('Invalid D1 migrations_dir');
|
|
30
|
+
return {binding:db.binding,path:resolve(dirname(file),db.migrations_dir),prefix:policy.migrationPrefix};
|
|
31
|
+
});
|
|
32
|
+
return collectMigrations(root,[...directories,...policy.extraMigrationDirectories],resources);
|
|
33
|
+
}
|
|
@@ -1,10 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { assertMigrationSqlSafe } from '../deploy-kit/sql-safety.mjs';
|
|
3
|
+
import { sqlTokens } from '../deploy-kit/sql-tokens.mjs';
|
|
2
4
|
import { recorded } from '../deploy-kit/migration-ledger.mjs';
|
|
5
|
+
function validateMigrations(migrations) {
|
|
6
|
+
const names = new Set();
|
|
7
|
+
for (const migration of migrations) {
|
|
8
|
+
if (!/^[\w.-]+\.sql$/.test(migration.name) || names.has(migration.name)) throw new Error('migration-order-or-name');
|
|
9
|
+
names.add(migration.name);
|
|
10
|
+
if (typeof migration.sql !== 'string' || !migration.sql.trim() || Buffer.byteLength(migration.sql) > 10*1024*1024 || createHash('sha256').update(migration.sql).digest('hex') !== migration.sha256 || !sqlTokens(migration.sql).length) throw new Error('invalid-migration-bytes');
|
|
11
|
+
assertMigrationSqlSafe(migration.sql);
|
|
12
|
+
if (migration.rewrites !== undefined && (!Array.isArray(migration.rewrites) || !migration.rewrites.every(rewrite => /^[a-f0-9]{64}$/.test(rewrite?.from ?? '') && rewrite.from !== migration.sha256 && typeof rewrite.reason === 'string' && rewrite.reason.trim()))) throw new Error('invalid-migration-rewrite');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
3
15
|
export async function migrate(db, migrations, { ledger = '_rer_deploy_migrations' } = {}) {
|
|
4
16
|
if (!['_rer_deploy_migrations', '_rer_portability_migrations'].includes(ledger)) throw new Error('Invalid migration ledger');
|
|
5
17
|
validateMigrations(migrations);
|
|
6
18
|
await db.prepare(`CREATE TABLE IF NOT EXISTS ${ledger}(name TEXT PRIMARY KEY,sha256 TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('applying','applied')))`).run();
|
|
7
|
-
|
|
19
|
+
// The producer preserves declared directory order, including prefixes. Rowid
|
|
20
|
+
// preserves application order without changing the existing ledger schema.
|
|
21
|
+
const history = (await db.prepare(`SELECT name,sha256,state FROM ${ledger} ORDER BY rowid`).all()).results;
|
|
8
22
|
if (history.some((row, i) => !recorded(row, migrations[i]) || row.state !== 'applied')) throw new Error('changed-or-uncertain-migration-history');
|
|
9
23
|
const legacy = await db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='d1_migrations'").first();
|
|
10
24
|
if (ledger === '_rer_deploy_migrations' && legacy && (await db.prepare('SELECT name FROM d1_migrations ORDER BY id').all()).results.some(row => !history.some(prior => prior.name === row.name))) throw new Error('legacy-migration-history-needs-reviewed-hash-adoption');
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { ServerResponse } from 'node:http';
|
|
2
|
+
import { WebSocketServer } from 'ws';
|
|
3
|
+
import { outgoing } from './ingress.mjs';
|
|
4
|
+
|
|
5
|
+
// Keep the Worker response's cookies and selected protocol. ws owns the wire
|
|
6
|
+
// handshake (including key validation) and never negotiates compression here.
|
|
7
|
+
const handshakeHeaders = new Set(['connection', 'upgrade', 'sec-websocket-accept', 'sec-websocket-extensions', 'content-length', 'transfer-encoding']);
|
|
8
|
+
export function attachWebSockets(server, { engine, incoming, activity }) {
|
|
9
|
+
const responses = new WeakMap(), sockets = new Set();
|
|
10
|
+
const bridge = new WebSocketServer({ noServer:true, handleProtocols:() => false });
|
|
11
|
+
bridge.on('headers', (headers, req) => {
|
|
12
|
+
const response = responses.get(req); responses.delete(req);
|
|
13
|
+
for (const [name, value] of response.headers) if (!handshakeHeaders.has(name) && name !== 'set-cookie') headers.push(`${name}: ${value}`);
|
|
14
|
+
for (const cookie of response.headers.getSetCookie()) headers.push(`set-cookie: ${cookie}`);
|
|
15
|
+
});
|
|
16
|
+
const refuse = (req, socket, response) => {
|
|
17
|
+
const res = new ServerResponse(req); res.assignSocket(socket);
|
|
18
|
+
res.shouldKeepAlive = false;
|
|
19
|
+
const headers = new Headers(response.headers); headers.set('connection', 'close');
|
|
20
|
+
outgoing(new Response(response.body, { status:response.status, headers }), res);
|
|
21
|
+
};
|
|
22
|
+
server.on('upgrade', async (req, socket, head) => {
|
|
23
|
+
sockets.add(socket); socket.once('close', () => sockets.delete(socket));
|
|
24
|
+
// A peer may disappear while ingress or the Worker is still dispatching.
|
|
25
|
+
socket.on('error', () => socket.destroy());
|
|
26
|
+
let pair, coupled = false;
|
|
27
|
+
const abandon = () => { if (pair && !coupled) { try { pair.accept(); pair.close(1001, 'Client disconnected'); } catch {} } };
|
|
28
|
+
socket.once('close', abandon);
|
|
29
|
+
try {
|
|
30
|
+
activity();
|
|
31
|
+
if (req.headers.upgrade?.toLowerCase() !== 'websocket') return refuse(req, socket, new Response('Unsupported upgrade', { status:400 }));
|
|
32
|
+
const request = await incoming(req); request.headers.set('upgrade', 'websocket');
|
|
33
|
+
const response = await engine.fetch(request);
|
|
34
|
+
pair = response.webSocket;
|
|
35
|
+
if (socket.destroyed) { abandon(); return; }
|
|
36
|
+
if (response.status !== 101) return refuse(req, socket, response);
|
|
37
|
+
if (!pair || !engine.coupleWebSocket) return refuse(req, socket, new Response('Invalid WebSocket response', { status:502 }));
|
|
38
|
+
responses.set(req, response);
|
|
39
|
+
bridge.handleUpgrade(req, socket, head, ws => {
|
|
40
|
+
coupled = true;
|
|
41
|
+
ws.on('message', activity); ws.on('ping', activity); ws.on('pong', activity);
|
|
42
|
+
pair.addEventListener('message', activity);
|
|
43
|
+
// Miniflare's coupling preserves text/binary messages, queued app sends,
|
|
44
|
+
// close codes and abrupt disconnects on its returned WebSocketPair.
|
|
45
|
+
engine.coupleWebSocket(ws, pair).catch(() => { ws.terminate(); try { pair.close(1011, 'Bridge failed'); } catch {} });
|
|
46
|
+
});
|
|
47
|
+
} catch (cause) {
|
|
48
|
+
abandon();
|
|
49
|
+
if (!socket.destroyed) refuse(req, socket, new Response('Container upgrade failed', { status:cause.status ?? 500 }));
|
|
50
|
+
console.error('Container upgrade failed:', cause.name);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
return () => { for (const socket of sockets) socket.destroy(); bridge.close(); };
|
|
54
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
|
|
1
|
+
import { Miniflare, convertV4MiniflareOptions, coupleWebSocket } from 'miniflare';
|
|
2
2
|
import { readdir } from 'node:fs/promises';
|
|
3
3
|
import { join, relative } from 'node:path';
|
|
4
4
|
import { rootCertificates } from 'node:tls';
|
|
@@ -27,7 +27,7 @@ export async function workerEngine({ root, data, manifest, settings, edge }) {
|
|
|
27
27
|
for (const [binding, plan] of Object.entries(manifest.migrations)) { const db = await mf.getD1Database(binding, 'app'); databases[binding] = db; await migrate(db, plan); await ensurePortabilitySchema(db, manifest.portabilityMigrations); }
|
|
28
28
|
for (const bucket of config.r2_buckets ?? []) objects[bucket.binding] = await mf.getR2Bucket(bucket.binding, 'app');
|
|
29
29
|
const worker = await mf.getWorker('app');
|
|
30
|
-
return { mf, databases, objects, app:worker,
|
|
30
|
+
return { mf, databases, objects, app:worker, coupleWebSocket,
|
|
31
31
|
fetch(request) { const headers = new Headers(request.headers); headers.set('x-rer-original-url', request.url); return mf.dispatchFetch(request.url, { method:request.method,headers,body:request.body,duplex:'half',redirect:'manual' }); },
|
|
32
32
|
scheduled:event => worker.scheduled(event), async drain() {}, dead:() => 0, close:() => mf.dispose(),
|
|
33
33
|
};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import {lstat, readFile, readdir, realpath} from 'node:fs/promises';
|
|
2
|
+
import {resolve, relative, isAbsolute, sep, join} from 'node:path';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
import {array, keys, string, bindingPattern} from './bindings.mjs';
|
|
5
|
+
export const codeUnitOrder = (a,b) => a < b ? -1 : a > b ? 1 : 0;
|
|
6
|
+
const privatePart = /^(?:\.git|\.env(?:\..*)?|\.dev\.vars(?:\..*)?|\.npmrc|\.yarnrc(?:\.yml)?|\.netrc|\.pypirc|release-provenance\.json)$/i;
|
|
7
|
+
/** Check each actual path component, including in-root symlinks. Never read through one. */
|
|
8
|
+
export async function sourcePath(root, input, {base = root, kind = 'file', optional = false} = {}) {
|
|
9
|
+
if (typeof input !== 'string' || !input || /[\\\x00-\x1f\x7f]/.test(input)) throw Error('Invalid candidate source path');
|
|
10
|
+
const rootPath = await realpath(root);
|
|
11
|
+
let destination = resolve(base, input);
|
|
12
|
+
// macOS /var and /tmp aliases (and an explicitly supplied root alias) refer
|
|
13
|
+
// to the same candidate root. Normalize only that known root, not child links.
|
|
14
|
+
const lexicalWithin = relative(resolve(root), destination);
|
|
15
|
+
if (lexicalWithin && lexicalWithin !== '..' && !lexicalWithin.startsWith(`..${sep}`) && !isAbsolute(lexicalWithin)) destination = resolve(rootPath, lexicalWithin);
|
|
16
|
+
const within = relative(rootPath, destination);
|
|
17
|
+
if (!within || within === '..' || within.startsWith(`..${sep}`) || isAbsolute(within)) throw Error('Input escapes candidate source or names its root');
|
|
18
|
+
const parts = within.split(sep);
|
|
19
|
+
if (parts.some(part => privatePart.test(part))) throw Error('Private candidate source path is forbidden');
|
|
20
|
+
let path = rootPath;
|
|
21
|
+
for (let index = 0; index < parts.length; index++) {
|
|
22
|
+
path = join(path, parts[index]);
|
|
23
|
+
let stat;
|
|
24
|
+
try { stat = await lstat(path); }
|
|
25
|
+
catch (error) { if (error.code === 'ENOENT' && optional) return null; throw error; }
|
|
26
|
+
if (stat.isSymbolicLink()) throw Error('Candidate source symlink is forbidden');
|
|
27
|
+
if (index < parts.length - 1 ? !stat.isDirectory() : kind === 'directory' ? !stat.isDirectory() : !stat.isFile()) throw Error(`Candidate source must be a regular ${kind}`);
|
|
28
|
+
}
|
|
29
|
+
return path;
|
|
30
|
+
}
|
|
31
|
+
export function decodeUtf8(bytes, label) {
|
|
32
|
+
// Preserve a UTF-8 BOM: it is part of both SQL text and its byte digest.
|
|
33
|
+
try { return new TextDecoder('utf-8', {fatal:true, ignoreBOM:true}).decode(bytes); }
|
|
34
|
+
catch { throw Error(`Invalid UTF-8 ${label}`); }
|
|
35
|
+
}
|
|
36
|
+
export async function collectMigrations(root, directories, resources) {
|
|
37
|
+
const result = [], identities = new Set();
|
|
38
|
+
for (const directory of array(directories, 'migration directories')) {
|
|
39
|
+
keys(directory, ['binding','path','prefix','optional'], 'migration directory');
|
|
40
|
+
string(directory.binding, 'migration binding', bindingPattern);
|
|
41
|
+
if (!resources.some(row => row.kind === 'd1' && row.binding === directory.binding)) throw Error(`Migration directory requires D1 binding: ${directory.binding}`);
|
|
42
|
+
if (directory.optional !== undefined && typeof directory.optional !== 'boolean') throw Error('Invalid migration optional flag');
|
|
43
|
+
const prefix = directory.prefix === undefined ? '' : directory.prefix;
|
|
44
|
+
if (typeof prefix !== 'string' || !/^[\w.-]*$/.test(prefix)) throw Error('Invalid migration prefix');
|
|
45
|
+
const path = await sourcePath(root, directory.path, {kind:'directory',optional:directory.optional === true});
|
|
46
|
+
if (path === null) continue;
|
|
47
|
+
for (const file of (await readdir(path, {withFileTypes:true})).sort((a,b) => codeUnitOrder(a.name,b.name))) {
|
|
48
|
+
if (!file.name.endsWith('.sql')) continue;
|
|
49
|
+
if (!file.isFile() || !/^[\w.-]+\.sql$/.test(file.name)) throw Error('Migration must be a regular SQL file');
|
|
50
|
+
const name = prefix + file.name, identity = `${directory.binding}/${name}`;
|
|
51
|
+
if (identities.has(identity)) throw Error(`Duplicate migration identity: ${identity}`);
|
|
52
|
+
identities.add(identity);
|
|
53
|
+
const filePath = await sourcePath(root, join(path, file.name));
|
|
54
|
+
const bytes = await readFile(filePath);
|
|
55
|
+
if (bytes.length > 10 * 1024 * 1024) throw Error('Migration exceeds supported limit');
|
|
56
|
+
const sql = decodeUtf8(bytes, 'migration');
|
|
57
|
+
result.push({binding:directory.binding,name,sha256:createHash('sha256').update(bytes).digest('hex'),sql});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return result;
|
|
61
|
+
}
|
package/modules/demo/README.md
CHANGED
|
@@ -18,6 +18,10 @@ Production build/deploy refuses that setting; ordinary builds keep real effects.
|
|
|
18
18
|
provider response should supply its own exact success shape this way.
|
|
19
19
|
- Mail in local dev and demo is silently suppressed. There is no outbox or
|
|
20
20
|
blocked-send UI. Logs contain only the mocked request's method and host.
|
|
21
|
+
- The configured owner's authenticated session supplies step-up proof inside
|
|
22
|
+
its own demo, including owner invitations and role changes. The demo guard
|
|
23
|
+
must be active; ordinary hosted instances still require real proof. Each
|
|
24
|
+
visitor's separate session secret and store reject other visitors' cookies.
|
|
21
25
|
- `seed(env, { ownerEmail, now })` runs once after the owner exists and must
|
|
22
26
|
be idempotent. Its only table is the demo's throwaway `rer_demo` marker.
|
|
23
27
|
- Base adds ` Demo` to the document title, including client-side navigation.
|
package/modules/demo/effects.mjs
CHANGED
|
@@ -4,6 +4,10 @@ import { effectSuccess } from './responses.mjs';
|
|
|
4
4
|
const readRequests = new WeakSet();
|
|
5
5
|
let installed = false;
|
|
6
6
|
|
|
7
|
+
// Shared runtime consumers may honour suppressed results only while the demo
|
|
8
|
+
// guard is installed. This keeps Node-side authoring imports free of Workers APIs.
|
|
9
|
+
export function demoEffectsEnabled() { return installed; }
|
|
10
|
+
|
|
7
11
|
// Read intent stays in memory, never in a header the remote server could use.
|
|
8
12
|
export function fetchDemoRead(input, init) {
|
|
9
13
|
const request = new Request(input, init);
|
package/modules/demo/label.mjs
CHANGED
|
@@ -1,23 +1,26 @@
|
|
|
1
1
|
import { allow, sha256 } from '../operator-auth/csp.mjs';
|
|
2
2
|
|
|
3
3
|
// CSS leaves React's text alone during hydration. The title observer handles
|
|
4
|
-
// client-side route changes, whose head manager writes a fresh title.
|
|
4
|
+
// client-side route changes, whose head manager writes a fresh title. The script
|
|
5
|
+
// is one constant text (so one constant CSP hash); the suffix reaches it as data
|
|
6
|
+
// on the label's style element, never as code.
|
|
7
|
+
const SCRIPT = "(()=>{const suffix=document.querySelector('style[data-rer-label]').dataset.rerLabel,update=()=>{const title=document.title.replace(/ (?:Demo|Dev)$/,'')+' '+suffix;if(document.title!==title)document.title=title};update();new MutationObserver(update).observe(document.head,{childList:true,subtree:true,characterData:true})})()";
|
|
8
|
+
|
|
5
9
|
export async function decorateLabel(response, mode) {
|
|
6
10
|
if (!response.body || !response.headers.get('content-type')?.toLowerCase().startsWith('text/html')) return response;
|
|
7
11
|
const suffix = mode === 'Demo' ? 'Demo' : 'Dev';
|
|
8
12
|
const style = `[data-rer-name]::after{content:" ${suffix}"}`;
|
|
9
|
-
const script = `(()=>{const suffix=${JSON.stringify(suffix)},update=()=>{const title=document.title.replace(/ (?:Demo|Dev)$/,'')+' '+suffix;if(document.title!==title)document.title=title};update();new MutationObserver(update).observe(document.head,{childList:true,subtree:true,characterData:true})})()`;
|
|
10
13
|
const html = await response.text();
|
|
11
14
|
if (html.includes('data-rer-label=')) return new Response(html, response);
|
|
12
15
|
const headers = new Headers(response.headers);
|
|
13
16
|
let policy = headers.get('content-security-policy');
|
|
14
17
|
if (policy) {
|
|
15
18
|
policy = allow(policy, 'style-src', await sha256(style));
|
|
16
|
-
headers.set('content-security-policy', allow(policy, 'script-src', await sha256(
|
|
19
|
+
headers.set('content-security-policy', allow(policy, 'script-src', await sha256(SCRIPT)));
|
|
17
20
|
}
|
|
18
21
|
headers.delete('content-length');
|
|
19
22
|
headers.delete('etag');
|
|
20
|
-
const addition = `<style data-rer-label="${suffix}">${style}</style><script>${
|
|
23
|
+
const addition = `<style data-rer-label="${suffix}">${style}</style><script>${SCRIPT}</script>`;
|
|
21
24
|
const titled = html.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title>)/i, (_, open, title, close) => `${open}${title.replace(/ (?:Demo|Dev)$/, '')} ${suffix}${close}`);
|
|
22
25
|
const body = /<\/head\s*>/i.test(titled) ? titled.replace(/<\/head\s*>/i, `${addition}</head>`) : addition + titled;
|
|
23
26
|
return new Response(body, { status: response.status, statusText: response.statusText, headers });
|
|
@@ -7,7 +7,7 @@ export async function effectSuccess(request) {
|
|
|
7
7
|
if (host === 'api.resend.com') return json({ id });
|
|
8
8
|
if (host === 'api.twilio.com') return json({ sid: `SM${crypto.randomUUID().replaceAll('-', '')}`, status: 'queued', error_code: null, error_message: null }, 201);
|
|
9
9
|
if (host === 'api.postmarkapp.com') return json({ ErrorCode: 0, Message: 'OK', MessageID: id, SubmittedAt: new Date().toISOString() });
|
|
10
|
-
if (host.endsWith('mailgun.net')) return json({ id: `<${id}@demo.invalid>`, message: 'Queued. Thank you.' });
|
|
10
|
+
if (host === 'mailgun.net' || host.endsWith('.mailgun.net')) return json({ id: `<${id}@demo.invalid>`, message: 'Queued. Thank you.' });
|
|
11
11
|
if (host === 'slack.com') return json({ ok: true, channel: 'demo', ts: `${Math.floor(Date.now() / 1000)}.000001`, message: { type: 'message', text: 'Message sent' } });
|
|
12
12
|
if (host === 'hooks.slack.com' || host.endsWith('.webhook.office.com') || host.endsWith('.logic.azure.com')) return new Response(host === 'hooks.slack.com' ? 'ok' : '1');
|
|
13
13
|
if (host === 'api.stripe.com') {
|
|
@@ -5,7 +5,14 @@ that adopted demo mode (`withDemo`, export/DEMO.md). `plan.mjs` turns `deploy-de
|
|
|
5
5
|
(optionally `instanceType`, one of Cloudflare's predefined Container instance
|
|
6
6
|
types, `basic` unless set) into the Worker's Wrangler configuration; the CLI (`cli/demo-host.mjs`) writes
|
|
7
7
|
it with these files and the seed's container image folder (workerd engine) to
|
|
8
|
-
`.rer/demo-host/` and runs `wrangler deploy` there.
|
|
8
|
+
`.rer/demo-host/` and runs `wrangler deploy` there. Declared
|
|
9
|
+
`container.hostVariables` resolve from demo settings to the primary hostname or
|
|
10
|
+
its descendants (for example `page.demo.<domain>`); each gets a custom-domain
|
|
11
|
+
route to the same front. The visitor cookie covers these hosts, while the
|
|
12
|
+
primary host's `__Host` owner session stays host-only. The front supplies a
|
|
13
|
+
validated public origin to the container ingress, so secondary page routing
|
|
14
|
+
sees the requested host. Anonymous secondary requests return to the primary
|
|
15
|
+
start page.
|
|
9
16
|
|
|
10
17
|
- `worker.mjs`: `GET /` is the start page; `POST /__demo/start` checks the
|
|
11
18
|
exact Origin, the `STARTS` rate limit (3 per IP per 60 s), Turnstile's
|
|
@@ -29,17 +36,17 @@ it with these files and the seed's container image folder (workerd engine) to
|
|
|
29
36
|
guard simulates effects on people and third-party accounts, while the
|
|
30
37
|
container egress independently refuses direct mail/SMS provider transports
|
|
31
38
|
and SMTP ports. Public-address filtering and TLS remain enforced.
|
|
32
|
-
The platform
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
and answers the ended page (410), never a 5xx.
|
|
39
|
+
The platform inactivity timeout is set after start and reapplied when an
|
|
40
|
+
object recovers an already-running container. Persisted alarms enforce the
|
|
41
|
+
exact idle/absolute deadline without keeping a timer in flight. Requests
|
|
42
|
+
check both deadlines before refreshing activity. A container found stopped
|
|
43
|
+
ends the demo and answers the ended page (410).
|
|
38
44
|
- `capacity.mjs`: `DemoCapacity` counts unexpired reservation rows inside a
|
|
39
45
|
storage transaction, excluding diagnostics and expired rows. A lost start
|
|
40
46
|
handoff expires after one minute; a successful claim extends the reservation
|
|
41
47
|
to the demo's end. Refusals log the held ids as SHA-256 fingerprints (also
|
|
42
|
-
logged with each start's correlation), never visitor bearer cookies.
|
|
48
|
+
logged with each start's correlation), never visitor bearer cookies. The
|
|
49
|
+
refusal's response correlation also identifies that held-place snapshot.
|
|
43
50
|
- `image.mjs`, `prepare.mjs`, `template.mjs`, `entrypoint.sh`: the demo image
|
|
44
51
|
build migrates fresh workerd persistence with the packaged engine and closes
|
|
45
52
|
it into `/template`, with no network and no app requests. The entrypoint
|
|
@@ -54,7 +61,8 @@ it with these files and the seed's container image folder (workerd engine) to
|
|
|
54
61
|
with the refusal's status)
|
|
55
62
|
and shows each step: the check, the private copy starting, the sign-in. A
|
|
56
63
|
refusal, a network failure or a start past 25 seconds is shown with Try
|
|
57
|
-
again, which
|
|
64
|
+
again, which first destroys the abandoned copy and releases its place through
|
|
65
|
+
`POST /__demo/cancel`, then runs a new check; progress is announced through a
|
|
58
66
|
`role="status"` region and failures through `role="alert"`. Without
|
|
59
67
|
JavaScript the form posts as before and gets the 303 or the page.
|
|
60
68
|
- `remove.mjs`: `rer deploy --demo --remove --yes`. The deploy passes the
|
|
@@ -77,13 +85,16 @@ is in DEMO.md.
|
|
|
77
85
|
Startup has a 45-second budget, with a separate five-second HTTP probe limit.
|
|
78
86
|
The Durable Object owns that work and cleanup while the page polls; a browser
|
|
79
87
|
that leaves cannot abandon it. Retrying a pending copy resumes the same
|
|
80
|
-
reservation. Failed starts retain the bounded operator diagnostic and destroy
|
|
81
|
-
the container
|
|
82
|
-
|
|
88
|
+
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
|
|
89
|
+
the container. Destruction retries for failed starts never extend or reclaim the
|
|
90
|
+
released place. Each release logs the id's SHA-256 fingerprint with the start's
|
|
91
|
+
correlation. Every attempt logs its timestamp, elapsed time, duration and
|
|
83
92
|
HTTP status or fixed error category, including successful probes. Exit records
|
|
84
93
|
include the numeric platform exit code when supplied. A separate random
|
|
85
94
|
`x-rer-demo-correlation` response header joins these events without disclosing
|
|
86
|
-
the visitor's bearer cookie.
|
|
95
|
+
the visitor's bearer cookie. Early refusals, including capacity, rate-limit,
|
|
96
|
+
Origin and human-check refusals, also carry a correlation and log their status.
|
|
97
|
+
Worker observability also enables the platform's
|
|
87
98
|
private Container stdout/stderr logs; historical stdout is not exposed by the
|
|
88
99
|
Container lifecycle API. Read those logs with an account principal granted
|
|
89
100
|
Workers Observability Write, and filter by the application and boot interval.
|
|
@@ -99,16 +110,18 @@ no access. The token never belongs in a URL. Ordinary visitors keep the generic
|
|
|
99
110
|
failure page. No raw error text, health body, cookies or environment values are
|
|
100
111
|
included in this diagnostic.
|
|
101
112
|
|
|
102
|
-
Failed destruction retains its alarm
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
failure
|
|
113
|
+
Failed destruction retains its alarm for cleanup. A live visitor's demo also
|
|
114
|
+
retains its capacity reservation until destruction is confirmed (or the
|
|
115
|
+
container is already stopped); a terminal start failure releases it immediately.
|
|
116
|
+
A cleanup failure is logged separately and cannot replace the startup failure
|
|
117
|
+
shown to the visitor.
|
|
106
118
|
|
|
107
119
|
Cloudflare may briefly report that it has no prepared container instance even
|
|
108
120
|
when the application is below `max_instances`. `placement.mjs` keeps the same
|
|
109
121
|
reservation and launch options, requests placement again only for that specific
|
|
110
122
|
provider response, and stays within the original startup deadline. Boot, health
|
|
111
|
-
and claim errors are not retried. Placement exhaustion answers
|
|
112
|
-
|
|
123
|
+
and claim errors are not retried. Placement exhaustion answers with the normal
|
|
124
|
+
failed-start retry state and releases the reservation; the capacity notice is
|
|
125
|
+
reserved for actual reservation exhaustion. Cleanup keeps only that terminal
|
|
113
126
|
answer and correlation for one minute, so a status poll after object recovery
|
|
114
127
|
still receives the right answer; its alarm then deletes the remaining metadata.
|
|
@@ -18,7 +18,7 @@ export class DemoCapacity extends DurableObject {
|
|
|
18
18
|
}
|
|
19
19
|
async alarm() { await this.ctx.storage.deleteAll(); }
|
|
20
20
|
|
|
21
|
-
async acquire(id, ends, max) {
|
|
21
|
+
async acquire(id, ends, max, correlation) {
|
|
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');
|
|
@@ -28,7 +28,7 @@ export class DemoCapacity extends DurableObject {
|
|
|
28
28
|
if (held.length >= max) {
|
|
29
29
|
// Fingerprints identify held reservations without logging bearer cookies.
|
|
30
30
|
const heldIds = await Promise.all(held.map(async ([key, until]) => ({ id: await fingerprint(key), ends: until })));
|
|
31
|
-
console.log(JSON.stringify({ event: 'demo_capacity_refused', max, held: heldIds }));
|
|
31
|
+
console.log(JSON.stringify({ event: 'demo_capacity_refused', correlation, max, held: heldIds }));
|
|
32
32
|
return false;
|
|
33
33
|
}
|
|
34
34
|
await storage.put(id, ends);
|
|
@@ -45,7 +45,7 @@ export class DemoCapacity extends DurableObject {
|
|
|
45
45
|
}
|
|
46
46
|
|
|
47
47
|
async release(id) {
|
|
48
|
-
|
|
48
|
+
return this.ctx.storage.delete(id);
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
51
|
|