/** * The request being collected. * * A `Collection` is one request's worth of everything the collectors hear. * Hooks fire from anywhere (a query deep inside a model, a log line in a * listener), so the collection in flight is found through an * `AsyncLocalStorage` slot instead of being passed along. * * The slot is keyed on a process-global symbol, as the router's request store * is, so two physical copies of this package in one process still share it. */ import type { DebugbarProcess, DebugbarRequestKind, ResolvedDebugbarConfig } from './types' import { AsyncLocalStorage } from 'node:async_hooks' const STORAGE_KEY = Symbol.for('stacks.debugbar.collection') const storage = ((globalThis as Record)[STORAGE_KEY] ??= new AsyncLocalStorage()) as AsyncLocalStorage /** How many entries one collector may hold for a request before it only counts. */ const BAG_LIMIT = 1000 let counter = 0 /** * A record id: when it was made, then randomness. * * Time first, in fixed-width base 36, so ids sort by age as plain strings. * That ordering is the store's index: the newest records are the last file * names, with no index file to keep in step between two processes. */ export function createRecordId(now: number = Date.now()): string { counter = (counter + 1) % 1296 const random = crypto.getRandomValues(new Uint32Array(2)) return now.toString(36).padStart(9, '0') + counter.toString(36).padStart(2, '0') + random[0]!.toString(36).padStart(7, '0').slice(-7) + random[1]!.toString(36).padStart(7, '0').slice(-6) } const RECORD_ID = /^[0-9a-z]{20,32}$/ export function isRecordId(value: unknown): value is string { return typeof value === 'string' && RECORD_ID.test(value) } export class Collection { readonly id: string readonly process: DebugbarProcess readonly request: Request readonly url: URL readonly config: ResolvedDebugbarConfig /** Wall clock, for the record. */ readonly startedAt: number /** Monotonic, for durations. */ readonly startedMs: number kind: DebugbarRequestKind /** Set once the response is known. Hooks that fire afterwards are ignored. */ finished: boolean = false /** Milliseconds the request took, set when it finishes. */ duration: number | undefined private readonly bags = new Map() private readonly overflow = new Map() private readonly values = new Map() constructor(request: Request, process: DebugbarProcess, config: ResolvedDebugbarConfig) { this.id = createRecordId() this.process = process this.request = request this.url = new URL(request.url) this.config = config this.startedAt = Date.now() this.startedMs = performance.now() this.kind = process === 'api' ? 'api' : 'page' } /** Milliseconds since the request began, or how long it took once it has finished. */ elapsed(): number { return this.duration ?? performance.now() - this.startedMs } /** Append to a collector's list. Past the limit the entry is counted, not kept. */ push(name: string, entry: T, limit: number = BAG_LIMIT): void { if (this.finished) return let bag = this.bags.get(name) if (!bag) { bag = [] this.bags.set(name, bag) } if (bag.length >= limit) { this.overflow.set(name, (this.overflow.get(name) ?? 0) + 1) return } bag.push(entry) } list(name: string): T[] { return (this.bags.get(name) ?? []) as T[] } /** How many entries `push` turned away for being over the limit. */ dropped(name: string): number { return this.overflow.get(name) ?? 0 } set(name: string, value: unknown): void { if (!this.finished) this.values.set(name, value) } get(name: string): T | undefined { return this.values.get(name) as T | undefined } } /** The collection the caller is running inside, or undefined. */ export function currentCollection(): Collection | undefined { const collection = storage.getStore() return collection && !collection.finished ? collection : undefined } /** Run `fn` with `collection` as the one in flight. */ export function runWithCollection(collection: Collection, fn: () => T): T { return storage.run(collection, fn) } /** * Make `collection` the one in flight for the rest of the current async * context. For a server whose request hook returns before the work it starts, * where there is no function to wrap. Call it before the hook's first `await`. */ export function enterCollection(collection: Collection): void { storage.enterWith(collection) } /** Run `fn` outside any collection, so the debugbar's own work is not recorded. */ export function withoutCollection(fn: () => T): T { return storage.run(undefined, fn) }