diff --git a/sdk/analytics.ts b/sdk/analytics.ts index b601cd6..4366f97 100644 --- a/sdk/analytics.ts +++ b/sdk/analytics.ts @@ -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(); } /** diff --git a/tests/sdk/analytics.test.ts b/tests/sdk/analytics.test.ts index 98b6ce3..b77122a 100644 --- a/tests/sdk/analytics.test.ts +++ b/tests/sdk/analytics.test.ts @@ -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(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(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 }); +});