beam.com 0.1.0-rc.1
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/LICENSE +202 -0
- package/NOTICE +97 -0
- package/README.md +369 -0
- package/js/beam.com.mjs +33 -0
- package/js/download.mjs +78 -0
- package/js/node.mjs +75 -0
- package/package.json +36 -0
- package/runtime/app-com.js +203 -0
- package/runtime/beam.mjs +2 -0
- package/runtime/beam.wasm +0 -0
- package/runtime/browser/beam-wasm.js +2 -0
- package/runtime/browser/net.js +7 -0
- package/runtime/browser/none.js +4 -0
- package/runtime/browser.js +161 -0
- package/runtime/cloudflare/durable.js +361 -0
- package/runtime/cloudflare/index.js +76 -0
- package/runtime/cloudflare/release.js +42 -0
- package/runtime/cloudflare/snapshot.js +3 -0
- package/runtime/cloudflare/worker.js +1891 -0
- package/runtime/deno/app.js +8 -0
- package/runtime/deno/beam-wasm.js +3 -0
- package/runtime/deno/none.js +3 -0
- package/runtime/deno/release-bin.js +46 -0
- package/runtime/deno/snapshot-bin.js +11 -0
- package/runtime/deno/worker.js +1891 -0
- package/runtime/deno.js +346 -0
- package/runtime/deno.json +5 -0
- package/runtime/durable-global.js +40 -0
- package/runtime/durable.js +361 -0
- package/runtime/global.js +26 -0
- package/runtime/licenses/LICENSE +202 -0
- package/runtime/licenses/NOTICE +97 -0
- package/runtime/licenses/bcrypt_elixir.txt +87 -0
- package/runtime/licenses/cosmopolitan.txt +16 -0
- package/runtime/licenses/elixir/Apache-2.0.txt +73 -0
- package/runtime/licenses/elixir/LicenseRef-elixir-trademark-policy.txt +98 -0
- package/runtime/licenses/elixir/LicenseRef-scancode-unicode.txt +58 -0
- package/runtime/licenses/emscripten.txt +102 -0
- package/runtime/licenses/exqlite.txt +21 -0
- package/runtime/licenses/llvm.txt +311 -0
- package/runtime/licenses/musl.txt +193 -0
- package/runtime/licenses/otp/BSD-2-Clause.txt +22 -0
- package/runtime/licenses/otp/BSD-3-Clause.txt +25 -0
- package/runtime/licenses/otp/LicenseRef-IETF-MIB.txt +9 -0
- package/runtime/licenses/otp/LicenseRef-RSA-PKCS3.txt +23 -0
- package/runtime/licenses/otp/LicenseRef-RSA-PKCS5v2-0.txt +17 -0
- package/runtime/licenses/otp/LicenseRef-scancode-ietf-trust.txt +296 -0
- package/runtime/licenses/otp/LicenseRef-scancode-ietf.txt +23 -0
- package/runtime/licenses/otp/LicenseRef-scancode-w3c-docs-19990405.txt +26 -0
- package/runtime/licenses/otp/LicenseRef-scancode-wxwindows-free-doc-3.txt +57 -0
- package/runtime/licenses/otp/MIT.txt +17 -0
- package/runtime/licenses/otp/SGI-B-2.0.txt +25 -0
- package/runtime/licenses/otp/W3C-19980720.txt +55 -0
- package/runtime/licenses/picosat.txt +19 -0
- package/runtime/licenses/wamr.txt +219 -0
- package/runtime/nifs.js +2 -0
- package/runtime/package.json +1 -0
- package/runtime/page/404.html +49 -0
- package/runtime/page/app-com.js +203 -0
- package/runtime/page/beam.mjs +2 -0
- package/runtime/page/browser/beam-wasm.js +2 -0
- package/runtime/page/browser/net.js +7 -0
- package/runtime/page/browser/none.js +4 -0
- package/runtime/page/browser.js +161 -0
- package/runtime/page/index.html +50 -0
- package/runtime/page/licenses/LICENSE +202 -0
- package/runtime/page/licenses/NOTICE +97 -0
- package/runtime/page/licenses/bcrypt_elixir.txt +87 -0
- package/runtime/page/licenses/cosmopolitan.txt +16 -0
- package/runtime/page/licenses/elixir/Apache-2.0.txt +73 -0
- package/runtime/page/licenses/elixir/LicenseRef-elixir-trademark-policy.txt +98 -0
- package/runtime/page/licenses/elixir/LicenseRef-scancode-unicode.txt +58 -0
- package/runtime/page/licenses/emscripten.txt +102 -0
- package/runtime/page/licenses/exqlite.txt +21 -0
- package/runtime/page/licenses/llvm.txt +311 -0
- package/runtime/page/licenses/musl.txt +193 -0
- package/runtime/page/licenses/otp/BSD-2-Clause.txt +22 -0
- package/runtime/page/licenses/otp/BSD-3-Clause.txt +25 -0
- package/runtime/page/licenses/otp/LicenseRef-IETF-MIB.txt +9 -0
- package/runtime/page/licenses/otp/LicenseRef-RSA-PKCS3.txt +23 -0
- package/runtime/page/licenses/otp/LicenseRef-RSA-PKCS5v2-0.txt +17 -0
- package/runtime/page/licenses/otp/LicenseRef-scancode-ietf-trust.txt +296 -0
- package/runtime/page/licenses/otp/LicenseRef-scancode-ietf.txt +23 -0
- package/runtime/page/licenses/otp/LicenseRef-scancode-w3c-docs-19990405.txt +26 -0
- package/runtime/page/licenses/otp/LicenseRef-scancode-wxwindows-free-doc-3.txt +57 -0
- package/runtime/page/licenses/otp/MIT.txt +17 -0
- package/runtime/page/licenses/otp/SGI-B-2.0.txt +25 -0
- package/runtime/page/licenses/otp/W3C-19980720.txt +55 -0
- package/runtime/page/licenses/picosat.txt +19 -0
- package/runtime/page/licenses/wamr.txt +219 -0
- package/runtime/page/main.js +176 -0
- package/runtime/page/runtime-id.js +3 -0
- package/runtime/page/scope.js +17 -0
- package/runtime/page/sw.js +111 -0
- package/runtime/page/vm.js +148 -0
- package/runtime/page/worker.js +1891 -0
- package/runtime/page/ws-shim.js +143 -0
- package/runtime/release/app.js +17 -0
- package/runtime/release.json +1 -0
- package/runtime/runtime-id.js +3 -0
- package/runtime/tcp-proxy.mjs +30 -0
- package/runtime/worker.js +1891 -0
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
// The VM in one Durable Object, in place of one VM for each isolate: one
|
|
2
|
+
// instance for all the requests (a server whose state must be in one
|
|
3
|
+
// place), which runs all the time while it is in memory, and whose SQLite
|
|
4
|
+
// storage is the database of Ecto SQLite. All the requests go to the object
|
|
5
|
+
// "main" (BEAM_OBJECT names another one).
|
|
6
|
+
//
|
|
7
|
+
// Tenants: with the var BEAM_TENANTS, each tenant has its own object (its
|
|
8
|
+
// own VM, state and SQLite storage), and the request header x-beam-tenant
|
|
9
|
+
// gives its name to the app:
|
|
10
|
+
// - "cookie": GET /.tenant/NAME sets the cookie beam_tenant, and the cookie
|
|
11
|
+
// names the object (for a workers.dev URL);
|
|
12
|
+
// - "host": the first label of the host names the object (NAME.example.com);
|
|
13
|
+
// - "path": /t/NAME/... names the object. The front Worker removes the
|
|
14
|
+
// prefix, and the VM gets BEAM_TENANT=NAME and BEAM_TENANT_PATH=/t/NAME,
|
|
15
|
+
// the base path of the URLs that the app writes. A request from an
|
|
16
|
+
// iframe of another site has no cookie, but it has its path.
|
|
17
|
+
// A name has 1 to 32 characters: a-z, 0-9 and "-".
|
|
18
|
+
//
|
|
19
|
+
// Instances (path tenants, with the var BEAM_INSTANCES): each visitor can
|
|
20
|
+
// start an instance (the button of the page of /), with a random name and
|
|
21
|
+
// a time limit. At the limit, the object deletes its storage and stops.
|
|
22
|
+
// The object ".registry" admits the visitors:
|
|
23
|
+
// - BEAM_INSTANCES: the instances at one time (then a queue);
|
|
24
|
+
// - BEAM_INSTANCE_TTL: the life of an instance in seconds (1800);
|
|
25
|
+
// - BEAM_INSTANCE_HOURS: the hours of instances in each UTC day (24), a
|
|
26
|
+
// bound for the Durable Objects of the Free plan;
|
|
27
|
+
// - BEAM_INSTANCES_PER_IP: the instances at one time for one address (2).
|
|
28
|
+
// The VM gets BEAM_INSTANCE_EXPIRES (Unix seconds). A cron trigger (each
|
|
29
|
+
// 30 minutes) calls sweep(): the registry deletes the storage of each
|
|
30
|
+
// instance past its limit (if its alarm did not), and once the storage of
|
|
31
|
+
// each object that BEAM_RETIRE names ("a,b,c": objects of an earlier mode,
|
|
32
|
+
// which the registry did not make).
|
|
33
|
+
//
|
|
34
|
+
// wrangler deploy -c wrangler.durable.jsonc
|
|
35
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
36
|
+
import { Vm } from './worker.js';
|
|
37
|
+
|
|
38
|
+
const valid = (name) => /^[a-z0-9-]{1,32}$/.test(name ?? '');
|
|
39
|
+
const REGISTRY = '.registry';
|
|
40
|
+
const EXPIRES = 'beam:expires';
|
|
41
|
+
|
|
42
|
+
export class Beam extends DurableObject {
|
|
43
|
+
constructor(ctx, env) {
|
|
44
|
+
super(ctx, env);
|
|
45
|
+
this.vm = null;
|
|
46
|
+
this.expires = undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The VM starts at the first request: a path tenant gives its name there.
|
|
50
|
+
// The storage of the object keeps the secrets that the VM makes, and the
|
|
51
|
+
// host of the request is the default PHX_HOST (Vm.autoVars).
|
|
52
|
+
makeVm(vars, host) {
|
|
53
|
+
return new Vm(this.env, { plain: false, sql: this.ctx.storage.sql, id: this.ctx.id.toString(), vars,
|
|
54
|
+
secrets: this.ctx.storage, host });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async fetch(request) {
|
|
58
|
+
if (this.env.BEAM_INSTANCES && this.env.BEAM_TENANTS === 'path') {
|
|
59
|
+
this.expires ??= (await this.ctx.storage.get(EXPIRES)) ?? null;
|
|
60
|
+
if (!this.expires || this.expires <= Date.now()) {
|
|
61
|
+
if (this.expires) await this.expire();
|
|
62
|
+
return page(410, 'This instance is not available', `<p>An instance stops at its time limit, and its files are deleted.</p>
|
|
63
|
+
<form method="post" action="/.instance"><button>Start a new instance</button></form>`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (!this.vm) {
|
|
67
|
+
const vars = {};
|
|
68
|
+
const tenant = request.headers.get('x-beam-tenant');
|
|
69
|
+
if (this.env.BEAM_TENANTS === 'path' && valid(tenant)) {
|
|
70
|
+
vars.BEAM_TENANT = tenant;
|
|
71
|
+
vars.BEAM_TENANT_PATH = `/t/${tenant}`;
|
|
72
|
+
}
|
|
73
|
+
if (this.expires) vars.BEAM_INSTANCE_EXPIRES = String(Math.floor(this.expires / 1000));
|
|
74
|
+
this.vm = this.makeVm(vars, new URL(request.url).hostname);
|
|
75
|
+
}
|
|
76
|
+
return this.vm.fetch(request);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// An instance: its time limit (from the registry).
|
|
80
|
+
async start(expires) {
|
|
81
|
+
await this.ctx.storage.put(EXPIRES, expires);
|
|
82
|
+
await this.ctx.storage.setAlarm(expires);
|
|
83
|
+
this.expires = expires;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async alarm() {
|
|
87
|
+
await this.expire();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// The end of an instance: its storage (the files of BEAM_PERSIST, the
|
|
91
|
+
// database) is deleted, and the VM stops.
|
|
92
|
+
async expire() {
|
|
93
|
+
this.expires = null;
|
|
94
|
+
await this.ctx.storage.deleteAll();
|
|
95
|
+
if (this.vm) setTimeout(() => this.ctx.abort('the instance expired'), 0);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The registry (the object ".registry") admits a visitor: a ticket and a
|
|
99
|
+
// hash of its address. It gives {name, expires} of a new or running
|
|
100
|
+
// instance, the place in the queue, or a limit.
|
|
101
|
+
async admit(ticket, address) {
|
|
102
|
+
const env = this.env, sql = this.ctx.storage.sql, now = Date.now();
|
|
103
|
+
// A limit that is not a number is the default (NaN would be no limit).
|
|
104
|
+
const max = limit(env.BEAM_INSTANCES, 1);
|
|
105
|
+
const ttl = limit(env.BEAM_INSTANCE_TTL, 1800);
|
|
106
|
+
const hours = limit(env.BEAM_INSTANCE_HOURS, 24);
|
|
107
|
+
const perAddress = limit(env.BEAM_INSTANCES_PER_IP, 2);
|
|
108
|
+
this.tables();
|
|
109
|
+
// A visitor that did not refresh its page for 60 s left the queue.
|
|
110
|
+
sql.exec('DELETE FROM beam_waiting WHERE seen < ?', now - 60000);
|
|
111
|
+
// The rows of the instances past their limit stay until sweep().
|
|
112
|
+
const one = (q, ...a) => [...sql.exec(q, ...a)][0];
|
|
113
|
+
const mine = one('SELECT name, expires FROM beam_instances WHERE ticket = ? AND expires > ?', ticket, now);
|
|
114
|
+
if (mine) return { name: mine.name, expires: mine.expires, running: true };
|
|
115
|
+
const count = one('SELECT count(*) AS n FROM beam_instances WHERE expires > ?', now).n;
|
|
116
|
+
const next = one('SELECT min(expires) AS t FROM beam_instances WHERE expires > ?', now).t;
|
|
117
|
+
if (one('SELECT count(*) AS n FROM beam_instances WHERE address = ? AND expires > ?', address, now).n >= perAddress) {
|
|
118
|
+
return { limit: 'address', next };
|
|
119
|
+
}
|
|
120
|
+
const day = new Date(now).toISOString().slice(0, 10);
|
|
121
|
+
const used = one('SELECT seconds FROM beam_budget WHERE day = ?', day)?.seconds ?? 0;
|
|
122
|
+
if (used + ttl > hours * 3600) return { limit: 'day' };
|
|
123
|
+
// An address has at most perAddress places in the queue, so that one
|
|
124
|
+
// client with many tickets cannot fill it.
|
|
125
|
+
const queued = one('SELECT count(*) AS n FROM beam_waiting WHERE address = ? AND ticket <> ?', address, ticket).n;
|
|
126
|
+
if (queued >= perAddress) return { limit: 'address', next };
|
|
127
|
+
sql.exec('INSERT INTO beam_waiting VALUES (?, ?, ?, ?) ON CONFLICT(ticket) DO UPDATE SET seen = excluded.seen',
|
|
128
|
+
ticket, address, now, now);
|
|
129
|
+
const since = one('SELECT since FROM beam_waiting WHERE ticket = ?', ticket).since;
|
|
130
|
+
const position = one('SELECT count(*) AS n FROM beam_waiting WHERE since < ? OR (since = ? AND ticket < ?)',
|
|
131
|
+
since, since, ticket).n + 1;
|
|
132
|
+
if (position > max - count) {
|
|
133
|
+
return { position, waiting: one('SELECT count(*) AS n FROM beam_waiting').n, next };
|
|
134
|
+
}
|
|
135
|
+
const name = randomName();
|
|
136
|
+
const expires = now + ttl * 1000;
|
|
137
|
+
sql.exec('INSERT INTO beam_instances VALUES (?, ?, ?, ?)', name, ticket, address, expires);
|
|
138
|
+
sql.exec('DELETE FROM beam_waiting WHERE ticket = ?', ticket);
|
|
139
|
+
sql.exec('DELETE FROM beam_budget WHERE day < ?', day);
|
|
140
|
+
sql.exec('INSERT INTO beam_budget VALUES (?, ?) ON CONFLICT(day) DO UPDATE SET seconds = seconds + excluded.seconds',
|
|
141
|
+
day, ttl);
|
|
142
|
+
return { name, expires };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// The registry: deletes the storage of the instances past their limit,
|
|
146
|
+
// and of the objects that BEAM_RETIRE names (once). Gives the counts.
|
|
147
|
+
async sweep() {
|
|
148
|
+
const env = this.env, sql = this.ctx.storage.sql, now = Date.now();
|
|
149
|
+
this.tables();
|
|
150
|
+
const stub = (name) => env.BEAM.get(env.BEAM.idFromName(name));
|
|
151
|
+
let expired = 0, retired = 0;
|
|
152
|
+
// An error of one object does not stop the sweep of the others.
|
|
153
|
+
for (const { name } of [...sql.exec('SELECT name FROM beam_instances WHERE expires <= ?', now)]) {
|
|
154
|
+
try {
|
|
155
|
+
await stub(name).expire();
|
|
156
|
+
sql.exec('DELETE FROM beam_instances WHERE name = ?', name);
|
|
157
|
+
expired++;
|
|
158
|
+
} catch (e) {
|
|
159
|
+
console.log(`beam: sweep: ${name}: ${e}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const done = new Set([...sql.exec('SELECT name FROM beam_retired')].map((r) => r.name));
|
|
163
|
+
for (const name of (env.BEAM_RETIRE ?? '').split(',').map((n) => n.trim()).filter(valid)) {
|
|
164
|
+
if (done.has(name)) continue;
|
|
165
|
+
try {
|
|
166
|
+
await stub(name).expire();
|
|
167
|
+
sql.exec('INSERT INTO beam_retired VALUES (?, ?)', name, now);
|
|
168
|
+
retired++;
|
|
169
|
+
} catch (e) {
|
|
170
|
+
console.log(`beam: sweep: ${name}: ${e}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return { expired, retired };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// The registry: the instances in use, for the page of /.
|
|
177
|
+
async usage() {
|
|
178
|
+
this.tables();
|
|
179
|
+
const n = [...this.ctx.storage.sql.exec('SELECT count(*) AS n FROM beam_instances WHERE expires > ?', Date.now())][0].n;
|
|
180
|
+
return { used: n, max: Number(this.env.BEAM_INSTANCES), ttl: Number(this.env.BEAM_INSTANCE_TTL ?? 1800) };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
tables() {
|
|
184
|
+
const sql = this.ctx.storage.sql;
|
|
185
|
+
sql.exec('CREATE TABLE IF NOT EXISTS beam_instances (name TEXT PRIMARY KEY, ticket TEXT, address TEXT, expires INTEGER)');
|
|
186
|
+
sql.exec('CREATE TABLE IF NOT EXISTS beam_waiting (ticket TEXT PRIMARY KEY, address TEXT, since INTEGER, seen INTEGER)');
|
|
187
|
+
sql.exec('CREATE TABLE IF NOT EXISTS beam_budget (day TEXT PRIMARY KEY, seconds INTEGER)');
|
|
188
|
+
sql.exec('CREATE TABLE IF NOT EXISTS beam_retired (name TEXT PRIMARY KEY, time INTEGER)');
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// 20 characters of a-z and 2-7: 100 random bits.
|
|
193
|
+
function randomName() {
|
|
194
|
+
const abc = 'abcdefghijklmnopqrstuvwxyz234567';
|
|
195
|
+
return [...crypto.getRandomValues(new Uint8Array(20))].map((b) => abc[b & 31]).join('');
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// A limit of the vars: a number of 0 or more, else the default.
|
|
199
|
+
function limit(value, fallback) {
|
|
200
|
+
const n = Number(value);
|
|
201
|
+
return value !== undefined && value !== '' && Number.isFinite(n) && n >= 0 ? n : fallback;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// The address of a client for its limits: an IPv6 client has a whole /64,
|
|
205
|
+
// so the limits count the /64.
|
|
206
|
+
function clientKey(ip) {
|
|
207
|
+
if (!ip.includes(':')) return ip;
|
|
208
|
+
const [head, tail = ''] = ip.split('::');
|
|
209
|
+
const h = head ? head.split(':') : [], t = tail ? tail.split(':') : [];
|
|
210
|
+
const all = ip.includes('::') ? [...h, ...Array(8 - h.length - t.length).fill('0'), ...t] : h;
|
|
211
|
+
return all.slice(0, 4).map((x) => x.toLowerCase().replace(/^0+(?=.)/, '')).join(':') + '::/64';
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const hex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
215
|
+
|
|
216
|
+
function cookie(request, name) {
|
|
217
|
+
return new RegExp(`(?:^|;\\s*)${name}=([^;]*)`).exec(request.headers.get('cookie') ?? '')?.[1];
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function tenant(request, env) {
|
|
221
|
+
if (env.BEAM_TENANTS === 'host') return new URL(request.url).hostname.split('.')[0];
|
|
222
|
+
if (env.BEAM_TENANTS === 'cookie') return cookie(request, 'beam_tenant');
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
227
|
+
|
|
228
|
+
function page(status, title, body, headers = {}) {
|
|
229
|
+
return new Response(`<!doctype html><html lang="en"><head><meta charset="utf-8">
|
|
230
|
+
<meta name="viewport" content="width=device-width, initial-scale=1"><title>${esc(title)}</title>
|
|
231
|
+
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem;color:#1f2937}
|
|
232
|
+
button{font:inherit;padding:.5rem 1rem;border-radius:.5rem;border:0;background:#4f46e5;color:#fff;cursor:pointer}</style>
|
|
233
|
+
</head><body><h1>${esc(title)}</h1>${body}</body></html>`,
|
|
234
|
+
{ status, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', ...headers } });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const minutes = (ms) => Math.max(1, Math.ceil(ms / 60000));
|
|
238
|
+
|
|
239
|
+
// A static file of the app, in the front Worker (no request to the
|
|
240
|
+
// object): BEAM_STATICS (serve(app) of the npm package gives it, for the
|
|
241
|
+
// static files in app.com), else, with assets, the static assets of the
|
|
242
|
+
// binding ASSETS (wasm/erts/host/static.mjs). Cloudflare serves the
|
|
243
|
+
// assets of the root before the Worker runs, so only a path tenant asks
|
|
244
|
+
// ASSETS (after its prefix).
|
|
245
|
+
async function staticFile(env, request, assets = false) {
|
|
246
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return null;
|
|
247
|
+
if (env.BEAM_STATICS) return env.BEAM_STATICS(request);
|
|
248
|
+
if (!assets || !env.ASSETS) return null;
|
|
249
|
+
const asset = await env.ASSETS.fetch(request);
|
|
250
|
+
return asset.status !== 404 ? asset : null;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// The instances: the page of /, and POST (the button) or GET (the refresh
|
|
254
|
+
// of the queue) of /.instance. Only a POST makes a ticket, so a crawler
|
|
255
|
+
// that reads / starts no instance.
|
|
256
|
+
async function instances(request, env, url) {
|
|
257
|
+
const registry = env.BEAM.get(env.BEAM.idFromName(REGISTRY));
|
|
258
|
+
if (url.pathname === '/' && request.method === 'GET') {
|
|
259
|
+
const { used, max, ttl } = await registry.usage();
|
|
260
|
+
return page(200, env.BEAM_INSTANCE_TITLE ?? 'Start an instance', `<p>Each visitor gets an instance of its own, for ${minutes(ttl * 1000)} minutes.
|
|
261
|
+
At the end, the instance stops, and its files are deleted.</p>
|
|
262
|
+
<p>${used} of ${max} instances are in use.</p>
|
|
263
|
+
<form method="post" action="/.instance"><button>Start an instance</button></form>`);
|
|
264
|
+
}
|
|
265
|
+
if (url.pathname !== '/.instance' || (request.method !== 'POST' && request.method !== 'GET')) {
|
|
266
|
+
return new Response('not found\n', { status: 404 });
|
|
267
|
+
}
|
|
268
|
+
// Only the navigation of a page (the button, the refresh) gets the name
|
|
269
|
+
// of an instance: a script of a page of another instance, on this same
|
|
270
|
+
// origin, cannot read it with fetch().
|
|
271
|
+
const mode = request.headers.get('sec-fetch-mode');
|
|
272
|
+
if (mode && mode !== 'navigate') return new Response('forbidden\n', { status: 403 });
|
|
273
|
+
let ticket = cookie(request, 'beam_ticket');
|
|
274
|
+
const headers = {};
|
|
275
|
+
if (!/^[0-9a-f]{32}$/.test(ticket ?? '')) {
|
|
276
|
+
if (request.method === 'GET') return Response.redirect(new URL('/', url), 303);
|
|
277
|
+
ticket = hex(crypto.getRandomValues(new Uint8Array(16)));
|
|
278
|
+
headers['set-cookie'] = `beam_ticket=${ticket}; Path=/; Secure; HttpOnly; SameSite=Lax`;
|
|
279
|
+
}
|
|
280
|
+
// A hash of the address and the day, not the address.
|
|
281
|
+
const day = new Date().toISOString().slice(0, 10);
|
|
282
|
+
const digest = await crypto.subtle.digest('SHA-256',
|
|
283
|
+
new TextEncoder().encode(`${clientKey(request.headers.get('cf-connecting-ip') ?? '')} ${day}`));
|
|
284
|
+
const r = await registry.admit(ticket, hex(new Uint8Array(digest).slice(0, 16)));
|
|
285
|
+
if (r.name) {
|
|
286
|
+
if (!r.running) await env.BEAM.get(env.BEAM.idFromName(r.name)).start(r.expires);
|
|
287
|
+
return new Response(null, { status: 303, headers: { ...headers, location: `/t/${r.name}/` } });
|
|
288
|
+
}
|
|
289
|
+
if (r.limit === 'day') {
|
|
290
|
+
return page(503, 'No more instances today', '<p>The instances of today are used. They start again at 00:00 UTC.</p>', headers);
|
|
291
|
+
}
|
|
292
|
+
const wait = r.next ? `The next instance stops in about ${minutes(r.next - Date.now())} minutes.` : '';
|
|
293
|
+
if (r.limit === 'address') {
|
|
294
|
+
return page(429, 'Too many instances', `<p>Your address has the most instances that it can have at one time. ${wait}</p>`, headers);
|
|
295
|
+
}
|
|
296
|
+
return page(200, 'You are in the queue', `<p>Your place: ${r.position} of ${r.waiting}. ${wait}</p>
|
|
297
|
+
<p>This page refreshes each 10 seconds. Keep it open to keep your place.</p>`,
|
|
298
|
+
{ ...headers, refresh: '10; url=/.instance' });
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export default {
|
|
302
|
+
// The cron trigger of the instances (see sweep()).
|
|
303
|
+
async scheduled(controller, env, ctx) {
|
|
304
|
+
if (!env.BEAM_INSTANCES) return;
|
|
305
|
+
const registry = env.BEAM.get(env.BEAM.idFromName(REGISTRY));
|
|
306
|
+
ctx.waitUntil(registry.sweep().then((r) => console.log(`beam: sweep: ${r.expired} expired, ${r.retired} retired`)));
|
|
307
|
+
},
|
|
308
|
+
|
|
309
|
+
async fetch(request, env) {
|
|
310
|
+
const url = new URL(request.url);
|
|
311
|
+
if (env.BEAM_TENANTS === 'path') {
|
|
312
|
+
const m = /^\/t\/([^/]+)(\/.*)?$/.exec(url.pathname);
|
|
313
|
+
if (!m) {
|
|
314
|
+
// A path of the app with no prefix (Livebook writes some so).
|
|
315
|
+
const asset = await staticFile(env, request);
|
|
316
|
+
if (asset) return asset;
|
|
317
|
+
if (env.BEAM_INSTANCES) return instances(request, env, url);
|
|
318
|
+
return new Response('not found\n', { status: 404 });
|
|
319
|
+
}
|
|
320
|
+
if (!valid(m[1])) return new Response('bad tenant name\n', { status: 400 });
|
|
321
|
+
if (m[2] === undefined) return Response.redirect(new URL(`/t/${m[1]}/`, url), 301);
|
|
322
|
+
// The path of the app, with no prefix, on the same origin (a path
|
|
323
|
+
// "//host/..." must not change the host).
|
|
324
|
+
const inner = new URL(url);
|
|
325
|
+
inner.pathname = m[2];
|
|
326
|
+
const asset = await staticFile(env, new Request(inner, request), true);
|
|
327
|
+
if (asset) return asset;
|
|
328
|
+
// All the tenants share this origin. A service worker of one tenant
|
|
329
|
+
// could take the requests of the others, so none can register.
|
|
330
|
+
if (request.headers.get('service-worker') === 'script') {
|
|
331
|
+
return new Response('no service workers for tenants\n', { status: 403 });
|
|
332
|
+
}
|
|
333
|
+
// The app can trust the header: a client cannot give it.
|
|
334
|
+
request = new Request(inner, request);
|
|
335
|
+
request.headers.set('x-beam-tenant', m[1]);
|
|
336
|
+
const response = await env.BEAM.get(env.BEAM.idFromName(m[1])).fetch(request);
|
|
337
|
+
if (!response.headers.has('service-worker-allowed')) return response;
|
|
338
|
+
const out = new Response(response.body, response);
|
|
339
|
+
out.headers.delete('service-worker-allowed');
|
|
340
|
+
return out;
|
|
341
|
+
}
|
|
342
|
+
const set = env.BEAM_TENANTS === 'cookie' && /^\/\.tenant\/([^/]+)$/.exec(url.pathname);
|
|
343
|
+
if (set) {
|
|
344
|
+
if (!valid(set[1])) return new Response('bad tenant name\n', { status: 400 });
|
|
345
|
+
return new Response(null, {
|
|
346
|
+
status: 303,
|
|
347
|
+
headers: { location: '/', 'set-cookie': `beam_tenant=${set[1]}; Path=/; Secure; HttpOnly; SameSite=Lax` },
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
const asset = await staticFile(env, request);
|
|
351
|
+
if (asset) return asset;
|
|
352
|
+
let name = env.BEAM_OBJECT ?? 'main';
|
|
353
|
+
const t = tenant(request, env);
|
|
354
|
+
if (t !== undefined && t !== null && !valid(t)) return new Response('bad tenant name\n', { status: 400 });
|
|
355
|
+
name = t ?? name;
|
|
356
|
+
request = new Request(request);
|
|
357
|
+
if (env.BEAM_TENANTS) request.headers.set('x-beam-tenant', name);
|
|
358
|
+
else request.headers.delete('x-beam-tenant');
|
|
359
|
+
return env.BEAM.get(env.BEAM.idFromName(name)).fetch(request);
|
|
360
|
+
},
|
|
361
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// The runtime Worker with the release and a snapshot of the build in it
|
|
2
|
+
// (release/release.bin, and release/snapshot.bin of wasm/snapshot/snapshot.mjs):
|
|
3
|
+
// the global scope of the Worker restores the VM before the first request.
|
|
4
|
+
// Cloudflare runs the global scope of a new isolate with its own limit
|
|
5
|
+
// (1 s). The first request then only starts the threads. The var
|
|
6
|
+
// BEAM_WARM (a path, as "/") also sends one GET request to the app there,
|
|
7
|
+
// so that V8 compiles the code of a request before the first request.
|
|
8
|
+
// That request must not use I/O of the host (SQL, sockets). Measured on
|
|
9
|
+
// Cloudflare: see docs/WORKERS.md.
|
|
10
|
+
//
|
|
11
|
+
// node wasm/snapshot/snapshot.mjs DIR --warm 4000:/
|
|
12
|
+
// (cd DIR && wrangler deploy -c wrangler.global.jsonc)
|
|
13
|
+
import { env } from 'cloudflare:workers';
|
|
14
|
+
import { Vm } from './worker.js';
|
|
15
|
+
import release from './release/release.bin';
|
|
16
|
+
import snapshot from './release/snapshot.bin';
|
|
17
|
+
|
|
18
|
+
const vm = new Vm(env, { release, snapshot });
|
|
19
|
+
await vm.ready;
|
|
20
|
+
if (env.BEAM_WARM) await vm.warm(env.BEAM_WARM);
|
|
21
|
+
|
|
22
|
+
export default {
|
|
23
|
+
fetch(request, env, ctx) {
|
|
24
|
+
return vm.fetch(request, ctx);
|
|
25
|
+
},
|
|
26
|
+
};
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|