Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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/**'
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
7 changes: 7 additions & 0 deletions apps/server/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 6 additions & 0 deletions apps/server/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions apps/server/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions apps/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
20 changes: 20 additions & 0 deletions apps/server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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)
Expand Down
138 changes: 138 additions & 0 deletions apps/server/src/lib/cairn.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
shutdown: (timeoutMs?: number) => Promise<void>;
};

export function createCairnReporter(
env: NodeJS.ProcessEnv = process.env,
fetcher?: TelemetryOptions["fetch"],
): CairnReporter {
let exporter: ReturnType<typeof createTelemetry> | 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();
39 changes: 39 additions & 0 deletions apps/server/src/lib/cairnShutdown.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
},
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);
}
5 changes: 5 additions & 0 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -16,3 +19,5 @@ const server = app.listen(port, () => {
});

attachTrainingSockets(server);

installCairnShutdown(server, cairn);
Loading
Loading