@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/README.md CHANGED
@@ -49,11 +49,11 @@ export { databaseService };
49
49
  ### Use Services in Constructs
50
50
 
51
51
  ```typescript
52
- import { e } from '@geekmidas/constructs/endpoints';
52
+ import { api } from '../constructs/api';
53
53
  import { databaseService } from './services/database';
54
54
  import { z } from 'zod';
55
55
 
56
- export const getUser = e
56
+ export const getUser = api
57
57
  .get('/users/:id')
58
58
  .params(z.object({ id: z.string() }))
59
59
  .services([databaseService])
@@ -210,17 +210,17 @@ const userEventPublisher = {
210
210
  Inject multiple services into a construct:
211
211
 
212
212
  ```typescript
213
- import { e } from '@geekmidas/constructs/endpoints';
213
+ import { api } from '../constructs/api';
214
214
  import { databaseService } from './services/database';
215
215
  import { cacheService } from './services/cache';
216
216
  import { emailService } from './services/email';
217
217
  import { z } from 'zod';
218
218
 
219
- export const createUser = e
219
+ export const createUser = api
220
220
  .post('/users')
221
221
  .body(z.object({
222
222
  name: z.string(),
223
- email: z.string().email()
223
+ email: z.email()
224
224
  }))
225
225
  .services([databaseService, cacheService, emailService])
226
226
  .handle(async ({ body, services }) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geekmidas/services",
3
- "version": "2.0.1",
3
+ "version": "10.0.0-alpha.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {
@@ -45,6 +45,9 @@
45
45
  }
46
46
  }
47
47
  },
48
+ "files": [
49
+ "dist"
50
+ ],
48
51
  "repository": {
49
52
  "type": "git",
50
53
  "url": "https://github.com/geekmidas/toolbox"
@@ -58,8 +61,8 @@
58
61
  "@middy/core": ">=6.3.1",
59
62
  "@trpc/server": ">=11.0.0",
60
63
  "@types/aws-lambda": ">=8.10.92",
61
- "@geekmidas/envkit": "^1.1.1",
62
- "@geekmidas/logger": "^1.0.3"
64
+ "@geekmidas/envkit": "^10.0.0-alpha.0",
65
+ "@geekmidas/logger": "^10.0.0-alpha.0"
63
66
  },
64
67
  "peerDependenciesMeta": {
65
68
  "@geekmidas/envkit": {
@@ -83,8 +86,8 @@
83
86
  "@trpc/server": "~11.16.0",
84
87
  "@types/aws-lambda": "~8.10.147",
85
88
  "@types/node": "~24.9.1",
86
- "@geekmidas/envkit": "^1.1.1",
87
- "@geekmidas/logger": "^1.0.3"
89
+ "@geekmidas/envkit": "^10.0.0-alpha.0",
90
+ "@geekmidas/logger": "^10.0.0-alpha.0"
88
91
  },
89
92
  "scripts": {
90
93
  "ts": "tsc --noEmit --skipLibCheck src/**/*.ts"
package/CHANGELOG.md DELETED
@@ -1,87 +0,0 @@
1
- # @geekmidas/services
2
-
3
- ## 2.0.1
4
-
5
- ### Patch Changes
6
-
7
- - 🐛 [#11](https://github.com/geekmidas/toolbox/pull/11) [`40f4dc0`](https://github.com/geekmidas/toolbox/commit/40f4dc095911b2223a255029d8f776caf7781309) Thanks [@geekmidas](https://github.com/geekmidas)! - Patch release across all packages to realign published versions with the
8
- registry. The previous release only published the four packages that had
9
- version bumps; the remaining packages failed with "cannot publish over the
10
- previously published versions" because their versions were unchanged.
11
- - Updated dependencies [[`40f4dc0`](https://github.com/geekmidas/toolbox/commit/40f4dc095911b2223a255029d8f776caf7781309)]:
12
- - @geekmidas/envkit@1.1.1
13
- - @geekmidas/logger@1.0.3
14
-
15
- ## 2.0.0
16
-
17
- ### Patch Changes
18
-
19
- - Updated dependencies [[`7323f34`](https://github.com/geekmidas/toolbox/commit/7323f34176d63170dd53450889ac0b5959420c3c), [`79e2929`](https://github.com/geekmidas/toolbox/commit/79e292978d3dbc8927e25814bdb051d1c380600a)]:
20
- - @geekmidas/envkit@1.1.0
21
-
22
- ## 1.1.1
23
-
24
- ### Patch Changes
25
-
26
- - 🐛 [`9f02e9c`](https://github.com/geekmidas/toolbox/commit/9f02e9c8419db1e41692e996e177f2473237ca76) Thanks [@geekmidas](https://github.com/geekmidas)! - fix(services): bind `this` when invoking request-scoped logger methods
27
-
28
- The request-scoped logger proxy re-resolved log methods at call time but
29
- invoked them unbound. Pino's log methods read internal state off the
30
- receiver (`this[Symbol(pino.msgPrefix)]`), so calling them without `this`
31
- threw "Cannot read properties of undefined (reading 'Symbol(pino.msgPrefix)')"
32
- in production (pino), while dev/test console & spy loggers were unaffected.
33
- The proxy now invokes the resolved method with the current request's logger
34
- as `this`.
35
-
36
- ## 1.1.0
37
-
38
- ### Minor Changes
39
-
40
- - [#5](https://github.com/geekmidas/toolbox/pull/5) [`811d740`](https://github.com/geekmidas/toolbox/commit/811d740ae3875d59ad1b0dc50261266963c8cb76) Thanks [@geekmidas](https://github.com/geekmidas)! - Move the tRPC and Middy service integrations from `@geekmidas/constructs` to `@geekmidas/services`, where they belong — they depend only on `@geekmidas/services`, not on any construct.
41
- - ✨ **`@geekmidas/constructs`:** the `@geekmidas/constructs/trpc` and `@geekmidas/constructs/middy` entry points are removed (they were only just added). Import from `@geekmidas/services/trpc` and `@geekmidas/services/middy` instead. (`@trpc/server` is no longer a peer dependency of `@geekmidas/constructs`.)
42
- - ✨ **`@geekmidas/services`:** adds `/trpc` (`createServicesMiddleware`, `createRequestContextMiddleware`) and `/middy` (`requestContext`, `addServices`, `withServices`, `EventServices`) exports.
43
-
44
- The Middy middlewares were also tightened:
45
- - `requestContext` / `withServices` now require an explicit `logger` (no `ConsoleLogger` default) and are generic over `TLogger extends Logger`, so a custom logger type is preserved.
46
- - `addServices` / `withServices` now require an `envParser` (no implicit `process.env` default).
47
- - 🐛 Resolved services are attached to `event.services` (matching the `Function`/`Cron` constructs).
48
-
49
- ## 1.0.4
50
-
51
- ### Patch Changes
52
-
53
- - 🐛 [#3](https://github.com/geekmidas/toolbox/pull/3) [`42fda53`](https://github.com/geekmidas/toolbox/commit/42fda532bdf4489a3352f6a684f5f30beafccedd) Thanks [@geekmidas](https://github.com/geekmidas)! - Fix stale logger from service initialization
54
-
55
- ## 1.0.3
56
-
57
- ### Patch Changes
58
-
59
- - ✨ [`351f73b`](https://github.com/geekmidas/toolbox/commit/351f73b032bc0742b7f611a9fbcdfc85bbfd69a8) Thanks [@geekmidas](https://github.com/geekmidas)! - Update request context and add support for trpc
60
-
61
- ## 1.0.2
62
-
63
- ### Patch Changes
64
-
65
- - 🐛 [`d70c6c0`](https://github.com/geekmidas/toolbox/commit/d70c6c0aeb8a79da2473ac77dbd8255a4a2f5651) Thanks [@geekmidas](https://github.com/geekmidas)! - Fix `package.json` exports so TypeScript declarations resolve correctly under NodeNext/Bundler module resolution. Each subpath export now nests `types` inside its `import`/`require` condition, pointing at the `.d.mts` and `.d.cts` files that `tsdown` actually emits (previously the exports referenced non-existent `.d.ts` files, causing type-resolution failures for consumers). Both ESM (`.mjs`) and CJS (`.cjs`) runtime entry points are preserved. Additionally, `@geekmidas/ui` had `import` paths pointing at `.js` files that were never emitted — those are corrected to `.mjs`.
66
-
67
- - Updated dependencies [[`d70c6c0`](https://github.com/geekmidas/toolbox/commit/d70c6c0aeb8a79da2473ac77dbd8255a4a2f5651)]:
68
- - @geekmidas/envkit@1.0.7
69
- - @geekmidas/logger@1.0.2
70
-
71
- ## 1.0.1
72
-
73
- ### Patch Changes
74
-
75
- - 🔥 [`4bed570`](https://github.com/geekmidas/toolbox/commit/4bed57049db24417ef81279bc88fa0e1255f7b9a) Thanks [@geekmidas](https://github.com/geekmidas)! - Remove singleton enforcement so people can use it how they see fit
76
-
77
- ## 1.0.0
78
-
79
- ### Major Changes
80
-
81
- - [`ff7b115`](https://github.com/geekmidas/toolbox/commit/ff7b11599f60f84ac6cdc73714c853ecf786b2e8) Thanks [@geekmidas](https://github.com/geekmidas)! - Version 1 Stable release
82
-
83
- ### Patch Changes
84
-
85
- - Updated dependencies [[`ff7b115`](https://github.com/geekmidas/toolbox/commit/ff7b11599f60f84ac6cdc73714c853ecf786b2e8)]:
86
- - @geekmidas/envkit@1.0.0
87
- - @geekmidas/logger@1.0.0
@@ -1,167 +0,0 @@
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.
154
-
155
- ## Establishing the context
156
-
157
- The request context this relies on is established by the adaptors that run your
158
- code:
159
-
160
- - **Constructs** (`Endpoint`, `Function`, `Cron`, `Subscriber`) wrap each
161
- invocation in `runWithRequestContext` automatically.
162
- - **Standalone Middy handlers** can opt in with the
163
- `@geekmidas/services/middy` middlewares (`requestContext`, `addServices`,
164
- `withServices`), which establish the context (and optionally resolve services)
165
- before the handler runs.
166
- - **Tests** can use `@geekmidas/testkit`'s `runInRequestContext` /
167
- `requestContextFixture`.
@@ -1,252 +0,0 @@
1
- import type { EnvironmentParser } from '@geekmidas/envkit';
2
- import { serviceContext } from './context';
3
- import type { Service } from './types';
4
-
5
- /**
6
- * Service discovery container that manages service registration and retrieval.
7
- * Implements a singleton pattern with lazy initialization of services.
8
- *
9
- * @template TServices - Record type mapping service names to their instance types
10
- *
11
- * @example
12
- * ```typescript
13
- * // Define service types
14
- * interface MyServices {
15
- * database: Database;
16
- * cache: CacheService;
17
- * auth: AuthService;
18
- * }
19
- *
20
- * // Get service discovery instance
21
- * const discovery = ServiceDiscovery.getInstance<MyServices>(envParser);
22
- *
23
- * // Register services
24
- * await discovery.register([
25
- * databaseService,
26
- * cacheService,
27
- * authService
28
- * ]);
29
- *
30
- * // Retrieve services
31
- * const db = await discovery.get('database');
32
- * const { cache, auth } = await discovery.getMany(['cache', 'auth']);
33
- * ```
34
- */
35
- export class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {
36
- /** Singleton instance of ServiceDiscovery */
37
- private static _instance: ServiceDiscovery<any>;
38
- /** Map of registered service definitions */
39
- private services = new Map<string, Service>();
40
- /** Map of instantiated service instances */
41
- private instances = new Map<keyof TServices, TServices[keyof TServices]>();
42
-
43
- /**
44
- * Gets the singleton instance of ServiceDiscovery.
45
- * Creates a new instance if one doesn't exist.
46
- *
47
- * @template T - Record type mapping service names to their instance types
48
- * @param envParser - Environment parser for service configuration
49
- * @returns The ServiceDiscovery singleton instance
50
- *
51
- * @example
52
- * ```typescript
53
- * const services = ServiceDiscovery.getInstance<MyServices>(envParser);
54
- * ```
55
- */
56
- static getInstance<T extends Record<any, unknown> = any>(
57
- envParser: EnvironmentParser<{}>,
58
- ): ServiceDiscovery<T> {
59
- if (!ServiceDiscovery._instance) {
60
- ServiceDiscovery._instance = new ServiceDiscovery<T>(envParser);
61
- }
62
- return ServiceDiscovery._instance as ServiceDiscovery<T>;
63
- }
64
-
65
- /**
66
- * Resets the singleton instance. Use only for testing purposes.
67
- * This clears all cached services and allows a fresh instance to be created.
68
- *
69
- * @example
70
- * ```typescript
71
- * // In test teardown
72
- * afterEach(() => {
73
- * ServiceDiscovery.reset();
74
- * });
75
- * ```
76
- */
77
- static reset(): void {
78
- ServiceDiscovery._instance = undefined as any;
79
- }
80
-
81
- /**
82
- *
83
- * @param envParser - Environment parser for service configuration
84
- */
85
- constructor(readonly envParser: EnvironmentParser<{}>) {}
86
-
87
- /**
88
- * Register multiple services with the service discovery.
89
- * Services are instantiated lazily on first access.
90
- * Already instantiated services are returned from cache.
91
- *
92
- * @template T - Array type of services to register
93
- * @param services - Array of services to register
94
- * @returns Promise resolving to a record of service names to instances
95
- *
96
- * @example
97
- * ```typescript
98
- * const services = await discovery.register([
99
- * databaseService,
100
- * cacheService,
101
- * authService
102
- * ]);
103
- *
104
- * // services = {
105
- * // database: Database instance,
106
- * // cache: CacheService instance,
107
- * // auth: AuthService instance
108
- * // }
109
- * ```
110
- */
111
- async register<T extends Service[]>(services: T): Promise<ServiceRecord<T>> {
112
- const registeredServices = {} as ServiceRecord<T>;
113
- for (const service of services) {
114
- const name = service.serviceName as T[number]['serviceName'];
115
- if (this.instances.has(name)) {
116
- (registeredServices as any)[name] = this.instances.get(
117
- name,
118
- ) as TServices[keyof TServices];
119
- continue;
120
- }
121
-
122
- // Pass both envParser and context to service
123
- const instance = await service.register({
124
- envParser: this.envParser,
125
- context: serviceContext,
126
- });
127
-
128
- this.instances.set(name, instance as TServices[keyof TServices]);
129
- (registeredServices as any)[name] =
130
- instance as TServices[keyof TServices];
131
- }
132
-
133
- return registeredServices;
134
- }
135
-
136
- /**
137
- * Get a service from the service discovery.
138
- * Services are instantiated on first access if not already cached.
139
- *
140
- * @template K - The service name key
141
- * @param name - The name of the service to get
142
- * @returns Promise resolving to the service instance
143
- * @throws {Error} If the service is not registered
144
- *
145
- * @example
146
- * ```typescript
147
- * const database = await discovery.get('database');
148
- * const users = await database.query('SELECT * FROM users');
149
- * ```
150
- */
151
- get<K extends keyof TServices & string>(name: K): Promise<TServices[K]> {
152
- const service = this.services.get(name);
153
-
154
- if (!service) {
155
- throw new Error(`Service '${name}' not found in service discovery`);
156
- }
157
-
158
- return service.register({
159
- envParser: this.envParser,
160
- context: serviceContext,
161
- }) as Promise<TServices[K]>;
162
- }
163
- /**
164
- * Get multiple services from the service discovery.
165
- * Useful for retrieving multiple dependencies at once.
166
- *
167
- * @template K - Array of service name keys
168
- * @param names - Array of service names to retrieve
169
- * @returns Promise resolving to an object containing the service instances
170
- *
171
- * @example
172
- * ```typescript
173
- * const { database, cache, auth } = await discovery.getMany([
174
- * 'database',
175
- * 'cache',
176
- * 'auth'
177
- * ]);
178
- * ```
179
- */
180
- async getMany<K extends (keyof TServices & string)[]>(
181
- names: [...K],
182
- ): Promise<{ [P in K[number]]: TServices[P] }> {
183
- const result = {} as { [P in K[number]]: TServices[P] };
184
-
185
- for (const name of names) {
186
- result[name] = await this.get(name);
187
- }
188
-
189
- return result;
190
- }
191
-
192
- /**
193
- * Check if a service exists in the service discovery.
194
- * Can check by service name or service instance.
195
- *
196
- * @param service - The service name or service instance to check
197
- * @returns True if the service exists, false otherwise
198
- *
199
- * @example
200
- * ```typescript
201
- * if (discovery.has('database')) {
202
- * const db = await discovery.get('database');
203
- * }
204
- *
205
- * // Or check with service instance
206
- * if (!discovery.has(databaseService)) {
207
- * await discovery.register([databaseService]);
208
- * }
209
- * ```
210
- */
211
- has(service: string | Service): boolean {
212
- if (typeof service === 'string') {
213
- return this.services.has(service);
214
- }
215
-
216
- return this.services.has(service.serviceName);
217
- }
218
- }
219
-
220
- /**
221
- * Utility type to extract service names from an array of services.
222
- *
223
- * @template T - Array of Service types
224
- *
225
- * @example
226
- * ```typescript
227
- * type Names = ExtractServiceNames<[typeof databaseService, typeof cacheService]>;
228
- * // type Names = 'database' | 'cache'
229
- * ```
230
- */
231
- export type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];
232
-
233
- /**
234
- * Utility type to create a record type from an array of services.
235
- * Maps service names to their registered instance types.
236
- *
237
- * @template T - Array of Service types
238
- *
239
- * @example
240
- * ```typescript
241
- * type MyServiceRecord = ServiceRecord<[typeof databaseService, typeof cacheService]>;
242
- * // type MyServiceRecord = {
243
- * // database: DatabaseInstance;
244
- * // cache: CacheInstance;
245
- * // }
246
- * ```
247
- */
248
- export type ServiceRecord<T extends Service[]> = {
249
- [K in T[number] as K['serviceName']]: K extends Service
250
- ? Awaited<ReturnType<K['register']>>
251
- : never;
252
- };