@plitzi/sdk-runtime 0.0.0-stage → 0.39.2
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/CHANGELOG.md +11 -0
- package/README.md +84 -2
- package/dist/chunks/service-DDDJomiH.mjs +2322 -0
- package/dist/contract/runtime.d.ts +3 -0
- package/dist/functions-api.d.ts +724 -0
- package/dist/host/host.d.ts +42 -0
- package/dist/host/index.d.ts +3 -0
- package/dist/host/index.mjs +107 -0
- package/dist/host/runner.d.ts +11 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.mjs +5 -0
- package/dist/prelude.js +1 -0
- package/dist/runner/cpuMeter.d.ts +35 -0
- package/dist/runner/driver.d.ts +37 -0
- package/dist/runner/guest/bytes.d.ts +27 -0
- package/dist/runner/guest/crypto.d.ts +47 -0
- package/dist/runner/guest/events.d.ts +152 -0
- package/dist/runner/guest/fetch.d.ts +305 -0
- package/dist/runner/guest/install.d.ts +23 -0
- package/dist/runner/guest/types.d.ts +38 -0
- package/dist/runner/index.d.ts +6 -0
- package/dist/runner/index.mjs +1 -0
- package/dist/runner/isolate.d.ts +65 -0
- package/dist/runner/memoryGuard.d.ts +25 -0
- package/dist/runner/prelude.d.ts +10 -0
- package/dist/runner/service.d.ts +76 -0
- package/dist/runner/turns.d.ts +12 -0
- package/package.json +64 -3
|
@@ -0,0 +1,2322 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { FUNCTIONS_PROTOCOL, FunctionFailure, changeKv, changeListEntry, errorOfAnswer, failedAnswerOf, functionSizeOfMemory, invocationUrgency, isFunctionLimit, isStreamedRouteAnswer, largerFunctionSize, protocolKnows, protocolRefusal, readRequestMessage } from "@plitzi/sdk-shared/functions";
|
|
3
|
+
import { SHUTDOWN_GRACE_MS, bearerMatches, frameText, shutdownOf, watchConnections } from "@plitzi/sdk-kernel/http";
|
|
4
|
+
import http from "node:http";
|
|
5
|
+
import { WebSocketServer } from "ws";
|
|
6
|
+
import { logQueryOf, readLogTail, serverLog } from "@plitzi/sdk-kernel/log";
|
|
7
|
+
import { STATS_LOGS_PATH, STATS_PATH, cpuLimitCores, createStatsRecorder, sampleProcessMemory, withStopping } from "@plitzi/sdk-kernel/stats";
|
|
8
|
+
import { createHash, createHmac, pbkdf2, randomBytes } from "node:crypto";
|
|
9
|
+
import { promisify } from "node:util";
|
|
10
|
+
import { readFileSync } from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
// src/runner/driver.ts
|
|
14
|
+
/**
|
|
15
|
+
* What a definition declares, as the platform reads a manifest (`readManifest`) — nothing of it trusted there. Printed
|
|
16
|
+
* into the sandbox's guest and imported by a space runtime, like the driver below: self-contained for that.
|
|
17
|
+
*/
|
|
18
|
+
var describeFunctions = (definition) => {
|
|
19
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
20
|
+
const listOf = (value) => Array.isArray(value) ? value : [];
|
|
21
|
+
const found = isRecord(definition) ? definition : {};
|
|
22
|
+
return {
|
|
23
|
+
hosts: listOf((isRecord(found.allow) ? found.allow : {}).hosts),
|
|
24
|
+
tasks: listOf(found.tasks).map((task) => isRecord(task) ? {
|
|
25
|
+
namespace: task.namespace,
|
|
26
|
+
action: task.action,
|
|
27
|
+
title: task.title,
|
|
28
|
+
description: task.description,
|
|
29
|
+
params: task.params,
|
|
30
|
+
limits: task.limits
|
|
31
|
+
} : {}),
|
|
32
|
+
routes: isRecord(found.routes) ? Object.keys(found.routes) : [],
|
|
33
|
+
limits: found.limits,
|
|
34
|
+
oauth: found.oauth,
|
|
35
|
+
jobs: isRecord(found.jobs) ? Object.fromEntries(Object.entries(found.jobs).map(([name, job]) => [name, isRecord(job) ? {
|
|
36
|
+
watch: job.watch,
|
|
37
|
+
maxSeconds: job.maxSeconds
|
|
38
|
+
} : job])) : found.jobs
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* A space's functions, driven: one invocation of a definition — a task or a route, with a `ctx` whose every method is
|
|
43
|
+
* a call to the platform.
|
|
44
|
+
*
|
|
45
|
+
* The one driver there is. The sandbox's guest is handed this function's SOURCE and runs it inside the isolate
|
|
46
|
+
* (`isolate.ts`), and a space runtime imports it and runs it in its own process — so code behaves the same in both, down
|
|
47
|
+
* to `ctx`. Self-contained by contract for that: no import, nothing of this module's, only what `environment` brings.
|
|
48
|
+
*/
|
|
49
|
+
var createFunctionsDriver = (environment) => {
|
|
50
|
+
const { call, signal, responseOf, requestOf, wireOfResponse, refusal } = environment;
|
|
51
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
52
|
+
const isCallable = (value) => typeof value === "function";
|
|
53
|
+
const listOf = (value) => Array.isArray(value) ? value : [];
|
|
54
|
+
/** `ctx.visitors.get`'s answer: a person's public fields, or nobody — whatever came over the wire. */
|
|
55
|
+
const visitorOf = (value) => isRecord(value) && typeof value.id === "number" && typeof value.username === "string" ? {
|
|
56
|
+
id: value.id,
|
|
57
|
+
username: value.username,
|
|
58
|
+
...typeof value.name === "string" ? { name: value.name } : {},
|
|
59
|
+
...typeof value.avatar === "string" ? { avatar: value.avatar } : {}
|
|
60
|
+
} : void 0;
|
|
61
|
+
/** `ctx.presence`'s answer, as the platform said it — whatever came over the wire, read as what it must be. */
|
|
62
|
+
const presenceOf = (value) => {
|
|
63
|
+
const members = (isRecord(value) ? listOf(value.members) : []).flatMap((member) => isRecord(member) && typeof member.from === "string" && typeof member.since === "number" ? [{
|
|
64
|
+
from: member.from,
|
|
65
|
+
since: member.since,
|
|
66
|
+
...isRecord(member.user) && typeof member.user.id === "number" && typeof member.user.name === "string" ? { user: {
|
|
67
|
+
id: member.user.id,
|
|
68
|
+
name: member.user.name
|
|
69
|
+
} } : {}
|
|
70
|
+
}] : []);
|
|
71
|
+
return {
|
|
72
|
+
count: members.length,
|
|
73
|
+
members
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
const isSignal = (value) => isRecord(value) && typeof value.aborted === "boolean" && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function";
|
|
77
|
+
/** Why a request was cut: the signal's reason, as a web `fetch` rejects with it — an `AbortError` when it gave none. */
|
|
78
|
+
const abortedWith = (signal) => signal.reason instanceof Error ? signal.reason : Object.assign(/* @__PURE__ */ new Error("This operation was aborted"), { name: "AbortError" });
|
|
79
|
+
let requests = 0;
|
|
80
|
+
/**
|
|
81
|
+
* A request the code may cut short with its init's `signal`: the signal stays here — it does not cross — and the
|
|
82
|
+
* call is numbered, so that its firing tells the platform which request to cut (`abort`). The code stops waiting at
|
|
83
|
+
* once, with the signal's reason, as a web `fetch` does.
|
|
84
|
+
*/
|
|
85
|
+
const cuttable = (message, init) => {
|
|
86
|
+
const { signal: given, ...rest } = init;
|
|
87
|
+
if (given === void 0 || given === null) return call({
|
|
88
|
+
...message,
|
|
89
|
+
init: rest
|
|
90
|
+
});
|
|
91
|
+
if (!isSignal(given)) return Promise.reject(/* @__PURE__ */ new TypeError("The signal of a request is an AbortSignal"));
|
|
92
|
+
if (given.aborted) return Promise.reject(abortedWith(given));
|
|
93
|
+
const request = ++requests;
|
|
94
|
+
return new Promise((resolve, reject) => {
|
|
95
|
+
const cut = () => {
|
|
96
|
+
call({
|
|
97
|
+
op: "abort",
|
|
98
|
+
request
|
|
99
|
+
}).catch(() => void 0);
|
|
100
|
+
reject(abortedWith(given));
|
|
101
|
+
};
|
|
102
|
+
given.addEventListener("abort", cut, { once: true });
|
|
103
|
+
call({
|
|
104
|
+
...message,
|
|
105
|
+
init: rest,
|
|
106
|
+
request
|
|
107
|
+
}).then(resolve, reject).finally(() => {
|
|
108
|
+
given.removeEventListener("abort", cut);
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
};
|
|
112
|
+
/** A value as the wire can carry it; how a line reads is the platform's (`lineOf`), not the driver's. */
|
|
113
|
+
const wireValue = (value) => {
|
|
114
|
+
if (value instanceof Error) return `${value.name}: ${value.message}`;
|
|
115
|
+
if (value === void 0 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") return typeof value;
|
|
116
|
+
return value;
|
|
117
|
+
};
|
|
118
|
+
/** `ctx.log`, and whatever else the code writes a line with: onto its step, never failing the code for it. */
|
|
119
|
+
const log = (...values) => {
|
|
120
|
+
call({
|
|
121
|
+
op: "log",
|
|
122
|
+
values: values.map(wireValue)
|
|
123
|
+
}).catch(() => void 0);
|
|
124
|
+
};
|
|
125
|
+
const contextOf = (invocation) => {
|
|
126
|
+
const facts = isRecord(invocation.context) ? invocation.context : {};
|
|
127
|
+
const kvCall = (method) => (...args) => call({
|
|
128
|
+
op: "kv",
|
|
129
|
+
method,
|
|
130
|
+
args
|
|
131
|
+
});
|
|
132
|
+
const kv = {
|
|
133
|
+
get: kvCall("get"),
|
|
134
|
+
set: kvCall("set"),
|
|
135
|
+
delete: kvCall("delete"),
|
|
136
|
+
increment: kvCall("increment"),
|
|
137
|
+
swap: (key, expected, next, ttlSeconds) => kvCall("swap")(key, expected, next, ttlSeconds).then((written) => written === true),
|
|
138
|
+
listPut: kvCall("listPut"),
|
|
139
|
+
listRange: kvCall("listRange"),
|
|
140
|
+
listRemove: kvCall("listRemove"),
|
|
141
|
+
listSwap: (list, id, expected, next) => kvCall("listSwap")(list, id, expected ?? null, next).then((written) => written === true),
|
|
142
|
+
listChange: (list, id, change) => environment.changeListEntry({
|
|
143
|
+
listRange: (listName) => kvCall("listRange")(listName).then((entries) => Array.isArray(entries) ? entries : []),
|
|
144
|
+
listSwap: (listName, entryId, expected, next) => kvCall("listSwap")(listName, entryId, expected ?? null, next).then((written) => written === true)
|
|
145
|
+
}, list, id, change, { refusal }),
|
|
146
|
+
change: (key, change, lifetime) => environment.changeKv(kv, key, change, {
|
|
147
|
+
lifetime,
|
|
148
|
+
refusal
|
|
149
|
+
})
|
|
150
|
+
};
|
|
151
|
+
return {
|
|
152
|
+
...facts,
|
|
153
|
+
kv,
|
|
154
|
+
fetch: async (url, init = {}) => {
|
|
155
|
+
const answer = await cuttable({
|
|
156
|
+
op: "fetch",
|
|
157
|
+
url: String(url)
|
|
158
|
+
}, init);
|
|
159
|
+
return responseOf(isRecord(answer) ? answer : {});
|
|
160
|
+
},
|
|
161
|
+
publish: async (topic, type, data) => {
|
|
162
|
+
await call({
|
|
163
|
+
op: "publish",
|
|
164
|
+
topic,
|
|
165
|
+
type,
|
|
166
|
+
data
|
|
167
|
+
});
|
|
168
|
+
},
|
|
169
|
+
presence: async (topic) => presenceOf(await call({
|
|
170
|
+
op: "presence",
|
|
171
|
+
topic
|
|
172
|
+
})),
|
|
173
|
+
visitors: { get: async (who) => visitorOf(await call({
|
|
174
|
+
op: "visitor",
|
|
175
|
+
who
|
|
176
|
+
})) },
|
|
177
|
+
grant: (topic, ttlSeconds) => call({
|
|
178
|
+
op: "grant",
|
|
179
|
+
topic,
|
|
180
|
+
ttlSeconds
|
|
181
|
+
}),
|
|
182
|
+
revoke: async (topic, grant) => {
|
|
183
|
+
await call({
|
|
184
|
+
op: "revoke",
|
|
185
|
+
topic,
|
|
186
|
+
grant
|
|
187
|
+
});
|
|
188
|
+
},
|
|
189
|
+
later: (request) => call({
|
|
190
|
+
op: "later",
|
|
191
|
+
request
|
|
192
|
+
}),
|
|
193
|
+
cancelLater: (key) => call({
|
|
194
|
+
op: "cancelLater",
|
|
195
|
+
key
|
|
196
|
+
}),
|
|
197
|
+
rateLimit: async (bucket, limit) => {
|
|
198
|
+
const count = await call({
|
|
199
|
+
op: "rateLimit",
|
|
200
|
+
bucket,
|
|
201
|
+
limit
|
|
202
|
+
});
|
|
203
|
+
if (isRecord(limit) && typeof limit.refuse === "string" && isRecord(count) && count.allowed === false) throw refusal(limit.refuse);
|
|
204
|
+
return count;
|
|
205
|
+
},
|
|
206
|
+
sign: (value) => call({
|
|
207
|
+
op: "sign",
|
|
208
|
+
value
|
|
209
|
+
}),
|
|
210
|
+
verify: (value, signature) => call({
|
|
211
|
+
op: "verify",
|
|
212
|
+
value,
|
|
213
|
+
signature
|
|
214
|
+
}),
|
|
215
|
+
data: (file) => call({
|
|
216
|
+
op: "data",
|
|
217
|
+
file
|
|
218
|
+
}),
|
|
219
|
+
jobs: {
|
|
220
|
+
start: (name, input = {}, options = {}) => call({
|
|
221
|
+
op: "jobs",
|
|
222
|
+
method: "start",
|
|
223
|
+
name,
|
|
224
|
+
input,
|
|
225
|
+
key: options.key
|
|
226
|
+
}),
|
|
227
|
+
get: (id) => call({
|
|
228
|
+
op: "jobs",
|
|
229
|
+
method: "get",
|
|
230
|
+
id
|
|
231
|
+
}).then((found) => found ?? void 0),
|
|
232
|
+
pause: (id) => call({
|
|
233
|
+
op: "jobs",
|
|
234
|
+
method: "pause",
|
|
235
|
+
id
|
|
236
|
+
}),
|
|
237
|
+
resume: (id) => call({
|
|
238
|
+
op: "jobs",
|
|
239
|
+
method: "resume",
|
|
240
|
+
id
|
|
241
|
+
}),
|
|
242
|
+
cancel: (id) => call({
|
|
243
|
+
op: "jobs",
|
|
244
|
+
method: "cancel",
|
|
245
|
+
id
|
|
246
|
+
})
|
|
247
|
+
},
|
|
248
|
+
oauth: {
|
|
249
|
+
connect: (connection, options = {}) => call({
|
|
250
|
+
op: "oauth",
|
|
251
|
+
method: "connect",
|
|
252
|
+
connection,
|
|
253
|
+
returnTo: options.returnTo,
|
|
254
|
+
authorizeParams: options.authorizeParams,
|
|
255
|
+
owner: options.owner
|
|
256
|
+
}),
|
|
257
|
+
status: (connection, options = {}) => call({
|
|
258
|
+
op: "oauth",
|
|
259
|
+
method: "status",
|
|
260
|
+
connection,
|
|
261
|
+
owner: options.owner
|
|
262
|
+
}),
|
|
263
|
+
disconnect: (connection, options = {}) => call({
|
|
264
|
+
op: "oauth",
|
|
265
|
+
method: "disconnect",
|
|
266
|
+
connection,
|
|
267
|
+
owner: options.owner
|
|
268
|
+
}),
|
|
269
|
+
token: (connection, options = {}) => call({
|
|
270
|
+
op: "oauth",
|
|
271
|
+
method: "token",
|
|
272
|
+
connection,
|
|
273
|
+
owner: options.owner
|
|
274
|
+
}),
|
|
275
|
+
callbackUrl: () => call({
|
|
276
|
+
op: "oauth",
|
|
277
|
+
method: "callbackUrl"
|
|
278
|
+
}),
|
|
279
|
+
fetch: async (connection, url, init = {}) => {
|
|
280
|
+
const { owner, ...rest } = init;
|
|
281
|
+
const answer = await cuttable({
|
|
282
|
+
op: "oauth",
|
|
283
|
+
method: "fetch",
|
|
284
|
+
connection,
|
|
285
|
+
url: String(url),
|
|
286
|
+
owner
|
|
287
|
+
}, rest);
|
|
288
|
+
return responseOf(isRecord(answer) ? answer : {});
|
|
289
|
+
}
|
|
290
|
+
},
|
|
291
|
+
log,
|
|
292
|
+
emit: (chunk) => {
|
|
293
|
+
call({
|
|
294
|
+
op: "emit",
|
|
295
|
+
chunk
|
|
296
|
+
}).catch(() => void 0);
|
|
297
|
+
},
|
|
298
|
+
signal
|
|
299
|
+
};
|
|
300
|
+
};
|
|
301
|
+
const STOPS = [
|
|
302
|
+
"pause",
|
|
303
|
+
"cancel",
|
|
304
|
+
"limit",
|
|
305
|
+
"shutdown"
|
|
306
|
+
];
|
|
307
|
+
/**
|
|
308
|
+
* Why the slice is asked to end, once it is: the reason the signal was aborted with — said as itself in a runtime, and
|
|
309
|
+
* as the message of the `AbortError` the sandbox raises — and a cancel when it said none of them.
|
|
310
|
+
*/
|
|
311
|
+
const stoppingOf = () => {
|
|
312
|
+
const current = signal;
|
|
313
|
+
if (typeof current !== "object" || current === null || !("aborted" in current) || current.aborted !== true) return;
|
|
314
|
+
const reason = "reason" in current ? current.reason : void 0;
|
|
315
|
+
const said = typeof reason === "string" ? reason : typeof reason === "object" && reason !== null && "message" in reason && typeof reason.message === "string" ? reason.message : void 0;
|
|
316
|
+
return said !== void 0 && STOPS.includes(said) ? said : "cancel";
|
|
317
|
+
};
|
|
318
|
+
/** A job's `run` and what it is handed: the slice, how it saves and reports, and why it is asked to end. */
|
|
319
|
+
const runJob = async (found, invocation, ctx) => {
|
|
320
|
+
const jobs = isRecord(found.jobs) ? found.jobs : {};
|
|
321
|
+
const name = String(invocation.name);
|
|
322
|
+
const job = Object.hasOwn(jobs, name) ? jobs[name] : void 0;
|
|
323
|
+
if (!isRecord(job) || !isCallable(job.run)) throw new Error(`This space's functions have no job "${name}"`);
|
|
324
|
+
const slice = isRecord(invocation.job) ? invocation.job : {};
|
|
325
|
+
const handle = {
|
|
326
|
+
id: slice.id,
|
|
327
|
+
name,
|
|
328
|
+
state: slice.state,
|
|
329
|
+
attempt: slice.attempt,
|
|
330
|
+
save: async (state) => {
|
|
331
|
+
await call({
|
|
332
|
+
op: "job",
|
|
333
|
+
method: "save",
|
|
334
|
+
state
|
|
335
|
+
});
|
|
336
|
+
},
|
|
337
|
+
report: (fraction, step) => {
|
|
338
|
+
call({
|
|
339
|
+
op: "job",
|
|
340
|
+
method: "report",
|
|
341
|
+
fraction,
|
|
342
|
+
step
|
|
343
|
+
}).catch(() => void 0);
|
|
344
|
+
},
|
|
345
|
+
get stopping() {
|
|
346
|
+
return stoppingOf();
|
|
347
|
+
},
|
|
348
|
+
signal
|
|
349
|
+
};
|
|
350
|
+
const value = await job.run(isRecord(invocation.input) ? invocation.input : {}, handle, ctx);
|
|
351
|
+
return value === void 0 ? null : value;
|
|
352
|
+
};
|
|
353
|
+
/** One invocation: what a task or a job's slice returned (`null` for nothing), or the wire response a route answered. */
|
|
354
|
+
const invoke = async (definition, invocation) => {
|
|
355
|
+
const found = isRecord(definition) ? definition : {};
|
|
356
|
+
const ctx = contextOf(invocation);
|
|
357
|
+
if (invocation.kind === "job") return runJob(found, invocation, ctx);
|
|
358
|
+
if (invocation.kind === "task") {
|
|
359
|
+
const task = listOf(found.tasks).find((entry) => isRecord(entry) && `${String(entry.namespace)}.${String(entry.action)}` === invocation.name);
|
|
360
|
+
if (!isRecord(task) || !isCallable(task.run)) throw new Error(`This space's functions have no task "${String(invocation.name)}"`);
|
|
361
|
+
const value = await task.run(isRecord(invocation.params) ? invocation.params : {}, ctx);
|
|
362
|
+
return value === void 0 ? null : value;
|
|
363
|
+
}
|
|
364
|
+
const handler = (isRecord(found.routes) ? found.routes : {})[String(invocation.key)];
|
|
365
|
+
if (!isCallable(handler)) throw new Error(`This space's functions have no route "${String(invocation.key)}"`);
|
|
366
|
+
const request = requestOf(isRecord(invocation.request) ? invocation.request : {});
|
|
367
|
+
const wire = await wireOfResponse(await handler(request, {
|
|
368
|
+
...ctx,
|
|
369
|
+
params: invocation.params
|
|
370
|
+
}));
|
|
371
|
+
if (!wire) throw new Error(`Route "${String(invocation.key)}" answered something that is not a Response`);
|
|
372
|
+
return wire;
|
|
373
|
+
};
|
|
374
|
+
return {
|
|
375
|
+
invoke,
|
|
376
|
+
log
|
|
377
|
+
};
|
|
378
|
+
};
|
|
379
|
+
// src/runner/cpuMeter.ts
|
|
380
|
+
/**
|
|
381
|
+
* How far back the meter's share is read: the system counts a thread's CPU in its scheduler's ticks, a few ms each, so a
|
|
382
|
+
* look of 5 ms read 0 or 12 ms beside a smooth measure, and the lower bound of each look lost the lumps — eight spinners
|
|
383
|
+
* that took 25 s of CPU were charged 7. Over a quarter of a second the lumps even out, and it follows a change as soon.
|
|
384
|
+
*/
|
|
385
|
+
var SHARE_WINDOW_MS = 250;
|
|
386
|
+
/**
|
|
387
|
+
* The CPU the isolates' threads took, as the system counts it, in ms: the process's, every thread on a core, less its
|
|
388
|
+
* main thread's — making isolates, compiling bundles, speaking to the platform is the runner's work, and counted with
|
|
389
|
+
* theirs it let a running isolate be charged what V8 measured while the main thread was busy.
|
|
390
|
+
*/
|
|
391
|
+
var isolatesCpuMs = () => {
|
|
392
|
+
const all = process.cpuUsage();
|
|
393
|
+
const main = process.threadCpuUsage();
|
|
394
|
+
return (all.user + all.system - main.user - main.system) / 1e3;
|
|
395
|
+
};
|
|
396
|
+
/** The CPU the runner's main thread took, in ms: what its cores held that no isolate had. */
|
|
397
|
+
var mainThreadCpuMs = () => {
|
|
398
|
+
const main = process.threadCpuUsage();
|
|
399
|
+
return (main.user + main.system) / 1e3;
|
|
400
|
+
};
|
|
401
|
+
/**
|
|
402
|
+
* The CPU the isolates' threads took, shared out between the isolates that ran.
|
|
403
|
+
*
|
|
404
|
+
* V8 measures an isolate's CPU as the time it spent running JavaScript — on a core, or ready and waiting for one — so
|
|
405
|
+
* beside more threads than cores each is measured as if it had a core of its own: a 5 ms route was measured past its
|
|
406
|
+
* 100 ms limit under load, and a ceiling on how much a limit may grow for it let code that spun go on, or stopped light
|
|
407
|
+
* code, depending on the burst. Each look, what the isolates were measured at is scaled down, in proportion, to the
|
|
408
|
+
* most they can have taken together, by whichever bound is lower: what their threads took as the system counts it, and
|
|
409
|
+
* the cores for the time the look spans less what the main thread took of them — V8's collector and the runner's helper
|
|
410
|
+
* threads take CPU nobody is measured at, and on the threads' count alone a measure inflated in those moments went
|
|
411
|
+
* through whole. The cores are the container's quota (`cpuLimitCores`): over the window it holds every thread to it, and
|
|
412
|
+
* an isolate whose thread the main one took the core from — a thousand sockets under load — is measured by V8 as if it
|
|
413
|
+
* ran: on the machine's cores, a 5 ms route was charged past its 100 ms limit. Code that spins alone is charged all it
|
|
414
|
+
* took; code beside others, never the cores it waited for.
|
|
415
|
+
*/
|
|
416
|
+
var createCpuMeter = (everyMs, cores, readProcess = isolatesCpuMs, readMain = mainThreadCpuMs) => {
|
|
417
|
+
const live = /* @__PURE__ */ new Set();
|
|
418
|
+
let lastProcess = readProcess();
|
|
419
|
+
let lastMain = readMain();
|
|
420
|
+
let lastAt = Date.now();
|
|
421
|
+
let timer;
|
|
422
|
+
/** The last quarter second of looks: what the threads took, what the cores held, what the isolates were measured at. */
|
|
423
|
+
const window = [];
|
|
424
|
+
const look = () => {
|
|
425
|
+
const now = readProcess();
|
|
426
|
+
const spent = Math.max(0, now - lastProcess);
|
|
427
|
+
lastProcess = now;
|
|
428
|
+
const at = Date.now();
|
|
429
|
+
const main = readMain();
|
|
430
|
+
const capacity = Math.max(0, cores * Math.max(everyMs, at - lastAt) - Math.max(0, main - lastMain));
|
|
431
|
+
lastMain = main;
|
|
432
|
+
lastAt = at;
|
|
433
|
+
const slices = [...live].map((entry) => {
|
|
434
|
+
const read = entry.read();
|
|
435
|
+
const slice = Math.max(0, read - entry.last);
|
|
436
|
+
entry.last = read;
|
|
437
|
+
return {
|
|
438
|
+
entry,
|
|
439
|
+
slice
|
|
440
|
+
};
|
|
441
|
+
});
|
|
442
|
+
const measured = slices.reduce((total, { slice }) => total + slice, 0);
|
|
443
|
+
window.push({
|
|
444
|
+
at,
|
|
445
|
+
spent,
|
|
446
|
+
capacity,
|
|
447
|
+
measured
|
|
448
|
+
});
|
|
449
|
+
while (window.length > 1 && (window[0]?.at ?? at) < at - SHARE_WINDOW_MS) window.shift();
|
|
450
|
+
const sum = (key) => window.reduce((total, look) => total + look[key], 0);
|
|
451
|
+
const inWindow = sum("measured");
|
|
452
|
+
const share = inWindow > 0 ? Math.min(1, sum("spent") / inWindow, sum("capacity") / inWindow) : 1;
|
|
453
|
+
slices.forEach(({ entry, slice }) => {
|
|
454
|
+
entry.charged += slice * share;
|
|
455
|
+
});
|
|
456
|
+
};
|
|
457
|
+
return { meter: (read) => {
|
|
458
|
+
if (live.size === 0) {
|
|
459
|
+
lastProcess = readProcess();
|
|
460
|
+
lastMain = readMain();
|
|
461
|
+
lastAt = Date.now();
|
|
462
|
+
timer = setInterval(look, everyMs);
|
|
463
|
+
timer.unref();
|
|
464
|
+
}
|
|
465
|
+
const entry = {
|
|
466
|
+
read,
|
|
467
|
+
last: read(),
|
|
468
|
+
charged: 0
|
|
469
|
+
};
|
|
470
|
+
live.add(entry);
|
|
471
|
+
return {
|
|
472
|
+
charged: () => entry.charged,
|
|
473
|
+
end: () => {
|
|
474
|
+
if (!live.has(entry)) return;
|
|
475
|
+
look();
|
|
476
|
+
live.delete(entry);
|
|
477
|
+
if (live.size === 0 && timer) {
|
|
478
|
+
clearInterval(timer);
|
|
479
|
+
timer = void 0;
|
|
480
|
+
window.length = 0;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
} };
|
|
485
|
+
};
|
|
486
|
+
// src/runner/guest/bytes.ts
|
|
487
|
+
/**
|
|
488
|
+
* Text and bytes, as the guest reads them: UTF-8 both ways, base64, copies — and `TextEncoder`/`TextDecoder`.
|
|
489
|
+
*
|
|
490
|
+
* Printed into the isolate on its own, as the guest is (`isolate.ts`): it may use nothing but its parameters.
|
|
491
|
+
*/
|
|
492
|
+
var guestBytes = () => {
|
|
493
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
494
|
+
const encodeUtf8 = (text) => {
|
|
495
|
+
const out = [];
|
|
496
|
+
for (const char of text) {
|
|
497
|
+
let code = char.codePointAt(0) ?? 0;
|
|
498
|
+
if (code >= 55296 && code <= 57343) code = 65533;
|
|
499
|
+
if (code < 128) out.push(code);
|
|
500
|
+
else if (code < 2048) out.push(192 | code >> 6, 128 | code & 63);
|
|
501
|
+
else if (code < 65536) out.push(224 | code >> 12, 128 | code >> 6 & 63, 128 | code & 63);
|
|
502
|
+
else out.push(240 | code >> 18, 128 | code >> 12 & 63, 128 | code >> 6 & 63, 128 | code & 63);
|
|
503
|
+
}
|
|
504
|
+
return new Uint8Array(out);
|
|
505
|
+
};
|
|
506
|
+
/** UTF-8, with U+FFFD for every byte that does not belong to a well-formed sequence — what a web `TextDecoder` does. */
|
|
507
|
+
const decodeUtf8 = (bytes) => {
|
|
508
|
+
const points = [];
|
|
509
|
+
let text = "";
|
|
510
|
+
let index = 0;
|
|
511
|
+
const continuation = (at) => at < bytes.length && ((bytes[at] ?? 0) & 192) === 128;
|
|
512
|
+
while (index < bytes.length) {
|
|
513
|
+
const lead = bytes[index] ?? 0;
|
|
514
|
+
const length = lead < 128 ? 1 : lead >= 194 && lead < 224 ? 2 : lead >= 224 && lead < 240 ? 3 : lead >= 240 && lead < 245 ? 4 : 0;
|
|
515
|
+
let code = 65533;
|
|
516
|
+
let used = 1;
|
|
517
|
+
if (length === 1) code = lead;
|
|
518
|
+
else if (length > 1) {
|
|
519
|
+
let valid = true;
|
|
520
|
+
let value = lead & 255 >> length + 1;
|
|
521
|
+
for (let offset = 1; offset < length; offset++) {
|
|
522
|
+
if (!continuation(index + offset)) {
|
|
523
|
+
valid = false;
|
|
524
|
+
used = offset;
|
|
525
|
+
break;
|
|
526
|
+
}
|
|
527
|
+
value = value << 6 | (bytes[index + offset] ?? 0) & 63;
|
|
528
|
+
}
|
|
529
|
+
if (valid && value >= (length === 3 ? 2048 : length === 4 ? 65536 : 128) && value <= 1114111 && (value < 55296 || value > 57343)) {
|
|
530
|
+
code = value;
|
|
531
|
+
used = length;
|
|
532
|
+
} else if (valid) used = 1;
|
|
533
|
+
}
|
|
534
|
+
points.push(code);
|
|
535
|
+
index += used;
|
|
536
|
+
if (points.length >= 4096) {
|
|
537
|
+
text += String.fromCodePoint(...points);
|
|
538
|
+
points.length = 0;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return text + String.fromCodePoint(...points);
|
|
542
|
+
};
|
|
543
|
+
const bytesToBase64 = (bytes) => {
|
|
544
|
+
let binary = "";
|
|
545
|
+
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
|
|
546
|
+
return btoa(binary);
|
|
547
|
+
};
|
|
548
|
+
const base64ToBytes = (base64) => {
|
|
549
|
+
const binary = atob(base64);
|
|
550
|
+
const bytes = new Uint8Array(binary.length);
|
|
551
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
|
552
|
+
return bytes;
|
|
553
|
+
};
|
|
554
|
+
const copyBytes = (view) => {
|
|
555
|
+
const source = view instanceof ArrayBuffer ? new Uint8Array(view) : new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
|
556
|
+
const bytes = new Uint8Array(source.length);
|
|
557
|
+
bytes.set(source);
|
|
558
|
+
return bytes;
|
|
559
|
+
};
|
|
560
|
+
class GuestTextEncoder {
|
|
561
|
+
encoding = "utf-8";
|
|
562
|
+
encode(text = "") {
|
|
563
|
+
return encodeUtf8(typeof text === "string" ? text : String(text));
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
class GuestTextDecoder {
|
|
567
|
+
encoding = "utf-8";
|
|
568
|
+
constructor(label = "utf-8") {
|
|
569
|
+
if (![
|
|
570
|
+
"utf-8",
|
|
571
|
+
"utf8",
|
|
572
|
+
"unicode-1-1-utf-8"
|
|
573
|
+
].includes(label.toLowerCase())) throw new RangeError(`This runtime decodes UTF-8 only, not "${label}"`);
|
|
574
|
+
}
|
|
575
|
+
decode(input) {
|
|
576
|
+
if (!input) return "";
|
|
577
|
+
const text = decodeUtf8(copyBytes(input));
|
|
578
|
+
return text.startsWith("") ? text.slice(1) : text;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return {
|
|
582
|
+
isRecord,
|
|
583
|
+
encodeUtf8,
|
|
584
|
+
decodeUtf8,
|
|
585
|
+
bytesToBase64,
|
|
586
|
+
base64ToBytes,
|
|
587
|
+
copyBytes,
|
|
588
|
+
GuestTextEncoder,
|
|
589
|
+
GuestTextDecoder
|
|
590
|
+
};
|
|
591
|
+
};
|
|
592
|
+
// src/runner/guest/crypto.ts
|
|
593
|
+
/**
|
|
594
|
+
* `crypto`: random values from the runner's CSPRNG, and a `crypto.subtle` of digests, HMAC and PBKDF2 the runner computes.
|
|
595
|
+
*
|
|
596
|
+
* Printed into the isolate on its own, as the guest is (`isolate.ts`): it may use nothing but its parameters.
|
|
597
|
+
*/
|
|
598
|
+
var guestCrypto = (host, { isRecord, bytesToBase64, base64ToBytes, copyBytes }) => {
|
|
599
|
+
const getRandomValues = (array) => {
|
|
600
|
+
if (array.byteLength > 65536) throw new DOMException("At most 65536 bytes at a time", "QuotaExceededError");
|
|
601
|
+
new Uint8Array(array.buffer, array.byteOffset, array.byteLength).set(host.random(array.byteLength));
|
|
602
|
+
return array;
|
|
603
|
+
};
|
|
604
|
+
const randomUUID = () => {
|
|
605
|
+
const bytes = getRandomValues(/* @__PURE__ */ new Uint8Array(16));
|
|
606
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
607
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
608
|
+
const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
609
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
610
|
+
};
|
|
611
|
+
const HASHES = [
|
|
612
|
+
"SHA-1",
|
|
613
|
+
"SHA-256",
|
|
614
|
+
"SHA-384",
|
|
615
|
+
"SHA-512"
|
|
616
|
+
];
|
|
617
|
+
const nameOf = (algorithm) => {
|
|
618
|
+
const name = typeof algorithm === "string" ? algorithm : isRecord(algorithm) ? algorithm.name : void 0;
|
|
619
|
+
return typeof name === "string" ? name.toUpperCase() : "";
|
|
620
|
+
};
|
|
621
|
+
const hashOf = (algorithm) => {
|
|
622
|
+
const upper = nameOf(algorithm);
|
|
623
|
+
if (!HASHES.includes(upper)) throw new DOMException(`${upper || String(algorithm)} is not a supported hash (${HASHES.join(", ")})`, "NotSupportedError");
|
|
624
|
+
return upper;
|
|
625
|
+
};
|
|
626
|
+
/** An HMAC key's length when its algorithm names none: the hash's block, as Web Crypto has it. */
|
|
627
|
+
const blockBitsOf = (hash) => hash === "SHA-384" || hash === "SHA-512" ? 1024 : 512;
|
|
628
|
+
/**
|
|
629
|
+
* The two kinds of key this runtime's `crypto.subtle` makes: HMAC, what signing a webhook needs, and PBKDF2, a
|
|
630
|
+
* password to derive from — what keeping a password needs.
|
|
631
|
+
*/
|
|
632
|
+
class GuestCryptoKey {
|
|
633
|
+
type = "secret";
|
|
634
|
+
algorithm;
|
|
635
|
+
extractable;
|
|
636
|
+
usages;
|
|
637
|
+
raw;
|
|
638
|
+
constructor(raw, algorithm, extractable, usages) {
|
|
639
|
+
this.raw = raw;
|
|
640
|
+
this.algorithm = algorithm;
|
|
641
|
+
this.extractable = extractable;
|
|
642
|
+
this.usages = usages;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
const bytesOf = (data) => {
|
|
646
|
+
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) return copyBytes(data);
|
|
647
|
+
throw new TypeError("crypto.subtle takes bytes: an ArrayBuffer or a typed array");
|
|
648
|
+
};
|
|
649
|
+
const cryptoCall = async (message) => {
|
|
650
|
+
const answer = JSON.parse(await host.crypto(JSON.stringify(message)));
|
|
651
|
+
if (!isRecord(answer) || answer.ok !== true || typeof answer.value !== "string") throw new DOMException(isRecord(answer) && typeof answer.error === "string" ? answer.error : "The operation failed", "OperationError");
|
|
652
|
+
return base64ToBytes(answer.value);
|
|
653
|
+
};
|
|
654
|
+
const isKeyOf = (key, name) => key instanceof GuestCryptoKey && key.algorithm.name === name;
|
|
655
|
+
/** The key an operation was handed, when it is of the kind the operation takes and was imported for it. */
|
|
656
|
+
const keyFor = (key, name, usage) => {
|
|
657
|
+
if (!isKeyOf(key, name)) throw new DOMException(`${usage} takes a ${name} key, from crypto.subtle.importKey`, "InvalidAccessError");
|
|
658
|
+
if (!key.usages.includes(usage)) throw new DOMException(`The key was not imported for ${usage}`, "InvalidAccessError");
|
|
659
|
+
return key;
|
|
660
|
+
};
|
|
661
|
+
const hmacOf = (key, usage, data) => {
|
|
662
|
+
const { algorithm, raw } = keyFor(key, "HMAC", usage);
|
|
663
|
+
return cryptoCall({
|
|
664
|
+
op: "hmac",
|
|
665
|
+
hash: algorithm.hash.name,
|
|
666
|
+
key: bytesToBase64(raw),
|
|
667
|
+
data: bytesToBase64(bytesOf(data))
|
|
668
|
+
});
|
|
669
|
+
};
|
|
670
|
+
/** How many rounds and bits a derivation may take is the runner's to say: it is the one doing the work. */
|
|
671
|
+
const pbkdf2Of = (algorithm, baseKey, bits, usage) => {
|
|
672
|
+
if (!isRecord(algorithm) || nameOf(algorithm) !== "PBKDF2") throw new DOMException("This runtime derives with PBKDF2 only", "NotSupportedError");
|
|
673
|
+
const { raw } = keyFor(baseKey, "PBKDF2", usage);
|
|
674
|
+
if (typeof algorithm.iterations !== "number" || typeof bits !== "number") throw new TypeError("PBKDF2 takes { name, hash, salt, iterations } and a length in bits");
|
|
675
|
+
return cryptoCall({
|
|
676
|
+
op: "pbkdf2",
|
|
677
|
+
hash: hashOf(algorithm.hash),
|
|
678
|
+
key: bytesToBase64(raw),
|
|
679
|
+
salt: bytesToBase64(bytesOf(algorithm.salt)),
|
|
680
|
+
iterations: String(algorithm.iterations),
|
|
681
|
+
bits: String(bits)
|
|
682
|
+
});
|
|
683
|
+
};
|
|
684
|
+
/** The key `importKey` makes — thrown, not answered, when it is none this runtime has. */
|
|
685
|
+
const importedKey = (format, keyData, algorithm, extractable, usages) => {
|
|
686
|
+
const name = nameOf(algorithm);
|
|
687
|
+
if (format === "raw" && name === "HMAC" && isRecord(algorithm)) return new GuestCryptoKey(bytesOf(keyData), {
|
|
688
|
+
name,
|
|
689
|
+
hash: { name: hashOf(algorithm.hash) }
|
|
690
|
+
}, extractable, usages);
|
|
691
|
+
if (format === "raw" && name === "PBKDF2") {
|
|
692
|
+
if (extractable) throw new DOMException("A PBKDF2 key is never extractable", "SyntaxError");
|
|
693
|
+
return new GuestCryptoKey(bytesOf(keyData), { name }, false, usages);
|
|
694
|
+
}
|
|
695
|
+
throw new DOMException("This runtime imports raw keys for HMAC and PBKDF2 only (format \"raw\", { name: \"HMAC\", hash } or \"PBKDF2\")", "NotSupportedError");
|
|
696
|
+
};
|
|
697
|
+
return {
|
|
698
|
+
getRandomValues,
|
|
699
|
+
randomUUID,
|
|
700
|
+
subtle: {
|
|
701
|
+
digest: async (algorithm, data) => (await cryptoCall({
|
|
702
|
+
op: "digest",
|
|
703
|
+
hash: hashOf(algorithm),
|
|
704
|
+
data: bytesToBase64(bytesOf(data))
|
|
705
|
+
})).buffer,
|
|
706
|
+
importKey: (format, keyData, algorithm, extractable, usages) => new Promise((resolve) => {
|
|
707
|
+
resolve(importedKey(format, keyData, algorithm, extractable, usages));
|
|
708
|
+
}),
|
|
709
|
+
sign: async (_algorithm, key, data) => (await hmacOf(key, "sign", data)).buffer,
|
|
710
|
+
verify: async (_algorithm, key, signature, data) => {
|
|
711
|
+
const expected = await hmacOf(key, "verify", data);
|
|
712
|
+
const given = bytesOf(signature);
|
|
713
|
+
let difference = expected.length ^ given.length;
|
|
714
|
+
expected.forEach((byte, index) => {
|
|
715
|
+
difference |= byte ^ (given[index] ?? 0);
|
|
716
|
+
});
|
|
717
|
+
return difference === 0;
|
|
718
|
+
},
|
|
719
|
+
deriveBits: async (algorithm, baseKey, length) => (await pbkdf2Of(algorithm, baseKey, length, "deriveBits")).buffer,
|
|
720
|
+
/** Derives an HMAC key — the one other kind this runtime has. */
|
|
721
|
+
deriveKey: async (algorithm, baseKey, derivedKeyAlgorithm, extractable, usages) => {
|
|
722
|
+
if (!isRecord(derivedKeyAlgorithm) || nameOf(derivedKeyAlgorithm) !== "HMAC") throw new DOMException("This runtime derives HMAC keys only", "NotSupportedError");
|
|
723
|
+
const hash = hashOf(derivedKeyAlgorithm.hash);
|
|
724
|
+
const length = derivedKeyAlgorithm.length ?? blockBitsOf(hash);
|
|
725
|
+
const raw = await pbkdf2Of(algorithm, baseKey, length, "deriveKey");
|
|
726
|
+
return new GuestCryptoKey(raw, {
|
|
727
|
+
name: "HMAC",
|
|
728
|
+
hash: { name: hash }
|
|
729
|
+
}, extractable, usages);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
};
|
|
733
|
+
};
|
|
734
|
+
// src/runner/guest/events.ts
|
|
735
|
+
/**
|
|
736
|
+
* Events, abort and timers: `Event`, `EventTarget`, `AbortSignal`, `AbortController` and the timers, on the runner's clock.
|
|
737
|
+
*
|
|
738
|
+
* Printed into the isolate on its own, as the guest is (`isolate.ts`): it may use nothing but its parameters.
|
|
739
|
+
*/
|
|
740
|
+
var guestEvents = (host) => {
|
|
741
|
+
class GuestEvent {
|
|
742
|
+
type;
|
|
743
|
+
constructor(type) {
|
|
744
|
+
this.type = type;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Each target's listeners, kept out of the object the code holds — a WeakMap rather than a private field, so the
|
|
749
|
+
* part's type can be named outside it (`GuestEvents`).
|
|
750
|
+
*/
|
|
751
|
+
const listenersOf = /* @__PURE__ */ new WeakMap();
|
|
752
|
+
const listenersFor = (target) => {
|
|
753
|
+
const listeners = listenersOf.get(target) ?? /* @__PURE__ */ new Map();
|
|
754
|
+
listenersOf.set(target, listeners);
|
|
755
|
+
return listeners;
|
|
756
|
+
};
|
|
757
|
+
class GuestEventTarget {
|
|
758
|
+
addEventListener(type, listener, options) {
|
|
759
|
+
if (!listener) return;
|
|
760
|
+
const listeners = listenersFor(this).get(type) ?? /* @__PURE__ */ new Map();
|
|
761
|
+
listeners.set(listener, { once: typeof options === "object" && options.once === true });
|
|
762
|
+
listenersFor(this).set(type, listeners);
|
|
763
|
+
}
|
|
764
|
+
removeEventListener(type, listener) {
|
|
765
|
+
if (listener) listenersFor(this).get(type)?.delete(listener);
|
|
766
|
+
}
|
|
767
|
+
dispatchEvent(event) {
|
|
768
|
+
const listeners = listenersFor(this).get(event.type);
|
|
769
|
+
[...listeners ?? /* @__PURE__ */ new Map()].forEach(([listener, { once }]) => {
|
|
770
|
+
if (once) listeners?.delete(listener);
|
|
771
|
+
listener.call(this, event);
|
|
772
|
+
});
|
|
773
|
+
return true;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
const signals = /* @__PURE__ */ new WeakMap();
|
|
777
|
+
const CONSTRUCT = Symbol("AbortSignal");
|
|
778
|
+
class GuestAbortSignal extends GuestEventTarget {
|
|
779
|
+
onabort = null;
|
|
780
|
+
constructor(token) {
|
|
781
|
+
super();
|
|
782
|
+
if (token !== CONSTRUCT) throw new TypeError("Illegal constructor: an AbortSignal comes from an AbortController");
|
|
783
|
+
signals.set(this, {
|
|
784
|
+
aborted: false,
|
|
785
|
+
reason: void 0
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
get aborted() {
|
|
789
|
+
return signals.get(this)?.aborted ?? false;
|
|
790
|
+
}
|
|
791
|
+
get reason() {
|
|
792
|
+
return signals.get(this)?.reason;
|
|
793
|
+
}
|
|
794
|
+
throwIfAborted() {
|
|
795
|
+
if (this.aborted) throw this.reason;
|
|
796
|
+
}
|
|
797
|
+
static abort(reason) {
|
|
798
|
+
const signal = new GuestAbortSignal(CONSTRUCT);
|
|
799
|
+
abortSignal(signal, reason);
|
|
800
|
+
return signal;
|
|
801
|
+
}
|
|
802
|
+
static timeout(ms) {
|
|
803
|
+
const signal = new GuestAbortSignal(CONSTRUCT);
|
|
804
|
+
guestSetTimeout(() => {
|
|
805
|
+
abortSignal(signal, new DOMException("The operation timed out.", "TimeoutError"));
|
|
806
|
+
}, ms);
|
|
807
|
+
return signal;
|
|
808
|
+
}
|
|
809
|
+
static any(sources) {
|
|
810
|
+
const signal = new GuestAbortSignal(CONSTRUCT);
|
|
811
|
+
const aborted = sources.find((source) => source.aborted);
|
|
812
|
+
if (aborted) {
|
|
813
|
+
abortSignal(signal, aborted.reason);
|
|
814
|
+
return signal;
|
|
815
|
+
}
|
|
816
|
+
sources.forEach((source) => {
|
|
817
|
+
source.addEventListener("abort", () => abortSignal(signal, source.reason), { once: true });
|
|
818
|
+
});
|
|
819
|
+
return signal;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
const abortSignal = (signal, reason) => {
|
|
823
|
+
const state = signals.get(signal);
|
|
824
|
+
if (!state || state.aborted) return;
|
|
825
|
+
state.aborted = true;
|
|
826
|
+
state.reason = reason === void 0 ? new DOMException("This operation was aborted", "AbortError") : reason;
|
|
827
|
+
const event = new GuestEvent("abort");
|
|
828
|
+
signal.onabort?.call(signal, event);
|
|
829
|
+
signal.dispatchEvent(event);
|
|
830
|
+
};
|
|
831
|
+
class GuestAbortController {
|
|
832
|
+
signal = new GuestAbortSignal(CONSTRUCT);
|
|
833
|
+
abort(reason) {
|
|
834
|
+
abortSignal(this.signal, reason);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
const timers = /* @__PURE__ */ new Set();
|
|
838
|
+
let nextTimer = 1;
|
|
839
|
+
const delayOf = (ms) => Math.max(0, Number(ms) || 0);
|
|
840
|
+
const guestSetTimeout = (callback, ms, ...args) => {
|
|
841
|
+
const id = nextTimer++;
|
|
842
|
+
timers.add(id);
|
|
843
|
+
host.sleep(delayOf(ms)).then(() => {
|
|
844
|
+
if (timers.delete(id)) callback(...args);
|
|
845
|
+
});
|
|
846
|
+
return id;
|
|
847
|
+
};
|
|
848
|
+
const guestSetInterval = (callback, ms, ...args) => {
|
|
849
|
+
const id = nextTimer++;
|
|
850
|
+
timers.add(id);
|
|
851
|
+
const tick = () => {
|
|
852
|
+
host.sleep(Math.max(1, delayOf(ms))).then(() => {
|
|
853
|
+
if (timers.has(id)) {
|
|
854
|
+
callback(...args);
|
|
855
|
+
tick();
|
|
856
|
+
}
|
|
857
|
+
});
|
|
858
|
+
};
|
|
859
|
+
tick();
|
|
860
|
+
return id;
|
|
861
|
+
};
|
|
862
|
+
const clearTimer = (id) => {
|
|
863
|
+
if (id !== void 0) timers.delete(id);
|
|
864
|
+
};
|
|
865
|
+
return {
|
|
866
|
+
GuestEvent,
|
|
867
|
+
GuestEventTarget,
|
|
868
|
+
GuestAbortSignal,
|
|
869
|
+
GuestAbortController,
|
|
870
|
+
guestSetTimeout,
|
|
871
|
+
guestSetInterval,
|
|
872
|
+
clearTimer
|
|
873
|
+
};
|
|
874
|
+
};
|
|
875
|
+
// src/runner/guest/fetch.ts
|
|
876
|
+
/**
|
|
877
|
+
* Headers, bodies, requests and responses — and how a body crosses to the runner and back.
|
|
878
|
+
*
|
|
879
|
+
* Printed into the isolate on its own, as the guest is (`isolate.ts`): it may use nothing but its parameters.
|
|
880
|
+
*/
|
|
881
|
+
var guestFetch = ({ isRecord, encodeUtf8, decodeUtf8, bytesToBase64, base64ToBytes, copyBytes }, { GuestAbortController }) => {
|
|
882
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
883
|
+
/** A name as headers keep it — refused when it is no header name. */
|
|
884
|
+
const headerName = (name) => {
|
|
885
|
+
if (!TOKEN.test(name)) throw new TypeError(`"${name}" is not a valid header name`);
|
|
886
|
+
return name.toLowerCase();
|
|
887
|
+
};
|
|
888
|
+
/**
|
|
889
|
+
* Each `Headers`' values by name, kept out of the object the code holds — a WeakMap rather than a private field, so
|
|
890
|
+
* the part's type can be named outside it (`GuestFetch`).
|
|
891
|
+
*/
|
|
892
|
+
const headerValues = /* @__PURE__ */ new WeakMap();
|
|
893
|
+
const valuesOf = (headers) => {
|
|
894
|
+
const values = headerValues.get(headers) ?? /* @__PURE__ */ new Map();
|
|
895
|
+
headerValues.set(headers, values);
|
|
896
|
+
return values;
|
|
897
|
+
};
|
|
898
|
+
class GuestHeaders {
|
|
899
|
+
constructor(init) {
|
|
900
|
+
if (init instanceof GuestHeaders) init.forEach((value, name) => this.append(name, value));
|
|
901
|
+
else if (Array.isArray(init)) init.forEach(([name, value]) => this.append(name, value));
|
|
902
|
+
else if (init) Object.entries(init).forEach(([name, value]) => this.append(name, value));
|
|
903
|
+
}
|
|
904
|
+
append(name, value) {
|
|
905
|
+
const key = headerName(name);
|
|
906
|
+
valuesOf(this).set(key, [...valuesOf(this).get(key) ?? [], String(value).trim()]);
|
|
907
|
+
}
|
|
908
|
+
set(name, value) {
|
|
909
|
+
valuesOf(this).set(headerName(name), [String(value).trim()]);
|
|
910
|
+
}
|
|
911
|
+
get(name) {
|
|
912
|
+
return valuesOf(this).get(headerName(name))?.join(", ") ?? null;
|
|
913
|
+
}
|
|
914
|
+
getSetCookie() {
|
|
915
|
+
return [...valuesOf(this).get("set-cookie") ?? []];
|
|
916
|
+
}
|
|
917
|
+
has(name) {
|
|
918
|
+
return valuesOf(this).has(headerName(name));
|
|
919
|
+
}
|
|
920
|
+
delete(name) {
|
|
921
|
+
valuesOf(this).delete(headerName(name));
|
|
922
|
+
}
|
|
923
|
+
*entries() {
|
|
924
|
+
for (const name of [...valuesOf(this).keys()].sort()) if (name === "set-cookie") for (const value of valuesOf(this).get(name) ?? []) yield [name, value];
|
|
925
|
+
else yield [name, valuesOf(this).get(name)?.join(", ") ?? ""];
|
|
926
|
+
}
|
|
927
|
+
*keys() {
|
|
928
|
+
for (const [name] of this.entries()) yield name;
|
|
929
|
+
}
|
|
930
|
+
*values() {
|
|
931
|
+
for (const [, value] of this.entries()) yield value;
|
|
932
|
+
}
|
|
933
|
+
forEach(callback) {
|
|
934
|
+
for (const [name, value] of this.entries()) callback(value, name, this);
|
|
935
|
+
}
|
|
936
|
+
[Symbol.iterator]() {
|
|
937
|
+
return this.entries();
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
const sourceOf = (body, headers) => {
|
|
941
|
+
const typed = (type) => {
|
|
942
|
+
if (!headers.has("content-type")) headers.set("content-type", type);
|
|
943
|
+
};
|
|
944
|
+
if (body === null || body === void 0) return null;
|
|
945
|
+
if (typeof body === "string") {
|
|
946
|
+
typed("text/plain;charset=UTF-8");
|
|
947
|
+
return { text: body };
|
|
948
|
+
}
|
|
949
|
+
if (body instanceof URLSearchParams) {
|
|
950
|
+
typed("application/x-www-form-urlencoded;charset=UTF-8");
|
|
951
|
+
return { text: body.toString() };
|
|
952
|
+
}
|
|
953
|
+
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return { bytes: copyBytes(body) };
|
|
954
|
+
throw new TypeError("A body is a string, bytes or URLSearchParams — this runtime has no streams, Blob or FormData");
|
|
955
|
+
};
|
|
956
|
+
/** Each body's source and whether it was read, kept out of the objects the code holds. */
|
|
957
|
+
const bodies = /* @__PURE__ */ new WeakMap();
|
|
958
|
+
const take = (body) => {
|
|
959
|
+
const state = bodies.get(body);
|
|
960
|
+
if (!state) return null;
|
|
961
|
+
if (state.used) throw new TypeError("Body has already been read");
|
|
962
|
+
state.used = state.source !== null;
|
|
963
|
+
return state.source;
|
|
964
|
+
};
|
|
965
|
+
/** A body as it was written, to copy it: text stays text and bytes stay bytes. */
|
|
966
|
+
const peek = (body) => {
|
|
967
|
+
const source = bodies.get(body)?.source ?? null;
|
|
968
|
+
if (!source) return null;
|
|
969
|
+
return "text" in source ? source.text : source.bytes;
|
|
970
|
+
};
|
|
971
|
+
class GuestBody {
|
|
972
|
+
headers;
|
|
973
|
+
constructor(body, headers) {
|
|
974
|
+
this.headers = new GuestHeaders(headers);
|
|
975
|
+
bodies.set(this, {
|
|
976
|
+
source: sourceOf(body, this.headers),
|
|
977
|
+
used: false
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
get bodyUsed() {
|
|
981
|
+
return bodies.get(this)?.used ?? false;
|
|
982
|
+
}
|
|
983
|
+
get body() {
|
|
984
|
+
return null;
|
|
985
|
+
}
|
|
986
|
+
text() {
|
|
987
|
+
try {
|
|
988
|
+
const source = take(this);
|
|
989
|
+
if (!source) return Promise.resolve("");
|
|
990
|
+
return Promise.resolve("text" in source ? source.text : decodeUtf8(source.bytes));
|
|
991
|
+
} catch (error) {
|
|
992
|
+
return Promise.reject(error instanceof Error ? error : new TypeError(String(error)));
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
async json() {
|
|
996
|
+
return JSON.parse(await this.text());
|
|
997
|
+
}
|
|
998
|
+
bytes() {
|
|
999
|
+
try {
|
|
1000
|
+
const source = take(this);
|
|
1001
|
+
if (!source) return Promise.resolve(/* @__PURE__ */ new Uint8Array(0));
|
|
1002
|
+
return Promise.resolve("text" in source ? encodeUtf8(source.text) : copyBytes(source.bytes));
|
|
1003
|
+
} catch (error) {
|
|
1004
|
+
return Promise.reject(error instanceof Error ? error : new TypeError(String(error)));
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
async arrayBuffer() {
|
|
1008
|
+
return (await this.bytes()).buffer;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
const METHODS = [
|
|
1012
|
+
"DELETE",
|
|
1013
|
+
"GET",
|
|
1014
|
+
"HEAD",
|
|
1015
|
+
"OPTIONS",
|
|
1016
|
+
"POST",
|
|
1017
|
+
"PUT",
|
|
1018
|
+
"PATCH"
|
|
1019
|
+
];
|
|
1020
|
+
class GuestRequest extends GuestBody {
|
|
1021
|
+
url;
|
|
1022
|
+
method;
|
|
1023
|
+
signal;
|
|
1024
|
+
constructor(input, init = {}) {
|
|
1025
|
+
const from = input instanceof GuestRequest ? input : void 0;
|
|
1026
|
+
const method = init.method ?? from?.method ?? "GET";
|
|
1027
|
+
const upper = method.toUpperCase();
|
|
1028
|
+
const normal = METHODS.includes(upper) ? upper : method;
|
|
1029
|
+
if ((normal === "GET" || normal === "HEAD") && init.body !== void 0 && init.body !== null) throw new TypeError(`A ${normal} request has no body`);
|
|
1030
|
+
super(init.body, init.headers ?? from?.headers);
|
|
1031
|
+
this.url = new URL(input instanceof GuestRequest ? input.url : input).href;
|
|
1032
|
+
this.method = normal;
|
|
1033
|
+
this.signal = init.signal ?? from?.signal ?? new GuestAbortController().signal;
|
|
1034
|
+
}
|
|
1035
|
+
clone() {
|
|
1036
|
+
return new GuestRequest(this.url, {
|
|
1037
|
+
method: this.method,
|
|
1038
|
+
headers: this.headers,
|
|
1039
|
+
body: peek(this),
|
|
1040
|
+
signal: this.signal
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
class GuestResponse extends GuestBody {
|
|
1045
|
+
status;
|
|
1046
|
+
statusText;
|
|
1047
|
+
type = "default";
|
|
1048
|
+
url = "";
|
|
1049
|
+
redirected = false;
|
|
1050
|
+
constructor(body, init = {}) {
|
|
1051
|
+
super(body, init.headers);
|
|
1052
|
+
const status = init.status ?? 200;
|
|
1053
|
+
if (!Number.isInteger(status) || status < 200 || status > 599) throw new RangeError(`A response status is 200–599, not ${String(status)}`);
|
|
1054
|
+
this.status = status;
|
|
1055
|
+
this.statusText = init.statusText ?? "";
|
|
1056
|
+
}
|
|
1057
|
+
get ok() {
|
|
1058
|
+
return this.status >= 200 && this.status < 300;
|
|
1059
|
+
}
|
|
1060
|
+
clone() {
|
|
1061
|
+
return new GuestResponse(peek(this), {
|
|
1062
|
+
status: this.status,
|
|
1063
|
+
statusText: this.statusText,
|
|
1064
|
+
headers: this.headers
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
static json(data, init = {}) {
|
|
1068
|
+
const headers = new GuestHeaders(init.headers);
|
|
1069
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
1070
|
+
return new GuestResponse(JSON.stringify(data), {
|
|
1071
|
+
...init,
|
|
1072
|
+
headers
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
static redirect(url, status = 302) {
|
|
1076
|
+
if (![
|
|
1077
|
+
301,
|
|
1078
|
+
302,
|
|
1079
|
+
303,
|
|
1080
|
+
307,
|
|
1081
|
+
308
|
|
1082
|
+
].includes(status)) throw new RangeError(`${String(status)} is not a redirect status`);
|
|
1083
|
+
return new GuestResponse(null, {
|
|
1084
|
+
status,
|
|
1085
|
+
headers: { location: new URL(String(url)).href }
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
/** Text back as text and bytes as base64: what the code wrote crosses unchanged, and nothing is decided from its type. */
|
|
1090
|
+
const wireOf = (body) => {
|
|
1091
|
+
const source = take(body);
|
|
1092
|
+
if (!source) return null;
|
|
1093
|
+
return "text" in source ? { text: source.text } : { base64: bytesToBase64(source.bytes) };
|
|
1094
|
+
};
|
|
1095
|
+
const headerPairs = (value) => Array.isArray(value) ? value.flatMap((pair) => Array.isArray(pair) && typeof pair[0] === "string" && typeof pair[1] === "string" ? [[pair[0], pair[1]]] : []) : [];
|
|
1096
|
+
const bodyOfWire = (body) => {
|
|
1097
|
+
if (!isRecord(body)) return null;
|
|
1098
|
+
if (typeof body.text === "string") return body.text;
|
|
1099
|
+
return typeof body.base64 === "string" ? base64ToBytes(body.base64) : null;
|
|
1100
|
+
};
|
|
1101
|
+
return {
|
|
1102
|
+
GuestHeaders,
|
|
1103
|
+
GuestRequest,
|
|
1104
|
+
GuestResponse,
|
|
1105
|
+
wireOf,
|
|
1106
|
+
headerPairs,
|
|
1107
|
+
bodyOfWire
|
|
1108
|
+
};
|
|
1109
|
+
};
|
|
1110
|
+
// src/runner/guest/install.ts
|
|
1111
|
+
/**
|
|
1112
|
+
* The runtime a space's code finds in an isolate: the web APIs a bare V8 lacks (`Headers`, `Request`, `Response`,
|
|
1113
|
+
* `TextEncoder`, `AbortSignal`, timers, `crypto`) and the `ctx` its functions are handed.
|
|
1114
|
+
*
|
|
1115
|
+
* It is installed by PRINTING this function into the isolate (`installGuest.toString()`), after the prelude that brings
|
|
1116
|
+
* `URL`, `atob`, `structuredClone` and `DOMException` — and after its web APIs, each part printed the same way and
|
|
1117
|
+
* handed in built (`parts`). So none of them may use anything from outside its own body — no import, no helper beside
|
|
1118
|
+
* it — and all they have of the runner is `host`, the functions in `shared` and the parts before them. Streams are not
|
|
1119
|
+
* provided: a body is text or bytes.
|
|
1120
|
+
*/
|
|
1121
|
+
var installGuest = (scope, host, shared, { bytes, events, fetch, crypto }) => {
|
|
1122
|
+
const { isRecord, GuestTextEncoder, GuestTextDecoder } = bytes;
|
|
1123
|
+
const { GuestEvent, GuestEventTarget, GuestAbortSignal, GuestAbortController, guestSetTimeout, guestSetInterval, clearTimer } = events;
|
|
1124
|
+
const { GuestHeaders, GuestRequest, GuestResponse, wireOf, headerPairs, bodyOfWire } = fetch;
|
|
1125
|
+
const { getRandomValues, randomUUID, subtle } = crypto;
|
|
1126
|
+
/**
|
|
1127
|
+
* A refusal: what the code threw to tell whoever asked — a wrong password, a full board — rather than a fault. It is
|
|
1128
|
+
* `ActionRefusal` from `@plitzi/sdk-runtime`, known here by its name: the bundle carries its own copy of the
|
|
1129
|
+
* class, printed from the platform's (`build.ts`).
|
|
1130
|
+
*/
|
|
1131
|
+
const REFUSAL = "ActionRefusal";
|
|
1132
|
+
const isRefusal = (error) => error instanceof Error && error.name === REFUSAL;
|
|
1133
|
+
const refusal = (message, code) => Object.assign(new Error(message), { name: REFUSAL }, code === void 0 ? {} : { code });
|
|
1134
|
+
const call = async (message) => {
|
|
1135
|
+
const answer = JSON.parse(await host.call(JSON.stringify(message)));
|
|
1136
|
+
if (isRecord(answer) && answer.ok === true) return answer.value;
|
|
1137
|
+
const said = isRecord(answer) && typeof answer.error === "string" ? answer.error : "The platform refused the call";
|
|
1138
|
+
if (isRecord(answer) && answer.refused === true) throw refusal(said, typeof answer.code === "string" ? answer.code : void 0);
|
|
1139
|
+
throw new Error(said);
|
|
1140
|
+
};
|
|
1141
|
+
const run = new GuestAbortController();
|
|
1142
|
+
const driver = shared.createFunctionsDriver({
|
|
1143
|
+
call,
|
|
1144
|
+
signal: run.signal,
|
|
1145
|
+
responseOf: (wire) => new GuestResponse(bodyOfWire(wire.body), {
|
|
1146
|
+
status: typeof wire.status === "number" ? wire.status : 502,
|
|
1147
|
+
statusText: typeof wire.statusText === "string" ? wire.statusText : "",
|
|
1148
|
+
headers: headerPairs(wire.headers)
|
|
1149
|
+
}),
|
|
1150
|
+
requestOf: (wire) => new GuestRequest(String(wire.url), {
|
|
1151
|
+
method: String(wire.method),
|
|
1152
|
+
headers: headerPairs(wire.headers),
|
|
1153
|
+
body: wire.method === "GET" || wire.method === "HEAD" ? null : bodyOfWire(wire.body),
|
|
1154
|
+
signal: run.signal
|
|
1155
|
+
}),
|
|
1156
|
+
wireOfResponse: (response) => Promise.resolve(response instanceof GuestResponse ? {
|
|
1157
|
+
status: response.status,
|
|
1158
|
+
statusText: response.statusText,
|
|
1159
|
+
headers: [...response.headers],
|
|
1160
|
+
body: wireOf(response)
|
|
1161
|
+
} : void 0),
|
|
1162
|
+
changeKv: shared.changeKv,
|
|
1163
|
+
changeListEntry: shared.changeListEntry,
|
|
1164
|
+
refusal
|
|
1165
|
+
});
|
|
1166
|
+
const { log } = driver;
|
|
1167
|
+
const refuseFetch = () => Promise.reject(/* @__PURE__ */ new TypeError("Functions reach the network through ctx.fetch, which knows the hosts they may reach"));
|
|
1168
|
+
Object.assign(scope, {
|
|
1169
|
+
TextEncoder: GuestTextEncoder,
|
|
1170
|
+
TextDecoder: GuestTextDecoder,
|
|
1171
|
+
Event: GuestEvent,
|
|
1172
|
+
EventTarget: GuestEventTarget,
|
|
1173
|
+
AbortSignal: GuestAbortSignal,
|
|
1174
|
+
AbortController: GuestAbortController,
|
|
1175
|
+
Headers: GuestHeaders,
|
|
1176
|
+
Request: GuestRequest,
|
|
1177
|
+
Response: GuestResponse,
|
|
1178
|
+
setTimeout: guestSetTimeout,
|
|
1179
|
+
clearTimeout: clearTimer,
|
|
1180
|
+
setInterval: guestSetInterval,
|
|
1181
|
+
clearInterval: clearTimer,
|
|
1182
|
+
queueMicrotask: (callback) => {
|
|
1183
|
+
Promise.resolve().then(callback);
|
|
1184
|
+
},
|
|
1185
|
+
crypto: {
|
|
1186
|
+
getRandomValues,
|
|
1187
|
+
randomUUID,
|
|
1188
|
+
subtle
|
|
1189
|
+
},
|
|
1190
|
+
console: {
|
|
1191
|
+
log,
|
|
1192
|
+
info: log,
|
|
1193
|
+
warn: log,
|
|
1194
|
+
error: log,
|
|
1195
|
+
debug: log
|
|
1196
|
+
},
|
|
1197
|
+
fetch: refuseFetch
|
|
1198
|
+
});
|
|
1199
|
+
const describe = (definition) => JSON.stringify({
|
|
1200
|
+
ok: true,
|
|
1201
|
+
value: shared.describeFunctions(definition)
|
|
1202
|
+
});
|
|
1203
|
+
return {
|
|
1204
|
+
describe,
|
|
1205
|
+
invoke: async (definition, invocationText) => {
|
|
1206
|
+
let answer;
|
|
1207
|
+
try {
|
|
1208
|
+
const invocation = JSON.parse(invocationText);
|
|
1209
|
+
answer = {
|
|
1210
|
+
ok: true,
|
|
1211
|
+
value: await driver.invoke(definition, isRecord(invocation) ? invocation : {})
|
|
1212
|
+
};
|
|
1213
|
+
} catch (error) {
|
|
1214
|
+
answer = {
|
|
1215
|
+
ok: false,
|
|
1216
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1217
|
+
...isRefusal(error) ? { refused: true } : {}
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
try {
|
|
1221
|
+
return JSON.stringify(answer);
|
|
1222
|
+
} catch (error) {
|
|
1223
|
+
return JSON.stringify({
|
|
1224
|
+
ok: false,
|
|
1225
|
+
error: `What the function answered is not JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
},
|
|
1229
|
+
abort: (reason) => {
|
|
1230
|
+
run.abort(new DOMException(reason, "AbortError"));
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
};
|
|
1234
|
+
// src/runner/prelude.ts
|
|
1235
|
+
/**
|
|
1236
|
+
* The web APIs a bare V8 lacks that are the spec's to get right rather than ours: `URL`, `URLSearchParams`, `atob`,
|
|
1237
|
+
* `btoa`, `structuredClone`, `DOMException` — core-js's, bundled into one script every isolate starts with. What is left
|
|
1238
|
+
* (`Headers`, `Request`, `Response`, timers, `crypto`, `ctx`) is the guest's, because each of those is a call to the
|
|
1239
|
+
* runner.
|
|
1240
|
+
*/
|
|
1241
|
+
var POLYFILLS = [
|
|
1242
|
+
"core-js/actual/dom-exception",
|
|
1243
|
+
"core-js/actual/url",
|
|
1244
|
+
"core-js/actual/url-search-params",
|
|
1245
|
+
"core-js/actual/structured-clone",
|
|
1246
|
+
"core-js/actual/atob",
|
|
1247
|
+
"core-js/actual/btoa"
|
|
1248
|
+
];
|
|
1249
|
+
/** Where the package's build keeps the prelude it made (`scripts/prelude.mjs`), from the package's root. */
|
|
1250
|
+
var BUILT_PRELUDE = "dist/prelude.js";
|
|
1251
|
+
/**
|
|
1252
|
+
* The prelude, built from core-js with esbuild: what the package's build writes to {@link BUILT_PRELUDE}, and what a
|
|
1253
|
+
* process running this package's sources (its tests, the workspace's servers) makes for itself. Neither core-js nor
|
|
1254
|
+
* esbuild is a runner's to install.
|
|
1255
|
+
*/
|
|
1256
|
+
var buildPrelude = async () => {
|
|
1257
|
+
const require = createRequire(import.meta.url);
|
|
1258
|
+
let entries;
|
|
1259
|
+
try {
|
|
1260
|
+
entries = POLYFILLS.map((entry) => require.resolve(entry));
|
|
1261
|
+
} catch {
|
|
1262
|
+
throw new Error("Building the functions prelude needs core-js@3 installed beside @plitzi/sdk-runtime");
|
|
1263
|
+
}
|
|
1264
|
+
const { esbuildBuild } = await import("@plitzi/sdk-kernel/build");
|
|
1265
|
+
return (await esbuildBuild({
|
|
1266
|
+
stdin: {
|
|
1267
|
+
contents: entries.map((entry) => `import ${JSON.stringify(entry)};`).join("\n"),
|
|
1268
|
+
loader: "js",
|
|
1269
|
+
resolveDir: path.dirname(fileURLToPath(import.meta.url))
|
|
1270
|
+
},
|
|
1271
|
+
bundle: true,
|
|
1272
|
+
write: false,
|
|
1273
|
+
format: "iife",
|
|
1274
|
+
platform: "browser",
|
|
1275
|
+
target: "es2022",
|
|
1276
|
+
minify: true,
|
|
1277
|
+
logLevel: "silent"
|
|
1278
|
+
})).outputFiles[0]?.text ?? "";
|
|
1279
|
+
};
|
|
1280
|
+
/** This package's root: the nearest `package.json` above this module that names it — under `src` or under `dist`. */
|
|
1281
|
+
var packageRoot = () => {
|
|
1282
|
+
for (let dir = path.dirname(fileURLToPath(import.meta.url)); dir !== path.dirname(dir); dir = path.dirname(dir)) try {
|
|
1283
|
+
const { name } = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf-8"));
|
|
1284
|
+
if (name === "@plitzi/sdk-runtime") return dir;
|
|
1285
|
+
} catch {}
|
|
1286
|
+
throw new Error("@plitzi/sdk-runtime cannot find its own package.json, where its built prelude is kept");
|
|
1287
|
+
};
|
|
1288
|
+
/**
|
|
1289
|
+
* The prelude as this process has it: from its sources, built now — so a change to the polyfills is never hidden by an
|
|
1290
|
+
* old build; from the package's build, the file it shipped with, which it refuses to run without.
|
|
1291
|
+
*/
|
|
1292
|
+
var loadPrelude = () => {
|
|
1293
|
+
if (import.meta.url.endsWith(".ts")) return buildPrelude();
|
|
1294
|
+
const file = path.join(packageRoot(), BUILT_PRELUDE);
|
|
1295
|
+
try {
|
|
1296
|
+
return Promise.resolve(readFileSync(file, "utf-8"));
|
|
1297
|
+
} catch {
|
|
1298
|
+
return Promise.reject(/* @__PURE__ */ new Error(`@plitzi/sdk-runtime is missing ${BUILT_PRELUDE}, which its build writes: reinstall it, or build it`));
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
var prelude;
|
|
1302
|
+
/** The prelude's source, read or built on first use and the same for every isolate this process makes. */
|
|
1303
|
+
var guestPrelude = () => {
|
|
1304
|
+
prelude ??= loadPrelude();
|
|
1305
|
+
return prelude;
|
|
1306
|
+
};
|
|
1307
|
+
/**
|
|
1308
|
+
* Turns at running JavaScript, handed out in the order they were asked for: as many running at once as the runner has
|
|
1309
|
+
* cores — what keeps them from fighting for its CPU. A turn held past a slice no longer counts against them while others
|
|
1310
|
+
* wait: a long run shares the CPU with the next, as a scheduler would, rather than holding every other isolate up. Long
|
|
1311
|
+
* runs all at once are the CPU truly short, and the service's own CPU gate turns new invocations away to another runner.
|
|
1312
|
+
*/
|
|
1313
|
+
var createTurns = (size) => {
|
|
1314
|
+
const held = /* @__PURE__ */ new Map();
|
|
1315
|
+
const queue = [];
|
|
1316
|
+
let next = 0;
|
|
1317
|
+
let timer;
|
|
1318
|
+
/** The turns held within their slice: what the next one waits for. */
|
|
1319
|
+
const fresh = (now) => [...held.values()].filter((since) => now - since < 20).length;
|
|
1320
|
+
const grant = () => {
|
|
1321
|
+
const id = next++;
|
|
1322
|
+
held.set(id, Date.now());
|
|
1323
|
+
return id;
|
|
1324
|
+
};
|
|
1325
|
+
const serve = () => {
|
|
1326
|
+
const now = Date.now();
|
|
1327
|
+
while (queue.length > 0 && fresh(now) < size) queue.shift()?.(grant());
|
|
1328
|
+
if (queue.length === 0 && timer) {
|
|
1329
|
+
clearInterval(timer);
|
|
1330
|
+
timer = void 0;
|
|
1331
|
+
} else if (queue.length > 0 && !timer) timer = setInterval(serve, 5);
|
|
1332
|
+
};
|
|
1333
|
+
return {
|
|
1334
|
+
take: async () => {
|
|
1335
|
+
if (queue.length === 0 && held.size < size) return grant();
|
|
1336
|
+
const turn = new Promise((resolve) => queue.push(resolve));
|
|
1337
|
+
serve();
|
|
1338
|
+
return turn;
|
|
1339
|
+
},
|
|
1340
|
+
give: (id) => {
|
|
1341
|
+
held.delete(id);
|
|
1342
|
+
serve();
|
|
1343
|
+
}
|
|
1344
|
+
};
|
|
1345
|
+
};
|
|
1346
|
+
// src/runner/isolate.ts
|
|
1347
|
+
/** Why a runner gave an invocation back that was within its own memory: the runner's, never the code's. */
|
|
1348
|
+
var SHED_SAID = "The functions runner ran short of memory and gave this invocation back before it took the whole runner down: another runner takes it";
|
|
1349
|
+
/** What reading a bundle's declaration may spend: its top level runs, and nothing else. */
|
|
1350
|
+
var DESCRIBE_LIMITS = {
|
|
1351
|
+
cpuMs: 1e3,
|
|
1352
|
+
wallMs: 5e3,
|
|
1353
|
+
memoryMb: 64,
|
|
1354
|
+
outputBytes: 1e6,
|
|
1355
|
+
calls: 100
|
|
1356
|
+
};
|
|
1357
|
+
/**
|
|
1358
|
+
* What a bundle's top level can call while it is read: only the console, since `ctx` exists only in an invocation — and
|
|
1359
|
+
* a line logged while loading is nobody's to read.
|
|
1360
|
+
*/
|
|
1361
|
+
var describeAnswer = (call) => typeof call === "object" && call !== null && "op" in call && call.op === "log" ? Promise.resolve(void 0) : Promise.reject(/* @__PURE__ */ new Error("Nothing is reachable while a bundle is read"));
|
|
1362
|
+
var WATCHDOG_MS = 5;
|
|
1363
|
+
/** How much of an invocation's time is the runner's before the platform is told, so its wait for the answer grows. */
|
|
1364
|
+
var TELL_WAITED_MS = 100;
|
|
1365
|
+
/**
|
|
1366
|
+
* What isolated-vm throws when a `timeout` it was given runs out. Its timeout is wall time while the isolate runs, not
|
|
1367
|
+
* CPU: a runner whose isolates share its CPU stretched a 5 ms route past a 100 ms "CPU limit" under load. So it is given
|
|
1368
|
+
* the wall limit, a backstop; the CPU limit is the watchdog's, which reads the isolate's share of the process's CPU
|
|
1369
|
+
* (`createCpuMeter`).
|
|
1370
|
+
*/
|
|
1371
|
+
var ISOLATE_TIMEOUT = "Script execution timed out.";
|
|
1372
|
+
/** How long code that listens to `ctx.signal` gets to stop by itself before the isolate is disposed under it. */
|
|
1373
|
+
var ABORT_GRACE_MS = 50;
|
|
1374
|
+
var NO_NODE_SNAPSHOT = "--no-node-snapshot";
|
|
1375
|
+
/**
|
|
1376
|
+
* Since Node 20 the process starts from Node's own V8 snapshot, and isolated-vm's isolates crash beside it — not always,
|
|
1377
|
+
* which is why this refuses up front rather than letting a process run until the one invocation that brings it down.
|
|
1378
|
+
*/
|
|
1379
|
+
var nodeSnapshotOff = () => Number(process.versions.node.split(".")[0]) < 20 || process.execArgv.includes(NO_NODE_SNAPSHOT) || (process.env.NODE_OPTIONS ?? "").split(/\s+/).includes(NO_NODE_SNAPSHOT);
|
|
1380
|
+
var loadIvm = async () => {
|
|
1381
|
+
if (!nodeSnapshotOff()) throw new Error(`Running space functions in isolates needs Node started with ${NO_NODE_SNAPSHOT} (e.g. NODE_OPTIONS=${NO_NODE_SNAPSHOT}): isolated-vm crashes beside Node's startup snapshot`);
|
|
1382
|
+
try {
|
|
1383
|
+
return (await import("isolated-vm")).default;
|
|
1384
|
+
} catch {
|
|
1385
|
+
throw new Error("Running space functions in isolates needs isolated-vm installed beside @plitzi/sdk-server");
|
|
1386
|
+
}
|
|
1387
|
+
};
|
|
1388
|
+
/**
|
|
1389
|
+
* The code cache a compile produced. isolated-vm sets it on the compiled script or module, and its declarations leave
|
|
1390
|
+
* it out — so it is looked for rather than assumed.
|
|
1391
|
+
*/
|
|
1392
|
+
var cachedDataOf = (ivm, compiled) => "cachedData" in compiled && compiled.cachedData instanceof ivm.ExternalCopy ? compiled.cachedData : void 0;
|
|
1393
|
+
var messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
1394
|
+
/** Past its memory: how much, and the size to ask for instead — the one thing its author can change. */
|
|
1395
|
+
var memoryStopMessage = (memoryMb) => {
|
|
1396
|
+
const size = functionSizeOfMemory(memoryMb);
|
|
1397
|
+
const larger = size ? largerFunctionSize(size) : void 0;
|
|
1398
|
+
const ran = size ? ` (a ${size} task)` : "";
|
|
1399
|
+
return larger ? `Went over its ${String(memoryMb)} MB of memory${ran}: a task that needs more asks to be larger in its limits ({ size: '${larger}' }), as far as its plan allows` : `Went over its ${String(memoryMb)} MB of memory${ran}, the most a task runs with: hold less of it at once`;
|
|
1400
|
+
};
|
|
1401
|
+
var stopMessage = (reason, limits) => {
|
|
1402
|
+
switch (reason) {
|
|
1403
|
+
case "cpu": return `Stopped after ${String(limits.cpuMs)} ms of CPU`;
|
|
1404
|
+
case "wall": return `Did not finish within ${String(limits.wallMs)} ms`;
|
|
1405
|
+
case "memory": return memoryStopMessage(limits.memoryMb);
|
|
1406
|
+
case "output": return `Answered more than the ${String(limits.outputBytes)} bytes it may`;
|
|
1407
|
+
case "calls": return `Made more than the ${String(limits.calls)} calls to the platform it may`;
|
|
1408
|
+
case "aborted": return "The run was aborted";
|
|
1409
|
+
}
|
|
1410
|
+
};
|
|
1411
|
+
/**
|
|
1412
|
+
* The most a PBKDF2 derivation may ask for. The runner does the work, outside the isolate's clock, so each is bounded
|
|
1413
|
+
* here and its time is charged to the run's CPU: a million rounds is past any password guidance, and 1024 bits past
|
|
1414
|
+
* any key.
|
|
1415
|
+
*/
|
|
1416
|
+
var PBKDF2_MAX_ITERATIONS = 1e6;
|
|
1417
|
+
var PBKDF2_MAX_BITS = 1024;
|
|
1418
|
+
var derive = promisify(pbkdf2);
|
|
1419
|
+
var cryptoField = (request, name) => {
|
|
1420
|
+
const value = request[name];
|
|
1421
|
+
if (typeof value !== "string") throw new Error(`The operation has no ${name}`);
|
|
1422
|
+
return value;
|
|
1423
|
+
};
|
|
1424
|
+
var boundedInteger = (text, what, max) => {
|
|
1425
|
+
const value = Number(text);
|
|
1426
|
+
if (!Number.isInteger(value) || value < 1 || value > max) throw new Error(`${what} is a whole number from 1 to ${String(max)}`);
|
|
1427
|
+
return value;
|
|
1428
|
+
};
|
|
1429
|
+
/**
|
|
1430
|
+
* The `crypto.subtle` a guest cannot do by itself, done with the runner's own: digests, HMAC and PBKDF2. A derivation
|
|
1431
|
+
* is the one that costs, and `charge` is handed what it took.
|
|
1432
|
+
*/
|
|
1433
|
+
var cryptoAnswer = async (message, charge) => {
|
|
1434
|
+
try {
|
|
1435
|
+
const request = JSON.parse(message);
|
|
1436
|
+
if (typeof request !== "object" || request === null || Array.isArray(request)) throw new Error("Not a crypto operation");
|
|
1437
|
+
const fields = { ...request };
|
|
1438
|
+
const hash = cryptoField(fields, "hash").replace("-", "").toLowerCase();
|
|
1439
|
+
const bytes = (name) => Buffer.from(cryptoField(fields, name), "base64");
|
|
1440
|
+
const op = cryptoField(fields, "op");
|
|
1441
|
+
if (op === "pbkdf2") {
|
|
1442
|
+
const iterations = boundedInteger(cryptoField(fields, "iterations"), "PBKDF2 iterations", PBKDF2_MAX_ITERATIONS);
|
|
1443
|
+
const bits = boundedInteger(cryptoField(fields, "bits"), "A PBKDF2 length in bits", PBKDF2_MAX_BITS);
|
|
1444
|
+
if (bits % 8 !== 0) throw new Error("A PBKDF2 length is a multiple of 8 bits");
|
|
1445
|
+
const started = performance.now();
|
|
1446
|
+
const derived = await derive(bytes("key"), bytes("salt"), iterations, bits / 8, hash);
|
|
1447
|
+
charge(performance.now() - started);
|
|
1448
|
+
return JSON.stringify({
|
|
1449
|
+
ok: true,
|
|
1450
|
+
value: derived.toString("base64")
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
if (op !== "hmac" && op !== "digest") throw new Error(`${op} is not a crypto operation`);
|
|
1454
|
+
const digest = op === "hmac" ? createHmac(hash, bytes("key")).update(bytes("data")).digest() : createHash(hash).update(bytes("data")).digest();
|
|
1455
|
+
return JSON.stringify({
|
|
1456
|
+
ok: true,
|
|
1457
|
+
value: digest.toString("base64")
|
|
1458
|
+
});
|
|
1459
|
+
} catch (error) {
|
|
1460
|
+
return JSON.stringify({
|
|
1461
|
+
ok: false,
|
|
1462
|
+
error: messageOf(error)
|
|
1463
|
+
});
|
|
1464
|
+
}
|
|
1465
|
+
};
|
|
1466
|
+
/**
|
|
1467
|
+
* Sets the guest up in a fresh context: the runner's four calls, taken off the global the moment they are captured,
|
|
1468
|
+
* and the guest printed from its own source, its web APIs first, a part at a time — with the platform's functions it runs
|
|
1469
|
+
* as they are (`GuestShared`),
|
|
1470
|
+
* printed from theirs. Answers the driver.
|
|
1471
|
+
*/
|
|
1472
|
+
var BOOTSTRAP = `(() => {
|
|
1473
|
+
const refs = { call: __plitziCall, sleep: __plitziSleep, random: __plitziRandom, crypto: __plitziCrypto };
|
|
1474
|
+
delete globalThis.__plitziCall;
|
|
1475
|
+
delete globalThis.__plitziSleep;
|
|
1476
|
+
delete globalThis.__plitziRandom;
|
|
1477
|
+
delete globalThis.__plitziCrypto;
|
|
1478
|
+
const transfer = { arguments: { copy: true }, result: { promise: true, copy: true } };
|
|
1479
|
+
const host = {
|
|
1480
|
+
call: message => refs.call.apply(undefined, [message], transfer),
|
|
1481
|
+
sleep: ms => refs.sleep.apply(undefined, [ms], transfer),
|
|
1482
|
+
random: length => refs.random(length),
|
|
1483
|
+
crypto: message => refs.crypto.apply(undefined, [message], transfer)
|
|
1484
|
+
};
|
|
1485
|
+
const bytes = (${guestBytes.toString()})();
|
|
1486
|
+
const events = (${guestEvents.toString()})(host);
|
|
1487
|
+
const parts = {
|
|
1488
|
+
bytes,
|
|
1489
|
+
events,
|
|
1490
|
+
fetch: (${guestFetch.toString()})(bytes, events),
|
|
1491
|
+
crypto: (${guestCrypto.toString()})(host, bytes)
|
|
1492
|
+
};
|
|
1493
|
+
return (${installGuest.toString()})(globalThis, host, { changeKv: ${changeKv.toString()}, changeListEntry: ${changeListEntry.toString()}, describeFunctions: ${describeFunctions.toString()}, createFunctionsDriver: ${createFunctionsDriver.toString()} }, parts);
|
|
1494
|
+
})()`;
|
|
1495
|
+
var createIsolateRunner = ({ concurrency = 8, cacheBytes = 33554432, turns: turnCount = Math.max(1, Math.round(cpuLimitCores())), cpuMeter: cpu = createCpuMeter(WATCHDOG_MS, cpuLimitCores()) } = {}) => {
|
|
1496
|
+
const turns = createTurns(turnCount);
|
|
1497
|
+
/** Every invocation running, with the memory its isolate holds and the way to give it back (`shed`). */
|
|
1498
|
+
const live = /* @__PURE__ */ new Set();
|
|
1499
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1500
|
+
let cachedBytes = 0;
|
|
1501
|
+
/** Every isolate starts from a heap with the prelude already run in it: running it each time was most of the cost. */
|
|
1502
|
+
let snapshot;
|
|
1503
|
+
let guestCache;
|
|
1504
|
+
let running = 0;
|
|
1505
|
+
const waiting = [];
|
|
1506
|
+
const acquire = async () => {
|
|
1507
|
+
if (running >= concurrency) await new Promise((resolve) => waiting.push(resolve));
|
|
1508
|
+
running++;
|
|
1509
|
+
};
|
|
1510
|
+
const release = () => {
|
|
1511
|
+
running--;
|
|
1512
|
+
waiting.shift()?.();
|
|
1513
|
+
};
|
|
1514
|
+
/** The bundle's entry, most recently used now: its code fetched only when this runner has never kept it. */
|
|
1515
|
+
const cached = async (bundle) => {
|
|
1516
|
+
const kept = cache.get(bundle.id);
|
|
1517
|
+
if (kept) {
|
|
1518
|
+
cache.delete(bundle.id);
|
|
1519
|
+
cache.set(bundle.id, kept);
|
|
1520
|
+
return kept;
|
|
1521
|
+
}
|
|
1522
|
+
const code = await bundle.load();
|
|
1523
|
+
const entry = {
|
|
1524
|
+
code,
|
|
1525
|
+
bytes: Buffer.byteLength(code)
|
|
1526
|
+
};
|
|
1527
|
+
cache.set(bundle.id, entry);
|
|
1528
|
+
cachedBytes += entry.bytes;
|
|
1529
|
+
for (const [id, oldest] of cache) {
|
|
1530
|
+
if (cachedBytes <= cacheBytes || id === bundle.id) break;
|
|
1531
|
+
cache.delete(id);
|
|
1532
|
+
cachedBytes -= oldest.bytes;
|
|
1533
|
+
}
|
|
1534
|
+
return entry;
|
|
1535
|
+
};
|
|
1536
|
+
/** What every isolate is made from, once per process: the module, the prelude, the heap it starts as. */
|
|
1537
|
+
const ready = async () => {
|
|
1538
|
+
const ivm = await loadIvm();
|
|
1539
|
+
snapshot ??= ivm.Isolate.createSnapshot([{
|
|
1540
|
+
code: await guestPrelude(),
|
|
1541
|
+
filename: "plitzi:prelude"
|
|
1542
|
+
}]);
|
|
1543
|
+
return ivm;
|
|
1544
|
+
};
|
|
1545
|
+
const session = async ({ bundle, limits, answer, signal, graceMs = ABORT_GRACE_MS, onUsage, onWaited, drive, spaceId = 0 }) => {
|
|
1546
|
+
const ivm = await ready();
|
|
1547
|
+
const entry = await cached(bundle);
|
|
1548
|
+
await acquire();
|
|
1549
|
+
const isolate = new ivm.Isolate({
|
|
1550
|
+
memoryLimit: limits.memoryMb,
|
|
1551
|
+
snapshot
|
|
1552
|
+
});
|
|
1553
|
+
const timers = /* @__PURE__ */ new Set();
|
|
1554
|
+
/** Why it was stopped: a limit of its own, an abort — or `shed`, given back by a runner short of memory. */
|
|
1555
|
+
let stopped;
|
|
1556
|
+
let calls = 0;
|
|
1557
|
+
const startedAt = Date.now();
|
|
1558
|
+
/** The CPU the isolate was measured at, kept as it is read: a disposed isolate has none left to ask. */
|
|
1559
|
+
let isolateCpuMs = 0;
|
|
1560
|
+
/** What the runner spent on the run's behalf — a PBKDF2 derivation — which the isolate's clock never sees. */
|
|
1561
|
+
let hostCpuMs = 0;
|
|
1562
|
+
/**
|
|
1563
|
+
* The isolate's CPU once it was ready — the guest and the bundle compiled, the first time on a runner without V8's
|
|
1564
|
+
* cache of them: the platform's work, not the space's code. Its time is the code's own from there.
|
|
1565
|
+
*/
|
|
1566
|
+
let readyCpuMs;
|
|
1567
|
+
const readIsolateCpu = () => {
|
|
1568
|
+
if (!isolate.isDisposed) isolateCpuMs = Number(isolate.cpuTime) / 1e6;
|
|
1569
|
+
return isolateCpuMs;
|
|
1570
|
+
};
|
|
1571
|
+
/** Whether it ran since the last look: what it was measured at moved. */
|
|
1572
|
+
const readCpu = () => (readyCpuMs === void 0 ? 0 : readIsolateCpu() - readyCpuMs) + hostCpuMs;
|
|
1573
|
+
/** Its share of the process's CPU from the moment it was ready (`createCpuMeter`), and what the runner spent for it. */
|
|
1574
|
+
let metered;
|
|
1575
|
+
const chargedCpu = () => (metered?.charged() ?? 0) + hostCpuMs;
|
|
1576
|
+
/** Whether its code began: what came before — the isolate made, the bundle compiled — is the platform's time. */
|
|
1577
|
+
let codeBegan = false;
|
|
1578
|
+
/** How long it waited on what it asked of the platform — calls, sleeps — counted once while it waits on several. */
|
|
1579
|
+
let awaitedMs = 0;
|
|
1580
|
+
let awaitingSince;
|
|
1581
|
+
/**
|
|
1582
|
+
* Its own time: what it waited on that it asked for, and the CPU it took — what it would take on a runner of its own.
|
|
1583
|
+
* Never the runner's: a turn waited for, a place behind other isolates in isolated-vm's threads (one per core: a
|
|
1584
|
+
* spinner holds one until it ends), a core it was ready for and did not get. Counted from the clock, a route that
|
|
1585
|
+
* slept 200 ms on a crowded runner was stopped at its 10 s.
|
|
1586
|
+
*/
|
|
1587
|
+
/**
|
|
1588
|
+
* A sleep counts what it asked for: the timer that wakes it is the runner's, on its main thread, and a crowded runner
|
|
1589
|
+
* woke a 200 ms sleep seconds late — counted, a route was stopped at its 10 s. Its lateness, of the sleeps that ended
|
|
1590
|
+
* and of the ones still past their time, is the runner's.
|
|
1591
|
+
*/
|
|
1592
|
+
let lateMs = 0;
|
|
1593
|
+
const sleeping = /* @__PURE__ */ new Set();
|
|
1594
|
+
const lateNow = (now) => [...sleeping].reduce((late, sleep) => late + Math.max(0, now - sleep.from - sleep.wanted), lateMs);
|
|
1595
|
+
const ownMs = () => {
|
|
1596
|
+
if (!codeBegan) return 0;
|
|
1597
|
+
const now = Date.now();
|
|
1598
|
+
const awaitedNow = awaitedMs + (awaitingSince === void 0 ? 0 : now - awaitingSince);
|
|
1599
|
+
return Math.max(0, awaitedNow - lateNow(now)) + chargedCpu();
|
|
1600
|
+
};
|
|
1601
|
+
/** The turn at running JavaScript this isolate holds, if any, and how many answers of the platform it waits for. */
|
|
1602
|
+
let holding;
|
|
1603
|
+
let awaited = 0;
|
|
1604
|
+
/** What its CPU read when the watchdog last looked: still, while it waits, it is not running. */
|
|
1605
|
+
let lastCpuMs = 0;
|
|
1606
|
+
/** A turn asked for and not yet given: two answers back at once ask once. */
|
|
1607
|
+
let taking;
|
|
1608
|
+
/** Ended: a turn handed to it after that goes straight back. */
|
|
1609
|
+
let ended = false;
|
|
1610
|
+
/** What of its time was the runner's, and told the platform so far: its wait for the answer grows by it. */
|
|
1611
|
+
let toldWaitedMs = 0;
|
|
1612
|
+
const takeTurn = async () => {
|
|
1613
|
+
if (holding !== void 0) return;
|
|
1614
|
+
taking ??= turns.take().then((id) => {
|
|
1615
|
+
taking = void 0;
|
|
1616
|
+
if (ended) turns.give(id);
|
|
1617
|
+
else holding = id;
|
|
1618
|
+
});
|
|
1619
|
+
await taking;
|
|
1620
|
+
};
|
|
1621
|
+
const giveTurn = () => {
|
|
1622
|
+
if (holding !== void 0) {
|
|
1623
|
+
turns.give(holding);
|
|
1624
|
+
holding = void 0;
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
/** Something it asked of the platform, its turn given up while it waits and taken again before it hears back. */
|
|
1628
|
+
const waitingOn = async (work) => {
|
|
1629
|
+
if (awaited === 0) awaitingSince = Date.now();
|
|
1630
|
+
awaited++;
|
|
1631
|
+
giveTurn();
|
|
1632
|
+
try {
|
|
1633
|
+
return await work();
|
|
1634
|
+
} finally {
|
|
1635
|
+
awaited--;
|
|
1636
|
+
if (awaited === 0 && awaitingSince !== void 0) {
|
|
1637
|
+
awaitedMs += Date.now() - awaitingSince;
|
|
1638
|
+
awaitingSince = void 0;
|
|
1639
|
+
}
|
|
1640
|
+
await takeTurn();
|
|
1641
|
+
}
|
|
1642
|
+
};
|
|
1643
|
+
const stop = (reason) => {
|
|
1644
|
+
stopped ??= reason;
|
|
1645
|
+
readCpu();
|
|
1646
|
+
if (!isolate.isDisposed) isolate.dispose();
|
|
1647
|
+
};
|
|
1648
|
+
/** How a stop reads to the platform: a limit of its own as itself; given back by the runner, as `busy`. */
|
|
1649
|
+
const failureOf = (reason) => reason === "shed" ? new FunctionFailure("busy", SHED_SAID) : new FunctionFailure(reason, stopMessage(reason, limits));
|
|
1650
|
+
const running = {
|
|
1651
|
+
heldBytes: () => {
|
|
1652
|
+
if (isolate.isDisposed) return 0;
|
|
1653
|
+
const heap = isolate.getHeapStatisticsSync();
|
|
1654
|
+
return heap.used_heap_size + heap.externally_allocated_size;
|
|
1655
|
+
},
|
|
1656
|
+
limitBytes: limits.memoryMb * 1048576,
|
|
1657
|
+
spaceId,
|
|
1658
|
+
shed: (overItsOwn) => {
|
|
1659
|
+
stop(overItsOwn ? "memory" : "shed");
|
|
1660
|
+
}
|
|
1661
|
+
};
|
|
1662
|
+
live.add(running);
|
|
1663
|
+
const later = (ms, run) => {
|
|
1664
|
+
const timer = setTimeout(() => {
|
|
1665
|
+
timers.delete(timer);
|
|
1666
|
+
run();
|
|
1667
|
+
}, ms);
|
|
1668
|
+
timers.add(timer);
|
|
1669
|
+
};
|
|
1670
|
+
const watchdog = setInterval(() => {
|
|
1671
|
+
const cpuMs = readCpu();
|
|
1672
|
+
if (!isolate.isDisposed && chargedCpu() > limits.cpuMs) stop("cpu");
|
|
1673
|
+
const own = ownMs();
|
|
1674
|
+
if (!isolate.isDisposed && own > limits.wallMs) stop("wall");
|
|
1675
|
+
const runners = Date.now() - startedAt - own;
|
|
1676
|
+
if (onWaited && runners - toldWaitedMs >= TELL_WAITED_MS) {
|
|
1677
|
+
onWaited(runners - toldWaitedMs);
|
|
1678
|
+
toldWaitedMs = runners;
|
|
1679
|
+
}
|
|
1680
|
+
if (holding !== void 0 && awaited > 0 && cpuMs === lastCpuMs) giveTurn();
|
|
1681
|
+
lastCpuMs = cpuMs;
|
|
1682
|
+
}, WATCHDOG_MS);
|
|
1683
|
+
let driver;
|
|
1684
|
+
const onAbort = () => {
|
|
1685
|
+
const reason = typeof signal?.reason === "string" ? signal.reason : "The run was aborted";
|
|
1686
|
+
driver?.get("abort", { reference: true }).then((abort) => abort.apply(void 0, [reason])).catch(() => void 0);
|
|
1687
|
+
later(graceMs, () => stop("aborted"));
|
|
1688
|
+
};
|
|
1689
|
+
try {
|
|
1690
|
+
const context = isolate.createContextSync();
|
|
1691
|
+
const global = context.global;
|
|
1692
|
+
global.setSync("globalThis", global.derefInto());
|
|
1693
|
+
global.setSync("__plitziCall", new ivm.Reference(async (message) => {
|
|
1694
|
+
calls++;
|
|
1695
|
+
if (calls > limits.calls) {
|
|
1696
|
+
stop("calls");
|
|
1697
|
+
return JSON.stringify({
|
|
1698
|
+
ok: false,
|
|
1699
|
+
error: stopMessage("calls", limits)
|
|
1700
|
+
});
|
|
1701
|
+
}
|
|
1702
|
+
return waitingOn(async () => {
|
|
1703
|
+
try {
|
|
1704
|
+
const value = await answer(JSON.parse(message));
|
|
1705
|
+
return JSON.stringify({
|
|
1706
|
+
ok: true,
|
|
1707
|
+
value: value ?? null
|
|
1708
|
+
});
|
|
1709
|
+
} catch (error) {
|
|
1710
|
+
return JSON.stringify(failedAnswerOf(error));
|
|
1711
|
+
}
|
|
1712
|
+
});
|
|
1713
|
+
}));
|
|
1714
|
+
global.setSync("__plitziSleep", new ivm.Reference((ms) => {
|
|
1715
|
+
const left = limits.wallMs - ownMs();
|
|
1716
|
+
const wanted = Math.max(0, ms);
|
|
1717
|
+
if (wanted >= left) {
|
|
1718
|
+
later(Math.max(0, left), () => stop("wall"));
|
|
1719
|
+
return waitingOn(() => new Promise(() => void 0));
|
|
1720
|
+
}
|
|
1721
|
+
const sleep = {
|
|
1722
|
+
from: Date.now(),
|
|
1723
|
+
wanted
|
|
1724
|
+
};
|
|
1725
|
+
sleeping.add(sleep);
|
|
1726
|
+
return waitingOn(() => new Promise((resolve) => {
|
|
1727
|
+
later(wanted, () => {
|
|
1728
|
+
sleeping.delete(sleep);
|
|
1729
|
+
lateMs += Math.max(0, Date.now() - sleep.from - wanted);
|
|
1730
|
+
resolve();
|
|
1731
|
+
});
|
|
1732
|
+
}));
|
|
1733
|
+
}));
|
|
1734
|
+
global.setSync("__plitziRandom", new ivm.Callback((length) => [...randomBytes(Math.min(Math.max(0, length), 65536))]));
|
|
1735
|
+
global.setSync("__plitziCrypto", new ivm.Reference((message) => waitingOn(() => cryptoAnswer(message, (ms) => {
|
|
1736
|
+
hostCpuMs += ms;
|
|
1737
|
+
if (chargedCpu() > limits.cpuMs) stop("cpu");
|
|
1738
|
+
}))));
|
|
1739
|
+
const guestScript = isolate.compileScriptSync(BOOTSTRAP, {
|
|
1740
|
+
filename: "plitzi:guest",
|
|
1741
|
+
...guestCache ? { cachedData: guestCache } : { produceCachedData: true }
|
|
1742
|
+
});
|
|
1743
|
+
guestCache ??= cachedDataOf(ivm, guestScript);
|
|
1744
|
+
driver = guestScript.runSync(context, { reference: true });
|
|
1745
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1746
|
+
if (signal?.aborted) onAbort();
|
|
1747
|
+
const module = isolate.compileModuleSync(entry.code, {
|
|
1748
|
+
filename: "functions.js",
|
|
1749
|
+
...entry.cachedData ? { cachedData: entry.cachedData } : { produceCachedData: true }
|
|
1750
|
+
});
|
|
1751
|
+
entry.cachedData ??= cachedDataOf(ivm, module);
|
|
1752
|
+
module.instantiateSync(context, (specifier) => {
|
|
1753
|
+
throw new Error(`"${specifier}" cannot be imported: a bundle is one module`);
|
|
1754
|
+
});
|
|
1755
|
+
await takeTurn();
|
|
1756
|
+
readyCpuMs = readIsolateCpu();
|
|
1757
|
+
metered = cpu.meter(readIsolateCpu);
|
|
1758
|
+
codeBegan = true;
|
|
1759
|
+
await module.evaluate();
|
|
1760
|
+
const definition = module.namespace.getSync("default", { reference: true });
|
|
1761
|
+
if (definition.typeof !== "object") throw new FunctionFailure("error", "The functions bundle exports no definition: each file at the top of functions/ exports one by default — export default defineFunctions({ tasks: [ … ] })");
|
|
1762
|
+
const text = await drive(driver, definition);
|
|
1763
|
+
if (Buffer.byteLength(text) > limits.outputBytes) stop("output");
|
|
1764
|
+
if (stopped) throw failureOf(stopped);
|
|
1765
|
+
const outcome = JSON.parse(text);
|
|
1766
|
+
if (typeof outcome !== "object" || outcome === null || !("ok" in outcome)) throw new FunctionFailure("error", "The runtime answered something that is not an outcome");
|
|
1767
|
+
if (outcome.ok !== true) throw new FunctionFailure("refused" in outcome && outcome.refused === true ? "refused" : "error", "error" in outcome ? String(outcome.error) : "The function failed");
|
|
1768
|
+
return "value" in outcome ? outcome.value : null;
|
|
1769
|
+
} catch (error) {
|
|
1770
|
+
if (error instanceof FunctionFailure && !stopped) throw error;
|
|
1771
|
+
const timedOut = error instanceof Error && error.message === ISOLATE_TIMEOUT;
|
|
1772
|
+
const reason = stopped ?? (timedOut ? "wall" : isolate.isDisposed ? "memory" : void 0);
|
|
1773
|
+
throw reason ? failureOf(reason) : new FunctionFailure("error", messageOf(error));
|
|
1774
|
+
} finally {
|
|
1775
|
+
live.delete(running);
|
|
1776
|
+
metered?.end();
|
|
1777
|
+
onUsage?.({
|
|
1778
|
+
cpuMs: Math.round(chargedCpu()),
|
|
1779
|
+
wallMs: Date.now() - startedAt,
|
|
1780
|
+
calls
|
|
1781
|
+
});
|
|
1782
|
+
clearInterval(watchdog);
|
|
1783
|
+
timers.forEach((timer) => clearTimeout(timer));
|
|
1784
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1785
|
+
if (!isolate.isDisposed) isolate.dispose();
|
|
1786
|
+
ended = true;
|
|
1787
|
+
giveTurn();
|
|
1788
|
+
release();
|
|
1789
|
+
}
|
|
1790
|
+
};
|
|
1791
|
+
const describe = (bundle) => session({
|
|
1792
|
+
bundle: {
|
|
1793
|
+
id: bundle.id,
|
|
1794
|
+
load: () => Promise.resolve(bundle.code)
|
|
1795
|
+
},
|
|
1796
|
+
limits: DESCRIBE_LIMITS,
|
|
1797
|
+
answer: describeAnswer,
|
|
1798
|
+
drive: async (driver, definition) => {
|
|
1799
|
+
return driver.getSync("describe", { reference: true }).apply(driver.derefInto(), [definition.derefInto()], {
|
|
1800
|
+
result: { copy: true },
|
|
1801
|
+
timeout: DESCRIBE_LIMITS.wallMs
|
|
1802
|
+
});
|
|
1803
|
+
}
|
|
1804
|
+
});
|
|
1805
|
+
return {
|
|
1806
|
+
describe,
|
|
1807
|
+
invoke: ({ bundle, invocation, limits, answer, signal, onUsage, onWaited }) => session({
|
|
1808
|
+
bundle,
|
|
1809
|
+
limits,
|
|
1810
|
+
answer,
|
|
1811
|
+
signal,
|
|
1812
|
+
spaceId: invocation.context.spaceId,
|
|
1813
|
+
...invocation.kind === "job" ? { graceMs: invocation.graceMs } : {},
|
|
1814
|
+
onUsage,
|
|
1815
|
+
...onWaited ? { onWaited } : {},
|
|
1816
|
+
drive: async (driver, definition) => {
|
|
1817
|
+
const invoke = driver.getSync("invoke", { reference: true });
|
|
1818
|
+
const message = JSON.stringify(invocation);
|
|
1819
|
+
return invoke.apply(driver.derefInto(), [definition.derefInto(), message], { result: {
|
|
1820
|
+
promise: true,
|
|
1821
|
+
copy: true
|
|
1822
|
+
} });
|
|
1823
|
+
}
|
|
1824
|
+
}),
|
|
1825
|
+
shed: () => {
|
|
1826
|
+
const largest = [...live].map((each) => ({
|
|
1827
|
+
each,
|
|
1828
|
+
held: each.heldBytes()
|
|
1829
|
+
})).reduce((most, next) => most === void 0 || next.held > most.held ? next : most, void 0);
|
|
1830
|
+
if (!largest) return;
|
|
1831
|
+
const overItsOwn = largest.held > largest.each.limitBytes;
|
|
1832
|
+
largest.each.shed(overItsOwn);
|
|
1833
|
+
return {
|
|
1834
|
+
overItsOwn,
|
|
1835
|
+
heldMb: Math.round(largest.held / 1048576),
|
|
1836
|
+
spaceId: largest.each.spaceId
|
|
1837
|
+
};
|
|
1838
|
+
},
|
|
1839
|
+
warm: async () => {
|
|
1840
|
+
await ready();
|
|
1841
|
+
await describe({
|
|
1842
|
+
id: "plitzi:warm-up",
|
|
1843
|
+
code: "export default {};"
|
|
1844
|
+
});
|
|
1845
|
+
}
|
|
1846
|
+
};
|
|
1847
|
+
};
|
|
1848
|
+
// src/runner/memoryGuard.ts
|
|
1849
|
+
/** How full of its memory a runner may get before it gives the largest invocation back: above where it takes new ones. */
|
|
1850
|
+
var SHED_SHARE = .92;
|
|
1851
|
+
/**
|
|
1852
|
+
* What keeps a runner from being killed for its invocations' memory.
|
|
1853
|
+
*
|
|
1854
|
+
* It takes an invocation while a share of what that one may grow to fits (`busy`), since most hold a few MB; nothing
|
|
1855
|
+
* kept the ones it took from growing together past its container's limit, and the kernel killed the runner — every
|
|
1856
|
+
* invocation in it with it (`closed with 1006`), 150 calls of one load round. Near its limit it gives back the one
|
|
1857
|
+
* whose isolate holds the most (`IsolateRunner.shed`): stopped at its own limit if it is past it, else handed back as
|
|
1858
|
+
* `busy` for another runner — one invocation said, never all of them lost.
|
|
1859
|
+
*/
|
|
1860
|
+
var createMemoryGuard = ({ readMemory, shed, share = SHED_SHARE, coolMs = 500, now = Date.now }) => {
|
|
1861
|
+
let shedAt = Number.NEGATIVE_INFINITY;
|
|
1862
|
+
return { look: () => {
|
|
1863
|
+
const memory = readMemory();
|
|
1864
|
+
if (memory.usedBytes <= memory.limitBytes * share || now() - shedAt < coolMs) return false;
|
|
1865
|
+
if (!shed()) return false;
|
|
1866
|
+
shedAt = now();
|
|
1867
|
+
return true;
|
|
1868
|
+
} };
|
|
1869
|
+
};
|
|
1870
|
+
// src/runner/service.ts
|
|
1871
|
+
/** A bundle is at most 1 MB and an answer a few; anything past this on one frame is not the platform talking. */
|
|
1872
|
+
var MAX_FRAME_BYTES = 8388608;
|
|
1873
|
+
/**
|
|
1874
|
+
* What one invocation may hold, in MB, as the runner reserves it: its limit, what isolated-vm lets an isolate grow past
|
|
1875
|
+
* it before it is stopped, and an isolate's own (measured: 32 MB → ~40, 128 → ~147, 256 → ~262). Reserved whole from
|
|
1876
|
+
* the moment it is taken until it ends — as a Lambda's memory is its own — since a share let invocations that grew
|
|
1877
|
+
* together kill the runner, every invocation in it with it. One rule, read by the platform's sizing too.
|
|
1878
|
+
*/
|
|
1879
|
+
var invocationFootprintMb = (memoryMb) => Math.ceil(memoryMb * 1.1 + 8);
|
|
1880
|
+
/** How often what is kept waiting is looked at again, beside each invocation that ends: memory frees between them. */
|
|
1881
|
+
var KEPT_LOOK_MS = 100;
|
|
1882
|
+
/**
|
|
1883
|
+
* The share of a runner's room — its memory past what it holds idle — that what nobody waits on may take (a schedule's
|
|
1884
|
+
* run, a job's slice): the rest is kept for a visitor's request. Under a load probe, minute-long job slices and
|
|
1885
|
+
* scheduled actions filled every runner, and visitors' calls waited behind them past their own timeout.
|
|
1886
|
+
*/
|
|
1887
|
+
var BACKGROUND_SHARE = .75;
|
|
1888
|
+
/** How an invocation that did not answer reads to the stats: a limit, its code refusing, or a failure. */
|
|
1889
|
+
var endOf = (reason) => isFunctionLimit(reason) ? { limit: reason } : reason === "refused" ? { refused: true } : { failed: reason };
|
|
1890
|
+
var serveConnection = (socket, runner, stats) => {
|
|
1891
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1892
|
+
const controller = new AbortController();
|
|
1893
|
+
let nextCall = 1;
|
|
1894
|
+
let started = false;
|
|
1895
|
+
let waitingBundle;
|
|
1896
|
+
const send = (message) => {
|
|
1897
|
+
if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(message));
|
|
1898
|
+
};
|
|
1899
|
+
let invokedAt;
|
|
1900
|
+
/** What it runs, for its stats: which space's task, route or job. */
|
|
1901
|
+
let label;
|
|
1902
|
+
/** What the invocation it took was reserved of the runner's memory by: given back as it ends. */
|
|
1903
|
+
let takenLimits;
|
|
1904
|
+
const finish = (message) => {
|
|
1905
|
+
if (invokedAt !== void 0) {
|
|
1906
|
+
stats.inFlight.count -= 1;
|
|
1907
|
+
stats.recorder.run(Date.now() - invokedAt, message.type === "failed" ? endOf(message.reason) : void 0, label);
|
|
1908
|
+
invokedAt = void 0;
|
|
1909
|
+
}
|
|
1910
|
+
if (takenLimits) {
|
|
1911
|
+
stats.ended(takenLimits);
|
|
1912
|
+
takenLimits = void 0;
|
|
1913
|
+
}
|
|
1914
|
+
send(message);
|
|
1915
|
+
socket.close(1e3);
|
|
1916
|
+
};
|
|
1917
|
+
let usage;
|
|
1918
|
+
/** A route answering as it writes: its head now, each part of its body as it comes, and `done` once it ends. */
|
|
1919
|
+
const stream = async (answer) => {
|
|
1920
|
+
send({
|
|
1921
|
+
type: "head",
|
|
1922
|
+
status: answer.status,
|
|
1923
|
+
statusText: answer.statusText,
|
|
1924
|
+
headers: answer.headers
|
|
1925
|
+
});
|
|
1926
|
+
const reader = answer.body.getReader();
|
|
1927
|
+
const stop = () => {
|
|
1928
|
+
reader.cancel().catch(() => void 0);
|
|
1929
|
+
};
|
|
1930
|
+
controller.signal.addEventListener("abort", stop, { once: true });
|
|
1931
|
+
try {
|
|
1932
|
+
for (;;) {
|
|
1933
|
+
const { done, value } = await reader.read();
|
|
1934
|
+
if (done) break;
|
|
1935
|
+
send({
|
|
1936
|
+
type: "chunk",
|
|
1937
|
+
chunk: { base64: Buffer.from(value).toString("base64") }
|
|
1938
|
+
});
|
|
1939
|
+
}
|
|
1940
|
+
} finally {
|
|
1941
|
+
controller.signal.removeEventListener("abort", stop);
|
|
1942
|
+
}
|
|
1943
|
+
};
|
|
1944
|
+
const settle = (work) => {
|
|
1945
|
+
work.then(async (value) => {
|
|
1946
|
+
if (!isStreamedRouteAnswer(value)) {
|
|
1947
|
+
finish({
|
|
1948
|
+
type: "done",
|
|
1949
|
+
value,
|
|
1950
|
+
...usage ? { usage } : {}
|
|
1951
|
+
});
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
try {
|
|
1955
|
+
await stream(value);
|
|
1956
|
+
finish({
|
|
1957
|
+
type: "done",
|
|
1958
|
+
value: null,
|
|
1959
|
+
...usage ? { usage } : {}
|
|
1960
|
+
});
|
|
1961
|
+
} catch (error) {
|
|
1962
|
+
finish({
|
|
1963
|
+
type: "failed",
|
|
1964
|
+
reason: "error",
|
|
1965
|
+
error: `The route's answer broke off: ${error instanceof Error ? error.message : String(error)}`,
|
|
1966
|
+
...usage ? { usage } : {}
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
}, (error) => finish({
|
|
1970
|
+
type: "failed",
|
|
1971
|
+
...error instanceof FunctionFailure ? {
|
|
1972
|
+
reason: error.reason,
|
|
1973
|
+
error: error.message
|
|
1974
|
+
} : {
|
|
1975
|
+
reason: "error",
|
|
1976
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1977
|
+
},
|
|
1978
|
+
...usage ? { usage } : {}
|
|
1979
|
+
}));
|
|
1980
|
+
};
|
|
1981
|
+
const answer = (call) => new Promise((resolve, reject) => {
|
|
1982
|
+
const id = nextCall++;
|
|
1983
|
+
pending.set(id, (reply) => reply.ok ? resolve(reply.value) : reject(errorOfAnswer(reply)));
|
|
1984
|
+
send({
|
|
1985
|
+
type: "call",
|
|
1986
|
+
id,
|
|
1987
|
+
call
|
|
1988
|
+
});
|
|
1989
|
+
});
|
|
1990
|
+
socket.on("message", (data) => {
|
|
1991
|
+
const message = readRequestMessage(frameText(data));
|
|
1992
|
+
if (!message) {
|
|
1993
|
+
finish({
|
|
1994
|
+
type: "failed",
|
|
1995
|
+
reason: "error",
|
|
1996
|
+
error: "Not a message of the functions protocol"
|
|
1997
|
+
});
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
if (message.type === "answer") {
|
|
2001
|
+
const reply = pending.get(message.id);
|
|
2002
|
+
pending.delete(message.id);
|
|
2003
|
+
reply?.(message.answer);
|
|
2004
|
+
return;
|
|
2005
|
+
}
|
|
2006
|
+
if (message.type === "abort") {
|
|
2007
|
+
controller.abort(message.reason);
|
|
2008
|
+
return;
|
|
2009
|
+
}
|
|
2010
|
+
if (message.type === "bundle") {
|
|
2011
|
+
waitingBundle?.(message.bundle.code);
|
|
2012
|
+
waitingBundle = void 0;
|
|
2013
|
+
return;
|
|
2014
|
+
}
|
|
2015
|
+
if (started) {
|
|
2016
|
+
finish({
|
|
2017
|
+
type: "failed",
|
|
2018
|
+
reason: "error",
|
|
2019
|
+
error: "One operation per connection"
|
|
2020
|
+
});
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
started = true;
|
|
2024
|
+
const refusal = protocolRefusal(message.protocol);
|
|
2025
|
+
if (refusal) {
|
|
2026
|
+
stats.recorder.refuse("protocol");
|
|
2027
|
+
finish({
|
|
2028
|
+
type: "failed",
|
|
2029
|
+
reason: "error",
|
|
2030
|
+
error: refusal
|
|
2031
|
+
});
|
|
2032
|
+
return;
|
|
2033
|
+
}
|
|
2034
|
+
if (message.type === "describe") {
|
|
2035
|
+
settle(runner.describe(message.bundle));
|
|
2036
|
+
return;
|
|
2037
|
+
}
|
|
2038
|
+
start(message).catch((error) => {
|
|
2039
|
+
finish({
|
|
2040
|
+
type: "failed",
|
|
2041
|
+
reason: "error",
|
|
2042
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2043
|
+
});
|
|
2044
|
+
});
|
|
2045
|
+
});
|
|
2046
|
+
/** An invocation taken — now, or once there is room for it — and run. */
|
|
2047
|
+
const start = async (message) => {
|
|
2048
|
+
const { bundleId, invocation, limits } = message;
|
|
2049
|
+
const urgency = invocationUrgency(invocation);
|
|
2050
|
+
const tooLarge = stats.tooLarge(limits);
|
|
2051
|
+
if (tooLarge) {
|
|
2052
|
+
stats.recorder.refuse("busy");
|
|
2053
|
+
finish({
|
|
2054
|
+
type: "failed",
|
|
2055
|
+
reason: protocolKnows(message.protocol, "1.4") ? "too_large" : "busy",
|
|
2056
|
+
error: tooLarge
|
|
2057
|
+
});
|
|
2058
|
+
return;
|
|
2059
|
+
}
|
|
2060
|
+
const busy = stats.busy(limits, urgency);
|
|
2061
|
+
if (busy) {
|
|
2062
|
+
if (!(!stats.stopping() && message.queue === true && protocolKnows(message.protocol, "1.3"))) {
|
|
2063
|
+
stats.recorder.refuse(stats.stopping() ? "stopping" : "busy");
|
|
2064
|
+
finish({
|
|
2065
|
+
type: "failed",
|
|
2066
|
+
reason: "busy",
|
|
2067
|
+
error: busy
|
|
2068
|
+
});
|
|
2069
|
+
return;
|
|
2070
|
+
}
|
|
2071
|
+
send({ type: "queued" });
|
|
2072
|
+
if (!await stats.wait(limits, urgency, controller.signal)) {
|
|
2073
|
+
if (!controller.signal.aborted) {
|
|
2074
|
+
stats.recorder.refuse("stopping");
|
|
2075
|
+
finish({
|
|
2076
|
+
type: "failed",
|
|
2077
|
+
reason: "busy",
|
|
2078
|
+
error: "This functions runner started stopping while it kept the invocation: another runner takes it"
|
|
2079
|
+
});
|
|
2080
|
+
}
|
|
2081
|
+
return;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
takenLimits = limits;
|
|
2085
|
+
label = {
|
|
2086
|
+
spaceId: invocation.context.spaceId,
|
|
2087
|
+
kind: invocation.kind,
|
|
2088
|
+
name: invocation.kind === "route" ? invocation.key : invocation.name,
|
|
2089
|
+
trigger: invocation.context.trigger,
|
|
2090
|
+
runId: invocation.context.runId
|
|
2091
|
+
};
|
|
2092
|
+
invokedAt = Date.now();
|
|
2093
|
+
stats.inFlight.count += 1;
|
|
2094
|
+
if (protocolKnows(message.protocol, "1.2")) send({ type: "accepted" });
|
|
2095
|
+
settle(runner.invoke({
|
|
2096
|
+
bundle: {
|
|
2097
|
+
id: bundleId,
|
|
2098
|
+
load: () => new Promise((resolve) => {
|
|
2099
|
+
waitingBundle = resolve;
|
|
2100
|
+
send({ type: "needBundle" });
|
|
2101
|
+
})
|
|
2102
|
+
},
|
|
2103
|
+
invocation,
|
|
2104
|
+
limits,
|
|
2105
|
+
answer,
|
|
2106
|
+
signal: controller.signal,
|
|
2107
|
+
onUsage: (spent) => {
|
|
2108
|
+
usage = spent;
|
|
2109
|
+
},
|
|
2110
|
+
...protocolKnows(message.protocol, "1.3") ? { onWaited: (ms) => send({
|
|
2111
|
+
type: "waited",
|
|
2112
|
+
ms
|
|
2113
|
+
}) } : {}
|
|
2114
|
+
}));
|
|
2115
|
+
};
|
|
2116
|
+
socket.on("close", () => {
|
|
2117
|
+
controller.abort();
|
|
2118
|
+
pending.forEach((reply) => reply({
|
|
2119
|
+
ok: false,
|
|
2120
|
+
error: "The platform went away"
|
|
2121
|
+
}));
|
|
2122
|
+
pending.clear();
|
|
2123
|
+
});
|
|
2124
|
+
};
|
|
2125
|
+
/**
|
|
2126
|
+
* The functions runner as a service: a process that holds no secrets, no database and no documents, and runs the
|
|
2127
|
+
* spaces' code in isolates for the platform that authenticates to it. What a sandbox escape reaches is this process.
|
|
2128
|
+
*
|
|
2129
|
+
* `GET /health` answers 200 for the orchestrator; `GET /_stats` its stats and everything else the WebSocket protocol,
|
|
2130
|
+
* behind the secret.
|
|
2131
|
+
*/
|
|
2132
|
+
var startFunctionsRunnerService = async ({ secret, port = 8790, host = "0.0.0.0", runner, http: answerHttp, stats: naming, version, memoryShare = .85, announce = true, shutdown, readMemory = sampleProcessMemory(), ...isolate }) => {
|
|
2133
|
+
if (secret.length < 32) throw new Error("The functions runner needs a secret of at least 32 characters");
|
|
2134
|
+
let engine;
|
|
2135
|
+
/** The memory guard's look, while the runner is its own isolates (`createMemoryGuard`). */
|
|
2136
|
+
let memoryWatch;
|
|
2137
|
+
if (runner) engine = runner;
|
|
2138
|
+
else {
|
|
2139
|
+
const isolates = createIsolateRunner(isolate);
|
|
2140
|
+
await isolates.warm();
|
|
2141
|
+
engine = isolates;
|
|
2142
|
+
const guard = createMemoryGuard({
|
|
2143
|
+
readMemory,
|
|
2144
|
+
shed: () => {
|
|
2145
|
+
const gave = isolates.shed();
|
|
2146
|
+
if (gave) serverLog.warn("Functions", `ran short of memory: gave back an invocation of space ${String(gave.spaceId)} holding ${String(gave.heldMb)} MB` + (gave.overItsOwn ? ", past its own limit — stopped at it" : ", within its own — for another runner"));
|
|
2147
|
+
return gave !== void 0;
|
|
2148
|
+
}
|
|
2149
|
+
});
|
|
2150
|
+
memoryWatch = setInterval(() => void guard.look(), 100);
|
|
2151
|
+
memoryWatch.unref();
|
|
2152
|
+
}
|
|
2153
|
+
const recorder = createStatsRecorder({
|
|
2154
|
+
pool: "runner",
|
|
2155
|
+
...naming,
|
|
2156
|
+
protocol: FUNCTIONS_PROTOCOL,
|
|
2157
|
+
...version ? { version } : {}
|
|
2158
|
+
});
|
|
2159
|
+
const inFlight = { count: 0 };
|
|
2160
|
+
let stopping = false;
|
|
2161
|
+
const most = isolate.concurrency ?? 8;
|
|
2162
|
+
const MB = 1048576;
|
|
2163
|
+
/** What the runner holds with nothing running — read whenever nothing does: what every reservation is counted beside. */
|
|
2164
|
+
let idleBytes = readMemory().usedBytes;
|
|
2165
|
+
/**
|
|
2166
|
+
* The least it was read holding with nothing running: what it holds empty at its leanest, which an invocation may be
|
|
2167
|
+
* judged by for good (`tooLarge`) — the last reading may be a moment's (its start, a collection not yet run).
|
|
2168
|
+
*/
|
|
2169
|
+
let leanestIdleBytes = idleBytes;
|
|
2170
|
+
/** What the invocations it took are reserved, whole (`invocationFootprintMb`), until each ends. */
|
|
2171
|
+
let reservedBytes = 0;
|
|
2172
|
+
const footprintOf = (limits) => invocationFootprintMb(limits.memoryMb) * MB;
|
|
2173
|
+
const release = (limits) => {
|
|
2174
|
+
reservedBytes = Math.max(0, reservedBytes - footprintOf(limits));
|
|
2175
|
+
};
|
|
2176
|
+
const tooLarge = (limits) => {
|
|
2177
|
+
const room = readMemory().limitBytes * memoryShare - leanestIdleBytes;
|
|
2178
|
+
const need = footprintOf(limits);
|
|
2179
|
+
if (need <= room) return;
|
|
2180
|
+
const mb = (bytes) => String(Math.round(bytes / MB));
|
|
2181
|
+
return `This functions runner could never hold it: it may hold ${mb(need)} MB (${String(limits.memoryMb)} MB of memory), past the ${mb(room)} MB this runner has for invocations with nothing else running — a larger runner takes it`;
|
|
2182
|
+
};
|
|
2183
|
+
const busy = (limits, urgency) => {
|
|
2184
|
+
if (stopping) return "This functions runner is stopping — a deploy or a scale-down — and takes no new invocation: another does";
|
|
2185
|
+
if (!runner && inFlight.count >= most) return `This functions runner runs ${String(most)} invocations, the most it takes at once: another runner takes it`;
|
|
2186
|
+
const memory = readMemory();
|
|
2187
|
+
if (reservedBytes === 0) {
|
|
2188
|
+
idleBytes = memory.usedBytes;
|
|
2189
|
+
leanestIdleBytes = Math.min(leanestIdleBytes, idleBytes);
|
|
2190
|
+
}
|
|
2191
|
+
const need = footprintOf(limits);
|
|
2192
|
+
const whole = memory.limitBytes * memoryShare;
|
|
2193
|
+
const cap = urgency === "background" && reservedBytes > 0 ? idleBytes + (whole - idleBytes) * BACKGROUND_SHARE : whole;
|
|
2194
|
+
const mb = (bytes) => String(Math.round(bytes / MB));
|
|
2195
|
+
if (Math.max(idleBytes + reservedBytes, memory.usedBytes) + need <= cap) {
|
|
2196
|
+
reservedBytes += need;
|
|
2197
|
+
return;
|
|
2198
|
+
}
|
|
2199
|
+
return `The functions runner is short of memory — ${mb(idleBytes + reservedBytes)} MB reserved for what it runs (${mb(memory.usedBytes)} in use), and this one may hold ${mb(need)}, past the ${mb(cap)} MB ` + (urgency === "background" ? `it takes work nobody waits on up to (${String(Math.round(BACKGROUND_SHARE * 100))}% of its room, the rest kept for visitors' requests) — ` : `(${String(Math.round(memoryShare * 100))}% of ${mb(memory.limitBytes)}) it takes new ones up to — `) + "so it took none: another runner takes it. A deployment that sees this often gives the runners more memory or more instances.";
|
|
2200
|
+
};
|
|
2201
|
+
const kept = [];
|
|
2202
|
+
let keptTimer;
|
|
2203
|
+
const nextKept = () => kept.find((entry) => entry.urgency === "interactive") ?? kept.at(0);
|
|
2204
|
+
const letIn = () => {
|
|
2205
|
+
for (let head = nextKept(); head; head = nextKept()) {
|
|
2206
|
+
if (!stopping && busy(head.limits, head.urgency) !== void 0) break;
|
|
2207
|
+
kept.splice(kept.indexOf(head), 1);
|
|
2208
|
+
head.admit(!stopping);
|
|
2209
|
+
}
|
|
2210
|
+
if (kept.length === 0 && keptTimer) {
|
|
2211
|
+
clearInterval(keptTimer);
|
|
2212
|
+
keptTimer = void 0;
|
|
2213
|
+
} else if (kept.length > 0 && !keptTimer) keptTimer = setInterval(letIn, KEPT_LOOK_MS);
|
|
2214
|
+
};
|
|
2215
|
+
const wait = (limits, urgency, signal) => new Promise((resolve) => {
|
|
2216
|
+
const entry = {
|
|
2217
|
+
limits,
|
|
2218
|
+
urgency,
|
|
2219
|
+
admit: resolve
|
|
2220
|
+
};
|
|
2221
|
+
kept.push(entry);
|
|
2222
|
+
signal.addEventListener("abort", () => {
|
|
2223
|
+
const at = kept.indexOf(entry);
|
|
2224
|
+
if (at >= 0) {
|
|
2225
|
+
kept.splice(at, 1);
|
|
2226
|
+
resolve(false);
|
|
2227
|
+
}
|
|
2228
|
+
}, { once: true });
|
|
2229
|
+
letIn();
|
|
2230
|
+
});
|
|
2231
|
+
if (!runner) recorder.slot("isolates", most, () => inFlight.count);
|
|
2232
|
+
const sockets = new WebSocketServer({
|
|
2233
|
+
noServer: true,
|
|
2234
|
+
maxPayload: MAX_FRAME_BYTES
|
|
2235
|
+
});
|
|
2236
|
+
const notFound = (res) => {
|
|
2237
|
+
res.writeHead(404, { "content-type": "text/plain" });
|
|
2238
|
+
res.end("");
|
|
2239
|
+
};
|
|
2240
|
+
const server = http.createServer((req, res) => {
|
|
2241
|
+
if (req.method === "GET" && req.url === "/health") {
|
|
2242
|
+
res.writeHead(stopping ? 503 : 200, { "content-type": "text/plain" });
|
|
2243
|
+
res.end(stopping ? "stopping" : "ok");
|
|
2244
|
+
return;
|
|
2245
|
+
}
|
|
2246
|
+
const asked = new URL(req.url ?? "/", "http://runner");
|
|
2247
|
+
if (req.method === "GET" && (asked.pathname === STATS_PATH || asked.pathname === STATS_LOGS_PATH)) {
|
|
2248
|
+
const allowed = bearerMatches(req.headers.authorization, secret);
|
|
2249
|
+
res.writeHead(allowed ? 200 : 401, {
|
|
2250
|
+
"content-type": "application/json; charset=utf-8",
|
|
2251
|
+
"cache-control": "no-store"
|
|
2252
|
+
});
|
|
2253
|
+
const answer = () => asked.pathname === STATS_LOGS_PATH ? readLogTail(logQueryOf(Object.fromEntries(asked.searchParams))) : withStopping(recorder.snapshot(), stopping);
|
|
2254
|
+
res.end(JSON.stringify(allowed ? answer() : { error: `${asked.pathname} is read with the runner's secret` }));
|
|
2255
|
+
return;
|
|
2256
|
+
}
|
|
2257
|
+
if (!answerHttp) {
|
|
2258
|
+
notFound(res);
|
|
2259
|
+
return;
|
|
2260
|
+
}
|
|
2261
|
+
if (!bearerMatches(req.headers.authorization, secret)) {
|
|
2262
|
+
res.writeHead(401, { "content-type": "text/plain" });
|
|
2263
|
+
res.end("");
|
|
2264
|
+
return;
|
|
2265
|
+
}
|
|
2266
|
+
answerHttp(req, res).then((taken) => {
|
|
2267
|
+
if (!taken) notFound(res);
|
|
2268
|
+
}, (error) => {
|
|
2269
|
+
serverLog.error("Functions", "an HTTP request failed", error);
|
|
2270
|
+
if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain" });
|
|
2271
|
+
res.end("");
|
|
2272
|
+
});
|
|
2273
|
+
});
|
|
2274
|
+
server.on("upgrade", (req, socket, head) => {
|
|
2275
|
+
if (!bearerMatches(req.headers.authorization, secret)) {
|
|
2276
|
+
socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
|
2277
|
+
return;
|
|
2278
|
+
}
|
|
2279
|
+
sockets.handleUpgrade(req, socket, head, (ws) => serveConnection(ws, engine, {
|
|
2280
|
+
recorder,
|
|
2281
|
+
inFlight,
|
|
2282
|
+
busy,
|
|
2283
|
+
tooLarge,
|
|
2284
|
+
stopping: () => stopping,
|
|
2285
|
+
wait,
|
|
2286
|
+
ended: (limits) => {
|
|
2287
|
+
release(limits);
|
|
2288
|
+
letIn();
|
|
2289
|
+
}
|
|
2290
|
+
}));
|
|
2291
|
+
});
|
|
2292
|
+
const connections = watchConnections(server);
|
|
2293
|
+
await new Promise((resolve, reject) => {
|
|
2294
|
+
server.once("error", reject);
|
|
2295
|
+
server.listen(port, host, () => {
|
|
2296
|
+
server.off("error", reject);
|
|
2297
|
+
resolve();
|
|
2298
|
+
});
|
|
2299
|
+
});
|
|
2300
|
+
if (announce) serverLog.info("Functions", `runner listening on ${host}:${String(port)}`);
|
|
2301
|
+
return {
|
|
2302
|
+
address: () => {
|
|
2303
|
+
const address = server.address();
|
|
2304
|
+
if (!address || typeof address === "string") throw new Error("The functions runner is not listening");
|
|
2305
|
+
return address;
|
|
2306
|
+
},
|
|
2307
|
+
close: async () => {
|
|
2308
|
+
clearInterval(memoryWatch);
|
|
2309
|
+
const { announceMs, graceMs } = shutdownOf({ ...shutdown ? { shutdown } : {} }, { graceMs: SHUTDOWN_GRACE_MS });
|
|
2310
|
+
stopping = true;
|
|
2311
|
+
letIn();
|
|
2312
|
+
if (announceMs > 0) await new Promise((resolve) => setTimeout(resolve, announceMs));
|
|
2313
|
+
const deadline = Date.now() + graceMs;
|
|
2314
|
+
while (inFlight.count > 0 && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 50));
|
|
2315
|
+
if (inFlight.count > 0) serverLog.warn("Functions", `${String(inFlight.count)} invocation(s) still running ${String(graceMs)} ms after stopping: cut`);
|
|
2316
|
+
sockets.clients.forEach((client) => client.terminate());
|
|
2317
|
+
await connections.drain("Functions");
|
|
2318
|
+
await engine.close?.();
|
|
2319
|
+
}
|
|
2320
|
+
};
|
|
2321
|
+
};
|
|
2322
|
+
export { createIsolateRunner as a, describeFunctions as c, PBKDF2_MAX_ITERATIONS as i, startFunctionsRunnerService as n, createCpuMeter as o, PBKDF2_MAX_BITS as r, createFunctionsDriver as s, invocationFootprintMb as t };
|