323 lines
15 KiB
TypeScript
323 lines
15 KiB
TypeScript
// Mock Bugsink (PEP-58) for tests: the subset of /api/canonical/0/ Peppa uses (projects,
|
|
// issues, events, resolve) with the same JSON shapes as Bugsink 2.6, Bearer auth, and
|
|
// outgoing custom-webhook alerts (NEW / REGRESSED) like Bugsink's `custom` backend.
|
|
import { randomUUID } from "node:crypto";
|
|
import { createServer, type Server } from "node:http";
|
|
import type { AddressInfo } from "node:net";
|
|
|
|
export interface MockFrame {
|
|
filename: string;
|
|
function: string;
|
|
lineno: number;
|
|
in_app?: boolean;
|
|
pre_context?: string[];
|
|
context_line?: string;
|
|
post_context?: string[];
|
|
}
|
|
|
|
export interface MockErrorEvent {
|
|
type: string;
|
|
value: string;
|
|
/** Outermost first, as Sentry SDKs send them. */
|
|
frames?: MockFrame[];
|
|
environment?: string;
|
|
release?: string;
|
|
level?: string;
|
|
/** Event tags (service, where, route, user…). */
|
|
tags?: Record<string, string>;
|
|
}
|
|
|
|
interface Project {
|
|
id: number;
|
|
name: string;
|
|
team: string;
|
|
key: string;
|
|
webhook?: string;
|
|
}
|
|
|
|
interface Issue {
|
|
id: string;
|
|
friendlyNo: number;
|
|
project: number;
|
|
type: string;
|
|
value: string;
|
|
culprit: string;
|
|
firstSeen: string;
|
|
lastSeen: string;
|
|
count: number;
|
|
resolved: boolean;
|
|
muted: boolean;
|
|
releases: string[];
|
|
events: string[];
|
|
}
|
|
|
|
interface Event {
|
|
id: string;
|
|
issue: string;
|
|
timestamp: string;
|
|
data: Record<string, unknown>;
|
|
}
|
|
|
|
export class MockBugsink {
|
|
readonly token = "mock-bugsink-token";
|
|
readonly teamId = randomUUID();
|
|
readonly projects = new Map<number, Project>();
|
|
readonly issues = new Map<string, Issue>();
|
|
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 = "";
|
|
|
|
async start(): Promise<this> {
|
|
this.server = createServer((req, res) => {
|
|
let body = "";
|
|
req.on("data", (c) => (body += c));
|
|
req.on("end", () => {
|
|
const ingest = /^\/api\/(\d+)\/envelope\/$/.exec(req.url!.split("?")[0]!);
|
|
if (req.method === "POST" && ingest) {
|
|
void this.ingestEnvelope(Number(ingest[1]), String(req.headers["x-sentry-auth"] ?? ""), body).then((r) => {
|
|
res.writeHead(r.status, { "Content-Type": "application/json" });
|
|
res.end(JSON.stringify(r.body));
|
|
});
|
|
return;
|
|
}
|
|
const r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {});
|
|
res.writeHead(r.status, { "Content-Type": "application/json" });
|
|
res.end(JSON.stringify(r.body ?? {}));
|
|
});
|
|
});
|
|
await new Promise<void>((r) => this.server!.listen(0, "127.0.0.1", r));
|
|
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
|
return this;
|
|
}
|
|
|
|
async stop() {
|
|
await new Promise<void>((r) => (this.server ? this.server.close(() => r()) : r()));
|
|
}
|
|
|
|
/** What Bugsink's UI/ORM does for alerts (there is no API for it). */
|
|
setWebhook(projectId: number, url: string | undefined) {
|
|
this.projects.get(projectId)!.webhook = url;
|
|
}
|
|
|
|
dsn(p: Project) {
|
|
return `https://${p.key}@bugsink.mock/${p.id}`;
|
|
}
|
|
|
|
issueJson(i: Issue) {
|
|
const p = this.projects.get(i.project)!;
|
|
return {
|
|
id: i.id,
|
|
friendly_id: `${p.name.toUpperCase()}-${i.friendlyNo}`,
|
|
project: i.project,
|
|
digest_order: i.friendlyNo,
|
|
last_seen: i.lastSeen,
|
|
first_seen: i.firstSeen,
|
|
digested_event_count: i.count,
|
|
stored_event_count: i.count,
|
|
calculated_type: i.type,
|
|
calculated_value: i.value,
|
|
transaction: "",
|
|
is_resolved: i.resolved,
|
|
is_resolved_unconditionally: false,
|
|
is_resolved_by_next_release: false,
|
|
fixed_at: [],
|
|
events_at: i.releases,
|
|
is_muted: i.muted,
|
|
unmute_after: null,
|
|
unmute_on_volume_based_conditions: [],
|
|
};
|
|
}
|
|
|
|
/**
|
|
* An SDK sends an error event: groups it into an issue (type + value + culprit) and, for a
|
|
* new or regressed issue, posts the alert to the project's webhook. Resolves with the issue id.
|
|
*/
|
|
async capture(projectId: number, e: MockErrorEvent, at = new Date()): Promise<string> {
|
|
const frames = e.frames ?? [{ filename: "app.js", function: "main", lineno: 1, in_app: true }];
|
|
const inner = [...frames].reverse().find((f) => f.in_app !== false) ?? frames.at(-1)!;
|
|
const culprit = inner.filename;
|
|
let issue = [...this.issues.values()].find((i) => i.project === projectId && i.type === e.type && i.value === e.value && i.culprit === culprit);
|
|
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, muted: false, releases: [], events: [] };
|
|
this.issues.set(issue.id, issue);
|
|
reason = "NEW";
|
|
} else if (issue.resolved) {
|
|
issue.resolved = false;
|
|
reason = "REGRESSED";
|
|
}
|
|
issue.count++;
|
|
// Events may arrive out of order (tests, stands): first/last seen are the min/max.
|
|
if (ts > issue.lastSeen) issue.lastSeen = ts;
|
|
if (ts < issue.firstSeen) issue.firstSeen = ts;
|
|
if (e.release && !issue.releases.includes(e.release)) issue.releases.push(e.release);
|
|
const ev: Event = {
|
|
id: randomUUID(),
|
|
issue: issue.id,
|
|
timestamp: ts,
|
|
data: {
|
|
level: e.level ?? "error",
|
|
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" } })) } }] },
|
|
},
|
|
};
|
|
this.events.set(ev.id, ev);
|
|
issue.events.push(ev.id);
|
|
if (reason) await this.alert(issue, reason);
|
|
return issue.id;
|
|
}
|
|
|
|
/** Envelopes taken by the ingest endpoint (PEP-91): the raw event as the SDK sent it. */
|
|
readonly ingested: Array<{ projectId: number; event: Record<string, unknown> }> = [];
|
|
|
|
/** `POST /api/<id>/envelope/` like Bugsink's ingest: sentry_key must match the project's DSN. */
|
|
async ingestEnvelope(projectId: number, auth: string, body: string): Promise<{ status: number; body: unknown }> {
|
|
const p = this.projects.get(projectId);
|
|
const key = /sentry_key=([^,\s]+)/.exec(auth)?.[1];
|
|
if (!p || key !== p.key) return { status: 403, body: { error: "invalid sentry_key" } };
|
|
const lines = body.split("\n").filter(Boolean);
|
|
const item = lines.findIndex((l, n) => n > 0 && (JSON.parse(l) as { type?: string }).type === "event");
|
|
if (item < 0 || !lines[item + 1]) return { status: 400, body: { error: "no event item" } };
|
|
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, tags: event.tags });
|
|
return { status: 200, body: { id: event.event_id } };
|
|
}
|
|
|
|
private async alert(i: Issue, reason: string) {
|
|
const p = this.projects.get(i.project)!;
|
|
if (!p.webhook) return;
|
|
const body = { ...this.issueJson(i), title: `${i.type}: ${i.value}`, project_name: p.name, url: `${this.url}/issues/issue/${i.id}/event/last/`, alert_reason: reason };
|
|
try {
|
|
const res = await fetch(p.webhook, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
this.alerts.push({ url: p.webhook, body, status: res.status });
|
|
} catch (e) {
|
|
this.alerts.push({ url: p.webhook, body, status: (e as Error).message });
|
|
}
|
|
}
|
|
|
|
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/, "");
|
|
let m: RegExpExecArray | null;
|
|
if (method === "POST" && path === "/projects/") {
|
|
if (body.team !== this.teamId) return { status: 400, body: { team: ["Invalid pk"] } };
|
|
const p: Project = { id: this.seq++, name: String(body.name), team: this.teamId, key: randomUUID().replace(/-/g, "") };
|
|
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 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|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 (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.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, 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]!);
|
|
return e ? { status: 200, body: { ...e, stacktrace_md: "(mock)" } } : { status: 404, body: { detail: "Not found." } };
|
|
}
|
|
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 };
|
|
}
|