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
58 changes: 34 additions & 24 deletions sdk/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,35 +59,45 @@ export class AnalyticsProcessor {
* Try to flush pending collected data to the Flagsmith analytics API.
*/
async flush() {
if (this.currentFlush || !Object.keys(this.analyticsData).length) {
if (this.currentFlush) {
return;
}

try {
this.currentFlush = this.customFetch(this.analyticsUrl, {
method: 'POST',
body: JSON.stringify(this.analyticsData),
signal: AbortSignal.timeout(this.requestTimeoutMs),
headers: {
'Content-Type': 'application/json',
'X-Environment-Key': this.environmentKey,
'User-Agent': getUserAgent()
while (Object.keys(this.analyticsData).length > 0) {
const analyticsData = this.analyticsData;
this.analyticsData = {};

try {
this.currentFlush = this.customFetch(this.analyticsUrl, {
method: 'POST',
body: JSON.stringify(analyticsData),
signal: AbortSignal.timeout(this.requestTimeoutMs),
headers: {
'Content-Type': 'application/json',
'X-Environment-Key': this.environmentKey,
'User-Agent': getUserAgent()
}
});
const response = await this.currentFlush;
if (response && typeof response.ok === 'boolean' && !response.ok) {
throw new Error(`HTTP ${response.status}`);
}
});
await this.currentFlush;
} catch (error) {
// We don't want failing to write analytics to cause any exceptions in the main
// thread so we just swallow them here.
this.logger.warn(
'Failed to post analytics to Flagsmith API. Not clearing data, will retry.'
);
return;
} finally {
this.currentFlush = undefined;
this.lastFlushed = Date.now();
} catch (error) {
for (const [featureName, count] of Object.entries(analyticsData)) {
this.analyticsData[featureName] =
(this.analyticsData[featureName] || 0) + count;
}
// We don't want failing to write analytics to cause any exceptions in the main
// thread so we just swallow them here.
this.logger.warn(
'Failed to post analytics to Flagsmith API. Not clearing data, will retry.'
);
return;
} finally {
this.currentFlush = undefined;
}
}

this.analyticsData = {};
this.lastFlushed = Date.now();
}

/**
Expand Down
64 changes: 64 additions & 0 deletions tests/sdk/analytics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,67 @@ test('analytics is only flushed once even if requested concurrently', async () =
await flushes;
expect(fetch).toHaveBeenCalledTimes(1);
});

test('analytics flushes evaluations tracked while flush is in flight', async () => {
// Given
let resolveFlush!: () => void;
fetch
.mockImplementationOnce(
() =>
new Promise<Response>(resolve => {
resolveFlush = () => resolve(new Response(null, { status: 200 }));
})
)
.mockResolvedValueOnce(new Response(null, { status: 200 }));

const processor = analyticsProcessor();
processor.trackFeature('myFeature');
const pendingFlush = processor.flush();

// When
processor.trackFeature('duringFlush');
resolveFlush();
await pendingFlush;

// Then
expect(fetch).toHaveBeenCalledTimes(2);
expect(fetch).toHaveBeenNthCalledWith(
1,
'http://testUrl/analytics/flags/',
expect.objectContaining({
body: '{"myFeature":1}'
})
);
expect(fetch).toHaveBeenNthCalledWith(
2,
'http://testUrl/analytics/flags/',
expect.objectContaining({
body: '{"duringFlush":1}'
})
);
expect(processor.analyticsData).toStrictEqual({});
});

test('analytics retains counts when fetch returns an error response', async () => {
// Given
let rejectFlush!: () => void;
fetch.mockImplementationOnce(
() =>
new Promise<Response>(resolve => {
rejectFlush = () => resolve(new Response(null, { status: 503 }));
})
);

const processor = analyticsProcessor();
processor.trackFeature('myFeature');
const pendingFlush = processor.flush();

// When
processor.trackFeature('duringFailedFlush');
rejectFlush();
await pendingFlush;

// Then
expect(fetch).toHaveBeenCalledTimes(1);
expect(processor.analyticsData).toStrictEqual({ myFeature: 1, duringFailedFlush: 1 });
});