| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | /** |
| 9 | * This file is expected to be run via child_process.fork() where: |
| 10 | * |
| 11 | * - The arguments to `startServer()` are JSON-serialized as the value |
| 12 | * of the ISL_SERVER_ARGS environment variable. |
| 13 | * - Communication to the parent process must be done via process.send() |
| 14 | * and the parent process expects messages that conform to |
| 15 | * `ChildProcessResponse`. |
| 16 | */ |
| 17 | |
| 18 | import type {StartServerArgs, StartServerResult} from './server'; |
| 19 | |
| 20 | import * as fs from 'node:fs'; |
| 21 | |
| 22 | /** |
| 23 | * This defines the shape of the messages that the parent process accepts. |
| 24 | * As such, it is imperative that these types are serializable. |
| 25 | */ |
| 26 | export type ChildProcessResponse = |
| 27 | | { |
| 28 | type: 'message'; |
| 29 | args: Parameters<typeof console.log>; |
| 30 | } |
| 31 | | { |
| 32 | type: 'result'; |
| 33 | result: StartServerResult; |
| 34 | }; |
| 35 | |
| 36 | function sendMessageToParentProcess(msg: ChildProcessResponse): void { |
| 37 | process.send?.(msg, undefined, {swallowErrors: true}); |
| 38 | } |
| 39 | |
| 40 | function info(...args: Parameters<typeof console.log>): void { |
| 41 | const msg = { |
| 42 | type: 'message', |
| 43 | args, |
| 44 | } as ChildProcessResponse; |
| 45 | sendMessageToParentProcess(msg); |
| 46 | } |
| 47 | |
| 48 | const args: StartServerArgs = JSON.parse(process.env.ISL_SERVER_ARGS as string); |
| 49 | args.logInfo = info; |
| 50 | import('./server') |
| 51 | .then(({startServer}) => startServer(args)) |
| 52 | .then((result: StartServerResult) => { |
| 53 | sendMessageToParentProcess({type: 'result', result}); |
| 54 | }) |
| 55 | .catch(error => |
| 56 | sendMessageToParentProcess({type: 'result', result: {type: 'error', error: String(error)}}), |
| 57 | ); |
| 58 | |
| 59 | process.on('uncaughtException', err => { |
| 60 | const {logFileLocation} = args; |
| 61 | fs.promises.appendFile( |
| 62 | logFileLocation, |
| 63 | `\n[${new Date().toString()}] ISL server child process got an uncaught exception:\n${ |
| 64 | err?.stack ?? err?.message |
| 65 | }\n\n`, |
| 66 | 'utf8', |
| 67 | ); |
| 68 | }); |
| 69 | |