Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: prerender & analyse in worker rather than subprocess to support Deno #9919

Merged
merged 3 commits into from
May 16, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 18 additions & 23 deletions packages/kit/src/utils/fork.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { fileURLToPath } from 'node:url';
import child_process from 'node:child_process';
import { Worker, isMainThread, parentPort } from 'node:worker_threads';

/**
* Runs a task in a subprocess so any dangling stuff gets killed upon completion.
Expand All @@ -11,23 +11,21 @@ import child_process from 'node:child_process';
* @returns {(opts: T) => Promise<U>} A function that when called starts the subprocess
*/
export function forked(module, callback) {
if (process.env.SVELTEKIT_FORK && process.send) {
process.send({ type: 'ready', module });

process.on(
if (!isMainThread && parentPort) {
parentPort.on(
'message',
/** @param {any} data */ async (data) => {
if (data?.type === 'args' && data.module === module) {
if (process.send) {
process.send({
type: 'result',
module,
payload: await callback(data.payload)
});
}
parentPort?.postMessage({
type: 'result',
module,
payload: await callback(data.payload)
});
}
}
);

parentPort.postMessage({ type: 'ready', module });
}

/**
Expand All @@ -36,34 +34,31 @@ export function forked(module, callback) {
*/
const fn = function (opts) {
return new Promise((fulfil, reject) => {
const child = child_process.fork(fileURLToPath(module), {
stdio: 'inherit',
const worker = new Worker(fileURLToPath(module), {
env: {
...process.env,
SVELTEKIT_FORK: 'true'
},
serialization: 'advanced'
...process.env
}
});

child.on(
worker.on(
'message',
/** @param {any} data */ (data) => {
/** @param {any} data */ async (data) => {
fernandolguevara marked this conversation as resolved.
Show resolved Hide resolved
if (data?.type === 'ready' && data.module === module) {
child.send({
worker.postMessage({
type: 'args',
module,
payload: opts
});
}

if (data?.type === 'result' && data.module === module) {
child.kill();
worker.terminate();
fulfil(data.payload);
}
}
);

child.on('exit', (code) => {
worker.on('exit', (code) => {
if (code) {
reject(new Error(`Failed with code ${code}`));
}
Expand Down