From 4534727bff12b65ec67c214ba45d63425e02ea82 Mon Sep 17 00:00:00 2001 From: tharunkumardeveloper <142856777+tharunkumardeveloper@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:21:30 +0530 Subject: [PATCH 1/2] feat(events): report dropped events through onEventsDropped and droppedEvents Part of #330: a programmatic signal when the event processor drops events without sending them. --- sdk/events.ts | 35 +++++++++++++++++++++ sdk/types.ts | 8 +++++ tests/sdk/events.test.ts | 68 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+) diff --git a/sdk/events.ts b/sdk/events.ts index d467ff9..2180148 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; @@ -160,6 +170,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; @@ -341,6 +352,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.` ); + this.reportDropped(1, 'buffer_full'); } } @@ -369,10 +381,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 +427,25 @@ 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; + try { + this.onEventsDropped?.({ count, reason }); + } catch (error) { + this.logger.warn(error, 'onEventsDropped threw an error.'); } } 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..969f406 100644 --- a/tests/sdk/events.test.ts +++ b/tests/sdk/events.test.ts @@ -298,6 +298,74 @@ 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 () => { + fetch.mockResolvedValueOnce(new Response(null, { status: 401 })); + const onEventsDropped = vi.fn(); + const processor = eventProcessor({ logger: silentLogger, onEventsDropped }); + + trackPurchase(processor, 'user-1'); + await processor.flush(); + + expect(onEventsDropped).toHaveBeenCalledWith({ count: 1, reason: 'unauthorised' }); + expect(processor.droppedEvents).toBe(1); +}); + +test('an onEventsDropped that throws never breaks tracking', async () => { + const pending = new Deferred(); + fetch.mockReturnValueOnce(pending.promise); + const processor = eventProcessor({ + maxBuffer: 1, + logger: silentLogger, + 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); + + 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 })) From 1edf046974fa839f38c7fdf58599ba961ffcfbc5 Mon Sep 17 00:00:00 2001 From: tharunkumardeveloper <142856777+tharunkumardeveloper@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:59:12 +0530 Subject: [PATCH 2/2] fix: Address review of the dropped-events callback - A buffer-full drop is reported once the new event is in the buffer, and drops caused while onEventsDropped runs (by events it tracks itself) are counted in droppedEvents without calling it again: no recursion, and the buffer never exceeds maxBuffer. - Events tracked after the environment key was refused are reported as unauthorised and counted. - Tests: the 401 case buffers a second event while the request is pending; events tracked after the refusal; a callback that tracks events; the throwing callback's error is logged. Co-Authored-By: Claude Opus 5.5 --- sdk/events.ts | 17 ++++++++++- tests/sdk/events.test.ts | 66 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 79 insertions(+), 4 deletions(-) diff --git a/sdk/events.ts b/sdk/events.ts index 2180148..cc862da 100644 --- a/sdk/events.ts +++ b/sdk/events.ts @@ -154,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(); @@ -311,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) { @@ -343,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. @@ -352,7 +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.` ); - this.reportDropped(1, 'buffer_full'); + droppedOldest = true; } } @@ -360,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.`); @@ -442,10 +451,16 @@ export class EventProcessor { 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/tests/sdk/events.test.ts b/tests/sdk/events.test.ts index 969f406..305096d 100644 --- a/tests/sdk/events.test.ts +++ b/tests/sdk/events.test.ts @@ -334,23 +334,79 @@ test('a batch that fails for good is reported as failed', async () => { }); 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).toHaveBeenCalledWith({ count: 1, reason: 'unauthorised' }); - expect(processor.droppedEvents).toBe(1); + 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: silentLogger, + logger, onEventsDropped: () => { throw new Error('boom'); } @@ -361,6 +417,10 @@ test('an onEventsDropped that throws never breaks tracking', async () => { 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;