Skip to content

An open-source, self-hosted system for apps built with web technologies.

Unify server runtime entry handling

zohayrslilehb7854d3c05c0
diff --git a/source/dec.d.ts b/source/dec.d.ts
new file mode 100644
index 0000000..3b1be31
--- /dev/null
+++ b/source/dec.d.ts
@@ -0,0 +1,6 @@
+declare module "*?worker-thread" {
+
+ const entry: URL
+
+ export default entry
+}
diff --git a/source/libs/worker-thread-plugin.ts b/source/libs/worker-thread-plugin.ts
new file mode 100644
index 0000000..538d637
--- /dev/null
+++ b/source/libs/worker-thread-plugin.ts
@@ -0,0 +1,43 @@
+import { pathToFileURL } from "node:url"
+import type { Plugin } from "vite"
+
+const query = "?worker-thread"
+const prefix = "\0worker-thread:"
+
+/** Resolves a module as a separately executable Node Worker entry. */
+export default function workerThreadPlugin(): Plugin {
+
+ let building = false
+
+ return {
+
+ name: "worker-thread",
+ enforce: "pre",
+
+ configResolved(config) { building = config.command === "build" },
+
+ async resolveId(source, importer) {
+
+ if (!source.endsWith(query)) return
+
+ const resolution = await this.resolve(source.slice(0, -query.length), importer, { skipSelf: true })
+
+ if (!resolution) throw new Error(`Cannot resolve the Worker entry "${source.slice(0, -query.length)}"`)
+
+ return `${prefix}${resolution.id}`
+ },
+
+ load(id) {
+
+ if (!id.startsWith(prefix)) return
+
+ const entry = id.slice(prefix.length)
+
+ if (!building) return `export default new URL(${JSON.stringify(pathToFileURL(entry).href)})`
+
+ const reference = this.emitFile({ type: "chunk", id: entry })
+
+ return `export default new URL(import.meta.ROLLUP_FILE_URL_${reference})`
+ }
+ }
+}
diff --git a/source/server/core/server-runtime/sandbox-bootstrap.ts b/source/server/core/server-runtime/sandbox-bootstrap.ts
index e683563..4183bc8 100644
--- a/source/server/core/server-runtime/sandbox-bootstrap.ts
+++ b/source/server/core/server-runtime/sandbox-bootstrap.ts
@@ -13,6 +13,7 @@ const QuickJS = await newQuickJSWASMModuleFromVariant(variant)
const runtime = QuickJS.newRuntime({ memoryLimitBytes: 128 * 1024 * 1024, maxStackSizeBytes: 2 * 1024 * 1024 })
const context = runtime.newContext()
const timers = new Map<number, { timer: ReturnType<typeof setTimeout>, callback: QuickJSHandle }>()
+const pendingResults = new Set<QuickJSHandle>()
const rejectedModule = "sandbox:rejected:"
let nextTimer = 1
let stopped = false
@@ -99,8 +100,8 @@ function installEnvironment(vm: QuickJSContext) {
const timer = setTimeout(() => {
timers.delete(identity)
- call(retained)
- retained.dispose()
+ try { call(retained) }
+ finally { retained.dispose() }
}, milliseconds)
timers.set(identity, { timer, callback: retained })
return vm.newNumber(identity)
@@ -120,8 +121,8 @@ function installEnvironment(vm: QuickJSContext) {
const retained = callback.dup()
queueMicrotask(() => {
- call(retained)
- retained.dispose()
+ try { call(retained) }
+ finally { retained.dispose() }
})
})
@@ -308,9 +309,11 @@ function installEnvironment(vm: QuickJSContext) {
const result = vm.callFunction(callback, vm.undefined)
if (result.error) {
- process.stderr.write(`${printable(vm.dump(result.error))}\n`)
+ const error = vm.dump(result.error)
result.error.dispose()
- } else result.value.dispose()
+ throw new Error(printable(error))
+ }
+ consumeResult(result.value)
pump()
}
}
@@ -324,7 +327,7 @@ function evaluate(code: string, filename: string, options?: { type: "module" | "
result.error.dispose()
throw new Error(printable(error))
}
- result.value.dispose()
+ consumeResult(result.value)
}
function pump() {
@@ -334,11 +337,41 @@ function pump() {
const result = runtime.executePendingJobs()
if (result.error) {
- process.stderr.write(`${printable(result.error.context.dump(result.error))}\n`)
+ const error = result.error.context.dump(result.error)
result.error.dispose()
- break
+ throw new Error(printable(error))
}
}
+
+ for (const result of [...pendingResults]) consumeResult(result)
+}
+
+function consumeResult(value: QuickJSHandle) {
+
+ // QuickJS reports synchronous exceptions through eval/call results, but a
+ // Promise rejection belongs to the returned Promise. Retain that result
+ // until it settles so an uncaught async callback has the same lifecycle
+ // consequence as an uncaught callback in a Worker or child process.
+ const state = context.getPromiseState(value)
+
+ if (state.type === "pending") {
+
+ pendingResults.add(value)
+ return
+ }
+
+ pendingResults.delete(value)
+ value.dispose()
+
+ if (state.type === "fulfilled") {
+
+ if (!state.notAPromise) state.value.dispose()
+ return
+ }
+
+ const error = context.dump(state.error)
+ state.error.dispose()
+ throw new Error(printable(error))
}
function confined(path: string) {
@@ -384,6 +417,8 @@ function dispose() {
retained.callback.dispose()
}
timers.clear()
+ for (const result of pendingResults) result.dispose()
+ pendingResults.clear()
context.dispose()
runtime.dispose()
}
diff --git a/source/server/core/server-runtime/sandbox.ts b/source/server/core/server-runtime/sandbox.ts
index 21ee394..a0cdaf2 100644
--- a/source/server/core/server-runtime/sandbox.ts
+++ b/source/server/core/server-runtime/sandbox.ts
@@ -1,15 +1,11 @@
import ThreadServerRuntime from "./thread"
+import bootstrap from "./sandbox-bootstrap.ts?worker-thread"
/** Runs one capability-contained JavaScript Server Endpoint in QuickJS. */
export default class SandboxServerRuntime extends ThreadServerRuntime {
public constructor(entry: string, root: string) {
- super(bootstrap("sandbox"), { entry, root })
+ super(bootstrap, { entry, root })
}
}
-
-function bootstrap(runtime: "sandbox") {
-
- return new URL(`./${runtime}-bootstrap.${import.meta.url.endsWith(".ts") ? "ts" : "js"}`, import.meta.url)
-}
diff --git a/source/server/core/server-runtime/worker.ts b/source/server/core/server-runtime/worker.ts
index ab928a8..9bddfeb 100644
--- a/source/server/core/server-runtime/worker.ts
+++ b/source/server/core/server-runtime/worker.ts
@@ -1,15 +1,11 @@
import ThreadServerRuntime from "./thread"
+import bootstrap from "./worker-bootstrap.ts?worker-thread"
/** Runs one JavaScript Server Endpoint in a Node Worker. */
export default class WorkerServerRuntime extends ThreadServerRuntime {
public constructor(entry: string) {
- super(bootstrap("worker"), { entry })
+ super(bootstrap, { entry })
}
}
-
-function bootstrap(runtime: "worker") {
-
- return new URL(`./${runtime}-bootstrap.${import.meta.url.endsWith(".ts") ? "ts" : "js"}`, import.meta.url)
-}
diff --git a/tests/worker-runtime.test.ts b/tests/worker-runtime.test.ts
index f67d271..859bc98 100644
--- a/tests/worker-runtime.test.ts
+++ b/tests/worker-runtime.test.ts
@@ -19,6 +19,9 @@ test("server runtime contract", async () => {
const dependency = join(directory, "dependency.mjs")
const bareEntry = join(directory, "bare.mjs")
const escapedEntry = join(directory, "escaped.mjs")
+ const failedEntry = join(directory, "failed.mjs")
+ const timerEntry = join(directory, "timer.mjs")
+ const asyncTimerEntry = join(directory, "async-timer.mjs")
const outsideDirectory = await mkdtemp(join(tmpdir(), "phresh-sandbox-outside-"))
const outsideModule = join(outsideDirectory, "outside.mjs")
const linkedModule = join(directory, "linked.mjs")
@@ -51,6 +54,9 @@ test("server runtime contract", async () => {
await writeFile(outsideModule, `export const outside = true\n`)
await symlink(outsideModule, linkedModule)
await writeFile(escapedEntry, `import "./linked.mjs"\n`)
+ await writeFile(failedEntry, `throw new Error("failed runtime module")\n`)
+ await writeFile(timerEntry, `setTimeout(() => { throw new Error("failed runtime timer") })\n`)
+ await writeFile(asyncTimerEntry, `setTimeout(async () => { throw new Error("failed async runtime timer") })\n`)
await writeFile(commandEntry, `
import { deserialize as decode, serialize as encode } from ${JSON.stringify(codec)}
@@ -96,6 +102,10 @@ test("server runtime contract", async () => {
await verifyContainedRuntime(new WorkerServerRuntime(entry))
await verifyContainedRuntime(new SandboxServerRuntime(entry, directory))
await verifyCodecRuntime(new SandboxServerRuntime(codecEntry, codecDirectory))
+ await verifyFailedRuntime(new WorkerServerRuntime(failedEntry), "failed runtime module")
+ await verifyFailedRuntime(new SandboxServerRuntime(failedEntry, directory), "failed runtime module")
+ await verifyFailedRuntime(new SandboxServerRuntime(timerEntry, directory), "failed runtime timer")
+ await verifyFailedRuntime(new SandboxServerRuntime(asyncTimerEntry, directory), "failed async runtime timer")
const sandbox = new Program({ identity: "sandbox-verification", server: { location: directory, sandbox: "server.mjs" } })
await sandbox.validate()
@@ -216,6 +226,27 @@ test("server runtime contract", async () => {
await runtime.finished
}
+ async function verifyFailedRuntime(runtime: WorkerServerRuntime | SandboxServerRuntime, message: string) {
+
+ const output: ["out" | "err", string][] = []
+ runtime.onOutput((stream, text) => output.push([stream, text]))
+
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ const expiration = new Promise<never>((_, reject) => {
+ timeout = setTimeout(() => reject(new Error(`${runtime.constructor.name} did not terminate after an uncaught error`)), 2_000)
+ })
+ let ending
+ try { ending = await Promise.race([runtime.finished, expiration]) }
+ finally {
+ if (timeout) clearTimeout(timeout)
+ runtime.stop()
+ }
+
+ assert.equal(ending.code, 1)
+ assert.equal(ending.signal, null)
+ assert.match(output.filter(([stream]) => stream === "err").map(([, text]) => text).join(""), new RegExp(message))
+ }
+
async function until(condition: () => boolean, timeout = 2_000) {
const began = Date.now()
diff --git a/vite.config.ts b/vite.config.ts
index be7823c..39cc34f 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,5 +1,6 @@
import packageConfig from "./package.json" with { type: "json" }
import decoratorPlugin from "./source/libs/decorator-plugin.js"
+import workerThreadPlugin from "./source/libs/worker-thread-plugin.js"
import { defineConfig } from "vite"
import { resolve } from "node:path"
@@ -10,7 +11,7 @@ export const externalDependencies: (keyof typeof packageConfig.dependencies)[] =
export default defineConfig({
root: "source/server",
- plugins: [decoratorPlugin()],
+ plugins: [decoratorPlugin(), workerThreadPlugin()],
resolve: {
tsconfigPaths: true
},
@@ -22,11 +23,7 @@ export default defineConfig({
emptyOutDir: true,
outDir: resolve(import.meta.dirname, "dist/server"),
rolldownOptions: {
- input: {
- main: "main.ts",
- "worker-bootstrap": "core/server-runtime/worker-bootstrap.ts",
- "sandbox-bootstrap": "core/server-runtime/sandbox-bootstrap.ts"
- }
+ input: "main.ts"
}
}
})
diff --git a/vitest.config.ts b/vitest.config.ts
index 086ca9b..3b95022 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -1,8 +1,9 @@
import { defineConfig } from "vitest/config"
import decoratorPlugin from "./source/libs/decorator-plugin.js"
+import workerThreadPlugin from "./source/libs/worker-thread-plugin.js"
export default defineConfig({
- plugins: [decoratorPlugin()],
+ plugins: [decoratorPlugin(), workerThreadPlugin()],
resolve: { tsconfigPaths: true },
test: {
pool: "forks",