fix(telemetry): send both telemetry ports through one collector transport (Q-6.9-4)
The application port (best-effort-telemetry) and the feature port (feature-telemetry pipeline) each posted to TELEMETRY_ENDPOINT on their own: 20+20 sends per minute, cookies on the application side, no pagehide flush or dispose abort on the feature side, and no deadline on any fetch, so a hung collector held activeFlush forever (6.3-10). New src/adapters/telemetry/telemetry-collector.ts is the one transport: shared send-rate window (createTelemetrySendRate, now in the platform pipeline and injectable via `sendRate`), credentials "omit", cache "no-store", a per-request deadline through the kernel createAbortableOperation, and one pagehide fan-out. runtime-adapters builds one collector and passes it to both ports. Body projections are unchanged and pinned by characterization tests first. Verified: new tests in tests/unit/telemetry.test.ts (5 RED before wiring: credentials/cache, hung collector timeout, shared rate, feature pagehide flush, feature dispose abort); all gates pass except the known tests/unit/removal-fixture.test.ts (artifacts/ absent); check:adapter-inventory 137/137; FE-RB-004 drill PASS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b35304dd48
commit
a328776bf2
@@ -6,6 +6,10 @@ import type {
|
||||
} from "../../contracts/telemetry.ts";
|
||||
import type { TelemetryPort } from "../../application/ports/telemetry-port.ts";
|
||||
import { assertBoundedCapacity } from "../platform/bounded-capacity.ts";
|
||||
import {
|
||||
createTelemetryCollector,
|
||||
type TelemetryCollector,
|
||||
} from "./telemetry-collector.ts";
|
||||
|
||||
export type TelemetryAdapter = TelemetryPort &
|
||||
Readonly<{
|
||||
@@ -36,10 +40,14 @@ export type TelemetryAdapterOptions = Readonly<{
|
||||
monotonicNow?: () => number;
|
||||
setTimer?: (callback: () => void, ms: number) => unknown;
|
||||
clearTimer?: (handle: unknown) => void;
|
||||
/**
|
||||
* Q-6.9-4. The collector transport shared with feature telemetry. When set,
|
||||
* it owns `fetcher`, `lifecycle`, `maxSendsPerMinute` and `monotonicNow`.
|
||||
*/
|
||||
collector?: TelemetryCollector;
|
||||
}>;
|
||||
|
||||
export const DEFAULT_TELEMETRY_SENDS_PER_MINUTE = 20;
|
||||
const SEND_WINDOW_MS = 60_000;
|
||||
export { DEFAULT_TELEMETRY_SENDS_PER_MINUTE } from "./telemetry-collector.ts";
|
||||
|
||||
export const noOpTelemetry: TelemetryAdapter = Object.freeze({
|
||||
emit: () => {},
|
||||
@@ -67,27 +75,28 @@ export function createTelemetryAdapter(
|
||||
return noOpTelemetry;
|
||||
}
|
||||
|
||||
const endpoint = options.endpoint;
|
||||
const fetcher = options.fetcher ?? fetch;
|
||||
const maxQueue = assertBoundedCapacity(
|
||||
options.maxQueue ?? 100,
|
||||
MAX_TELEMETRY_QUEUE,
|
||||
"telemetry maxQueue",
|
||||
);
|
||||
const schedule = options.schedule ?? queueMicrotask;
|
||||
const maxSendsPerMinute = assertBoundedCapacity(
|
||||
options.maxSendsPerMinute ?? DEFAULT_TELEMETRY_SENDS_PER_MINUTE,
|
||||
MAX_TELEMETRY_QUEUE,
|
||||
"telemetry maxSendsPerMinute",
|
||||
);
|
||||
const monotonicNow = options.monotonicNow ?? (() => performance.now());
|
||||
const collector =
|
||||
options.collector ??
|
||||
createTelemetryCollector({
|
||||
endpoint: options.endpoint,
|
||||
...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }),
|
||||
...(options.maxSendsPerMinute === undefined
|
||||
? {}
|
||||
: { maxSendsPerMinute: options.maxSendsPerMinute }),
|
||||
...(options.monotonicNow === undefined ? {} : { now: options.monotonicNow }),
|
||||
...(options.lifecycle === undefined ? {} : { lifecycle: options.lifecycle }),
|
||||
});
|
||||
const setTimer =
|
||||
options.setTimer ?? ((callback: () => void, ms: number) => setTimeout(callback, ms));
|
||||
const clearTimer =
|
||||
options.clearTimer ??
|
||||
((handle: unknown) => clearTimeout(handle as ReturnType<typeof setTimeout>));
|
||||
/** Send instants inside the current window; never longer than the limit. */
|
||||
const sendTimes: number[] = [];
|
||||
let rateTimer: unknown = null;
|
||||
const queue: TelemetryEvent[] = [];
|
||||
let lifecycleState: TelemetryLifecycle = "ACTIVE";
|
||||
@@ -99,12 +108,6 @@ export function createTelemetryAdapter(
|
||||
let dropped = 0;
|
||||
const dropReasons = new Map<string, number>();
|
||||
let lastDeliveryEvidence: TelemetryEvent | null = null;
|
||||
const lifecycle =
|
||||
options.lifecycle ??
|
||||
(typeof globalThis.addEventListener === "function" &&
|
||||
typeof globalThis.removeEventListener === "function"
|
||||
? globalThis
|
||||
: undefined);
|
||||
|
||||
function recordDrop(reason: string, count = 1): void {
|
||||
const safeReason =
|
||||
@@ -173,16 +176,8 @@ export function createTelemetryAdapter(
|
||||
scheduleFlush();
|
||||
}
|
||||
|
||||
function rateAllows(at: number): boolean {
|
||||
while (sendTimes.length > 0 && at - (sendTimes[0] as number) >= SEND_WINDOW_MS) {
|
||||
sendTimes.shift();
|
||||
}
|
||||
return sendTimes.length < maxSendsPerMinute;
|
||||
}
|
||||
|
||||
function armRateTimer(at: number): void {
|
||||
function armRateTimer(reopenIn: number): void {
|
||||
if (rateTimer !== null || lifecycleState === "DISPOSED") return;
|
||||
const reopenIn = Math.max(1, (sendTimes[0] ?? at) + SEND_WINDOW_MS - at);
|
||||
rateTimer = setTimer(() => {
|
||||
rateTimer = null;
|
||||
void flush();
|
||||
@@ -198,31 +193,18 @@ export function createTelemetryAdapter(
|
||||
if (lifecycleState === "DISPOSED" || queue.length === 0) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
const at = monotonicNow();
|
||||
if (!rateAllows(at)) {
|
||||
if (!bypassRate) {
|
||||
armRateTimer(at);
|
||||
return Promise.resolve();
|
||||
}
|
||||
const reopenIn = collector.sendRate.take(bypassRate);
|
||||
if (reopenIn > 0) {
|
||||
armRateTimer(reopenIn);
|
||||
return Promise.resolve();
|
||||
}
|
||||
sendTimes.push(at);
|
||||
if (sendTimes.length > maxSendsPerMinute) sendTimes.shift();
|
||||
const generation = scheduleGeneration;
|
||||
const run = async () => {
|
||||
const batch = queue.splice(0, queue.length);
|
||||
const controller = new AbortController();
|
||||
activeSink = controller;
|
||||
try {
|
||||
const response = await fetcher(endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ events: batch }),
|
||||
keepalive: true,
|
||||
signal: controller.signal,
|
||||
});
|
||||
// A sink that ignored the abort must not update post-dispose state.
|
||||
if (generation !== scheduleGeneration) return;
|
||||
if (!response.ok) recordDrop("sink-failure", batch.length);
|
||||
await collector.post(batch, controller.signal);
|
||||
} catch {
|
||||
if (generation !== scheduleGeneration) return;
|
||||
recordDrop("sink-failure", batch.length);
|
||||
@@ -239,10 +221,9 @@ export function createTelemetryAdapter(
|
||||
}
|
||||
|
||||
// Page exit is the last chance to deliver: it may exceed the window once.
|
||||
const flushBeforePageExit = () => {
|
||||
const stopPageExitFlush = collector.onPageExit(() => {
|
||||
void flush(true);
|
||||
};
|
||||
lifecycle?.addEventListener("pagehide", flushBeforePageExit);
|
||||
});
|
||||
|
||||
/**
|
||||
* N-04. Terminal disposal: one state transition, no further admission, no
|
||||
@@ -253,7 +234,7 @@ export function createTelemetryAdapter(
|
||||
lifecycleState = "DISPOSED";
|
||||
scheduleGeneration += 1;
|
||||
scheduled = false;
|
||||
lifecycle?.removeEventListener("pagehide", flushBeforePageExit);
|
||||
stopPageExitFlush();
|
||||
if (rateTimer !== null) clearTimer(rateTimer);
|
||||
rateTimer = null;
|
||||
queue.length = 0;
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
type TelemetryPipelineBudget,
|
||||
type TelemetryTransport,
|
||||
} from "../../platform/telemetry/telemetry-pipeline.ts";
|
||||
import {
|
||||
createTelemetryCollector,
|
||||
type TelemetryCollector,
|
||||
} from "./telemetry-collector.ts";
|
||||
|
||||
/**
|
||||
* Spec §24–§27. Adapter side of the provider-neutral feature telemetry port.
|
||||
@@ -15,26 +19,31 @@ import {
|
||||
* transport here, never in feature code.
|
||||
*/
|
||||
export function createFetchTelemetryTransport(
|
||||
options: Readonly<{ endpoint: string; fetcher?: typeof fetch }>,
|
||||
options: Readonly<{
|
||||
endpoint: string;
|
||||
fetcher?: typeof fetch;
|
||||
/** Q-6.9-4. Posts through this shared collector instead of a private one. */
|
||||
collector?: TelemetryCollector;
|
||||
/** Aborts in-flight batches (feature telemetry disposal). */
|
||||
signal?: AbortSignal;
|
||||
}>,
|
||||
): TelemetryTransport {
|
||||
const fetcher = options.fetcher ?? fetch;
|
||||
const collector =
|
||||
options.collector ??
|
||||
createTelemetryCollector({
|
||||
endpoint: options.endpoint,
|
||||
...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }),
|
||||
});
|
||||
return Object.freeze({
|
||||
async send(batch: readonly TelemetryBatchItem[]): Promise<void> {
|
||||
const response = await fetcher(options.endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
events: batch.map((item) => ({
|
||||
...item.event,
|
||||
fingerprint: item.fingerprint,
|
||||
occurrences: item.occurrences,
|
||||
})),
|
||||
}),
|
||||
keepalive: true,
|
||||
credentials: "omit",
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!response.ok) throw new Error("telemetry collector rejected batch");
|
||||
send(batch: readonly TelemetryBatchItem[]): Promise<void> {
|
||||
return collector.post(
|
||||
batch.map((item) => ({
|
||||
...item.event,
|
||||
fingerprint: item.fingerprint,
|
||||
occurrences: item.occurrences,
|
||||
})),
|
||||
options.signal,
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -65,14 +74,42 @@ export function createFeatureTelemetry(
|
||||
endpoint?: string;
|
||||
fetcher?: typeof fetch;
|
||||
budget?: TelemetryPipelineBudget;
|
||||
/**
|
||||
* Q-6.9-4. The collector shared with the application telemetry port: one
|
||||
* send-rate window and one page-exit flush for the endpoint. When set, it
|
||||
* owns `fetcher` and the send rate.
|
||||
*/
|
||||
collector?: TelemetryCollector;
|
||||
}>,
|
||||
): TelemetryPipeline {
|
||||
if (!options.enabled || !options.endpoint) return DISABLED_FEATURE_TELEMETRY;
|
||||
return createTelemetryPipeline({
|
||||
transport: createFetchTelemetryTransport({
|
||||
const budget = options.budget ?? DEFAULT_TELEMETRY_PIPELINE_BUDGET;
|
||||
const collector =
|
||||
options.collector ??
|
||||
createTelemetryCollector({
|
||||
endpoint: options.endpoint,
|
||||
...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }),
|
||||
maxSendsPerMinute: budget.maxSendsPerMinute,
|
||||
});
|
||||
const lifetime = new AbortController();
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: createFetchTelemetryTransport({
|
||||
endpoint: options.endpoint,
|
||||
collector,
|
||||
signal: lifetime.signal,
|
||||
}),
|
||||
budget: options.budget ?? DEFAULT_TELEMETRY_PIPELINE_BUDGET,
|
||||
budget,
|
||||
sendRate: collector.sendRate,
|
||||
});
|
||||
const stopPageExitFlush = collector.onPageExit(() => {
|
||||
void pipeline.flush();
|
||||
});
|
||||
return Object.freeze({
|
||||
...pipeline,
|
||||
dispose(): void {
|
||||
stopPageExitFlush();
|
||||
lifetime.abort();
|
||||
pipeline.dispose();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,3 +10,9 @@ export {
|
||||
createFeatureTelemetry,
|
||||
createFetchTelemetryTransport,
|
||||
} from "./feature-telemetry.ts";
|
||||
/** Q-6.9-4. 두 텔레메트리 포트가 공유하는 수집기 전송(rate·타임아웃·pagehide). */
|
||||
export {
|
||||
createTelemetryCollector,
|
||||
type TelemetryCollector,
|
||||
type TelemetryCollectorOptions,
|
||||
} from "./telemetry-collector.ts";
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import {
|
||||
createTelemetrySendRate,
|
||||
type TelemetrySendRate,
|
||||
} from "../../platform/telemetry/telemetry-pipeline.ts";
|
||||
import { createAbortableOperation } from "../platform/abortable-operation.ts";
|
||||
import { assertBoundedCapacity } from "../platform/bounded-capacity.ts";
|
||||
|
||||
/**
|
||||
* Q-6.9-4. The one transport layer behind both telemetry ports.
|
||||
*
|
||||
* The application port (`best-effort-telemetry.ts`) and the feature port
|
||||
* (`feature-telemetry.ts`) keep their own queue and body projection, but every
|
||||
* POST to the collector goes through here: one send-rate window for the
|
||||
* endpoint, no cookies, no HTTP cache, a deadline on every request, and one
|
||||
* `pagehide` listener that flushes every queue.
|
||||
*/
|
||||
export type TelemetryCollector = Readonly<{
|
||||
/** Spec §27. Shared by every queue posting to this collector. */
|
||||
sendRate: TelemetrySendRate;
|
||||
/**
|
||||
* POSTs `{ events }`. Rejects when the collector refuses the batch, the
|
||||
* deadline passes, or `signal` aborts — a hung collector never stalls the
|
||||
* caller's next flush.
|
||||
*/
|
||||
post(events: readonly unknown[], signal?: AbortSignal): Promise<void>;
|
||||
/** Runs `flush` on `pagehide`. Returns the unsubscribe. */
|
||||
onPageExit(flush: () => void): () => void;
|
||||
}>;
|
||||
|
||||
export type TelemetryCollectorOptions = Readonly<{
|
||||
endpoint: string;
|
||||
fetcher?: typeof fetch;
|
||||
/** Sends per rolling minute across every queue (default 20). */
|
||||
maxSendsPerMinute?: number;
|
||||
/** Per-request deadline (default 10s). */
|
||||
timeoutMs?: number;
|
||||
/** Monotonic clock for the send-rate window (default `performance.now`). */
|
||||
now?: () => number;
|
||||
lifecycle?: Pick<EventTarget, "addEventListener" | "removeEventListener">;
|
||||
}>;
|
||||
|
||||
export const DEFAULT_TELEMETRY_SENDS_PER_MINUTE = 20;
|
||||
export const DEFAULT_TELEMETRY_TIMEOUT_MS = 10_000;
|
||||
/** Also bounds the send-time window the rate keeps in memory. */
|
||||
const MAX_SENDS_PER_MINUTE = 10_000;
|
||||
const MAX_TIMEOUT_MS = 60_000;
|
||||
|
||||
export function createTelemetryCollector(
|
||||
options: TelemetryCollectorOptions,
|
||||
): TelemetryCollector {
|
||||
const { endpoint } = options;
|
||||
const fetcher = options.fetcher ?? fetch;
|
||||
const timeoutMs = assertBoundedCapacity(
|
||||
options.timeoutMs ?? DEFAULT_TELEMETRY_TIMEOUT_MS,
|
||||
MAX_TIMEOUT_MS,
|
||||
"telemetry timeoutMs",
|
||||
);
|
||||
const sendRate = createTelemetrySendRate(
|
||||
assertBoundedCapacity(
|
||||
options.maxSendsPerMinute ?? DEFAULT_TELEMETRY_SENDS_PER_MINUTE,
|
||||
MAX_SENDS_PER_MINUTE,
|
||||
"telemetry maxSendsPerMinute",
|
||||
),
|
||||
options.now,
|
||||
);
|
||||
const lifecycle =
|
||||
options.lifecycle ??
|
||||
(typeof globalThis.addEventListener === "function" &&
|
||||
typeof globalThis.removeEventListener === "function"
|
||||
? globalThis
|
||||
: undefined);
|
||||
const exitFlushes = new Set<() => void>();
|
||||
const onPageHide = () => {
|
||||
for (const flush of [...exitFlushes]) flush();
|
||||
};
|
||||
|
||||
async function post(
|
||||
events: readonly unknown[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const operation = createAbortableOperation({
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
timeoutMs,
|
||||
});
|
||||
try {
|
||||
const outcome = await operation.race(
|
||||
Promise.resolve(
|
||||
fetcher(endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ events }),
|
||||
keepalive: true,
|
||||
credentials: "omit",
|
||||
cache: "no-store",
|
||||
signal: operation.signal,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (outcome.kind !== "VALUE" || !outcome.value.ok) {
|
||||
throw new Error("telemetry collector did not accept the batch");
|
||||
}
|
||||
} finally {
|
||||
operation.close();
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
sendRate,
|
||||
post,
|
||||
onPageExit(flush: () => void): () => void {
|
||||
// The listener exists only while some queue wants a page-exit flush.
|
||||
if (exitFlushes.size === 0) {
|
||||
lifecycle?.addEventListener("pagehide", onPageHide);
|
||||
}
|
||||
exitFlushes.add(flush);
|
||||
return () => {
|
||||
if (exitFlushes.delete(flush) && exitFlushes.size === 0) {
|
||||
lifecycle?.removeEventListener("pagehide", onPageHide);
|
||||
}
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import { createBrowserMutationIntentFactory } from "../adapters/platform/index.t
|
||||
import {
|
||||
createFeatureTelemetry,
|
||||
createTelemetryAdapter,
|
||||
createTelemetryCollector,
|
||||
} from "../adapters/telemetry/index.ts";
|
||||
import type { AuthSessionPort } from "../application/ports/auth-session-port.ts";
|
||||
import type { ReleaseInfo } from "../application/ports/release-info-port.ts";
|
||||
@@ -307,10 +308,20 @@ export async function createRuntimeAdapters(
|
||||
? createExternalAuthSessionAdapter(externalOwner)
|
||||
: createUnavailableSessionAdapter();
|
||||
const diagnostics = createDiagnosticsAdapter();
|
||||
// Q-6.9-4. Both telemetry ports post through one collector transport: one
|
||||
// send-rate window, one page-exit flush and one fetch policy per endpoint.
|
||||
const telemetryCollector =
|
||||
config.TELEMETRY_ENABLED && config.TELEMETRY_ENDPOINT
|
||||
? createTelemetryCollector({
|
||||
endpoint: config.TELEMETRY_ENDPOINT,
|
||||
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
|
||||
})
|
||||
: undefined;
|
||||
const telemetry = createTelemetryAdapter({
|
||||
enabled: config.TELEMETRY_ENABLED,
|
||||
endpoint: config.TELEMETRY_ENDPOINT,
|
||||
fetcher: context.fetcher,
|
||||
...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }),
|
||||
onDrop(event) {
|
||||
const attributes =
|
||||
event.attributes && typeof event.attributes === "object"
|
||||
@@ -543,6 +554,7 @@ export async function createRuntimeAdapters(
|
||||
? {}
|
||||
: { endpoint: config.TELEMETRY_ENDPOINT }),
|
||||
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
|
||||
...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }),
|
||||
});
|
||||
// Each installed contribution receives only the capabilities it declares.
|
||||
const featureCapabilities = Object.freeze({
|
||||
|
||||
@@ -93,12 +93,53 @@ function assertPositive(name: string, value: number): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Spec §27. A rolling one-minute send budget. Several queues that post to the
|
||||
* same collector share one instance, so the limit belongs to the collector
|
||||
* rather than to each queue (Q-6.9-4).
|
||||
*/
|
||||
export interface TelemetrySendRate {
|
||||
/**
|
||||
* Takes a send slot and returns 0, or returns the milliseconds until a slot
|
||||
* reopens. `force` always takes one: page exit may exceed the window once.
|
||||
*/
|
||||
take(force?: boolean): number;
|
||||
}
|
||||
|
||||
export function createTelemetrySendRate(
|
||||
maxSendsPerMinute: number,
|
||||
now: () => number = () => performance.now(),
|
||||
): TelemetrySendRate {
|
||||
assertPositive("maxSendsPerMinute", maxSendsPerMinute);
|
||||
/** Send instants inside the current window; never longer than the limit. */
|
||||
const sendTimes: number[] = [];
|
||||
return Object.freeze({
|
||||
take(force = false): number {
|
||||
const at = now();
|
||||
while (sendTimes.length > 0 && at - (sendTimes[0] as number) >= RATE_WINDOW_MS) {
|
||||
sendTimes.shift();
|
||||
}
|
||||
if (!force && sendTimes.length >= maxSendsPerMinute) {
|
||||
return Math.max(1, (sendTimes[0] as number) + RATE_WINDOW_MS - at);
|
||||
}
|
||||
sendTimes.push(at);
|
||||
if (sendTimes.length > maxSendsPerMinute) sendTimes.shift();
|
||||
return 0;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function createTelemetryPipeline(
|
||||
options: Readonly<{
|
||||
transport: TelemetryTransport;
|
||||
budget?: TelemetryPipelineBudget;
|
||||
/** Monotonic clock. */
|
||||
now?: () => number;
|
||||
/**
|
||||
* A send-rate window shared with other queues posting to the same
|
||||
* collector. Default: a private one from `budget.maxSendsPerMinute`.
|
||||
*/
|
||||
sendRate?: TelemetrySendRate;
|
||||
/** Schedules a flush soon (default: microtask). */
|
||||
schedule?: (callback: () => void) => void;
|
||||
/** Schedules a flush after a rate window reopens (default: setTimeout). */
|
||||
@@ -136,8 +177,8 @@ export function createTelemetryPipeline(
|
||||
});
|
||||
/** Duplicates counted but not yet reported, per fingerprint. */
|
||||
const held = new Map<string, { event: TelemetryEvent<unknown>; count: number }>();
|
||||
/** Send timestamps inside the current rate window; never above the limit. */
|
||||
const sendTimes: number[] = [];
|
||||
const sendRate =
|
||||
options.sendRate ?? createTelemetrySendRate(budget.maxSendsPerMinute, now);
|
||||
|
||||
let disposed = false;
|
||||
let flushScheduled = false;
|
||||
@@ -156,16 +197,8 @@ export function createTelemetryPipeline(
|
||||
peakBuffered: 0,
|
||||
};
|
||||
|
||||
function rateAllows(at: number): boolean {
|
||||
while (sendTimes.length > 0 && at - (sendTimes[0] as number) >= RATE_WINDOW_MS) {
|
||||
sendTimes.shift();
|
||||
}
|
||||
return sendTimes.length < budget.maxSendsPerMinute;
|
||||
}
|
||||
|
||||
function armRateTimer(at: number): void {
|
||||
function armRateTimer(reopenIn: number): void {
|
||||
if (rateTimer !== null || disposed) return;
|
||||
const reopenIn = Math.max(1, (sendTimes[0] ?? at) + RATE_WINDOW_MS - at);
|
||||
rateTimer = setTimer(() => {
|
||||
rateTimer = null;
|
||||
void flush();
|
||||
@@ -227,13 +260,12 @@ export function createTelemetryPipeline(
|
||||
|
||||
async function drain(): Promise<void> {
|
||||
while (!disposed && pending()) {
|
||||
const at = now();
|
||||
if (!rateAllows(at)) {
|
||||
armRateTimer(at);
|
||||
const reopenIn = sendRate.take();
|
||||
if (reopenIn > 0) {
|
||||
armRateTimer(reopenIn);
|
||||
return;
|
||||
}
|
||||
const batch = takeBatch();
|
||||
sendTimes.push(at);
|
||||
counters.sends += 1;
|
||||
try {
|
||||
await options.transport.send(batch);
|
||||
|
||||
Reference in New Issue
Block a user