From 0119924c10d211f3cbcc48c58141c5056719e402 Mon Sep 17 00:00:00 2001 From: czy Date: Sat, 21 Nov 2026 12:13:59 -0600 Subject: [PATCH 1/2] FX-047: keep events on temporary errors, honour Retry-After, count drops, bound flush() - 5xx/503/429/408/timeout/network: the event is kept and retried with backoff (up to 60 s between cycles) for maxRetryDuration (default 1 h) instead of being deleted after 10 failed flush cycles (~2 minutes). Same event object, same eventId. - Retry-After (seconds or HTTP date, capped at 5 min) is honoured inline and between cycles. - 401/403 kept and retried for 10 minutes, then dropped; other 4xx stay final. - getStats(): queued, in-flight and dropped counts by reason; drops logged as one summary line per flush cycle. - flush() bounded by flushTimeout (default 30 s); flush() and close() resolve with { unsent }. - Event id builder unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 22 +++ README.md | 60 ++++--- package.json | 2 +- src/index.ts | 434 ++++++++++++++++++++++++++++++++++--------------- tests/retry.ts | 243 +++++++++++++++++++++++++++ tests/test.ts | 11 +- 6 files changed, 621 insertions(+), 151 deletions(-) create mode 100644 tests/retry.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f90a31a..53b1735 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,28 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Fixed +- **Events were deleted during a server outage.** An event that failed with a temporary + error (`5xx`, `503`, `429`, `408`, a timeout or a network error) was dropped after 10 + failed flush cycles, about two minutes at the default settings. It is now kept and + retried for `maxRetryDuration` (new, default 1 hour), with backoff of up to 60 s between + cycles. Every retry carries the same `eventId`, and an event the server accepted (`2xx`) + is never sent again. +- **`Retry-After` was ignored.** The server answers `503` and `429` with `Retry-After`; the + SDK now waits at least that long (seconds or an HTTP date, capped at 5 minutes). +- **`401`/`403` deleted events at once.** A key check that fails for a moment now costs + nothing: the event is kept and retried for 10 minutes, then dropped as + `permanent_client_error`. Other `4xx` answers (`400`, `413`, ...) are still final. +- **`flush()` had no time bound** and could wait through every retry of every event. It now + waits at most `flushTimeout` (new, default 30 s). + +### Added +- `getStats()`: queued, in-flight and dropped counts, by drop reason. +- `flush()` and `close()` resolve with `{ unsent }`, the number of events not delivered when + they returned, and log one line when it is above zero. +- Drops (queue cap, final answers, expired retries) are logged as one summary line per flush + cycle instead of a first-overflow warning and a line per expired event. + ## [1.3.4] - 2026-11-14 ### Fixed diff --git a/README.md b/README.md index 8894b47..a52613c 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,8 @@ const datalyr = new Datalyr({ retryLimit: 3, maxQueueSize: 1000, closeTimeout: 30000, + flushTimeout: 30000, + maxRetryDuration: 3600000, onError: (event, error) => console.error(event.event, error), onDrop: (events, reason) => console.error(reason, events.length), }); @@ -108,6 +110,8 @@ Every numeric option is clamped. A value outside its range becomes the nearest b | `retryLimit` | `number` | `3` | retries | 0–10 | | `maxQueueSize` | `number` | `1000` | events | 100–10000 | | `closeTimeout` | `number` | `30000` | milliseconds | 1000–120000 | +| `flushTimeout` | `number` | `30000` | milliseconds | 1000–120000 | +| `maxRetryDuration` | `number` | `3600000` | milliseconds | 60000–86400000 | | `debug` | `boolean` | `false` | — | — | | `onError` | `(event: TrackEvent, error: Error) => void` | Unset | — | — | | `onDrop` | `(events: TrackEvent[], reason: DropReason) => void` | Unset | — | — | @@ -128,8 +132,9 @@ Every option above is read by the SDK. None is dead. | `page` | `(userId: string, name?: string, properties?: any, anonymousId?: string) => Promise` | | `group` | `(userId: string, groupId: string, traits?: any, anonymousId?: string) => Promise` | | `trackPurchase` | `(userId: string \| null, purchase: PurchaseProperties, opts?: { anonymousId?: string; eventId?: string; timestamp?: string \| Date \| number }) => Promise` | -| `flush` | `() => Promise` | -| `close` | `() => Promise` | +| `flush` | `() => Promise` — `{ unsent: number }` | +| `close` | `() => Promise` — `{ unsent: number }` | +| `getStats` | `() => DatalyrStats` — `{ queued, inFlight, dropped, droppedByReason }` | | `getAnonymousId` | `() => string` | ## Identity @@ -350,9 +355,11 @@ await datalyr.close(); // once, at process shutdown ### flush() -`flush()` drains the whole queue and resolves once every event is sent, or once a pass -delivers nothing against a down endpoint. It loops, so events enqueued during a flush are -also sent. When a drain is already running, `flush()` awaits that drain instead of +`flush()` sends the queue and resolves once every event is sent, once a pass delivers +nothing against a down endpoint, or once `flushTimeout` (default 30,000 ms) has passed, +whichever comes first. It resolves with `{ unsent }`: the events still queued or in +flight. Those are kept and retried later, not dropped, and one log line says how many. It +loops, so events enqueued during a flush are also sent. When a drain is already running, `flush()` awaits that drain instead of starting a second one. That includes a drain started by reaching `flushAt`, even though the queue is already empty by then. Before 1.3.4, `flush()` returned at once in that case with the sends still in flight. @@ -384,10 +391,11 @@ process.on('SIGTERM', async () => { }); ``` -Events still queued when the budget expires go to `onDrop(events, 'close_timeout')`. A +`close()` resolves with `{ unsent }`, and logs one line when it is above zero. Events +still queued when the budget expires go to `onDrop(events, 'close_timeout')`. A send still running at that moment keeps going in the background, so its result arrives after `close()` has returned: it is delivered, or `onDrop` fires for it then -(`close_timeout` for a retryable failure, `permanent_client_error` for a 4xx). +(`close_timeout` for a retryable failure, `permanent_client_error` for a final 4xx). The SDK also registers a `beforeExit` hook that calls `flush()` best-effort. That hook does not replace `await close()`. @@ -411,13 +419,22 @@ const datalyr = new Datalyr({ | --- | --- | | `validation_error` | A missing event name, `userId`, `newUserId`, or `groupId`, or a non-finite purchase `value` | | `queue_overflow` | The queue reached `maxQueueSize`. The oldest event was evicted. | -| `permanent_client_error` | A `4xx` other than `408` or `429` | -| `max_flush_attempts` | 10 failed flush cycles for one event | +| `permanent_client_error` | A final `4xx` (any `4xx` except `401`, `403`, `408`, `429`) at once; `401`/`403` after 10 minutes of refusals | +| `max_flush_attempts` | Temporary failures for longer than `maxRetryDuration` (default 1 hour). The name is kept from earlier versions. | | `close_timeout` | `close()` ran out of time | | `closed` | `track()` ran after `close()` | An exception thrown inside your hook is swallowed. A hook can never crash the SDK. +Every drop is also counted, with or without hooks. `getStats()` returns the counts since +the client was created, by reason, plus how many events are queued and in flight. Drops by +the queue cap, final answers and expired retries are logged as one summary line per flush +cycle, never one line per event. + +```javascript +const { dropped, droppedByReason, queued, inFlight } = datalyr.getStats(); +``` + ## Delivery, retries, and limits The SDK never batches. It sends one HTTP request per event, with up to 10 requests in @@ -430,11 +447,14 @@ flight at once. | HTTP concurrency | 10 requests in parallel, one event each | | Requests per event | One | | Retries per send | `retryLimit`, default 3 | -| Retry backoff | `min(2^n × 1000, 10000)` ms, multiplied by `0.5 + random()/2` | +| Retry backoff | `min(2^n × 1000, 10000)` ms, multiplied by `0.5 + random()/2`, and never shorter than the server's `Retry-After` | +| Backoff between failed cycles | `min(2^(n-1) × 1000, 60000)` ms, jittered, and never before `Retry-After` | +| `Retry-After` | Honoured on any answer, as seconds or an HTTP date, capped at 5 minutes | | Request timeout | `timeout`, default 10,000 ms, through `AbortController` | | Queue | `maxQueueSize`, default 1000. The oldest event is dropped first. | -| Failed flush cycles per event | 10, then the event is dropped | +| Retry window per event | `maxRetryDuration`, default 1 hour (10 minutes for `401`/`403`) | | Drain passes per flush | 12 | +| `flush()` budget | `flushTimeout`, default 30,000 ms | | `close()` budget | `closeTimeout`, default 30,000 ms | | `eventId` length | 256 characters | | Server-side dedupe window | 7 days | @@ -443,14 +463,16 @@ flight at once. | Response | Behavior | | --- | --- | -| `2xx` | Success. | -| `408`, `429`, any `5xx` | Retried with jittered exponential backoff, up to `retryLimit`. | -| `401`, `403` | Dropped. The SDK logs an authentication failure once. | -| Other `4xx` | Dropped immediately. Never retried. | -| Network, DNS, TLS, abort | Retried like a `5xx`. | - -An event that exhausts its retries returns to the front of the queue. After 10 failed -flush cycles the SDK drops it, so one bad event cannot block the queue. +| `2xx` | Success. A duplicate of an `eventId` the server already has is a `200` too. Never sent again. | +| `408`, `429`, any `5xx` (including `503`) | Kept. Retried with jittered exponential backoff, waiting at least `Retry-After` when the server sends it. | +| `401`, `403` | Kept and retried for 10 minutes, then dropped. The SDK logs an authentication failure once. | +| Other `4xx` (`400`, `413`, ...) | Final. Dropped immediately. Never retried. | +| Network, DNS, TLS, timeout | Kept. Retried like a `5xx`. | + +Every retry sends the same event, with the same `eventId`, so the server stores it once. +An event that exhausts its quick retries (`retryLimit`) returns to the front of the queue +and waits out its backoff. It is dropped only when its failures have lasted longer than +`maxRetryDuration`, when the queue cap evicts it, or when `close()` runs out of time. ## Attribution preservation diff --git a/package.json b/package.json index cb6ae58..1975ad3 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "scripts": { "build": "tsup src/index.ts --format cjs,esm --dts --clean", "dev": "tsup src/index.ts --format cjs,esm --dts --watch", - "test": "node tests/test.ts", + "test": "node tests/test.ts && node tests/retry.ts", "prepublishOnly": "npm run build" }, "files": [ diff --git a/src/index.ts b/src/index.ts index dad4725..f00e5b6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,8 +4,8 @@ import { randomUUID, createHash } from 'node:crypto'; export type DropReason = | 'validation_error' // track/identify/alias/group called with invalid args (9.D.4) | 'queue_overflow' // maxQueueSize reached; oldest evicted (NODE-5) - | 'permanent_client_error' // non-retryable 4xx (≠408/429), e.g. 401/403/400 (9.D.8) - | 'max_flush_attempts' // transient failures exceeded MAX_FLUSH_ATTEMPTS cycles (NODE-8) + | 'permanent_client_error' // a final 4xx (400, 413, ...) at once; 401/403 after AUTH_RETRY_WINDOW_MS (FX-047) + | 'max_flush_attempts' // temporary failures lasted longer than maxRetryDuration (FX-047; the name is kept for compatibility) | 'close_timeout' // still queued when close()'s closeTimeout budget expired (NODE-1) | 'closed'; // track() called after close() (9.D.3) @@ -22,6 +22,14 @@ export interface DatalyrConfig { * Must be >= worst-case retry time (sendEvent backoff is up to ~7s for 3 retries), * or close() drops events still mid-retry. */ closeTimeout?: number; + /** FX-047: max ms an explicit `await flush()` waits for sends and their retries. Default + * 30000. Events not delivered by then stay queued and are retried later; flush() resolves + * with `{ unsent }`. */ + flushTimeout?: number; + /** FX-047: how long (ms) an event that keeps failing with a temporary error (5xx, 503, + * 429, 408, timeout, network error) is kept and retried before it is dropped with reason + * `max_flush_attempts`. Default 3600000 (1 hour); at most 24 hours. */ + maxRetryDuration?: number; /** 9.D.7: called for every send failure (before any retry/requeue/drop decision), so you * can log/alert on delivery problems. Never throws into the SDK — exceptions are swallowed. */ onError?: (event: TrackEvent, error: Error) => void; @@ -68,6 +76,23 @@ export interface TrackOptions { externalIds?: Record; } +/** FX-047: what flush() and close() report. `unsent` = events queued or still in flight + * when the call returned (for close(), these are the events it gave up on). */ +export interface FlushResult { + unsent: number; +} + +/** FX-047: delivery counters, read with `getStats()`. Counts are since construction. */ +export interface DatalyrStats { + /** Events waiting in memory, including those waiting out a backoff. */ + queued: number; + /** Events taken by a send that has not settled yet. */ + inFlight: number; + /** Every event dropped so far, all reasons. */ + dropped: number; + droppedByReason: Record; +} + /** 9.D.6: the revenue payload for trackPurchase(). `value` is required and must be a finite * number (the server reads value ?? revenue ?? amount — value is the canonical field). */ export interface PurchaseProperties { @@ -93,12 +118,57 @@ function generateAnonymousId(): string { const SDK_VERSION = '1.3.4'; // keep in sync with package.json -// NODE-8: max FAILED flush-cycles before an event is dropped (DLQ-lite). Separate from — -// and more generous than — retryLimit (the per-send retry count): a brief outage spans a -// few flush cycles before recovering, so this must be high enough to survive that, while -// still preventing a permanently-failing "poison" event from cycling at the queue front -// forever. -const MAX_FLUSH_ATTEMPTS = 10; +// Hard cap on drain passes per flush (a producer that keeps enqueuing during a drain must +// not keep one flush running forever). +const MAX_DRAIN_PASSES = 12; + +// FX-047: what the ingest worker's answers mean (datalyr-v2 infra/cloudflare/ingest, +// handleServerTrack). 2xx = stored (or a duplicate of an id it already has). 400, 405, 413, +// 415 = this exact request can never succeed: final. 401/403 = a key a healthy lookup refused; +// final in principle, but a key check can fail for a moment, so they are kept for +// AUTH_RETRY_WINDOW_MS. 408, 429, every 5xx (503 + Retry-After is the worker's "my own fault, +// send it again"), a timeout or a network error = temporary: keep the event and retry. +const AUTH_RETRY_WINDOW_MS = 10 * 60_000; +// Backoff between failed cycles for one event: 1s, 2s, 4s ... capped at 60s, jittered. +const MAX_CYCLE_BACKOFF_MS = 60_000; +// A Retry-After longer than this is not waited out inside one send's quick retries; the event +// goes back to the queue and is not sent again before the time the server named. +const MAX_INLINE_WAIT_MS = 10_000; +// Never wait longer than this for one Retry-After, whatever the server says. +const MAX_RETRY_AFTER_MS = 5 * 60_000; + +const ALL_DROP_REASONS: DropReason[] = [ + 'validation_error', 'queue_overflow', 'permanent_client_error', 'max_flush_attempts', 'close_timeout', 'closed', +]; +// Reasons the periodic summary line reports. The others already log at the call +// (validation_error, closed) or in close()'s own line (close_timeout). +const SUMMARY_REASONS: DropReason[] = ['queue_overflow', 'permanent_client_error', 'max_flush_attempts']; + +/** Retry-After as milliseconds: delta-seconds or an HTTP date; undefined when absent or unreadable. */ +function parseRetryAfterMs(value: string | null | undefined): number | undefined { + if (!value) return undefined; + const v = value.trim(); + let ms: number; + if (/^\d+$/.test(v)) { + ms = Number(v) * 1000; + } else { + const at = Date.parse(v); + if (!Number.isFinite(at)) return undefined; + ms = at - Date.now(); + } + return Math.min(Math.max(0, ms), MAX_RETRY_AFTER_MS); +} + +/** A 4xx the server means as final (everything except 401/403, 408 and 429). */ +function isFinalStatus(status: number): boolean { + return status >= 400 && status < 500 && status !== 401 && status !== 403 && status !== 408 && status !== 429; +} + +interface RetryState { + firstFailedAt: number; + failures: number; + notBefore: number; +} // B-4: cap the caller-supplied eventId. Longer ids become pathological Redis keys server-side; // overflow is hash-collapsed (deterministic, so redeliveries still dedup) below. @@ -115,17 +185,21 @@ export class Datalyr { private retryLimit: number; private maxQueueSize: number; private closeTimeout: number; + private flushTimeout: number; + private maxRetryDuration: number; private timer?: NodeJS.Timeout; private isFlushing: boolean = false; private isClosing: boolean = false; private closeFinished = false; // close() has given up; a late transient failure is dropped, not re-queued (DLR-8) private currentFlush?: Promise; // the in-flight drain — callers/close() await this instead of getting a no-op (NODE-3/TR-25) - private closePromise?: Promise; // memoized so close() is idempotent under repeat/concurrent calls (9.D.3) + private closePromise?: Promise; // memoized so close() is idempotent under repeat/concurrent calls (9.D.3) private warnedNoId = false; // one-time warn for calls with neither userId nor anonymousId (NODE-6) - private warnedQueueFull = false; // one-time prod warn when the queue overflows (NODE-5) private warnedClosed = false; // one-time loud error for track() after close() (9.D.3) private warnedAuthFailure = false; // one-time loud error for 401/403 (9.D.8) - private flushAttempts = new WeakMap(); // failed-flush-cycle count per event (NODE-8); WeakMap → no payload pollution + private retryState = new WeakMap(); // FX-047: per-event retry clock; WeakMap → no payload pollution + private inFlight = 0; // FX-047: events taken from the queue by a pass and not settled yet + private droppedByReason: Record = Object.fromEntries(ALL_DROP_REASONS.map((r) => [r, 0])) as Record; + private reportedByReason: Record = Object.fromEntries(ALL_DROP_REASONS.map((r) => [r, 0])) as Record; private exitHook?: () => void; // the beforeExit listener (stored so close() can remove it — review M2) private onError?: (event: TrackEvent, error: Error) => void; // 9.D.7 private onDrop?: (events: TrackEvent[], reason: DropReason) => void; // 9.D.7 @@ -141,6 +215,8 @@ export class Datalyr { this.retryLimit = 3; this.maxQueueSize = 1000; this.closeTimeout = 30000; + this.flushTimeout = 30000; + this.maxRetryDuration = 3_600_000; } else { this.apiKey = config.apiKey; this.host = config.host || 'https://ingest.datalyr.com/track'; @@ -151,6 +227,8 @@ export class Datalyr { this.retryLimit = config.retryLimit ?? 3; this.maxQueueSize = config.maxQueueSize || 1000; this.closeTimeout = config.closeTimeout ?? 30000; + this.flushTimeout = config.flushTimeout ?? 30000; + this.maxRetryDuration = config.maxRetryDuration ?? 3_600_000; this.onError = typeof config.onError === 'function' ? config.onError : undefined; this.onDrop = typeof config.onDrop === 'function' ? config.onDrop : undefined; } @@ -176,6 +254,12 @@ export class Datalyr { if (this.flushInterval > 3_600_000) this.flushInterval = 3_600_000; if (!(this.closeTimeout >= 1000)) this.closeTimeout = 30000; if (this.closeTimeout > 120_000) this.closeTimeout = 120_000; + if (!(this.flushTimeout >= 1000)) this.flushTimeout = 30000; + if (this.flushTimeout > 120_000) this.flushTimeout = 120_000; + if (!(this.maxRetryDuration >= 60_000)) this.maxRetryDuration = this.maxRetryDuration < 60_000 ? 60_000 : 3_600_000; + // At most 24 h, well inside the server's dedup window (DEDUP_TTL_SECONDS, 7 days): a retry + // after it could store twice an event whose earlier attempt the server did accept. + if (this.maxRetryDuration > 86_400_000) this.maxRetryDuration = 86_400_000; // retryLimit: `?? 3` above preserves an explicit 0 (no retries); clamp negatives/NaN. if (!(this.retryLimit >= 0)) this.retryLimit = 3; if (this.retryLimit > 10) this.retryLimit = 10; @@ -197,7 +281,7 @@ export class Datalyr { this.exitHook = () => { if (this.isClosing || this.queue.length === 0) return; // beforeExit lets the loop run async work; best-effort (use close() for guarantees). - this.flush().catch(() => {}); + this.startDrain()?.catch(() => {}); }; process.once('beforeExit', this.exitHook); } @@ -205,6 +289,7 @@ export class Datalyr { // 9.D.7: fan a drop/error out to the caller's observability hook. A hook that throws must // never crash the SDK (the whole point is defensive delivery), so swallow its exceptions. private notifyDrop(events: TrackEvent[], reason: DropReason): void { + this.droppedByReason[reason] += events.length; // FX-047: every drop is counted, hook or not if (!this.onDrop) return; try { this.onDrop(events, reason); } catch { /* a hook must never break the SDK */ } } @@ -444,13 +529,9 @@ export class Datalyr { } private enqueue(event: TrackEvent): void { - // Check queue size limit to prevent memory issues. NODE-5: surface the drop in PROD - // (once) — it was debug-only, so silent data loss under sustained overload. + // Check queue size limit to prevent memory issues. NODE-5 / FX-047: every eviction is + // counted (getStats()) and reported as ONE summary line per flush cycle, never per event. if (this.queue.length >= this.maxQueueSize) { - if (!this.warnedQueueFull) { - this.warnedQueueFull = true; - console.warn(`[Datalyr] Queue full (${this.maxQueueSize}) — dropping oldest events. Increase maxQueueSize, or flush()/close() more often.`); - } const dropped = this.queue.shift(); // Remove oldest event // 9.D.7: overflow is a drop path — surface it so callers can persist to their own DLQ. if (dropped) this.notifyDrop([dropped], 'queue_overflow'); @@ -464,7 +545,7 @@ export class Datalyr { if (this.queue.length >= this.flushAt) { // Don't await to avoid blocking - this.flush().catch(err => { + this.startDrain()?.catch(err => { if (this.debug) { console.error('[Datalyr] Auto-flush error:', err); } @@ -472,51 +553,116 @@ export class Datalyr { } } - async flush(): Promise { - // NODE-3 / TR-25: if a drain is already running, AWAIT it (return the in-flight promise) - // rather than no-op'ing. Because the drain LOOPS until the queue empties, awaiting it now - // also guarantees events enqueued AFTER it started are sent — fixing the serverless - // `track(); track(); await flush(); return` bug where the second event stranded. - // DLR-8: this check must come BEFORE the empty-queue return. _flush() empties the queue - // as soon as a pass starts, so after an auto-flush (flushAt reached) took the events the - // queue is empty while their POSTs/retries are still running — returning early there let - // `await flush()` resolve with sends in flight (serverless freeze → silent loss). - if (this.isFlushing) { - return this.currentFlush ?? Promise.resolve(); + /** + * Send what is queued and wait, up to `flushTimeout` (default 30 s), for those sends and + * their quick retries. Resolves with `{ unsent }`: events still queued (for example waiting + * out a backoff or a Retry-After) or still in flight. Those are kept and retried later; they + * are not dropped. When anything is left unsent, one line says how many. + */ + async flush(): Promise { + // NODE-3 / TR-25 / DLR-8: startDrain() returns the drain already running (even when the + // queue is empty because an auto-flush took the events) instead of no-op'ing, and the + // drain loops so events enqueued meanwhile are sent too. + await this.drainWithin(this.flushTimeout); + this.reportDrops(); + const unsent = this.pendingCount(); + if (unsent > 0) { + console.warn(`[Datalyr] flush(): ${unsent} event(s) not delivered yet; kept in memory and retried later.`); } - if (this.queue.length === 0) return; + return { unsent }; + } + + /** FX-047: delivery counters. `dropped` and `droppedByReason` count since construction. */ + getStats(): DatalyrStats { + const droppedByReason = { ...this.droppedByReason }; + const dropped = ALL_DROP_REASONS.reduce((n, r) => n + droppedByReason[r], 0); + return { queued: this.queue.length, inFlight: this.inFlight, dropped, droppedByReason }; + } + private pendingCount(): number { + return this.queue.length + this.inFlight; + } + + private notBefore(event: TrackEvent): number { + return this.retryState.get(event)?.notBefore ?? 0; + } + + private hasReady(): boolean { + const now = Date.now(); + return this.queue.some((e) => this.notBefore(e) <= now); + } + + private earliestReadyAt(): number { + let earliest = Infinity; + for (const e of this.queue) earliest = Math.min(earliest, this.notBefore(e)); + return earliest; + } + + // The running drain, or a new one when an event is ready to send; undefined when nothing + // is running and nothing is ready. + private startDrain(): Promise | undefined { + if (this.isFlushing) return this.currentFlush; + if (!this.hasReady()) return undefined; this.isFlushing = true; - this.currentFlush = this._drain(); - try { - await this.currentFlush; - } finally { + this.currentFlush = this._drain().finally(() => { this.isFlushing = false; this.currentFlush = undefined; + }); + return this.currentFlush; + } + + // Wait for the drain, but never longer than `ms`. A drain still running when the bound + // expires keeps going in the background (it has its own catch), so the caller is bounded. + private async drainWithin(ms: number): Promise { + const drain = this.startDrain(); + if (!drain) return; + const budget = this.delay(ms); + try { + await Promise.race([drain.catch(() => {}), budget.promise]); + } finally { + budget.cancel(); } } - // TR-25: a single _flush pass snapshots the queue, so events enqueued during the pass — or - // failures it re-queues — would strand on `await flush()`. Loop passes until the queue is - // empty or a pass DELIVERS NOTHING (every event failed: a down endpoint re-queued/dropped - // them all). Progress must be measured by successful sends, NOT queue length — a pass that - // sends e1 while e2 arrives leaves the length unchanged yet clearly made progress. The - // zero-progress break stops us hot-spinning against a down endpoint (the flush timer / - // close() budget retries later); the hard cap is a belt-and-suspenders termination - // guarantee if a producer keeps enqueuing during the drain. + // FX-047: one line for the drops since the last report, never one per event. + private reportDrops(): void { + const parts: string[] = []; + let total = 0; + for (const r of SUMMARY_REASONS) { + const n = this.droppedByReason[r] - this.reportedByReason[r]; + if (n > 0) { parts.push(`${r}=${n}`); total += n; } + this.reportedByReason[r] = this.droppedByReason[r]; + } + if (total === 0) return; + const hint = this.droppedByReason.queue_overflow > 0 + ? ` Queue cap is ${this.maxQueueSize}: increase maxQueueSize, or flush() more often.` + : ''; + console.warn(`[Datalyr] ${total} event(s) dropped since the last report (${parts.join(', ')}); getStats() has the totals.${hint}`); + } + + // TR-25: a single _flush pass snapshots the ready events, so events enqueued during the + // pass would strand on `await flush()`. Loop passes until nothing is ready or a pass + // DELIVERS NOTHING (every event failed: a down endpoint). Progress is measured by + // successful sends, not queue length. A failed event waits out its backoff before it is + // ready again, so this never hot-spins; the hard cap guarantees termination when a + // producer keeps enqueuing during the drain. private async _drain(): Promise { - for (let pass = 0; this.queue.length > 0 && pass < MAX_FLUSH_ATTEMPTS + 2; pass++) { + for (let pass = 0; this.hasReady() && pass < MAX_DRAIN_PASSES; pass++) { const sent = await this._flush(); if (sent === 0) break; } } - // Returns the number of events SUCCESSFULLY sent this pass (events.length − failed), so - // _drain can tell real progress from a fully-failing endpoint (see _drain). + // Returns the number of events SUCCESSFULLY sent this pass, so _drain can tell real + // progress from a fully-failing endpoint. private async _flush(): Promise { - // Take all events from queue - const events = [...this.queue]; - this.queue = []; + // Take the events that are ready; leave those waiting out a backoff in the queue. + const now = Date.now(); + const events: TrackEvent[] = []; + const waiting: TrackEvent[] = []; + for (const e of this.queue) (this.notBefore(e) <= now ? events : waiting).push(e); + this.queue = waiting; + this.inFlight += events.length; if (this.debug) { console.log(`[Datalyr] Flushing ${events.length} events`); @@ -531,47 +677,13 @@ export class Datalyr { for (let i = 0; i < events.length; i += batchSize) { const batch = events.slice(i, i + batchSize); const promises = batch.map(event => - this.sendEvent(event).catch((err: any) => { - failed++; - // 9.D.7: every send failure reaches onError before any drop/requeue decision. - this.notifyError(event, err instanceof Error ? err : new Error(String(err))); - - // 9.D.8: a permanent client error (4xx ≠ 408/429 — bad key, malformed, forbidden) - // will NEVER succeed on retry, so drop it IMMEDIATELY instead of cycling it 10 - // times. A wrong API key (401/403) black-holes everything, so raise it loudly ONCE - // as an auth failure — the single most common "no data" support case. - if (err && err.permanent) { - if ((err.status === 401 || err.status === 403) && !this.warnedAuthFailure) { - this.warnedAuthFailure = true; - console.error(`[Datalyr] Authentication failing (HTTP ${err.status}) — check your API key ("dk_..."). Events are being dropped.`); - } - this.notifyDrop([event], 'permanent_client_error'); - return; - } - - // NODE-8 / NODE-9 / NODE-10: bound re-queue attempts so a permanently-failing - // (transient) event can't cycle at the front forever (re-failing every flush). - // Count failed flush-cycles per event (WeakMap, no payload pollution); drop with a - // VISIBLE warn after MAX_FLUSH_ATTEMPTS cycles. Re-queue at the front so failures - // retry first. - // DLR-8: a send still running when close()'s budget expired is not in the queue, - // so close() could not report it. If it now fails transiently, re-queueing would - // strand it on a closed client (no timer, no further drain) — never sent, never - // reported. Hand it to onDrop as close_timeout instead. - if (this.closeFinished) { - this.notifyDrop([event], 'close_timeout'); - return; - } - - const n = (this.flushAttempts.get(event) || 0) + 1; - this.flushAttempts.set(event, n); - if (n >= MAX_FLUSH_ATTEMPTS) { - console.warn(`[Datalyr] Dropping event after ${n} failed flush attempts: ${event.event}`); - this.notifyDrop([event], 'max_flush_attempts'); - } else { - this.queue.unshift(event); - } - }) + this.sendEvent(event) + .then(() => { this.retryState.delete(event); }) + .catch((err: any) => { + failed++; + this.handleFailure(event, err); + }) + .finally(() => { this.inFlight--; }) ); await Promise.allSettled(promises); } @@ -583,6 +695,58 @@ export class Datalyr { return events.length - failed; } + // FX-047: keep or drop one event whose send (with its quick retries) failed. The event + // object itself goes back to the queue, so every later attempt sends the SAME eventId. + private handleFailure(event: TrackEvent, err: any): void { + // 9.D.7: every send failure reaches onError before any drop/requeue decision. + this.notifyError(event, err instanceof Error ? err : new Error(String(err))); + + // A final 4xx (malformed, too large, wrong method) can never succeed: drop at once. + if (err && err.permanent) { + this.retryState.delete(event); + this.notifyDrop([event], 'permanent_client_error'); + return; + } + + // DLR-8: a send still running when close()'s budget expired is not in the queue, so + // close() could not report it. Re-queueing would strand it on a closed client. + if (this.closeFinished) { + this.retryState.delete(event); + this.notifyDrop([event], 'close_timeout'); + return; + } + + const now = Date.now(); + const state = this.retryState.get(event) ?? { firstFailedAt: now, failures: 0, notBefore: 0 }; + state.failures++; + + if (err && err.auth) { + // 9.D.8: a wrong key black-holes everything; say so loudly, once. + if (!this.warnedAuthFailure) { + this.warnedAuthFailure = true; + console.error(`[Datalyr] Authentication failing (HTTP ${err.status}) — check your API key ("dk_..."). Events are kept and retried for ${AUTH_RETRY_WINDOW_MS / 60_000} minutes, then dropped.`); + } + if (now - state.firstFailedAt >= Math.min(AUTH_RETRY_WINDOW_MS, this.maxRetryDuration)) { + this.retryState.delete(event); + this.notifyDrop([event], 'permanent_client_error'); + return; + } + } else if (now - state.firstFailedAt >= this.maxRetryDuration) { + this.retryState.delete(event); + this.notifyDrop([event], 'max_flush_attempts'); + return; + } + + // Back off before this event is sent again: 1s, 2s, 4s ... 60s with jitter, and never + // before the time a Retry-After named. + const backoff = Math.min(1000 * Math.pow(2, state.failures - 1), MAX_CYCLE_BACKOFF_MS) * (0.5 + Math.random() * 0.5); + const retryAfter = typeof err?.retryAfterMs === 'number' ? err.retryAfterMs : 0; + state.notBefore = now + Math.max(backoff, retryAfter); + this.retryState.set(event, state); + // Back at the front so the oldest failures go first. + this.queue.unshift(event); + } + private async sendEvent(event: TrackEvent, retryCount = 0): Promise { try { const controller = new AbortController(); @@ -609,21 +773,28 @@ export class Datalyr { } catch { // Ignore body read errors } - - // 9.D.8: 408 (Request Timeout) and 429 (Too Many Requests) are TRANSIENT — retry - // them like 5xx. Every other 4xx is a permanent client error: tag it so the flush - // layer drops it immediately instead of cycling it MAX_FLUSH_ATTEMPTS times. - if (response.status !== 408 && response.status !== 429 && - response.status >= 400 && response.status < 500) { - const err: any = new Error(`Client error: ${response.status} ${response.statusText} - ${errorText}`); - err.status = response.status; + const status = response.status; + let retryAfter: string | null | undefined; + try { retryAfter = response.headers?.get?.('Retry-After'); } catch { retryAfter = undefined; } + + // A final 4xx: never retried. + if (isFinalStatus(status)) { + const err: any = new Error(`Client error: ${status} ${response.statusText} - ${errorText}`); + err.status = status; err.permanent = true; throw err; } - - // Retry on 5xx / 408 / 429 (transient) - const err: any = new Error(`Server error: ${response.status} ${response.statusText} - ${errorText}`); - err.status = response.status; + // 401/403: no quick retries; the flush layer keeps the event for AUTH_RETRY_WINDOW_MS. + if (status === 401 || status === 403) { + const err: any = new Error(`Authentication error: ${status} ${response.statusText} - ${errorText}`); + err.status = status; + err.auth = true; + throw err; + } + // 408 / 429 / 5xx: temporary. + const err: any = new Error(`Server error: ${status} ${response.statusText} - ${errorText}`); + err.status = status; + err.retryAfterMs = parseRetryAfterMs(retryAfter); throw err; } @@ -637,24 +808,28 @@ export class Datalyr { } } } catch (error: any) { - // Don't retry permanent client errors (bad key/forbidden/malformed). - if (error && error.permanent) { + // Final answers and auth failures are decided by the flush layer, not retried here. + if (error && (error.permanent || error.auth)) { if (this.debug) { - console.error('[Datalyr] Permanent error, not retrying:', error.message); + console.error('[Datalyr] Not retrying now:', error.message); } throw error; } - // Retry server errors / network failures with exponential backoff + // Temporary (5xx / 408 / 429 / timeout / network): quick retries with backoff. if (retryCount < this.retryLimit) { + const retryAfterMs: number | undefined = error?.retryAfterMs; + // A Retry-After too long to wait out here: hand the event back to the queue, which + // will not send it before that time. + if (retryAfterMs !== undefined && retryAfterMs > MAX_INLINE_WAIT_MS) throw error; if (this.debug) { console.log(`[Datalyr] Retrying event (attempt ${retryCount + 1}/${this.retryLimit})`); } // NODE-8: full jitter so many SDK instances don't retry in lockstep against a - // recovering server. + // recovering server; FX-047: never sooner than the server's Retry-After. const backoffMs = Math.min(Math.pow(2, retryCount) * 1000, 10000); // Max 10s const jittered = backoffMs * (0.5 + Math.random() * 0.5); - await new Promise(resolve => setTimeout(resolve, jittered)); + await new Promise(resolve => setTimeout(resolve, Math.max(jittered, retryAfterMs ?? 0))); return this.sendEvent(event, retryCount + 1); } @@ -665,7 +840,8 @@ export class Datalyr { private startFlushTimer(): void { this.timer = setInterval(() => { if (!this.isClosing) { - this.flush().catch(err => { + this.reportDrops(); + this.startDrain()?.catch(err => { if (this.debug) { console.error('[Datalyr] Timer flush error:', err); } @@ -699,8 +875,13 @@ export class Datalyr { return { promise, cancel: () => { if (timer) clearTimeout(timer); } }; } - // Cleanup - async close(): Promise { + /** + * Stop the timer and drain, waiting for sends, their retries and any backoff, up to + * `closeTimeout`. Terminal and idempotent. Resolves with `{ unsent }`: the events it gave + * up on (queued ones go to onDrop('close_timeout') now; ones still in flight are delivered + * or reach onDrop when their send settles). + */ + async close(): Promise { // 9.D.3: idempotent — repeat or concurrent close() calls share ONE drain and never // restart it (a second close() must not re-run the loop or double-remove the exit hook). if (this.closePromise) return this.closePromise; @@ -708,7 +889,7 @@ export class Datalyr { return this.closePromise; } - private async _close(): Promise { + private async _close(): Promise { this.isClosing = true; if (this.timer) { @@ -734,25 +915,18 @@ export class Datalyr { // after close() resolved (proven: close resolved 14ms, process exited 8016ms). // // DLR-8: also loop while a drain is in flight with an EMPTY queue (an auto-flush already - // took the events). flush() returns that drain, so close() waits for its sends — and + // took the events). startDrain() returns that drain, so close() waits for its sends — and // their onDrop/onError — instead of resolving at ~0ms. const start = Date.now(); const deadline = start + this.closeTimeout; while ((this.queue.length > 0 || this.isFlushing) && Date.now() < deadline) { - const remaining = deadline - Date.now(); - const budget = this.delay(remaining); - try { - await Promise.race([ - this.flush().catch(() => {}), - budget.promise, - ]); - } finally { - budget.cancel(); - } - // If events remain (failed + re-queued) and no flush is in flight, pause briefly so - // we don't hot-loop against a still-failing endpoint (bounded by the deadline). + await this.drainWithin(deadline - Date.now()); + // FX-047: events remain but none is ready (each is waiting out its backoff or a + // Retry-After) and nothing is in flight: wait until the first is ready, bounded by the + // deadline, instead of hot-looping or sending early. if (this.queue.length > 0 && !this.isFlushing && Date.now() < deadline) { - const pause = this.delay(Math.min(100, Math.max(0, deadline - Date.now()))); + const until = Math.max(this.earliestReadyAt(), Date.now() + 10); + const pause = this.delay(Math.max(0, Math.min(until, deadline) - Date.now())); try { await pause.promise; } finally { @@ -769,13 +943,19 @@ export class Datalyr { this.exitHook = undefined; } + this.reportDrops(); + const unsent = this.pendingCount(); + if (unsent > 0) { + console.warn(`[Datalyr] close(): ${unsent} event(s) undelivered after ~${Date.now() - start}ms (budget ${this.closeTimeout}ms): ${this.queue.length} queued, ${this.inFlight} still in flight.`); + } if (this.queue.length > 0) { const undelivered = [...this.queue]; - console.warn(`[Datalyr] close(): ${undelivered.length} event(s) undelivered after ~${Date.now() - start}ms (budget ${this.closeTimeout}ms).`); + this.queue = []; // 9.D.7: hand the survivors to onDrop so callers can persist them (their durability is // now the caller's — close() has given up on them). this.notifyDrop(undelivered, 'close_timeout'); } + return { unsent }; } } diff --git a/tests/retry.ts b/tests/retry.ts new file mode 100644 index 0000000..1dd5eeb --- /dev/null +++ b/tests/retry.ts @@ -0,0 +1,243 @@ +// FX-047 piece 1: keep events on temporary failures, honour Retry-After, count what the +// queue cap drops, and bound flush()/close(). Mocks global fetch (no real network) and +// moves Date.now forward instead of sleeping through backoff. Run with: node tests/retry.ts +// +// What the ingest worker answers on POST /track (datalyr-v2 infra/cloudflare/ingest/index.js +// handleServerTrack, main ef756fd42, pinned by infra/cloudflare/tests/ingest-answer-contract.test.js): +// 200 stored, or a duplicate of an event id it already has (success:false) +// 400 / 405 / 413 malformed body, missing event name or identity, wrong method, too large: final +// 401 no key, over-long key, or a key a healthy lookup refused: final +// 429 + Retry-After: 1 over 1,000 requests a second for one key: try again +// 500 queue outage or unexpected error (the dedup claim is released): try again +// 503 + Retry-After: 5 its own database failed while checking the key (INGEST_OWN_FAULT_503 on) +import { Datalyr } from '../src/index.ts'; + +let failures = 0; +function assert(cond: boolean, msg: string): void { + if (cond) { console.log('PASS ' + msg); } + else { failures++; console.error('FAIL ' + msg); } +} + +// Move the SDK's clock without waiting. Timers (setTimeout) still run on real time. +const realNow = Date.now; +let clockOffset = 0; +Date.now = () => realNow() + clockOffset; +const advance = (ms: number) => { clockOffset += ms; }; + +const KEY = 'dk_test_not_a_real_key'; +const base = { apiKey: KEY, flushAt: 100, flushInterval: 3_600_000 }; + +function answer(status: number, headers: Record = {}) { + return { + ok: status >= 200 && status < 300, status, statusText: String(status), + headers: new Headers(headers), text: async () => '', json: async () => ({}), + }; +} + +// Resolve a promise or give up after `ms` (the pre-fix flush() could hang forever). +async function within(p: Promise, ms: number): Promise<{ done: boolean; value?: T }> { + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise<{ done: boolean }>((r) => { timer = setTimeout(() => r({ done: false }), ms); }); + try { + return await Promise.race([p.then((value) => ({ done: true, value })), timeout]); + } finally { if (timer) clearTimeout(timer); } +} + +async function main() { + // ---- A long outage of every temporary kind loses nothing; every attempt carries the SAME id ---- + { + const bodies: any[] = []; + let calls = 0, accepted = 0; + const kinds = ['503', '500', '429', 'timeout', 'network', '502']; + const failingCalls = 14; // more than the 10 flush cycles after which 1.3.4 deleted the event + (globalThis as any).fetch = async (_u: string, opts: any) => { + bodies.push(JSON.parse(opts.body)); + const kind = calls < failingCalls ? kinds[calls % kinds.length] : 'ok'; + calls++; + if (kind === 'ok') { accepted++; return answer(200); } + if (kind === '503') return answer(503, { 'Retry-After': '5' }); + if (kind === '429') return answer(429, { 'Retry-After': '1' }); + if (kind === 'timeout') { + // Wait for the SDK's own abort, the way a real fetch fails on a timeout. + return await new Promise((_res, rej) => opts.signal.addEventListener('abort', () => { + rej(Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })); + })); + } + if (kind === 'network') throw new TypeError('fetch failed'); + return answer(Number(kind)); + }; + const drops: string[] = []; + const dl = new Datalyr({ ...base, retryLimit: 0, timeout: 1000, onDrop: (_e, r) => drops.push(r) }); + await dl.track({ userId: 'u', event: 'purchase', properties: { value: 10 } }); + // One flush a simulated minute: a 15-minute outage, far past the old 10-cycle cut-off. + for (let i = 0; i <= failingCalls; i++) { + await dl.flush(); + advance(61_000); + } + assert(accepted === 1, `outage: the event is delivered once the server recovers (accepted ${accepted}, attempts ${calls})`); + assert(drops.length === 0, `outage: nothing dropped during a 503/500/429/timeout/network/502 outage (got ${JSON.stringify(drops)})`); + const ids = new Set(bodies.map((b) => b.eventId)); + assert(bodies.length === failingCalls + 1 && ids.size === 1, + `outage: all ${bodies.length} attempts carry the SAME event id (distinct ids: ${ids.size})`); + // After a 2xx the event is gone: more flushes send nothing. + const before = calls; + await dl.flush(); advance(61_000); await dl.flush(); + assert(calls === before, `outage: an accepted event is never sent again (calls ${before} -> ${calls})`); + await dl.close(); + } + + // ---- A short Retry-After is honoured before the next quick retry; same id ---- + { + const stamps: number[] = []; + const ids: string[] = []; + (globalThis as any).fetch = async (_u: string, opts: any) => { + stamps.push(realNow()); + ids.push(JSON.parse(opts.body).eventId); + return stamps.length === 1 ? answer(503, { 'Retry-After': '2' }) : answer(200); + }; + const dl = new Datalyr({ ...base, retryLimit: 1 }); + await dl.track({ userId: 'u', event: 'retry_after_short' }); + await dl.flush(); + const gap = stamps.length >= 2 ? stamps[1] - stamps[0] : -1; + assert(stamps.length === 2 && gap >= 1950, + `Retry-After: 2 waits at least 2 s before the retry (gap ${gap} ms; 1.3.4 waited 0.5-1 s)`); + assert(ids.length === 2 && ids[0] === ids[1], 'Retry-After: the retry carries the same event id'); + await dl.close(); + } + + // ---- Retry-After as an HTTP date is honoured too ---- + { + const stamps: number[] = []; + (globalThis as any).fetch = async () => { + stamps.push(realNow()); + return stamps.length === 1 + ? answer(503, { 'Retry-After': new Date(Date.now() + 3000).toUTCString() }) + : answer(200); + }; + const dl = new Datalyr({ ...base, retryLimit: 1 }); + await dl.track({ userId: 'u', event: 'retry_after_date' }); + await dl.flush(); + const gap = stamps.length >= 2 ? stamps[1] - stamps[0] : -1; + assert(stamps.length === 2 && gap >= 1950, `Retry-After as an HTTP date (3 s ahead) is waited out (gap ${gap} ms)`); + await dl.close(); + } + + // ---- A long Retry-After is not retried early; the event is kept, then sent ---- + { + let calls = 0, accepted = 0; + (globalThis as any).fetch = async () => { + calls++; + if (calls === 1) return answer(429, { 'Retry-After': '120' }); + accepted++; + return answer(200); + }; + const dl = new Datalyr({ ...base, retryLimit: 3 }); + await dl.track({ userId: 'u', event: 'retry_after_long' }); + const r1: any = await dl.flush(); + assert(calls === 1, `Retry-After: 120 is not retried inside the same flush (attempts ${calls}; 1.3.4 made 4)`); + assert(r1 && r1.unsent === 1, `Retry-After: flush() says 1 event is left unsent (got ${JSON.stringify(r1)})`); + advance(60_000); + await dl.flush(); + assert(calls === 1, `Retry-After: still not retried 60 s later (attempts ${calls})`); + advance(61_000); + const r2: any = await dl.flush(); + assert(accepted === 1 && r2 && r2.unsent === 0, `Retry-After: sent once the 120 s pass (accepted ${accepted}, ${JSON.stringify(r2)})`); + await dl.close(); + } + + // ---- 401/403 are kept for 10 minutes (a key check can fail for a moment), then dropped ---- + { + let calls = 0; + (globalThis as any).fetch = async () => { calls++; return answer(401); }; + const drops: string[] = []; + const dl = new Datalyr({ ...base, retryLimit: 3, onDrop: (_e, r) => drops.push(r) }); + await dl.track({ userId: 'u', event: 'auth_blip' }); + await dl.flush(); + assert(calls === 1 && drops.length === 0, `401: sent once per cycle and kept, not dropped (attempts ${calls}, drops ${JSON.stringify(drops)})`); + advance(5 * 60_000); + await dl.flush(); + assert(calls === 2 && drops.length === 0, `401: still kept after 5 minutes (attempts ${calls}, drops ${JSON.stringify(drops)})`); + advance(6 * 60_000); + await dl.flush(); + assert(drops.length === 1 && drops[0] === 'permanent_client_error', + `401: dropped as permanent_client_error once 10 minutes have passed (drops ${JSON.stringify(drops)})`); + assert((dl as any).getStats?.().droppedByReason?.permanent_client_error === 1, '401: the drop is counted'); + await dl.close(); + + // A 403 that clears: delivered with the same id. + const ids: string[] = []; + (globalThis as any).fetch = async (_u: string, opts: any) => { + ids.push(JSON.parse(opts.body).eventId); + return ids.length === 1 ? answer(403) : answer(200); + }; + const drops2: string[] = []; + const dl2 = new Datalyr({ ...base, onDrop: (_e, r) => drops2.push(r) }); + await dl2.track({ userId: 'u', event: 'auth_recovers' }); + await dl2.flush(); + advance(61_000); + await dl2.flush(); + assert(ids.length === 2 && ids[0] === ids[1] && drops2.length === 0, + `403 then 200: delivered on the retry with the same id, nothing dropped (attempts ${ids.length})`); + await dl2.close(); + } + + // ---- Final answers drop at once: 400 and 413 are sent once and never again ---- + { + for (const status of [400, 413]) { + let calls = 0; + (globalThis as any).fetch = async () => { calls++; return answer(status); }; + const drops: string[] = []; + const dl = new Datalyr({ ...base, retryLimit: 3, onDrop: (_e, r) => drops.push(r) }); + await dl.track({ userId: 'u', event: 'final_' + status }); + await dl.flush(); + advance(61_000); + await dl.flush(); + assert(calls === 1 && drops.length === 1 && drops[0] === 'permanent_client_error', + `${status}: final, sent once and dropped as permanent_client_error (attempts ${calls}, drops ${JSON.stringify(drops)})`); + await dl.close(); + } + } + + // ---- The queue cap: drops are counted, readable, and logged as ONE summary line ---- + { + (globalThis as any).fetch = () => new Promise(() => {}); // a send that never settles + const warnings: string[] = []; + const realWarn = console.warn; + console.warn = (...args: any[]) => { warnings.push(args.join(' ')); }; + const dl = new Datalyr({ ...base, maxQueueSize: 100, timeout: 1000, flushTimeout: 1000, closeTimeout: 1000 } as any); + try { + // The first 100 are taken by the auto-flush (stuck in flight); 260 more refill a 100 cap. + for (let i = 0; i < 360; i++) void dl.track({ userId: 'u', event: 'e' + i }); + const t0 = realNow(); + const res = await within(dl.flush() as Promise, 4000); + const elapsed = realNow() - t0; + assert(res.done && elapsed < 2500, `flush() returns within flushTimeout while sends hang (${res.done ? elapsed + ' ms' : 'did not return in 4 s'})`); + assert(res.done && res.value && res.value.unsent === 200, + `flush() says how many are unsent: 100 queued + 100 in flight (got ${JSON.stringify(res.value)})`); + const stats = (dl as any).getStats?.(); + assert(!!stats && stats.droppedByReason.queue_overflow === 160 && stats.dropped === 160, + `getStats() counts the 160 events the cap dropped (got ${JSON.stringify(stats)})`); + assert(!!stats && stats.queued === 100 && stats.inFlight === 100, + `getStats() shows 100 queued and 100 in flight (got ${stats && JSON.stringify({ q: stats.queued, f: stats.inFlight })})`); + const capLines = warnings.filter((w) => /queue/i.test(w) && /dropped/i.test(w)); + assert(capLines.length === 1 && capLines[0].includes('160'), + `one summary line for the cap, with the count, never one per event (got ${JSON.stringify(capLines)})`); + // Nothing new dropped: the next report says nothing. + await within(dl.flush() as Promise, 4000); + assert(warnings.filter((w) => /queue/i.test(w) && /dropped/i.test(w)).length === 1, + 'the summary line is not repeated when nothing new was dropped'); + + // close() is bounded too and says how many it could not send. + const c = await within(dl.close() as Promise, 4000); + assert(c.done && c.value && c.value.unsent === 200, + `close() returns within closeTimeout and says 200 left unsent (got ${JSON.stringify(c.value)})`); + } finally { + console.warn = realWarn; + } + } + + console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILED`); + process.exit(failures === 0 ? 0 : 1); +} + +main().catch((e) => { console.error('test harness threw:', e); process.exit(1); }); diff --git a/tests/test.ts b/tests/test.ts index d594f16..669a2e9 100644 --- a/tests/test.ts +++ b/tests/test.ts @@ -169,7 +169,9 @@ async function main() { '9.D.3: pre-close event delivered; post-close event dropped (not sent)'); assert(drops93.includes('closed'), "9.D.3: post-close track() fires onDrop('closed')"); - // ---- 9.D.8: permanent 401 → sent ONCE, immediate drop, no 10-cycle requeue ---- + // ---- 9.D.8 / FX-047: 401 → no quick retries, logged once, kept (not dropped at once) ---- + // FX-047 changed this: a 401 is kept and retried for 10 minutes (tests/retry.ts covers the + // window and the final drop), because a key check can fail for a moment. let calls401 = 0; const drops401: string[] = []; // Count only THIS test's event — an earlier bounded-close test (dl4) may still be running a // best-effort background flush against the shared global fetch; filtering keeps the count clean. @@ -180,10 +182,11 @@ async function main() { const dl401 = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000, retryLimit: 3, closeTimeout: 2000, onDrop: (_e, r) => drops401.push(r) }); await dl401.track({ userId: 'u', event: 'bad_key' }); await dl401.flush(); - assert(calls401 === 1, `9.D.8: permanent 401 sent exactly ONCE — no retry, no requeue (got ${calls401}; retry would be 4)`); - assert(drops401.includes('permanent_client_error'), "9.D.8: 401 fires onDrop('permanent_client_error')"); + assert(calls401 === 1, `9.D.8: 401 sent ONCE per flush — no quick retries (got ${calls401}; quick retries would be 4)`); + assert(drops401.length === 0, `FX-047: a 401 is kept, not dropped at once (got ${JSON.stringify(drops401)})`); await dl401.close(); - assert(calls401 === 1, `9.D.8: 401 event not re-queued across close() either — still ${calls401} POST`); + assert(drops401.length === 1 && drops401[0] === 'close_timeout', + `FX-047: close() gives the still-refused event to onDrop('close_timeout') (got ${JSON.stringify(drops401)})`); // ---- 9.D.8: 429 is TRANSIENT (retried like 5xx), NOT permanent ---- let calls429 = 0; From f70ea21df36e04590205a13956033435150d1d4d Mon Sep 17 00:00:00 2001 From: czy Date: Sat, 21 Nov 2026 12:28:50 -0600 Subject: [PATCH 2/2] FX-047 review fixes: cap counts in-flight and re-queued events, 401/403 final, jitter on Retry-After - maxQueueSize now bounds queued + in flight; a re-queued failure counts against it and the oldest queued event is evicted as queue_overflow (counted). Queue kept in arrival order. - 401/403 are final again (the server answers 503 for its own faults), counted as the new drop reason auth_refused and in the summary line. - Retry-After waits get up to 20% jitter, between cycles and in the quick retries. - Tests: steady sender through a 30-minute outage never exceeds the cap; drop after maxRetryDuration; malformed Retry-After; close() waits out a backoff. - eventId doc comment: 7-day dedup window. Changelog: ships as 1.4.0 (flush/close return type). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 34 +++++++--- README.md | 15 +++-- src/index.ts | 113 +++++++++++++++++--------------- tests/retry.ts | 170 ++++++++++++++++++++++++++++++++++++------------- tests/test.ts | 11 ++-- 5 files changed, 226 insertions(+), 117 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 53b1735..d1d72c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +Release as **1.4.0**, not a patch: `flush()` and `close()` now resolve with `{ unsent }` +instead of `void` (see Changed). + ### Fixed - **Events were deleted during a server outage.** An event that failed with a temporary error (`5xx`, `503`, `429`, `408`, a timeout or a network error) was dropped after 10 @@ -12,19 +15,34 @@ All notable changes to this project will be documented in this file. cycles. Every retry carries the same `eventId`, and an event the server accepted (`2xx`) is never sent again. - **`Retry-After` was ignored.** The server answers `503` and `429` with `Retry-After`; the - SDK now waits at least that long (seconds or an HTTP date, capped at 5 minutes). -- **`401`/`403` deleted events at once.** A key check that fails for a moment now costs - nothing: the event is kept and retried for 10 minutes, then dropped as - `permanent_client_error`. Other `4xx` answers (`400`, `413`, ...) are still final. + SDK now waits at least that long plus up to 20% jitter (seconds or an HTTP date, capped at + 5 minutes), so clients do not all retry at the same instant. - **`flush()` had no time bound** and could wait through every retry of every event. It now waits at most `flushTimeout` (new, default 30 s). +### Changed +- **Breaking for typed code:** `flush()` and `close()` return `Promise` + (`{ unsent: number }`) instead of `Promise`. Code that ignores the value is + unaffected; a subclass that overrides `flush(): Promise` or code annotated to + expect `Promise` from them no longer type-checks. +- `maxQueueSize` now counts queued plus in-flight events, including those waiting to be + retried, so memory stays bounded through an outage. When every held event is in flight, + a new event is the one dropped (`queue_overflow`). +- `401`/`403` are still final, but reach `onDrop` with the new reason `auth_refused` + instead of `permanent_client_error`. +- `max_flush_attempts` now means "temporary failures lasted longer than + `maxRetryDuration`", not "10 failed flush cycles". +- Log lines: + - removed: `Queue full (N) — dropping oldest events. ...` (once, on first overflow) + - removed: `Dropping event after N failed flush attempts: ` (once per event) + - added: `N event(s) dropped since the last report (=, ...); getStats() has the totals.` (at most once per flush cycle) + - added: `flush(): N event(s) not delivered yet; kept in memory and retried later.` + - changed: `close(): N event(s) undelivered after ~Xms (budget Yms)` now ends with `: Q queued, F still in flight.` and counts in-flight events + ### Added - `getStats()`: queued, in-flight and dropped counts, by drop reason. -- `flush()` and `close()` resolve with `{ unsent }`, the number of events not delivered when - they returned, and log one line when it is above zero. -- Drops (queue cap, final answers, expired retries) are logged as one summary line per flush - cycle instead of a first-overflow warning and a line per expired event. +- `flushTimeout` and `maxRetryDuration` options. +- Drop reason `auth_refused`. ## [1.3.4] - 2026-11-14 diff --git a/README.md b/README.md index a52613c..dc99fbc 100644 --- a/README.md +++ b/README.md @@ -418,8 +418,9 @@ const datalyr = new Datalyr({ | `reason` | Cause | | --- | --- | | `validation_error` | A missing event name, `userId`, `newUserId`, or `groupId`, or a non-finite purchase `value` | -| `queue_overflow` | The queue reached `maxQueueSize`. The oldest event was evicted. | -| `permanent_client_error` | A final `4xx` (any `4xx` except `401`, `403`, `408`, `429`) at once; `401`/`403` after 10 minutes of refusals | +| `queue_overflow` | Queued plus in-flight events reached `maxQueueSize`. The oldest queued event was evicted, or the new one when every held event was in flight. | +| `permanent_client_error` | A final `4xx` other than `401`/`403` (`400`, `413`, ...) | +| `auth_refused` | `401` or `403`: the API key was refused | | `max_flush_attempts` | Temporary failures for longer than `maxRetryDuration` (default 1 hour). The name is kept from earlier versions. | | `close_timeout` | `close()` ran out of time | | `closed` | `track()` ran after `close()` | @@ -451,8 +452,8 @@ flight at once. | Backoff between failed cycles | `min(2^(n-1) × 1000, 60000)` ms, jittered, and never before `Retry-After` | | `Retry-After` | Honoured on any answer, as seconds or an HTTP date, capped at 5 minutes | | Request timeout | `timeout`, default 10,000 ms, through `AbortController` | -| Queue | `maxQueueSize`, default 1000. The oldest event is dropped first. | -| Retry window per event | `maxRetryDuration`, default 1 hour (10 minutes for `401`/`403`) | +| Queue | `maxQueueSize`, default 1000, counting queued plus in-flight events, including events waiting to be retried. The oldest queued event is dropped first. | +| Retry window per event | `maxRetryDuration`, default 1 hour | | Drain passes per flush | 12 | | `flush()` budget | `flushTimeout`, default 30,000 ms | | `close()` budget | `closeTimeout`, default 30,000 ms | @@ -464,9 +465,9 @@ flight at once. | Response | Behavior | | --- | --- | | `2xx` | Success. A duplicate of an `eventId` the server already has is a `200` too. Never sent again. | -| `408`, `429`, any `5xx` (including `503`) | Kept. Retried with jittered exponential backoff, waiting at least `Retry-After` when the server sends it. | -| `401`, `403` | Kept and retried for 10 minutes, then dropped. The SDK logs an authentication failure once. | -| Other `4xx` (`400`, `413`, ...) | Final. Dropped immediately. Never retried. | +| `408`, `429`, any `5xx` (including `503`) | Kept. Retried with jittered exponential backoff, waiting at least `Retry-After` (plus up to 20% jitter) when the server sends it. | +| `401`, `403` | Final. Dropped as `auth_refused`. The SDK logs an authentication failure once. | +| Other `4xx` (`400`, `413`, ...) | Final. Dropped immediately as `permanent_client_error`. Never retried. | | Network, DNS, TLS, timeout | Kept. Retried like a `5xx`. | Every retry sends the same event, with the same `eventId`, so the server stores it once. diff --git a/src/index.ts b/src/index.ts index f00e5b6..2cfcac6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,8 +3,9 @@ import { randomUUID, createHash } from 'node:crypto'; /** Why an event was dropped, passed to the onDrop hook (9.D.7). */ export type DropReason = | 'validation_error' // track/identify/alias/group called with invalid args (9.D.4) - | 'queue_overflow' // maxQueueSize reached; oldest evicted (NODE-5) - | 'permanent_client_error' // a final 4xx (400, 413, ...) at once; 401/403 after AUTH_RETRY_WINDOW_MS (FX-047) + | 'queue_overflow' // queued + in flight reached maxQueueSize; oldest queued evicted (NODE-5, FX-047) + | 'permanent_client_error' // a final 4xx other than 401/403 (400, 413, ...), dropped at once + | 'auth_refused' // 401/403: the key was refused (final; counted apart from other 4xx, FX-047) | 'max_flush_attempts' // temporary failures lasted longer than maxRetryDuration (FX-047; the name is kept for compatibility) | 'close_timeout' // still queued when close()'s closeTimeout budget expired (NODE-1) | 'closed'; // track() called after close() (9.D.3) @@ -55,7 +56,7 @@ export interface TrackOptions { anonymousId?: string; event: string; properties?: Record; - /** Idempotency key for this event. The ingest server de-duplicates on it (6h window), + /** Idempotency key for this event. The ingest server de-duplicates on it (7-day window), * so pass a stable id from your source system — e.g. the Stripe webhook `event.id` — * and at-least-once webhook redeliveries won't double-count. Must be a non-empty * string; anything else is ignored (a random UUID is generated, as when omitted). */ @@ -124,11 +125,10 @@ const MAX_DRAIN_PASSES = 12; // FX-047: what the ingest worker's answers mean (datalyr-v2 infra/cloudflare/ingest, // handleServerTrack). 2xx = stored (or a duplicate of an id it already has). 400, 405, 413, -// 415 = this exact request can never succeed: final. 401/403 = a key a healthy lookup refused; -// final in principle, but a key check can fail for a moment, so they are kept for -// AUTH_RETRY_WINDOW_MS. 408, 429, every 5xx (503 + Retry-After is the worker's "my own fault, -// send it again"), a timeout or a network error = temporary: keep the event and retry. -const AUTH_RETRY_WINDOW_MS = 10 * 60_000; +// 415 = this exact request can never succeed: final. 401/403 = a key a healthy lookup refused: +// final too, because the worker answers 503 (not 401) when its own key check fails +// (INGEST_OWN_FAULT_503). 408, 429, every 5xx (503 + Retry-After is the worker's "my own +// fault, send it again"), a timeout or a network error = temporary: keep the event and retry. // Backoff between failed cycles for one event: 1s, 2s, 4s ... capped at 60s, jittered. const MAX_CYCLE_BACKOFF_MS = 60_000; // A Retry-After longer than this is not waited out inside one send's quick retries; the event @@ -138,11 +138,16 @@ const MAX_INLINE_WAIT_MS = 10_000; const MAX_RETRY_AFTER_MS = 5 * 60_000; const ALL_DROP_REASONS: DropReason[] = [ - 'validation_error', 'queue_overflow', 'permanent_client_error', 'max_flush_attempts', 'close_timeout', 'closed', + 'validation_error', 'queue_overflow', 'permanent_client_error', 'auth_refused', 'max_flush_attempts', 'close_timeout', 'closed', ]; // Reasons the periodic summary line reports. The others already log at the call // (validation_error, closed) or in close()'s own line (close_timeout). -const SUMMARY_REASONS: DropReason[] = ['queue_overflow', 'permanent_client_error', 'max_flush_attempts']; +const SUMMARY_REASONS: DropReason[] = ['queue_overflow', 'permanent_client_error', 'auth_refused', 'max_flush_attempts']; + +// Spread retries that a Retry-After would otherwise line up on the same instant. +function jitterUp(ms: number): number { + return ms * (1 + Math.random() * 0.2); +} /** Retry-After as milliseconds: delta-seconds or an HTTP date; undefined when absent or unreadable. */ function parseRetryAfterMs(value: string | null | undefined): number | undefined { @@ -159,9 +164,9 @@ function parseRetryAfterMs(value: string | null | undefined): number | undefined return Math.min(Math.max(0, ms), MAX_RETRY_AFTER_MS); } -/** A 4xx the server means as final (everything except 401/403, 408 and 429). */ +/** A 4xx the server means as final (everything except 408 and 429). */ function isFinalStatus(status: number): boolean { - return status >= 400 && status < 500 && status !== 401 && status !== 403 && status !== 408 && status !== 429; + return status >= 400 && status < 500 && status !== 408 && status !== 429; } interface RetryState { @@ -198,6 +203,8 @@ export class Datalyr { private warnedAuthFailure = false; // one-time loud error for 401/403 (9.D.8) private retryState = new WeakMap(); // FX-047: per-event retry clock; WeakMap → no payload pollution private inFlight = 0; // FX-047: events taken from the queue by a pass and not settled yet + private nextSeq = 0; // FX-047: arrival order, so the cap always evicts the oldest + private seqOf = new WeakMap(); private droppedByReason: Record = Object.fromEntries(ALL_DROP_REASONS.map((r) => [r, 0])) as Record; private reportedByReason: Record = Object.fromEntries(ALL_DROP_REASONS.map((r) => [r, 0])) as Record; private exitHook?: () => void; // the beforeExit listener (stored so close() can remove it — review M2) @@ -374,7 +381,7 @@ export class Datalyr { ...(providedExternalIds && typeof providedExternalIds === 'object' ? { externalIds: providedExternalIds } : {}), // 9.D.1: honor a caller-supplied eventId VERBATIM — it is the ingest server's dedup - // key (6h window), so webhook handlers can pass the source event id (e.g. Stripe + // key (7-day window), so webhook handlers can pass the source event id (e.g. Stripe // `event.id`) and at-least-once redeliveries no longer double-count revenue. A fresh // uuid per call (the old unconditional behavior) made every redelivery look new. eventId: this.resolveEventId(providedEventId), @@ -529,12 +536,16 @@ export class Datalyr { } private enqueue(event: TrackEvent): void { - // Check queue size limit to prevent memory issues. NODE-5 / FX-047: every eviction is - // counted (getStats()) and reported as ONE summary line per flush cycle, never per event. - if (this.queue.length >= this.maxQueueSize) { - const dropped = this.queue.shift(); // Remove oldest event - // 9.D.7: overflow is a drop path — surface it so callers can persist to their own DLQ. - if (dropped) this.notifyDrop([dropped], 'queue_overflow'); + // Memory cap. NODE-5 / FX-047: queued + in flight never exceeds maxQueueSize. The oldest + // QUEUED event is evicted; when every held event is in flight, the new one is dropped. + // Every eviction is counted (getStats()) and reported as ONE summary line per flush + // cycle, never per event. 9.D.7: each also reaches onDrop. + this.seqOf.set(event, this.nextSeq++); + if (this.queue.length + this.inFlight >= this.maxQueueSize) { + const dropped = this.queue.length > 0 ? this.queue.shift()! : event; + this.retryState.delete(dropped); + this.notifyDrop([dropped], 'queue_overflow'); + if (dropped === event) return; } this.queue.push(event); @@ -677,13 +688,14 @@ export class Datalyr { for (let i = 0; i < events.length; i += batchSize) { const batch = events.slice(i, i + batchSize); const promises = batch.map(event => - this.sendEvent(event) - .then(() => { this.retryState.delete(event); }) - .catch((err: any) => { + this.sendEvent(event).then( + () => { this.inFlight--; this.retryState.delete(event); }, + (err: any) => { + // Settled: no longer in flight before the keep/drop decision (the cap counts it again if kept). + this.inFlight--; failed++; this.handleFailure(event, err); }) - .finally(() => { this.inFlight--; }) ); await Promise.allSettled(promises); } @@ -701,10 +713,19 @@ export class Datalyr { // 9.D.7: every send failure reaches onError before any drop/requeue decision. this.notifyError(event, err instanceof Error ? err : new Error(String(err))); - // A final 4xx (malformed, too large, wrong method) can never succeed: drop at once. + // A final 4xx (malformed, too large, wrong method, refused key) can never succeed: drop at once. if (err && err.permanent) { this.retryState.delete(event); - this.notifyDrop([event], 'permanent_client_error'); + if (err.auth) { + // 9.D.8: a wrong key black-holes everything; say so loudly, once. + if (!this.warnedAuthFailure) { + this.warnedAuthFailure = true; + console.error(`[Datalyr] Authentication failing (HTTP ${err.status}) — check your API key ("dk_..."). Events are being dropped.`); + } + this.notifyDrop([event], 'auth_refused'); + } else { + this.notifyDrop([event], 'permanent_client_error'); + } return; } @@ -720,18 +741,7 @@ export class Datalyr { const state = this.retryState.get(event) ?? { firstFailedAt: now, failures: 0, notBefore: 0 }; state.failures++; - if (err && err.auth) { - // 9.D.8: a wrong key black-holes everything; say so loudly, once. - if (!this.warnedAuthFailure) { - this.warnedAuthFailure = true; - console.error(`[Datalyr] Authentication failing (HTTP ${err.status}) — check your API key ("dk_..."). Events are kept and retried for ${AUTH_RETRY_WINDOW_MS / 60_000} minutes, then dropped.`); - } - if (now - state.firstFailedAt >= Math.min(AUTH_RETRY_WINDOW_MS, this.maxRetryDuration)) { - this.retryState.delete(event); - this.notifyDrop([event], 'permanent_client_error'); - return; - } - } else if (now - state.firstFailedAt >= this.maxRetryDuration) { + if (now - state.firstFailedAt >= this.maxRetryDuration) { this.retryState.delete(event); this.notifyDrop([event], 'max_flush_attempts'); return; @@ -740,11 +750,20 @@ export class Datalyr { // Back off before this event is sent again: 1s, 2s, 4s ... 60s with jitter, and never // before the time a Retry-After named. const backoff = Math.min(1000 * Math.pow(2, state.failures - 1), MAX_CYCLE_BACKOFF_MS) * (0.5 + Math.random() * 0.5); - const retryAfter = typeof err?.retryAfterMs === 'number' ? err.retryAfterMs : 0; + const retryAfter = typeof err?.retryAfterMs === 'number' ? jitterUp(err.retryAfterMs) : 0; state.notBefore = now + Math.max(backoff, retryAfter); this.retryState.set(event, state); - // Back at the front so the oldest failures go first. - this.queue.unshift(event); + // Back in arrival order, so the oldest go first and the cap evicts the oldest. + const seq = this.seqOf.get(event) ?? -1; + let at = this.queue.length; + while (at > 0 && (this.seqOf.get(this.queue[at - 1]) ?? -1) > seq) at--; + this.queue.splice(at, 0, event); + // FX-047: a re-queued event counts against the cap like a new one. + while (this.queue.length + this.inFlight > this.maxQueueSize && this.queue.length > 0) { + const evicted = this.queue.shift()!; + this.retryState.delete(evicted); + this.notifyDrop([evicted], 'queue_overflow'); + } } private async sendEvent(event: TrackEvent, retryCount = 0): Promise { @@ -782,13 +801,7 @@ export class Datalyr { const err: any = new Error(`Client error: ${status} ${response.statusText} - ${errorText}`); err.status = status; err.permanent = true; - throw err; - } - // 401/403: no quick retries; the flush layer keeps the event for AUTH_RETRY_WINDOW_MS. - if (status === 401 || status === 403) { - const err: any = new Error(`Authentication error: ${status} ${response.statusText} - ${errorText}`); - err.status = status; - err.auth = true; + err.auth = status === 401 || status === 403; // dropped as auth_refused throw err; } // 408 / 429 / 5xx: temporary. @@ -808,8 +821,8 @@ export class Datalyr { } } } catch (error: any) { - // Final answers and auth failures are decided by the flush layer, not retried here. - if (error && (error.permanent || error.auth)) { + // Final answers are decided by the flush layer, never retried here. + if (error && error.permanent) { if (this.debug) { console.error('[Datalyr] Not retrying now:', error.message); } @@ -829,7 +842,7 @@ export class Datalyr { // recovering server; FX-047: never sooner than the server's Retry-After. const backoffMs = Math.min(Math.pow(2, retryCount) * 1000, 10000); // Max 10s const jittered = backoffMs * (0.5 + Math.random() * 0.5); - await new Promise(resolve => setTimeout(resolve, Math.max(jittered, retryAfterMs ?? 0))); + await new Promise(resolve => setTimeout(resolve, Math.max(jittered, retryAfterMs === undefined ? 0 : jitterUp(retryAfterMs)))); return this.sendEvent(event, retryCount + 1); } diff --git a/tests/retry.ts b/tests/retry.ts index 1dd5eeb..fd77a03 100644 --- a/tests/retry.ts +++ b/tests/retry.ts @@ -139,46 +139,39 @@ async function main() { advance(60_000); await dl.flush(); assert(calls === 1, `Retry-After: still not retried 60 s later (attempts ${calls})`); - advance(61_000); + advance(90_000); // 150 s in all: past 120 s plus up to 20% jitter const r2: any = await dl.flush(); - assert(accepted === 1 && r2 && r2.unsent === 0, `Retry-After: sent once the 120 s pass (accepted ${accepted}, ${JSON.stringify(r2)})`); + assert(accepted === 1 && r2 && r2.unsent === 0, `Retry-After: sent once the 120 s (plus jitter) pass (accepted ${accepted}, ${JSON.stringify(r2)})`); await dl.close(); } - // ---- 401/403 are kept for 10 minutes (a key check can fail for a moment), then dropped ---- + // ---- 401/403 are final (the server answers 503 for its own faults): sent once, dropped, counted ---- { - let calls = 0; - (globalThis as any).fetch = async () => { calls++; return answer(401); }; - const drops: string[] = []; - const dl = new Datalyr({ ...base, retryLimit: 3, onDrop: (_e, r) => drops.push(r) }); - await dl.track({ userId: 'u', event: 'auth_blip' }); - await dl.flush(); - assert(calls === 1 && drops.length === 0, `401: sent once per cycle and kept, not dropped (attempts ${calls}, drops ${JSON.stringify(drops)})`); - advance(5 * 60_000); - await dl.flush(); - assert(calls === 2 && drops.length === 0, `401: still kept after 5 minutes (attempts ${calls}, drops ${JSON.stringify(drops)})`); - advance(6 * 60_000); - await dl.flush(); - assert(drops.length === 1 && drops[0] === 'permanent_client_error', - `401: dropped as permanent_client_error once 10 minutes have passed (drops ${JSON.stringify(drops)})`); - assert((dl as any).getStats?.().droppedByReason?.permanent_client_error === 1, '401: the drop is counted'); - await dl.close(); - - // A 403 that clears: delivered with the same id. - const ids: string[] = []; - (globalThis as any).fetch = async (_u: string, opts: any) => { - ids.push(JSON.parse(opts.body).eventId); - return ids.length === 1 ? answer(403) : answer(200); - }; - const drops2: string[] = []; - const dl2 = new Datalyr({ ...base, onDrop: (_e, r) => drops2.push(r) }); - await dl2.track({ userId: 'u', event: 'auth_recovers' }); - await dl2.flush(); - advance(61_000); - await dl2.flush(); - assert(ids.length === 2 && ids[0] === ids[1] && drops2.length === 0, - `403 then 200: delivered on the retry with the same id, nothing dropped (attempts ${ids.length})`); - await dl2.close(); + const warnings: string[] = []; + const realWarn = console.warn; + console.warn = (...args: any[]) => { warnings.push(args.join(' ')); }; + try { + for (const status of [401, 403]) { + let calls = 0; + (globalThis as any).fetch = async () => { calls++; return answer(status); }; + const drops: string[] = []; + const dl = new Datalyr({ ...base, retryLimit: 3, onDrop: (_e, r) => drops.push(r) }); + await dl.track({ userId: 'u', event: 'auth_' + status + '_a' }); + await dl.track({ userId: 'u', event: 'auth_' + status + '_b' }); + await dl.flush(); + advance(61_000); + await dl.flush(); + assert(calls === 2 && drops.length === 2 && drops.every((r) => r === 'auth_refused'), + `${status}: final, each event sent once and dropped as auth_refused (attempts ${calls}, drops ${JSON.stringify(drops)})`); + const st = (dl as any).getStats?.(); + assert(st?.droppedByReason?.auth_refused === 2, `${status}: counted under auth_refused (got ${JSON.stringify(st?.droppedByReason)})`); + await dl.close(); + } + const authLines = warnings.filter((w) => /auth_refused=2/.test(w)); + assert(authLines.length === 2, `one summary line per client for its auth drops, not one per event (got ${JSON.stringify(authLines)})`); + } finally { + console.warn = realWarn; + } } // ---- Final answers drop at once: 400 and 413 are sent once and never again ---- @@ -198,6 +191,92 @@ async function main() { } } + // ---- A long outage with a steady sender never holds more than maxQueueSize; every eviction counted ---- + { + let peak = 0, calls = 0; + let dlRef: any; + (globalThis as any).fetch = async () => { + calls++; + const st = dlRef.getStats(); + peak = Math.max(peak, st.queued + st.inFlight); + return answer(503); + }; + const realWarn = console.warn; + console.warn = () => {}; + try { + const dl = new Datalyr({ ...base, flushAt: 20, maxQueueSize: 100, retryLimit: 0 }); + dlRef = dl; + let tracked = 0, worst = 0; + for (let round = 0; round < 30; round++) { + for (let i = 0; i < 20; i++) { await dl.track({ userId: 'u', event: `steady_${round}_${i}` }); tracked++; } + await dl.flush(); + const st = (dl as any).getStats(); + worst = Math.max(worst, st.queued + st.inFlight); + advance(61_000); + } + const st = (dl as any).getStats(); + assert(worst <= 100 && peak <= 100, + `steady sender, 30-minute 503 outage: queued + in flight never above the cap of 100 (worst after a flush ${worst}, peak during sends ${peak})`); + assert(st.droppedByReason.queue_overflow + st.queued + st.inFlight === tracked && st.dropped === st.droppedByReason.queue_overflow, + `every event is either held or counted as queue_overflow (${tracked} tracked, ${st.queued + st.inFlight} held, ${st.droppedByReason.queue_overflow} evicted)`); + await dl.close(); + } finally { + console.warn = realWarn; + } + } + + // ---- Temporary failures longer than maxRetryDuration: dropped as max_flush_attempts, counted ---- + { + let calls = 0; + (globalThis as any).fetch = async () => { calls++; return answer(503); }; + const drops: string[] = []; + const dl = new Datalyr({ ...base, retryLimit: 0, maxRetryDuration: 60_000, onDrop: (_e, r) => drops.push(r) } as any); + await dl.track({ userId: 'u', event: 'expires' }); + await dl.flush(); + advance(30_000); + await dl.flush(); + assert(drops.length === 0, `maxRetryDuration: still kept after 30 s of a 60 s window (drops ${JSON.stringify(drops)})`); + advance(31_000); + await dl.flush(); + assert(calls === 3 && drops.length === 1 && drops[0] === 'max_flush_attempts', + `maxRetryDuration: dropped as max_flush_attempts once the window passed (attempts ${calls}, drops ${JSON.stringify(drops)})`); + assert((dl as any).getStats().droppedByReason.max_flush_attempts === 1, 'maxRetryDuration: the drop is counted'); + await dl.close(); + } + + // ---- A malformed Retry-After is ignored: normal backoff, then delivered ---- + { + const stamps: number[] = []; + (globalThis as any).fetch = async () => { + stamps.push(realNow()); + return stamps.length === 1 ? answer(503, { 'Retry-After': 'soon' }) : answer(200); + }; + const dl = new Datalyr({ ...base, retryLimit: 1 }); + await dl.track({ userId: 'u', event: 'retry_after_bad' }); + const r: any = await dl.flush(); + const gap = stamps.length >= 2 ? stamps[1] - stamps[0] : -1; + assert(stamps.length === 2 && gap >= 400 && gap < 1500 && r.unsent === 0, + `Retry-After: soon is ignored: retried after the normal 0.5-1 s backoff and delivered (gap ${gap} ms, ${JSON.stringify(r)})`); + await dl.close(); + } + + // ---- close() waits out a backoff (Retry-After: 2) and delivers instead of dropping ---- + { + const stamps: number[] = []; + (globalThis as any).fetch = async () => { + stamps.push(realNow()); + return stamps.length === 1 ? answer(503, { 'Retry-After': '2' }) : answer(200); + }; + const drops: string[] = []; + const dl = new Datalyr({ ...base, retryLimit: 0, closeTimeout: 10_000, onDrop: (_e, r) => drops.push(r) }); + await dl.track({ userId: 'u', event: 'close_waits' }); + await dl.flush(); + const c: any = await dl.close(); + const gap = stamps.length >= 2 ? stamps[1] - stamps[0] : -1; + assert(stamps.length === 2 && gap >= 1950 && c.unsent === 0 && drops.length === 0, + `close() waits out the 2 s Retry-After, then delivers (gap ${gap} ms, ${JSON.stringify(c)}, drops ${JSON.stringify(drops)})`); + } + // ---- The queue cap: drops are counted, readable, and logged as ONE summary line ---- { (globalThis as any).fetch = () => new Promise(() => {}); // a send that never settles @@ -206,21 +285,22 @@ async function main() { console.warn = (...args: any[]) => { warnings.push(args.join(' ')); }; const dl = new Datalyr({ ...base, maxQueueSize: 100, timeout: 1000, flushTimeout: 1000, closeTimeout: 1000 } as any); try { - // The first 100 are taken by the auto-flush (stuck in flight); 260 more refill a 100 cap. + // The first 100 are taken by the auto-flush (stuck in flight). Queued + in flight is + // already at the cap of 100 and nothing is queued to evict, so the 260 that follow are dropped. for (let i = 0; i < 360; i++) void dl.track({ userId: 'u', event: 'e' + i }); const t0 = realNow(); const res = await within(dl.flush() as Promise, 4000); const elapsed = realNow() - t0; assert(res.done && elapsed < 2500, `flush() returns within flushTimeout while sends hang (${res.done ? elapsed + ' ms' : 'did not return in 4 s'})`); - assert(res.done && res.value && res.value.unsent === 200, - `flush() says how many are unsent: 100 queued + 100 in flight (got ${JSON.stringify(res.value)})`); + assert(res.done && res.value && res.value.unsent === 100, + `flush() says how many are unsent: 100 in flight (got ${JSON.stringify(res.value)})`); const stats = (dl as any).getStats?.(); - assert(!!stats && stats.droppedByReason.queue_overflow === 160 && stats.dropped === 160, - `getStats() counts the 160 events the cap dropped (got ${JSON.stringify(stats)})`); - assert(!!stats && stats.queued === 100 && stats.inFlight === 100, - `getStats() shows 100 queued and 100 in flight (got ${stats && JSON.stringify({ q: stats.queued, f: stats.inFlight })})`); + assert(!!stats && stats.droppedByReason.queue_overflow === 260 && stats.dropped === 260, + `getStats() counts the 260 events the cap dropped (got ${JSON.stringify(stats)})`); + assert(!!stats && stats.queued === 0 && stats.inFlight === 100, + `getStats() shows 0 queued and 100 in flight (got ${stats && JSON.stringify({ q: stats.queued, f: stats.inFlight })})`); const capLines = warnings.filter((w) => /queue/i.test(w) && /dropped/i.test(w)); - assert(capLines.length === 1 && capLines[0].includes('160'), + assert(capLines.length === 1 && capLines[0].includes('260'), `one summary line for the cap, with the count, never one per event (got ${JSON.stringify(capLines)})`); // Nothing new dropped: the next report says nothing. await within(dl.flush() as Promise, 4000); @@ -229,8 +309,8 @@ async function main() { // close() is bounded too and says how many it could not send. const c = await within(dl.close() as Promise, 4000); - assert(c.done && c.value && c.value.unsent === 200, - `close() returns within closeTimeout and says 200 left unsent (got ${JSON.stringify(c.value)})`); + assert(c.done && c.value && c.value.unsent === 100, + `close() returns within closeTimeout and says 100 left unsent (got ${JSON.stringify(c.value)})`); } finally { console.warn = realWarn; } diff --git a/tests/test.ts b/tests/test.ts index 669a2e9..44cf7b3 100644 --- a/tests/test.ts +++ b/tests/test.ts @@ -169,9 +169,7 @@ async function main() { '9.D.3: pre-close event delivered; post-close event dropped (not sent)'); assert(drops93.includes('closed'), "9.D.3: post-close track() fires onDrop('closed')"); - // ---- 9.D.8 / FX-047: 401 → no quick retries, logged once, kept (not dropped at once) ---- - // FX-047 changed this: a 401 is kept and retried for 10 minutes (tests/retry.ts covers the - // window and the final drop), because a key check can fail for a moment. + // ---- 9.D.8: final 401 → sent ONCE, immediate drop (FX-047: counted as auth_refused) ---- let calls401 = 0; const drops401: string[] = []; // Count only THIS test's event — an earlier bounded-close test (dl4) may still be running a // best-effort background flush against the shared global fetch; filtering keeps the count clean. @@ -182,11 +180,10 @@ async function main() { const dl401 = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000, retryLimit: 3, closeTimeout: 2000, onDrop: (_e, r) => drops401.push(r) }); await dl401.track({ userId: 'u', event: 'bad_key' }); await dl401.flush(); - assert(calls401 === 1, `9.D.8: 401 sent ONCE per flush — no quick retries (got ${calls401}; quick retries would be 4)`); - assert(drops401.length === 0, `FX-047: a 401 is kept, not dropped at once (got ${JSON.stringify(drops401)})`); + assert(calls401 === 1, `9.D.8: final 401 sent exactly ONCE — no retry, no requeue (got ${calls401}; retry would be 4)`); + assert(drops401.length === 1 && drops401[0] === 'auth_refused', `9.D.8 / FX-047: 401 fires onDrop('auth_refused') (got ${JSON.stringify(drops401)})`); await dl401.close(); - assert(drops401.length === 1 && drops401[0] === 'close_timeout', - `FX-047: close() gives the still-refused event to onDrop('close_timeout') (got ${JSON.stringify(drops401)})`); + assert(calls401 === 1, `9.D.8: 401 event not re-queued across close() either — still ${calls401} POST`); // ---- 9.D.8: 429 is TRANSIENT (retried like 5xx), NOT permanent ---- let calls429 = 0;