Skip to content
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
"./*": "./*"
Expand Down
4 changes: 1 addition & 3 deletions rolldown.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" };

Expand Down Expand Up @@ -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",
Expand Down
14 changes: 14 additions & 0 deletions server/plugins/child_cleanup.ts
Original file line number Diff line number Diff line change
@@ -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);
});
67 changes: 67 additions & 0 deletions server/utils/browser_server.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
}

async function waitExit(
nuxtProcess: child_process.ChildProcessWithoutNullStreams,
signal: AbortSignal,
): Promise<boolean> {
try {
await once(nuxtProcess, "exit", { signal });
return true;
} catch {
return false;
}
}

async function waitStopTimeout(signal: AbortSignal): Promise<boolean> {
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<void> {
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 };
68 changes: 68 additions & 0 deletions server/utils/child_registry.ts
Original file line number Diff line number Diff line change
@@ -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<ChildProcess>();
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 };
2 changes: 2 additions & 0 deletions server/utils/microservices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -126,6 +127,7 @@ async function runExtensionServer(entryPath: string, attempts = 0): Promise<numb
PORT: String(port),
},
});
registerChild(child);
await waitUntilListening(child);
return port;
} catch (error) {
Expand Down
2 changes: 2 additions & 0 deletions server/utils/microservices_process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { consola } from "consola";
// Local imports
import { type NamedChildProcess, waitForReady } from "./scripts.js";
import { executablePath } from "./path.js";
import { registerChild } from "./child_registry.js";

interface RunArgs {
projectFolderPath: string;
Expand All @@ -33,6 +34,7 @@ async function runScript(
const child = child_process.spawn(command, args, {
stdio: ["ignore", "pipe", "pipe"],
}) as NamedChildProcess;
registerChild(child);
child.name = command.replace(/^.*[\\/]/u, "");
child.on("spawn", () => {
consola.info(`[${child.name}] spawned, pid=${child.pid}`);
Expand Down
50 changes: 50 additions & 0 deletions server/utils/process_tree.ts
Original file line number Diff line number Diff line change
@@ -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<number, number[]> {
const output = child_process.execFileSync("ps", ["-A", "-o", "pid=,ppid="], {
encoding: "utf8",
});
const childrenByParent = new Map<number, number[]>();
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 };
13 changes: 10 additions & 3 deletions server/utils/scripts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -186,7 +187,7 @@ async function waitNuxt(
}
throw new Error("Nuxt process closed");
}
async function runBrowser(scriptName: string): Promise<number> {
async function runBrowser(scriptName: string): Promise<BrowserServer> {
process.env.MODE = appMode.BROWSER;
const port = await getAvailablePort();
const nuxtProcess = child_process.spawn("npm", ["run", scriptName], {
Expand All @@ -197,8 +198,14 @@ async function runBrowser(scriptName: string): Promise<number> {
},
});
await waitNuxt(nuxtProcess);
await setAppBaseUrl(`http://localhost:${port}`);
return port;
const appBaseUrl = `http://localhost:${port}`;
await setAppBaseUrl(appBaseUrl);
return {
port,
stop: async (): Promise<void> => {
await stopServer(nuxtProcess, appBaseUrl);
},
};
}
export { commandExistsSync, getAvailablePort, runBrowser, waitForReady };
export type { NamedChildProcess };
10 changes: 9 additions & 1 deletion shared/scripts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,12 @@ async function getIsAppReady(appBaseUrl: string): Promise<unknown> {
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<unknown> {
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 };
11 changes: 8 additions & 3 deletions tests/browser/helpers/screenshot_path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[/\\](?<suite>.+)\.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[/\\](?<suite>.+)\.[jt]s$/u;

// The fields of the Playwright TestInfo the path depends on
type ScreenshotTestInfo = Pick<TestInfo, "file" | "titlePath"> & {
project: Pick<TestInfo["project"], "testDir">;
};

// Same as Playwright's {testName}: every ASCII character except letters, digits and "-" becomes "-"
function sanitizeForFilePath(name: string): string {
Expand All @@ -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/<suite>.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) {
Expand Down
12 changes: 12 additions & 0 deletions tests/browser/suites/image/index.ts
Original file line number Diff line number Diff line change
@@ -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<string, (runtime: SuiteRuntime) => void> = {
"image/raster_image": rasterImage,
};

export { suites };
Loading
Loading