@posthog/core 1.65.0 → 1.66.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/package.json +2 -2
- package/src/logs/index.spec.ts +119 -0
- package/src/logs/index.ts +57 -3
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":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;OAWG;IACG,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAOvD;IAED;;;;;OAKG;IACH,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,CA6BjC;IAED,OAAO,CAAC,kBAAkB;CAG3B"}
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@posthog/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.66.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
|
}
|