addons/isl-server/proxy/child.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318/**
b69ab319 * This file is expected to be run via child_process.fork() where:
b69ab3110 *
b69ab3111 * - The arguments to `startServer()` are JSON-serialized as the value
b69ab3112 * of the ISL_SERVER_ARGS environment variable.
b69ab3113 * - Communication to the parent process must be done via process.send()
b69ab3114 * and the parent process expects messages that conform to
b69ab3115 * `ChildProcessResponse`.
b69ab3116 */
b69ab3117
b69ab3118import type {StartServerArgs, StartServerResult} from './server';
b69ab3119
b69ab3120import * as fs from 'node:fs';
b69ab3121
b69ab3122/**
b69ab3123 * This defines the shape of the messages that the parent process accepts.
b69ab3124 * As such, it is imperative that these types are serializable.
b69ab3125 */
b69ab3126export type ChildProcessResponse =
b69ab3127 | {
b69ab3128 type: 'message';
b69ab3129 args: Parameters<typeof console.log>;
b69ab3130 }
b69ab3131 | {
b69ab3132 type: 'result';
b69ab3133 result: StartServerResult;
b69ab3134 };
b69ab3135
b69ab3136function sendMessageToParentProcess(msg: ChildProcessResponse): void {
b69ab3137 process.send?.(msg, undefined, {swallowErrors: true});
b69ab3138}
b69ab3139
b69ab3140function info(...args: Parameters<typeof console.log>): void {
b69ab3141 const msg = {
b69ab3142 type: 'message',
b69ab3143 args,
b69ab3144 } as ChildProcessResponse;
b69ab3145 sendMessageToParentProcess(msg);
b69ab3146}
b69ab3147
b69ab3148const args: StartServerArgs = JSON.parse(process.env.ISL_SERVER_ARGS as string);
b69ab3149args.logInfo = info;
b69ab3150import('./server')
b69ab3151 .then(({startServer}) => startServer(args))
b69ab3152 .then((result: StartServerResult) => {
b69ab3153 sendMessageToParentProcess({type: 'result', result});
b69ab3154 })
b69ab3155 .catch(error =>
b69ab3156 sendMessageToParentProcess({type: 'result', result: {type: 'error', error: String(error)}}),
b69ab3157 );
b69ab3158
b69ab3159process.on('uncaughtException', err => {
b69ab3160 const {logFileLocation} = args;
b69ab3161 fs.promises.appendFile(
b69ab3162 logFileLocation,
b69ab3163 `\n[${new Date().toString()}] ISL server child process got an uncaught exception:\n${
b69ab3164 err?.stack ?? err?.message
b69ab3165 }\n\n`,
b69ab3166 'utf8',
b69ab3167 );
b69ab3168});