Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions sdk/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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;
Expand All @@ -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();

Expand All @@ -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;
Expand Down Expand Up @@ -300,6 +313,8 @@ export class EventProcessor {
metadata: Record<string, unknown> | 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) {
Expand Down Expand Up @@ -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.
Expand All @@ -341,13 +357,18 @@ 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;
}
}

if (exposureKey !== undefined) {
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.`);
Expand All @@ -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');
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
this.buffer = [];
this.seenExposures.clear();
if (this.interval) {
Expand Down Expand Up @@ -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;
}
}

Expand Down
8 changes: 8 additions & 0 deletions sdk/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
128 changes: 128 additions & 0 deletions tests/sdk/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response>();
fetch.mockReturnValueOnce(pending.promise);
const onEventsDropped = vi.fn();
const processor = eventProcessor({ maxBuffer: 2, logger: silentLogger, onEventsDropped });

trackPurchase(processor, 'user-1');
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
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<Response>();
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<Response>();
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<Response>();
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 }))
Expand Down