diff --git a/CHANGELOG.md b/CHANGELOG.md index 381f35f..ade6249 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,48 @@ 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 + 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 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). - **`import Datalyr from '@datalyr/api'` threw "Datalyr is not a constructor" in Node ESM.** With no `exports` map, Node loaded the CommonJS build for `import`, so the default import was the whole module object. An `exports` map now sends `import` to `dist/index.mjs` (types `dist/index.d.mts`) and `require` to `dist/index.js` (types `dist/index.d.ts`). `main`, `module` and `types` are unchanged, and deep imports under `dist/` still work. - **Release as a minor version (1.4.0).** Two narrow cases change: an ESM workaround for the old bug (`new Datalyr.default()`, `Datalyr.Datalyr`, `(await import('@datalyr/api')).default.default`) no longer works, because the default import is now the class; use `import Datalyr from '@datalyr/api'` or `import { Datalyr } from '@datalyr/api'`. A deep import without a file extension (`@datalyr/api/dist/index`) no longer resolves; add `.js` or `.mjs`. +### 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. +- `flushTimeout` and `maxRetryDuration` options. +- Drop reason `auth_refused`. + ## [1.3.4] - 2026-11-14 ### Fixed diff --git a/package.json b/package.json index 61e9016..02f1cab 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,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 698105c..420fee5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,9 +3,10 @@ import { randomUUID, createHash } from 'node:crypto'; /** Why an event was dropped, passed to the onDrop hook. */ export type DropReason = | 'validation_error' // track/identify/alias/group called with invalid args - | 'queue_overflow' // maxQueueSize reached; oldest evicted - | 'permanent_client_error' // non-retryable 4xx (≠408/429), e.g. 401/403/400 - | 'max_flush_attempts' // transient failures exceeded MAX_FLUSH_ATTEMPTS cycles + | 'queue_overflow' // queued + in flight reached maxQueueSize; oldest queued evicted + | '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, ) + | 'max_flush_attempts' // temporary failures lasted longer than maxRetryDuration (; the name is kept for compatibility) | 'close_timeout' // still queued when close()'s closeTimeout budget expired | 'closed'; // track() called after close() @@ -22,6 +23,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; + /** 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; + /** 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; /** 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; @@ -47,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). */ @@ -57,7 +66,7 @@ export interface TrackOptions { * `event.created`). Defaults to now. Invalid values are ignored (defaults to now) — * pass this on delayed webhook replays so the event lands on the right day. */ timestamp?: string | Date | number; - /** Declared external identity namespaces: + /** Declared external identity namespaces (Datalyr person contract ): * `{ namespace: id }`, e.g. `{ stripe: 'cus_123', crm: 'acct_9' }`. Use this for * ANY identifier that is not the same userId your client-side identify() uses — * internal database ids, provider customer ids, private namespaces. Declared ids @@ -68,7 +77,24 @@ export interface TrackOptions { externalIds?: Record; } -/** The revenue payload for trackPurchase(). `value` is required and must be a finite +/** 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; +} + +/** 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; +} + +/** 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 { value: number; @@ -84,7 +110,7 @@ function generateEventId(): string { } // A FRESH anonymous id, generated PER CALL — never a shared instance value. This is the -// a single long-lived server process tracking many distinct end-users +// fix for a single long-lived server process tracking many distinct end-users // must not stamp them all with one anonymous_id (which the ingest identity-resolution // then cross-links into one merged identity, leaking traits across users). function generateAnonymousId(): string { @@ -93,12 +119,61 @@ function generateAnonymousId(): string { const SDK_VERSION = '1.3.4'; // keep in sync with package.json -// 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; + +// 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 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 +// 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', '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', '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 { + 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 408 and 429). */ +function isFinalStatus(status: number): boolean { + return status >= 400 && status < 500 && status !== 408 && status !== 429; +} + +interface RetryState { + firstFailedAt: number; + failures: number; + notBefore: number; +} // cap the caller-supplied eventId. Longer ids become pathological Redis keys server-side; // overflow is hash-collapsed (deterministic, so redeliveries still dedup) below. @@ -115,20 +190,26 @@ 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 private currentFlush?: Promise; // the in-flight drain — callers/close() await this instead of getting a no-op - private closePromise?: Promise; // memoized so close() is idempotent under repeat/concurrent calls + private closePromise?: Promise; // memoized so close() is idempotent under repeat/concurrent calls private warnedNoId = false; // one-time warn for calls with neither userId nor anonymousId - private warnedQueueFull = false; // one-time prod warn when the queue overflows private warnedClosed = false; // one-time loud error for track() after close() private warnedAuthFailure = false; // one-time loud error for 401/403 - private flushAttempts = new WeakMap(); // failed-flush-cycle count per event; WeakMap → no payload pollution + private retryState = new WeakMap(); // per-event retry clock; WeakMap → no payload pollution + private inFlight = 0; // events taken from the queue by a pass and not settled yet + private nextSeq = 0; // 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) - private onError?: (event: TrackEvent, error: Error) => void; - private onDrop?: (events: TrackEvent[], reason: DropReason) => void; + private onError?: (event: TrackEvent, error: Error) => void; // + private onDrop?: (events: TrackEvent[], reason: DropReason) => void; // constructor(config: DatalyrConfig | string) { if (typeof config === 'string') { @@ -141,6 +222,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 +234,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 +261,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 +288,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 +296,7 @@ export class Datalyr { // 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; // every drop is counted, hook or not if (!this.onDrop) return; try { this.onDrop(events, reason); } catch { /* a hook must never break the SDK */ } } @@ -284,12 +376,12 @@ export class Datalyr { const trackEvent: TrackEvent = { userId: userId || undefined, anonymousId: anonymousId, // Always include for identity resolution - // declared namespaces ride the envelope top-level; + // Person contract : declared namespaces ride the envelope top-level; // the ingest worker classifies + preserves them for identity joining. ...(providedExternalIds && typeof providedExternalIds === 'object' ? { externalIds: providedExternalIds } : {}), // 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), @@ -398,7 +490,7 @@ export class Datalyr { }); } - // caller-supplied idempotency key. Defensive by design — this SDK must never + // + caller-supplied idempotency key. Defensive by design — this SDK must never // crash the host — so anything that isn't a non-empty string is IGNORED (fresh uuid, same // as omitting it) with a debug warning, never a throw. An over-long id (pathological Redis // key server-side) is collapsed to a DETERMINISTIC sha256-based value so redeliveries of @@ -444,16 +536,16 @@ export class Datalyr { } private enqueue(event: TrackEvent): void { - // Check queue size limit to prevent memory issues. Surface the drop in PROD - // (once) — it was debug-only, so silent data loss under sustained overload. - 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 - // overflow is a drop path — surface it so callers can persist to their own DLQ. - if (dropped) this.notifyDrop([dropped], 'queue_overflow'); + // Memory cap. / 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. 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); @@ -464,7 +556,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 +564,116 @@ export class Datalyr { } } - async flush(): Promise { - // 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. - // 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 { + // / / 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 }; + } + /** 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(); + } + } + + // 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}`); } - // 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. + // 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 +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).catch((err: any) => { - failed++; - // every send failure reaches onError before any drop/requeue decision. - this.notifyError(event, err instanceof Error ? err : new Error(String(err))); - - // 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; - } - - // 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. - // 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.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); + }) ); await Promise.allSettled(promises); } @@ -583,6 +707,65 @@ export class Datalyr { return events.length - failed; } + // 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 { + // 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, refused key) can never succeed: drop at once. + if (err && err.permanent) { + this.retryState.delete(event); + if (err.auth) { + // 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; + } + + // 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 (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' ? jitterUp(err.retryAfterMs) : 0; + state.notBefore = now + Math.max(backoff, retryAfter); + this.retryState.set(event, state); + // 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); + // 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 { try { const controller = new AbortController(); @@ -609,21 +792,22 @@ export class Datalyr { } catch { // Ignore body read errors } - - // 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; + err.auth = status === 401 || status === 403; // dropped as auth_refused throw err; } - - // Retry on 5xx / 408 / 429 (transient) - const err: any = new Error(`Server error: ${response.status} ${response.statusText} - ${errorText}`); - err.status = response.status; + // 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 +821,28 @@ export class Datalyr { } } } catch (error: any) { - // Don't retry permanent client errors (bad key/forbidden/malformed). + // Final answers are decided by the flush layer, never retried here. if (error && error.permanent) { 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})`); } // full jitter so many SDK instances don't retry in lockstep against a - // recovering server. + // recovering server; 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 === undefined ? 0 : jitterUp(retryAfterMs)))); return this.sendEvent(event, retryCount + 1); } @@ -665,7 +853,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); } @@ -680,7 +869,7 @@ export class Datalyr { } /** - * Generate a NEW anonymous id. There is no longer a shared process-wide anon + * Generate a NEW anonymous id. there is no longer a shared process-wide anon * (that merged distinct users). Each call returns a fresh id — persist it in YOUR * per-user/session store and pass it back as `anonymousId` to stitch that user's * events. (Behavior change from <=1.2.3, which returned one shared id.) @@ -689,7 +878,7 @@ export class Datalyr { return generateAnonymousId(); } - // A cancelable delay. Returns the promise AND a cancel() that clears the underlying + // A cancelable delay: . Returns the promise AND a cancel() that clears the underlying // timer, so a Promise.race that settles via the OTHER arm doesn't leave a live (non-unref'd) // timer holding the event loop open until it fires — the exact hang the 1.3.0 unref work // fixed and the close() race timer had reintroduced. @@ -699,8 +888,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 { // 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 +902,7 @@ export class Datalyr { return this.closePromise; } - private async _close(): Promise { + private async _close(): Promise { this.isClosing = true; if (this.timer) { @@ -716,7 +910,7 @@ export class Datalyr { this.timer = undefined; } - // actually DRAIN the queue. The old close() flushed ONCE and raced a hard + // /2/4: actually DRAIN the queue. The old close() flushed ONCE and raced a hard // 5s timeout — one flush isn't enough (it re-queues failures), a no-op flush won if one // was in flight, and 5s < worst-case retry (~7s) dropped mid-retry events. Loop flush() // (which now drains until the queue empties instead of no-op'ing) until the queue drains @@ -734,25 +928,18 @@ export class Datalyr { // after close() resolved (proven: close resolved 14ms, process exited 8016ms). // // 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()); + // 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 +956,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 = []; // 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..fd77a03 --- /dev/null +++ b/tests/retry.ts @@ -0,0 +1,323 @@ +// 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(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 (plus jitter) pass (accepted ${accepted}, ${JSON.stringify(r2)})`); + await dl.close(); + } + + // ---- 401/403 are final (the server answers 503 for its own faults): sent once, dropped, counted ---- + { + 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 ---- + { + 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(); + } + } + + // ---- 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 + 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). 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 === 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 === 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('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); + 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 === 100, + `close() returns within closeTimeout and says 100 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..44cf7b3 100644 --- a/tests/test.ts +++ b/tests/test.ts @@ -169,7 +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: permanent 401 → sent ONCE, immediate drop, no 10-cycle requeue ---- + // ---- 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. @@ -180,8 +180,8 @@ 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: 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(calls401 === 1, `9.D.8: 401 event not re-queued across close() either — still ${calls401} POST`);