Skip to content

Commit f6ffcfa

Browse files
committed
Stop everything Syntax Auth's dev and preview start, and hand the port back
scripts/local_server.js runs the server in its own process group, stops all of it however the command ends, and starts the shared container again. It holds the container lock until the server listens, so consumer apps never race it for the port.
1 parent f303f6d commit f6ffcfa

4 files changed

Lines changed: 201 additions & 13 deletions

File tree

‎CONSUMING_AUTH.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,8 @@ identical to production. It needs no secrets, 1Password, or GitHub OAuth App.
116116
volume, and skips Vitest. If Docker is missing, the image is not accessible, or another program
117117
holds the port, it prints one warning and the app runs signed out. Apps without Vite run the
118118
`syntax-auth-local` command before their dev server instead. Contributors working on Syntax Auth
119-
itself run `pnpm dev` in this repository, which stops the container and serves the same port;
120-
other apps then use that server.
119+
itself run `pnpm dev` or `pnpm preview` in this repository, which stops the container and serves
120+
the same port; other apps then use that server. When it stops, it starts the container again.
121121

122122
The Docker image is private to the Syntax team. For syntaxfm members, the plugin pulls it with
123123
their GitHub CLI login in a throwaway Docker config, so the token is never stored and existing

‎README.md‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -90,17 +90,21 @@ pnpm dev
9090
```
9191

9292
`pnpm dev` stops the shared `syntax-auth` container if one is running, applies migrations to local
93-
D1, and serves `http://localhost:37960`. It needs no secrets: the Cloudflare adapter reads the
94-
committed `local` Wrangler environment, which has a loopback URL, no shared cookie domain, and a
95-
local-only D1 database under the ignored `.wrangler/` directory. In that mode Syntax Auth replaces
96-
GitHub with a one-click local developer account (user ID `local-developer`), trusts only
97-
`localhost` origins, and refuses requests for any other host. Deploys use the top-level
98-
configuration and never enable local mode.
93+
D1, and serves `http://localhost:37960`. `pnpm preview` does the same with a production build.
94+
Both run through `scripts/local_server.js`: however they stop, they stop every process they
95+
started and start the container again, so other Syntax apps keep signing in. Neither needs
96+
secrets: the Cloudflare adapter reads the committed `local` Wrangler environment, which has a
97+
loopback URL, no shared cookie domain, and a local-only D1 database under the ignored `.wrangler/`
98+
directory. In that mode Syntax Auth replaces GitHub with a one-click local developer account (user
99+
ID `local-developer`), trusts only `localhost` origins, and refuses requests for any other host.
100+
Deploys use the top-level configuration and never enable local mode.
99101

100102
Consumer apps run the same service from the private `ghcr.io/syntaxfm/auth-local` Docker image,
101-
which `.github/workflows/local-image.yml` publishes from `main`. The `packages/auth-local` Vite
102-
plugin starts it and, for syntaxfm members, pulls it with their GitHub CLI login without storing
103-
the token; see `CONSUMING_AUTH.md`. The port lives in `packages/auth-local/container.js`,
103+
which `.github/workflows/local-image.yml` publishes from `main`. The image serves a production
104+
build with `vite preview`, which watches no files; local mode turns off Better Auth's rate
105+
limiting, as dev builds always have. The `packages/auth-local` Vite plugin starts it and, for
106+
syntaxfm members, pulls it with their GitHub CLI login without storing the token; see
107+
`CONSUMING_AUTH.md`. The port lives in `packages/auth-local/container.js`,
104108
`vite.config.ts`, and the `local` and `oauth-registration` envs in `wrangler.jsonc`.
105109

106110
Useful commands:

‎package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
"private": true,
55
"type": "module",
66
"scripts": {
7-
"dev": "docker stop syntax-auth >/dev/null 2>&1; pnpm d1:migrate:local && vite dev",
7+
"dev": "node scripts/local_server.js dev",
88
"build": "vite build",
9-
"preview": "docker stop syntax-auth >/dev/null 2>&1; pnpm build && wrangler dev --env local --ip 127.0.0.1 --port 37960",
9+
"preview": "node scripts/local_server.js preview",
1010
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
1111
"lint": "prettier --check . && eslint .",
1212
"format": "prettier --write .",

‎scripts/local_server.js‎

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
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

Comments
 (0)