diff --git a/package.json b/package.json index 12b63a299..e9ad75270 100644 --- a/package.json +++ b/package.json @@ -44,18 +44,22 @@ ".": "./nuxt.config.ts", "./server/utils/*.js": { "types": "./server/utils/*.ts", + "geode-source": "./server/utils/*.ts", "default": "./.build/server/utils/*.js" }, "./tests/browser/helpers/*.js": { "types": "./tests/browser/helpers/*.ts", + "geode-source": "./tests/browser/helpers/*.ts", "default": "./.build/tests/browser/helpers/*.js" }, "./tests/browser/suites/*.js": { "types": "./tests/browser/suites/*.ts", + "geode-source": "./tests/browser/suites/*.ts", "default": "./.build/tests/browser/suites/*.js" }, "./shared/*.js": { "types": "./shared/*.ts", + "geode-source": "./shared/*.ts", "default": "./.build/shared/*.js" }, "./*": "./*" diff --git a/rolldown.config.ts b/rolldown.config.ts index 882130cb7..65edfcf31 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -2,7 +2,6 @@ import fs from "node:fs"; import path from "node:path"; import { defineConfig } from "rolldown"; -import { viteImportGlobPlugin } from "rolldown/experimental"; import package_json from "./package.json" with { type: "json" }; @@ -74,8 +73,7 @@ export default defineConfig({ ], platform: "node", external: isExternal, - // The suites index collects the suite files with import.meta.glob - plugins: [helpersAssetsPlugin, viteImportGlobPlugin()], + plugins: [helpersAssetsPlugin], output: { dir: ".build", format: "esm", diff --git a/server/plugins/child_cleanup.ts b/server/plugins/child_cleanup.ts new file mode 100644 index 000000000..f9153646e --- /dev/null +++ b/server/plugins/child_cleanup.ts @@ -0,0 +1,14 @@ +// Node imports + +// Third party imports +import { defineNitroPlugin } from "nitropack/runtime"; + +// Local imports +import { killAllChildren } from "@geode/opengeodeweb-front/server/utils/child_registry.ts"; + +// Stop the microservices when Nitro closes (graceful shutdown on SIGINT/SIGTERM, dev server restart). +// In dev, every server-code edit reloads Nitro and closes it: the back and viewer of the open page are killed too, +// Which is better than leaking them (client-code edits go through Vite HMR and keep them). +export default defineNitroPlugin((nitroApp) => { + nitroApp.hooks.hook("close", killAllChildren); +}); diff --git a/server/utils/browser_server.ts b/server/utils/browser_server.ts new file mode 100644 index 000000000..c3105b506 --- /dev/null +++ b/server/utils/browser_server.ts @@ -0,0 +1,67 @@ +// Node imports +import type child_process from "node:child_process"; +import { setTimeout as delay } from "node:timers/promises"; +import { once } from "node:events"; + +// Third party imports +import { consola } from "consola"; + +// Local imports +import { killApp } from "@geode/opengeodeweb-front/shared/scripts.ts"; +import { killProcessTree } from "./process_tree.js"; + +const STOP_TIMEOUT_MS = 10_000; + +interface BrowserServer { + port: number; + // Resolves once the server has exited; its microservices were sent SIGTERM, they may still be exiting + stop: () => Promise; +} + +async function waitExit( + nuxtProcess: child_process.ChildProcessWithoutNullStreams, + signal: AbortSignal, +): Promise { + try { + await once(nuxtProcess, "exit", { signal }); + return true; + } catch { + return false; + } +} + +async function waitStopTimeout(signal: AbortSignal): Promise { + try { + await delay(STOP_TIMEOUT_MS, undefined, { signal }); + } catch { + consola.debug("Nuxt exited before the stop timeout"); + } + return false; +} + +// Asks the server to exit, which sends SIGTERM to its microservices, then kills its process tree when it is still +// Running after STOP_TIMEOUT_MS. It resolves once the server is gone: the microservices may still be exiting. +async function stopServer( + nuxtProcess: child_process.ChildProcessWithoutNullStreams, + appBaseUrl: string, +): Promise { + if (nuxtProcess.exitCode !== null || nuxtProcess.signalCode !== null) { + return; + } + const controller = new AbortController(); + const exited = waitExit(nuxtProcess, controller.signal); + try { + await killApp(appBaseUrl); + } catch (error) { + consola.debug("killApp request ended with", error); + } + const hasExited = await Promise.race([exited, waitStopTimeout(controller.signal)]); + controller.abort(); + if (!hasExited && nuxtProcess.pid !== undefined) { + consola.warn("Nuxt did not exit in time, killing its process tree"); + killProcessTree(nuxtProcess.pid); + } +} + +export { stopServer }; +export type { BrowserServer }; diff --git a/server/utils/child_registry.ts b/server/utils/child_registry.ts new file mode 100644 index 000000000..7e6282016 --- /dev/null +++ b/server/utils/child_registry.ts @@ -0,0 +1,68 @@ +// Node imports +import child_process, { type ChildProcess } from "node:child_process"; + +// Third party imports +import { consola } from "consola"; + +// Local imports + +// The microservices run with --timeout 0: without this registry they outlive the server that spawned them. +// In dev, Nitro runs in a worker thread where the signal listeners below never fire: the cleanup then relies on +// The Nitro close hook (../plugins/child_cleanup.ts) and on the exit event. +const CLEANUP_SIGNALS: readonly NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP"]; +const children = new Set(); +let handlersInstalled = false; + +function killChild(child: ChildProcess): void { + const { pid } = child; + if (pid === undefined || child.exitCode !== null || child.signalCode !== null) { + return; + } + try { + if (process.platform === "win32") { + child_process.spawnSync("taskkill", ["/PID", String(pid), "/T", "/F"]); + } else { + process.kill(pid, "SIGTERM"); + } + } catch (error) { + consola.warn(`[child_registry] failed to kill pid=${pid}`, error); + } +} + +function killAllChildren(): void { + for (const child of children) { + killChild(child); + } + children.clear(); +} + +// Nitro's graceful shutdown listens to SIGINT and SIGTERM and exits by itself. When no one else listens, the +// Signal is raised again without this handler, so that the process ends as it would have without it. +function onSignal(signal: NodeJS.Signals): void { + killAllChildren(); + if (process.listenerCount(signal) === 1) { + process.removeListener(signal, onSignal); + process.kill(process.pid, signal); + } +} + +function installCleanupHandlers(): void { + if (handlersInstalled) { + return; + } + handlersInstalled = true; + process.once("exit", killAllChildren); + for (const signal of CLEANUP_SIGNALS) { + process.on(signal, onSignal); + } +} + +function registerChild(child: ChildProcess): void { + installCleanupHandlers(); + children.add(child); + child.once("exit", () => { + children.delete(child); + }); +} + +export { killAllChildren, registerChild }; diff --git a/server/utils/microservices.ts b/server/utils/microservices.ts index a4822100b..71bb5eb22 100644 --- a/server/utils/microservices.ts +++ b/server/utils/microservices.ts @@ -20,6 +20,7 @@ import { type Microservice, microservicesMetadatasPath, projectMicroservices } f import { addNginxLocation, addSupervisorProgram } from "./cloud.js"; import { executablePath } from "./path.js"; import { getAvailablePort } from "./scripts.js"; +import { registerChild } from "./child_registry.js"; async function runBack( execName: string, @@ -126,6 +127,7 @@ async function runExtensionServer(entryPath: string, attempts = 0): Promise { consola.info(`[${child.name}] spawned, pid=${child.pid}`); diff --git a/server/utils/process_tree.ts b/server/utils/process_tree.ts new file mode 100644 index 000000000..698abda69 --- /dev/null +++ b/server/utils/process_tree.ts @@ -0,0 +1,50 @@ +// Node imports +import child_process from "node:child_process"; + +// Third party imports +import { consola } from "consola"; + +// Local imports + +function parentPids(): Map { + const output = child_process.execFileSync("ps", ["-A", "-o", "pid=,ppid="], { + encoding: "utf8", + }); + const childrenByParent = new Map(); + for (const line of output.split("\n")) { + const [pid, ppid] = line.trim().split(/\s+/u).map(Number); + if (pid !== undefined && ppid !== undefined && !Number.isNaN(pid) && !Number.isNaN(ppid)) { + const siblings = childrenByParent.get(ppid) ?? []; + siblings.push(pid); + childrenByParent.set(ppid, siblings); + } + } + return childrenByParent; +} + +function processTree(rootPid: number): number[] { + const childrenByParent = parentPids(); + const tree = [rootPid]; + // The loop also visits the pids pushed while it runs + for (const pid of tree) { + tree.push(...(childrenByParent.get(pid) ?? [])); + } + return tree; +} + +// Kills a process and all its descendants at once, without letting them clean up +function killProcessTree(rootPid: number): void { + if (process.platform === "win32") { + child_process.spawnSync("taskkill", ["/PID", String(rootPid), "/T", "/F"]); + return; + } + for (const pid of processTree(rootPid)) { + try { + process.kill(pid, "SIGKILL"); + } catch (error) { + consola.debug(`[killProcessTree] pid=${pid} already gone`, error); + } + } +} + +export { killProcessTree }; diff --git a/server/utils/scripts.ts b/server/utils/scripts.ts index 8631eba89..be187fcdd 100644 --- a/server/utils/scripts.ts +++ b/server/utils/scripts.ts @@ -11,6 +11,7 @@ import { consola } from "consola"; import { getPort } from "get-port-please"; // Local imports +import { type BrowserServer, stopServer } from "./browser_server.js"; import { appMode } from "@geode/opengeodeweb-front/shared/app_mode.ts"; import { setAppBaseUrl } from "@geode/opengeodeweb-front/shared/scripts.ts"; @@ -186,7 +187,7 @@ async function waitNuxt( } throw new Error("Nuxt process closed"); } -async function runBrowser(scriptName: string): Promise { +async function runBrowser(scriptName: string): Promise { process.env.MODE = appMode.BROWSER; const port = await getAvailablePort(); const nuxtProcess = child_process.spawn("npm", ["run", scriptName], { @@ -197,8 +198,14 @@ async function runBrowser(scriptName: string): Promise { }, }); await waitNuxt(nuxtProcess); - await setAppBaseUrl(`http://localhost:${port}`); - return port; + const appBaseUrl = `http://localhost:${port}`; + await setAppBaseUrl(appBaseUrl); + return { + port, + stop: async (): Promise => { + await stopServer(nuxtProcess, appBaseUrl); + }, + }; } export { commandExistsSync, getAvailablePort, runBrowser, waitForReady }; export type { NamedChildProcess }; diff --git a/shared/scripts.ts b/shared/scripts.ts index 372ffc757..85d4c3abe 100644 --- a/shared/scripts.ts +++ b/shared/scripts.ts @@ -47,4 +47,12 @@ async function getIsAppReady(appBaseUrl: string): Promise { return result; } -export { getIsAppReady, setAppBaseUrl, setBackBaseUrl, setIsAppReady, setViewerBaseUrl }; +// The server exits before answering: the request fails even when the server stops +async function killApp(appBaseUrl: string): Promise { + consola.info("[API] killApp", appBaseUrl); + const schema = opengeodeweb_front_schemas.api.local.app.kill; + const result = await fetchSchema({ schema, baseURL: appBaseUrl }); + return result; +} + +export { getIsAppReady, killApp, setAppBaseUrl, setBackBaseUrl, setIsAppReady, setViewerBaseUrl }; diff --git a/tests/browser/helpers/screenshot_path.ts b/tests/browser/helpers/screenshot_path.ts index fb7801751..b007df726 100644 --- a/tests/browser/helpers/screenshot_path.ts +++ b/tests/browser/helpers/screenshot_path.ts @@ -8,8 +8,13 @@ import path from "node:path"; import type { TestInfo } from "@playwright/test"; const SUITE_TEST_FILE_EXTENSION = ".test.ts"; -// Built suite files of this layer, where the tests of its suites are located -const SUITE_FILE_REGEX = /tests[/\\]browser[/\\]suites[/\\](?.+)\.js$/u; +// Suite files of this layer (sources or built), where the tests of its suites are located +const SUITE_FILE_REGEX = /tests[/\\]browser[/\\]suites[/\\](?.+)\.[jt]s$/u; + +// The fields of the Playwright TestInfo the path depends on +type ScreenshotTestInfo = Pick & { + project: Pick; +}; // Same as Playwright's {testName}: every ASCII character except letters, digits and "-" becomes "-" function sanitizeForFilePath(name: string): string { @@ -18,7 +23,7 @@ function sanitizeForFilePath(name: string): string { // The shared suites (one describe each, see ../suites/index.ts) keep the folders of their test files here, // Tests/browser/tests/.test.ts; the other tests keep their path in the test folder of the app -function screenshotPath(testInfo: TestInfo): string[] { +function screenshotPath(testInfo: ScreenshotTestInfo): string[] { const titles = testInfo.titlePath.slice(1); const suite = SUITE_FILE_REGEX.exec(testInfo.file)?.groups?.suite; if (suite !== undefined) { diff --git a/tests/browser/suites/image/index.ts b/tests/browser/suites/image/index.ts new file mode 100644 index 000000000..af9e38553 --- /dev/null +++ b/tests/browser/suites/image/index.ts @@ -0,0 +1,12 @@ +// The image suites, by their path in tests/browser/suites without .ts (see ../index.ts) + +// Local imports +import { registerTests as rasterImage } from "./raster_image"; + +import type { SuiteRuntime } from "#browser_helpers/suite_runtime"; + +const suites: Record void> = { + "image/raster_image": rasterImage, +}; + +export { suites }; diff --git a/tests/browser/suites/index.ts b/tests/browser/suites/index.ts index da2b1d514..d6166cd04 100644 --- a/tests/browser/suites/index.ts +++ b/tests/browser/suites/index.ts @@ -1,24 +1,33 @@ // Every shared suite, by its path in tests/browser/suites without .ts (e.g. "mesh/edged_curve"): the apps built on this -// Layer run them all from one test file, each suite in its own describe. Collected from the folder, a new suite file is -// Run by these apps without any change on their side +// Layer run them all from one test file, each suite in its own describe. Listed by hand (Node, which runs the suites +// From the sources in the workspace, has no import.meta.glob): tests/unit/browser_suites.test.ts checks that each suite +// File is listed + +// Local imports +import { registerTests as crs } from "./crs"; +import { registerTests as crsHarmonize } from "./crs_harmonize"; +import { registerTests as crsShortlist } from "./crs_shortlist"; +import { registerTests as gridScale } from "./grid_scale"; +import { suites as imageSuites } from "./image/index"; +import { suites as meshSuites } from "./mesh/index"; +import { suites as modelSuites } from "./model/index"; +import { suites as objectTreeSuites } from "./object_tree/index"; +import { registerTests as timeSeries } from "./time_series"; import type { test as AppTest } from "#browser_helpers/app_test"; import type { SuiteRuntime } from "#browser_helpers/suite_runtime"; -interface SuiteModule { - registerTests: (runtime: SuiteRuntime) => void; -} - -const SUITE_PATH_REGEX = /^\.\/(?.+)\.ts$/u; - -const suiteModules = import.meta.glob(["./**/*.ts", "!./index.ts"], { eager: true }); - -const suites: Record = Object.fromEntries( - Object.entries(suiteModules).map(([file, { registerTests }]) => [ - SUITE_PATH_REGEX.exec(file)?.groups?.name ?? file, - registerTests, - ]), -); +const suites: Record void> = { + crs, + crs_harmonize: crsHarmonize, + crs_shortlist: crsShortlist, + grid_scale: gridScale, + ...imageSuites, + ...meshSuites, + ...modelSuites, + ...objectTreeSuites, + time_series: timeSeries, +}; // Runs every suite from the test file of an app (its test extends ../helpers/app_test.ts): each suite is a describe // Named by its path, which opens the app, runs its tests and closes the app diff --git a/tests/browser/suites/mesh/index.ts b/tests/browser/suites/mesh/index.ts new file mode 100644 index 000000000..636a3be60 --- /dev/null +++ b/tests/browser/suites/mesh/index.ts @@ -0,0 +1,26 @@ +// The mesh suites, by their path in tests/browser/suites without .ts (see ../index.ts) + +// Local imports +import { registerTests as edgedCurve } from "./edged_curve"; +import { registerTests as grid2d } from "./grid2d"; +import { registerTests as grid3d } from "./grid3d"; +import { registerTests as pointSet } from "./point_set"; +import { registerTests as polygonalSurface } from "./polygonal_surface"; +import { registerTests as solid } from "./solid"; +import { registerTests as tetrahedralSolid } from "./tetrahedral_solid"; +import { registerTests as triangulatedSurface } from "./triangulated_surface"; + +import type { SuiteRuntime } from "#browser_helpers/suite_runtime"; + +const suites: Record void> = { + "mesh/edged_curve": edgedCurve, + "mesh/grid2d": grid2d, + "mesh/grid3d": grid3d, + "mesh/point_set": pointSet, + "mesh/polygonal_surface": polygonalSurface, + "mesh/solid": solid, + "mesh/tetrahedral_solid": tetrahedralSolid, + "mesh/triangulated_surface": triangulatedSurface, +}; + +export { suites }; diff --git a/tests/browser/suites/model/index.ts b/tests/browser/suites/model/index.ts new file mode 100644 index 000000000..b6a517a0f --- /dev/null +++ b/tests/browser/suites/model/index.ts @@ -0,0 +1,30 @@ +// The model suites, by their path in tests/browser/suites without .ts (see ../index.ts) + +// Local imports +import { registerTests as blocks } from "./blocks"; +import { registerTests as collections } from "./collections"; +import { registerTests as corners } from "./corners"; +import { registerTests as display } from "./display"; +import { registerTests as edges } from "./edges"; +import { registerTests as lines } from "./lines"; +import { registerTests as physicalProperties } from "./physical_properties"; +import { registerTests as points } from "./points"; +import { registerTests as structuralModel } from "./structural_model"; +import { registerTests as surfaces } from "./surfaces"; + +import type { SuiteRuntime } from "#browser_helpers/suite_runtime"; + +const suites: Record void> = { + "model/blocks": blocks, + "model/collections": collections, + "model/corners": corners, + "model/display": display, + "model/edges": edges, + "model/lines": lines, + "model/physical_properties": physicalProperties, + "model/points": points, + "model/structural_model": structuralModel, + "model/surfaces": surfaces, +}; + +export { suites }; diff --git a/tests/browser/suites/object_tree/index.ts b/tests/browser/suites/object_tree/index.ts new file mode 100644 index 000000000..431f0b2f4 --- /dev/null +++ b/tests/browser/suites/object_tree/index.ts @@ -0,0 +1,20 @@ +// The object_tree suites, by their path in tests/browser/suites without .ts (see ../index.ts) + +// Local imports +import { registerTests as componentRelations } from "./component_relations"; +import { registerTests as controls } from "./controls"; +import { registerTests as groupContextMenu } from "./group_context_menu"; +import { registerTests as modelTreeBar } from "./model_tree_bar"; +import { registerTests as multiTypeImport } from "./multi_type_import"; + +import type { SuiteRuntime } from "#browser_helpers/suite_runtime"; + +const suites: Record void> = { + "object_tree/component_relations": componentRelations, + "object_tree/controls": controls, + "object_tree/group_context_menu": groupContextMenu, + "object_tree/model_tree_bar": modelTreeBar, + "object_tree/multi_type_import": multiTypeImport, +}; + +export { suites }; diff --git a/tests/unit/browser_suites.test.ts b/tests/unit/browser_suites.test.ts new file mode 100644 index 000000000..a478eb760 --- /dev/null +++ b/tests/unit/browser_suites.test.ts @@ -0,0 +1,29 @@ +// Node imports +import fs from "node:fs"; +import path from "node:path"; + +// Third party imports +import { describe, expect, test, vi } from "vitest"; + +// Local imports +import { suites } from "@ogw_tests/browser/suites/index"; + +// The suites only use Playwright when they register their tests +vi.mock(import("@playwright/test"), () => ({})); + +const TS_EXTENSION = ".ts"; +const suitesFolder = path.resolve(import.meta.dirname, "..", "browser", "suites"); + +function suiteFiles(): string[] { + return fs + .readdirSync(suitesFolder, { recursive: true, encoding: "utf8" }) + .filter((file) => file.endsWith(TS_EXTENSION) && path.basename(file) !== `index${TS_EXTENSION}`) + .map((file) => file.slice(0, -TS_EXTENSION.length).split(path.sep).join("/")) + .toSorted(); +} + +describe("browser suites index", () => { + test("lists every suite file", () => { + expect(Object.keys(suites).toSorted()).toStrictEqual(suiteFiles()); + }); +}); diff --git a/tests/unit/helpers/process.ts b/tests/unit/helpers/process.ts new file mode 100644 index 000000000..258c33e78 --- /dev/null +++ b/tests/unit/helpers/process.ts @@ -0,0 +1,47 @@ +// Node imports +import child_process from "node:child_process"; +import { once } from "node:events"; + +// A node process that prints "ready", then waits forever (the microservices run with --timeout 0) +const READY_MESSAGE = "ready"; +const IDLE_SCRIPT = `console.log("${READY_MESSAGE}"); setInterval(() => {}, 1000);`; + +function pidOf(child: child_process.ChildProcess): number { + if (child.pid === undefined) { + throw new Error("The process did not start"); + } + return child.pid; +} + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + if (error instanceof Error && "code" in error && error.code === "ESRCH") { + return false; + } + throw error; + } +} + +async function spawnIdleNode(): Promise { + const child = child_process.spawn(process.execPath, ["-e", IDLE_SCRIPT], { stdio: "ignore" }); + await once(child, "spawn"); + return child; +} + +// A node process whose own child (pid printed on stdout) also waits forever +async function spawnNodeWithGrandchild(): Promise<{ + child: child_process.ChildProcess; + grandchildPid: number; +}> { + const script = `const c = require("node:child_process").spawn(process.execPath, ["-e", ${JSON.stringify(IDLE_SCRIPT)}], { stdio: "ignore" }); console.log(c.pid); setInterval(() => {}, 1000);`; + const child = child_process.spawn(process.execPath, ["-e", script], { + stdio: ["ignore", "pipe", "ignore"], + }); + const output: unknown[] = await once(child.stdout, "data"); + return { child, grandchildPid: Number(String(output[0]).trim()) }; +} + +export { READY_MESSAGE, IDLE_SCRIPT, isAlive, pidOf, spawnIdleNode, spawnNodeWithGrandchild }; diff --git a/tests/unit/screenshot_path.test.ts b/tests/unit/screenshot_path.test.ts new file mode 100644 index 000000000..7b5828590 --- /dev/null +++ b/tests/unit/screenshot_path.test.ts @@ -0,0 +1,38 @@ +// Node imports + +// Third party imports +import { describe, expect, test } from "vitest"; + +// Local imports +import { screenshotPath } from "@ogw_tests/browser/helpers/screenshot_path"; + +const TEST_DIR = "/app/tests/browser/tests"; +const EXPECTED = ["mesh", "points.test.ts", "load-the-points.png"]; + +function suiteTestInfo(file: string): Parameters[0] { + return { + file, + project: { testDir: TEST_DIR }, + titlePath: ["", "Points", "load", "the points"], + }; +} + +describe("screenshot path of a test", () => { + test("built suite file", () => { + const testInfo = suiteTestInfo("/ws/front/.build/tests/browser/suites/mesh/points.js"); + + expect(screenshotPath(testInfo)).toStrictEqual(EXPECTED); + }); + + test("suite source file", () => { + const testInfo = suiteTestInfo("/ws/front/tests/browser/suites/mesh/points.ts"); + + expect(screenshotPath(testInfo)).toStrictEqual(EXPECTED); + }); + + test("suite source file with Windows separators", () => { + const testInfo = suiteTestInfo(String.raw`C:\ws\front\tests\browser\suites\mesh\points.ts`); + + expect(screenshotPath(testInfo)).toStrictEqual(EXPECTED); + }); +}); diff --git a/tests/unit/server/child_registry.nuxt.test.ts b/tests/unit/server/child_registry.nuxt.test.ts new file mode 100644 index 000000000..28ab0fdf8 --- /dev/null +++ b/tests/unit/server/child_registry.nuxt.test.ts @@ -0,0 +1,58 @@ +// Node imports +import { once } from "node:events"; + +// Third party imports +import { describe, expect, test, vi } from "vitest"; + +// Local imports +import { + IDLE_SCRIPT, + READY_MESSAGE, + isAlive, + pidOf, + spawnIdleNode, + spawnNodeWithGrandchild, +} from "@ogw_tests/unit/helpers/process"; +import { + killAllChildren, + registerChild, +} from "@geode/opengeodeweb-front/server/utils/child_registry.ts"; +import { killProcessTree } from "@geode/opengeodeweb-front/server/utils/process_tree.ts"; +import { runScript } from "@geode/opengeodeweb-front/server/utils/microservices_process.ts"; + +vi.setConfig({ testTimeout: 10_000 }); + +describe("child registry", () => { + test("kills the registered children", async () => { + const child = await spawnIdleNode(); + const exited = once(child, "exit"); + registerChild(child); + killAllChildren(); + await exited; + + expect(isAlive(pidOf(child))).toBe(false); + }); + + test("kills the microservices started by runScript", async () => { + const child = await runScript("", "node", ["-e", IDLE_SCRIPT], READY_MESSAGE); + const exited = once(child, "exit"); + killAllChildren(); + await exited; + + expect(isAlive(pidOf(child))).toBe(false); + }); +}); + +describe("process tree", () => { + test("kills a process and its descendants", async () => { + const { child, grandchildPid } = await spawnNodeWithGrandchild(); + const exited = once(child, "exit"); + killProcessTree(pidOf(child)); + await exited; + await vi.waitFor(() => { + expect(isAlive(grandchildPid)).toBe(false); + }); + + expect(isAlive(pidOf(child))).toBe(false); + }); +});