diff --git a/.claude/skills/verify-outline/scripts/verify-outline.sh b/.claude/skills/verify-outline/scripts/verify-outline.sh index 375380346c..3869f76ae3 100755 --- a/.claude/skills/verify-outline/scripts/verify-outline.sh +++ b/.claude/skills/verify-outline/scripts/verify-outline.sh @@ -240,7 +240,7 @@ cmd_down() { local pid pids pid="$(cat "$PID_FILE" 2>/dev/null || true)" if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then - # throng forks a worker; stop the tree we started, never by process name. + # the cluster forks a worker; stop the tree we started, never by process name. pids="$(tree "$pid" | tr '\n' ' ')" kill $pids 2>/dev/null || true for _ in $(seq 1 10); do kill -0 $pids 2>/dev/null || break; sleep 1; done diff --git a/package.json b/package.json index e55a84e6de..0060c4ac4e 100644 --- a/package.json +++ b/package.json @@ -254,7 +254,6 @@ "stoppable": "^1.1.0", "string-replace-to-array": "^2.1.1", "styled-components": "^6.5.3", - "throng": "^5.0.0", "tiny-cookie": "^2.5.1", "tmp": "^0.2.6", "tunnel-agent": "^0.6.0", @@ -322,7 +321,6 @@ "@types/semver": "^7.7.1", "@types/slug": "^5.0.9", "@types/stoppable": "^1.1.3", - "@types/throng": "^5.0.7", "@types/tmp": "^0.2.6", "@types/utf8": "^3.0.3", "@types/validator": "^13.15.10", diff --git a/server/index.ts b/server/index.ts index c996f9e7f7..0af855f440 100644 --- a/server/index.ts +++ b/server/index.ts @@ -2,9 +2,9 @@ import "zod/compile"; import "./logging/tracer"; // must come before importing any instrumented module import os from "node:os"; -import throng from "throng"; import env from "./env"; import Logger from "./logging/Logger"; +import { ClusterManager } from "./utils/ClusterManager"; import { printEnv, checkPendingMigrations, @@ -28,8 +28,8 @@ if (env.SERVICES.includes("collaboration") && !env.REDIS_COLLABORATION_URL) { // This function will only be called once in the original process. The database // connection and migration checks run in a short-lived child process so that -// the long-lived master never loads the (heavy) Sequelize models graph. -async function master() { +// the long-lived primary never loads the (heavy) Sequelize models graph. +async function primary() { await checkPendingMigrations(); await printEnv(); } @@ -42,8 +42,6 @@ const isWebProcess = const isWorkerProcess = env.SERVICES.length === 1 && env.SERVICES.includes("worker"); -// Mirrors the `count` passed to throng below, where undefined falls back to -// throng's default of one process per CPU. const processCount = isWorkerProcess ? 1 : isWebProcess @@ -52,11 +50,11 @@ const processCount = isWorkerProcess configureChildHeapLimit(processCount); -void throng({ - master, +void ClusterManager.start({ + primary, // The worker's heavy dependency graph is loaded lazily so it never enters the - // master process, which only supervises the forked workers. + // primary process, which only supervises the forked workers. worker: (id, disconnect) => import("./main").then(({ start }) => start(id, disconnect)), - count: isWorkerProcess ? 1 : isWebProcess ? webProcessCount : undefined, + count: processCount, }); diff --git a/server/logging/Logger.ts b/server/logging/Logger.ts index fe30ded307..48c06ceb7d 100644 --- a/server/logging/Logger.ts +++ b/server/logging/Logger.ts @@ -6,7 +6,7 @@ import winston from "winston"; import env from "@server/env"; import Metrics from "@server/logging/Metrics"; import Sentry from "@server/logging/sentry"; -import ShutdownHelper from "@server/utils/ShutdownHelper"; +import { ShutdownHelper } from "@server/utils/ShutdownHelper"; import * as Tracing from "./tracer"; type LogCategory = diff --git a/server/logging/tracer.ts b/server/logging/tracer.ts index 7db4d208fc..72445810d4 100644 --- a/server/logging/tracer.ts +++ b/server/logging/tracer.ts @@ -63,7 +63,7 @@ export const queryStringObfuscation = `(?<=(?:^|&)(?!(?:${allowedQueryParameters // If the DataDog agent is installed and the DD_API_KEY environment variable is // in the environment then we can safely attempt to start the DD tracer. This // must happen before any instrumented module is imported. -// Note: the tracer is only loaded in worker processes. The throng master +// Note: the tracer is only loaded in worker processes. The cluster primary // supervises forked workers and never serves traffic. if (env.DD_API_KEY && cluster.isWorker) { // oxlint-disable-next-line typescript/no-require-imports -- kept lazy so dd-trace stays off the startup path diff --git a/server/main.ts b/server/main.ts index 7c88a4b98e..45a57edb9b 100644 --- a/server/main.ts +++ b/server/main.ts @@ -21,7 +21,7 @@ import { CacheHelper } from "./utils/CacheHelper"; import { PluginManager } from "./utils/PluginManager"; import { redirectOnClient } from "./utils/redirectOnClient"; import { RedisPrefixHelper } from "./utils/RedisPrefixHelper"; -import ShutdownHelper, { ShutdownOrder } from "./utils/ShutdownHelper"; +import { ShutdownHelper, ShutdownOrder } from "./utils/ShutdownHelper"; import { getSSLOptions } from "./utils/ssl"; import { checkUpdates } from "./utils/updates"; @@ -30,7 +30,7 @@ import { checkUpdates } from "./utils/updates"; * graph (Sequelize models, services, middleware) is loaded, so it is imported * dynamically from the entry point to keep the supervising master process lean. * - * @param id the cluster worker id assigned by throng. + * @param id the cluster worker id assigned by the ClusterManager. * @param disconnect callback used to signal the worker has stopped. */ export async function start(id: number, disconnect: () => void) { diff --git a/server/queues/queue.ts b/server/queues/queue.ts index d8ad6af85f..18aac146fe 100644 --- a/server/queues/queue.ts +++ b/server/queues/queue.ts @@ -6,7 +6,7 @@ import env from "@server/env"; import Logger from "@server/logging/Logger"; import Metrics from "@server/logging/Metrics"; import Redis from "@server/storage/redis"; -import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; +import { ShutdownHelper, ShutdownOrder } from "@server/utils/ShutdownHelper"; export function createQueue( name: string, diff --git a/server/scripts/checkMigrations.ts b/server/scripts/checkMigrations.ts index 3e232a828f..8979c1c309 100644 --- a/server/scripts/checkMigrations.ts +++ b/server/scripts/checkMigrations.ts @@ -14,7 +14,7 @@ import { } from "@server/storage/database"; import { getArg } from "@server/utils/args"; import { MutexLock } from "@server/utils/MutexLock"; -import ShutdownHelper from "@server/utils/ShutdownHelper"; +import { ShutdownHelper } from "@server/utils/ShutdownHelper"; /** * Checks for pending database migrations and runs them, unless the diff --git a/server/services/collaboration.ts b/server/services/collaboration.ts index f839e1fb1e..fb4200a987 100644 --- a/server/services/collaboration.ts +++ b/server/services/collaboration.ts @@ -15,7 +15,7 @@ import env from "@server/env"; import Logger from "@server/logging/Logger"; import { rejectUpgrade } from "@server/onupgrade"; import RedisAdapter from "@server/storage/redis"; -import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; +import { ShutdownHelper, ShutdownOrder } from "@server/utils/ShutdownHelper"; import AuthenticationExtension from "../collaboration/AuthenticationExtension"; import AwarenessIdentityExtension from "../collaboration/AwarenessIdentityExtension"; import { EditorVersionExtension } from "../collaboration/EditorVersionExtension"; diff --git a/server/services/web.ts b/server/services/web.ts index 6f6273396c..8541da9b1a 100644 --- a/server/services/web.ts +++ b/server/services/web.ts @@ -14,7 +14,7 @@ import Logger from "@server/logging/Logger"; import Metrics from "@server/logging/Metrics"; import csp from "@server/middlewares/csp"; import { attachCSRFToken } from "@server/middlewares/csrf"; -import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; +import { ShutdownHelper, ShutdownOrder } from "@server/utils/ShutdownHelper"; import { initI18n } from "@server/utils/i18n"; import routes from "../routes"; import api from "../routes/api"; diff --git a/server/services/websockets.ts b/server/services/websockets.ts index 57542a8332..ade9380e0e 100644 --- a/server/services/websockets.ts +++ b/server/services/websockets.ts @@ -15,7 +15,7 @@ import { traceFunction } from "@server/logging/tracing"; import type { User } from "@server/models"; import { rejectUpgrade } from "@server/onupgrade"; import Redis from "@server/storage/redis"; -import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; +import { ShutdownHelper, ShutdownOrder } from "@server/utils/ShutdownHelper"; import { getUserForJWT } from "@server/utils/jwt"; import { websocketQueue } from "../queues"; import WebsocketsProcessor from "../queues/processors/WebsocketsProcessor"; diff --git a/server/utils/ClusterManager.test.ts b/server/utils/ClusterManager.test.ts new file mode 100644 index 0000000000..09cca5d5ee --- /dev/null +++ b/server/utils/ClusterManager.test.ts @@ -0,0 +1,135 @@ +// @vitest-isolate true +import cluster from "node:cluster"; +import type { Worker } from "node:cluster"; + +vi.mock("node:cluster", () => { + const listeners: Record void> = {}; + return { + default: { + worker: undefined, + workers: {}, + fork: vi.fn(), + on: vi.fn((event: string, listener: () => void) => { + listeners[event] = listener; + }), + emit: (event: string) => listeners[event]?.(), + }, + }; +}); + +const mockCluster = vi.mocked(cluster) as typeof cluster & { + emit: (event: string) => void; +}; + +describe("ClusterManager", () => { + let signalHandlers: Map void>; + + beforeEach(() => { + vi.resetModules(); + vi.mocked(cluster.fork).mockClear(); + Object.assign(cluster, { worker: undefined, workers: {} }); + signalHandlers = new Map(); + vi.spyOn(process, "on").mockImplementation((( + event: string, + handler: () => void + ) => { + signalHandlers.set(event, handler); + return process; + }) as typeof process.on); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it("should run the primary callback then fork workers", async () => { + const { ClusterManager } = await import("./ClusterManager"); + const order: string[] = []; + vi.mocked(cluster.fork).mockImplementation(() => { + order.push("fork"); + return {} as Worker; + }); + + await ClusterManager.start({ + primary: () => { + order.push("primary"); + }, + worker: vi.fn(), + count: 3, + }); + + expect(order).toEqual(["primary", "fork", "fork", "fork"]); + expect([...signalHandlers.keys()]).toEqual(["SIGTERM", "SIGINT"]); + }); + + it("should run the worker callback in a worker process", async () => { + const { ClusterManager } = await import("./ClusterManager"); + const disconnect = vi.fn(); + Object.assign(cluster, { worker: { id: 7, disconnect } }); + const worker = vi.fn(); + const primary = vi.fn(); + + await ClusterManager.start({ primary, worker, count: 2 }); + + expect(primary).not.toHaveBeenCalled(); + expect(cluster.fork).not.toHaveBeenCalled(); + expect(worker).toHaveBeenCalledWith(7, expect.any(Function)); + + vi.useFakeTimers(); + worker.mock.calls[0][1](); + expect(disconnect).not.toHaveBeenCalled(); + vi.advanceTimersByTime(50); + expect(disconnect).toHaveBeenCalled(); + }); + + it("should replace workers that disconnect until shutdown", async () => { + const { ClusterManager } = await import("./ClusterManager"); + await ClusterManager.start({ worker: vi.fn(), count: 1 }); + expect(cluster.fork).toHaveBeenCalledTimes(1); + + mockCluster.emit("disconnect"); + expect(cluster.fork).toHaveBeenCalledTimes(2); + + vi.useFakeTimers(); + const kill = vi.fn(); + Object.assign(cluster, { workers: { 1: { process: { kill } } } }); + signalHandlers.get("SIGTERM")?.(); + expect(kill).toHaveBeenCalledWith("SIGTERM"); + + mockCluster.emit("disconnect"); + expect(cluster.fork).toHaveBeenCalledTimes(2); + }); + + it("should force kill workers after the grace period", async () => { + const { ClusterManager } = await import("./ClusterManager"); + const exit = vi + .spyOn(process, "exit") + .mockImplementation((() => undefined) as typeof process.exit); + await ClusterManager.start({ worker: vi.fn(), count: 1 }); + + vi.useFakeTimers(); + const kill = vi.fn(); + Object.assign(cluster, { workers: { 1: { process: { kill } } } }); + signalHandlers.get("SIGTERM")?.(); + expect(kill).toHaveBeenCalledWith("SIGTERM"); + expect(exit).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(ClusterManager.gracePeriod); + expect(kill).toHaveBeenCalledWith("SIGKILL"); + expect(exit).toHaveBeenCalled(); + }); + + it("should not fork workers when shutdown begins during the primary callback", async () => { + const { ClusterManager } = await import("./ClusterManager"); + vi.useFakeTimers(); + + await ClusterManager.start({ + primary: () => signalHandlers.get("SIGTERM")?.(), + worker: vi.fn(), + count: 2, + }); + + expect(cluster.fork).not.toHaveBeenCalled(); + }); +}); diff --git a/server/utils/ClusterManager.ts b/server/utils/ClusterManager.ts new file mode 100644 index 0000000000..de3fee8309 --- /dev/null +++ b/server/utils/ClusterManager.ts @@ -0,0 +1,97 @@ +import cluster, { type Worker } from "node:cluster"; +import os from "node:os"; +import { Second } from "@shared/utils/time"; +import { ShutdownHelper } from "./ShutdownHelper"; + +interface ClusterOptions { + /** Called once in the primary process before any worker is forked. */ + primary?: () => Promise | void; + /** Called in each forked worker process with its id and a disconnect callback. */ + worker: (id: number, disconnect: () => void) => Promise | void; + /** The number of workers to fork, defaults to one per CPU. */ + count?: number; +} + +/** + * Supervises a cluster of forked worker processes. The primary process forks + * the workers, replaces any that exit unexpectedly, and forwards termination + * signals to them. + */ +export class ClusterManager { + /** + * The amount of time to wait for workers to exit after a termination signal + * before they are force killed and the primary process exits. This is longer + * than the worker's own force quit timeout so that it can exit first. + */ + public static readonly gracePeriod = + ShutdownHelper.forceQuitTimeout + 5 * Second.ms; + + /** The signals that cause the cluster to shut down. */ + public static readonly signals: NodeJS.Signals[] = ["SIGTERM", "SIGINT"]; + + /** + * Starts the cluster. In the primary process this runs the primary callback + * and then forks the workers; in a worker process it runs the worker callback. + * + * @param options the callbacks and worker count for the cluster. + * @returns a promise that resolves when the callback for this process completes. + */ + public static async start({ + primary, + worker, + count = os.cpus().length, + }: ClusterOptions) { + const current = cluster.worker; + if (current) { + return worker(current.id, () => this.disconnect(current)); + } + + cluster.on("disconnect", () => { + if (this.running) { + cluster.fork(); + } + }); + + for (const signal of this.signals) { + process.on(signal, () => this.shutdown(signal)); + } + + await primary?.(); + + // A termination signal may arrive while the primary callback runs. + if (!this.running) { + return; + } + + for (let i = 0; i < count; i++) { + cluster.fork(); + } + } + + private static running = true; + + private static shutdown(signal: NodeJS.Signals) { + this.running = false; + + setTimeout(() => { + for (const worker of Object.values(cluster.workers ?? {})) { + worker?.process.kill("SIGKILL"); + } + process.exit(); + }, this.gracePeriod).unref(); + + for (const worker of Object.values(cluster.workers ?? {})) { + worker?.process.kill(signal); + } + } + + /** + * Disconnects the worker after a short delay, so that pending I/O such as + * log output can flush before the process exits. + * + * @param worker the worker to disconnect. + */ + private static disconnect(worker: Worker) { + setTimeout(() => worker.disconnect(), 50); + } +} diff --git a/server/utils/MutexLock.ts b/server/utils/MutexLock.ts index f56603e577..c3df41c86b 100644 --- a/server/utils/MutexLock.ts +++ b/server/utils/MutexLock.ts @@ -8,7 +8,7 @@ import Redlock, { import { toError } from "@shared/utils/error"; import Redis from "@server/storage/redis"; import Logger from "@server/logging/Logger"; -import ShutdownHelper, { ShutdownOrder } from "./ShutdownHelper"; +import { ShutdownHelper, ShutdownOrder } from "./ShutdownHelper"; type AcquireOptions = { /** Whether a lock should be automatically released on server shutdown */ diff --git a/server/utils/ShutdownHelper.ts b/server/utils/ShutdownHelper.ts index 0b22ebcc2a..0dda465065 100644 --- a/server/utils/ShutdownHelper.ts +++ b/server/utils/ShutdownHelper.ts @@ -21,7 +21,7 @@ type Handler = { * Coordinates graceful shutdown of the process by executing registered * handlers in order. */ -export default class ShutdownHelper { +export class ShutdownHelper { /** * The amount of time to wait for connections to close before forcefully * closing them. This allows for regular HTTP requests to complete but diff --git a/yarn.lock b/yarn.lock index 84628281ee..bbd975ffbd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6770,13 +6770,6 @@ __metadata: languageName: node linkType: hard -"@types/throng@npm:^5.0.7": - version: 5.0.7 - resolution: "@types/throng@npm:5.0.7" - checksum: 10c0/58574cacbff8c6f36c652d745b9e2f16f28054c11d756ab2cfc3533e1a06264b176a5d869b28c1d53e299b0bc5c2f48b88a6f7aa1a29b4d276d19503d81b4787 - languageName: node - linkType: hard - "@types/tmp@npm:^0.2.6": version: 0.2.6 resolution: "@types/tmp@npm:0.2.6" @@ -13052,7 +13045,7 @@ __metadata: languageName: node linkType: hard -"lodash@npm:^4.17.11, lodash@npm:^4.17.20, lodash@npm:^4.17.21, lodash@npm:^4.18.1": +"lodash@npm:^4.17.11, lodash@npm:^4.17.21, lodash@npm:^4.18.1": version: 4.18.1 resolution: "lodash@npm:4.18.1" checksum: 10c0/757228fc68805c59789e82185135cf85f05d0b2d3d54631d680ca79ec21944ec8314d4533639a14b8bcfbd97a517e78960933041a5af17ecb693ec6eecb99a27 @@ -14325,7 +14318,6 @@ __metadata: "@types/semver": "npm:^7.7.1" "@types/slug": "npm:^5.0.9" "@types/stoppable": "npm:^1.1.3" - "@types/throng": "npm:^5.0.7" "@types/tmp": "npm:^0.2.6" "@types/utf8": "npm:^3.0.3" "@types/validator": "npm:^13.15.10" @@ -14487,7 +14479,6 @@ __metadata: string-replace-to-array: "npm:^2.1.1" styled-components: "npm:^6.5.3" terser: "npm:^5.49.0" - throng: "npm:^5.0.0" tiny-cookie: "npm:^2.5.1" tmp: "npm:^0.2.6" tunnel-agent: "npm:^0.6.0" @@ -18104,15 +18095,6 @@ __metadata: languageName: node linkType: hard -"throng@npm:^5.0.0": - version: 5.0.0 - resolution: "throng@npm:5.0.0" - dependencies: - lodash: "npm:^4.17.20" - checksum: 10c0/560103857ecb2077761887917e7e2ad6ef07351c7869017420369e5bea1225c9dd331d92b835903cc513f259afd9b23fa77ecc14770fb7e5713803ee02519a59 - languageName: node - linkType: hard - "through2@npm:^2.0.1": version: 2.0.5 resolution: "through2@npm:2.0.5"