posthog-node 5.40.0 → 5.41.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.
- package/LICENSE +2 -2
- package/dist/capture-v1/config.d.ts +11 -0
- package/dist/capture-v1/config.d.ts.map +1 -0
- package/dist/capture-v1/config.js +42 -0
- package/dist/capture-v1/config.mjs +8 -0
- package/dist/capture-v1/errors.d.ts +32 -0
- package/dist/capture-v1/errors.d.ts.map +1 -0
- package/dist/capture-v1/errors.js +49 -0
- package/dist/capture-v1/errors.mjs +15 -0
- package/dist/capture-v1/routing.d.ts +21 -0
- package/dist/capture-v1/routing.d.ts.map +1 -0
- package/dist/capture-v1/routing.js +47 -0
- package/dist/capture-v1/routing.mjs +7 -0
- package/dist/capture-v1/sender.d.ts +70 -0
- package/dist/capture-v1/sender.d.ts.map +1 -0
- package/dist/capture-v1/sender.js +222 -0
- package/dist/capture-v1/sender.mjs +188 -0
- package/dist/capture-v1/transform.d.ts +34 -0
- package/dist/capture-v1/transform.d.ts.map +1 -0
- package/dist/capture-v1/transform.js +142 -0
- package/dist/capture-v1/transform.mjs +99 -0
- package/dist/capture-v1/types.d.ts +50 -0
- package/dist/capture-v1/types.d.ts.map +1 -0
- package/dist/capture-v1/types.js +18 -0
- package/dist/capture-v1/types.mjs +0 -0
- package/dist/client.d.ts +22 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +42 -0
- package/dist/client.mjs +43 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +2 -2
- package/src/capture-v1/config.ts +18 -0
- package/src/capture-v1/errors.ts +52 -0
- package/src/capture-v1/routing.ts +28 -0
- package/src/capture-v1/sender.ts +298 -0
- package/src/capture-v1/transform.ts +159 -0
- package/src/capture-v1/types.ts +55 -0
- package/src/client.ts +77 -0
- package/src/version.ts +1 -1
package/dist/client.js
CHANGED
|
@@ -44,6 +44,9 @@ const feature_flags_js_namespaceObject = require("./extensions/feature-flags/fea
|
|
|
44
44
|
const index_js_namespaceObject = require("./extensions/error-tracking/index.js");
|
|
45
45
|
var index_js_default = /*#__PURE__*/ __webpack_require__.n(index_js_namespaceObject);
|
|
46
46
|
const external_storage_memory_js_namespaceObject = require("./storage-memory.js");
|
|
47
|
+
const config_js_namespaceObject = require("./capture-v1/config.js");
|
|
48
|
+
const routing_js_namespaceObject = require("./capture-v1/routing.js");
|
|
49
|
+
const sender_js_namespaceObject = require("./capture-v1/sender.js");
|
|
47
50
|
const MINIMUM_POLLING_INTERVAL = 100;
|
|
48
51
|
const THIRTY_SECONDS = 30000;
|
|
49
52
|
const MAX_CACHE_SIZE = 50000;
|
|
@@ -94,6 +97,7 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
|
|
|
94
97
|
};
|
|
95
98
|
super(normalizedApiKey, normalizedOptions), this._memoryStorage = new external_storage_memory_js_namespaceObject.PostHogMemoryStorage();
|
|
96
99
|
this.options = normalizedOptions;
|
|
100
|
+
this.captureMode = (0, config_js_namespaceObject.resolveCaptureMode)();
|
|
97
101
|
this.context = this.initializeContext();
|
|
98
102
|
this.options.featureFlagsPollingInterval = 'number' == typeof normalizedOptions.featureFlagsPollingInterval ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
|
|
99
103
|
if ('number' == typeof normalizedOptions.waitUntilDebounceMs) this.options.waitUntilDebounceMs = Math.max(normalizedOptions.waitUntilDebounceMs, 0);
|
|
@@ -190,6 +194,44 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
|
|
|
190
194
|
fetch(url, options) {
|
|
191
195
|
return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
|
|
192
196
|
}
|
|
197
|
+
getQueueRouteKey(message) {
|
|
198
|
+
return 'v1' === this.captureMode && (0, routing_js_namespaceObject.isLegacyOnlyEvent)(message) ? routing_js_namespaceObject.AI_ROUTE : routing_js_namespaceObject.ANALYTICS_ROUTE;
|
|
199
|
+
}
|
|
200
|
+
persistedQueueKeyForRoute(route) {
|
|
201
|
+
return route === routing_js_namespaceObject.AI_ROUTE ? core_namespaceObject.PostHogPersistedProperty.AiQueue : core_namespaceObject.PostHogPersistedProperty.Queue;
|
|
202
|
+
}
|
|
203
|
+
getActiveQueueRoutes() {
|
|
204
|
+
return 'v1' === this.captureMode ? [
|
|
205
|
+
routing_js_namespaceObject.ANALYTICS_ROUTE,
|
|
206
|
+
routing_js_namespaceObject.AI_ROUTE
|
|
207
|
+
] : [
|
|
208
|
+
routing_js_namespaceObject.ANALYTICS_ROUTE
|
|
209
|
+
];
|
|
210
|
+
}
|
|
211
|
+
async sendBatch(batchMessages, retryOptions, route = routing_js_namespaceObject.ANALYTICS_ROUTE) {
|
|
212
|
+
if ('v1' !== this.captureMode || route === routing_js_namespaceObject.AI_ROUTE) return super.sendBatch(batchMessages, retryOptions, route);
|
|
213
|
+
const v1Events = batchMessages.filter((message)=>void 0 !== message);
|
|
214
|
+
await this.getV1Sender().sendV1Batch(v1Events);
|
|
215
|
+
}
|
|
216
|
+
getV1Sender() {
|
|
217
|
+
if (!this._v1Sender) this._v1Sender = new sender_js_namespaceObject.V1CaptureSender({
|
|
218
|
+
host: this.host,
|
|
219
|
+
apiKey: this.apiKey,
|
|
220
|
+
libraryId: this.getLibraryId(),
|
|
221
|
+
libraryVersion: this.getLibraryVersion(),
|
|
222
|
+
userAgent: this.getCustomUserAgent() || void 0,
|
|
223
|
+
historicalMigration: this.historicalMigration,
|
|
224
|
+
compressionEnabled: !this.disableCompression,
|
|
225
|
+
requestTimeoutMs: this.requestTimeout,
|
|
226
|
+
maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
|
|
227
|
+
initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
|
|
228
|
+
isDebug: this.isDebug
|
|
229
|
+
}, {
|
|
230
|
+
fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),
|
|
231
|
+
onError: (error)=>this._events.emit('error', error)
|
|
232
|
+
});
|
|
233
|
+
return this._v1Sender;
|
|
234
|
+
}
|
|
193
235
|
getLibraryVersion() {
|
|
194
236
|
return external_version_js_namespaceObject.version;
|
|
195
237
|
}
|
package/dist/client.mjs
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { version } from "./version.mjs";
|
|
2
|
-
import { PostHogCoreStateless, isBlockedUA, isPlainObject, safeSetTimeout, uuidv7 } from "@posthog/core";
|
|
2
|
+
import { PostHogCoreStateless, PostHogPersistedProperty, isBlockedUA, isPlainObject, safeSetTimeout, uuidv7 } from "@posthog/core";
|
|
3
3
|
import { FeatureFlagError } from "./types.mjs";
|
|
4
4
|
import { FeatureFlagEvaluations } from "./feature-flag-evaluations.mjs";
|
|
5
5
|
import { FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation } from "./extensions/feature-flags/feature-flags.mjs";
|
|
6
6
|
import error_tracking from "./extensions/error-tracking/index.mjs";
|
|
7
7
|
import { PostHogMemoryStorage } from "./storage-memory.mjs";
|
|
8
|
+
import { resolveCaptureMode } from "./capture-v1/config.mjs";
|
|
9
|
+
import { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from "./capture-v1/routing.mjs";
|
|
10
|
+
import { V1CaptureSender } from "./capture-v1/sender.mjs";
|
|
8
11
|
const MINIMUM_POLLING_INTERVAL = 100;
|
|
9
12
|
const THIRTY_SECONDS = 30000;
|
|
10
13
|
const MAX_CACHE_SIZE = 50000;
|
|
@@ -55,6 +58,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
|
|
|
55
58
|
};
|
|
56
59
|
super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage();
|
|
57
60
|
this.options = normalizedOptions;
|
|
61
|
+
this.captureMode = resolveCaptureMode();
|
|
58
62
|
this.context = this.initializeContext();
|
|
59
63
|
this.options.featureFlagsPollingInterval = 'number' == typeof normalizedOptions.featureFlagsPollingInterval ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
|
|
60
64
|
if ('number' == typeof normalizedOptions.waitUntilDebounceMs) this.options.waitUntilDebounceMs = Math.max(normalizedOptions.waitUntilDebounceMs, 0);
|
|
@@ -151,6 +155,44 @@ class PostHogBackendClient extends PostHogCoreStateless {
|
|
|
151
155
|
fetch(url, options) {
|
|
152
156
|
return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
|
|
153
157
|
}
|
|
158
|
+
getQueueRouteKey(message) {
|
|
159
|
+
return 'v1' === this.captureMode && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;
|
|
160
|
+
}
|
|
161
|
+
persistedQueueKeyForRoute(route) {
|
|
162
|
+
return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue;
|
|
163
|
+
}
|
|
164
|
+
getActiveQueueRoutes() {
|
|
165
|
+
return 'v1' === this.captureMode ? [
|
|
166
|
+
ANALYTICS_ROUTE,
|
|
167
|
+
AI_ROUTE
|
|
168
|
+
] : [
|
|
169
|
+
ANALYTICS_ROUTE
|
|
170
|
+
];
|
|
171
|
+
}
|
|
172
|
+
async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {
|
|
173
|
+
if ('v1' !== this.captureMode || route === AI_ROUTE) return super.sendBatch(batchMessages, retryOptions, route);
|
|
174
|
+
const v1Events = batchMessages.filter((message)=>void 0 !== message);
|
|
175
|
+
await this.getV1Sender().sendV1Batch(v1Events);
|
|
176
|
+
}
|
|
177
|
+
getV1Sender() {
|
|
178
|
+
if (!this._v1Sender) this._v1Sender = new V1CaptureSender({
|
|
179
|
+
host: this.host,
|
|
180
|
+
apiKey: this.apiKey,
|
|
181
|
+
libraryId: this.getLibraryId(),
|
|
182
|
+
libraryVersion: this.getLibraryVersion(),
|
|
183
|
+
userAgent: this.getCustomUserAgent() || void 0,
|
|
184
|
+
historicalMigration: this.historicalMigration,
|
|
185
|
+
compressionEnabled: !this.disableCompression,
|
|
186
|
+
requestTimeoutMs: this.requestTimeout,
|
|
187
|
+
maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
|
|
188
|
+
initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
|
|
189
|
+
isDebug: this.isDebug
|
|
190
|
+
}, {
|
|
191
|
+
fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),
|
|
192
|
+
onError: (error)=>this._events.emit('error', error)
|
|
193
|
+
});
|
|
194
|
+
return this._v1Sender;
|
|
195
|
+
}
|
|
154
196
|
getLibraryVersion() {
|
|
155
197
|
return version;
|
|
156
198
|
}
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const version = "5.
|
|
1
|
+
export declare const version = "5.41.0";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
package/dist/version.js
CHANGED
|
@@ -26,7 +26,7 @@ __webpack_require__.r(__webpack_exports__);
|
|
|
26
26
|
__webpack_require__.d(__webpack_exports__, {
|
|
27
27
|
version: ()=>version
|
|
28
28
|
});
|
|
29
|
-
const version = '5.
|
|
29
|
+
const version = '5.41.0';
|
|
30
30
|
exports.version = __webpack_exports__.version;
|
|
31
31
|
for(var __webpack_i__ in __webpack_exports__)if (-1 === [
|
|
32
32
|
"version"
|
package/dist/version.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const version = '5.
|
|
1
|
+
const version = '5.41.0';
|
|
2
2
|
export { version };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "posthog-node",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.41.0",
|
|
4
4
|
"bugs": {
|
|
5
5
|
"url": "https://github.com/PostHog/posthog-js/issues"
|
|
6
6
|
},
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"module": "dist/entrypoints/index.node.mjs",
|
|
29
29
|
"types": "dist/entrypoints/index.node.d.ts",
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@posthog/core": "^1.
|
|
31
|
+
"@posthog/core": "^1.40.2"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
34
|
"@edge-runtime/jest-environment": "^4.0.0",
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Capture submission mode: `v0` is the legacy `/batch/` endpoint, `v1` is `/i/v1/analytics/events`. */
|
|
2
|
+
export type CaptureMode = 'v0' | 'v1'
|
|
3
|
+
|
|
4
|
+
function isCaptureMode(value: unknown): value is CaptureMode {
|
|
5
|
+
return value === 'v0' || value === 'v1'
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Resolve the effective capture mode from the `POSTHOG_CAPTURE_MODE` environment
|
|
10
|
+
* variable (guarded for edge / no-`process` runtimes). The default is `v0`, so
|
|
11
|
+
* existing users are unaffected unless they explicitly opt in. Capture V1 is
|
|
12
|
+
* intentionally env-var-only during the transition — there is no public option,
|
|
13
|
+
* so nothing on the API surface has to be removed when v1 becomes the default.
|
|
14
|
+
*/
|
|
15
|
+
export function resolveCaptureMode(): CaptureMode {
|
|
16
|
+
const envMode = typeof process !== 'undefined' ? process.env?.POSTHOG_CAPTURE_MODE : undefined
|
|
17
|
+
return isCaptureMode(envMode) ? envMode : 'v0'
|
|
18
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** A single event the server explicitly rejected (`drop`). */
|
|
2
|
+
export interface V1DroppedEvent {
|
|
3
|
+
uuid: string
|
|
4
|
+
details?: string
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface CaptureV1ErrorParams {
|
|
8
|
+
requestId: string
|
|
9
|
+
/** Events the server rejected outright (billing/validation). */
|
|
10
|
+
drops: V1DroppedEvent[]
|
|
11
|
+
/** UUIDs of events still pending `retry` after the attempt budget was exhausted, or lost to a batch-level failure. */
|
|
12
|
+
retryExhausted: string[]
|
|
13
|
+
/** The underlying transport/HTTP/parse failure, when the whole batch failed. */
|
|
14
|
+
cause?: unknown
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Surfaced on the client error channel whenever a Capture V1 batch did not
|
|
19
|
+
* fully deliver: some events were `drop`ped, some `retry` events outlived the
|
|
20
|
+
* attempt budget, or the batch hit a terminal transport/HTTP/parse failure.
|
|
21
|
+
*
|
|
22
|
+
* A 2xx with drops is still a partial failure and is reported here — a
|
|
23
|
+
* successful HTTP status does not mean every event was accepted.
|
|
24
|
+
*/
|
|
25
|
+
export class CaptureV1Error extends Error {
|
|
26
|
+
name = 'CaptureV1Error'
|
|
27
|
+
readonly requestId: string
|
|
28
|
+
readonly drops: V1DroppedEvent[]
|
|
29
|
+
readonly retryExhausted: string[]
|
|
30
|
+
cause?: unknown
|
|
31
|
+
|
|
32
|
+
constructor({ requestId, drops, retryExhausted, cause }: CaptureV1ErrorParams) {
|
|
33
|
+
super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause))
|
|
34
|
+
this.requestId = requestId
|
|
35
|
+
this.drops = drops
|
|
36
|
+
this.retryExhausted = retryExhausted
|
|
37
|
+
this.cause = cause
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
private static buildMessage(
|
|
41
|
+
requestId: string,
|
|
42
|
+
drops: V1DroppedEvent[],
|
|
43
|
+
retryExhausted: string[],
|
|
44
|
+
cause: unknown
|
|
45
|
+
): string {
|
|
46
|
+
let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`
|
|
47
|
+
if (cause instanceof Error) {
|
|
48
|
+
message += ` (${cause.message})`
|
|
49
|
+
}
|
|
50
|
+
return message
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { PostHogEventProperties } from '@posthog/core'
|
|
2
|
+
|
|
3
|
+
/** Event-name prefix for AI analytics events, which have no Capture V1 form yet. */
|
|
4
|
+
const AI_EVENT_PREFIX = '$ai_'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Queue route for events eligible for Capture V1 (everything except `$ai_*`). Its queue is the
|
|
8
|
+
* historical {@link PostHogPersistedProperty.Queue}, so v0 mode is byte-identical to before.
|
|
9
|
+
*/
|
|
10
|
+
export const ANALYTICS_ROUTE = 'analytics'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Queue route for `$ai_*` events, kept on the legacy (v0) transport in v1 mode and isolated on
|
|
14
|
+
* its own queue so a v0 failure can't re-send events already accepted on the V1 route. This route
|
|
15
|
+
* will later host a dedicated v1 AI-events transport once that endpoint exists — segregating it
|
|
16
|
+
* now means no re-plumbing then.
|
|
17
|
+
*/
|
|
18
|
+
export const AI_ROUTE = 'ai'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* True for events that must keep using the legacy (v0) submitter even when the
|
|
22
|
+
* client is in v1 mode. Today that is only `$ai_*` events: the dedicated AI
|
|
23
|
+
* ingestion path has no v1 form, so they stay on v0 until AI v1 is designed.
|
|
24
|
+
* The check runs on the post-`before_send` event name.
|
|
25
|
+
*/
|
|
26
|
+
export function isLegacyOnlyEvent(message: PostHogEventProperties): boolean {
|
|
27
|
+
return typeof message.event === 'string' && message.event.startsWith(AI_EVENT_PREFIX)
|
|
28
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type FetchLike,
|
|
3
|
+
type PostHogEventProperties,
|
|
4
|
+
type PostHogFetchOptions,
|
|
5
|
+
type PostHogFetchResponse,
|
|
6
|
+
gzipCompress,
|
|
7
|
+
safeJsonStringify,
|
|
8
|
+
safeSetTimeout,
|
|
9
|
+
uuidv7,
|
|
10
|
+
} from '@posthog/core'
|
|
11
|
+
|
|
12
|
+
import { CaptureV1Error, type V1DroppedEvent } from './errors'
|
|
13
|
+
import { buildV1Batch } from './transform'
|
|
14
|
+
import type { V1BatchResponse, V1Event } from './types'
|
|
15
|
+
|
|
16
|
+
const V1_ANALYTICS_PATH = '/i/v1/analytics/events'
|
|
17
|
+
const DEFAULT_MAX_BACKOFF_MS = 30_000
|
|
18
|
+
|
|
19
|
+
/** HTTP statuses the v1 backend wants retried. 429 is intentionally terminal in v1. */
|
|
20
|
+
const RETRYABLE_STATUSES = new Set([408, 500, 502, 503, 504])
|
|
21
|
+
|
|
22
|
+
export interface V1CaptureSenderConfig {
|
|
23
|
+
host: string
|
|
24
|
+
apiKey: string
|
|
25
|
+
/** Canonical `$lib` identity, materialized by the server from `PostHog-Sdk-Info`. */
|
|
26
|
+
libraryId: string
|
|
27
|
+
libraryVersion: string
|
|
28
|
+
/** Value for the `User-Agent` header, if the runtime allows setting it. */
|
|
29
|
+
userAgent?: string
|
|
30
|
+
historicalMigration: boolean
|
|
31
|
+
/** When true, the body is gzip-compressed (falling back to uncompressed on failure). */
|
|
32
|
+
compressionEnabled: boolean
|
|
33
|
+
requestTimeoutMs: number
|
|
34
|
+
/** Total attempts, including the first (1 initial + N retries). */
|
|
35
|
+
maxAttempts: number
|
|
36
|
+
/** Base exponential backoff, doubled each retry and capped at `maxBackoffMs`. */
|
|
37
|
+
initialRetryDelayMs: number
|
|
38
|
+
/** Single ceiling for both the backoff schedule and the `Retry-After` clamp. */
|
|
39
|
+
maxBackoffMs?: number
|
|
40
|
+
isDebug?: boolean
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface V1CaptureSenderHooks {
|
|
44
|
+
fetch: FetchLike
|
|
45
|
+
/** Surfaces partial/terminal delivery failures on the client error channel. */
|
|
46
|
+
onError: (error: Error) => void
|
|
47
|
+
now?: () => number
|
|
48
|
+
sleep?: (ms: number) => Promise<void>
|
|
49
|
+
generateRequestId?: () => string
|
|
50
|
+
compress?: (payload: string, isDebug?: boolean) => Promise<Blob | null>
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Sends already-normalized events to the Capture V1 endpoint
|
|
55
|
+
* (`POST /i/v1/analytics/events`), owning the full attempt loop: per-event
|
|
56
|
+
* partial retry, exponential backoff clamped against `Retry-After`, v1 status
|
|
57
|
+
* classification, and surfacing drops / undelivered events on the error
|
|
58
|
+
* channel. Used by both the batched and immediate send paths.
|
|
59
|
+
*
|
|
60
|
+
* Never throws for a handled outcome: after exhausting its own attempt budget it
|
|
61
|
+
* reports the failure via `onError` and resolves, so the caller's queue treats
|
|
62
|
+
* the batch as consumed (the internal budget replaces v0's queue-level retry).
|
|
63
|
+
*/
|
|
64
|
+
export class V1CaptureSender {
|
|
65
|
+
private readonly config: V1CaptureSenderConfig
|
|
66
|
+
private readonly maxBackoffMs: number
|
|
67
|
+
private readonly fetchFn: FetchLike
|
|
68
|
+
private readonly onError: (error: Error) => void
|
|
69
|
+
private readonly now: () => number
|
|
70
|
+
private readonly sleep: (ms: number) => Promise<void>
|
|
71
|
+
private readonly generateRequestId: () => string
|
|
72
|
+
private readonly compress: (payload: string, isDebug?: boolean) => Promise<Blob | null>
|
|
73
|
+
|
|
74
|
+
constructor(config: V1CaptureSenderConfig, hooks: V1CaptureSenderHooks) {
|
|
75
|
+
this.config = config
|
|
76
|
+
this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS
|
|
77
|
+
this.fetchFn = hooks.fetch
|
|
78
|
+
this.onError = hooks.onError
|
|
79
|
+
this.now = hooks.now ?? Date.now
|
|
80
|
+
this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve) => safeSetTimeout(resolve, ms)))
|
|
81
|
+
this.generateRequestId = hooks.generateRequestId ?? uuidv7
|
|
82
|
+
this.compress = hooks.compress ?? gzipCompress
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async sendV1Batch(messages: PostHogEventProperties[]): Promise<void> {
|
|
86
|
+
if (messages.length === 0) {
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const requestId = this.generateRequestId()
|
|
91
|
+
// created_at is generated once and stays stable across every retry.
|
|
92
|
+
const createdAt = new Date(this.now()).toISOString()
|
|
93
|
+
const { batch } = buildV1Batch(messages, {
|
|
94
|
+
createdAt,
|
|
95
|
+
historicalMigration: this.config.historicalMigration,
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
const url = `${this.config.host}${V1_ANALYTICS_PATH}`
|
|
99
|
+
const drops: V1DroppedEvent[] = []
|
|
100
|
+
let pending = batch
|
|
101
|
+
|
|
102
|
+
// Guard against a misconfigured budget (e.g. fetchRetryCount: -1): always make
|
|
103
|
+
// at least one attempt so a bad config surfaces a delivery error instead of
|
|
104
|
+
// silently dropping the batch without ever sending or calling onError.
|
|
105
|
+
const maxAttempts = Math.max(1, this.config.maxAttempts)
|
|
106
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
107
|
+
const isLastAttempt = attempt === maxAttempts
|
|
108
|
+
const payload = safeJsonStringify({
|
|
109
|
+
created_at: createdAt,
|
|
110
|
+
...(this.config.historicalMigration ? { historical_migration: true } : {}),
|
|
111
|
+
batch: pending,
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
let response: PostHogFetchResponse
|
|
115
|
+
try {
|
|
116
|
+
response = await this.sendOnce(url, payload, attempt, requestId)
|
|
117
|
+
} catch (transportError) {
|
|
118
|
+
// Connection/timeout with no HTTP response: retry until the budget runs out.
|
|
119
|
+
if (isLastAttempt) {
|
|
120
|
+
return this.surfaceBatchFailure(requestId, drops, pending, transportError)
|
|
121
|
+
}
|
|
122
|
+
await this.sleep(this.backoffDelay(attempt))
|
|
123
|
+
continue
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const { status } = response
|
|
127
|
+
if (status < 200 || status >= 300) {
|
|
128
|
+
if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
|
|
129
|
+
const retryAfterMs = this.parseRetryAfter(response)
|
|
130
|
+
await this.cancelBody(response)
|
|
131
|
+
await this.sleep(this.backoffDelay(attempt, retryAfterMs))
|
|
132
|
+
continue
|
|
133
|
+
}
|
|
134
|
+
const httpError = await this.buildHttpError(response, status)
|
|
135
|
+
return this.surfaceBatchFailure(requestId, drops, pending, httpError)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
let parsed: V1BatchResponse
|
|
139
|
+
try {
|
|
140
|
+
parsed = await this.parseResponse(response)
|
|
141
|
+
} catch {
|
|
142
|
+
// A 2xx we cannot parse is terminal — re-sending against a broken success would loop forever.
|
|
143
|
+
return this.surfaceBatchFailure(
|
|
144
|
+
requestId,
|
|
145
|
+
drops,
|
|
146
|
+
pending,
|
|
147
|
+
new Error(`Capture V1 returned an unparseable ${status} response body`)
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const retryable = this.classify(pending, parsed, drops)
|
|
152
|
+
if (retryable.length === 0) {
|
|
153
|
+
return this.surfacePartialDrops(requestId, drops)
|
|
154
|
+
}
|
|
155
|
+
if (isLastAttempt) {
|
|
156
|
+
this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: retryable.map((event) => event.uuid) }))
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
pending = retryable
|
|
160
|
+
// A 200 partial-retry body can also carry Retry-After (e.g. rate-limited
|
|
161
|
+
// retry events); honor it as a minimum the same way as on a retryable status.
|
|
162
|
+
const retryAfterMs = this.parseRetryAfter(response)
|
|
163
|
+
await this.sleep(this.backoffDelay(attempt, retryAfterMs))
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private async sendOnce(
|
|
168
|
+
url: string,
|
|
169
|
+
payload: string,
|
|
170
|
+
attempt: number,
|
|
171
|
+
requestId: string
|
|
172
|
+
): Promise<PostHogFetchResponse> {
|
|
173
|
+
const headers = this.buildHeaders(attempt, requestId)
|
|
174
|
+
let body: string | Blob = payload
|
|
175
|
+
if (this.config.compressionEnabled) {
|
|
176
|
+
const compressed = await this.compress(payload, this.config.isDebug)
|
|
177
|
+
if (compressed !== null) {
|
|
178
|
+
body = compressed
|
|
179
|
+
headers['Content-Encoding'] = 'gzip'
|
|
180
|
+
}
|
|
181
|
+
// A codec that fails to compress falls back to sending uncompressed.
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const controller = new AbortController()
|
|
185
|
+
const timer = safeSetTimeout(() => controller.abort(), this.config.requestTimeoutMs)
|
|
186
|
+
try {
|
|
187
|
+
return await this.fetchFn(url, { method: 'POST', headers, body, signal: controller.signal })
|
|
188
|
+
} finally {
|
|
189
|
+
clearTimeout(timer)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
private buildHeaders(attempt: number, requestId: string): PostHogFetchOptions['headers'] {
|
|
194
|
+
const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`
|
|
195
|
+
const headers: { [key: string]: string } = {
|
|
196
|
+
'Content-Type': 'application/json',
|
|
197
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
198
|
+
'PostHog-Sdk-Info': sdkInfo,
|
|
199
|
+
'PostHog-Attempt': String(attempt),
|
|
200
|
+
'PostHog-Request-Id': requestId,
|
|
201
|
+
// Regenerated per attempt — a per-attempt wall-clock stamp, unlike Request-Id / created_at.
|
|
202
|
+
'PostHog-Request-Timestamp': new Date(this.now()).toISOString(),
|
|
203
|
+
}
|
|
204
|
+
if (this.config.userAgent) {
|
|
205
|
+
headers['User-Agent'] = this.config.userAgent
|
|
206
|
+
}
|
|
207
|
+
return headers
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Partition the pending events against a 2xx result map: `drop` accumulates as
|
|
212
|
+
* a terminal failure, `retry` is returned for the next attempt, and
|
|
213
|
+
* `ok`/`warning`/unknown/absent are terminal successes.
|
|
214
|
+
*/
|
|
215
|
+
private classify(pending: V1Event[], parsed: V1BatchResponse, drops: V1DroppedEvent[]): V1Event[] {
|
|
216
|
+
const results = parsed.results ?? {}
|
|
217
|
+
const retryable: V1Event[] = []
|
|
218
|
+
for (const event of pending) {
|
|
219
|
+
const result = results[event.uuid]
|
|
220
|
+
if (!result) {
|
|
221
|
+
continue
|
|
222
|
+
}
|
|
223
|
+
if (result.result === 'drop') {
|
|
224
|
+
drops.push({ uuid: event.uuid, details: result.details ?? undefined })
|
|
225
|
+
} else if (result.result === 'retry') {
|
|
226
|
+
retryable.push(event)
|
|
227
|
+
}
|
|
228
|
+
// ok / warning / unknown codes are terminal successes.
|
|
229
|
+
}
|
|
230
|
+
return retryable
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
private backoffDelay(attempt: number, retryAfterMs?: number): number {
|
|
234
|
+
const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs)
|
|
235
|
+
if (retryAfterMs === undefined) {
|
|
236
|
+
return exponential
|
|
237
|
+
}
|
|
238
|
+
// Retry-After is a minimum (never lets us retry earlier than our own backoff) and is clamped to the ceiling.
|
|
239
|
+
return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Parse `Retry-After` (delta-seconds or HTTP-date). Non-positive/past values are ignored. */
|
|
243
|
+
private parseRetryAfter(response: PostHogFetchResponse): number | undefined {
|
|
244
|
+
const raw = response.headers?.get('Retry-After')
|
|
245
|
+
if (!raw) {
|
|
246
|
+
return undefined
|
|
247
|
+
}
|
|
248
|
+
const trimmed = raw.trim()
|
|
249
|
+
if (/^\d+$/.test(trimmed)) {
|
|
250
|
+
const seconds = parseInt(trimmed, 10)
|
|
251
|
+
return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : undefined
|
|
252
|
+
}
|
|
253
|
+
const dateMs = Date.parse(trimmed)
|
|
254
|
+
if (Number.isNaN(dateMs)) {
|
|
255
|
+
return undefined
|
|
256
|
+
}
|
|
257
|
+
const delta = dateMs - this.now()
|
|
258
|
+
return delta > 0 ? delta : undefined
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private async parseResponse(response: PostHogFetchResponse): Promise<V1BatchResponse> {
|
|
262
|
+
const text = await response.text()
|
|
263
|
+
const parsed = JSON.parse(text)
|
|
264
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
265
|
+
throw new Error('unexpected response shape')
|
|
266
|
+
}
|
|
267
|
+
const results = (parsed as { results?: unknown }).results
|
|
268
|
+
if (results !== undefined && (typeof results !== 'object' || results === null || Array.isArray(results))) {
|
|
269
|
+
throw new Error('unexpected results shape')
|
|
270
|
+
}
|
|
271
|
+
return { results: (results as V1BatchResponse['results']) ?? {} }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private async buildHttpError(response: PostHogFetchResponse, status: number): Promise<Error> {
|
|
275
|
+
let bodyText = ''
|
|
276
|
+
try {
|
|
277
|
+
bodyText = (await response.text()).slice(0, 512)
|
|
278
|
+
} catch {
|
|
279
|
+
// best-effort; a missing body should not mask the status
|
|
280
|
+
}
|
|
281
|
+
const suffix = bodyText ? `: ${bodyText}` : ''
|
|
282
|
+
return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
private surfaceBatchFailure(requestId: string, drops: V1DroppedEvent[], pending: V1Event[], cause: unknown): void {
|
|
286
|
+
this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: pending.map((event) => event.uuid), cause }))
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private surfacePartialDrops(requestId: string, drops: V1DroppedEvent[]): void {
|
|
290
|
+
if (drops.length > 0) {
|
|
291
|
+
this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: [] }))
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
private async cancelBody(response: PostHogFetchResponse): Promise<void> {
|
|
296
|
+
await response.body?.cancel()?.catch(() => {})
|
|
297
|
+
}
|
|
298
|
+
}
|