posthog-node 5.73.1 → 6.0.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 (156) hide show
  1. package/MIGRATION.md +556 -0
  2. package/README.md +3 -1
  3. package/dist/ai-capture/routing.d.ts +0 -3
  4. package/dist/ai-capture/routing.d.ts.map +1 -1
  5. package/dist/ai-capture/routing.js +2 -14
  6. package/dist/ai-capture/routing.mjs +1 -4
  7. package/dist/capture-lane/lane.d.ts +109 -0
  8. package/dist/capture-lane/lane.d.ts.map +1 -0
  9. package/dist/capture-lane/lane.js +308 -0
  10. package/dist/capture-lane/lane.mjs +270 -0
  11. package/dist/capture-lane/limits.d.ts +7 -0
  12. package/dist/capture-lane/limits.d.ts.map +1 -0
  13. package/dist/{capture-v1/config.js → capture-lane/limits.js} +13 -11
  14. package/dist/capture-lane/limits.mjs +4 -0
  15. package/dist/capture-lane/settings.d.ts +30 -0
  16. package/dist/capture-lane/settings.d.ts.map +1 -0
  17. package/dist/capture-lane/settings.js +100 -0
  18. package/dist/capture-lane/settings.mjs +47 -0
  19. package/dist/capture-v1/compression.d.ts +18 -0
  20. package/dist/capture-v1/compression.d.ts.map +1 -0
  21. package/dist/capture-v1/compression.js +70 -0
  22. package/dist/capture-v1/compression.mjs +26 -0
  23. package/dist/capture-v1/errors.d.ts +23 -7
  24. package/dist/capture-v1/errors.d.ts.map +1 -1
  25. package/dist/capture-v1/errors.js +37 -8
  26. package/dist/capture-v1/errors.mjs +29 -6
  27. package/dist/capture-v1/sender.d.ts +63 -23
  28. package/dist/capture-v1/sender.d.ts.map +1 -1
  29. package/dist/capture-v1/sender.js +281 -74
  30. package/dist/capture-v1/sender.mjs +275 -77
  31. package/dist/capture-v1/serialize.d.ts +28 -0
  32. package/dist/capture-v1/serialize.d.ts.map +1 -0
  33. package/dist/capture-v1/serialize.js +82 -0
  34. package/dist/capture-v1/serialize.mjs +38 -0
  35. package/dist/capture-v1/transform.d.ts +10 -25
  36. package/dist/capture-v1/transform.d.ts.map +1 -1
  37. package/dist/capture-v1/transform.js +33 -64
  38. package/dist/capture-v1/transform.mjs +28 -53
  39. package/dist/capture-v1/types.d.ts +16 -14
  40. package/dist/capture-v1/types.d.ts.map +1 -1
  41. package/dist/capture-v1/types.js +27 -1
  42. package/dist/capture-v1/types.mjs +3 -1
  43. package/dist/capture-v1/uuid.d.ts +9 -0
  44. package/dist/capture-v1/uuid.d.ts.map +1 -0
  45. package/dist/capture-v1/uuid.js +75 -0
  46. package/dist/capture-v1/uuid.mjs +34 -0
  47. package/dist/client.d.ts +201 -94
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +485 -246
  50. package/dist/client.mjs +485 -246
  51. package/dist/compression.node.d.ts +13 -0
  52. package/dist/compression.node.d.ts.map +1 -0
  53. package/dist/{capture-v1/routing.js → compression.node.js} +23 -16
  54. package/dist/compression.node.mjs +18 -0
  55. package/dist/entrypoints/index.node.d.ts +2 -0
  56. package/dist/entrypoints/index.node.d.ts.map +1 -1
  57. package/dist/entrypoints/index.node.js +11 -4
  58. package/dist/entrypoints/index.node.mjs +4 -0
  59. package/dist/event-defaults.d.ts +46 -0
  60. package/dist/event-defaults.d.ts.map +1 -0
  61. package/dist/event-defaults.js +141 -0
  62. package/dist/event-defaults.mjs +79 -0
  63. package/dist/exports.d.ts +3 -0
  64. package/dist/exports.d.ts.map +1 -1
  65. package/dist/exports.js +22 -11
  66. package/dist/exports.mjs +1 -0
  67. package/dist/extensions/context/context.d.ts +0 -1
  68. package/dist/extensions/context/context.d.ts.map +1 -1
  69. package/dist/extensions/context/context.js +4 -3
  70. package/dist/extensions/context/context.mjs +4 -3
  71. package/dist/extensions/context/event-context.d.ts.map +1 -1
  72. package/dist/extensions/context/event-context.js +3 -0
  73. package/dist/extensions/context/event-context.mjs +3 -0
  74. package/dist/extensions/context/types.d.ts +9 -1
  75. package/dist/extensions/context/types.d.ts.map +1 -1
  76. package/dist/extensions/error-tracking/index.d.ts +1 -1
  77. package/dist/extensions/error-tracking/index.d.ts.map +1 -1
  78. package/dist/extensions/error-tracking/index.js +71 -7
  79. package/dist/extensions/error-tracking/index.mjs +75 -11
  80. package/dist/extensions/express.d.ts +8 -0
  81. package/dist/extensions/express.d.ts.map +1 -1
  82. package/dist/extensions/express.js +3 -3
  83. package/dist/extensions/express.mjs +4 -4
  84. package/dist/extensions/fetch-request.d.ts.map +1 -1
  85. package/dist/extensions/fetch-request.js +2 -2
  86. package/dist/extensions/fetch-request.mjs +3 -3
  87. package/dist/extensions/nestjs.d.ts.map +1 -1
  88. package/dist/extensions/nestjs.js +7 -4
  89. package/dist/extensions/nestjs.mjs +8 -5
  90. package/dist/extensions/tracing-headers.d.ts +7 -0
  91. package/dist/extensions/tracing-headers.d.ts.map +1 -1
  92. package/dist/extensions/tracing-headers.js +11 -1
  93. package/dist/extensions/tracing-headers.mjs +9 -2
  94. package/dist/feature-flag-evaluations.d.ts +5 -5
  95. package/dist/feature-flag-evaluations.d.ts.map +1 -1
  96. package/dist/feature-flag-evaluations.js +16 -9
  97. package/dist/feature-flag-evaluations.mjs +16 -9
  98. package/dist/flag-events.d.ts +1 -1
  99. package/dist/flag-events.d.ts.map +1 -1
  100. package/dist/flag-events.js +2 -2
  101. package/dist/flag-events.mjs +2 -2
  102. package/dist/flags-response.d.ts +2 -0
  103. package/dist/flags-response.d.ts.map +1 -1
  104. package/dist/flags-response.js +6 -0
  105. package/dist/flags-response.mjs +4 -1
  106. package/dist/types.d.ts +192 -27
  107. package/dist/types.d.ts.map +1 -1
  108. package/dist/types.js +1 -0
  109. package/dist/types.mjs +1 -0
  110. package/dist/version.d.ts +1 -1
  111. package/dist/version.d.ts.map +1 -1
  112. package/dist/version.js +1 -1
  113. package/dist/version.mjs +1 -1
  114. package/package.json +5 -4
  115. package/src/ai-capture/routing.ts +0 -6
  116. package/src/capture-lane/lane.ts +414 -0
  117. package/src/capture-lane/limits.ts +8 -0
  118. package/src/capture-lane/settings.ts +119 -0
  119. package/src/capture-v1/compression.ts +50 -0
  120. package/src/capture-v1/errors.ts +50 -11
  121. package/src/capture-v1/sender.ts +405 -111
  122. package/src/capture-v1/serialize.ts +77 -0
  123. package/src/capture-v1/transform.ts +59 -92
  124. package/src/capture-v1/types.ts +19 -15
  125. package/src/capture-v1/uuid.ts +53 -0
  126. package/src/client.ts +885 -446
  127. package/src/compression.node.ts +30 -0
  128. package/src/entrypoints/index.node.ts +6 -0
  129. package/src/event-defaults.ts +177 -0
  130. package/src/exports.ts +3 -0
  131. package/src/extensions/context/context.ts +4 -4
  132. package/src/extensions/context/event-context.ts +3 -1
  133. package/src/extensions/context/types.ts +10 -1
  134. package/src/extensions/error-tracking/index.ts +51 -7
  135. package/src/extensions/express.ts +12 -3
  136. package/src/extensions/fetch-request.ts +7 -3
  137. package/src/extensions/nestjs.ts +9 -5
  138. package/src/extensions/tracing-headers.ts +26 -7
  139. package/src/feature-flag-evaluations.ts +31 -23
  140. package/src/flag-events.ts +5 -2
  141. package/src/flags-response.ts +6 -1
  142. package/src/types.ts +212 -44
  143. package/src/version.ts +1 -1
  144. package/dist/ai-capture/batching.d.ts +0 -11
  145. package/dist/ai-capture/batching.d.ts.map +0 -1
  146. package/dist/ai-capture/batching.js +0 -77
  147. package/dist/ai-capture/batching.mjs +0 -36
  148. package/dist/capture-v1/config.d.ts +0 -11
  149. package/dist/capture-v1/config.d.ts.map +0 -1
  150. package/dist/capture-v1/config.mjs +0 -8
  151. package/dist/capture-v1/routing.d.ts +0 -21
  152. package/dist/capture-v1/routing.d.ts.map +0 -1
  153. package/dist/capture-v1/routing.mjs +0 -7
  154. package/src/ai-capture/batching.ts +0 -47
  155. package/src/capture-v1/config.ts +0 -18
  156. package/src/capture-v1/routing.ts +0 -28
@@ -1,58 +1,131 @@
1
+ import { type FetchLike, type PostHogFetchOptions, type PostHogFetchResponse, uuidv7 } from '@posthog/core'
2
+
3
+ import { type CaptureCodec, type CaptureCompression, webCompressor } from './compression'
1
4
  import {
2
- type FetchLike,
3
- type PostHogEventProperties,
4
- type PostHogFetchBodyBytes,
5
- type PostHogFetchOptions,
6
- type PostHogFetchResponse,
7
- gzipCompress,
8
- safeJsonStringify,
9
- safeSetTimeout,
10
- uuidv7,
11
- } from '@posthog/core'
12
-
13
- import { CaptureV1Error, type V1DroppedEvent } from './errors'
14
- import { buildV1Batch } from './transform'
15
- import type { V1BatchResponse, V1Event } from './types'
16
-
17
- const V1_ANALYTICS_PATH = '/i/v1/analytics/events'
18
- const DEFAULT_MAX_BACKOFF_MS = 30_000
5
+ CaptureError,
6
+ CaptureLossTally,
7
+ type CaptureDroppedEvent,
8
+ type CaptureErrorParams,
9
+ describeCaptureLoss,
10
+ } from './errors'
11
+ import { type SerializedV1Event, buildV1Body } from './serialize'
12
+ import type { CaptureEndpoint, V1BatchResponse, V1EventResult } from './types'
13
+ import { canonicalizeUuid } from './uuid'
14
+
15
+ /** Wait before the first retry; each later retry doubles it. */
16
+ export const RETRY_BASE_DELAY_MS = 100
17
+ /** Ceiling for every retry wait, including one raised by `Retry-After`. */
18
+ export const MAX_RETRY_DELAY_MS = 30_000
19
+
20
+ // Retry waits and request deadlines use ref'd timers, unlike safeSetTimeout, so an
21
+ // awaited flush or shutdown keeps the process alive until the send finishes.
22
+ /** Settles with `work`, or rejects with an `AbortError` as soon as `signal` aborts. */
23
+ async function raceAbort<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
24
+ if (!signal) {
25
+ return work
26
+ }
27
+ let onAbort!: () => void
28
+ const aborted = new Promise<never>((_resolve, reject) => {
29
+ onAbort = () => {
30
+ const abortError = new Error('Capture V1 request aborted while compressing the body')
31
+ abortError.name = 'AbortError'
32
+ abortError.cause = signal.reason
33
+ reject(abortError)
34
+ }
35
+ if (signal.aborted) {
36
+ onAbort()
37
+ } else {
38
+ signal.addEventListener('abort', onAbort, { once: true })
39
+ }
40
+ })
41
+ try {
42
+ return await Promise.race([work, aborted])
43
+ } finally {
44
+ signal.removeEventListener('abort', onAbort)
45
+ }
46
+ }
47
+
48
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
49
+ return new Promise((resolve) => {
50
+ const onAbort = (): void => {
51
+ clearTimeout(timer)
52
+ resolve()
53
+ }
54
+ // A lane reuses one signal for every send, so a finished wait must not leave its listener behind.
55
+ const timer = setTimeout(() => {
56
+ signal?.removeEventListener('abort', onAbort)
57
+ resolve()
58
+ }, ms)
59
+ signal?.addEventListener('abort', onAbort, { once: true })
60
+ })
61
+ }
19
62
 
20
63
  /** HTTP statuses a capture request is retried on. 404 and 429 can come from a proxy in front of capture. */
21
64
  const RETRYABLE_STATUSES = new Set([404, 408, 429, 500, 502, 503, 504])
22
65
 
66
+ /** Only these redirects keep the method and body, so they are the only ones a capture request follows. */
67
+ const FOLLOWED_REDIRECT_STATUSES = new Set([307, 308])
68
+ const MAX_REDIRECTS = 5
69
+
70
+ /** Errors the sender raised for its own request deadline, so a loss summary can call them timeouts. */
71
+ const timeoutErrors = new WeakSet<Error>()
72
+
73
+ /** Drop details for a copy of an event the server dropped as a duplicate of an earlier one in the request. */
74
+ export const DUPLICATE_EVENT_UUID = 'duplicate_event_uuid'
75
+
23
76
  export interface V1CaptureSenderConfig {
24
77
  host: string
78
+ /** The capture lane this sender posts to. */
79
+ path: CaptureEndpoint
25
80
  apiKey: string
26
- /** Canonical `$lib` identity, materialized by the server from `PostHog-Sdk-Info`. */
81
+ /** The `PostHog-Sdk-Info` library name. PostHog fills `$lib` from it only for an event that has no `$lib`. */
27
82
  libraryId: string
28
83
  libraryVersion: string
29
84
  /** Value for the `User-Agent` header, if the runtime allows setting it. */
30
85
  userAgent?: string
31
86
  historicalMigration: boolean
32
- /** When true, the body is gzip-compressed (falling back to uncompressed on failure). */
33
- compressionEnabled: boolean
87
+ /** The body encoding; a body that fails to compress is sent uncompressed. */
88
+ compression: CaptureCompression
34
89
  requestTimeoutMs: number
35
- /** Total attempts, including the first (1 initial + N retries). */
36
- maxAttempts: number
37
- /** Base exponential backoff, doubled each retry and capped at `maxBackoffMs`. */
38
- initialRetryDelayMs: number
39
- /** Single ceiling for both the backoff schedule and the `Retry-After` clamp. */
40
- maxBackoffMs?: number
90
+ /** Retries after the first attempt. */
91
+ maxRetries: number
41
92
  isDebug?: boolean
42
93
  }
43
94
 
44
95
  export interface V1CaptureSenderHooks {
45
96
  fetch: FetchLike
46
- /** Surfaces partial/terminal delivery failures on the client error channel. */
47
- onError: (error: Error) => void
97
+ /**
98
+ * Surfaces partial/terminal delivery failures on the client error channel, at most once per
99
+ * batch. `summary` is one line with counts and causes only, for when nothing listens.
100
+ */
101
+ onError: (error: CaptureError, summary: string) => void
48
102
  now?: () => number
49
- sleep?: (ms: number) => Promise<void>
103
+ /** Waits between attempts. The sender stops waiting when `signal` aborts, even if this does not. */
104
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>
50
105
  generateRequestId?: () => string
51
- compress?: (payload: string, isDebug?: boolean) => Promise<Blob | PostHogFetchBodyBytes | null>
106
+ /** Uniform in [0, 1); sets the jitter of each retry wait. */
107
+ random?: () => number
108
+ compress?: (payload: string, codec: CaptureCodec) => Promise<Uint8Array | null>
109
+ }
110
+
111
+ export interface V1SendOptions {
112
+ /** Aborting stops the current attempt and every later one; the pending events come back as unsent. */
113
+ signal?: AbortSignal
114
+ /**
115
+ * When true, events whose last attempt got no HTTP response (or were cut off by `signal`) are
116
+ * returned to the caller unreported, so it can queue them again. When false they are reported
117
+ * as undelivered.
118
+ */
119
+ keepUnsent?: boolean
52
120
  }
53
121
 
54
- interface V1CaptureAttempt {
122
+ interface RedirectOutcome {
55
123
  response: PostHogFetchResponse
124
+ /** Set when `response` is a redirect the sender does not follow. */
125
+ redirectFailure?: string
126
+ }
127
+
128
+ interface V1CaptureAttempt extends RedirectOutcome {
56
129
  signal: AbortSignal
57
130
  waitFor<T>(operation: Promise<T>): Promise<T>
58
131
  cancelBody: () => Promise<void>
@@ -60,72 +133,85 @@ interface V1CaptureAttempt {
60
133
  }
61
134
 
62
135
  /**
63
- * Sends already-normalized events to the Capture V1 endpoint
64
- * (`POST /i/v1/analytics/events`), owning the full attempt loop: per-event
65
- * partial retry, exponential backoff clamped against `Retry-After`, v1 status
66
- * classification, and surfacing drops / undelivered events on the error
67
- * channel. Used by both the batched and immediate send paths.
136
+ * Sends already-serialized events to one Capture V1 lane (`config.path`),
137
+ * owning the full attempt loop: per-event partial retry, exponential backoff
138
+ * clamped against `Retry-After`, v1 status classification, and surfacing drops
139
+ * / undelivered events on the error channel. Used by both the batched and
140
+ * immediate send paths.
68
141
  *
69
142
  * Never throws for a handled outcome: after exhausting its own attempt budget it
70
- * reports the failure via `onError` and resolves, so the caller's queue treats
71
- * the batch as consumed (the internal budget replaces v0's queue-level retry).
143
+ * reports the failure via `onError` and resolves. Only events that never got an
144
+ * HTTP response can come back to the caller, and only with `keepUnsent`.
72
145
  */
73
146
  export class V1CaptureSender {
74
147
  private readonly config: V1CaptureSenderConfig
75
- private readonly maxBackoffMs: number
148
+ private readonly hostOrigin: string | undefined
76
149
  private readonly fetchFn: FetchLike
77
- private readonly onError: (error: Error) => void
150
+ private readonly onError: (error: CaptureError, summary: string) => void
78
151
  private readonly now: () => number
79
- private readonly sleep: (ms: number) => Promise<void>
152
+ private readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>
80
153
  private readonly generateRequestId: () => string
81
- private readonly compress: (payload: string, isDebug?: boolean) => Promise<Blob | PostHogFetchBodyBytes | null>
154
+ private readonly random: () => number
155
+ private readonly compress: (payload: string, codec: CaptureCodec) => Promise<Uint8Array | null>
82
156
 
83
157
  constructor(config: V1CaptureSenderConfig, hooks: V1CaptureSenderHooks) {
84
158
  this.config = config
85
- this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS
159
+ this.hostOrigin = originOf(config.host)
86
160
  this.fetchFn = hooks.fetch
87
161
  this.onError = hooks.onError
88
162
  this.now = hooks.now ?? Date.now
89
- this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve) => safeSetTimeout(resolve, ms)))
163
+ this.sleep = hooks.sleep ?? abortableSleep
90
164
  this.generateRequestId = hooks.generateRequestId ?? uuidv7
91
- this.compress = hooks.compress ?? gzipCompress
165
+ this.random = hooks.random ?? Math.random
166
+ this.compress = hooks.compress ?? webCompressor.compress
92
167
  }
93
168
 
94
- async sendV1Batch(messages: PostHogEventProperties[]): Promise<void> {
95
- if (messages.length === 0) {
96
- return
169
+ /** Sends `events` and resolves with the ones to queue again (always empty unless `keepUnsent`). */
170
+ async send<T extends SerializedV1Event>(events: T[], options: V1SendOptions = {}): Promise<T[]> {
171
+ if (events.length === 0) {
172
+ return []
97
173
  }
98
174
 
175
+ const { signal, keepUnsent = false } = options
99
176
  const requestId = this.generateRequestId()
100
177
  // created_at is generated once and stays stable across every retry.
101
178
  const createdAt = new Date(this.now()).toISOString()
102
- const { batch } = buildV1Batch(messages, {
103
- createdAt,
104
- historicalMigration: this.config.historicalMigration,
105
- })
179
+ const url = `${this.config.host}${this.config.path}`
180
+ const drops: CaptureDroppedEvent[] = []
181
+ const loss = new CaptureLossTally()
182
+ let pending = events
106
183
 
107
- const url = `${this.config.host}${V1_ANALYTICS_PATH}`
108
- const drops: V1DroppedEvent[] = []
109
- let pending = batch
184
+ const unsent = (cause: unknown, failure: string): T[] => {
185
+ if (keepUnsent) {
186
+ this.surfacePartialDrops(requestId, drops, loss)
187
+ return pending
188
+ }
189
+ this.surfaceBatchFailure(requestId, drops, pending, cause, loss, failure)
190
+ return []
191
+ }
110
192
 
111
- // Guard against a misconfigured budget (e.g. fetchRetryCount: -1): always make
112
- // at least one attempt so a bad config surfaces a delivery error instead of
113
- // silently dropping the batch without ever sending or calling onError.
114
- const maxAttempts = Math.max(1, this.config.maxAttempts)
193
+ // Always make one attempt, so a bad budget reports a delivery error instead of dropping the batch silently.
194
+ const { maxRetries } = this.config
195
+ const maxAttempts = (Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 0) + 1
115
196
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
197
+ if (signal?.aborted) {
198
+ return unsent(signal.reason, 'not sent: aborted')
199
+ }
116
200
  const isLastAttempt = attempt === maxAttempts
117
- const payload = safeJsonStringify({
118
- created_at: createdAt,
119
- ...(this.config.historicalMigration ? { historical_migration: true } : {}),
120
- batch: pending,
121
- })
201
+ const payload = buildV1Body(pending, { createdAt, historicalMigration: this.config.historicalMigration })
122
202
 
123
203
  let captureAttempt: V1CaptureAttempt | undefined
124
204
  let retryDelayMs: number | undefined
125
205
  try {
126
- captureAttempt = await this.sendOnce(url, payload, attempt, requestId)
127
- const { response, signal } = captureAttempt
206
+ captureAttempt = await this.sendOnce(url, payload, attempt, requestId, signal)
207
+ const { response, signal: attemptSignal, redirectFailure } = captureAttempt
128
208
  const { status } = response
209
+ if (redirectFailure !== undefined) {
210
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {})
211
+ const failure = `failed on a redirect it does not follow (HTTP ${status})`
212
+ this.surfaceBatchFailure(requestId, drops, pending, new Error(redirectFailure), loss, failure)
213
+ return []
214
+ }
129
215
  if (status < 200 || status >= 300) {
130
216
  if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
131
217
  const retryAfterMs = this.parseRetryAfter(response)
@@ -133,32 +219,50 @@ export class V1CaptureSender {
133
219
  retryDelayMs = this.backoffDelay(attempt, retryAfterMs)
134
220
  } else {
135
221
  const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor)
136
- return this.surfaceBatchFailure(requestId, drops, pending, httpError)
222
+ this.surfaceBatchFailure(requestId, drops, pending, httpError, loss, `failed with HTTP ${status}`)
223
+ return []
137
224
  }
138
225
  } else {
139
226
  let parsed: V1BatchResponse
140
227
  try {
141
228
  parsed = await captureAttempt.waitFor(this.parseResponse(response))
142
229
  } catch (error) {
143
- if (signal.aborted) {
230
+ if (attemptSignal.aborted) {
144
231
  throw error
145
232
  }
146
- // A 2xx we cannot parse is terminal — re-sending against a broken success would loop forever.
147
- return this.surfaceBatchFailure(
233
+ // A 2xx without a readable results map is terminal — re-sending against a broken success would loop forever.
234
+ this.surfaceBatchFailure(
148
235
  requestId,
149
236
  drops,
150
237
  pending,
151
- new Error(`Capture V1 returned an unparseable ${status} response body`)
238
+ new Error(`Capture V1 returned an unparseable ${status} response body`),
239
+ loss,
240
+ `failed with an unreadable response (HTTP ${status})`
152
241
  )
242
+ return []
153
243
  }
154
244
 
245
+ const dropsBefore = drops.length
155
246
  const retryable = this.classify(pending, parsed, drops)
247
+ for (const drop of drops.slice(dropsBefore)) {
248
+ const cause = drop.details === DUPLICATE_EVENT_UUID ? 'dropped as duplicate uuids' : 'dropped by the server'
249
+ loss.add(`${cause} (HTTP ${status})`, 1)
250
+ }
156
251
  if (retryable.length === 0) {
157
- return this.surfacePartialDrops(requestId, drops)
252
+ this.surfacePartialDrops(requestId, drops, loss)
253
+ return []
158
254
  }
159
255
  if (isLastAttempt) {
160
- this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: retryable.map((event) => event.uuid) }))
161
- return
256
+ loss.add(`still marked for retry after ${maxAttempts} attempt(s) (HTTP ${status})`, retryable.length)
257
+ this.report(
258
+ this.captureError({
259
+ requestId,
260
+ drops,
261
+ retryExhausted: retryable.map((event) => event.uuid),
262
+ }),
263
+ loss
264
+ )
265
+ return []
162
266
  }
163
267
  pending = retryable
164
268
  // A 200 partial-retry body can also carry Retry-After (e.g. rate-limited
@@ -172,8 +276,8 @@ export class V1CaptureSender {
172
276
  }
173
277
  // Connection/timeouts, including a timeout while consuming the response body,
174
278
  // are retried until the budget runs out.
175
- if (isLastAttempt) {
176
- return this.surfaceBatchFailure(requestId, drops, pending, transportError)
279
+ if (isLastAttempt || signal?.aborted) {
280
+ return unsent(transportError, this.describeTransportFailure(transportError, signal))
177
281
  }
178
282
  retryDelayMs = this.backoffDelay(attempt)
179
283
  } finally {
@@ -181,54 +285,98 @@ export class V1CaptureSender {
181
285
  }
182
286
 
183
287
  if (retryDelayMs !== undefined) {
184
- await this.sleep(retryDelayMs)
288
+ await this.sleepUnlessAborted(retryDelayMs, signal)
185
289
  }
186
290
  }
291
+ return []
187
292
  }
188
293
 
189
- private async sendOnce(url: string, payload: string, attempt: number, requestId: string): Promise<V1CaptureAttempt> {
190
- const headers = this.buildHeaders(attempt, requestId)
191
- let body: string | Blob | PostHogFetchBodyBytes = payload
192
- if (this.config.compressionEnabled) {
193
- const compressed = await this.compress(payload, this.config.isDebug)
194
- if (compressed !== null) {
195
- body = compressed
196
- headers['Content-Encoding'] = 'gzip'
197
- }
198
- // A codec that fails to compress falls back to sending uncompressed.
294
+ private async sleepUnlessAborted(ms: number, signal: AbortSignal | undefined): Promise<void> {
295
+ if (!signal) {
296
+ return this.sleep(ms)
199
297
  }
298
+ if (signal.aborted) {
299
+ return
300
+ }
301
+ let onAbort!: () => void
302
+ const aborted = new Promise<void>((resolve) => {
303
+ onAbort = resolve
304
+ signal.addEventListener('abort', onAbort, { once: true })
305
+ })
306
+ try {
307
+ await Promise.race([this.sleep(ms, signal), aborted])
308
+ } finally {
309
+ signal.removeEventListener('abort', onAbort)
310
+ }
311
+ }
312
+
313
+ private async sendOnce(
314
+ url: string,
315
+ payload: string,
316
+ attempt: number,
317
+ requestId: string,
318
+ externalSignal: AbortSignal | undefined
319
+ ): Promise<V1CaptureAttempt> {
320
+ const headers = this.buildHeaders(attempt, requestId)
321
+ // Compression runs on the libuv pool, so a busy pool must not hold the request past an external deadline.
322
+ const body = await raceAbort(this.encodeBody(payload, headers), externalSignal)
200
323
 
201
324
  const controller = new AbortController()
202
325
  let timeoutPhase = 'waiting for response headers'
203
- let timer: ReturnType<typeof safeSetTimeout>
326
+ let timer: ReturnType<typeof setTimeout> | undefined
327
+ let onExternalAbort: (() => void) | undefined
328
+ const stopListening = (): void => {
329
+ if (onExternalAbort) {
330
+ externalSignal?.removeEventListener('abort', onExternalAbort)
331
+ }
332
+ }
204
333
  // hooks.fetch is user-injectable, so it may ignore an abort signal while
205
334
  // resolving headers or reading the body. Race both phases against the same
206
335
  // deadline rather than relying only on standards-compliant fetch behavior.
207
336
  const deadline = new Promise<never>((_resolve, reject) => {
208
- timer = safeSetTimeout(() => {
337
+ const abortWith = (error: Error): void => {
338
+ // Reject first so this phase-specific error wins even when an abort-aware
339
+ // custom fetch rejects synchronously from the abort event.
340
+ reject(error)
341
+ controller.abort(error)
342
+ }
343
+ timer = setTimeout(() => {
209
344
  const timeoutError = new Error(
210
345
  `Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`
211
346
  )
212
347
  timeoutError.name = 'AbortError'
213
- // Reject first so this phase-specific error wins even when an abort-aware
214
- // custom fetch rejects synchronously from the abort event.
215
- reject(timeoutError)
216
- controller.abort(timeoutError)
348
+ timeoutErrors.add(timeoutError)
349
+ abortWith(timeoutError)
217
350
  }, this.config.requestTimeoutMs)
351
+ if (externalSignal) {
352
+ onExternalAbort = () => {
353
+ const abortError = new Error(`Capture V1 request aborted ${timeoutPhase}`)
354
+ abortError.name = 'AbortError'
355
+ abortError.cause = externalSignal.reason
356
+ abortWith(abortError)
357
+ }
358
+ if (externalSignal.aborted) {
359
+ onExternalAbort()
360
+ } else {
361
+ externalSignal.addEventListener('abort', onExternalAbort, { once: true })
362
+ }
363
+ }
218
364
  })
365
+ // Keeps an early abort from surfacing as an unhandled rejection before the race below observes it.
366
+ deadline.catch(() => {})
219
367
  try {
220
- const fetchPromise = this.fetchFn(url, { method: 'POST', headers, body, signal: controller.signal })
368
+ const fetchPromise = this.fetchFollowingRedirects(url, headers, body, controller.signal)
221
369
  let responseAccepted = false
222
370
  void fetchPromise
223
- .then((lateResponse) => {
371
+ .then((late) => {
224
372
  if (controller.signal.aborted && !responseAccepted) {
225
373
  // An injected fetch may ignore abort and resolve after the deadline.
226
374
  // Cancel its otherwise unreachable body to release any held resources.
227
- void this.cancelBody(lateResponse)
375
+ void this.cancelBody(late.response)
228
376
  }
229
377
  })
230
378
  .catch(() => {})
231
- const response = await Promise.race([fetchPromise, deadline])
379
+ const { response, redirectFailure } = await Promise.race([fetchPromise, deadline])
232
380
  responseAccepted = true
233
381
  timeoutPhase = 'while reading the response body'
234
382
  let cleanedUp = false
@@ -236,6 +384,7 @@ export class V1CaptureSender {
236
384
  const cancelBody = (): Promise<void> => (cancellation ??= this.cancelBody(response))
237
385
  return {
238
386
  response,
387
+ redirectFailure,
239
388
  signal: controller.signal,
240
389
  waitFor: <T>(operation: Promise<T>) => Promise.race([operation, deadline]),
241
390
  cancelBody,
@@ -245,6 +394,7 @@ export class V1CaptureSender {
245
394
  }
246
395
  cleanedUp = true
247
396
  clearTimeout(timer)
397
+ stopListening()
248
398
  if (controller.signal.aborted) {
249
399
  // The attempt deadline has already elapsed, so cleanup cannot wait
250
400
  // for a custom response body's cancellation promise to settle.
@@ -254,10 +404,81 @@ export class V1CaptureSender {
254
404
  }
255
405
  } catch (error) {
256
406
  clearTimeout(timer)
407
+ stopListening()
257
408
  throw error
258
409
  }
259
410
  }
260
411
 
412
+ /**
413
+ * Sends with `redirect: 'manual'` and follows 307 and 308 to the configured host's origin, at most
414
+ * `MAX_REDIRECTS` times, with the same method, headers and body. A fetch that follows redirects
415
+ * itself still works: its final response is not a redirect.
416
+ */
417
+ private async fetchFollowingRedirects(
418
+ url: string,
419
+ headers: PostHogFetchOptions['headers'],
420
+ body: string | Uint8Array,
421
+ signal: AbortSignal
422
+ ): Promise<RedirectOutcome> {
423
+ let target = url
424
+ for (let redirects = 0; ; redirects++) {
425
+ const response = await this.fetchFn(target, {
426
+ method: 'POST',
427
+ headers,
428
+ // A fresh copy per request: fetch may detach a byte body it has sent.
429
+ body: typeof body === 'string' ? body : body.slice(),
430
+ signal,
431
+ redirect: 'manual',
432
+ })
433
+ const { status } = response
434
+ if (status < 300 || status >= 400) {
435
+ return { response }
436
+ }
437
+ if (!FOLLOWED_REDIRECT_STATUSES.has(status)) {
438
+ return {
439
+ response,
440
+ redirectFailure: `Capture V1 request got an HTTP ${status} redirect, which it does not follow`,
441
+ }
442
+ }
443
+ if (redirects === MAX_REDIRECTS) {
444
+ return { response, redirectFailure: `Capture V1 request was redirected more than ${MAX_REDIRECTS} times` }
445
+ }
446
+ const next = resolveLocation(response.headers?.get('Location'), target)
447
+ if (next === undefined || originOf(next) !== this.hostOrigin) {
448
+ return {
449
+ response,
450
+ redirectFailure: `Capture V1 request got an HTTP ${status} redirect away from the configured host`,
451
+ }
452
+ }
453
+ void this.cancelBody(response)
454
+ // An injected fetch may ignore abort, so stop the chain here.
455
+ if (signal.aborted) {
456
+ throw signal.reason
457
+ }
458
+ target = next
459
+ }
460
+ }
461
+
462
+ /** Compresses `payload` with the configured codec and sets `Content-Encoding` to match. */
463
+ private async encodeBody(payload: string, headers: PostHogFetchOptions['headers']): Promise<string | Uint8Array> {
464
+ const codec = this.config.compression
465
+ if (codec === 'none') {
466
+ return payload
467
+ }
468
+ try {
469
+ const compressed = await this.compress(payload, codec)
470
+ if (compressed !== null) {
471
+ headers['Content-Encoding'] = codec
472
+ return compressed
473
+ }
474
+ } catch (error) {
475
+ if (this.config.isDebug) {
476
+ console.error(`Failed to ${codec} compress the capture request body`, error)
477
+ }
478
+ }
479
+ return payload
480
+ }
481
+
261
482
  private buildHeaders(attempt: number, requestId: string): PostHogFetchOptions['headers'] {
262
483
  const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`
263
484
  const headers: { [key: string]: string } = {
@@ -280,14 +501,35 @@ export class V1CaptureSender {
280
501
  * a terminal failure, `retry` is returned for the next attempt, and
281
502
  * `ok`/`warning`/unknown/absent are terminal successes.
282
503
  */
283
- private classify(pending: V1Event[], parsed: V1BatchResponse, drops: V1DroppedEvent[]): V1Event[] {
284
- const results = parsed.results ?? {}
285
- const retryable: V1Event[] = []
504
+ private classify<T extends SerializedV1Event>(
505
+ pending: T[],
506
+ parsed: V1BatchResponse,
507
+ drops: CaptureDroppedEvent[]
508
+ ): T[] {
509
+ // Events carry canonical uuids, so results match by the canonical form of the server's keys.
510
+ const results = new Map<string, V1EventResult>()
511
+ for (const [uuid, result] of Object.entries(parsed.results)) {
512
+ results.set(canonicalizeUuid(uuid) ?? uuid, result)
513
+ }
514
+ const retryable: T[] = []
515
+ // Only built when a result reports duplicates, so the usual response costs nothing extra.
516
+ let copiesSeen: Map<string, number> | undefined
286
517
  for (const event of pending) {
287
- const result = results[event.uuid]
518
+ const result = results.get(event.uuid)
288
519
  if (!result) {
289
520
  continue
290
521
  }
522
+ const duplicates = result.duplicates_dropped
523
+ if (typeof duplicates === 'number' && Number.isSafeInteger(duplicates) && duplicates > 0) {
524
+ copiesSeen ??= new Map()
525
+ const copy = copiesSeen.get(event.uuid) ?? 0
526
+ copiesSeen.set(event.uuid, copy + 1)
527
+ // The first copy takes the result; the next `duplicates` copies are the ones the server dropped.
528
+ if (copy >= 1 && copy <= duplicates) {
529
+ drops.push({ uuid: event.uuid, details: DUPLICATE_EVENT_UUID })
530
+ continue
531
+ }
532
+ }
291
533
  if (result.result === 'drop') {
292
534
  drops.push({ uuid: event.uuid, details: result.details ?? undefined })
293
535
  } else if (result.result === 'retry') {
@@ -298,13 +540,15 @@ export class V1CaptureSender {
298
540
  return retryable
299
541
  }
300
542
 
543
+ /** The wait after failed attempt `attempt` (1-based): jittered exponential backoff, raised to `Retry-After`. */
301
544
  private backoffDelay(attempt: number, retryAfterMs?: number): number {
302
- const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs)
545
+ const jitter = 0.75 + 0.5 * this.random()
546
+ const backoff = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1) * jitter, MAX_RETRY_DELAY_MS)
303
547
  if (retryAfterMs === undefined) {
304
- return exponential
548
+ return backoff
305
549
  }
306
- // Retry-After is a minimum (never lets us retry earlier than our own backoff) and is clamped to the ceiling.
307
- return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs))
550
+ // Compared after jitter, so jitter can never make the wait shorter than Retry-After.
551
+ return Math.max(backoff, Math.min(retryAfterMs, MAX_RETRY_DELAY_MS))
308
552
  }
309
553
 
310
554
  /** Parse `Retry-After` (delta-seconds or HTTP-date). Non-positive/past values are ignored. */
@@ -333,10 +577,10 @@ export class V1CaptureSender {
333
577
  throw new Error('unexpected response shape')
334
578
  }
335
579
  const results = (parsed as { results?: unknown }).results
336
- if (results !== undefined && (typeof results !== 'object' || results === null || Array.isArray(results))) {
580
+ if (typeof results !== 'object' || results === null || Array.isArray(results)) {
337
581
  throw new Error('unexpected results shape')
338
582
  }
339
- return { results: (results as V1BatchResponse['results']) ?? {} }
583
+ return { results: results as V1BatchResponse['results'] }
340
584
  }
341
585
 
342
586
  private async buildHttpError(
@@ -354,16 +598,47 @@ export class V1CaptureSender {
354
598
  return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`)
355
599
  }
356
600
 
357
- private surfaceBatchFailure(requestId: string, drops: V1DroppedEvent[], pending: V1Event[], cause: unknown): void {
358
- this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: pending.map((event) => event.uuid), cause }))
601
+ private surfaceBatchFailure(
602
+ requestId: string,
603
+ drops: CaptureDroppedEvent[],
604
+ pending: SerializedV1Event[],
605
+ cause: unknown,
606
+ loss: CaptureLossTally,
607
+ failure: string
608
+ ): void {
609
+ loss.add(failure, pending.length)
610
+ this.report(
611
+ this.captureError({ requestId, drops, retryExhausted: pending.map((event) => event.uuid), cause }),
612
+ loss
613
+ )
359
614
  }
360
615
 
361
- private surfacePartialDrops(requestId: string, drops: V1DroppedEvent[]): void {
616
+ private surfacePartialDrops(requestId: string, drops: CaptureDroppedEvent[], loss: CaptureLossTally): void {
362
617
  if (drops.length > 0) {
363
- this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: [] }))
618
+ this.report(this.captureError({ requestId, drops, retryExhausted: [] }), loss)
364
619
  }
365
620
  }
366
621
 
622
+ private report(error: CaptureError, loss: CaptureLossTally): void {
623
+ this.onError(error, describeCaptureLoss(this.config.path, loss))
624
+ }
625
+
626
+ /** A failure without an HTTP response, named by type only: its message can carry server or proxy text. */
627
+ private describeTransportFailure(error: unknown, signal: AbortSignal | undefined): string {
628
+ if (error instanceof Error && timeoutErrors.has(error)) {
629
+ return 'failed: request timed out'
630
+ }
631
+ if (signal?.aborted) {
632
+ return 'failed: request aborted'
633
+ }
634
+ const name = error instanceof Error && /^\w{1,64}$/.test(error.name) ? error.name : 'unknown'
635
+ return `failed with a network error (${name})`
636
+ }
637
+
638
+ private captureError(params: Omit<CaptureErrorParams, 'endpoint'>): CaptureError {
639
+ return new CaptureError({ endpoint: this.config.path, ...params })
640
+ }
641
+
367
642
  private async cancelBody(response: PostHogFetchResponse): Promise<void> {
368
643
  try {
369
644
  await response.body?.cancel()
@@ -372,3 +647,22 @@ export class V1CaptureSender {
372
647
  }
373
648
  }
374
649
  }
650
+
651
+ function originOf(url: string): string | undefined {
652
+ try {
653
+ return new URL(url).origin
654
+ } catch {
655
+ return undefined
656
+ }
657
+ }
658
+
659
+ function resolveLocation(location: string | null | undefined, base: string): string | undefined {
660
+ if (!location) {
661
+ return undefined
662
+ }
663
+ try {
664
+ return new URL(location, base).href
665
+ } catch {
666
+ return undefined
667
+ }
668
+ }