|
| 1 | +import { describe, expect, mock, test } from "bun:test"; |
| 2 | +import type { OcxConfig } from "../src/types"; |
| 3 | +import { scheduleCatalogPrewarm } from "../src/cli/catalog-prewarm"; |
| 4 | + |
| 5 | +const root = new URL("../", import.meta.url); |
| 6 | + |
| 7 | +async function readText(path: string): Promise<string> { |
| 8 | + return await Bun.file(new URL(path, root)).text(); |
| 9 | +} |
| 10 | + |
| 11 | +describe("catalog prewarm on handleStart bind", () => { |
| 12 | + test("scheduleCatalogPrewarm calls gatherRoutedModels(loadConfig()) once", async () => { |
| 13 | + const config = { port: 9_001, providers: {}, defaultProvider: "fixture" } as OcxConfig; |
| 14 | + const gatherRoutedModels = mock(async (_config: OcxConfig) => []); |
| 15 | + const load = mock(() => config); |
| 16 | + const importCatalog = mock(async () => ({ gatherRoutedModels })); |
| 17 | + |
| 18 | + scheduleCatalogPrewarm({ loadConfig: load, importCatalog }); |
| 19 | + |
| 20 | + await Bun.sleep(0); |
| 21 | + expect(importCatalog).toHaveBeenCalledTimes(1); |
| 22 | + expect(load).toHaveBeenCalledTimes(1); |
| 23 | + expect(gatherRoutedModels).toHaveBeenCalledTimes(1); |
| 24 | + expect(gatherRoutedModels.mock.calls[0]?.[0]).toBe(config); |
| 25 | + }); |
| 26 | + |
| 27 | + test("scheduleCatalogPrewarm swallows gather failures", async () => { |
| 28 | + const gatherRoutedModels = mock(async () => { |
| 29 | + throw new Error("discovery failed"); |
| 30 | + }); |
| 31 | + scheduleCatalogPrewarm({ |
| 32 | + loadConfig: () => ({ port: 9_002, providers: {}, defaultProvider: "fixture" }) as OcxConfig, |
| 33 | + importCatalog: async () => ({ gatherRoutedModels }), |
| 34 | + }); |
| 35 | + await Bun.sleep(0); |
| 36 | + expect(gatherRoutedModels).toHaveBeenCalledTimes(1); |
| 37 | + }); |
| 38 | + |
| 39 | + test("handleStart schedules catalog prewarm immediately after a successful bind", async () => { |
| 40 | + const cli = (await readText("src/cli/index.ts")).replace(/\r\n/g, "\n"); |
| 41 | + const bindIdx = cli.indexOf("server = startServer(port);"); |
| 42 | + const prewarmIdx = cli.indexOf("scheduleCatalogPrewarm()"); |
| 43 | + const breakIdx = cli.indexOf("\n break;", bindIdx); |
| 44 | + |
| 45 | + expect(cli).toContain('from "./catalog-prewarm"'); |
| 46 | + expect(bindIdx).toBeGreaterThan(-1); |
| 47 | + expect(prewarmIdx).toBeGreaterThan(bindIdx); |
| 48 | + expect(breakIdx).toBeGreaterThan(prewarmIdx); |
| 49 | + // Must stay inside the successful-bind try path, not only on a later sync. |
| 50 | + expect(cli.slice(bindIdx, breakIdx)).toContain("scheduleCatalogPrewarm()"); |
| 51 | + expect(cli).not.toContain('void import("../codex/catalog").then(({ gatherRoutedModels })'); |
| 52 | + }); |
| 53 | +}); |
| 54 | + |
0 commit comments