@posthog/core 1.65.0 → 1.67.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/dist/logs/index.d.ts +18 -1
- package/dist/logs/index.d.ts.map +1 -1
- package/dist/logs/index.js +22 -3
- package/dist/logs/index.mjs +22 -3
- package/dist/metrics/index.d.ts +9 -0
- package/dist/metrics/index.d.ts.map +1 -1
- package/dist/metrics/index.js +13 -0
- package/dist/metrics/index.mjs +13 -0
- package/package.json +2 -2
- package/src/logs/index.spec.ts +119 -0
- package/src/logs/index.ts +57 -3
- package/src/metrics/index.spec.ts +70 -0
- package/src/metrics/index.ts +30 -0
package/dist/logs/index.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ export declare class PostHogLogs {
|
|
|
8
8
|
private readonly _onReady;
|
|
9
9
|
private readonly _waitForStoragePersist;
|
|
10
10
|
private readonly _scopeName?;
|
|
11
|
+
private readonly _isConsentWithdrawn;
|
|
11
12
|
private _maxBufferSize;
|
|
12
13
|
private _maxQueueSize;
|
|
13
14
|
private _flushIntervalMs;
|
|
@@ -16,6 +17,7 @@ export declare class PostHogLogs {
|
|
|
16
17
|
private _flushPromise;
|
|
17
18
|
private _evictedSinceAdvance;
|
|
18
19
|
private _queueGeneration;
|
|
20
|
+
private _backgroundFlushPromise;
|
|
19
21
|
private _retryAfter;
|
|
20
22
|
private _consecutiveFlushFailures;
|
|
21
23
|
private _flushJitter;
|
|
@@ -24,13 +26,15 @@ export declare class PostHogLogs {
|
|
|
24
26
|
private _intervalWindowStart;
|
|
25
27
|
private _intervalLogCount;
|
|
26
28
|
private _droppedWarned;
|
|
27
|
-
constructor(_instance: LogsHost, _config: ResolvedPostHogLogsConfig, _logger: Logger, _getContext: () => LogSdkContext, _onReady: (fn: () => void) => void, _waitForStoragePersist?: () => Promise<void>, _scopeName?: string | undefined);
|
|
29
|
+
constructor(_instance: LogsHost, _config: ResolvedPostHogLogsConfig, _logger: Logger, _getContext: () => LogSdkContext, _onReady: (fn: () => void) => void, _waitForStoragePersist?: () => Promise<void>, _scopeName?: string | undefined, _isConsentWithdrawn?: () => boolean);
|
|
28
30
|
/**
|
|
29
31
|
* Drops every queued record. A batch this instance has in flight is retired with
|
|
30
32
|
* them, so it can neither re-send what was just purged nor advance past records
|
|
31
33
|
* captured after this call.
|
|
32
34
|
*/
|
|
33
35
|
clearQueue(): void;
|
|
36
|
+
/** True while the endpoint's `Retry-After` window is open, so a host's automatic flush can skip logs. */
|
|
37
|
+
get throttled(): boolean;
|
|
34
38
|
/**
|
|
35
39
|
* Clears the flush timer and rate-cap state. The host owns the record queue
|
|
36
40
|
* and clears it separately (the browser empties its in-memory store).
|
|
@@ -88,6 +92,12 @@ export declare class PostHogLogs {
|
|
|
88
92
|
*/
|
|
89
93
|
flush(): Promise<void>;
|
|
90
94
|
private _flushInner;
|
|
95
|
+
/**
|
|
96
|
+
* Drops the queue once consent is withdrawn. Records carry the distinct id and
|
|
97
|
+
* session id, so whatever is still queued when the user opts out must not be
|
|
98
|
+
* exported, by a pending timer or by a drain already under way.
|
|
99
|
+
*/
|
|
100
|
+
private _discardQueueIfConsentWithdrawn;
|
|
91
101
|
private _persistQueueAdvance;
|
|
92
102
|
private _buildResourceAttributes;
|
|
93
103
|
private _enqueue;
|
|
@@ -118,6 +128,13 @@ export declare class PostHogLogs {
|
|
|
118
128
|
* unhandled-rejection logs — the next regular flush cycle will retry.
|
|
119
129
|
*/
|
|
120
130
|
flushWithTimeout(timeoutMs: number): Promise<void>;
|
|
131
|
+
/**
|
|
132
|
+
* `flush()` for a host that drives logs from its own flush cycle. Never rejects, and when
|
|
133
|
+
* records remain (a failed send, or captures that landed mid-flush) re-arms the timer with
|
|
134
|
+
* backoff, as the pipeline's own timer flush does. A bare `flush()` clears the timer and
|
|
135
|
+
* leaves nothing to retry the records once traffic stops.
|
|
136
|
+
*/
|
|
137
|
+
flushInBackground(): Promise<void>;
|
|
121
138
|
private _flushInBackground;
|
|
122
139
|
}
|
|
123
140
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/logs/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/logs/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAA4B,MAAM,UAAU,CAAA;AAK3D,OAAO,KAAK,EAAoB,iBAAiB,EAAE,aAAa,EAAE,QAAQ,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAA;AAItH,qBAAa,WAAW;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/logs/index.ts"],"names":[],"mappings":"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"}
|
package/dist/logs/index.js
CHANGED
|
@@ -37,7 +37,7 @@ const flush_timer_js_namespaceObject = require("../utils/flush-timer.js");
|
|
|
37
37
|
const retry_after_js_namespaceObject = require("../utils/retry-after.js");
|
|
38
38
|
const backoff_js_namespaceObject = require("../utils/backoff.js");
|
|
39
39
|
class PostHogLogs {
|
|
40
|
-
constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName){
|
|
40
|
+
constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName, _isConsentWithdrawn = ()=>false){
|
|
41
41
|
this._instance = _instance;
|
|
42
42
|
this._config = _config;
|
|
43
43
|
this._logger = _logger;
|
|
@@ -45,10 +45,12 @@ class PostHogLogs {
|
|
|
45
45
|
this._onReady = _onReady;
|
|
46
46
|
this._waitForStoragePersist = _waitForStoragePersist;
|
|
47
47
|
this._scopeName = _scopeName;
|
|
48
|
+
this._isConsentWithdrawn = _isConsentWithdrawn;
|
|
48
49
|
this._flushTimer = new flush_timer_js_namespaceObject.FlushTimer(()=>this._flushInBackground());
|
|
49
50
|
this._flushPromise = null;
|
|
50
51
|
this._evictedSinceAdvance = 0;
|
|
51
52
|
this._queueGeneration = 0;
|
|
53
|
+
this._backgroundFlushPromise = null;
|
|
52
54
|
this._retryAfter = new retry_after_js_namespaceObject.RetryAfterWindow();
|
|
53
55
|
this._consecutiveFlushFailures = 0;
|
|
54
56
|
this._flushJitter = backoff_js_namespaceObject.NO_JITTER;
|
|
@@ -66,6 +68,9 @@ class PostHogLogs {
|
|
|
66
68
|
this._queueGeneration++;
|
|
67
69
|
this._instance.setPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.LogsQueue, []);
|
|
68
70
|
}
|
|
71
|
+
get throttled() {
|
|
72
|
+
return this._retryAfter.isOpen();
|
|
73
|
+
}
|
|
69
74
|
reset() {
|
|
70
75
|
this._flushTimer.clear();
|
|
71
76
|
this._intervalWindowStart = 0;
|
|
@@ -148,11 +153,13 @@ class PostHogLogs {
|
|
|
148
153
|
}
|
|
149
154
|
async _flushInner() {
|
|
150
155
|
this._flushTimer.clear();
|
|
156
|
+
if (this._discardQueueIfConsentWithdrawn()) return;
|
|
151
157
|
let queue = this._instance.getPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.LogsQueue) ?? [];
|
|
152
158
|
if (0 === queue.length) return;
|
|
153
159
|
const originalQueueLength = queue.length;
|
|
154
160
|
let sentCount = 0;
|
|
155
161
|
while(queue.length > 0 && sentCount < originalQueueLength){
|
|
162
|
+
if (this._discardQueueIfConsentWithdrawn()) return;
|
|
156
163
|
const generation = this._queueGeneration;
|
|
157
164
|
this._evictedSinceAdvance = 0;
|
|
158
165
|
const batchSize = Math.min(queue.length, this._maxBatchRecordsPerPost);
|
|
@@ -177,6 +184,11 @@ class PostHogLogs {
|
|
|
177
184
|
if ('fatal' === outcome.kind) throw outcome.error;
|
|
178
185
|
}
|
|
179
186
|
}
|
|
187
|
+
_discardQueueIfConsentWithdrawn() {
|
|
188
|
+
if (!this._isConsentWithdrawn()) return false;
|
|
189
|
+
if (this._hasQueuedRecords()) this.clearQueue();
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
180
192
|
async _persistQueueAdvance(consumed) {
|
|
181
193
|
const evicted = this._evictedSinceAdvance;
|
|
182
194
|
const drop = Math.max(0, consumed - evicted);
|
|
@@ -223,8 +235,9 @@ class PostHogLogs {
|
|
|
223
235
|
flushPromise.catch(()=>{});
|
|
224
236
|
});
|
|
225
237
|
}
|
|
226
|
-
|
|
227
|
-
this.
|
|
238
|
+
flushInBackground() {
|
|
239
|
+
if (this._backgroundFlushPromise) return this._backgroundFlushPromise;
|
|
240
|
+
const promise = this.flush().then(()=>{
|
|
228
241
|
this._consecutiveFlushFailures = 0;
|
|
229
242
|
this._flushJitter = backoff_js_namespaceObject.NO_JITTER;
|
|
230
243
|
}, (err)=>{
|
|
@@ -232,8 +245,14 @@ class PostHogLogs {
|
|
|
232
245
|
this._flushJitter = (0, backoff_js_namespaceObject.drawJitter)();
|
|
233
246
|
this._logger.error('PostHog logs flush failed:', err);
|
|
234
247
|
}).finally(()=>{
|
|
248
|
+
if (this._backgroundFlushPromise === promise) this._backgroundFlushPromise = null;
|
|
235
249
|
if (!this._instance.isDisabled && this._hasQueuedRecords()) this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
|
|
236
250
|
});
|
|
251
|
+
this._backgroundFlushPromise = promise;
|
|
252
|
+
return promise;
|
|
253
|
+
}
|
|
254
|
+
_flushInBackground() {
|
|
255
|
+
this.flushInBackground();
|
|
237
256
|
}
|
|
238
257
|
}
|
|
239
258
|
exports.PostHogLogs = __webpack_exports__.PostHogLogs;
|
package/dist/logs/index.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { FlushTimer } from "../utils/flush-timer.mjs";
|
|
|
5
5
|
import { RetryAfterWindow } from "../utils/retry-after.mjs";
|
|
6
6
|
import { MAX_FLUSH_BACKOFF_MS, NO_JITTER, backoffDelayMs, drawJitter } from "../utils/backoff.mjs";
|
|
7
7
|
class PostHogLogs {
|
|
8
|
-
constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName){
|
|
8
|
+
constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName, _isConsentWithdrawn = ()=>false){
|
|
9
9
|
this._instance = _instance;
|
|
10
10
|
this._config = _config;
|
|
11
11
|
this._logger = _logger;
|
|
@@ -13,10 +13,12 @@ class PostHogLogs {
|
|
|
13
13
|
this._onReady = _onReady;
|
|
14
14
|
this._waitForStoragePersist = _waitForStoragePersist;
|
|
15
15
|
this._scopeName = _scopeName;
|
|
16
|
+
this._isConsentWithdrawn = _isConsentWithdrawn;
|
|
16
17
|
this._flushTimer = new FlushTimer(()=>this._flushInBackground());
|
|
17
18
|
this._flushPromise = null;
|
|
18
19
|
this._evictedSinceAdvance = 0;
|
|
19
20
|
this._queueGeneration = 0;
|
|
21
|
+
this._backgroundFlushPromise = null;
|
|
20
22
|
this._retryAfter = new RetryAfterWindow();
|
|
21
23
|
this._consecutiveFlushFailures = 0;
|
|
22
24
|
this._flushJitter = NO_JITTER;
|
|
@@ -34,6 +36,9 @@ class PostHogLogs {
|
|
|
34
36
|
this._queueGeneration++;
|
|
35
37
|
this._instance.setPersistedProperty(PostHogPersistedProperty.LogsQueue, []);
|
|
36
38
|
}
|
|
39
|
+
get throttled() {
|
|
40
|
+
return this._retryAfter.isOpen();
|
|
41
|
+
}
|
|
37
42
|
reset() {
|
|
38
43
|
this._flushTimer.clear();
|
|
39
44
|
this._intervalWindowStart = 0;
|
|
@@ -116,11 +121,13 @@ class PostHogLogs {
|
|
|
116
121
|
}
|
|
117
122
|
async _flushInner() {
|
|
118
123
|
this._flushTimer.clear();
|
|
124
|
+
if (this._discardQueueIfConsentWithdrawn()) return;
|
|
119
125
|
let queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];
|
|
120
126
|
if (0 === queue.length) return;
|
|
121
127
|
const originalQueueLength = queue.length;
|
|
122
128
|
let sentCount = 0;
|
|
123
129
|
while(queue.length > 0 && sentCount < originalQueueLength){
|
|
130
|
+
if (this._discardQueueIfConsentWithdrawn()) return;
|
|
124
131
|
const generation = this._queueGeneration;
|
|
125
132
|
this._evictedSinceAdvance = 0;
|
|
126
133
|
const batchSize = Math.min(queue.length, this._maxBatchRecordsPerPost);
|
|
@@ -145,6 +152,11 @@ class PostHogLogs {
|
|
|
145
152
|
if ('fatal' === outcome.kind) throw outcome.error;
|
|
146
153
|
}
|
|
147
154
|
}
|
|
155
|
+
_discardQueueIfConsentWithdrawn() {
|
|
156
|
+
if (!this._isConsentWithdrawn()) return false;
|
|
157
|
+
if (this._hasQueuedRecords()) this.clearQueue();
|
|
158
|
+
return true;
|
|
159
|
+
}
|
|
148
160
|
async _persistQueueAdvance(consumed) {
|
|
149
161
|
const evicted = this._evictedSinceAdvance;
|
|
150
162
|
const drop = Math.max(0, consumed - evicted);
|
|
@@ -191,8 +203,9 @@ class PostHogLogs {
|
|
|
191
203
|
flushPromise.catch(()=>{});
|
|
192
204
|
});
|
|
193
205
|
}
|
|
194
|
-
|
|
195
|
-
this.
|
|
206
|
+
flushInBackground() {
|
|
207
|
+
if (this._backgroundFlushPromise) return this._backgroundFlushPromise;
|
|
208
|
+
const promise = this.flush().then(()=>{
|
|
196
209
|
this._consecutiveFlushFailures = 0;
|
|
197
210
|
this._flushJitter = NO_JITTER;
|
|
198
211
|
}, (err)=>{
|
|
@@ -200,8 +213,14 @@ class PostHogLogs {
|
|
|
200
213
|
this._flushJitter = drawJitter();
|
|
201
214
|
this._logger.error('PostHog logs flush failed:', err);
|
|
202
215
|
}).finally(()=>{
|
|
216
|
+
if (this._backgroundFlushPromise === promise) this._backgroundFlushPromise = null;
|
|
203
217
|
if (!this._instance.isDisabled && this._hasQueuedRecords()) this._flushTimer.armNoEarlierThan(this._nextFlushDelay());
|
|
204
218
|
});
|
|
219
|
+
this._backgroundFlushPromise = promise;
|
|
220
|
+
return promise;
|
|
221
|
+
}
|
|
222
|
+
_flushInBackground() {
|
|
223
|
+
this.flushInBackground();
|
|
205
224
|
}
|
|
206
225
|
}
|
|
207
226
|
export { PostHogLogs };
|
package/dist/metrics/index.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ export declare class PostHogMetrics {
|
|
|
26
26
|
private _series;
|
|
27
27
|
private readonly _flushTimer;
|
|
28
28
|
private _flushPromise;
|
|
29
|
+
private _queuedFlush;
|
|
29
30
|
private _seriesCapWarned;
|
|
30
31
|
private _typeByName;
|
|
31
32
|
private _typeCollisionWarned;
|
|
@@ -42,6 +43,14 @@ export declare class PostHogMetrics {
|
|
|
42
43
|
histogram(name: string, value: number, options?: HistogramOptions): void;
|
|
43
44
|
/** Sends everything aggregated so far without waiting for the flush interval. */
|
|
44
45
|
flush(): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* A flush for callers that ask once per unit of work (a served request, say) rather than once per window.
|
|
48
|
+
* Callers share one queued flush, so at most one send is in flight and one waits behind it however often
|
|
49
|
+
* this is called, and every sample captured before the call is in one of them. While a failed send is
|
|
50
|
+
* backing off it starts nothing and the retry timer owns the next send.
|
|
51
|
+
*/
|
|
52
|
+
flushCoalesced(): Promise<void>;
|
|
53
|
+
private _isBackingOff;
|
|
45
54
|
/**
|
|
46
55
|
* Synchronously snapshots the current window into an OTLP payload and
|
|
47
56
|
* resets it, bypassing the flush serializer entirely — for unload-time
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/metrics/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EAOhB,kBAAkB,EAEnB,MAAM,gBAAgB,CAAA;AACvB,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAetC,OAAO,KAAK,EAAE,WAAW,EAAE,4BAA4B,EAAE,MAAM,SAAS,CAAA;AAqCxE;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,cAAc;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/metrics/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EAOhB,kBAAkB,EAEnB,MAAM,gBAAgB,CAAA;AACvB,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAetC,OAAO,KAAK,EAAE,WAAW,EAAE,4BAA4B,EAAE,MAAM,SAAS,CAAA;AAqCxE;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,cAAc;IAoCvB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO;IArC1B,OAAO,CAAC,OAAO,CAAiC;IAChD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAI3B;IAGD,OAAO,CAAC,aAAa,CAA6B;IAElD,OAAO,CAAC,YAAY,CAA6B;IAEjD,OAAO,CAAC,gBAAgB,CAAQ;IAIhC,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,oBAAoB,CAAoB;IAKhD,OAAO,CAAC,kBAAkB,CAA8B;IAExD,OAAO,CAAC,qBAAqB,CAAoB;IACjD,OAAO,CAAC,gBAAgB,CAAQ;IAChC,OAAO,CAAC,WAAW,CAAyB;IAC5C,OAAO,CAAC,yBAAyB,CAAI;IACrC,OAAO,CAAC,YAAY,CAAY;IAIhC,OAAO,CAAC,WAAW,CAAI;IAEvB,YACmB,SAAS,EAAE,WAAW,EACtB,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,MAAM,EAC9B;IAEJ,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,MAAU,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,IAAI,CAE3E;IAED,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,IAAI,CAEvE;IAED,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAUvE;IAED,iFAAiF;IACjF,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAerB;IAED;;;;;OAKG;IACH,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,CAe9B;IAED,OAAO,CAAC,aAAa;IAIrB;;;;;;OAMG;IACH,WAAW,IAAI,kBAAkB,GAAG,IAAI,CAOvC;IAED,2FAA2F;IAC3F,KAAK,IAAI,IAAI,CAWZ;IAED,wDAAwD;IACxD,OAAO,CAAC,YAAY;IAQpB,OAAO,CAAC,QAAQ;IAwFhB;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAY3B;;;OAGG;IACH,OAAO,CAAC,eAAe;IAcvB;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;IAwCxB,OAAO,CAAC,qBAAqB;IAgB7B,OAAO,CAAC,KAAK;IAoBb,OAAO,CAAC,cAAc;IAyBtB,OAAO,CAAC,cAAc;IAWtB,OAAO,CAAC,eAAe;YAYT,QAAQ;IAsDtB,OAAO,CAAC,aAAa;IASrB;;;OAGG;IACH,OAAO,CAAC,aAAa;IA6DrB,oFAAoF;IACpF,OAAO,CAAC,gBAAgB;CAoCzB;AAoDD,OAAO,EAAE,uBAAuB,EAAE,8BAA8B,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAA;AACnH,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAC/C,YAAY,EAAE,WAAW,EAAE,oBAAoB,EAAE,4BAA4B,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAA"}
|
package/dist/metrics/index.js
CHANGED
|
@@ -53,6 +53,7 @@ class PostHogMetrics {
|
|
|
53
53
|
this._logger.error('Metrics flush failed:', e);
|
|
54
54
|
}));
|
|
55
55
|
this._flushPromise = null;
|
|
56
|
+
this._queuedFlush = null;
|
|
56
57
|
this._seriesCapWarned = false;
|
|
57
58
|
this._typeByName = new Map();
|
|
58
59
|
this._typeCollisionWarned = new Set();
|
|
@@ -104,6 +105,17 @@ class PostHogMetrics {
|
|
|
104
105
|
this._flushPromise = p;
|
|
105
106
|
return p;
|
|
106
107
|
}
|
|
108
|
+
flushCoalesced() {
|
|
109
|
+
if (this._isBackingOff()) return this._flushPromise ?? Promise.resolve();
|
|
110
|
+
if (!this._queuedFlush) this._queuedFlush = (this._flushPromise ?? Promise.resolve()).catch(()=>{}).then(()=>{
|
|
111
|
+
this._queuedFlush = null;
|
|
112
|
+
return this._isBackingOff() ? void 0 : this.flush();
|
|
113
|
+
});
|
|
114
|
+
return this._queuedFlush;
|
|
115
|
+
}
|
|
116
|
+
_isBackingOff() {
|
|
117
|
+
return this._consecutiveFlushFailures > 0 || this._retryAfter.remainingMs() > 0;
|
|
118
|
+
}
|
|
107
119
|
drainWindow() {
|
|
108
120
|
if (0 === this._series.size) return null;
|
|
109
121
|
const window = this._series;
|
|
@@ -117,6 +129,7 @@ class PostHogMetrics {
|
|
|
117
129
|
this._flushJitter = backoff_js_namespaceObject.NO_JITTER;
|
|
118
130
|
this._flushTimer.clear();
|
|
119
131
|
this._flushPromise = null;
|
|
132
|
+
this._queuedFlush = null;
|
|
120
133
|
this._startWindow();
|
|
121
134
|
this._boundsByHistogram = new Map();
|
|
122
135
|
this._boundsCapWarned = false;
|
package/dist/metrics/index.mjs
CHANGED
|
@@ -16,6 +16,7 @@ class PostHogMetrics {
|
|
|
16
16
|
this._logger.error('Metrics flush failed:', e);
|
|
17
17
|
}));
|
|
18
18
|
this._flushPromise = null;
|
|
19
|
+
this._queuedFlush = null;
|
|
19
20
|
this._seriesCapWarned = false;
|
|
20
21
|
this._typeByName = new Map();
|
|
21
22
|
this._typeCollisionWarned = new Set();
|
|
@@ -67,6 +68,17 @@ class PostHogMetrics {
|
|
|
67
68
|
this._flushPromise = p;
|
|
68
69
|
return p;
|
|
69
70
|
}
|
|
71
|
+
flushCoalesced() {
|
|
72
|
+
if (this._isBackingOff()) return this._flushPromise ?? Promise.resolve();
|
|
73
|
+
if (!this._queuedFlush) this._queuedFlush = (this._flushPromise ?? Promise.resolve()).catch(()=>{}).then(()=>{
|
|
74
|
+
this._queuedFlush = null;
|
|
75
|
+
return this._isBackingOff() ? void 0 : this.flush();
|
|
76
|
+
});
|
|
77
|
+
return this._queuedFlush;
|
|
78
|
+
}
|
|
79
|
+
_isBackingOff() {
|
|
80
|
+
return this._consecutiveFlushFailures > 0 || this._retryAfter.remainingMs() > 0;
|
|
81
|
+
}
|
|
70
82
|
drainWindow() {
|
|
71
83
|
if (0 === this._series.size) return null;
|
|
72
84
|
const window = this._series;
|
|
@@ -80,6 +92,7 @@ class PostHogMetrics {
|
|
|
80
92
|
this._flushJitter = NO_JITTER;
|
|
81
93
|
this._flushTimer.clear();
|
|
82
94
|
this._flushPromise = null;
|
|
95
|
+
this._queuedFlush = null;
|
|
83
96
|
this._startWindow();
|
|
84
97
|
this._boundsByHistogram = new Map();
|
|
85
98
|
this._boundsCapWarned = false;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@posthog/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.67.0",
|
|
4
4
|
"bugs": {
|
|
5
5
|
"url": "https://github.com/PostHog/posthog-js/issues"
|
|
6
6
|
},
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
}
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
|
-
"@posthog/types": "^1.
|
|
75
|
+
"@posthog/types": "^1.423.0"
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
78
78
|
"@rslib/core": "0.23.2",
|
package/src/logs/index.spec.ts
CHANGED
|
@@ -2300,3 +2300,122 @@ describe('PostHogLogs', () => {
|
|
|
2300
2300
|
})
|
|
2301
2301
|
})
|
|
2302
2302
|
})
|
|
2303
|
+
|
|
2304
|
+
describe('PostHogLogs consent and shared background flush', () => {
|
|
2305
|
+
const create = (instance: any, logger: Logger = createMockLogger(), config = resolveForTest()): PostHogLogs =>
|
|
2306
|
+
new PostHogLogs(
|
|
2307
|
+
instance,
|
|
2308
|
+
config,
|
|
2309
|
+
logger,
|
|
2310
|
+
getContextFor(instance),
|
|
2311
|
+
immediateOnReady,
|
|
2312
|
+
undefined,
|
|
2313
|
+
undefined,
|
|
2314
|
+
() => instance.consentWithdrawn === true
|
|
2315
|
+
)
|
|
2316
|
+
|
|
2317
|
+
it('discards queued records instead of exporting them after opt-out', async () => {
|
|
2318
|
+
const instance = createMockInstance()
|
|
2319
|
+
const logs = create(instance)
|
|
2320
|
+
logs.captureLog({ body: 'before opt-out' })
|
|
2321
|
+
|
|
2322
|
+
instance.consentWithdrawn = true
|
|
2323
|
+
await logs.flush()
|
|
2324
|
+
|
|
2325
|
+
expect(instance._sendLogsBatch).not.toHaveBeenCalled()
|
|
2326
|
+
expect(readQueue(instance)).toHaveLength(0)
|
|
2327
|
+
|
|
2328
|
+
// Opting back in does not resurrect what was captured before the withdrawal.
|
|
2329
|
+
instance.consentWithdrawn = false
|
|
2330
|
+
await logs.flush()
|
|
2331
|
+
expect(instance._sendLogsBatch).not.toHaveBeenCalled()
|
|
2332
|
+
})
|
|
2333
|
+
|
|
2334
|
+
it('stops a drain under way when the user opts out between batches', async () => {
|
|
2335
|
+
let releaseFirst: () => void = () => {}
|
|
2336
|
+
const instance = createMockInstance({
|
|
2337
|
+
_sendLogsBatch: vi.fn(
|
|
2338
|
+
() =>
|
|
2339
|
+
new Promise((resolve) => {
|
|
2340
|
+
releaseFirst = () => resolve({ kind: 'ok' })
|
|
2341
|
+
})
|
|
2342
|
+
),
|
|
2343
|
+
})
|
|
2344
|
+
const logs = create(instance, createMockLogger(), resolveForTest({ maxBatchRecordsPerPost: 1 }))
|
|
2345
|
+
logs.captureLog({ body: 'first' })
|
|
2346
|
+
logs.captureLog({ body: 'second' })
|
|
2347
|
+
|
|
2348
|
+
const flushing = logs.flush()
|
|
2349
|
+
await Promise.resolve()
|
|
2350
|
+
instance.consentWithdrawn = true
|
|
2351
|
+
releaseFirst()
|
|
2352
|
+
await flushing
|
|
2353
|
+
|
|
2354
|
+
expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
|
|
2355
|
+
expect(readQueue(instance)).toHaveLength(0)
|
|
2356
|
+
})
|
|
2357
|
+
|
|
2358
|
+
it('does not retry a 413-rejected batch after the user opts out', async () => {
|
|
2359
|
+
let rejectFirst: () => void = () => {}
|
|
2360
|
+
const instance = createMockInstance({
|
|
2361
|
+
_sendLogsBatch: vi.fn(
|
|
2362
|
+
() =>
|
|
2363
|
+
new Promise((resolve) => {
|
|
2364
|
+
rejectFirst = () => resolve({ kind: 'too-large' })
|
|
2365
|
+
})
|
|
2366
|
+
),
|
|
2367
|
+
})
|
|
2368
|
+
const logs = create(instance, createMockLogger(), resolveForTest({ maxBatchRecordsPerPost: 4 }))
|
|
2369
|
+
logs.captureLog({ body: 'a' })
|
|
2370
|
+
logs.captureLog({ body: 'b' })
|
|
2371
|
+
|
|
2372
|
+
const flushing = logs.flush()
|
|
2373
|
+
await Promise.resolve()
|
|
2374
|
+
instance.consentWithdrawn = true
|
|
2375
|
+
rejectFirst()
|
|
2376
|
+
await flushing
|
|
2377
|
+
|
|
2378
|
+
expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
|
|
2379
|
+
expect(readQueue(instance)).toHaveLength(0)
|
|
2380
|
+
})
|
|
2381
|
+
|
|
2382
|
+
it('shares one background wrapper across overlapping callers', async () => {
|
|
2383
|
+
let failSend: () => void = () => {}
|
|
2384
|
+
const instance = createMockInstance({
|
|
2385
|
+
_sendLogsBatch: vi.fn(
|
|
2386
|
+
() =>
|
|
2387
|
+
new Promise((resolve) => {
|
|
2388
|
+
failSend = () => resolve({ kind: 'retry-later', error: new Error('down') })
|
|
2389
|
+
})
|
|
2390
|
+
),
|
|
2391
|
+
})
|
|
2392
|
+
const logger = createMockLogger()
|
|
2393
|
+
const logs = create(instance, logger)
|
|
2394
|
+
logs.captureLog({ body: 'slow' })
|
|
2395
|
+
|
|
2396
|
+
const first = logs.flushInBackground()
|
|
2397
|
+
const second = logs.flushInBackground()
|
|
2398
|
+
expect(second).toBe(first)
|
|
2399
|
+
await Promise.resolve()
|
|
2400
|
+
failSend()
|
|
2401
|
+
await Promise.all([first, second])
|
|
2402
|
+
|
|
2403
|
+
expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
|
|
2404
|
+
expect(logger.error).toHaveBeenCalledTimes(1)
|
|
2405
|
+
})
|
|
2406
|
+
|
|
2407
|
+
it('keeps flushing a host whose optedOut is only a shutdown gate when no consent callback is given', async () => {
|
|
2408
|
+
const instance = createMockInstance({ optedOut: false })
|
|
2409
|
+
const logs = new PostHogLogs(
|
|
2410
|
+
instance,
|
|
2411
|
+
resolveForTest(),
|
|
2412
|
+
createMockLogger(),
|
|
2413
|
+
getContextFor(instance),
|
|
2414
|
+
immediateOnReady
|
|
2415
|
+
)
|
|
2416
|
+
logs.captureLog({ body: 'final flush' })
|
|
2417
|
+
instance.optedOut = true
|
|
2418
|
+
await logs.flush()
|
|
2419
|
+
expect(instance._sendLogsBatch).toHaveBeenCalledTimes(1)
|
|
2420
|
+
})
|
|
2421
|
+
})
|
package/src/logs/index.ts
CHANGED
|
@@ -29,6 +29,9 @@ export class PostHogLogs {
|
|
|
29
29
|
// A batch captures this when it is assembled, so it can tell that the records it is
|
|
30
30
|
// holding no longer correspond to anything queued.
|
|
31
31
|
private _queueGeneration = 0
|
|
32
|
+
// The `flushInBackground()` wrapper for the flush in flight, shared so overlapping
|
|
33
|
+
// callers count and log one failed POST once rather than once per caller.
|
|
34
|
+
private _backgroundFlushPromise: Promise<void> | null = null
|
|
32
35
|
// Every path that can start a send checks this, not just the retry timer.
|
|
33
36
|
private _retryAfter = new RetryAfterWindow()
|
|
34
37
|
// Consecutive failed flushes; drives exponential backoff on the retry timer.
|
|
@@ -61,7 +64,12 @@ export class PostHogLogs {
|
|
|
61
64
|
// OTLP instrumentation scope name. Overrides the `getLibraryId()` fallback
|
|
62
65
|
// so a host can label a specific capture stream (e.g. 'console' for browser
|
|
63
66
|
// console auto-capture). Defaults to `getLibraryId()` when omitted.
|
|
64
|
-
private readonly _scopeName?: string
|
|
67
|
+
private readonly _scopeName?: string,
|
|
68
|
+
// True once the user has withdrawn consent. Checked before every flush iteration so
|
|
69
|
+
// queued records are dropped rather than exported, by a timer or a drain under way.
|
|
70
|
+
// Opt-in: a browser host's `optedOut` also reads true while it shuts down, when the
|
|
71
|
+
// final flush must still go out, so only a host that separates the two passes this.
|
|
72
|
+
private readonly _isConsentWithdrawn: () => boolean = () => false
|
|
65
73
|
) {
|
|
66
74
|
this._maxBufferSize = _config.maxBufferSize
|
|
67
75
|
// Never below the flush trigger: a smaller eviction cap would stop the
|
|
@@ -83,6 +91,11 @@ export class PostHogLogs {
|
|
|
83
91
|
this._instance.setPersistedProperty(PostHogPersistedProperty.LogsQueue, [])
|
|
84
92
|
}
|
|
85
93
|
|
|
94
|
+
/** True while the endpoint's `Retry-After` window is open, so a host's automatic flush can skip logs. */
|
|
95
|
+
get throttled(): boolean {
|
|
96
|
+
return this._retryAfter.isOpen()
|
|
97
|
+
}
|
|
98
|
+
|
|
86
99
|
/**
|
|
87
100
|
* Clears the flush timer and rate-cap state. The host owns the record queue
|
|
88
101
|
* and clears it separately (the browser empties its in-memory store).
|
|
@@ -269,6 +282,9 @@ export class PostHogLogs {
|
|
|
269
282
|
private async _flushInner(): Promise<void> {
|
|
270
283
|
this._flushTimer.clear()
|
|
271
284
|
|
|
285
|
+
if (this._discardQueueIfConsentWithdrawn()) {
|
|
286
|
+
return
|
|
287
|
+
}
|
|
272
288
|
let queue = this._instance.getPersistedProperty<BufferedLogEntry[]>(PostHogPersistedProperty.LogsQueue) ?? []
|
|
273
289
|
if (queue.length === 0) {
|
|
274
290
|
return
|
|
@@ -278,6 +294,11 @@ export class PostHogLogs {
|
|
|
278
294
|
let sentCount = 0
|
|
279
295
|
|
|
280
296
|
while (queue.length > 0 && sentCount < originalQueueLength) {
|
|
297
|
+
// Re-checked on every iteration, including a 413 shrink-and-retry that sends no
|
|
298
|
+
// progress: a send suspends, so the user can opt out while one is in flight.
|
|
299
|
+
if (this._discardQueueIfConsentWithdrawn()) {
|
|
300
|
+
return
|
|
301
|
+
}
|
|
281
302
|
// Captured per batch, not per flush: a clear that lands between batches leaves
|
|
282
303
|
// the next one assembled from an already-fresh queue, so that batch advances
|
|
283
304
|
// normally instead of being retired for a purge it never held.
|
|
@@ -360,6 +381,21 @@ export class PostHogLogs {
|
|
|
360
381
|
}
|
|
361
382
|
}
|
|
362
383
|
|
|
384
|
+
/**
|
|
385
|
+
* Drops the queue once consent is withdrawn. Records carry the distinct id and
|
|
386
|
+
* session id, so whatever is still queued when the user opts out must not be
|
|
387
|
+
* exported, by a pending timer or by a drain already under way.
|
|
388
|
+
*/
|
|
389
|
+
private _discardQueueIfConsentWithdrawn(): boolean {
|
|
390
|
+
if (!this._isConsentWithdrawn()) {
|
|
391
|
+
return false
|
|
392
|
+
}
|
|
393
|
+
if (this._hasQueuedRecords()) {
|
|
394
|
+
this.clearQueue()
|
|
395
|
+
}
|
|
396
|
+
return true
|
|
397
|
+
}
|
|
398
|
+
|
|
363
399
|
private async _persistQueueAdvance(consumed: number): Promise<void> {
|
|
364
400
|
// Re-read in case captures landed mid-flush. Subtract head records the FIFO cap
|
|
365
401
|
// evicted during the send (already-sent records that left the queue), so we drop
|
|
@@ -481,8 +517,17 @@ export class PostHogLogs {
|
|
|
481
517
|
})
|
|
482
518
|
}
|
|
483
519
|
|
|
484
|
-
|
|
485
|
-
|
|
520
|
+
/**
|
|
521
|
+
* `flush()` for a host that drives logs from its own flush cycle. Never rejects, and when
|
|
522
|
+
* records remain (a failed send, or captures that landed mid-flush) re-arms the timer with
|
|
523
|
+
* backoff, as the pipeline's own timer flush does. A bare `flush()` clears the timer and
|
|
524
|
+
* leaves nothing to retry the records once traffic stops.
|
|
525
|
+
*/
|
|
526
|
+
flushInBackground(): Promise<void> {
|
|
527
|
+
if (this._backgroundFlushPromise) {
|
|
528
|
+
return this._backgroundFlushPromise
|
|
529
|
+
}
|
|
530
|
+
const promise = this.flush()
|
|
486
531
|
.then(
|
|
487
532
|
() => {
|
|
488
533
|
this._consecutiveFlushFailures = 0
|
|
@@ -498,9 +543,18 @@ export class PostHogLogs {
|
|
|
498
543
|
// Records remaining (transient failure or mid-flush captures) would otherwise
|
|
499
544
|
// sit undelivered on a quiet page; re-arm so the timer retries them, backing
|
|
500
545
|
// off on consecutive failures.
|
|
546
|
+
if (this._backgroundFlushPromise === promise) {
|
|
547
|
+
this._backgroundFlushPromise = null
|
|
548
|
+
}
|
|
501
549
|
if (!this._instance.isDisabled && this._hasQueuedRecords()) {
|
|
502
550
|
this._flushTimer.armNoEarlierThan(this._nextFlushDelay())
|
|
503
551
|
}
|
|
504
552
|
})
|
|
553
|
+
this._backgroundFlushPromise = promise
|
|
554
|
+
return promise
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
private _flushInBackground(): void {
|
|
558
|
+
void this.flushInBackground()
|
|
505
559
|
}
|
|
506
560
|
}
|
|
@@ -59,6 +59,76 @@ describe('PostHogMetrics', () => {
|
|
|
59
59
|
vi.useRealTimers()
|
|
60
60
|
})
|
|
61
61
|
|
|
62
|
+
describe('flushCoalesced', () => {
|
|
63
|
+
it('keeps at most one send in flight and one queued behind it, and sends every sample', async () => {
|
|
64
|
+
let resolveSend!: (o: SendMetricsBatchOutcome) => void
|
|
65
|
+
mockInstance._sendMetricsBatch
|
|
66
|
+
.mockImplementationOnce(() => new Promise<SendMetricsBatchOutcome>((r) => (resolveSend = r)))
|
|
67
|
+
.mockResolvedValue({ kind: 'ok' })
|
|
68
|
+
const metrics = createMetrics()
|
|
69
|
+
|
|
70
|
+
metrics.count('requests', 1)
|
|
71
|
+
const first = metrics.flushCoalesced()
|
|
72
|
+
await Promise.resolve()
|
|
73
|
+
await Promise.resolve()
|
|
74
|
+
expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
|
|
75
|
+
|
|
76
|
+
// Many requests finish while the first send is in flight: they share one queued flush.
|
|
77
|
+
const queued = [1, 2, 3, 4, 5].map(() => {
|
|
78
|
+
metrics.count('requests', 1)
|
|
79
|
+
return metrics.flushCoalesced()
|
|
80
|
+
})
|
|
81
|
+
expect(new Set(queued).size).toBe(1)
|
|
82
|
+
|
|
83
|
+
resolveSend({ kind: 'ok' })
|
|
84
|
+
await Promise.all([first, ...queued])
|
|
85
|
+
expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(2)
|
|
86
|
+
expect(sentMetrics().reduce((sum, m) => sum + m.sum!.dataPoints[0].asDouble!, 0)).toBe(6)
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it('does not start a queued flush when the send it waited behind starts a backoff', async () => {
|
|
90
|
+
let resolveSend!: (o: SendMetricsBatchOutcome) => void
|
|
91
|
+
mockInstance._sendMetricsBatch
|
|
92
|
+
.mockImplementationOnce(() => new Promise<SendMetricsBatchOutcome>((r) => (resolveSend = r)))
|
|
93
|
+
.mockResolvedValue({ kind: 'ok' })
|
|
94
|
+
const metrics = createMetrics()
|
|
95
|
+
|
|
96
|
+
metrics.count('requests', 1)
|
|
97
|
+
const first = metrics.flushCoalesced()
|
|
98
|
+
await Promise.resolve()
|
|
99
|
+
await Promise.resolve()
|
|
100
|
+
metrics.count('requests', 1)
|
|
101
|
+
const queued = metrics.flushCoalesced()
|
|
102
|
+
|
|
103
|
+
resolveSend({ kind: 'retry-later', error: new Error('429'), retryAfterMs: 300_000 })
|
|
104
|
+
await Promise.all([first, queued])
|
|
105
|
+
expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
|
|
106
|
+
|
|
107
|
+
// The retry timer delivers the retained samples once the backoff ends.
|
|
108
|
+
await vi.advanceTimersByTimeAsync(300_000)
|
|
109
|
+
expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(2)
|
|
110
|
+
const retried = sentPayloads()[1].resourceMetrics[0].scopeMetrics[0].metrics
|
|
111
|
+
expect(retried[0].sum!.dataPoints[0].asDouble).toBe(2)
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
it('does not send while a failed send is backing off', async () => {
|
|
115
|
+
mockInstance._sendMetricsBatch.mockResolvedValueOnce({
|
|
116
|
+
kind: 'retry-later',
|
|
117
|
+
error: new Error('429'),
|
|
118
|
+
retryAfterMs: 300_000,
|
|
119
|
+
})
|
|
120
|
+
const metrics = createMetrics()
|
|
121
|
+
metrics.count('requests', 1)
|
|
122
|
+
await metrics.flushCoalesced()
|
|
123
|
+
expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
|
|
124
|
+
|
|
125
|
+
metrics.count('requests', 1)
|
|
126
|
+
await metrics.flushCoalesced()
|
|
127
|
+
await metrics.flushCoalesced()
|
|
128
|
+
expect(mockInstance._sendMetricsBatch).toHaveBeenCalledTimes(1)
|
|
129
|
+
})
|
|
130
|
+
})
|
|
131
|
+
|
|
62
132
|
describe('aggregation semantics', () => {
|
|
63
133
|
it('sums count samples for the same series into one delta data point', async () => {
|
|
64
134
|
const metrics = createMetrics()
|
package/src/metrics/index.ts
CHANGED
|
@@ -90,6 +90,8 @@ export class PostHogMetrics {
|
|
|
90
90
|
// Serializes flushes — a manual flush() during an in-flight timer flush
|
|
91
91
|
// queues behind it instead of racing it for the same window.
|
|
92
92
|
private _flushPromise: Promise<void> | null = null
|
|
93
|
+
// The one flush `flushCoalesced()` has queued but not yet started.
|
|
94
|
+
private _queuedFlush: Promise<void> | null = null
|
|
93
95
|
// One cardinality warning per window, however many series get dropped.
|
|
94
96
|
private _seriesCapWarned = false
|
|
95
97
|
// Type seen per metric name this window; reusing a name with a different
|
|
@@ -157,6 +159,33 @@ export class PostHogMetrics {
|
|
|
157
159
|
return p
|
|
158
160
|
}
|
|
159
161
|
|
|
162
|
+
/**
|
|
163
|
+
* A flush for callers that ask once per unit of work (a served request, say) rather than once per window.
|
|
164
|
+
* Callers share one queued flush, so at most one send is in flight and one waits behind it however often
|
|
165
|
+
* this is called, and every sample captured before the call is in one of them. While a failed send is
|
|
166
|
+
* backing off it starts nothing and the retry timer owns the next send.
|
|
167
|
+
*/
|
|
168
|
+
flushCoalesced(): Promise<void> {
|
|
169
|
+
if (this._isBackingOff()) {
|
|
170
|
+
return this._flushPromise ?? Promise.resolve()
|
|
171
|
+
}
|
|
172
|
+
if (!this._queuedFlush) {
|
|
173
|
+
// Starts after any send in flight, so samples captured while it runs are in this one.
|
|
174
|
+
this._queuedFlush = (this._flushPromise ?? Promise.resolve())
|
|
175
|
+
.catch(() => {})
|
|
176
|
+
.then(() => {
|
|
177
|
+
this._queuedFlush = null
|
|
178
|
+
// The send it waited behind may have failed and started a backoff.
|
|
179
|
+
return this._isBackingOff() ? undefined : this.flush()
|
|
180
|
+
})
|
|
181
|
+
}
|
|
182
|
+
return this._queuedFlush
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
private _isBackingOff(): boolean {
|
|
186
|
+
return this._consecutiveFlushFailures > 0 || this._retryAfter.remainingMs() > 0
|
|
187
|
+
}
|
|
188
|
+
|
|
160
189
|
/**
|
|
161
190
|
* Synchronously snapshots the current window into an OTLP payload and
|
|
162
191
|
* resets it, bypassing the flush serializer entirely — for unload-time
|
|
@@ -181,6 +210,7 @@ export class PostHogMetrics {
|
|
|
181
210
|
this._flushJitter = NO_JITTER
|
|
182
211
|
this._flushTimer.clear()
|
|
183
212
|
this._flushPromise = null
|
|
213
|
+
this._queuedFlush = null
|
|
184
214
|
this._startWindow()
|
|
185
215
|
this._boundsByHistogram = new Map()
|
|
186
216
|
this._boundsCapWarned = false
|