From 7d27d6a3daba72b42dd88a61623acade515d2541 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Mon, 5 Oct 2026 15:39:54 -0700 Subject: [PATCH] test(cli): speed up managed service tests (#53441) --- packages/cli/test/fixture/environment.ts | 6 + packages/cli/test/service-lifecycle.test.ts | 16 +-- packages/cli/test/service.test.ts | 151 +++++++++----------- 3 files changed, 80 insertions(+), 93 deletions(-) diff --git a/packages/cli/test/fixture/environment.ts b/packages/cli/test/fixture/environment.ts index c3723fde0f1..7e3ced6fee5 100644 --- a/packages/cli/test/fixture/environment.ts +++ b/packages/cli/test/fixture/environment.ts @@ -1,8 +1,14 @@ +import os from "node:os" import path from "node:path" +// Each isolated home gets its own XDG_CACHE_HOME, where Bun would otherwise keep its transpiler cache, +// so every spawned CLI process would transpile the source from scratch. Share one cache instead. +export const transpilerCache = path.join(os.tmpdir(), "opencode-test-transpiler-cache") + export function isolatedEnv(root: string, overrides: Record = {}) { return { ...process.env, + BUN_RUNTIME_TRANSPILER_CACHE_PATH: transpilerCache, HOME: root, OPENCODE_CLI_CONFIG_CONTENT: undefined, OPENCODE_CONFIG_CONTENT: "{}", diff --git a/packages/cli/test/service-lifecycle.test.ts b/packages/cli/test/service-lifecycle.test.ts index 96f6e652cf8..f0b0223e3d5 100644 --- a/packages/cli/test/service-lifecycle.test.ts +++ b/packages/cli/test/service-lifecycle.test.ts @@ -14,8 +14,6 @@ import { isolatedEnv } from "./fixture/environment" // the configured port, which a stop removes without leftovers. const entry = path.join(import.meta.dir, "../src/index.ts") -// Servers run the CLI from source. A shared transpiler cache keeps each new home from starting cold. -const transpilerCache = path.join(os.tmpdir(), "opencode-test-transpiler-cache") const serviceTest = process.platform === "win32" ? test.skip : test serviceTest( @@ -114,8 +112,14 @@ serviceTest( await using home = await serviceHome() using listener = Bun.serve({ hostname: "127.0.0.1", port: home.port, fetch: () => new Response("unrelated") }) - await expect(cli(home, "service", "start")).rejects.toThrow("already in use by another process") + const conflict = await cli(home, "service", "start").then( + () => undefined, + (error: Error) => error.message, + ) + expect(conflict).toContain(`Managed service port ${home.port} on 127.0.0.1 is already in use by another process`) + expect(conflict).toContain("opencode service set port ") expect(await servers(home)).toEqual([]) + expect(await Bun.file(home.registration).exists()).toBe(false) await listener.stop(true) await cli(home, "service", "start") @@ -172,17 +176,13 @@ async function serviceHome(options: { readonly failBoot?: boolean } = {}) { const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-lifecycle-"))) const port = await availablePort() await fs.mkdir(path.join(root, "config"), { recursive: true }) - await fs.mkdir(transpilerCache, { recursive: true }) await fs.writeFile(path.join(root, "config", "service-local.json"), JSON.stringify({ port })) // A directory where the database file belongs makes boot fail after the server registers. if (options.failBoot) await fs.mkdir(path.join(root, "database")) // Servers spawned through this home's entry carry its path, so `servers()` sees only this home. const homeEntry = path.join(root, "opencode.ts") await fs.writeFile(homeEntry, `import ${JSON.stringify(entry)}\n`) - const overrides = { - BUN_RUNTIME_TRANSPILER_CACHE_PATH: transpilerCache, - ...(options.failBoot ? { OPENCODE_DB: path.join(root, "database") } : {}), - } + const overrides = options.failBoot ? { OPENCODE_DB: path.join(root, "database") } : {} const home = { root, port, diff --git a/packages/cli/test/service.test.ts b/packages/cli/test/service.test.ts index c6fa8d5f195..8690227c6c6 100644 --- a/packages/cli/test/service.test.ts +++ b/packages/cli/test/service.test.ts @@ -3,13 +3,17 @@ import { Service, type Info } from "@opencode/client/effect/service" import { Global } from "@opencode/util/global" import { OPENCODE_VERSION } from "../src/version" import { expect, test } from "bun:test" -import { Effect, FileSystem, Schedule, Schema } from "effect" +import { Deferred, Effect, FileSystem, Schedule, Schema } from "effect" +import { TestClock } from "effect/testing" import fs from "node:fs/promises" import os from "node:os" import path from "node:path" import { ServiceConfig } from "../src/services/service-config" import { ServiceRegistration } from "../src/services/service-registration" -import { isolatedEnv } from "./fixture/environment" +import { isolatedEnv, transpilerCache } from "./fixture/environment" +import { testEffect } from "../../core/test/lib/effect" + +const it = testEffect(NodeFileSystem.layer) test("managed service ports are stable per installation channel", () => { expect(ServiceConfig.defaultPort("latest")).toBe(0xc0de) @@ -170,18 +174,38 @@ test("preview registration migration never moves stable discovery", async () => } }) -test("deleting a managed service registration stops its owner", async () => { - const service = await startManagedService("opencode-service-delete-") - try { - await fs.rm(service.registration) - expect(await waitForExit(service.owner)).toBe(true) - expect(await Bun.file(service.registration).exists()).toBe(false) - await expectPortAvailable(service.port) - } finally { - await stopManagedService(service) - } -}, 30_000) +it.effect("deleting a managed service registration stops its owner", () => + Effect.gen(function* () { + const service = yield* registered() + yield* service.fileSystem.remove(service.file) + yield* service.stops + yield* service.cleanup + expect(yield* service.fileSystem.exists(service.file)).toBe(false) + }), +) +it.effect("corrupting a managed service registration stops its owner", () => + Effect.gen(function* () { + const service = yield* registered() + yield* service.fileSystem.writeFileString(service.file, "not-json") + yield* service.stops + yield* service.cleanup + expect(yield* service.fileSystem.readFileString(service.file)).toBe("not-json") + }), +) + +it.effect("replacing a managed service registration stops its owner and preserves the foreign owner", () => + Effect.gen(function* () { + const service = yield* registered() + const foreign = JSON.stringify({ id: "foreign-owner", url: "http://127.0.0.1:4322", pid: process.pid }) + yield* service.fileSystem.writeFileString(service.file, foreign) + yield* service.stops + yield* service.cleanup + expect(yield* service.fileSystem.readFileString(service.file)).toBe(foreign) + }), +) + +// Real process: a server whose boot failed must still be watching its registration. test("deleting a failed service registration stops its owner", async () => { const service = await startManagedService("opencode-service-failed-delete-", true) try { @@ -194,31 +218,6 @@ test("deleting a failed service registration stops its owner", async () => { } }, 30_000) -test("corrupting a managed service registration stops its owner", async () => { - const service = await startManagedService("opencode-service-corrupt-") - try { - await fs.writeFile(service.registration, "not-json") - expect(await waitForExit(service.owner)).toBe(true) - expect(await Bun.file(service.registration).text()).toBe("not-json") - await expectPortAvailable(service.port) - } finally { - await stopManagedService(service) - } -}, 30_000) - -test("replacing a managed service registration stops its owner and preserves the foreign owner", async () => { - const service = await startManagedService("opencode-service-foreign-") - const foreign = { ...service.info, id: "foreign-owner", pid: process.pid } - try { - await fs.writeFile(service.registration, JSON.stringify(foreign)) - expect(await waitForExit(service.owner)).toBe(true) - expect(await Bun.file(service.registration).json()).toEqual(foreign) - await expectPortAvailable(service.port) - } finally { - await stopManagedService(service) - } -}, 30_000) - test("clean managed service shutdown removes its registration", async () => { const service = await startManagedService("opencode-service-clean-") try { @@ -232,17 +231,7 @@ test("clean managed service shutdown removes its registration", async () => { test("concurrent service processes elect one server", async () => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-election-")) - const database = path.join(root, "opencode.db") - const env = { - ...process.env, - HOME: root, - OPENCODE_DB: database, - OPENCODE_TEST_HOME: root, - XDG_CACHE_HOME: path.join(root, "cache"), - XDG_CONFIG_HOME: path.join(root, "config"), - XDG_DATA_HOME: path.join(root, "data"), - XDG_STATE_HOME: path.join(root, "state"), - } + const env = serviceEnv(root) const command = [process.execPath, path.join(import.meta.dir, "../src/index.ts"), "serve", "--service"] const registration = path.join(root, "state", "opencode", "service-local.json") const port = await availablePort() @@ -377,32 +366,6 @@ test.each([ 30_000, ) -test("unrelated managed port occupancy reports an actionable conflict", async () => { - const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-conflict-")) - const listener = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("unrelated") }) - const port = listener.port - const registration = path.join(root, "state", "opencode", "service-local.json") - await fs.mkdir(path.join(root, "config", "opencode"), { recursive: true }) - await fs.writeFile(path.join(root, "config", "opencode", "service-local.json"), JSON.stringify({ port })) - const contender = Bun.spawn([process.execPath, path.join(import.meta.dir, "../src/index.ts"), "serve", "--service"], { - env: serviceEnv(root), - stderr: "pipe", - stdout: "pipe", - }) - try { - expect(await contender.exited).not.toBe(0) - const output = (await new Response(contender.stdout).text()) + (await new Response(contender.stderr).text()) - expect(output).toContain(`Managed service port ${port} on 127.0.0.1 is already in use by another process`) - expect(output).toContain("opencode service set port ") - expect(await Bun.file(registration).exists()).toBe(false) - } finally { - listener.stop(true) - contender.kill("SIGTERM") - await contender.exited - await fs.rm(root, { recursive: true, force: true }) - } -}, 30_000) - test("the original managed service contender binds when the occupied port is released", async () => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-bind-retry-")) const recognizing = Promise.withResolvers() @@ -619,16 +582,7 @@ test("a failed service stays registered and owns the selected port until stopped await fs.mkdir(database) await fs.mkdir(path.join(root, "config", "opencode"), { recursive: true }) await fs.writeFile(path.join(root, "config", "opencode", "service-local.json"), JSON.stringify({ port })) - const env = { - ...process.env, - HOME: root, - OPENCODE_DB: database, - OPENCODE_TEST_HOME: root, - XDG_CACHE_HOME: path.join(root, "cache"), - XDG_CONFIG_HOME: path.join(root, "config"), - XDG_DATA_HOME: path.join(root, "data"), - XDG_STATE_HOME: path.join(root, "state"), - } + const env = { ...serviceEnv(root), OPENCODE_DB: database } const command = [process.execPath, path.join(import.meta.dir, "../src/index.ts"), "serve", "--service"] const registration = path.join(root, "state", "opencode", "service-local.json") const owner = Bun.spawn(command, { env, stderr: "pipe", stdout: "ignore" }) @@ -689,9 +643,36 @@ async function availablePort() { return port } +/** A registration watched in-process. `stops` advances the test clock until the watch shuts the server down. */ +const registered = Effect.fnUntraced(function* () { + const fileSystem = yield* FileSystem.FileSystem + const file = path.join(yield* fileSystem.makeTempDirectoryScoped(), "service-local.json") + const stopped = yield* Deferred.make() + const cleanup = yield* ServiceRegistration.register({ + address: { _tag: "TcpAddress", hostname: "127.0.0.1", port: 4321 }, + password: "secret", + id: "owner", + file, + shutdown: Deferred.succeed(stopped, undefined).pipe(Effect.asVoid), + }) + // Let the watch's immediate first check read the intact file, so the damage is found by a scheduled check. + yield* TestClock.withLive(Effect.sleep("50 millis")) + // Each check reads the file for real, so give that I/O live time between 5 s steps. Fail rather than hang. + const stops = Effect.gen(function* () { + for (const _ of Array.from({ length: 100 })) { + if (yield* Deferred.isDone(stopped)) return + yield* TestClock.adjust("5 seconds") + yield* TestClock.withLive(Effect.sleep("10 millis")) + } + return yield* Effect.fail(new Error("The registration watch never shut the server down")) + }) + return { fileSystem, file, stops, cleanup } +}) + function serviceEnv(root: string) { return { ...process.env, + BUN_RUNTIME_TRANSPILER_CACHE_PATH: transpilerCache, HOME: root, OPENCODE_DB: path.join(root, "opencode.db"), OPENCODE_TEST_HOME: root,