@geekmidas/services 1.0.2 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +24 -0
- package/dist/{ServiceDiscovery-Dvqa-Q1_.d.cts → ServiceDiscovery-CadEgTKz.d.mts} +2 -2
- package/dist/{ServiceDiscovery-ykolgkIj.d.mts.map → ServiceDiscovery-CadEgTKz.d.mts.map} +1 -1
- package/dist/{ServiceDiscovery-YeM2FZsl.cjs → ServiceDiscovery-Cxus7ber.cjs} +2 -2
- package/dist/{ServiceDiscovery-YeM2FZsl.cjs.map → ServiceDiscovery-Cxus7ber.cjs.map} +1 -1
- package/dist/{ServiceDiscovery-ykolgkIj.d.mts → ServiceDiscovery-DF4OKEZp.d.cts} +2 -2
- package/dist/{ServiceDiscovery-Dvqa-Q1_.d.cts.map → ServiceDiscovery-DF4OKEZp.d.cts.map} +1 -1
- package/dist/{ServiceDiscovery-BQ45ZFgI.mjs → ServiceDiscovery-SujDuYHr.mjs} +2 -2
- package/dist/{ServiceDiscovery-BQ45ZFgI.mjs.map → ServiceDiscovery-SujDuYHr.mjs.map} +1 -1
- package/dist/ServiceDiscovery.cjs +2 -2
- package/dist/ServiceDiscovery.d.cts +2 -2
- package/dist/ServiceDiscovery.d.mts +2 -2
- package/dist/ServiceDiscovery.mjs +2 -2
- package/dist/context-BojeLlxs.mjs +141 -0
- package/dist/context-BojeLlxs.mjs.map +1 -0
- package/dist/context-CkCPt2Fe.cjs +187 -0
- package/dist/context-CkCPt2Fe.cjs.map +1 -0
- package/dist/{context-BVeZOvOd.d.cts → context-D5pIUGkm.d.cts} +22 -3
- package/dist/context-D5pIUGkm.d.cts.map +1 -0
- package/dist/{context-DMExgNzl.d.mts → context-OmKid3Mr.d.mts} +22 -3
- package/dist/context-OmKid3Mr.d.mts.map +1 -0
- package/dist/context.cjs +3 -1
- package/dist/context.d.cts +3 -3
- package/dist/context.d.mts +3 -3
- package/dist/context.mjs +2 -2
- package/dist/index.cjs +4 -2
- package/dist/index.d.cts +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -3
- package/dist/{types-CcHmCx_U.d.mts → types-B99KrvXR.d.mts} +8 -1
- package/dist/types-B99KrvXR.d.mts.map +1 -0
- package/dist/{types-D7d_yeU5.d.cts → types-BY9yrY6Y.d.cts} +8 -1
- package/dist/types-BY9yrY6Y.d.cts.map +1 -0
- package/dist/types.d.cts +1 -1
- package/dist/types.d.mts +1 -1
- package/docs/request-scoped-logging.md +153 -0
- package/package.json +1 -1
- package/src/__tests__/context.spec.ts +180 -4
- package/src/context.ts +131 -8
- package/src/index.ts +2 -0
- package/src/types.ts +7 -0
- package/dist/context-B5YTspJR.mjs +0 -61
- package/dist/context-B5YTspJR.mjs.map +0 -1
- package/dist/context-BVeZOvOd.d.cts.map +0 -1
- package/dist/context-DMExgNzl.d.mts.map +0 -1
- package/dist/context-DUTDtYd2.cjs +0 -95
- package/dist/context-DUTDtYd2.cjs.map +0 -1
- package/dist/types-CcHmCx_U.d.mts.map +0 -1
- package/dist/types-D7d_yeU5.d.cts.map +0 -1
package/src/context.ts
CHANGED
|
@@ -19,6 +19,101 @@ export interface RequestContextData {
|
|
|
19
19
|
*/
|
|
20
20
|
const requestContextStorage = new AsyncLocalStorage<RequestContextData>();
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Resolve the logger for the current request, or throw if there is none.
|
|
24
|
+
*/
|
|
25
|
+
function resolveRequestLogger(): Logger {
|
|
26
|
+
const store = requestContextStorage.getStore();
|
|
27
|
+
if (!store) {
|
|
28
|
+
throw new Error(
|
|
29
|
+
'ServiceContext.getLogger() called outside request context. ' +
|
|
30
|
+
'Ensure code runs within runWithRequestContext().',
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
return store.logger;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Create a Logger that re-resolves its underlying logger on every call instead
|
|
38
|
+
* of capturing it once.
|
|
39
|
+
*
|
|
40
|
+
* This is what makes it safe for a **singleton** service to grab the logger a
|
|
41
|
+
* single time (e.g. during `register()`, which `ServiceDiscovery` only runs
|
|
42
|
+
* once and then caches) and reuse that reference for every request: each log
|
|
43
|
+
* call resolves the *current* request's logger from `AsyncLocalStorage`, so
|
|
44
|
+
* requests no longer inherit the first request's logger (and its `requestId`,
|
|
45
|
+
* user bindings, etc.).
|
|
46
|
+
*
|
|
47
|
+
* Implemented as a `Proxy` rather than a fixed list of methods so it forwards
|
|
48
|
+
* the *entire* surface of whatever logger is supplied — including members
|
|
49
|
+
* beyond the base `Logger` interface (e.g. a richer pino-backed logger's
|
|
50
|
+
* `flush()` or `level`) and any methods added to `Logger` in the future.
|
|
51
|
+
*
|
|
52
|
+
* @param bindings - `child()` bindings applied, in order, on top of the
|
|
53
|
+
* resolved logger before each call.
|
|
54
|
+
*/
|
|
55
|
+
function createRequestScopedLogger(bindings: object[] = []): Logger {
|
|
56
|
+
// Memoise the resolved (optionally child) logger per underlying base logger
|
|
57
|
+
// so we don't rebuild the child chain on every access within a request.
|
|
58
|
+
// Recomputed whenever the current request's logger changes — there is no
|
|
59
|
+
// await between the check and use, so this is safe under concurrency.
|
|
60
|
+
let cachedBase: Logger | undefined;
|
|
61
|
+
let cachedResolved: Logger | undefined;
|
|
62
|
+
|
|
63
|
+
const resolve = (): Logger => {
|
|
64
|
+
const base = resolveRequestLogger();
|
|
65
|
+
if (base !== cachedBase) {
|
|
66
|
+
cachedBase = base;
|
|
67
|
+
cachedResolved = bindings.reduce<Logger>(
|
|
68
|
+
(log, obj) => log.child(obj),
|
|
69
|
+
base,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
return cachedResolved as Logger;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
return new Proxy({} as Logger, {
|
|
76
|
+
get(_target, prop) {
|
|
77
|
+
// `child()` must stay request-scoped: return a new proxy carrying the
|
|
78
|
+
// extra binding, NOT the underlying logger's child (which would freeze
|
|
79
|
+
// to the current request).
|
|
80
|
+
if (prop === 'child') {
|
|
81
|
+
return (obj: object) => createRequestScopedLogger([...bindings, obj]);
|
|
82
|
+
}
|
|
83
|
+
// Never look like a thenable, and don't answer symbol/inspection probes
|
|
84
|
+
// (util.inspect, Symbol.toPrimitive, etc.) with bound functions.
|
|
85
|
+
if (prop === 'then' || typeof prop === 'symbol') {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
const value = (resolve() as Record<string, unknown>)[prop];
|
|
89
|
+
// Functions are re-resolved at *call* time so detached references
|
|
90
|
+
// (`const info = logger.info`) still target the current request's
|
|
91
|
+
// logger. Non-function members (e.g. `level`) forward as their live
|
|
92
|
+
// value on the current request's logger.
|
|
93
|
+
return typeof value === 'function'
|
|
94
|
+
? (...args: unknown[]) =>
|
|
95
|
+
(resolve() as Record<string, (...a: unknown[]) => unknown>)[prop](
|
|
96
|
+
...args,
|
|
97
|
+
)
|
|
98
|
+
: value;
|
|
99
|
+
},
|
|
100
|
+
// Keep `'prop' in logger` / hasOwnProperty truthful against the underlying
|
|
101
|
+
// logger so feature-detection works.
|
|
102
|
+
has(_target, prop) {
|
|
103
|
+
if (prop === 'child') return true;
|
|
104
|
+
if (prop === 'then' || typeof prop === 'symbol') return false;
|
|
105
|
+
return prop in (resolve() as object);
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Stable, process-wide request-scoped logger proxy. Shared across requests on
|
|
112
|
+
* purpose — it carries no request state itself, delegating to the current
|
|
113
|
+
* `AsyncLocalStorage` store on each call.
|
|
114
|
+
*/
|
|
115
|
+
const requestScopedLogger = createRequestScopedLogger();
|
|
116
|
+
|
|
22
117
|
/**
|
|
23
118
|
* ServiceContext implementation.
|
|
24
119
|
* Singleton that reads from AsyncLocalStorage.
|
|
@@ -26,14 +121,13 @@ const requestContextStorage = new AsyncLocalStorage<RequestContextData>();
|
|
|
26
121
|
*/
|
|
27
122
|
export const serviceContext: ServiceContext = {
|
|
28
123
|
getLogger() {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
return store.logger;
|
|
124
|
+
// Throw eagerly if there is no context, preserving the "catch bugs early"
|
|
125
|
+
// contract for callers that read the logger at an unexpected time.
|
|
126
|
+
resolveRequestLogger();
|
|
127
|
+
// Return the shared proxy rather than the raw `store.logger`. A service
|
|
128
|
+
// that captures this once still logs against the correct per-request
|
|
129
|
+
// logger because the proxy re-resolves on every call.
|
|
130
|
+
return requestScopedLogger;
|
|
37
131
|
},
|
|
38
132
|
|
|
39
133
|
getRequestId() {
|
|
@@ -89,3 +183,32 @@ export function runWithRequestContext<T>(
|
|
|
89
183
|
): T | Promise<T> {
|
|
90
184
|
return requestContextStorage.run(data, fn);
|
|
91
185
|
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Mutate the current async task's store so that subsequent code in this task
|
|
189
|
+
* (and any descendants) sees the supplied request context.
|
|
190
|
+
*
|
|
191
|
+
* Unlike `runWithRequestContext`, this does not scope the context to a
|
|
192
|
+
* callback — useful when the caller can't wrap a function, for example in a
|
|
193
|
+
* Vitest fixture that suspends on `use()` and yields control to the test
|
|
194
|
+
* runner before the test body executes.
|
|
195
|
+
*
|
|
196
|
+
* **Test setup only.** In production handlers, prefer `runWithRequestContext`
|
|
197
|
+
* so the frame is automatically cleaned up.
|
|
198
|
+
*/
|
|
199
|
+
export function enterRequestContext(data: RequestContextData): void {
|
|
200
|
+
requestContextStorage.enterWith(data);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Clear the request context for the current async task. Pairs with
|
|
205
|
+
* `enterRequestContext`. After calling, `serviceContext.hasContext()` returns
|
|
206
|
+
* false for the remainder of the current async resource.
|
|
207
|
+
*/
|
|
208
|
+
export function exitRequestContext(): void {
|
|
209
|
+
// AsyncLocalStorage<T>.enterWith requires T, but Node accepts undefined at
|
|
210
|
+
// runtime — passing it resets getStore() back to undefined.
|
|
211
|
+
(requestContextStorage as unknown as AsyncLocalStorage<unknown>).enterWith(
|
|
212
|
+
undefined,
|
|
213
|
+
);
|
|
214
|
+
}
|
package/src/index.ts
CHANGED
package/src/types.ts
CHANGED
|
@@ -9,6 +9,13 @@ import type { Logger } from '@geekmidas/logger';
|
|
|
9
9
|
export interface ServiceContext {
|
|
10
10
|
/**
|
|
11
11
|
* Get the current request's logger.
|
|
12
|
+
*
|
|
13
|
+
* Returns a **request-scoped proxy** that re-resolves the underlying logger
|
|
14
|
+
* from AsyncLocalStorage on every call. This makes it safe for a singleton
|
|
15
|
+
* service to capture the logger once (e.g. during `register()`) and reuse it
|
|
16
|
+
* across requests — each log call routes to the current request's logger
|
|
17
|
+
* instead of freezing the first request's logger.
|
|
18
|
+
*
|
|
12
19
|
* @throws Error if called outside a request context
|
|
13
20
|
*/
|
|
14
21
|
getLogger(): Logger;
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
-
|
|
3
|
-
//#region src/context.ts
|
|
4
|
-
/**
|
|
5
|
-
* Internal AsyncLocalStorage instance for request context.
|
|
6
|
-
* Not exported - use runWithRequestContext() to establish context
|
|
7
|
-
* and serviceContext to access it.
|
|
8
|
-
*/
|
|
9
|
-
const requestContextStorage = new AsyncLocalStorage();
|
|
10
|
-
/**
|
|
11
|
-
* ServiceContext implementation.
|
|
12
|
-
* Singleton that reads from AsyncLocalStorage.
|
|
13
|
-
* Methods throw if called outside a request context (catches bugs early).
|
|
14
|
-
*/
|
|
15
|
-
const serviceContext = {
|
|
16
|
-
getLogger() {
|
|
17
|
-
const store = requestContextStorage.getStore();
|
|
18
|
-
if (!store) throw new Error("ServiceContext.getLogger() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
19
|
-
return store.logger;
|
|
20
|
-
},
|
|
21
|
-
getRequestId() {
|
|
22
|
-
const store = requestContextStorage.getStore();
|
|
23
|
-
if (!store) throw new Error("ServiceContext.getRequestId() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
24
|
-
return store.requestId;
|
|
25
|
-
},
|
|
26
|
-
getRequestStartTime() {
|
|
27
|
-
const store = requestContextStorage.getStore();
|
|
28
|
-
if (!store) throw new Error("ServiceContext.getRequestStartTime() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
29
|
-
return store.startTime;
|
|
30
|
-
},
|
|
31
|
-
hasContext() {
|
|
32
|
-
return requestContextStorage.getStore() !== void 0;
|
|
33
|
-
}
|
|
34
|
-
};
|
|
35
|
-
/**
|
|
36
|
-
* Run a function with request context.
|
|
37
|
-
* Used by endpoint/function/subscriber adaptors.
|
|
38
|
-
*
|
|
39
|
-
* @param data - Request context data (logger, requestId, startTime)
|
|
40
|
-
* @param fn - Function to run with context
|
|
41
|
-
* @returns Result of the function
|
|
42
|
-
*
|
|
43
|
-
* @example
|
|
44
|
-
* ```typescript
|
|
45
|
-
* const result = await runWithRequestContext(
|
|
46
|
-
* { logger, requestId, startTime: Date.now() },
|
|
47
|
-
* async () => {
|
|
48
|
-
* // Inside here, serviceContext.getLogger() returns `logger`
|
|
49
|
-
* // serviceContext.getRequestId() returns `requestId`
|
|
50
|
-
* return await handleRequest();
|
|
51
|
-
* }
|
|
52
|
-
* );
|
|
53
|
-
* ```
|
|
54
|
-
*/
|
|
55
|
-
function runWithRequestContext(data, fn) {
|
|
56
|
-
return requestContextStorage.run(data, fn);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
//#endregion
|
|
60
|
-
export { runWithRequestContext, serviceContext };
|
|
61
|
-
//# sourceMappingURL=context-B5YTspJR.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-B5YTspJR.mjs","names":["serviceContext: ServiceContext","data: RequestContextData","fn: () => T | Promise<T>"],"sources":["../src/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceContext } from './types';\n\n/**\n * Internal storage for request context data.\n * Not exported - services use ServiceContext interface.\n */\nexport interface RequestContextData {\n\tlogger: Logger;\n\trequestId: string;\n\tstartTime: number;\n}\n\n/**\n * Internal AsyncLocalStorage instance for request context.\n * Not exported - use runWithRequestContext() to establish context\n * and serviceContext to access it.\n */\nconst requestContextStorage = new AsyncLocalStorage<RequestContextData>();\n\n/**\n * ServiceContext implementation.\n * Singleton that reads from AsyncLocalStorage.\n * Methods throw if called outside a request context (catches bugs early).\n */\nexport const serviceContext: ServiceContext = {\n\tgetLogger() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getLogger() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.logger;\n\t},\n\n\tgetRequestId() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestId() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.requestId;\n\t},\n\n\tgetRequestStartTime() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestStartTime() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.startTime;\n\t},\n\n\thasContext() {\n\t\treturn requestContextStorage.getStore() !== undefined;\n\t},\n};\n\n/**\n * Run a function with request context.\n * Used by endpoint/function/subscriber adaptors.\n *\n * @param data - Request context data (logger, requestId, startTime)\n * @param fn - Function to run with context\n * @returns Result of the function\n *\n * @example\n * ```typescript\n * const result = await runWithRequestContext(\n * { logger, requestId, startTime: Date.now() },\n * async () => {\n * // Inside here, serviceContext.getLogger() returns `logger`\n * // serviceContext.getRequestId() returns `requestId`\n * return await handleRequest();\n * }\n * );\n * ```\n */\nexport function runWithRequestContext<T>(\n\tdata: RequestContextData,\n\tfn: () => T | Promise<T>,\n): T | Promise<T> {\n\treturn requestContextStorage.run(data, fn);\n}\n"],"mappings":";;;;;;;;AAmBA,MAAM,wBAAwB,IAAI;;;;;;AAOlC,MAAaA,iBAAiC;CAC7C,YAAY;EACX,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,eAAe;EACd,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,sBAAsB;EACrB,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,aAAa;AACZ,SAAO,sBAAsB,UAAU;CACvC;AACD;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,sBACfC,MACAC,IACiB;AACjB,QAAO,sBAAsB,IAAI,MAAM,GAAG;AAC1C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-BVeZOvOd.d.cts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAkBA;AA2DgB,UA7EC,kBAAA,CA6EoB;EAAA,MAAA,EA5E5B,MA4E4B;EAAA,SAC9B,EAAA,MAAA;EAAkB,SACd,EAAA,MAAA;;;;;;AACG;cA9DD,gBAAgB;;;;;;;;;;;;;;;;;;;;;iBA2Db,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-DMExgNzl.d.mts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAkBA;AA2DgB,UA7EC,kBAAA,CA6EoB;EAAA,MAAA,EA5E5B,MA4E4B;EAAA,SAC9B,EAAA,MAAA;EAAkB,SACd,EAAA,MAAA;;;;;;AACG;cA9DD,gBAAgB;;;;;;;;;;;;;;;;;;;;;iBA2Db,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ"}
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
//#region rolldown:runtime
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __copyProps = (to, from, except, desc) => {
|
|
9
|
-
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
-
key = keys[i];
|
|
11
|
-
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
-
get: ((k) => from[k]).bind(null, key),
|
|
13
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
-
value: mod,
|
|
20
|
-
enumerable: true
|
|
21
|
-
}) : target, mod));
|
|
22
|
-
|
|
23
|
-
//#endregion
|
|
24
|
-
const node_async_hooks = __toESM(require("node:async_hooks"));
|
|
25
|
-
|
|
26
|
-
//#region src/context.ts
|
|
27
|
-
/**
|
|
28
|
-
* Internal AsyncLocalStorage instance for request context.
|
|
29
|
-
* Not exported - use runWithRequestContext() to establish context
|
|
30
|
-
* and serviceContext to access it.
|
|
31
|
-
*/
|
|
32
|
-
const requestContextStorage = new node_async_hooks.AsyncLocalStorage();
|
|
33
|
-
/**
|
|
34
|
-
* ServiceContext implementation.
|
|
35
|
-
* Singleton that reads from AsyncLocalStorage.
|
|
36
|
-
* Methods throw if called outside a request context (catches bugs early).
|
|
37
|
-
*/
|
|
38
|
-
const serviceContext = {
|
|
39
|
-
getLogger() {
|
|
40
|
-
const store = requestContextStorage.getStore();
|
|
41
|
-
if (!store) throw new Error("ServiceContext.getLogger() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
42
|
-
return store.logger;
|
|
43
|
-
},
|
|
44
|
-
getRequestId() {
|
|
45
|
-
const store = requestContextStorage.getStore();
|
|
46
|
-
if (!store) throw new Error("ServiceContext.getRequestId() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
47
|
-
return store.requestId;
|
|
48
|
-
},
|
|
49
|
-
getRequestStartTime() {
|
|
50
|
-
const store = requestContextStorage.getStore();
|
|
51
|
-
if (!store) throw new Error("ServiceContext.getRequestStartTime() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
52
|
-
return store.startTime;
|
|
53
|
-
},
|
|
54
|
-
hasContext() {
|
|
55
|
-
return requestContextStorage.getStore() !== void 0;
|
|
56
|
-
}
|
|
57
|
-
};
|
|
58
|
-
/**
|
|
59
|
-
* Run a function with request context.
|
|
60
|
-
* Used by endpoint/function/subscriber adaptors.
|
|
61
|
-
*
|
|
62
|
-
* @param data - Request context data (logger, requestId, startTime)
|
|
63
|
-
* @param fn - Function to run with context
|
|
64
|
-
* @returns Result of the function
|
|
65
|
-
*
|
|
66
|
-
* @example
|
|
67
|
-
* ```typescript
|
|
68
|
-
* const result = await runWithRequestContext(
|
|
69
|
-
* { logger, requestId, startTime: Date.now() },
|
|
70
|
-
* async () => {
|
|
71
|
-
* // Inside here, serviceContext.getLogger() returns `logger`
|
|
72
|
-
* // serviceContext.getRequestId() returns `requestId`
|
|
73
|
-
* return await handleRequest();
|
|
74
|
-
* }
|
|
75
|
-
* );
|
|
76
|
-
* ```
|
|
77
|
-
*/
|
|
78
|
-
function runWithRequestContext(data, fn) {
|
|
79
|
-
return requestContextStorage.run(data, fn);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
//#endregion
|
|
83
|
-
Object.defineProperty(exports, 'runWithRequestContext', {
|
|
84
|
-
enumerable: true,
|
|
85
|
-
get: function () {
|
|
86
|
-
return runWithRequestContext;
|
|
87
|
-
}
|
|
88
|
-
});
|
|
89
|
-
Object.defineProperty(exports, 'serviceContext', {
|
|
90
|
-
enumerable: true,
|
|
91
|
-
get: function () {
|
|
92
|
-
return serviceContext;
|
|
93
|
-
}
|
|
94
|
-
});
|
|
95
|
-
//# sourceMappingURL=context-DUTDtYd2.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-DUTDtYd2.cjs","names":["AsyncLocalStorage","serviceContext: ServiceContext","data: RequestContextData","fn: () => T | Promise<T>"],"sources":["../src/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceContext } from './types';\n\n/**\n * Internal storage for request context data.\n * Not exported - services use ServiceContext interface.\n */\nexport interface RequestContextData {\n\tlogger: Logger;\n\trequestId: string;\n\tstartTime: number;\n}\n\n/**\n * Internal AsyncLocalStorage instance for request context.\n * Not exported - use runWithRequestContext() to establish context\n * and serviceContext to access it.\n */\nconst requestContextStorage = new AsyncLocalStorage<RequestContextData>();\n\n/**\n * ServiceContext implementation.\n * Singleton that reads from AsyncLocalStorage.\n * Methods throw if called outside a request context (catches bugs early).\n */\nexport const serviceContext: ServiceContext = {\n\tgetLogger() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getLogger() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.logger;\n\t},\n\n\tgetRequestId() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestId() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.requestId;\n\t},\n\n\tgetRequestStartTime() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestStartTime() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.startTime;\n\t},\n\n\thasContext() {\n\t\treturn requestContextStorage.getStore() !== undefined;\n\t},\n};\n\n/**\n * Run a function with request context.\n * Used by endpoint/function/subscriber adaptors.\n *\n * @param data - Request context data (logger, requestId, startTime)\n * @param fn - Function to run with context\n * @returns Result of the function\n *\n * @example\n * ```typescript\n * const result = await runWithRequestContext(\n * { logger, requestId, startTime: Date.now() },\n * async () => {\n * // Inside here, serviceContext.getLogger() returns `logger`\n * // serviceContext.getRequestId() returns `requestId`\n * return await handleRequest();\n * }\n * );\n * ```\n */\nexport function runWithRequestContext<T>(\n\tdata: RequestContextData,\n\tfn: () => T | Promise<T>,\n): T | Promise<T> {\n\treturn requestContextStorage.run(data, fn);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,wBAAwB,IAAIA;;;;;;AAOlC,MAAaC,iBAAiC;CAC7C,YAAY;EACX,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,eAAe;EACd,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,sBAAsB;EACrB,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,aAAa;AACZ,SAAO,sBAAsB,UAAU;CACvC;AACD;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,sBACfC,MACAC,IACiB;AACjB,QAAO,sBAAsB,IAAI,MAAM,GAAG;AAC1C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types-CcHmCx_U.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AA8BA;;AAEY,UAhCK,cAAA,CAgCL;EAAiB;AAEL;AA8BxB;;EAAwB,SAIV,EAAA,EA/DA,MA+DA;EAAK;;;;EAO4C,YAAA,EAAA,EAAA,MAAA;;;;;;;;;;;;;;;;UA7C9C,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types-D7d_yeU5.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AA8BA;;AAEY,UAhCK,cAAA,CAgCL;EAAiB;AAEL;AA8BxB;;EAAwB,SAIV,EAAA,EA/DA,MA+DA;EAAK;;;;EAO4C,YAAA,EAAA,EAAA,MAAA;;;;;;;;;;;;;;;;UA7C9C,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}
|