diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 8adac0444..9d2084184 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -328,7 +328,8 @@ export async function runCli( const { closeGlobalDispatcher } = await import("./lib/close-dispatcher.js"); const { isTrialEligible, promptAndStartTrial } = await import("./lib/seer-trial.js"); - const { withTelemetry } = await import("./lib/telemetry.js"); + const { flushTelemetryOnExit, withTelemetry } = + await import("./lib/telemetry.js"); const { startCleanupOldBinary } = await import("./lib/upgrade.js"); const { abortPendingVersionCheck, @@ -721,11 +722,12 @@ export async function runCli( } finally { // Abort any pending version check to allow clean exit abortPendingVersionCheck(); - // Arm the backstop first so it fires regardless of what the dispatcher - // teardown does. The unref'd timer only triggers if the loop is still - // referenced after a drained command, so it's a no-op on clean exits + // Send the session, metrics, and client reports now, together with the + // cli.command transaction, so the exit waits for one round trip. Arm the + // backstop before the dispatcher teardown so it fires regardless of what + // the teardown does. It waits for the flush and is a no-op on clean exits // (a libuv refcount quirk on macOS keeps it worthwhile — see #1237). - scheduleForceExit(); + scheduleForceExit(flushTelemetryOnExit()); // Release undici's pooled keep-alive sockets so the event loop can drain // on its own — the root-cause fix. Never rejects (see close-dispatcher.ts). await closeGlobalDispatcher(); diff --git a/packages/cli/src/lib/force-exit.ts b/packages/cli/src/lib/force-exit.ts index a9615ff15..dbc4d65a8 100644 --- a/packages/cli/src/lib/force-exit.ts +++ b/packages/cli/src/lib/force-exit.ts @@ -6,15 +6,60 @@ * #833). * * Schedule a force-exit safety net once the CLI's outer recovery middleware - * has reached a terminal result. The unref'd timer only fires when another - * handle keeps the event loop alive past a drained command, so it stays a - * no-op on clean exits and never arms for commands that intentionally keep - * running (their awaited work never resolves, so this is never reached). + * has reached a terminal result. An unref'd timer arms when the exit + * telemetry flush settles. It only fires when another handle keeps the event + * loop alive past a drained command, so it stays a no-op on clean exits and + * never arms for commands that intentionally keep running (their awaited work + * never resolves, so this is never reached). Outside macOS, the timer is + * longer: it only catches ingest responses that stall after their headers. + * + * On every platform, the process exits when the flush does not settle in its + * time limit. Open ingest requests would otherwise keep it alive, and on a + * slow network the runtime metrics send new ones every 5 s. + * + * @param telemetryFlush - Resolves `true` when the exit telemetry flush + * settles, `false` when its time limit elapses first */ -export function scheduleForceExit(): void { - if (process.platform === "darwin" && process.env.NODE_ENV !== "test") { - setTimeout(() => { - process.exit(process.exitCode ?? 0); - }, 100).unref(); +export function scheduleForceExit( + telemetryFlush: Promise = Promise.resolve(true), +): void { + if (process.env.NODE_ENV === "test") { + return; } + void telemetryFlush.then((settled) => { + if (!settled) { + exitAfterOutputDrains(); + return; + } + const lingerLimitMs = + process.platform === "darwin" + ? DARWIN_LINGER_LIMIT_MS + : DEFAULT_LINGER_LIMIT_MS; + setTimeout(exitAfterOutputDrains, lingerLimitMs).unref(); + }); +} + +const DARWIN_LINGER_LIMIT_MS = 100; +const DEFAULT_LINGER_LIMIT_MS = 1000; + +/** + * `process.exit()` drops stdout and stderr data that a pipe has not taken + * yet, on Linux and macOS. Wait until both streams flush. + * + * `drain` fires only after a `write()` returned `false`, so data below the + * high-water mark can stay pending without it. The callback of an empty write + * runs after all earlier writes, or with an error when the stream is closed. + */ +function exitAfterOutputDrains(): void { + const pending = [process.stdout, process.stderr].filter( + (stream) => stream.writableLength > 0, + ); + void Promise.all( + pending.map( + (stream) => + new Promise((resolve) => { + stream.write("", resolve); + }), + ), + ).then(() => process.exit(process.exitCode ?? 0)); } diff --git a/packages/cli/src/lib/telemetry.ts b/packages/cli/src/lib/telemetry.ts index 9c5d323c9..e325070f5 100644 --- a/packages/cli/src/lib/telemetry.ts +++ b/packages/cli/src/lib/telemetry.ts @@ -164,10 +164,10 @@ export function isTelemetryEnabled(): boolean { * * Creates a Sentry span for the command execution and captures exceptions. * Session lifecycle is managed by the SDK's processSessionIntegration - * (started during Sentry.init) and a beforeExit handler (registered in - * initSentry) that ends healthy sessions and flushes events. This ensures - * sessions are reliably tracked even for unhandled rejections and other - * paths that bypass this function's try/catch. + * (started during Sentry.init) and {@link flushTelemetryOnExit}, which + * `runCli` calls when the command ends. A beforeExit handler (registered in + * initSentry) runs the same flush for unhandled rejections and other paths + * that bypass this function's try/catch. * * Telemetry can be disabled via: * - `SENTRY_CLI_NO_TELEMETRY=1` environment variable @@ -259,13 +259,78 @@ export async function withTelemetry( } } +/** + * Longest time the CLI waits for telemetry after the command ends. + * + * A new connection to ingest and one envelope request take about 200–250 ms + * on a good network (DNS, TCP, TLS, and the response). This bound covers a + * round trip about four times slower. Past it, the network is slow or blocks + * ingest, and the CLI exits and drops the rest. + */ +export const EXIT_FLUSH_TIMEOUT_MS = 1000; + +/** Exit flush of each client, so that every caller shares one flush. */ +const exitFlushes = new WeakMap>(); + +/** + * End a healthy session and send all buffered telemetry in one batch. + * + * The session update, metrics, logs, client reports, and the `cli.command` + * transaction leave together, so the CLI waits for one round trip. Later + * calls for the same client return the first flush. + * + * @returns `true` when the flush settles, `false` when + * {@link EXIT_FLUSH_TIMEOUT_MS} elapses first and requests are still open + * + * @internal Exported for testing + */ +export function flushClientOnExit(client: Sentry.NodeClient): Promise { + const existing = exitFlushes.get(client); + if (existing) { + return existing; + } + + // The SDK's processSessionIntegration ends only OK sessions, and only on + // beforeExit, which open requests delay. End it here (clean exit → + // 'exited'). Crashed and errored sessions keep their status. + const session = Sentry.getIsolationScope().getSession(); + if (session?.status === "ok") { + Sentry.endSession(); + } + + const flushed = Promise.resolve(client.flush(EXIT_FLUSH_TIMEOUT_MS)).catch( + () => true, + ); + const timedOut = new Promise((resolve) => { + setTimeout(() => resolve(false), EXIT_FLUSH_TIMEOUT_MS).unref(); + }); + const flush = Promise.race([flushed, timedOut]); + exitFlushes.set(client, flush); + return flush; +} + +/** + * Send all buffered telemetry when the command ends. See + * {@link flushClientOnExit}. + * + * @returns `true` when telemetry is off or the flush settles, `false` when + * {@link EXIT_FLUSH_TIMEOUT_MS} elapses first + */ +export function flushTelemetryOnExit(): Promise { + const client = Sentry.getClient(); + if (!client?.getOptions().enabled) { + return Promise.resolve(true); + } + return flushClientOnExit(client); +} + /** * Create a beforeExit handler that ends healthy sessions and flushes events. * - * The SDK's processSessionIntegration only ends non-OK sessions (crashed/errored). - * This handler complements it by ending OK sessions (clean exit → 'exited') - * and flushing pending events. Includes a re-entry guard since flush is async - * and causes beforeExit to re-fire when complete. + * `runCli` flushes when the command ends. This handler covers the paths that + * skip it, such as unhandled rejections. It shares the flush of + * {@link flushClientOnExit}, so it does nothing after the exit flush and when + * beforeExit fires again. * * @param client - The Sentry client to flush * @returns A handler function for process.on("beforeExit") @@ -273,25 +338,8 @@ export async function withTelemetry( * @internal Exported for testing */ export function createBeforeExitHandler(client: Sentry.NodeClient): () => void { - let isFlushing = false; return () => { - if (isFlushing) { - return; - } - isFlushing = true; - - const session = Sentry.getIsolationScope().getSession(); - if (session?.status === "ok") { - Sentry.endSession(); - } - - // Flush pending events before exit. Convert PromiseLike to Promise - // for proper error handling. The async work causes beforeExit to - // re-fire when complete, which the isFlushing guard handles. - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - Promise.resolve(client.flush(3000)).catch(() => { - // Ignore flush errors — telemetry should never block CLI exit - }); + void flushClientOnExit(client); }; } @@ -790,11 +838,8 @@ export function initSentry( attachSentryReporter(sentryReporter(Sentry.logger)); // End healthy sessions and flush events when the event loop drains. - // The SDK's processSessionIntegration starts a session during init and - // registers its own beforeExit handler that ends non-OK (crashed/errored) - // sessions. We complement it by ending OK sessions (clean exit → 'exited') - // and flushing pending events. This covers unhandled rejections and other - // paths that bypass withTelemetry's try/catch. + // runCli already flushes when the command ends; this covers unhandled + // rejections and other paths that bypass it. // Ref: https://nodejs.org/api/process.html#event-beforeexit // // Skipped in library mode — the host owns the process lifecycle. diff --git a/packages/cli/test/e2e/telemetry-exit.test.ts b/packages/cli/test/e2e/telemetry-exit.test.ts index 7c066937c..b525a371c 100644 --- a/packages/cli/test/e2e/telemetry-exit.test.ts +++ b/packages/cli/test/e2e/telemetry-exit.test.ts @@ -1,69 +1,240 @@ /** - * Telemetry Exit Timing E2E Tests + * Telemetry Exit E2E Tests * - * Tests that the CLI exits quickly even when telemetry is enabled. - * This verifies the @sentry/core patch that adds .unref() to flush timers. - * - * Without the patch, flush(3000) blocks for ~3 seconds due to non-unref'd timers. - * With the patch, the process can exit immediately when there's nothing to send. + * Runs the npm bundle with telemetry on against a local mock ingest server. + * `test/fixtures/ingest-redirect.cjs` sends the CLI's ingest requests to the + * mock, so no test sends telemetry to Sentry. The SEA binary ignores + * `--require` and `NODE_OPTIONS`, so these tests always use the bundle. */ import { spawn } from "node:child_process"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; import { join } from "node:path"; -import { describe, expect, test } from "vitest"; -import { getCliCommand } from "../fixture.js"; +import zlib from "node:zlib"; +import { afterEach, beforeAll, describe, expect, test } from "vitest"; +import { BUNDLE_BIN_PATH, ensureBundleBuilt } from "./bundle-setup.js"; + +const PRELOAD_PATH = join( + import.meta.dirname, + "../fixtures/ingest-redirect.cjs", +); + +/** Longer than any exit wait the CLI allows, much shorter than a hang. */ +const HANG_TIMEOUT_MS = 15_000; + +/** `release finalize` without auth exits with this code before any API call. */ +const NOT_AUTHENTICATED_EXIT_CODE = 10; + +type ReceivedEnvelope = { + types: string[]; + /** True when the mock had already answered another request. */ + afterFirstResponse: boolean; +}; + +type MockIngest = { + port: number; + envelopes: ReceivedEnvelope[]; + close: () => Promise; +}; + +type CliRun = { + exitCode: number | null; + hung: boolean; +}; function noop(): void { // Intentionally empty — absorbs async spawn errors } -const cliDir = join(import.meta.dirname, "../.."); +function decodeBody(body: Buffer, encoding: string | undefined): Buffer { + if (encoding === "zstd" && zlib.zstdDecompressSync) { + return zlib.zstdDecompressSync(body); + } + if (encoding === "gzip") { + return zlib.gunzipSync(body); + } + return body; +} -describe("telemetry exit timing", () => { - test("process exits without waiting for flush timeout", async () => { - const cmd = getCliCommand(); +/** Item types of an envelope: lines alternate item header and payload. */ +function envelopeItemTypes(body: Buffer): string[] { + const lines = body.toString("utf8").split("\n").slice(1); + const types: string[] = []; + for (let i = 0; i < lines.length; i += 2) { + const header = lines[i]; + if (header) { + types.push((JSON.parse(header) as { type: string }).type); + } + } + return types; +} - // Baseline: telemetry disabled - const disabledStart = performance.now(); - const [cmdBin, ...cmdArgs] = cmd; - const disabledProc = spawn(cmdBin, [...cmdArgs, "--version"], { - cwd: cliDir, - env: { ...process.env, SENTRY_CLI_NO_TELEMETRY: "1" }, - stdio: ["pipe", "pipe", "pipe"], +/** + * Start a mock ingest server that answers `200 {}` after `delayMs`, or never + * when `delayMs` is `null`. With `stallBody`, it sends the headers and part of + * the body, then keeps the connection open. + */ +async function startMockIngest( + delayMs: number | null, + { stallBody = false } = {}, +): Promise { + const envelopes: ReceivedEnvelope[] = []; + let responses = 0; + const server: Server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + const body = decodeBody( + Buffer.concat(chunks), + req.headers["content-encoding"], + ); + envelopes.push({ + types: envelopeItemTypes(body), + afterFirstResponse: responses > 0, + }); + if (delayMs === null) { + return; + } + setTimeout(() => { + responses += 1; + res.writeHead(200, { "content-type": "application/json" }); + if (stallBody) { + res.write("{"); + } else { + res.end("{}"); + } + }, delayMs); }); - disabledProc.on("error", noop); - const disabledExitCode = await new Promise((resolve) => - disabledProc.on("close", (code) => resolve(code ?? 1)), + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return { + port: (server.address() as AddressInfo).port, + envelopes, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +function cliEnv( + ingest: MockIngest, + telemetry: boolean, +): Record { + const env: Record = { + ...process.env, + MOCK_INGEST_PORT: String(ingest.port), + SENTRY_CLI_NO_UPDATE_CHECK: "1", + }; + // The CLI disables its force exit under NODE_ENV=test. + delete env.NODE_ENV; + delete env.SENTRY_AUTH_TOKEN; + delete env.SENTRY_TOKEN; + delete env.DO_NOT_TRACK; + if (telemetry) { + delete env.SENTRY_CLI_NO_TELEMETRY; + } else { + env.SENTRY_CLI_NO_TELEMETRY = "1"; + } + return env; +} + +async function runCli( + ingest: MockIngest, + args: string[], + { telemetry = true } = {}, +): Promise { + const proc = spawn( + process.execPath, + ["--require", PRELOAD_PATH, BUNDLE_BIN_PATH, ...args], + { env: cliEnv(ingest, telemetry), stdio: ["ignore", "pipe", "pipe"] }, + ); + proc.on("error", noop); + proc.stdout.resume(); + proc.stderr.resume(); + + let hung = false; + const killTimer = setTimeout(() => { + hung = true; + proc.kill("SIGKILL"); + }, HANG_TIMEOUT_MS); + const exitCode = await new Promise((resolve) => + proc.on("close", (code) => resolve(code)), + ); + clearTimeout(killTimer); + return { exitCode, hung }; +} + +describe("telemetry at exit", () => { + let ingest: MockIngest | undefined; + + beforeAll(async () => { + await ensureBundleBuilt(); + }, 120_000); // Cold CI builds include the MCP runtime dependencies + + afterEach(async () => { + await ingest?.close(); + ingest = undefined; + }); + + test("sends every exit envelope in one round trip", async () => { + // Longer than the old 100 ms macOS force exit, so a second round trip + // loses data there and is visible in the arrival order everywhere. + ingest = await startMockIngest(300); + + const run = await runCli(ingest, ["release", "finalize", "1.0.0"]); + + expect(run.hung).toBe(false); + expect(run.exitCode).toBe(NOT_AUTHENTICATED_EXIT_CODE); + const types = ingest.envelopes.flatMap((envelope) => envelope.types); + expect(types).toEqual( + expect.arrayContaining(["transaction", "session", "trace_metric"]), ); - const disabledDuration = performance.now() - disabledStart; + expect( + ingest.envelopes.filter((envelope) => envelope.afterFirstResponse), + ).toEqual([]); + }, 30_000); - // Test: telemetry enabled (with patched Sentry) - // Remove SENTRY_CLI_NO_TELEMETRY to enable telemetry - const envWithTelemetry = { ...process.env }; - delete envWithTelemetry.SENTRY_CLI_NO_TELEMETRY; + test("exits when ingest never answers", async () => { + ingest = await startMockIngest(null); - const enabledStart = performance.now(); - const enabledProc = spawn(cmdBin, [...cmdArgs, "--version"], { - cwd: cliDir, - env: envWithTelemetry, - stdio: ["pipe", "pipe", "pipe"], - }); - enabledProc.on("error", noop); - const enabledExitCode = await new Promise((resolve) => - enabledProc.on("close", (code) => resolve(code ?? 1)), + const run = await runCli(ingest, ["release", "finalize", "1.0.0"]); + + expect(run.hung).toBe(false); + expect(run.exitCode).toBe(NOT_AUTHENTICATED_EXIT_CODE); + expect(ingest.envelopes.flatMap((envelope) => envelope.types)).toEqual( + expect.arrayContaining(["transaction", "session"]), ); + }, 30_000); + + test("exits when an ingest response stalls after its headers", async () => { + ingest = await startMockIngest(0, { stallBody: true }); + + const run = await runCli(ingest, ["release", "finalize", "1.0.0"]); + + expect(run.hung).toBe(false); + expect(run.exitCode).toBe(NOT_AUTHENTICATED_EXIT_CODE); + }, 30_000); + + test("process exits without waiting for flush timeout", async () => { + ingest = await startMockIngest(0); + + const disabledStart = performance.now(); + const disabled = await runCli(ingest, ["--version"], { telemetry: false }); + const disabledDuration = performance.now() - disabledStart; + + const enabledStart = performance.now(); + const enabled = await runCli(ingest, ["--version"]); const enabledDuration = performance.now() - enabledStart; - // Both should complete successfully - expect(disabledExitCode).toBe(0); - expect(enabledExitCode).toBe(0); + expect(disabled.exitCode).toBe(0); + expect(enabled.exitCode).toBe(0); - // Enabled should not be significantly slower than disabled. - // Allow 1000ms overhead for Sentry init + potential network attempt + - // CI scheduling jitter, but NOT the old 3000ms+ timeout behavior. + // Allow 1000ms overhead for Sentry init + the mock round trip + CI + // scheduling jitter, but NOT the old 3000ms+ timeout behavior. expect(enabledDuration).toBeLessThan(disabledDuration * 1.5 + 1000); - - // And definitely under 2 seconds total (old behavior was 3+ seconds) expect(enabledDuration).toBeLessThan(2000); - }); + }, 30_000); }); diff --git a/packages/cli/test/fixtures/ingest-redirect.cjs b/packages/cli/test/fixtures/ingest-redirect.cjs new file mode 100644 index 000000000..7193fc808 --- /dev/null +++ b/packages/cli/test/fixtures/ingest-redirect.cjs @@ -0,0 +1,28 @@ +/** + * `--require` preload that sends the CLI's telemetry to a local mock ingest + * server at `127.0.0.1:$MOCK_INGEST_PORT` instead of Sentry. + */ +const http = require("node:http"); +const https = require("node:https"); + +const port = Number(process.env.MOCK_INGEST_PORT); +const ingestHost = /^o\d+\.ingest\.(\w+\.)?sentry\.io$/; +const httpsRequest = https.request; + +https.request = function request(options, ...rest) { + if ( + typeof options === "object" && + !(options instanceof URL) && + ingestHost.test(options.hostname ?? "") + ) { + const local = Object.assign({}, options, { + agent: undefined, + ca: undefined, + protocol: "http:", + hostname: "127.0.0.1", + port, + }); + return http.request(local, ...rest); + } + return httpsRequest.call(this, options, ...rest); +}; diff --git a/packages/cli/test/lib/force-exit.test.ts b/packages/cli/test/lib/force-exit.test.ts index 68acb863c..1044f954a 100644 --- a/packages/cli/test/lib/force-exit.test.ts +++ b/packages/cli/test/lib/force-exit.test.ts @@ -26,8 +26,13 @@ afterEach(() => { } }); +/** Let the `.then()` on the flush promise run. */ +async function settle(): Promise { + await new Promise((resolve) => setImmediate(resolve)); +} + describe("force-exit safety net", () => { - test("schedules an unref'd 100ms timer on macOS outside tests", () => { + test("schedules an unref'd 100ms timer on macOS outside tests", async () => { const unref = vi.fn(); const timeout = { unref } as unknown as ReturnType; const setTimeoutSpy = vi @@ -37,28 +42,79 @@ describe("force-exit safety net", () => { process.env.NODE_ENV = "production"; scheduleForceExit(); + await settle(); expect(setTimeoutSpy).toHaveBeenCalledOnce(); expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 100); expect(unref).toHaveBeenCalledOnce(); }); - test("does nothing outside macOS", () => { - const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout"); + test("schedules an unref'd 1s timer outside macOS when the flush settles", async () => { + const unref = vi.fn(); + const timeout = { unref } as unknown as ReturnType; + const setTimeoutSpy = vi + .spyOn(globalThis, "setTimeout") + .mockReturnValue(timeout); + const exitSpy = vi + .spyOn(process, "exit") + .mockImplementation(() => undefined as never); process.env.NODE_ENV = "production"; - scheduleForceExit(); + scheduleForceExit(Promise.resolve(true)); + await settle(); - expect(setTimeoutSpy).not.toHaveBeenCalled(); + expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 1000); + expect(unref).toHaveBeenCalledOnce(); + expect(exitSpy).not.toHaveBeenCalled(); }); - test("does nothing in the test environment even on macOS", () => { + test("exits on every platform when the flush times out", async () => { + const exitSpy = vi + .spyOn(process, "exit") + .mockImplementation(() => undefined as never); + process.env.NODE_ENV = "production"; + process.exitCode = 10; + + scheduleForceExit(Promise.resolve(false)); + await settle(); + process.exitCode = undefined; + + expect(exitSpy).toHaveBeenCalledWith(10); + }); + + test("exits after pending output flushes without a drain event", async () => { + const exitSpy = vi + .spyOn(process, "exit") + .mockImplementation(() => undefined as never); + vi.spyOn(process.stdout, "writableLength", "get").mockReturnValue(1000); + const writeSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation((_chunk, callback) => { + setImmediate(callback as () => void); + return true; + }); + process.env.NODE_ENV = "production"; + + scheduleForceExit(Promise.resolve(false)); + await settle(); + await settle(); + + expect(writeSpy).toHaveBeenCalledWith("", expect.any(Function)); + expect(exitSpy).toHaveBeenCalledWith(0); + }); + + test("does nothing in the test environment even on macOS", async () => { const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout"); + const exitSpy = vi + .spyOn(process, "exit") + .mockImplementation(() => undefined as never); setPlatform("darwin"); process.env.NODE_ENV = "test"; - scheduleForceExit(); + scheduleForceExit(Promise.resolve(false)); + await settle(); expect(setTimeoutSpy).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); }); }); diff --git a/packages/cli/test/lib/telemetry-session.test.ts b/packages/cli/test/lib/telemetry-session.test.ts index 536d7dd1d..8ce86f38a 100644 --- a/packages/cli/test/lib/telemetry-session.test.ts +++ b/packages/cli/test/lib/telemetry-session.test.ts @@ -16,6 +16,8 @@ import * as Sentry from "@sentry/node"; import { afterEach, describe, expect, test, vi } from "vitest"; import { createBeforeExitHandler, + EXIT_FLUSH_TIMEOUT_MS, + flushClientOnExit, markSessionCrashed, } from "../../src/lib/telemetry.js"; @@ -130,13 +132,52 @@ describe("createBeforeExitHandler", () => { handler(); - expect(flushSpy).toHaveBeenCalledWith(3000); + expect(flushSpy).toHaveBeenCalledWith(EXIT_FLUSH_TIMEOUT_MS); getIsolationScopeSpy.mockRestore(); flushSpy.mockRestore(); }); }); +describe("flushClientOnExit", () => { + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + function mockNoSession(): void { + vi.spyOn(Sentry, "getIsolationScope").mockReturnValue({ + getSession: () => null, + } as unknown as Sentry.Scope); + } + + test("shares one flush with the beforeExit handler", async () => { + mockNoSession(); + const flush = vi.fn(() => Promise.resolve(true)); + const client = { flush } as unknown as Sentry.NodeClient; + + const first = flushClientOnExit(client); + createBeforeExitHandler(client)(); + + expect(flushClientOnExit(client)).toBe(first); + expect(flush).toHaveBeenCalledOnce(); + expect(await first).toBe(true); + }); + + test("resolves false when the flush does not settle in time", async () => { + vi.useFakeTimers(); + mockNoSession(); + const client = { + flush: () => new Promise(() => undefined), + } as unknown as Sentry.NodeClient; + + const flush = flushClientOnExit(client); + await vi.advanceTimersByTimeAsync(EXIT_FLUSH_TIMEOUT_MS); + + expect(await flush).toBe(false); + }); +}); + describe("markSessionCrashed", () => { let getCurrentScopeSpy: ReturnType; let getIsolationScopeSpy: ReturnType;