@geekmidas/services 2.0.1 → 10.0.0-alpha.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.
package/src/middy.ts DELETED
@@ -1,226 +0,0 @@
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 DELETED
@@ -1,190 +0,0 @@
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 DELETED
@@ -1,92 +0,0 @@
1
- import type { EnvironmentParser } from '@geekmidas/envkit';
2
- import type { Logger } from '@geekmidas/logger';
3
-
4
- /**
5
- * Request context available to services.
6
- * Methods are guaranteed to return values when called within a request context.
7
- * Throws if called outside a request context (catches bugs early).
8
- */
9
- export interface ServiceContext {
10
- /**
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
- *
19
- * @throws Error if called outside a request context
20
- */
21
- getLogger(): Logger;
22
-
23
- /**
24
- * Get the current request ID.
25
- * @throws Error if called outside a request context
26
- */
27
- getRequestId(): string;
28
-
29
- /**
30
- * Get the current request's start time (from Date.now()).
31
- * Useful for calculating request duration.
32
- * @throws Error if called outside a request context
33
- */
34
- getRequestStartTime(): number;
35
-
36
- /**
37
- * Check if currently running inside a request context.
38
- * Use this to guard calls if you need to handle both cases.
39
- */
40
- hasContext(): boolean;
41
- }
42
-
43
- /**
44
- * Options passed to service register method.
45
- */
46
- export interface ServiceRegisterOptions {
47
- /** Environment parser for configuration */
48
- envParser: EnvironmentParser<{}>;
49
- /** Request context for logging and tracing */
50
- context: ServiceContext;
51
- }
52
-
53
- /**
54
- * Service interface for the simplified service pattern.
55
- * Services are objects with a serviceName and register method.
56
- *
57
- * @template TName - The literal string type for the service name
58
- * @template TInstance - The type of the service instance that will be registered
59
- *
60
- * @example
61
- * ```typescript
62
- * const databaseService = {
63
- * serviceName: 'database' as const,
64
- * register({ envParser, context }: ServiceRegisterOptions) {
65
- * const config = envParser.create((get) => ({
66
- * url: get('DATABASE_URL').string()
67
- * })).parse();
68
- *
69
- * return {
70
- * async query(sql: string) {
71
- * const logger = context.getLogger();
72
- * logger.debug({ sql }, 'Executing query');
73
- * // ... execute query
74
- * }
75
- * };
76
- * }
77
- * } satisfies Service<'database', DatabaseInstance>;
78
- * ```
79
- */
80
- export interface Service<TName extends string = string, TInstance = unknown> {
81
- /**
82
- * Unique name for the service, used for lookup via services.get()
83
- */
84
- serviceName: TName;
85
- /**
86
- * Register method that returns the actual service instance.
87
- * Called once on first access, then cached.
88
- *
89
- * @param options - Registration options including envParser and context
90
- */
91
- register(options: ServiceRegisterOptions): TInstance | Promise<TInstance>;
92
- }
package/tsconfig.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src",
6
- "composite": true
7
- },
8
- "include": ["src/**/*"]
9
- }
package/tsdown.config.ts DELETED
@@ -1,13 +0,0 @@
1
- import { defineConfig } from 'tsdown';
2
-
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
- });