/** * The debugbar's one piece of process state: whether it is running here, and * with what. * * Both servers go through `bootDebugbar`. It answers `undefined` and does * nothing at all when the debugbar is not enabled, so a caller that holds * `undefined` has, by construction, registered no hook, opened no store and * mounted no endpoint. */ import type { DebugbarConfig } from '@stacksjs/types' import type { ResponseSnapshot } from './collectors' import type { EnvironmentInputs } from './state' import type { DebugbarStore } from './storage' import type { DebugbarProcess, DebugbarRecord, DebugbarRequestKind, DebugbarSummary, QueriesSection, ResolvedDebugbarConfig, RouteSection, ViewSection } from './types' import { randomBytes } from 'node:crypto' import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import process from 'node:process' import { config } from '@stacksjs/config' import { projectPath, storagePath } from '@stacksjs/path' import { beginCollectors, collectors, installCollectors, registerCollector, runCollectors, uninstallCollectors } from './collectors' import { builtInCollectors } from './collectors/index' import { setViewsRoot } from './collectors/views' import { Collection, withoutCollection } from './context' import { setProjectRoot } from './frames' import { releaseSocketPeerCapture } from './peer' import { redactUrl } from './redact' import { isDebugbarEnabled, isExcludedPath, resolveDebugbarConfig } from './state' import { createStore, ensureStorageDirectory } from './storage' export interface DebugbarRuntime { readonly config: ResolvedDebugbarConfig readonly store: DebugbarStore readonly process: DebugbarProcess /** `config.app.url`, for deciding which hostnames are this machine's. */ readonly appUrl?: string } export interface BootOptions extends EnvironmentInputs { /** Use this instead of `config.debugbar`. */ config?: DebugbarConfig /** The project root, for telling application frames from framework ones. */ root?: string } let runtime: DebugbarRuntime | undefined const builtInNames = new Set() const builtInRemovers: Array<() => void> = [] function appSettings(): { env?: string, url?: string } { try { const app = (config as { app?: { env?: string, url?: string } }).app return { env: app?.env, url: app?.url } } catch { return {} } } /** Whether the debugbar would run in this process. Reads the environment and config, starts nothing. */ export function debugbarEnabled(options: BootOptions = {}): boolean { const app = appSettings() return isDebugbarEnabled(options.config ?? (config as { debugbar?: DebugbarConfig }).debugbar, { env: options.env, appEnv: options.appEnv ?? app.env, }) } /** * Start the debugbar in this process, or do nothing and return undefined * when it is not enabled. Idempotent. */ export function bootDebugbar(processName: DebugbarProcess, options: BootOptions = {}): DebugbarRuntime | undefined { if (runtime) return runtime // First, and before anything is constructed: production and disabled // processes leave here having touched nothing. if (!debugbarEnabled(options)) return undefined const root = options.root ?? projectPath() const resolved = resolveDebugbarConfig( options.config ?? (config as { debugbar?: DebugbarConfig }).debugbar, storagePath('framework/debugbar'), ) setProjectRoot(root) setViewsRoot(join(root, 'resources/views')) // A collector the app registered under a built-in's name replaces it. const taken = new Set(collectors().map(collector => collector.name)) for (const collector of builtInCollectors(resolved)) { if (taken.has(collector.name)) continue builtInRemovers.push(registerCollector(collector)) builtInNames.add(collector.name) } installCollectors(resolved, processName) ensureStorageDirectory(resolved.storage.path) runtime = { config: resolved, store: createStore({ directory: resolved.storage.path, maxRequests: resolved.storage.maxRequests }), process: processName, appUrl: appSettings().url, } return runtime } /** The running debugbar, or undefined when it is not running in this process. */ export function debugbarRuntime(): DebugbarRuntime | undefined { return runtime } /** Stop the debugbar and detach every hook. For tests and hot reload. */ export function shutdownDebugbar(): void { uninstallCollectors() for (const remove of builtInRemovers.splice(0)) remove() builtInNames.clear() releaseSocketPeerCapture() runtime = undefined token = undefined } /** Whether this request is one the debugbar records. */ export function shouldCollect(active: DebugbarRuntime, path: string): boolean { return !isExcludedPath(path, active.config.except) } export function beginCollection(active: DebugbarRuntime, request: Request): Collection { const collection = new Collection(request, active.process, active.config) beginCollectors(collection) return collection } function summarize(collection: Collection, response: ResponseSnapshot, sections: Record): DebugbarSummary { const queries = sections.queries as QueriesSection | undefined const route = sections.route as RouteSection | undefined const view = sections.views as ViewSection | undefined const auth = sections.auth as { user?: { id: number | string, name?: string, email?: string } | null } | undefined const list = (name: string): number => Array.isArray(sections[name]) ? (sections[name] as unknown[]).length : 0 return { method: collection.request.method, url: redactUrl(collection.url), path: collection.url.pathname, status: response.status, kind: response.kind, process: collection.process, duration: collection.elapsed(), memory: Math.round(process.memoryUsage().rss / 1048576 * 10) / 10, queries: queries?.count ?? 0, queryDuration: queries?.duration ?? 0, logs: list('logs') + list('messages'), exceptions: list('exceptions'), route: route ? `${route.method} ${route.path}` : view?.template, user: auth?.user ?? undefined, } } /** * Close a request and write its record. * * Synchronous up to the point the response is known, so it adds nothing a * client waits on. The collectors that need I/O (who the token belongs to, * the source lines around an exception) and the write itself happen after, * and nothing they do can reach the response. */ export function finishCollection(active: DebugbarRuntime, collection: Collection, response: { status: number, headers: Headers }, kind: DebugbarRequestKind = collection.kind): Promise { if (collection.finished) return Promise.resolve() collection.duration = performance.now() - collection.startedMs collection.kind = kind collection.finished = true const snapshot: ResponseSnapshot = { status: response.status, headers: new Headers(response.headers), kind } return withoutCollection(async () => { try { const { sections, labels } = await runCollectors(collection, snapshot) const custom = Object.fromEntries(Object.entries(labels).filter(([name]) => !builtInNames.has(name))) const record: DebugbarRecord = { id: collection.id, version: 1, startedAt: new Date(collection.startedAt).toISOString(), summary: summarize(collection, snapshot, sections), collectors: sections, ...(Object.keys(custom).length > 0 && { labels: custom }), } await active.store.write(record) } catch { // A record that cannot be built is a record that is missing. } }) } let token: string | undefined /** * The secret a page must echo to use "Sign in as". * * Kept in the storage directory so it survives the dev server restarting * under a page that is still open, and readable only by the user who runs it. */ export function debugbarToken(active: DebugbarRuntime): string { if (token) return token const file = join(active.config.storage.path, '.token') try { if (existsSync(file)) { const stored = readFileSync(file, 'utf8').trim() if (/^[a-f0-9]{48}$/.test(stored)) return token = stored } const fresh = randomBytes(24).toString('hex') ensureStorageDirectory(active.config.storage.path) writeFileSync(file, fresh, { mode: 0o600 }) chmodSync(file, 0o600) return token = fresh } catch { // No writable storage: a token for this process only. return token = randomBytes(24).toString('hex') } }