peppa/packages/core/src/bugsink-errors.ts

415 lines
18 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-218: production errors from Bugsink inside Peppa — a summary per Bugsink project, a
// filtered list and an error card, read from Bugsink's REST API on the server (the browser never
// talks to Bugsink). Answers are cached for CACHE_MS; when Bugsink fails, the last answer is
// served with `stale`, or empty data with `down` — a page never breaks because of Bugsink.
// Access: the superadmin sees every Bugsink project, anybody else — the Bugsink projects of
// their own Peppa projects (`error_sources`). See openspec/changes/pep-218-bugsink-errors/design.md.
import {
bugsinkFromEnv,
eventTags,
stackFrames,
type BugsinkClient,
type BugsinkIssueJson,
type BugsinkProjectJson,
type IssueState,
type StackFrame,
} from "@peppa/bugsink";
import { errorSources, incidents, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { m as tr } from "@peppa/shared/i18n";
import { inArray, isNull, and, eq } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { isSuperadmin } from "./monitor.ts";
import { getUiMode } from "./ui-mode.ts";
import { projectForUser, userProjectIds } from "./users.ts";
import type { User } from "./users.ts";
export const ERRORS_CACHE_MS = 45_000;
const DAY_MS = 24 * 3600_000;
const HOUR_MS = 3600_000;
const TOP_MAX = 10;
const EVENTS_MAX = 10;
/** Tag keys that identify a user of the product (SDKs send no PII, so usually absent). */
const USER_TAGS = ["user", "user.id", "user.email", "user.username", "user.ip_address"];
// ---------------------------------------------------------------- cache
interface CacheEntry {
at: number;
value: unknown;
}
const g = globalThis as unknown as { __peppaBugsinkCache?: Map<string, CacheEntry> };
const cache = (g.__peppaBugsinkCache ??= new Map());
export interface Fetched<T> {
value: T;
/** Bugsink failed now; `value` is the last good answer (or empty). */
down: boolean;
/** When `value` was fetched (null — never). */
at: Date | null;
}
async function cached<T>(client: BugsinkClient, key: string, empty: T, load: () => Promise<T>, now = Date.now()): Promise<Fetched<T>> {
const k = `${client.publicUrl}\u0000${key}`;
const hit = cache.get(k);
if (hit && now - hit.at < ERRORS_CACHE_MS) return { value: hit.value as T, down: false, at: new Date(hit.at) };
try {
const value = await load();
cache.set(k, { at: now, value });
if (cache.size > 2000) cache.delete(cache.keys().next().value!);
return { value, down: false, at: new Date(now) };
} catch {
return hit ? { value: hit.value as T, down: true, at: new Date(hit.at) } : { value: empty, down: true, at: null };
}
}
/** After an action the next read goes to Bugsink. */
export function clearErrorsCache(): void {
cache.clear();
}
function clientOr(client: BugsinkClient | null | undefined): BugsinkClient | null {
return client === undefined ? bugsinkFromEnv() : client;
}
// ---------------------------------------------------------------- scope
/** A Bugsink project the viewer may see, with the Peppa project it feeds (if connected). */
export interface ErrorProject {
bugsinkId: number;
name: string;
projectId: number | null;
projectKey: string | null;
kind: "web" | "api" | null;
}
export interface ErrorScope {
superadmin: boolean;
/** «Инженер» or superadmin: stack, paths, tags and releases are shown. */
tech: boolean;
projects: ErrorProject[];
down: boolean;
}
export interface ErrorsOptions {
/** Default: the client from env; null — Bugsink isn't configured. */
client?: BugsinkClient | null;
now?: Date;
}
/**
* The Bugsink projects `user` may see. With `projectId` — only that Peppa project's sources
* (and «not found» without access to it).
*/
export async function errorScope(db: Db, user: Pick<User, "id" | "login">, o: ErrorsOptions & { projectId?: number } = {}): Promise<ErrorScope> {
const superadmin = await isSuperadmin(db, user);
const tech = superadmin || (await getUiMode(db, user.id)) === "engineer";
if (o.projectId != null) await projectForUser(db, user.id, o.projectId);
const ids = o.projectId != null ? [o.projectId] : superadmin ? null : await userProjectIds(db, user.id);
const sources = await db
.select({ bugsinkId: errorSources.bugsinkProjectId, kind: errorSources.kind, projectId: projects.id, key: projects.key })
.from(errorSources)
.innerJoin(projects, eq(projects.id, errorSources.projectId))
.where(and(ids ? inArray(projects.id, ids.length ? ids : [-1]) : undefined, isNull(projects.deletedAt)));
const client = clientOr(o.client);
const listed = client ? await cached<BugsinkProjectJson[]>(client, "projects", [], () => client.listProjects(), o.now?.getTime()) : null;
const names = new Map((listed?.value ?? []).map((p) => [p.id, p.name]));
const bySource = new Map(sources.map((s) => [s.bugsinkId, s]));
const out: ErrorProject[] = sources.map((s) => ({ bugsinkId: s.bugsinkId, name: names.get(s.bugsinkId) ?? `${s.key}-${s.kind}`, projectId: s.projectId, projectKey: s.key, kind: s.kind }));
if (superadmin && o.projectId == null) {
for (const p of listed?.value ?? []) if (!bySource.has(p.id)) out.push({ bugsinkId: p.id, name: p.name, projectId: null, projectKey: null, kind: null });
}
out.sort((a, b) => a.name.localeCompare(b.name));
return { superadmin, tech, projects: out, down: listed?.down ?? false };
}
// ---------------------------------------------------------------- rows
export type ErrorState = "unresolved" | "resolved" | "muted";
export interface ErrorRow {
id: string;
friendlyId: string | null;
title: string;
/** Where in the code (from Peppa's incident, else Bugsink's transaction). */
culprit: string | null;
events: number;
firstSeen: Date;
lastSeen: Date;
release: string | null;
state: ErrorState;
bugsinkId: number;
bugsinkName: string;
projectKey: string | null;
incidentId: number | null;
taskKey: string | null;
}
function stateOf(i: BugsinkIssueJson): ErrorState {
return i.is_resolved ? "resolved" : i.is_muted ? "muted" : "unresolved";
}
function titleOf(i: BugsinkIssueJson): string {
return i.title ?? (i.calculated_value ? `${i.calculated_type}: ${i.calculated_value}` : i.calculated_type);
}
async function toRows(db: Db, issues: BugsinkIssueJson[], scope: ErrorScope): Promise<ErrorRow[]> {
const ids = issues.map((i) => i.id);
const known = ids.length
? await db
.select({ issueId: incidents.bugsinkIssueId, id: incidents.id, culprit: incidents.culprit, number: tasks.number, key: projects.key })
.from(incidents)
.leftJoin(tasks, eq(tasks.id, incidents.taskId))
.leftJoin(projects, eq(projects.id, tasks.projectId))
.where(inArray(incidents.bugsinkIssueId, ids))
: [];
const byIssue = new Map(known.map((k) => [k.issueId, k]));
const byProject = new Map(scope.projects.map((p) => [p.bugsinkId, p]));
return issues.map((i) => {
const k = byIssue.get(i.id);
const p = byProject.get(Number(i.project));
return {
id: i.id,
friendlyId: i.friendly_id ?? null,
title: titleOf(i),
culprit: k?.culprit ?? (i.transaction || null),
events: i.digested_event_count,
firstSeen: new Date(i.first_seen),
lastSeen: new Date(i.last_seen),
release: (i.events_at ?? []).filter(Boolean).at(-1) ?? null,
state: stateOf(i),
bugsinkId: Number(i.project),
bugsinkName: p?.name ?? `#${i.project}`,
projectKey: p?.projectKey ?? null,
incidentId: k?.id ?? null,
taskKey: k?.number != null && k.key ? formatTaskKey(k.key, k.number) : null,
};
});
}
// ---------------------------------------------------------------- list
export interface ErrorFilter {
/** A Bugsink project id (must be in scope). */
bugsink?: number;
state?: ErrorState | "all";
environment?: string;
release?: string;
q?: string;
sort?: "last_seen" | "digested_event_count";
cursor?: string;
}
export interface ErrorList {
rows: ErrorRow[];
next: string | null;
down: boolean;
at: Date | null;
}
const STATE_API: Record<ErrorState | "all", IssueState> = { unresolved: "open", resolved: "resolved", muted: "muted", all: "all" };
function quoteTag(k: string, v: string): string {
return /[\s"]/.test(v) ? `${k}:"${v.replace(/"/g, "")}"` : `${k}:${v}`;
}
export function errorQuery(f: ErrorFilter): string {
return [f.q?.trim(), f.environment ? quoteTag("environment", f.environment) : null, f.release ? quoteTag("release", f.release) : null].filter(Boolean).join(" ");
}
/** Errors in scope matching the filter, newest (or most frequent) first. */
export async function listErrors(db: Db, scope: ErrorScope, f: ErrorFilter = {}, o: ErrorsOptions = {}): Promise<ErrorList> {
const client = clientOr(o.client);
if (!client) return { rows: [], next: null, down: true, at: null };
const state = STATE_API[f.state ?? "unresolved"];
const q = errorQuery(f);
const sort = f.sort ?? "last_seen";
const now = o.now?.getTime();
// One cross-project query for the superadmin; otherwise one per Bugsink project in scope.
const targets =
f.bugsink != null ? scope.projects.filter((p) => p.bugsinkId === f.bugsink).map((p) => p.bugsinkId) : scope.superadmin && scope.projects.some((p) => p.projectId == null) ? [null] : scope.projects.map((p) => p.bugsinkId);
if (!targets.length) return { rows: [], next: null, down: false, at: null };
const pages = await Promise.all(
targets.map((project) =>
cached(client, `issues:${project ?? "*"}:${state}:${q}:${sort}:${f.cursor ?? ""}`, { results: [] as BugsinkIssueJson[], next: null as string | null }, () =>
client.searchIssues({ project: project ?? undefined, state, q, sort, order: "desc", cursor: targets.length === 1 ? f.cursor : undefined }),
now),
),
);
const allowed = new Set(scope.projects.map((p) => p.bugsinkId));
const issues = pages
.flatMap((p) => p.value.results)
.filter((i) => allowed.has(Number(i.project)))
.sort((a, b) => (sort === "digested_event_count" ? b.digested_event_count - a.digested_event_count : b.last_seen.localeCompare(a.last_seen)));
return {
rows: await toRows(db, issues, scope),
next: targets.length === 1 ? pages[0]!.value.next : null,
down: pages.some((p) => p.down),
at: pages.map((p) => p.at).filter((d): d is Date => !!d).sort((a, b) => a.getTime() - b.getTime())[0] ?? null,
};
}
// ---------------------------------------------------------------- overview
export interface ErrorProjectSummary extends ErrorProject {
unresolved: number;
/** The first page was full: «≥ unresolved». */
more: boolean;
newDay: number;
lastHour: number;
/** Mean events per hour over the previous day. */
dayAvg: number;
growing: boolean;
}
export interface ErrorsOverview {
projects: ErrorProjectSummary[];
/** Unresolved errors: seen within a day first, then by frequency. */
top: ErrorRow[];
down: boolean;
at: Date | null;
}
/** Growing: the last hour has ≥ 3 events and more than twice the previous day's hourly mean. */
export function isGrowing(lastHour: number, dayAvg: number): boolean {
return lastHour >= 3 && lastHour > 2 * dayAvg;
}
export async function errorsOverview(db: Db, scope: ErrorScope, o: ErrorsOptions = {}): Promise<ErrorsOverview> {
const client = clientOr(o.client);
if (!client) return { projects: [], top: [], down: true, at: null };
const now = o.now ?? new Date();
const end = new Date(Math.floor(now.getTime() / HOUR_MS) * HOUR_MS + HOUR_MS);
const start = new Date(end.getTime() - 26 * HOUR_MS);
const per = await Promise.all(
scope.projects.map(async (p) => {
const [issues, counts] = await Promise.all([
cached(client, `issues:${p.bugsinkId}:open::last_seen:`, { results: [] as BugsinkIssueJson[], next: null as string | null }, () =>
client.searchIssues({ project: p.bugsinkId, state: "open", sort: "last_seen", order: "desc" }),
now.getTime()),
cached(client, `counts:${p.bugsinkId}:${end.toISOString()}`, [] as number[], async () => (await client.eventCounts({ project: p.bugsinkId }, start, end)).buckets.map((b) => b.count), now.getTime()),
]);
const b = counts.value;
// The current hour is incomplete: «last hour» is the larger of it and the last full one.
const lastHour = b.length ? Math.max(b.at(-1)!, b.at(-2) ?? 0) : 0;
const prev = b.slice(0, -2);
const dayAvg = prev.length ? prev.reduce((s, n) => s + n, 0) / prev.length : 0;
const list = issues.value.results;
const summary: ErrorProjectSummary = {
...p,
unresolved: list.length,
more: issues.value.next != null,
newDay: list.filter((i) => now.getTime() - Date.parse(i.first_seen) < DAY_MS).length,
lastHour,
dayAvg: Math.round(dayAvg * 10) / 10,
growing: isGrowing(lastHour, dayAvg),
};
return { summary, list, down: issues.down || counts.down, at: issues.at };
}),
);
const fresh = (i: BugsinkIssueJson) => now.getTime() - Date.parse(i.last_seen) < DAY_MS;
const top = per
.flatMap((x) => x.list)
.sort((a, b) => Number(fresh(b)) - Number(fresh(a)) || b.digested_event_count - a.digested_event_count || b.last_seen.localeCompare(a.last_seen))
.slice(0, TOP_MAX);
const projectsOut = per.map((x) => x.summary).sort((a, b) => Number(b.growing) - Number(a.growing) || Number(b.unresolved > 0) - Number(a.unresolved > 0) || b.newDay - a.newDay || a.name.localeCompare(b.name));
return {
projects: projectsOut,
top: await toRows(db, top, scope),
down: scope.down || per.some((x) => x.down),
at: per.map((x) => x.at).filter((d): d is Date => !!d).sort((a, b) => a.getTime() - b.getTime())[0] ?? null,
};
}
// ---------------------------------------------------------------- card
export interface ErrorEventRow {
id: string;
at: Date;
}
export interface ErrorDetail {
row: ErrorRow;
/** Peppa project the error belongs to (null — a Bugsink project not connected to Peppa). */
projectId: number | null;
frames: StackFrame[];
/** Tags of the latest event (service, where, route…). */
tags: Record<string, string>;
/** All tag values seen on the error, with counts. */
tagCounts: Array<{ key: string; value: string; count: number }>;
environment: string | null;
level: string | null;
url: string | null;
users: number | null;
events: ErrorEventRow[];
bugsinkUrl: string;
down: boolean;
at: Date | null;
}
/** Full error card, or null when the error doesn't exist or is outside the viewer's scope. */
export async function errorDetail(db: Db, scope: ErrorScope, issueId: string, o: ErrorsOptions = {}): Promise<ErrorDetail | null> {
const client = clientOr(o.client);
if (!client) return null;
const now = o.now?.getTime();
const issue = await cached<BugsinkIssueJson | null>(client, `issue:${issueId}`, null, () => client.getIssue(issueId).catch((e) => (e.status === 404 ? null : Promise.reject(e))), now);
const i = issue.value;
if (!i) return null;
const p = scope.projects.find((x) => x.bugsinkId === Number(i.project));
if (!p) return null;
const [events, tags] = await Promise.all([
cached(client, `events:${i.id}`, [] as Array<{ id: string; timestamp: string }>, () => client.listEvents(i.id), now),
cached(client, `tags:${i.id}`, [] as Array<{ key: string; value: string; count: number }>, () => client.issueTags(i.id), now),
]);
const latestId = events.value[0]?.id;
const latest = latestId ? await cached(client, `event:${latestId}`, null, () => client.getEvent(latestId), now) : null;
const e = latest?.value ?? null;
const [row] = await toRows(db, [i], scope);
const userValues = tags.value.filter((t) => USER_TAGS.includes(t.key));
return {
row: row!,
projectId: p.projectId,
frames: stackFrames(e),
tags: eventTags(e),
tagCounts: tags.value.map(({ key, value, count }) => ({ key, value, count })),
environment: e?.data.environment ?? null,
level: e?.data.level ?? null,
url: e?.data.request?.url ?? null,
users: userValues.length ? userValues.length : null,
events: events.value.map((x) => ({ id: x.id, at: new Date(x.timestamp) })).sort((a, b) => b.at.getTime() - a.at.getTime()).slice(0, EVENTS_MAX),
bugsinkUrl: client.issueUrl(i.id),
down: issue.down || events.down || tags.down || !!latest?.down,
at: issue.at,
};
}
/** The client and the error, for an action; «not found» outside the scope. */
export async function errorForAction(db: Db, scope: ErrorScope, issueId: string, o: ErrorsOptions = {}): Promise<{ client: BugsinkClient; issue: BugsinkIssueJson; project: ErrorProject }> {
const client = clientOr(o.client);
if (!client) throw new PeppaError(tr("Учёт ошибок не настроен."));
let issue: BugsinkIssueJson;
try {
issue = await client.getIssue(issueId);
} catch (e) {
if ((e as { status?: number }).status === 404) throw new PeppaError(tr("Не найдено"));
throw new PeppaError(tr("Учёт ошибок не отвечает. Попробуйте через минуту."));
}
const project = scope.projects.find((p) => p.bugsinkId === Number(issue.project));
if (!project) throw new PeppaError(tr("Не найдено"));
return { client, issue, project };
}
/** «Решено» / «Приглушить» / «Вернуть» straight in Bugsink (no Peppa incident involved). */
export async function setErrorState(db: Db, scope: ErrorScope, issueId: string, action: "resolve" | "mute" | "unmute" | "reopen", o: ErrorsOptions = {}): Promise<ErrorState> {
const { client, issue } = await errorForAction(db, scope, issueId, o);
let next: BugsinkIssueJson;
try {
if (action === "resolve" && issue.is_resolved) next = issue;
else next = await (action === "resolve" ? client.resolveIssue(issue.id) : action === "mute" ? client.muteIssue(issue.id) : action === "unmute" ? client.unmuteIssue(issue.id) : client.reopenIssue(issue.id));
} catch {
throw new PeppaError(tr("Учёт ошибок не отвечает. Попробуйте через минуту."));
}
clearErrorsCache();
return stateOf(next);
}