Skip to content

Commit

Permalink
quick experiment to see if it's the process communication
Browse files Browse the repository at this point in the history
  • Loading branch information
dummdidumm committed Jan 26, 2023
1 parent e900343 commit b794a55
Showing 1 changed file with 39 additions and 32 deletions.
71 changes: 39 additions & 32 deletions packages/kit/src/utils/fork.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { fileURLToPath } from 'node:url';
import child_process from 'node:child_process';
import { dirname } from 'node:path';
import { readFileSync, unlinkSync, writeFileSync } from 'node:fs';
import * as devalue from 'devalue';

/**
* Runs a task in a subprocess so any dangling stuff gets killed upon completion.
Expand All @@ -12,22 +15,30 @@ import child_process from 'node:child_process';
*/
export function forked(module, callback) {
if (process.env.SVELTEKIT_FORK) {
process.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)
});

process.exit(0);
}
try {
const data = devalue.parse(
readFileSync(fileURLToPath(dirname(module)) + '/__sveltekit_args__', 'utf-8')
);
unlinkSync(fileURLToPath(dirname(module)) + '/__sveltekit_args__');
const run = async () => {
try {
const result = await callback(data);
writeFileSync(
fileURLToPath(dirname(module)) + '/__sveltekit_result__',
devalue.stringify(result),
'utf-8'
);
process.exit(0);
} catch (err) {
console.error(err);
process.exit(1);
}
}
);
};
run();
} catch (e) {
console.error(e);
process.exit(1);
}
}

/**
Expand All @@ -38,34 +49,30 @@ export function forked(module, callback) {
return new Promise((fulfil, reject) => {
const script = fileURLToPath(new URL(module, import.meta.url));

writeFileSync(
fileURLToPath(dirname(module)) + '/__sveltekit_args__',
devalue.stringify(opts),
'utf-8'
);
const child = child_process.fork(script, {
stdio: 'inherit',
env: {
SVELTEKIT_FORK: 'true'
},
serialization: 'advanced'
});

child.on(
'message',
/** @param {any} data */ (data) => {
if (data?.type === 'result' && data.module === module) {
fulfil(data.payload);
}
}
);
});

child.on('exit', (code) => {
if (code) {
reject(new Error(`Failed with code ${code}`));
} else {
const result = readFileSync(
fileURLToPath(dirname(module)) + '/__sveltekit_result__',
'utf-8'
);
unlinkSync(fileURLToPath(dirname(module)) + '/__sveltekit_result__');
fulfil(devalue.parse(result));
}
});

child.send({
type: 'args',
module,
payload: opts
});
});
};

Expand Down

0 comments on commit b794a55

Please sign in to comment.