Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

Enhance telemetry functionality and improve budget management

Lewis Carhartdadf5190745a
diff --git a/apps/agent/agent/lib/focus.ts b/apps/agent/agent/lib/focus.ts
index 0e58d33f..439acbd8 100644
--- a/apps/agent/agent/lib/focus.ts
+++ b/apps/agent/agent/lib/focus.ts
@@ -7,6 +7,7 @@ export const focus = defineState("crm.focus", () => ({
sessionId: null as string | null,
spent: 0,
budget: 4,
+ exhausted: false,
}));
export function currentFocus(): {
@@ -35,10 +36,13 @@ export function focusOn(input: {
}
export function spend(units = 1): { ok: true } | { ok: false; reason: string } {
- const { spent, budget } = focus.get();
+ const { spent, budget, exhausted } = focus.get();
if (spent + units > budget) {
- void bumpCounter(COUNTERS.budgetExhausted);
+ if (!exhausted) {
+ focus.update((current) => ({ ...current, exhausted: true }));
+ void bumpCounter(COUNTERS.budgetExhausted);
+ }
return {
ok: false,
@@ -53,5 +57,5 @@ export function spend(units = 1): { ok: true } | { ok: false; reason: string } {
}
export function setBudget(budget: number): void {
- focus.update((current) => ({ ...current, budget }));
+ focus.update((current) => ({ ...current, budget, exhausted: false }));
}
diff --git a/apps/api/src/telemetry/funnel.service.ts b/apps/api/src/telemetry/funnel.service.ts
index 0b6e5b46..1d65b9ff 100644
--- a/apps/api/src/telemetry/funnel.service.ts
+++ b/apps/api/src/telemetry/funnel.service.ts
@@ -9,6 +9,7 @@ import {
} from "@crm/telemetry";
import { Injectable, Logger } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
+import { GOOGLE_PROVIDER_ID } from "../google/google.constants";
import { SEED_OWNER_PREFIX } from "./seed";
@Injectable()
@@ -55,11 +56,24 @@ export class FunnelService {
(row) => row.createdAt,
);
- case "google_oauth_configured":
- return process.env.GOOGLE_CLIENT_ID?.trim() &&
- process.env.GOOGLE_CLIENT_SECRET?.trim()
- ? new Date()
- : null;
+ case "google_oauth_configured": {
+ const configured =
+ process.env.GOOGLE_CLIENT_ID?.trim() &&
+ process.env.GOOGLE_CLIENT_SECRET?.trim();
+
+ if (!configured) return null;
+
+ const linked = await this.earliest(
+ this.db.account.findFirst({
+ where: { providerId: GOOGLE_PROVIDER_ID },
+ orderBy: { createdAt: "asc" },
+ select: { createdAt: true },
+ }),
+ (row) => row.createdAt,
+ );
+
+ return linked ?? new Date();
+ }
case "first_mailbox_sync":
return this.earliest(
@@ -107,17 +121,37 @@ export class FunnelService {
);
case "first_fact_applied":
- return this.earliest(
- this.db.contactFact.findFirst({
- where: { status: FactStatus.APPLIED },
- orderBy: { observedAt: "asc" },
- select: { observedAt: true, decidedAt: true },
- }),
- (row) => row.decidedAt ?? row.observedAt,
- );
+ return this.firstApplied();
}
}
+ private async firstApplied(): Promise<Date | null> {
+ const everApplied = {
+ status: { in: [FactStatus.APPLIED, FactStatus.SUPERSEDED] },
+ };
+
+ const [decided, undecided] = await Promise.all([
+ this.db.contactFact.findFirst({
+ where: { ...everApplied, decidedAt: { not: null } },
+ orderBy: { decidedAt: "asc" },
+ select: { decidedAt: true },
+ }),
+ this.db.contactFact.findFirst({
+ where: { ...everApplied, decidedAt: null },
+ orderBy: { observedAt: "asc" },
+ select: { observedAt: true },
+ }),
+ ]);
+
+ const applied = [decided?.decidedAt, undecided?.observedAt].filter(
+ (at): at is Date => at instanceof Date,
+ );
+
+ if (applied.length === 0) return null;
+
+ return new Date(Math.min(...applied.map((at) => at.getTime())));
+ }
+
private async earliest<T>(
query: PromiseLike<T | null>,
pick: (row: T) => Date | null,
diff --git a/apps/api/src/telemetry/rollup.service.ts b/apps/api/src/telemetry/rollup.service.ts
index 68bb9913..bcd129cd 100644
--- a/apps/api/src/telemetry/rollup.service.ts
+++ b/apps/api/src/telemetry/rollup.service.ts
@@ -12,17 +12,18 @@ import { readAgentModel } from "@crm/db/settings";
import { WORKSPACE_ID } from "@crm/db/workspace";
import {
bucket,
+ claimRollup,
dayBucket,
drainCounters,
installDaily,
- markRollup,
type Properties,
permittedEvidenceKind,
permittedMethod,
permittedTaskKind,
permittedTool,
- readInstall,
- sameUtcDay,
+ releaseRollup,
+ restoreCounters,
+ telemetryDisabled,
} from "@crm/telemetry";
import { Injectable, Logger } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
@@ -61,24 +62,30 @@ export class RollupService {
) {}
async run(force = false): Promise<RollupOutcome> {
- const milestones = await this.funnel.sweep();
-
- const install = await readInstall();
- if (!install) {
- return { sent: false, reason: "no install row", milestones };
+ if (telemetryDisabled()) {
+ return { sent: false, reason: "telemetry is off", milestones: [] };
}
+ const milestones = await this.funnel.sweep();
+
const now = new Date();
- if (!force && sameUtcDay(install.lastRollupAt, now)) {
- return { sent: false, reason: "already sent today", milestones };
+ const claim = await claimRollup(now, force);
+ if (!claim.claimed) {
+ return { sent: false, reason: claim.reason, milestones };
}
const since = new Date(now.getTime() - WINDOW_HOURS * HOUR_MS);
+ let counters: Record<string, number> = {};
try {
- const properties = await this.gather(since);
- await installDaily(properties);
- await markRollup(now);
+ const gathered = await this.gather(since);
+ counters = gathered.counters;
+
+ if (!(await installDaily(gathered.properties))) {
+ await this.giveBack(claim.previous, counters);
+
+ return { sent: false, reason: "not delivered", milestones };
+ }
this.logger.log({
message: "Telemetry rollup sent",
@@ -88,6 +95,8 @@ export class RollupService {
return { sent: true, milestones };
} catch (error) {
+ await this.giveBack(claim.previous, counters);
+
this.logger.debug({
message: "Telemetry rollup could not be built",
reason: error instanceof Error ? error.message : String(error),
@@ -97,15 +106,30 @@ export class RollupService {
}
}
- private async gather(since: Date): Promise<Properties> {
+ private async giveBack(
+ previous: Date | null,
+ counters: Record<string, number>,
+ ): Promise<void> {
+ await releaseRollup(previous);
+ await restoreCounters(counters);
+ }
+
+ private async gather(
+ since: Date,
+ ): Promise<{ properties: Properties; counters: Record<string, number> }> {
+ const counters = await drainCounters();
+
const [shape, agent, ledger, crm] = await Promise.all([
this.shape(),
- this.agent(since),
+ this.agent(since, counters),
this.ledger(),
this.crm(since),
]);
- return { ...shape, ...agent, ...ledger, ...crm };
+ return {
+ properties: { ...shape, ...agent, ...ledger, ...crm },
+ counters,
+ };
}
private async shape(): Promise<Properties> {
@@ -157,24 +181,19 @@ export class RollupService {
}
}
- private async agent(since: Date): Promise<Properties> {
- const [
- tools,
- sessions,
- tasks,
- attempts,
- rechecks,
- counters,
- conversations,
- ] = await Promise.all([
- this.toolCalls(since),
- this.sessions(since),
- this.tasks(since),
- this.attempts(since),
- this.rechecks(since),
- drainCounters(),
- this.db.agentConversation.count(),
- ]);
+ private async agent(
+ since: Date,
+ counters: Record<string, number>,
+ ): Promise<Properties> {
+ const [tools, sessions, tasks, attempts, rechecks, conversations] =
+ await Promise.all([
+ this.toolCalls(since),
+ this.sessions(since),
+ this.tasks(since),
+ this.attempts(since),
+ this.rechecks(since),
+ this.db.agentConversation.count(),
+ ]);
const total = Object.values(tools.calls).reduce((sum, n) => sum + n, 0);
diff --git a/apps/api/src/telemetry/telemetry.service.ts b/apps/api/src/telemetry/telemetry.service.ts
index 67cda045..e898c7bc 100644
--- a/apps/api/src/telemetry/telemetry.service.ts
+++ b/apps/api/src/telemetry/telemetry.service.ts
@@ -1,5 +1,4 @@
import {
- crmVersion,
flushTelemetry,
onTelemetryProblem,
shutdownTelemetry,
@@ -30,7 +29,7 @@ export class TelemetryService implements OnModuleInit, OnApplicationShutdown {
return;
}
- const install = await syncVersion(crmVersion() ?? undefined);
+ const install = await syncVersion();
this.logger.log({
message: "Anonymous usage telemetry is on. See docs/telemetry.md.",
diff --git a/docs/telemetry.md b/docs/telemetry.md
index c1900578..c2553dde 100644
--- a/docs/telemetry.md
+++ b/docs/telemetry.md
@@ -29,6 +29,9 @@ a fork somewhere else by editing those two constants. Nothing is sent while `NOD
rather than "do not keep". Point this at a different project and you must set it there too.
- **Never blocks and never throws.** Every send is fire-and-forget behind a swallowed handler; a
telemetry failure logs at debug and is invisible everywhere else.
+- **Off leaves no marks.** With telemetry disabled the rollup route returns before the funnel
+ sweep runs: no milestone is recorded, no counter is drained, no rollup day is claimed. Turn it
+ back on and the funnel is still whole, because nothing was quietly consumed while it was off.
- **Nothing is sent from a test run.** `NODE_ENV=test` disables it, and `apps/api` and `apps/agent`
additionally set `CRM_TELEMETRY_DISABLED=1` in their `test` scripts — because a spec is allowed
to reassign `process.env.NODE_ENV`, and one that does was enough to let a real event out.
@@ -43,6 +46,11 @@ a fork somewhere else by editing those two constants. Nothing is sent while `NOD
Once per install per day, from `POST /internal/telemetry/rollup` on the API's cron. Counts and
distributions from grouped queries. Never a value from a row.
+The day is claimed under a row lock on `install` before anything is gathered, so two crons that
+fire at once produce one event rather than two — and the second does not find the counters
+already drained. A rollup that fails to send hands the day and the counters back, so tomorrow's
+run is not suppressed by a send that never happened.
+
#### The install
| Property | What it is |
@@ -79,7 +87,7 @@ Each is only whether the key is set. `cap_context_dev` is whether an `AppSetting
| `tools_per_session_mean` | Tool calls divided by sessions that made one |
| `tasks_claimed` / `tasks_completed` / `tasks_retired` | `AgentTask` counts keyed by `kind` |
| `task_attempts_mean` / `task_attempts_max` | Attempts per kind |
-| `budget_exhausted` | Sessions that stopped because the research budget ran out |
+| `budget_exhausted` | Sessions that stopped because the research budget ran out. Once per session, not once per blocked tool call |
| `recheck_scheduled` | `recheck` tasks queued in the window |
| `recheck_interval_days` | Their intervals, in day bands |
| `agent_conversations` | How many `AgentConversation` rows exist |
@@ -136,6 +144,23 @@ job is what sends it.
They carry no properties of their own beyond the common ones — version, days since install,
whether this is Vercel.
+`google_oauth_configured` is the one step with no row to read a time off: two environment
+variables leave no timestamp behind. It is stamped from the first Google `account` row when
+one exists — configuration must have come before the account did — and otherwise from the
+moment the sweep first saw the variables set. That sweep runs on every API boot, not only on
+the cron, so an install that arrives configured is stamped on its first boot.
+
+`first_fact_applied` is the earliest `decidedAt` of any fact a human accepted, or the earliest
+`observedAt` of any fact the agent applied itself, whichever came first. Facts that were
+applied and later superseded still count — being replaced later does not make the first
+application not have happened.
+
+A step is only recorded as reached once the event has actually left, so a failed send is tried
+again on the next sweep rather than being consumed and lost forever. The cost of that ordering
+is that a crash between the send and the write — or two processes sweeping at the same instant
+— can repeat a step. A one-shot event that arrives twice is a rounding error in a funnel; one
+that never arrives cannot be recovered. Nothing is recorded at all while telemetry is off.
+
### Errors
Error **class** and where it came from. Never a message, never a stack trace, never a payload:
@@ -178,7 +203,7 @@ actually drops it. See `adrs/telemetry.md`.
| `packages/telemetry` | The only place `posthog-node` is imported. Allowlist, install accessor, event builders |
| `install` table | The UUID, the version, and when the last rollup went. One row, made by the migration |
| `telemetryMilestone` table | Which funnel steps have fired |
-| `telemetryCounter` table | The two runtime numbers no other row records, drained by each rollup |
+| `telemetryCounter` table | The one runtime number no other row records — `budget_exhausted` — drained by each rollup and put back if the send fails |
| `apps/api/src/telemetry` | The daily rollup, the funnel sweep, the cron route |
| `apps/agent/agent/hooks/telemetry.ts` | Tool, turn and session failures |
diff --git a/packages/db/prisma/migrations/20260805160000_telemetry_install/migration.sql b/packages/db/prisma/migrations/20260805160000_telemetry_install/migration.sql
index a05a0c74..11cd9d80 100644
--- a/packages/db/prisma/migrations/20260805160000_telemetry_install/migration.sql
+++ b/packages/db/prisma/migrations/20260805160000_telemetry_install/migration.sql
@@ -19,15 +19,15 @@ CREATE TABLE "install" (
"version" TEXT NOT NULL,
"lastRollupAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "install_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "install_uuid_key" ON "install"("uuid");
-INSERT INTO "install" ("id", "uuid", "version")
-VALUES ('install', gen_random_uuid()::text, 'unknown');
+INSERT INTO "install" ("id", "uuid", "version", "updatedAt")
+VALUES ('install', gen_random_uuid()::text, 'unknown', CURRENT_TIMESTAMP);
-- The setup funnel is one-shot: each step fires once per install, ever. A
-- boolean column read and then written races between the API and the agent;
@@ -39,17 +39,20 @@ CREATE TABLE "telemetryMilestone" (
CONSTRAINT "telemetryMilestone_pkey" PRIMARY KEY ("step")
);
--- Counters for the two things the daily rollup wants that leave no other row:
--- a session that stopped because its research budget ran out, and a tool that
--- returned an error. Everything else the rollup reports is already in the
--- schema and is counted there.
+-- Counters for what the daily rollup wants that leaves no other row: today
+-- that is a session that stopped because its research budget ran out, and
+-- nothing else. Everything else the rollup reports is already in the schema
+-- and is counted there.
--
--- Drained with UPDATE … SET count = 0 … RETURNING, so an increment landing
--- mid-drain is counted tomorrow rather than lost.
+-- Drained with DELETE … RETURNING and recreated by the next `upsert`, so a row
+-- holds only what has arrived since the last rollup. An increment landing
+-- mid-drain waits on the row lock and then inserts a fresh row, so it is
+-- counted tomorrow rather than lost. A rollup that fails to send puts the
+-- counts back.
CREATE TABLE "telemetryCounter" (
"name" TEXT NOT NULL,
"count" INTEGER NOT NULL DEFAULT 0,
- "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "telemetryCounter_pkey" PRIMARY KEY ("name")
);
diff --git a/packages/telemetry/src/client.ts b/packages/telemetry/src/client.ts
index 1775dc1b..634c476c 100644
--- a/packages/telemetry/src/client.ts
+++ b/packages/telemetry/src/client.ts
@@ -24,6 +24,8 @@ let client: PostHog | null = null;
let built = false;
+let failures = 0;
+
function posthog(): PostHog | null {
if (built) return client;
built = true;
@@ -47,6 +49,7 @@ function posthog(): PostHog | null {
}
client.on("error", (error: unknown) => {
+ failures += 1;
debug(
`PostHog could not send: ${
error instanceof Error ? error.message : String(error)
@@ -68,6 +71,7 @@ function posthog(): PostHog | null {
export function resetTelemetryClient(): void {
client = null;
built = false;
+ failures = 0;
}
async function payload(
@@ -103,8 +107,8 @@ export async function captureNow(
event: string,
properties: Properties = {},
at?: Date,
-): Promise<void> {
- await send(event, properties, true, at);
+): Promise<boolean> {
+ return send(event, properties, true, at);
}
async function send(
@@ -112,15 +116,15 @@ async function send(
properties: Properties,
immediate = false,
at?: Date,
-): Promise<void> {
+): Promise<boolean> {
try {
- if (telemetryDisabled()) return;
+ if (telemetryDisabled()) return false;
const posted = posthog();
- if (!posted) return;
+ if (!posted) return false;
const message = await payload(properties);
- if (!message) return;
+ if (!message) return false;
const full = {
...message,
@@ -129,17 +133,22 @@ async function send(
} as Parameters<PostHog["capture"]>[0];
if (immediate) {
+ const before = failures;
await posted.captureImmediate(full);
- return;
+
+ return failures === before;
}
posted.capture(full);
+ return true;
} catch (error) {
debug(
`Telemetry could not capture ${event}: ${
error instanceof Error ? error.message : String(error)
}`,
);
+
+ return false;
}
}
diff --git a/packages/telemetry/src/events.ts b/packages/telemetry/src/events.ts
index 2fa69224..e64daa14 100644
--- a/packages/telemetry/src/events.ts
+++ b/packages/telemetry/src/events.ts
@@ -8,6 +8,7 @@ import {
permittedTool,
} from "./allowlist";
import { capture, captureNow } from "./client";
+import { telemetryDisabled } from "./disabled";
import { type Milestone, reachMilestone } from "./install";
export const INSTALL_DAILY = "install_daily";
@@ -20,15 +21,18 @@ export const API_ERROR = "api_error";
export const MODEL_ERROR = "model_error";
-export async function installDaily(properties: Properties): Promise<void> {
- await captureNow(INSTALL_DAILY, properties);
+export async function installDaily(properties: Properties): Promise<boolean> {
+ return captureNow(INSTALL_DAILY, properties);
}
export async function milestone(step: Milestone, at?: Date): Promise<boolean> {
- const first = await reachMilestone(step);
- if (!first) return false;
+ if (telemetryDisabled()) return false;
+
+ const sent = await captureNow(step, {}, at);
+ if (!sent) return false;
+
+ await reachMilestone(step);
- await captureNow(step, {}, at);
return true;
}
diff --git a/packages/telemetry/src/index.ts b/packages/telemetry/src/index.ts
index fdff4d06..6238c169 100644
--- a/packages/telemetry/src/index.ts
+++ b/packages/telemetry/src/index.ts
@@ -47,6 +47,7 @@ export {
export {
bumpCounter,
COUNTERS,
+ claimRollup,
daysSince,
drainCounters,
forgetInstall,
@@ -54,11 +55,13 @@ export {
type Install,
MILESTONES,
type Milestone,
- markRollup,
+ type RollupClaim,
reachedMilestones,
reachMilestone,
readInstall,
+ releaseRollup,
+ restoreCounters,
sameUtcDay,
syncVersion,
} from "./install";
-export { commitSha, crmVersion, UNKNOWN_VERSION } from "./version";
+export { commitSha, crmVersion } from "./version";
diff --git a/packages/telemetry/src/install.ts b/packages/telemetry/src/install.ts
index f1bfb166..0c8757b4 100644
--- a/packages/telemetry/src/install.ts
+++ b/packages/telemetry/src/install.ts
@@ -21,8 +21,13 @@ const SELECT = {
let cached: Install | null = null;
+const MISSING_FOR_MS = 30_000;
+
+let missingSince = 0;
+
export async function readInstall(): Promise<Install | null> {
if (cached) return cached;
+ if (missingSince && Date.now() - missingSince < MISSING_FOR_MS) return null;
try {
const row = await db.install.findUnique({
@@ -31,14 +36,18 @@ export async function readInstall(): Promise<Install | null> {
});
if (row) cached = row;
+ missingSince = row ? 0 : Date.now();
+
return row;
} catch {
+ missingSince = Date.now();
return null;
}
}
export function forgetInstall(): void {
cached = null;
+ missingSince = 0;
}
export async function syncVersion(
@@ -54,6 +63,8 @@ export async function syncVersion(
});
cached = row;
+ missingSince = 0;
+
return row;
} catch {
return readInstall();
@@ -134,15 +145,62 @@ export async function drainCounters(): Promise<Record<string, number>> {
}
}
-export async function markRollup(at: Date): Promise<void> {
+export async function restoreCounters(
+ counts: Record<string, number>,
+): Promise<void> {
+ for (const [name, count] of Object.entries(counts)) {
+ if (count > 0) await bumpCounter(name, count);
+ }
+}
+
+export type RollupRefusal = "no install row" | "already sent today" | "failed";
+
+export type RollupClaim =
+ | { claimed: true; previous: Date | null }
+ | { claimed: false; reason: RollupRefusal };
+
+export async function claimRollup(
+ at: Date,
+ force = false,
+): Promise<RollupClaim> {
try {
- const row = await db.install.update({
+ return await db.$transaction(async (tx): Promise<RollupClaim> => {
+ const locked = await tx.$queryRaw<{ lastRollupAt: Date | null }[]>`
+ SELECT "lastRollupAt"
+ FROM "install"
+ WHERE "id" = ${INSTALL_ID}
+ FOR UPDATE;
+ `;
+
+ if (locked.length === 0) {
+ return { claimed: false, reason: "no install row" };
+ }
+
+ const previous = locked[0]?.lastRollupAt ?? null;
+ if (!force && sameUtcDay(previous, at)) {
+ return { claimed: false, reason: "already sent today" };
+ }
+
+ cached = await tx.install.update({
+ where: { id: INSTALL_ID },
+ data: { lastRollupAt: at },
+ select: SELECT,
+ });
+
+ return { claimed: true, previous };
+ });
+ } catch {
+ return { claimed: false, reason: "failed" };
+ }
+}
+
+export async function releaseRollup(previous: Date | null): Promise<void> {
+ try {
+ cached = await db.install.update({
where: { id: INSTALL_ID },
- data: { lastRollupAt: at },
+ data: { lastRollupAt: previous },
select: SELECT,
});
-
- cached = row;
} catch {}
}
diff --git a/packages/telemetry/src/version.ts b/packages/telemetry/src/version.ts
index 0c0269fb..fab8eba1 100644
--- a/packages/telemetry/src/version.ts
+++ b/packages/telemetry/src/version.ts
@@ -2,8 +2,6 @@ import { readFileSync } from "node:fs";
import { join } from "node:path";
import { findWorkspaceRoot } from "@crm/env";
-export const UNKNOWN_VERSION = "unknown";
-
export function crmVersion(from = process.cwd()): string | null {
const root = findWorkspaceRoot(from);
if (!root) return null;
diff --git a/packages/telemetry/test/client.integration.spec.ts b/packages/telemetry/test/client.integration.spec.ts
index 36ea7a03..6a481fe1 100644
--- a/packages/telemetry/test/client.integration.spec.ts
+++ b/packages/telemetry/test/client.integration.spec.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
+import { db } from "@crm/db";
import { captureNow, POSTHOG_HOST, resetTelemetryClient } from "../src/client";
+import { milestone } from "../src/events";
import { forgetInstall, readInstall } from "../src/install";
const real = {
@@ -104,15 +106,22 @@ describe("capture", () => {
const { properties } = eventOf(calls[0]?.body);
expect(properties.$ip).toBeNull();
- expect(properties.$geoip_disable ?? true).toBeTruthy();
+ expect(properties.$geoip_disable).toBe(true);
+ });
+
+ it("reports a delivered event", async () => {
+ expect(await captureNow("install_daily", { crm_version: "1.0.0" })).toBe(
+ true,
+ );
});
it("makes no network call at all when CRM_TELEMETRY_DISABLED is set", async () => {
process.env.CRM_TELEMETRY_DISABLED = "1";
resetTelemetryClient();
- await captureNow("install_daily", { crm_version: "1.0.0" });
-
+ expect(await captureNow("install_daily", { crm_version: "1.0.0" })).toBe(
+ false,
+ );
expect(calls.length).toBe(0);
});
@@ -120,8 +129,9 @@ describe("capture", () => {
process.env.DO_NOT_TRACK = "1";
resetTelemetryClient();
- await captureNow("install_daily", { crm_version: "1.0.0" });
-
+ expect(await captureNow("install_daily", { crm_version: "1.0.0" })).toBe(
+ false,
+ );
expect(calls.length).toBe(0);
});
@@ -129,19 +139,74 @@ describe("capture", () => {
process.env.NODE_ENV = "test";
resetTelemetryClient();
- await captureNow("install_daily", { crm_version: "1.0.0" });
-
+ expect(await captureNow("install_daily", { crm_version: "1.0.0" })).toBe(
+ false,
+ );
expect(calls.length).toBe(0);
});
- it("stays silent when the host refuses the send", async () => {
+ it("stays silent but reports the failure when the host refuses the send", async () => {
+ globalThis.fetch = (async () => {
+ throw new Error("network is down");
+ }) as typeof fetch;
+
+ expect(await captureNow("install_daily", { crm_version: "1.0.0" })).toBe(
+ false,
+ );
+ });
+});
+
+describe("milestone", () => {
+ const step = "first_sign_in" as const;
+
+ let existing: { step: string; reachedAt: Date } | null = null;
+
+ beforeEach(async () => {
+ existing = await db.telemetryMilestone.findUnique({ where: { step } });
+ await db.telemetryMilestone.deleteMany({ where: { step } });
+ });
+
+ afterEach(async () => {
+ await db.telemetryMilestone.deleteMany({ where: { step } });
+ if (existing) await db.telemetryMilestone.create({ data: existing });
+ });
+
+ it("records the step once the event has left", async () => {
+ expect(await milestone(step)).toBe(true);
+ expect(await db.telemetryMilestone.count({ where: { step } })).toBe(1);
+ });
+
+ it("leaves the step unreached when the send fails", async () => {
+ globalThis.fetch = (async () => {
+ throw new Error("network is down");
+ }) as typeof fetch;
+
+ expect(await milestone(step)).toBe(false);
+ expect(await db.telemetryMilestone.count({ where: { step } })).toBe(0);
+ });
+
+ it("sends the step again on the attempt after a failed send", async () => {
globalThis.fetch = (async () => {
throw new Error("network is down");
}) as typeof fetch;
- expect(
- captureNow("install_daily", { crm_version: "1.0.0" }),
- ).resolves.toBeUndefined();
+ expect(await milestone(step)).toBe(false);
+
+ stubFetch();
+ resetTelemetryClient();
+
+ expect(await milestone(step)).toBe(true);
+ expect(eventOf(calls[0]?.body).event).toBe(step);
+ expect(await db.telemetryMilestone.count({ where: { step } })).toBe(1);
+ });
+
+ it("leaves the step unreached when telemetry is off", async () => {
+ process.env.CRM_TELEMETRY_DISABLED = "1";
+ resetTelemetryClient();
+
+ expect(await milestone(step)).toBe(false);
+ expect(await db.telemetryMilestone.count({ where: { step } })).toBe(0);
+ expect(calls.length).toBe(0);
});
});
diff --git a/packages/telemetry/test/install.integration.spec.ts b/packages/telemetry/test/install.integration.spec.ts
index 2c1bffa2..75f63b40 100644
--- a/packages/telemetry/test/install.integration.spec.ts
+++ b/packages/telemetry/test/install.integration.spec.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "bun:test";
+import { afterEach, describe, expect, it } from "bun:test";
import { join } from "node:path";
import { db } from "@crm/db";
import {
@@ -7,6 +7,7 @@ import {
INSTALL_ID,
reachMilestone,
readInstall,
+ restoreCounters,
syncVersion,
} from "../src/install";
@@ -66,31 +67,39 @@ describe("the install row", () => {
it("keeps the UUID when a boot writes a new version", async () => {
const before = await readInstall();
- const updated = await syncVersion("9.9.9-test");
- expect(updated?.version).toBe("9.9.9-test");
- expect(updated?.uuid).toBe(before?.uuid as string);
-
- await syncVersion(before?.version ?? "unknown");
+ try {
+ const updated = await syncVersion("9.9.9-test");
+ expect(updated?.version).toBe("9.9.9-test");
+ expect(updated?.uuid).toBe(before?.uuid as string);
+ } finally {
+ await syncVersion(before?.version ?? "unknown");
+ }
});
});
describe("milestones", () => {
const step = "first_fact_applied" as const;
+ afterEach(async () => {
+ await db.telemetryMilestone.deleteMany({ where: { step } });
+ });
+
it("reports the first arrival and nothing after it", async () => {
await db.telemetryMilestone.deleteMany({ where: { step } });
expect(await reachMilestone(step)).toBe(true);
expect(await reachMilestone(step)).toBe(false);
expect(await reachMilestone(step)).toBe(false);
-
- await db.telemetryMilestone.deleteMany({ where: { step } });
});
});
describe("counters", () => {
const name = "budget_exhausted";
+ afterEach(async () => {
+ await db.telemetryCounter.deleteMany({ where: { name } });
+ });
+
it("adds up and then drains to nothing", async () => {
await db.telemetryCounter.deleteMany({ where: { name } });
@@ -98,9 +107,17 @@ describe("counters", () => {
await bumpCounter(name);
await bumpCounter(name, 3);
+ expect((await drainCounters())[name]).toBe(5);
+ expect(await drainCounters()).not.toHaveProperty(name);
+ });
+
+ it("puts back what a rollup could not send", async () => {
+ await db.telemetryCounter.deleteMany({ where: { name } });
+
+ await bumpCounter(name, 2);
const drained = await drainCounters();
- expect(drained[name]).toBe(5);
- expect(await drainCounters()).toEqual({});
+ await restoreCounters(drained);
+ expect((await drainCounters())[name]).toBe(2);
});
});