@beignet/core
Version:
Core framework primitives for Beignet
93 lines • 3.09 kB
JavaScript
import { AsyncLocalStorage } from "node:async_hooks";
const activeRequestContext = new AsyncLocalStorage();
/**
* Enter the ambient request context for the current async execution.
*/
export function enterActiveRequestContext(context) {
activeRequestContext.enterWith(context);
}
/**
* Clear the ambient request context for the current async execution.
*/
export function clearActiveRequestContext() {
activeRequestContext.enterWith(undefined);
}
/**
* Run a function inside a scoped ambient request context frame.
*
* Internal to the server runtime — not part of the public package surface.
* `server.runServiceContext(...)` uses this `AsyncLocalStorage.run` form
* instead of `enterWith` because resuming an `enterWith` frame across
* top-level await crashes Bun 1.3.x in plain scripts.
*/
export function runWithActiveRequestContext(context, fn) {
return activeRequestContext.run(context, fn);
}
/**
* Read the ambient request context, when one is active.
*/
export function getActiveRequestContext() {
return activeRequestContext.getStore();
}
/**
* Read a normalized actor from an app context object, when present.
*/
export function readContextActor(ctx) {
if (!ctx || typeof ctx !== "object")
return undefined;
const actor = ctx.actor;
if (!actor || typeof actor !== "object")
return undefined;
return typeof actor.type === "string"
? actor
: undefined;
}
/**
* Read a normalized tenant from an app context object, when present.
*/
export function readContextTenant(ctx) {
if (!ctx || typeof ctx !== "object")
return undefined;
const tenant = ctx.tenant;
if (!tenant || typeof tenant !== "object")
return undefined;
return typeof tenant.id === "string"
? tenant
: undefined;
}
/**
* Update identity fields on the active ambient request context in place.
*
* The server calls this after hooks finalize a new request context so the
* elevated actor/tenant become visible to ambient consumers, including async
* frames that captured the context object before the update. No-op when no
* ambient context is active.
*/
export function setActiveRequestIdentity(identity) {
const context = activeRequestContext.getStore();
if (!context)
return;
if (identity.actor)
context.actor = identity.actor;
if (identity.tenant)
context.tenant = identity.tenant;
}
/**
* Fill missing correlation fields on an event from the ambient request
* context.
*/
export function inheritActiveRequestContext(event) {
const context = getActiveRequestContext();
if (!context)
return event;
return {
...event,
requestId: event.requestId ?? context.requestId,
traceId: event.traceId ?? context.traceId,
spanId: event.spanId ?? context.spanId,
parentSpanId: event.parentSpanId ?? context.parentSpanId,
traceparent: event.traceparent ?? context.traceparent,
tracestate: event.tracestate ?? context.tracestate,
};
}
//# sourceMappingURL=request-context.js.map