@geekmidas/services 1.0.3 → 1.1.0

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 (70) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +24 -0
  3. package/dist/{ServiceDiscovery-ykolgkIj.d.mts → ServiceDiscovery-BO8W-RY8.d.cts} +2 -2
  4. package/dist/{ServiceDiscovery-ykolgkIj.d.mts.map → ServiceDiscovery-BO8W-RY8.d.cts.map} +1 -1
  5. package/dist/{ServiceDiscovery-Dvqa-Q1_.d.cts → ServiceDiscovery-CRq_bGbi.d.mts} +2 -2
  6. package/dist/{ServiceDiscovery-Dvqa-Q1_.d.cts.map → ServiceDiscovery-CRq_bGbi.d.mts.map} +1 -1
  7. package/dist/{ServiceDiscovery-tZ6VKHIZ.mjs → ServiceDiscovery-DO_uDfuG.mjs} +2 -2
  8. package/dist/{ServiceDiscovery-tZ6VKHIZ.mjs.map → ServiceDiscovery-DO_uDfuG.mjs.map} +1 -1
  9. package/dist/{ServiceDiscovery-C5x1wcN1.cjs → ServiceDiscovery-m3XkNh32.cjs} +2 -2
  10. package/dist/{ServiceDiscovery-C5x1wcN1.cjs.map → ServiceDiscovery-m3XkNh32.cjs.map} +1 -1
  11. package/dist/{context-BpYagzpr.mjs → context-C9DCrFWA.mjs} +64 -4
  12. package/dist/context-C9DCrFWA.mjs.map +1 -0
  13. package/dist/{context-CaeISj3o.d.cts → context-CU-87vsM.d.mts} +2 -2
  14. package/dist/context-CU-87vsM.d.mts.map +1 -0
  15. package/dist/{context-CoyHq8lH.cjs → context-Cf2Ig5qr.cjs} +70 -4
  16. package/dist/context-Cf2Ig5qr.cjs.map +1 -0
  17. package/dist/{context-HGC2PJzv.d.mts → context-D2owD3ac.d.cts} +2 -2
  18. package/dist/context-D2owD3ac.d.cts.map +1 -0
  19. package/dist/context.cjs +1 -1
  20. package/dist/context.d.cts +2 -2
  21. package/dist/context.d.mts +2 -2
  22. package/dist/context.mjs +1 -1
  23. package/dist/index.cjs +2 -2
  24. package/dist/index.d.cts +3 -3
  25. package/dist/index.d.mts +3 -3
  26. package/dist/index.mjs +2 -2
  27. package/dist/middy.cjs +120 -0
  28. package/dist/middy.cjs.map +1 -0
  29. package/dist/middy.d.cts +146 -0
  30. package/dist/middy.d.cts.map +1 -0
  31. package/dist/middy.d.mts +146 -0
  32. package/dist/middy.d.mts.map +1 -0
  33. package/dist/middy.mjs +118 -0
  34. package/dist/middy.mjs.map +1 -0
  35. package/dist/trpc.cjs +66 -0
  36. package/dist/trpc.cjs.map +1 -0
  37. package/dist/trpc.d.cts +86 -0
  38. package/dist/trpc.d.cts.map +1 -0
  39. package/dist/trpc.d.mts +86 -0
  40. package/dist/trpc.d.mts.map +1 -0
  41. package/dist/trpc.mjs +65 -0
  42. package/dist/trpc.mjs.map +1 -0
  43. package/dist/{types-CcHmCx_U.d.mts → types-Bgk-0NOO.d.cts} +9 -2
  44. package/dist/types-Bgk-0NOO.d.cts.map +1 -0
  45. package/dist/{types-D7d_yeU5.d.cts → types-BoyOCa57.d.mts} +9 -2
  46. package/dist/types-BoyOCa57.d.mts.map +1 -0
  47. package/docs/request-scoped-logging.md +167 -0
  48. package/package.json +37 -1
  49. package/src/__tests__/context.spec.ts +180 -4
  50. package/src/__tests__/middy.spec.ts +218 -0
  51. package/src/__tests__/trpc.spec.ts +218 -0
  52. package/src/context.ts +104 -8
  53. package/src/middy.ts +226 -0
  54. package/src/trpc.ts +190 -0
  55. package/src/types.ts +7 -0
  56. package/tsdown.config.ts +11 -1
  57. package/dist/ServiceDiscovery.cjs +0 -4
  58. package/dist/ServiceDiscovery.d.cts +0 -3
  59. package/dist/ServiceDiscovery.d.mts +0 -3
  60. package/dist/ServiceDiscovery.mjs +0 -4
  61. package/dist/context-BpYagzpr.mjs.map +0 -1
  62. package/dist/context-CaeISj3o.d.cts.map +0 -1
  63. package/dist/context-CoyHq8lH.cjs.map +0 -1
  64. package/dist/context-HGC2PJzv.d.mts.map +0 -1
  65. package/dist/types-CcHmCx_U.d.mts.map +0 -1
  66. package/dist/types-D7d_yeU5.d.cts.map +0 -1
  67. package/dist/types.cjs +0 -0
  68. package/dist/types.d.cts +0 -2
  69. package/dist/types.d.mts +0 -2
  70. package/dist/types.mjs +0 -0
package/src/context.ts CHANGED
@@ -19,6 +19,103 @@ 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 unknown 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
+ const fn = (resolve() as unknown as Record<string, unknown>)[
96
+ prop
97
+ ] as (...a: unknown[]) => unknown;
98
+ return fn(...args);
99
+ }
100
+ : value;
101
+ },
102
+ // Keep `'prop' in logger` / hasOwnProperty truthful against the underlying
103
+ // logger so feature-detection works.
104
+ has(_target, prop) {
105
+ if (prop === 'child') return true;
106
+ if (prop === 'then' || typeof prop === 'symbol') return false;
107
+ return prop in (resolve() as object);
108
+ },
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Stable, process-wide request-scoped logger proxy. Shared across requests on
114
+ * purpose — it carries no request state itself, delegating to the current
115
+ * `AsyncLocalStorage` store on each call.
116
+ */
117
+ const requestScopedLogger = createRequestScopedLogger();
118
+
22
119
  /**
23
120
  * ServiceContext implementation.
24
121
  * Singleton that reads from AsyncLocalStorage.
@@ -26,14 +123,13 @@ const requestContextStorage = new AsyncLocalStorage<RequestContextData>();
26
123
  */
27
124
  export const serviceContext: ServiceContext = {
28
125
  getLogger() {
29
- const store = requestContextStorage.getStore();
30
- if (!store) {
31
- throw new Error(
32
- 'ServiceContext.getLogger() called outside request context. ' +
33
- 'Ensure code runs within runWithRequestContext().',
34
- );
35
- }
36
- return store.logger;
126
+ // Throw eagerly if there is no context, preserving the "catch bugs early"
127
+ // contract for callers that read the logger at an unexpected time.
128
+ resolveRequestLogger();
129
+ // Return the shared proxy rather than the raw `store.logger`. A service
130
+ // that captures this once still logs against the correct per-request
131
+ // logger because the proxy re-resolves on every call.
132
+ return requestScopedLogger;
37
133
  },
38
134
 
39
135
  getRequestId() {
package/src/middy.ts ADDED
@@ -0,0 +1,226 @@
1
+ import type { EnvironmentParser } from '@geekmidas/envkit';
2
+ import type { Logger } from '@geekmidas/logger';
3
+ import type { MiddlewareObj } from '@middy/core';
4
+ import type { Context } from 'aws-lambda';
5
+ import { enterRequestContext, exitRequestContext } from './context';
6
+ import { ServiceDiscovery, type ServiceRecord } from './ServiceDiscovery';
7
+ import type { Service } from './types';
8
+
9
+ /**
10
+ * Middy middleware helpers that bring `@geekmidas/services` request context and
11
+ * service discovery to **standalone** Middy Lambda handlers — i.e. functions
12
+ * that aren't built with the `@geekmidas/constructs` Function/Cron constructs
13
+ * but still want `serviceContext.getLogger()` and resolved services.
14
+ *
15
+ * Why middleware (and not `runWithRequestContext`)? Middy runs `before → handler
16
+ * → after` as sequential awaits in a single async context, so establishing the
17
+ * context with `AsyncLocalStorage.enterWith` (via `enterRequestContext`) in a
18
+ * `before` hook propagates to the handler. `after`/`onError` reset it.
19
+ *
20
+ * Teardown is best-effort: like `enterRequestContext`, the reset is observable
21
+ * to code the handler reaches but not necessarily to the frame that invoked the
22
+ * Middy handler. This is fine for Lambda, where each invocation runs in its own
23
+ * fresh async context — `requestContext` always establishes a brand-new context
24
+ * per invocation, so requests never inherit a previous invocation's logger.
25
+ *
26
+ * @module
27
+ */
28
+
29
+ /**
30
+ * Options for {@link requestContext}. Generic over the logger type so a custom
31
+ * logger that extends {@link Logger} is preserved rather than widened.
32
+ */
33
+ export interface RequestContextOptions<TLogger extends Logger = Logger> {
34
+ /**
35
+ * Logger to derive the per-request child logger from. Required — the caller
36
+ * decides which logger to use (there is no implicit default).
37
+ */
38
+ logger: TLogger;
39
+ /**
40
+ * Derive the request id from the event/context.
41
+ * Defaults to `context.awsRequestId` (always present in a Lambda invocation).
42
+ */
43
+ getRequestId?: (event: unknown, context: Context) => string;
44
+ /**
45
+ * Extra bindings to attach to the per-request child logger.
46
+ */
47
+ bindings?: (event: unknown, context: Context) => Record<string, unknown>;
48
+ }
49
+
50
+ /**
51
+ * Options for {@link addServices} — how services are resolved. No logger is
52
+ * needed because resolving services doesn't establish a request context.
53
+ */
54
+ export interface ServiceResolverOptions {
55
+ /**
56
+ * Environment parser used to build the {@link ServiceDiscovery}. Required —
57
+ * the caller supplies the parser (there is no implicit `process.env` default).
58
+ */
59
+ envParser: EnvironmentParser<{}>;
60
+ /**
61
+ * Explicit {@link ServiceDiscovery} to resolve services from. Takes
62
+ * precedence over `envParser`.
63
+ */
64
+ serviceDiscovery?: ServiceDiscovery;
65
+ }
66
+
67
+ /**
68
+ * Options for {@link withServices}: request context (logger) + service resolution.
69
+ */
70
+ export type ServiceMiddlewareOptions<TLogger extends Logger = Logger> =
71
+ RequestContextOptions<TLogger> & ServiceResolverOptions;
72
+
73
+ function deriveRequestId(
74
+ options: RequestContextOptions,
75
+ event: unknown,
76
+ context: Context,
77
+ ): string {
78
+ // Lambda always populates context.awsRequestId; getRequestId can override it.
79
+ return options.getRequestId?.(event, context) ?? context.awsRequestId;
80
+ }
81
+
82
+ function buildLogger(
83
+ baseLogger: Logger,
84
+ options: RequestContextOptions,
85
+ requestId: string,
86
+ event: unknown,
87
+ context: Context,
88
+ ): Logger {
89
+ return baseLogger.child({
90
+ requestId,
91
+ ...(options.bindings?.(event, context) ?? {}),
92
+ });
93
+ }
94
+
95
+ /**
96
+ * Middy middleware that establishes a request context for the handler so any
97
+ * code it reaches — including `@geekmidas/services` service methods — can call
98
+ * `serviceContext.getLogger()` / `getRequestId()` / `getRequestStartTime()`.
99
+ *
100
+ * Use this on standalone functions that need request-scoped logging. To also
101
+ * resolve services, pair it with {@link addServices}, or use
102
+ * {@link withServices} which bundles both.
103
+ *
104
+ * @example
105
+ * ```ts
106
+ * import middy from '@middy/core';
107
+ * import { serviceContext } from '@geekmidas/services';
108
+ * import { requestContext } from '@geekmidas/services/middy';
109
+ *
110
+ * export const handler = middy(async () => {
111
+ * serviceContext.getLogger().info('tick');
112
+ * }).use(requestContext({ logger }));
113
+ * ```
114
+ */
115
+ export function requestContext<TLogger extends Logger = Logger>(
116
+ options: RequestContextOptions<TLogger>,
117
+ ): MiddlewareObj<unknown, unknown, Error, Context> {
118
+ const baseLogger = options.logger;
119
+ return {
120
+ before: (request) => {
121
+ const { event, context } = request;
122
+ const requestId = deriveRequestId(options, event, context);
123
+ const logger = buildLogger(
124
+ baseLogger,
125
+ options,
126
+ requestId,
127
+ event,
128
+ context,
129
+ );
130
+ enterRequestContext({ logger, requestId, startTime: Date.now() });
131
+ },
132
+ after: () => {
133
+ exitRequestContext();
134
+ },
135
+ onError: () => {
136
+ exitRequestContext();
137
+ },
138
+ };
139
+ }
140
+
141
+ function resolveDiscovery(options: ServiceResolverOptions): ServiceDiscovery {
142
+ return (
143
+ options.serviceDiscovery ?? ServiceDiscovery.getInstance(options.envParser)
144
+ );
145
+ }
146
+
147
+ /**
148
+ * Event augmentation applied by {@link addServices} / {@link withServices}:
149
+ * resolved services keyed by `serviceName`. Intersect it with your own event
150
+ * type to type the handler, e.g. `(event: EventServices<T> & APIGatewayEvent)`.
151
+ */
152
+ export type EventServices<T extends Service[]> = {
153
+ services: ServiceRecord<T>;
154
+ };
155
+
156
+ /**
157
+ * Middy middleware that resolves an array of {@link Service}s via
158
+ * {@link ServiceDiscovery} and attaches the resolved record to `event.services`
159
+ * (keyed by each service's `serviceName`), matching how the `Function`/`Cron`
160
+ * constructs expose services on the event.
161
+ *
162
+ * This middleware only resolves services; it does **not** establish a request
163
+ * context. If your services read `serviceContext` (e.g. `getLogger()`), pair it
164
+ * with {@link requestContext}, or use {@link withServices} which bundles both.
165
+ *
166
+ * Chainable — `.use(addServices([a])).use(addServices([b]))` accumulates onto
167
+ * `event.services`.
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * import middy from '@middy/core';
172
+ * import { addServices, requestContext } from '@geekmidas/services/middy';
173
+ *
174
+ * export const handler = middy(async (event) => {
175
+ * await event.services.database.users.deletePast();
176
+ * event.services.cache.clear();
177
+ * })
178
+ * .use(requestContext())
179
+ * .use(addServices([databaseService, cacheService], { envParser }));
180
+ * ```
181
+ */
182
+ export function addServices<const T extends Service[]>(
183
+ services: [...T],
184
+ options: ServiceResolverOptions,
185
+ ): MiddlewareObj<EventServices<T>, unknown, Error, Context> {
186
+ const discovery = resolveDiscovery(options);
187
+
188
+ return {
189
+ before: async (request) => {
190
+ const resolved = await discovery.register(services);
191
+ const event = request.event as { services?: Record<string, unknown> };
192
+ // Merge so chained addServices(...) calls accumulate on event.services.
193
+ event.services = { ...(event.services ?? {}), ...resolved };
194
+ },
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Batteries-included Middy setup for service-backed handlers: returns a pair of
200
+ * middlewares — {@link requestContext} followed by {@link addServices} — so a
201
+ * single `.use(withServices([...]))` gives the handler both a request context
202
+ * and the resolved services on `event.services`.
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * import middy from '@middy/core';
207
+ * import { withServices } from '@geekmidas/services/middy';
208
+ *
209
+ * export const handler = middy(async (event) => {
210
+ * await event.services.database.users.deletePast();
211
+ * event.services.cache.clear();
212
+ * }).use(withServices([databaseService, cacheService], { envParser }));
213
+ * ```
214
+ */
215
+ export function withServices<
216
+ const T extends Service[],
217
+ TLogger extends Logger = Logger,
218
+ >(
219
+ services: [...T],
220
+ options: ServiceMiddlewareOptions<TLogger>,
221
+ ): [
222
+ MiddlewareObj<unknown, unknown, Error, Context>,
223
+ MiddlewareObj<EventServices<T>, unknown, Error, Context>,
224
+ ] {
225
+ return [requestContext(options), addServices(services, options)];
226
+ }
package/src/trpc.ts ADDED
@@ -0,0 +1,190 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { EnvironmentParser } from '@geekmidas/envkit';
3
+ import type { Logger } from '@geekmidas/logger';
4
+ import type {
5
+ TRPCMiddlewareBuilder,
6
+ TRPCMiddlewareFunction,
7
+ } from '@trpc/server';
8
+ import { runWithRequestContext } from './context';
9
+ import { ServiceDiscovery, type ServiceRecord } from './ServiceDiscovery';
10
+ import type { Service } from './types';
11
+
12
+ /**
13
+ * Shape of `t.middleware` from `@trpc/server`. We accept this rather than the
14
+ * initialized `t` object so callers retain ownership of their tRPC instance
15
+ * (no double-initialization, no opinion on context/meta shape).
16
+ */
17
+ type CreateMiddleware<TContext, TMeta> = <$ContextOverrides>(
18
+ fn: TRPCMiddlewareFunction<
19
+ TContext,
20
+ TMeta,
21
+ object,
22
+ $ContextOverrides,
23
+ unknown
24
+ >,
25
+ ) => TRPCMiddlewareBuilder<TContext, TMeta, $ContextOverrides, unknown>;
26
+
27
+ /**
28
+ * Result of `createServicesMiddleware`: a function that accepts a service
29
+ * tuple and returns a tRPC middleware that merges resolved services onto the
30
+ * context.
31
+ */
32
+ export type ServicesMiddleware<
33
+ TContext extends object,
34
+ TMeta extends object,
35
+ > = <const T extends Service[]>(
36
+ services: [...T],
37
+ ) => TRPCMiddlewareBuilder<TContext, TMeta, ServiceRecord<T>, unknown>;
38
+
39
+ /**
40
+ * Context shape required by `createServicesMiddleware` overload 2.
41
+ * Procedures that pull services via context-stored discovery must expose it
42
+ * under `serviceDiscovery`.
43
+ */
44
+ export interface ContextWithServiceDiscovery {
45
+ serviceDiscovery: ServiceDiscovery;
46
+ }
47
+
48
+ /**
49
+ * Minimum context required for request-context propagation. `logger` must be
50
+ * present so services can call `serviceContext.getLogger()`. `requestId` and
51
+ * `startTime` are auto-generated if missing.
52
+ */
53
+ export interface ContextWithLogger {
54
+ logger: Logger;
55
+ requestId?: string;
56
+ startTime?: number;
57
+ }
58
+
59
+ /**
60
+ * Create a tRPC middleware that:
61
+ *
62
+ * 1. Resolves the requested services via `ServiceDiscovery`.
63
+ * 2. Wraps the downstream call in `runWithRequestContext` so any code reached
64
+ * by the procedure (including service method implementations) can read the
65
+ * current logger/request id via `serviceContext`.
66
+ * 3. Merges the resolved services onto the tRPC context so handlers can access
67
+ * them by service name (`ctx.database`, `ctx.cache`, ...).
68
+ *
69
+ * Two overloads:
70
+ * - Pass an `envParser` to create a per-request `ServiceDiscovery` instance.
71
+ * - Omit `envParser` to read `ctx.serviceDiscovery` from the tRPC context.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * import { initTRPC } from '@trpc/server';
76
+ * import { createServicesMiddleware } from '@geekmidas/services/trpc';
77
+ *
78
+ * const t = initTRPC.context<Context>().create();
79
+ * const withServices = createServicesMiddleware(t.middleware, envParser);
80
+ *
81
+ * export const authedProcedure = t.procedure.use(
82
+ * withServices([databaseService, cacheService]),
83
+ * );
84
+ * ```
85
+ */
86
+ export function createServicesMiddleware<
87
+ TContext extends ContextWithLogger & object,
88
+ TMeta extends object,
89
+ >(
90
+ mw: CreateMiddleware<TContext, TMeta>,
91
+ envParser: EnvironmentParser<{}>,
92
+ ): ServicesMiddleware<TContext, TMeta>;
93
+ export function createServicesMiddleware<
94
+ TContext extends ContextWithLogger & ContextWithServiceDiscovery & object,
95
+ TMeta extends object,
96
+ >(mw: CreateMiddleware<TContext, TMeta>): ServicesMiddleware<TContext, TMeta>;
97
+ export function createServicesMiddleware<
98
+ TContext extends ContextWithLogger & object,
99
+ TMeta extends object,
100
+ >(
101
+ mw: CreateMiddleware<TContext, TMeta>,
102
+ envParser?: EnvironmentParser<{}>,
103
+ ): ServicesMiddleware<TContext, TMeta> {
104
+ return (<const T extends Service[]>(services: [...T]) => {
105
+ const builder = mw(async (opts) => {
106
+ const ctx = opts.ctx as TContext & Partial<ContextWithServiceDiscovery>;
107
+
108
+ const discovery =
109
+ ctx.serviceDiscovery ??
110
+ ServiceDiscovery.getInstance(
111
+ envParser ??
112
+ (() => {
113
+ // Hit only if overload 2 was selected but ctx.serviceDiscovery is
114
+ // missing at runtime — surface the mistake immediately rather
115
+ // than letting an undefined env parser fail deep inside register.
116
+ throw new Error(
117
+ 'createServicesMiddleware: no `envParser` provided and ' +
118
+ '`ctx.serviceDiscovery` is missing. Pass an EnvironmentParser ' +
119
+ 'to createServicesMiddleware(), or attach a ServiceDiscovery ' +
120
+ 'instance to the tRPC context.',
121
+ );
122
+ })(),
123
+ );
124
+
125
+ const requestId = ctx.requestId ?? randomUUID();
126
+ const startTime = ctx.startTime ?? Date.now();
127
+
128
+ return runWithRequestContext(
129
+ { logger: ctx.logger, requestId, startTime },
130
+ async () => {
131
+ const resolved = await discovery.register(services);
132
+ return opts.next({
133
+ ctx: { ...opts.ctx, ...resolved } as typeof opts.ctx &
134
+ ServiceRecord<T>,
135
+ });
136
+ },
137
+ );
138
+ });
139
+
140
+ // Tag the inner middleware function with the requested services so external
141
+ // tooling (e.g. detect-procedures route generators) can introspect a
142
+ // procedure's service dependencies without re-executing middleware.
143
+ const middlewares = (
144
+ builder as unknown as { _middlewares?: Array<{ _services?: Service[] }> }
145
+ )._middlewares;
146
+ if (middlewares?.length) {
147
+ const last = middlewares[middlewares.length - 1];
148
+ if (last) last._services = services as unknown as Service[];
149
+ }
150
+
151
+ return builder as TRPCMiddlewareBuilder<
152
+ TContext,
153
+ TMeta,
154
+ ServiceRecord<T>,
155
+ unknown
156
+ >;
157
+ }) as ServicesMiddleware<TContext, TMeta>;
158
+ }
159
+
160
+ /**
161
+ * Create a tRPC middleware that establishes a request context for downstream
162
+ * code without resolving any services. Useful when services aren't needed on
163
+ * a procedure but the handler (or libraries it calls) still wants to read
164
+ * `serviceContext.getLogger()` / `getRequestId()` / `getRequestStartTime()`.
165
+ *
166
+ * `requestId` and `startTime` are pulled from the tRPC context when present,
167
+ * otherwise generated (`randomUUID()` and `Date.now()`).
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * const withRequestContext = createRequestContextMiddleware(t.middleware);
172
+ * export const baseProcedure = t.procedure.use(withRequestContext);
173
+ * ```
174
+ */
175
+ export function createRequestContextMiddleware<
176
+ TContext extends ContextWithLogger & object,
177
+ TMeta extends object,
178
+ >(
179
+ mw: CreateMiddleware<TContext, TMeta>,
180
+ ): TRPCMiddlewareBuilder<TContext, TMeta, object, unknown> {
181
+ return mw(async (opts) => {
182
+ const ctx = opts.ctx as TContext;
183
+ const requestId = ctx.requestId ?? randomUUID();
184
+ const startTime = ctx.startTime ?? Date.now();
185
+ return runWithRequestContext(
186
+ { logger: ctx.logger, requestId, startTime },
187
+ () => opts.next(),
188
+ );
189
+ });
190
+ }
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;
package/tsdown.config.ts CHANGED
@@ -1,3 +1,13 @@
1
1
  import { defineConfig } from 'tsdown';
2
2
 
3
- export default defineConfig({});
3
+ export default defineConfig({
4
+ entry: ['src/index.ts', 'src/context.ts', 'src/trpc.ts', 'src/middy.ts'],
5
+ clean: true,
6
+ outDir: 'dist',
7
+ format: ['cjs', 'esm'],
8
+ sourcemap: true,
9
+ dts: true,
10
+ outExtensions: (ctx) => ({
11
+ js: ctx.format === 'es' ? '.mjs' : '.cjs',
12
+ }),
13
+ });
@@ -1,4 +0,0 @@
1
- require('./context-CoyHq8lH.cjs');
2
- const require_ServiceDiscovery = require('./ServiceDiscovery-C5x1wcN1.cjs');
3
-
4
- exports.ServiceDiscovery = require_ServiceDiscovery.ServiceDiscovery;
@@ -1,3 +0,0 @@
1
- import "./types-D7d_yeU5.cjs";
2
- import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-Dvqa-Q1_.cjs";
3
- export { ExtractServiceNames, ServiceDiscovery, ServiceRecord };
@@ -1,3 +0,0 @@
1
- import "./types-CcHmCx_U.mjs";
2
- import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-ykolgkIj.mjs";
3
- export { ExtractServiceNames, ServiceDiscovery, ServiceRecord };
@@ -1,4 +0,0 @@
1
- import "./context-BpYagzpr.mjs";
2
- import { ServiceDiscovery } from "./ServiceDiscovery-tZ6VKHIZ.mjs";
3
-
4
- export { ServiceDiscovery };
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-BpYagzpr.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\n/**\n * Mutate the current async task's store so that subsequent code in this task\n * (and any descendants) sees the supplied request context.\n *\n * Unlike `runWithRequestContext`, this does not scope the context to a\n * callback — useful when the caller can't wrap a function, for example in a\n * Vitest fixture that suspends on `use()` and yields control to the test\n * runner before the test body executes.\n *\n * **Test setup only.** In production handlers, prefer `runWithRequestContext`\n * so the frame is automatically cleaned up.\n */\nexport function enterRequestContext(data: RequestContextData): void {\n\trequestContextStorage.enterWith(data);\n}\n\n/**\n * Clear the request context for the current async task. Pairs with\n * `enterRequestContext`. After calling, `serviceContext.hasContext()` returns\n * false for the remainder of the current async resource.\n */\nexport function exitRequestContext(): void {\n\t// AsyncLocalStorage<T>.enterWith requires T, but Node accepts undefined at\n\t// runtime — passing it resets getStore() back to undefined.\n\t(requestContextStorage as unknown as AsyncLocalStorage<unknown>).enterWith(\n\t\tundefined,\n\t);\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;;;;;;;;;;;;;AAcD,SAAgB,oBAAoBD,MAAgC;AACnE,uBAAsB,UAAU,KAAK;AACrC;;;;;;AAOD,SAAgB,qBAA2B;AAG1C,CAAC,sBAAgE,iBAEhE;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-CaeISj3o.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;AAgBE,cA9EH,cA8EsB,EA9EN,cA8Ea;AAS1C;;;;;;;;;;;;;;;;;;;;iBA5BgB,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;iBAgBC,mBAAA,OAA0B;;;;;;iBAS1B,kBAAA,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-CoyHq8lH.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\n/**\n * Mutate the current async task's store so that subsequent code in this task\n * (and any descendants) sees the supplied request context.\n *\n * Unlike `runWithRequestContext`, this does not scope the context to a\n * callback — useful when the caller can't wrap a function, for example in a\n * Vitest fixture that suspends on `use()` and yields control to the test\n * runner before the test body executes.\n *\n * **Test setup only.** In production handlers, prefer `runWithRequestContext`\n * so the frame is automatically cleaned up.\n */\nexport function enterRequestContext(data: RequestContextData): void {\n\trequestContextStorage.enterWith(data);\n}\n\n/**\n * Clear the request context for the current async task. Pairs with\n * `enterRequestContext`. After calling, `serviceContext.hasContext()` returns\n * false for the remainder of the current async resource.\n */\nexport function exitRequestContext(): void {\n\t// AsyncLocalStorage<T>.enterWith requires T, but Node accepts undefined at\n\t// runtime — passing it resets getStore() back to undefined.\n\t(requestContextStorage as unknown as AsyncLocalStorage<unknown>).enterWith(\n\t\tundefined,\n\t);\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;;;;;;;;;;;;;AAcD,SAAgB,oBAAoBD,MAAgC;AACnE,uBAAsB,UAAU,KAAK;AACrC;;;;;;AAOD,SAAgB,qBAA2B;AAG1C,CAAC,sBAAgE,iBAEhE;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-HGC2PJzv.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;AAgBE,cA9EH,cA8EsB,EA9EN,cA8Ea;AAS1C;;;;;;;;;;;;;;;;;;;;iBA5BgB,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;iBAgBC,mBAAA,OAA0B;;;;;;iBAS1B,kBAAA,CAAA"}
@@ -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"}
package/dist/types.cjs DELETED
File without changes
package/dist/types.d.cts DELETED
@@ -1,2 +0,0 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-D7d_yeU5.cjs";
2
- export { Service, ServiceContext, ServiceRegisterOptions };
package/dist/types.d.mts DELETED
@@ -1,2 +0,0 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-CcHmCx_U.mjs";
2
- export { Service, ServiceContext, ServiceRegisterOptions };
package/dist/types.mjs DELETED
File without changes