|
| 1 | +// Runs Syntax Auth's own `pnpm dev` or `pnpm preview` on the shared local port, in place of the |
| 2 | +// `syntax-auth` container that other Syntax apps use (see CONSUMING_AUTH.md). However it stops |
| 3 | +// (Ctrl-C, `kill`, its parent exiting, a crash, or the server losing its port), it stops every |
| 4 | +// process it started and starts the container again, so nothing is left running and other apps |
| 5 | +// keep signing in. |
| 6 | +import { spawn } from 'node:child_process'; |
| 7 | +import { connect } from 'node:net'; |
| 8 | + |
| 9 | +import { |
| 10 | + CONTAINER_NAME, |
| 11 | + SYNTAX_AUTH_LOCAL_PORT, |
| 12 | + docker, |
| 13 | + get_container_state, |
| 14 | + log, |
| 15 | + sleep, |
| 16 | + warn, |
| 17 | + with_container_lock |
| 18 | +} from '../packages/auth-local/container.js'; |
| 19 | + |
| 20 | +const SERVER_COMMANDS = { |
| 21 | + dev: 'pnpm d1:migrate:local && exec vite dev', |
| 22 | + preview: `pnpm build && exec wrangler dev --env local --ip 127.0.0.1 --port ${SYNTAX_AUTH_LOCAL_PORT}` |
| 23 | +}; |
| 24 | +// Vite restarts its server within about a second when its config changes, so only a longer |
| 25 | +// silence means the server has lost the port for good. |
| 26 | +const WATCH_INTERVAL_MS = 10_000; |
| 27 | +const FAILED_PORT_CHECKS_BEFORE_STOPPING = 3; |
| 28 | +const PORT_RELEASE_TIMEOUT_MS = 5_000; |
| 29 | +const STOP_GRACE_MS = 5_000; |
| 30 | + |
| 31 | +const server_command = SERVER_COMMANDS[process.argv[2]]; |
| 32 | +if (!server_command) { |
| 33 | + console.error(`Usage: node scripts/local_server.js <${Object.keys(SERVER_COMMANDS).join('|')}>`); |
| 34 | + process.exit(1); |
| 35 | +} |
| 36 | + |
| 37 | +const parent_pid = process.ppid; |
| 38 | +/** @type {import('node:child_process').ChildProcess | null} */ |
| 39 | +let server = null; |
| 40 | +/** @type {Promise<never> | null} */ |
| 41 | +let stopping = null; |
| 42 | +/** @type {NodeJS.Timeout | undefined} */ |
| 43 | +let watch_timer; |
| 44 | + |
| 45 | +function is_port_open() { |
| 46 | + return new Promise((resolve) => { |
| 47 | + const socket = connect({ host: '127.0.0.1', port: SYNTAX_AUTH_LOCAL_PORT }); |
| 48 | + socket.setTimeout(2_000); |
| 49 | + socket.once('connect', () => { |
| 50 | + socket.destroy(); |
| 51 | + resolve(true); |
| 52 | + }); |
| 53 | + socket.once('timeout', () => { |
| 54 | + socket.destroy(); |
| 55 | + resolve(false); |
| 56 | + }); |
| 57 | + socket.once('error', () => resolve(false)); |
| 58 | + }); |
| 59 | +} |
| 60 | + |
| 61 | +/** @param {number} group_id */ |
| 62 | +function is_group_running(group_id) { |
| 63 | + try { |
| 64 | + process.kill(-group_id, 0); |
| 65 | + return true; |
| 66 | + } catch { |
| 67 | + return false; |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +/** @param {number} group_id @param {NodeJS.Signals} signal */ |
| 72 | +function signal_group(group_id, signal) { |
| 73 | + try { |
| 74 | + process.kill(-group_id, signal); |
| 75 | + } catch { |
| 76 | + // Every process in the group has already exited. |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +/** @param {number} group_id @param {number} timeout_ms */ |
| 81 | +async function wait_for_group_exit(group_id, timeout_ms) { |
| 82 | + const deadline = Date.now() + timeout_ms; |
| 83 | + while (is_group_running(group_id) && Date.now() < deadline) await sleep(100); |
| 84 | +} |
| 85 | + |
| 86 | +// Wrangler can outlive its workerd child, or the reverse, so signal the whole process group. |
| 87 | +/** @param {number} group_id */ |
| 88 | +async function stop_server_processes(group_id) { |
| 89 | + signal_group(group_id, 'SIGTERM'); |
| 90 | + await wait_for_group_exit(group_id, STOP_GRACE_MS); |
| 91 | + if (!is_group_running(group_id)) return; |
| 92 | + |
| 93 | + signal_group(group_id, 'SIGKILL'); |
| 94 | + await wait_for_group_exit(group_id, STOP_GRACE_MS); |
| 95 | +} |
| 96 | + |
| 97 | +async function restart_shared_container() { |
| 98 | + const state = await get_container_state(); |
| 99 | + if (!state || state.is_running) return; |
| 100 | + |
| 101 | + const result = await docker(['start', CONTAINER_NAME]); |
| 102 | + if (result.code === 0) log('Started the shared container again for other Syntax apps'); |
| 103 | + else warn(`Unable to start the shared container again: ${result.stderr}`); |
| 104 | +} |
| 105 | + |
| 106 | +/** @param {number} exit_code @returns {Promise<never>} */ |
| 107 | +function stop(exit_code) { |
| 108 | + stopping ??= (async () => { |
| 109 | + clearInterval(watch_timer); |
| 110 | + if (server?.pid) await stop_server_processes(server.pid); |
| 111 | + await with_container_lock(restart_shared_container); |
| 112 | + process.exit(exit_code); |
| 113 | + })(); |
| 114 | + return stopping; |
| 115 | +} |
| 116 | + |
| 117 | +async function wait_until_port_released() { |
| 118 | + const deadline = Date.now() + PORT_RELEASE_TIMEOUT_MS; |
| 119 | + while (Date.now() < deadline) { |
| 120 | + if (!(await is_port_open())) return true; |
| 121 | + await sleep(250); |
| 122 | + } |
| 123 | + return false; |
| 124 | +} |
| 125 | + |
| 126 | +async function wait_until_listening() { |
| 127 | + while (!stopping && server?.exitCode === null && server.signalCode === null) { |
| 128 | + if (await is_port_open()) return; |
| 129 | + await sleep(500); |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +function start_server() { |
| 134 | + // Its own process group, so one signal reaches every process it starts. Being detached also |
| 135 | + // keeps the terminal's Ctrl-C from reaching it directly; `stop` handles that signal instead. |
| 136 | + server = spawn(server_command, { shell: true, detached: true, stdio: 'inherit' }); |
| 137 | + server.once('exit', (code) => stop(code ?? 1)); |
| 138 | +} |
| 139 | + |
| 140 | +// Stops this command when its parent exits (for example, when `pnpm` is killed) or when the |
| 141 | +// server stops answering on its port while some of its processes keep running. |
| 142 | +function watch_server() { |
| 143 | + let failed_port_checks = 0; |
| 144 | + watch_timer = setInterval(async () => { |
| 145 | + if (process.ppid !== parent_pid) return stop(0); |
| 146 | + |
| 147 | + failed_port_checks = (await is_port_open()) ? 0 : failed_port_checks + 1; |
| 148 | + if (failed_port_checks < FAILED_PORT_CHECKS_BEFORE_STOPPING) return; |
| 149 | + |
| 150 | + warn(`Nothing answers on port ${SYNTAX_AUTH_LOCAL_PORT} anymore, so this command is stopping.`); |
| 151 | + stop(1); |
| 152 | + }, WATCH_INTERVAL_MS); |
| 153 | +} |
| 154 | + |
| 155 | +for (const signal of /** @type {const} */ (['SIGINT', 'SIGTERM', 'SIGHUP'])) { |
| 156 | + process.on(signal, () => stop(0)); |
| 157 | +} |
| 158 | + |
| 159 | +log( |
| 160 | + `Stop with Ctrl-C or \`kill ${process.pid}\`. Either stops everything this command started and starts the shared container again.` |
| 161 | +); |
| 162 | + |
| 163 | +// Holds the machine-wide container lock until this server listens, so another Syntax app's dev |
| 164 | +// server cannot start the container on the port in between. |
| 165 | +const is_started = await with_container_lock(async () => { |
| 166 | + if ((await get_container_state())?.is_running) { |
| 167 | + log('Stopping the shared container while this server uses its port'); |
| 168 | + await docker(['stop', CONTAINER_NAME]); |
| 169 | + } |
| 170 | + if (!(await wait_until_port_released())) return false; |
| 171 | + if (stopping) return true; |
| 172 | + |
| 173 | + start_server(); |
| 174 | + await wait_until_listening(); |
| 175 | + return true; |
| 176 | +}); |
| 177 | + |
| 178 | +if (!is_started) { |
| 179 | + warn( |
| 180 | + `Another program, perhaps another Syntax Auth server, is using port ${SYNTAX_AUTH_LOCAL_PORT}. Stop it, then try again.` |
| 181 | + ); |
| 182 | + process.exit(1); |
| 183 | +} |
| 184 | +if (!stopping) watch_server(); |
0 commit comments