posthog-node 5.74.0 → 6.0.1
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.
- package/MIGRATION.md +556 -0
- package/README.md +3 -1
- package/dist/ai-capture/routing.d.ts +0 -3
- package/dist/ai-capture/routing.d.ts.map +1 -1
- package/dist/ai-capture/routing.js +2 -14
- package/dist/ai-capture/routing.mjs +1 -4
- package/dist/capture-lane/lane.d.ts +109 -0
- package/dist/capture-lane/lane.d.ts.map +1 -0
- package/dist/capture-lane/lane.js +308 -0
- package/dist/capture-lane/lane.mjs +270 -0
- package/dist/capture-lane/limits.d.ts +7 -0
- package/dist/capture-lane/limits.d.ts.map +1 -0
- package/dist/{capture-v1/config.js → capture-lane/limits.js} +13 -11
- package/dist/capture-lane/limits.mjs +4 -0
- package/dist/capture-lane/settings.d.ts +30 -0
- package/dist/capture-lane/settings.d.ts.map +1 -0
- package/dist/capture-lane/settings.js +100 -0
- package/dist/capture-lane/settings.mjs +47 -0
- package/dist/capture-v1/compression.d.ts +18 -0
- package/dist/capture-v1/compression.d.ts.map +1 -0
- package/dist/capture-v1/compression.js +70 -0
- package/dist/capture-v1/compression.mjs +26 -0
- package/dist/capture-v1/errors.d.ts +23 -7
- package/dist/capture-v1/errors.d.ts.map +1 -1
- package/dist/capture-v1/errors.js +37 -8
- package/dist/capture-v1/errors.mjs +29 -6
- package/dist/capture-v1/sender.d.ts +63 -23
- package/dist/capture-v1/sender.d.ts.map +1 -1
- package/dist/capture-v1/sender.js +281 -74
- package/dist/capture-v1/sender.mjs +275 -77
- package/dist/capture-v1/serialize.d.ts +28 -0
- package/dist/capture-v1/serialize.d.ts.map +1 -0
- package/dist/capture-v1/serialize.js +82 -0
- package/dist/capture-v1/serialize.mjs +38 -0
- package/dist/capture-v1/transform.d.ts +10 -25
- package/dist/capture-v1/transform.d.ts.map +1 -1
- package/dist/capture-v1/transform.js +33 -64
- package/dist/capture-v1/transform.mjs +28 -53
- package/dist/capture-v1/types.d.ts +16 -14
- package/dist/capture-v1/types.d.ts.map +1 -1
- package/dist/capture-v1/types.js +27 -1
- package/dist/capture-v1/types.mjs +3 -1
- package/dist/capture-v1/uuid.d.ts +9 -0
- package/dist/capture-v1/uuid.d.ts.map +1 -0
- package/dist/capture-v1/uuid.js +75 -0
- package/dist/capture-v1/uuid.mjs +34 -0
- package/dist/client.d.ts +203 -96
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +456 -228
- package/dist/client.mjs +455 -227
- package/dist/compression.node.d.ts +13 -0
- package/dist/compression.node.d.ts.map +1 -0
- package/dist/{capture-v1/routing.js → compression.node.js} +23 -16
- package/dist/compression.node.mjs +18 -0
- package/dist/entrypoints/index.node.d.ts +2 -0
- package/dist/entrypoints/index.node.d.ts.map +1 -1
- package/dist/entrypoints/index.node.js +11 -4
- package/dist/entrypoints/index.node.mjs +4 -0
- package/dist/event-defaults.d.ts +46 -0
- package/dist/event-defaults.d.ts.map +1 -0
- package/dist/event-defaults.js +141 -0
- package/dist/event-defaults.mjs +79 -0
- package/dist/exports.d.ts +3 -0
- package/dist/exports.d.ts.map +1 -1
- package/dist/exports.js +22 -11
- package/dist/exports.mjs +1 -0
- package/dist/extensions/context/context.d.ts +0 -1
- package/dist/extensions/context/context.d.ts.map +1 -1
- package/dist/extensions/context/context.js +4 -3
- package/dist/extensions/context/context.mjs +4 -3
- package/dist/extensions/context/event-context.d.ts.map +1 -1
- package/dist/extensions/context/event-context.js +3 -0
- package/dist/extensions/context/event-context.mjs +3 -0
- package/dist/extensions/context/types.d.ts +9 -1
- package/dist/extensions/context/types.d.ts.map +1 -1
- package/dist/extensions/error-tracking/index.d.ts +1 -1
- package/dist/extensions/error-tracking/index.d.ts.map +1 -1
- package/dist/extensions/error-tracking/index.js +71 -7
- package/dist/extensions/error-tracking/index.mjs +75 -11
- package/dist/extensions/express.d.ts +8 -0
- package/dist/extensions/express.d.ts.map +1 -1
- package/dist/extensions/express.js +3 -3
- package/dist/extensions/express.mjs +4 -4
- package/dist/extensions/fetch-request.d.ts.map +1 -1
- package/dist/extensions/fetch-request.js +2 -2
- package/dist/extensions/fetch-request.mjs +3 -3
- package/dist/extensions/nestjs.d.ts.map +1 -1
- package/dist/extensions/nestjs.js +7 -4
- package/dist/extensions/nestjs.mjs +8 -5
- package/dist/extensions/tracing-headers.d.ts +7 -0
- package/dist/extensions/tracing-headers.d.ts.map +1 -1
- package/dist/extensions/tracing-headers.js +11 -1
- package/dist/extensions/tracing-headers.mjs +9 -2
- package/dist/flag-events.d.ts +1 -1
- package/dist/flag-events.d.ts.map +1 -1
- package/dist/flag-events.js +2 -2
- package/dist/flag-events.mjs +2 -2
- package/dist/types.d.ts +191 -27
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +3 -2
- package/src/ai-capture/routing.ts +0 -6
- package/src/capture-lane/lane.ts +414 -0
- package/src/capture-lane/limits.ts +8 -0
- package/src/capture-lane/settings.ts +119 -0
- package/src/capture-v1/compression.ts +50 -0
- package/src/capture-v1/errors.ts +50 -11
- package/src/capture-v1/sender.ts +405 -111
- package/src/capture-v1/serialize.ts +77 -0
- package/src/capture-v1/transform.ts +59 -92
- package/src/capture-v1/types.ts +19 -15
- package/src/capture-v1/uuid.ts +53 -0
- package/src/client.ts +847 -424
- package/src/compression.node.ts +30 -0
- package/src/entrypoints/index.node.ts +6 -0
- package/src/event-defaults.ts +177 -0
- package/src/exports.ts +3 -0
- package/src/extensions/context/context.ts +4 -4
- package/src/extensions/context/event-context.ts +3 -1
- package/src/extensions/context/types.ts +10 -1
- package/src/extensions/error-tracking/index.ts +51 -7
- package/src/extensions/express.ts +12 -3
- package/src/extensions/fetch-request.ts +7 -3
- package/src/extensions/nestjs.ts +9 -5
- package/src/extensions/tracing-headers.ts +26 -7
- package/src/flag-events.ts +5 -2
- package/src/types.ts +211 -44
- package/src/version.ts +1 -1
- package/dist/ai-capture/batching.d.ts +0 -11
- package/dist/ai-capture/batching.d.ts.map +0 -1
- package/dist/ai-capture/batching.js +0 -77
- package/dist/ai-capture/batching.mjs +0 -36
- package/dist/capture-v1/config.d.ts +0 -11
- package/dist/capture-v1/config.d.ts.map +0 -1
- package/dist/capture-v1/config.mjs +0 -8
- package/dist/capture-v1/routing.d.ts +0 -21
- package/dist/capture-v1/routing.d.ts.map +0 -1
- package/dist/capture-v1/routing.mjs +0 -7
- package/src/ai-capture/batching.ts +0 -47
- package/src/capture-v1/config.ts +0 -18
- package/src/capture-v1/routing.ts +0 -28
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { type Logger, type PostHogEventProperties, safeSetTimeout } from '@posthog/core'
|
|
2
|
+
|
|
3
|
+
import { CaptureError, CaptureLossTally, type CaptureDroppedEvent, describeCaptureLoss } from '../capture-v1/errors'
|
|
4
|
+
import type { V1SendOptions } from '../capture-v1/sender'
|
|
5
|
+
import { type SerializedV1Event, serializeV1Event, wireProblem } from '../capture-v1/serialize'
|
|
6
|
+
import type { CaptureEndpoint } from '../capture-v1/types'
|
|
7
|
+
|
|
8
|
+
/** Upper bound on the uuids one local-drop report lists; the message still carries the full count. */
|
|
9
|
+
const MAX_REPORTED_LOCAL_DROPS = 100
|
|
10
|
+
|
|
11
|
+
/** What a lane needs from its sender. `V1CaptureSender` implements it. */
|
|
12
|
+
export interface CaptureLaneSender {
|
|
13
|
+
send<T extends SerializedV1Event>(events: T[], options?: V1SendOptions): Promise<T[]>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface CaptureLaneConfig {
|
|
17
|
+
endpoint: CaptureEndpoint
|
|
18
|
+
/** Queue length that starts a flush. */
|
|
19
|
+
flushAt: number
|
|
20
|
+
/** Delay before a flush of queued events; 0 turns the timer off. */
|
|
21
|
+
flushIntervalMs: number
|
|
22
|
+
maxBatchSize: number
|
|
23
|
+
/** When the queue holds this many events, a new event drops the oldest. */
|
|
24
|
+
maxQueueSize: number
|
|
25
|
+
/** A batch stops before an event that would take its serialized bytes past this. */
|
|
26
|
+
targetBatchBytes: number
|
|
27
|
+
/** Events larger than this are dropped before sending. */
|
|
28
|
+
maxEventBytes: number
|
|
29
|
+
/** Whether `maxEventBytes` applies to the whole serialized event or to its `properties` only. */
|
|
30
|
+
maxEventBytesOf: 'event' | 'properties'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface CaptureLaneHooks {
|
|
34
|
+
sender: CaptureLaneSender
|
|
35
|
+
/**
|
|
36
|
+
* Events this lane dropped without sending, at most one report per flush cycle. `summary` is
|
|
37
|
+
* one line with counts and causes only, for when nothing listens.
|
|
38
|
+
*/
|
|
39
|
+
onLocalDrops: (errors: CaptureError[], summary: string) => void
|
|
40
|
+
/** Failures the sender did not handle itself. */
|
|
41
|
+
onError: (error: unknown) => void
|
|
42
|
+
/** The messages one flush cycle sent. */
|
|
43
|
+
onFlush: (messages: PostHogEventProperties[]) => void
|
|
44
|
+
/** Each flush the lane starts on its own, from its timer or `flushAt`. */
|
|
45
|
+
onBackgroundFlush?: (flush: Promise<void>) => void
|
|
46
|
+
logger: Logger
|
|
47
|
+
now?: () => number
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface QueuedEvent extends SerializedV1Event {
|
|
51
|
+
message: PostHogEventProperties
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
type LocalDropReason = 'queueFull' | 'tooLarge' | 'invalid' | 'unserializable'
|
|
55
|
+
|
|
56
|
+
interface LocalDropTally {
|
|
57
|
+
queueFull: number
|
|
58
|
+
tooLarge: number
|
|
59
|
+
invalid: number
|
|
60
|
+
unserializable: number
|
|
61
|
+
sample: CaptureDroppedEvent[]
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const emptyTally = (): LocalDropTally => ({ queueFull: 0, tooLarge: 0, invalid: 0, unserializable: 0, sample: [] })
|
|
65
|
+
|
|
66
|
+
const LOCAL_DROP_DETAILS: Record<LocalDropReason, string> = {
|
|
67
|
+
queueFull: 'queue full',
|
|
68
|
+
tooLarge: 'event too large',
|
|
69
|
+
invalid: 'invalid event',
|
|
70
|
+
unserializable: 'unserializable event',
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** An event ready to send, or the uuid and reason of one dropped before sending. */
|
|
74
|
+
type CheckedEvent = { event: SerializedV1Event } | { uuid: string; drop: LocalDropReason }
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* One capture endpoint's in-memory queue, flush timer, `flushAt` trigger, batching and
|
|
78
|
+
* in-flight send. Lanes share nothing, so a slow or failing lane never delays, drops
|
|
79
|
+
* or resends another lane's events.
|
|
80
|
+
*
|
|
81
|
+
* Every event is serialized once, on enqueue. Batches are cut by count and by
|
|
82
|
+
* serialized bytes, keeping queue order. An event whose last attempt got no HTTP
|
|
83
|
+
* response goes back to the head of the queue for the next flush; every other
|
|
84
|
+
* failure is final and reported by the sender.
|
|
85
|
+
*/
|
|
86
|
+
export class CaptureLane {
|
|
87
|
+
private readonly config: CaptureLaneConfig
|
|
88
|
+
private readonly hooks: CaptureLaneHooks
|
|
89
|
+
private readonly now: () => number
|
|
90
|
+
private queue: QueuedEvent[] = []
|
|
91
|
+
private flushTimer?: ReturnType<typeof safeSetTimeout>
|
|
92
|
+
private activeFlush: Promise<void> | null = null
|
|
93
|
+
// A flush requested while another is in flight; later requests share it.
|
|
94
|
+
private queuedFlush: Promise<void> | null = null
|
|
95
|
+
private abortController = new AbortController()
|
|
96
|
+
private abortTimer?: ReturnType<typeof safeSetTimeout>
|
|
97
|
+
private localDrops = emptyTally()
|
|
98
|
+
// Events that reached a final outcome, so a drain can tell whether a cycle moved anything.
|
|
99
|
+
private settledCount = 0
|
|
100
|
+
|
|
101
|
+
constructor(config: CaptureLaneConfig, hooks: CaptureLaneHooks) {
|
|
102
|
+
this.config = config
|
|
103
|
+
this.hooks = hooks
|
|
104
|
+
this.now = hooks.now ?? Date.now
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
get length(): number {
|
|
108
|
+
return this.queue.length
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
enqueue(message: PostHogEventProperties): void {
|
|
112
|
+
const checked = this.check(message)
|
|
113
|
+
if ('drop' in checked) {
|
|
114
|
+
this.recordLocalDrop(checked.uuid, checked.drop)
|
|
115
|
+
// Nothing may follow to flush, and the flush cycle is what reports the drop.
|
|
116
|
+
this.armFlushTimer()
|
|
117
|
+
return
|
|
118
|
+
}
|
|
119
|
+
if (this.queue.length >= this.config.maxQueueSize) {
|
|
120
|
+
this.recordLocalDrop(this.queue.shift()!.uuid, 'queueFull')
|
|
121
|
+
}
|
|
122
|
+
this.queue.push({ ...checked.event, message })
|
|
123
|
+
|
|
124
|
+
if (this.queue.length >= this.config.flushAt) {
|
|
125
|
+
this.flushInBackground()
|
|
126
|
+
} else {
|
|
127
|
+
this.armFlushTimer()
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Sends one event now, without queueing. Delivery failures are reported, not thrown. */
|
|
132
|
+
async sendImmediate(message: PostHogEventProperties): Promise<void> {
|
|
133
|
+
const checked = this.check(message)
|
|
134
|
+
if ('drop' in checked) {
|
|
135
|
+
const tally = emptyTally()
|
|
136
|
+
this.addToTally(tally, checked.uuid, checked.drop)
|
|
137
|
+
this.reportTally(tally)
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
await this.hooks.sender.send([checked.event], { signal: this.abortController.signal })
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Drops an event the client could not read before it reached the lane, as `unserializable`. A
|
|
145
|
+
* queued event's drop is reported with the next flush cycle and an immediate one at once. An
|
|
146
|
+
* event with no uuid yet is counted but not listed.
|
|
147
|
+
*/
|
|
148
|
+
dropUnserializable(uuid: string | undefined, immediate: boolean): void {
|
|
149
|
+
if (immediate) {
|
|
150
|
+
const tally = emptyTally()
|
|
151
|
+
this.addToTally(tally, uuid, 'unserializable')
|
|
152
|
+
this.reportTally(tally)
|
|
153
|
+
return
|
|
154
|
+
}
|
|
155
|
+
this.recordLocalDrop(uuid, 'unserializable')
|
|
156
|
+
// Nothing may follow to flush, and the flush cycle is what reports the drop.
|
|
157
|
+
this.armFlushTimer()
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Serializes the event and checks its name, ids and size. A value that throws while it is read
|
|
162
|
+
* or written (a getter or `toJSON`) drops only this event. The error is not kept, because its
|
|
163
|
+
* message can carry event data.
|
|
164
|
+
*/
|
|
165
|
+
private check(message: PostHogEventProperties): CheckedEvent {
|
|
166
|
+
let event: SerializedV1Event
|
|
167
|
+
try {
|
|
168
|
+
event = serializeV1Event(message)
|
|
169
|
+
if (wireProblem(message)) {
|
|
170
|
+
return { uuid: event.uuid, drop: 'invalid' }
|
|
171
|
+
}
|
|
172
|
+
} catch {
|
|
173
|
+
return { uuid: String(message.uuid), drop: 'unserializable' }
|
|
174
|
+
}
|
|
175
|
+
return this.isTooLarge(event) ? { uuid: event.uuid, drop: 'tooLarge' } : { event }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Sends everything queued when the returned flush starts. Never rejects. */
|
|
179
|
+
flush(): Promise<void> {
|
|
180
|
+
if (this.queuedFlush) {
|
|
181
|
+
return this.queuedFlush
|
|
182
|
+
}
|
|
183
|
+
if (!this.activeFlush) {
|
|
184
|
+
return this.startFlush()
|
|
185
|
+
}
|
|
186
|
+
const queued = this.activeFlush.then(() => {
|
|
187
|
+
this.queuedFlush = null
|
|
188
|
+
return this.startFlush()
|
|
189
|
+
})
|
|
190
|
+
this.queuedFlush = queued
|
|
191
|
+
return queued
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Flushes until the queue is empty, a cycle settles nothing (every send was requeued),
|
|
196
|
+
* or `deadlineMs` passes. At the deadline, in-flight and later sends are aborted.
|
|
197
|
+
*/
|
|
198
|
+
async drain(deadlineMs: number): Promise<void> {
|
|
199
|
+
this.abortAt(deadlineMs)
|
|
200
|
+
let settledBefore: number
|
|
201
|
+
do {
|
|
202
|
+
settledBefore = this.settledCount
|
|
203
|
+
await this.flush()
|
|
204
|
+
} while (this.queue.length > 0 && this.settledCount !== settledBefore && !this.abortController.signal.aborted)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Ends a shutdown: reports and discards what is still queued, and re-arms the lane so
|
|
209
|
+
* calls made after shutdown still send.
|
|
210
|
+
*/
|
|
211
|
+
finishShutdown(): void {
|
|
212
|
+
clearTimeout(this.abortTimer)
|
|
213
|
+
this.abortTimer = undefined
|
|
214
|
+
this.clearFlushTimer()
|
|
215
|
+
this.reportLocalDrops(this.queue.splice(0))
|
|
216
|
+
if (this.abortController.signal.aborted) {
|
|
217
|
+
this.abortController = new AbortController()
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
private startFlush(): Promise<void> {
|
|
222
|
+
const flush = this.runFlushCycle().finally(() => {
|
|
223
|
+
if (this.activeFlush === flush) {
|
|
224
|
+
this.activeFlush = null
|
|
225
|
+
}
|
|
226
|
+
})
|
|
227
|
+
this.activeFlush = flush
|
|
228
|
+
return flush
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private flushInBackground(): void {
|
|
232
|
+
if (this.queuedFlush) {
|
|
233
|
+
return
|
|
234
|
+
}
|
|
235
|
+
const flush = this.flush()
|
|
236
|
+
this.safely(() => this.hooks.onBackgroundFlush?.(flush))
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private async runFlushCycle(): Promise<void> {
|
|
240
|
+
this.clearFlushTimer()
|
|
241
|
+
// Lets events enqueued in the same burst join this cycle's first batch.
|
|
242
|
+
await Promise.resolve()
|
|
243
|
+
// Events enqueued during this cycle wait for the next one, so a steady stream cannot hold a flush open.
|
|
244
|
+
const budget = this.queue.length
|
|
245
|
+
const sent: PostHogEventProperties[] = []
|
|
246
|
+
let taken = 0
|
|
247
|
+
try {
|
|
248
|
+
while (taken < budget && this.queue.length > 0) {
|
|
249
|
+
const batch = this.takeBatch()
|
|
250
|
+
taken += batch.length
|
|
251
|
+
let unsent: QueuedEvent[]
|
|
252
|
+
try {
|
|
253
|
+
unsent = await this.hooks.sender.send(batch, { signal: this.abortController.signal, keepUnsent: true })
|
|
254
|
+
} catch (error) {
|
|
255
|
+
// An unexpected sender failure is final for the batch, like any other non-network failure.
|
|
256
|
+
this.settledCount += batch.length
|
|
257
|
+
this.safely(() => this.hooks.onError(error))
|
|
258
|
+
continue
|
|
259
|
+
}
|
|
260
|
+
this.settledCount += batch.length - unsent.length
|
|
261
|
+
const requeued = new Set(unsent)
|
|
262
|
+
for (const event of batch) {
|
|
263
|
+
if (!requeued.has(event)) {
|
|
264
|
+
sent.push(event.message)
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (unsent.length > 0) {
|
|
268
|
+
this.requeue(unsent)
|
|
269
|
+
// The network is likely down, so the rest of the queue waits for the next flush too.
|
|
270
|
+
break
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
} catch (error) {
|
|
274
|
+
this.safely(() => this.hooks.onError(error))
|
|
275
|
+
} finally {
|
|
276
|
+
if (sent.length > 0) {
|
|
277
|
+
this.safely(() => this.hooks.onFlush(sent))
|
|
278
|
+
}
|
|
279
|
+
this.reportLocalDrops()
|
|
280
|
+
if (this.queue.length > 0) {
|
|
281
|
+
this.armFlushTimer()
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
private takeBatch(): QueuedEvent[] {
|
|
287
|
+
let count = 0
|
|
288
|
+
let bytes = 0
|
|
289
|
+
while (count < this.queue.length && count < this.config.maxBatchSize) {
|
|
290
|
+
const next = this.queue[count]
|
|
291
|
+
// Check before appending: the event that would overflow starts the next batch, and an oversized one ships alone.
|
|
292
|
+
if (count > 0 && bytes + next.bytes > this.config.targetBatchBytes) {
|
|
293
|
+
break
|
|
294
|
+
}
|
|
295
|
+
bytes += next.bytes
|
|
296
|
+
count++
|
|
297
|
+
}
|
|
298
|
+
return this.queue.splice(0, count)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
private requeue(events: QueuedEvent[]): void {
|
|
302
|
+
this.queue.unshift(...events)
|
|
303
|
+
while (this.queue.length > this.config.maxQueueSize) {
|
|
304
|
+
this.recordLocalDrop(this.queue.shift()!.uuid, 'queueFull')
|
|
305
|
+
}
|
|
306
|
+
this.hooks.logger.debug(
|
|
307
|
+
`Kept ${events.length} event(s) for ${this.config.endpoint} after a network failure; the next flush sends them`
|
|
308
|
+
)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
private isTooLarge(event: SerializedV1Event): boolean {
|
|
312
|
+
const bytes = this.config.maxEventBytesOf === 'properties' ? event.propertiesBytes : event.bytes
|
|
313
|
+
return bytes > this.config.maxEventBytes
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
private recordLocalDrop(uuid: string | undefined, reason: LocalDropReason): void {
|
|
317
|
+
this.addToTally(this.localDrops, uuid, reason)
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
private addToTally(tally: LocalDropTally, uuid: string | undefined, reason: LocalDropReason): void {
|
|
321
|
+
tally[reason]++
|
|
322
|
+
if (uuid !== undefined && tally.sample.length < MAX_REPORTED_LOCAL_DROPS) {
|
|
323
|
+
tally.sample.push({ uuid, details: LOCAL_DROP_DETAILS[reason] })
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
private reportLocalDrops(leftovers: SerializedV1Event[] = []): void {
|
|
328
|
+
const tally = this.localDrops
|
|
329
|
+
this.localDrops = emptyTally()
|
|
330
|
+
this.reportTally(tally, leftovers)
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Reports `tally` and the events still queued at the end of a shutdown together, in one report. */
|
|
334
|
+
private reportTally(tally: LocalDropTally, leftovers: SerializedV1Event[] = []): void {
|
|
335
|
+
const errors: CaptureError[] = []
|
|
336
|
+
const loss = new CaptureLossTally()
|
|
337
|
+
const { endpoint } = this.config
|
|
338
|
+
if (leftovers.length > 0) {
|
|
339
|
+
const error = new CaptureError({
|
|
340
|
+
endpoint,
|
|
341
|
+
requestId: '',
|
|
342
|
+
drops: [],
|
|
343
|
+
retryExhausted: leftovers.map((event) => event.uuid),
|
|
344
|
+
})
|
|
345
|
+
error.message = `${leftovers.length} event(s) for ${endpoint} were still queued when shutdown ended and were not sent`
|
|
346
|
+
errors.push(error)
|
|
347
|
+
loss.add('still queued when shutdown ended', leftovers.length)
|
|
348
|
+
}
|
|
349
|
+
const total = tally.queueFull + tally.tooLarge + tally.invalid + tally.unserializable
|
|
350
|
+
if (total > 0) {
|
|
351
|
+
const { maxQueueSize, maxEventBytes, maxEventBytesOf } = this.config
|
|
352
|
+
const reasons: string[] = []
|
|
353
|
+
if (tally.queueFull > 0) {
|
|
354
|
+
reasons.push(`${tally.queueFull} because the queue was full (${maxQueueSize} events)`)
|
|
355
|
+
}
|
|
356
|
+
if (tally.tooLarge > 0) {
|
|
357
|
+
const measured = maxEventBytesOf === 'properties' ? 'properties larger' : 'larger'
|
|
358
|
+
reasons.push(`${tally.tooLarge} with ${measured} than ${maxEventBytes} bytes`)
|
|
359
|
+
}
|
|
360
|
+
if (tally.invalid > 0) {
|
|
361
|
+
reasons.push(`${tally.invalid} with a missing, empty or malformed event name or id`)
|
|
362
|
+
}
|
|
363
|
+
if (tally.unserializable > 0) {
|
|
364
|
+
reasons.push(`${tally.unserializable} with a value that could not be serialized`)
|
|
365
|
+
}
|
|
366
|
+
const error = new CaptureError({ endpoint, requestId: '', drops: tally.sample, retryExhausted: [] })
|
|
367
|
+
error.message = `Dropped ${total} event(s) for ${endpoint} before sending: ${reasons.join(', ')}`
|
|
368
|
+
errors.push(error)
|
|
369
|
+
loss.add(`dropped because the queue was full (${maxQueueSize} events)`, tally.queueFull)
|
|
370
|
+
const measured = maxEventBytesOf === 'properties' ? 'their properties were' : 'they were'
|
|
371
|
+
loss.add(`dropped because ${measured} larger than ${maxEventBytes} bytes`, tally.tooLarge)
|
|
372
|
+
loss.add('dropped because the event name or an id was missing, empty or malformed', tally.invalid)
|
|
373
|
+
loss.add('dropped because a value could not be serialized', tally.unserializable)
|
|
374
|
+
}
|
|
375
|
+
if (errors.length > 0) {
|
|
376
|
+
this.safely(() => this.hooks.onLocalDrops(errors, describeCaptureLoss(endpoint, loss)))
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private armFlushTimer(): void {
|
|
381
|
+
if (this.flushTimer || !this.config.flushIntervalMs) {
|
|
382
|
+
return
|
|
383
|
+
}
|
|
384
|
+
this.flushTimer = safeSetTimeout(() => {
|
|
385
|
+
this.flushTimer = undefined
|
|
386
|
+
this.flushInBackground()
|
|
387
|
+
}, this.config.flushIntervalMs)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
private clearFlushTimer(): void {
|
|
391
|
+
clearTimeout(this.flushTimer)
|
|
392
|
+
this.flushTimer = undefined
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private abortAt(deadlineMs: number): void {
|
|
396
|
+
clearTimeout(this.abortTimer)
|
|
397
|
+
const abort = (): void => this.abortController.abort(new Error('PostHog shutdown deadline reached'))
|
|
398
|
+
const delayMs = deadlineMs - this.now()
|
|
399
|
+
if (delayMs <= 0) {
|
|
400
|
+
abort()
|
|
401
|
+
return
|
|
402
|
+
}
|
|
403
|
+
this.abortTimer = safeSetTimeout(abort, delayMs)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// Hooks run user listeners, which must not break the lane's own bookkeeping.
|
|
407
|
+
private safely(fn: () => void): void {
|
|
408
|
+
try {
|
|
409
|
+
fn()
|
|
410
|
+
} catch (error) {
|
|
411
|
+
this.hooks.logger.error('Capture lane hook failed:', error)
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Serialized event bytes a lane aims to fit in one request. */
|
|
2
|
+
export const CAPTURE_BATCH_TARGET_BYTES = 5 * 1024 * 1024
|
|
3
|
+
|
|
4
|
+
/** Capture's request body limit: a larger analytics event can never be accepted. */
|
|
5
|
+
export const ANALYTICS_MAX_EVENT_BYTES = 10 * 1024 * 1024
|
|
6
|
+
|
|
7
|
+
/** The AI endpoint rejects an event whose serialized `properties` are larger than this. */
|
|
8
|
+
export const AI_MAX_PROPERTIES_BYTES = 8 * 1024 * 1024
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { CAPTURE_COMPRESSIONS, type CaptureCompression } from '../capture-v1/compression'
|
|
2
|
+
import type { PostHogOptions } from '../types'
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_CAPTURE_MAX_RETRIES = 3
|
|
5
|
+
export const MAX_CAPTURE_MAX_RETRIES = 9
|
|
6
|
+
export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000
|
|
7
|
+
export const DEFAULT_AI_REQUEST_TIMEOUT_MS = 30_000
|
|
8
|
+
export const DEFAULT_AI_MAX_QUEUE_SIZE = 1000
|
|
9
|
+
|
|
10
|
+
/** Capture settings resolved once per client from `PostHogOptions`. */
|
|
11
|
+
export interface CaptureSettings {
|
|
12
|
+
/** Retries after the first attempt, for both lanes. */
|
|
13
|
+
maxRetries: number
|
|
14
|
+
analytics: CaptureLaneSettings
|
|
15
|
+
ai: CaptureLaneSettings & {
|
|
16
|
+
/** Queued AI events; the analytics queue size stays a client setting. */
|
|
17
|
+
maxQueueSize: number
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface CaptureLaneSettings {
|
|
22
|
+
/** The requested body encoding; the runtime may not support it. */
|
|
23
|
+
compression: CaptureCompression
|
|
24
|
+
requestTimeoutMs: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type LogInvalid = (message: string) => void
|
|
28
|
+
|
|
29
|
+
const isIntegerInRange = (value: unknown, min: number, max: number): value is number =>
|
|
30
|
+
typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Validates the capture options. An invalid value is reported once through `logInvalid` and
|
|
34
|
+
* behaves as if it were not set, so a bad option never throws.
|
|
35
|
+
*/
|
|
36
|
+
export function resolveCaptureSettings(options: PostHogOptions, logInvalid: LogInvalid): CaptureSettings {
|
|
37
|
+
return {
|
|
38
|
+
maxRetries: resolveMaxRetries(options, logInvalid),
|
|
39
|
+
analytics: {
|
|
40
|
+
compression:
|
|
41
|
+
resolveCompression('captureCompression', options.captureCompression, logInvalid) ??
|
|
42
|
+
(options.disableCompression ? 'none' : 'gzip'),
|
|
43
|
+
requestTimeoutMs: options.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
44
|
+
},
|
|
45
|
+
ai: {
|
|
46
|
+
// The AI lane does not read captureCompression or disableCompression.
|
|
47
|
+
compression: resolveCompression('captureAiCompression', options.captureAiCompression, logInvalid) ?? 'gzip',
|
|
48
|
+
requestTimeoutMs: resolvePositive(
|
|
49
|
+
'captureAiRequestTimeoutMs',
|
|
50
|
+
options.captureAiRequestTimeoutMs,
|
|
51
|
+
DEFAULT_AI_REQUEST_TIMEOUT_MS,
|
|
52
|
+
logInvalid,
|
|
53
|
+
{ integer: false }
|
|
54
|
+
),
|
|
55
|
+
maxQueueSize: resolvePositive(
|
|
56
|
+
'captureAiMaxQueueSize',
|
|
57
|
+
options.captureAiMaxQueueSize,
|
|
58
|
+
DEFAULT_AI_MAX_QUEUE_SIZE,
|
|
59
|
+
logInvalid,
|
|
60
|
+
{ integer: true }
|
|
61
|
+
),
|
|
62
|
+
},
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function resolveCompression(name: string, value: unknown, logInvalid: LogInvalid): CaptureCompression | undefined {
|
|
67
|
+
if (value == null) {
|
|
68
|
+
return undefined
|
|
69
|
+
}
|
|
70
|
+
if ((CAPTURE_COMPRESSIONS as readonly unknown[]).includes(value)) {
|
|
71
|
+
return value as CaptureCompression
|
|
72
|
+
}
|
|
73
|
+
logInvalid(
|
|
74
|
+
`${name} must be one of ${CAPTURE_COMPRESSIONS.map((codec) => `'${codec}'`).join(', ')}; using the default.`
|
|
75
|
+
)
|
|
76
|
+
return undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Node clamps a timer delay above this to 1 ms, which would time out every request.
|
|
80
|
+
const MAX_SETTING_VALUE = 2_147_483_647
|
|
81
|
+
|
|
82
|
+
function resolvePositive(
|
|
83
|
+
name: string,
|
|
84
|
+
value: unknown,
|
|
85
|
+
fallback: number,
|
|
86
|
+
logInvalid: LogInvalid,
|
|
87
|
+
{ integer }: { integer: boolean }
|
|
88
|
+
): number {
|
|
89
|
+
if (value == null) {
|
|
90
|
+
return fallback
|
|
91
|
+
}
|
|
92
|
+
if (
|
|
93
|
+
typeof value === 'number' &&
|
|
94
|
+
value > 0 &&
|
|
95
|
+
value <= MAX_SETTING_VALUE &&
|
|
96
|
+
(integer ? Number.isSafeInteger(value) : Number.isFinite(value))
|
|
97
|
+
) {
|
|
98
|
+
return value
|
|
99
|
+
}
|
|
100
|
+
logInvalid(
|
|
101
|
+
`${name} must be a positive ${integer ? 'integer' : 'number'} up to ${MAX_SETTING_VALUE}; using the default.`
|
|
102
|
+
)
|
|
103
|
+
return fallback
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function resolveMaxRetries(options: PostHogOptions, logInvalid: LogInvalid): number {
|
|
107
|
+
const { captureMaxRetries, fetchRetryCount } = options
|
|
108
|
+
if (captureMaxRetries != null) {
|
|
109
|
+
if (isIntegerInRange(captureMaxRetries, 0, MAX_CAPTURE_MAX_RETRIES)) {
|
|
110
|
+
return captureMaxRetries
|
|
111
|
+
}
|
|
112
|
+
logInvalid(`captureMaxRetries must be an integer from 0 to ${MAX_CAPTURE_MAX_RETRIES}; using the default.`)
|
|
113
|
+
}
|
|
114
|
+
// fetchRetryCount also configures other requests, so an out-of-range value is clamped for capture, not reported.
|
|
115
|
+
if (typeof fetchRetryCount === 'number' && Number.isFinite(fetchRetryCount)) {
|
|
116
|
+
return Math.min(Math.max(Math.trunc(fetchRetryCount), 0), MAX_CAPTURE_MAX_RETRIES)
|
|
117
|
+
}
|
|
118
|
+
return DEFAULT_CAPTURE_MAX_RETRIES
|
|
119
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { gzipCompress, isGzipSupported } from '@posthog/core'
|
|
2
|
+
|
|
3
|
+
export const CAPTURE_COMPRESSIONS = ['none', 'gzip', 'deflate', 'zstd'] as const
|
|
4
|
+
|
|
5
|
+
/** A capture request body encoding; `deflate` is zlib-wrapped, as HTTP `Content-Encoding: deflate` requires. */
|
|
6
|
+
export type CaptureCompression = (typeof CAPTURE_COMPRESSIONS)[number]
|
|
7
|
+
|
|
8
|
+
export type CaptureCodec = Exclude<CaptureCompression, 'none'>
|
|
9
|
+
|
|
10
|
+
/** Compresses capture request bodies with the codecs one runtime provides. */
|
|
11
|
+
export interface CaptureCompressor {
|
|
12
|
+
supports(codec: CaptureCodec): boolean
|
|
13
|
+
/** Resolves to null, or rejects, when compression fails; the sender then sends the body uncompressed. */
|
|
14
|
+
compress(payload: string, codec: CaptureCodec): Promise<Uint8Array | null>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Uses CompressionStream, so it works wherever the runtime has one. It has no zstd. */
|
|
18
|
+
export const webCompressor: CaptureCompressor = {
|
|
19
|
+
supports: (codec) => codec !== 'zstd' && isGzipSupported(),
|
|
20
|
+
async compress(payload, codec) {
|
|
21
|
+
if (codec === 'gzip') {
|
|
22
|
+
const compressed = await gzipCompress(payload, false)
|
|
23
|
+
return compressed && new Uint8Array(await compressed.arrayBuffer())
|
|
24
|
+
}
|
|
25
|
+
if (codec !== 'deflate') {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
const stream = new Response(payload).body!.pipeThrough(new globalThis.CompressionStream('deflate'))
|
|
29
|
+
return new Uint8Array(await new Response(stream).arrayBuffer())
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The codec a lane sends with: `requested` when the runtime has it, gzip in place of an unavailable
|
|
35
|
+
* zstd, or no compression when the runtime cannot compress at all.
|
|
36
|
+
*/
|
|
37
|
+
export function resolveCaptureCodec(
|
|
38
|
+
requested: CaptureCompression,
|
|
39
|
+
compressor: CaptureCompressor,
|
|
40
|
+
onZstdUnavailable: (fallback: CaptureCompression) => void
|
|
41
|
+
): CaptureCompression {
|
|
42
|
+
if (requested === 'none' || compressor.supports(requested)) {
|
|
43
|
+
return requested
|
|
44
|
+
}
|
|
45
|
+
const fallback = compressor.supports('gzip') ? 'gzip' : 'none'
|
|
46
|
+
if (requested === 'zstd') {
|
|
47
|
+
onZstdUnavailable(fallback)
|
|
48
|
+
}
|
|
49
|
+
return fallback
|
|
50
|
+
}
|
package/src/capture-v1/errors.ts
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
|
+
import type { CaptureEndpoint } from './types'
|
|
2
|
+
|
|
1
3
|
/** A single event the server explicitly rejected (`drop`). */
|
|
2
|
-
export interface
|
|
4
|
+
export interface CaptureDroppedEvent {
|
|
3
5
|
uuid: string
|
|
4
6
|
details?: string
|
|
5
7
|
}
|
|
6
8
|
|
|
7
|
-
export interface
|
|
9
|
+
export interface CaptureErrorParams {
|
|
10
|
+
/** The capture lane the batch was sent to. */
|
|
11
|
+
endpoint: CaptureEndpoint
|
|
8
12
|
requestId: string
|
|
9
13
|
/** Events the server rejected outright (billing/validation). */
|
|
10
|
-
drops:
|
|
14
|
+
drops: CaptureDroppedEvent[]
|
|
11
15
|
/** UUIDs of events still pending `retry` after the attempt budget was exhausted, or lost to a batch-level failure. */
|
|
12
16
|
retryExhausted: string[]
|
|
13
17
|
/** The underlying transport/HTTP/parse failure, when the whole batch failed. */
|
|
@@ -15,22 +19,24 @@ export interface CaptureV1ErrorParams {
|
|
|
15
19
|
}
|
|
16
20
|
|
|
17
21
|
/**
|
|
18
|
-
* Surfaced on the client error channel whenever a
|
|
22
|
+
* Surfaced on the client error channel whenever a capture batch did not
|
|
19
23
|
* fully deliver: some events were `drop`ped, some `retry` events outlived the
|
|
20
24
|
* attempt budget, or the batch hit a terminal transport/HTTP/parse failure.
|
|
21
25
|
*
|
|
22
26
|
* A 2xx with drops is still a partial failure and is reported here — a
|
|
23
27
|
* successful HTTP status does not mean every event was accepted.
|
|
24
28
|
*/
|
|
25
|
-
export class
|
|
26
|
-
name = '
|
|
29
|
+
export class CaptureError extends Error {
|
|
30
|
+
name = 'CaptureError'
|
|
31
|
+
readonly endpoint: CaptureEndpoint
|
|
27
32
|
readonly requestId: string
|
|
28
|
-
readonly drops:
|
|
33
|
+
readonly drops: CaptureDroppedEvent[]
|
|
29
34
|
readonly retryExhausted: string[]
|
|
30
35
|
cause?: unknown
|
|
31
36
|
|
|
32
|
-
constructor({ requestId, drops, retryExhausted, cause }:
|
|
33
|
-
super(
|
|
37
|
+
constructor({ endpoint, requestId, drops, retryExhausted, cause }: CaptureErrorParams) {
|
|
38
|
+
super(CaptureError.buildMessage(endpoint, requestId, drops, retryExhausted, cause))
|
|
39
|
+
this.endpoint = endpoint
|
|
34
40
|
this.requestId = requestId
|
|
35
41
|
this.drops = drops
|
|
36
42
|
this.retryExhausted = retryExhausted
|
|
@@ -38,15 +44,48 @@ export class CaptureV1Error extends Error {
|
|
|
38
44
|
}
|
|
39
45
|
|
|
40
46
|
private static buildMessage(
|
|
47
|
+
endpoint: CaptureEndpoint,
|
|
41
48
|
requestId: string,
|
|
42
|
-
drops:
|
|
49
|
+
drops: CaptureDroppedEvent[],
|
|
43
50
|
retryExhausted: string[],
|
|
44
51
|
cause: unknown
|
|
45
52
|
): string {
|
|
46
|
-
let message = `Capture
|
|
53
|
+
let message = `Capture batch ${requestId} to ${endpoint} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`
|
|
47
54
|
if (cause instanceof Error) {
|
|
48
55
|
message += ` (${cause.message})`
|
|
49
56
|
}
|
|
50
57
|
return message
|
|
51
58
|
}
|
|
52
59
|
}
|
|
60
|
+
|
|
61
|
+
/** Counts of undelivered events by cause, in the order the causes first occurred. */
|
|
62
|
+
export class CaptureLossTally {
|
|
63
|
+
private readonly counts = new Map<string, number>()
|
|
64
|
+
|
|
65
|
+
add(cause: string, count: number): void {
|
|
66
|
+
if (count > 0) {
|
|
67
|
+
this.counts.set(cause, (this.counts.get(cause) ?? 0) + count)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
get total(): number {
|
|
72
|
+
let total = 0
|
|
73
|
+
for (const count of this.counts.values()) {
|
|
74
|
+
total += count
|
|
75
|
+
}
|
|
76
|
+
return total
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
entries(): [cause: string, count: number][] {
|
|
80
|
+
return [...this.counts]
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The one line logged for a capture loss when nothing listens for `'error'`. It holds the lane,
|
|
86
|
+
* counts and causes only: never server response text, event content or uuids.
|
|
87
|
+
*/
|
|
88
|
+
export function describeCaptureLoss(endpoint: CaptureEndpoint, loss: CaptureLossTally): string {
|
|
89
|
+
const causes = loss.entries().map(([cause, count]) => `${count} ${cause}`)
|
|
90
|
+
return `${loss.total} event(s) were not delivered to ${endpoint}: ${causes.join(', ')}`
|
|
91
|
+
}
|