import { Fetch } from "../requestUtils"; import { debounce } from "lodash"; import { cancelCallback, requestCallback } from "../requestIdleCallback"; import { currentPath } from "./helpers"; interface Options { flushEndpoint: string; } export interface LogData { key: string; value: any; [prop: string]: any; } export interface LogMetadata { uiRoute: string; recordedAt: string; } export type LogEntry = LogData & LogMetadata; type QueueItem = { logType: string; log: LogEntry; }; export type LogsByType = Record; let flushEndpoint: string; let queue: QueueItem[] = []; let flushTimerID: number; const FLUSH_ENDPOINT_ERROR = "BatchedLogger is not initialized; initialize using BatchedLogger.initialize({ flushEndpoint: ... });"; /** * Flushes the queue */ export async function flush() { if (!flushEndpoint) { throw new Error(FLUSH_ENDPOINT_ERROR); } clearTimer(); await Fetch.post(flushEndpoint, nextBatch()); } /** * Rate limit flushing metrics to the server * * The first mechanism is to wait until we have not seen a metric for at least * two seconds. When it cools off we request a flush. * * If another flush has already been requested, we do nothing. */ const queueFlush = debounce(() => { if (!flushTimerID && queue.length > 0) { flushTimerID = requestCallback(flush); } }, 2000); /** * Initializes BatchedLogger * * This module should be initialized with a configuration option before it is used */ export const initialize = (options: Options) => { if (options.flushEndpoint) { flushEndpoint = options.flushEndpoint; } }; /** * Adds an item to the batch * @param item - item to add to the batch */ export function addToBatch(logType: string, item: LogData): void { if (!flushEndpoint) { throw new Error(FLUSH_ENDPOINT_ERROR); } const recordedAt = new Date().toISOString(); const uiRoute = currentPath(); const log: LogEntry = { recordedAt, uiRoute, ...item, }; queue.push({ logType, log }); queueFlush(); } /** * Returns the next batch of items in the queue */ function nextBatch(): LogsByType { const currentBatch = queue; queue = []; return currentBatch.reduce((itemsByType, qi) => { if (!itemsByType[qi.logType]) { itemsByType[qi.logType] = []; } itemsByType[qi.logType].push(qi.log); return itemsByType; }, {}); } /** * Cancels and clears the callback timer */ function clearTimer() { cancelCallback(flushTimerID); flushTimerID = 0; }