Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3abd4ab804 | ||
|
|
954b0ced2e | ||
|
|
9dd88db4ae | ||
|
|
52e75a8760 | ||
|
|
b190d6fa1b | ||
|
|
3da9e47873 | ||
|
|
7f76c5287d |
No files matched your search
@@ -0,0 +1,47 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const rawBase = process.env.ERROR_REPORTING_ADMIN_API_BASE?.trim();
|
||||
if (!rawBase) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: "ERROR_REPORTING_ADMIN_API_BASE is not configured.",
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const base = rawBase.replace(/\/$/, "");
|
||||
const target = `${base}/api/error-monitoring/resolve-by-pattern`;
|
||||
const body = await request.text();
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
"Content-Type": request.headers.get("Content-Type") ?? "application/json",
|
||||
};
|
||||
const cookie = request.headers.get("cookie");
|
||||
if (cookie) {
|
||||
headers.Cookie = cookie;
|
||||
}
|
||||
const resolveHdr = request.headers.get("x-error-resolve-key");
|
||||
if (resolveHdr) {
|
||||
headers["X-Error-Resolve-Key"] = resolveHdr;
|
||||
}
|
||||
|
||||
const upstream = await fetch(target, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: body || undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const text = await upstream.text();
|
||||
const ct = upstream.headers.get("Content-Type") ?? "application/json; charset=utf-8";
|
||||
return new NextResponse(text, {
|
||||
status: upstream.status,
|
||||
headers: { "Content-Type": ct },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const rawBase = process.env.ERROR_REPORTING_ADMIN_API_BASE?.trim();
|
||||
if (!rawBase) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: "ERROR_REPORTING_ADMIN_API_BASE is not configured.",
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const base = rawBase.replace(/\/$/, "");
|
||||
const target = `${base}/api/error-monitoring/resolve-fixed-patterns`;
|
||||
const body = await request.text();
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
"Content-Type": request.headers.get("Content-Type") ?? "application/json",
|
||||
};
|
||||
const cookie = request.headers.get("cookie");
|
||||
if (cookie) {
|
||||
headers.Cookie = cookie;
|
||||
}
|
||||
const resolveHdr = request.headers.get("x-error-resolve-key");
|
||||
if (resolveHdr) {
|
||||
headers["X-Error-Resolve-Key"] = resolveHdr;
|
||||
}
|
||||
|
||||
const upstream = await fetch(target, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: body || undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const text = await upstream.text();
|
||||
const ct = upstream.headers.get("Content-Type") ?? "application/json; charset=utf-8";
|
||||
return new NextResponse(text, {
|
||||
status: upstream.status,
|
||||
headers: { "Content-Type": ct },
|
||||
});
|
||||
}
|
||||
@@ -100,6 +100,29 @@ function parseStatusList(raw: string | undefined): string[] | null {
|
||||
return parts.length > 0 ? parts : ['open', 'investigating'];
|
||||
}
|
||||
|
||||
|
||||
function slimContext(ctx: Record<string, unknown> | null): Record<string, unknown> | null {
|
||||
if (!ctx) return null;
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(ctx).slice(0, 40)) out[key] = slimContextValue(ctx[key], 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
function slimContextValue(value: unknown, depth: number): unknown {
|
||||
if (depth > 3) return '[nested]';
|
||||
if (typeof value === 'string') return value.length > 1500 ? `${value.slice(0, 1500)}…` : value;
|
||||
if (value == null || typeof value === 'number' || typeof value === 'boolean') return value;
|
||||
if (Array.isArray(value)) return value.slice(0, 20).map((item) => slimContextValue(item, depth + 1));
|
||||
if (typeof value === 'object') {
|
||||
const nested: Record<string, unknown> = {};
|
||||
for (const [key, item] of Object.entries(value as Record<string, unknown>).slice(0, 30)) {
|
||||
nested[key] = slimContextValue(item, depth + 1);
|
||||
}
|
||||
return nested;
|
||||
}
|
||||
return String(value).slice(0, 500);
|
||||
}
|
||||
|
||||
async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const db = request.server.db;
|
||||
|
||||
@@ -303,6 +326,8 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
|
||||
if (paperclip_project_id !== '') {
|
||||
rowOut.paperclip_project_id = paperclip_project_id;
|
||||
}
|
||||
const contextData = slimContext(ctx);
|
||||
if (contextData) rowOut.context_data = contextData;
|
||||
return rowOut;
|
||||
});
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ Env vars lidos (ver /etc/paperclip/paperclip-fleet-error-audit.env):
|
||||
PAPERCLIP_FLEET_AUDIT_HUB_BASE — base URL do hub (default: https://errors.bitreport.pt)
|
||||
PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS — CSV de slugs esperados
|
||||
PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS — limiar de frescura (default: 168)
|
||||
PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS_OVERRIDES — CSV "slug=horas" por slug (opcional,
|
||||
sobrepõe o limiar global para esse slug)
|
||||
PAPERCLIP_FLEET_AUDIT_FETCH_LIMIT — rows a buscar (default: 2000)
|
||||
PAPERCLIP_FLEET_AUDIT_MIN_ROWS — mínimo de rows antes de enforcement (default: 20)
|
||||
PAPERCLIP_FLEET_AUDIT_PROJECT_ID — Paperclip project ID para issues de correção
|
||||
@@ -27,6 +29,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
@@ -36,6 +39,12 @@ from typing import Any
|
||||
from urllib import request as urllib_request
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
# Marker convention used for one-off pipe-liveness verification events (e.g. sent by
|
||||
# hand while investigating a "stale" finding, per BIT-30273/BIT-30527). These are real
|
||||
# hub rows but not production traffic — counting them as "fresh" masks genuine staleness
|
||||
# for as long as they remain the newest row for a slug. Excluded from freshness scoring.
|
||||
_SYNTHETIC_EVENT_RE = re.compile(r"^\[BIT-\d+\]\s+\S+.*smoke test", re.IGNORECASE)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Env helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -126,7 +135,7 @@ def _patch_json(url: str, payload: dict[str, Any], headers: dict[str, str] | Non
|
||||
def fetch_hub_rows(hub_base: str, api_key: str, limit: int) -> list[dict[str, Any]]:
|
||||
url = (
|
||||
f"{hub_base}/api/error-monitoring/recent-errors"
|
||||
f"?limit={limit}&order=occurred_at_desc&api_key={api_key}"
|
||||
f"?limit={limit}&order=occurred_at_desc&status=open,investigating,resolved,ignored&api_key={api_key}"
|
||||
)
|
||||
# Use curl to avoid Cloudflare bot challenges on urllib
|
||||
result = subprocess.run(
|
||||
@@ -144,21 +153,45 @@ def fetch_hub_rows(hub_base: str, api_key: str, limit: int) -> list[dict[str, An
|
||||
return data.get("data", [])
|
||||
|
||||
|
||||
def _parse_max_age_overrides(raw: str) -> dict[str, int]:
|
||||
overrides: dict[str, int] = {}
|
||||
for part in raw.split(","):
|
||||
part = part.strip()
|
||||
if not part or "=" not in part:
|
||||
continue
|
||||
slug, _, hours_raw = part.partition("=")
|
||||
slug = slug.strip().lower()
|
||||
try:
|
||||
hours = int(hours_raw.strip())
|
||||
except ValueError:
|
||||
continue
|
||||
if slug:
|
||||
overrides[slug] = hours
|
||||
return overrides
|
||||
|
||||
|
||||
def analyse_rows(
|
||||
rows: list[dict[str, Any]],
|
||||
expected_slugs: list[str],
|
||||
max_age_hours: int,
|
||||
min_rows: int,
|
||||
max_age_overrides: dict[str, int] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
max_age_overrides = max_age_overrides or {}
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Aggregate per slug
|
||||
by_slug: dict[str, list[datetime]] = defaultdict(list)
|
||||
synthetic_skipped: dict[str, int] = defaultdict(int)
|
||||
for row in rows:
|
||||
slug = str(row.get("project_slug", "")).lower()
|
||||
occurred_at_raw = row.get("occurred_at", "")
|
||||
if not slug or not occurred_at_raw:
|
||||
continue
|
||||
message = str(row.get("message") or row.get("error_message") or "")
|
||||
if _SYNTHETIC_EVENT_RE.match(message.strip()):
|
||||
synthetic_skipped[slug] += 1
|
||||
continue
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(occurred_at_raw).replace("Z", "+00:00"))
|
||||
by_slug[slug].append(dt)
|
||||
@@ -171,6 +204,7 @@ def analyse_rows(
|
||||
results: list[dict[str, Any]] = []
|
||||
for slug in expected_slugs:
|
||||
times = by_slug.get(slug, [])
|
||||
slug_max_age = max_age_overrides.get(slug, max_age_hours)
|
||||
if not times:
|
||||
status = "silent"
|
||||
hours_since = None
|
||||
@@ -178,7 +212,7 @@ def analyse_rows(
|
||||
else:
|
||||
latest = max(times)
|
||||
hours_since = (now - latest).total_seconds() / 3600
|
||||
status = "stale" if hours_since > max_age_hours else "ok"
|
||||
status = "stale" if hours_since > slug_max_age else "ok"
|
||||
|
||||
results.append(
|
||||
{
|
||||
@@ -187,6 +221,8 @@ def analyse_rows(
|
||||
"event_count": len(times),
|
||||
"latest_occurred_at": latest.isoformat() if latest else None,
|
||||
"hours_since_last_event": round(hours_since, 1) if hours_since is not None else None,
|
||||
"max_age_hours": slug_max_age,
|
||||
"synthetic_events_excluded": synthetic_skipped.get(slug, 0),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -283,6 +319,7 @@ def main() -> int:
|
||||
hub_api_key = _env("PAPERCLIP_ERROR_API_KEY")
|
||||
expected_slugs_raw = _env("PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS", "")
|
||||
max_age_hours = _env_int("PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS", 168)
|
||||
max_age_overrides = _parse_max_age_overrides(_env("PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS_OVERRIDES", ""))
|
||||
fetch_limit = _env_int("PAPERCLIP_FLEET_AUDIT_FETCH_LIMIT", 2000)
|
||||
min_rows = _env_int("PAPERCLIP_FLEET_AUDIT_MIN_ROWS", 20)
|
||||
project_id = _env("PAPERCLIP_FLEET_AUDIT_PROJECT_ID")
|
||||
@@ -308,6 +345,8 @@ def main() -> int:
|
||||
print(f"Fleet audit starting — hub: {hub_base}")
|
||||
print(f"Expected slugs: {expected_slugs}")
|
||||
print(f"Max age: {max_age_hours}h, min rows: {min_rows}, fetch limit: {fetch_limit}")
|
||||
if max_age_overrides:
|
||||
print(f"Max age overrides: {max_age_overrides}")
|
||||
|
||||
# Fetch hub data
|
||||
try:
|
||||
@@ -319,7 +358,7 @@ def main() -> int:
|
||||
print(f"Fetched {len(rows)} rows from hub")
|
||||
|
||||
# Analyse
|
||||
report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows)
|
||||
report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows, max_age_overrides)
|
||||
print(json.dumps(report, indent=2, default=str))
|
||||
|
||||
# Determine problems
|
||||
@@ -352,10 +391,11 @@ def main() -> int:
|
||||
else:
|
||||
hours = p["hours_since_last_event"]
|
||||
latest = p["latest_occurred_at"]
|
||||
slug_max_age = p["max_age_hours"]
|
||||
title = f"[fleet-audit] {slug} — stale ({hours:.0f}h sem eventos)"
|
||||
desc = (
|
||||
f"O slug `{slug}` está stale: último evento há **{hours:.1f}h** "
|
||||
f"(limiar: {max_age_hours}h).\n\n"
|
||||
f"(limiar: {slug_max_age}h).\n\n"
|
||||
f"Último evento: `{latest}`\n"
|
||||
f"Hub: `{hub_base}`\n"
|
||||
f"Auditoria: {report['audited_at']}"
|
||||
@@ -396,7 +436,7 @@ def main() -> int:
|
||||
elif st == "stale":
|
||||
hours = r["hours_since_last_event"]
|
||||
icon = "⚠️"
|
||||
detail = f"stale — último evento há {hours:.1f}h (limiar: {max_age_hours}h)"
|
||||
detail = f"stale — último evento há {hours:.1f}h (limiar: {r['max_age_hours']}h)"
|
||||
else:
|
||||
icon = "🔴"
|
||||
detail = "silencioso — sem eventos"
|
||||
|
||||
Reference in new issue
Block a user