diff --git a/sdk/events.ts b/sdk/events.ts index d467ff9..cc862da 100644 --- a/sdk/events.ts +++ b/sdk/events.ts @@ -45,6 +45,9 @@ const UNAUTHORISED_STATUSES = [401, 403]; */ type Outcome = 'sent' | 'dropped' | 'kept' | 'unauthorised'; +/** Why events were dropped: the buffer was full, a batch failed for good, or the environment key was refused. **/ +export type DroppedReason = 'buffer_full' | 'failed' | 'unauthorised'; + /** Headers the SDK sets itself. Header names are case-insensitive, so custom variants are dropped. **/ const RESERVED_HEADERS = [ 'content-type', @@ -75,6 +78,11 @@ export interface EventProcessorOptions { retryBackoffMs?: number; /** Logger for dropped batches and other failures. Defaults to a new pino logger. **/ logger?: Logger; + /** + * Called whenever events are dropped without being sent, with how many and why. The same events are counted in + * {@link EventProcessor.droppedEvents}. Errors it throws are logged and ignored. + */ + onEventsDropped?: (dropped: { count: number; reason: DroppedReason }) => void; } /** @@ -125,6 +133,8 @@ export class EventProcessor { private agent?: Dispatcher; private customHeaders: { [key: string]: string }; private maxBuffer: number; + private onEventsDropped?: EventProcessorOptions['onEventsDropped']; + private dropped = 0; private flushInterval: number; private requestTimeoutMs: number; private retryBackoffMs: number; @@ -144,6 +154,8 @@ export class EventProcessor { private interval?: NodeJS.Timeout; /** Set once the events API refuses the environment key. **/ private unauthorised = false; + // True while onEventsDropped runs: drops it causes itself (by tracking events) are counted, not reported again. + private reportingDropped = false; /** Aborts the request and backoff in flight when {@link stop} times out. **/ private abortController = new AbortController(); @@ -160,6 +172,7 @@ export class EventProcessor { ) ); this.maxBuffer = opts.maxBuffer ?? DEFAULT_MAX_BUFFER; + this.onEventsDropped = opts.onEventsDropped; this.flushInterval = opts.flushInterval ?? DEFAULT_FLUSH_INTERVAL_MS; this.requestTimeoutMs = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS; this.retryBackoffMs = opts.retryBackoffMs ?? DEFAULT_RETRY_BACKOFF_MS; @@ -300,6 +313,8 @@ export class EventProcessor { metadata: Record | null; }): void { if (this.unauthorised) { + // The key was refused: nothing tracked from now on can be sent. + this.reportDropped(1, 'unauthorised'); return; } if (this.closed) { @@ -332,6 +347,7 @@ export class EventProcessor { return; } + let droppedOldest = false; if (this.buffer.length >= this.maxBuffer) { if (this.pendingFlushes === 0 && !this.hasKeptBatch) { // Takes the full buffer at once, so the new event starts the next batch. @@ -341,6 +357,7 @@ export class EventProcessor { this.logger.warn( `The events buffer is full (${this.maxBuffer} events) while a batch is in flight or kept. Dropping its oldest event.` ); + droppedOldest = true; } } @@ -348,6 +365,10 @@ export class EventProcessor { this.seenExposures.add(exposureKey); } this.buffer.push(event); + // Reported once the new event is in, so a callback that tracks events sees the buffer at maxBuffer. + if (droppedOldest) { + this.reportDropped(1, 'buffer_full'); + } } catch (error) { // Recording an event must never throw into the calling application. this.logger.warn(error, `Failed to record the "${args.event}" event.`); @@ -369,10 +390,14 @@ export class EventProcessor { try { const outcome = await this.postEvents(events); this.hasKeptBatch = outcome === 'kept'; + if (outcome === 'dropped') { + this.reportDropped(events.length, 'failed'); + } if (outcome === 'kept') { this.restoreKeptBatch(events); } else if (outcome === 'unauthorised') { this.unauthorised = true; + this.reportDropped(events.length + this.buffer.length, 'unauthorised'); this.buffer = []; this.seenExposures.clear(); if (this.interval) { @@ -411,6 +436,31 @@ export class EventProcessor { this.logger.warn( `The events buffer is full (${this.maxBuffer} events). Dropping its ${overflow} oldest events.` ); + this.reportDropped(overflow, 'buffer_full'); + } + } + + /** Number of events dropped without being sent since this processor was created. **/ + get droppedEvents(): number { + return this.dropped; + } + + /** Count dropped events and tell {@link EventProcessorOptions.onEventsDropped}, which must never break tracking. **/ + private reportDropped(count: number, reason: DroppedReason): void { + if (count <= 0) { + return; + } + this.dropped += count; + if (this.reportingDropped) { + return; + } + this.reportingDropped = true; + try { + this.onEventsDropped?.({ count, reason }); + } catch (error) { + this.logger.warn(error, 'onEventsDropped threw an error.'); + } finally { + this.reportingDropped = false; } } diff --git a/sdk/types.ts b/sdk/types.ts index 43db360..3791b15 100644 --- a/sdk/types.ts +++ b/sdk/types.ts @@ -145,6 +145,14 @@ export interface FlagsmithConfig { * @default 1000 */ maxBuffer?: number; + /** + * Called whenever events are dropped without being sent, with how many and why: the buffer was full + * (`buffer_full`), a batch failed for good (`failed`) or the environment key was refused (`unauthorised`). + */ + onEventsDropped?: (dropped: { + count: number; + reason: 'buffer_full' | 'failed' | 'unauthorised'; + }) => void; /** * The time, in milliseconds, between automatic flushes. 0 disables the timer. * diff --git a/tests/sdk/events.test.ts b/tests/sdk/events.test.ts index 450f63e..305096d 100644 --- a/tests/sdk/events.test.ts +++ b/tests/sdk/events.test.ts @@ -298,6 +298,134 @@ test('a full buffer drops its oldest event while a batch is in flight', async () expect(postedEvents().map(event => event.identifier)).toEqual(['user-1', 'user-3', 'user-4']); }); +test('dropped events are reported to onEventsDropped and counted in droppedEvents', async () => { + const pending = new Deferred(); + fetch.mockReturnValueOnce(pending.promise); + const onEventsDropped = vi.fn(); + const processor = eventProcessor({ maxBuffer: 2, logger: silentLogger, onEventsDropped }); + + trackPurchase(processor, 'user-1'); + const flush = processor.flush(); + trackPurchase(processor, 'user-2'); + trackPurchase(processor, 'user-3'); + trackPurchase(processor, 'user-4'); + + expect(onEventsDropped).toHaveBeenCalledTimes(1); + expect(onEventsDropped).toHaveBeenCalledWith({ count: 1, reason: 'buffer_full' }); + expect(processor.droppedEvents).toBe(1); + + pending.resolve(new Response(null, { status: 202 })); + await flush; + await processor.flush(); + expect(processor.droppedEvents).toBe(1); +}); + +test('a batch that fails for good is reported as failed', async () => { + fetch.mockResolvedValueOnce(new Response(null, { status: 400 })); + const onEventsDropped = vi.fn(); + const processor = eventProcessor({ logger: silentLogger, onEventsDropped }); + + trackPurchase(processor, 'user-1'); + trackPurchase(processor, 'user-2'); + await processor.flush(); + + expect(onEventsDropped).toHaveBeenCalledWith({ count: 2, reason: 'failed' }); + expect(processor.droppedEvents).toBe(2); +}); + +test('a refused environment key reports every buffered event as unauthorised', async () => { + const pending = new Deferred(); + fetch.mockReturnValueOnce(pending.promise); + const onEventsDropped = vi.fn(); + const processor = eventProcessor({ logger: silentLogger, onEventsDropped }); + + trackPurchase(processor, 'user-1'); + const flush = processor.flush(); + trackPurchase(processor, 'user-2'); // buffered while the batch is in flight + + pending.resolve(new Response(null, { status: 401 })); + await flush; + + expect(onEventsDropped).toHaveBeenCalledTimes(1); + expect(onEventsDropped).toHaveBeenCalledWith({ count: 2, reason: 'unauthorised' }); + expect(processor.droppedEvents).toBe(2); +}); + +test('events tracked after the key was refused are reported as unauthorised', async () => { + fetch.mockResolvedValueOnce(new Response(null, { status: 401 })); + const onEventsDropped = vi.fn(); + const processor = eventProcessor({ logger: silentLogger, onEventsDropped }); + + trackPurchase(processor, 'user-1'); + await processor.flush(); + trackPurchase(processor, 'user-2'); + trackPurchase(processor, 'user-3'); + + expect(onEventsDropped).toHaveBeenLastCalledWith({ count: 1, reason: 'unauthorised' }); + expect(onEventsDropped).toHaveBeenCalledTimes(3); + expect(processor.droppedEvents).toBe(3); + expect(fetch).toHaveBeenCalledTimes(1); +}); + +test('an onEventsDropped that tracks events itself never recurses or overfills the buffer', async () => { + const pending = new Deferred(); + fetch.mockReturnValueOnce(pending.promise); + let processor!: EventProcessor; + const onEventsDropped = vi.fn(() => { + trackPurchase(processor, 'from-callback'); + trackPurchase(processor, 'from-callback-2'); + }); + processor = eventProcessor({ maxBuffer: 2, logger: silentLogger, onEventsDropped }); + + trackPurchase(processor, 'user-1'); + const flush = processor.flush(); + trackPurchase(processor, 'user-2'); + trackPurchase(processor, 'user-3'); + expect(() => trackPurchase(processor, 'user-4')).not.toThrow(); + + // user-4 drops user-2 and calls the callback once; the two drops its own events cause are counted, not reported. + expect(onEventsDropped).toHaveBeenCalledTimes(1); + expect(onEventsDropped).toHaveBeenCalledWith({ count: 1, reason: 'buffer_full' }); + expect(processor.droppedEvents).toBe(3); + + pending.resolve(new Response(null, { status: 202 })); + await flush; + await processor.flush(); + // The second batch holds what was left: maxBuffer events, never more. + expect(postedEvents().map(event => event.identifier)).toEqual([ + 'user-1', + 'from-callback', + 'from-callback-2' + ]); +}); + +test('an onEventsDropped that throws never breaks tracking', async () => { + const pending = new Deferred(); + fetch.mockReturnValueOnce(pending.promise); + const logger = pino({ level: 'silent' }); + const warn = vi.spyOn(logger, 'warn'); + const processor = eventProcessor({ + maxBuffer: 1, + logger, + onEventsDropped: () => { + throw new Error('boom'); + } + }); + + trackPurchase(processor, 'user-1'); + const flush = processor.flush(); + expect(() => trackPurchase(processor, 'user-2')).not.toThrow(); + expect(() => trackPurchase(processor, 'user-3')).not.toThrow(); + expect(processor.droppedEvents).toBe(1); + expect(warn).toHaveBeenCalledWith( + expect.objectContaining({ message: 'boom' }), + 'onEventsDropped threw an error.' + ); + + pending.resolve(new Response(null, { status: 202 })); + await flush; +}); + test('a full buffer drops its oldest event while it holds a kept batch', async () => { fetch .mockResolvedValueOnce(new Response(null, { status: 503 }))