import type { LogRecord } from "./log-record.ts" /** * @description Describe a schedulable log emission task. */ export interface LogTask { record: LogRecord emit: () => void } /** * @description Represent supported scheduling strategies. */ export type LogSchedulerStrategy = "immediate" /** * @description Describe options used to configure a log scheduler. */ export interface LogSchedulerOptions { strategy: LogSchedulerStrategy } /** * @description Queue and dispatch log tasks based on scheduling strategy. */ export class LogScheduler { protected strategy: LogSchedulerStrategy protected taskQueue: LogTask[][] constructor(options: LogSchedulerOptions) { this.strategy = options.strategy this.taskQueue = [] } /** * @description Check if there are any tasks in the queue. */ hasTasks(): boolean { return this.taskQueue.length !== 0 } /** * @description Enqueue tasks and run immediately when strategy requires. */ enqueue(task: LogTask[]): void { this.taskQueue.push(task) if (this.strategy === "immediate") { this.run() } } /** * @description Flush queued tasks in insertion order. */ run(): void { const tasksToRun = [...this.taskQueue].flat() this.taskQueue = [] for (const task of tasksToRun) { task.emit() } } } /** * @description Get the singleton global `LogScheduler` instance. */ export const getGlobalLogScheduler: () => LogScheduler = (() => { let instance: LogScheduler | undefined = undefined return (): LogScheduler => { instance = instance ?? new LogScheduler({ strategy: "immediate" }) return instance } })()