From 82b157bac135be86a96ea15a2cd22407c3c14761 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Tue, 3 Nov 2026 23:20:36 +0530 Subject: [PATCH] fix(server): tell a CodeWork server runs from its URL, not its pid A home's service.json counted only while its pid was alive here. A server in WSL registers a Linux pid the Windows app cannot see, so it always read as stopped. The app now opens the registration's URL instead: a server that answers runs, whatever OS it is on, and a registration left behind with nothing listening is stopped rather than unreachable. The default server still checks that the pid it reports is the registration's. The health test runs the real CLI and covers a pid from another OS and a server killed outright. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/cli.ts | 21 ++----- apps/server/src/codework.ts | 11 ++++ apps/server/src/health.ts | 2 +- apps/server/src/server.ts | 14 ++++- apps/server/test/__artifacts__/health.json | 7 ++- apps/server/test/health.test.ts | 67 ++++++++++++++++++---- 6 files changed, 91 insertions(+), 31 deletions(-) diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts index e234a9b5..2d651fc7 100644 --- a/apps/server/src/cli.ts +++ b/apps/server/src/cli.ts @@ -112,29 +112,20 @@ const executableOf = (row: Servers.Row, foundOnce: typeof found) => { ); }; -/** Whether a process runs under `pid`. */ -export const alive = (pid: number) => - Effect.sync(() => { - try { - process.kill(pid, 0); - return true; - } catch (error) { - // EPERM: it exists, under another user. - return (error as NodeJS.ErrnoException).code === "EPERM"; - } - }); - -/** The server a home names, while its process lives. */ +/** The server a home names, while its URL answers. */ export const liveAt = (home: string) => Effect.gen(function* () { const registered = yield* Codework.registrationAt(home); - return Option.isSome(registered) && (yield* alive(registered.value.pid)) ? registered : Option.none(); + return Option.isSome(registered) && (yield* Codework.reachable(registered.value.url)) + ? registered + : Option.none(); }); /** * The server a home names. The default one is asked through the app's own connection, since a build * whose replies differ still answers `server.info`: a call the app depends on decides whether it - * works with this app. Any other is taken from its registration and process. + * works with this app, and the pid it reports must be the registration's, not another server's on + * that port. Any other is taken from its registration once its URL answers. */ export const serverAt = (home: string, isDefault: boolean) => Effect.gen(function* () { diff --git a/apps/server/src/codework.ts b/apps/server/src/codework.ts index 3e9ea417..115686d8 100644 --- a/apps/server/src/codework.ts +++ b/apps/server/src/codework.ts @@ -28,6 +28,17 @@ export const registrationAt = (home: string) => .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Registration)), Effect.option); }); +/** + * Whether a server answers at `url`: its WebSocket opens. A registration's pid says nothing here, since + * the server may run on another OS than this app, as one in WSL does for the Windows app. + */ +export const reachable = (url: string) => + Socket.makeWebSocket(url, { openTimeout: "2 seconds" }).pipe( + Effect.flatMap((socket) => Effect.scoped(socket.reader)), + Effect.isSuccess, + Effect.provide(NodeSocket.layerWebSocketConstructor), + ); + /** The server the default server's home names: the one the app connects to. */ export const registration = Effect.gen(function* () { return yield* registrationAt(yield* (yield* Servers.Service).defaultHome); diff --git a/apps/server/src/health.ts b/apps/server/src/health.ts index 28b975ce..2bb0b449 100644 --- a/apps/server/src/health.ts +++ b/apps/server/src/health.ts @@ -48,7 +48,7 @@ export const layer = Layer.effect( ); // The default server alone is cheap to ask; only a change is worth a full check. Unless `asked`, - // a running one is only looked for, without a call. + // a running one is only looked for at its URL, without a call. const checkDefault = (asked: boolean) => Effect.gen(function* () { const before = (yield* SubscriptionRef.get(current))?.find((status) => status.isDefault); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index acbff9f4..8d3b9f15 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -5,7 +5,6 @@ import { RpcSerialization, RpcServer } from "effect/rpc"; /* @effect-diagnostics nodeBuiltinImport:off -- the RPC listener needs a raw node server. */ import { createServer } from "node:http"; import type { Socket } from "node:net"; -import { Cli } from "./cli.ts"; import { Codework } from "./codework.ts"; import { Contract } from "@codeworksh/contract"; import { Db } from "./db.ts"; @@ -45,6 +44,17 @@ const announceReady = Layer.effectDiscard( }), ); +const alive = (pid: number) => + Effect.sync(() => { + try { + process.kill(pid, 0); + return true; + } catch (error) { + // EPERM: it exists, under another user. + return (error as NodeJS.ErrnoException).code === "EPERM"; + } + }); + /** * Stops this process once the one that started it is gone: Electron killed outright, or crashed, cannot * stop it, and an app server nobody can reach would only hold the database. It stops as on SIGTERM. @@ -55,7 +65,7 @@ const exitWithParent = Layer.effectDiscard( // Adopted by launchd (pid 1) is orphaned too, even when the parent was gone before this started. // Windows never adopts an orphan, so the parent itself is asked whether it still runs. const attached = Effect.suspend(() => - process.ppid === parent && process.ppid !== 1 ? Cli.alive(parent) : Effect.succeed(false), + process.ppid === parent && process.ppid !== 1 ? alive(parent) : Effect.succeed(false), ); yield* attached.pipe( Effect.repeat({ while: (running) => running, schedule: Schedule.spaced("1 second") }), diff --git a/apps/server/test/__artifacts__/health.json b/apps/server/test/__artifacts__/health.json index 2edb3a47..a897a488 100644 --- a/apps/server/test/__artifacts__/health.json +++ b/apps/server/test/__artifacts__/health.json @@ -1,6 +1,11 @@ { "first": "Stopped", - "registered": "Unreachable", + "running": "Running", + "otherOs": "Running", + "killed": "Stopped", + "leftBehind": true, + "otherOsKilled": "Stopped", + "stale": "Stopped", "gone": "Stopped", "health": { "interval": 300 diff --git a/apps/server/test/health.test.ts b/apps/server/test/health.test.ts index 8b062997..08a45aed 100644 --- a/apps/server/test/health.test.ts +++ b/apps/server/test/health.test.ts @@ -3,7 +3,7 @@ import { Effect, Layer, Option, Stream } from "effect"; import { RpcClient, RpcSerialization } from "effect/rpc"; import { Socket } from "effect/socket"; import { type ChildProcess, spawn } from "node:child_process"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createInterface } from "node:readline"; @@ -12,10 +12,22 @@ import { afterAll, beforeAll, expect, it } from "vite-plus/test"; import { Contract, type ServerStatus } from "@codeworksh/contract"; const entry = fileURLToPath(new URL("../src/index.ts", import.meta.url)); +const cli = fileURLToPath(new URL("../../../packages/codework/src/index.ts", import.meta.url)); const home = mkdtempSync(join(tmpdir(), "codework-health-")); +// A second server's home, whose registration names a pid this machine has no process for, as one written +// by a server in WSL does for the Windows app. +const otherHome = mkdtempSync(join(tmpdir(), "codework-health-other-")); let server: ChildProcess; +let codework: ChildProcess | undefined; let port: number; +const kill = (child: ChildProcess) => + new Promise((resolve) => { + if (child.exitCode !== null || child.signalCode !== null) return resolve(); + child.once("exit", () => resolve()); + child.kill("SIGKILL"); + }); + // The home names no CodeWork service until the test writes one; the install folder is empty too. beforeAll(async () => { server = spawn(process.execPath, [entry], { @@ -29,7 +41,9 @@ beforeAll(async () => { }); port = await new Promise((resolve, reject) => { server.once("exit", (code) => reject(new Error(`server exited before ready (code ${code})`))); + // Its other lines are logs, as the desktop app reads them. createInterface({ input: server.stdout! }).on("line", (line) => { + if (!line.startsWith('{"type":"ready"')) return; const message = JSON.parse(line) as { type?: string; port?: number }; if (message.type === "ready" && message.port !== undefined) resolve(message.port); }); @@ -37,10 +51,10 @@ beforeAll(async () => { }, 20_000); afterAll(async () => { - const exited = new Promise((resolve) => server.once("exit", resolve)); - server.kill("SIGKILL"); - await exited; + if (codework !== undefined) await kill(codework); + await kill(server); rmSync(home, { recursive: true, force: true }); + rmSync(otherHome, { recursive: true, force: true }); }); const protocol = () => @@ -51,8 +65,10 @@ const protocol = () => ); const defaultTag = (statuses: ReadonlyArray) => statuses.find((status) => status.isDefault)?.server._tag; +const tagOf = (statuses: ReadonlyArray, id: string) => + statuses.find((status) => status.id === id)?.server._tag; -it("keeps the servers' status and follows the default server going up and down", async () => { +it("tells a server runs from its URL, whatever its registered pid", async () => { const steps = await Effect.gen(function* () { const rpc = yield* RpcClient.make(Contract.Api); const watch = rpc["servers.watch"](undefined); @@ -66,26 +82,53 @@ it("keeps the servers' status and follows the default server going up and down", Effect.timeout("20 seconds"), ); + // Every server checked now, as read right after. + const checked = rpc["servers.check"](undefined).pipe( + Effect.andThen(watch.pipe(Stream.runHead, Effect.map(Option.getOrThrow))), + ); + const registration = join(home, "service.json"); + const first = yield* until("Stopped"); - // A registration whose process lives (this test) but whose server never answers. + // The real CLI, serving from this home: the app finds it through the registration it writes. + codework = spawn(process.execPath, ["--conditions=development", cli, "serve", "--port", "0"], { + env: { ...process.env, CODEWORK_HOME_DIR: home }, + stdio: "ignore", + }); + const running = yield* until("Running"); + + // The same server registered with a pid no process here has: its URL alone says it runs. + const otherId = yield* rpc["servers.add"]({ name: "Other OS", executable: null, home: otherHome, args: "" }); + const registered = JSON.parse(readFileSync(registration, "utf8")) as { pid: number }; + writeFileSync(join(otherHome, "service.json"), JSON.stringify({ ...registered, pid: 2_147_483_646 })); + const otherOs = tagOf(yield* checked, otherId); + + // Killed outright, the server leaves its registration behind; nothing answers at its URL. + yield* Effect.promise(() => kill(codework!)); + const killed = yield* until("Stopped"); + const leftBehind = existsSync(registration); + const otherOsKilled = tagOf(yield* checked, otherId); + + // A registration whose pid lives (this test) but whose URL nobody answers: stopped, not unreachable. writeFileSync( - join(home, "service.json"), + registration, JSON.stringify({ pid: process.pid, version: "0.0.0", url: "ws://127.0.0.1:9/rpc", port: 9 }), ); - const registered = yield* until("Unreachable"); + const stale = defaultTag(yield* checked); - rmSync(join(home, "service.json")); + rmSync(registration); const gone = yield* until("Stopped"); const health = yield* rpc["servers.health"](undefined); yield* rpc["servers.setHealth"]({ interval: 60 }); const changed = yield* rpc["servers.health"](undefined); - return { first, registered, gone, health, changed }; + return { first, running, otherOs, killed, leftBehind, otherOsKilled, stale, gone, health, changed }; }).pipe(Effect.scoped, Effect.provide(protocol()), Effect.runPromise); - expect(steps.registered).toBe("Unreachable"); + expect(steps.running).toBe("Running"); + expect(steps.otherOs).toBe("Running"); + expect(steps.stale).toBe("Stopped"); expect(steps.changed).toEqual({ interval: 60 }); await expect(`${JSON.stringify(steps, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/health.json"); -}, 60_000); +}, 120_000);