chore(lab): sync working tree from Paperclip execution host (10.10.50.17)
CI / Test ingest-api (push) Has been cancelled
CI / Test api (push) Has been cancelled
CI / Lint and typecheck admin-ui (push) Has been cancelled
CI / Validate Docker build (push) Has been cancelled

This commit is contained in:
David Santos committed 2026-04-16 10:24:33 +00:00
1 parent 2d93c4a3fc
commit 7daa867374
8 files changed
+189 -8

No files matched your search

+3
View File
@@ -32,6 +32,9 @@ ER_COLLECTOR_PROJECT_ALPHA_TOKEN=er_tst_a_secret_one
# SOURCE_REFRESH_MS=15000 # SOURCE_REFRESH_MS=15000
# HTTP_FETCH_TIMEOUT_MS=15000 # HTTP_FETCH_TIMEOUT_MS=15000
# INGEST_PUSH_TIMEOUT_MS=60000 # 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 # MAX_BACKOFF_EXPONENT=8
# COLLECTOR_DEFAULT_INGEST_TOKEN= # COLLECTOR_DEFAULT_INGEST_TOKEN=
+11
View File
@@ -5,6 +5,10 @@ export type CollectorEnv = {
INGEST_BASE_URL: string; INGEST_BASE_URL: string;
HTTP_FETCH_TIMEOUT_MS: number; HTTP_FETCH_TIMEOUT_MS: number;
INGEST_PUSH_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; TICK_INTERVAL_MS: number;
SOURCE_REFRESH_MS: number; SOURCE_REFRESH_MS: number;
MAX_BACKOFF_EXPONENT: 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)"); 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 _ingestPushMs = _parseIntWithDefault(process.env.INGEST_PUSH_TIMEOUT_MS, 60_000);
const _pushRetries = _parseIntWithDefault(process.env.INGEST_PUSH_MAX_RETRIES, 3);
return { return {
DATABASE_URL: _databaseUrl.trim(), DATABASE_URL: _databaseUrl.trim(),
INGEST_BASE_URL: _ingestBase.trim().replace(/\/$/, ""), INGEST_BASE_URL: _ingestBase.trim().replace(/\/$/, ""),
HTTP_FETCH_TIMEOUT_MS: _parseIntWithDefault(process.env.HTTP_FETCH_TIMEOUT_MS, 30_000), HTTP_FETCH_TIMEOUT_MS: _parseIntWithDefault(process.env.HTTP_FETCH_TIMEOUT_MS, 30_000),
INGEST_PUSH_TIMEOUT_MS: Math.max(1000, _ingestPushMs), 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), TICK_INTERVAL_MS: _parseIntWithDefault(process.env.TICK_INTERVAL_MS, 2000),
SOURCE_REFRESH_MS: _parseIntWithDefault(process.env.SOURCE_REFRESH_MS, 10_000), SOURCE_REFRESH_MS: _parseIntWithDefault(process.env.SOURCE_REFRESH_MS, 10_000),
MAX_BACKOFF_EXPONENT: _parseIntWithDefault(process.env.MAX_BACKOFF_EXPONENT, 8), MAX_BACKOFF_EXPONENT: _parseIntWithDefault(process.env.MAX_BACKOFF_EXPONENT, 8),
+64 -3
View File
@@ -24,7 +24,7 @@ describe("pushEventsToIngest", () => {
events: [], events: [],
timeoutMs: 5000, 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(); expect(global.fetch).not.toHaveBeenCalled();
}); });
@@ -51,8 +51,10 @@ describe("pushEventsToIngest", () => {
bearerToken: "t", bearerToken: "t",
events: [_sampleEvent], events: [_sampleEvent],
timeoutMs: 30, 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 () => { it("returns ok when ingest accepts the batch", async () => {
@@ -68,7 +70,7 @@ describe("pushEventsToIngest", () => {
events: [_sampleEvent], events: [_sampleEvent],
timeoutMs: 5000, 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( expect(global.fetch).toHaveBeenCalledWith(
"http://ingest/v1/ingest/events", "http://ingest/v1/ingest/events",
expect.objectContaining({ 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);
});
}); });
+82 -5
View File
@@ -1,18 +1,43 @@
import type { IngestEventInput } from "../types/ingest.js"; import type { IngestEventInput } from "../types/ingest.js";
export type PushIngestResult = 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: true; status: number; accepted: number }
| { ok: false; status: number | null; error: string }; | { 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<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function _pushEventsOnce(input: {
ingestBaseUrl: string; ingestBaseUrl: string;
bearerToken: string; bearerToken: string;
events: IngestEventInput[]; events: IngestEventInput[];
timeoutMs: number; timeoutMs: number;
}): Promise<PushIngestResult> { }): Promise<PushOnceResult> {
if (input.events.length === 0) {
return { ok: true, status: 200, accepted: 0 };
}
const _url = `${input.ingestBaseUrl}/v1/ingest/events`; const _url = `${input.ingestBaseUrl}/v1/ingest/events`;
const _controller = new AbortController(); const _controller = new AbortController();
const _timer = setTimeout(() => _controller.abort(), input.timeoutMs); const _timer = setTimeout(() => _controller.abort(), input.timeoutMs);
@@ -45,3 +70,55 @@ export async function pushEventsToIngest(input: {
clearTimeout(_timer); 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<PushIngestResult> {
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);
}
@@ -140,6 +140,9 @@ export async function runHttpSourceOnce(input: {
bearerToken: _token, bearerToken: _token,
events: _fetched.events, events: _fetched.events,
timeoutMs: env.INGEST_PUSH_TIMEOUT_MS, 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) { if (!_push.ok) {
@@ -164,6 +167,7 @@ export async function runHttpSourceOnce(input: {
http_status: _push.status, http_status: _push.status,
error: _summary.slice(0, 200), error: _summary.slice(0, 200),
consecutive_failures: state.consecutiveFailures, consecutive_failures: state.consecutiveFailures,
ingest_push_attempts: _push.attempts,
}); });
return; return;
} }
@@ -194,6 +198,7 @@ export async function runHttpSourceOnce(input: {
fetched_count: _fetched.events.length, fetched_count: _fetched.events.length,
accepted_count: _push.accepted, accepted_count: _push.accepted,
failed_count: 0, failed_count: 0,
ingest_push_attempts: _push.attempts,
}); });
} }
+3
View File
@@ -100,6 +100,9 @@ services:
SOURCE_REFRESH_MS: ${SOURCE_REFRESH_MS:-15000} SOURCE_REFRESH_MS: ${SOURCE_REFRESH_MS:-15000}
HTTP_FETCH_TIMEOUT_MS: ${HTTP_FETCH_TIMEOUT_MS:-15000} HTTP_FETCH_TIMEOUT_MS: ${HTTP_FETCH_TIMEOUT_MS:-15000}
INGEST_PUSH_TIMEOUT_MS: ${INGEST_PUSH_TIMEOUT_MS:-60000} 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} MAX_BACKOFF_EXPONENT: ${MAX_BACKOFF_EXPONENT:-8}
NODE_ENV: production NODE_ENV: production
ER_COLLECTOR_PROJECT_ALPHA_TOKEN: ${ER_COLLECTOR_PROJECT_ALPHA_TOKEN:-er_tst_a_secret_one} ER_COLLECTOR_PROJECT_ALPHA_TOKEN: ${ER_COLLECTOR_PROJECT_ALPHA_TOKEN:-er_tst_a_secret_one}
+20
View File
@@ -89,6 +89,26 @@ groups:
summary: "Error monitoring API is unreachable" 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 ## Prometheus Scrape Config
@@ -61,6 +61,7 @@ docker compose up --build
| `INGEST_RATE_LIMIT_MAX` | ingest-api | Máx. pedidos por janela (opcional) | | `INGEST_RATE_LIMIT_MAX` | ingest-api | Máx. pedidos por janela (opcional) |
| `INGEST_RATE_LIMIT_WINDOW_MS` | ingest-api | Janela em ms (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) | | `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) | | `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). 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).