@trifrost/core
Version:
Blazingly fast, runtime-agnostic server framework for modern edge and node environments
53 lines (52 loc) • 1.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ctx = ctx;
exports.activateCtx = activateCtx;
const node_async_hooks_1 = require("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 node_async_hooks_1.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.
*/
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
*/
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];
}
}