UNPKG

@sentry/core

Version:
87 lines (86 loc) • 2.76 kB
import { isPrimitive } from "./is.js"; import { safeUnref } from "./timer.js"; // src/utils/weightBasedFlushing.ts const DEFAULT_FLUSH_INTERVAL = 5e3; /** * Sets up weight-based flushing for logs or metrics. * This helper function encapsulates the common pattern of: * 1. Tracking accumulated weight of items * 2. Flushing when weight exceeds threshold (800KB) * 3. Flushing after timeout period from the first item * * Uses closure variables to track weight and timeout state. */ function setupWeightBasedFlushing(client, afterCaptureHook, flushHook, estimateSizeFn, flushFn) { let weight = 0; let flushTimeout; let isTimerActive = false; client.on(flushHook, () => { weight = 0; clearTimeout(flushTimeout); isTimerActive = false; }); client.on(afterCaptureHook, (item) => { weight += estimateSizeFn(item); if (weight >= 8e5) flushFn(client); else if (!isTimerActive) { const flushInterval = client.getOptions()._flushInterval ?? DEFAULT_FLUSH_INTERVAL; if (flushInterval > 0) { isTimerActive = true; flushTimeout = safeUnref(setTimeout(() => { flushFn(client); }, flushInterval)); } } }); client.on("flush", () => { flushFn(client); }); } /** * Estimate the size of a metric in bytes. * * @param metric - The metric to estimate the size of. * @returns The estimated size of the metric in bytes. */ function estimateMetricSizeInBytes(metric) { let weight = 0; if (metric.name) weight += metric.name.length * 2; weight += 8; return weight + estimateAttributesSizeInBytes(metric.attributes); } /** * Estimate the size of a log in bytes. * * @param log - The log to estimate the size of. * @returns The estimated size of the log in bytes. */ function estimateLogSizeInBytes(log) { let weight = 0; if (log.message) weight += log.message.length * 2; return weight + estimateAttributesSizeInBytes(log.attributes); } /** * Estimate the size of attributes in bytes. * * @param attributes - The attributes object to estimate the size of. * @returns The estimated size of the attributes in bytes. */ function estimateAttributesSizeInBytes(attributes) { if (!attributes) return 0; let weight = 0; Object.values(attributes).forEach((value) => { if (Array.isArray(value)) weight += value.length * estimatePrimitiveSizeInBytes(value[0]); else if (isPrimitive(value)) weight += estimatePrimitiveSizeInBytes(value); else weight += 100; }); return weight; } function estimatePrimitiveSizeInBytes(value) { if (typeof value === "string") return value.length * 2; else if (typeof value === "number") return 8; else if (typeof value === "boolean") return 4; return 0; } export { estimateLogSizeInBytes, estimateMetricSizeInBytes, setupWeightBasedFlushing }; //# sourceMappingURL=weightBasedFlushing.js.map