PEP-218: адаптер Bugsink, мок, ядро ошибок (сводка, список, карточка, действия) и тест

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-20 19:58:32 +05:00
parent 32b5acb265
commit acafb97b04
7 changed files with 934 additions and 10 deletions

View File

@ -32,7 +32,84 @@ interface Frame {
module?: string;
function?: string;
lineno?: number;
colno?: number;
in_app?: boolean;
pre_context?: string[];
context_line?: string;
post_context?: string[];
}
/** PEP-218: a stack frame for the error card, innermost first. */
export interface StackFrame {
file: string;
fn: string | null;
line: number | null;
inApp: boolean;
/** Code around the line, when the SDK sent it: [lineNo, text, isTheLine]. */
context: Array<[number | null, string, boolean]>;
}
/** Frames of the last (innermost) exception, innermost frame first, with code context. */
export function stackFrames(e: BugsinkEventJson | null, max = 40): StackFrame[] {
return frames(e)
.slice(0, max)
.map((f) => {
const line = f.lineno ?? null;
const pre = f.pre_context ?? [];
const ctx: StackFrame["context"] = [];
pre.forEach((s, n) => ctx.push([line != null ? line - pre.length + n : null, s, false]));
if (f.context_line != null) ctx.push([line, f.context_line, true]);
(f.post_context ?? []).forEach((s, n) => ctx.push([line != null ? line + 1 + n : null, s, false]));
return { file: f.filename ?? f.abs_path ?? f.module ?? "?", fn: f.function ?? null, line, inApp: f.in_app !== false, context: ctx };
});
}
/** Event tags as a flat record (the SDK sends either an object or [key, value] pairs). */
export function eventTags(e: BugsinkEventJson | null): Record<string, string> {
const t = e?.data.tags;
if (!t) return {};
return Array.isArray(t) ? Object.fromEntries(t.map(([k, v]) => [k, String(v)])) : Object.fromEntries(Object.entries(t).map(([k, v]) => [k, String(v)]));
}
/** A Bugsink project as `GET /projects/` lists it. */
export interface BugsinkProjectJson {
id: number;
name: string;
slug?: string;
digested_event_count?: number;
}
export interface BugsinkEventListJson {
id: string;
event_id?: string;
issue: string;
timestamp: string;
digested_at?: string;
}
export interface BugsinkTagJson {
key: string;
value: string;
count: number;
}
export interface BugsinkCountsJson {
start: string;
end: string;
interval_seconds: number;
buckets: Array<{ timestamp: string; count: number }>;
}
export type IssueState = "all" | "open" | "unresolved" | "resolved" | "muted";
export interface IssueSearch {
project?: number;
state?: IssueState;
/** Title text plus `key:value` tag filters (Bugsink's `q`). */
q?: string;
sort?: "last_seen" | "digested_event_count";
order?: "asc" | "desc";
cursor?: string;
}
/** Event detail: `data` is the Sentry event payload. */
@ -47,6 +124,7 @@ export interface BugsinkEventJson {
platform?: string;
exception?: { values?: Array<{ type?: string; value?: string; stacktrace?: { frames?: Frame[] } }> };
tags?: Record<string, string> | Array<[string, string]>;
request?: { url?: string; method?: string };
};
}
@ -197,6 +275,58 @@ export function createBugsinkClient(c: BugsinkConfig) {
resolveIssue: (issueId: string) => call<BugsinkIssueJson>("POST", `/issues/${issueId}/resolve/`),
// PEP-218: the error browser (endpoints checked against Bugsink 2.6.3, see the change's design.md).
async listProjects(): Promise<BugsinkProjectJson[]> {
const out: BugsinkProjectJson[] = [];
let path: string | null = "/projects/";
for (let n = 0; path && n < 20; n++) {
const r: { next: string | null; results: BugsinkProjectJson[] } = await call("GET", path);
out.push(...r.results);
path = r.next ? r.next.slice(r.next.indexOf("/projects/")) : null;
}
return out;
},
/** One page of issues; `next` is the cursor of the following page. */
async searchIssues(s: IssueSearch): Promise<{ results: BugsinkIssueJson[]; next: string | null }> {
const p = new URLSearchParams();
if (s.project != null) p.set("project", String(s.project));
p.set("state", s.state ?? "all");
if (s.q?.trim()) p.set("q", s.q.trim());
p.set("sort", s.sort ?? "last_seen");
p.set("order", s.order ?? "desc");
if (s.cursor) p.set("cursor", s.cursor);
const r = await call<{ results: BugsinkIssueJson[]; next: string | null }>("GET", `/issues/?${p}`);
return { results: r.results, next: r.next ? new URL(r.next).searchParams.get("cursor") : null };
},
async listEvents(issueId: string): Promise<BugsinkEventListJson[]> {
const r = await call<{ results: BugsinkEventListJson[] }>("GET", `/events/?issue=${encodeURIComponent(issueId)}&order=desc`);
return r.results;
},
getEvent: (eventId: string) => call<BugsinkEventJson>("GET", `/events/${eventId}/`),
async issueTags(issueId: string): Promise<BugsinkTagJson[]> {
const r = await call<{ results: BugsinkTagJson[] }>("GET", `/issues/${encodeURIComponent(issueId)}/tags/`);
return r.results;
},
/** Hourly event counts of a project (or of one issue) between UTC hour boundaries. */
eventCounts(target: { project: number } | { issue: string }, start?: Date, end?: Date): Promise<BugsinkCountsJson> {
const p = new URLSearchParams();
if (start) p.set("start", start.toISOString().replace(/\.\d+Z$/, "Z"));
if (end) p.set("end", end.toISOString().replace(/\.\d+Z$/, "Z"));
const q = p.size ? `?${p}` : "";
return "project" in target
? call<BugsinkCountsJson>("GET", `/projects/${target.project}/event-counts/${q}`)
: call<BugsinkCountsJson>("GET", `/issues/${encodeURIComponent(target.issue)}/event-counts/${q}`);
},
muteIssue: (issueId: string) => call<BugsinkIssueJson>("POST", `/issues/${issueId}/mute/`),
unmuteIssue: (issueId: string) => call<BugsinkIssueJson>("POST", `/issues/${issueId}/unmute/`),
reopenIssue: (issueId: string) => call<BugsinkIssueJson>("POST", `/issues/${issueId}/reopen/`),
/** Points the project's alerts (new / regressed / unmuted) at Peppa's webhook URL. */
async setAlertWebhook(projectId: number, webhookUrl: string): Promise<void> {
if (!c.container) throw new BugsinkError("API Bugsink не умеет настраивать алерты: добавьте Custom webhook вручную");

View File

@ -0,0 +1,414 @@
// 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.slice(0, EVENTS_MAX).map((x) => ({ id: x.id, at: new Date(x.timestamp) })),
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);
}

View File

@ -30,6 +30,7 @@ export * from "./error-report.ts";
export * from "./backup.ts";
export * from "./repo-info.ts";
export * from "./incidents.ts";
export * from "./bugsink-errors.ts";
export * from "./ci.ts";
export * from "./egov.ts";
export * from "./google.ts";

View File

@ -0,0 +1,64 @@
// PEP-218: actions on a Bugsink error from Peppa's error browser (web, MCP). «Завести задачу»
// goes the same way as an error from the webhook (PEP-58): the issue is recorded as an incident
// (`ingestIssue`, idempotent) and the PM's decision «backlog» makes the bug task — a second
// press, or the policy having been faster, returns the task that already exists.
import { issueFromEvent } from "@peppa/bugsink";
import {
clearErrorsCache,
errorForAction,
getIncident,
ingestIssue,
PeppaError,
resolveTask,
setErrorState,
type ErrorScope,
type ErrorsOptions,
type ErrorState,
type TaskRef,
} from "@peppa/core";
import { incidents, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { m } from "@peppa/shared/i18n";
import { eq } from "drizzle-orm";
import { decideIncident, resolveIncident } from "./incidents.ts";
async function taskOf(db: Db, taskId: number | null): Promise<TaskRef | null> {
if (!taskId) return null;
const [t] = await db.select({ key: projects.key, number: tasks.number }).from(tasks).innerJoin(projects, eq(projects.id, tasks.projectId)).where(eq(tasks.id, taskId));
return t ? resolveTask(db, formatTaskKey(t.key, t.number)) : null;
}
/** «Завести задачу»: the bug task of the error (existing or new, in the backlog). */
export async function fileErrorTask(db: Db, scope: ErrorScope, issueId: string, who: string, o: ErrorsOptions = {}): Promise<{ task: TaskRef; created: boolean }> {
const { client, issue, project } = await errorForAction(db, scope, issueId, o);
if (project.projectId == null) throw new PeppaError(m("Этот проект учёта ошибок не подключён ни к одному проекту — задачу завести некуда."));
const event = await client.latestEvent(issue.id).catch(() => null);
const r = await ingestIssue(db, issueFromEvent({ ...issue, url: client.issueUrl(issue.id) }, event, "POLL"));
if (!r) throw new PeppaError(m("Этот проект учёта ошибок не подключён ни к одному проекту — задачу завести некуда."));
const existing = await taskOf(db, r.incident.taskId);
if (existing) return { task: existing, created: false };
try {
const d = await decideIncident(db, r.incident.id, "backlog", who);
clearErrorsCache();
if (d.task) return { task: d.task, created: true };
} catch (e) {
// The policy (or another click) decided first: its task, if it made one, is the answer.
const again = await taskOf(db, (await getIncident(db, r.incident.id)).taskId);
if (again) return { task: again, created: false };
throw e;
}
throw new PeppaError(m("Задачу завести не удалось."));
}
/** «Решено»: through Peppa's incident when there is one (its task gets a note), else in Bugsink. */
export async function resolveError(db: Db, scope: ErrorScope, issueId: string, who: string, o: ErrorsOptions = {}): Promise<ErrorState> {
const { client, issue } = await errorForAction(db, scope, issueId, o);
const [inc] = await db.select().from(incidents).where(eq(incidents.bugsinkIssueId, issue.id));
if (inc && inc.status !== "resolved") {
const r = await resolveIncident(db, inc.id, { who, client });
clearErrorsCache();
if (!r.bugsinkResolved && !issue.is_resolved) throw new PeppaError(m("Учёт ошибок не отвечает. Попробуйте через минуту."));
return "resolved";
}
return setErrorState(db, scope, issueId, "resolve", o);
}

View File

@ -14,6 +14,7 @@ export * from "./monitor.ts";
export * from "./ci.ts";
export * from "./transfer.ts";
export * from "./incidents.ts";
export * from "./bugsink-errors.ts";
export * from "./analyst-chat.ts";
export * from "./message-intent.ts";
export * from "./product-review.ts";

View File

@ -10,6 +10,9 @@ export interface MockFrame {
function: string;
lineno: number;
in_app?: boolean;
pre_context?: string[];
context_line?: string;
post_context?: string[];
}
export interface MockErrorEvent {
@ -20,6 +23,8 @@ export interface MockErrorEvent {
environment?: string;
release?: string;
level?: string;
/** Event tags (service, where, route, user…). */
tags?: Record<string, string>;
}
interface Project {
@ -41,6 +46,7 @@ interface Issue {
lastSeen: string;
count: number;
resolved: boolean;
muted: boolean;
releases: string[];
events: string[];
}
@ -60,6 +66,8 @@ export class MockBugsink {
readonly events = new Map<string, Event>();
/** Alerts the mock tried to send: url, body, HTTP status (or error). */
readonly alerts: Array<{ url: string; body: Record<string, unknown>; status: number | string }> = [];
/** PEP-218: true — every API call answers 500 (Bugsink is down). */
down = false;
private seq = 1;
private server: Server | null = null;
url = "";
@ -119,7 +127,7 @@ export class MockBugsink {
is_resolved_by_next_release: false,
fixed_at: [],
events_at: i.releases,
is_muted: false,
is_muted: i.muted,
unmute_after: null,
unmute_on_volume_based_conditions: [],
};
@ -137,7 +145,7 @@ export class MockBugsink {
let reason: "NEW" | "REGRESSED" | null = null;
const ts = at.toISOString();
if (!issue) {
issue = { id: randomUUID(), friendlyNo: this.seq++, project: projectId, type: e.type, value: e.value, culprit, firstSeen: ts, lastSeen: ts, count: 0, resolved: false, releases: [], events: [] };
issue = { id: randomUUID(), friendlyNo: this.seq++, project: projectId, type: e.type, value: e.value, culprit, firstSeen: ts, lastSeen: ts, count: 0, resolved: false, muted: false, releases: [], events: [] };
this.issues.set(issue.id, issue);
reason = "NEW";
} else if (issue.resolved) {
@ -156,6 +164,7 @@ export class MockBugsink {
environment: e.environment,
release: e.release,
platform: "javascript",
tags: { ...(e.tags ?? {}), ...(e.environment ? { environment: e.environment } : {}), ...(e.release ? { release: e.release } : {}) },
exception: { values: [{ type: e.type, value: e.value, stacktrace: { frames: frames.map((f) => ({ ...f, in_app: f.in_app ?? true, vars: { secret: "mock-local-value" } })) } }] },
},
};
@ -179,7 +188,7 @@ export class MockBugsink {
const event = JSON.parse(lines[item + 1]!) as Record<string, any>;
this.ingested.push({ projectId, event });
const ex = event.exception?.values?.[0] ?? { type: "Error", value: String(event.message ?? "") };
await this.capture(projectId, { type: ex.type, value: ex.value, frames: ex.stacktrace?.frames, environment: event.environment, release: event.release, level: event.level });
await this.capture(projectId, { type: ex.type, value: ex.value, frames: ex.stacktrace?.frames, environment: event.environment, release: event.release, level: event.level, tags: event.tags });
return { status: 200, body: { id: event.event_id } };
}
@ -196,6 +205,7 @@ export class MockBugsink {
}
private handle(method: string, rawUrl: string, auth: string, body: Record<string, unknown>): { status: number; body?: unknown } {
if (this.down) return { status: 500, body: { detail: "mock-bugsink is down" } };
if (auth !== `Bearer ${this.token}`) return { status: 401, body: { detail: "Authentication credentials were not provided." } };
const url = new URL(rawUrl, "http://x");
const path = url.pathname.replace(/^\/api\/canonical\/0/, "");
@ -206,29 +216,71 @@ export class MockBugsink {
this.projects.set(p.id, p);
return { status: 201, body: { id: String(p.id), team: p.team, name: p.name, visibility: "team_members", alert_on_new_issue: true, alert_on_regression: true, alert_on_unmute: true } };
}
if (method === "GET" && path === "/projects/") {
const rows = [...this.projects.values()].sort((a, b) => a.name.localeCompare(b.name));
return { status: 200, body: { next: null, previous: null, results: rows.map((p) => ({ id: p.id, team: p.team, name: p.name, slug: p.name.toLowerCase(), dsn: this.dsn(p), digested_event_count: [...this.issues.values()].filter((i) => i.project === p.id).reduce((n, i) => n + i.count, 0) })) } };
}
if (method === "GET" && (m = /^\/(projects|issues)\/([^/]+)\/event-counts\/$/.exec(path))) {
const issue = m[1] === "issues" ? this.findIssue(m[2]!) : null;
if (m[1] === "issues" && !issue) return { status: 404, body: { detail: "Not found." } };
const end = url.searchParams.get("end") ? new Date(url.searchParams.get("end")!) : new Date(Math.floor(Date.now() / 3600e3) * 3600e3 + 3600e3);
const start = url.searchParams.get("start") ? new Date(url.searchParams.get("start")!) : new Date(end.getTime() - 24 * 3600e3);
if (start.getTime() % 3600e3 || end.getTime() % 3600e3) return { status: 400, body: { detail: "start and end must be UTC hour boundaries" } };
const evs = [...this.events.values()].filter((e) => (issue ? e.issue === issue.id : this.issues.get(e.issue)?.project === Number(m![2])));
const buckets = [];
for (let t = start.getTime(); t < end.getTime(); t += 3600e3) {
buckets.push({ timestamp: new Date(t).toISOString().replace(/\.\d+Z$/, "Z"), count: evs.filter((e) => { const at = Date.parse(e.timestamp); return at >= t && at < t + 3600e3; }).length });
}
return { status: 200, body: { start: start.toISOString(), end: end.toISOString(), interval_seconds: 3600, buckets } };
}
if (method === "GET" && (m = /^\/issues\/([^/]+)\/tags\/$/.exec(path))) {
const i = this.findIssue(m[1]!);
if (!i) return { status: 404, body: { detail: "Not found." } };
const counts = new Map<string, number>();
for (const id of i.events) for (const [k, v] of Object.entries(this.tagsOf(this.events.get(id)!))) counts.set(`${k}\u0000${v}`, (counts.get(`${k}\u0000${v}`) ?? 0) + 1);
const key = url.searchParams.get("key");
const results = [...counts].map(([kv, count], n) => ({ id: n + 1, key: kv.split("\u0000")[0]!, value: kv.split("\u0000")[1]!, count })).filter((r) => !key || r.key === key);
return { status: 200, body: { next: null, previous: null, results } };
}
if (method === "GET" && (m = /^\/projects\/(\d+)\/$/.exec(path))) {
const p = this.projects.get(Number(m[1]));
return p ? { status: 200, body: { id: p.id, team: p.team, name: p.name, slug: p.name.toLowerCase(), dsn: this.dsn(p) } } : { status: 404, body: { detail: "No Project matches the given query." } };
}
if (method === "GET" && path === "/issues/") {
const project = Number(url.searchParams.get("project"));
const rows = [...this.issues.values()].filter((i) => !project || i.project === project).sort((a, b) => b.lastSeen.localeCompare(a.lastSeen));
const state = url.searchParams.get("state") ?? "all";
const inState = (i: Issue) =>
state === "all" || (state === "resolved" && i.resolved) || (state === "unresolved" && !i.resolved) || (state === "muted" && i.muted) || (state === "open" && !i.resolved && !i.muted);
const { text, tags } = parseQ(url.searchParams.get("q") ?? "");
const matches = (i: Issue) =>
(!text || `${i.type}: ${i.value}`.toLowerCase().includes(text.toLowerCase())) &&
tags.every(([k, v]) => i.events.some((id) => this.tagsOf(this.events.get(id)!)[k] === v));
const sort = url.searchParams.get("sort") ?? "last_seen";
const desc = (url.searchParams.get("order") ?? "desc") === "desc";
const rows = [...this.issues.values()]
.filter((i) => (!project || i.project === project) && inState(i) && matches(i))
.sort((a, b) => (desc ? -1 : 1) * (sort === "digested_event_count" ? a.count - b.count : a.lastSeen.localeCompare(b.lastSeen)));
return { status: 200, body: { next: null, previous: null, results: rows.map((i) => this.issueJson(i)) } };
}
if ((m = /^\/issues\/([^/]+)\/(resolve\/)?$/.exec(path))) {
const i = this.issues.get(m[1]!);
if ((m = /^\/issues\/([^/]+)\/(?:(resolve|mute|unmute|reopen)\/)?$/.exec(path))) {
const i = this.findIssue(m[1]!);
if (!i) return { status: 404, body: { detail: "No Issue matches the given query." } };
if (m[2] && method === "POST") {
if (i.resolved) return { status: 400, body: { detail: "Issue is already resolved." } };
i.resolved = true;
if (m[2] === "resolve") {
if (i.resolved) return { status: 400, body: { detail: "Issue is already resolved." } };
i.resolved = true;
i.muted = false;
} else if (m[2] === "mute") i.muted = true;
else if (m[2] === "unmute") i.muted = false;
else i.resolved = false;
}
return { status: 200, body: this.issueJson(i) };
}
if (method === "GET" && path === "/events/") {
const i = this.issues.get(url.searchParams.get("issue") ?? "");
const i = this.findIssue(url.searchParams.get("issue") ?? "");
if (!i) return { status: 404, body: { detail: "Not found." } };
const ids = url.searchParams.get("order") === "asc" ? i.events : [...i.events].reverse();
return { status: 200, body: { next: null, previous: null, results: ids.map((id) => ({ id, issue: i.id, project: i.project })) } };
return { status: 200, body: { next: null, previous: null, results: ids.map((id) => ({ id, event_id: id, issue: i.id, project: i.project, timestamp: this.events.get(id)!.timestamp, digested_at: this.events.get(id)!.timestamp })) } };
}
if (method === "GET" && (m = /^\/events\/([^/]+)\/$/.exec(path))) {
const e = this.events.get(m[1]!);
@ -236,4 +288,33 @@ export class MockBugsink {
}
return { status: 404, body: { detail: `mock-bugsink: no route ${method} ${path}` } };
}
/** By UUID or friendly id (PEP-WEB-8), like Bugsink. */
findIssue(id: string): Issue | undefined {
return this.issues.get(id) ?? [...this.issues.values()].find((i) => this.issueJson(i).friendly_id === id);
}
private tagsOf(e: Event): Record<string, string> {
return (e.data.tags as Record<string, string> | undefined) ?? {};
}
/** A project without the API (tests): same as POST /projects/. */
addProject(name: string): number {
const p: Project = { id: this.seq++, name, team: this.teamId, key: randomUUID().replace(/-/g, "") };
this.projects.set(p.id, p);
return p.id;
}
}
/** Bugsink's `q`: plain title text plus `key:value` tag filters (values may be quoted). */
function parseQ(q: string): { text: string; tags: Array<[string, string]> } {
const tags: Array<[string, string]> = [];
const text = q
.replace(/([\w.-]+):(?:"([^"]*)"|(\S+))/g, (_, k: string, quoted?: string, plain?: string) => {
tags.push([k, quoted ?? plain ?? ""]);
return " ";
})
.replace(/\s+/g, " ")
.trim();
return { text, tags };
}

View File

@ -0,0 +1,233 @@
// PEP-218: Bugsink errors inside Peppa — summary, filtered list, error card, actions, access
// (superadmin: all Bugsink projects; owner: own project's sources), and Bugsink being down.
// Scenario names follow openspec/changes/pep-218-bugsink-errors/specs/error-browser/spec.md.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { core, db, runner, superadmin, teardown } from "./helpers.ts";
import { MockBugsink } from "../src/mock-bugsink.ts";
const { createBugsinkClient } = await import("@peppa/bugsink");
const { users } = await import("@peppa/db");
const { eq } = await import("drizzle-orm");
const bugsink = await new MockBugsink().start();
const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId });
const o = { client };
const HOUR = 3600_000;
const now = Date.now();
const ago = (ms: number) => new Date(now - ms);
let admin: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let other: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
const ids: Record<string, string> = {};
const bp: Record<string, number> = {};
before(async () => {
await superadmin();
const login = (await core.platformAdmins(db)).at(-1)!;
[admin] = await db.select().from(users).where(eq(users.login, login));
owner = await core.upsertUserFromGitea(db, { id: 8101, login: "mock-dik-owner" }, { access_token: "x" });
other = await core.upsertUserFromGitea(db, { id: 8102, login: "mock-pep-owner" }, { access_token: "y" });
const dik = await core.createProject(db, { slug: "dik", key: "DIK", name: "DIK", giteaOwner: "test", workspacePath: "/tmp/mock-dik", ownerId: owner.id });
const pep = await core.createProject(db, { slug: "pepx", key: "PEPX", name: "PEPX", giteaOwner: "test", workspacePath: "/tmp/mock-pepx", ownerId: other.id });
for (const [name, projectId, kind] of [["DIK-web", dik.id, "web"], ["DIK-api", dik.id, "api"], ["PEPX-api", pep.id, "api"]] as const) {
bp[name] = bugsink.addProject(name);
await core.addErrorSource(db, { projectId, kind, bugsinkProjectId: bp[name]!, dsn: "mock" });
}
await core.enableIncidents(db, dik.id);
await core.enableIncidents(db, pep.id);
bp.OTHER = bugsink.addProject("OTHER-web");
const frames = [
{ filename: "app/routes.ts", function: "handle", lineno: 10 },
{ filename: "billing/charge.ts", function: "charge", lineno: 42, pre_context: ["function charge(o) {", " const a = o.amount;"], context_line: " return a.toFixed(2);", post_context: ["}"] },
];
ids.boom = await bugsink.capture(bp["DIK-api"]!, { type: "Error", value: "boom", environment: "prod", release: "r1", frames, tags: { service: "api", where: "POST /pay", route: "/pay", user: "u1" } }, ago(2 * HOUR));
await bugsink.capture(bp["DIK-api"]!, { type: "Error", value: "boom", environment: "prod", release: "r2", frames, tags: { service: "api", where: "POST /pay", route: "/pay", user: "u2" } }, ago(HOUR / 2));
ids.stage = await bugsink.capture(bp["DIK-api"]!, { type: "Error", value: "stage", environment: "staging" }, ago(3 * 24 * HOUR));
ids.old = await bugsink.capture(bp["DIK-web"]!, { type: "Error", value: "old", environment: "prod" }, ago(4 * 24 * HOUR));
await bugsink.capture(bp["DIK-web"]!, { type: "Error", value: "old", environment: "prod" }, ago(4 * 24 * HOUR - 1000));
ids.pep = await bugsink.capture(bp["PEPX-api"]!, { type: "TypeError", value: "x is undefined", environment: "prod" }, ago(5 * HOUR));
// A burst in the current hour of an unconnected project: «растёт».
for (let n = 0; n < 5; n++) ids.burst = await bugsink.capture(bp.OTHER!, { type: "Error", value: "burst", environment: "prod" }, new Date(Math.max(now - n * 1000, Math.floor(now / HOUR) * HOUR)));
bugsink.issues.get(ids.old!)!.resolved = true;
core.clearErrorsCache();
});
after(async () => {
await bugsink.stop();
await teardown();
});
describe("Сводка ошибок для суперадмина", () => {
test("Сводка по проектам", async () => {
const scope = await core.errorScope(db, admin, o);
assert.equal(scope.superadmin, true);
assert.deepEqual(scope.projects.map((p) => p.name), ["DIK-api", "DIK-web", "OTHER-web", "PEPX-api"]);
const ov = await core.errorsOverview(db, scope, o);
assert.equal(ov.down, false);
const dikApi = ov.projects.find((p) => p.name === "DIK-api")!;
assert.equal(dikApi.unresolved, 2);
assert.equal(dikApi.newDay, 1);
assert.equal(dikApi.projectKey, "DIK");
const burst = ov.projects.find((p) => p.name === "OTHER-web")!;
assert.equal(burst.growing, true, JSON.stringify(burst));
assert.equal(ov.projects[0]!.name, "OTHER-web", "growing first");
const titles = ov.top.map((r) => r.title);
assert.ok(titles.includes("Error: boom") && titles.includes("Error: stage"));
assert.ok(!titles.includes("Error: old"), "resolved not in top");
assert.ok(titles.indexOf("Error: boom") < titles.indexOf("Error: stage"), "fresh first");
});
test("Не суперадмин", async () => {
const scope = await core.errorScope(db, owner, o);
assert.equal(scope.superadmin, false);
assert.deepEqual(scope.projects.map((p) => p.name).sort(), ["DIK-api", "DIK-web"]);
});
});
describe("Список ошибок с фильтрами", () => {
test("Фильтр по окружению", async () => {
const scope = await core.errorScope(db, admin, o);
const prod = await core.listErrors(db, scope, { environment: "prod", bugsink: bp["DIK-api"] }, o);
assert.deepEqual(prod.rows.map((r) => r.title), ["Error: boom"]);
const row = prod.rows[0]!;
assert.equal(row.events, 2);
assert.equal(row.release, "r2");
const staging = await core.listErrors(db, scope, { environment: "staging" }, o);
assert.deepEqual(staging.rows.map((r) => r.title), ["Error: stage"]);
const text = await core.listErrors(db, scope, { q: "undefined" }, o);
assert.deepEqual(text.rows.map((r) => r.title), ["TypeError: x is undefined"]);
const rel = await core.listErrors(db, scope, { release: "r1" }, o);
assert.deepEqual(rel.rows.map((r) => r.title), ["Error: boom"]);
});
test("Решённые скрыты по умолчанию", async () => {
const scope = await core.errorScope(db, admin, o);
const open = await core.listErrors(db, scope, {}, o);
assert.ok(!open.rows.some((r) => r.title === "Error: old"));
const resolved = await core.listErrors(db, scope, { state: "resolved" }, o);
assert.deepEqual(resolved.rows.map((r) => r.title), ["Error: old"]);
const byCount = await core.listErrors(db, scope, { sort: "digested_event_count" }, o);
assert.equal(byCount.rows[0]!.title, "Error: burst");
});
});
describe("Карточка ошибки и действия", () => {
test("Стек, теги, события", async () => {
const scope = await core.errorScope(db, admin, o);
const d = (await core.errorDetail(db, scope, ids.boom!, o))!;
assert.equal(d.row.title, "Error: boom");
assert.equal(d.frames[0]!.file, "billing/charge.ts", "innermost first");
assert.deepEqual(d.frames[0]!.context.find((c) => c[2]), [42, " return a.toFixed(2);", true]);
assert.equal(d.frames[0]!.context[0]![0], 40);
assert.equal(d.tags.where, "POST /pay");
assert.equal(d.users, 2);
assert.equal(d.events.length, 2);
assert.match(d.bugsinkUrl, new RegExp(`/issues/issue/${ids.boom}/`));
assert.equal(d.environment, "prod");
// By friendly id too.
assert.equal((await core.errorDetail(db, scope, d.row.friendlyId!, o))?.row.id, ids.boom);
});
test("Завести задачу", async () => {
const scope = await core.errorScope(db, owner, o);
const r = await runner.fileErrorTask(db, scope, ids.boom!, owner.login, o);
assert.equal(r.created, true);
assert.match(r.task.key, /^DIK-\d+$/);
assert.equal(r.task.task.status, "backlog");
assert.match(r.task.task.title, /boom/);
core.clearErrorsCache();
const d = (await core.errorDetail(db, scope, ids.boom!, o))!;
assert.equal(d.row.taskKey, r.task.key);
});
test("Повторное нажатие", async () => {
const scope = await core.errorScope(db, owner, o);
const first = (await core.errorDetail(db, scope, ids.boom!, o))!.row.taskKey;
const r = await runner.fileErrorTask(db, scope, ids.boom!, owner.login, o);
assert.equal(r.created, false);
assert.equal(r.task.key, first);
});
test("Решено", async () => {
const scope = await core.errorScope(db, owner, o);
assert.equal(await runner.resolveError(db, scope, ids.boom!, owner.login, o), "resolved");
assert.equal(bugsink.issues.get(ids.boom!)!.resolved, true);
const inc = (await core.listIncidents(db, (await core.errorScope(db, owner, o)).projects[0]!.projectId!)).find((i) => i.bugsinkIssueId === ids.boom);
assert.equal(inc?.status, "resolved");
const open = await core.listErrors(db, scope, {}, o);
assert.ok(!open.rows.some((r) => r.id === ids.boom));
// Without an incident: straight in Bugsink; «Приглушить» and back.
assert.equal(await core.setErrorState(db, scope, ids.stage!, "mute", o), "muted");
assert.deepEqual((await core.listErrors(db, scope, { state: "muted" }, o)).rows.map((r) => r.id), [ids.stage]);
assert.equal(await core.setErrorState(db, scope, ids.stage!, "unmute", o), "unresolved");
});
test("Не подключённый проект: задачу завести некуда", async () => {
const scope = await core.errorScope(db, admin, o);
await assert.rejects(runner.fileErrorTask(db, scope, ids.burst!, admin.login, o), /некуда/);
});
});
describe("Ошибки своего проекта", () => {
test("Владелец видит свои", async () => {
const dik = (await core.errorScope(db, owner, o)).projects[0]!.projectId!;
const scope = await core.errorScope(db, owner, { ...o, projectId: dik });
const list = await core.listErrors(db, scope, { state: "all" }, o);
assert.deepEqual(new Set(list.rows.map((r) => r.bugsinkName)), new Set(["DIK-api", "DIK-web"]));
// Another owner's project: «not found».
await assert.rejects(core.errorScope(db, other, { ...o, projectId: dik }), /Не найдено/);
});
test("Чужая карточка", async () => {
const scope = await core.errorScope(db, owner, o);
assert.equal(await core.errorDetail(db, scope, ids.pep!, o), null);
await assert.rejects(runner.resolveError(db, scope, ids.pep!, owner.login, o), /Не найдено/);
await assert.rejects(runner.fileErrorTask(db, scope, ids.pep!, owner.login, o), /Не найдено/);
});
test("Продакт без техники", async () => {
assert.equal((await core.errorScope(db, owner, o)).tech, false);
await core.setUiMode(db, owner.id, "engineer");
assert.equal((await core.errorScope(db, owner, o)).tech, true);
await core.setUiMode(db, owner.id, "product");
});
});
describe("Bugsink не отвечает", () => {
test("Отказ после удачного запроса", async () => {
core.clearErrorsCache();
const scope = await core.errorScope(db, admin, o);
const before = await core.errorsOverview(db, scope, o);
bugsink.down = true;
try {
// The cache is fresh for 45 s: pretend a minute has passed.
const later = { ...o, now: new Date(Date.now() + 60_000) };
const ov = await core.errorsOverview(db, await core.errorScope(db, admin, later), later);
assert.equal(ov.down, true);
assert.deepEqual(ov.top.map((r) => r.id), before.top.map((r) => r.id));
} finally {
bugsink.down = false;
}
});
test("Отказ без кэша", async () => {
core.clearErrorsCache();
bugsink.down = true;
try {
const scope = await core.errorScope(db, admin, o);
assert.equal(scope.down, true);
const ov = await core.errorsOverview(db, scope, o);
assert.equal(ov.down, true);
assert.deepEqual(ov.top, []);
const list = await core.listErrors(db, scope, {}, o);
assert.equal(list.down, true);
assert.deepEqual(list.rows, []);
await assert.rejects(core.setErrorState(db, scope, ids.stage!, "mute", o), /не отвечает/);
} finally {
bugsink.down = false;
}
});
});