Files
2026-07-08 16:15:37 +02:00

172 lines
6.0 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import {
initializeTracing,
shutdownTracing,
type NodeSdkInstance,
type NodeSdkLikeModule,
type OtlpExporterLikeModule,
} from "./tracing.js";
const ENDPOINT_ENV = "OTEL_EXPORTER_OTLP_ENDPOINT";
/**
* `initializeTracing` keeps a module-level `activeState`. None of the tests in
* this file successfully start the SDK (every path fails to load deps or throws
* during construction), so the global stays clean; the afterEach shutdown is a
* belt-and-braces guard.
*/
describe("initializeTracing dynamic-import fallback", () => {
afterEach(async () => {
await shutdownTracing();
vi.restoreAllMocks();
});
it("uses the real OpenTelemetry loaders and stays disabled when the packages are absent", async () => {
// No loadSdk / loadOtlpExporter overrides => production loaders run. The
// @opentelemetry/* packages are not installed here, so both resolve to
// undefined and the helper degrades to a warning-only no-op.
const warn = vi.fn();
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
onMissingDependency: warn,
});
expect(warn).toHaveBeenCalledWith(
expect.stringContaining("@opentelemetry/sdk-node or @opentelemetry/exporter-trace-otlp-http is not installed")
);
});
it("routes the missing-dependency warning through the default console.warn logger", async () => {
const original = process.env[ENDPOINT_ENV];
delete process.env[ENDPOINT_ENV];
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
try {
// No onMissingDependency and no endpoint => default logger + endpoint warning.
await initializeTracing({ serviceName: "api" });
} finally {
if (original !== undefined) {
process.env[ENDPOINT_ENV] = original;
}
}
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining(ENDPOINT_ENV));
});
});
describe("initializeTracing endpoint resolution from the environment", () => {
afterEach(async () => {
await shutdownTracing();
vi.restoreAllMocks();
});
it("reads and trims the OTLP endpoint from the environment when no option is given", async () => {
const original = process.env[ENDPOINT_ENV];
process.env[ENDPOINT_ENV] = " http://env-endpoint:4318/v1/traces ";
const warn = vi.fn();
try {
await initializeTracing({
serviceName: "api",
// otlpEndpoint omitted on purpose => readEnv must supply the trimmed value.
loadSdk: async () => undefined,
loadOtlpExporter: async () => undefined,
onMissingDependency: warn,
});
} finally {
if (original === undefined) {
delete process.env[ENDPOINT_ENV];
} else {
process.env[ENDPOINT_ENV] = original;
}
}
// Reaching the "not installed" branch proves readEnv returned a usable value
// rather than short-circuiting on a missing endpoint.
expect(warn).toHaveBeenCalledWith(expect.stringContaining("is not installed"));
expect(warn).not.toHaveBeenCalledWith(expect.stringContaining("is not set"));
});
it("treats a whitespace-only endpoint env var as unset", async () => {
const original = process.env[ENDPOINT_ENV];
process.env[ENDPOINT_ENV] = " ";
const warn = vi.fn();
try {
await initializeTracing({ serviceName: "api", onMissingDependency: warn });
} finally {
if (original === undefined) {
delete process.env[ENDPOINT_ENV];
} else {
process.env[ENDPOINT_ENV] = original;
}
}
expect(warn).toHaveBeenCalledWith(expect.stringContaining("OTEL_EXPORTER_OTLP_ENDPOINT is not set"));
});
});
describe("initializeTracing startup failure descriptions", () => {
afterEach(async () => {
await shutdownTracing();
vi.restoreAllMocks();
});
it("stringifies non-Error startup failures via describeCause", async () => {
const warn = vi.fn();
const OTLPTraceExporter = vi.fn().mockImplementation(() => ({}));
const NodeSDK = vi.fn().mockImplementation(() => {
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw "constructor-blew-up";
});
const sdkModule: NodeSdkLikeModule = { NodeSDK: NodeSDK as unknown as NodeSdkLikeModule["NodeSDK"] };
const exporterModule: OtlpExporterLikeModule = {
OTLPTraceExporter: OTLPTraceExporter as unknown as OtlpExporterLikeModule["OTLPTraceExporter"],
};
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => sdkModule,
loadOtlpExporter: async () => exporterModule,
onMissingDependency: warn,
});
expect(warn).toHaveBeenCalledWith(
expect.stringContaining("failed to start OpenTelemetry NodeSDK (constructor-blew-up)")
);
});
it("does not retain active state after a failed startup (shutdown is a no-op)", async () => {
const warn = vi.fn();
const shutdown = vi.fn(async () => undefined);
const start = vi.fn(async () => {
throw new Error("start rejected");
});
const sdkInstance: NodeSdkInstance = { start, shutdown };
const NodeSDK = vi.fn().mockImplementation(() => sdkInstance);
const OTLPTraceExporter = vi.fn().mockImplementation(() => ({}));
const sdkModule: NodeSdkLikeModule = { NodeSDK: NodeSDK as unknown as NodeSdkLikeModule["NodeSDK"] };
const exporterModule: OtlpExporterLikeModule = {
OTLPTraceExporter: OTLPTraceExporter as unknown as OtlpExporterLikeModule["OTLPTraceExporter"],
};
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => sdkModule,
loadOtlpExporter: async () => exporterModule,
onMissingDependency: warn,
});
expect(warn).toHaveBeenCalledWith(expect.stringContaining("failed to start OpenTelemetry NodeSDK (start rejected)"));
// No active state => shutdown must not touch the SDK instance.
await shutdownTracing();
expect(shutdown).not.toHaveBeenCalled();
});
});