@posthog/core 1.70.0 → 1.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/capture-v1/package.json +6 -0
  2. package/dist/capture-v1/compression.d.ts +18 -0
  3. package/dist/capture-v1/compression.d.ts.map +1 -0
  4. package/dist/capture-v1/compression.js +70 -0
  5. package/dist/capture-v1/compression.mjs +26 -0
  6. package/dist/capture-v1/errors.d.ts +48 -0
  7. package/dist/capture-v1/errors.d.ts.map +1 -0
  8. package/dist/capture-v1/errors.js +82 -0
  9. package/dist/capture-v1/errors.mjs +38 -0
  10. package/dist/capture-v1/index.d.ts +15 -0
  11. package/dist/capture-v1/index.d.ts.map +1 -0
  12. package/dist/capture-v1/index.js +88 -0
  13. package/dist/capture-v1/index.mjs +7 -0
  14. package/dist/capture-v1/sender.d.ts +150 -0
  15. package/dist/capture-v1/sender.d.ts.map +1 -0
  16. package/dist/capture-v1/sender.js +554 -0
  17. package/dist/capture-v1/sender.mjs +507 -0
  18. package/dist/capture-v1/serialize.d.ts +30 -0
  19. package/dist/capture-v1/serialize.d.ts.map +1 -0
  20. package/dist/capture-v1/serialize.js +106 -0
  21. package/dist/capture-v1/serialize.mjs +59 -0
  22. package/dist/capture-v1/transform.d.ts +19 -0
  23. package/dist/capture-v1/transform.d.ts.map +1 -0
  24. package/dist/capture-v1/transform.js +118 -0
  25. package/dist/capture-v1/transform.mjs +77 -0
  26. package/dist/capture-v1/types.d.ts +52 -0
  27. package/dist/capture-v1/types.d.ts.map +1 -0
  28. package/dist/capture-v1/types.js +44 -0
  29. package/dist/capture-v1/types.mjs +3 -0
  30. package/dist/capture-v1/uuid.d.ts +9 -0
  31. package/dist/capture-v1/uuid.d.ts.map +1 -0
  32. package/dist/capture-v1/uuid.js +75 -0
  33. package/dist/capture-v1/uuid.mjs +34 -0
  34. package/dist/featureFlagUtils.d.ts +7 -5
  35. package/dist/featureFlagUtils.d.ts.map +1 -1
  36. package/dist/featureFlagUtils.js +17 -11
  37. package/dist/featureFlagUtils.mjs +14 -11
  38. package/dist/index.d.ts +1 -1
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +27 -16
  41. package/dist/index.mjs +1 -1
  42. package/dist/posthog-core-stateless.d.ts +40 -3
  43. package/dist/posthog-core-stateless.d.ts.map +1 -1
  44. package/dist/posthog-core-stateless.js +87 -19
  45. package/dist/posthog-core-stateless.mjs +87 -19
  46. package/dist/posthog-core.d.ts +138 -53
  47. package/dist/posthog-core.d.ts.map +1 -1
  48. package/dist/posthog-core.js +341 -115
  49. package/dist/posthog-core.mjs +338 -115
  50. package/dist/types.d.ts +24 -1
  51. package/dist/types.d.ts.map +1 -1
  52. package/dist/utils/index.d.ts +1 -1
  53. package/dist/utils/index.d.ts.map +1 -1
  54. package/dist/utils/index.js +25 -12
  55. package/dist/utils/index.mjs +1 -1
  56. package/dist/utils/json-utils.d.ts +11 -1
  57. package/dist/utils/json-utils.d.ts.map +1 -1
  58. package/dist/utils/json-utils.js +50 -2
  59. package/dist/utils/json-utils.mjs +46 -1
  60. package/package.json +12 -2
  61. package/src/capture-v1/compression.ts +50 -0
  62. package/src/capture-v1/errors.ts +91 -0
  63. package/src/capture-v1/index.ts +34 -0
  64. package/src/capture-v1/sender.ts +779 -0
  65. package/src/capture-v1/serialize.ts +113 -0
  66. package/src/capture-v1/transform.ts +135 -0
  67. package/src/capture-v1/types.ts +59 -0
  68. package/src/capture-v1/uuid.ts +53 -0
  69. package/src/featureFlagUtils.ts +22 -10
  70. package/src/index.ts +1 -0
  71. package/src/posthog-core-stateless.ts +166 -30
  72. package/src/posthog-core.ts +615 -178
  73. package/src/types.ts +21 -1
  74. package/src/utils/index.ts +1 -1
  75. package/src/utils/json-utils.ts +64 -1
  76. package/src/error-tracking/chunk-ids.spec.ts +0 -77
  77. package/src/error-tracking/coercers/error-event-coercer.spec.ts +0 -142
  78. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +0 -77
  79. package/src/error-tracking/coercers/string-coercer.spec.ts +0 -26
  80. package/src/error-tracking/error-properties-builder.aggregate-errors.spec.ts +0 -412
  81. package/src/error-tracking/error-properties-builder.coerce.spec.ts +0 -337
  82. package/src/error-tracking/error-properties-builder.metadata.spec.ts +0 -318
  83. package/src/error-tracking/error-properties-builder.parse.spec.ts +0 -37
  84. package/src/error-tracking/exception-steps.spec.ts +0 -115
  85. package/src/error-tracking/parsers/base.spec.ts +0 -156
  86. package/src/error-tracking/parsers/index.spec.ts +0 -270
  87. package/src/error-tracking/parsers/node.spec.ts +0 -34
  88. package/src/error-tracking/release.spec.ts +0 -34
  89. package/src/logs/index.spec.ts +0 -2421
  90. package/src/logs/logs-utils.spec.ts +0 -266
  91. package/src/metrics/index.spec.ts +0 -1249
  92. package/src/surveys/activation.spec.ts +0 -61
  93. package/src/surveys/events.spec.ts +0 -183
  94. package/src/surveys/keys.spec.ts +0 -29
  95. package/src/surveys/property-matching.spec.ts +0 -539
  96. package/src/surveys/shuffling.spec.ts +0 -51
  97. package/src/surveys/translations.spec.ts +0 -274
  98. package/src/surveys/validation.spec.ts +0 -168
  99. package/src/traces/config.spec.ts +0 -271
  100. package/src/traces/ids.spec.ts +0 -115
  101. package/src/traces/index.spec.ts +0 -3287
  102. package/src/traces/live-spans.spec.ts +0 -69
  103. package/src/traces/otlp.spec.ts +0 -368
  104. package/src/traces/span.spec.ts +0 -1137
  105. package/src/traces/traceparent.spec.ts +0 -184
  106. package/src/utils/bot-detection.spec.ts +0 -107
  107. package/src/utils/bucketed-rate-limiter.spec.ts +0 -327
  108. package/src/utils/json-utils.spec.ts +0 -115
  109. package/src/utils/named-error.spec.ts +0 -36
  110. package/src/utils/number-utils.spec.ts +0 -212
  111. package/src/utils/otlp-any-value.spec.ts +0 -376
  112. package/src/utils/otlp-resource.spec.ts +0 -171
  113. package/src/utils/promise-queue.spec.ts +0 -55
  114. package/src/utils/string-utils.spec.ts +0 -158
  115. package/src/utils/type-utils.spec.ts +0 -38
  116. package/src/utils/webview-app-utils.spec.ts +0 -118
  117. package/src/vendor/uuidv7.spec.ts +0 -26
@@ -1,2421 +0,0 @@
1
- import { PostHogPersistedProperty } from '../types'
2
- import { createTestClient, PostHogCoreTestClient } from '../testing'
3
- import type { Logger } from '../types'
4
- import { PostHogLogs } from './index'
5
- import type { BufferedLogEntry, ResolvedPostHogLogsConfig } from './types'
6
-
7
- // Default resolved config for tests — mirrors what each SDK would build by
8
- // merging user config onto its own defaults. Test-only fixture; the real
9
- // defaults live per-SDK. Takes the resolved (flat) shape directly so tests
10
- // can override `maxLogsPerInterval` / `rateCapWindowMs` without going through
11
- // the public `rateCap: { maxLogs, windowMs }` wrapper.
12
- const DEFAULT_MAX_BUFFER_SIZE = 100
13
- const DEFAULT_FLUSH_INTERVAL_MS = 10000
14
- const DEFAULT_MAX_BATCH_RECORDS_PER_POST = 50
15
- const DEFAULT_RATE_CAP_WINDOW_MS = 10000
16
- const DEFAULT_BACKGROUND_FLUSH_BUDGET_MS = 25000
17
- const DEFAULT_TERMINATION_FLUSH_BUDGET_MS = 2000
18
- const resolveForTest = (partial?: Partial<ResolvedPostHogLogsConfig>): ResolvedPostHogLogsConfig => ({
19
- ...partial,
20
- maxBufferSize: partial?.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE,
21
- flushIntervalMs: partial?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
22
- maxBatchRecordsPerPost: partial?.maxBatchRecordsPerPost ?? DEFAULT_MAX_BATCH_RECORDS_PER_POST,
23
- rateCapWindowMs: partial?.rateCapWindowMs ?? DEFAULT_RATE_CAP_WINDOW_MS,
24
- backgroundFlushBudgetMs: DEFAULT_BACKGROUND_FLUSH_BUDGET_MS,
25
- terminationFlushBudgetMs: DEFAULT_TERMINATION_FLUSH_BUDGET_MS,
26
- // Uncapped by default so existing tests aren't affected. The rate-limit
27
- // describe block opts in explicitly via { maxLogsPerInterval: N }.
28
- maxLogsPerInterval: partial?.maxLogsPerInterval,
29
- })
30
-
31
- // Mock PostHog instance exposing the `PostHogCoreStateless` surface PostHogLogs
32
- // touches. Init gating is injected separately via the onReady closure.
33
- const createMockInstance = (overrides: Record<string, any> = {}): any => {
34
- const store: Record<string, any> = {}
35
- const instance: any = {
36
- optedOut: false,
37
- getDistinctId: vi.fn(() => 'user-123'),
38
- getSessionId: vi.fn(() => 'sess-456'),
39
- getLibraryId: vi.fn(() => 'posthog-core-tests'),
40
- getLibraryVersion: vi.fn(() => '0.0.0-test'),
41
- getPersistedProperty: vi.fn((key: string) => store[key]),
42
- setPersistedProperty: vi.fn((key: string, value: any) => {
43
- if (value === null || value === undefined) {
44
- delete store[key]
45
- } else {
46
- store[key] = value
47
- }
48
- }),
49
- _sendLogsBatch: vi.fn(() => Promise.resolve({ kind: 'ok' })),
50
- addPendingPromise: vi.fn(<T>(promise: Promise<T>) => promise),
51
- _store: store,
52
- ...overrides,
53
- }
54
- return instance
55
- }
56
-
57
- // Default onReady for tests — runs fn synchronously, matching a post-init SDK.
58
- // Tests that model pre-init or rejected init provide their own closure.
59
- const immediateOnReady = (fn: () => void): void => fn()
60
-
61
- const createMockLogger = (): Logger => {
62
- const logger: any = {
63
- debug: vi.fn(),
64
- info: vi.fn(),
65
- warn: vi.fn(),
66
- error: vi.fn(),
67
- critical: vi.fn(),
68
- }
69
- logger.createLogger = vi.fn(() => logger)
70
- return logger as Logger
71
- }
72
-
73
- const readQueue = (instance: any): BufferedLogEntry[] => {
74
- return (instance._store[PostHogPersistedProperty.LogsQueue] as BufferedLogEntry[] | undefined) ?? []
75
- }
76
-
77
- // Default getContext closure for tests — reads from the mock instance the way
78
- // a real SDK adapter would. Tests that need dynamic context override per-call.
79
- const getContextFor = (instance: any) => (): { distinctId?: string; sessionId?: string } => ({
80
- distinctId: instance.getDistinctId() || undefined,
81
- sessionId: instance.getSessionId() || undefined,
82
- })
83
-
84
- // Drives a real core host rather than a stubbed `_sendLogsBatch`, so the sender's
85
- // error classification and the queue bookkeeping are exercised together.
86
- describe('PostHogLogs over the core sender', () => {
87
- const createLogsOverCore = (status: number): { logs: PostHogLogs; client: PostHogCoreTestClient } => {
88
- const [client, mocks] = createTestClient('TEST_API_KEY', {
89
- fetchRetryCount: 0,
90
- preloadFeatureFlags: false,
91
- })
92
- mocks.fetch.mockResolvedValue({
93
- status,
94
- text: () => Promise.resolve('err'),
95
- json: () => Promise.resolve({ status: 'err' }),
96
- })
97
- const logs = new PostHogLogs(
98
- client,
99
- resolveForTest(),
100
- createMockLogger(),
101
- () => ({ distinctId: 'user-123' }),
102
- immediateOnReady
103
- )
104
- return { logs, client }
105
- }
106
-
107
- const queueOf = (client: PostHogCoreTestClient): BufferedLogEntry[] =>
108
- client.getPersistedProperty<BufferedLogEntry[]>(PostHogPersistedProperty.LogsQueue) ?? []
109
-
110
- it.each([408, 429, 500, 503])('keeps records queued when the endpoint answers %i', async (status) => {
111
- const { logs, client } = createLogsOverCore(status)
112
- logs.captureLog({ body: 'keep me' })
113
-
114
- await expect(logs.flush()).rejects.toHaveProperty('name', 'PostHogFetchHttpError')
115
-
116
- expect(queueOf(client)).toHaveLength(1)
117
- })
118
-
119
- it('retains and resends records after transport retries are exhausted', async () => {
120
- vi.useRealTimers()
121
- const [client, mocks] = createTestClient('TEST_API_KEY', {
122
- fetchRetryCount: 2,
123
- fetchRetryDelay: 1,
124
- preloadFeatureFlags: false,
125
- })
126
- const unavailableResponse = { status: 503, text: async () => 'unavailable', json: async () => ({}) }
127
- mocks.fetch
128
- .mockResolvedValueOnce(unavailableResponse)
129
- .mockResolvedValueOnce(unavailableResponse)
130
- .mockResolvedValueOnce(unavailableResponse)
131
- .mockResolvedValueOnce({ status: 200, text: async () => 'ok', json: async () => ({}) })
132
- const logs = new PostHogLogs(
133
- client,
134
- resolveForTest(),
135
- createMockLogger(),
136
- () => ({ distinctId: 'user-123' }),
137
- immediateOnReady
138
- )
139
-
140
- logs.captureLog({ body: 'retry me' })
141
- await expect(logs.flush()).rejects.toHaveProperty('name', 'PostHogFetchHttpError')
142
- expect(mocks.fetch).toHaveBeenCalledTimes(3)
143
- expect(queueOf(client)).toHaveLength(1)
144
-
145
- await expect(logs.flush()).resolves.toBeUndefined()
146
- expect(mocks.fetch).toHaveBeenCalledTimes(4)
147
- expect(queueOf(client)).toHaveLength(0)
148
- })
149
-
150
- it('drops the batch when the endpoint answers 401', async () => {
151
- const { logs, client } = createLogsOverCore(401)
152
- logs.captureLog({ body: 'unauthorized' })
153
-
154
- await expect(logs.flush()).rejects.toHaveProperty('name', 'PostHogFetchHttpError')
155
-
156
- expect(queueOf(client)).toHaveLength(0)
157
- })
158
- })
159
-
160
- describe('PostHogLogs', () => {
161
- let mockInstance: any
162
- let logger: Logger
163
-
164
- beforeEach(() => {
165
- mockInstance = createMockInstance()
166
- logger = createMockLogger()
167
- // Retry delays carry jitter; pinned to its midpoint so every timing
168
- // assertion here measures the backoff itself and cannot flake.
169
- vi.spyOn(Math, 'random').mockReturnValue(0.5)
170
- })
171
-
172
- it('constructs without throwing', () => {
173
- const logs = new PostHogLogs(mockInstance, resolveForTest(), logger, getContextFor(mockInstance), immediateOnReady)
174
- expect(logs).toBeDefined()
175
- })
176
-
177
- describe('clearQueue', () => {
178
- it('does not let an in-flight batch drop records captured after the clear', async () => {
179
- let releaseSend: (v: any) => void = () => {}
180
- const mockInstance = createMockInstance({
181
- _sendLogsBatch: vi.fn(() => new Promise((resolve) => (releaseSend = resolve))),
182
- })
183
- const logs = new PostHogLogs(
184
- mockInstance,
185
- resolveForTest(),
186
- logger,
187
- getContextFor(mockInstance),
188
- immediateOnReady
189
- )
190
- logs.captureLog({ body: 'before the clear' })
191
-
192
- const flushing = logs.flush()
193
- logs.clearQueue()
194
- logs.captureLog({ body: 'captured after the clear' })
195
-
196
- releaseSend({ kind: 'ok' })
197
- await flushing
198
-
199
- expect(readQueue(mockInstance).map((e) => e.record.body)).toEqual([{ stringValue: 'captured after the clear' }])
200
- })
201
- })
202
-
203
- describe('a 413 retry that lands after the queue is cleared', () => {
204
- it('does not re-send records the clear purged', async () => {
205
- const sentBodies: string[][] = []
206
- let releaseSend: (v: any) => void = () => {}
207
- const mockInstance = createMockInstance({
208
- _sendLogsBatch: vi.fn((payload: any) => {
209
- sentBodies.push(payload.resourceLogs[0].scopeLogs[0].logRecords.map((r: any) => r.body.stringValue))
210
- // Only the first send is held open; any retry resolves at once so a
211
- // regression fails on the assertion rather than by hanging the test.
212
- return sentBodies.length === 1
213
- ? new Promise((resolve) => (releaseSend = resolve))
214
- : Promise.resolve({ kind: 'ok' })
215
- }),
216
- })
217
- const logs = new PostHogLogs(
218
- mockInstance,
219
- resolveForTest(),
220
- logger,
221
- getContextFor(mockInstance),
222
- immediateOnReady
223
- )
224
- logs.captureLog({ body: 'purged one' })
225
- logs.captureLog({ body: 'purged two' })
226
-
227
- const flushing = logs.flush()
228
- logs.clearQueue()
229
- // A 413 makes `_flushInner` retry the same records with a smaller batch cap.
230
- releaseSend({ kind: 'too-large' })
231
- await flushing
232
-
233
- expect(sentBodies).toEqual([['purged one', 'purged two']])
234
- })
235
- })
236
-
237
- describe('a clear that lands between two batches of one flush', () => {
238
- it('still advances the batch assembled after the clear', async () => {
239
- const sent: string[][] = []
240
- let releasePersist: (() => void) | null = null
241
- const mockInstance = createMockInstance({
242
- _sendLogsBatch: vi.fn((payload: any) => {
243
- sent.push(payload.resourceLogs[0].scopeLogs[0].logRecords.map((r: any) => r.body.stringValue))
244
- return Promise.resolve({ kind: 'ok' })
245
- }),
246
- })
247
- const logs = new PostHogLogs(
248
- mockInstance,
249
- resolveForTest({ maxBatchRecordsPerPost: 1 }),
250
- logger,
251
- getContextFor(mockInstance),
252
- immediateOnReady,
253
- () => new Promise<void>((resolve) => (releasePersist = resolve))
254
- )
255
- logs.captureLog({ body: 'a' })
256
- logs.captureLog({ body: 'b' })
257
-
258
- const flushing = logs.flush()
259
- // Let batch ['a'] send and park inside the persist await between batches.
260
- for (let i = 0; i < 10; i++) {
261
- await Promise.resolve()
262
- }
263
- logs.clearQueue()
264
- logs.captureLog({ body: 'c' })
265
- // Each batch installs a fresh persist gate; release whichever is pending until
266
- // the flush drains.
267
- for (let i = 0; i < 20; i++) {
268
- const pending = releasePersist
269
- releasePersist = null
270
- pending?.()
271
- await Promise.resolve()
272
- }
273
- await flushing
274
-
275
- expect({ sent, queue: readQueue(mockInstance).map((e) => e.record.body.stringValue) }).toEqual({
276
- sent: [['a'], ['c']],
277
- queue: [],
278
- })
279
- })
280
- })
281
-
282
- describe('reset during an in-flight flush', () => {
283
- it('does not let an in-flight batch drop records captured after the reset', async () => {
284
- let releaseSend: (v: any) => void = () => {}
285
- const mockInstance = createMockInstance({
286
- _sendLogsBatch: vi.fn(() => new Promise((resolve) => (releaseSend = resolve))),
287
- })
288
- const logs = new PostHogLogs(
289
- mockInstance,
290
- resolveForTest(),
291
- logger,
292
- getContextFor(mockInstance),
293
- immediateOnReady
294
- )
295
- logs.captureLog({ body: 'before the reset' })
296
-
297
- const flushing = logs.flush()
298
- logs.clearQueue()
299
- logs.reset()
300
- logs.captureLog({ body: 'captured after the reset' })
301
-
302
- releaseSend({ kind: 'ok' })
303
- await flushing
304
-
305
- expect(readQueue(mockInstance).map((e) => e.record.body)).toEqual([{ stringValue: 'captured after the reset' }])
306
- })
307
-
308
- it('does not let a flush started after the reset run alongside the in-flight one', async () => {
309
- let releaseSend: (v: any) => void = () => {}
310
- const mockInstance = createMockInstance({
311
- _sendLogsBatch: vi.fn(() => new Promise((resolve) => (releaseSend = resolve))),
312
- })
313
- const logs = new PostHogLogs(
314
- mockInstance,
315
- resolveForTest(),
316
- logger,
317
- getContextFor(mockInstance),
318
- immediateOnReady
319
- )
320
- logs.captureLog({ body: 'before the reset' })
321
-
322
- const flushing = logs.flush()
323
- logs.clearQueue()
324
- logs.reset()
325
- logs.captureLog({ body: 'captured after the reset' })
326
- const second = logs.flush()
327
-
328
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
329
-
330
- releaseSend({ kind: 'ok' })
331
- await flushing
332
- await second
333
-
334
- expect(readQueue(mockInstance).map((e) => e.record.body)).toEqual([{ stringValue: 'captured after the reset' }])
335
- })
336
- })
337
-
338
- describe('captureLog', () => {
339
- it('writes a record to the logs queue via setPersistedProperty', () => {
340
- const logs = new PostHogLogs(
341
- mockInstance,
342
- resolveForTest(),
343
- logger,
344
- getContextFor(mockInstance),
345
- immediateOnReady
346
- )
347
- logs.captureLog({ body: 'hello world' })
348
-
349
- const queue = readQueue(mockInstance)
350
- expect(queue).toHaveLength(1)
351
- expect(queue[0].record.body).toEqual({ stringValue: 'hello world' })
352
- expect(mockInstance.setPersistedProperty).toHaveBeenCalledWith(
353
- PostHogPersistedProperty.LogsQueue,
354
- expect.any(Array)
355
- )
356
- })
357
-
358
- it('stamps a record from `capturedAt` rather than live state', () => {
359
- const logs = new PostHogLogs(
360
- mockInstance,
361
- resolveForTest(),
362
- logger,
363
- getContextFor(mockInstance),
364
- immediateOnReady
365
- )
366
- const occurredAtMs = Date.now() - 5000
367
-
368
- logs.captureLog(
369
- { body: 'buffered before identify' },
370
- { context: { distinctId: 'anon-1', sessionId: 'session-1' }, occurredAtMs }
371
- )
372
-
373
- const [{ record }] = readQueue(mockInstance)
374
- const attributes = Object.fromEntries(record.attributes.map((a: any) => [a.key, a.value.stringValue]))
375
- expect(attributes.posthogDistinctId).toBe('anon-1')
376
- expect(attributes.sessionId).toBe('session-1')
377
- expect(record.timeUnixNano).toBe(String(occurredAtMs) + '000000')
378
- expect(record.observedTimeUnixNano).toBe(record.timeUnixNano)
379
- })
380
-
381
- it('maps severity levels correctly', () => {
382
- const logs = new PostHogLogs(
383
- mockInstance,
384
- resolveForTest(),
385
- logger,
386
- getContextFor(mockInstance),
387
- immediateOnReady
388
- )
389
- logs.captureLog({ body: 'oh no', level: 'error' })
390
-
391
- const queue = readQueue(mockInstance)
392
- expect(queue[0].record.severityText).toBe('ERROR')
393
- expect(queue[0].record.severityNumber).toBe(17)
394
- })
395
-
396
- it('defaults to INFO when no level is provided', () => {
397
- const logs = new PostHogLogs(
398
- mockInstance,
399
- resolveForTest(),
400
- logger,
401
- getContextFor(mockInstance),
402
- immediateOnReady
403
- )
404
- logs.captureLog({ body: 'hello' })
405
-
406
- const queue = readQueue(mockInstance)
407
- expect(queue[0].record.severityText).toBe('INFO')
408
- })
409
-
410
- it('auto-populates distinctId and sessionId', () => {
411
- const logs = new PostHogLogs(
412
- mockInstance,
413
- resolveForTest(),
414
- logger,
415
- getContextFor(mockInstance),
416
- immediateOnReady
417
- )
418
- logs.captureLog({ body: 'test' })
419
-
420
- const queue = readQueue(mockInstance)
421
- const attrs = Object.fromEntries(queue[0].record.attributes.map((a: any) => [a.key, a.value]))
422
- expect(attrs['posthogDistinctId']).toEqual({ stringValue: 'user-123' })
423
- expect(attrs['sessionId']).toEqual({ stringValue: 'sess-456' })
424
- })
425
-
426
- it('merges user attributes over auto-populated ones', () => {
427
- const logs = new PostHogLogs(
428
- mockInstance,
429
- resolveForTest(),
430
- logger,
431
- getContextFor(mockInstance),
432
- immediateOnReady
433
- )
434
- logs.captureLog({ body: 'test', attributes: { posthogDistinctId: 'override' } })
435
-
436
- const queue = readQueue(mockInstance)
437
- const attrs = Object.fromEntries(queue[0].record.attributes.map((a: any) => [a.key, a.value]))
438
- expect(attrs['posthogDistinctId']).toEqual({ stringValue: 'override' })
439
- })
440
-
441
- it('is a no-op when body is empty', () => {
442
- const logs = new PostHogLogs(
443
- mockInstance,
444
- resolveForTest(),
445
- logger,
446
- getContextFor(mockInstance),
447
- immediateOnReady
448
- )
449
- logs.captureLog({ body: '' })
450
- expect(readQueue(mockInstance)).toHaveLength(0)
451
- expect(mockInstance.setPersistedProperty).not.toHaveBeenCalled()
452
- })
453
-
454
- it('is a no-op when body is missing', () => {
455
- const logs = new PostHogLogs(
456
- mockInstance,
457
- resolveForTest(),
458
- logger,
459
- getContextFor(mockInstance),
460
- immediateOnReady
461
- )
462
- logs.captureLog({} as any)
463
- expect(readQueue(mockInstance)).toHaveLength(0)
464
- })
465
-
466
- it('is a no-op when optedOut is true', () => {
467
- const instance = createMockInstance({ optedOut: true })
468
- const logs = new PostHogLogs(instance, resolveForTest(), logger, getContextFor(instance), immediateOnReady)
469
- logs.captureLog({ body: 'should be dropped' })
470
- expect(readQueue(instance)).toHaveLength(0)
471
- })
472
-
473
- it('captures unconditionally — only optedOut, missing body, and beforeSend can drop', () => {
474
- const logs = new PostHogLogs(
475
- mockInstance,
476
- resolveForTest(),
477
- logger,
478
- getContextFor(mockInstance),
479
- immediateOnReady
480
- )
481
- logs.captureLog({ body: 'kept' })
482
- expect(readQueue(mockInstance)).toHaveLength(1)
483
- })
484
-
485
- it('appends subsequent captures to the existing queue', () => {
486
- const logs = new PostHogLogs(
487
- mockInstance,
488
- resolveForTest(),
489
- logger,
490
- getContextFor(mockInstance),
491
- immediateOnReady
492
- )
493
- logs.captureLog({ body: 'first' })
494
- logs.captureLog({ body: 'second' })
495
- logs.captureLog({ body: 'third' })
496
-
497
- const queue = readQueue(mockInstance)
498
- expect(queue).toHaveLength(3)
499
- expect(queue[0].record.body.stringValue).toBe('first')
500
- expect(queue[1].record.body.stringValue).toBe('second')
501
- expect(queue[2].record.body.stringValue).toBe('third')
502
- })
503
-
504
- it('drops the oldest record when buffer overflows maxBufferSize', () => {
505
- const logs = new PostHogLogs(
506
- mockInstance,
507
- resolveForTest({ maxBufferSize: 3 }),
508
- logger,
509
- getContextFor(mockInstance),
510
- immediateOnReady
511
- )
512
-
513
- logs.captureLog({ body: 'one' })
514
- logs.captureLog({ body: 'two' })
515
- logs.captureLog({ body: 'three' })
516
- logs.captureLog({ body: 'four' })
517
-
518
- const queue = readQueue(mockInstance)
519
- expect(queue).toHaveLength(3)
520
- expect(queue.map((e) => e.record.body.stringValue)).toEqual(['two', 'three', 'four'])
521
- })
522
-
523
- it('holds a burst up to maxQueueSize, evicting only above it (flush trigger decoupled from eviction cap)', () => {
524
- // maxBufferSize triggers a flush at 2, but the async drain can't run mid-burst,
525
- // so the queue grows to the larger eviction cap (4) before the oldest is dropped.
526
- const logs = new PostHogLogs(
527
- mockInstance,
528
- resolveForTest({ maxBufferSize: 2, maxQueueSize: 4 }),
529
- logger,
530
- getContextFor(mockInstance),
531
- immediateOnReady
532
- )
533
-
534
- logs.captureLog({ body: 'one' })
535
- logs.captureLog({ body: 'two' })
536
- logs.captureLog({ body: 'three' })
537
- logs.captureLog({ body: 'four' })
538
- logs.captureLog({ body: 'five' })
539
-
540
- const queue = readQueue(mockInstance)
541
- // Grew past the flush trigger (2) to the eviction cap (4); only 'one' evicted.
542
- expect(queue.map((e) => e.record.body.stringValue)).toEqual(['two', 'three', 'four', 'five'])
543
- })
544
-
545
- it('clamps a maxQueueSize below maxBufferSize up to maxBufferSize (flush trigger always reachable)', () => {
546
- // A misconfigured eviction cap below the flush trigger would otherwise stop
547
- // the size-based flush from ever firing; it collapses to single-knob instead.
548
- const logs = new PostHogLogs(
549
- mockInstance,
550
- resolveForTest({ maxBufferSize: 3, maxQueueSize: 1 }),
551
- logger,
552
- getContextFor(mockInstance),
553
- immediateOnReady
554
- )
555
-
556
- logs.captureLog({ body: 'one' })
557
- logs.captureLog({ body: 'two' })
558
- logs.captureLog({ body: 'three' })
559
- logs.captureLog({ body: 'four' })
560
-
561
- const queue = readQueue(mockInstance)
562
- // Evicts at maxBufferSize (3), not the bogus maxQueueSize (1).
563
- expect(queue.map((e) => e.record.body.stringValue)).toEqual(['two', 'three', 'four'])
564
- })
565
-
566
- it('logs a diagnostic when evicting on overflow', () => {
567
- const logs = new PostHogLogs(
568
- mockInstance,
569
- resolveForTest({ maxBufferSize: 1 }),
570
- logger,
571
- getContextFor(mockInstance),
572
- immediateOnReady
573
- )
574
-
575
- logs.captureLog({ body: 'first' })
576
- logs.captureLog({ body: 'second' })
577
-
578
- expect(logger.info).toHaveBeenCalledWith('Logs queue is full, dropping oldest record.')
579
- })
580
-
581
- it('passes trace context through to the OTLP record', () => {
582
- const logs = new PostHogLogs(
583
- mockInstance,
584
- resolveForTest(),
585
- logger,
586
- getContextFor(mockInstance),
587
- immediateOnReady
588
- )
589
- logs.captureLog({
590
- body: 'trace test',
591
- trace_id: '4bf92f3577b34da6a3ce929d0e0e4736',
592
- span_id: '00f067aa0ba902b7',
593
- trace_flags: 1,
594
- })
595
-
596
- const queue = readQueue(mockInstance)
597
- expect(queue[0].record.traceId).toBe('4bf92f3577b34da6a3ce929d0e0e4736')
598
- expect(queue[0].record.spanId).toBe('00f067aa0ba902b7')
599
- expect(queue[0].record.flags).toBe(1)
600
- })
601
- })
602
-
603
- // captureLog routes deferred work through the injected onReady closure. These
604
- // tests exercise that contract by substituting a custom onReady.
605
- describe('init gating via onReady', () => {
606
- it('defers captures until onReady runs fn, then drains in order', () => {
607
- const pending: Array<() => void> = []
608
- const defer = (fn: () => void): void => {
609
- pending.push(fn)
610
- }
611
-
612
- mockInstance._store[PostHogPersistedProperty.LogsQueue] = [
613
- { record: { body: { stringValue: 'prior-session' } } as any },
614
- ]
615
-
616
- const logs = new PostHogLogs(mockInstance, resolveForTest(), logger, getContextFor(mockInstance), defer)
617
- logs.captureLog({ body: 'before-init' })
618
-
619
- expect(mockInstance.setPersistedProperty).not.toHaveBeenCalled()
620
-
621
- pending.forEach((fn) => fn())
622
-
623
- const queue = readQueue(mockInstance)
624
- expect(queue).toHaveLength(2)
625
- expect(queue[0].record.body.stringValue).toBe('prior-session')
626
- expect(queue[1].record.body.stringValue).toBe('before-init')
627
- })
628
-
629
- it('silently drops captures when onReady never invokes fn (rejected init)', () => {
630
- const neverReady = vi.fn(() => {
631
- /* simulate rejected init: fn is never called */
632
- })
633
- const logs = new PostHogLogs(mockInstance, resolveForTest(), logger, getContextFor(mockInstance), neverReady)
634
-
635
- logs.captureLog({ body: 'dropped' })
636
-
637
- expect(readQueue(mockInstance)).toHaveLength(0)
638
- expect(mockInstance.setPersistedProperty).not.toHaveBeenCalled()
639
- expect(neverReady).toHaveBeenCalledTimes(1)
640
- })
641
-
642
- it('builds record with capture-time context even when onReady defers drain', () => {
643
- const pending: Array<() => void> = []
644
- const defer = (fn: () => void): void => {
645
- pending.push(fn)
646
- }
647
- const instance = createMockInstance({
648
- getDistinctId: vi.fn().mockReturnValue('user-A'),
649
- })
650
-
651
- const logs = new PostHogLogs(instance, resolveForTest(), logger, getContextFor(instance), defer)
652
- logs.captureLog({ body: 'captured-as-user-A' })
653
-
654
- instance.getDistinctId = vi.fn().mockReturnValue('user-B')
655
-
656
- pending.forEach((fn) => fn())
657
-
658
- const queue = readQueue(instance)
659
- expect(queue).toHaveLength(1)
660
- const attrs = Object.fromEntries(queue[0].record.attributes.map((a: any) => [a.key, a.value]))
661
- expect(attrs['posthogDistinctId']).toEqual({ stringValue: 'user-A' })
662
- })
663
-
664
- it('captureLog does not throw to the caller', () => {
665
- const neverReady = (): void => {
666
- /* simulate rejected init */
667
- }
668
- const logs = new PostHogLogs(mockInstance, resolveForTest(), logger, getContextFor(mockInstance), neverReady)
669
-
670
- expect(() => logs.captureLog({ body: 'after-reject-1' })).not.toThrow()
671
- expect(() => logs.captureLog({ body: 'after-reject-2' })).not.toThrow()
672
- })
673
- })
674
-
675
- describe('flush', () => {
676
- it('is a no-op when the queue is empty', async () => {
677
- const logs = new PostHogLogs(
678
- mockInstance,
679
- resolveForTest(),
680
- logger,
681
- getContextFor(mockInstance),
682
- immediateOnReady
683
- )
684
- await logs.flush()
685
- expect(mockInstance._sendLogsBatch).not.toHaveBeenCalled()
686
- })
687
-
688
- it('drains the queue and sends an OTLP payload with resource + scope attrs', async () => {
689
- const logs = new PostHogLogs(
690
- mockInstance,
691
- resolveForTest({ serviceName: 'my-service', environment: 'prod', serviceVersion: '1.2.3' }),
692
- logger,
693
- getContextFor(mockInstance),
694
- immediateOnReady
695
- )
696
- logs.captureLog({ body: 'one' })
697
- logs.captureLog({ body: 'two' })
698
-
699
- await logs.flush()
700
-
701
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
702
- const payload = mockInstance._sendLogsBatch.mock.calls[0][0]
703
- const resourceAttrs = Object.fromEntries(
704
- payload.resourceLogs[0].resource.attributes.map((a: any) => [a.key, a.value])
705
- )
706
- expect(resourceAttrs['service.name']).toEqual({ stringValue: 'my-service' })
707
- expect(resourceAttrs['deployment.environment']).toEqual({ stringValue: 'prod' })
708
- expect(resourceAttrs['service.version']).toEqual({ stringValue: '1.2.3' })
709
- // OTLP-standard SDK identification — pulled from the instance's
710
- // getLibraryId/Version so every SDK self-identifies.
711
- expect(resourceAttrs['telemetry.sdk.name']).toEqual({ stringValue: 'posthog-core-tests' })
712
- expect(resourceAttrs['telemetry.sdk.version']).toEqual({ stringValue: '0.0.0-test' })
713
-
714
- const scope = payload.resourceLogs[0].scopeLogs[0].scope
715
- expect(scope).toEqual({ name: 'posthog-core-tests', version: '0.0.0-test' })
716
-
717
- const bodies = payload.resourceLogs[0].scopeLogs[0].logRecords.map((r: any) => r.body.stringValue)
718
- expect(bodies).toEqual(['one', 'two'])
719
-
720
- expect(readQueue(mockInstance)).toHaveLength(0)
721
- })
722
-
723
- it('uses the scopeName constructor param as the OTLP scope name', async () => {
724
- vi.useFakeTimers()
725
- const logs = new PostHogLogs(
726
- mockInstance,
727
- resolveForTest(),
728
- logger,
729
- getContextFor(mockInstance),
730
- immediateOnReady,
731
- () => Promise.resolve(),
732
- 'console'
733
- )
734
- logs.captureLog({ body: 'test' })
735
-
736
- await logs.flush()
737
-
738
- const payload = mockInstance._sendLogsBatch.mock.calls[0][0]
739
- const scope = payload.resourceLogs[0].scopeLogs[0].scope
740
- // scopeName param overrides getLibraryId(); telemetry.sdk.name still uses getLibraryId().
741
- expect(scope.name).toBe('console')
742
- const resourceAttrs = Object.fromEntries(
743
- payload.resourceLogs[0].resource.attributes.map((a: any) => [a.key, a.value])
744
- )
745
- expect(resourceAttrs['telemetry.sdk.name']).toEqual({ stringValue: 'posthog-core-tests' })
746
- vi.useRealTimers()
747
- })
748
-
749
- it('defaults service.name to "unknown_service" when not configured', async () => {
750
- const logs = new PostHogLogs(
751
- mockInstance,
752
- resolveForTest(),
753
- logger,
754
- getContextFor(mockInstance),
755
- immediateOnReady
756
- )
757
- logs.captureLog({ body: 'hi' })
758
- await logs.flush()
759
-
760
- const attrs = Object.fromEntries(
761
- mockInstance._sendLogsBatch.mock.calls[0][0].resourceLogs[0].resource.attributes.map((a: any) => [
762
- a.key,
763
- a.value,
764
- ])
765
- )
766
- expect(attrs['service.name']).toEqual({ stringValue: 'unknown_service' })
767
- })
768
-
769
- it('SDK-controlled telemetry.sdk.* and service.name win over user resourceAttributes', async () => {
770
- // Most logs backends index on these keys for routing, SDK-version
771
- // dashboards, and bug-correlation. Letting a stray user key clobber
772
- // them silently breaks ingestion attribution, so the layout puts
773
- // user attrs first and SDK identity attrs on top.
774
- const logs = new PostHogLogs(
775
- mockInstance,
776
- resolveForTest({
777
- resourceAttributes: {
778
- 'telemetry.sdk.name': 'my-wrapper',
779
- 'service.name': 'user-supplied-service',
780
- // Non-protected user keys still pass through.
781
- 'host.name': 'my-host',
782
- },
783
- }),
784
- logger,
785
- getContextFor(mockInstance),
786
- immediateOnReady
787
- )
788
- logs.captureLog({ body: 'hi' })
789
- await logs.flush()
790
-
791
- const attrs = Object.fromEntries(
792
- mockInstance._sendLogsBatch.mock.calls[0][0].resourceLogs[0].resource.attributes.map((a: any) => [
793
- a.key,
794
- a.value,
795
- ])
796
- )
797
- expect(attrs['telemetry.sdk.name']).toEqual({ stringValue: 'posthog-core-tests' })
798
- expect(attrs['telemetry.sdk.version']).toEqual({ stringValue: '0.0.0-test' })
799
- expect(attrs['service.name']).toEqual({ stringValue: 'unknown_service' })
800
- expect(attrs['host.name']).toEqual({ stringValue: 'my-host' })
801
- })
802
-
803
- it('splits a large queue into multiple batches of maxBatchRecordsPerPost and persists after each', async () => {
804
- const sendOrder: number[] = []
805
- let persistCallsBeforeSecondSend = 0
806
- mockInstance._sendLogsBatch = vi.fn(async (payload: any) => {
807
- // Record the persist count *at the start of* send #2. The first send
808
- // must have already persisted its queue advance by then — otherwise a
809
- // crash between sends could double-send the first batch.
810
- if (sendOrder.length === 1) {
811
- persistCallsBeforeSecondSend = mockInstance.setPersistedProperty.mock.calls.length
812
- }
813
- sendOrder.push(payload.resourceLogs[0].scopeLogs[0].logRecords.length)
814
- return { kind: 'ok' }
815
- })
816
- const logs = new PostHogLogs(
817
- mockInstance,
818
- resolveForTest({ maxBatchRecordsPerPost: 2, maxBufferSize: 10 }),
819
- logger,
820
- getContextFor(mockInstance),
821
- immediateOnReady
822
- )
823
- for (let i = 0; i < 5; i++) {
824
- logs.captureLog({ body: `msg-${i}` })
825
- }
826
-
827
- await logs.flush()
828
-
829
- // 2 + 2 + 1 = 5 records across 3 POSTs
830
- expect(sendOrder).toEqual([2, 2, 1])
831
- // After the first send, the queue must have been persisted before the second send —
832
- // otherwise a crash between sends could double-send the first batch.
833
- expect(persistCallsBeforeSecondSend).toBeGreaterThan(5 /* enqueue writes */)
834
- expect(readQueue(mockInstance)).toHaveLength(0)
835
- })
836
-
837
- it('halves maxBatchRecordsPerPost and retries the same records on too-large outcome', async () => {
838
- const sendSizes: number[] = []
839
- mockInstance._sendLogsBatch = vi.fn(async (payload: any) => {
840
- const size = payload.resourceLogs[0].scopeLogs[0].logRecords.length
841
- sendSizes.push(size)
842
- if (sendSizes.length === 1) {
843
- return { kind: 'too-large' }
844
- }
845
- return { kind: 'ok' }
846
- })
847
- const logs = new PostHogLogs(
848
- mockInstance,
849
- resolveForTest({ maxBatchRecordsPerPost: 4, maxBufferSize: 10 }),
850
- logger,
851
- getContextFor(mockInstance),
852
- immediateOnReady
853
- )
854
- for (let i = 0; i < 4; i++) {
855
- logs.captureLog({ body: `msg-${i}` })
856
- }
857
-
858
- await logs.flush()
859
-
860
- // First POST: 4 records → too-large. Retry with halved cap = 2, so: 2 + 2.
861
- expect(sendSizes).toEqual([4, 2, 2])
862
- expect(readQueue(mockInstance)).toHaveLength(0)
863
- })
864
-
865
- it('ramps maxBatchRecordsPerPost back toward the configured cap after a healthy streak', async () => {
866
- // Reproduces the Greptile P1 concern: a one-off oversized payload
867
- // should not permanently degrade throughput. After a 413 halves the
868
- // cap, each healthy send grows it back by 1 until the configured
869
- // maximum is reached.
870
- const sendSizes: number[] = []
871
- mockInstance._sendLogsBatch = vi.fn(async (payload: any) => {
872
- const size = payload.resourceLogs[0].scopeLogs[0].logRecords.length
873
- sendSizes.push(size)
874
- // First POST is rejected as too-large; everything else succeeds.
875
- if (sendSizes.length === 1) {
876
- return { kind: 'too-large' }
877
- }
878
- return { kind: 'ok' }
879
- })
880
- const logs = new PostHogLogs(
881
- mockInstance,
882
- resolveForTest({ maxBatchRecordsPerPost: 4, maxBufferSize: 100 }),
883
- logger,
884
- getContextFor(mockInstance),
885
- immediateOnReady
886
- )
887
- // Enqueue plenty so the recovery has room to ramp.
888
- for (let i = 0; i < 16; i++) {
889
- logs.captureLog({ body: `msg-${i}` })
890
- }
891
-
892
- await logs.flush()
893
-
894
- // First POST: 4 records → too-large. Cap halves to 2. From there each
895
- // healthy send grows the cap by 1 toward the configured 4:
896
- // sizes: [4 (413), 2, 3, 4, 4, ...] (the trailing 3 drains the
897
- // remainder of the 16-record queue).
898
- expect(sendSizes).toEqual([4, 2, 3, 4, 4, 3])
899
- expect(readQueue(mockInstance)).toHaveLength(0)
900
- })
901
-
902
- it('drops the only record when too-large arrives on a batch of size 1', async () => {
903
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve({ kind: 'too-large' }))
904
- const logs = new PostHogLogs(
905
- mockInstance,
906
- resolveForTest({ maxBatchRecordsPerPost: 1 }),
907
- logger,
908
- getContextFor(mockInstance),
909
- immediateOnReady
910
- )
911
- logs.captureLog({ body: 'too-big' })
912
-
913
- await logs.flush()
914
-
915
- // Batch of 1 that's rejected as too-large is permanent — drop it rather
916
- // than spin on the same record forever.
917
- expect(readQueue(mockInstance)).toHaveLength(0)
918
- })
919
-
920
- it('warns explicitly when dropping a size-1 413 (visibility for the lost record)', async () => {
921
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve({ kind: 'too-large' }))
922
- const logs = new PostHogLogs(
923
- mockInstance,
924
- resolveForTest({ maxBatchRecordsPerPost: 1 }),
925
- logger,
926
- getContextFor(mockInstance),
927
- immediateOnReady
928
- )
929
- logs.captureLog({ body: 'oversized' })
930
- await logs.flush()
931
-
932
- expect(logger.warn).toHaveBeenCalledWith(
933
- expect.stringContaining('Dropping a single log record with batch size 1')
934
- )
935
- })
936
-
937
- it('keeps draining the queue after a size-1 413 drop (one bad record does not stall the pipeline)', async () => {
938
- // First record returns too-large with size 1 (drops and warns), then
939
- // the rest of the queue should continue flushing normally.
940
- let callCount = 0
941
- mockInstance._sendLogsBatch = vi.fn(() => {
942
- callCount++
943
- return Promise.resolve(callCount === 1 ? { kind: 'too-large' } : { kind: 'ok' })
944
- })
945
- const logs = new PostHogLogs(
946
- mockInstance,
947
- resolveForTest({ maxBatchRecordsPerPost: 1, maxBufferSize: 10 }),
948
- logger,
949
- getContextFor(mockInstance),
950
- immediateOnReady
951
- )
952
- logs.captureLog({ body: 'oversized' })
953
- logs.captureLog({ body: 'ok-1' })
954
- logs.captureLog({ body: 'ok-2' })
955
-
956
- await logs.flush()
957
-
958
- // Three sends: oversized (dropped), ok-1, ok-2. Queue is empty.
959
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(3)
960
- expect(readQueue(mockInstance)).toHaveLength(0)
961
- })
962
-
963
- it('size-1 413 retry-shrink path: starts at maxBatchRecordsPerPost, halves to 1, drops at 1', async () => {
964
- // Realistic flow: batch=N gets too-large, halves to N/2, halves to 1,
965
- // then 413 on size 1 is the permanent drop. Verifies the cap actually
966
- // shrinks all the way down before the size-1 drop fires.
967
- const sendSizes: number[] = []
968
- mockInstance._sendLogsBatch = vi.fn(async (payload: any) => {
969
- const size = payload.resourceLogs[0].scopeLogs[0].logRecords.length
970
- sendSizes.push(size)
971
- return { kind: 'too-large' }
972
- })
973
- const logs = new PostHogLogs(
974
- mockInstance,
975
- resolveForTest({ maxBatchRecordsPerPost: 4, maxBufferSize: 10 }),
976
- logger,
977
- getContextFor(mockInstance),
978
- immediateOnReady
979
- )
980
- // Single oversized record. With maxBatchRecordsPerPost=4 but only 1 record
981
- // in the queue, the first send is size 1 — going straight to the drop path.
982
- logs.captureLog({ body: 'huge' })
983
-
984
- await logs.flush()
985
-
986
- // Single send of size 1, dropped immediately (no halving rounds because
987
- // batch was already at 1).
988
- expect(sendSizes).toEqual([1])
989
- expect(readQueue(mockInstance)).toHaveLength(0)
990
- expect(logger.warn).toHaveBeenCalledWith(
991
- expect.stringContaining('Dropping a single log record with batch size 1')
992
- )
993
- })
994
-
995
- it('keeps records in the queue on retry-later outcome and re-throws the carried error', async () => {
996
- const netErr = new Error('offline')
997
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve({ kind: 'retry-later', error: netErr }))
998
- const logs = new PostHogLogs(
999
- mockInstance,
1000
- resolveForTest(),
1001
- logger,
1002
- getContextFor(mockInstance),
1003
- immediateOnReady
1004
- )
1005
- logs.captureLog({ body: 'queued' })
1006
-
1007
- await expect(logs.flush()).rejects.toBe(netErr)
1008
-
1009
- expect(readQueue(mockInstance)).toHaveLength(1)
1010
- })
1011
-
1012
- it('drops the batch on fatal outcome and re-throws the carried error', async () => {
1013
- const bogus = new Error('malformed')
1014
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve({ kind: 'fatal', error: bogus }))
1015
- const logs = new PostHogLogs(
1016
- mockInstance,
1017
- resolveForTest(),
1018
- logger,
1019
- getContextFor(mockInstance),
1020
- immediateOnReady
1021
- )
1022
- logs.captureLog({ body: 'doomed' })
1023
-
1024
- await expect(logs.flush()).rejects.toBe(bogus)
1025
-
1026
- expect(readQueue(mockInstance)).toHaveLength(0)
1027
- })
1028
-
1029
- it('awaits _waitForStoragePersist between batches so a crash can’t replay records', async () => {
1030
- const sequence: string[] = []
1031
- mockInstance._sendLogsBatch = vi.fn(async (payload: any) => {
1032
- sequence.push(`send:${payload.resourceLogs[0].scopeLogs[0].logRecords.length}`)
1033
- return { kind: 'ok' }
1034
- })
1035
- const waitForStoragePersist = vi.fn(async () => {
1036
- sequence.push('waitForPersist')
1037
- })
1038
- const logs = new PostHogLogs(
1039
- mockInstance,
1040
- resolveForTest({ maxBatchRecordsPerPost: 2, maxBufferSize: 10 }),
1041
- logger,
1042
- getContextFor(mockInstance),
1043
- immediateOnReady,
1044
- waitForStoragePersist
1045
- )
1046
- for (let i = 0; i < 3; i++) {
1047
- logs.captureLog({ body: `msg-${i}` })
1048
- }
1049
-
1050
- await logs.flush()
1051
-
1052
- // Send 2 → waitForPersist → send 1 → waitForPersist. If the wait
1053
- // landed out-of-order (e.g. before send), a crash mid-batch could
1054
- // replay records on the next startup.
1055
- expect(sequence).toEqual(['send:2', 'waitForPersist', 'send:1', 'waitForPersist'])
1056
- expect(waitForStoragePersist).toHaveBeenCalledTimes(2)
1057
- })
1058
-
1059
- it('serializes concurrent flush calls rather than racing them', async () => {
1060
- let resolveFirst: (v: any) => void = () => {}
1061
- mockInstance._sendLogsBatch = vi.fn(
1062
- () =>
1063
- new Promise((r) => {
1064
- resolveFirst = r
1065
- })
1066
- )
1067
- const logs = new PostHogLogs(
1068
- mockInstance,
1069
- resolveForTest(),
1070
- logger,
1071
- getContextFor(mockInstance),
1072
- immediateOnReady
1073
- )
1074
- logs.captureLog({ body: 'a' })
1075
-
1076
- const first = logs.flush()
1077
- const second = logs.flush()
1078
-
1079
- // Both callers observe the same in-flight promise, so only one POST happens.
1080
- resolveFirst({ kind: 'ok' })
1081
- await Promise.all([first, second])
1082
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1083
- })
1084
- })
1085
-
1086
- describe('flush triggers', () => {
1087
- beforeEach(() => vi.useFakeTimers())
1088
- afterEach(() => vi.useRealTimers())
1089
-
1090
- it('fires a flush when the buffer hits maxBufferSize', () => {
1091
- const logs = new PostHogLogs(
1092
- mockInstance,
1093
- resolveForTest({ maxBufferSize: 3 }),
1094
- logger,
1095
- getContextFor(mockInstance),
1096
- immediateOnReady
1097
- )
1098
- logs.captureLog({ body: 'a' })
1099
- logs.captureLog({ body: 'b' })
1100
- expect(mockInstance._sendLogsBatch).not.toHaveBeenCalled()
1101
-
1102
- logs.captureLog({ body: 'c' })
1103
- // Threshold trigger fires `flush()` fire-and-forget; the call happens
1104
- // synchronously on the hot path.
1105
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1106
- })
1107
-
1108
- it('schedules one timer per idle window and fires flush on expiry', () => {
1109
- const logs = new PostHogLogs(
1110
- mockInstance,
1111
- resolveForTest({ flushIntervalMs: 5000 }),
1112
- logger,
1113
- getContextFor(mockInstance),
1114
- immediateOnReady
1115
- )
1116
- logs.captureLog({ body: 'first' })
1117
- logs.captureLog({ body: 'second' })
1118
- logs.captureLog({ body: 'third' })
1119
-
1120
- // Only one timer armed, not three — subsequent enqueues inside the
1121
- // window must not push the flush out.
1122
- expect(mockInstance._sendLogsBatch).not.toHaveBeenCalled()
1123
- vi.advanceTimersByTime(4999)
1124
- expect(mockInstance._sendLogsBatch).not.toHaveBeenCalled()
1125
- vi.advanceTimersByTime(1)
1126
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1127
- })
1128
-
1129
- it('does not schedule a timer for the threshold-triggered path', () => {
1130
- const logs = new PostHogLogs(
1131
- mockInstance,
1132
- resolveForTest({ maxBufferSize: 2, flushIntervalMs: 5000 }),
1133
- logger,
1134
- getContextFor(mockInstance),
1135
- immediateOnReady
1136
- )
1137
- logs.captureLog({ body: 'a' })
1138
- logs.captureLog({ body: 'b' })
1139
- // Threshold path flushed already; advancing time must not trigger a second send.
1140
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1141
- vi.advanceTimersByTime(5000)
1142
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1143
- })
1144
-
1145
- it('re-arms the timer after a failed flush so a retry happens without a new capture', async () => {
1146
- // First flush fails (retry-later keeps the records); the second succeeds.
1147
- mockInstance._sendLogsBatch = vi
1148
- .fn()
1149
- .mockResolvedValueOnce({ kind: 'retry-later', error: new Error('net') })
1150
- .mockResolvedValueOnce({ kind: 'ok' })
1151
-
1152
- const logs = new PostHogLogs(
1153
- mockInstance,
1154
- resolveForTest({ flushIntervalMs: 5000 }),
1155
- logger,
1156
- getContextFor(mockInstance),
1157
- immediateOnReady
1158
- )
1159
- logs.captureLog({ body: 'retry-me' })
1160
-
1161
- // First timer fires → flush #1 → retry-later → record retained, timer re-armed.
1162
- await vi.advanceTimersByTimeAsync(5000)
1163
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1164
- expect(readQueue(mockInstance)).toHaveLength(1)
1165
-
1166
- // No new capture: the re-armed timer alone fires the retry, which drains.
1167
- await vi.advanceTimersByTimeAsync(5000)
1168
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1169
- expect(readQueue(mockInstance)).toHaveLength(0)
1170
- })
1171
-
1172
- it('waits out Retry-After even when a capture re-arms the timer mid-flush', async () => {
1173
- // The capture that lands while the send is in flight arms a timer at the
1174
- // plain interval; the 429 then asks for far longer. The earlier timer must
1175
- // not fire first, or the SDK sends inside the window it was told to skip.
1176
- mockInstance._sendLogsBatch = vi.fn(async () => {
1177
- logs.captureLog({ body: 'arrived mid-flush' })
1178
- return { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 }
1179
- })
1180
-
1181
- const logs = new PostHogLogs(
1182
- mockInstance,
1183
- resolveForTest({ flushIntervalMs: 5000 }),
1184
- logger,
1185
- getContextFor(mockInstance),
1186
- immediateOnReady
1187
- )
1188
- logs.captureLog({ body: 'first' })
1189
-
1190
- await vi.advanceTimersByTimeAsync(5000)
1191
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1192
-
1193
- await vi.advanceTimersByTimeAsync(6000)
1194
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1195
-
1196
- await vi.advanceTimersByTimeAsync(300_000)
1197
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1198
- })
1199
-
1200
- it('does not let the size trigger send inside a Retry-After window', async () => {
1201
- mockInstance._sendLogsBatch = vi.fn(() =>
1202
- Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
1203
- )
1204
- const logs = new PostHogLogs(
1205
- mockInstance,
1206
- resolveForTest({ flushIntervalMs: 1000, maxBufferSize: 2 }),
1207
- logger,
1208
- getContextFor(mockInstance),
1209
- immediateOnReady
1210
- )
1211
- logs.captureLog({ body: 'first' })
1212
- await vi.advanceTimersByTimeAsync(1000)
1213
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1214
-
1215
- // Enough records to trip the size trigger, well inside the window.
1216
- logs.captureLog({ body: 'second' })
1217
- logs.captureLog({ body: 'third' })
1218
- await vi.advanceTimersByTimeAsync(1000)
1219
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1220
-
1221
- await vi.advanceTimersByTimeAsync(300_000)
1222
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1223
- })
1224
-
1225
- it('does not let onReconnect send inside a Retry-After window', async () => {
1226
- // `online` fires on every network handover; it says nothing about the
1227
- // rate-limit window the endpoint set.
1228
- mockInstance._sendLogsBatch = vi.fn(() =>
1229
- Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
1230
- )
1231
- const logs = new PostHogLogs(
1232
- mockInstance,
1233
- resolveForTest({ flushIntervalMs: 1000 }),
1234
- logger,
1235
- getContextFor(mockInstance),
1236
- immediateOnReady
1237
- )
1238
- logs.captureLog({ body: 'first' })
1239
- await vi.advanceTimersByTimeAsync(1000)
1240
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1241
-
1242
- logs.onReconnect()
1243
- await vi.advanceTimersByTimeAsync(1000)
1244
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1245
- })
1246
-
1247
- it('flushes on reconnect once the Retry-After window has passed', async () => {
1248
- const outcomes: any[] = [{ kind: 'retry-later', error: new Error('429'), retryAfterMs: 5000 }]
1249
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve(outcomes.shift() ?? { kind: 'ok' }))
1250
- const logs = new PostHogLogs(
1251
- mockInstance,
1252
- resolveForTest({ flushIntervalMs: 1000 }),
1253
- logger,
1254
- getContextFor(mockInstance),
1255
- immediateOnReady
1256
- )
1257
- logs.captureLog({ body: 'first' })
1258
- await vi.advanceTimersByTimeAsync(1000)
1259
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1260
-
1261
- // Stop just short of the deadline, then cross it without letting the
1262
- // re-armed timer fire — otherwise the timer satisfies the assertion and
1263
- // the test says nothing about onReconnect.
1264
- await vi.advanceTimersByTimeAsync(4999)
1265
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1266
- vi.setSystemTime(Date.now() + 2)
1267
-
1268
- logs.onReconnect()
1269
- await vi.advanceTimersByTimeAsync(1)
1270
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1271
- })
1272
-
1273
- it('does not let a capture after an explicit flush send inside the window', async () => {
1274
- // `flush()` is the lifecycle path (RN foreground/background, shutdown).
1275
- // It leaves no timer behind, so the next capture is the one that arms
1276
- // one — at the plain interval unless the window floors it.
1277
- mockInstance._sendLogsBatch = vi.fn(() =>
1278
- Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
1279
- )
1280
- const logs = new PostHogLogs(
1281
- mockInstance,
1282
- resolveForTest({ flushIntervalMs: 5000 }),
1283
- logger,
1284
- getContextFor(mockInstance),
1285
- immediateOnReady
1286
- )
1287
- logs.captureLog({ body: 'first' })
1288
- await logs.flush().catch(() => {})
1289
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1290
-
1291
- logs.captureLog({ body: 'second' })
1292
- await vi.advanceTimersByTimeAsync(5000)
1293
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1294
-
1295
- await vi.advanceTimersByTimeAsync(295_000)
1296
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1297
- })
1298
-
1299
- it('does not let a capture during an explicit flush send inside the window', async () => {
1300
- // The sibling case covers a capture *after* the flush settles. This one
1301
- // lands while the send is in flight, so it arms the timer at the plain
1302
- // interval before the window exists.
1303
- let release: (v: any) => void = () => {}
1304
- mockInstance._sendLogsBatch = vi.fn(
1305
- () =>
1306
- new Promise((resolve) => {
1307
- release = resolve
1308
- })
1309
- )
1310
- const logs = new PostHogLogs(
1311
- mockInstance,
1312
- resolveForTest({ flushIntervalMs: 5000 }),
1313
- logger,
1314
- getContextFor(mockInstance),
1315
- immediateOnReady
1316
- )
1317
- logs.captureLog({ body: 'first' })
1318
- const flushed = logs.flush().catch(() => {})
1319
- await vi.advanceTimersByTimeAsync(0)
1320
-
1321
- logs.captureLog({ body: 'second' })
1322
- release({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
1323
- await flushed
1324
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1325
-
1326
- await vi.advanceTimersByTimeAsync(5000)
1327
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1328
- })
1329
-
1330
- it('arms a timer when onReconnect lands inside the window after an explicit flush', async () => {
1331
- // `flush()` leaves no timer behind, so returning early here without
1332
- // arming one leaves the records with nothing scheduled at all.
1333
- mockInstance._sendLogsBatch = vi.fn(() =>
1334
- Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
1335
- )
1336
- const logs = new PostHogLogs(
1337
- mockInstance,
1338
- resolveForTest({ flushIntervalMs: 10_000 }),
1339
- logger,
1340
- getContextFor(mockInstance),
1341
- immediateOnReady
1342
- )
1343
- logs.captureLog({ body: 'first' })
1344
- await logs.flush().catch(() => {})
1345
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1346
-
1347
- await vi.advanceTimersByTimeAsync(10_000)
1348
- logs.onReconnect()
1349
-
1350
- await vi.advanceTimersByTimeAsync(289_000)
1351
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1352
- await vi.advanceTimersByTimeAsync(2000)
1353
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1354
- })
1355
-
1356
- it('releases a record captured mid-flush once that flush closes the window', async () => {
1357
- // The capture arms against the window that was open when it landed; the
1358
- // outcome then closes that window, so the timer has to come back down.
1359
- const logs = new PostHogLogs(
1360
- mockInstance,
1361
- resolveForTest({ flushIntervalMs: 10_000 }),
1362
- logger,
1363
- getContextFor(mockInstance),
1364
- immediateOnReady
1365
- )
1366
- let sends = 0
1367
- mockInstance._sendLogsBatch = vi.fn(async () => {
1368
- sends += 1
1369
- if (sends === 1) {
1370
- return { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 }
1371
- }
1372
- await Promise.resolve()
1373
- if (sends === 2) {
1374
- logs.captureLog({ body: 'mid' })
1375
- }
1376
- return { kind: 'ok' }
1377
- })
1378
-
1379
- logs.captureLog({ body: 'first' })
1380
- await vi.advanceTimersByTimeAsync(10_000)
1381
- await logs.flush().catch(() => {})
1382
-
1383
- await vi.advanceTimersByTimeAsync(10_000)
1384
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(3)
1385
- })
1386
-
1387
- it('keeps the Retry-After window when a batch is refused for size', async () => {
1388
- // `too-large` is a verdict on the body's size — the SDK's own or a 413 —
1389
- // so it says nothing about the endpoint's rate limit and must not end the
1390
- // wait.
1391
- const outcomes: any[] = [{ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 }]
1392
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve(outcomes.shift() ?? { kind: 'too-large' }))
1393
- const logs = new PostHogLogs(
1394
- mockInstance,
1395
- resolveForTest({ flushIntervalMs: 1000, maxBatchRecordsPerPost: 1 }),
1396
- logger,
1397
- getContextFor(mockInstance),
1398
- immediateOnReady
1399
- )
1400
- logs.captureLog({ body: 'first' })
1401
- await vi.advanceTimersByTimeAsync(1000)
1402
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1403
-
1404
- // A batch of one the endpoint cannot accept: the record is dropped.
1405
- await logs.flush()
1406
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1407
-
1408
- logs.captureLog({ body: 'second' })
1409
- logs.onReconnect()
1410
- await vi.advanceTimersByTimeAsync(1000)
1411
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1412
- })
1413
-
1414
- it('ends the window when an explicit flush succeeds', async () => {
1415
- // The endpoint just accepted a batch, so the wait it asked for earlier is
1416
- // over — the gated paths must not stay blocked for the rest of it.
1417
- const outcomes: any[] = [{ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 }]
1418
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve(outcomes.shift() ?? { kind: 'ok' }))
1419
- const logs = new PostHogLogs(
1420
- mockInstance,
1421
- resolveForTest({ flushIntervalMs: 5000, maxBufferSize: 2 }),
1422
- logger,
1423
- getContextFor(mockInstance),
1424
- immediateOnReady
1425
- )
1426
- logs.captureLog({ body: 'first' })
1427
- await vi.advanceTimersByTimeAsync(5000)
1428
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1429
-
1430
- await logs.flush()
1431
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1432
-
1433
- logs.captureLog({ body: 'second' })
1434
- logs.onReconnect()
1435
- await vi.advanceTimersByTimeAsync(1)
1436
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(3)
1437
- })
1438
-
1439
- it('drops a Retry-After wait on reset', async () => {
1440
- const outcomes: any[] = [{ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 }]
1441
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve(outcomes.shift() ?? { kind: 'ok' }))
1442
- const logs = new PostHogLogs(
1443
- mockInstance,
1444
- resolveForTest({ flushIntervalMs: 1000 }),
1445
- logger,
1446
- getContextFor(mockInstance),
1447
- immediateOnReady
1448
- )
1449
- logs.captureLog({ body: 'first' })
1450
- await vi.advanceTimersByTimeAsync(1000)
1451
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1452
-
1453
- // Asserted through a gated path: a plain capture would flush either way.
1454
- logs.reset()
1455
- logs.captureLog({ body: 'second' })
1456
- logs.onReconnect()
1457
- await vi.advanceTimersByTimeAsync(1)
1458
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1459
- })
1460
-
1461
- it('keeps its own backoff when the endpoint asks for less', async () => {
1462
- // A proxy answering `Retry-After: 1` must not turn the retry into a
1463
- // one-second hot loop against an endpoint already refusing traffic.
1464
- mockInstance._sendLogsBatch = vi.fn(() =>
1465
- Promise.resolve({ kind: 'retry-later', error: new Error('503'), retryAfterMs: 10 })
1466
- )
1467
- const logs = new PostHogLogs(
1468
- mockInstance,
1469
- resolveForTest({ flushIntervalMs: 5000 }),
1470
- logger,
1471
- getContextFor(mockInstance),
1472
- immediateOnReady
1473
- )
1474
- logs.captureLog({ body: 'first' })
1475
- await vi.advanceTimersByTimeAsync(5000)
1476
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1477
-
1478
- await vi.advanceTimersByTimeAsync(1000)
1479
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1480
-
1481
- await vi.advanceTimersByTimeAsync(5000)
1482
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1483
- })
1484
-
1485
- it('does not restart a served-out wait for a capture during the retry', async () => {
1486
- // A deadline, not a duration. The retry's timer has already fired, so the
1487
- // capture below arms the next one — and it sees the wait still set,
1488
- // because the send it belongs to has not settled. Holding a duration here
1489
- // re-arms for the whole window again and leaves the record 300s behind an
1490
- // endpoint that has already recovered.
1491
- let settle: ((outcome: any) => void) | undefined
1492
- let call = 0
1493
- mockInstance._sendLogsBatch = vi.fn(() => {
1494
- call++
1495
- if (call === 1) {
1496
- return Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
1497
- }
1498
- return new Promise((resolve) => {
1499
- settle = resolve
1500
- })
1501
- })
1502
- const logs = new PostHogLogs(
1503
- mockInstance,
1504
- resolveForTest({ flushIntervalMs: 5000 }),
1505
- logger,
1506
- getContextFor(mockInstance),
1507
- immediateOnReady
1508
- )
1509
- logs.captureLog({ body: 'first' })
1510
- await vi.advanceTimersByTimeAsync(5000)
1511
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1512
-
1513
- // The wait elapses and the retry goes out, but hangs.
1514
- await vi.advanceTimersByTimeAsync(300_000)
1515
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1516
-
1517
- logs.captureLog({ body: 'second' })
1518
- settle?.({ kind: 'ok' })
1519
- await vi.advanceTimersByTimeAsync(0)
1520
-
1521
- // One interval, not another window.
1522
- await vi.advanceTimersByTimeAsync(5000)
1523
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(3)
1524
- })
1525
-
1526
- it('closes the window at the ceiling for a host out-pacing it', async () => {
1527
- // RN takes flush() on every app-state transition, and each refusal pushes
1528
- // the deadline out. The ceiling is what stops the gated paths — the size
1529
- // trigger and onReconnect — from being suppressed for good.
1530
- mockInstance._sendLogsBatch = vi.fn(() =>
1531
- Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 30_000 })
1532
- )
1533
- const logs = new PostHogLogs(
1534
- mockInstance,
1535
- resolveForTest({ flushIntervalMs: 60_000 }),
1536
- logger,
1537
- getContextFor(mockInstance),
1538
- immediateOnReady
1539
- )
1540
- logs.captureLog({ body: 'first' })
1541
- await logs.flush().catch(() => {})
1542
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1543
-
1544
- // Lifecycle flushes every 5s against a 30s window, for longer than the
1545
- // 5-minute ceiling. Sampled rather than asserted through onReconnect:
1546
- // whether a given moment falls inside a window is timing-dependent, but
1547
- // past the ceiling it must fall outside one.
1548
- let sawWindowClosed = false
1549
- for (let i = 0; i < 70; i++) {
1550
- await vi.advanceTimersByTimeAsync(5000)
1551
- // Sampled before the flush: a flush that finds the window closed opens
1552
- // a fresh one, so sampling after it would always look open.
1553
- if ((logs as any)._retryAfter.remainingMs() === 0) {
1554
- sawWindowClosed = true
1555
- }
1556
- logs.captureLog({ body: `line ${i}` })
1557
- await logs.flush().catch(() => {})
1558
- }
1559
- expect(sawWindowClosed).toBe(true)
1560
- })
1561
-
1562
- it('keeps flushing after a backward clock step', async () => {
1563
- const outcomes: any[] = [{ kind: 'retry-later', error: new Error('429'), retryAfterMs: 60_000 }]
1564
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve(outcomes.shift() ?? { kind: 'ok' }))
1565
- const logs = new PostHogLogs(
1566
- mockInstance,
1567
- resolveForTest({ flushIntervalMs: 1000, maxBufferSize: 2 }),
1568
- logger,
1569
- getContextFor(mockInstance),
1570
- immediateOnReady
1571
- )
1572
- logs.captureLog({ body: 'first' })
1573
- await vi.advanceTimersByTimeAsync(1000)
1574
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1575
-
1576
- const real = Date.now()
1577
- vi.spyOn(Date, 'now').mockImplementation(() => real - 3_600_000)
1578
-
1579
- // A gated path: suppressed for the size of the step without the guard.
1580
- logs.captureLog({ body: 'second' })
1581
- logs.onReconnect()
1582
- await vi.advanceTimersByTimeAsync(1)
1583
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1584
- })
1585
-
1586
- it('ends the wait when a later failure names none', async () => {
1587
- // 429 with a window, then a plain 503: the queue drops back to its own
1588
- // backoff rather than waiting the old window out on every attempt.
1589
- const outcomes: any[] = [
1590
- { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 },
1591
- { kind: 'retry-later', error: new Error('503') },
1592
- ]
1593
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve(outcomes.shift() ?? { kind: 'ok' }))
1594
- const logs = new PostHogLogs(
1595
- mockInstance,
1596
- resolveForTest({ flushIntervalMs: 1000 }),
1597
- logger,
1598
- getContextFor(mockInstance),
1599
- immediateOnReady
1600
- )
1601
- logs.captureLog({ body: 'first' })
1602
- await vi.advanceTimersByTimeAsync(1000)
1603
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1604
-
1605
- await vi.advanceTimersByTimeAsync(300_000)
1606
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1607
-
1608
- // Back on the plain backoff, not another 300s.
1609
- await vi.advanceTimersByTimeAsync(4000)
1610
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(3)
1611
- })
1612
-
1613
- it('keeps flushing on the interval while captures keep arriving', async () => {
1614
- // Every capture arms the timer. Re-arming a pending one would push the
1615
- // flush out for as long as logs keep coming, stranding a steady stream
1616
- // that never reaches the size trigger.
1617
- const logs = new PostHogLogs(
1618
- mockInstance,
1619
- resolveForTest({ flushIntervalMs: 10_000, maxBufferSize: 100 }),
1620
- logger,
1621
- getContextFor(mockInstance),
1622
- immediateOnReady
1623
- )
1624
-
1625
- for (let i = 0; i < 30; i++) {
1626
- logs.captureLog({ body: `line ${i}` })
1627
- await vi.advanceTimersByTimeAsync(2000)
1628
- }
1629
-
1630
- expect(mockInstance._sendLogsBatch).toHaveBeenCalled()
1631
- expect(readQueue(mockInstance)).toHaveLength(0)
1632
- })
1633
-
1634
- it('stops re-arming once the queue is empty', async () => {
1635
- const logs = new PostHogLogs(
1636
- mockInstance,
1637
- resolveForTest({ flushIntervalMs: 5000 }),
1638
- logger,
1639
- getContextFor(mockInstance),
1640
- immediateOnReady
1641
- )
1642
- logs.captureLog({ body: 'one' })
1643
-
1644
- await vi.advanceTimersByTimeAsync(5000)
1645
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1646
- expect(readQueue(mockInstance)).toHaveLength(0)
1647
-
1648
- // Successful drain leaves nothing queued, so no further timer should fire.
1649
- await vi.advanceTimersByTimeAsync(20000)
1650
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1651
- })
1652
-
1653
- it('caps the retry delay at 30s however long the outage runs', async () => {
1654
- // The logs contract states the backoff as capped at ~30s. Without the cap
1655
- // a 5s interval reaches 320s after six doublings.
1656
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve({ kind: 'retry-later', error: new Error('down') }))
1657
- const logs = new PostHogLogs(
1658
- mockInstance,
1659
- resolveForTest({ flushIntervalMs: 5000 }),
1660
- logger,
1661
- getContextFor(mockInstance),
1662
- immediateOnReady
1663
- )
1664
- logs.captureLog({ body: 'retry-me' })
1665
-
1666
- // Ten failures, well past the six doublings the exponent allows.
1667
- for (let i = 0; i < 10; i++) {
1668
- await vi.advanceTimersByTimeAsync(30_000)
1669
- }
1670
- // Capped, the delay settles at 30s and 300s of outage buys ten retries on
1671
- // top of the two the first doublings allow. Uncapped it reaches 320s and
1672
- // buys six attempts in total, so the difference is not a rounding one.
1673
- expect(mockInstance._sendLogsBatch.mock.calls.length).toBeGreaterThanOrEqual(11)
1674
- })
1675
-
1676
- it('backs off exponentially across consecutive failed flushes', async () => {
1677
- // Every flush fails, so the record stays queued and the retry interval grows:
1678
- // base (initial), base (1st retry), 2x, 4x, ...
1679
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve({ kind: 'retry-later', error: new Error('down') }))
1680
- const base = 1000
1681
- const logs = new PostHogLogs(
1682
- mockInstance,
1683
- resolveForTest({ flushIntervalMs: base }),
1684
- logger,
1685
- getContextFor(mockInstance),
1686
- immediateOnReady
1687
- )
1688
- logs.captureLog({ body: 'x' })
1689
-
1690
- await vi.advanceTimersByTimeAsync(base) // initial timer → attempt #1
1691
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1692
- await vi.advanceTimersByTimeAsync(base) // 1st retry still at base → attempt #2
1693
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1694
-
1695
- // Now backoff: next retry is 2x base — base alone must not fire it.
1696
- await vi.advanceTimersByTimeAsync(base)
1697
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1698
- await vi.advanceTimersByTimeAsync(base) // 2x base elapsed → attempt #3
1699
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(3)
1700
-
1701
- // Next retry is 4x base.
1702
- await vi.advanceTimersByTimeAsync(2 * base)
1703
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(3)
1704
- await vi.advanceTimersByTimeAsync(2 * base) // 4x base elapsed → attempt #4
1705
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(4)
1706
- })
1707
-
1708
- it('resets the backoff after a successful flush', async () => {
1709
- let shouldFail = true
1710
- mockInstance._sendLogsBatch = vi.fn(() =>
1711
- Promise.resolve(shouldFail ? { kind: 'retry-later', error: new Error('down') } : { kind: 'ok' })
1712
- )
1713
- const base = 1000
1714
- const logs = new PostHogLogs(
1715
- mockInstance,
1716
- resolveForTest({ flushIntervalMs: base }),
1717
- logger,
1718
- getContextFor(mockInstance),
1719
- immediateOnReady
1720
- )
1721
- logs.captureLog({ body: 'a' })
1722
-
1723
- await vi.advanceTimersByTimeAsync(base) // attempt #1 fail (failures→1)
1724
- await vi.advanceTimersByTimeAsync(base) // attempt #2 fail (failures→2, next 2x)
1725
- await vi.advanceTimersByTimeAsync(2 * base) // attempt #3 fail (failures→3, next 4x)
1726
- shouldFail = false
1727
- await vi.advanceTimersByTimeAsync(4 * base) // attempt #4 succeeds → drains + resets
1728
- expect(readQueue(mockInstance)).toHaveLength(0)
1729
-
1730
- // A new capture flushes at the base interval again, not the backed-off one.
1731
- ;(mockInstance._sendLogsBatch as vi.Mock).mockClear()
1732
- logs.captureLog({ body: 'b' })
1733
- await vi.advanceTimersByTimeAsync(base)
1734
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1735
- })
1736
-
1737
- it('onReconnect flushes immediately without waiting out the backoff', async () => {
1738
- let shouldFail = true
1739
- mockInstance._sendLogsBatch = vi.fn(() =>
1740
- Promise.resolve(shouldFail ? { kind: 'retry-later', error: new Error('down') } : { kind: 'ok' })
1741
- )
1742
- const base = 1000
1743
- const logs = new PostHogLogs(
1744
- mockInstance,
1745
- resolveForTest({ flushIntervalMs: base }),
1746
- logger,
1747
- getContextFor(mockInstance),
1748
- immediateOnReady
1749
- )
1750
- logs.captureLog({ body: 'x' })
1751
-
1752
- await vi.advanceTimersByTimeAsync(base) // attempt #1 fails → record retained, backoff armed
1753
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1754
- expect(readQueue(mockInstance)).toHaveLength(1)
1755
-
1756
- // Reconnect drains now — no timer advance needed.
1757
- shouldFail = false
1758
- logs.onReconnect()
1759
- await vi.advanceTimersByTimeAsync(0)
1760
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
1761
- expect(readQueue(mockInstance)).toHaveLength(0)
1762
- })
1763
- })
1764
-
1765
- describe('flushWithTimeout', () => {
1766
- beforeEach(() => vi.useFakeTimers())
1767
- afterEach(() => vi.useRealTimers())
1768
-
1769
- it('clears the timeout timer when the flush finishes first', async () => {
1770
- const logs = new PostHogLogs(
1771
- mockInstance,
1772
- resolveForTest(),
1773
- logger,
1774
- getContextFor(mockInstance),
1775
- immediateOnReady
1776
- )
1777
- mockInstance.setPersistedProperty(PostHogPersistedProperty.LogsQueue, [
1778
- { record: { body: { stringValue: 'a' } } },
1779
- ])
1780
-
1781
- await logs.flushWithTimeout(5000)
1782
-
1783
- expect(vi.getTimerCount()).toBe(0)
1784
- })
1785
- })
1786
-
1787
- describe('shutdown', () => {
1788
- beforeEach(() => vi.useFakeTimers())
1789
- afterEach(() => vi.useRealTimers())
1790
-
1791
- it('drains the queue and clears any armed flush timer', async () => {
1792
- const logs = new PostHogLogs(
1793
- mockInstance,
1794
- resolveForTest({ flushIntervalMs: 5000 }),
1795
- logger,
1796
- getContextFor(mockInstance),
1797
- immediateOnReady
1798
- )
1799
- logs.captureLog({ body: 'a' })
1800
- // A timer is now armed — shutdown must cancel it so the process can
1801
- // exit cleanly even if the final flush triggers a duplicate send.
1802
-
1803
- await logs.shutdown()
1804
-
1805
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1806
- // Advancing past the original interval must not produce a second flush.
1807
- vi.advanceTimersByTime(10000)
1808
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1809
- })
1810
-
1811
- it('clears the timeout timer when the final flush finishes first', async () => {
1812
- const logs = new PostHogLogs(
1813
- mockInstance,
1814
- resolveForTest({ flushIntervalMs: 5000 }),
1815
- logger,
1816
- getContextFor(mockInstance),
1817
- immediateOnReady
1818
- )
1819
- logs.captureLog({ body: 'a' })
1820
-
1821
- await logs.shutdown(5000)
1822
-
1823
- expect(vi.getTimerCount()).toBe(0)
1824
- })
1825
-
1826
- it('swallows flush errors so shutdown can complete', async () => {
1827
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve({ kind: 'fatal', error: new Error('boom') }))
1828
- const logs = new PostHogLogs(
1829
- mockInstance,
1830
- resolveForTest(),
1831
- logger,
1832
- getContextFor(mockInstance),
1833
- immediateOnReady
1834
- )
1835
- logs.captureLog({ body: 'doomed' })
1836
-
1837
- await expect(logs.shutdown()).resolves.toBeUndefined()
1838
- })
1839
-
1840
- it('is a no-op when the queue is empty and no timer is armed', async () => {
1841
- const logs = new PostHogLogs(
1842
- mockInstance,
1843
- resolveForTest(),
1844
- logger,
1845
- getContextFor(mockInstance),
1846
- immediateOnReady
1847
- )
1848
- await logs.shutdown()
1849
- expect(mockInstance._sendLogsBatch).not.toHaveBeenCalled()
1850
- })
1851
-
1852
- it('called twice is idempotent (second call is a no-op once queue drains)', async () => {
1853
- const logs = new PostHogLogs(
1854
- mockInstance,
1855
- resolveForTest(),
1856
- logger,
1857
- getContextFor(mockInstance),
1858
- immediateOnReady
1859
- )
1860
- logs.captureLog({ body: 'x' })
1861
- await logs.shutdown()
1862
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1863
-
1864
- // Queue is empty now — a second shutdown shouldn't re-send.
1865
- await logs.shutdown()
1866
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1867
- })
1868
-
1869
- it('while a flush is in flight, the shared promise coordinates a single drain', async () => {
1870
- let resolveFirst: (v: any) => void = () => {}
1871
- mockInstance._sendLogsBatch = vi.fn(
1872
- () =>
1873
- new Promise((r) => {
1874
- resolveFirst = r
1875
- })
1876
- )
1877
- const logs = new PostHogLogs(
1878
- mockInstance,
1879
- resolveForTest(),
1880
- logger,
1881
- getContextFor(mockInstance),
1882
- immediateOnReady
1883
- )
1884
- logs.captureLog({ body: 'a' })
1885
-
1886
- // Real timers only here — shutdown(timeoutMs) path uses safeSetTimeout,
1887
- // which is incompatible with the default `vi.useFakeTimers()`.
1888
- vi.useRealTimers()
1889
-
1890
- const flushP = logs.flush()
1891
- const shutdownP = logs.shutdown()
1892
-
1893
- resolveFirst({ kind: 'ok' })
1894
- await Promise.all([flushP, shutdownP])
1895
-
1896
- // Both callers joined the same in-flight flush — no double-send.
1897
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
1898
- })
1899
-
1900
- it('races the final flush against timeoutMs so a stalled send does not hang shutdown', async () => {
1901
- vi.useRealTimers()
1902
- // _sendLogsBatch never resolves — the budget must force shutdown to return.
1903
- mockInstance._sendLogsBatch = vi.fn(() => new Promise(() => {}))
1904
- const logs = new PostHogLogs(
1905
- mockInstance,
1906
- resolveForTest(),
1907
- logger,
1908
- getContextFor(mockInstance),
1909
- immediateOnReady
1910
- )
1911
- logs.captureLog({ body: 'stuck' })
1912
-
1913
- const start = Date.now()
1914
- await logs.shutdown(30)
1915
- const elapsed = Date.now() - start
1916
-
1917
- // Loose upper bound — just prove we didn't wait forever.
1918
- expect(elapsed).toBeLessThan(500)
1919
- })
1920
-
1921
- it('propagates a _waitForStoragePersist rejection out of flush (so callers can react)', async () => {
1922
- const persistErr = new Error('disk is gone')
1923
- const logs = new PostHogLogs(
1924
- mockInstance,
1925
- resolveForTest(),
1926
- logger,
1927
- getContextFor(mockInstance),
1928
- immediateOnReady,
1929
- // Persist fails AFTER the HTTP send succeeds — records were sent but
1930
- // the queue-advance didn't reach disk. Surface the error so the
1931
- // caller knows a retry on restart may re-send.
1932
- () => Promise.reject(persistErr)
1933
- )
1934
- logs.captureLog({ body: 'sent-but-not-persisted' })
1935
-
1936
- await expect(logs.flush()).rejects.toBe(persistErr)
1937
- })
1938
- })
1939
-
1940
- describe('beforeSend hook', () => {
1941
- // Helper that hides the constructor boilerplate so the table-driven
1942
- // cases below can be a single line of setup each.
1943
- const makeLogs = (beforeSend: PostHogLogsConfig['beforeSend']): PostHogLogs =>
1944
- new PostHogLogs(
1945
- mockInstance,
1946
- resolveForTest({ beforeSend }),
1947
- logger,
1948
- getContextFor(mockInstance),
1949
- immediateOnReady
1950
- )
1951
-
1952
- // Cases that share a "captureLog → assert queue body" shape. Bespoke
1953
- // assertions (logger expectations, throw-drops-the-record) live in their
1954
- // own `it` blocks below — those were warping the table when forced into it.
1955
- type Case = {
1956
- name: string
1957
- beforeSend: PostHogLogsConfig['beforeSend']
1958
- input: string
1959
- expectedQueueLen: number
1960
- expectedBody?: string
1961
- }
1962
- const cases: Case[] = [
1963
- {
1964
- name: 'transforms body when fn returns mutated value',
1965
- beforeSend: (r) => ({ ...r, body: r.body.toUpperCase() }),
1966
- input: 'hello',
1967
- expectedQueueLen: 1,
1968
- expectedBody: 'HELLO',
1969
- },
1970
- {
1971
- name: 'drops the record when fn returns null',
1972
- beforeSend: () => null,
1973
- input: 'silent',
1974
- expectedQueueLen: 0,
1975
- },
1976
- {
1977
- name: 'chains an array left-to-right (each fn sees previous result)',
1978
- beforeSend: [
1979
- (r) => ({ ...r, body: `${r.body}-1` }),
1980
- (r) => ({ ...r, body: `${r.body}-2` }),
1981
- (r) => ({ ...r, body: `${r.body}-3` }),
1982
- ],
1983
- input: 'x',
1984
- expectedQueueLen: 1,
1985
- expectedBody: 'x-1-2-3',
1986
- },
1987
- {
1988
- name: 'short-circuits the chain when any fn returns null',
1989
- beforeSend: [(r) => r, () => null, (r) => r],
1990
- input: 'dropped',
1991
- expectedQueueLen: 0,
1992
- },
1993
- {
1994
- name: 'treats an empty body returned by beforeSend as a drop',
1995
- beforeSend: (r) => ({ ...r, body: '' }),
1996
- input: 'will-be-emptied',
1997
- expectedQueueLen: 0,
1998
- },
1999
- ]
2000
-
2001
- it.each(cases)('$name', ({ beforeSend, input, expectedQueueLen, expectedBody }) => {
2002
- const logs = makeLogs(beforeSend)
2003
- logs.captureLog({ body: input })
2004
-
2005
- const queue = readQueue(mockInstance)
2006
- expect(queue).toHaveLength(expectedQueueLen)
2007
- if (expectedBody !== undefined) {
2008
- expect(queue[0].record.body.stringValue).toBe(expectedBody)
2009
- }
2010
- })
2011
-
2012
- it('logs an info line when a fn returns null', () => {
2013
- // Carved out because the table only asserts queue shape; this
2014
- // verifies the diagnostic path that warns the user a record was
2015
- // dropped by their filter (no other knob to surface that).
2016
- const logs = makeLogs(() => null)
2017
- logs.captureLog({ body: 'silent' })
2018
- expect(logger.info).toHaveBeenCalledWith('Log was rejected in beforeSend function')
2019
- })
2020
-
2021
- it('logs the same info line when a fn empties the body', () => {
2022
- // An emptied body is a drop too, so it surfaces the same diagnostic as a
2023
- // null return rather than vanishing silently.
2024
- const logs = makeLogs((r) => ({ ...r, body: '' }))
2025
- logs.captureLog({ body: 'will-be-emptied' })
2026
- expect(logger.info).toHaveBeenCalledWith('Log was rejected in beforeSend function')
2027
- })
2028
-
2029
- it('never crashes the caller when a fn throws — drops the record (fail closed) and logs', () => {
2030
- const thrower = vi.fn(() => {
2031
- throw new Error('bad filter')
2032
- })
2033
- const after = vi.fn((r: any) => ({ ...r, body: `${r.body}!` }))
2034
- const logs = new PostHogLogs(
2035
- mockInstance,
2036
- resolveForTest({ beforeSend: [thrower, after] }),
2037
- logger,
2038
- getContextFor(mockInstance),
2039
- immediateOnReady
2040
- )
2041
-
2042
- expect(() => logs.captureLog({ body: 'hi' })).not.toThrow()
2043
- expect(readQueue(mockInstance)).toHaveLength(0)
2044
- expect(after).not.toHaveBeenCalled()
2045
- expect(logger.error).toHaveBeenCalledWith(
2046
- expect.stringContaining('Error in beforeSend function for log:'),
2047
- expect.any(Error)
2048
- )
2049
- })
2050
- })
2051
-
2052
- describe('rate limiting', () => {
2053
- beforeEach(() => vi.useFakeTimers({ now: 0 }))
2054
- afterEach(() => vi.useRealTimers())
2055
-
2056
- // Tabular form for the simple in-window cap cases. Bespoke ones
2057
- // (warn-once, window-roll reset, clock-jump backward, beforeSend
2058
- // accounting) keep their own `it` blocks because they assert
2059
- // multi-window or interleaving behavior.
2060
- type CapCase = {
2061
- name: string
2062
- maxLogsPerInterval: number | undefined
2063
- capturesInWindow: number
2064
- expectedQueueLen: number
2065
- }
2066
- const capCases: CapCase[] = [
2067
- {
2068
- name: 'is uncapped when maxLogsPerInterval is undefined (default)',
2069
- maxLogsPerInterval: undefined,
2070
- capturesInWindow: 50,
2071
- expectedQueueLen: 50,
2072
- },
2073
- {
2074
- name: 'drops captures beyond maxLogsPerInterval within the window',
2075
- maxLogsPerInterval: 3,
2076
- capturesInWindow: 5,
2077
- expectedQueueLen: 3,
2078
- },
2079
- ]
2080
-
2081
- it.each(capCases)('$name', ({ maxLogsPerInterval, capturesInWindow, expectedQueueLen }) => {
2082
- const logs = new PostHogLogs(
2083
- mockInstance,
2084
- resolveForTest({ maxLogsPerInterval, rateCapWindowMs: 1000 }),
2085
- logger,
2086
- getContextFor(mockInstance),
2087
- immediateOnReady
2088
- )
2089
- for (let i = 0; i < capturesInWindow; i++) {
2090
- logs.captureLog({ body: `msg-${i}` })
2091
- }
2092
- expect(readQueue(mockInstance)).toHaveLength(expectedQueueLen)
2093
- })
2094
-
2095
- it('warns exactly once per window when dropping, regardless of how many drops', () => {
2096
- const logs = new PostHogLogs(
2097
- mockInstance,
2098
- resolveForTest({ maxLogsPerInterval: 2, rateCapWindowMs: 1000 }),
2099
- logger,
2100
- getContextFor(mockInstance),
2101
- immediateOnReady
2102
- )
2103
- for (let i = 0; i < 10; i++) {
2104
- logs.captureLog({ body: `msg-${i}` })
2105
- }
2106
- expect(logger.warn).toHaveBeenCalledTimes(1)
2107
- expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('captureLog dropping logs'))
2108
- })
2109
-
2110
- it('resets the counter when the window rolls (and warns again on next overflow)', () => {
2111
- const logs = new PostHogLogs(
2112
- mockInstance,
2113
- resolveForTest({ maxLogsPerInterval: 1, rateCapWindowMs: 1000 }),
2114
- logger,
2115
- getContextFor(mockInstance),
2116
- immediateOnReady
2117
- )
2118
- logs.captureLog({ body: 'window-1-kept' })
2119
- logs.captureLog({ body: 'window-1-dropped' })
2120
- expect(readQueue(mockInstance)).toHaveLength(1)
2121
- expect(logger.warn).toHaveBeenCalledTimes(1)
2122
-
2123
- vi.setSystemTime(1001)
2124
- logs.captureLog({ body: 'window-2-kept' })
2125
- logs.captureLog({ body: 'window-2-dropped' })
2126
- expect(readQueue(mockInstance)).toHaveLength(2)
2127
- expect(logger.warn).toHaveBeenCalledTimes(2)
2128
- })
2129
-
2130
- it('resets the window when the clock jumps backward (NTP correction / manual clock change)', () => {
2131
- const logs = new PostHogLogs(
2132
- mockInstance,
2133
- resolveForTest({ maxLogsPerInterval: 2, rateCapWindowMs: 1000 }),
2134
- logger,
2135
- getContextFor(mockInstance),
2136
- immediateOnReady
2137
- )
2138
- // Seed the window at t=5000, fill the budget.
2139
- vi.setSystemTime(5000)
2140
- logs.captureLog({ body: 'a' })
2141
- logs.captureLog({ body: 'b' })
2142
- logs.captureLog({ body: 'dropped-pre-jump' })
2143
- expect(readQueue(mockInstance)).toHaveLength(2)
2144
-
2145
- // Clock jumps backward by 1 hour (e.g. user reset device time).
2146
- // Without the `elapsed < 0` guard, the rate cap would stay "stuck"
2147
- // until `now` exceeds the old window-start again — potentially
2148
- // dropping every log for the duration of the backward jump.
2149
- vi.setSystemTime(5000 - 60 * 60 * 1000)
2150
- logs.captureLog({ body: 'accepted-post-jump' })
2151
-
2152
- expect(readQueue(mockInstance)).toHaveLength(3)
2153
- expect(readQueue(mockInstance)[2].record.body.stringValue).toBe('accepted-post-jump')
2154
- })
2155
-
2156
- it('beforeSend-rejected records do not consume the per-interval budget', () => {
2157
- // beforeSend drops the first record; rate cap is 1 per window. The
2158
- // SECOND capture should still succeed — if beforeSend consumed the
2159
- // budget, it'd be dropped.
2160
- const beforeSend = vi
2161
- .fn()
2162
- .mockReturnValueOnce(null)
2163
- .mockImplementation((r: any) => r)
2164
- const logs = new PostHogLogs(
2165
- mockInstance,
2166
- resolveForTest({ maxLogsPerInterval: 1, rateCapWindowMs: 1000, beforeSend }),
2167
- logger,
2168
- getContextFor(mockInstance),
2169
- immediateOnReady
2170
- )
2171
- logs.captureLog({ body: 'pre-filtered-out' })
2172
- logs.captureLog({ body: 'should-still-fit' })
2173
-
2174
- expect(readQueue(mockInstance)).toHaveLength(1)
2175
- expect(readQueue(mockInstance)[0].record.body.stringValue).toBe('should-still-fit')
2176
- })
2177
- })
2178
-
2179
- describe('concurrent capture during flush', () => {
2180
- it('mid-flush captures land in the queue for the next cycle — not lost, not double-sent', async () => {
2181
- let resolveSend: (v: any) => void = () => {}
2182
- let captureDuringSend: (() => void) | null = null
2183
-
2184
- mockInstance._sendLogsBatch = vi.fn(
2185
- () =>
2186
- new Promise((r) => {
2187
- if (captureDuringSend) {
2188
- captureDuringSend()
2189
- captureDuringSend = null
2190
- }
2191
- resolveSend = (v) => r(v)
2192
- })
2193
- )
2194
-
2195
- const logs = new PostHogLogs(
2196
- mockInstance,
2197
- resolveForTest({ maxBatchRecordsPerPost: 1, maxBufferSize: 10 }),
2198
- logger,
2199
- getContextFor(mockInstance),
2200
- immediateOnReady
2201
- )
2202
- logs.captureLog({ body: 'first' })
2203
- captureDuringSend = (): void => {
2204
- logs.captureLog({ body: 'mid-flight' })
2205
- }
2206
-
2207
- const flushP = logs.flush()
2208
- await new Promise((r) => setImmediate(r))
2209
- resolveSend({ kind: 'ok' })
2210
- await flushP
2211
-
2212
- // flush() uses `originalQueueLength` at entry, so a mid-flight capture
2213
- // is intentionally left for the NEXT flush (matches events semantics).
2214
- // The invariant we care about: not lost, not double-sent.
2215
- expect(readQueue(mockInstance)).toHaveLength(1)
2216
- expect(readQueue(mockInstance)[0].record.body.stringValue).toBe('mid-flight')
2217
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
2218
-
2219
- // A subsequent flush picks it up — no data lost.
2220
- const flushP2 = logs.flush()
2221
- await new Promise((r) => setImmediate(r))
2222
- resolveSend({ kind: 'ok' })
2223
- await flushP2
2224
- expect(readQueue(mockInstance)).toHaveLength(0)
2225
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(2)
2226
- })
2227
- })
2228
-
2229
- describe('queue advance under FIFO eviction', () => {
2230
- it('keeps records captured during an in-flight flush at capacity', async () => {
2231
- // Regression: the advance used to drop `consumed` records positionally,
2232
- // but the FIFO cap evicts from the head while a batch is in flight, so a
2233
- // positional drop discarded the records that arrived during the send.
2234
- let resolveSend: (v: any) => void = () => {}
2235
- const sendGate = new Promise((r) => {
2236
- resolveSend = r
2237
- })
2238
- mockInstance._sendLogsBatch = vi.fn(() => sendGate)
2239
-
2240
- const logs = new PostHogLogs(
2241
- mockInstance,
2242
- resolveForTest({ maxBufferSize: 3, maxBatchRecordsPerPost: 3 }),
2243
- logger,
2244
- getContextFor(mockInstance),
2245
- immediateOnReady
2246
- )
2247
-
2248
- // Fill to capacity → triggers a background flush that awaits the gate.
2249
- logs.captureLog({ body: 'a' })
2250
- logs.captureLog({ body: 'b' })
2251
- logs.captureLog({ body: 'c' })
2252
- expect(mockInstance._sendLogsBatch).toHaveBeenCalledTimes(1)
2253
-
2254
- // While the send is in flight, two captures arrive at capacity and evict
2255
- // the (already-sent) head records a and b.
2256
- logs.captureLog({ body: 'd' })
2257
- logs.captureLog({ body: 'e' })
2258
-
2259
- resolveSend({ kind: 'ok' })
2260
- await logs.flush()
2261
-
2262
- // The sent batch [a, b, c] leaves the queue; d and e survive for next flush.
2263
- expect(readQueue(mockInstance).map((entry) => entry.record.body.stringValue)).toEqual(['d', 'e'])
2264
- })
2265
-
2266
- it('advances correctly across batches when eviction happens between iterations', async () => {
2267
- // Regression: the eviction counter was reset once per flush, so an eviction
2268
- // during the persist-await between batches got counted against the NEXT
2269
- // batch's advance — under-dropping and re-sending an already-sent record.
2270
- const entry = (body: string): any => ({ record: { body: { stringValue: body } } })
2271
- mockInstance._store[PostHogPersistedProperty.LogsQueue] = [entry('a'), entry('b'), entry('c'), entry('d')]
2272
- mockInstance._sendLogsBatch = vi.fn(() => Promise.resolve({ kind: 'ok' }))
2273
-
2274
- let persistCalls = 0
2275
- // oxlint-disable-next-line prefer-const
2276
- let logs: PostHogLogs
2277
- logs = new PostHogLogs(
2278
- mockInstance,
2279
- resolveForTest({ maxBufferSize: 4, maxQueueSize: 4, maxBatchRecordsPerPost: 2 }),
2280
- logger,
2281
- getContextFor(mockInstance),
2282
- immediateOnReady,
2283
- () => {
2284
- persistCalls++
2285
- if (persistCalls === 1) {
2286
- // After batch 1 [a,b] advances, captures arrive before batch 2 and
2287
- // evict the head record 'c' at capacity.
2288
- logs.captureLog({ body: 'e' })
2289
- logs.captureLog({ body: 'f' })
2290
- logs.captureLog({ body: 'g' })
2291
- }
2292
- return Promise.resolve()
2293
- }
2294
- )
2295
-
2296
- await logs.flush()
2297
-
2298
- // batch1 [a,b] dropped, 'c' evicted, batch2 [d,e] dropped — nothing sent twice.
2299
- expect(readQueue(mockInstance).map((x) => x.record.body.stringValue)).toEqual(['f', 'g'])
2300
- })
2301
- })
2302
- })
2303
-
2304
- describe('PostHogLogs consent and shared background flush', () => {
2305
- const create = (instance: any, logger: Logger = createMockLogger(), config = resolveForTest()): PostHogLogs =>
2306
- new PostHogLogs(
2307
- instance,
2308
- config,
2309
- logger,
2310
- getContextFor(instance),
2311
- immediateOnReady,
2312
- undefined,
2313
- undefined,
2314
- () => instance.consentWithdrawn === true
2315
- )
2316
-
2317
- it('discards queued records instead of exporting them after opt-out', async () => {
2318
- const instance = createMockInstance()
2319
- const logs = create(instance)
2320
- logs.captureLog({ body: 'before opt-out' })
2321
-
2322
- instance.consentWithdrawn = true
2323
- await logs.flush()
2324
-
2325
- expect(instance._sendLogsBatch).not.toHaveBeenCalled()
2326
- expect(readQueue(instance)).toHaveLength(0)
2327
-
2328
- // Opting back in does not resurrect what was captured before the withdrawal.
2329
- instance.consentWithdrawn = false
2330
- await logs.flush()
2331
- expect(instance._sendLogsBatch).not.toHaveBeenCalled()
2332
- })
2333
-
2334
- it('stops a drain under way when the user opts out between batches', async () => {
2335
- let releaseFirst: () => void = () => {}
2336
- const instance = createMockInstance({
2337
- _sendLogsBatch: vi.fn(
2338
- () =>
2339
- new Promise((resolve) => {
2340
- releaseFirst = () => resolve({ kind: 'ok' })
2341
- })
2342
- ),
2343
- })
2344
- const logs = create(instance, createMockLogger(), resolveForTest({ maxBatchRecordsPerPost: 1 }))
2345
- logs.captureLog({ body: 'first' })
2346
- logs.captureLog({ body: 'second' })
2347
-
2348
- const flushing = logs.flush()
2349
- await Promise.resolve()
2350
- instance.consentWithdrawn = true
2351
- releaseFirst()
2352
- await flushing
2353
-
2354
- expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
2355
- expect(readQueue(instance)).toHaveLength(0)
2356
- })
2357
-
2358
- it('does not retry a 413-rejected batch after the user opts out', async () => {
2359
- let rejectFirst: () => void = () => {}
2360
- const instance = createMockInstance({
2361
- _sendLogsBatch: vi.fn(
2362
- () =>
2363
- new Promise((resolve) => {
2364
- rejectFirst = () => resolve({ kind: 'too-large' })
2365
- })
2366
- ),
2367
- })
2368
- const logs = create(instance, createMockLogger(), resolveForTest({ maxBatchRecordsPerPost: 4 }))
2369
- logs.captureLog({ body: 'a' })
2370
- logs.captureLog({ body: 'b' })
2371
-
2372
- const flushing = logs.flush()
2373
- await Promise.resolve()
2374
- instance.consentWithdrawn = true
2375
- rejectFirst()
2376
- await flushing
2377
-
2378
- expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
2379
- expect(readQueue(instance)).toHaveLength(0)
2380
- })
2381
-
2382
- it('shares one background wrapper across overlapping callers', async () => {
2383
- let failSend: () => void = () => {}
2384
- const instance = createMockInstance({
2385
- _sendLogsBatch: vi.fn(
2386
- () =>
2387
- new Promise((resolve) => {
2388
- failSend = () => resolve({ kind: 'retry-later', error: new Error('down') })
2389
- })
2390
- ),
2391
- })
2392
- const logger = createMockLogger()
2393
- const logs = create(instance, logger)
2394
- logs.captureLog({ body: 'slow' })
2395
-
2396
- const first = logs.flushInBackground()
2397
- const second = logs.flushInBackground()
2398
- expect(second).toBe(first)
2399
- await Promise.resolve()
2400
- failSend()
2401
- await Promise.all([first, second])
2402
-
2403
- expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
2404
- expect(logger.error).toHaveBeenCalledTimes(1)
2405
- })
2406
-
2407
- it('keeps flushing a host whose optedOut is only a shutdown gate when no consent callback is given', async () => {
2408
- const instance = createMockInstance({ optedOut: false })
2409
- const logs = new PostHogLogs(
2410
- instance,
2411
- resolveForTest(),
2412
- createMockLogger(),
2413
- getContextFor(instance),
2414
- immediateOnReady
2415
- )
2416
- logs.captureLog({ body: 'final flush' })
2417
- instance.optedOut = true
2418
- await logs.flush()
2419
- expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
2420
- })
2421
- })