@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.
Files changed (50) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +24 -0
  3. package/dist/{ServiceDiscovery-Dvqa-Q1_.d.cts → ServiceDiscovery-CadEgTKz.d.mts} +2 -2
  4. package/dist/{ServiceDiscovery-ykolgkIj.d.mts.map → ServiceDiscovery-CadEgTKz.d.mts.map} +1 -1
  5. package/dist/{ServiceDiscovery-YeM2FZsl.cjs → ServiceDiscovery-Cxus7ber.cjs} +2 -2
  6. package/dist/{ServiceDiscovery-YeM2FZsl.cjs.map → ServiceDiscovery-Cxus7ber.cjs.map} +1 -1
  7. package/dist/{ServiceDiscovery-ykolgkIj.d.mts → ServiceDiscovery-DF4OKEZp.d.cts} +2 -2
  8. package/dist/{ServiceDiscovery-Dvqa-Q1_.d.cts.map → ServiceDiscovery-DF4OKEZp.d.cts.map} +1 -1
  9. package/dist/{ServiceDiscovery-BQ45ZFgI.mjs → ServiceDiscovery-SujDuYHr.mjs} +2 -2
  10. package/dist/{ServiceDiscovery-BQ45ZFgI.mjs.map → ServiceDiscovery-SujDuYHr.mjs.map} +1 -1
  11. package/dist/ServiceDiscovery.cjs +2 -2
  12. package/dist/ServiceDiscovery.d.cts +2 -2
  13. package/dist/ServiceDiscovery.d.mts +2 -2
  14. package/dist/ServiceDiscovery.mjs +2 -2
  15. package/dist/context-BojeLlxs.mjs +141 -0
  16. package/dist/context-BojeLlxs.mjs.map +1 -0
  17. package/dist/context-CkCPt2Fe.cjs +187 -0
  18. package/dist/context-CkCPt2Fe.cjs.map +1 -0
  19. package/dist/{context-BVeZOvOd.d.cts → context-D5pIUGkm.d.cts} +22 -3
  20. package/dist/context-D5pIUGkm.d.cts.map +1 -0
  21. package/dist/{context-DMExgNzl.d.mts → context-OmKid3Mr.d.mts} +22 -3
  22. package/dist/context-OmKid3Mr.d.mts.map +1 -0
  23. package/dist/context.cjs +3 -1
  24. package/dist/context.d.cts +3 -3
  25. package/dist/context.d.mts +3 -3
  26. package/dist/context.mjs +2 -2
  27. package/dist/index.cjs +4 -2
  28. package/dist/index.d.cts +4 -4
  29. package/dist/index.d.mts +4 -4
  30. package/dist/index.mjs +3 -3
  31. package/dist/{types-CcHmCx_U.d.mts → types-B99KrvXR.d.mts} +8 -1
  32. package/dist/types-B99KrvXR.d.mts.map +1 -0
  33. package/dist/{types-D7d_yeU5.d.cts → types-BY9yrY6Y.d.cts} +8 -1
  34. package/dist/types-BY9yrY6Y.d.cts.map +1 -0
  35. package/dist/types.d.cts +1 -1
  36. package/dist/types.d.mts +1 -1
  37. package/docs/request-scoped-logging.md +153 -0
  38. package/package.json +1 -1
  39. package/src/__tests__/context.spec.ts +180 -4
  40. package/src/context.ts +131 -8
  41. package/src/index.ts +2 -0
  42. package/src/types.ts +7 -0
  43. package/dist/context-B5YTspJR.mjs +0 -61
  44. package/dist/context-B5YTspJR.mjs.map +0 -1
  45. package/dist/context-BVeZOvOd.d.cts.map +0 -1
  46. package/dist/context-DMExgNzl.d.mts.map +0 -1
  47. package/dist/context-DUTDtYd2.cjs +0 -95
  48. package/dist/context-DUTDtYd2.cjs.map +0 -1
  49. package/dist/types-CcHmCx_U.d.mts.map +0 -1
  50. package/dist/types-D7d_yeU5.d.cts.map +0 -1
@@ -1,4 +1,4 @@
1
- import { ServiceContext } from "./types-D7d_yeU5.cjs";
1
+ import { ServiceContext } from "./types-BY9yrY6Y.cjs";
2
2
  import { Logger } from "@geekmidas/logger";
3
3
 
4
4
  //#region src/context.d.ts
@@ -39,7 +39,26 @@ declare const serviceContext: ServiceContext;
39
39
  * ```
40
40
  */
41
41
  declare function runWithRequestContext<T>(data: RequestContextData, fn: () => T | Promise<T>): T | Promise<T>;
42
+ /**
43
+ * Mutate the current async task's store so that subsequent code in this task
44
+ * (and any descendants) sees the supplied request context.
45
+ *
46
+ * Unlike `runWithRequestContext`, this does not scope the context to a
47
+ * callback — useful when the caller can't wrap a function, for example in a
48
+ * Vitest fixture that suspends on `use()` and yields control to the test
49
+ * runner before the test body executes.
50
+ *
51
+ * **Test setup only.** In production handlers, prefer `runWithRequestContext`
52
+ * so the frame is automatically cleaned up.
53
+ */
54
+ declare function enterRequestContext(data: RequestContextData): void;
55
+ /**
56
+ * Clear the request context for the current async task. Pairs with
57
+ * `enterRequestContext`. After calling, `serviceContext.hasContext()` returns
58
+ * false for the remainder of the current async resource.
59
+ */
60
+ declare function exitRequestContext(): void;
42
61
  //# sourceMappingURL=context.d.ts.map
43
62
  //#endregion
44
- export { RequestContextData, runWithRequestContext, serviceContext };
45
- //# sourceMappingURL=context-BVeZOvOd.d.cts.map
63
+ export { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
64
+ //# sourceMappingURL=context-D5pIUGkm.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-D5pIUGkm.d.cts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAiHA;AA0DgB,UA3KC,kBAAA,CA2KoB;EAAA,MAAA,EA1K5B,MA0K4B;EAAA,SAC9B,EAAA,MAAA;EAAkB,SACd,EAAA,MAAA;;;;;;AACG;AAgBE,cA7EH,cA6EsB,EA7EN,cA6Ea;AAS1C;;;;;;;;;;;;;;;;;;;;iBA5BgB,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;iBAgBC,mBAAA,OAA0B;;;;;;iBAS1B,kBAAA,CAAA"}
@@ -1,4 +1,4 @@
1
- import { ServiceContext } from "./types-CcHmCx_U.mjs";
1
+ import { ServiceContext } from "./types-B99KrvXR.mjs";
2
2
  import { Logger } from "@geekmidas/logger";
3
3
 
4
4
  //#region src/context.d.ts
@@ -39,7 +39,26 @@ declare const serviceContext: ServiceContext;
39
39
  * ```
40
40
  */
41
41
  declare function runWithRequestContext<T>(data: RequestContextData, fn: () => T | Promise<T>): T | Promise<T>;
42
+ /**
43
+ * Mutate the current async task's store so that subsequent code in this task
44
+ * (and any descendants) sees the supplied request context.
45
+ *
46
+ * Unlike `runWithRequestContext`, this does not scope the context to a
47
+ * callback — useful when the caller can't wrap a function, for example in a
48
+ * Vitest fixture that suspends on `use()` and yields control to the test
49
+ * runner before the test body executes.
50
+ *
51
+ * **Test setup only.** In production handlers, prefer `runWithRequestContext`
52
+ * so the frame is automatically cleaned up.
53
+ */
54
+ declare function enterRequestContext(data: RequestContextData): void;
55
+ /**
56
+ * Clear the request context for the current async task. Pairs with
57
+ * `enterRequestContext`. After calling, `serviceContext.hasContext()` returns
58
+ * false for the remainder of the current async resource.
59
+ */
60
+ declare function exitRequestContext(): void;
42
61
  //# sourceMappingURL=context.d.ts.map
43
62
  //#endregion
44
- export { RequestContextData, runWithRequestContext, serviceContext };
45
- //# sourceMappingURL=context-DMExgNzl.d.mts.map
63
+ export { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
64
+ //# sourceMappingURL=context-OmKid3Mr.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-OmKid3Mr.d.mts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAiHA;AA0DgB,UA3KC,kBAAA,CA2KoB;EAAA,MAAA,EA1K5B,MA0K4B;EAAA,SAC9B,EAAA,MAAA;EAAkB,SACd,EAAA,MAAA;;;;;;AACG;AAgBE,cA7EH,cA6EsB,EA7EN,cA6Ea;AAS1C;;;;;;;;;;;;;;;;;;;;iBA5BgB,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;iBAgBC,mBAAA,OAA0B;;;;;;iBAS1B,kBAAA,CAAA"}
package/dist/context.cjs CHANGED
@@ -1,4 +1,6 @@
1
- const require_context = require('./context-DUTDtYd2.cjs');
1
+ const require_context = require('./context-CkCPt2Fe.cjs');
2
2
 
3
+ exports.enterRequestContext = require_context.enterRequestContext;
4
+ exports.exitRequestContext = require_context.exitRequestContext;
3
5
  exports.runWithRequestContext = require_context.runWithRequestContext;
4
6
  exports.serviceContext = require_context.serviceContext;
@@ -1,3 +1,3 @@
1
- import "./types-D7d_yeU5.cjs";
2
- import { RequestContextData, runWithRequestContext, serviceContext } from "./context-BVeZOvOd.cjs";
3
- export { RequestContextData, runWithRequestContext, serviceContext };
1
+ import "./types-BY9yrY6Y.cjs";
2
+ import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-D5pIUGkm.cjs";
3
+ export { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
@@ -1,3 +1,3 @@
1
- import "./types-CcHmCx_U.mjs";
2
- import { RequestContextData, runWithRequestContext, serviceContext } from "./context-DMExgNzl.mjs";
3
- export { RequestContextData, runWithRequestContext, serviceContext };
1
+ import "./types-B99KrvXR.mjs";
2
+ import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-OmKid3Mr.mjs";
3
+ export { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
package/dist/context.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { runWithRequestContext, serviceContext } from "./context-B5YTspJR.mjs";
1
+ import { enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-BojeLlxs.mjs";
2
2
 
3
- export { runWithRequestContext, serviceContext };
3
+ export { enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
package/dist/index.cjs CHANGED
@@ -1,6 +1,8 @@
1
- const require_context = require('./context-DUTDtYd2.cjs');
2
- const require_ServiceDiscovery = require('./ServiceDiscovery-YeM2FZsl.cjs');
1
+ const require_context = require('./context-CkCPt2Fe.cjs');
2
+ const require_ServiceDiscovery = require('./ServiceDiscovery-Cxus7ber.cjs');
3
3
 
4
4
  exports.ServiceDiscovery = require_ServiceDiscovery.ServiceDiscovery;
5
+ exports.enterRequestContext = require_context.enterRequestContext;
6
+ exports.exitRequestContext = require_context.exitRequestContext;
5
7
  exports.runWithRequestContext = require_context.runWithRequestContext;
6
8
  exports.serviceContext = require_context.serviceContext;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-D7d_yeU5.cjs";
2
- import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-Dvqa-Q1_.cjs";
3
- import { RequestContextData, runWithRequestContext, serviceContext } from "./context-BVeZOvOd.cjs";
4
- export { ExtractServiceNames, RequestContextData, Service, ServiceContext, ServiceDiscovery, ServiceRecord, ServiceRegisterOptions, runWithRequestContext, serviceContext };
1
+ import { Service, ServiceContext, ServiceRegisterOptions } from "./types-BY9yrY6Y.cjs";
2
+ import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-DF4OKEZp.cjs";
3
+ import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-D5pIUGkm.cjs";
4
+ export { ExtractServiceNames, RequestContextData, Service, ServiceContext, ServiceDiscovery, ServiceRecord, ServiceRegisterOptions, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-CcHmCx_U.mjs";
2
- import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-ykolgkIj.mjs";
3
- import { RequestContextData, runWithRequestContext, serviceContext } from "./context-DMExgNzl.mjs";
4
- export { ExtractServiceNames, RequestContextData, Service, ServiceContext, ServiceDiscovery, ServiceRecord, ServiceRegisterOptions, runWithRequestContext, serviceContext };
1
+ import { Service, ServiceContext, ServiceRegisterOptions } from "./types-B99KrvXR.mjs";
2
+ import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-CadEgTKz.mjs";
3
+ import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-OmKid3Mr.mjs";
4
+ export { ExtractServiceNames, RequestContextData, Service, ServiceContext, ServiceDiscovery, ServiceRecord, ServiceRegisterOptions, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { runWithRequestContext, serviceContext } from "./context-B5YTspJR.mjs";
2
- import { ServiceDiscovery } from "./ServiceDiscovery-BQ45ZFgI.mjs";
1
+ import { enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-BojeLlxs.mjs";
2
+ import { ServiceDiscovery } from "./ServiceDiscovery-SujDuYHr.mjs";
3
3
 
4
- export { ServiceDiscovery, runWithRequestContext, serviceContext };
4
+ export { ServiceDiscovery, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
@@ -11,6 +11,13 @@ import { Logger } from "@geekmidas/logger";
11
11
  interface ServiceContext {
12
12
  /**
13
13
  * Get the current request's logger.
14
+ *
15
+ * Returns a **request-scoped proxy** that re-resolves the underlying logger
16
+ * from AsyncLocalStorage on every call. This makes it safe for a singleton
17
+ * service to capture the logger once (e.g. during `register()`) and reuse it
18
+ * across requests — each log call routes to the current request's logger
19
+ * instead of freezing the first request's logger.
20
+ *
14
21
  * @throws Error if called outside a request context
15
22
  */
16
23
  getLogger(): Logger;
@@ -83,4 +90,4 @@ interface Service<TName extends string = string, TInstance = unknown> {
83
90
  //# sourceMappingURL=types.d.ts.map
84
91
  //#endregion
85
92
  export { Service, ServiceContext, ServiceRegisterOptions };
86
- //# sourceMappingURL=types-CcHmCx_U.d.mts.map
93
+ //# sourceMappingURL=types-B99KrvXR.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-B99KrvXR.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAqCA;;AAEY,UAvCK,cAAA,CAuCL;EAAiB;AAEL;AA8BxB;;;;;;;AAW+D;;eAtEjD;;;;;;;;;;;;;;;;;;;;;UAyBG,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}
@@ -11,6 +11,13 @@ import { Logger } from "@geekmidas/logger";
11
11
  interface ServiceContext {
12
12
  /**
13
13
  * Get the current request's logger.
14
+ *
15
+ * Returns a **request-scoped proxy** that re-resolves the underlying logger
16
+ * from AsyncLocalStorage on every call. This makes it safe for a singleton
17
+ * service to capture the logger once (e.g. during `register()`) and reuse it
18
+ * across requests — each log call routes to the current request's logger
19
+ * instead of freezing the first request's logger.
20
+ *
14
21
  * @throws Error if called outside a request context
15
22
  */
16
23
  getLogger(): Logger;
@@ -83,4 +90,4 @@ interface Service<TName extends string = string, TInstance = unknown> {
83
90
  //# sourceMappingURL=types.d.ts.map
84
91
  //#endregion
85
92
  export { Service, ServiceContext, ServiceRegisterOptions };
86
- //# sourceMappingURL=types-D7d_yeU5.d.cts.map
93
+ //# sourceMappingURL=types-BY9yrY6Y.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-BY9yrY6Y.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAqCA;;AAEY,UAvCK,cAAA,CAuCL;EAAiB;AAEL;AA8BxB;;;;;;;AAW+D;;eAtEjD;;;;;;;;;;;;;;;;;;;;;UAyBG,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}
package/dist/types.d.cts CHANGED
@@ -1,2 +1,2 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-D7d_yeU5.cjs";
1
+ import { Service, ServiceContext, ServiceRegisterOptions } from "./types-BY9yrY6Y.cjs";
2
2
  export { Service, ServiceContext, ServiceRegisterOptions };
package/dist/types.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-CcHmCx_U.mjs";
1
+ import { Service, ServiceContext, ServiceRegisterOptions } from "./types-B99KrvXR.mjs";
2
2
  export { Service, ServiceContext, ServiceRegisterOptions };
@@ -0,0 +1,153 @@
1
+ # Request-Scoped Logging in Singleton Services
2
+
3
+ ## Problem
4
+
5
+ Services in `@geekmidas/services` are **singletons**. `ServiceDiscovery.register()`
6
+ (and `get()`) instantiates a service **once**, caches the instance in an internal
7
+ `Map`, and returns that same instance for every subsequent request:
8
+
9
+ ```ts
10
+ // ServiceDiscovery.register()
11
+ if (this.instances.has(name)) {
12
+ return this.instances.get(name); // cached — register() does NOT run again
13
+ }
14
+ const instance = await service.register({ envParser, context: serviceContext });
15
+ this.instances.set(name, instance);
16
+ ```
17
+
18
+ The per-request logger, on the other hand, is **not** a singleton. On every request
19
+ an adaptor builds a fresh child logger with request-specific bindings and stores it
20
+ in `AsyncLocalStorage` via `runWithRequestContext`:
21
+
22
+ ```ts
23
+ // e.g. HonoEndpointAdaptor
24
+ const logger = endpoint.logger.child({
25
+ requestId, // unique per request
26
+ endpoint, route, host, method, path,
27
+ });
28
+
29
+ return runWithRequestContext({ logger, requestId, startTime }, async () => {
30
+ const services = await serviceDiscovery.register(endpoint.services);
31
+ // ...handle request...
32
+ });
33
+ ```
34
+
35
+ ### The bug
36
+
37
+ `service.register()` runs **inside the first request's context**. If a service reads
38
+ the logger **at registration time** and stores the concrete reference:
39
+
40
+ ```ts
41
+ const databaseService = {
42
+ serviceName: 'database' as const,
43
+ register({ context }) {
44
+ const logger = context.getLogger(); // ❌ resolved ONCE, during request #1
45
+
46
+ return {
47
+ async query(sql: string) {
48
+ logger.debug({ sql }, 'Executing query'); // always request #1's logger
49
+ },
50
+ };
51
+ },
52
+ } satisfies Service<'database', Database>;
53
+ ```
54
+
55
+ …then `logger` is frozen to the **first** request's logger forever, because
56
+ `register()` never runs again. Every later request reuses the cached service
57
+ instance, so its logs carry the **first** request's `requestId` (and any user/session
58
+ bindings).
59
+
60
+ **Symptom:** logs make it look like the user who made the *first* request after a
61
+ cold start is responsible for actions actually performed by *other* users on later
62
+ requests. Request correlation, per-user log filtering, and audit trails are all
63
+ silently wrong.
64
+
65
+ This is an easy mistake to make because `register()` is handed a `context` object,
66
+ and "grab the logger once and reuse it" looks reasonable — but it is incompatible
67
+ with the singleton lifecycle.
68
+
69
+ ## Solution
70
+
71
+ `serviceContext.getLogger()` returns a **stable, request-scoped proxy logger**
72
+ instead of the raw logger. The proxy holds no logger of its own — on **every** log
73
+ call it re-resolves the current request's logger from `AsyncLocalStorage`:
74
+
75
+ ```
76
+ proxy.info('x') → asyncLocalStorage.getStore().logger.info('x') // resolved at call time
77
+ ```
78
+
79
+ Because resolution happens per call (not at capture time), capturing the logger once
80
+ during `register()` is now **safe**: the single captured reference routes each call
81
+ to whichever request is currently executing.
82
+
83
+ ```ts
84
+ register({ context }) {
85
+ const logger = context.getLogger(); // ✅ now safe to capture — it's a live proxy
86
+
87
+ return {
88
+ async query(sql: string) {
89
+ logger.debug({ sql }, 'Executing query'); // logs to the CURRENT request
90
+ },
91
+ };
92
+ }
93
+ ```
94
+
95
+ ### Child loggers compose correctly too
96
+
97
+ `proxy.child(bindings)` returns **another** proxy carrying the bindings, applied lazily
98
+ on top of the current request's logger at call time:
99
+
100
+ ```ts
101
+ register({ context }) {
102
+ // Captured once. `{ svc: 'db' }` is the static part; the per-request bindings
103
+ // (requestId, user, ...) come from whichever base logger is current.
104
+ const logger = context.getLogger().child({ svc: 'db' });
105
+
106
+ return {
107
+ async query(sql: string) {
108
+ // request A → loggerA.child({ svc: 'db' }).debug(...)
109
+ // request B → loggerB.child({ svc: 'db' }).debug(...)
110
+ logger.debug({ sql }, 'Executing query');
111
+ },
112
+ };
113
+ }
114
+ ```
115
+
116
+ ### Implementation
117
+
118
+ See `createRequestScopedLogger` in
119
+ [`src/context.ts`](../src/context.ts):
120
+
121
+ - `getLogger()` still **throws eagerly** if called with no active request context,
122
+ preserving the "catch bugs early" contract.
123
+ - The returned object is a shared, process-wide proxy. It carries no request state,
124
+ so sharing it across requests is safe — `AsyncLocalStorage` provides correct
125
+ per-async-context isolation, and each resolve/log call is synchronous (no `await`
126
+ between resolving and using the logger), so it is concurrency-safe.
127
+ - Each `child()` call returns a new proxy that remembers its bindings and rebuilds
128
+ the child chain off the current base logger, memoised per underlying logger to
129
+ avoid rebuilding the chain on every log line.
130
+
131
+ ## Guidance for service authors
132
+
133
+ - ✅ You **may** capture `context.getLogger()` (or a `.child()` of it) once in
134
+ `register()` and reuse it — it stays correct per request.
135
+ - ✅ You **may** also call `context.getLogger()` inside each method; behaviour is
136
+ identical.
137
+ - ⚠️ Do **not** wrap the proxy in something that snapshots a concrete logger, e.g.
138
+ `const real = someConcreteLogger; ...` outside the proxy. Resolution only stays
139
+ live while you go through the proxy returned by `getLogger()`/`.child()`.
140
+ - ⚠️ Calling a log method outside any request context throws
141
+ (`called outside request context`). Guard background work with
142
+ `serviceContext.hasContext()` if it may run detached from a request.
143
+
144
+ ## Tests
145
+
146
+ Regression coverage lives in
147
+ [`src/__tests__/context.spec.ts`](../src/__tests__/context.spec.ts):
148
+
149
+ - `captured-once logger follows each request (singleton service fix)` — a logger
150
+ captured during the first request still logs to the second request's logger.
151
+ - `child loggers also follow the current request` — the same guarantee for
152
+ `.child()` proxies.
153
+ - `should delegate to the current request logger` — basic delegation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geekmidas/services",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,7 +1,40 @@
1
+ import type { Logger } from '@geekmidas/logger';
1
2
  import { ConsoleLogger } from '@geekmidas/logger/console';
2
- import { describe, expect, it } from 'vitest';
3
+ import { describe, expect, it, vi } from 'vitest';
3
4
  import { runWithRequestContext, serviceContext } from '../context';
4
5
 
6
+ /** Minimal spy logger whose `child()` returns itself for easy assertions. */
7
+ function makeSpyLogger(): Logger {
8
+ const logger: Logger = {
9
+ trace: vi.fn(),
10
+ debug: vi.fn(),
11
+ info: vi.fn(),
12
+ warn: vi.fn(),
13
+ error: vi.fn(),
14
+ fatal: vi.fn(),
15
+ child: vi.fn(() => logger),
16
+ };
17
+ return logger;
18
+ }
19
+
20
+ /**
21
+ * A logger that carries MORE than the base `Logger` interface: an extra method
22
+ * (`flush`) and a data property (`level`). Models a richer real-world logger
23
+ * (e.g. pino) so we can assert the request-scoped proxy forwards the full
24
+ * surface, not just the known log methods.
25
+ */
26
+ type ExtendedLogger = Logger & {
27
+ flush: ReturnType<typeof vi.fn>;
28
+ level: string;
29
+ };
30
+
31
+ function makeExtendedSpyLogger(level = 'info'): ExtendedLogger {
32
+ const logger = makeSpyLogger() as ExtendedLogger;
33
+ logger.flush = vi.fn();
34
+ logger.level = level;
35
+ return logger;
36
+ }
37
+
5
38
  describe('Request Context', () => {
6
39
  const logger = new ConsoleLogger({ app: 'test' });
7
40
 
@@ -28,13 +61,156 @@ describe('Request Context', () => {
28
61
  );
29
62
  });
30
63
 
31
- it('should return logger inside request context', async () => {
64
+ it('should delegate to the current request logger', async () => {
65
+ const requestLogger = makeSpyLogger();
32
66
  await runWithRequestContext(
33
- { logger, requestId: 'test-id', startTime: Date.now() },
67
+ {
68
+ logger: requestLogger,
69
+ requestId: 'test-id',
70
+ startTime: Date.now(),
71
+ },
34
72
  async () => {
35
- expect(serviceContext.getLogger()).toBe(logger);
73
+ serviceContext.getLogger().info('hello');
36
74
  },
37
75
  );
76
+ expect(requestLogger.info).toHaveBeenCalledWith('hello');
77
+ });
78
+
79
+ it('captured-once logger follows each request (singleton service fix)', async () => {
80
+ // Mimic a singleton service that grabs the logger ONCE (during its
81
+ // one-time register) and reuses that reference for every request.
82
+ let captured: Logger | undefined;
83
+ const handle = (requestLogger: Logger) =>
84
+ runWithRequestContext(
85
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
86
+ async () => {
87
+ captured ??= serviceContext.getLogger();
88
+ captured.info('handled');
89
+ },
90
+ );
91
+
92
+ const first = makeSpyLogger();
93
+ const second = makeSpyLogger();
94
+ await handle(first);
95
+ await handle(second);
96
+
97
+ // Before the fix, the captured logger stayed bound to `first`, so
98
+ // `second` never saw the call.
99
+ expect(first.info).toHaveBeenCalledTimes(1);
100
+ expect(second.info).toHaveBeenCalledTimes(1);
101
+ });
102
+
103
+ it('child loggers also follow the current request', async () => {
104
+ let capturedChild: Logger | undefined;
105
+ const handle = (requestLogger: Logger) =>
106
+ runWithRequestContext(
107
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
108
+ async () => {
109
+ capturedChild ??= serviceContext
110
+ .getLogger()
111
+ .child({ scope: 'svc' });
112
+ capturedChild.info('scoped');
113
+ },
114
+ );
115
+
116
+ const first = makeSpyLogger();
117
+ const second = makeSpyLogger();
118
+ await handle(first);
119
+ await handle(second);
120
+
121
+ expect(first.child).toHaveBeenCalledWith({ scope: 'svc' });
122
+ expect(second.child).toHaveBeenCalledWith({ scope: 'svc' });
123
+ expect(first.info).toHaveBeenCalledWith('scoped');
124
+ expect(second.info).toHaveBeenCalledWith('scoped');
125
+ });
126
+
127
+ describe('forwards the full logger surface (logger with more)', () => {
128
+ it('forwards an extra method beyond the Logger interface', async () => {
129
+ const requestLogger = makeExtendedSpyLogger();
130
+ await runWithRequestContext(
131
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
132
+ async () => {
133
+ (serviceContext.getLogger() as ExtendedLogger).flush();
134
+ },
135
+ );
136
+ expect(requestLogger.flush).toHaveBeenCalledTimes(1);
137
+ });
138
+
139
+ it('re-resolves an extra method per request when captured once', async () => {
140
+ let captured: ExtendedLogger | undefined;
141
+ const handle = (requestLogger: Logger) =>
142
+ runWithRequestContext(
143
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
144
+ async () => {
145
+ captured ??= serviceContext.getLogger() as ExtendedLogger;
146
+ captured.flush();
147
+ },
148
+ );
149
+
150
+ const first = makeExtendedSpyLogger();
151
+ const second = makeExtendedSpyLogger();
152
+ await handle(first);
153
+ await handle(second);
154
+
155
+ expect(first.flush).toHaveBeenCalledTimes(1);
156
+ expect(second.flush).toHaveBeenCalledTimes(1);
157
+ });
158
+
159
+ it('forwards a data property as the current request logger value', async () => {
160
+ const captureLevel = (requestLogger: Logger) =>
161
+ runWithRequestContext(
162
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
163
+ async () => (serviceContext.getLogger() as ExtendedLogger).level,
164
+ );
165
+
166
+ const debugLogger = makeExtendedSpyLogger('debug');
167
+ const warnLogger = makeExtendedSpyLogger('warn');
168
+
169
+ expect(await captureLevel(debugLogger)).toBe('debug');
170
+ expect(await captureLevel(warnLogger)).toBe('warn');
171
+ });
172
+
173
+ it('detached method reference still targets the current request', async () => {
174
+ const requestLogger = makeExtendedSpyLogger();
175
+ await runWithRequestContext(
176
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
177
+ async () => {
178
+ const { info } = serviceContext.getLogger();
179
+ info('detached');
180
+ },
181
+ );
182
+ expect(requestLogger.info).toHaveBeenCalledWith('detached');
183
+ });
184
+
185
+ it('reflects underlying membership via the `in` operator', async () => {
186
+ const requestLogger = makeExtendedSpyLogger();
187
+ await runWithRequestContext(
188
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
189
+ async () => {
190
+ const proxy = serviceContext.getLogger();
191
+ expect('flush' in proxy).toBe(true);
192
+ expect('child' in proxy).toBe(true);
193
+ expect('nope' in proxy).toBe(false);
194
+ },
195
+ );
196
+ });
197
+
198
+ it('is not thenable (safe to return from async / await)', async () => {
199
+ await runWithRequestContext(
200
+ {
201
+ logger: makeExtendedSpyLogger(),
202
+ requestId: 'r',
203
+ startTime: Date.now(),
204
+ },
205
+ async () => {
206
+ const proxy = serviceContext.getLogger();
207
+ expect((proxy as { then?: unknown }).then).toBeUndefined();
208
+ // Awaiting a non-thenable yields the value itself rather than
209
+ // hanging or invoking a spurious `then`.
210
+ expect(await proxy).toBe(proxy);
211
+ },
212
+ );
213
+ });
38
214
  });
39
215
  });
40
216