From 7daa8673744f67ef5bd4b4d758da2b0dff7983a4 Mon Sep 17 00:00:00 2001 From: David Santos Date: Thu, 16 Apr 2026 10:24:33 +0000 Subject: [PATCH] chore(lab): sync working tree from Paperclip execution host (10.10.50.17) --- .env.example | 3 + collector-worker/src/config/loadEnv.ts | 11 +++ .../src/ingest/pushEvents.test.ts | 67 +++++++++++++- collector-worker/src/ingest/pushEvents.ts | 87 +++++++++++++++++-- .../src/scheduler/runHttpSourceOnce.ts | 5 ++ docker-compose.yml | 3 + docs/RUNBOOK_SLO.md | 20 +++++ ...treport-error-reporting-compose-proxmox.md | 1 + 8 files changed, 189 insertions(+), 8 deletions(-) diff --git a/.env.example b/.env.example index c47f35c..4874fde 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,9 @@ ER_COLLECTOR_PROJECT_ALPHA_TOKEN=er_tst_a_secret_one # SOURCE_REFRESH_MS=15000 # HTTP_FETCH_TIMEOUT_MS=15000 # INGEST_PUSH_TIMEOUT_MS=60000 +# INGEST_PUSH_MAX_RETRIES=3 +# INGEST_PUSH_RETRY_BASE_MS=500 +# INGEST_PUSH_RETRY_MAX_JITTER_MS=250 # MAX_BACKOFF_EXPONENT=8 # COLLECTOR_DEFAULT_INGEST_TOKEN= diff --git a/collector-worker/src/config/loadEnv.ts b/collector-worker/src/config/loadEnv.ts index 1ff89eb..7a6f159 100644 --- a/collector-worker/src/config/loadEnv.ts +++ b/collector-worker/src/config/loadEnv.ts @@ -5,6 +5,10 @@ export type CollectorEnv = { INGEST_BASE_URL: string; HTTP_FETCH_TIMEOUT_MS: number; INGEST_PUSH_TIMEOUT_MS: number; + /** Retries after the first failed push when the failure looks transient (5xx, 429, timeout, etc.). */ + INGEST_PUSH_MAX_RETRIES: number; + INGEST_PUSH_RETRY_BASE_MS: number; + INGEST_PUSH_RETRY_MAX_JITTER_MS: number; TICK_INTERVAL_MS: number; SOURCE_REFRESH_MS: number; MAX_BACKOFF_EXPONENT: number; @@ -32,11 +36,18 @@ export function loadEnv(): CollectorEnv { throw new Error("INGEST_BASE_URL is required (e.g. http://ingest-api:3041)"); } const _ingestPushMs = _parseIntWithDefault(process.env.INGEST_PUSH_TIMEOUT_MS, 60_000); + const _pushRetries = _parseIntWithDefault(process.env.INGEST_PUSH_MAX_RETRIES, 3); return { DATABASE_URL: _databaseUrl.trim(), INGEST_BASE_URL: _ingestBase.trim().replace(/\/$/, ""), HTTP_FETCH_TIMEOUT_MS: _parseIntWithDefault(process.env.HTTP_FETCH_TIMEOUT_MS, 30_000), INGEST_PUSH_TIMEOUT_MS: Math.max(1000, _ingestPushMs), + INGEST_PUSH_MAX_RETRIES: Math.min(12, Math.max(0, _pushRetries)), + INGEST_PUSH_RETRY_BASE_MS: Math.max(0, _parseIntWithDefault(process.env.INGEST_PUSH_RETRY_BASE_MS, 500)), + INGEST_PUSH_RETRY_MAX_JITTER_MS: Math.max( + 0, + _parseIntWithDefault(process.env.INGEST_PUSH_RETRY_MAX_JITTER_MS, 250), + ), TICK_INTERVAL_MS: _parseIntWithDefault(process.env.TICK_INTERVAL_MS, 2000), SOURCE_REFRESH_MS: _parseIntWithDefault(process.env.SOURCE_REFRESH_MS, 10_000), MAX_BACKOFF_EXPONENT: _parseIntWithDefault(process.env.MAX_BACKOFF_EXPONENT, 8), diff --git a/collector-worker/src/ingest/pushEvents.test.ts b/collector-worker/src/ingest/pushEvents.test.ts index 648d356..72f4abc 100644 --- a/collector-worker/src/ingest/pushEvents.test.ts +++ b/collector-worker/src/ingest/pushEvents.test.ts @@ -24,7 +24,7 @@ describe("pushEventsToIngest", () => { events: [], timeoutMs: 5000, }); - expect(_r).toEqual({ ok: true, status: 200, accepted: 0 }); + expect(_r).toEqual({ ok: true, status: 200, accepted: 0, attempts: 0 }); expect(global.fetch).not.toHaveBeenCalled(); }); @@ -51,8 +51,10 @@ describe("pushEventsToIngest", () => { bearerToken: "t", events: [_sampleEvent], timeoutMs: 30, + maxRetries: 0, }); - expect(_r).toEqual({ ok: false, status: null, error: "ingest_push_timeout" }); + expect(_r).toEqual({ ok: false, status: null, error: "ingest_push_timeout", attempts: 1 }); + expect(global.fetch).toHaveBeenCalledTimes(1); }); it("returns ok when ingest accepts the batch", async () => { @@ -68,7 +70,7 @@ describe("pushEventsToIngest", () => { events: [_sampleEvent], timeoutMs: 5000, }); - expect(_r).toEqual({ ok: true, status: 200, accepted: 1 }); + expect(_r).toEqual({ ok: true, status: 200, accepted: 1, attempts: 1 }); expect(global.fetch).toHaveBeenCalledWith( "http://ingest/v1/ingest/events", expect.objectContaining({ @@ -77,4 +79,63 @@ describe("pushEventsToIngest", () => { }), ); }); + + it("retries transient 503 and succeeds on a later attempt", async () => { + let _n = 0; + global.fetch = vi.fn(async () => { + _n += 1; + if (_n < 3) { + return new Response("unavailable", { status: 503 }); + } + return new Response(null, { status: 200 }); + }) as typeof fetch; + const _r = await pushEventsToIngest({ + ingestBaseUrl: "http://ingest", + bearerToken: "t", + events: [_sampleEvent], + timeoutMs: 5000, + maxRetries: 4, + retryBaseDelayMs: 0, + retryMaxJitterMs: 0, + }); + expect(_r.ok).toBe(true); + if (_r.ok) { + expect(_r.attempts).toBe(3); + } + expect(global.fetch).toHaveBeenCalledTimes(3); + }); + + it("does not retry non-transient 401", async () => { + global.fetch = vi.fn(async () => new Response("nope", { status: 401 })) as typeof fetch; + const _r = await pushEventsToIngest({ + ingestBaseUrl: "http://ingest", + bearerToken: "t", + events: [_sampleEvent], + timeoutMs: 5000, + maxRetries: 3, + retryBaseDelayMs: 0, + retryMaxJitterMs: 0, + }); + expect(_r).toMatchObject({ ok: false, status: 401, attempts: 1 }); + expect(global.fetch).toHaveBeenCalledTimes(1); + }); + + it("exhausts retries on persistent 503", async () => { + global.fetch = vi.fn(async () => new Response("unavailable", { status: 503 })) as typeof fetch; + const _r = await pushEventsToIngest({ + ingestBaseUrl: "http://ingest", + bearerToken: "t", + events: [_sampleEvent], + timeoutMs: 5000, + maxRetries: 2, + retryBaseDelayMs: 0, + retryMaxJitterMs: 0, + }); + expect(_r.ok).toBe(false); + if (!_r.ok) { + expect(_r.status).toBe(503); + expect(_r.attempts).toBe(3); + } + expect(global.fetch).toHaveBeenCalledTimes(3); + }); }); diff --git a/collector-worker/src/ingest/pushEvents.ts b/collector-worker/src/ingest/pushEvents.ts index 049df76..1bfcf97 100644 --- a/collector-worker/src/ingest/pushEvents.ts +++ b/collector-worker/src/ingest/pushEvents.ts @@ -1,18 +1,43 @@ import type { IngestEventInput } from "../types/ingest.js"; export type PushIngestResult = + | { ok: true; status: number; accepted: number; attempts: number } + | { ok: false; status: number | null; error: string; attempts: number }; + +type PushOnceResult = | { ok: true; status: number; accepted: number } | { ok: false; status: number | null; error: string }; -export async function pushEventsToIngest(input: { +function _isTransientIngestFailure(input: { status: number | null; error: string }): boolean { + if (input.status !== null) { + return [408, 425, 429, 500, 502, 503, 504].includes(input.status); + } + if (input.error === "ingest_push_timeout") { + return true; + } + const _m = input.error.toLowerCase(); + return ( + _m.includes("fetch failed") || + _m.includes("econnreset") || + _m.includes("econnrefused") || + _m.includes("etimedout") || + _m.includes("socket hang up") || + _m.includes("networkerror") + ); +} + +function _sleepMs(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + +async function _pushEventsOnce(input: { ingestBaseUrl: string; bearerToken: string; events: IngestEventInput[]; timeoutMs: number; -}): Promise { - if (input.events.length === 0) { - return { ok: true, status: 200, accepted: 0 }; - } +}): Promise { const _url = `${input.ingestBaseUrl}/v1/ingest/events`; const _controller = new AbortController(); const _timer = setTimeout(() => _controller.abort(), input.timeoutMs); @@ -45,3 +70,55 @@ export async function pushEventsToIngest(input: { clearTimeout(_timer); } } + +function _withAttempts(result: PushOnceResult, attempts: number): PushIngestResult { + if (result.ok) { + return { ok: true, status: result.status, accepted: result.accepted, attempts }; + } + return { ok: false, status: result.status, error: result.error, attempts }; +} + +export async function pushEventsToIngest(input: { + ingestBaseUrl: string; + bearerToken: string; + events: IngestEventInput[]; + timeoutMs: number; + /** Extra attempts after the first failure (0 = single attempt). */ + maxRetries?: number; + /** Base delay before the first retry; doubles each retry (ms). */ + retryBaseDelayMs?: number; + /** Inclusive upper bound for random jitter added to each delay (ms). */ + retryMaxJitterMs?: number; +}): Promise { + if (input.events.length === 0) { + return { ok: true, status: 200, accepted: 0, attempts: 0 }; + } + const _maxRetries = input.maxRetries ?? 0; + const _base = Math.max(0, input.retryBaseDelayMs ?? 500); + const _jitterCap = Math.max(0, input.retryMaxJitterMs ?? 250); + + let _last = await _pushEventsOnce({ + ingestBaseUrl: input.ingestBaseUrl, + bearerToken: input.bearerToken, + events: input.events, + timeoutMs: input.timeoutMs, + }); + let _attempts = 1; + + for (let _r = 0; _r < _maxRetries && !_last.ok; _r++) { + if (!_isTransientIngestFailure(_last)) { + break; + } + const _delay = _base * 2 ** _r + Math.floor(Math.random() * (_jitterCap + 1)); + await _sleepMs(_delay); + _last = await _pushEventsOnce({ + ingestBaseUrl: input.ingestBaseUrl, + bearerToken: input.bearerToken, + events: input.events, + timeoutMs: input.timeoutMs, + }); + _attempts += 1; + } + + return _withAttempts(_last, _attempts); +} diff --git a/collector-worker/src/scheduler/runHttpSourceOnce.ts b/collector-worker/src/scheduler/runHttpSourceOnce.ts index 35e8da9..1cf5a47 100644 --- a/collector-worker/src/scheduler/runHttpSourceOnce.ts +++ b/collector-worker/src/scheduler/runHttpSourceOnce.ts @@ -140,6 +140,9 @@ export async function runHttpSourceOnce(input: { bearerToken: _token, events: _fetched.events, timeoutMs: env.INGEST_PUSH_TIMEOUT_MS, + maxRetries: env.INGEST_PUSH_MAX_RETRIES, + retryBaseDelayMs: env.INGEST_PUSH_RETRY_BASE_MS, + retryMaxJitterMs: env.INGEST_PUSH_RETRY_MAX_JITTER_MS, }); if (!_push.ok) { @@ -164,6 +167,7 @@ export async function runHttpSourceOnce(input: { http_status: _push.status, error: _summary.slice(0, 200), consecutive_failures: state.consecutiveFailures, + ingest_push_attempts: _push.attempts, }); return; } @@ -194,6 +198,7 @@ export async function runHttpSourceOnce(input: { fetched_count: _fetched.events.length, accepted_count: _push.accepted, failed_count: 0, + ingest_push_attempts: _push.attempts, }); } diff --git a/docker-compose.yml b/docker-compose.yml index f4c0d82..9040ebc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -100,6 +100,9 @@ services: SOURCE_REFRESH_MS: ${SOURCE_REFRESH_MS:-15000} HTTP_FETCH_TIMEOUT_MS: ${HTTP_FETCH_TIMEOUT_MS:-15000} INGEST_PUSH_TIMEOUT_MS: ${INGEST_PUSH_TIMEOUT_MS:-60000} + INGEST_PUSH_MAX_RETRIES: ${INGEST_PUSH_MAX_RETRIES:-3} + INGEST_PUSH_RETRY_BASE_MS: ${INGEST_PUSH_RETRY_BASE_MS:-500} + INGEST_PUSH_RETRY_MAX_JITTER_MS: ${INGEST_PUSH_RETRY_MAX_JITTER_MS:-250} MAX_BACKOFF_EXPONENT: ${MAX_BACKOFF_EXPONENT:-8} NODE_ENV: production ER_COLLECTOR_PROJECT_ALPHA_TOKEN: ${ER_COLLECTOR_PROJECT_ALPHA_TOKEN:-er_tst_a_secret_one} diff --git a/docs/RUNBOOK_SLO.md b/docs/RUNBOOK_SLO.md index cf514f1..facad59 100644 --- a/docs/RUNBOOK_SLO.md +++ b/docs/RUNBOOK_SLO.md @@ -89,6 +89,26 @@ groups: summary: "Error monitoring API is unreachable" ``` +### Collector → ingest resilience ([BIT-2600](/BIT/issues/BIT-2600)) + +The **collector-worker** pushes batched events to **ingest-api** (`POST /v1/ingest/events`). Large or bursty payloads (for example many “feed upload” failure reports from upstream jobs) benefit from tunable timeouts and client-side retries before the worker applies source-level backoff. + +| Variable | Default (code / compose) | Role | +|----------|--------------------------|------| +| `INGEST_PUSH_TIMEOUT_MS` | `60000` | Per-attempt HTTP timeout (abort + retry if transient). | +| `INGEST_PUSH_MAX_RETRIES` | `3` | Extra attempts after the first failure (cap 12 in code). | +| `INGEST_PUSH_RETRY_BASE_MS` | `500` | Base delay; delay before retry *k* is `base * 2^k` + jitter. | +| `INGEST_PUSH_RETRY_MAX_JITTER_MS` | `250` | Random jitter upper bound (inclusive) added to each delay. | + +Transient failures retried: HTTP `408`, `425`, `429`, `5xx`, timeouts, and common Node `fetch` network errors. Non-transient `4xx` (except those listed) are not retried. + +**Structured logs:** on failure, `collector_ingest_failed` includes `ingest_push_attempts` (total HTTP attempts in that cycle) and `consecutive_failures` (scheduler backoff counter). On success after retries, `collector_cycle_complete` still includes `ingest_push_attempts` when it was greater than one. + +**Alerting ideas** + +- **Ingest SLO:** keep using `IngestErrorRateHigh` on `er_ingest_requests_total` — sustained 5xx/429 from the collector’s perspective show up here. +- **Log / trace backend:** alert when `msg="collector_ingest_failed"` and `consecutive_failures` stays above a threshold (for example ≥ 5) for longer than your SLO window, which indicates the source is failing every poll even after ingest push retries. + --- ## Prometheus Scrape Config diff --git a/docs/deployment/bitreport-error-reporting-compose-proxmox.md b/docs/deployment/bitreport-error-reporting-compose-proxmox.md index c651531..90f1ff8 100644 --- a/docs/deployment/bitreport-error-reporting-compose-proxmox.md +++ b/docs/deployment/bitreport-error-reporting-compose-proxmox.md @@ -61,6 +61,7 @@ docker compose up --build | `INGEST_RATE_LIMIT_MAX` | ingest-api | Máx. pedidos por janela (opcional) | | `INGEST_RATE_LIMIT_WINDOW_MS` | ingest-api | Janela em ms (opcional) | | `TICK_INTERVAL_MS`, `SOURCE_REFRESH_MS`, `HTTP_FETCH_TIMEOUT_MS`, `MAX_BACKOFF_EXPONENT` | collector-worker | Intervalos e limites (opcional) | +| `INGEST_PUSH_TIMEOUT_MS`, `INGEST_PUSH_MAX_RETRIES`, `INGEST_PUSH_RETRY_BASE_MS`, `INGEST_PUSH_RETRY_MAX_JITTER_MS` | collector-worker | Push para ingest-api: timeout por tentativa, retries com backoff exponencial + jitter (opcional; ver [RUNBOOK_SLO.md](../RUNBOOK_SLO.md) § Collector) | | `COLLECTOR_DEFAULT_INGEST_TOKEN` | collector-worker | Fallback para referências `env:VAR` vazias (opcional) | A `DATABASE_URL` usada nos containers é construída pelo Compose no formato `mysql://USER:PASSWORD@mariadb:3306/DATABASE`. Palavras-passe com caracteres especiais devem ser [percent-encoded](https://datatracker.ietf.org/doc/html/rfc3986#section-2.1).