Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
258f0b3cd4 | ||
|
|
b757ec671a | ||
|
|
baac48a632 | ||
|
|
b8ca70709e | ||
|
|
e01c8f62d5 | ||
|
|
836d967aeb | ||
|
|
73acc917f5 | ||
|
|
8f7ff6b1d5 | ||
|
|
dc1aa3365e | ||
|
|
d987d2aaf4 | ||
|
|
d4059d801a | ||
|
|
9e318b5b9a | ||
|
|
954b0ced2e | ||
|
|
9dd88db4ae | ||
|
|
52e75a8760 | ||
|
|
b190d6fa1b | ||
|
|
3da9e47873 | ||
|
|
a1fd3d2db0 | ||
|
|
7f76c5287d | ||
|
|
7987aa94ae | ||
|
|
308ff624cf | ||
|
|
23704d2e59 | ||
|
|
caeb37ff0a | ||
|
|
37ab9f1ccb | ||
|
|
615d771ade | ||
|
|
3c307ea32d | ||
|
|
be735a16b6 | ||
|
|
050a380230 | ||
|
|
bebbfb3e57 | ||
|
|
7fe045d314 | ||
|
|
1181093739 | ||
|
|
2b8976551f | ||
|
|
8bb129ac77 | ||
|
|
f19ff03dd6 | ||
|
|
47f77e85de | ||
|
|
8773f12b25 | ||
|
|
ea41eb2205 | ||
|
|
3ae3ac4fd1 |
No files matched your search
@@ -0,0 +1,29 @@
|
||||
---
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Deploy: nunca sobrescrever `.env` de produção (BIT-25005)
|
||||
|
||||
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
|
||||
|
||||
## Proibido em scripts de deploy e agentes
|
||||
|
||||
| Proibido | Alternativa |
|
||||
|----------|------------|
|
||||
| `cp .env.example .env` sobre `.env` **já existente** em produção | `git pull` / rsync **excluindo** `.env` |
|
||||
| Escrever `root`, `changeme`, `password` ou superuser como credencial de BD em produção | Valores da vault; documentar chaves novas em `.env.example` **vazias** |
|
||||
| Alterar `DB_*` / `DATABASE_*` / `MYSQL_*` no host sem issue, rollback e log | Entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo) antes de aplicar |
|
||||
|
||||
## Regras obrigatórias
|
||||
|
||||
1. Scripts de deploy devem **falhar** (`exit 1`) se um passo tentaria sobrescrever um `.env` existente com conteúdo de exemplo.
|
||||
2. Usar **`rsync --exclude='.env'`** (e paths documentados por serviço) ou `git pull` sem toque no `.env`.
|
||||
3. Pós-deploy: validar que variáveis críticas **não** regressaram a placeholders (`changeme`, `root`, `password`, `secret`, etc.).
|
||||
4. Qualquer alteração a `.env` de produção requer: issue explícita, plano de rollback, e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md`.
|
||||
|
||||
## Quando a regra se aplica
|
||||
|
||||
- Todos os scripts de deploy (webhook, CI, manual).
|
||||
- Agentes que editam, geram ou sugerem alterações a ficheiros `.env`, `.env.example`, `docker-compose.yml` com variáveis de ambiente, ou scripts que copiam/escrevem ficheiros de configuração em produção.
|
||||
|
||||
**Referência:** `docs/DEPLOY_STANDARD.md` §3.1 no meta-repo `paperclip` (regra canónica).
|
||||
+4
-4
@@ -2,11 +2,11 @@
|
||||
# Replace/add owners as needed per repository domain.
|
||||
|
||||
# CI and forge metadata
|
||||
/.gitea/ @tiago-neves @david-santos
|
||||
/.gitea/workflows/ @tiago-neves @david-santos
|
||||
/.gitea/ @devops-engineer @founding-engineer
|
||||
/.gitea/workflows/ @devops-engineer @founding-engineer
|
||||
|
||||
# Documentation
|
||||
/docs/ @david-santos @planner
|
||||
/docs/ @founding-engineer
|
||||
|
||||
# Catch-all
|
||||
* @david-santos
|
||||
* @founding-engineer
|
||||
@@ -1,6 +1,6 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
'on':
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: 'ingest-api/package-lock.json'
|
||||
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: 'api/package-lock.json'
|
||||
|
||||
@@ -60,7 +60,7 @@ jobs:
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: 'admin-ui/package-lock.json'
|
||||
|
||||
|
||||
+3
-3
@@ -1,17 +1,17 @@
|
||||
# Next.js 15 admin UI (Velzon-style) — production image for docker-compose.
|
||||
FROM node:20-bookworm-slim AS deps
|
||||
FROM node:24-bookworm-slim AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM node:20-bookworm-slim AS build
|
||||
FROM node:24-bookworm-slim AS build
|
||||
WORKDIR /app
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-bookworm-slim AS runner
|
||||
FROM node:24-bookworm-slim AS runner
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
@@ -35,6 +35,17 @@ interface CrmPhpPayload {
|
||||
project_slug?: unknown;
|
||||
project_name?: unknown;
|
||||
gitea_repo?: unknown;
|
||||
// Paperclip project UUID — used by error loop to route issues to the correct project board column
|
||||
paperclip_project_id?: unknown;
|
||||
paperclipProjectId?: unknown;
|
||||
// telemetry metadata (BIT-33316) — canonical keys + legacy aliases
|
||||
component?: unknown;
|
||||
release?: unknown;
|
||||
release_version?: unknown;
|
||||
runtime_name?: unknown;
|
||||
runtime_version?: unknown;
|
||||
host_name?: unknown;
|
||||
hostname?: unknown;
|
||||
}
|
||||
|
||||
function safeStr(v: unknown): string {
|
||||
@@ -94,9 +105,23 @@ export async function POST(request: NextRequest) {
|
||||
const gitea_repo = safeStr(body.gitea_repo);
|
||||
const project_slug = safeStr(body.project_slug);
|
||||
const project_name = safeStr(body.project_name);
|
||||
const paperclip_project_id = safeStr(body.paperclip_project_id || body.paperclipProjectId);
|
||||
if (gitea_repo) contextData.gitea_repo = gitea_repo;
|
||||
if (project_slug) contextData.project_slug = project_slug;
|
||||
if (project_name) contextData.project_name = project_name;
|
||||
if (paperclip_project_id) contextData.paperclip_project_id = paperclip_project_id;
|
||||
|
||||
const metaPairs: Array<[string, string]> = [
|
||||
["component", safeStr(body.component)],
|
||||
["release_version", safeStr(body.release_version || body.release)],
|
||||
["runtime_name", safeStr(body.runtime_name)],
|
||||
["runtime_version", safeStr(body.runtime_version)],
|
||||
["host_name", safeStr(body.host_name || body.hostname)],
|
||||
["environment", safeStr(body.environment)],
|
||||
];
|
||||
for (const [k, v] of metaPairs) {
|
||||
if (v) contextData[k] = v;
|
||||
}
|
||||
|
||||
// Preserve other top-level diagnostic fields.
|
||||
const file_path = safeStr(body.file_path);
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { IncidentDetail, IncidentSummary } from "./types";
|
||||
const _demoSummaries: IncidentSummary[] = [
|
||||
{
|
||||
id: "demo-1",
|
||||
projectSlug: "wdmi-store",
|
||||
projectSlug: "crm",
|
||||
fingerprint: "fp_checkout_timeout",
|
||||
title: "Checkout API timeout after 30s",
|
||||
severity: "high",
|
||||
@@ -15,7 +15,7 @@ const _demoSummaries: IncidentSummary[] = [
|
||||
},
|
||||
{
|
||||
id: "demo-2",
|
||||
projectSlug: "crm-wdmi",
|
||||
projectSlug: "ott",
|
||||
fingerprint: "fp_null_sku",
|
||||
title: "TypeError: Cannot read properties of undefined (reading 'sku')",
|
||||
severity: "medium",
|
||||
@@ -26,7 +26,7 @@ const _demoSummaries: IncidentSummary[] = [
|
||||
},
|
||||
{
|
||||
id: "demo-3",
|
||||
projectSlug: "wdmi-store",
|
||||
projectSlug: "crm",
|
||||
fingerprint: "fp_rate_limit",
|
||||
title: "429 Too Many Requests on /api/v1/prices",
|
||||
severity: "low",
|
||||
|
||||
@@ -7,6 +7,15 @@ import type { NextConfig } from "next";
|
||||
const INGEST_API_URL =
|
||||
process.env.INGEST_API_URL || "http://127.0.0.1:3041";
|
||||
|
||||
/**
|
||||
* Admin/mutation API backend (same LXC, port 3200).
|
||||
* Proxies hub-only mutation endpoints (resolve-fixed-patterns, etc.) so they are
|
||||
* reachable via the public errors.bitreport.pt hostname without a separate FQDN.
|
||||
* BIT-25072: resolve-fixed-patterns is hub-only; CRM error-loop calls this via HTTPS.
|
||||
*/
|
||||
const ADMIN_API_URL =
|
||||
process.env.ERROR_REPORTING_ADMIN_API_BASE || "http://127.0.0.1:3200";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
reactStrictMode: true,
|
||||
@@ -14,7 +23,20 @@ const nextConfig: NextConfig = {
|
||||
async rewrites() {
|
||||
return [
|
||||
{ source: "/health", destination: `${INGEST_API_URL}/health` },
|
||||
// BIT-31442: the recent-errors handler (api/src/routes/public/recentErrors.ts)
|
||||
// registers the /v1/paperclip/recent-errors alias on the admin API (port 3200),
|
||||
// not on ingest-api. The generic /v1/* rule below would otherwise send it to
|
||||
// ingest-api (port 3041), which has no such route and returns 404. This more
|
||||
// specific rule must come first; Next.js evaluates rewrites in order.
|
||||
{
|
||||
source: "/v1/paperclip/:path*",
|
||||
destination: `${ADMIN_API_URL}/v1/paperclip/:path*`,
|
||||
},
|
||||
{ source: "/v1/:path*", destination: `${INGEST_API_URL}/v1/:path*` },
|
||||
{
|
||||
source: "/api/error-monitoring/:path*",
|
||||
destination: `${ADMIN_API_URL}/api/error-monitoring/:path*`,
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
Generated
+11
-27
@@ -15,7 +15,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"eslint": "^9.15.0",
|
||||
@@ -24,7 +24,7 @@
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
@@ -931,7 +931,6 @@
|
||||
"version": "2.5.6",
|
||||
"resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.6.tgz",
|
||||
"integrity": "sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
@@ -971,7 +970,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -992,7 +990,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1013,7 +1010,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1034,7 +1030,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1055,7 +1050,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1076,7 +1070,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1097,7 +1090,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1118,7 +1110,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1139,7 +1130,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1160,7 +1150,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1181,7 +1170,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1202,7 +1190,6 @@
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1223,7 +1210,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1241,7 +1227,6 @@
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
@@ -1318,13 +1303,13 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.19.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz",
|
||||
"integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",
|
||||
"version": "24.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
|
||||
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
"undici-types": ">=7.24.0 <7.24.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
@@ -3811,7 +3796,7 @@
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -3857,7 +3842,7 @@
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
|
||||
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-extglob": "^2.1.1"
|
||||
@@ -4407,7 +4392,6 @@
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",
|
||||
"integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
@@ -5664,9 +5648,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"eslint": "^9.15.0",
|
||||
@@ -27,6 +27,6 @@
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,10 @@ Each row includes CRM-compatible fields. For non-resolved incidents, `status` is
|
||||
|
||||
**`stack_trace`:** Non-empty for every row: missing client stacks are synthesized on ingest; legacy DB rows with null/blank `stack_trace` get the same synthesis when serializing this endpoint (BIT-1008).
|
||||
|
||||
**`gitea_repo`** *(optional)*: Gitea `Owner/Repo` path (e.g. `BitReport.pt/WDMI`) if the reporter sent `gitea_repo` in the error payload. Omitted when not present.
|
||||
|
||||
**`paperclip_project_id`** *(optional)*: Paperclip project UUID sent by the reporter (via `paperclip_project_id` or `paperclipProjectId` payload field). When present, the Paperclip error loop uses this UUID directly to route issues to the correct project board column instead of falling back to the `PAPERCLIP_ERROR_LOOP_PROJECT_ID_BY_SLUG` env map. Omitted when not present.
|
||||
|
||||
**Example**
|
||||
|
||||
```bash
|
||||
|
||||
Generated
+30
-585
@@ -14,7 +14,7 @@
|
||||
"@fastify/rate-limit": "^9.1.0",
|
||||
"@fastify/swagger": "^8.14.0",
|
||||
"@fastify/swagger-ui": "^3.0.0",
|
||||
"bcrypt": "^5.1.1",
|
||||
"bcrypt": "^6.0.0",
|
||||
"fastify": "^4.28.1",
|
||||
"mysql2": "^3.11.5",
|
||||
"pino": "^9.1.0",
|
||||
@@ -23,10 +23,13 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/node": "^20.14.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"tsx": "^4.15.6",
|
||||
"typescript": "^5.4.5",
|
||||
"vitest": "^1.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -658,26 +661,6 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/@mapbox/node-pre-gyp": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
|
||||
"integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"detect-libc": "^2.0.0",
|
||||
"https-proxy-agent": "^5.0.0",
|
||||
"make-dir": "^3.1.0",
|
||||
"node-fetch": "^2.6.7",
|
||||
"nopt": "^5.0.0",
|
||||
"npmlog": "^5.0.1",
|
||||
"rimraf": "^3.0.2",
|
||||
"semver": "^7.3.5",
|
||||
"tar": "^6.1.11"
|
||||
},
|
||||
"bin": {
|
||||
"node-pre-gyp": "bin/node-pre-gyp"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/api": {
|
||||
"version": "1.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
|
||||
@@ -1078,12 +1061,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "20.19.37",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz",
|
||||
"integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==",
|
||||
"version": "24.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
|
||||
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
"undici-types": ">=7.24.0 <7.24.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/expect": {
|
||||
@@ -1160,12 +1143,6 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/abbrev": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
|
||||
"integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/abstract-logging": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
|
||||
@@ -1198,18 +1175,6 @@
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-base": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
|
||||
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv": {
|
||||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
@@ -1284,26 +1249,6 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/aproba": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/aproba/-/aproba-2.1.0.tgz",
|
||||
"integrity": "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/are-we-there-yet": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz",
|
||||
"integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==",
|
||||
"deprecated": "This package is no longer supported.",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"delegates": "^1.0.0",
|
||||
"readable-stream": "^3.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1.js": {
|
||||
"version": "5.4.1",
|
||||
"resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz",
|
||||
@@ -1361,17 +1306,17 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/bcrypt": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz",
|
||||
"integrity": "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==",
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-6.0.0.tgz",
|
||||
"integrity": "sha512-cU8v/EGSrnH+HnxV2z0J7/blxH8gq7Xh2JFT6Aroax7UohdmiJJlxApMxtKfuI7z68NvvVcmR78k2LbT6efhRg==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@mapbox/node-pre-gyp": "^1.0.11",
|
||||
"node-addon-api": "^5.0.0"
|
||||
"node-addon-api": "^8.3.0",
|
||||
"node-gyp-build": "^4.8.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
"node": ">= 18"
|
||||
}
|
||||
},
|
||||
"node_modules/bintrees": {
|
||||
@@ -1437,15 +1382,6 @@
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/chownr": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
|
||||
"integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
@@ -1464,21 +1400,6 @@
|
||||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/color-support": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz",
|
||||
"integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==",
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"color-support": "bin.js"
|
||||
}
|
||||
},
|
||||
"node_modules/concat-map": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/confbox": {
|
||||
"version": "0.1.8",
|
||||
"resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz",
|
||||
@@ -1486,12 +1407,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/console-control-strings": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
|
||||
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/content-disposition": {
|
||||
"version": "0.5.4",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||
@@ -1566,12 +1481,6 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/delegates": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
|
||||
"integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/denque": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
|
||||
@@ -1590,15 +1499,6 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/diff-sequences": {
|
||||
"version": "29.6.3",
|
||||
"resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz",
|
||||
@@ -1912,36 +1812,6 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/fs-minipass": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
|
||||
"integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"minipass": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/fs-minipass/node_modules/minipass": {
|
||||
"version": "3.3.6",
|
||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
|
||||
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/fs.realpath": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
|
||||
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
@@ -1957,74 +1827,6 @@
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/gauge": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz",
|
||||
"integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==",
|
||||
"deprecated": "This package is no longer supported.",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"aproba": "^1.0.3 || ^2.0.0",
|
||||
"color-support": "^1.1.2",
|
||||
"console-control-strings": "^1.0.0",
|
||||
"has-unicode": "^2.0.1",
|
||||
"object-assign": "^4.1.1",
|
||||
"signal-exit": "^3.0.0",
|
||||
"string-width": "^4.2.3",
|
||||
"strip-ansi": "^6.0.1",
|
||||
"wide-align": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/gauge/node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/gauge/node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/gauge/node_modules/signal-exit": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
|
||||
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/gauge/node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/gauge/node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/generate-function": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
|
||||
@@ -2091,12 +1893,6 @@
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/has-unicode": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
|
||||
"integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/helmet": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/helmet/-/helmet-7.2.0.tgz",
|
||||
@@ -2122,19 +1918,6 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/https-proxy-agent": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
|
||||
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"agent-base": "6",
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/human-signals": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz",
|
||||
@@ -2161,17 +1944,6 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/inflight": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
||||
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
|
||||
"deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"once": "^1.3.0",
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
@@ -2350,30 +2122,6 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/make-dir": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
|
||||
"integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"semver": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/make-dir/node_modules/semver": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
|
||||
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
}
|
||||
},
|
||||
"node_modules/merge-stream": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
|
||||
@@ -2436,43 +2184,6 @@
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/minizlib": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
|
||||
"integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"minipass": "^3.0.0",
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/minizlib/node_modules/minipass": {
|
||||
"version": "3.3.6",
|
||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
|
||||
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/mkdirp": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
|
||||
"integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"mkdirp": "bin/cmd.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/mlly": {
|
||||
"version": "1.8.2",
|
||||
"resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz",
|
||||
@@ -2562,44 +2273,23 @@
|
||||
}
|
||||
},
|
||||
"node_modules/node-addon-api": {
|
||||
"version": "5.1.0",
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz",
|
||||
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/node-fetch": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
|
||||
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
|
||||
"version": "8.9.2",
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz",
|
||||
"integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"whatwg-url": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "4.x || >=6.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"encoding": "^0.1.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"encoding": {
|
||||
"optional": true
|
||||
}
|
||||
"node": "^18 || ^20 || >= 21"
|
||||
}
|
||||
},
|
||||
"node_modules/nopt": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz",
|
||||
"integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"abbrev": "1"
|
||||
},
|
||||
"node_modules/node-gyp-build": {
|
||||
"version": "4.8.4",
|
||||
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
|
||||
"integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"nopt": "bin/nopt.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
"node-gyp-build": "bin.js",
|
||||
"node-gyp-build-optional": "optional.js",
|
||||
"node-gyp-build-test": "build-test.js"
|
||||
}
|
||||
},
|
||||
"node_modules/npm-run-path": {
|
||||
@@ -2631,28 +2321,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/npmlog": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz",
|
||||
"integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==",
|
||||
"deprecated": "This package is no longer supported.",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"are-we-there-yet": "^2.0.0",
|
||||
"console-control-strings": "^1.1.0",
|
||||
"gauge": "^3.0.0",
|
||||
"set-blocking": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-assign": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/obliterator": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz",
|
||||
@@ -2668,15 +2336,6 @@
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/once": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
||||
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/onetime": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz",
|
||||
@@ -2721,15 +2380,6 @@
|
||||
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
|
||||
"license": "BlueOak-1.0.0"
|
||||
},
|
||||
"node_modules/path-is-absolute": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
|
||||
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/path-key": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
||||
@@ -2949,20 +2599,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/readable-stream": {
|
||||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
||||
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"inherits": "^2.0.3",
|
||||
"string_decoder": "^1.1.1",
|
||||
"util-deprecate": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/real-require": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
|
||||
@@ -3016,65 +2652,6 @@
|
||||
"integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/rimraf": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
|
||||
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
|
||||
"deprecated": "Rimraf versions prior to v4 are no longer supported",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"glob": "^7.1.3"
|
||||
},
|
||||
"bin": {
|
||||
"rimraf": "bin.js"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/rimraf/node_modules/brace-expansion": {
|
||||
"version": "1.1.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
|
||||
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0",
|
||||
"concat-map": "0.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/rimraf/node_modules/glob": {
|
||||
"version": "7.2.3",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
||||
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
||||
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"fs.realpath": "^1.0.0",
|
||||
"inflight": "^1.0.4",
|
||||
"inherits": "2",
|
||||
"minimatch": "^3.1.1",
|
||||
"once": "^1.3.0",
|
||||
"path-is-absolute": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/rimraf/node_modules/minimatch": {
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
|
||||
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^1.1.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/rollup": {
|
||||
"version": "4.60.0",
|
||||
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.0.tgz",
|
||||
@@ -3182,12 +2759,6 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/set-blocking": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/set-cookie-parser": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
|
||||
@@ -3319,15 +2890,6 @@
|
||||
"reusify": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/string_decoder": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
||||
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safe-buffer": "~5.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/string-width": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
|
||||
@@ -3450,33 +3012,6 @@
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
}
|
||||
},
|
||||
"node_modules/tar": {
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
|
||||
"integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==",
|
||||
"deprecated": "Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"chownr": "^2.0.0",
|
||||
"fs-minipass": "^2.0.0",
|
||||
"minipass": "^5.0.0",
|
||||
"minizlib": "^2.1.1",
|
||||
"mkdirp": "^1.0.3",
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/tar/node_modules/minipass": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
|
||||
"integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/tdigest": {
|
||||
"version": "0.1.2",
|
||||
"resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz",
|
||||
@@ -3540,12 +3075,6 @@
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/tr46": {
|
||||
"version": "0.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
||||
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tsx": {
|
||||
"version": "4.21.0",
|
||||
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
|
||||
@@ -3598,9 +3127,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/uri-js": {
|
||||
@@ -3612,12 +3141,6 @@
|
||||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/util-deprecate": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "5.4.21",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
|
||||
@@ -4197,22 +3720,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/webidl-conversions": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
|
||||
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/whatwg-url": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
||||
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tr46": "~0.0.3",
|
||||
"webidl-conversions": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||
@@ -4245,56 +3752,6 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/wide-align": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz",
|
||||
"integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^1.0.2 || 2 || 3 || 4"
|
||||
}
|
||||
},
|
||||
"node_modules/wide-align/node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/wide-align/node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/wide-align/node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/wide-align/node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/wrap-ansi": {
|
||||
"version": "8.1.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
|
||||
@@ -4398,12 +3855,6 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/wrappy": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/xtend": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||
@@ -4413,12 +3864,6 @@
|
||||
"node": ">=0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
|
||||
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yaml": {
|
||||
"version": "2.8.3",
|
||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz",
|
||||
|
||||
+5
-2
@@ -12,6 +12,9 @@
|
||||
"test:watch": "vitest",
|
||||
"db:migrate": "bash ../scripts/run-mysql-migrations.sh"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24.22.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^9.3.1",
|
||||
"@fastify/helmet": "^11.1.1",
|
||||
@@ -19,7 +22,7 @@
|
||||
"@fastify/rate-limit": "^9.1.0",
|
||||
"@fastify/swagger": "^8.14.0",
|
||||
"@fastify/swagger-ui": "^3.0.0",
|
||||
"bcrypt": "^5.1.1",
|
||||
"bcrypt": "^6.0.0",
|
||||
"fastify": "^4.28.1",
|
||||
"mysql2": "^3.11.5",
|
||||
"pino": "^9.1.0",
|
||||
@@ -28,7 +31,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/node": "^20.14.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"tsx": "^4.15.6",
|
||||
"typescript": "^5.4.5",
|
||||
"vitest": "^1.6.0"
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Known-resolved error patterns for the hub resolve-fixed-patterns endpoint (BIT-25072).
|
||||
* Each entry matches against er_incident_occurrences.message (via LIKE or exact).
|
||||
*
|
||||
* Schema: { messagePatterns, note, addedAt?, expiresAfterDays? }
|
||||
* messagePatterns: SQL LIKE patterns (use % wildcards). All patterns in an entry are AND-ed.
|
||||
* note: human-readable reason / fix reference (written to er_incident_state_history.change_note).
|
||||
* addedAt: ISO date when this pattern was added (YYYY-MM-DD).
|
||||
* expiresAfterDays: if set, the pattern stops auto-resolving this many days after addedAt.
|
||||
* This forces errors that persist beyond the grace period back to open state, ensuring the
|
||||
* fix landed in code and wasn't just hidden. Omit for permanent patterns (transient infra noise
|
||||
* with no code fix expected). See BIT-26790.
|
||||
*
|
||||
* Transient infrastructure errors: noise from known-bad infra states that self-resolve.
|
||||
* Fixed code errors: added after the fix is deployed to production — set expiresAfterDays.
|
||||
*/
|
||||
export interface FixedPattern {
|
||||
/** Each element becomes: o.message LIKE ? (all AND-ed together for this entry). */
|
||||
messagePatterns: string[];
|
||||
note: string;
|
||||
/** ISO date (YYYY-MM-DD) when this pattern was added. */
|
||||
addedAt?: string;
|
||||
/**
|
||||
* Days after addedAt when this pattern expires and stops auto-resolving.
|
||||
* Expired patterns are skipped so the error resurfaces if it still occurs,
|
||||
* signalling that the code fix hasn't landed yet. Omit for permanent patterns.
|
||||
*/
|
||||
expiresAfterDays?: number;
|
||||
}
|
||||
|
||||
const patterns: FixedPattern[] = [
|
||||
// Galera/WSREP cluster transient — node not ready
|
||||
{
|
||||
messagePatterns: ['%WSREP has not yet prepared node%'],
|
||||
note: 'Transient: Galera cluster node not ready; infrastructure',
|
||||
addedAt: '2026-06-13',
|
||||
},
|
||||
// Google API backendError — transient external
|
||||
{
|
||||
messagePatterns: ['%Internal error encountered%', '%backendError%'],
|
||||
note: 'Transient: Google API 500 backendError; external; no code fix',
|
||||
addedAt: '2026-06-13',
|
||||
},
|
||||
// Session write fails when DB is unavailable (cascading)
|
||||
{
|
||||
messagePatterns: ['%session_write_close(): Failed to write session data%'],
|
||||
note: 'Transient: cascades from DB unavailability; no code fix',
|
||||
addedAt: '2026-06-13',
|
||||
},
|
||||
// Storage / COMMIT transient
|
||||
{
|
||||
messagePatterns: ['%No such device or address%'],
|
||||
note: 'Transient: storage/infrastructure during COMMIT; retry on next request',
|
||||
addedAt: '2026-06-13',
|
||||
},
|
||||
// CRM: fix-duplicate-logo.js load failure (BIT-25223 ERRCLUSTER:33b4e527d8fd)
|
||||
// File is present and protected by CopyWebpackPlugin + deploy gate; client-side noise
|
||||
// filter (PR #684) suppresses at source. Chrome-style messages include the URL; this
|
||||
// pattern resolves any that still reach the hub. Firefox-style resolved by bulk-resolve.
|
||||
// Expires after 14 days — if still occurring after that, the deploy or filter is broken.
|
||||
{
|
||||
messagePatterns: ['%fix-duplicate-logo.js%'],
|
||||
note: 'Fixed: fix-duplicate-logo.js present + protected (BIT-25223); client noise filter PR #684',
|
||||
addedAt: '2026-07-17',
|
||||
expiresAfterDays: 14,
|
||||
},
|
||||
];
|
||||
|
||||
export default patterns;
|
||||
@@ -45,6 +45,22 @@ export function authorizeReadQuery(request: FastifyRequest, reply: FastifyReply)
|
||||
return true;
|
||||
}
|
||||
|
||||
// BIT-31442: accept X-Api-Key header as an alternative to the query param so
|
||||
// programmatic callers (Paperclip, QA) can avoid leaking the key in URLs/logs.
|
||||
// The header may carry either the resolve/reporting key or the read-only
|
||||
// DEBUG_VIEW_ERRORS_KEY, mirroring the query-param semantics.
|
||||
const headerRaw = request.headers['x-api-key'];
|
||||
const headerVal = Array.isArray(headerRaw) ? headerRaw[0] : headerRaw;
|
||||
const providedHeader = typeof headerVal === 'string' ? headerVal.trim() : '';
|
||||
if (providedHeader !== '') {
|
||||
if (apiKey && safeEqual(providedHeader, apiKey)) {
|
||||
return true;
|
||||
}
|
||||
if (viewKey && safeEqual(providedHeader, viewKey)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
reply.code(401).send({
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
|
||||
@@ -359,7 +359,7 @@ describe('POST /api/error-monitoring/resolve-by-pattern', () => {
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: { project_slug: 'wdmi' },
|
||||
payload: { project_slug: 'crm' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
@@ -405,7 +405,7 @@ describe('POST /api/error-monitoring/resolve-by-pattern', () => {
|
||||
headers: authHeaders(),
|
||||
payload: {
|
||||
severity: 'critical',
|
||||
project_slug: 'wdmi',
|
||||
project_slug: 'crm',
|
||||
message_pattern: 'timeout',
|
||||
from_date: '2026-03-01T00:00:00Z',
|
||||
},
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
* POST /api/error-monitoring/resolve
|
||||
* POST /api/error-monitoring/bulk-resolve
|
||||
* POST /api/error-monitoring/resolve-by-pattern
|
||||
* POST /api/error-monitoring/resolve-fixed-patterns
|
||||
* POST /api/error-monitoring/purge-resolved
|
||||
*/
|
||||
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { ResultSetHeader, RowDataPacket } from 'mysql2';
|
||||
import fixedPatterns from '../../config/resolveFixedPatterns.js';
|
||||
import {
|
||||
authorizeMutation,
|
||||
changedByRef,
|
||||
@@ -611,10 +613,136 @@ async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply)
|
||||
});
|
||||
}
|
||||
|
||||
async function handleResolveFixedPatterns(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const db = request.server.db;
|
||||
const body = parseJsonBody(request.body);
|
||||
const auth = await authorizeMutation(request, reply, body, 'errors:triage');
|
||||
if (!auth) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dryRun = Boolean(body.dry_run);
|
||||
const { type, ref } = changedByRef(auth);
|
||||
|
||||
const details: Array<{
|
||||
note: string;
|
||||
resolved?: number;
|
||||
would_resolve?: number;
|
||||
expired?: boolean;
|
||||
expires_at?: string;
|
||||
}> = [];
|
||||
let total = 0;
|
||||
let expiredCount = 0;
|
||||
const nowMs = Date.now();
|
||||
|
||||
for (const pattern of fixedPatterns) {
|
||||
if (pattern.messagePatterns.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip patterns that have passed their expiry window (BIT-26790).
|
||||
// Expired patterns stop suppressing so the error resurfaces if still present.
|
||||
if (pattern.addedAt && pattern.expiresAfterDays !== undefined) {
|
||||
const addedMs = new Date(pattern.addedAt).getTime();
|
||||
const expiresAt = new Date(addedMs + pattern.expiresAfterDays * 86_400_000);
|
||||
if (nowMs > expiresAt.getTime()) {
|
||||
expiredCount += 1;
|
||||
details.push({ note: pattern.note, expired: true, expires_at: expiresAt.toISOString().slice(0, 10) });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const likeClauses = pattern.messagePatterns.map(() => 'o.message LIKE ?').join(' AND ');
|
||||
const params: string[] = pattern.messagePatterns;
|
||||
|
||||
const [countRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT COUNT(DISTINCT i.id) AS c
|
||||
FROM er_incidents i
|
||||
INNER JOIN er_incident_occurrences o ON o.incident_id = i.id
|
||||
WHERE i.current_state IN ('open','investigating')
|
||||
AND (${likeClauses})`,
|
||||
params,
|
||||
);
|
||||
const n = Number((countRows[0] as { c?: number }).c ?? 0);
|
||||
if (n === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
total += n;
|
||||
details.push({ note: pattern.note, would_resolve: n });
|
||||
continue;
|
||||
}
|
||||
|
||||
const [matchRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT DISTINCT CAST(i.id AS CHAR) AS incident_id,
|
||||
CAST(i.project_id AS CHAR) AS project_id,
|
||||
i.current_state AS current_state
|
||||
FROM er_incidents i
|
||||
INNER JOIN er_incident_occurrences o ON o.incident_id = i.id
|
||||
WHERE i.current_state IN ('open','investigating')
|
||||
AND (${likeClauses})`,
|
||||
params,
|
||||
);
|
||||
const targets = (matchRows as Record<string, unknown>[]).map((r) => ({
|
||||
incidentId: String(r.incident_id),
|
||||
projectId: String(r.project_id),
|
||||
currentState: String(r.current_state),
|
||||
}));
|
||||
|
||||
let resolved = 0;
|
||||
const conn = await db.getConnection();
|
||||
try {
|
||||
await conn.beginTransaction();
|
||||
for (const row of targets) {
|
||||
const [upd] = await conn.execute<ResultSetHeader>(
|
||||
`UPDATE er_incidents
|
||||
SET current_state = 'resolved', updated_at = CURRENT_TIMESTAMP(6)
|
||||
WHERE id = ? AND current_state IN ('open','investigating')`,
|
||||
[row.incidentId],
|
||||
);
|
||||
if (upd.affectedRows === 0) {
|
||||
continue;
|
||||
}
|
||||
await conn.execute(
|
||||
`INSERT INTO er_incident_state_history
|
||||
(incident_id, project_id, from_state, to_state, changed_by_type, changed_by_ref, change_note)
|
||||
VALUES (?, ?, ?, 'resolved', ?, ?, ?)`,
|
||||
[row.incidentId, row.projectId, row.currentState, type, ref, pattern.note],
|
||||
);
|
||||
resolved += upd.affectedRows;
|
||||
}
|
||||
await conn.commit();
|
||||
} catch (e) {
|
||||
await conn.rollback();
|
||||
throw e;
|
||||
} finally {
|
||||
conn.release();
|
||||
}
|
||||
|
||||
total += resolved;
|
||||
details.push({ note: pattern.note, resolved });
|
||||
}
|
||||
|
||||
if (!dryRun) {
|
||||
await auditMutation(request.server, request, auth, 'error_monitoring.resolve_fixed_patterns', 'batch', {
|
||||
resolved: total,
|
||||
pattern_count: fixedPatterns.length,
|
||||
expired_pattern_count: expiredCount,
|
||||
});
|
||||
}
|
||||
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: dryRun ? `Would resolve ${total} incidents` : `Resolved ${total} incidents`,
|
||||
data: { total, dry_run: dryRun, expired_pattern_count: expiredCount, details },
|
||||
});
|
||||
}
|
||||
|
||||
export default async function errorMonitoringMutationsRoutes(app: FastifyInstance): Promise<void> {
|
||||
const rl = { config: { rateLimit: app.rateLimits.mutation } };
|
||||
app.post('/api/error-monitoring/resolve', rl, handleResolve);
|
||||
app.post('/api/error-monitoring/bulk-resolve', rl, handleBulkResolve);
|
||||
app.post('/api/error-monitoring/resolve-by-pattern', rl, handleResolveByPattern);
|
||||
app.post('/api/error-monitoring/resolve-fixed-patterns', rl, handleResolveFixedPatterns);
|
||||
app.post('/api/error-monitoring/purge-resolved', rl, handlePurgeResolved);
|
||||
}
|
||||
@@ -31,13 +31,13 @@ describe('GET /api/error-monitoring/recent-errors', () => {
|
||||
{
|
||||
incident_id: '1',
|
||||
occurrence_id: '99',
|
||||
project_slug: 'wdmi-store',
|
||||
project_slug: 'crm',
|
||||
incident_severity: 'high',
|
||||
incident_state: 'open',
|
||||
message: 'probe',
|
||||
stack_trace: '',
|
||||
context_json: JSON.stringify({
|
||||
gitea_repo: 'BitReport.pt/WDMI_STORE',
|
||||
gitea_repo: 'BitReport.pt/CRM_Project',
|
||||
file_path: '/src/x.ts',
|
||||
line_number: 3,
|
||||
}),
|
||||
@@ -54,7 +54,7 @@ describe('GET /api/error-monitoring/recent-errors', () => {
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { data: Array<{ gitea_repo?: string; file_path?: string }> };
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].gitea_repo).toBe('BitReport.pt/WDMI_STORE');
|
||||
expect(body.data[0].gitea_repo).toBe('BitReport.pt/CRM_Project');
|
||||
expect(body.data[0].file_path).toBe('/src/x.ts');
|
||||
});
|
||||
|
||||
@@ -84,4 +84,147 @@ describe('GET /api/error-monitoring/recent-errors', () => {
|
||||
const body = res.json() as { data: Array<{ gitea_repo?: string }> };
|
||||
expect(body.data[0].gitea_repo).toBeUndefined();
|
||||
});
|
||||
|
||||
it('includes top-level paperclip_project_id when stored in context_json', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([
|
||||
[
|
||||
{
|
||||
incident_id: '2',
|
||||
occurrence_id: '100',
|
||||
project_slug: 'crm',
|
||||
incident_severity: 'high',
|
||||
incident_state: 'open',
|
||||
message: 'probe',
|
||||
stack_trace: '',
|
||||
context_json: JSON.stringify({
|
||||
paperclip_project_id: 'dba3fc26-c728-4e51-a23c-083881a2f534',
|
||||
}),
|
||||
environment: 'production',
|
||||
occurred_at: '2026-01-01T00:00:00.000Z',
|
||||
} as RowDataPacket,
|
||||
],
|
||||
]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors?api_key=test-recent-errors-key',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { data: Array<{ paperclip_project_id?: string }> };
|
||||
expect(body.data[0].paperclip_project_id).toBe('dba3fc26-c728-4e51-a23c-083881a2f534');
|
||||
});
|
||||
|
||||
it('omits paperclip_project_id when not present in context', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([
|
||||
[
|
||||
{
|
||||
incident_id: '3',
|
||||
occurrence_id: '101',
|
||||
project_slug: 'wdmi-store',
|
||||
incident_severity: 'low',
|
||||
incident_state: 'open',
|
||||
message: 'y',
|
||||
stack_trace: '',
|
||||
context_json: JSON.stringify({ project_slug: 'wdmi-store' }),
|
||||
environment: 'production',
|
||||
occurred_at: '2026-01-01T00:00:00.000Z',
|
||||
} as RowDataPacket,
|
||||
],
|
||||
]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors?api_key=test-recent-errors-key',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { data: Array<{ paperclip_project_id?: string }> };
|
||||
expect(body.data[0].paperclip_project_id).toBeUndefined();
|
||||
});
|
||||
|
||||
it('paginates by incident (er_incidents) first when no q is given, incl. status=resolved (BIT-29730)', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors?status=resolved&limit=50&api_key=test-recent-errors-key',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
const [sql, params] = execute.mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('selected_incidents');
|
||||
expect(sql).not.toContain('o.message LIKE');
|
||||
// ['resolved', limit, offset]
|
||||
expect(params).toEqual(['resolved', 50, 0]);
|
||||
});
|
||||
|
||||
it('falls back to the occurrence-first scan when q is given', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors?status=resolved&q=boom&limit=10&api_key=test-recent-errors-key',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const [sql, params] = execute.mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).not.toContain('selected_incidents');
|
||||
expect(sql).toContain('o.message LIKE');
|
||||
// ['resolved', '%boom%', '%boom%', '%boom%', limit, offset]
|
||||
expect(params).toEqual(['resolved', '%boom%', '%boom%', '%boom%', 10, 0]);
|
||||
});
|
||||
|
||||
it('serves the /v1/paperclip/recent-errors alias from the same handler (BIT-31442)', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/v1/paperclip/recent-errors?api_key=test-recent-errors-key',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('accepts the resolve key via X-Api-Key header (BIT-31442)', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors',
|
||||
headers: { 'x-api-key': 'test-recent-errors-key' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('accepts the read-only view key via X-Api-Key header (BIT-31442)', async () => {
|
||||
const prevView = process.env.DEBUG_VIEW_ERRORS_KEY;
|
||||
process.env.DEBUG_VIEW_ERRORS_KEY = 'test-view-key';
|
||||
try {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors',
|
||||
headers: { 'x-api-key': 'test-view-key' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
} finally {
|
||||
if (prevView === undefined) {
|
||||
delete process.env.DEBUG_VIEW_ERRORS_KEY;
|
||||
} else {
|
||||
process.env.DEBUG_VIEW_ERRORS_KEY = prevView;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an invalid X-Api-Key header with 401 (BIT-31442)', async () => {
|
||||
const execute = vi.fn().mockResolvedValue([[]]);
|
||||
const app = await buildApp(execute);
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/error-monitoring/recent-errors',
|
||||
headers: { 'x-api-key': 'wrong-key' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -65,6 +65,15 @@ function extractFileLine(ctx: Record<string, unknown> | null): { file_path: stri
|
||||
return { file_path, line_number };
|
||||
}
|
||||
|
||||
function ctxStr(ctx: Record<string, unknown> | null, keys: string[]): string {
|
||||
if (!ctx) return '';
|
||||
for (const k of keys) {
|
||||
const v = ctx[k];
|
||||
if (typeof v === 'string' && v.trim() !== '') return v.trim();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/** Paperclip error loop reads top-level `gitea_repo` on each recent-error row. */
|
||||
function extractGiteaRepo(ctx: Record<string, unknown> | null): string {
|
||||
if (!ctx) {
|
||||
@@ -74,6 +83,15 @@ function extractGiteaRepo(ctx: Record<string, unknown> | null): string {
|
||||
return typeof raw === 'string' ? raw.trim() : '';
|
||||
}
|
||||
|
||||
/** Paperclip error loop reads top-level `paperclip_project_id` to route issues to the correct project. */
|
||||
function extractPaperclipProjectId(ctx: Record<string, unknown> | null): string {
|
||||
if (!ctx) {
|
||||
return '';
|
||||
}
|
||||
const raw = ctx.paperclip_project_id ?? ctx.paperclipProjectId;
|
||||
return typeof raw === 'string' ? raw.trim() : '';
|
||||
}
|
||||
|
||||
function parseStatusList(raw: string | undefined): string[] | null {
|
||||
if (raw == null || raw.trim() === '') {
|
||||
return ['open', 'investigating'];
|
||||
@@ -149,28 +167,80 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
|
||||
orderRaw === 'occurred_at_asc' ? 'r.occurred_at ASC, r.id ASC' : 'r.occurred_at DESC, r.id DESC';
|
||||
|
||||
const statePlaceholders = states.map(() => '?').join(', ');
|
||||
const conditions: string[] = [`i.current_state IN (${statePlaceholders})`];
|
||||
const params: Array<string | number> = [...states];
|
||||
const incidentConditions: string[] = [`i.current_state IN (${statePlaceholders})`];
|
||||
const incidentParams: Array<string | number> = [...states];
|
||||
|
||||
if (q.severity != null && q.severity !== '') {
|
||||
conditions.push('i.severity = ?');
|
||||
params.push(q.severity.trim().toLowerCase());
|
||||
incidentConditions.push('i.severity = ?');
|
||||
incidentParams.push(q.severity.trim().toLowerCase());
|
||||
}
|
||||
|
||||
if (q.project_slug != null && q.project_slug.trim() !== '') {
|
||||
conditions.push('p.slug = ?');
|
||||
params.push(q.project_slug.trim().toLowerCase());
|
||||
incidentConditions.push('p.slug = ?');
|
||||
incidentParams.push(q.project_slug.trim().toLowerCase());
|
||||
}
|
||||
|
||||
if (q.q != null && q.q.trim() !== '') {
|
||||
const term = `%${q.q.trim()}%`;
|
||||
conditions.push('(i.title LIKE ? OR o.message LIKE ? OR i.fingerprint LIKE ?)');
|
||||
params.push(term, term, term);
|
||||
}
|
||||
const incidentWhereClause = incidentConditions.join(' AND ');
|
||||
const hasSearch = q.q != null && q.q.trim() !== '';
|
||||
|
||||
const whereClause = conditions.join(' AND ');
|
||||
let sql: string;
|
||||
let params: Array<string | number>;
|
||||
|
||||
const sql = `
|
||||
if (!hasSearch) {
|
||||
// Fast path (BIT-29730, tightened in BIT-30040): page through er_incidents
|
||||
// first (small, indexed by current_state) and fetch only the single latest
|
||||
// occurrence per selected incident via a correlated subquery. Earlier this
|
||||
// still used ROW_NUMBER() over ALL occurrences of the selected incidents —
|
||||
// MariaDB can't turn PARTITION BY into a loose index scan, so it
|
||||
// materialized and sorted the entire occurrence history of every matching
|
||||
// incident before filtering rn = 1. Fleet-audit-scale "mega-incidents"
|
||||
// (100k+ occurrences each) blew that up to minutes even after the
|
||||
// incident-first paging fix. A `LIMIT 1` correlated subquery per incident
|
||||
// instead walks er_incident_occurrences_incident_time_idx
|
||||
// (incident_id, occurred_at DESC) and stops at the first row — no
|
||||
// materialization of the rest of that incident's history.
|
||||
const incidentOrderDir = orderRaw === 'occurred_at_asc' ? 'ASC' : 'DESC';
|
||||
sql = `
|
||||
WITH selected_incidents AS (
|
||||
SELECT i.id AS incident_id
|
||||
FROM er_incidents i
|
||||
INNER JOIN er_projects p ON p.id = i.project_id
|
||||
WHERE ${incidentWhereClause}
|
||||
ORDER BY i.last_seen_at ${incidentOrderDir}, i.id ${incidentOrderDir}
|
||||
LIMIT ? OFFSET ?
|
||||
)
|
||||
SELECT CAST(i.id AS CHAR) AS incident_id,
|
||||
CAST(r.id AS CHAR) AS occurrence_id,
|
||||
p.slug AS project_slug,
|
||||
i.severity AS incident_severity,
|
||||
i.current_state AS incident_state,
|
||||
r.message,
|
||||
r.stack_trace,
|
||||
r.context_json,
|
||||
r.environment,
|
||||
r.occurred_at
|
||||
FROM selected_incidents si
|
||||
INNER JOIN er_incidents i ON i.id = si.incident_id
|
||||
INNER JOIN er_projects p ON p.id = i.project_id
|
||||
INNER JOIN er_incident_occurrences r ON r.id = (
|
||||
SELECT o.id
|
||||
FROM er_incident_occurrences o
|
||||
WHERE o.incident_id = si.incident_id
|
||||
ORDER BY o.occurred_at DESC, o.id DESC
|
||||
LIMIT 1
|
||||
)
|
||||
ORDER BY ${orderSql}
|
||||
`;
|
||||
params = [...incidentParams, limit, offset];
|
||||
} else {
|
||||
// Search path: `q` matches against occurrence message too, so an incident's
|
||||
// latest occurrence isn't necessarily the one that matched. Keep the
|
||||
// original occurrence-first scan for correctness; status=resolved + q can
|
||||
// still be slow (not the case reported in BIT-29730, tracked separately).
|
||||
const term = `%${q.q!.trim()}%`;
|
||||
const conditions = [...incidentConditions, '(i.title LIKE ? OR o.message LIKE ? OR i.fingerprint LIKE ?)'];
|
||||
const whereClause = conditions.join(' AND ');
|
||||
sql = `
|
||||
WITH ranked AS (
|
||||
SELECT o.id,
|
||||
o.incident_id,
|
||||
@@ -202,8 +272,8 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
|
||||
ORDER BY ${orderSql}
|
||||
LIMIT ? OFFSET ?
|
||||
`;
|
||||
|
||||
params.push(limit, offset);
|
||||
params = [...incidentParams, term, term, term, limit, offset];
|
||||
}
|
||||
|
||||
const [rows] = await db.execute<RowDataPacket[]>(sql, params);
|
||||
|
||||
@@ -211,6 +281,7 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
|
||||
const ctx = parseJsonObject(row.context_json != null ? String(row.context_json) : null);
|
||||
const { file_path, line_number } = extractFileLine(ctx);
|
||||
const gitea_repo = extractGiteaRepo(ctx);
|
||||
const paperclip_project_id = extractPaperclipProjectId(ctx);
|
||||
const incSev = String(row.incident_severity ?? 'medium').toLowerCase();
|
||||
const sev = ['critical', 'high', 'medium', 'low'].includes(incSev) ? incSev : 'medium';
|
||||
const st = String(row.incident_state ?? 'open').toLowerCase();
|
||||
@@ -238,6 +309,18 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
|
||||
if (gitea_repo !== '') {
|
||||
rowOut.gitea_repo = gitea_repo;
|
||||
}
|
||||
const extra: Record<string, string> = {
|
||||
component: ctxStr(ctx, ['component']),
|
||||
release_version: ctxStr(ctx, ['release_version', 'release', 'app_version']),
|
||||
runtime_name: ctxStr(ctx, ['runtime_name', 'runtime']),
|
||||
host_name: ctxStr(ctx, ['host_name', 'hostname', 'host']),
|
||||
};
|
||||
for (const [k, v] of Object.entries(extra)) {
|
||||
if (v !== '') rowOut[k] = v;
|
||||
}
|
||||
if (paperclip_project_id !== '') {
|
||||
rowOut.paperclip_project_id = paperclip_project_id;
|
||||
}
|
||||
return rowOut;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* BitReport Error Reporter — lightweight Node.js client for errors.bitreport.pt
|
||||
*
|
||||
* Zero dependencies (uses native fetch). Drop this file into any Node.js 18+ project.
|
||||
* Zero dependencies (uses native fetch). Drop this file into any Node.js 24+ project.
|
||||
*
|
||||
* Usage:
|
||||
* import { initReporter, reportError, reportMessage } from './errorReporter.mjs';
|
||||
|
||||
@@ -4,7 +4,7 @@ declare(strict_types=1);
|
||||
/**
|
||||
* BitReport Error Reporter — PHP client for errors.bitreport.pt ingest API.
|
||||
*
|
||||
* Drop this file into any PHP 8+ project. No Composer dependencies.
|
||||
* Drop this file into any PHP 8.4+ project. No Composer dependencies.
|
||||
*
|
||||
* Usage:
|
||||
* require_once __DIR__ . '/ErrorReporter.php';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM node:20-bookworm-slim AS build
|
||||
FROM node:24-bookworm-slim AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
@@ -6,7 +6,7 @@ COPY tsconfig.json ./
|
||||
COPY src ./src
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-bookworm-slim
|
||||
FROM node:24-bookworm-slim
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
COPY package.json package-lock.json ./
|
||||
|
||||
Generated
+9
-9
@@ -12,13 +12,13 @@
|
||||
"mysql2": "^3.11.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^2.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -828,12 +828,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.19.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz",
|
||||
"integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",
|
||||
"version": "24.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
|
||||
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
"undici-types": ">=7.24.0 <7.24.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/expect": {
|
||||
@@ -1519,9 +1519,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
|
||||
@@ -16,12 +16,12 @@
|
||||
"mysql2": "^3.11.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^2.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Irreversible: WDMI project rows and incident history were purged in the up migration (BIT-24704).
|
||||
-- Re-onboarding WDMI slugs is intentionally blocked in ingest-api (`retiredProjects.ts`).
|
||||
|
||||
BEGIN;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,29 @@
|
||||
BEGIN;
|
||||
|
||||
-- Retire WDMI-family projects from the hub (BIT-24704).
|
||||
-- Slug families: wdmi, wdmi-*, *-wdmi, crm-wdmi*.
|
||||
|
||||
UPDATE er_ingest_keys k
|
||||
INNER JOIN er_projects p ON p.id = k.project_id
|
||||
SET k.status = 'revoked',
|
||||
k.revoked_at = NOW(6)
|
||||
WHERE LOWER(p.slug) = 'wdmi'
|
||||
OR LOWER(p.slug) LIKE 'wdmi-%'
|
||||
OR LOWER(p.slug) LIKE '%-wdmi'
|
||||
OR LOWER(p.slug) LIKE 'crm-wdmi%';
|
||||
|
||||
UPDATE er_collector_sources cs
|
||||
INNER JOIN er_projects p ON p.id = cs.project_id
|
||||
SET cs.is_active = FALSE
|
||||
WHERE LOWER(p.slug) = 'wdmi'
|
||||
OR LOWER(p.slug) LIKE 'wdmi-%'
|
||||
OR LOWER(p.slug) LIKE '%-wdmi'
|
||||
OR LOWER(p.slug) LIKE 'crm-wdmi%';
|
||||
|
||||
DELETE FROM er_projects
|
||||
WHERE LOWER(slug) = 'wdmi'
|
||||
OR LOWER(slug) LIKE 'wdmi-%'
|
||||
OR LOWER(slug) LIKE '%-wdmi'
|
||||
OR LOWER(slug) LIKE 'crm-wdmi%';
|
||||
|
||||
COMMIT;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
BEGIN;
|
||||
|
||||
DROP INDEX IF EXISTS er_incidents_state_seen_idx ON er_incidents;
|
||||
|
||||
COMMIT;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
BEGIN;
|
||||
|
||||
-- BIT-29730: GET /api/error-monitoring/recent-errors timed out for status=resolved.
|
||||
-- er_incidents_project_state_seen_idx (project_id, current_state, last_seen_at DESC)
|
||||
-- only helps when project_slug is also filtered. recent-errors now filters/paginates
|
||||
-- er_incidents by current_state alone (no project_id) before touching occurrences,
|
||||
-- so add a state-only index to support that lookup.
|
||||
CREATE INDEX IF NOT EXISTS er_incidents_state_seen_idx
|
||||
ON er_incidents (current_state, last_seen_at DESC);
|
||||
|
||||
COMMIT;
|
||||
@@ -57,6 +57,8 @@ _run_sql "${_MIG_ER}/20260322044500_add_ingest_idempotency.up.sql"
|
||||
_run_sql "${_MIG_ER}/20260322045000_create_collectors_retention_and_audit.up.sql"
|
||||
_run_sql "${_MIG_ER}/20260402103000_add_occurred_at_for_stats.up.sql"
|
||||
_run_sql "${_MIG_ER}/20260402140000_ingest_key_rate_limits.up.sql"
|
||||
_run_sql "${_MIG_ER}/20260608150000_retire_wdmi_projects.up.sql"
|
||||
_run_sql "${_MIG_ER}/20260824120000_add_incidents_state_seen_idx.up.sql"
|
||||
_run_sql "${_MIG_ADMIN}/001_admin_users.sql"
|
||||
_run_sql "${_MIG_ADMIN}/002_admin_refresh_tokens.sql"
|
||||
_run_sql "${_MIG_ADMIN}/003_audit_logs.sql"
|
||||
|
||||
@@ -44,6 +44,28 @@ if [[ "${ER_WEBHOOK_RESTART_SERVICES:-1}" == "1" ]]; then
|
||||
systemctl restart bitreport-error-reporting-admin-ui.service
|
||||
systemctl restart bitreport-error-reporting-collector-worker.service
|
||||
systemctl restart bitreport-error-reporting-api.service
|
||||
|
||||
# Auto-apply resolve-fixed-patterns after every deploy so code fixes clear stale incidents.
|
||||
if [[ -n "${ERROR_RESOLVE_API_KEY:-}" ]]; then
|
||||
_api_port="${ER_API_PORT:-3200}"
|
||||
_ready=0
|
||||
for _i in $(seq 1 20); do
|
||||
if curl -sf "http://localhost:${_api_port}/health" >/dev/null 2>&1; then
|
||||
_ready=1; break
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
if [[ "${_ready}" == "1" ]]; then
|
||||
curl -sf -X POST "http://localhost:${_api_port}/api/error-monitoring/resolve-fixed-patterns" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"api_key\":\"${ERROR_RESOLVE_API_KEY}\"}" \
|
||||
>/dev/null 2>&1 \
|
||||
&& echo "webhook-deploy: resolve-fixed-patterns applied" \
|
||||
|| echo "webhook-deploy: WARN resolve-fixed-patterns failed (non-fatal)"
|
||||
else
|
||||
echo "webhook-deploy: WARN API not ready after 60s, skipping resolve-fixed-patterns"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "webhook-deploy: done"
|
||||
@@ -59,6 +59,10 @@ Alias: `GET /v1/paperclip/recent-errors` (same handler).
|
||||
|
||||
**Query:** `api_key` *or* `view_errors`, plus optional `limit`, `offset`, `status`, `severity`, `project_slug`, `q`, `order`.
|
||||
|
||||
**Header (BIT-31442):** `X-Api-Key: <key>` is accepted as an alternative to the `api_key`/`view_errors` query params, so programmatic callers can avoid leaking the key in URLs and access logs. The header may carry either `ERROR_RESOLVE_API_KEY`/`ERROR_REPORTING_API_KEY` or the read-only `DEBUG_VIEW_ERRORS_KEY`.
|
||||
|
||||
> **Proxy note (BIT-31442):** the `/v1/paperclip/*` alias is served by the admin API (port 3200), not ingest-api (port 3041). The `admin-ui` Next.js rewrite routes `/v1/paperclip/:path*` to the admin API *before* the generic `/v1/:path*` → ingest-api rule. If the alias returns 404 in production, verify that rewrite order in `admin-ui/next.config.ts`.
|
||||
|
||||
**Response 200**
|
||||
|
||||
```json
|
||||
|
||||
@@ -72,7 +72,7 @@ Automation or Grafana can **poll** that endpoint on an interval (with read key)
|
||||
|--------|--------|---------|
|
||||
| `er_ingest_request_duration_seconds` | `status_code` | End-to-end POST latency (SLO: watch p95/p99) |
|
||||
| `er_ingest_requests_total` | `status_code` | Request volume by outcome class |
|
||||
| `er_ingest_events_total` | `outcome` | `stored`, `skipped_noise`, `error` |
|
||||
| `er_ingest_events_total` | `outcome`, `rule_id` | `stored` / `error` use empty `rule_id`; `skipped_noise` sets noise policy id (e.g. `resize_observer_loop`) |
|
||||
| `er_ingest_batch_size` | — | Histogram of events per request |
|
||||
| `er_ingest_active_connections` | — | In-flight requests (gauge) |
|
||||
|
||||
@@ -84,7 +84,7 @@ Plus `er_ingest_*` process defaults from `prom-client`.
|
||||
|
||||
1. **Ingest availability:** `sum(rate(er_ingest_requests_total[5m])) by (status_code)`.
|
||||
2. **Ingest latency:** histogram quantiles on `er_ingest_request_duration_seconds` (e.g. `histogram_quantile(0.95, …)`).
|
||||
3. **Noise vs stored:** `rate(er_ingest_events_total{outcome="stored"}[5m])` vs `skipped_noise`.
|
||||
3. **Noise vs stored:** `rate(er_ingest_events_total{outcome="stored"}[5m])` vs `skipped_noise`. Per-rule noise: `sum(rate(er_ingest_events_total{outcome="skipped_noise"}[5m])) by (rule_id)`.
|
||||
4. **Open incidents:** `er_incidents_total` by `state` (after stats refresh).
|
||||
5. **Hub HTTP errors:** `sum(rate(er_api_http_requests_total{status_code=~"5.."}[5m]))`.
|
||||
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
# DevOps runbook — SSH from Paperclip host to WDMI Importer (BIT-1044)
|
||||
|
||||
**Issue:** [BIT-1044](/BIT/issues/BIT-1044)
|
||||
**Unblocks:** [BIT-1041](/BIT/issues/BIT-1041) (Importer maintenance scripts on the production guest, not in `WDMI_UBUNTU` git).
|
||||
|
||||
## Goal
|
||||
|
||||
From the Paperclip execution host (**`10.10.50.17`**, user **`paperclip`**), run:
|
||||
|
||||
```bash
|
||||
ssh -o BatchMode=yes -o ConnectTimeout=10 root@192.168.1.123 echo ok
|
||||
```
|
||||
|
||||
Expected stdout: `ok` (no password prompt).
|
||||
|
||||
Canonical Importer LAN IP and deploy path: [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) §2.
|
||||
|
||||
## Prerequisites (network)
|
||||
|
||||
The host has **dual homing**: VLAN **1050** (`10.10.50.17`) and LAN **`192.168.1.0/24`** (`192.168.1.239` on `eth1`). Traffic to **`192.168.1.123`** must leave via **`eth1`** with working L2/L3 to the Importer.
|
||||
|
||||
**Typical failure (pre-fix):** `ip neigh show 192.168.1.123` stays **`INCOMPLETE`** / **`FAILED`**; `ping` loss; SSH **`No route to host`**.
|
||||
|
||||
**Route OK, auth missing:** SSH connects (no *No route to host*) but **`Permission denied (publickey,password)`** with **BatchMode** means **TCP/22** is fine and **`root`** is not yet accepting **`paperclip@bitreport-cto`** — apply the **SSH key** section below on **`192.168.1.123`** (console or an existing privileged session).
|
||||
|
||||
**Isolation check (Paperclip host, 2026-04):** On **`10.10.50.17`**, if **`192.168.1.1`** (gateway) and **`192.168.1.17`** (CT 220 `wdmi-store` `eth1`) answer **`ping`** but **`192.168.1.123`** does not, the Paperclip **`eth1`** path on **`192.168.1.0/24`** is healthy and the fault is almost certainly **Importer-specific** (wrong IP, guest down, host firewall, isolated switch port, or ACL dropping that host). Fix those before spending time on VLAN **1050** routing.
|
||||
|
||||
**Operator actions (edge firewall / switch / guest):**
|
||||
|
||||
1. Confirm **`192.168.1.123`** is the live Importer address (vault / inventory).
|
||||
2. Allow **TCP/22** from at least:
|
||||
- **`192.168.1.239`** (Paperclip `eth1`), and
|
||||
- **`192.168.1.17`** (CT 220 `wdmi-store` `eth1`, if CTO uses that hop).
|
||||
3. Ensure the Importer OS is up, `sshd` listening on **`:22`**, and no host firewall drops those sources.
|
||||
|
||||
## SSH key (Paperclip → `root` on Importer)
|
||||
|
||||
Use the same **Ed25519** public key as [BIT-720](/BIT/issues/BIT-720) / [BIT-721](/BIT/issues/BIT-721) (`paperclip@bitreport-cto`):
|
||||
|
||||
On **`10.10.50.17`** as **`paperclip`**:
|
||||
|
||||
```bash
|
||||
cat ~/.ssh/id_ed25519.pub
|
||||
```
|
||||
|
||||
On **`192.168.1.123`** as a user with privilege to edit **`root`** keys (console, IPMI, or existing SSH):
|
||||
|
||||
```bash
|
||||
install -d -m 700 /root/.ssh
|
||||
touch /root/.ssh/authorized_keys
|
||||
chmod 600 /root/.ssh/authorized_keys
|
||||
grep -qF '<paste line from id_ed25519.pub>' /root/.ssh/authorized_keys || echo '<paste line>' >> /root/.ssh/authorized_keys
|
||||
```
|
||||
|
||||
**Do not** commit private keys or paste them into issues.
|
||||
|
||||
## Alternative path (Proxmox guest)
|
||||
|
||||
If the Importer is an LXC/VM on **node9** and LAN routing cannot be fixed quickly, **`root`** on the Paperclip host may use **`pct`** via **`ssh [email protected]`** after one-time trust — see Paperclip meta-repo `docs/runbooks/AUTOMATION_PAPERCLIP_HOST_NODE9.md` and `tools/proxmox/push_pubkey_to_lxc_via_node9.sh` (workstation or **`root`** on **10.10.50.17** with node9 key). The unprivileged **`paperclip`** account does not perform that hop unless explicitly configured.
|
||||
|
||||
## Verification (automation-friendly)
|
||||
|
||||
From the **`errors.bitreport.pt`** repo on a machine that should have access (normally **10.10.50.17**):
|
||||
|
||||
```bash
|
||||
./scripts/devops/verify_importer_ssh_bit1044.sh
|
||||
```
|
||||
|
||||
Exit code **0** only when the BatchMode SSH check succeeds.
|
||||
|
||||
## Related hub docs
|
||||
|
||||
- [BIT-1079](/BIT/issues/BIT-1079) — CTO escalation when **`192.168.1.123`** is offline or LAN routing is broken for multiple dependents ([BIT-1044](/BIT/issues/BIT-1044), [BIT-1041](/BIT/issues/BIT-1041), etc.).
|
||||
- [RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md](RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md) — Importer reachability note for runners.
|
||||
- [RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md](RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) — Importer deploy references.
|
||||
@@ -121,7 +121,7 @@ When **`Idempotency-Key`** is reused with a **different** JSON body, the API ret
|
||||
|
||||
## 7. Noise rules — events “disappear”
|
||||
|
||||
If the response shows `results[]` entries with `"skipped": true`, the event matched a **noise rule** (`rule_id`, `reason`). This is expected for filtered traffic. Check `noise_filtered_count` and compare with `er_ingest_events_total{outcome="skipped_noise"}` in Prometheus.
|
||||
If the response shows `results[]` entries with `"skipped": true`, the event matched a **noise rule** (`rule_id`, `reason`). This is expected for filtered traffic. Check `noise_filtered_count` and compare with `er_ingest_events_total{outcome="skipped_noise"}` in Prometheus (series also carry `rule_id`).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
# Runbook — `wdmi-store` Importer: `mkdir(): File exists` (cache em disco)
|
||||
|
||||
**Audiência:** Operação e engenharia que mantêm **aplicações que reportam** para `errors.bitreport.pt` (ex.: `wdmi-store` / `Importer`).
|
||||
**Não confundir com** falhas de **ingest** no hub — para isso ver [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md).
|
||||
**Contraste:** [RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md](RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md) cobre **`mkdir(): Permission denied`** no CRM; aqui a mensagem é **`File exists`**, com causa raiz diferente.
|
||||
|
||||
**Última revisão:** 2026-04-05
|
||||
**Contexto:** O stack no hub pode citar **`Engine\CacheFilesystem::putFile()`** / `CacheFilesystem.class.php` (~28) em instalações ou árvores antigas; no **Importer que alimenta produção** (`BitReport.pt/WDMI_UBUNTU`, sync para o guest — ver comentários em [BIT-985](/BIT/issues/BIT-985)), a criação de directórios de cache foi corrigida em **`Engine/Cache.class.php`** (`setCachedFile()` → `ensureCacheDirectory()` com `mkdir` idempotente, commit [4cd6d10d](https://git.bitreport.pt/BitReport.pt/WDMI_UBUNTU/commit/4cd6d10d) em `master`). A corrida manifesta-se sob jobs paralelos (`__maintenance_build.php`, `_ingram.php`, etc.). No hub: [BIT-924](/BIT/issues/BIT-924), cluster `ERRCLUSTER:57ccbd98f57e`, loop [BIT-309](/BIT/issues/BIT-309). **Se a assinatura voltar após [BIT-985](/BIT/issues/BIT-985) fechada com gate de deploy:** confirmar que **todo** o código em execução no guest inclui `ensureCacheDirectory` (pull/webhook, sem PHP opcache antigo) e resolver incidentes antigos no hub com `er-cli`.
|
||||
|
||||
---
|
||||
|
||||
## 1. O que o erro significa
|
||||
|
||||
- O código tenta **`mkdir()`** para garantir um directório de cache antes de escrever um ficheiro.
|
||||
- **`mkdir(): File exists`** (PHP warning, frequentemente capturado pelo `ErrorMonitoringReporter`) significa que o alvo **já existe no filesystem** de forma incompatível com `mkdir` naquele momento — não é (tipicamente) falta de permissão (ver runbook CRM acima).
|
||||
- Causas frequentes:
|
||||
1. **Condição de corrida:** dois ou mais processos PHP criam o mesmo subdirectório em simultâneo; um ganha e o outro recebe `EEXIST`.
|
||||
2. **Colisão path/ficheiro:** o segmento final do caminho de cache **já é um ficheiro** (chave de cache mapeada para um path inválido, artefacto de deploy, ou limpeza parcial).
|
||||
3. **Estrutura inconsistente:** symlink ou árvore de cache partilhada entre ambientes/jobs de forma inesperada.
|
||||
|
||||
Isto é um problema **no host `wdmi-store` / código Importer e uso concorrente do cache**, não do hub de erros.
|
||||
|
||||
---
|
||||
|
||||
## 2. Reprodução e diagnóstico no host afetado
|
||||
|
||||
Executar no servidor onde está o Importer (caminho típico `/data/wwwroot/default/Importer/`).
|
||||
|
||||
1. **Identificar onde o `mkdir` é chamado na árvore *real* em execução:**
|
||||
- Preferir **`Engine/Cache.class.php`** — procurar `ensureCacheDirectory` / `setCachedFile` / `mkdir`.
|
||||
- Em árvores legadas ou monorepos diferentes, pode existir **`Engine/CacheFilesystem.class.php`**; alinhar o diagnóstico ao ficheiro que o autoload efectivamente carrega.
|
||||
2. **Correlacionar com o evento no hub:** `unique_id` / contexto da mensagem, se disponível, e horário — cruzar com **cron** de `__maintenance_build.php`, jobs `_ingram.php`, e número de workers PHP.
|
||||
3. **Inspeccionar o path alvo** quando o erro ocorre (log adicional temporário ou `strace` / audit em ambiente de staging, se política permitir):
|
||||
- Se o último componente **já existe como ficheiro** → tratar como colisão de naming ou limpeza.
|
||||
- Se é directório e o erro é esporádico sob carga → forte indício de **corrida**.
|
||||
4. **Listar concorrência:** verificar se o mesmo job está agendado em sobreposição (múltiplas entradas crontab, `systemd` timers, ou deploy com duas versões a correr).
|
||||
|
||||
---
|
||||
|
||||
## 3. Checklist de causa raiz (ordem sugerida)
|
||||
|
||||
1. **Sobreposição de jobs** — duas instâncias do mesmo maintenance/import ao mesmo tempo.
|
||||
2. **Race em `mkdir`** — código que não trata “já existe” de forma idempotente (deveria usar `is_dir` / `clearstatcache` após `@mkdir`, ou tratar `EEXIST` como sucesso quando o resultado final é um directório válido).
|
||||
3. **Colisão ficheiro vs directório** no path de cache.
|
||||
4. **Cache partilhado** entre utilizadores/processos com permissões que permitem criar ficheiros no meio da árvore esperada.
|
||||
5. **Deploy incompleto** — repositório corrigido em Gitea mas guest ainda sem `ensureCacheDirectory` em `Cache.class.php` (ver §2).
|
||||
6. **Não mascarar no hub** — não filtrar esta assinatura como ruído até existir correção ou mitigação no Importer em execução; alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md) quando existir no repositório.
|
||||
|
||||
---
|
||||
|
||||
## 4. Mitigação recomendada (código / operações)
|
||||
|
||||
- **Código (referência aplicada em WDMI_UBUNTU):** `ensureCacheDirectory()` com criação recursiva idempotente (`@mkdir`, `clearstatcache`, validação `is_dir`; retry sem `@` em falhas reais) antes de escrever ficheiros em cache — ver [BIT-985](/BIT/issues/BIT-985) e commit ligado no § *Contexto*.
|
||||
- **Operações:** evitar **overlap** explícito de crons pesados; garantir **single runner** por job de manutenção onde aplicável; após `git pull`, reiniciar PHP-FPM se necessário para limpar opcache.
|
||||
- Após deploy da correcção, **resolver** incidentes no hub conforme [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) e confirmar ausência de novos eventos com a mesma `ERRSIG`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Ligação ao hub (errors.bitreport.pt)
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:57ccbd98f57e"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:db6f9979f37d"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "db6f9979f37d"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "Cache.class.php"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "CacheFilesystem.class.php"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "mkdir(): File exists"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "CacheFilesystem"
|
||||
```
|
||||
|
||||
### 5.1 Caso documentado — `wdmi-store` / cache (`mkdir` `File exists`, BIT-924)
|
||||
|
||||
- **Paperclip:** [BIT-924](/BIT/issues/BIT-924) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309)); entrega de código em [BIT-985](/BIT/issues/BIT-985).
|
||||
- **Cluster (hub):** `ERRCLUSTER:57ccbd98f57e` (pode coincidir com o título da issue no Paperclip)
|
||||
- **Mensagem típica:** `mkdir(): File exists`
|
||||
- **Origem no stack (hub):** frequentemente `Engine\CacheFilesystem.class.php` (~28) **ou** caminhos via `Engine\Cache` → `ProductInformation` → `Product` → `_ingram.php` / `__maintenance_build.php` — validar no servidor qual ficheiro está em uso.
|
||||
- **Acção no produto:** confirmar mitigação em **`Engine/Cache.class.php`** no guest de produção; usar §2–§3 para corrida vs colisão vs deploy pendente.
|
||||
|
||||
---
|
||||
|
||||
## 6. Evidência de deploy (gate Paperclip `in_review`)
|
||||
|
||||
O comentário automático `paperclip-in-review-gate` exige **evidência de produção** na thread da issue. Quem tiver SSH ao guest Importer deve colar num **comentário** em [BIT-924](/BIT/issues/BIT-924) a saída (ou equivalente) de:
|
||||
|
||||
```bash
|
||||
# No host onde corre o Importer (ajustar path se diferente)
|
||||
grep -n ensureCacheDirectory /data/wwwroot/default/Importer/Engine/Cache.class.php | head -5
|
||||
|
||||
cd /data/wwwroot/default/Importer && (git rev-parse HEAD 2>/dev/null || echo "checkout não-git / path alternativo")
|
||||
```
|
||||
|
||||
Opcional — hub sem incidentes abertos para o cluster:
|
||||
|
||||
```bash
|
||||
# Máquina com ERROR_RESOLVE_API_KEY e acesso à API do hub
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:57ccbd98f57e"
|
||||
```
|
||||
|
||||
**Nota:** mesmo com `eth1` `192.168.1.239/24` no host Paperclip (`10.10.50.17`), o alvo **`192.168.1.123`** (Importer LAN canónico) continua **inacessível** (ICMP sem resposta; TCP/22 *No route to host*; vizinho ARP **INCOMPLETE** / **FAILED**). O mesmo sintoma verifica-se a partir do LXC **CT 220** (`wdmi-store`, `192.168.1.17`). Abrir firewall / rota ou confirmar IP de produção em [BIT-1044](/BIT/issues/BIT-1044). Até lá, runners **não** substituem evidência no guest; só documentar o procedimento.
|
||||
|
||||
**Reabertura pelo loop após `done`:** se o loop [BIT-309](/BIT/issues/BIT-309) voltar a registar recorrência na issue [BIT-924](/BIT/issues/BIT-924) **depois** de o gate `in_review` ter passado e a issue ter ido para `done`, tratar como **revalidação obrigatória**: repetir §6 e §3 — vários pools PHP / opcache, segundo docroot ou release antiga, ou incidentes ainda **abertos** no hub (resolver com `er-cli` após confirmar ausência de novos eventos).
|
||||
|
||||
---
|
||||
|
||||
## Ver também
|
||||
|
||||
- [RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md](RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md) — rede + SSH Paperclip → Importer **192.168.1.123** ([BIT-1044](/BIT/issues/BIT-1044)).
|
||||
- [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) — triagem e fecho no hub.
|
||||
- [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) — upload de feeds (`clients.wdmi.pt`).
|
||||
- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — cenários CLI.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,297 +0,0 @@
|
||||
# Runbook — `simplexml_load_file` no Importer Flexit (`wdmi-store`)
|
||||
|
||||
**Audiência:** Operação e engenharia que mantêm **aplicações que reportam** para `errors.bitreport.pt` (ex.: `wdmi-store` / `Importer`).
|
||||
**Não confundir com** falhas de **ingest** no hub — para isso ver [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md).
|
||||
|
||||
**Última revisão:** 2026-04-05
|
||||
**Contexto:** Erros de PHP em `simplexml_load_file()` originados em `Importer/_flexit.php` (tipicamente linha ~53), incluídos via `__maintenance_build.php`. Exemplos de assinatura no hub: `ERRSIG:6f82e20ec332`, `ERRSIG:5278058355a5`, `ERRSIG:948b0236b852`, `ERRSIG:033b36032168`, `ERRSIG:102101c1758d`, `ERRSIG:37670027b2d7`, `ERRSIG:5e3b58b8a99f`, `ERRSIG:63100e2b35c0`, `ERRSIG:4ca3a546fb62`, `ERRSIG:8e233f7a57b8`.
|
||||
|
||||
---
|
||||
|
||||
## 1. O que o erro significa
|
||||
|
||||
- `simplexml_load_file()` falha quando o **ficheiro ou URL** passado não é legível, não existe, está vazio/corrupto, ou o conteúdo **não é XML válido**.
|
||||
- O stack típico inclui `_flexit.php` ← `__maintenance_build.php` (job de manutenção / build de dados Flexit).
|
||||
|
||||
Isto é um problema **no host / ficheiros de entrada / conteúdo XML** do job Importer, não um bug do hub de erros.
|
||||
|
||||
---
|
||||
|
||||
## 2. Reprodução e diagnóstico no host afetado
|
||||
|
||||
Executar **no mesmo servidor** onde corre o PHP (caminho típico `/data/wwwroot/default/Importer/`).
|
||||
|
||||
1. **Confirmar o argumento efectivo** em `_flexit.php` (caminho local, URL, ou variável derivada) na linha indicada pelo stack — sem isso não há correção segura.
|
||||
2. **Se for caminho local:**
|
||||
- `test -r "<path>" && echo OK || echo unreadable`
|
||||
- `head -c 400 "<path>"` — ver se há conteúdo e se começa por `<?xml` ou elemento raiz esperado.
|
||||
3. **Se for URL remota:**
|
||||
- `curl -sfS --max-time 30 -o /tmp/flexit-sample.xml "<url>" && xmllint --noout /tmp/flexit-sample.xml`
|
||||
- Verificar `allow_url_fopen`, timeouts, TLS e DNS no host (ver também [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md) se o feed passar por HTTPS problemático).
|
||||
4. **Permissões e utilizador do PHP-FPM / Apache** — o processo web/CLI que corre o maintenance script tem de conseguir ler o ficheiro ou alcançar a URL.
|
||||
|
||||
### 2.1 Ficheiro local `FlexIT.XML` (wdmi-store — path típico)
|
||||
|
||||
No host onde corre o Importer, alinhar com o checklist [BIT-984](/BIT/issues/BIT-984) (execução fora de `errors.bitreport.pt`). A partir de `/data/wwwroot/default/Importer`:
|
||||
|
||||
```bash
|
||||
test -r downloads/FlexIT.XML && echo OK || echo unreadable
|
||||
head -c 400 downloads/FlexIT.XML
|
||||
xmllint --noout downloads/FlexIT.XML
|
||||
```
|
||||
|
||||
Equivalente a partir de `/data/wwwroot/default`:
|
||||
|
||||
```bash
|
||||
test -r Importer/downloads/FlexIT.XML && echo OK || echo unreadable
|
||||
head -c 400 Importer/downloads/FlexIT.XML
|
||||
xmllint --noout Importer/downloads/FlexIT.XML
|
||||
```
|
||||
|
||||
Se a fonte for **URL remota**, usar o padrão do §2 (item 3) com o URL efectivo lido em `_flexit.php`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Checklist de causa raiz (ordem sugerida)
|
||||
|
||||
1. **Ficheiro ausente ou path errado** — deploy incompleto, variável de ambiente errada, ou directorio de trabalho diferente entre cron e web.
|
||||
2. **Ficheiro vazio ou truncado** — escrita concorrente, disco cheio, download incompleto.
|
||||
3. **XML inválido** — feed externo alterado, encoding errado (BOM, `UTF-8` vs `ISO-8859-1`), entidades não declaradas.
|
||||
4. **Race / ordem de jobs** — `__maintenance_build.php` a correr antes de o ficheiro estar disponível; considerar lock ou pré-condição explícita no script.
|
||||
5. **Não mascarar no hub** — evitar filtros de ruído até a causa de dados/caminho estar tratada; alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md).
|
||||
|
||||
---
|
||||
|
||||
## 4. Mitigação na aplicação (recomendado)
|
||||
|
||||
- Validar existência e tamanho mínimo **antes** de `simplexml_load_file()`; logar caminho/URL (sanitizado) e `libxml_get_errors()` em falha.
|
||||
- Usar `libxml_use_internal_errors(true)` para mensagens controladas e não depender só do warning genérico.
|
||||
- Tornar o job **idempotente** e, se aplicável, **retry com backoff** quando a fonte for remota e intermitente.
|
||||
|
||||
---
|
||||
|
||||
## 5. Ligação ao hub (errors.bitreport.pt)
|
||||
|
||||
- Listar incidentes abertos por assinatura ou texto:
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:6f82e20ec332"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5278058355a5"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:e83a5ee5e95d"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "e83a5ee5e95d"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:948b0236b852"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:8e1c5d253902"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "8e1c5d253902"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:033b36032168"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "d75e81fb29c9"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:102101c1758d"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:37670027b2d7"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:32b818809f98"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "32b818809f98"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5e3b58b8a99f"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:63100e2b35c0"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:4ca3a546fb62"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:8e233f7a57b8"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "eb0dad83413f"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "f2d78c625221"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "simplexml_load_file"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "_flexit.php"
|
||||
```
|
||||
|
||||
- Após correcção no reporter (ficheiro válido, path correcto, ou tratamento de erro explícito), **resolver** incidentes conforme [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) e confirmar que novos eventos deixaram de ingressar.
|
||||
|
||||
### 5.1 Caso documentado — `wdmi-store` / Flexit (BIT-877)
|
||||
|
||||
- **Assinatura:** `ERRSIG:6f82e20ec332`
|
||||
- **Cluster (loop BIT-309):** `ERRCLUSTER:0eaf1e3a7ef5` — o título ou comentários Paperclip podem referir este cluster; a triagem operacional é a mesma que para a assinatura acima.
|
||||
- **Mensagem típica:** `simplexml_load_file():` (warning/notice capturado pelo reporter)
|
||||
- **Stack útil:** `_flexit.php` ← `__maintenance_build.php`
|
||||
- **Correção aplicacional (histórico):** filho [BIT-915](/BIT/issues/BIT-915) fechado com endurecimento em `WDMI_UBUNTU/default/Importer/_flexit.php` (validação pré-parse, `simplexml_load_string` com flags libxml). **Deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) (`gitea-sync-importer.sh` a partir de `BitReport.pt/WDMI_UBUNTU.git`).
|
||||
- **Acção no produto:** após deploy, confirmar ausência de novos eventos; **resolver** incidentes antigos ainda abertos no hub para esta assinatura/cluster (ver comandos abaixo). Se o cluster voltar a ingressar após deploy verificado, reabrir triagem no produto (feed ou ficheiro local corrupto).
|
||||
- **Ciclo Paperclip:** se [BIT-877](/BIT/issues/BIT-877) for fechada e o loop BIT-309 **reabrir** o mesmo ticket com este cluster, tratar primeiro como **deploy não reflectido** ou **incidentes `open` no hub** — não como defeito novo do repositório `errors.bitreport.pt` sem evidência em produção.
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:0eaf1e3a7ef5"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:6f82e20ec332"
|
||||
```
|
||||
|
||||
### 5.2 Caso documentado — `wdmi-store` / Flexit (BIT-903)
|
||||
|
||||
- **Assinatura:** `ERRSIG:5278058355a5`
|
||||
- **Cluster (loop BIT-309):** `ERRCLUSTER:e83a5ee5e95d` — quando o título ou comentários Paperclip referirem este cluster, a triagem operacional é a mesma que para **ERRSIG:5278058355a5**.
|
||||
- **Paperclip:** [BIT-903](/BIT/issues/BIT-903) (recorrências agregadas pelo loop BIT-309)
|
||||
- **Comentários automáticos de recorrência (BIT-309):** entradas do tipo "Recorrência detetada" na mesma thread confirmam que o loop voltou a observar eventos neste cluster (ou incidentes ainda relevantes no hub). Tratar como **sinal do reporter / dados de entrada** ou backlog de resolução no hub — **não** como falha de ingest em `errors.bitreport.pt`.
|
||||
- **Mensagem típica (excerpt):** texto de erro que inclui fragmentos de markup (`…ebDescription></Record><Record><Manufacturer>HPINC…`) — indica **XML mal formado ou truncado** (parser a falhar no meio do stream), não um problema do hub.
|
||||
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
|
||||
- **Correção aplicacional (referência):** endurecimento em `WDMI_UBUNTU/default/Importer/_flexit.php` e checklist de host em [BIT-915](/BIT/issues/BIT-915) / [BIT-984](/BIT/issues/BIT-984); **deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md). Até o guest reflectir o código ou os dados de entrada estarem estáveis, novos eventos podem continuar a ingressar.
|
||||
- **Acção no produto:** seguir §2–§4 deste runbook no host de `wdmi-store` (validar ficheiro/URL de entrada, `xmllint`, permissões, corrupção de feed); aplicar validação pré-parse e logging com `libxml_get_errors()` antes de marcar resolvido no hub.
|
||||
- **Stack ainda com `simplexml_load_file()` em `_flexit.php` (~53):** tratar primeiro como Importer em produção **sem** o endurecimento BIT-915 (`47d2c2bf`) — usar os mesmos comandos `grep` / `nl` de verificação pós-deploy descritos em §5.3.1 (*Código antigo em produção*, BIT-968); o procedimento é o mesmo para **ERRSIG:5278058355a5** e para as outras assinaturas FlexIT deste runbook.
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5278058355a5"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "5278058355a5"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:e83a5ee5e95d"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "e83a5ee5e95d"
|
||||
```
|
||||
|
||||
### 5.3 Caso documentado — `wdmi-store` / Flexit (BIT-920)
|
||||
|
||||
- **Assinatura:** `ERRSIG:948b0236b852`
|
||||
- **Cluster (loop BIT-309):** `ERRCLUSTER:8e1c5d253902` — o título ou comentários Paperclip podem referir este cluster; a triagem operacional é a mesma que para a assinatura acima.
|
||||
- **Paperclip:** [BIT-920](/BIT/issues/BIT-920) (recorrências agregadas pelo loop BIT-309). Execução no host: follow-up [BIT-968](/BIT/issues/BIT-968) (quando aberto).
|
||||
- **Mensagem típica (excerpt):** `simplexml_load_file(): ><NAVPN>L70777-051-RP</NAVPN><OS></OS><WebDescription></WebDescription></Record>` — fragmento de markup no texto do erro; mesma classe operacional que §5.2 (**XML mal formado ou truncado** / entrada inválida para o parser), não falha de ingest no hub.
|
||||
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
|
||||
- **Acção no produto:** seguir §2–§4 deste runbook no host de `wdmi-store`; alinhar com §5.2 para validação pré-parse e logging. Resolver no hub após deploy e confirmação de ausência de novos eventos com esta assinatura.
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:948b0236b852"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "948b0236b852"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:8e1c5d253902"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "8e1c5d253902"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "NAVPN"
|
||||
```
|
||||
|
||||
#### 5.3.1 Código antigo em produção — `simplexml_load_file()` na linha ~53 (BIT-968)
|
||||
|
||||
- **Projecto no hub vs. guest Proxmox:** o projecto de erros **`wdmi-store`** no hub identifica a **aplicação** que reporta; o caminho típico **`/data/wwwroot/default/Importer/`** é docroot **PHP** (Importer clássico). O LXC **`wdmi-store`** (CT **220**, **10.10.50.20** na matriz interna — ver `docs/ENVIRONMENTS.md` § LXC) é a stack **WDMI_STORE** (Node/Fastify) e **não** expõe, por omissão, esse docroot. **Não** assumir que o hostname do projecto no hub coincide com o guest onde corre o PHP Importer.
|
||||
- **Alvo canónico (deploy PHP Importer):** conforme o [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) §2, o sync da árvore **`WDMI_UBUNTU`** aplica-se ao servidor **Importer** em **LAN `192.168.1.123`** (`/usr/local/sbin/gitea-sync-importer.sh`; fila CRM **69** → SSH ao **123**). O código fonte está no monorepo **`BitReport.pt/WDMI`**, caminho **`WDMI_UBUNTU/default/Importer/`**. Isto **não** é o LXC **CT 220** `wdmi-store` (**WDMI_STORE**). Excepções ao IP ficam apenas no **vault** / inventário aprovado pelo board.
|
||||
- Se o stack no hub ainda mostrar **`simplexml_load_file()`** em **`_flexit.php` (~53)**, o docroot em produção **não** reflecte o Importer endurecido já fundido no monorepo **`BitReport.pt/WDMI`**, caminho **`WDMI_UBUNTU/default/Importer/_flexit.php`** (commit **`47d2c2bf`** — *harden FlexIT XML parse for error hub BIT-915*; antecessor histórico BIT-877 / [BIT-915](/BIT/issues/BIT-915)).
|
||||
- No **`main`** actual de **`BitReport.pt/WDMI`** (directório **`WDMI_UBUNTU/default/Importer/_flexit.php`**), por volta da linha 53 aparece **`$oXML = false;`**, seguido de **`file_get_contents`** + **`simplexml_load_string(..., LIBXML_NOERROR | LIBXML_NOWARNING)`** — não **`simplexml_load_file()`**.
|
||||
- **Remediação:** sincronizar `default/Importer/` para `/data/wwwroot/default/Importer/` conforme o [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) (ex.: **`gitea-sync-importer.sh`** a partir de **`WDMI_UBUNTU`**; alinhar com §5.1 / BIT-915).
|
||||
- **Verificação pós-deploy** no servidor:
|
||||
|
||||
```bash
|
||||
grep -n simplexml_load_file /data/wwwroot/default/Importer/_flexit.php || echo "OK: no simplexml_load_file in _flexit.php"
|
||||
nl -ba /data/wwwroot/default/Importer/_flexit.php | sed -n '50,72p'
|
||||
```
|
||||
|
||||
- Só depois disto faz sentido tratar **feed/XML inválido** como causa residual (§2–§4). Fechar **BIT-968** / **BIT-920** após deploy **e** ausência de novos eventos **`ERRSIG:948b0236b852`** (ver [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md)).
|
||||
|
||||
### 5.4 Caso documentado — `wdmi-store` / Flexit (BIT-926)
|
||||
|
||||
- **Assinatura:** `ERRSIG:033b36032168`
|
||||
- **Cluster (loop BIT-309):** `ERRCLUSTER:d75e81fb29c9` — quando o título ou comentário Paperclip referir este cluster, a triagem operacional é a mesma que para **ERRSIG:033b36032168** (histórico único na board).
|
||||
- **Paperclip:** [BIT-926](/BIT/issues/BIT-926) (recorrências agregadas pelo loop BIT-309)
|
||||
- **Comentários automáticos de recorrência (BIT-309):** entradas do tipo "Recorrência detetada" na mesma thread confirmam que o loop voltou a observar eventos neste cluster — **sem nova causa no hub**; tratar como sinal de **dados de entrada / guest** ou incidentes ainda `open` no hub até deploy e resolução em massa.
|
||||
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : Opening and ending tag mismatch: Record line 1 and ManufacturerPartNumber` — **XML mal formado** (tags não fechadas na ordem esperada ou conteúdo corrupto no ficheiro local `FlexIT.XML`), mesma classe operacional que §5.2–§5.3; não é falha de ingest no hub.
|
||||
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
|
||||
- **Correção aplicacional (referência):** checklist no host + hardening `_flexit.php` em [BIT-984](/BIT/issues/BIT-984) (filha de [BIT-950](/BIT/issues/BIT-950)); **deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md). Até o guest reflectir o código ou o `FlexIT.XML` estar válido, o loop pode continuar a comentar recorrências nesta issue.
|
||||
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (integridade, encoding, escrita concorrente); validar com `xmllint --noout`; seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, idempotência). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:033b36032168"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "033b36032168"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "d75e81fb29c9"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "FlexIT.XML"
|
||||
```
|
||||
|
||||
### 5.5 Caso documentado — `wdmi-store` / Flexit (BIT-932)
|
||||
|
||||
- **Assinatura:** `ERRSIG:102101c1758d`
|
||||
- **Paperclip:** [BIT-932](/BIT/issues/BIT-932) (recorrências agregadas pelo loop BIT-309)
|
||||
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : Couldn't find end of Start Tag Manufac1-RP-N2 line 1` — **XML mal formado** (tag de abertura não fechada / conteúdo corrupto no ficheiro local `FlexIT.XML`), mesma classe operacional que §5.2–§5.4; não é falha de ingest no hub.
|
||||
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
|
||||
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (integridade, encoding, escrita concorrente, feed truncado); validar com `xmllint --noout`; seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, idempotência). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:102101c1758d"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "102101c1758d"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "Manufac1-RP-N2"
|
||||
```
|
||||
|
||||
### 5.6 Caso documentado — `wdmi-store` / Flexit (BIT-939)
|
||||
|
||||
- **Assinatura:** `ERRSIG:37670027b2d7`
|
||||
- **Cluster (loop BIT-309):** `ERRCLUSTER:32b818809f98` — quando o título ou comentários Paperclip referirem este cluster, a triagem operacional é a mesma que para **ERRSIG:37670027b2d7** (histórico único na board).
|
||||
- **Paperclip:** [BIT-939](/BIT/issues/BIT-939) (recorrências agregadas pelo loop BIT-309)
|
||||
- **Comentários automáticos de recorrência (BIT-309):** entradas do tipo "Recorrência detetada" ou "Recorrência após fecho" na mesma thread confirmam que o loop voltou a observar eventos neste cluster — **sem nova causa no hub**; tratar como sinal de **dados de entrada / guest** ou incidentes ainda `open` no hub até deploy e resolução em massa.
|
||||
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : Extra content at the end of the document` — indica **XML com mais do que um documento raiz**, lixo/append após o fecho do documento válido, ou **ficheiro concatenado / escrita concorrente** que deixou bytes extra no `FlexIT.XML` local; mesma classe operacional que §5.2–§5.5; não é falha de ingest no hub.
|
||||
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
|
||||
- **Correção aplicacional (referência):** checklist no host + hardening `_flexit.php` em [BIT-984](/BIT/issues/BIT-984) (filha de [BIT-950](/BIT/issues/BIT-950)); alinhar com [BIT-915](/BIT/issues/BIT-915) e §2–§4; **deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md). Até o guest reflectir o código ou o `FlexIT.XML` estar válido, o loop pode continuar a comentar recorrências nesta issue.
|
||||
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (tamanho, `tail`, procura por segundo `<?xml` ou markup após o fecho do primeiro documento); validar com `xmllint --noout`; rever download atómico / lock se dois jobs escrevem o mesmo path; seguir §2–§4. Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
|
||||
- **Ciclo Paperclip:** se [BIT-939](/BIT/issues/BIT-939) for fechada e o loop BIT-309 **reabrir** a mesma issue com este cluster, tratar primeiro como **dados de entrada / deploy não reflectido** ou **incidentes `open` no hub** — não como defeito novo do repositório `errors.bitreport.pt` sem evidência em produção.
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:37670027b2d7"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "37670027b2d7"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:32b818809f98"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "32b818809f98"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "Extra content at the end"
|
||||
```
|
||||
|
||||
### 5.7 Caso documentado — `wdmi-store` / Flexit (BIT-945)
|
||||
|
||||
- **Assinatura:** `ERRSIG:5e3b58b8a99f`
|
||||
- **Paperclip:** [BIT-945](/BIT/issues/BIT-945) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309))
|
||||
- **Cluster (agregação BIT-309):** `ERRCLUSTER:2f4da462d83a` — pode conter só esta assinatura enquanto o sintoma for estável; tratar como a mesma família que §5.2–§5.6.
|
||||
- **Comentários automáticos de recorrência (BIT-309):** entradas do tipo "Recorrência detetada" ou "Recorrência após fecho" na mesma thread confirmam que o loop voltou a observar eventos neste cluster — **sem nova causa no hub**; tratar como sinal de **dados de entrada / guest** ou incidentes ainda `open` no hub até deploy e resolução em massa.
|
||||
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : attributes construct error` — indica **atributos XML mal formados** (aspas em falta ou desemparelhadas, `=` inválido, caracteres não escapados em valores de atributo, ou markup corrupto na primeira linha do ficheiro local `FlexIT.XML`); mesma classe operacional que §5.2–§5.6 (**XML inválido no ficheiro de entrada**); não é falha de ingest no hub.
|
||||
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
|
||||
- **Correção aplicacional (referência):** checklist no host + endurecimento em `WDMI_UBUNTU/default/Importer/_flexit.php` em [BIT-984](/BIT/issues/BIT-984) / [BIT-915](/BIT/issues/BIT-915); **deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) (`gitea-sync-importer.sh` a partir de `BitReport.pt/WDMI_UBUNTU.git`). Até o guest reflectir o código ou o `FlexIT.XML` estar válido, novos eventos podem continuar a ingressar.
|
||||
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (`head`, `xmllint --noout`, encoding); seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, idempotência / download atómico se aplicável). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
|
||||
- **Reabertura após fecho (loop [BIT-309](/BIT/issues/BIT-309)):** novos eventos com a mesma assinatura ou cluster **depois** de a issue Paperclip estar `done` significam que o **Importer em `wdmi-store` continua a receber ou a parsear XML inválido** — repetir diagnósticos §2–§4; só então marcar a issue como concluída e resolver incidentes no hub com evidência (`./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5e3b58b8a99f"` vazio ou janela 24–48h estável sem ingresso).
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5e3b58b8a99f"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "5e3b58b8a99f"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:2f4da462d83a"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "2f4da462d83a"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "attributes construct error"
|
||||
```
|
||||
|
||||
### 5.8 Caso documentado — `wdmi-store` / Flexit (BIT-946)
|
||||
|
||||
- **Assinatura:** `ERRSIG:63100e2b35c0`
|
||||
- **Paperclip:** [BIT-946](/BIT/issues/BIT-946) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309))
|
||||
- **Cluster (agregação BIT-309):** `ERRCLUSTER:a44bd34001aa` — pode conter só esta assinatura enquanto o sintoma for estável; tratar como a mesma família que §5.2–§5.7.
|
||||
- **Mensagem típica (excerpt):** `simplexml_load_file(): ecord><Manufacturer>HPINC</Manufacturer><Manufac1-RP-N2</ManufacturerPartNumber>` — fragmento de markup truncado ou corrupto no texto do erro (stream incompleto / XML inválido), alinhado com §5.2 e §5.5 (inclui referência a `Manufac1-RP-N2`); não é falha de ingest no hub.
|
||||
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
|
||||
- **Acção no produto:** no host de `wdmi-store`, seguir §2–§4 (inspeccionar `Importer/downloads/FlexIT.XML` ou URL de origem, `xmllint --noout`, encoding, download atómico e locks se houver escrita concorrente). Resolver no hub após deploy e confirmação de ausência de novos eventos com esta assinatura.
|
||||
- **Reabertura após fecho (loop [BIT-309](/BIT/issues/BIT-309)):** novos eventos com a mesma assinatura ou cluster **depois** de a issue Paperclip estar `done` significam que o **Importer em `wdmi-store` continua a falhar com XML truncado/corrupto** — o runbook no repositório `errors.bitreport.pt` não substitui deploy no guest. Repetir diagnósticos §2–§4; só então marcar a issue como concluída e resolver incidentes no hub com evidência (`./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:63100e2b35c0"` sem novos abertos relevantes ou janela 24–48h estável sem ingresso).
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:63100e2b35c0"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "63100e2b35c0"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "Manufac1-RP-N2"
|
||||
```
|
||||
|
||||
### 5.9 Caso documentado — `wdmi-store` / Flexit (BIT-943)
|
||||
|
||||
- **Assinatura:** `ERRSIG:4ca3a546fb62`
|
||||
- **Paperclip:** [BIT-943](/BIT/issues/BIT-943) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309))
|
||||
- **Cluster (agregação BIT-309):** `ERRCLUSTER:eb0dad83413f` — pode conter só esta assinatura enquanto o sintoma for estável; tratar como a mesma família operacional que §5.7 (**atributos / markup inválido na primeira linha** do `FlexIT.XML` local), com texto de diagnóstico libxml distinto.
|
||||
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : error parsing attribute name` — indica **nome de atributo XML inválido** ou **estrutura de atributos corrupta** (token inesperado antes de `=`, caracteres ilegais no nome do atributo, ou markup partido na zona de atributos); não é falha de ingest no hub.
|
||||
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
|
||||
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (`head -c`, `xmllint --noout`, encoding); alinhar com §5.7 para hipóteses (aspas, `=`, entidades); seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, download atómico / locks se aplicável). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:4ca3a546fb62"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "4ca3a546fb62"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "eb0dad83413f"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "error parsing attribute name"
|
||||
```
|
||||
|
||||
### 5.10 Caso documentado — `wdmi-store` / Flexit (BIT-950)
|
||||
|
||||
- **Assinatura:** `ERRSIG:8e233f7a57b8`
|
||||
- **Paperclip:** [BIT-950](/BIT/issues/BIT-950) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309)); tarefa filha operacional [BIT-984](/BIT/issues/BIT-984) (validação no host + hardening `_flexit.php`). Meta de fila / ownership quando o pulse assinalar execução presa: [BIT-988](/BIT/issues/BIT-988) (filha de BIT-984).
|
||||
- **Cluster (agregação BIT-309):** `ERRCLUSTER:f2d78c625221` — pode conter só esta assinatura enquanto o sintoma for estável; tratar como a mesma família operacional que §5.4 (**tag mismatch** no `FlexIT.XML` local).
|
||||
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : Opening and ending tag mismatch: FlexIT_DataExport line 1 and Record` — **XML mal formado** (estrutura de tags incoerente na raiz ou conteúdo corrupto no ficheiro local `FlexIT.XML`); não é falha de ingest no hub.
|
||||
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
|
||||
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (integridade, encoding, escrita concorrente, feed truncado); validar com `xmllint --noout`; seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, idempotência). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:8e233f7a57b8"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "8e233f7a57b8"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "f2d78c625221"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "FlexIT_DataExport"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ver também
|
||||
|
||||
- [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) — triagem e fecho no hub.
|
||||
- [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) — falhas de upload de feed para `clients.wdmi.pt` (`_upload_feed_via_api`).
|
||||
- [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md) — TLS/cURL para APIs Google no reporter PHP.
|
||||
- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — cenários CLI.
|
||||
@@ -1,112 +0,0 @@
|
||||
# Runbook — Importer (`wdmi-store` / `wdmi-ubuntu`): `SimpleXLS` / `_auferma.php` (`Uninitialized string offset`)
|
||||
|
||||
**Audiência:** Operação e engenharia que mantêm **aplicações que reportam** para `errors.bitreport.pt` (ex.: `wdmi-store`, **`wdmi-ubuntu`** / `Importer`).
|
||||
**Não confundir com** falhas de **ingest** no hub — para isso ver [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md).
|
||||
|
||||
**Última revisão:** 2026-04-05
|
||||
**Contexto:** Avisos/erros PHP do tipo **`Uninitialized string offset`** (índice muito elevado, ex. `557102`) originados em `vendor/shuchkin/simplexls/src/SimpleXLS.php` durante `_parse()`, invocados desde `_auferma.php` (tipicamente `SimpleXLS::parse()` ≈ linha 61) e incluídos via `__maintenance_build.php`. No hub, caso documentado em **`wdmi-store`:** [BIT-869](/BIT/issues/BIT-869) com **cluster** `ERRCLUSTER:0a642d62d724` (agregação [BIT-309](/BIT/issues/BIT-309)), onde o hub pode agregar mais do que uma `ERRSIG` (p.ex. `57ad438cb103` e `9a08d2cdd005` na mesma recorrência). Instalações com **`project_slug` `wdmi-ubuntu`** seguem o **mesmo plano técnico** no guest onde corre o Importer — ver §5.3 ([BIT-1055](/BIT/issues/BIT-1055)).
|
||||
|
||||
---
|
||||
|
||||
## 1. O que o erro significa
|
||||
|
||||
- A biblioteca **SimpleXLS** (Shuchkin) está a indexar uma **string interna** (buffer do ficheiro BIFF/XLS) **fora dos limites** — o índice reportado costuma reflectir **offset binário** dentro do stream parseado.
|
||||
- Causas típicas no **reporter**:
|
||||
1. **Ficheiro `.xls` corrupto, truncado ou incompleto** (download interrompido, disco cheio, escrita concorrente).
|
||||
2. **Ficheiro que não é um XLS legível** pela versão do vendor (extensão errada, HTML de erro no lugar do binário, ficheiro vazio).
|
||||
3. **Bug ou limite** na versão fixada do `vendor/shuchkin/simplexls` para certos inputs (menos comum que ficheiro inválido).
|
||||
|
||||
Isto é um problema **no host onde corre o Importer** (`wdmi-store`, **`wdmi-ubuntu`**, etc.) — **ficheiro de entrada e parser XLS** — não do hub de erros.
|
||||
|
||||
---
|
||||
|
||||
## 2. Reprodução e diagnóstico no host afetado
|
||||
|
||||
Executar no servidor onde está o Importer (caminho típico `/data/wwwroot/default/Importer/`).
|
||||
|
||||
1. **Identificar o path do `.xls`** passado a `SimpleXLS::parse()` em `_auferma.php` (variável ou constante efectiva na linha indicada pelo stack).
|
||||
2. **Inspeccionar o ficheiro:**
|
||||
- `ls -l "<path>"` — tamanho zero ou suspeitamente pequeno vs. esperado.
|
||||
- `file "<path>"` — deve indicar dados compostos / CDF / Microsoft Excel (conforme `file` no host).
|
||||
- `xxd "<path>" | head` — assinatura binária; ficheiros HTML ou texto puro são red flag.
|
||||
3. **Correlacionar com ingestão:** o ficheiro vem de download HTTP, cópia de rede, ou filesystem partilhado? Verificar **atomicidade** (escrever para `.tmp` + `rename`) e **locks** se vários jobs partilham o mesmo path.
|
||||
4. **Reproduzir em CLI** no host (PHP do mesmo ambiente): invocar o mesmo `parse()` sobre uma cópia do ficheiro problemático para confirmar.
|
||||
|
||||
---
|
||||
|
||||
## 3. Checklist de causa raiz (ordem sugerida)
|
||||
|
||||
1. **Integridade do ficheiro** — truncado, corrupto, ou substituído por resposta de erro (HTML/JSON).
|
||||
2. **Concorrência** — dois processos a escrever o mesmo `.xls` durante o parse.
|
||||
3. **Path errado** — apontar para cache antigo ou ficheiro intermédio errado.
|
||||
4. **Versão do vendor** — actualizar ou substituir apenas após reprodução controlada; preferir primeiro validar input.
|
||||
5. **Não mascarar no hub** — não filtrar esta assinatura como ruído até existir validação pré-parse ou correção de fonte de dados; alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md) quando existir no repositório.
|
||||
|
||||
---
|
||||
|
||||
## 4. Mitigação recomendada (código / operações)
|
||||
|
||||
- **Antes de `parse()`:** verificar `is_readable`, tamanho mínimo, e opcionalmente assinatura/magic bytes esperados para XLS.
|
||||
- **Download / escrita:** ficheiro temporário + `rename` atómico; evitar que `__maintenance_build` leia meio-download.
|
||||
- **Logging:** path (sanitizado), tamanho, e hash curto do ficheiro em falha para correlacionar com o hub (`unique_id`).
|
||||
- **Vendor:** após confirmar inputs válidos, avaliar actualização do pacote `shuchkin/simplexls` ou substituição por parser mais tolerante — sempre com teste em staging.
|
||||
- Após deploy, **resolver** incidentes no hub conforme [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) e confirmar ausência de novos eventos com as mesmas `ERRSIG` / o mesmo `ERRCLUSTER`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Ligação ao hub (errors.bitreport.pt)
|
||||
|
||||
**`wdmi-store`:**
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:57ad438cb103"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:9a08d2cdd005"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:0a642d62d724"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "57ad438cb103"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "_auferma.php"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "SimpleXLS.php"
|
||||
```
|
||||
|
||||
**`wdmi-ubuntu` (mesma família de stack):**
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "ERRSIG:4f8c89aa27c0"
|
||||
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "ERRSIG:9e119a768e6d"
|
||||
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "ERRCLUSTER:640553efed73"
|
||||
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "_auferma.php"
|
||||
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "SimpleXLS.php"
|
||||
```
|
||||
|
||||
### 5.1 Caso documentado — `wdmi-store` / Auferma + SimpleXLS ([BIT-869](/BIT/issues/BIT-869))
|
||||
|
||||
- **Assinaturas (exemplos no mesmo cluster):** `ERRSIG:57ad438cb103`, `ERRSIG:9a08d2cdd005` — tratar como **mesma classe operacional** até o hub deixar de as agregar em `ERRCLUSTER:0a642d62d724`.
|
||||
- **Cluster (agregação [BIT-309](/BIT/issues/BIT-309)):** `ERRCLUSTER:0a642d62d724`
|
||||
- **Mensagem típica (excerpt):** `Uninitialized string offset 557102` em `SimpleXLS.php` (≈671) durante `_parse()`.
|
||||
- **Stack útil:** `SimpleXLS.php` ← `_auferma.php` (≈61) ← `__maintenance_build.php` (≈50)
|
||||
- **Acção no produto:** validar o `.xls` de entrada e a pipeline que o produz (§2–§4); não fechar no hub só por documentação sem deploy ou evidência de ficheiros válidos.
|
||||
|
||||
### 5.2 Reabertura automática (recorrência [BIT-309](/BIT/issues/BIT-309))
|
||||
|
||||
- Se o cartão Paperclip [BIT-869](/BIT/issues/BIT-869) tiver sido fechado com âmbito **só documentação** no repositório do hub, mas as **occurrences continuarem** no mesmo `ERRCLUSTER:0a642d62d724`, o agregador do loop **[BIT-309](/BIT/issues/BIT-309)** pode **reabrir** o mesmo issue (histórico único, sem duplicar cartões) e registar no comentário o volume do ciclo (ex.: ocorrências no período).
|
||||
- Isto **não** indica regressão do serviço `errors.bitreport.pt`: confirma que a **causa no reporter** (`wdmi-store` / Importer / ficheiro de entrada) **persiste**. Priorizar diagnóstico §2–§4 e **deploy ou correcção no host**; só marcar o cartão Paperclip como `done` outra vez com **evidência** (ex.: ausência de novos eventos após deploy, ou resolução explícita dos incidentes no hub).
|
||||
|
||||
### 5.3 Caso documentado — `wdmi-ubuntu` / Auferma + SimpleXLS ([BIT-1055](/BIT/issues/BIT-1055))
|
||||
|
||||
- **Assinaturas agregadas no mesmo cluster:** `ERRSIG:4f8c89aa27c0`, `ERRSIG:9e119a768e6d`.
|
||||
- **Cluster (agregação [BIT-309](/BIT/issues/BIT-309)):** `ERRCLUSTER:640553efed73`.
|
||||
- **Mensagem típica (excerpt):** `Uninitialized string offset 557104` em `SimpleXLS.php` (≈674) durante `_parse()`.
|
||||
- **Stack útil:** `SimpleXLS.php` ← `_auferma.php` (≈61) ← `__maintenance_build.php` (≈50) — mesmo desenho que §5.1; **`project_slug` no hub:** `wdmi-ubuntu`.
|
||||
- **Paperclip:** cartão no projecto **[CLI] WDMI_UBUNTU** (`cli-wdmi-ubuntu`); **código / deploy:** repositório Gitea **BitReport.pt/WDMI_UBUNTU** (não o hub `errors.bitreport.pt`).
|
||||
- **Acção no produto:** §2–§4 (validar `.xls`, pipeline, possível actualização do vendor); fecho no board só com **PR/commit em WDMI_UBUNTU** ou evidência operacional equivalente.
|
||||
|
||||
### 5.4 Reabertura — `wdmi-ubuntu` (`ERRCLUSTER:640553efed73`)
|
||||
|
||||
- Comentários *Recorrência* no Paperclip com o mesmo `ERRSIG` / `ERRCLUSTER` **depois** de `done` ou `bulk-resolve` no hub indicam que o **Importer em `wdmi-ubuntu` continua a falhar no parse XLS** — repetir §2–§4 no **guest correcto**; correlacionar com `er-cli` usando `--project wdmi-ubuntu` (comandos em §5).
|
||||
|
||||
---
|
||||
|
||||
## Ver também
|
||||
|
||||
- [RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md](RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) — outros jobs Importer / XML (`_flexit.php`).
|
||||
- [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) — triagem e fecho no hub.
|
||||
- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — cenários CLI.
|
||||
@@ -1,72 +0,0 @@
|
||||
# Runbook — `wdmi-store` Importer: Visiotech / `strlen()` com `null` (PHP 8.1+)
|
||||
|
||||
**Audiência:** Operação e engenharia que mantêm **aplicações que reportam** para `errors.bitreport.pt` (ex.: `wdmi-store` / `Importer`).
|
||||
**Não confundir com** falhas de **ingest** no hub — para isso ver [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md).
|
||||
|
||||
**Última revisão:** 2026-04-05
|
||||
**Contexto:** Em PHP 8.1+, **`strlen()`** com argumento **`null`** gera *deprecation* (`Passing null to parameter #1 ($string) of type string is deprecated`), frequentemente capturada pelo `ErrorMonitoringReporter` como incidente no hub. Pilhas observadas incluem `_visiotech.php` (ex.: linha ~108) durante `Product->save()` / `_applyBeforeInsert()`, acionadas por `__maintenance_build.php`. O caso documentado em [BIT-954](/BIT/issues/BIT-954) usa **assinatura** `ERRSIG:a26dda2636bd` e **cluster** `ERRCLUSTER:634c0a250aba` (agregação [BIT-309](/BIT/issues/BIT-309)). A correcção definitiva é **no código Importer** (repo **WDMI_UBUNTU** / deploy no guest); este runbook orienta triagem e fecho no hub após deploy.
|
||||
|
||||
---
|
||||
|
||||
## 1. O que o erro significa
|
||||
|
||||
- **`strlen(): Passing null … is deprecated`:** algum caminho de código chama `strlen($x)` quando `$x` pode ser **`null`** (campo opcional do produto, valor não preenchido no feed Visiotech, ou conversão incompleta antes do insert).
|
||||
- O stack típico referencia **`_visiotech.php`** e **`Engine\Product->_applyBeforeInsert()`** — a lógica de normalização antes de gravar está a assumir string onde o runtime entrega `null`.
|
||||
- Isto é **comportamento do reporter PHP** sob PHP 8.1+, não falha do hub de erros nem da API de ingestão.
|
||||
|
||||
---
|
||||
|
||||
## 2. Reprodução e diagnóstico no host afetado
|
||||
|
||||
Executar no servidor onde está o Importer (caminho típico `/data/wwwroot/default/Importer/`).
|
||||
|
||||
1. **Confirmar versão PHP** (`php -v`) — deprecations deste tipo aparecem a partir do 8.1 com `error_reporting` que inclui `E_DEPRECATED`.
|
||||
2. **Abrir `_visiotech.php`** em torno da linha citada no incidente (ex.: 108) e localizar **`strlen(`** (ou helpers que o invocam indirectamente).
|
||||
3. **Rastrear a origem do `null`:** campos mapeados do feed Visiotech → `Product` / arrays intermediários; verificar propriedades opcionais não inicializadas.
|
||||
4. **Correlacionar com o job:** stack com `__maintenance_build.php` → reproduzir o include de `_visiotech.php` no mesmo contexto (dados de teste ou log de SKU/produto quando disponível).
|
||||
|
||||
---
|
||||
|
||||
## 3. Checklist de causa raiz (ordem sugerida)
|
||||
|
||||
1. **Chamada directa** `strlen($var)` sem garantir tipo `string` — substituir por padrão seguro (ver §4).
|
||||
2. **Campo de produto `null`** no ramo Visiotech antes de `_applyBeforeInsert` — corrigir mapeamento / default no importador.
|
||||
3. **Confundir com outro `strlen`** noutro ficheiro — validar sempre **ficheiro e linha** do evento no hub.
|
||||
4. **Não filtrar como ruído** no hub até existir correcção em código — alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md) quando aplicável.
|
||||
|
||||
---
|
||||
|
||||
## 4. Mitigação recomendada (código)
|
||||
|
||||
- **Garantir string antes de medir comprimento:** por exemplo `(string) ($var ?? '')`, ou `strlen((string) $var)` apenas quando `null` deve contar como vazio; preferir **`$var === null || $var === ''`** quando a intenção é “vazio”, em vez de `strlen` em valores potencialmente `null`.
|
||||
- **Normalizar no mapeamento Visiotech** (defaults explícitos para campos opcionais) para que `_applyBeforeInsert` não receba `null` onde esperava string.
|
||||
- Após deploy, **resolver** incidentes no hub conforme [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) e confirmar ausência de novos eventos com a mesma `ERRSIG` (24–48h estáveis).
|
||||
|
||||
---
|
||||
|
||||
## 5. Ligação ao hub (errors.bitreport.pt)
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:634c0a250aba"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:a26dda2636bd"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "a26dda2636bd"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "_visiotech.php"
|
||||
./scripts/er-cli.sh list-open --project wdmi-store --q "strlen(): Passing null"
|
||||
```
|
||||
|
||||
### 5.1 Caso documentado — `wdmi-store` / Visiotech + `Product` insert (BIT-954)
|
||||
|
||||
- **Paperclip:** [BIT-954](/BIT/issues/BIT-954) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309))
|
||||
- **Assinatura:** `ERRSIG:a26dda2636bd`
|
||||
- **Cluster:** `ERRCLUSTER:634c0a250aba`
|
||||
- **Mensagem típica:** `strlen(): Passing null to parameter #1 ($string) of type string is deprecated`
|
||||
- **Origem útil:** `_visiotech.php` (~108); stack com `ErrorMonitoringReporter::handleError`, `Engine\Product->_applyBeforeInsert()`, `Product->save()`, `__maintenance_build.php`
|
||||
- **Acção no produto:** aplicar §4 no Importer / deploy em `wdmi-store`; usar §2 para confirmar o campo ou ramo que entrega `null`.
|
||||
|
||||
---
|
||||
|
||||
## Ver também
|
||||
|
||||
- [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) — triagem e fecho no hub.
|
||||
- [RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md](RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md) — outro padrão de erros no Importer `wdmi-store`.
|
||||
- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — cenários CLI.
|
||||
@@ -203,6 +203,9 @@ scrape_configs:
|
||||
# Ingest throughput (events/sec)
|
||||
sum(rate(er_ingest_events_total[5m])) by (outcome)
|
||||
|
||||
# Noise skips by rule (BIT-26791)
|
||||
sum(rate(er_ingest_events_total{outcome="skipped_noise"}[5m])) by (rule_id)
|
||||
|
||||
# Ingest request rate by status
|
||||
sum(rate(er_ingest_requests_total[5m])) by (status_code)
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Runbook — errors.bitreport.pt: Triagem, Correção, Deploy e Fecho
|
||||
|
||||
**Audiência:** Operação, agentes Paperclip, on-call.
|
||||
**Última revisão:** 2026-04-05
|
||||
**Última revisão:** 2026-06-08
|
||||
**Requisitos:** `curl`, `jq`, acesso à variável `ERROR_RESOLVE_API_KEY`, acesso SSH ao LXC host (se deploy necessário).
|
||||
|
||||
**Documentação relacionada:** [HTTP_CONTRACTS.md](HTTP_CONTRACTS.md) (contratos + curl), [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) (5 cenários CLI), [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md) (ingest 401/429/fingerprint), [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md) (cURL 35 / 6 — TLS e DNS / Google OAuth no **reporter** PHP; HTTP 503/500 Sheets `backendError` — §5.7–§5.9, p.ex. [BIT-909](/BIT/issues/BIT-909) / [BIT-938](/BIT/issues/BIT-938) (503), [BIT-912](/BIT/issues/BIT-912) / [BIT-916](/BIT/issues/BIT-916) (500); DNS `oauth2` + `import_margin` em `wdmi-store` — §5.11 / [BIT-921](/BIT/issues/BIT-921); CRM `import_margin` cURL 35 em `sheets.googleapis.com` — §5.12 / [BIT-947](/BIT/issues/BIT-947); DNS `sheets.googleapis.com` (folha **Portes**, supplier fees) no **CRM** — §5.6 / [BIT-995](/BIT/issues/BIT-995)), [RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md](RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) (`simplexml_load_file` / Flexit Importer no **reporter** PHP; p.ex. [BIT-903](/BIT/issues/BIT-903) — `ERRCLUSTER:e83a5ee5e95d` / §5.2; [BIT-943](/BIT/issues/BIT-943) — `ERRCLUSTER:eb0dad83413f` / §5.9 *error parsing attribute name*), [RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md](RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md) (`SimpleXLS` / `_auferma.php` / `Uninitialized string offset` no **reporter** `wdmi-store` ou **`wdmi-ubuntu`**; p.ex. [BIT-869](/BIT/issues/BIT-869) — `ERRCLUSTER:0a642d62d724` / §5.1; [BIT-1055](/BIT/issues/BIT-1055) — `ERRCLUSTER:640553efed73` / §5.3), [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) (upload de feed / `upload_feed_tier` / `clients.wdmi.pt` no **reporter** PHP; confusão *host ingestão* vs URL de upload — ver §1.1 desse runbook), [RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md](RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md) (`mkdir(): File exists` / cache Importer — `Cache.class.php` em WDMI_UBUNTU; stack pode citar `CacheFilesystem` legado — ver runbook; [BIT-924](/BIT/issues/BIT-924) / [BIT-985](/BIT/issues/BIT-985)), [RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md](RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md) (Importer `_visiotech.php` / `strlen(null)` deprecation PHP 8.1+ no **reporter** `wdmi-store`), [RUNBOOK_REPORTER_CRM_ERRORMONITORING_VIEW.md](RUNBOOK_REPORTER_CRM_ERRORMONITORING_VIEW.md) (CRM `View.php` / `@errormonitoring/dashboard` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_PROCESSMANAGER_VIEW.md](RUNBOOK_REPORTER_CRM_PROCESSMANAGER_VIEW.md) (CRM `View.php` / `@processmanager/dashboard` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md](RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md) (CRM `Logger.php` / `mkdir(): Permission denied` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_USERPROFILE_SANITIZE.md](RUNBOOK_REPORTER_CRM_USERPROFILE_SANITIZE.md) (CRM `UserController` / `array_map('Sanitize::…')` vs classe global — perfil & skills no **reporter** PHP; [BIT-881](/BIT/issues/BIT-881)), [RUNBOOK_REPORTER_CRM_AUTH_PASS_RESET_BASIC.md](RUNBOOK_REPORTER_CRM_AUTH_PASS_RESET_BASIC.md) (CRM `layouts/auth.php` / password reset basic / `Closure` com layout aninhado no **reporter** PHP; [BIT-935](/BIT/issues/BIT-935)), [RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md](RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md) (CRM `Validate::email` / argumento `string` vs `null` no POST de login — `AuthController::handleLogin`; [BIT-941](/BIT/issues/BIT-941)), [RUNBOOK_REPORTER_CRM_VENDOR_CLASSLIST.md](RUNBOOK_REPORTER_CRM_VENDOR_CLASSLIST.md) (CRM `vendor.*.js` / `classList` em nó nulo no **reporter** front-end; [BIT-936](/BIT/issues/BIT-936)), [RUNBOOK_REPORTER_CRM_TASKS_DUE_TIME.md](RUNBOOK_REPORTER_CRM_TASKS_DUE_TIME.md) (CRM `crm_tasks.due_time` / string vazia vs `NULL` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md](RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md) (CRM SQL 1064 próximo a `'10'` / `LIMIT`–`OFFSET` quotados ou binds incorrectos no **reporter** PHP; [BIT-937](/BIT/issues/BIT-937) / [BIT-952](/BIT/issues/BIT-952)), [RUNBOOK_REPORTER_CRM_DATABASE_MEMORY.md](RUNBOOK_REPORTER_CRM_DATABASE_MEMORY.md) (CRM `DatabaseManager.php` / esgotamento de `memory_limit` no **reporter** PHP), [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md).
|
||||
**Documentação relacionada:** [HTTP_CONTRACTS.md](HTTP_CONTRACTS.md) (contratos + curl), [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) (5 cenários CLI), [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md) (ingest 401/429/fingerprint), [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md) (cURL 35 / 6 — TLS e DNS / Google OAuth no **reporter** PHP), runbooks CRM em [docs/runbooks/README.md](runbooks/README.md), [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md). Projetos WDMI foram retirados do hub em [BIT-24704](/BIT/issues/BIT-24704).
|
||||
|
||||
---
|
||||
|
||||
@@ -29,7 +29,7 @@ Filtros opcionais:
|
||||
|
||||
```bash
|
||||
./scripts/er-cli.sh list-open --project crm --severity critical
|
||||
./scripts/er-cli.sh list-open --project wdmi --limit 50
|
||||
./scripts/er-cli.sh list-open --project ott --limit 50
|
||||
./scripts/er-cli.sh list-open --q "Connection refused"
|
||||
```
|
||||
|
||||
@@ -65,8 +65,8 @@ curl -sf "${ER_API_BASE}/api/error-monitoring/recent-errors?api_key=${ERROR_RESO
|
||||
### 1.5 Paperclip — loop [BIT-309](/BIT/issues/BIT-309) e reaberturas
|
||||
|
||||
- Comentários **“Recorrência após fecho”** (ou equivalente no loop) reabrem a **mesma** issue Paperclip para `todo` para evitar duplicados — não implica por si um bug novo no repositório **errors.bitreport.pt**.
|
||||
- **Sweeps / fecho administrativo:** antes de marcar uma issue do **error loop** como concluída só com base no último comentário de agente («Done» / «Fecho» com documentação no hub) ou num sweep operacional, confirmar no **hub** que não há incidentes abertos para a mesma assinatura ou cluster (`./scripts/er-cli.sh list-open --project <slug> --q "ERRSIG:…"` ou texto do título). Se o **reporter** ainda ingressa o erro, o loop volta a comentar **«Recorrência após fecho»**; a causa continua no guest (runbook do serviço de origem — ex. Flexit [RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md](RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) §5.8 / [BIT-946](/BIT/issues/BIT-946), §5.9 / [BIT-943](/BIT/issues/BIT-943) *parser error : error parsing attribute name* em `FlexIT.XML`).
|
||||
- Enquanto o **reporter** continuar a emitir o mesmo erro em produção, o hub e o Paperclip reflectem-no; a causa raiz segue os runbooks do **sistema de origem** (ex.: upload de feed — [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) §5.28 / [BIT-925](/BIT/issues/BIT-925)).
|
||||
- **Sweeps / fecho administrativo:** antes de marcar uma issue do **error loop** como concluída só com base no último comentário de agente («Done» / «Fecho» com documentação no hub) ou num sweep operacional, confirmar no **hub** que não há incidentes abertos para a mesma assinatura ou cluster (`./scripts/er-cli.sh list-open --project <slug> --q "ERRSIG:…"` ou texto do título). Se o **reporter** ainda ingressa o erro, o loop volta a comentar **«Recorrência após fecho»**; a causa continua no guest (runbook do serviço de origem — ex. CRM SQL [RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md](RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md) §5.1 / [BIT-937](/BIT/issues/BIT-937)).
|
||||
- Enquanto o **reporter** continuar a emitir o mesmo erro em produção, o hub e o Paperclip reflectem-no; a causa raiz segue os runbooks do **sistema de origem** (ex.: Google TLS no CRM — [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md)).
|
||||
- **Agentes:** só é necessário novo commit no hub se a documentação ou o contrato mudarem; caso o runbook já cubra a assinatura, actualizar a thread Paperclip com ponteiro para a secção e fechar conforme governança após verificação (ou deixar explícito o que falta em ops no reporter).
|
||||
|
||||
---
|
||||
@@ -214,9 +214,9 @@ echo "Backup: ${BACKUP_FILE} ($(wc -l < "${BACKUP_FILE}") linhas)"
|
||||
|
||||
### 6.1 Issues Paperclip (Error Loop / BIT-309) com causa no **reporter**
|
||||
|
||||
Muitos tickets descrevem erros **ingeridos** pelo hub cuja **causa raiz** está no código ou na infra do projecto reporter (`wdmi-store`, `crm`, etc.), não no serviço `errors.bitreport.pt`.
|
||||
Muitos tickets descrevem erros **ingeridos** pelo hub cuja **causa raiz** está no código ou na infra do projecto reporter (`crm`, `ott`, etc.), não no serviço `errors.bitreport.pt`.
|
||||
|
||||
- Trabalho **só no repositório do hub** (runbooks, contratos HTTP) **não elimina** novas occurrences no produto reporter; o loop **BIT-309** pode **reabrir** o mesmo issue Paperclip enquanto os eventos continuarem a chegar (ex.: [BIT-904](/BIT/issues/BIT-904) após fecho com documentação de upload tier `ref_1`, [BIT-910](/BIT/issues/BIT-910) com o mesmo padrão para tier `ref_2` / `ERRCLUSTER:026e79c87500`, [BIT-905](/BIT/issues/BIT-905) com `upload_feed_base` / `feed_ref` / `ref` — ver [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) §5.20 (BIT-904), §5.24 (BIT-910) e §5.21 (BIT-905), ou [BIT-937](/BIT/issues/BIT-937) / `ERRCLUSTER:5291566782c4` no **CRM** com SQL `LIMIT` quotado — [RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md](RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md) §5.1).
|
||||
- Trabalho **só no repositório do hub** (runbooks, contratos HTTP) **não elimina** novas occurrences no produto reporter; o loop **BIT-309** pode **reabrir** o mesmo issue Paperclip enquanto os eventos continuarem a chegar (ex.: [BIT-937](/BIT/issues/BIT-937) / `ERRCLUSTER:5291566782c4` no **CRM** com SQL `LIMIT` quotado — [RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md](RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md) §5.1).
|
||||
- **Consolidação CTO (`cancelled` / duplicado):** vários sintomas de upload podem fundir-se num ticket canónico (ex.: [BIT-905](/BIT/issues/BIT-905) ou [BIT-906](/BIT/issues/BIT-906) → [BIT-1020](/BIT/issues/BIT-1020)). O plano de correcção e o estado Paperclip seguem o **issue canónico**; o runbook (§5.21 [BIT-905](/BIT/issues/BIT-905), §5.22 [BIT-906](/BIT/issues/BIT-906)) mantém `ERRSIG` / `er-cli` para diagnóstico.
|
||||
- Marcar o issue Paperclip como **`done`** só após **verificação em produção** (repro desapareceu, `curl` de upload OK, deploy aplicado) **ou** acordo explícito de que o âmbito era **apenas documentação** e que recorrências são esperadas até alguém tratar o reporter.
|
||||
- Não adicionar regras de ruído no ingest do hub para **esconder** estes erros até a causa no destino estar tratada; alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md).
|
||||
|
||||
@@ -9,10 +9,20 @@ Stack versionada em [`docker-compose.yml`](../docker-compose.yml) na raiz deste
|
||||
- Docker Engine 24+ e Docker Compose v2 (plugin `docker compose`), ou Podman Compose compatível.
|
||||
- Portas livres no host (por omissão): **3306** → MariaDB, **3041** → ingest API, **3040** → admin UI. Ajustáveis em `.env` (`ER_PUBLISH_*`).
|
||||
|
||||
## Preservação de `.env` em runtime (BIT-25005)
|
||||
|
||||
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
|
||||
|
||||
- **Nunca** executar `cp .env.example .env` sobre um `.env` **já existente** em produção ou staging.
|
||||
- O `cp` abaixo aplica-se **apenas** à configuração inicial num servidor novo onde não existe ainda `.env`.
|
||||
- Em redeploys: `git pull` apenas; o `.env` existente **não é tocado**.
|
||||
- Alterações a `ER_MYSQL_*` requerem issue explícita, plano de rollback e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo).
|
||||
|
||||
## Arranque reproduzível (qualquer ambiente)
|
||||
|
||||
```bash
|
||||
cd /path/to/errors.bitreport.pt # raiz do clone (ver inventário em docs/ENVIRONMENTS.md)
|
||||
# APENAS para configuração inicial — NÃO executar se já existir .env em produção (BIT-25005)
|
||||
cp .env.example .env
|
||||
# Editar .env: definir palavras-passe fortes antes de produção
|
||||
docker compose up --build -d
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
|
||||
Deploy nativo da stack na **raiz do repositório `errors.bitreport.pt`** num contentor **LXC** (Debian 12 ou Ubuntu 24.04 LTS, alinhado com o resto da infra BitReport): **MariaDB 10.11+** (ou MySQL 8+), **Node.js 20+**, **systemd** para **ingest-api**, **admin-ui**, **collector-worker**, env em **`/etc/error-reporting/env`**, proxy TLS opcional com **nginx**.
|
||||
|
||||
## Preservação de `.env` em runtime (BIT-25005)
|
||||
|
||||
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
|
||||
|
||||
- **Nunca** sobrescrever `/etc/error-reporting/env` (ou `.env` no clone) com conteúdo de exemplo num servidor de produção já configurado.
|
||||
- Ficheiro de env em `/etc/error-reporting/env` é **fora do Git** — nunca incluir no repositório.
|
||||
- Alterações a `ER_MYSQL_*` requerem issue explícita, plano de rollback e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo).
|
||||
- Credenciais de placeholder (`CHANGE_ME_STRONG`, `changeme`) são proibidas em produção.
|
||||
|
||||
Comparação com Compose: variáveis e ordem de migrações espelham [`bitreport-error-reporting-compose-proxmox.md`](./bitreport-error-reporting-compose-proxmox.md) e [`docker-compose.yml`](../docker-compose.yml).
|
||||
|
||||
## Redis
|
||||
|
||||
@@ -32,7 +32,7 @@ Per-key overrides: set `rate_limit_max` and/or `rate_limit_window_ms` on the key
|
||||
|
||||
- Rules live in `ingest-api/src/lib/noisePolicy.ts`; ruleset id: `noise_ruleset_version` in the ingest response.
|
||||
- **Check:** send a known-noise payload (for example ResizeObserver message at non-fatal level); expect `skipped: true`, `noise_filtered_count` incremented, and no new `er_incidents` row.
|
||||
- **Check:** send the same pattern at `fatal` / `critical` level; expect **not** skipped (noise rules do not hide critical), **except** when the **message** or **client-provided stacktrace** contains reserved substring `BIT-SMOKE-` (intentional reporter smoke, e.g. wdmi-store `/smoke/wdmi.js`, CRM `/smoke/crm-main.php`, CRM `/smoke/crm.php` direct-forward `BIT-SMOKE-CRM-DIRECT-FWD`) — those are skipped at every level (`rule_id`: `bitreport_smoke_marker`). Matching treats unicode hyphen/minus characters as ASCII `-` (ruleset **1.0.5+**). The exact deploy-probe failure ribbon `BIT-SMOKE error hub ingest live check` (space after `BIT-SMOKE`, see [RUNBOOK_INGEST_DEBUG.md](../RUNBOOK_INGEST_DEBUG.md) §0) is also skipped at every level with the same `rule_id`.
|
||||
- **Check:** send the same pattern at `fatal` / `critical` level; expect **not** skipped (noise rules do not hide critical), **except** when the **message** or **client-provided stacktrace** contains reserved substring `BIT-SMOKE-` (intentional reporter smoke, e.g. wdmi-store `/smoke/wdmi.js`, CRM `/smoke/crm-main.php`, CRM `/smoke/crm.php` direct-forward `BIT-SMOKE-CRM-DIRECT-FWD`) — those are skipped at every level (`rule_id`: `bitreport_smoke_marker`). Matching treats unicode hyphen/minus characters as ASCII `-` (ruleset **1.0.5+**). The exact deploy-probe failure ribbon `BIT-SMOKE error hub ingest live check` (space after `BIT-SMOKE`, see [RUNBOOK_INGEST_DEBUG.md](../RUNBOOK_INGEST_DEBUG.md) §0) is also skipped at every level with the same `rule_id`. Hand-sent pipe-liveness probes referenced by a BIT task id — `BIT-<id> smoke test` (bare) or `[BIT-<id>] ... smoke test` (bracketed) — are likewise skipped at every level (ruleset **1.0.8+**, BIT-32681), aligning ingest with the fleet audit synthetic-event exclusion.
|
||||
|
||||
## Rate limits
|
||||
|
||||
|
||||
@@ -50,11 +50,14 @@ These routes mirror the CRM error-monitoring module for Paperclip and automation
|
||||
|
||||
### Read: `GET /api/error-monitoring/recent-errors`
|
||||
|
||||
Alias: `GET /v1/paperclip/recent-errors` (same handler; served by the admin API via the `admin-ui` rewrite — BIT-31442).
|
||||
|
||||
| Credential | Notes |
|
||||
|------------|--------|
|
||||
| `api_key` query | Must match `ERROR_RESOLVE_API_KEY` or `ERROR_REPORTING_API_KEY` |
|
||||
| `view_errors` query | Must match `DEBUG_VIEW_ERRORS_KEY` (read-oriented) |
|
||||
| Admin session | Not used on this path; query credentials only |
|
||||
| `X-Api-Key` header (BIT-31442) | Carries either the resolve/reporting key or `DEBUG_VIEW_ERRORS_KEY`; alternative to the query params to avoid key leakage in URLs/logs |
|
||||
| Admin session | Not used on this path; query/header credentials only |
|
||||
|
||||
At least one of the server secrets above must be configured or the endpoint returns **503**.
|
||||
|
||||
|
||||
@@ -17,14 +17,6 @@ Index of **hub-local** operational docs in this repository (pointers only). Gove
|
||||
- [`RUNBOOK_INGEST_DEBUG.md`](../RUNBOOK_INGEST_DEBUG.md) — debug ingest API behaviour and payloads.
|
||||
- [`operations/ingest-hardening-runbook.md`](../operations/ingest-hardening-runbook.md) — post-deploy validation after ingest hardening / rate-limit changes (BIT-735).
|
||||
|
||||
## Reporter (PHP) — WDMI / Importer
|
||||
|
||||
- [`RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md`](../RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) — feed upload API with no response (`wdmi-store` / `clients.wdmi.pt`).
|
||||
- [`RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md`](../RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) — `simplexml_load_file` in Flexit Importer (`wdmi-store`).
|
||||
- [`RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md`](../RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md) — `SimpleXLS` / `_auferma.php` uninitialized string offset.
|
||||
- [`RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md`](../RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md) — `mkdir(): File exists` on Importer cache disk.
|
||||
- [`RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md`](../RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md) — Visiotech / `strlen()` with `null` (PHP 8.1+).
|
||||
|
||||
## Reporter (PHP) — CRM
|
||||
|
||||
- [`RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md`](../RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md) — `Validate::email()` with `null` at login.
|
||||
@@ -49,7 +41,6 @@ Index of **hub-local** operational docs in this repository (pointers only). Gove
|
||||
## Operations & observability
|
||||
|
||||
- [`RUNBOOK_OPERATIONS.md`](../RUNBOOK_OPERATIONS.md) — five common operational scenarios on the hub.
|
||||
- [`RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md`](../RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md) — SSH from Paperclip host to WDMI Importer (BIT-1044).
|
||||
- [`OBSERVABILITY_PROMETHEUS.md`](../OBSERVABILITY_PROMETHEUS.md) — Prometheus & Grafana for this stack.
|
||||
|
||||
## Deployment
|
||||
@@ -62,3 +53,7 @@ Index of **hub-local** operational docs in this repository (pointers only). Gove
|
||||
- [`HTTP_CONTRACTS.md`](../HTTP_CONTRACTS.md) — HTTP API contracts for this hub.
|
||||
- [`ADMIN_STATS_API.md`](../ADMIN_STATS_API.md) — `/v1/stats/*` operational statistics.
|
||||
- [`permission-matrix.md`](../permission-matrix.md) — admin RBAC permission matrix.
|
||||
|
||||
## Retired clients
|
||||
|
||||
WDMI-family projects were removed from this hub in [BIT-24704](/BIT/issues/BIT-24704). Ingest rejects retired slugs; use `scripts/offboard-project.sh` for future client removals.
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM node:20-bookworm-slim AS build
|
||||
FROM node:24-bookworm-slim AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
@@ -6,7 +6,7 @@ COPY tsconfig.json ./
|
||||
COPY src ./src
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-bookworm-slim
|
||||
FROM node:24-bookworm-slim
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
COPY package.json package-lock.json ./
|
||||
|
||||
Generated
+9
-9
@@ -16,14 +16,14 @@
|
||||
"prom-client": "^15.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"ajv": "^8.18.0",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^2.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -981,12 +981,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.19.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz",
|
||||
"integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",
|
||||
"version": "24.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
|
||||
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
"undici-types": ">=7.24.0 <7.24.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/expect": {
|
||||
@@ -2638,9 +2638,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/uri-js": {
|
||||
|
||||
@@ -21,13 +21,13 @@
|
||||
"prom-client": "^15.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"ajv": "^8.18.0",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^2.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
}
|
||||
@@ -239,16 +239,20 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
|
||||
idempotencyKey: _idempotencyKey,
|
||||
bodyHash: _bodyHash,
|
||||
});
|
||||
// Track event outcomes
|
||||
// Track event outcomes (rule_id on skipped_noise for BIT-26791)
|
||||
if (_out.body && typeof _out.body === "object" && "results" in _out.body) {
|
||||
const results = (_out.body as { results: Array<{ skipped?: boolean }> }).results;
|
||||
const results = (
|
||||
_out.body as { results: Array<{ skipped?: boolean; rule_id?: string }> }
|
||||
).results;
|
||||
let stored = 0;
|
||||
let skipped = 0;
|
||||
let _maxOccurredSec = 0;
|
||||
const skippedByRule = new Map<string, number>();
|
||||
for (let _i = 0; _i < results.length; _i++) {
|
||||
const r = results[_i]!;
|
||||
if (r.skipped) {
|
||||
skipped++;
|
||||
const _ruleId =
|
||||
typeof r.rule_id === "string" && r.rule_id !== "" ? r.rule_id : "unknown";
|
||||
skippedByRule.set(_ruleId, (skippedByRule.get(_ruleId) ?? 0) + 1);
|
||||
continue;
|
||||
}
|
||||
stored++;
|
||||
@@ -262,8 +266,12 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stored > 0) ingestEventsTotal.inc({ outcome: "stored" }, stored);
|
||||
if (skipped > 0) ingestEventsTotal.inc({ outcome: "skipped_noise" }, skipped);
|
||||
if (stored > 0) {
|
||||
ingestEventsTotal.inc({ outcome: "stored", rule_id: "" }, stored);
|
||||
}
|
||||
for (const [_ruleId, _n] of skippedByRule) {
|
||||
ingestEventsTotal.inc({ outcome: "skipped_noise", rule_id: _ruleId }, _n);
|
||||
}
|
||||
const _slug = request.ingestAuth.projectSlug;
|
||||
if (_slug !== "" && _maxOccurredSec > 0) {
|
||||
errorHubLastEventTimestamp.set({ project_slug: _slug }, _maxOccurredSec);
|
||||
@@ -284,7 +292,7 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
|
||||
message: "occurred_at must be a valid ISO-8601 timestamp.",
|
||||
});
|
||||
}
|
||||
ingestEventsTotal.inc({ outcome: "error" }, _body.events.length);
|
||||
ingestEventsTotal.inc({ outcome: "error", rule_id: "" }, _body.events.length);
|
||||
const _slugErr = request.ingestAuth?.projectSlug ?? "";
|
||||
if (_slugErr !== "") {
|
||||
errorHubIngestFailuresTotal.inc({ project_slug: _slugErr }, _body.events.length);
|
||||
|
||||
@@ -242,6 +242,11 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
|
||||
expect(_body.noise_filtered_count).toBe(1);
|
||||
expect(_body.results[0]?.skipped).toBe(true);
|
||||
expect(_body.results[0]?.rule_id).toBe("resize_observer_loop");
|
||||
const _metrics = await _app.inject({ method: "GET", url: "/metrics" });
|
||||
expect(_metrics.statusCode).toBe(200);
|
||||
expect(_metrics.body).toContain(
|
||||
'er_ingest_events_total{outcome="skipped_noise",rule_id="resize_observer_loop"}',
|
||||
);
|
||||
const [after] = await _pool.execute<RowDataPacket[]>(
|
||||
`SELECT COUNT(*) AS c FROM er_incidents WHERE project_id = ?`,
|
||||
[_projectIdA],
|
||||
@@ -265,7 +270,7 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
|
||||
schema_version: 1,
|
||||
occurred_at: "2026-04-05T10:00:00.000Z",
|
||||
level: "error",
|
||||
message: "Error: BIT-SMOKE-WDMI-DIRECT-INGEST",
|
||||
message: "Error: BIT-SMOKE-CRM-DIRECT-INGEST",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -34,8 +34,8 @@ describe("extractLocationFromContext", () => {
|
||||
|
||||
describe("extractProjectStableKey", () => {
|
||||
it("prefers project_slug", () => {
|
||||
expect(extractProjectStableKey({ project_slug: "wdmi-store", project_name: "X" })).toBe(
|
||||
"wdmi-store",
|
||||
expect(extractProjectStableKey({ project_slug: "crm", project_name: "X" })).toBe(
|
||||
"crm",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -21,7 +21,7 @@ function _asTrimmedString(value: unknown): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull file + line from ingest `context` (CRM / WDMI ErrorCollector shapes).
|
||||
* Pull file + line from ingest `context` (CRM ErrorCollector shapes).
|
||||
*/
|
||||
export function extractLocationFromContext(
|
||||
context: Record<string, unknown> | null | undefined,
|
||||
|
||||
@@ -57,7 +57,7 @@ describe("evaluateNoise", () => {
|
||||
level: "error",
|
||||
message:
|
||||
"Uncaught TypeError: Cannot read properties of undefined (reading '_x_refreshXForScope')",
|
||||
filePathHint: "/data/wwwroot/crm-wdmi/app/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php",
|
||||
filePathHint: "/data/wwwroot/crm/app/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php",
|
||||
});
|
||||
expect(_r).toEqual({
|
||||
matched: true,
|
||||
@@ -76,11 +76,11 @@ describe("evaluateNoise", () => {
|
||||
expect(_r).toEqual({ matched: false });
|
||||
});
|
||||
|
||||
it("matches reserved BIT-SMOKE- probe messages (wdmi direct ingest smoke)", () => {
|
||||
it("matches reserved BIT-SMOKE- probe messages (direct ingest smoke)", () => {
|
||||
const _r = evaluateNoise({
|
||||
level: "error",
|
||||
message: "Error: BIT-SMOKE-WDMI-DIRECT-INGEST",
|
||||
filePathHint: "/smoke/wdmi.js",
|
||||
message: "Error: BIT-SMOKE-CRM-DIRECT-INGEST",
|
||||
filePathHint: "/smoke/crm-main.php",
|
||||
});
|
||||
expect(_r).toEqual({
|
||||
matched: true,
|
||||
@@ -92,7 +92,7 @@ describe("evaluateNoise", () => {
|
||||
it("suppresses BIT-SMOKE- even at critical ingest level", () => {
|
||||
const _r = evaluateNoise({
|
||||
level: "critical",
|
||||
message: "BIT-SMOKE-WDMI-DIRECT-INGEST",
|
||||
message: "BIT-SMOKE-CRM-DIRECT-INGEST",
|
||||
filePathHint: "",
|
||||
});
|
||||
expect(_r).toEqual({
|
||||
@@ -143,7 +143,55 @@ describe("evaluateNoise", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("matches wdmi-store / CRM deploy ingest live-check failure ribbon (BIT-931 family)", () => {
|
||||
it("matches bare 'BIT-<id> smoke test' pipe-liveness probe (BIT-32681)", () => {
|
||||
const _r = evaluateNoise({
|
||||
level: "error",
|
||||
message: "BIT-32663 smoke test",
|
||||
filePathHint: "",
|
||||
});
|
||||
expect(_r).toEqual({
|
||||
matched: true,
|
||||
ruleId: "bitreport_smoke_marker",
|
||||
reason: "filtered_intentional_smoke_event",
|
||||
});
|
||||
});
|
||||
|
||||
it("matches bracketed '[BIT-<id>] ... smoke test' probe (fleet-audit synthetic form)", () => {
|
||||
const _r = evaluateNoise({
|
||||
level: "error",
|
||||
message: "[BIT-30527] paperclip-chat pipe-liveness smoke test",
|
||||
filePathHint: "",
|
||||
});
|
||||
expect(_r).toEqual({
|
||||
matched: true,
|
||||
ruleId: "bitreport_smoke_marker",
|
||||
reason: "filtered_intentional_smoke_event",
|
||||
});
|
||||
});
|
||||
|
||||
it("suppresses 'BIT-<id> smoke test' probe even at critical level", () => {
|
||||
const _r = evaluateNoise({
|
||||
level: "critical",
|
||||
message: "BIT-32663 smoke test",
|
||||
filePathHint: "",
|
||||
});
|
||||
expect(_r).toEqual({
|
||||
matched: true,
|
||||
ruleId: "bitreport_smoke_marker",
|
||||
reason: "filtered_intentional_smoke_event",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not match a real error that merely contains 'smoke' without the BIT-<id> probe shape", () => {
|
||||
const _r = evaluateNoise({
|
||||
level: "error",
|
||||
message: "Smoke detector sensor offline",
|
||||
filePathHint: "",
|
||||
});
|
||||
expect(_r).toEqual({ matched: false });
|
||||
});
|
||||
|
||||
it("matches CRM deploy ingest live-check failure ribbon (BIT-931 family)", () => {
|
||||
const _r = evaluateNoise({
|
||||
level: "critical",
|
||||
message: "BIT-SMOKE error hub ingest live check",
|
||||
|
||||
@@ -4,7 +4,7 @@ import { normalizeLevelToSeverity } from "./normalize.js";
|
||||
* Versioned ruleset id (document in release notes when rules change).
|
||||
* Rule inventory and validation steps: `docs/operations/ingest-hardening-runbook.md`.
|
||||
*/
|
||||
export const NOISE_RULESET_VERSION = "1.0.5";
|
||||
export const NOISE_RULESET_VERSION = "1.0.8";
|
||||
|
||||
export type NoiseEvaluation =
|
||||
| { matched: false }
|
||||
@@ -12,6 +12,15 @@ export type NoiseEvaluation =
|
||||
|
||||
const _DEPLOY_INGEST_PROBE_MESSAGE = "BIT-SMOKE error hub ingest live check";
|
||||
|
||||
/**
|
||||
* Hand-sent pipe-liveness probes referenced by a BIT task id (e.g. `BIT-32663 smoke test`
|
||||
* or `[BIT-30527] paperclip-chat pipe-liveness smoke test`). The fleet audit already
|
||||
* treats the bracketed form as synthetic (`_SYNTHETIC_EVENT_RE`); ingest must agree so
|
||||
* these probes do not open Error Loop issues. Matched at every severity, like `BIT-SMOKE-`.
|
||||
* BIT-32681 / ERRCLUSTER a513bc4e4505.
|
||||
*/
|
||||
const _BIT_ID_SMOKE_PROBE_RE = /\[?BIT-\d+\]?\s+.*smoke test/i;
|
||||
|
||||
/**
|
||||
* CRM / editor copy-paste sometimes inserts unicode hyphens (U+2011 etc.) in the reserved
|
||||
* `BIT-SMOKE-` token; strip ZW* / BOM so probes still match `bitreport_smoke_marker` (BIT-933).
|
||||
@@ -90,12 +99,6 @@ const _RULES: NoiseRule[] = [
|
||||
match: (i) =>
|
||||
i.message.includes("ResizeObserver loop completed with undelivered notifications"),
|
||||
},
|
||||
{
|
||||
id: "wdmi_media_bitreport_load",
|
||||
reason: "filtered_media_404_noise",
|
||||
match: (i) =>
|
||||
i.message.startsWith("Resource failed to load: https://wdmi-media.bitreport.pt/media/"),
|
||||
},
|
||||
{
|
||||
id: "transient_offset_null",
|
||||
reason: "filtered_transient_frontend_noise",
|
||||
@@ -110,24 +113,12 @@ const _RULES: NoiseRule[] = [
|
||||
"Uncaught TypeError: Cannot read properties of undefined (reading 'after')",
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "stale_bundle_switch_selection_tab",
|
||||
reason: "filtered_stale_frontend_bundle_noise",
|
||||
match: (i) =>
|
||||
i.message.includes("Uncaught ReferenceError: switchSelectionEditorTab is not defined"),
|
||||
},
|
||||
{
|
||||
id: "stale_bundle_description_editor_ready",
|
||||
reason: "filtered_stale_frontend_bundle_noise",
|
||||
match: (i) =>
|
||||
i.message.includes("Uncaught ReferenceError: descriptionEditorReady is not defined"),
|
||||
},
|
||||
{
|
||||
id: "transient_parser_promise",
|
||||
reason: "filtered_transient_frontend_noise",
|
||||
match: (i) => i.message.includes("Unhandled Promise Rejection: Error: parser Error"),
|
||||
},
|
||||
/** Alpine.js v3 internal during teardown / navigation when scope is already gone (crm-wdmi / wdmi-store). */
|
||||
/** Alpine.js v3 internal during teardown / navigation when scope is already gone. */
|
||||
{
|
||||
id: "alpine_refresh_x_for_scope_teardown",
|
||||
reason: "filtered_transient_frontend_noise",
|
||||
@@ -139,8 +130,8 @@ const _RULES: NoiseRule[] = [
|
||||
|
||||
/**
|
||||
* Conservative: never classify fatal/critical ingest levels as noise (avoid hiding real outages).
|
||||
* Exception: reserved `BIT-SMOKE-` markers are intentional end-to-end probes (e.g. wdmi-store
|
||||
* `/smoke/wdmi.js`, CRM `/smoke/crm-main.php`) and are filtered at every ingest level so they do
|
||||
* Exception: reserved `BIT-SMOKE-` markers are intentional end-to-end probes (e.g. CRM
|
||||
* `/smoke/crm-main.php`) and are filtered at every ingest level so they do
|
||||
* not open incidents. Some PHP reporters put the marker only in `stack_trace`, not in `message`.
|
||||
*
|
||||
* Deploy probes also emit a fixed failure ribbon `BIT-SMOKE error hub ingest live check` (space, not
|
||||
@@ -173,6 +164,13 @@ export function evaluateNoise(input: {
|
||||
reason: "filtered_intentional_smoke_event",
|
||||
};
|
||||
}
|
||||
if (_BIT_ID_SMOKE_PROBE_RE.test(_msg) || _BIT_ID_SMOKE_PROBE_RE.test(_stack)) {
|
||||
return {
|
||||
matched: true,
|
||||
ruleId: "bitreport_smoke_marker",
|
||||
reason: "filtered_intentional_smoke_event",
|
||||
};
|
||||
}
|
||||
const _sev = normalizeLevelToSeverity(input.level);
|
||||
if (_sev === "critical") {
|
||||
return { matched: false };
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isRetiredProjectSlug } from "./retiredProjects.js";
|
||||
|
||||
describe("isRetiredProjectSlug", () => {
|
||||
it("matches known WDMI hub slugs", () => {
|
||||
expect(isRetiredProjectSlug("wdmi")).toBe(true);
|
||||
expect(isRetiredProjectSlug("wdmi-store")).toBe(true);
|
||||
expect(isRetiredProjectSlug("crm-wdmi")).toBe(true);
|
||||
expect(isRetiredProjectSlug("wdmi-ubuntu")).toBe(true);
|
||||
});
|
||||
|
||||
it("matches WDMI slug families", () => {
|
||||
expect(isRetiredProjectSlug("wdmi-legacy")).toBe(true);
|
||||
expect(isRetiredProjectSlug("store-wdmi")).toBe(true);
|
||||
expect(isRetiredProjectSlug("crm-wdmi-staging")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not match unrelated projects", () => {
|
||||
expect(isRetiredProjectSlug("crm")).toBe(false);
|
||||
expect(isRetiredProjectSlug("pa")).toBe(false);
|
||||
expect(isRetiredProjectSlug("ott")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Projects removed from the error reporting hub (BIT-24704).
|
||||
* Ingest must reject these slugs even if a project row or key is recreated by mistake.
|
||||
*/
|
||||
export const RETIRED_PROJECT_SLUGS = new Set([
|
||||
"wdmi",
|
||||
"wdmi-store",
|
||||
"crm-wdmi",
|
||||
"wdmi-ubuntu",
|
||||
]);
|
||||
|
||||
export function isRetiredProjectSlug(slug: string): boolean {
|
||||
const _normalized = slug.trim().toLowerCase();
|
||||
if (_normalized === "") {
|
||||
return false;
|
||||
}
|
||||
if (RETIRED_PROJECT_SLUGS.has(_normalized)) {
|
||||
return true;
|
||||
}
|
||||
if (_normalized.startsWith("wdmi-") || _normalized.endsWith("-wdmi")) {
|
||||
return true;
|
||||
}
|
||||
if (_normalized.startsWith("crm-wdmi")) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ingestEventsTotal, prometheusRegistry } from "./prometheus.js";
|
||||
|
||||
describe("er_ingest_events_total rule_id label (BIT-26791)", () => {
|
||||
it("records skipped_noise with rule_id", async () => {
|
||||
ingestEventsTotal.inc(
|
||||
{ outcome: "skipped_noise", rule_id: "resize_observer_loop" },
|
||||
1,
|
||||
);
|
||||
const _text = await prometheusRegistry.metrics();
|
||||
expect(_text).toContain(
|
||||
'er_ingest_events_total{outcome="skipped_noise",rule_id="resize_observer_loop"}',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -34,7 +34,8 @@ export const ingestDuration = new Histogram({
|
||||
export const ingestEventsTotal = new Counter({
|
||||
name: "er_ingest_events_total",
|
||||
help: "Total events ingested",
|
||||
labelNames: ["outcome"] as const, // stored, skipped_noise, error
|
||||
// rule_id is set for skipped_noise (noise policy id); empty for stored/error
|
||||
labelNames: ["outcome", "rule_id"] as const,
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { extractOccurrenceMetadata } from "./processIngestBatch.js";
|
||||
|
||||
describe("extractOccurrenceMetadata (BIT-33316)", () => {
|
||||
it("maps canonical keys", () => {
|
||||
const m = extractOccurrenceMetadata({}, {
|
||||
runtime_name: "php", runtime_version: "8.3", host_name: "h1",
|
||||
release_version: "1.2.3", request_id: "r1", environment: "Staging",
|
||||
});
|
||||
expect(m).toEqual({
|
||||
environment: "staging", runtime_name: "php", runtime_version: "8.3",
|
||||
host_name: "h1", release_version: "1.2.3", request_id: "r1",
|
||||
});
|
||||
});
|
||||
it("falls back to legacy aliases and production", () => {
|
||||
const m = extractOccurrenceMetadata({}, { hostname: "h2", app_version: "9" });
|
||||
expect(m.host_name).toBe("h2");
|
||||
expect(m.release_version).toBe("9");
|
||||
expect(m.environment).toBe("production");
|
||||
expect(m.runtime_name).toBeNull();
|
||||
});
|
||||
it("event.environment wins, invalid falls back", () => {
|
||||
expect(extractOccurrenceMetadata({ environment: "dev" }, { environment: "x" }).environment).toBe("dev");
|
||||
expect(extractOccurrenceMetadata({}, { environment: "bad env!" }).environment).toBe("production");
|
||||
expect(extractOccurrenceMetadata({}, null).host_name).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import type { Pool } from "mysql2/promise";
|
||||
import type { RowDataPacket } from "mysql2";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { sha256Hex } from "../lib/hash.js";
|
||||
import { isRetiredProjectSlug } from "../lib/retiredProjects.js";
|
||||
|
||||
export type IngestAuthContext = {
|
||||
keyId: string;
|
||||
@@ -51,6 +52,7 @@ export async function attachIngestAuth(
|
||||
WHERE k.token_hash = ?
|
||||
AND k.status = 'active'
|
||||
AND k.revoked_at IS NULL
|
||||
AND p.is_active = TRUE
|
||||
AND (k.expires_at IS NULL OR k.expires_at > NOW(6))`,
|
||||
[_hash],
|
||||
);
|
||||
@@ -75,12 +77,20 @@ export async function attachIngestAuth(
|
||||
});
|
||||
return;
|
||||
}
|
||||
const _projectSlug = String(_row.project_slug ?? "").trim().toLowerCase();
|
||||
if (isRetiredProjectSlug(_projectSlug)) {
|
||||
await reply.status(403).send({
|
||||
error: "project_retired",
|
||||
message: "This project is no longer accepted by the error reporting hub.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const _rlMaxNum = _row.rate_limit_max != null ? Number(_row.rate_limit_max) : NaN;
|
||||
const _rlWinNum = _row.rate_limit_window_ms != null ? Number(_row.rate_limit_window_ms) : NaN;
|
||||
request.ingestAuth = {
|
||||
keyId: _row.id,
|
||||
projectId: _row.project_id,
|
||||
projectSlug: String(_row.project_slug ?? "").trim().toLowerCase(),
|
||||
projectSlug: _projectSlug,
|
||||
rateLimitMax: Number.isFinite(_rlMaxNum) && _rlMaxNum > 0 ? _rlMaxNum : null,
|
||||
rateLimitWindowMs: Number.isFinite(_rlWinNum) && _rlWinNum > 0 ? _rlWinNum : null,
|
||||
};
|
||||
|
||||
@@ -232,6 +232,44 @@ export async function processIngestBatch(input: {
|
||||
}
|
||||
}
|
||||
|
||||
const _META_ENV_RE = /^[A-Za-z0-9._-]{1,32}$/;
|
||||
|
||||
function _metaStr(ctx: Record<string, unknown> | null, keys: string[], max: number): string | null {
|
||||
if (!ctx) return null;
|
||||
for (const k of keys) {
|
||||
const v = ctx[k];
|
||||
if (typeof v === "string" && v.trim() !== "") return v.trim().slice(0, max);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Canonical keys first, legacy aliases (hostname, app_version, ...) as fallback. BIT-33316. */
|
||||
export function extractOccurrenceMetadata(
|
||||
ev: unknown,
|
||||
ctx: Record<string, unknown> | null,
|
||||
): {
|
||||
environment: string;
|
||||
runtime_name: string | null;
|
||||
runtime_version: string | null;
|
||||
host_name: string | null;
|
||||
release_version: string | null;
|
||||
request_id: string | null;
|
||||
} {
|
||||
const evObj = (ev && typeof ev === "object" ? ev : {}) as Record<string, unknown>;
|
||||
const rawEnv =
|
||||
(typeof evObj.environment === "string" ? evObj.environment.trim() : "") ||
|
||||
_metaStr(ctx, ["environment", "env"], 32) ||
|
||||
"";
|
||||
return {
|
||||
environment: _META_ENV_RE.test(rawEnv) ? rawEnv.toLowerCase() : "production",
|
||||
runtime_name: _metaStr(ctx, ["runtime_name", "runtime"], 32),
|
||||
runtime_version: _metaStr(ctx, ["runtime_version"], 32),
|
||||
host_name: _metaStr(ctx, ["host_name", "hostname", "host"], 128),
|
||||
release_version: _metaStr(ctx, ["release_version", "release", "app_version"], 64),
|
||||
request_id: _metaStr(ctx, ["request_id", "requestId"], 128),
|
||||
};
|
||||
}
|
||||
|
||||
async function _ingestOneEvent(
|
||||
client: PoolConnection,
|
||||
input: { ingestKeyId: string; projectId: string; event: IngestEventInput },
|
||||
@@ -296,11 +334,14 @@ async function _ingestOneEvent(
|
||||
throw new Error("incident_upsert_failed");
|
||||
}
|
||||
|
||||
const _meta = extractOccurrenceMetadata(_ev, _context);
|
||||
|
||||
const [occHeader] = await client.execute<ResultSetHeader>(
|
||||
`INSERT INTO er_incident_occurrences (
|
||||
project_id, incident_id, ingest_key_id, occurred_at, level_raw, severity,
|
||||
message, stack_trace, context_json, schema_version, environment
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'production')`,
|
||||
message, stack_trace, context_json, schema_version, environment,
|
||||
runtime_name, runtime_version, host_name, release_version, request_id
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
input.projectId,
|
||||
_incidentRow.id,
|
||||
@@ -312,6 +353,12 @@ async function _ingestOneEvent(
|
||||
_stack,
|
||||
_context === null ? null : JSON.stringify(_context),
|
||||
_ev.schema_version,
|
||||
_meta.environment,
|
||||
_meta.runtime_name,
|
||||
_meta.runtime_version,
|
||||
_meta.host_name,
|
||||
_meta.release_version,
|
||||
_meta.request_id,
|
||||
],
|
||||
);
|
||||
const _occId = occHeader.insertId;
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Acceptance check for BIT-1044: BatchMode SSH from this host to WDMI Importer (LAN).
|
||||
# See docs/RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/devops/verify_importer_ssh_bit1044.sh
|
||||
# IMPORTER_HOST=192.168.1.123 SSH_USER=root ./scripts/devops/verify_importer_ssh_bit1044.sh
|
||||
# ./scripts/devops/verify_importer_ssh_bit1044.sh --diagnose # print route/neigh/ping, then SSH; exit code from SSH only
|
||||
set -euo pipefail
|
||||
|
||||
readonly IMPORTER_HOST="${IMPORTER_HOST:-192.168.1.123}"
|
||||
readonly SSH_USER="${SSH_USER:-root}"
|
||||
readonly CONNECT_TIMEOUT="${SSH_CONNECT_TIMEOUT:-10}"
|
||||
|
||||
_diagnose=0
|
||||
if [[ "${1:-}" == "--diagnose" ]]; then
|
||||
_diagnose=1
|
||||
fi
|
||||
|
||||
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
|
||||
sed -n '1,20p' "$0"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ -n "${1:-}" && "${1}" != "--diagnose" ]]; then
|
||||
echo "unknown argument: $1 (use --diagnose or no args)" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if ((_diagnose)); then
|
||||
echo "verify_importer_ssh_bit1044: route to ${IMPORTER_HOST}"
|
||||
ip route get "${IMPORTER_HOST}" 2>/dev/null || true
|
||||
echo "verify_importer_ssh_bit1044: neighbour ${IMPORTER_HOST}"
|
||||
ip neigh show "${IMPORTER_HOST}" 2>/dev/null || true
|
||||
echo "verify_importer_ssh_bit1044: ping (2 probes, 2s max wait)"
|
||||
ping -c 2 -W 2 "${IMPORTER_HOST}" 2>&1 || true
|
||||
fi
|
||||
|
||||
echo "verify_importer_ssh_bit1044: ssh BatchMode ${SSH_USER}@${IMPORTER_HOST} echo ok"
|
||||
if ssh -o BatchMode=yes -o ConnectTimeout="${CONNECT_TIMEOUT}" -o StrictHostKeyChecking=accept-new \
|
||||
"${SSH_USER}@${IMPORTER_HOST}" echo ok; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "verify_importer_ssh_bit1044: SSH failed; neighbour ${IMPORTER_HOST}:" >&2
|
||||
ip neigh show "${IMPORTER_HOST}" 2>/dev/null || true
|
||||
echo "verify_importer_ssh_bit1044: hint: run with --diagnose for route + ping" >&2
|
||||
exit 1
|
||||
@@ -22,6 +22,10 @@ _run_sql_file "/migrations/error_reporting/20260322043000_create_error_reporting
|
||||
_run_sql_file "/migrations/error_reporting/20260322044000_create_error_occurrences_and_states.up.sql"
|
||||
_run_sql_file "/migrations/error_reporting/20260322044500_add_ingest_idempotency.up.sql"
|
||||
_run_sql_file "/migrations/error_reporting/20260322045000_create_collectors_retention_and_audit.up.sql"
|
||||
_run_sql_file "/migrations/error_reporting/20260402103000_add_occurred_at_for_stats.up.sql"
|
||||
_run_sql_file "/migrations/error_reporting/20260402140000_ingest_key_rate_limits.up.sql"
|
||||
_run_sql_file "/migrations/error_reporting/20260608150000_retire_wdmi_projects.up.sql"
|
||||
_run_sql_file "/migrations/error_reporting/20260824120000_add_incidents_state_seen_idx.up.sql"
|
||||
_run_sql_file "/migrations/admin/001_admin_users.sql"
|
||||
_run_sql_file "/migrations/admin/002_admin_refresh_tokens.sql"
|
||||
_run_sql_file "/migrations/admin/003_audit_logs.sql"
|
||||
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env bash
|
||||
# offboard-project.sh — revoke keys, disable collectors, and delete a project from error_reporting.
|
||||
#
|
||||
# Usage:
|
||||
# offboard-project.sh <slug>
|
||||
#
|
||||
# Example:
|
||||
# ./scripts/offboard-project.sh wdmi-store
|
||||
#
|
||||
# Environment:
|
||||
# DATABASE_URL If set and mysql client available, applies SQL directly.
|
||||
# Otherwise prints SQL to stdout.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
_die() { echo "error: $*" >&2; exit 1; }
|
||||
|
||||
[[ $# -eq 1 ]] || _die "Usage: offboard-project.sh <slug>"
|
||||
|
||||
SLUG="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
|
||||
[[ "${SLUG}" =~ ^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$ ]] \
|
||||
|| _die "slug must be 2-64 lowercase alphanumeric/hyphens: ${SLUG}"
|
||||
|
||||
SQL="$(cat <<EOSQL
|
||||
-- Offboard project: ${SLUG}
|
||||
BEGIN;
|
||||
|
||||
UPDATE er_ingest_keys k
|
||||
INNER JOIN er_projects p ON p.id = k.project_id
|
||||
SET k.status = 'revoked',
|
||||
k.revoked_at = NOW(6)
|
||||
WHERE LOWER(p.slug) = '${SLUG}';
|
||||
|
||||
UPDATE er_collector_sources cs
|
||||
INNER JOIN er_projects p ON p.id = cs.project_id
|
||||
SET cs.is_active = FALSE
|
||||
WHERE LOWER(p.slug) = '${SLUG}';
|
||||
|
||||
DELETE FROM er_projects WHERE LOWER(slug) = '${SLUG}';
|
||||
|
||||
COMMIT;
|
||||
EOSQL
|
||||
)"
|
||||
|
||||
echo "================================================================"
|
||||
echo " Offboard project slug: ${SLUG}"
|
||||
echo "================================================================"
|
||||
echo ""
|
||||
echo "--- SQL (apply to error_reporting database) ---"
|
||||
echo "${SQL}"
|
||||
echo ""
|
||||
|
||||
if [[ -n "${DATABASE_URL:-}" ]] && command -v mysql >/dev/null 2>&1; then
|
||||
echo "DATABASE_URL is set. Applying SQL..."
|
||||
DB_URL="${DATABASE_URL#mysql://}"
|
||||
DB_USER="${DB_URL%%:*}"
|
||||
DB_REST="${DB_URL#*:}"
|
||||
DB_PASS="${DB_REST%%@*}"
|
||||
DB_REST="${DB_REST#*@}"
|
||||
DB_HOST="${DB_REST%%:*}"
|
||||
DB_REST="${DB_REST#*:}"
|
||||
DB_PORT="${DB_REST%%/*}"
|
||||
DB_NAME="${DB_REST#*/}"
|
||||
|
||||
echo "${SQL}" | mysql -h"${DB_HOST}" -P"${DB_PORT}" -u"${DB_USER}" -p"${DB_PASS}" "${DB_NAME}"
|
||||
echo "Applied successfully."
|
||||
fi
|
||||
@@ -40,6 +40,10 @@ _run "${_ROOT}/database/error_reporting/migrations/20260322043000_create_error_r
|
||||
_run "${_ROOT}/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql"
|
||||
_run "${_ROOT}/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql"
|
||||
_run "${_ROOT}/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql"
|
||||
_run "${_ROOT}/database/error_reporting/migrations/20260402103000_add_occurred_at_for_stats.up.sql"
|
||||
_run "${_ROOT}/database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.up.sql"
|
||||
_run "${_ROOT}/database/error_reporting/migrations/20260608150000_retire_wdmi_projects.up.sql"
|
||||
_run "${_ROOT}/database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.up.sql"
|
||||
_run "${_ROOT}/db/migrations/001_admin_users.sql"
|
||||
_run "${_ROOT}/db/migrations/002_admin_refresh_tokens.sql"
|
||||
_run "${_ROOT}/db/migrations/003_audit_logs.sql"
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Fleet audit — error reporting por slug (semanal).
|
||||
|
||||
Verifica se todos os slugs esperados estão a reportar eventos frescos para
|
||||
errors.bitreport.pt. Para cada slug silencioso ou stale, cria uma issue de
|
||||
correção no Paperclip.
|
||||
|
||||
Env vars lidos (ver /etc/paperclip/paperclip-fleet-error-audit.env):
|
||||
PAPERCLIP_ERROR_API_KEY — chave leitura do hub
|
||||
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
|
||||
PAPERCLIP_FLEET_AUDIT_ASSIGNEE_ID — Paperclip agent ID para assignar issues
|
||||
PAPERCLIP_FLEET_AUDIT_PARENT_ID — (opcional) parent issue ID para sub-issues
|
||||
PAPERCLIP_FLEET_AUDIT_ANCHOR_ISSUE_ID — (opcional) issue onde postar resumo
|
||||
PAPERCLIP_API_URL — Paperclip API base
|
||||
PAPERCLIP_API_KEY — Paperclip auth token
|
||||
PAPERCLIP_COMPANY_ID — Paperclip company ID
|
||||
PAPERCLIP_RUN_ID — run ID para audit trail
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
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.
|
||||
# Accepts both the bracketed form (`[BIT-30527] ... smoke test`) and the bare form
|
||||
# (`BIT-32663 smoke test`), matching the ingest noise policy `_BIT_ID_SMOKE_PROBE_RE`
|
||||
# (BIT-32681). Anchored to start so a real error mentioning the phrase mid-sentence is not
|
||||
# misclassified.
|
||||
_SYNTHETIC_EVENT_RE = re.compile(r"^\[?BIT-\d+\]?\s+.*smoke test", re.IGNORECASE)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Env helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _load_env_file(path: str) -> None:
|
||||
try:
|
||||
lines = Path(path).read_text(encoding="utf-8").splitlines()
|
||||
except OSError:
|
||||
return
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if "=" not in line:
|
||||
continue
|
||||
k, _, v = line.partition("=")
|
||||
k = k.strip()
|
||||
v = v.strip()
|
||||
# strip inline comments
|
||||
if "#" in v:
|
||||
v = v[: v.index("#")].strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
def _env(key: str, default: str = "") -> str:
|
||||
return os.environ.get(key, default).strip()
|
||||
|
||||
|
||||
def _env_int(key: str, default: int) -> int:
|
||||
raw = _env(key)
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTTP helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _get_json(url: str, headers: dict[str, str] | None = None) -> Any:
|
||||
req = urllib_request.Request(url, headers=headers or {})
|
||||
try:
|
||||
with urllib_request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read().decode())
|
||||
except HTTPError as e:
|
||||
body = e.read().decode(errors="replace")
|
||||
raise RuntimeError(f"HTTP {e.code} {e.url}: {body[:300]}") from e
|
||||
except URLError as e:
|
||||
raise RuntimeError(f"URL error {url}: {e.reason}") from e
|
||||
|
||||
|
||||
def _post_json(url: str, payload: dict[str, Any], headers: dict[str, str] | None = None) -> Any:
|
||||
data = json.dumps(payload).encode()
|
||||
hdrs = {"Content-Type": "application/json", **(headers or {})}
|
||||
req = urllib_request.Request(url, data=data, headers=hdrs, method="POST")
|
||||
try:
|
||||
with urllib_request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read().decode())
|
||||
except HTTPError as e:
|
||||
body = e.read().decode(errors="replace")
|
||||
raise RuntimeError(f"HTTP {e.code} {e.url}: {body[:300]}") from e
|
||||
except URLError as e:
|
||||
raise RuntimeError(f"URL error {url}: {e.reason}") from e
|
||||
|
||||
|
||||
def _patch_json(url: str, payload: dict[str, Any], headers: dict[str, str] | None = None) -> Any:
|
||||
data = json.dumps(payload).encode()
|
||||
hdrs = {"Content-Type": "application/json", **(headers or {})}
|
||||
req = urllib_request.Request(url, data=data, headers=hdrs, method="PATCH")
|
||||
try:
|
||||
with urllib_request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read().decode())
|
||||
except HTTPError as e:
|
||||
body = e.read().decode(errors="replace")
|
||||
raise RuntimeError(f"HTTP {e.code} {e.url}: {body[:300]}") from e
|
||||
except URLError as e:
|
||||
raise RuntimeError(f"URL error {url}: {e.reason}") from e
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Hub query
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
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&status=open,investigating,resolved,ignored&api_key={api_key}"
|
||||
)
|
||||
# Use curl to avoid Cloudflare bot challenges on urllib
|
||||
result = subprocess.run(
|
||||
["curl", "-sf", "--max-time", "30", url],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"curl failed (exit {result.returncode}): {result.stderr[:200]}")
|
||||
try:
|
||||
data = json.loads(result.stdout)
|
||||
except json.JSONDecodeError as e:
|
||||
raise RuntimeError(f"Invalid JSON from hub: {e} — body: {result.stdout[:200]}") from e
|
||||
if not data.get("success"):
|
||||
raise RuntimeError(f"Hub returned success=false: {data}")
|
||||
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)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
total_rows = len(rows)
|
||||
enforcement_active = total_rows >= min_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
|
||||
latest = None
|
||||
else:
|
||||
latest = max(times)
|
||||
hours_since = (now - latest).total_seconds() / 3600
|
||||
status = "stale" if hours_since > slug_max_age else "ok"
|
||||
|
||||
results.append(
|
||||
{
|
||||
"slug": slug,
|
||||
"status": status,
|
||||
"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),
|
||||
}
|
||||
)
|
||||
|
||||
seen_slugs = sorted(by_slug.keys())
|
||||
unexpected_slugs = [s for s in seen_slugs if s not in expected_slugs]
|
||||
|
||||
return {
|
||||
"total_rows_fetched": total_rows,
|
||||
"min_rows": min_rows,
|
||||
"enforcement_active": enforcement_active,
|
||||
"max_age_hours": max_age_hours,
|
||||
"expected_slugs": expected_slugs,
|
||||
"results": results,
|
||||
"unexpected_slugs": unexpected_slugs,
|
||||
"audited_at": now.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Paperclip helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def paperclip_create_issue(
|
||||
api_url: str,
|
||||
api_key: str,
|
||||
run_id: str,
|
||||
company_id: str,
|
||||
title: str,
|
||||
description: str,
|
||||
project_id: str,
|
||||
assignee_id: str,
|
||||
parent_id: str | None,
|
||||
) -> dict[str, Any]:
|
||||
payload: dict[str, Any] = {
|
||||
"title": title,
|
||||
"description": description,
|
||||
"status": "todo",
|
||||
"priority": "high",
|
||||
"projectId": project_id,
|
||||
"assigneeAgentId": assignee_id,
|
||||
}
|
||||
if parent_id:
|
||||
payload["parentId"] = parent_id
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"X-Paperclip-Run-Id": run_id,
|
||||
}
|
||||
return _post_json(f"{api_url}/api/companies/{company_id}/issues", payload, headers)
|
||||
|
||||
|
||||
def paperclip_post_comment(
|
||||
api_url: str,
|
||||
api_key: str,
|
||||
run_id: str,
|
||||
issue_id: str,
|
||||
body: str,
|
||||
) -> dict[str, Any]:
|
||||
headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"X-Paperclip-Run-Id": run_id,
|
||||
}
|
||||
return _post_json(
|
||||
f"{api_url}/api/issues/{issue_id}/comments",
|
||||
{"body": body},
|
||||
headers,
|
||||
)
|
||||
|
||||
|
||||
def paperclip_update_issue(
|
||||
api_url: str,
|
||||
api_key: str,
|
||||
run_id: str,
|
||||
issue_id: str,
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"X-Paperclip-Run-Id": run_id,
|
||||
}
|
||||
return _patch_json(f"{api_url}/api/issues/{issue_id}", payload, headers)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def main() -> int:
|
||||
# Load env files (automation.env first so fleet-audit.env can override)
|
||||
_load_env_file("/etc/paperclip/automation.env")
|
||||
_load_env_file("/etc/paperclip/paperclip-fleet-error-audit.env")
|
||||
|
||||
hub_base = _env("PAPERCLIP_FLEET_AUDIT_HUB_BASE", "https://errors.bitreport.pt").rstrip("/")
|
||||
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")
|
||||
assignee_id = _env("PAPERCLIP_FLEET_AUDIT_ASSIGNEE_ID")
|
||||
parent_id = _env("PAPERCLIP_FLEET_AUDIT_PARENT_ID") or None
|
||||
anchor_issue_id = _env("PAPERCLIP_FLEET_AUDIT_ANCHOR_ISSUE_ID") or None
|
||||
|
||||
api_url = _env("PAPERCLIP_API_URL", "http://127.0.0.1:3100")
|
||||
api_key = _env("PAPERCLIP_API_KEY")
|
||||
run_id = _env("PAPERCLIP_RUN_ID", "")
|
||||
company_id = _env("PAPERCLIP_COMPANY_ID")
|
||||
|
||||
# Validation
|
||||
if not hub_api_key:
|
||||
print("ERROR: PAPERCLIP_ERROR_API_KEY is not set", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
expected_slugs = [s.strip().lower() for s in expected_slugs_raw.split(",") if s.strip()]
|
||||
if not expected_slugs:
|
||||
print("ERROR: PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS is empty", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
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:
|
||||
rows = fetch_hub_rows(hub_base, hub_api_key, fetch_limit)
|
||||
except RuntimeError as e:
|
||||
print(f"ERROR fetching hub rows: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"Fetched {len(rows)} rows from hub")
|
||||
|
||||
# Analyse
|
||||
report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows, max_age_overrides)
|
||||
print(json.dumps(report, indent=2, default=str))
|
||||
|
||||
# Determine problems
|
||||
if not report["enforcement_active"]:
|
||||
print(
|
||||
f"\nEnforcement SKIPPED — only {report['total_rows_fetched']} rows "
|
||||
f"(threshold: {min_rows}). Hub may be quiet; no correction issues created."
|
||||
)
|
||||
else:
|
||||
problems = [r for r in report["results"] if r["status"] in ("silent", "stale")]
|
||||
if problems:
|
||||
print(f"\n{len(problems)} problem slug(s) found — creating correction issues")
|
||||
else:
|
||||
print("\nAll expected slugs are fresh — no correction issues needed")
|
||||
|
||||
problems = [r for r in report["results"] if r["status"] in ("silent", "stale")]
|
||||
created_issues: list[dict[str, Any]] = []
|
||||
|
||||
if report["enforcement_active"] and problems and project_id and assignee_id and api_key and company_id:
|
||||
for p in problems:
|
||||
slug = p["slug"]
|
||||
status = p["status"]
|
||||
if status == "silent":
|
||||
title = f"[fleet-audit] {slug} — sem eventos no hub (slug silencioso)"
|
||||
desc = (
|
||||
f"O slug `{slug}` não tem eventos registados em `{hub_base}`.\n\n"
|
||||
f"Auditoria: {report['audited_at']}\n"
|
||||
f"Total de rows no hub: {report['total_rows_fetched']}"
|
||||
)
|
||||
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: {slug_max_age}h).\n\n"
|
||||
f"Último evento: `{latest}`\n"
|
||||
f"Hub: `{hub_base}`\n"
|
||||
f"Auditoria: {report['audited_at']}"
|
||||
)
|
||||
|
||||
try:
|
||||
issue = paperclip_create_issue(
|
||||
api_url, api_key, run_id, company_id,
|
||||
title, desc, project_id, assignee_id, parent_id,
|
||||
)
|
||||
issue_id = issue.get("id", "")
|
||||
identifier = issue.get("identifier", "")
|
||||
created_issues.append({"slug": slug, "issue_id": issue_id, "identifier": identifier})
|
||||
print(f" Created correction issue {identifier} for slug '{slug}'")
|
||||
except RuntimeError as e:
|
||||
print(f" ERROR creating issue for slug '{slug}': {e}", file=sys.stderr)
|
||||
|
||||
# Build summary comment
|
||||
lines = ["## Fleet Audit — Error Reporting por Slug", ""]
|
||||
lines.append(f"**Auditado em:** {report['audited_at']}")
|
||||
lines.append(f"**Hub:** {hub_base}")
|
||||
lines.append(f"**Rows fetched:** {report['total_rows_fetched']} (min para enforcement: {min_rows})")
|
||||
lines.append("")
|
||||
|
||||
if not report["enforcement_active"]:
|
||||
lines.append("> **Enforcement inativo** — hub com poucos eventos, possível dia tranquilo.")
|
||||
lines.append("")
|
||||
|
||||
lines.append("### Slugs esperados")
|
||||
lines.append("")
|
||||
for r in report["results"]:
|
||||
slug = r["slug"]
|
||||
st = r["status"]
|
||||
if st == "ok":
|
||||
hours = r["hours_since_last_event"]
|
||||
icon = "✅"
|
||||
detail = f"fresco — último evento há {hours:.1f}h"
|
||||
elif st == "stale":
|
||||
hours = r["hours_since_last_event"]
|
||||
icon = "⚠️"
|
||||
detail = f"stale — último evento há {hours:.1f}h (limiar: {r['max_age_hours']}h)"
|
||||
else:
|
||||
icon = "🔴"
|
||||
detail = "silencioso — sem eventos"
|
||||
lines.append(f"- {icon} **{slug}**: {detail}")
|
||||
|
||||
if report["unexpected_slugs"]:
|
||||
lines.append("")
|
||||
lines.append("### Slugs inesperados no hub (informação)")
|
||||
for s in report["unexpected_slugs"]:
|
||||
lines.append(f"- `{s}`")
|
||||
|
||||
if created_issues:
|
||||
lines.append("")
|
||||
lines.append("### Issues de correção criadas")
|
||||
for ci in created_issues:
|
||||
identifier = ci["identifier"]
|
||||
issue_id = ci["issue_id"]
|
||||
lines.append(f"- [{identifier}](/BIT/issues/{identifier}) — slug `{ci['slug']}`")
|
||||
|
||||
if not problems or not report["enforcement_active"]:
|
||||
lines.append("")
|
||||
lines.append("_Sem ações corretivas necessárias nesta execução._")
|
||||
|
||||
summary_comment = "\n".join(lines)
|
||||
print("\n--- SUMMARY ---")
|
||||
print(summary_comment)
|
||||
|
||||
# Post summary to anchor issue if configured
|
||||
if anchor_issue_id and api_key:
|
||||
try:
|
||||
paperclip_post_comment(api_url, api_key, run_id, anchor_issue_id, summary_comment)
|
||||
print(f"\nSummary posted to issue {anchor_issue_id}")
|
||||
except RuntimeError as e:
|
||||
print(f"WARNING: could not post summary comment: {e}", file=sys.stderr)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Generated
+9
-9
@@ -15,7 +15,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"eslint": "^9.15.0",
|
||||
@@ -23,7 +23,7 @@
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
@@ -982,13 +982,13 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.19.17",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.17.tgz",
|
||||
"integrity": "sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q==",
|
||||
"version": "24.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
|
||||
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
"undici-types": ">=7.24.0 <7.24.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
@@ -5311,9 +5311,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"eslint": "^9.15.0",
|
||||
@@ -25,6 +25,6 @@
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user