@posthog/core 1.69.9 → 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 (122) 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/featureFlagLocalEvaluation.d.ts +2 -0
  35. package/dist/featureFlagLocalEvaluation.d.ts.map +1 -1
  36. package/dist/featureFlagLocalEvaluation.js +38 -0
  37. package/dist/featureFlagLocalEvaluation.mjs +38 -0
  38. package/dist/featureFlagUtils.d.ts +7 -5
  39. package/dist/featureFlagUtils.d.ts.map +1 -1
  40. package/dist/featureFlagUtils.js +17 -11
  41. package/dist/featureFlagUtils.mjs +14 -11
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +27 -16
  45. package/dist/index.mjs +1 -1
  46. package/dist/posthog-core-stateless.d.ts +44 -7
  47. package/dist/posthog-core-stateless.d.ts.map +1 -1
  48. package/dist/posthog-core-stateless.js +103 -24
  49. package/dist/posthog-core-stateless.mjs +103 -24
  50. package/dist/posthog-core.d.ts +138 -53
  51. package/dist/posthog-core.d.ts.map +1 -1
  52. package/dist/posthog-core.js +341 -115
  53. package/dist/posthog-core.mjs +338 -115
  54. package/dist/types.d.ts +33 -1
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/utils/index.d.ts +1 -1
  57. package/dist/utils/index.d.ts.map +1 -1
  58. package/dist/utils/index.js +25 -12
  59. package/dist/utils/index.mjs +1 -1
  60. package/dist/utils/json-utils.d.ts +11 -1
  61. package/dist/utils/json-utils.d.ts.map +1 -1
  62. package/dist/utils/json-utils.js +50 -2
  63. package/dist/utils/json-utils.mjs +46 -1
  64. package/package.json +13 -3
  65. package/src/capture-v1/compression.ts +50 -0
  66. package/src/capture-v1/errors.ts +91 -0
  67. package/src/capture-v1/index.ts +34 -0
  68. package/src/capture-v1/sender.ts +779 -0
  69. package/src/capture-v1/serialize.ts +113 -0
  70. package/src/capture-v1/transform.ts +135 -0
  71. package/src/capture-v1/types.ts +59 -0
  72. package/src/capture-v1/uuid.ts +53 -0
  73. package/src/featureFlagLocalEvaluation.ts +51 -0
  74. package/src/featureFlagUtils.ts +22 -10
  75. package/src/index.ts +1 -0
  76. package/src/posthog-core-stateless.ts +190 -35
  77. package/src/posthog-core.ts +615 -178
  78. package/src/types.ts +31 -1
  79. package/src/utils/index.ts +1 -1
  80. package/src/utils/json-utils.ts +64 -1
  81. package/src/error-tracking/chunk-ids.spec.ts +0 -77
  82. package/src/error-tracking/coercers/error-event-coercer.spec.ts +0 -142
  83. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +0 -77
  84. package/src/error-tracking/coercers/string-coercer.spec.ts +0 -26
  85. package/src/error-tracking/error-properties-builder.aggregate-errors.spec.ts +0 -412
  86. package/src/error-tracking/error-properties-builder.coerce.spec.ts +0 -337
  87. package/src/error-tracking/error-properties-builder.metadata.spec.ts +0 -318
  88. package/src/error-tracking/error-properties-builder.parse.spec.ts +0 -37
  89. package/src/error-tracking/exception-steps.spec.ts +0 -115
  90. package/src/error-tracking/parsers/base.spec.ts +0 -156
  91. package/src/error-tracking/parsers/index.spec.ts +0 -270
  92. package/src/error-tracking/parsers/node.spec.ts +0 -34
  93. package/src/error-tracking/release.spec.ts +0 -34
  94. package/src/logs/index.spec.ts +0 -2421
  95. package/src/logs/logs-utils.spec.ts +0 -266
  96. package/src/metrics/index.spec.ts +0 -1249
  97. package/src/surveys/activation.spec.ts +0 -61
  98. package/src/surveys/events.spec.ts +0 -183
  99. package/src/surveys/keys.spec.ts +0 -29
  100. package/src/surveys/property-matching.spec.ts +0 -539
  101. package/src/surveys/shuffling.spec.ts +0 -51
  102. package/src/surveys/translations.spec.ts +0 -274
  103. package/src/surveys/validation.spec.ts +0 -168
  104. package/src/traces/config.spec.ts +0 -271
  105. package/src/traces/ids.spec.ts +0 -115
  106. package/src/traces/index.spec.ts +0 -3287
  107. package/src/traces/live-spans.spec.ts +0 -69
  108. package/src/traces/otlp.spec.ts +0 -368
  109. package/src/traces/span.spec.ts +0 -1137
  110. package/src/traces/traceparent.spec.ts +0 -184
  111. package/src/utils/bot-detection.spec.ts +0 -107
  112. package/src/utils/bucketed-rate-limiter.spec.ts +0 -327
  113. package/src/utils/json-utils.spec.ts +0 -115
  114. package/src/utils/named-error.spec.ts +0 -36
  115. package/src/utils/number-utils.spec.ts +0 -212
  116. package/src/utils/otlp-any-value.spec.ts +0 -376
  117. package/src/utils/otlp-resource.spec.ts +0 -171
  118. package/src/utils/promise-queue.spec.ts +0 -55
  119. package/src/utils/string-utils.spec.ts +0 -158
  120. package/src/utils/type-utils.spec.ts +0 -38
  121. package/src/utils/webview-app-utils.spec.ts +0 -118
  122. package/src/vendor/uuidv7.spec.ts +0 -26
@@ -1,1249 +0,0 @@
1
- import type { Logger } from '../types'
2
- import { PostHogMetrics } from './index'
3
- import type { OtlpMetric, OtlpMetricsPayload, ResolvedPostHogMetricsConfig, SendMetricsBatchOutcome } from './types'
4
-
5
- const DEFAULT_FLUSH_INTERVAL_MS = 10000
6
- const DEFAULT_MAX_SERIES_PER_FLUSH = 1000
7
-
8
- const resolveForTest = (partial?: Partial<ResolvedPostHogMetricsConfig>): ResolvedPostHogMetricsConfig => ({
9
- ...partial,
10
- flushIntervalMs: partial?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
11
- maxSeriesPerFlush: partial?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH,
12
- })
13
-
14
- const createMockInstance = (overrides: Record<string, any> = {}): any => ({
15
- isDisabled: false,
16
- optedOut: false,
17
- getLibraryId: vi.fn(() => 'posthog-core-tests'),
18
- getLibraryVersion: vi.fn(() => '0.0.0-test'),
19
- _sendMetricsBatch: vi.fn((): Promise<SendMetricsBatchOutcome> => Promise.resolve({ kind: 'ok' })),
20
- ...overrides,
21
- })
22
-
23
- const createMockLogger = (): Logger => {
24
- const logger: any = {
25
- debug: vi.fn(),
26
- info: vi.fn(),
27
- warn: vi.fn(),
28
- error: vi.fn(),
29
- critical: vi.fn(),
30
- }
31
- logger.createLogger = vi.fn(() => logger)
32
- return logger as Logger
33
- }
34
-
35
- describe('PostHogMetrics', () => {
36
- let mockInstance: any
37
- let logger: Logger
38
-
39
- const createMetrics = (config?: Partial<ResolvedPostHogMetricsConfig>, instance?: any): PostHogMetrics => {
40
- return new PostHogMetrics(instance ?? mockInstance, resolveForTest(config), logger)
41
- }
42
-
43
- const sentPayloads = (instance?: any): OtlpMetricsPayload[] =>
44
- (instance ?? mockInstance)._sendMetricsBatch.mock.calls.map((c: any[]) => c[0])
45
-
46
- const sentMetrics = (instance?: any): OtlpMetric[] =>
47
- sentPayloads(instance).flatMap((p) => p.resourceMetrics[0].scopeMetrics[0].metrics)
48
-
49
- beforeEach(() => {
50
- vi.useFakeTimers()
51
- mockInstance = createMockInstance()
52
- logger = createMockLogger()
53
- // Retry delays carry jitter; pinned to its midpoint so every timing
54
- // assertion here measures the backoff itself and cannot flake.
55
- vi.spyOn(Math, 'random').mockReturnValue(0.5)
56
- })
57
-
58
- afterEach(() => {
59
- vi.useRealTimers()
60
- })
61
-
62
- describe('flushCoalesced', () => {
63
- it('keeps at most one send in flight and one queued behind it, and sends every sample', async () => {
64
- let resolveSend!: (o: SendMetricsBatchOutcome) => void
65
- mockInstance._sendMetricsBatch
66
- .mockImplementationOnce(() => new Promise<SendMetricsBatchOutcome>((r) => (resolveSend = r)))
67
- .mockResolvedValue({ kind: 'ok' })
68
- const metrics = createMetrics()
69
-
70
- metrics.count('requests', 1)
71
- const first = metrics.flushCoalesced()
72
- await Promise.resolve()
73
- await Promise.resolve()
74
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
75
-
76
- // Many requests finish while the first send is in flight: they share one queued flush.
77
- const queued = [1, 2, 3, 4, 5].map(() => {
78
- metrics.count('requests', 1)
79
- return metrics.flushCoalesced()
80
- })
81
- expect(new Set(queued).size).toBe(1)
82
-
83
- resolveSend({ kind: 'ok' })
84
- await Promise.all([first, ...queued])
85
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(2)
86
- expect(sentMetrics().reduce((sum, m) => sum + m.sum!.dataPoints[0].asDouble!, 0)).toBe(6)
87
- })
88
-
89
- it('does not start a queued flush when the send it waited behind starts a backoff', async () => {
90
- let resolveSend!: (o: SendMetricsBatchOutcome) => void
91
- mockInstance._sendMetricsBatch
92
- .mockImplementationOnce(() => new Promise<SendMetricsBatchOutcome>((r) => (resolveSend = r)))
93
- .mockResolvedValue({ kind: 'ok' })
94
- const metrics = createMetrics()
95
-
96
- metrics.count('requests', 1)
97
- const first = metrics.flushCoalesced()
98
- await Promise.resolve()
99
- await Promise.resolve()
100
- metrics.count('requests', 1)
101
- const queued = metrics.flushCoalesced()
102
-
103
- resolveSend({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
104
- await Promise.all([first, queued])
105
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
106
-
107
- // The retry timer delivers the retained samples once the backoff ends.
108
- await vi.advanceTimersByTimeAsync(300_000)
109
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(2)
110
- const retried = sentPayloads()[1].resourceMetrics[0].scopeMetrics[0].metrics
111
- expect(retried[0].sum!.dataPoints[0].asDouble).toBe(2)
112
- })
113
-
114
- it('does not send while a failed send is backing off', async () => {
115
- mockInstance._sendMetricsBatch.mockResolvedValueOnce({
116
- kind: 'retry-later',
117
- error: new Error('429'),
118
- retryAfterMs: 300_000,
119
- })
120
- const metrics = createMetrics()
121
- metrics.count('requests', 1)
122
- await metrics.flushCoalesced()
123
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
124
-
125
- metrics.count('requests', 1)
126
- await metrics.flushCoalesced()
127
- await metrics.flushCoalesced()
128
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
129
- })
130
- })
131
-
132
- describe('aggregation semantics', () => {
133
- it('sums count samples for the same series into one delta data point', async () => {
134
- const metrics = createMetrics()
135
- metrics.count('orders_created', 1)
136
- metrics.count('orders_created', 1)
137
- metrics.count('orders_created', 3)
138
- await metrics.flush()
139
-
140
- const sent = sentMetrics()
141
- expect(sent).toHaveLength(1)
142
- expect(sent[0].name).toBe('orders_created')
143
- expect(sent[0].sum).toMatchObject({ aggregationTemporality: 1, isMonotonic: true })
144
- expect(sent[0].sum!.dataPoints).toHaveLength(1)
145
- expect(sent[0].sum!.dataPoints[0].asDouble).toBe(5)
146
- })
147
-
148
- it('defaults count value to 1', async () => {
149
- const metrics = createMetrics()
150
- metrics.count('clicks')
151
- metrics.count('clicks')
152
- await metrics.flush()
153
-
154
- expect(sentMetrics()[0].sum!.dataPoints[0].asDouble).toBe(2)
155
- })
156
-
157
- it('keeps only the last gauge value per series per window', async () => {
158
- const metrics = createMetrics()
159
- metrics.gauge('active_connections', 42)
160
- metrics.gauge('active_connections', 17)
161
- await metrics.flush()
162
-
163
- const sent = sentMetrics()
164
- expect(sent).toHaveLength(1)
165
- expect(sent[0].gauge!.dataPoints).toHaveLength(1)
166
- expect(sent[0].gauge!.dataPoints[0].asDouble).toBe(17)
167
- })
168
-
169
- it('accumulates histogram observations into count/sum/min/max and buckets', async () => {
170
- const metrics = createMetrics()
171
- metrics.histogram('api_latency', 10, { unit: 'ms' })
172
- metrics.histogram('api_latency', 20, { unit: 'ms' })
173
- metrics.histogram('api_latency', 30, { unit: 'ms' })
174
- await metrics.flush()
175
-
176
- const sent = sentMetrics()
177
- expect(sent).toHaveLength(1)
178
- expect(sent[0].unit).toBe('ms')
179
- const dp = sent[0].histogram!.dataPoints[0]
180
- expect(dp.count).toBe(3)
181
- expect(dp.sum).toBe(60)
182
- expect(dp.min).toBe(10)
183
- expect(dp.max).toBe(30)
184
- expect(dp.explicitBounds.length).toBeGreaterThan(0)
185
- expect(dp.bucketCounts).toHaveLength(dp.explicitBounds.length + 1)
186
- expect(dp.bucketCounts.reduce((a, b) => a + b, 0)).toBe(3)
187
- expect(sent[0].histogram!.aggregationTemporality).toBe(1)
188
- })
189
-
190
- it('places histogram observations in the correct buckets', async () => {
191
- const metrics = createMetrics()
192
- // Default OTel bounds start [0, 5, 10, 25, ...]: -1 → bucket 0 (≤0),
193
- // 3 → bucket 1 (≤5), 10 → bucket 2 (≤10), 1e9 → overflow bucket.
194
- metrics.histogram('x', -1)
195
- metrics.histogram('x', 3)
196
- metrics.histogram('x', 10)
197
- metrics.histogram('x', 1e9)
198
- await metrics.flush()
199
-
200
- const dp = sentMetrics()[0].histogram!.dataPoints[0]
201
- expect(dp.bucketCounts[0]).toBe(1)
202
- expect(dp.bucketCounts[1]).toBe(1)
203
- expect(dp.bucketCounts[2]).toBe(1)
204
- expect(dp.bucketCounts[dp.bucketCounts.length - 1]).toBe(1)
205
- })
206
-
207
- it('splits series by attribute values but merges identical attribute sets regardless of key order', async () => {
208
- const metrics = createMetrics()
209
- metrics.count('api_calls', 1, { attributes: { route: '/home', plan: 'free' } })
210
- metrics.count('api_calls', 1, { attributes: { plan: 'free', route: '/home' } })
211
- metrics.count('api_calls', 1, { attributes: { route: '/checkout', plan: 'free' } })
212
- await metrics.flush()
213
-
214
- const sent = sentMetrics()
215
- expect(sent).toHaveLength(1)
216
- expect(sent[0].sum!.dataPoints).toHaveLength(2)
217
- const values = sent[0].sum!.dataPoints.map((dp) => dp.asDouble).sort()
218
- expect(values).toEqual([1, 2])
219
- })
220
-
221
- it('emits separate metric entries for the same name with different types or units', async () => {
222
- const metrics = createMetrics()
223
- metrics.count('throughput', 1)
224
- metrics.gauge('throughput', 5)
225
- metrics.histogram('size', 1, { unit: 'byte' })
226
- metrics.histogram('size', 1, { unit: 'kilobyte' })
227
- await metrics.flush()
228
-
229
- const sent = sentMetrics()
230
- expect(sent).toHaveLength(4)
231
- const throughput = sent.filter((m) => m.name === 'throughput')
232
- expect(throughput.some((m) => m.sum)).toBe(true)
233
- expect(throughput.some((m) => m.gauge)).toBe(true)
234
- const sizes = sent.filter((m) => m.name === 'size')
235
- expect(sizes.map((m) => m.unit).sort()).toEqual(['byte', 'kilobyte'])
236
- })
237
-
238
- it('encodes attributes as OTLP key-value pairs on the data point', async () => {
239
- const metrics = createMetrics()
240
- metrics.count('api_calls', 1, { attributes: { route: '/home', retries: 2, cached: true } })
241
- await metrics.flush()
242
-
243
- const attrs = sentMetrics()[0].sum!.dataPoints[0].attributes
244
- expect(attrs).toContainEqual({ key: 'route', value: { stringValue: '/home' } })
245
- expect(attrs).toContainEqual({ key: 'retries', value: { intValue: '2' } })
246
- expect(attrs).toContainEqual({ key: 'cached', value: { boolValue: true } })
247
- })
248
-
249
- // The encoder is shared with logs, so the debug line it emits on the
250
- // out-of-range path only reaches anyone if metrics passes its logger down.
251
- it('encodes an out-of-int64 attribute as a string and reports it through the logger', async () => {
252
- const metrics = createMetrics()
253
- metrics.count('api_calls', 1, { attributes: { huge: 2 ** 63 } as any })
254
- await metrics.flush()
255
-
256
- const attrs = sentMetrics()[0].sum!.dataPoints[0].attributes
257
- expect(attrs).toContainEqual({ key: 'huge', value: { stringValue: '9223372036854775808' } })
258
- expect((logger.debug as vi.Mock).mock.calls.some((c) => String(c[0]).includes('outside the int64 range'))).toBe(
259
- true
260
- )
261
- })
262
-
263
- it('stamps delta data points with a window: startTimeUnixNano <= timeUnixNano, both nano strings', async () => {
264
- const metrics = createMetrics()
265
- metrics.count('orders_created', 1)
266
- vi.advanceTimersByTime(2000)
267
- await metrics.flush()
268
-
269
- const dp = sentMetrics()[0].sum!.dataPoints[0]
270
- expect(dp.timeUnixNano).toMatch(/^\d+$/)
271
- expect(dp.startTimeUnixNano).toMatch(/^\d+$/)
272
- expect(BigInt(dp.startTimeUnixNano!)).toBeLessThanOrEqual(BigInt(dp.timeUnixNano))
273
- })
274
- })
275
-
276
- describe('histogram bounds', () => {
277
- const DEFAULT_BOUNDS = [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000]
278
- const histogramPoints = (name: string) =>
279
- sentMetrics()
280
- .filter((m) => m.name === name)
281
- .flatMap((m) => m.histogram!.dataPoints)
282
- const warnings = () => (logger.warn as vi.Mock).mock.calls.map((c) => String(c[0]))
283
-
284
- it('uses the OpenTelemetry default bounds when none are passed', async () => {
285
- const metrics = createMetrics()
286
- metrics.histogram('h', 1)
287
- await metrics.flush()
288
-
289
- expect(histogramPoints('h')[0].explicitBounds).toEqual(DEFAULT_BOUNDS)
290
- })
291
-
292
- it('buckets values with the bounds the caller passes', async () => {
293
- const metrics = createMetrics()
294
- // (-inf, 100] ← 50 and 100, (100, 200] ← 150, overflow ← 201.
295
- for (const v of [50, 100, 150, 201]) {
296
- metrics.histogram('h', v, { bounds: [100, 200] })
297
- }
298
- await metrics.flush()
299
-
300
- const dp = histogramPoints('h')[0]
301
- expect(dp.explicitBounds).toEqual([100, 200])
302
- expect(dp.bucketCounts).toEqual([2, 1, 1])
303
- expect(dp.min).toBe(50)
304
- expect(dp.max).toBe(201)
305
- })
306
-
307
- it('copies the bounds so a caller mutating its array cannot change the buckets', async () => {
308
- const metrics = createMetrics()
309
- const bounds = [100, 200]
310
- metrics.histogram('h', 150, { bounds })
311
- bounds[0] = 175
312
- metrics.histogram('h', 150, { bounds: [100, 200] })
313
- await metrics.flush()
314
-
315
- const dp = histogramPoints('h')[0]
316
- expect(dp.explicitBounds).toEqual([100, 200])
317
- expect(dp.bucketCounts).toEqual([0, 2, 0])
318
- // The second call passes equal bounds in a new array, which is not a conflict.
319
- expect(logger.warn).not.toHaveBeenCalled()
320
- })
321
-
322
- it('records a sample with conflicting bounds in the first bounds and warns once', async () => {
323
- const metrics = createMetrics()
324
- metrics.histogram('h', 150, { bounds: [100, 200] })
325
- metrics.histogram('h', 150, { bounds: [10, 20, 30] })
326
- metrics.histogram('h', 150, { bounds: [10, 20, 30] })
327
- metrics.histogram('h', 150)
328
- await metrics.flush()
329
-
330
- const dp = histogramPoints('h')[0]
331
- expect(dp.explicitBounds).toEqual([100, 200])
332
- expect(dp.bucketCounts).toEqual([0, 4, 0])
333
- expect(warnings().filter((w) => w.includes("Histogram 'h' already uses the bounds"))).toHaveLength(1)
334
- })
335
-
336
- it('treats omitted bounds as the default when checking for a conflict', async () => {
337
- const metrics = createMetrics()
338
- metrics.histogram('h', 1)
339
- metrics.histogram('h', 1, { bounds: [100, 200] })
340
- await metrics.flush()
341
-
342
- expect(histogramPoints('h')[0].explicitBounds).toHaveLength(15)
343
- expect(warnings().some((w) => w.includes("Histogram 'h' already uses the bounds"))).toBe(true)
344
- })
345
-
346
- it('fixes the bounds per histogram across attribute series', async () => {
347
- const metrics = createMetrics()
348
- metrics.histogram('h', 150, { bounds: [100, 200], attributes: { route: 'a' } })
349
- metrics.histogram('h', 150, { bounds: [10, 20], attributes: { route: 'b' } })
350
- await metrics.flush()
351
-
352
- const points = histogramPoints('h')
353
- expect(points).toHaveLength(2)
354
- expect(points.map((dp) => dp.explicitBounds)).toEqual([
355
- [100, 200],
356
- [100, 200],
357
- ])
358
- })
359
-
360
- it('keeps the bounds of a histogram separate per unit', async () => {
361
- const metrics = createMetrics()
362
- metrics.histogram('h', 1, { unit: 'ms', bounds: [100, 200] })
363
- metrics.histogram('h', 1, { unit: 's', bounds: [1, 2, 3] })
364
- await metrics.flush()
365
-
366
- const byUnit = Object.fromEntries(sentMetrics().map((m) => [m.unit, m.histogram!.dataPoints[0].explicitBounds]))
367
- expect(byUnit).toEqual({ ms: [100, 200], s: [1, 2, 3] })
368
- expect(logger.warn).not.toHaveBeenCalled()
369
- })
370
-
371
- it('keeps the first bounds across flush windows and warns on a conflict once per window', async () => {
372
- const metrics = createMetrics()
373
- metrics.histogram('h', 150, { bounds: [100, 200] })
374
- metrics.histogram('h', 150, { bounds: [10, 20] })
375
- await metrics.flush()
376
- metrics.histogram('h', 150, { bounds: [10, 20] })
377
- await metrics.flush()
378
-
379
- expect(histogramPoints('h').map((dp) => dp.explicitBounds)).toEqual([
380
- [100, 200],
381
- [100, 200],
382
- ])
383
- expect(warnings().filter((w) => w.includes("Histogram 'h' already uses the bounds"))).toHaveLength(2)
384
- })
385
-
386
- it('merges a failed window back into a live window with the same bounds', async () => {
387
- mockInstance._sendMetricsBatch
388
- .mockResolvedValueOnce({ kind: 'retry-later', error: new Error('offline') })
389
- .mockResolvedValue({ kind: 'ok' })
390
- const metrics = createMetrics()
391
- metrics.histogram('h', 50, { bounds: [100, 200] })
392
- await metrics.flush()
393
- metrics.histogram('h', 150, { bounds: [10, 20] })
394
- await metrics.flush()
395
-
396
- const dp = histogramPoints('h')[1]
397
- expect(dp.explicitBounds).toEqual([100, 200])
398
- expect(dp.bucketCounts).toEqual([1, 1, 0])
399
- expect(dp.count).toBe(2)
400
- expect(dp.sum).toBe(200)
401
- expect(dp.min).toBe(50)
402
- expect(dp.max).toBe(150)
403
- })
404
-
405
- it('lets reset() clear the bounds so the next sample sets them again', async () => {
406
- const metrics = createMetrics()
407
- metrics.histogram('h', 150, { bounds: [100, 200] })
408
- metrics.reset()
409
- metrics.histogram('h', 15, { bounds: [10, 20] })
410
- await metrics.flush()
411
-
412
- expect(histogramPoints('h').map((dp) => dp.explicitBounds)).toEqual([[10, 20]])
413
- expect(logger.warn).not.toHaveBeenCalled()
414
- })
415
-
416
- it.each([
417
- ['empty', []],
418
- ['not an array', 'nope'],
419
- ['not increasing', [100, 100]],
420
- ['decreasing', [200, 100]],
421
- ['non-finite', [100, Infinity]],
422
- ['NaN', [NaN]],
423
- ['non-number', [100, '200']],
424
- ])('drops a sample whose bounds are %s', async (_name, bounds) => {
425
- const metrics = createMetrics()
426
- metrics.histogram('h', 1, { bounds: bounds as any })
427
- await metrics.flush()
428
-
429
- expect(sentMetrics()).toHaveLength(0)
430
- expect(warnings().some((w) => w.includes("Dropping histogram 'h': bounds must be"))).toBe(true)
431
- })
432
-
433
- it('does not fix the bounds from a sample with invalid bounds', async () => {
434
- const metrics = createMetrics()
435
- metrics.histogram('h', 1, { bounds: [200, 100] })
436
- metrics.histogram('h', 150, { bounds: [100, 200] })
437
- await metrics.flush()
438
-
439
- expect(histogramPoints('h')[0].explicitBounds).toEqual([100, 200])
440
- })
441
-
442
- it('drops new histograms that pass custom bounds past the bounds limit, and warns once', async () => {
443
- const metrics = createMetrics({ maxSeriesPerFlush: 2 })
444
- metrics.histogram('a', 1)
445
- metrics.histogram('b', 1)
446
- await metrics.flush()
447
- metrics.histogram('c', 15, { bounds: [10, 20] })
448
- metrics.histogram('d', 1)
449
- await metrics.flush()
450
- metrics.histogram('c', 150, { bounds: [100, 200] })
451
- metrics.histogram('d', 1, { bounds: [...DEFAULT_BOUNDS] })
452
- await metrics.flush()
453
-
454
- expect(sentMetrics().map((m) => m.name)).toEqual(['a', 'b', 'd', 'd'])
455
- expect(histogramPoints('d').map((dp) => dp.explicitBounds)).toEqual([DEFAULT_BOUNDS, DEFAULT_BOUNDS])
456
- expect(warnings().filter((w) => w.includes('Histogram bounds limit reached'))).toHaveLength(1)
457
- })
458
-
459
- it('never sends one histogram with different bounds from two clients when only one is past the bounds limit', async () => {
460
- const instanceA = createMockInstance()
461
- const instanceB = createMockInstance()
462
- const clientA = createMetrics({ maxSeriesPerFlush: 1 }, instanceA)
463
- const clientB = createMetrics({ maxSeriesPerFlush: 1 }, instanceB)
464
-
465
- clientA.histogram('h', 150, { bounds: [100, 200] })
466
- await clientA.flush()
467
- clientB.histogram('other', 1)
468
- await clientB.flush()
469
- clientB.histogram('h', 150, { bounds: [100, 200] })
470
- await clientB.flush()
471
-
472
- const bounds = [...sentMetrics(instanceA), ...sentMetrics(instanceB)]
473
- .filter((m) => m.name === 'h')
474
- .map((m) => m.histogram!.dataPoints[0].explicitBounds)
475
- expect(bounds).toEqual([[100, 200]])
476
- })
477
-
478
- it('merges a failed window of a histogram past the bounds limit into the live window', async () => {
479
- let traceparent: string | null = null
480
- mockInstance = createMockInstance({ getActiveSpan: () => ({ traceparent: () => traceparent }) })
481
- const metrics = createMetrics({ maxSeriesPerFlush: 1 })
482
- metrics.histogram('a', 1)
483
- await metrics.flush()
484
- let resolveSend!: (outcome: SendMetricsBatchOutcome) => void
485
- mockInstance._sendMetricsBatch.mockImplementationOnce(
486
- () => new Promise<SendMetricsBatchOutcome>((resolve) => (resolveSend = resolve))
487
- )
488
-
489
- traceparent = '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'
490
- metrics.histogram('c', 15)
491
- const inflight = metrics.flush()
492
- traceparent = null
493
- metrics.histogram('c', 150)
494
- resolveSend({ kind: 'retry-later', error: new Error('offline') })
495
- await inflight
496
- await metrics.flush()
497
-
498
- const dp = histogramPoints('c')[1]
499
- expect(dp.explicitBounds).toEqual(DEFAULT_BOUNDS)
500
- expect(dp.count).toBe(2)
501
- expect(dp.sum).toBe(165)
502
- // 15 falls in (10, 25] and 150 in (100, 250].
503
- expect(dp.bucketCounts).toEqual([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
504
- expect(dp.min).toBe(15)
505
- expect(dp.max).toBe(150)
506
- expect(dp.exemplars?.map((e) => e.asDouble)).toEqual([15])
507
- })
508
-
509
- it('keeps the caller bounds intact when beforeSend edits them in place', async () => {
510
- const metrics = createMetrics({
511
- beforeSend: (m) => {
512
- m.bounds?.forEach((b, i) => (m.bounds![i] = b / 1000))
513
- m.value /= 1000
514
- m.unit = 's'
515
- return m
516
- },
517
- })
518
- const bounds = [100, 1000]
519
- metrics.histogram('h', 500, { unit: 'ms', bounds })
520
- metrics.histogram('h', 500, { unit: 'ms', bounds })
521
- await metrics.flush()
522
-
523
- expect(bounds).toEqual([100, 1000])
524
- const dp = histogramPoints('h')[0]
525
- expect(dp.explicitBounds).toEqual([0.1, 1])
526
- expect(dp.bucketCounts).toEqual([0, 2, 0])
527
- expect(logger.warn).not.toHaveBeenCalled()
528
- })
529
-
530
- it('does not fix the bounds for a sample the series cap drops', async () => {
531
- const metrics = createMetrics({ maxSeriesPerFlush: 1 })
532
- metrics.count('fills_the_window', 1)
533
- metrics.histogram('h', 1, { bounds: [10, 20] })
534
- await metrics.flush()
535
- metrics.histogram('h', 150, { bounds: [100, 200] })
536
- await metrics.flush()
537
-
538
- expect(histogramPoints('h').map((dp) => dp.explicitBounds)).toEqual([[100, 200]])
539
- })
540
- })
541
-
542
- describe('exemplars', () => {
543
- const TRACE_ID = '4bf92f3577b34da6a3ce929d0e0e4736'
544
- const SPAN_ID = '00f067aa0ba902b7'
545
- const withActiveSpan = (traceparent: string | null): any =>
546
- createMockInstance({ getActiveSpan: () => ({ traceparent: () => traceparent }) })
547
-
548
- const dataPoints = (instance: any): any[] =>
549
- sentMetrics(instance).map((m) => (m.sum ?? m.gauge ?? m.histogram)!.dataPoints[0])
550
-
551
- it('stamps every metric type with the last sample recorded inside a sampled span', async () => {
552
- const instance = withActiveSpan(`00-${TRACE_ID}-${SPAN_ID}-01`)
553
- const metrics = createMetrics(undefined, instance)
554
- metrics.count('c', 1)
555
- metrics.count('c', 4)
556
- metrics.gauge('g', 7)
557
- metrics.histogram('h', 12)
558
- await metrics.flush()
559
-
560
- const points = dataPoints(instance)
561
- expect(points.map((p) => p.exemplars)).toEqual(
562
- [4, 7, 12].map((value) => [
563
- {
564
- filteredAttributes: [],
565
- timeUnixNano: expect.stringMatching(/^\d+$/),
566
- asDouble: value,
567
- traceId: TRACE_ID,
568
- spanId: SPAN_ID,
569
- },
570
- ])
571
- )
572
- })
573
-
574
- it.each([
575
- ['no getActiveSpan on the host', createMockInstance],
576
- ['no active span', () => createMockInstance({ getActiveSpan: () => null })],
577
- ['an unsampled span', () => withActiveSpan(`00-${TRACE_ID}-${SPAN_ID}-00`)],
578
- ['a span with no traceparent', () => withActiveSpan(null)],
579
- [
580
- 'a throwing host',
581
- () =>
582
- createMockInstance({
583
- getActiveSpan: () => {
584
- throw new Error('boom')
585
- },
586
- }),
587
- ],
588
- ])('records the sample without an exemplar for %s', async (_, makeInstance) => {
589
- const instance = makeInstance()
590
- const metrics = createMetrics(undefined, instance)
591
- metrics.count('c', 2)
592
- await metrics.flush()
593
-
594
- const [point] = dataPoints(instance)
595
- expect(point.asDouble).toBe(2)
596
- expect(point).not.toHaveProperty('exemplars')
597
- })
598
-
599
- it('keeps the exemplar of a window merged back after a failed flush', async () => {
600
- const instance = withActiveSpan(`00-${TRACE_ID}-${SPAN_ID}-01`)
601
- instance._sendMetricsBatch
602
- .mockResolvedValueOnce({ kind: 'retry-later', error: new Error('503') })
603
- .mockResolvedValue({ kind: 'ok' })
604
- const metrics = createMetrics(undefined, instance)
605
- metrics.count('c', 1)
606
- await metrics.flush()
607
- instance.getActiveSpan = () => null
608
- metrics.count('c', 2)
609
- await metrics.flush()
610
-
611
- const point = dataPoints(instance)[1]
612
- expect(point.asDouble).toBe(3)
613
- expect(point.exemplars[0]).toMatchObject({ traceId: TRACE_ID, spanId: SPAN_ID, asDouble: 1 })
614
- })
615
- })
616
-
617
- describe('resource attributes', () => {
618
- it('attaches service.name, sdk identity, and user resource attributes', async () => {
619
- const metrics = createMetrics({
620
- serviceName: 'checkout-web',
621
- environment: 'production',
622
- resourceAttributes: { 'k8s.pod': 'web-1' },
623
- })
624
- metrics.count('orders_created', 1)
625
- await metrics.flush()
626
-
627
- const payload = sentPayloads()[0]
628
- const resourceAttrs = payload.resourceMetrics[0].resource.attributes
629
- expect(resourceAttrs).toContainEqual({ key: 'service.name', value: { stringValue: 'checkout-web' } })
630
- expect(resourceAttrs).toContainEqual({ key: 'deployment.environment', value: { stringValue: 'production' } })
631
- expect(resourceAttrs).toContainEqual({ key: 'k8s.pod', value: { stringValue: 'web-1' } })
632
- expect(resourceAttrs).toContainEqual({ key: 'telemetry.sdk.name', value: { stringValue: 'posthog-core-tests' } })
633
- expect(payload.resourceMetrics[0].scopeMetrics[0].scope).toEqual({
634
- name: 'posthog-core-tests',
635
- version: '0.0.0-test',
636
- })
637
- })
638
-
639
- it('falls back to unknown_service and never lets resourceAttributes clobber service.name', async () => {
640
- const metrics = createMetrics({ resourceAttributes: { 'service.name': 'spoofed' } })
641
- metrics.count('x', 1)
642
- await metrics.flush()
643
-
644
- const resourceAttrs = sentPayloads()[0].resourceMetrics[0].resource.attributes
645
- expect(resourceAttrs).toContainEqual({ key: 'service.name', value: { stringValue: 'unknown_service' } })
646
- expect(resourceAttrs.filter((kv) => kv.key === 'service.name')).toHaveLength(1)
647
- })
648
- })
649
-
650
- describe('flush behavior', () => {
651
- it('sends nothing until the flush interval elapses, then sends the window once', async () => {
652
- const metrics = createMetrics({ flushIntervalMs: 5000 })
653
- metrics.count('orders_created', 1)
654
- expect(mockInstance._sendMetricsBatch).not.toHaveBeenCalled()
655
-
656
- await vi.advanceTimersByTimeAsync(5000)
657
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
658
- })
659
-
660
- it('keeps flushing on the interval while captures keep arriving', async () => {
661
- // Every capture arms the timer, and metrics have no size trigger to fall
662
- // back on: re-arming a pending one would stop the window ever being sent.
663
- const metrics = createMetrics({ flushIntervalMs: 10_000 })
664
-
665
- for (let i = 0; i < 60; i++) {
666
- metrics.count('orders_created', 1)
667
- await vi.advanceTimersByTimeAsync(1000)
668
- }
669
-
670
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalled()
671
- })
672
-
673
- it('waits out Retry-After even when a flush timer is already pending', async () => {
674
- // The capture arms a timer at the flush interval; the failed flush then asks
675
- // for far longer. The pending timer must not fire first.
676
- const instance = createMockInstance({
677
- _sendMetricsBatch: vi.fn((): Promise<SendMetricsBatchOutcome> =>
678
- Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
679
- ),
680
- })
681
- const metrics = createMetrics({ flushIntervalMs: 10_000 }, instance)
682
- metrics.count('orders_created', 1)
683
- await metrics.flush()
684
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
685
-
686
- await vi.advanceTimersByTimeAsync(11_000)
687
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
688
-
689
- await vi.advanceTimersByTimeAsync(300_000)
690
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(2)
691
- })
692
-
693
- it('clears Retry-After on an outcome that is not a retry', async () => {
694
- // Only a retriable outcome carries a wait. A stale one left set here would
695
- // pin every later flush at the server's old window forever.
696
- const outcomes: SendMetricsBatchOutcome[] = [
697
- { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 },
698
- { kind: 'fatal', error: new Error('400') },
699
- ]
700
- const instance = createMockInstance({
701
- _sendMetricsBatch: vi.fn(() => Promise.resolve(outcomes.shift() ?? { kind: 'ok' })),
702
- })
703
- const metrics = createMetrics({ flushIntervalMs: 10_000 }, instance)
704
- metrics.count('orders_created', 1)
705
- await metrics.flush()
706
-
707
- // The wait elapses, the retry lands a 400, and that ends the wait.
708
- await vi.advanceTimersByTimeAsync(300_000)
709
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(2)
710
-
711
- metrics.count('orders_created', 1)
712
- await vi.advanceTimersByTimeAsync(10_000)
713
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(3)
714
- })
715
-
716
- it('keeps the Retry-After window when a batch is refused for size', async () => {
717
- // `too-large` is a verdict on the body's size — the SDK's own or a 413 —
718
- // so it says nothing about the endpoint's rate limit. Ending the wait on
719
- // it lets the next refusal install a fresh window, pushing the retry out
720
- // past the deadline the endpoint actually named — observed here as the
721
- // flush landing at 300s rather than at 310s.
722
- const outcomes: SendMetricsBatchOutcome[] = [
723
- { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 },
724
- { kind: 'too-large' },
725
- { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 },
726
- ]
727
- const instance = createMockInstance({
728
- _sendMetricsBatch: vi.fn(() => Promise.resolve(outcomes.shift() ?? { kind: 'ok' })),
729
- })
730
- const metrics = createMetrics({ flushIntervalMs: 1000 }, instance)
731
- metrics.count('orders_created', 1)
732
- await metrics.flush()
733
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
734
-
735
- await vi.advanceTimersByTimeAsync(10_000)
736
- await metrics.flush()
737
- metrics.count('orders_created', 1)
738
- await metrics.flush()
739
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(3)
740
-
741
- await vi.advanceTimersByTimeAsync(295_000)
742
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(4)
743
- })
744
-
745
- it('closes the window at the ceiling for a host out-pacing it', async () => {
746
- // Each refusal sliding the deadline would keep `_nextFlushDelay` pinned at
747
- // the full window, so the flush cadence would never recover.
748
- const instance = createMockInstance({
749
- _sendMetricsBatch: vi.fn((): Promise<SendMetricsBatchOutcome> =>
750
- Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 30_000 })
751
- ),
752
- })
753
- const metrics = createMetrics({ flushIntervalMs: 60_000 }, instance)
754
- metrics.count('orders_created', 1)
755
- await metrics.flush()
756
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
757
-
758
- // Sampled: whether a given moment falls inside a window is timing
759
- // dependent, but it must fall outside one sometimes.
760
- let sawWindowClosed = false
761
- for (let i = 0; i < 70; i++) {
762
- await vi.advanceTimersByTimeAsync(5000)
763
- // Sampled before the flush: a flush that finds the window closed opens
764
- // a fresh one, so sampling after it would always look open.
765
- if ((metrics as any)._retryAfter.remainingMs() === 0) {
766
- sawWindowClosed = true
767
- }
768
- metrics.count('orders_created', 1)
769
- await metrics.flush()
770
- }
771
- expect(sawWindowClosed).toBe(true)
772
- })
773
-
774
- it('does not install a Retry-After that lands after reset', async () => {
775
- let settle: ((outcome: SendMetricsBatchOutcome) => void) | undefined
776
- const instance = createMockInstance({
777
- _sendMetricsBatch: vi.fn(
778
- (): Promise<SendMetricsBatchOutcome> =>
779
- new Promise((resolve) => {
780
- settle = resolve
781
- })
782
- ),
783
- })
784
- const metrics = createMetrics({ flushIntervalMs: 1000 }, instance)
785
- metrics.count('orders_created', 1)
786
- await vi.advanceTimersByTimeAsync(1000)
787
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
788
-
789
- metrics.reset()
790
-
791
- // Settle first: the capture that arms the next timer must not find a
792
- // window belonging to the client that was just torn down.
793
- settle?.({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
794
- await vi.advanceTimersByTimeAsync(0)
795
-
796
- metrics.count('orders_created', 1)
797
- await vi.advanceTimersByTimeAsync(1000)
798
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(2)
799
- })
800
-
801
- it('drops a Retry-After wait on reset', async () => {
802
- const instance = createMockInstance({
803
- _sendMetricsBatch: vi.fn((): Promise<SendMetricsBatchOutcome> =>
804
- Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
805
- ),
806
- })
807
- const metrics = createMetrics({ flushIntervalMs: 10_000 }, instance)
808
- metrics.count('orders_created', 1)
809
- await metrics.flush()
810
-
811
- metrics.reset()
812
- metrics.count('orders_created', 1)
813
- await vi.advanceTimersByTimeAsync(10_000)
814
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(2)
815
- })
816
-
817
- it('does not restart a served-out wait for a sample captured mid-retry', async () => {
818
- // A deadline, not a duration. The retry's timer has already fired, so the
819
- // capture below is the one that arms the next timer — and it sees the
820
- // wait still set, because the send it belongs to has not settled. Holding
821
- // a duration here re-arms for the whole window a second time and leaves
822
- // the sample 300s behind on an endpoint that has already recovered.
823
- let settleRetry: ((outcome: SendMetricsBatchOutcome) => void) | undefined
824
- let call = 0
825
- const instance = createMockInstance({
826
- _sendMetricsBatch: vi.fn((): Promise<SendMetricsBatchOutcome> => {
827
- call++
828
- if (call === 1) {
829
- return Promise.resolve({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
830
- }
831
- return new Promise<SendMetricsBatchOutcome>((resolve) => {
832
- settleRetry = resolve
833
- })
834
- }),
835
- })
836
- const metrics = createMetrics({ flushIntervalMs: 10_000 }, instance)
837
- metrics.count('orders_created', 1)
838
- await vi.advanceTimersByTimeAsync(10_000)
839
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
840
-
841
- // The wait elapses and the retry goes out, but hangs.
842
- await vi.advanceTimersByTimeAsync(300_000)
843
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(2)
844
-
845
- metrics.count('orders_created', 1)
846
- settleRetry?.({ kind: 'ok' })
847
- await vi.advanceTimersByTimeAsync(0)
848
-
849
- // One interval, not another window.
850
- await vi.advanceTimersByTimeAsync(10_000)
851
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(3)
852
- })
853
-
854
- it('keeps its own interval when the endpoint asks for less', async () => {
855
- const instance = createMockInstance({
856
- _sendMetricsBatch: vi.fn((): Promise<SendMetricsBatchOutcome> =>
857
- Promise.resolve({ kind: 'retry-later', error: new Error('503'), retryAfterMs: 10 })
858
- ),
859
- })
860
- const metrics = createMetrics({ flushIntervalMs: 10_000 }, instance)
861
- metrics.count('orders_created', 1)
862
- await vi.advanceTimersByTimeAsync(10_000)
863
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
864
-
865
- await vi.advanceTimersByTimeAsync(1000)
866
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
867
-
868
- await vi.advanceTimersByTimeAsync(10_000)
869
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(2)
870
- })
871
-
872
- it('sends on an explicit flush inside the window', async () => {
873
- // Lifecycle drains (RN background, shutdown) must not become no-ops for
874
- // the length of a window; metrics has no `force` escape hatch.
875
- const outcomes: SendMetricsBatchOutcome[] = [
876
- { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 },
877
- ]
878
- const instance = createMockInstance({
879
- _sendMetricsBatch: vi.fn((): Promise<SendMetricsBatchOutcome> =>
880
- Promise.resolve(outcomes.shift() ?? { kind: 'ok' })
881
- ),
882
- })
883
- const metrics = createMetrics({ flushIntervalMs: 10_000 }, instance)
884
- metrics.count('orders_created', 1)
885
- await vi.advanceTimersByTimeAsync(10_000)
886
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
887
-
888
- metrics.count('orders_created', 1)
889
- await metrics.flush()
890
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(2)
891
- })
892
-
893
- it('ends the wait when a later failure names none', async () => {
894
- const outcomes: SendMetricsBatchOutcome[] = [
895
- { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 },
896
- { kind: 'retry-later', error: new Error('503') },
897
- ]
898
- const instance = createMockInstance({
899
- _sendMetricsBatch: vi.fn((): Promise<SendMetricsBatchOutcome> =>
900
- Promise.resolve(outcomes.shift() ?? { kind: 'ok' })
901
- ),
902
- })
903
- const metrics = createMetrics({ flushIntervalMs: 10_000 }, instance)
904
- metrics.count('orders_created', 1)
905
- await vi.advanceTimersByTimeAsync(10_000)
906
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(1)
907
-
908
- await vi.advanceTimersByTimeAsync(300_000)
909
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(2)
910
-
911
- // Off the 300s window and back on our own backoff: two consecutive
912
- // failures, so one doubling of the interval rather than another 300s.
913
- await vi.advanceTimersByTimeAsync(20_000)
914
- expect(instance._sendMetricsBatch).toHaveBeenCalledTimes(3)
915
- })
916
-
917
- it('does not send when the window is empty', async () => {
918
- createMetrics({ flushIntervalMs: 5000 })
919
- await vi.advanceTimersByTimeAsync(15000)
920
- expect(mockInstance._sendMetricsBatch).not.toHaveBeenCalled()
921
-
922
- const metrics = createMetrics()
923
- await metrics.flush()
924
- expect(mockInstance._sendMetricsBatch).not.toHaveBeenCalled()
925
- })
926
-
927
- it('resets the window after a successful flush — values do not leak into the next one', async () => {
928
- const metrics = createMetrics()
929
- metrics.count('orders_created', 5)
930
- await metrics.flush()
931
- metrics.count('orders_created', 2)
932
- await metrics.flush()
933
-
934
- const payloads = sentPayloads()
935
- expect(payloads).toHaveLength(2)
936
- expect(payloads[1].resourceMetrics[0].scopeMetrics[0].metrics[0].sum!.dataPoints[0].asDouble).toBe(2)
937
- })
938
-
939
- it('retains the window and merges with new samples when the send says retry-later', async () => {
940
- mockInstance._sendMetricsBatch
941
- .mockResolvedValueOnce({ kind: 'retry-later', error: new Error('offline') })
942
- .mockResolvedValue({ kind: 'ok' })
943
-
944
- const metrics = createMetrics()
945
- metrics.count('orders_created', 5)
946
- await metrics.flush()
947
- metrics.count('orders_created', 2)
948
- await metrics.flush()
949
-
950
- const payloads = sentPayloads()
951
- expect(payloads).toHaveLength(2)
952
- expect(payloads[1].resourceMetrics[0].scopeMetrics[0].metrics[0].sum!.dataPoints[0].asDouble).toBe(7)
953
- })
954
-
955
- it('drops the window on a fatal send outcome', async () => {
956
- mockInstance._sendMetricsBatch
957
- .mockResolvedValueOnce({ kind: 'fatal', error: new Error('bad key') })
958
- .mockResolvedValue({ kind: 'ok' })
959
-
960
- const metrics = createMetrics()
961
- metrics.count('orders_created', 5)
962
- await metrics.flush()
963
- metrics.count('orders_created', 2)
964
- await metrics.flush()
965
-
966
- expect(sentPayloads()[1].resourceMetrics[0].scopeMetrics[0].metrics[0].sum!.dataPoints[0].asDouble).toBe(2)
967
- })
968
-
969
- it('keeps flushing on the interval', async () => {
970
- const metrics = createMetrics({ flushIntervalMs: 5000 })
971
- metrics.count('a', 1)
972
- await vi.advanceTimersByTimeAsync(5000)
973
- metrics.count('a', 1)
974
- await vi.advanceTimersByTimeAsync(5000)
975
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(2)
976
- })
977
-
978
- it('stops the timer and clears state on reset', async () => {
979
- const metrics = createMetrics({ flushIntervalMs: 5000 })
980
- metrics.count('a', 1)
981
- metrics.reset()
982
- await vi.advanceTimersByTimeAsync(20000)
983
- expect(mockInstance._sendMetricsBatch).not.toHaveBeenCalled()
984
- })
985
-
986
- it('drainWindow returns the built payload synchronously and resets the window', async () => {
987
- const metrics = createMetrics()
988
- metrics.count('orders_created', 3)
989
-
990
- const payload = metrics.drainWindow()
991
- expect(payload!.resourceMetrics[0].scopeMetrics[0].metrics[0].sum!.dataPoints[0].asDouble).toBe(3)
992
-
993
- // The window was consumed: nothing left for the regular flush.
994
- await metrics.flush()
995
- expect(mockInstance._sendMetricsBatch).not.toHaveBeenCalled()
996
- })
997
-
998
- it('retries a merged-back window on the next interval even with no new samples', async () => {
999
- mockInstance._sendMetricsBatch
1000
- .mockResolvedValueOnce({ kind: 'retry-later', error: new Error('offline') })
1001
- .mockResolvedValue({ kind: 'ok' })
1002
-
1003
- const metrics = createMetrics({ flushIntervalMs: 5000 })
1004
- metrics.count('orders_created', 5)
1005
- await vi.advanceTimersByTimeAsync(5000)
1006
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
1007
-
1008
- // No new captures — the retained window must not be stranded until shutdown.
1009
- await vi.advanceTimersByTimeAsync(5000)
1010
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(2)
1011
- const payload: OtlpMetricsPayload = mockInstance._sendMetricsBatch.mock.calls[1][0]
1012
- expect(payload.resourceMetrics[0].scopeMetrics[0].metrics[0].sum!.dataPoints[0].asDouble).toBe(5)
1013
- })
1014
-
1015
- it('drainWindow returns null when the window is empty', () => {
1016
- const metrics = createMetrics()
1017
- expect(metrics.drainWindow()).toBeNull()
1018
- })
1019
- })
1020
-
1021
- describe('guardrails and filtering', () => {
1022
- it('caps distinct series per window and warns once', async () => {
1023
- const metrics = createMetrics({ maxSeriesPerFlush: 2 })
1024
- metrics.count('a', 1)
1025
- metrics.count('b', 1)
1026
- metrics.count('c', 1)
1027
- metrics.count('d', 1)
1028
- metrics.count('a', 1) // existing series still aggregates
1029
- await metrics.flush()
1030
-
1031
- const sent = sentMetrics()
1032
- expect(sent.map((m) => m.name).sort()).toEqual(['a', 'b'])
1033
- expect(sent.find((m) => m.name === 'a')!.sum!.dataPoints[0].asDouble).toBe(2)
1034
- expect((logger.warn as vi.Mock).mock.calls.length).toBe(1)
1035
- })
1036
-
1037
- it('re-applies the series cap when merging a failed window back', async () => {
1038
- let resolveSend!: (outcome: SendMetricsBatchOutcome) => void
1039
- mockInstance._sendMetricsBatch
1040
- .mockImplementationOnce(() => new Promise<SendMetricsBatchOutcome>((resolve) => (resolveSend = resolve)))
1041
- .mockResolvedValue({ kind: 'ok' })
1042
-
1043
- const metrics = createMetrics({ maxSeriesPerFlush: 2 })
1044
- metrics.count('a', 1)
1045
- metrics.count('b', 1)
1046
- const inflight = metrics.flush()
1047
- // New series captured while the failing send is in flight fill the fresh window to the cap.
1048
- metrics.count('c', 1)
1049
- metrics.count('d', 1)
1050
- resolveSend({ kind: 'retry-later', error: new Error('offline') })
1051
- await inflight
1052
-
1053
- await metrics.flush()
1054
-
1055
- const payloads = sentPayloads()
1056
- expect(payloads).toHaveLength(2)
1057
- const dataPointCount = payloads[1].resourceMetrics[0].scopeMetrics[0].metrics.reduce(
1058
- (n, m) => n + (m.sum?.dataPoints.length ?? 0),
1059
- 0
1060
- )
1061
- expect(dataPointCount).toBeLessThanOrEqual(2)
1062
- expect((logger.warn as vi.Mock).mock.calls.some((c) => String(c[0]).includes('series cap'))).toBe(true)
1063
- })
1064
-
1065
- it('drops non-finite values and negative counts', async () => {
1066
- const metrics = createMetrics()
1067
- metrics.count('a', NaN)
1068
- metrics.count('a', Infinity)
1069
- metrics.count('a', -1)
1070
- metrics.gauge('b', NaN)
1071
- metrics.histogram('c', -Infinity)
1072
- metrics.gauge('b', -5) // negative gauge is valid
1073
- await metrics.flush()
1074
-
1075
- const sent = sentMetrics()
1076
- expect(sent).toHaveLength(1)
1077
- expect(sent[0].name).toBe('b')
1078
- expect(sent[0].gauge!.dataPoints[0].asDouble).toBe(-5)
1079
- })
1080
-
1081
- it('drops samples with unserializable attributes instead of throwing', async () => {
1082
- const metrics = createMetrics()
1083
- const throwingAttrs = {}
1084
- Object.defineProperty(throwingAttrs, 'bad', {
1085
- enumerable: true,
1086
- get() {
1087
- throw new Error('boom')
1088
- },
1089
- })
1090
-
1091
- expect(() => metrics.count('good', 1, { attributes: { plan: 'free' } })).not.toThrow()
1092
- expect(() => metrics.count('bigint_attr', 1, { attributes: { jobId: BigInt(1) } as any })).not.toThrow()
1093
- expect(() => metrics.count('throwing_attr', 1, { attributes: throwingAttrs as any })).not.toThrow()
1094
- await metrics.flush()
1095
-
1096
- // Only the well-formed sample ships; the malformed ones are dropped with a warning.
1097
- expect(sentMetrics().map((m) => m.name)).toEqual(['good'])
1098
- const attrWarns = (logger.warn as vi.Mock).mock.calls.filter((c) => String(c[0]).includes('attributes'))
1099
- expect(attrWarns).toHaveLength(2)
1100
- })
1101
-
1102
- it('drops samples with an empty name', async () => {
1103
- const metrics = createMetrics()
1104
- metrics.count('', 1)
1105
- await metrics.flush()
1106
- expect(mockInstance._sendMetricsBatch).not.toHaveBeenCalled()
1107
- })
1108
-
1109
- it('applies beforeSend: transform, chain, drop, and throw', async () => {
1110
- const metrics = createMetrics({
1111
- beforeSend: [
1112
- (m) => (m.name === 'dropped' ? null : m),
1113
- (m) => ({ ...m, attributes: { ...m.attributes, processed: true } }),
1114
- ],
1115
- })
1116
- metrics.count('kept', 1)
1117
- metrics.count('dropped', 1)
1118
- await metrics.flush()
1119
-
1120
- const sent = sentMetrics()
1121
- expect(sent).toHaveLength(1)
1122
- expect(sent[0].name).toBe('kept')
1123
- expect(sent[0].sum!.dataPoints[0].attributes).toContainEqual({
1124
- key: 'processed',
1125
- value: { boolValue: true },
1126
- })
1127
- })
1128
-
1129
- it('snapshots attributes at capture time — later caller mutation cannot corrupt the series', async () => {
1130
- const metrics = createMetrics()
1131
- const attributes = { plan: 'free' }
1132
- metrics.count('api_calls', 1, { attributes })
1133
- attributes.plan = 'pro'
1134
- metrics.count('api_calls', 1, { attributes })
1135
- await metrics.flush()
1136
-
1137
- const sent = sentMetrics()
1138
- expect(sent[0].sum!.dataPoints).toHaveLength(2)
1139
- const values = sent[0].sum!.dataPoints.map((dp) => dp.attributes.find((a) => a.key === 'plan')!.value.stringValue)
1140
- expect(values.sort()).toEqual(['free', 'pro'])
1141
- })
1142
-
1143
- it('warns once when a metric name is reused with a different type, but keeps both series', async () => {
1144
- const metrics = createMetrics()
1145
- metrics.count('throughput', 5)
1146
- metrics.gauge('throughput', 42)
1147
- metrics.gauge('throughput', 43)
1148
- await metrics.flush()
1149
-
1150
- // Both series still ship — the warning is a dev-time hint, not a drop.
1151
- const sent = sentMetrics()
1152
- expect(sent.some((m) => m.sum)).toBe(true)
1153
- expect(sent.some((m) => m.gauge)).toBe(true)
1154
- const typeWarns = (logger.warn as vi.Mock).mock.calls.filter((c) => String(c[0]).includes('already used'))
1155
- expect(typeWarns).toHaveLength(1)
1156
- })
1157
-
1158
- it('drops counts made negative by beforeSend', async () => {
1159
- const metrics = createMetrics({
1160
- beforeSend: (m) => ({ ...m, value: -5 }),
1161
- })
1162
- metrics.count('a', 1)
1163
- await metrics.flush()
1164
- expect(mockInstance._sendMetricsBatch).not.toHaveBeenCalled()
1165
- })
1166
-
1167
- it('drops a sample whose beforeSend result has an unknown type and still sends the rest', async () => {
1168
- const metrics = createMetrics({
1169
- beforeSend: (m) => (m.name === 'bad' ? ({ name: m.name, value: m.value } as any) : m),
1170
- })
1171
- metrics.count('good', 1)
1172
- metrics.count('bad', 1)
1173
- await metrics.flush()
1174
-
1175
- expect(sentMetrics().map((m) => m.name)).toEqual(['good'])
1176
- expect((logger.warn as vi.Mock).mock.calls.some((c) => String(c[0]).includes('unknown type'))).toBe(true)
1177
- })
1178
-
1179
- it('drops the sample when beforeSend throws', async () => {
1180
- const metrics = createMetrics({
1181
- beforeSend: () => {
1182
- throw new Error('boom')
1183
- },
1184
- })
1185
- metrics.count('a', 1)
1186
- await metrics.flush()
1187
- expect(mockInstance._sendMetricsBatch).not.toHaveBeenCalled()
1188
- })
1189
-
1190
- it('no-ops when the host is disabled or opted out', async () => {
1191
- const disabledInstance = createMockInstance({ isDisabled: true })
1192
- const disabled = createMetrics({}, disabledInstance)
1193
- disabled.count('a', 1)
1194
- await disabled.flush()
1195
-
1196
- const optedOutInstance = createMockInstance({ optedOut: true })
1197
- const optedOut = createMetrics({}, optedOutInstance)
1198
- optedOut.count('a', 1)
1199
- await optedOut.flush()
1200
-
1201
- expect(disabledInstance._sendMetricsBatch).not.toHaveBeenCalled()
1202
- expect(optedOutInstance._sendMetricsBatch).not.toHaveBeenCalled()
1203
- })
1204
- })
1205
-
1206
- it('does not hold a later capture at a window a successful flush already closed', async () => {
1207
- let sends = 0
1208
- mockInstance._sendMetricsBatch = vi.fn(async (): Promise<SendMetricsBatchOutcome> => {
1209
- sends += 1
1210
- return sends === 1 ? { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 } : { kind: 'ok' }
1211
- })
1212
- const metrics = createMetrics({ flushIntervalMs: 5000 })
1213
-
1214
- metrics.count('a', 1)
1215
- await vi.advanceTimersByTimeAsync(5000)
1216
- await metrics.flush()
1217
- const closedAt = Date.now()
1218
-
1219
- metrics.count('b', 1)
1220
- await vi.advanceTimersByTimeAsync(5000)
1221
-
1222
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(3)
1223
- expect(Date.now() - closedAt).toBeLessThanOrEqual(5000)
1224
- })
1225
-
1226
- it('releases a series captured mid-flush once that flush closes the window', async () => {
1227
- const metrics = createMetrics({ flushIntervalMs: 10_000 })
1228
- let sends = 0
1229
- mockInstance._sendMetricsBatch = vi.fn(async (): Promise<SendMetricsBatchOutcome> => {
1230
- sends += 1
1231
- if (sends === 1) {
1232
- return { kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 }
1233
- }
1234
- await Promise.resolve()
1235
- if (sends === 2) {
1236
- metrics.count('mid', 1)
1237
- }
1238
- return { kind: 'ok' }
1239
- })
1240
-
1241
- metrics.count('a', 1)
1242
- await vi.advanceTimersByTimeAsync(10_000)
1243
- await vi.advanceTimersByTimeAsync(10_000)
1244
- await metrics.flush()
1245
-
1246
- await vi.advanceTimersByTimeAsync(10_000)
1247
- expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(3)
1248
- })
1249
- })