Unverified Commit 332b0c51 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

feat(next-swc): add WASI loader hooks

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent fea76de6
...@@ -685,6 +685,7 @@ jobs: ...@@ -685,6 +685,7 @@ jobs:
# runtime provides it. See scripts/wasi-test-host/README.md, which also lists the platform # runtime provides it. See scripts/wasi-test-host/README.md, which also lists the platform
# limitations behind the tests that are `ignore`d on wasm. # limitations behind the tests that are `ignore`d on wasm.
export CARGO_TARGET_WASM32_WASIP1_THREADS_RUNNER="node $PWD/scripts/wasi-test-host/run.mjs" export CARGO_TARGET_WASM32_WASIP1_THREADS_RUNNER="node $PWD/scripts/wasi-test-host/run.mjs"
node --test packages/next/src/build/swc/wasi-loader.test.mjs
cargo test \ cargo test \
-p turbo-rcstr \ -p turbo-rcstr \
-p turbo-tasks \ -p turbo-tasks \
......
import process from 'node:process'
import { WASI } from 'node:wasi'
import { parentPort, workerData } from 'node:worker_threads'
import type { LoadPayload, WorkerMessageType } from '@emnapi/wasi-threads'
import {
createWasiImportObject,
initializeWasiThread,
type NapiModuleLike,
type WasiThreadWorkerData,
} from './wasi-loader'
import { createThreadRuntime } from './wasi-runtime'
async function listenForThreads(data: WasiThreadWorkerData) {
const port = parentPort
if (port === null) {
throw new Error('WASI thread worker has no parent port')
}
// @emnapi/wasi-threads is ESM-only. Keep package resolution dynamic because the eventual wasm
// package, like @emnapi/core, decides where this runtime dependency is provided.
const { ThreadMessageHandler } = await import(data.wasiThreadsModuleSpecifier)
const handler = new ThreadMessageHandler({
postMessage: (message: unknown) => port.postMessage(message),
onError(error: Error, type: WorkerMessageType) {
console.error(`wasi thread failed during ${type}:`, error)
process.exitCode = 1
},
async onLoad({ wasmModule, wasmMemory }: LoadPayload) {
const wasi = new WASI({
version: 'preview1',
args: data.args,
env: data.env,
preopens: data.preopens,
returnOnExit: true,
})
const emnapi = await import(data.napiModuleSpecifier)
const napiModule = emnapi.createNapiModule({
childThread: true,
postMessage: (message: unknown) => port.postMessage(message),
}) as NapiModuleLike
// A Tokio worker may itself spawn blocking workers. Give each instance a local manager so
// nested creation does not depend on the main event loop while the main wasm thread is parked.
const { threadSpawn } = await createThreadRuntime({
module: wasmModule,
memory: wasmMemory,
threadIds: data.threadIds,
workerPath: data.workerPath,
wasiThreadsModuleSpecifier: data.wasiThreadsModuleSpecifier,
workerData: {
args: data.args,
env: data.env,
preopens: data.preopens,
workerPath: data.workerPath,
napiModuleSpecifier: data.napiModuleSpecifier,
},
onError(error, threadId) {
const suffix = threadId === undefined ? '' : ` ${threadId}`
console.error(`wasi thread${suffix} failed:`, error)
process.exitCode = 1
},
})
const imports = createWasiImportObject({
module: wasmModule,
memory: wasmMemory,
napiImports: napiModule.imports,
wasiImports: wasi.getImportObject(),
threadSpawn,
})
const instance = await WebAssembly.instantiate(wasmModule, imports)
initializeWasiThread(wasi, instance)
napiModule.init({ instance, module: wasmModule, memory: wasmMemory })
return { module: wasmModule, instance }
},
})
port.on('message', (message) => handler.handle({ data: message }))
}
listenForThreads(workerData as WasiThreadWorkerData).catch((error) => {
console.error('wasi thread failed to initialize:', error)
process.exitCode = 1
})
import assert from 'node:assert/strict'
import { test } from 'node:test'
import loader from '../../../dist/build/swc/wasi-loader.js'
const {
createImportedMemory,
createReadCustomSection,
createThreadRuntime,
createWasiEnvironment,
createWasiImportObject,
initializeWasiThread,
nextThreadId,
WASI_MEMORY_INITIAL_PAGES,
WASI_MEMORY_MAXIMUM_PAGES,
} = loader
const uleb = (value) => {
const bytes = []
do {
let byte = value & 0x7f
value = Math.floor(value / 128)
if (value !== 0) byte |= 0x80
bytes.push(byte)
} while (value !== 0)
return bytes
}
const string = (value) => {
const bytes = Buffer.from(value)
return [...uleb(bytes.length), ...bytes]
}
function section(id, contents) {
return [id, ...uleb(contents.length), ...contents]
}
function buildModule({ initial = 1, maximum = 4, customSections = [] } = {}) {
const memory = [
...string('env'),
...string('memory'),
0x02,
...uleb(0x03),
...uleb(initial),
...uleb(maximum),
]
return new Uint8Array([
0x00,
0x61,
0x73,
0x6d,
0x01,
0x00,
0x00,
0x00,
...section(2, [...uleb(1), ...memory]),
...customSections.flatMap(({ name, bytes }) =>
section(0, [...string(name), ...bytes])
),
])
}
const CUSTOM_SECTION = '.data.link_section.TEST'
const CUSTOM_BYTES = [1, 2, 3, 4, 5]
async function customSectionFixture(
customSections = [{ name: CUSTOM_SECTION, bytes: CUSTOM_BYTES }]
) {
const bytes = buildModule({ customSections })
const module = await WebAssembly.compile(bytes)
const memory = new WebAssembly.Memory({ initial: 1, maximum: 4 })
const read = createReadCustomSection(module, memory)
const nameBytes = Buffer.from(CUSTOM_SECTION)
new Uint8Array(memory.buffer, 71, nameBytes.length).set(nameBytes)
return { memory, read, nameLength: nameBytes.length }
}
test('creates the shared memory configured by the WASI linker flags', () => {
const memory = createImportedMemory()
assert.equal(WASI_MEMORY_INITIAL_PAGES, 8_192)
assert.equal(WASI_MEMORY_MAXIMUM_PAGES, 65_536)
assert.equal(memory.buffer.byteLength, WASI_MEMORY_INITIAL_PAGES * 65_536)
assert.ok(memory.buffer instanceof SharedArrayBuffer)
})
test('implements the two-phase custom-section protocol', async () => {
const { memory, read, nameLength } = await customSectionFixture()
const target = 512
new Uint8Array(memory.buffer, target, CUSTOM_BYTES.length).fill(0xaa)
assert.equal(
read(71, nameLength, target, CUSTOM_BYTES.length - 1),
CUSTOM_BYTES.length
)
assert.deepEqual(
[...new Uint8Array(memory.buffer, target, CUSTOM_BYTES.length)],
[0xaa, 0xaa, 0xaa, 0xaa, 0xaa]
)
assert.equal(
read(71, nameLength, target, CUSTOM_BYTES.length),
CUSTOM_BYTES.length
)
assert.deepEqual(
[...new Uint8Array(memory.buffer, target, CUSTOM_BYTES.length)],
CUSTOM_BYTES
)
})
test('returns zero for a missing custom section and validates memory ranges', async () => {
const { memory, read, nameLength } = await customSectionFixture()
const missing = Buffer.from('.data.link_section.MISSING')
new Uint8Array(memory.buffer, 100, missing.length).set(missing)
assert.equal(read(100, missing.length, 512, 0), 0)
assert.throws(
() => read(-1, nameLength, 512, 10),
/outside WebAssembly memory/
)
assert.throws(
() => read(71, nameLength, memory.buffer.byteLength, CUSTOM_BYTES.length),
/outside WebAssembly memory/
)
})
test('rejects duplicate custom sections instead of picking one', async () => {
const { read, nameLength } = await customSectionFixture([
{ name: CUSTOM_SECTION, bytes: [1] },
{ name: CUSTOM_SECTION, bytes: [2] },
])
assert.throws(() => read(71, nameLength, 512, 8), /is ambiguous/)
})
test('aliases @emnapi/core napi imports into napi-sys env imports', async () => {
const bytes = buildModule({ customSections: [] })
const module = await WebAssembly.compile(bytes)
const memory = new WebAssembly.Memory({
initial: 1,
maximum: 4,
shared: true,
})
const napiGetValue = () => 1
const emnapiEnv = () => 2
const wasiFdWrite = () => 3
const threadSpawn = () => 4
const imports = createWasiImportObject({
module,
memory,
napiImports: {
napi: { napi_get_value: napiGetValue },
env: { _emnapi_env_ref: emnapiEnv },
emnapi: { emnapi_sync_memory: () => 5 },
},
wasiImports: {
wasi_snapshot_preview1: { fd_write: wasiFdWrite },
wasi: { existing: () => 6 },
},
threadSpawn,
})
assert.equal(imports.env.napi_get_value, napiGetValue)
assert.equal(imports.env._emnapi_env_ref, emnapiEnv)
assert.equal(imports.env.memory, memory)
assert.equal(typeof imports.env.read_custom_section, 'function')
assert.equal(imports.wasi['thread-spawn'], threadSpawn)
assert.equal(imports.wasi_snapshot_preview1.fd_write, wasiFdWrite)
})
test('allocates thread ids atomically from shared state', () => {
const ids = new Int32Array(new SharedArrayBuffer(4))
assert.equal(nextThreadId(ids), 1)
assert.equal(nextThreadId(ids), 2)
assert.throws(() => nextThreadId(new Int32Array(1)), /shared Int32Array/)
})
test('uses Node parallelism by default and preserves unrelated env', () => {
assert.deepEqual(createWasiEnvironment({ KEEP: 'yes' }, 6), {
TURBO_TASKS_AVAILABLE_PARALLELISM: '6',
KEEP: 'yes',
})
assert.deepEqual(
createWasiEnvironment({ TURBO_TASKS_AVAILABLE_PARALLELISM: '2' }, 6),
{ TURBO_TASKS_AVAILABLE_PARALLELISM: '2' }
)
})
test('transfers one compiled module through the shared thread manager', async () => {
const workers = []
class FakeWorker {
messages = []
unreferenced = false
constructor(filename, options) {
this.filename = filename
this.options = options
workers.push(this)
}
postMessage(message) {
this.messages.push(message)
}
unref() {
this.unreferenced = true
}
}
class FakeThreadManager {
pthreads = Object.create(null)
constructor(options) {
this.options = options
}
init() {}
setup(module, memory) {
this.module = module
this.memory = memory
}
getNewWorker() {
const worker = this.options.onCreateWorker()
worker.postMessage({
__emnapi__: {
type: 'load',
payload: { wasmModule: this.module, wasmMemory: this.memory },
},
})
return worker
}
}
const module = { compiled: true }
const memory = new WebAssembly.Memory({
initial: 1,
maximum: 4,
shared: true,
})
const ids = new Int32Array(new SharedArrayBuffer(4))
const { threadSpawn, manager } = await createThreadRuntime({
module,
memory,
threadIds: ids,
workerData: {
args: ['test.wasm'],
env: { KEEP: 'yes' },
preopens: {},
workerPath: '/loader-worker.js',
napiModuleSpecifier: '/emnapi-provider.js',
},
workerPath: '/loader-worker.js',
wasiThreadsModuleSpecifier: '/wasi-threads-provider.js',
onError: assert.fail,
WorkerClass: FakeWorker,
ThreadManagerClass: FakeThreadManager,
})
assert.equal(threadSpawn(41), 1)
assert.equal(manager.module, module)
assert.equal(manager.memory, memory)
assert.equal(workers[0].options.workerData.threadIds, ids)
assert.equal('bytes' in workers[0].options.workerData, false)
assert.equal(
workers[0].options.workerData.wasiThreadsModuleSpecifier,
'/wasi-threads-provider.js'
)
assert.equal(workers[0].messages[0].__emnapi__.payload.wasmModule, module)
assert.equal(workers[0].messages[0].__emnapi__.payload.wasmMemory, memory)
assert.deepEqual(workers[0].messages[1], {
__emnapi__: { type: 'start', payload: { tid: 1, arg: 41 } },
})
assert.equal(workers[0].unreferenced, true)
})
test('spawned threads initialize WASI without _start before entering the thread', () => {
const calls = []
const wasi = {
initialize(instance) {
calls.push(['initialize', instance.exports])
},
}
const instance = {
exports: {
_start: () => calls.push(['unexpected start']),
wasi_thread_start: (id, arg) => calls.push(['thread start', id, arg]),
},
}
initializeWasiThread(wasi, instance)(7, 11)
assert.equal('_start' in calls[0][1], false)
assert.deepEqual(calls[1], ['thread start', 7, 11])
assert.throws(
() => initializeWasiThread(wasi, { exports: {} }),
/does not export wasi_thread_start/
)
})
/**
* Instantiation hooks for a `wasm32-wasip1-threads` build of the native bindings.
*
* Such a module cannot be instantiated by a stock WASI runtime: `turbo-tasks` collects its task
* registries with `link-section`, whose wasm host contract requires `env.read_custom_section`, and
* Node's WASI implementation does not provide the wasi-threads proposal's `wasi.thread-spawn`
* import. The common host support lives in `./wasi-runtime`; `scripts/wasi-test-host/` consumes the
* compiled copy so the production loader and test runner cannot drift.
*
* This is groundwork only — nothing here is wired into the SWC-only wasm fallback in `./index.ts`,
* and `module_init` (absent on wasm) and packaging are deliberately out of scope, so loading
* Turbopack from wasm does not work yet.
*/
import path from 'node:path'
import {
createImportedMemory,
createReadCustomSection,
createThreadRuntime,
createWasiEnvironment,
nextThreadId,
WASI_MEMORY_INITIAL_PAGES,
WASI_MEMORY_MAXIMUM_PAGES,
type WasiThreadWorkerData as RuntimeWorkerData,
} from './wasi-runtime'
export {
createImportedMemory,
createReadCustomSection,
createThreadRuntime,
createWasiEnvironment,
nextThreadId,
WASI_MEMORY_INITIAL_PAGES,
WASI_MEMORY_MAXIMUM_PAGES,
}
type ImportNamespace = Record<string, WebAssembly.ImportValue>
export type NapiModuleLike = {
imports: WebAssembly.Imports
init(options: {
instance: WebAssembly.Instance
module: WebAssembly.Module
memory: WebAssembly.Memory
}): void
}
export type WasiLike = {
getImportObject(): object
initialize(instance: WebAssembly.Instance): void
}
export type WasiThreadWorkerData = RuntimeWorkerData & {
args: string[]
env: Record<string, string>
preopens: Record<string, string>
workerPath: string
napiModuleSpecifier: string
}
/**
* napi-sys imports N-API symbols from env, while @emnapi/core exposes them in its napi namespace.
* Alias those functions into env and add the WASI hooks.
*/
export function createWasiImportObject(options: {
module: WebAssembly.Module
memory: WebAssembly.Memory
napiImports: WebAssembly.Imports
wasiImports: object
threadSpawn: (startArg: number) => number
}): WebAssembly.Imports {
const { module, memory, napiImports, threadSpawn } = options
const wasiImports = options.wasiImports as WebAssembly.Imports
const napi = (napiImports.napi ?? {}) as ImportNamespace
const napiEnv = (napiImports.env ?? {}) as ImportNamespace
const wasiThreads = (wasiImports.wasi ?? {}) as ImportNamespace
return {
...napiImports,
...wasiImports,
env: {
...napi,
...napiEnv,
memory,
read_custom_section: createReadCustomSection(module, memory),
},
wasi: {
...wasiThreads,
'thread-spawn': threadSpawn,
},
}
}
/**
* Bind WASI for a worker without running the command-only `_start` export.
*
* `WASI#initialize` rejects a command exporting `_start`, which must run exactly once on the main
* thread. `ThreadMessageHandler` enters the bound instance through `wasi_thread_start` instead.
*/
export function initializeWasiThread(
wasi: WasiLike,
instance: WebAssembly.Instance
) {
const threadStart = instance.exports.wasi_thread_start
if (typeof threadStart !== 'function') {
throw new Error('spawned wasm instance does not export wasi_thread_start')
}
const threadExports = { ...instance.exports }
delete threadExports._start
wasi.initialize({ exports: threadExports } as WebAssembly.Instance)
return threadStart
}
export async function instantiateWasiNapiModule(options: {
bytes: Uint8Array
napiModule: NapiModuleLike
wasi: WasiLike
args?: string[]
env?: Record<string, string>
preopens?: Record<string, string>
onThreadError: (error: Error, threadId: number | undefined) => void
workerPath?: string
napiModuleSpecifier?: string
wasiThreadsModuleSpecifier?: string
}) {
const { bytes, napiModule, wasi } = options
const args = options.args ?? []
const env = options.env ?? {}
const preopens = options.preopens ?? {}
const workerPath =
options.workerPath ?? path.join(__dirname, 'wasi-loader-worker.js')
const napiModuleSpecifier = options.napiModuleSpecifier ?? '@emnapi/core'
const wasiThreadsModuleSpecifier =
options.wasiThreadsModuleSpecifier ?? '@emnapi/wasi-threads'
const module = await WebAssembly.compile(Uint8Array.from(bytes))
const memory = createImportedMemory()
const threadIds = new Int32Array(
new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)
)
const { threadSpawn } = await createThreadRuntime({
module,
memory,
threadIds,
workerPath,
wasiThreadsModuleSpecifier,
workerData: {
args,
env,
preopens,
workerPath,
napiModuleSpecifier,
},
onError: options.onThreadError,
})
const imports = createWasiImportObject({
module,
memory,
napiImports: napiModule.imports,
wasiImports: wasi.getImportObject(),
threadSpawn,
})
const instance = await WebAssembly.instantiate(module, imports)
wasi.initialize(instance)
napiModule.init({ instance, module, memory })
return { instance, module, memory, threadIds }
}
import { availableParallelism } from 'node:os'
import path from 'node:path'
import { Worker } from 'node:worker_threads'
import type {
ThreadManager as EmnapiThreadManager,
WorkerLike as EmnapiWorkerLike,
} from '@emnapi/wasi-threads'
const WASM_PAGE_SIZE_BYTES = 65_536
// 512 MiB. Keep in sync with --initial-memory in .cargo/config.toml.
export const WASI_MEMORY_INITIAL_PAGES = 536_870_912 / WASM_PAGE_SIZE_BYTES
// 4 GiB. Keep in sync with --max-memory in .cargo/config.toml.
export const WASI_MEMORY_MAXIMUM_PAGES = 4_294_967_296 / WASM_PAGE_SIZE_BYTES
const PARALLELISM_ENV = 'TURBO_TASKS_AVAILABLE_PARALLELISM'
export type WasiThreadWorkerData = {
threadIds: Int32Array
wasiThreadsModuleSpecifier: string
[key: string]: unknown
}
type ThreadManagerConstructor = typeof EmnapiThreadManager
type WorkerConstructor = new (
filename: string,
options: {
workerData: WasiThreadWorkerData
stdout: false
stderr: false
}
) => EmnapiWorkerLike
/** Pass Node's effective CPU allowance into Rust before WASI constructors run. */
export function createWasiEnvironment(
env: Record<string, string> = {},
detectedParallelism = availableParallelism()
) {
return {
[PARALLELISM_ENV]: String(env[PARALLELISM_ENV] ?? detectedParallelism),
...env,
}
}
/** Create the shared memory configured by the wasm32-wasip1-threads linker flags. */
export function createImportedMemory() {
return new WebAssembly.Memory({
initial: WASI_MEMORY_INITIAL_PAGES,
maximum: WASI_MEMORY_MAXIMUM_PAGES,
shared: true,
})
}
function memoryView(
memory: WebAssembly.Memory,
pointer: number,
length: number,
purpose: string
) {
if (
!Number.isSafeInteger(pointer) ||
!Number.isSafeInteger(length) ||
pointer < 0 ||
length < 0 ||
pointer + length > memory.buffer.byteLength
) {
throw new RangeError(`${purpose} is outside WebAssembly memory`)
}
return new Uint8Array(memory.buffer, pointer, length)
}
/**
* Implement the two-phase `env.read_custom_section` contract documented by `link-section`.
*
* https://github.com/mmastrac/linktime/blob/ae29e51d94a955df2442ed6418b8a712c1f2bfb3/link-section/docs/PREAMBLE.md#wasm
*/
export function createReadCustomSection(
module: WebAssembly.Module,
memory: WebAssembly.Memory
) {
const decoder = new TextDecoder('utf-8', { fatal: true })
return (
namePtr: number,
nameLength: number,
targetPtr: number,
targetLength: number
) => {
const sectionName = decoder.decode(
Uint8Array.from(memoryView(memory, namePtr, nameLength, 'section name'))
)
const sections = WebAssembly.Module.customSections(module, sectionName)
if (sections.length === 0) return 0
if (sections.length !== 1) {
throw new Error(
`custom section ${JSON.stringify(sectionName)} is ambiguous`
)
}
const section = new Uint8Array(sections[0])
if (targetLength < section.byteLength) return section.byteLength
memoryView(
memory,
targetPtr,
section.byteLength,
'custom section target'
).set(section)
return section.byteLength
}
}
/** Atomically allocate IDs shared by the main instance and every Worker-owned manager. */
export function nextThreadId(threadIds: Int32Array) {
if (
threadIds.length !== 1 ||
!(threadIds.buffer instanceof SharedArrayBuffer)
) {
throw new TypeError('threadIds must be a one-element shared Int32Array')
}
const threadId = Atomics.add(threadIds, 0, 1) + 1
if (threadId <= 0) {
throw new RangeError('wasi thread id counter overflowed')
}
return threadId
}
/**
* Create the old one-argument `wasi.thread-spawn` ABI over `@emnapi/wasi-threads` primitives.
*
* The package's high-level wrapper calls guest `malloc`/`free` for this ABI, but Rust test binaries
* do not export them. A local manager per Worker also permits recursive spawning while the main wasm
* thread is parked; all managers share one atomic ID counter.
*/
export async function createThreadRuntime(options: {
module: WebAssembly.Module
memory: WebAssembly.Memory
threadIds: Int32Array
workerData?: Record<string, unknown>
workerPath?: string
wasiThreadsModuleSpecifier?: string
onError: (error: Error, threadId: number | undefined) => void
WorkerClass?: WorkerConstructor
ThreadManagerClass?: ThreadManagerConstructor
}): Promise<{
threadSpawn: (startArg: number) => number
manager: EmnapiThreadManager
}> {
const {
module,
memory,
threadIds,
workerData = {},
workerPath = path.join(__dirname, 'wasi-loader-worker.js'),
wasiThreadsModuleSpecifier = '@emnapi/wasi-threads',
onError,
WorkerClass = Worker as unknown as WorkerConstructor,
} = options
const ThreadManagerClass =
options.ThreadManagerClass ??
((await import(wasiThreadsModuleSpecifier))
.ThreadManager as ThreadManagerConstructor)
class SharedIdThreadManager extends ThreadManagerClass {
override markId(worker: EmnapiWorkerLike) {
if (worker.__emnapi_tid !== undefined) return worker.__emnapi_tid
const threadId = nextThreadId(threadIds)
this.pthreads[threadId] = worker
worker.__emnapi_tid = threadId
return threadId
}
}
const manager = new SharedIdThreadManager({
reuseWorker: false,
onCreateWorker: () =>
new WorkerClass(workerPath, {
workerData: {
...workerData,
threadIds,
wasiThreadsModuleSpecifier,
},
stdout: false,
stderr: false,
}),
printErr: (message) => onError(new Error(String(message)), undefined),
})
manager.init()
// ThreadManager structured-clones the already-compiled module in its `load` message.
manager.setup(module, memory)
const threadSpawn = (startArg: number) => {
try {
const worker = manager.getNewWorker()
if (!worker) return -1
const threadId = manager.markId(worker)
worker.postMessage({
__emnapi__: {
type: 'start',
payload: { tid: threadId, arg: startArg },
},
})
if ('unref' in worker) worker.unref()
return threadId
} catch (error) {
onError(
error instanceof Error ? error : new Error(String(error)),
undefined
)
return -1
}
}
manager.threadSpawn = threadSpawn
return { threadSpawn, manager }
}
...@@ -23,14 +23,15 @@ The other missing host feature is ...@@ -23,14 +23,15 @@ The other missing host feature is
memory and atomics, but Node's `WASI#getImportObject()` exposes only `wasi_snapshot_preview1`, not the memory and atomics, but Node's `WASI#getImportObject()` exposes only `wasi_snapshot_preview1`, not the
proposal's `wasi` namespace. `@emnapi/wasi-threads` bridges that import to Node Workers. proposal's `wasi` namespace. `@emnapi/wasi-threads` bridges that import to Node Workers.
The same hook will be needed by the Next.js wasm loader for Turbopack itself, so the The Next.js production loader needs the same hooks. Their single implementation now lives in
`read_custom_section` implementation here is a first cut of that work rather than test-only `packages/next/src/build/swc/wasi-runtime.ts`; this runner imports the compiled copy instead of
scaffolding. maintaining test-only versions that could drift.
## Usage ## Usage
```sh ```sh
pnpm install pnpm install
pnpm --filter next build
export CARGO_TARGET_WASM32_WASIP1_THREADS_RUNNER="node scripts/wasi-test-host/run.mjs" export CARGO_TARGET_WASM32_WASIP1_THREADS_RUNNER="node scripts/wasi-test-host/run.mjs"
cargo test -p turbo-tasks --lib --target wasm32-wasip1-threads cargo test -p turbo-tasks --lib --target wasm32-wasip1-threads
cargo test -p turbo-tasks-backend --lib --target wasm32-wasip1-threads cargo test -p turbo-tasks-backend --lib --target wasm32-wasip1-threads
...@@ -40,14 +41,22 @@ Building for that target also needs a WASI C toolchain, because `lz4-sys` and `z ...@@ -40,14 +41,22 @@ Building for that target also needs a WASI C toolchain, because `lz4-sys` and `z
scripts — see the `test-next-napi-bindings-wasi` job in `.github/workflows/build_and_test.yml` for the scripts — see the `test-next-napi-bindings-wasi` job in `.github/workflows/build_and_test.yml` for the
wasi-sdk setup. wasi-sdk setup.
Its own tests run against the same compiled production support:
```sh
node --test packages/next/src/build/swc/wasi-loader.test.mjs
```
(Pass the file. `node --test <dir>` tries to resolve the directory as a module and fails.)
## What it provides ## What it provides
| Import | Source | | Import | Source |
|---|---| |---|---|
| `wasi_snapshot_preview1.*` | `node:wasi` | | `wasi_snapshot_preview1.*` | `node:wasi` |
| `wasi.thread-spawn` | `@emnapi/wasi-threads` over `node:worker_threads` (`spawn.mjs`) | | `wasi.thread-spawn` | `@emnapi/wasi-threads` over `node:worker_threads` |
| `env.memory` | a shared `WebAssembly.Memory` matching the explicit linker limits in `.cargo/config.toml` | | `env.memory` | shared `WebAssembly.Memory` created by `packages/next/dist/build/swc/wasi-runtime.js` |
| `env.read_custom_section` | `WebAssembly.Module.customSections` (`lib.mjs`) | | `env.read_custom_section` | `WebAssembly.Module.customSections`, from the same shared runtime |
| filesystem | working directory at `/`; the system `os.tmpdir()` at `/tmp`, also exported as `TMPDIR` | | filesystem | working directory at `/`; the system `os.tmpdir()` at `/tmp`, also exported as `TMPDIR` |
`@emnapi/wasi-threads` owns Worker lifecycle, compiled-module transfer, load/start ordering, and `@emnapi/wasi-threads` owns Worker lifecycle, compiled-module transfer, load/start ordering, and
...@@ -57,8 +66,8 @@ uses for that ABI. ...@@ -57,8 +66,8 @@ uses for that ABI.
The imported shared memory uses 8,192 initial pages (512 MiB) and 65,536 maximum pages (4 GiB). The imported shared memory uses 8,192 initial pages (512 MiB) and 65,536 maximum pages (4 GiB).
Those values are also explicit `wasm32-wasip1-threads` linker flags in `.cargo/config.toml`; keep the Those values are also explicit `wasm32-wasip1-threads` linker flags in `.cargo/config.toml`; keep the
host constants and linker byte values in sync. A shared WebAssembly memory must declare a maximum, shared runtime constants and linker byte values in sync. A shared WebAssembly memory must declare a
and 65,536 pages is the wasm32 architectural ceiling. maximum, and 65,536 pages is the wasm32 architectural ceiling.
### `read_custom_section` ### `read_custom_section`
...@@ -95,7 +104,7 @@ module's `wasi_thread_start` export. Three details are worth knowing: ...@@ -95,7 +104,7 @@ module's `wasi_thread_start` export. Three details are worth knowing:
shared memory so they stay unique across all of them. shared memory so they stay unique across all of them.
- **`wasi.initialize()` refuses a module exporting `_start`**, since that marks a command whose - **`wasi.initialize()` refuses a module exporting `_start`**, since that marks a command whose
`_start` must run exactly once, on the main thread. A spawned thread hides that export to get the `_start` must run exactly once, on the main thread. A spawned thread hides that export to get the
WASI binding, then calls `wasi_thread_start` itself. WASI binding; `ThreadMessageHandler` then calls `wasi_thread_start`.
## Tests that cannot run on wasm ## Tests that cannot run on wasm
......
/** /**
* Host support for running `wasm32-wasip1-threads` test binaries that link `turbo-tasks`. * Test-host access to the production-owned WASI support.
* *
* Such a binary cannot be run by a stock WASI runtime, because `turbo-tasks` gathers its task * The CI job builds `packages/next` before running Rust tests, so importing its compiled CommonJS
* registries with the `link-section` crate, which on wasm stores them in **custom sections** and * output keeps the memory contract and link-section handling identical to the production loader.
* requires the embedder to hand them back through an `env.read_custom_section` import. See the
* [`link-section` wasm preamble](https://github.com/mmastrac/linktime/blob/ae29e51d94a955df2442ed6418b8a712c1f2bfb3/link-section/docs/PREAMBLE.md#wasm);
* the implementation below is that contract.
*
* Worker lifecycle and compiled-module transfer come from `@emnapi/wasi-threads`; this file contains
* only the Turbopack-specific custom-section hook and shared-memory contract.
*/ */
const WASM_PAGE_SIZE_BYTES = 65_536 import wasiRuntime from '../../packages/next/dist/build/swc/wasi-runtime.js'
// 512 MiB. Keep in sync with --initial-memory in .cargo/config.toml.
export const WASI_MEMORY_INITIAL_PAGES = 536_870_912 / WASM_PAGE_SIZE_BYTES export const {
// 4 GiB. Keep in sync with --max-memory in .cargo/config.toml. createImportedMemory,
export const WASI_MEMORY_MAXIMUM_PAGES = 4_294_967_296 / WASM_PAGE_SIZE_BYTES createReadCustomSection,
WASI_MEMORY_INITIAL_PAGES,
WASI_MEMORY_MAXIMUM_PAGES,
} = wasiRuntime
/** Guest path mapped to the host's real temporary directory by the test runner. */ /** Guest path mapped to the system's real temporary directory by the test runner. */
export const WASI_TEST_TEMP_DIR = '/tmp' export const WASI_TEST_TEMP_DIR = '/tmp'
/** Build the environment and preopens shared by the main instance and all pthread instances. */ /** Build the environment and preopens shared by the main instance and all pthread instances. */
...@@ -27,51 +24,3 @@ export function createWasiTestEnvironment(env, cwd, hostTempDir) { ...@@ -27,51 +24,3 @@ export function createWasiTestEnvironment(env, cwd, hostTempDir) {
preopens: { '/': cwd, [WASI_TEST_TEMP_DIR]: hostTempDir }, preopens: { '/': cwd, [WASI_TEST_TEMP_DIR]: hostTempDir },
} }
} }
/** Create the imported shared memory configured by the wasm32-wasip1-threads linker flags. */
export function createImportedMemory() {
return new WebAssembly.Memory({
initial: WASI_MEMORY_INITIAL_PAGES,
maximum: WASI_MEMORY_MAXIMUM_PAGES,
shared: true,
})
}
/**
* Implements the `env.read_custom_section` import that `link-section` requires on wasm. The exact
* guest/host contract is documented in the
* [`link-section` wasm preamble](https://github.com/mmastrac/linktime/blob/ae29e51d94a955df2442ed6418b8a712c1f2bfb3/link-section/docs/PREAMBLE.md#wasm).
*
* The protocol is two-phase, so the guest can ask for the size before allocating:
*
* - the section does not exist -> return 0, copy nothing;
* - `targetLength` is too small -> return the size needed, copy nothing;
* - otherwise -> copy the section into guest memory and return how many bytes were written.
*
* Returning 0 unconditionally would let a module instantiate with **empty** registries, which fails
* later in confusing ways rather than at the point of the mistake, so the real sections are read.
*
* @param {WebAssembly.Module} module
* @param {WebAssembly.Memory} memory
* @returns {(namePtr: number, nameLength: number, targetPtr: number, targetLength: number) => number}
*/
export function createReadCustomSection(module, memory) {
const decoder = new TextDecoder()
return (namePtr, nameLength, targetPtr, targetLength) => {
const nameBytes = new Uint8Array(memory.buffer, namePtr, nameLength)
// The name has to be copied out before decoding: a shared growable buffer can be detached.
const sectionName = decoder.decode(new Uint8Array(nameBytes))
const sections = WebAssembly.Module.customSections(module, sectionName)
if (sections.length === 0) return 0
const section = new Uint8Array(sections[0])
if (targetLength < section.byteLength) {
// Report the required size; the guest will call again with a large enough buffer.
return section.byteLength
}
new Uint8Array(memory.buffer, targetPtr, section.byteLength).set(section)
return section.byteLength
}
}
...@@ -13,6 +13,7 @@ import { WASI } from 'node:wasi' ...@@ -13,6 +13,7 @@ import { WASI } from 'node:wasi'
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import { tmpdir } from 'node:os' import { tmpdir } from 'node:os'
import process from 'node:process' import process from 'node:process'
import { fileURLToPath } from 'node:url'
import { import {
createImportedMemory, createImportedMemory,
...@@ -21,6 +22,8 @@ import { ...@@ -21,6 +22,8 @@ import {
} from './lib.mjs' } from './lib.mjs'
import { createThreadRuntime } from './spawn.mjs' import { createThreadRuntime } from './spawn.mjs'
const THREAD_WORKER = fileURLToPath(new URL('./thread.mjs', import.meta.url))
const [wasmPath, ...testArgs] = process.argv.slice(2) const [wasmPath, ...testArgs] = process.argv.slice(2)
if (!wasmPath) { if (!wasmPath) {
console.error('usage: run.mjs <binary.wasm> [test args...]') console.error('usage: run.mjs <binary.wasm> [test args...]')
...@@ -39,7 +42,6 @@ const { env, preopens } = createWasiTestEnvironment( ...@@ -39,7 +42,6 @@ const { env, preopens } = createWasiTestEnvironment(
process.cwd(), process.cwd(),
tmpdir() tmpdir()
) )
const wasi = new WASI({ const wasi = new WASI({
version: 'preview1', version: 'preview1',
args, args,
...@@ -55,13 +57,16 @@ const wasi = new WASI({ ...@@ -55,13 +57,16 @@ const wasi = new WASI({
*/ */
const threadIds = new Int32Array(new SharedArrayBuffer(4)) const threadIds = new Int32Array(new SharedArrayBuffer(4))
const { threadSpawn } = createThreadRuntime({ const { threadSpawn } = await createThreadRuntime({
module, module,
memory, memory,
threadIds, threadIds,
args, workerPath: THREAD_WORKER,
env, workerData: {
preopens, args,
env,
preopens,
},
onError: (error, threadId) => { onError: (error, threadId) => {
// A thread that dies takes the process with it, like a real aborted thread would. // A thread that dies takes the process with it, like a real aborted thread would.
const suffix = threadId === undefined ? '' : ` ${threadId}` const suffix = threadId === undefined ? '' : ` ${threadId}`
......
/** /** Test-host access to the production-owned WASI thread manager. */
* `wasi.thread-spawn` over `node:worker_threads`.
*
* V8 supports shared WebAssembly memory and atomics, but Node's WASI implementation only supplies
* `wasi_snapshot_preview1`; it does not implement the `wasi.thread-spawn` host import from the
* wasi-threads proposal. `@emnapi/wasi-threads` supplies the Worker lifecycle and transfers the
* already-compiled module to each Worker.
*
* Spec: https://github.com/WebAssembly/wasi-threads
*/
import { ThreadManager } from '@emnapi/wasi-threads' import wasiRuntime from '../../packages/next/dist/build/swc/wasi-runtime.js'
import { Worker } from 'node:worker_threads'
import { fileURLToPath } from 'node:url'
const THREAD_WORKER = fileURLToPath(new URL('./thread.mjs', import.meta.url)) export const { createThreadRuntime, nextThreadId } = wasiRuntime
/**
* Allocate thread ids from one shared counter so ids stay unique across every thread that spawns.
*
* A plain JS variable would not do: each Worker has its own module instance, so each would hand out
* ids starting from the same value. `Atomics.add` on shared memory is the only counter all of them
* can see.
*
* @param {Int32Array} threadIds a one-element `Int32Array` over a `SharedArrayBuffer`
*/
export function nextThreadId(threadIds) {
if (
threadIds.length !== 1 ||
!(threadIds.buffer instanceof SharedArrayBuffer)
) {
throw new TypeError('threadIds must be a one-element shared Int32Array')
}
// Main thread is 0; spawned threads start at 1.
const threadId = Atomics.add(threadIds, 0, 1) + 1
if (threadId <= 0) {
throw new RangeError('wasi thread id counter overflowed')
}
return threadId
}
/**
* Build a `wasi.thread-spawn` implementation and Worker manager for one instance.
*
* Rust currently imports the proposal's original one-argument ABI, which returns the new thread id
* directly. `WASIThreads` supports that ABI by calling guest `malloc`/`free`, but Rust test binaries
* do not export those functions. The lower-level manager and handler do not impose that requirement,
* so this small adapter preserves the original ABI while delegating module transfer, load/start
* ordering, cleanup, and Worker lifecycle to `@emnapi/wasi-threads`.
*
* Every Worker creates a local manager because a Tokio worker may itself spawn a thread while the
* main wasm thread is parked in `Atomics.wait`. All managers allocate IDs from the same shared
* counter.
*
* @param {{ module: WebAssembly.Module, memory: WebAssembly.Memory, threadIds: Int32Array, args: string[], env: Record<string, string>, preopens: Record<string, string>, onError: (error: Error, threadId: number | undefined) => void, workerPath?: string, WorkerClass?: typeof Worker, ThreadManagerClass?: typeof ThreadManager }} context
*/
export function createThreadRuntime(context) {
const {
module,
memory,
threadIds,
args,
env,
preopens,
onError,
workerPath = THREAD_WORKER,
WorkerClass = Worker,
ThreadManagerClass = ThreadManager,
} = context
class SharedIdThreadManager extends ThreadManagerClass {
markId(worker) {
if (worker.__emnapi_tid !== undefined) return worker.__emnapi_tid
const threadId = nextThreadId(threadIds)
this.pthreads[threadId] = worker
worker.__emnapi_tid = threadId
return threadId
}
}
const manager = new SharedIdThreadManager({
reuseWorker: false,
onCreateWorker: () =>
new WorkerClass(workerPath, {
workerData: { threadIds, args, env, preopens },
// Inherit stdio so panics and test output from threads reach the terminal.
stdout: false,
stderr: false,
}),
printErr: (message) => onError(new Error(String(message)), undefined),
})
manager.init()
// `ThreadManager` posts these structured-cloneable values in its `load` message. In particular,
// Workers receive the compiled module rather than the original bytes, so they only instantiate.
manager.setup(module, memory)
const threadSpawn = (startArg) => {
try {
const worker = manager.getNewWorker()
if (!worker) return -1
const threadId = manager.markId(worker)
worker.postMessage({
__emnapi__: {
type: 'start',
payload: { tid: threadId, arg: startArg },
},
})
worker.unref()
return threadId
} catch (error) {
onError(
error instanceof Error ? error : new Error(String(error)),
undefined
)
return -1
}
}
// The package calls this callback if a child-mode handler asks its owner to spawn. Our workers
// normally own local managers instead, but keeping the callback set makes the manager complete.
manager.threadSpawn = threadSpawn
return { threadSpawn, manager }
}
/** /** Worker body for one `wasi.thread-spawn`ed test thread. */
* Worker body for one `wasi.thread-spawn`ed thread.
*
* `@emnapi/wasi-threads` sends the compiled module and shared memory in a `load` message, then queues
* the `start` message until instantiation finishes. No Worker recompiles the wasm bytes.
*/
import { ThreadMessageHandler } from '@emnapi/wasi-threads'
import process from 'node:process' import process from 'node:process'
import { fileURLToPath } from 'node:url'
import { WASI } from 'node:wasi' import { WASI } from 'node:wasi'
import { parentPort, workerData } from 'node:worker_threads' import { parentPort, workerData } from 'node:worker_threads'
import { createReadCustomSection } from './lib.mjs' import { createReadCustomSection } from './lib.mjs'
import { createThreadRuntime } from './spawn.mjs' import { createThreadRuntime } from './spawn.mjs'
const { threadIds, args, env, preopens } = workerData const { threadIds, wasiThreadsModuleSpecifier, args, env, preopens } =
workerData
const { ThreadMessageHandler } = await import(wasiThreadsModuleSpecifier)
const THREAD_WORKER = fileURLToPath(new URL('./thread.mjs', import.meta.url))
const handler = new ThreadMessageHandler({ const handler = new ThreadMessageHandler({
postMessage: (message) => parentPort.postMessage(message), postMessage: (message) => parentPort.postMessage(message),
...@@ -29,36 +27,28 @@ const handler = new ThreadMessageHandler({ ...@@ -29,36 +27,28 @@ const handler = new ThreadMessageHandler({
preopens, preopens,
returnOnExit: true, returnOnExit: true,
}) })
const { threadSpawn } = await createThreadRuntime({
// A Tokio worker may itself spawn blocking workers. Give every instance a local manager so that
// nested spawning does not depend on the main JS event loop while the main wasm thread is parked.
const { threadSpawn } = createThreadRuntime({
module: wasmModule, module: wasmModule,
memory: wasmMemory, memory: wasmMemory,
threadIds, threadIds,
args, workerData: { args, env, preopens },
env, workerPath: THREAD_WORKER,
preopens, wasiThreadsModuleSpecifier,
onError: (error, threadId) => { onError: (error, threadId) => {
const suffix = threadId === undefined ? '' : ` ${threadId}` const suffix = threadId === undefined ? '' : ` ${threadId}`
console.error(`wasi thread${suffix} failed:`, error) console.error(`wasi thread${suffix} failed:`, error)
process.exit(1) process.exit(1)
}, },
}) })
const instance = await WebAssembly.instantiate(wasmModule, { const instance = await WebAssembly.instantiate(wasmModule, {
...wasi.getImportObject(), ...wasi.getImportObject(),
env: { env: {
memory: wasmMemory, memory: wasmMemory,
read_custom_section: createReadCustomSection(wasmModule, wasmMemory), read_custom_section: createReadCustomSection(wasmModule, wasmMemory),
}, },
wasi: { wasi: { 'thread-spawn': threadSpawn },
'thread-spawn': threadSpawn,
},
}) })
// Bind preview1 imports without invoking the command's `_start`; ThreadMessageHandler enters the
// instance through `wasi_thread_start` when it processes the queued `start` message.
const threadExports = { ...instance.exports } const threadExports = { ...instance.exports }
delete threadExports._start delete threadExports._start
wasi.initialize({ exports: threadExports }) wasi.initialize({ exports: threadExports })
......
...@@ -162,6 +162,9 @@ async function readNormalizedNFT(next, name) { ...@@ -162,6 +162,9 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/build/swc/loaderWorkerPool.js", "/node_modules/next/dist/build/swc/loaderWorkerPool.js",
"/node_modules/next/dist/build/swc/options.js", "/node_modules/next/dist/build/swc/options.js",
"/node_modules/next/dist/build/swc/types.js", "/node_modules/next/dist/build/swc/types.js",
"/node_modules/next/dist/build/swc/wasi-loader-worker.js",
"/node_modules/next/dist/build/swc/wasi-loader.js",
"/node_modules/next/dist/build/swc/wasi-runtime.js",
"/node_modules/next/dist/build/utils.js", "/node_modules/next/dist/build/utils.js",
"/node_modules/next/dist/cli/next-test.js", "/node_modules/next/dist/cli/next-test.js",
"/node_modules/next/dist/client/*", "/node_modules/next/dist/client/*",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment