diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d0c3de0c..1c58ade12 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,10 +30,12 @@ jobs: worker: - 'apps/worker/**' - 'packages/db/**' + - 'packages/cairn-telemetry/**' - '.github/workflows/ci.yml' server: - 'apps/server/**' - 'packages/db/**' + - 'packages/cairn-telemetry/**' - '.github/workflows/ci.yml' dashboard: - 'apps/dashboard/**' @@ -211,6 +213,8 @@ jobs: bun-version: 1.3.14 - run: npm --prefix ../../packages/db ci --include=dev - run: npm --prefix ../../packages/db run build + - run: npm --prefix ../../packages/cairn-telemetry ci --include=dev + - run: npm --prefix ../../packages/cairn-telemetry run build - run: bun install --frozen-lockfile --ignore-scripts - run: bun run typecheck - name: Test worker against disposable PostgreSQL diff --git a/AGENTS.md b/AGENTS.md index 6e7e74cc5..1c21edd78 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,3 +62,11 @@ The aggregate script assumes app dependencies are already installed and intentio - Collection Android and web have tracked pre-existing issues. - Dashboard analysis has one baseline informational failure and little test coverage. - Website check and formatting commands fail at the migration baseline; production build needs private environment configuration. + +## Cairn integration + +The user authorized a separate PR to add the merged Cairn server SDK to Lovat. Scope is Server, Worker, and their shared source package/build contracts. CAIRN_ENABLED defaults false; do not configure live credentials, mutate Railway, or merge this PR without a further instruction. The earlier no-Lovat-changes restriction is superseded only for this reviewed integration PR. Preserve unrelated dirty training checkouts; this task uses an isolated checkout from current main. + +packages/cairn-telemetry contains an exact source snapshot from Cairn commit fd029d1c90b100fd31313e902b065effeaac8712. UPSTREAM.json records provenance/checksums. It follows the existing independent app/local file dependency model, without a root workspace. SDK/build changes must trigger Server and Worker CI, and both Dockerfiles must copy/build this package. No credentials, databases, scouting payloads, tarballs, or generated output may be tracked. + +Integration verification: Server build, application/test typechecks, and 1,377 unit tests pass under Node 22.20.0; per-file unit coverage remains 100% for lines/statements/functions/branches. Lint has zero errors and 80 existing warnings. Worker typecheck and 40 behavior tests pass; 21 database integration tests are skipped locally because no disposable Lovat services were enabled. CI retains its guarded PostgreSQL/Redis integration and Docker checks. Source checksums verify the seven upstream SDK files. New telemetry and shutdown behavior are explicitly tested; no production exporter is enabled. Accurate recurring worker summaries require the linked Cairn follow-up PR #2. diff --git a/README.md b/README.md index 567f804b1..ab341dfca 100644 --- a/README.md +++ b/README.md @@ -100,3 +100,9 @@ and the [complete commit archive](docs/history/README.md) for all retained main and tagged application history, beginning in December 2022. This repository combines formerly separate repositories, including `MangoSwirl/lovat-learn` (see [Learn import](docs/migration/learn-import.md)). Default-branch histories and namespaced release tags are retained. Original-to-rewritten maps and migration evidence are in [`docs/migration`](docs/migration); the source repositories remain the record for old pull requests and feature branches. + +## Optional Cairn observability + +Server and Worker have opt-in Cairn metadata reporting, disabled until their own scoped credentials and collector origin are configured. See [Server setup](apps/server/README.md#optional-cairn-telemetry), [Worker setup](apps/worker/README.md#optional-cairn-reporting), and the [pinned SDK source package](packages/cairn-telemetry/README.md). The API reports template/status/timing metadata; the worker reports lease-fenced import attempts and health requests. Scouting data, identities, provider bodies, and secrets are excluded. No database migration or live Railway configuration is part of this code integration. + +Integration verification: Server build, application/test typechecks, and 1,377 unit tests pass under Node 22.20.0; per-file unit coverage remains 100% for lines/statements/functions/branches. Lint has zero errors and 80 existing warnings. Worker typecheck and 40 behavior tests pass; 21 database integration tests are skipped locally because no disposable Lovat services were enabled. CI retains its guarded PostgreSQL/Redis integration and Docker checks. Source checksums verify the seven upstream SDK files. New telemetry and shutdown behavior are explicitly tested; no production exporter is enabled. Accurate recurring worker summaries require the linked Cairn follow-up PR #2. diff --git a/apps/server/.env.example b/apps/server/.env.example index 961d30baa..431f6756a 100644 --- a/apps/server/.env.example +++ b/apps/server/.env.example @@ -39,3 +39,10 @@ SLACK_APP_ID= # Key for Posthog, used for error reporting and analytics POSTHOG_PROJECT_API_KEY= + +# Optional Cairn server telemetry. Disabled unless explicitly true. +# Production requires an HTTPS origin and a service/environment-scoped ingestion token. +CAIRN_ENABLED=false +CAIRN_URL= +CAIRN_INGESTION_TOKEN= +CAIRN_ENVIRONMENT=production diff --git a/apps/server/AGENTS.md b/apps/server/AGENTS.md index fcdee6dc1..ea6e79ac2 100644 --- a/apps/server/AGENTS.md +++ b/apps/server/AGENTS.md @@ -16,3 +16,9 @@ - Use braces for every control-flow block, including single-statement guards; avoid compressed one-line conditions and statements. - Group related fields together and separate distinct groups with blank lines when it improves readability. Avoid blank lines between every statement or field. - Run Prettier from `apps/server` on edited files so formatting follows the Server's resolved configuration. + +## Cairn metadata export + +Cairn is opt-in through CAIRN_ENABLED=true and validated endpoint/token/environment settings. Do not enable it or add real credentials in tests, deployment settings, or examples. Its Express adapter must never inspect bodies, arbitrary URLs/query strings, auth headers, tenant identities, or scouting notes. Route mount prefixes are explicit static constants; unknown mounts use /**unmatched**. No DB/Redis lookups may be introduced for telemetry. Keep collector work off the response's awaited path. x-cairn-request-id is generated only while enabled. + +The private SDK is a source snapshot under packages/cairn-telemetry, pinned and hashed in UPSTREAM.json; update it from reviewed Cairn source rather than hand editing it. Built output is ignored. Preserve npm for Server and Bun for Worker; no root workspace or cross-app source import. The Server's postinstall/prebuild prepare the shared package. Shutdown handlers register only when enabled and have a hard five-second process budget. Verify disabled/invalid config, template privacy, collector outage behavior, and shutdown with tests. diff --git a/apps/server/Dockerfile b/apps/server/Dockerfile index 6b226db40..26fe740d1 100644 --- a/apps/server/Dockerfile +++ b/apps/server/Dockerfile @@ -3,6 +3,7 @@ FROM node:22.20.0-bookworm-slim RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates && rm -rf /var/lib/apt/lists/* WORKDIR /app COPY packages/db ./packages/db +COPY packages/cairn-telemetry ./packages/cairn-telemetry COPY apps/server ./apps/server WORKDIR /app/apps/server RUN npm ci --include=dev && npm run build diff --git a/apps/server/README.md b/apps/server/README.md index 65a17a4fe..3686b885a 100644 --- a/apps/server/README.md +++ b/apps/server/README.md @@ -195,3 +195,13 @@ imports the schedule twice to check keys, scheduling markers, and duplicates. It refuses an event already present in the test database and removes only its own temporary tournament and match rows. This optional check needs live Nexus availability and is not part of the offline unit suite. + +## Optional Cairn telemetry + +Cairn request reporting is disabled by default. Set `CAIRN_ENABLED=true`, an HTTPS origin in `CAIRN_URL`, a dedicated ingestion token scoped to `lovat-api` and the selected environment, and `CAIRN_ENVIRONMENT` to enable it. `CAIRN_URL` must have no path, query, embedded credentials, or fragment. Plain HTTP is allowed only for loopback development. Invalid/incomplete settings produce a generic warning and leave request serving enabled. Never put a token in source or PR text. + +The Express adapter runs before parsers/routes and queues method, status, duration, a generated `x-cairn-request-id`, deployment/version, and registered route templates. It does not read request/response bodies, query strings, cookies, auth headers, team identities, or scouting notes. Known static router mounts are allowlisted; unmatched or unfamiliar mounts become `/__unmatched__` rather than exposing raw paths. Add new static prefixes to that list when introducing a new router. No extra SQL/Redis lookups are performed. Existing PostHog instrumentation is unchanged. + +Exports use the reviewed [local SDK source snapshot](../../packages/cairn-telemetry/README.md). Server `npm ci` and prebuild prepare its compiled output. Request handling does not await collector traffic. Queue/retry work uses the same process CPU and can drop events during outages. With reporting enabled, SIGINT/SIGTERM stops accepting HTTP work, allows up to five seconds for active connections, and gives SDK draining a one-second budget; stalled connections are then forcibly closed. With reporting disabled, no SDK timer, outgoing telemetry, new diagnostic header, or shutdown handler is enabled. + +This PR provides code and environment placeholders only. It does not configure Railway, create ingestion credentials, change authentication/report payloads, or enable production export. Validate a staging rollout against a reachable Cairn deployment before enabling production. diff --git a/apps/server/package-lock.json b/apps/server/package-lock.json index 60b465490..173dd1322 100644 --- a/apps/server/package-lock.json +++ b/apps/server/package-lock.json @@ -11,6 +11,7 @@ "license": "ISC", "dependencies": { "@asteasolutions/zod-to-openapi": "^9.1.0", + "@cairn/telemetry": "file:../../packages/cairn-telemetry", "@lovat/db": "file:../../packages/db", "@slack/web-api": "^8.1.1", "axios": "^1.20.0", @@ -63,6 +64,21 @@ "node": "22.20.0" } }, + "../../packages/cairn-telemetry": { + "name": "@cairn/telemetry", + "version": "0.1.0", + "dependencies": { + "hono": "4.13.16", + "zod": "4.6.7" + }, + "devDependencies": { + "@types/node": "22.20.0", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=22" + } + }, "../../packages/db": { "name": "@lovat/db", "version": "0.0.0", @@ -203,6 +219,10 @@ "keyv": "^5.6.0" } }, + "node_modules/@cairn/telemetry": { + "resolved": "../../packages/cairn-telemetry", + "link": true + }, "node_modules/@cspotcode/source-map-support": { "version": "0.8.1", "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", diff --git a/apps/server/package.json b/apps/server/package.json index 81aebffd4..568841b6e 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -18,8 +18,8 @@ "lint": "eslint .", "format": "prettier --write .", "format:check": "prettier --check .", - "postinstall": "npm --prefix ../../packages/db ci --include=dev && npm --prefix ../../packages/db run build", - "prebuild": "npm --prefix ../../packages/db run build", + "postinstall": "npm --prefix ../../packages/cairn-telemetry ci --include=dev && npm --prefix ../../packages/cairn-telemetry run build && npm --prefix ../../packages/db ci --include=dev && npm --prefix ../../packages/db run build", + "prebuild": "npm --prefix ../../packages/cairn-telemetry run build && npm --prefix ../../packages/db run build", "db:seed": "tsx src/seed.ts", "test:coverage:unit": "vitest run --coverage", "test:report:preview": "vite preview --outDir test-report --host 127.0.0.1" @@ -48,7 +48,8 @@ "swagger-ui-express": "^5.0.1", "ts-node": "^10.9.2", "ws": "^8.22.0", - "zod": "^4.6.5" + "zod": "^4.6.5", + "@cairn/telemetry": "file:../../packages/cairn-telemetry" }, "devDependencies": { "@eslint/js": "^10.0.1", diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 33559837a..7537c9d6a 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -6,6 +6,7 @@ import rateLimit from "express-rate-limit"; import "./loadEnv.js"; import { setupExpressErrorHandler } from "posthog-node"; +import { cairn } from "./lib/cairn.js"; import { posthog } from "./posthogClient.js"; import posthogReporter from "./lib/middleware/posthogMiddleware.js"; @@ -17,6 +18,7 @@ import { getVersion } from "./handler/manager/version.js"; export const app = express(); setupExpressErrorHandler(posthog, app); +app.use(cairn.middleware); app.set("trust proxy", 1); // Compress responses for clients that advertise support (Accept-Encoding: gzip) diff --git a/apps/server/src/lib/cairn.ts b/apps/server/src/lib/cairn.ts new file mode 100644 index 000000000..fc9b439d9 --- /dev/null +++ b/apps/server/src/lib/cairn.ts @@ -0,0 +1,138 @@ +import type { RequestHandler } from "express"; +import { createTelemetry, type TelemetryOptions } from "@cairn/telemetry"; + +const methods = new Set([ + "GET", + "POST", + "PUT", + "PATCH", + "DELETE", + "HEAD", + "OPTIONS", +]); +const prefixes = new Set([ + "", + "/v1", + "/v1/analysis", + "/v1/slack", + "/v1/doc", + "/collection", + "/v2/collection", + "/v1/manager", + ...[ + "onboarding", + "picklists", + "mutablepicklists", + "registeredteams", + "scoutershifts", + "tournament", + "scoutreports", + "settings", + "apikey", + ].map((path) => `/v1/manager/${path}`), +]); + +export type CairnReporter = { + enabled: boolean; + middleware: RequestHandler; + flush: () => Promise; + shutdown: (timeoutMs?: number) => Promise; +}; + +export function createCairnReporter( + env: NodeJS.ProcessEnv = process.env, + fetcher?: TelemetryOptions["fetch"], +): CairnReporter { + let exporter: ReturnType | undefined; + + if (env.CAIRN_ENABLED === "true") { + try { + const endpoint = new URL(env.CAIRN_URL ?? ""); + const environment = + env.CAIRN_ENVIRONMENT ?? env.NODE_ENV ?? "development"; + const local = + env.NODE_ENV !== "production" && + ["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname); + + if ( + (endpoint.protocol !== "https:" && + !(local && endpoint.protocol === "http:")) || + endpoint.username || + endpoint.password || + endpoint.search || + endpoint.hash || + endpoint.pathname !== "/" || + !env.CAIRN_INGESTION_TOKEN?.trim() || + !/^[a-zA-Z0-9_.:-]{1,120}$/.test(environment) + ) { + throw new Error("Invalid Cairn configuration"); + } + + exporter = createTelemetry({ + endpoint: endpoint.origin, + token: env.CAIRN_INGESTION_TOKEN, + service: "lovat-api", + environment, + deploymentId: env.RAILWAY_DEPLOYMENT_ID, + appVersion: env.npm_package_version, + fetch: fetcher, + }); + } catch { + console.warn( + "Cairn telemetry disabled: check CAIRN_URL, environment, and ingestion credential.", + ); + } + } + + const middleware: RequestHandler = (req, res, next) => { + if (!exporter || !methods.has(req.method)) { + next(); + return; + } + + const id = crypto.randomUUID(); + const receivedAt = new Date().toISOString(); + const started = performance.now(); + res.setHeader("x-cairn-request-id", id); + + res.once("finish", () => { + const template: unknown = req.route?.path; + const route = + typeof template === "string" && + template.startsWith("/") && + !/[?#]/.test(template) && + prefixes.has(req.baseUrl) && + req.baseUrl.length + template.length <= 500 + ? `${req.baseUrl}${template}` + : "/__unmatched__"; + + exporter.record({ + id, + requestId: id, + receivedAt, + completedAt: new Date().toISOString(), + durationMs: performance.now() - started, + service: "lovat-api", + environment: env.CAIRN_ENVIRONMENT ?? env.NODE_ENV ?? "development", + deploymentId: env.RAILWAY_DEPLOYMENT_ID, + appVersion: env.npm_package_version, + method: req.method as + "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS", + route, + statusCode: res.statusCode, + }); + }); + + next(); + }; + + return { + enabled: Boolean(exporter), + middleware, + flush: () => exporter?.flush() ?? Promise.resolve(), + shutdown: (timeoutMs = 1000) => + exporter?.shutdown({ timeoutMs }) ?? Promise.resolve(), + }; +} + +export const cairn = createCairnReporter(); diff --git a/apps/server/src/lib/cairnShutdown.ts b/apps/server/src/lib/cairnShutdown.ts new file mode 100644 index 000000000..925aeede0 --- /dev/null +++ b/apps/server/src/lib/cairnShutdown.ts @@ -0,0 +1,39 @@ +import type { Server } from "node:http"; + +// Register only when collection is enabled; the default process behavior is unchanged. +export function installCairnShutdown( + server: Server, + reporter: { + enabled: boolean; + shutdown: (timeoutMs?: number) => Promise; + }, + runtime = process, +): void { + if (!reporter.enabled) { + return; + } + + let stopping = false; + const stop = () => { + if (stopping) { + return; + } + stopping = true; + + const deadline = setTimeout(() => { + server.closeAllConnections(); + runtime.exit(0); + }, 5000); + + server.close(() => { + const finish = () => { + clearTimeout(deadline); + runtime.exit(0); + }; + void reporter.shutdown(1000).then(finish, finish); + }); + }; + + runtime.once("SIGTERM", stop); + runtime.once("SIGINT", stop); +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 57521d830..859ac111a 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -5,6 +5,9 @@ import { clearCache } from "./lib/clearCache.js"; import { attachTrainingSockets } from "./handler/training/trainingSockets.js"; +import { cairn } from "./lib/cairn.js"; +import { installCairnShutdown } from "./lib/cairnShutdown.js"; + const port = process.env.PORT || 3000; await ensureBuiltInTrainingExercise(); @@ -16,3 +19,5 @@ const server = app.listen(port, () => { }); attachTrainingSockets(server); + +installCairnShutdown(server, cairn); diff --git a/apps/server/test/cairn.unit.test.ts b/apps/server/test/cairn.unit.test.ts new file mode 100644 index 000000000..16de96496 --- /dev/null +++ b/apps/server/test/cairn.unit.test.ts @@ -0,0 +1,186 @@ +import express, { Router } from "express"; +import request from "supertest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { EventEmitter } from "node:events"; +import type { Server } from "node:http"; +import { createCairnReporter } from "../src/lib/cairn.js"; +import { installCairnShutdown } from "../src/lib/cairnShutdown.js"; +const env = { + CAIRN_ENABLED: "true", + CAIRN_URL: "https://cairn.example", + CAIRN_INGESTION_TOKEN: "fake-test-ingestion", + NODE_ENV: "production", + RAILWAY_DEPLOYMENT_ID: "release-test", + npm_package_version: "26.0.0", +}; +afterEach(() => vi.restoreAllMocks()); +describe("Cairn request reporting", () => { + it("is inert by default", async () => { + const send = vi.fn(); + const sdk = createCairnReporter({}, send); + const app = express(); + app.use(sdk.middleware); + app.get("/", (_req, res) => res.send("ok")); + const response = await request(app).get("/"); + expect(response.headers["x-cairn-request-id"]).toBeUndefined(); + await sdk.flush(); + await sdk.shutdown(); + expect(send).not.toHaveBeenCalled(); + }); + it.each([ + { CAIRN_URL: undefined }, + { CAIRN_URL: "invalid" }, + { CAIRN_URL: "http://cairn.example" }, + { CAIRN_URL: "https://user:password@cairn.example" }, + { CAIRN_URL: "https://cairn.example/path" }, + { CAIRN_URL: "https://cairn.example?secret=private" }, + { CAIRN_URL: "https://cairn.example#private" }, + { CAIRN_INGESTION_TOKEN: "" }, + { CAIRN_ENVIRONMENT: "invalid environment" }, + { CAIRN_URL: "ftp://localhost", NODE_ENV: "development" }, + ])("fails open for invalid settings %j", (overrides) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + expect(createCairnReporter({ ...env, ...overrides }).enabled).toBe(false); + expect(warn).toHaveBeenCalledWith(expect.not.stringContaining("password@")); + }); + it("exports templates and status without private request/response content", async () => { + const events: unknown[] = []; + const sdk = createCairnReporter( + { ...env, CAIRN_ENVIRONMENT: "staging" }, + async (url, init) => { + if (url.endsWith("/requests")) { + events.push(...JSON.parse(String(init?.body))); + } + return new Response("{}"); + }, + ); + const app = express(); + app.use(sdk.middleware); + app.use(express.json()); + const router = Router(); + router.post("/teams/:team", (_req, res) => + res.status(503).json({ note: "PRIVATE-NOTES" }), + ); + app.use("/v1/manager", router); + const response = await request(app) + .post("/v1/manager/teams/8033?token=PRIVATE-QUERY") + .set("authorization", "Bearer PRIVATE-TOKEN") + .send({ note: "PRIVATE-NOTES" }); + expect(response.status).toBe(503); + expect(response.headers["x-cairn-request-id"]).toBeTruthy(); + await sdk.flush(); + await request(app).get("/PRIVATE-PATH"); + await sdk.shutdown(); + expect(events).toHaveLength(2); + expect(events[0]).toMatchObject({ + route: "/v1/manager/teams/:team", + environment: "staging", + service: "lovat-api", + statusCode: 503, + }); + expect(events[1]).toMatchObject({ route: "/__unmatched__" }); + expect(JSON.stringify(events)).not.toContain("PRIVATE-"); + }); + it("allows loopback in development and keeps collector outages off the response path", async () => { + const sdk = createCairnReporter( + { ...env, NODE_ENV: "development", CAIRN_URL: "http://127.0.0.1:3000" }, + async () => { + throw new Error("offline"); + }, + ); + const app = express(); + app.use(sdk.middleware); + app.get("/status", (_req, res) => res.json({ ok: true })); + expect((await request(app).get("/status")).status).toBe(200); + await sdk.shutdown(0); + }); + it("hides unknown mount prefixes and skips unsupported methods", async () => { + const events: unknown[] = []; + const sdk = createCairnReporter( + { ...env, NODE_ENV: undefined }, + async (url, init) => { + if (url.endsWith("/requests")) { + events.push(...JSON.parse(String(init?.body))); + } + return new Response("{}"); + }, + ); + const app = express(); + app.use(sdk.middleware); + const router = Router(); + router.get("/data", (_req, res) => res.end()); + app.use("/private-tenant", router); + app.all("/", (_req, res) => res.end()); + await request(app).get("/private-tenant/data"); + await request(app).trace("/"); + await sdk.shutdown(); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + route: "/__unmatched__", + environment: "development", + }); + }); +}); +describe("Cairn shutdown", () => { + it("registers no handlers while disabled", () => { + const runtime = { once: vi.fn(), exit: vi.fn() }; + installCairnShutdown( + {} as Server, + { enabled: false, shutdown: vi.fn() }, + runtime as unknown as NodeJS.Process, + ); + expect(runtime.once).not.toHaveBeenCalled(); + }); + it.each([false, true])( + "drains once and exits after close (reject=%s)", + async (reject) => { + vi.useFakeTimers(); + try { + const runtime = Object.assign(new EventEmitter(), { exit: vi.fn() }); + let closed: () => void = () => undefined; + const server = { + close: vi.fn((cb: () => void) => { + closed = cb; + }), + closeAllConnections: vi.fn(), + }; + const shutdown = vi.fn(() => + reject ? Promise.reject(new Error("offline")) : Promise.resolve(), + ); + installCairnShutdown( + server as unknown as Server, + { enabled: true, shutdown }, + runtime as unknown as NodeJS.Process, + ); + runtime.emit("SIGTERM"); + runtime.emit("SIGINT"); + expect(server.close).toHaveBeenCalledTimes(1); + closed(); + await Promise.resolve(); + expect(shutdown).toHaveBeenCalledWith(1000); + expect(runtime.exit).toHaveBeenCalledWith(0); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } + }, + ); + it("forces stuck connections closed after five seconds", async () => { + vi.useFakeTimers(); + try { + const runtime = Object.assign(new EventEmitter(), { exit: vi.fn() }); + const server = { close: vi.fn(), closeAllConnections: vi.fn() }; + installCairnShutdown( + server as unknown as Server, + { enabled: true, shutdown: vi.fn() }, + runtime as unknown as NodeJS.Process, + ); + runtime.emit("SIGTERM"); + await vi.advanceTimersByTimeAsync(5000); + expect(server.closeAllConnections).toHaveBeenCalledTimes(1); + expect(runtime.exit).toHaveBeenCalledWith(0); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/apps/worker/.env.example b/apps/worker/.env.example index 7ce88949f..8ec347dfa 100644 --- a/apps/worker/.env.example +++ b/apps/worker/.env.example @@ -2,3 +2,9 @@ DATABASE_URL=postgresql://lovat_test:lovat_test@127.0.0.1:5432/lovat_test TBA_KEY= WORKER_CONCURRENCY=2 PORT=8080 + +# Optional Cairn metadata export; use a separate lovat-worker ingestion credential. +CAIRN_ENABLED=false +CAIRN_URL= +CAIRN_INGESTION_TOKEN= +CAIRN_ENVIRONMENT=production diff --git a/apps/worker/AGENTS.md b/apps/worker/AGENTS.md new file mode 100644 index 000000000..a6258e32d --- /dev/null +++ b/apps/worker/AGENTS.md @@ -0,0 +1,7 @@ +# Worker instructions + +Use Bun 1.3.14 and the existing worker lockfile. Database schema/client remains owned by packages/db. Run bun run typecheck and bun test. Live integration tests require the explicit LOVAT_DB_TEST=1 disposable lovat_test database guard; never run them against production. + +Cairn reporting is opt-in. Only job lifecycle metadata and health-route request metadata may leave the worker; never include target keys, lease tokens, provider bodies/errors, raw SQL, credentials, or scouting data. Success/failure observations follow the existing fenced scheduling write and cannot change job execution/retry state. Collector failures must be isolated. Preserve the current shutdown sequence and drain SDK queues after consumers finish. + +The private SDK's reviewed source snapshot lives in packages/cairn-telemetry and is pinned by UPSTREAM.json. Build it before Bun copies the local file dependency; Docker and CI must include this package. Do not commit generated output or publish packages. Use a separate service-scoped lovat-worker ingestion token; examples remain disabled with empty secrets. diff --git a/apps/worker/Dockerfile b/apps/worker/Dockerfile index 22b3abe21..ea7268483 100644 --- a/apps/worker/Dockerfile +++ b/apps/worker/Dockerfile @@ -7,6 +7,8 @@ COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun WORKDIR /app COPY packages/db ./packages/db +COPY packages/cairn-telemetry ./packages/cairn-telemetry +RUN npm --prefix packages/cairn-telemetry ci --include=dev && npm --prefix packages/cairn-telemetry run build RUN npm --prefix packages/db ci --include=dev && npm --prefix packages/db run build COPY apps/worker ./apps/worker diff --git a/apps/worker/README.md b/apps/worker/README.md index 852243ac7..cabf3f531 100644 --- a/apps/worker/README.md +++ b/apps/worker/README.md @@ -3,6 +3,10 @@ To install dependencies: ```bash +npm --prefix ../../packages/cairn-telemetry ci --include=dev +npm --prefix ../../packages/cairn-telemetry run build +npm --prefix ../../packages/db ci --include=dev +npm --prefix ../../packages/db run build bun install ``` @@ -285,3 +289,22 @@ data. A fresh empty response clears withdrawn data, while HTTP 304 preserves it. ### Historical seasons Run `bun run backfill 1992 2025` with the target database and TBA credentials configured to queue archived season imports. With no arguments, it queues every season from 1992 through the current year. Existing jobs keep their leases and retry schedules. Tournament and district imports queue event and district details through the existing scheduler, so the backfill continues on the worker. + +## Optional Cairn reporting + +The worker can report its health HTTP route and metadata-only import attempts to Cairn. It is off unless `CAIRN_ENABLED=true`, `CAIRN_URL` is a valid HTTPS origin (loopback HTTP is permitted in development), and `CAIRN_INGESTION_TOKEN` is set. Use a dedicated token scoped to `lovat-worker` and `CAIRN_ENVIRONMENT`; never reuse the API service's token. + +Events contain internal job ID, import kind, queue `imports`, attempt count, outcome, timestamps/duration, and deployment ID. They exclude target keys, lease tokens, provider response/error bodies, SQL, scouting reports, and credentials. A running attempt is observed after claim; success/failure is emitted only after the lease-fenced scheduling write succeeds. An attempt whose completion cannot be confirmed is reported as cancelled rather than successful. Observer exceptions cannot alter execution or retry/lease semantics. Existing scheduler retry counts reset after a successful recurring job; values outside the SDK's 1–100 attempt contract are rejected and counted as dropped by the SDK. + +The worker drains SDK queues with a one-second budget during its existing shutdown after consumers finish. Export queues are in-memory and best-effort. No additional database queries, stateful synthetic probes, or application-data capture are added. + +The SDK is a pinned source package, not a published npm release. Before a clean local `bun install`, run from the monorepo root: + +```sh +npm --prefix packages/cairn-telemetry ci --include=dev +npm --prefix packages/cairn-telemetry run build +npm --prefix packages/db ci --include=dev +npm --prefix packages/db run build +``` + +CI and Docker perform these builds before Bun copies local dependencies. Hono is aligned to SDK-compatible patch 4.13.16. No production destination or token is configured in this change. diff --git a/apps/worker/bun.lock b/apps/worker/bun.lock index 6f91422e2..4214248e5 100644 --- a/apps/worker/bun.lock +++ b/apps/worker/bun.lock @@ -5,8 +5,9 @@ "": { "name": "worker", "dependencies": { + "@cairn/telemetry": "file:../../packages/cairn-telemetry", "@lovat/db": "file:../../packages/db", - "hono": "^4.13.13", + "hono": "4.13.16", "zod": "4.6.5", }, "devDependencies": { @@ -18,6 +19,8 @@ }, }, "packages": { + "@cairn/telemetry": ["@cairn/telemetry@file:../../packages/cairn-telemetry", { "dependencies": { "hono": "4.13.16", "zod": "4.6.7" }, "devDependencies": { "@types/node": "22.20.0", "typescript": "5.9.3" } }], + "@electric-sql/pglite": ["@electric-sql/pglite@0.4.3", "", {}, "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ=="], "@electric-sql/pglite-socket": ["@electric-sql/pglite-socket@0.1.3", "", { "peerDependencies": { "@electric-sql/pglite": "0.4.3" }, "bin": { "pglite-server": "dist/scripts/server.js" } }, "sha512-LAciWM0M1dCL8hlsxu2venbVZcdxema0BtDfpWYVqr+Y468UADw0pFWidhKw1M8sfJ8rdLT71tjMmnirf/IZRQ=="], @@ -100,7 +103,7 @@ "@types/lodash": ["@types/lodash@4.17.26", "", {}, "sha512-48NWfiY6oNcKOh47Z4h+sIvwcQR91h6KPhaYKgeMIrkT2jV82Gy90SErj60vW8jQbeMSOSbhIv3bZ7JoqPPVhA=="], - "@types/node": ["@types/node@22.20.5", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA=="], + "@types/node": ["@types/node@22.20.0", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-QWlFW2wf3nTjC13/DqRnBpR4ZO36VJH/JVBkA/vcnmbTBNQIlnObqyqZE1tUR7+Ni23Lda8R1BxMfbXRpCUx5g=="], "@types/pg": ["@types/pg@8.23.1", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A=="], @@ -214,7 +217,7 @@ "graphmatch": ["graphmatch@1.1.1", "", {}, "sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg=="], - "hono": ["hono@4.13.13", "", {}, "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA=="], + "hono": ["hono@4.13.16", "", {}, "sha512-AOLOEhvrV+iH92xXCnFr/5+3KjPKcI3xP63XJtX5spAnkznPdHijlIsUTpi7/9EhWqrTCekw5c5zh1K+YsVw7A=="], "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], @@ -332,6 +335,10 @@ "zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], + "@cairn/telemetry/zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + + "@lovat/db/@types/node": ["@types/node@22.20.5", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA=="], + "@prisma/engines/@prisma/get-platform": ["@prisma/get-platform@7.10.0", "", { "dependencies": { "@prisma/debug": "7.10.0" } }, "sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w=="], "@prisma/fetch-engine/@prisma/get-platform": ["@prisma/get-platform@7.10.0", "", { "dependencies": { "@prisma/debug": "7.10.0" } }, "sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w=="], diff --git a/apps/worker/index.ts b/apps/worker/index.ts index da0a3a52a..152c6caed 100644 --- a/apps/worker/index.ts +++ b/apps/worker/index.ts @@ -1,3 +1,4 @@ +import { cairn } from "./src/telemetry"; import { db } from "./src/db"; import { tba } from "./src/tba"; import { runWorker } from "./src/worker"; @@ -13,6 +14,7 @@ let lastReconciledAt = 0; const port = healthPort(); const concurrency = Number(process.env.WORKER_CONCURRENCY ?? 2); const app = createHealthApp({ + middleware: cairn.requests?.middleware, isReady: () => !shutdown.signal.aborted && lastReconciledAt > 0 && @@ -41,5 +43,6 @@ try { process.removeListener("SIGINT", stop); process.removeListener("SIGTERM", stop); await server.stop(true); + await cairn.shutdown(); await db.$disconnect(); } diff --git a/apps/worker/package.json b/apps/worker/package.json index 788c91df2..9f8162a3b 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -7,7 +7,7 @@ "start": "bun run index.ts", "enqueue": "bun run src/enqueue.ts", "backfill": "bun run src/backfill.ts", - "postinstall": "npm --prefix ../../packages/db ci --include=dev && npm --prefix ../../packages/db run build", + "postinstall": "npm --prefix ../../packages/cairn-telemetry ci --include=dev && npm --prefix ../../packages/cairn-telemetry run build && npm --prefix ../../packages/db ci --include=dev && npm --prefix ../../packages/db run build", "test": "bun test", "typecheck": "tsc --noEmit" }, @@ -19,7 +19,8 @@ }, "dependencies": { "@lovat/db": "file:../../packages/db", - "hono": "^4.13.13", - "zod": "4.6.5" + "hono": "4.13.16", + "zod": "4.6.5", + "@cairn/telemetry": "file:../../packages/cairn-telemetry" } } diff --git a/apps/worker/src/scheduler.ts b/apps/worker/src/scheduler.ts index edbcd0e12..8efccbdd4 100644 --- a/apps/worker/src/scheduler.ts +++ b/apps/worker/src/scheduler.ts @@ -1,3 +1,8 @@ +import { + recordImportAttempt, + type AttemptObserver, + type AttemptOutcome, +} from "./telemetry"; import type { ImportJob, PrismaClient } from "@lovat/db"; import { importAllTeams } from "./jobs/teams"; import { importTournaments } from "./jobs/tournaments"; @@ -230,11 +235,23 @@ export function retryDelay(attempts: number, error: unknown, now = new Date()) { export async function runNextJob( db: PrismaClient, execute: (job: ImportJob, db: PrismaClient) => Promise = executeImport, + observer: AttemptObserver = recordImportAttempt, ) { const job = await claimJob(db); if (!job) return false; + const startedAt = new Date().toISOString(); + let terminal = false; + const observe = (outcome: AttemptOutcome) => { + try { + observer(job, outcome, startedAt); + } catch { + // Telemetry must never change job execution or lease handling. + } + }; + observe("running"); + let renewing = false; let lostLease = false; @@ -284,6 +301,8 @@ export async function runNextJob( }, }); if (completed.count === 1) { + observe("success"); + terminal = true; console.info( `Import completed: ${job.kind} ${job.targetKey}; next refresh ${new Date(now.getTime() + interval).toISOString()}`, ); @@ -300,7 +319,7 @@ export async function runNextJob( : "Unknown import error"; if (!lostLease) { - await db.importJob.updateMany({ + const failed = await db.importJob.updateMany({ where: { id: job.id, leaseToken: job.leaseToken, @@ -314,11 +333,18 @@ export async function runNextJob( leaseExpiresAt: null, }, }); + if (failed.count === 1) { + observe("failed"); + terminal = true; + } } console.error(`Import failed: ${job.kind} ${job.targetKey} (${lastError})`); } finally { clearInterval(heartbeat); + if (!terminal) { + observe("cancelled"); + } } return true; diff --git a/apps/worker/src/server.ts b/apps/worker/src/server.ts index 461ed667e..9f3359076 100644 --- a/apps/worker/src/server.ts +++ b/apps/worker/src/server.ts @@ -1,13 +1,18 @@ -import { Hono } from "hono"; +import { Hono, type MiddlewareHandler } from "hono"; export function createHealthApp({ isReady, checkDatabase, + middleware, }: { + middleware?: MiddlewareHandler; isReady: () => boolean; checkDatabase: () => Promise; }) { const app = new Hono(); + if (middleware) { + app.use("*", middleware); + } app.get("/health", async (c) => { if (!isReady()) return c.json({ status: "unavailable" }, 503); diff --git a/apps/worker/src/telemetry.ts b/apps/worker/src/telemetry.ts new file mode 100644 index 000000000..98351921a --- /dev/null +++ b/apps/worker/src/telemetry.ts @@ -0,0 +1,86 @@ +import { + createDiagnostics, + createTelemetry, + type TelemetryOptions, +} from "@cairn/telemetry"; +import type { ImportJob } from "@lovat/db"; + +export type AttemptOutcome = "running" | "success" | "failed" | "cancelled"; +export type AttemptObserver = ( + job: ImportJob, + outcome: AttemptOutcome, + startedAt: string, +) => void; + +export function createWorkerTelemetry( + env: Record = process.env, + fetcher?: TelemetryOptions["fetch"], +) { + let requests: ReturnType | undefined; + let diagnostics: ReturnType | undefined; + if (env.CAIRN_ENABLED === "true") { + try { + const url = new URL(env.CAIRN_URL ?? ""); + const environment = + env.CAIRN_ENVIRONMENT ?? env.NODE_ENV ?? "development"; + const local = + env.NODE_ENV !== "production" && + ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + if ( + (url.protocol !== "https:" && !(local && url.protocol === "http:")) || + url.username || + url.password || + url.search || + url.hash || + url.pathname !== "/" || + !env.CAIRN_INGESTION_TOKEN?.trim() || + !/^[a-zA-Z0-9_.:-]{1,120}$/.test(environment) + ) { + throw new Error("Invalid Cairn configuration"); + } + const options = { + endpoint: url.origin, + token: env.CAIRN_INGESTION_TOKEN, + service: "lovat-worker", + environment, + deploymentId: env.RAILWAY_DEPLOYMENT_ID, + fetch: fetcher, + }; + requests = createTelemetry(options); + diagnostics = createDiagnostics(options); + } catch { + console.warn( + "Cairn worker telemetry disabled: check endpoint, environment, and ingestion credential.", + ); + } + } + const record: AttemptObserver = (job, outcome, startedAt) => { + if (!diagnostics) { + return; + } + diagnostics.record("jobs", { + jobId: job.id, + kind: job.kind, + queue: "imports", + attempt: job.attempts + 1, + outcome, + startedAt, + completedAt: outcome === "running" ? undefined : new Date().toISOString(), + durationMs: + outcome === "running" ? undefined : Date.now() - Date.parse(startedAt), + deploymentId: env.RAILWAY_DEPLOYMENT_ID, + }); + }; + return { + requests, + record, + async shutdown() { + await Promise.all([ + requests?.shutdown({ timeoutMs: 1000 }), + diagnostics?.shutdown({ timeoutMs: 1000 }), + ]); + }, + }; +} +export const cairn = createWorkerTelemetry(); +export const recordImportAttempt = cairn.record; diff --git a/apps/worker/test/telemetry.test.ts b/apps/worker/test/telemetry.test.ts new file mode 100644 index 000000000..a86ffa8b5 --- /dev/null +++ b/apps/worker/test/telemetry.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, test, mock } from "bun:test"; +import type { ImportJob, PrismaClient } from "@lovat/db"; +import { createWorkerTelemetry } from "../src/telemetry"; +import { runNextJob } from "../src/scheduler"; +import { createHealthApp } from "../src/server"; +const job = { + id: "job-123", + kind: "teams", + targetKey: "PRIVATE-TARGET", + attempts: 2, + leaseToken: "PRIVATE-LEASE", + leaseExpiresAt: new Date(Date.now() + 600000), +} as ImportJob; +const env = { + CAIRN_ENABLED: "true", + CAIRN_URL: "https://cairn.example", + CAIRN_INGESTION_TOKEN: "test-only", + NODE_ENV: "production", +}; +describe("worker Cairn telemetry", () => { + test("is disabled by default", async () => { + const sdk = createWorkerTelemetry({}); + expect(sdk.requests).toBeUndefined(); + sdk.record(job, "success", new Date().toISOString()); + await sdk.shutdown(); + }); + test("exports metadata without job targets, lease tokens, or provider bodies", async () => { + const sent: unknown[] = []; + const sdk = createWorkerTelemetry(env, async (url, init) => { + if (!url.endsWith("/health")) { + sent.push({ url, events: JSON.parse(String(init?.body)) }); + } + return new Response("{}"); + }); + const app = createHealthApp({ + isReady: () => true, + checkDatabase: async () => {}, + middleware: sdk.requests?.middleware, + }); + expect((await app.request("http://local/health")).status).toBe(200); + sdk.record(job, "running", new Date().toISOString()); + sdk.record(job, "failed", new Date().toISOString()); + await sdk.shutdown(); + const json = JSON.stringify(sent); + expect(json).toContain('"attempt":3'); + expect(json).toContain('"outcome":"failed"'); + expect(json).toContain('"service":"lovat-worker"'); + expect(json).not.toContain("PRIVATE-"); + }); + test("fails open on invalid production endpoints", async () => { + const warn = console.warn; + console.warn = () => {}; + try { + const sdk = createWorkerTelemetry({ + ...env, + CAIRN_URL: "http://cairn.example", + }); + expect(sdk.requests).toBeUndefined(); + await sdk.shutdown(); + } finally { + console.warn = warn; + } + }); + test("only reports success for committed lease completion", async () => { + for (const count of [1, 0]) { + const observe = mock((..._args: unknown[]) => {}); + const db = { + $queryRaw: mock(async () => [job]), + importJob: { updateMany: mock(async () => ({ count })) }, + } as unknown as PrismaClient; + await runNextJob(db, async () => {}, observe); + expect(observe.mock.calls.map((v) => v[1])).toEqual([ + "running", + count ? "success" : "cancelled", + ]); + } + }); + test("reports persisted failure and isolates collector exceptions", async () => { + const observe = mock((..._args: unknown[]) => {}); + const db = { + $queryRaw: mock(async () => [job]), + importJob: { updateMany: mock(async () => ({ count: 1 })) }, + } as unknown as PrismaClient; + await runNextJob( + db, + async () => { + throw new Error("PRIVATE-BODY"); + }, + observe, + ); + expect(observe.mock.calls.map((v) => v[1])).toEqual(["running", "failed"]); + await expect( + runNextJob( + db, + async () => {}, + () => { + throw new Error("collector"); + }, + ), + ).resolves.toBe(true); + }); +}); diff --git a/packages/README.md b/packages/README.md index 37963829b..8687c7917 100644 --- a/packages/README.md +++ b/packages/README.md @@ -1,5 +1,6 @@ # Shared packages - [`@lovat/db`](db): canonical Prisma schema, migration history, generated types, and PostgreSQL client. Server consumes it today; the separate Support backend will consume it when implemented. +- [`@cairn/telemetry`](cairn-telemetry): source-pinned private Cairn producer SDK consumed by Server and Worker. Includes reviewed upstream checksums and local build metadata; no registry/private-repository credentials or committed build output are required. Each package owns its lockfile. Applications consume the built package through a local `file:` dependency, without cross-app source imports or a root workspace. diff --git a/packages/cairn-telemetry/README.md b/packages/cairn-telemetry/README.md new file mode 100644 index 000000000..da35a66a2 --- /dev/null +++ b/packages/cairn-telemetry/README.md @@ -0,0 +1,16 @@ +# Cairn telemetry source snapshot + +This is the producer SDK from `HighlanderRobotics/cairn`, pinned to merged commit `fd029d1c90b100fd31313e902b065effeaac8712` (SDK 0.1.0). `UPSTREAM.json` records the source files and SHA-256 checksums. The source is copied verbatim, including its request/diagnostic contracts; only local package/build metadata is adapted to Lovat's existing independent-app installation model. + +The upstream package is private and unpublished. Keeping a reviewed source snapshot lets CI and Railway build without a cross-repository credential, root workspace, downloaded binary artifact, or committed generated JavaScript. Applications depend on it through `file:../../packages/cairn-telemetry`, like `@lovat/db`. Do not hand-edit snapshot source; update it from a reviewed upstream commit and refresh its checksum manifest together. + +```sh +npm ci --include=dev +npm run build +``` + +The package owns its npm lockfile. Build output under `dist/` is ignored. Server's install/build scripts prepare this dependency. Worker CI and Docker builds prepare it before Bun copies local dependencies. For a clean local Worker setup, build this package and `@lovat/db` before `bun install`. + +Only the producer request queue, redaction helpers, diagnostic exporters, and validation contracts are included. No database client, server ingestion code, Better Auth, or provider integrations are included. The Hono 4.13.16 version must match Worker types; Worker intentionally advances from 4.13.13 to this SDK-compatible patch. Zod 4.6.7 is private to the SDK and does not upgrade application validation dependencies. + +Queues are memory-only and bounded by event count, not exact bytes. The middleware queues synchronously and exports asynchronously on the application event loop. Default request queues hold 2,000 waiting events plus one in-flight batch, with two-second flushes and health reports even when idle. The SDK supports a bounded shutdown budget and counts dropped/failed exports. A collector outage can lose observations but must not fail a request or alter worker job leases. No registry publication or real telemetry transmission occurs merely by installing the package. diff --git a/packages/cairn-telemetry/UPSTREAM.json b/packages/cairn-telemetry/UPSTREAM.json new file mode 100644 index 000000000..5c4f31c39 --- /dev/null +++ b/packages/cairn-telemetry/UPSTREAM.json @@ -0,0 +1,15 @@ +{ + "repository": "https://github.com/HighlanderRobotics/cairn", + "commit": "fd029d1c90b100fd31313e902b065effeaac8712", + "package": "@cairn/telemetry", + "version": "0.1.0", + "sha256": { + "packages/telemetry/index.ts": "efc700f6261f20737be8ae7e13de9493c655e45278f1f2451f02ac0ad53837f3", + "packages/telemetry/sdk.ts": "fdcb0214fe3be96b3af1dfed42f358c659e779994802e14356508fc351429fe0", + "packages/telemetry/diagnostics.ts": "d36f80985db91de2e2bd50df9d7f24e8a371139db96c0ffe89d62decd5c35670", + "packages/telemetry/redaction.ts": "bef07f331a9635bdddb891c16133fc632c966736c9530625ec64f11d97d91444", + "packages/telemetry/lifecycle.ts": "ad0aabb64c1e4dda5f15f3e0d4bcd066a49fabdfa5afa6f50198afd5368a7618", + "packages/schemas/index.ts": "bae183289a838dc810cb761fc08458c04d18256ba6965fc62d9d415eb463ae7f", + "packages/operations/schemas.ts": "abb274fa7db35a0916f326e61b0798bccd5f063076fabb716e91d862b0fb8d02" + } +} diff --git a/packages/cairn-telemetry/package-lock.json b/packages/cairn-telemetry/package-lock.json new file mode 100644 index 000000000..2aa0e8f29 --- /dev/null +++ b/packages/cairn-telemetry/package-lock.json @@ -0,0 +1,72 @@ +{ + "name": "@cairn/telemetry", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@cairn/telemetry", + "version": "0.1.0", + "dependencies": { + "hono": "4.13.16", + "zod": "4.6.7" + }, + "devDependencies": { + "@types/node": "22.20.0", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@types/node": { + "version": "22.20.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.0.tgz", + "integrity": "sha512-QWlFW2wf3nTjC13/DqRnBpR4ZO36VJH/JVBkA/vcnmbTBNQIlnObqyqZE1tUR7+Ni23Lda8R1BxMfbXRpCUx5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/hono": { + "version": "4.13.16", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.16.tgz", + "integrity": "sha512-AOLOEhvrV+iH92xXCnFr/5+3KjPKcI3xP63XJtX5spAnkznPdHijlIsUTpi7/9EhWqrTCekw5c5zh1K+YsVw7A==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/packages/cairn-telemetry/package.json b/packages/cairn-telemetry/package.json new file mode 100644 index 000000000..de4268ddf --- /dev/null +++ b/packages/cairn-telemetry/package.json @@ -0,0 +1,36 @@ +{ + "name": "@cairn/telemetry", + "version": "0.1.0", + "private": true, + "type": "module", + "main": "./dist/telemetry/index.js", + "types": "./dist/telemetry/index.d.ts", + "exports": { + ".": { + "types": "./dist/telemetry/index.d.ts", + "import": "./dist/telemetry/index.js" + } + }, + "scripts": { + "build": "node verify-upstream.mjs && tsc" + }, + "dependencies": { + "zod": "4.6.7", + "hono": "4.13.16" + }, + "devDependencies": { + "typescript": "5.9.3", + "@types/node": "22.20.0" + }, + "engines": { + "node": ">=22" + }, + "files": [ + "dist", + "src", + "UPSTREAM.json", + "verify-upstream.mjs", + "tsconfig.json", + "README.md" + ] +} diff --git a/packages/cairn-telemetry/src/operations/schemas.ts b/packages/cairn-telemetry/src/operations/schemas.ts new file mode 100644 index 000000000..d2be946b7 --- /dev/null +++ b/packages/cairn-telemetry/src/operations/schemas.ts @@ -0,0 +1,176 @@ +import { z } from "zod"; + +const label = z + .string() + .min(1) + .max(120) + .regex(/^[a-zA-Z0-9_.:-]+$/), + count = z.number().int().min(0).max(100000000), + duration = z.number().finite().min(0).max(86400000); +export const context = { service: label, environment: label }; +export const syncEvent = z.object({ + id: z.uuid(), + timestamp: z.iso.datetime(), + ...context, + installationId: z.uuid(), + attemptId: label, + event: z.enum([ + "sync_queued", + "sync_started", + "sync_batch_attempted", + "sync_batch_succeeded", + "sync_batch_failed", + "sync_retry_scheduled", + "sync_conflict_detected", + "sync_completed", + "sync_queue_state", + "sync_storage_error", + ]), + appVersion: label, + build: label.optional(), + platform: z.enum(["ios", "android", "web"]), + queueDepth: count, + batchRecords: count.optional(), + retryCount: count.default(0), + latencyMs: duration.optional(), + errorCode: label.optional(), + networkState: z.enum(["online", "offline", "unknown"]).optional(), + oldestItemAgeMs: z.number().min(0).max(31536000000).optional(), +}); +export const jobEvent = z.object({ + id: z.uuid(), + ...context, + jobId: label, + kind: label, + queue: label, + attempt: z.number().int().min(1).max(100), + outcome: z.enum(["queued", "running", "success", "failed", "cancelled"]), + enqueuedAt: z.iso.datetime().optional(), + startedAt: z.iso.datetime(), + completedAt: z.iso.datetime().optional(), + durationMs: duration.optional(), + errorFingerprint: label.optional(), + deploymentId: label.optional(), + traceId: label.optional(), +}); +export const qualityEvent = z + .object({ + id: z.uuid(), + ...context, + rule: label, + source: label, + status: z.enum(["passed", "failed", "unavailable"]), + checkedRecords: count, + affectedRecords: count, + severity: z.enum(["SEV1", "SEV2", "SEV3"]), + checkedAt: z.iso.datetime(), + }) + .refine( + (v) => v.affectedRecords <= v.checkedRecords, + "Affected records exceed checked records", + ); +export const contactEvent = z.object({ + id: z.uuid(), + ...context, + installationId: z.uuid(), + appVersion: label, + build: label.optional(), + platform: z.enum(["ios", "android", "web"]), + osVersion: label.optional(), + contactedAt: z.iso.datetime(), +}); +export const configEvent = z.object({ + id: z.uuid(), + ...context, + revision: label, + runtime: label, + keysPresent: z.array(label).max(200), + publicValues: z.record( + z.enum([ + "runtimeVersion", + "region", + "replicas", + "telemetryEnabled", + "targetSdk", + "minimumVersion", + ]), + z.union([z.string().max(100), z.number(), z.boolean()]), + ), + createdAt: z.iso.datetime(), +}); +export const flagEvent = z + .object({ + id: z.uuid(), + ...context, + flag: label, + variant: label, + appVersion: label, + requests: count, + errors: count, + durationSumMs: z.number().finite().nonnegative(), + observedAt: z.iso.datetime(), + }) + .refine((v) => v.errors <= v.requests, "Errors exceed requests"); +export const costInput = z + .object({ + id: z.uuid(), + ...context, + provider: label, + amount: z.number().nonnegative().finite(), + currency: z.string().regex(/^[A-Z]{3}$/), + kind: z.enum(["provider-reported", "estimate"]), + periodStart: z.iso.datetime(), + periodEnd: z.iso.datetime(), + assumptions: z.string().max(1000).optional(), + observedAt: z.iso.datetime(), + }) + .refine( + (v) => Date.parse(v.periodEnd) > Date.parse(v.periodStart), + "Invalid cost period", + ) + .refine( + (v) => v.kind !== "estimate" || Boolean(v.assumptions), + "Estimates require assumptions", + ); +export const sloInput = z + .object({ + ...context, + name: z.string().min(3).max(120), + kind: z.enum(["availability", "latency", "sync", "synthetic", "jobs"]), + target: z.number().min(90).max(99.9999), + latencyMs: duration.optional(), + windowDays: z.number().int().min(1).max(30).default(7), + minSamples: z.number().int().min(1).default(100), + }) + .refine( + (v) => v.kind !== "latency" || v.latencyMs !== undefined, + "Latency SLO requires an ms threshold", + ); +export const syntheticInput = z.object({ + ...context, + name: z.string().min(3).max(120), + url: z.url().max(1000), + expectedStatus: z.number().int().min(200).max(499).default(200), + intervalSeconds: z.number().int().min(60).max(86400).default(300), + critical: z.boolean().default(true), + enabled: z.boolean().default(true), +}); +export const runbookInput = z.object({ + ...context, + title: z.string().min(3).max(200), + owner: label, + trigger: z.string().min(1).max(500), + body: z.string().min(10).max(30000), + reviewedAt: z.iso.datetime().nullable().optional(), +}); +export const databaseEvent = z.object({ + id: z.uuid(), + ...context, + queryId: label, + durationMs: duration, + waitMs: duration.default(0), + outcome: z.enum(["success", "error", "timeout"]), + traceId: label.optional(), + requestId: label.optional(), + timestamp: z.iso.datetime(), +}); diff --git a/packages/cairn-telemetry/src/schemas/index.ts b/packages/cairn-telemetry/src/schemas/index.ts new file mode 100644 index 000000000..eeb68c00b --- /dev/null +++ b/packages/cairn-telemetry/src/schemas/index.ts @@ -0,0 +1,158 @@ +import { z } from "zod"; + +const label = z + .string() + .min(1) + .max(120) + .regex(/^[a-zA-Z0-9_.:-]+$/); +const duration = z.number().finite().min(0).max(86_400_000); +export const requestEvent = z + .object({ + id: z.uuid(), + requestId: z.string().min(1).max(128), + traceId: z.string().max(128).optional(), + receivedAt: z.iso.datetime(), + completedAt: z.iso.datetime(), + durationMs: duration, + service: label, + environment: label, + deploymentId: z.string().max(128).optional(), + appVersion: z.string().max(80).optional(), + method: z.enum([ + "GET", + "POST", + "PUT", + "PATCH", + "DELETE", + "HEAD", + "OPTIONS", + ]), + route: z + .string() + .min(1) + .max(500) + .startsWith("/") + .refine( + (v) => !/[?#]/.test(v), + "Use a normalized route without query parameters", + ), + statusCode: z.number().int().min(100).max(599), + requestBytes: z.number().int().nonnegative().optional(), + responseBytes: z.number().int().nonnegative().optional(), + authDurationMs: duration.optional(), + handlerDurationMs: duration.optional(), + databaseDurationMs: duration.optional(), + externalDurationMs: duration.optional(), + errorCode: z.string().max(100).optional(), + errorGroupId: z.uuid().optional(), + metadata: z + .record( + z.string().max(80), + z.union([z.string().max(500), z.number().finite(), z.boolean()]), + ) + .refine((v) => Object.keys(v).length <= 30) + .optional(), + }) + .refine( + (e) => Date.parse(e.completedAt) >= Date.parse(e.receivedAt), + "Completion must follow receipt", + ) + .refine( + (e) => Date.parse(e.receivedAt) <= Date.now() + 60_000, + "Future event", + ); +export type RequestEvent = z.infer; +export const errorEvent = z.object({ + id: z.uuid(), + timestamp: z.iso.datetime(), + service: label, + environment: label, + type: z.string().min(1).max(100), + message: z.string().min(1).max(2000), + stack: z.string().max(12000).optional(), + requestId: z.string().max(128).optional(), + deploymentId: z.string().max(128).optional(), + appVersion: z.string().max(80).optional(), +}); +export const analyticsEvent = z.object({ + id: z.uuid(), + timestamp: z.iso.datetime(), + service: label, + environment: label, + name: label, + path: z.string().max(500).optional(), + durationMs: duration.optional(), +}); +export const traceEvent = z.object({ + id: z.uuid(), + traceId: z.string().min(1).max(128), + parentId: z.uuid().optional(), + name: z.string().min(1).max(200), + service: label, + environment: label, + startedAt: z.iso.datetime(), + durationMs: duration, + kind: z + .enum(["server", "client", "database", "internal"]) + .default("internal"), +}); +export const caseInput = z.object({ + name: z.string().min(1).max(100), + email: z.email().max(254), + category: z.enum(["bug", "question", "account", "feedback"]), + subject: z.string().min(3).max(200), + description: z.string().min(10).max(10000), + teamNumber: z.coerce.number().int().positive().max(99999).optional(), + requestId: z.string().max(128).optional(), + website: z.string().max(0).optional(), +}); +export const caseStates = [ + "New", + "Open", + "Waiting on requester", + "Waiting on engineering", + "Resolved", + "Closed", +] as const; +export const incidentStates = [ + "Open", + "Acknowledged", + "Mitigating", + "Resolved", +] as const; +export const queryInput = z + .object({ + start: z.iso.datetime(), + end: z.iso.datetime(), + service: label.optional(), + environment: label.optional(), + q: z.string().max(200).optional(), + status: z.coerce.number().int().min(100).max(599).optional(), + method: z + .enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]) + .optional(), + minDuration: z.coerce.number().min(0).optional(), + limit: z.coerce.number().int().min(1).max(200).default(100), + cursor: z.string().max(300).optional(), + }) + .refine( + (v) => + Date.parse(v.end) > Date.parse(v.start) && + Date.parse(v.end) - Date.parse(v.start) <= 31 * 86400000, + "Time window must be positive and at most 31 days", + ); +export type QueryInput = z.infer; +export const ruleInput = z.object({ + name: z.string().min(3).max(120), + service: label, + environment: label, + metric: z.enum(["error_rate", "p95_latency", "request_count"]), + comparator: z.enum(["gt", "lt"]), + threshold: z.number().nonnegative(), + windowMinutes: z.number().int().min(1).max(60), + minSamples: z.number().int().min(1), + severity: z.enum(["SEV1", "SEV2", "SEV3"]), + cooldownMinutes: z.number().int().min(1).max(1440), + enabled: z.boolean().default(true), +}); +export const role = z.enum(["admin", "developer", "viewer"]); diff --git a/packages/cairn-telemetry/src/telemetry/diagnostics.ts b/packages/cairn-telemetry/src/telemetry/diagnostics.ts new file mode 100644 index 000000000..5cb673023 --- /dev/null +++ b/packages/cairn-telemetry/src/telemetry/diagnostics.ts @@ -0,0 +1,129 @@ +import { + configEvent, + contactEvent, + databaseEvent, + flagEvent, + jobEvent, + qualityEvent, + syncEvent, +} from "../operations/schemas.ts"; + +import { + beforeDeadline, + exportLifecycle, + shutdownDeadline, +} from "./lifecycle.ts"; + +const schemas = { + sync: syncEvent, + jobs: jobEvent, + quality: qualityEvent, + installations: contactEvent, + config: configEvent, + flags: flagEvent, + database: databaseEvent, +}; +type Kind = keyof typeof schemas; +export function createDiagnostics(options: { + endpoint: string; + token: string; + service: string; + environment: string; + maxQueue?: number; + flushMs?: number; + fetch?: (url: string, init?: RequestInit) => Promise; +}) { + const queue: { kind: Kind; event: unknown }[] = [], + health = { dropped: 0, failedExports: 0, exported: 0 }; + let flushing: Promise | undefined, + closed = false; + const send = options.fetch ?? fetch; + const lifecycle = exportLifecycle(); + function record(kind: Kind, input: Record) { + if (closed || queue.length >= (options.maxQueue ?? 1000)) { + health.dropped++; + return false; + } + const parsed = schemas[kind].safeParse({ + ...input, + id: input.id ?? crypto.randomUUID(), + service: options.service, + environment: options.environment, + }); + if (!parsed.success) { + health.dropped++; + return false; + } + queue.push({ kind, event: parsed.data }); + return true; + } + async function drain() { + const next = queue[0]; + if (!next) return; + const batch = queue.splice(0, 100), + groups = new Map(); + for (const item of batch) { + const group = groups.get(item.kind) ?? []; + group.push(item.event); + groups.set(item.kind, group); + } + for (const [kind, events] of groups) { + let ok = false; + for (let retry = 0; retry < 3; retry++) { + if (lifecycle.stopped) break; + try { + const response = await send(`${options.endpoint}/v1/ingest/${kind}`, { + method: "POST", + headers: { + authorization: `Bearer ${options.token}`, + "content-type": "application/json", + }, + body: JSON.stringify(events), + signal: lifecycle.signal(4000), + }); + if (response.ok) { + health.exported += events.length; + ok = true; + break; + } + health.failedExports++; + if (response.status < 500 && response.status !== 429) break; + } catch { + health.failedExports++; + } + if (retry < 2) + await lifecycle.delay(250 * 2 ** retry + Math.random() * 100); + } + if (!ok) health.dropped += events.length; + } + } + function flush() { + if (!flushing) + flushing = drain().finally(() => { + flushing = undefined; + }); + return flushing; + } + const timer = setInterval(() => { + void flush(); + }, options.flushMs ?? 2000); + timer.unref?.(); + return { + record, + flush, + health, + queued: () => queue.length, + async shutdown({ timeoutMs = 10000 }: { timeoutMs?: number } = {}) { + const deadline = shutdownDeadline(timeoutMs); + closed = true; + clearInterval(timer); + try { + while ((queue.length || flushing) && Date.now() < deadline) + await beforeDeadline(flush(), deadline); + } finally { + lifecycle.stop(); + health.dropped += queue.splice(0).length; + } + }, + }; +} diff --git a/packages/cairn-telemetry/src/telemetry/index.ts b/packages/cairn-telemetry/src/telemetry/index.ts new file mode 100644 index 000000000..9c62d0410 --- /dev/null +++ b/packages/cairn-telemetry/src/telemetry/index.ts @@ -0,0 +1,4 @@ +export type { RequestEvent } from "../schemas/index.ts"; +export { createDiagnostics } from "./diagnostics.ts"; +export type { TelemetryOptions } from "./sdk.ts"; +export { createTelemetry } from "./sdk.ts"; diff --git a/packages/cairn-telemetry/src/telemetry/lifecycle.ts b/packages/cairn-telemetry/src/telemetry/lifecycle.ts new file mode 100644 index 000000000..751d18bd5 --- /dev/null +++ b/packages/cairn-telemetry/src/telemetry/lifecycle.ts @@ -0,0 +1,41 @@ +export function exportLifecycle() { + const controller = new AbortController(); + return { + signal: (timeoutMs: number) => + AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]), + get stopped() { + return controller.signal.aborted; + }, + stop: () => controller.abort(), + async delay(ms: number) { + if (controller.signal.aborted) return; + await new Promise((resolve) => { + const finish = () => { + clearTimeout(timer); + controller.signal.removeEventListener("abort", finish); + resolve(); + }; + const timer = setTimeout(finish, ms); + controller.signal.addEventListener("abort", finish, { once: true }); + }); + }, + }; +} +export async function beforeDeadline(work: Promise, deadline: number) { + let timer: ReturnType | undefined; + try { + await Promise.race([ + work, + new Promise((resolve) => { + timer = setTimeout(resolve, Math.max(0, deadline - Date.now())); + }), + ]); + } finally { + if (timer) clearTimeout(timer); + } +} +export function shutdownDeadline(timeoutMs = 10000) { + if (!Number.isFinite(timeoutMs) || timeoutMs < 0) + throw new Error("Shutdown timeout must be a finite nonnegative number"); + return Date.now() + timeoutMs; +} diff --git a/packages/cairn-telemetry/src/telemetry/redaction.ts b/packages/cairn-telemetry/src/telemetry/redaction.ts new file mode 100644 index 000000000..7a932254a --- /dev/null +++ b/packages/cairn-telemetry/src/telemetry/redaction.ts @@ -0,0 +1,53 @@ +const secret = + /authorization|cookie|password|passwd|secret|token|api.?key|credential|email|ip.?address/i; +const approved = new Set([ + "platform", + "os", + "browser", + "region", + "sdkVersion", + "exporterDropped", + "exporterFailures", +]); +export function sanitizeMetadata( + input: Record | undefined, +) { + return Object.fromEntries( + Object.entries(input ?? {}) + .filter(([key]) => approved.has(key) && !secret.test(key)) + .map(([k, v]) => [k, typeof v === "string" ? redact(v) : v]), + ); +} +export function redact(input: string) { + return input + .replace(/Bearer\s+[^\s]+/gi, "Bearer [REDACTED]") + .replace( + /([?&](?:token|key|password|secret|email)=)[^&\s]+/gi, + "$1[REDACTED]", + ) + .replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, "[EMAIL]") + .replace( + /((?:password|secret|token|api[_-]?key|authorization|cookie)\s*[=:]\s*)[^\s,;]+/gi, + "$1[REDACTED]", + ); +} +export function normalizeRoute(path: string) { + return path + .split("?")[0] + .replace(/\/[0-9]+(?=\/|$)/g, "/:id") + .replace(/\/[a-f0-9]{8}-[a-f0-9-]{27,}(?=\/|$)/gi, "/:id"); +} +export async function fingerprint(type: string, message: string, stack = "") { + const normalized = `${type}:${message.replace(/\b\d+\b/g, "#")}:${stack + .split("\n") + .slice(0, 4) + .join("\n") + .replace(/:\d+:\d+/g, ":#:#")}`; + const data = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(normalized), + ); + return [...new Uint8Array(data)] + .map((v) => v.toString(16).padStart(2, "0")) + .join(""); +} diff --git a/packages/cairn-telemetry/src/telemetry/sdk.ts b/packages/cairn-telemetry/src/telemetry/sdk.ts new file mode 100644 index 000000000..a45ffac15 --- /dev/null +++ b/packages/cairn-telemetry/src/telemetry/sdk.ts @@ -0,0 +1,162 @@ +import type { MiddlewareHandler } from "hono"; +import type { RequestEvent } from "../schemas/index.ts"; +import { + beforeDeadline, + exportLifecycle, + shutdownDeadline, +} from "./lifecycle.ts"; +import { normalizeRoute, sanitizeMetadata } from "./redaction.ts"; + +export type TelemetryOptions = { + endpoint: string; + token: string; + service: string; + environment: string; + deploymentId?: string; + appVersion?: string; + maxQueue?: number; + batchSize?: number; + flushMs?: number; + maxRetries?: number; + fetch?: (url: string, init?: RequestInit) => Promise; +}; +export function createTelemetry(options: TelemetryOptions) { + const max = options.maxQueue ?? 2000, + batch = Math.min(options.batchSize ?? 200, 500); + if (max < batch || batch < 1) + throw new Error("Queue must fit a positive batch"); + const queue: RequestEvent[] = []; + let running: Promise | undefined, + closed = false; + const health = { dropped: 0, failedExports: 0, exported: 0 }; + const send = options.fetch ?? fetch; + const exporterId = crypto.randomUUID(); + const lifecycle = exportLifecycle(); + async function reportHealth() { + try { + await send(`${options.endpoint}/v1/ingest/health`, { + method: "POST", + headers: { + authorization: `Bearer ${options.token}`, + "content-type": "application/json", + }, + body: JSON.stringify({ + id: exporterId, + service: options.service, + environment: options.environment, + dropped: health.dropped, + failedExports: health.failedExports, + }), + signal: lifecycle.signal(2000), + }); + } catch {} + } + + async function drain() { + const items = queue.splice(0, batch); + if (!items.length) return; + let ok = false; + for (let attempt = 0; attempt <= (options.maxRetries ?? 3); attempt++) { + if (lifecycle.stopped) break; + try { + const response = await send(`${options.endpoint}/v1/ingest/requests`, { + method: "POST", + headers: { + authorization: `Bearer ${options.token}`, + "content-type": "application/json", + }, + body: JSON.stringify(items), + signal: lifecycle.signal(4000), + }); + if (response.ok) { + health.exported += items.length; + ok = true; + break; + } + if (response.status < 500 && response.status !== 429) break; + } catch {} + health.failedExports++; + if (attempt < (options.maxRetries ?? 3)) + await lifecycle.delay( + Math.min(250 * 2 ** attempt, 4000) + Math.random() * 200, + ); + } + if (!ok) health.dropped += items.length; + } + function flush() { + if (!running) + running = drain() + .then(reportHealth) + .finally(() => { + running = undefined; + }); + return running; + } + const timer = setInterval(() => { + void flush(); + }, options.flushMs ?? 2000); + timer.unref?.(); + function record(event: RequestEvent) { + if (closed || queue.length >= max) { + health.dropped++; + return; + } + queue.push({ ...event, metadata: sanitizeMetadata(event.metadata) }); + if (queue.length >= batch) void flush(); + } + const middleware: MiddlewareHandler = async (c, next) => { + const start = performance.now(), + receivedAt = new Date().toISOString(), + id = crypto.randomUUID(); + c.header("x-request-id", id); + try { + await next(); + } finally { + const route = + c.req.routePath?.startsWith("/") && c.req.routePath !== "/*" + ? c.req.routePath + : c.res.status === 404 + ? "/__unmatched__" + : normalizeRoute(c.req.path); + record({ + id, + requestId: id, + traceId: /^[a-f0-9]{2}-[a-f0-9]{32}-[a-f0-9]{16}-[a-f0-9]{2}$/i.test( + c.req.header("traceparent") ?? "", + ) + ? c.req.header("traceparent")?.split("-")[1] + : undefined, + receivedAt, + completedAt: new Date().toISOString(), + durationMs: performance.now() - start, + service: options.service, + environment: options.environment, + deploymentId: options.deploymentId, + appVersion: options.appVersion, + method: c.req.method as RequestEvent["method"], + route, + statusCode: c.error ? 500 : c.res.status, + responseBytes: Number(c.res.headers.get("content-length")) || undefined, + }); + } + }; + return { + record, + flush, + middleware, + health, + queued: () => queue.length, + async shutdown({ timeoutMs = 10000 }: { timeoutMs?: number } = {}) { + const deadline = shutdownDeadline(timeoutMs); + closed = true; + clearInterval(timer); + try { + while ((queue.length || running) && Date.now() < deadline) + await beforeDeadline(flush(), deadline); + } finally { + lifecycle.stop(); + health.dropped += queue.splice(0).length; + } + }, + }; +} diff --git a/packages/cairn-telemetry/tsconfig.json b/packages/cairn-telemetry/tsconfig.json new file mode 100644 index 000000000..cd2b45f1a --- /dev/null +++ b/packages/cairn-telemetry/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "skipLibCheck": true, + "declaration": true, + "rewriteRelativeImportExtensions": true, + "rootDir": "src", + "outDir": "dist", + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/packages/cairn-telemetry/verify-upstream.mjs b/packages/cairn-telemetry/verify-upstream.mjs new file mode 100644 index 000000000..aec3227be --- /dev/null +++ b/packages/cairn-telemetry/verify-upstream.mjs @@ -0,0 +1,21 @@ +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { dirname, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +const root = dirname(fileURLToPath(import.meta.url)); +const manifest = JSON.parse( + await readFile(resolve(root, "UPSTREAM.json"), "utf8"), +); +for (const [upstream, expected] of Object.entries(manifest.sha256)) { + const path = resolve(root, "src", upstream.replace(/^packages\//, "")); + if (!path.startsWith(resolve(root, "src") + sep)) + throw new Error("Invalid upstream path"); + const actual = createHash("sha256") + .update(await readFile(path)) + .digest("hex"); + if (actual !== expected) + throw new Error(`Upstream source checksum mismatch: ${upstream}`); +} +console.log( + `Verified ${Object.keys(manifest.sha256).length} SDK sources from Cairn ${manifest.commit}`, +);