UNPKG

@trifrost/core

Version:

Blazingly fast, runtime-agnostic server framework for modern edge and node environments

49 lines (48 loc) 1.66 kB
import { AsyncLocalStorage } from 'node:async_hooks'; /** * AsyncLocalStorage instance for tracking the lifetime of an async execution context. * * Instead of storing the whole context in AsyncLocalStorage (which can * have perf/memory costs), we only store a key, and keep the actual * TriFrostContext in a plain in-memory map keyed by that key. */ const als = new AsyncLocalStorage(); /** * A map from key -> TriFrostContext instance. * * This allows us to quickly retrieve the active request's context * without passing it explicitly down the call stack. */ const map = {}; /** * Retrieve the current TriFrostContext bound to the active async * execution context, if any. */ export function ctx() { const key = als.getStore(); return key ? map[key] : undefined; } /** * Activate an AsyncLocalStorage execution context with a given key * and bind it to a TriFrostContext for the duration of `fn`. * * This ensures that any code running within `fn` (and its async descendants) * can call `context()` to retrieve the bound TriFrostContext without * having to pass it manually. * * @param {string} key - key to store in als * @param {TriFrostContext} ctx - Context for als run * @param {() => Promise<void | Response>} fn - Method to bind to als */ export async function activateCtx(key, ctx, fn) { // Store the context in the map for retrieval during execution map[key] = ctx; try { // Run the function within the ALS scope, storing the key as the "current store" value return await als.run(key, fn); } finally { // Clean up after run is finished delete map[key]; } }