@aligent/aws-wrappers 0.4.1 → 0.5.1

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.
@@ -0,0 +1,79 @@
1
+ [**@aligent/aws-wrappers**](../../../modules.md)
2
+
3
+ ***
4
+
5
+ [@aligent/aws-wrappers](../../../modules.md) / [testing/testing](../modules.md) / createMockService
6
+
7
+ # Function: createMockService()
8
+
9
+ > **createMockService**\<`T`, `O`\>(`service`, `overrides`): `T` & `O`
10
+
11
+ Defined in: [testing/testing.ts:66](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/testing/testing.ts#L66)
12
+
13
+ Build a stand-in for a service class from an object of method overrides, for
14
+ use in unit tests of code that depends on the service.
15
+
16
+ Accessing a method of the class that was not overridden throws immediately,
17
+ naming the service and the method, rather than failing later as
18
+ `is not a function`. Any key that is neither an override nor a method of the
19
+ class falls through to the overrides object — so `toString`, `valueOf` and
20
+ `constructor` resolve from `Object.prototype` as usual, and anything else is
21
+ `undefined`. That fallback is what keeps probe properties safe: `then` (so
22
+ awaiting the mock does not throw), `Symbol.toStringTag`, inspection symbols,
23
+ and whatever a test framework's error serialiser reaches for.
24
+
25
+ Only the overrides are enumerable, so spreading, serialising or deep-equalling
26
+ an object that holds the mock does not trip the throw.
27
+
28
+ The helper imports no test framework: callers supply their own spies, and
29
+ overridden keys keep the caller's spy type so `.mock` resolves through the
30
+ returned object.
31
+
32
+ ## Type Parameters
33
+
34
+ ### T
35
+
36
+ `T` *extends* `object`
37
+
38
+ ### O
39
+
40
+ `O` *extends* `Partial`\<`T`\>
41
+
42
+ ## Parameters
43
+
44
+ ### service
45
+
46
+ The service class itself. It is never constructed — only
47
+ its prototype is read — so the parameter is typed as just that capability,
48
+ which also accepts abstract classes and classes with required constructor
49
+ arguments. Passing the class as a value (rather than as an explicit type
50
+ argument) is load-bearing for the types: TypeScript has no partial
51
+ type-argument inference, so an explicit `T` would suppress inference of the
52
+ overrides type and lose the caller's spy typing on overridden keys.
53
+
54
+ #### prototype
55
+
56
+ `T`
57
+
58
+ ### overrides
59
+
60
+ `O`
61
+
62
+ The methods the code under test actually calls. Keys are
63
+ checked against the class's public surface, so a typo or a wrong-shaped
64
+ override is a compile error.
65
+
66
+ ## Returns
67
+
68
+ `T` & `O`
69
+
70
+ ## Example
71
+
72
+ ```typescript
73
+ const getJsonObject = vi.fn().mockResolvedValue({ id: 1 });
74
+ const s3 = createMockService(S3Service, { getJsonObject });
75
+
76
+ await handler({ s3 });
77
+
78
+ expect(s3.getJsonObject.mock.calls).toHaveLength(1);
79
+ ```
@@ -0,0 +1,11 @@
1
+ [**@aligent/aws-wrappers**](../../modules.md)
2
+
3
+ ***
4
+
5
+ [@aligent/aws-wrappers](../../modules.md) / testing/testing
6
+
7
+ # testing/testing
8
+
9
+ ## Functions
10
+
11
+ - [createMockService](functions/createMockService.md)
package/esm/index.mjs CHANGED
@@ -52,6 +52,8 @@ function filterFieldsForLogLevel(logger, input, safeFields) {
52
52
 
53
53
  const BATCH_WRITE_MAX_ATTEMPTS = 5;
54
54
  const BATCH_WRITE_BASE_DELAY_MS = 200;
55
+ const BATCH_GET_MAX_ATTEMPTS = 5;
56
+ const BATCH_GET_BASE_DELAY_MS = 200;
55
57
  /**
56
58
  * Fields safe to log at INFO. Omits `Key` (may carry customer IDs / tenant IDs).
57
59
  */
@@ -137,8 +139,8 @@ const SCAN_SAFE_FIELDS = [
137
139
  'ReturnConsumedCapacity',
138
140
  ];
139
141
  const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
140
- const backoffDelay = (attempt) => {
141
- const exp = BATCH_WRITE_BASE_DELAY_MS * 2 ** attempt;
142
+ const backoffDelay = (attempt, baseDelayMs) => {
143
+ const exp = baseDelayMs * 2 ** attempt;
142
144
  return exp + Math.random() * exp;
143
145
  };
144
146
  /**
@@ -266,7 +268,10 @@ class DynamoDBService {
266
268
  return response;
267
269
  }
268
270
  /**
269
- * Batch-get items from one or more DynamoDB tables.
271
+ * Batch-get items from one or more DynamoDB tables, retrying
272
+ * `UnprocessedKeys` with jittered exponential backoff. Up to 5 attempts
273
+ * (200ms base delay). Throws when keys remain unprocessed after the final
274
+ * attempt. `Responses` are merged across attempts, keyed by table name.
270
275
  *
271
276
  * Note: this method is intentionally **not** generic. `BatchGet`'s
272
277
  * `Responses` field is a multi-table `Record<string, item[]>` whose item
@@ -282,7 +287,26 @@ class DynamoDBService {
282
287
  this.logger.info('Batch getting DynamoDB items', {
283
288
  input: logFullInput ? input : { tables: Object.keys(input.RequestItems ?? {}) },
284
289
  });
285
- return this.client.send(new BatchGetCommand(input));
290
+ let current = input;
291
+ const mergedResponses = {};
292
+ for (let attempt = 0; attempt < BATCH_GET_MAX_ATTEMPTS; attempt++) {
293
+ const response = await this.client.send(new BatchGetCommand(current));
294
+ for (const [table, items] of Object.entries(response.Responses ?? {})) {
295
+ mergedResponses[table] = [...(mergedResponses[table] ?? []), ...items];
296
+ }
297
+ const unprocessed = response.UnprocessedKeys;
298
+ if (!unprocessed || Object.keys(unprocessed).length === 0) {
299
+ return { ...response, Responses: mergedResponses };
300
+ }
301
+ this.logger.warn('Retrying unprocessed DynamoDB items', {
302
+ attempt: attempt + 1,
303
+ tables: Object.keys(unprocessed),
304
+ });
305
+ if (attempt < BATCH_GET_MAX_ATTEMPTS - 1)
306
+ await sleep(backoffDelay(attempt, BATCH_GET_BASE_DELAY_MS));
307
+ current = { ...input, RequestItems: unprocessed };
308
+ }
309
+ throw new Error(`batchGet failed after ${BATCH_GET_MAX_ATTEMPTS} attempts`);
286
310
  }
287
311
  /**
288
312
  * Batch-write items to DynamoDB, retrying `UnprocessedItems` with jittered
@@ -309,7 +333,7 @@ class DynamoDBService {
309
333
  tables: Object.keys(unprocessed),
310
334
  });
311
335
  if (attempt < BATCH_WRITE_MAX_ATTEMPTS - 1)
312
- await sleep(backoffDelay(attempt));
336
+ await sleep(backoffDelay(attempt, BATCH_WRITE_BASE_DELAY_MS));
313
337
  current = { ...input, RequestItems: unprocessed };
314
338
  }
315
339
  throw new Error(`batchWrite failed after ${BATCH_WRITE_MAX_ATTEMPTS} attempts`);
@@ -1276,6 +1300,7 @@ class SQSService {
1276
1300
  }
1277
1301
  }
1278
1302
 
1303
+ const GET_PARAMETERS_LIMIT = 10;
1279
1304
  /**
1280
1305
  * Fields safe to log at INFO level for `putParameter`. Omits `Value` (the
1281
1306
  * parameter content itself).
@@ -1345,6 +1370,11 @@ class SSMService {
1345
1370
  * });
1346
1371
  * ```
1347
1372
  *
1373
+ * The AWS SSM `GetParameters` API caps requests at
1374
+ * `GET_PARAMETERS_LIMIT` (10) names per call, so this method auto-chunks
1375
+ * the underlying parameter names and sends one request per chunk,
1376
+ * merging the results before building the alias-keyed return value.
1377
+ *
1348
1378
  * @param aliases - Record mapping each desired local alias to its SSM
1349
1379
  * parameter name (or ARN).
1350
1380
  * @returns A record keyed by the same aliases, mapping each to the
@@ -1353,14 +1383,18 @@ class SSMService {
1353
1383
  */
1354
1384
  async getParameters(aliases) {
1355
1385
  this.logger.info('Fetching SSM parameters', { input: { aliases } });
1356
- const response = await this.client.send(new GetParametersCommand({
1357
- Names: Object.values(aliases),
1358
- WithDecryption: true,
1359
- }));
1386
+ const names = Object.values(aliases);
1360
1387
  const byPath = new Map();
1361
- for (const parameter of response.Parameters ?? []) {
1362
- if (parameter.Name !== undefined)
1363
- byPath.set(parameter.Name, parameter.Value);
1388
+ for (let i = 0; i < names.length; i += GET_PARAMETERS_LIMIT) {
1389
+ const chunk = names.slice(i, i + GET_PARAMETERS_LIMIT);
1390
+ const response = await this.client.send(new GetParametersCommand({
1391
+ Names: chunk,
1392
+ WithDecryption: true,
1393
+ }));
1394
+ for (const parameter of response.Parameters ?? []) {
1395
+ if (parameter.Name !== undefined)
1396
+ byPath.set(parameter.Name, parameter.Value);
1397
+ }
1364
1398
  }
1365
1399
  const result = {};
1366
1400
  for (const alias of Object.keys(aliases)) {
package/esm/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aligent/aws-wrappers",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Opinionated AWS SDK wrappers with Powertools logging and X-Ray tracing",
5
5
  "engines": {
6
6
  "node": ">=18"
@@ -19,6 +19,16 @@
19
19
  "default": "./cjs/index.cjs"
20
20
  }
21
21
  },
22
+ "./testing": {
23
+ "import": {
24
+ "types": "./esm/src/testing/testing.d.ts",
25
+ "default": "./esm/testing.mjs"
26
+ },
27
+ "require": {
28
+ "types": "./cjs/src/testing/testing.d.ts",
29
+ "default": "./cjs/testing.cjs"
30
+ }
31
+ },
22
32
  "./package.json": "./package.json"
23
33
  },
24
34
  "files": [
@@ -103,7 +103,10 @@ export declare class DynamoDBService {
103
103
  Items?: T[];
104
104
  }>;
105
105
  /**
106
- * Batch-get items from one or more DynamoDB tables.
106
+ * Batch-get items from one or more DynamoDB tables, retrying
107
+ * `UnprocessedKeys` with jittered exponential backoff. Up to 5 attempts
108
+ * (200ms base delay). Throws when keys remain unprocessed after the final
109
+ * attempt. `Responses` are merged across attempts, keyed by table name.
107
110
  *
108
111
  * Note: this method is intentionally **not** generic. `BatchGet`'s
109
112
  * `Responses` field is a multi-table `Record<string, item[]>` whose item
@@ -49,6 +49,11 @@ export declare class SSMService {
49
49
  * });
50
50
  * ```
51
51
  *
52
+ * The AWS SSM `GetParameters` API caps requests at
53
+ * `GET_PARAMETERS_LIMIT` (10) names per call, so this method auto-chunks
54
+ * the underlying parameter names and sends one request per chunk,
55
+ * merging the results before building the alias-keyed return value.
56
+ *
52
57
  * @param aliases - Record mapping each desired local alias to its SSM
53
58
  * parameter name (or ARN).
54
59
  * @returns A record keyed by the same aliases, mapping each to the
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Build a stand-in for a service class from an object of method overrides, for
3
+ * use in unit tests of code that depends on the service.
4
+ *
5
+ * Accessing a method of the class that was not overridden throws immediately,
6
+ * naming the service and the method, rather than failing later as
7
+ * `is not a function`. Any key that is neither an override nor a method of the
8
+ * class falls through to the overrides object — so `toString`, `valueOf` and
9
+ * `constructor` resolve from `Object.prototype` as usual, and anything else is
10
+ * `undefined`. That fallback is what keeps probe properties safe: `then` (so
11
+ * awaiting the mock does not throw), `Symbol.toStringTag`, inspection symbols,
12
+ * and whatever a test framework's error serialiser reaches for.
13
+ *
14
+ * Only the overrides are enumerable, so spreading, serialising or deep-equalling
15
+ * an object that holds the mock does not trip the throw.
16
+ *
17
+ * The helper imports no test framework: callers supply their own spies, and
18
+ * overridden keys keep the caller's spy type so `.mock` resolves through the
19
+ * returned object.
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const getJsonObject = vi.fn().mockResolvedValue({ id: 1 });
24
+ * const s3 = createMockService(S3Service, { getJsonObject });
25
+ *
26
+ * await handler({ s3 });
27
+ *
28
+ * expect(s3.getJsonObject.mock.calls).toHaveLength(1);
29
+ * ```
30
+ *
31
+ * @param service - The service class itself. It is never constructed — only
32
+ * its prototype is read — so the parameter is typed as just that capability,
33
+ * which also accepts abstract classes and classes with required constructor
34
+ * arguments. Passing the class as a value (rather than as an explicit type
35
+ * argument) is load-bearing for the types: TypeScript has no partial
36
+ * type-argument inference, so an explicit `T` would suppress inference of the
37
+ * overrides type and lose the caller's spy typing on overridden keys.
38
+ * @param overrides - The methods the code under test actually calls. Keys are
39
+ * checked against the class's public surface, so a typo or a wrong-shaped
40
+ * override is a compile error.
41
+ */
42
+ export declare function createMockService<T extends object, O extends Partial<T>>(service: {
43
+ prototype: T;
44
+ }, overrides: O): T & O;
@@ -0,0 +1 @@
1
+ export * from "./src/testing/testing";
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Collect the method names of a class, walking the prototype chain up to but
3
+ * excluding `Object.prototype` so inherited methods are found.
4
+ *
5
+ * Property *descriptors* are inspected rather than properties read: reading a
6
+ * prototype getter here would execute consumer code with `this` bound to the
7
+ * mock. Accessor properties are therefore neither mockable nor throwable.
8
+ */
9
+ function collectMethodNames(prototype) {
10
+ const names = new Set();
11
+ let current = prototype;
12
+ while (current !== null && current !== Object.prototype) {
13
+ for (const key of Object.getOwnPropertyNames(current)) {
14
+ if (key === 'constructor')
15
+ continue;
16
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
17
+ if (typeof descriptor?.value === 'function')
18
+ names.add(key);
19
+ }
20
+ current = Object.getPrototypeOf(current);
21
+ }
22
+ return names;
23
+ }
24
+ /**
25
+ * Build a stand-in for a service class from an object of method overrides, for
26
+ * use in unit tests of code that depends on the service.
27
+ *
28
+ * Accessing a method of the class that was not overridden throws immediately,
29
+ * naming the service and the method, rather than failing later as
30
+ * `is not a function`. Any key that is neither an override nor a method of the
31
+ * class falls through to the overrides object — so `toString`, `valueOf` and
32
+ * `constructor` resolve from `Object.prototype` as usual, and anything else is
33
+ * `undefined`. That fallback is what keeps probe properties safe: `then` (so
34
+ * awaiting the mock does not throw), `Symbol.toStringTag`, inspection symbols,
35
+ * and whatever a test framework's error serialiser reaches for.
36
+ *
37
+ * Only the overrides are enumerable, so spreading, serialising or deep-equalling
38
+ * an object that holds the mock does not trip the throw.
39
+ *
40
+ * The helper imports no test framework: callers supply their own spies, and
41
+ * overridden keys keep the caller's spy type so `.mock` resolves through the
42
+ * returned object.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const getJsonObject = vi.fn().mockResolvedValue({ id: 1 });
47
+ * const s3 = createMockService(S3Service, { getJsonObject });
48
+ *
49
+ * await handler({ s3 });
50
+ *
51
+ * expect(s3.getJsonObject.mock.calls).toHaveLength(1);
52
+ * ```
53
+ *
54
+ * @param service - The service class itself. It is never constructed — only
55
+ * its prototype is read — so the parameter is typed as just that capability,
56
+ * which also accepts abstract classes and classes with required constructor
57
+ * arguments. Passing the class as a value (rather than as an explicit type
58
+ * argument) is load-bearing for the types: TypeScript has no partial
59
+ * type-argument inference, so an explicit `T` would suppress inference of the
60
+ * overrides type and lose the caller's spy typing on overridden keys.
61
+ * @param overrides - The methods the code under test actually calls. Keys are
62
+ * checked against the class's public surface, so a typo or a wrong-shaped
63
+ * override is a compile error.
64
+ */
65
+ function createMockService(service, overrides) {
66
+ const { prototype } = service;
67
+ const methodNames = collectMethodNames(prototype);
68
+ const className = prototype.constructor?.name;
69
+ const isUnmockedMethod = (key) => typeof key === 'string' && methodNames.has(key);
70
+ const mock = new Proxy(overrides, {
71
+ get(target, key, receiver) {
72
+ // `hasOwn`, not `has`: a class method that shadows one of
73
+ // `Object.prototype`'s (`toString`, `valueOf`, …) must still throw
74
+ // rather than be served silently from the prototype chain.
75
+ if (Object.hasOwn(target, key))
76
+ return Reflect.get(target, key, receiver);
77
+ if (isUnmockedMethod(key)) {
78
+ throw new Error(`${className ?? 'Service'}.${key} was accessed but not mocked`);
79
+ }
80
+ return Reflect.get(target, key, receiver);
81
+ },
82
+ has(target, key) {
83
+ return Reflect.has(target, key) || isUnmockedMethod(key);
84
+ },
85
+ });
86
+ // The services declare `private readonly client` / `private readonly logger`.
87
+ // Those fields are nominal, so no structurally-constructed value is
88
+ // assignable to the class type — this cast is unavoidable. Concentrating
89
+ // it here is the point of the helper: consumer test suites contain none.
90
+ return mock;
91
+ }
92
+
93
+ export { createMockService };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aligent/aws-wrappers",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Opinionated AWS SDK wrappers with Powertools logging and X-Ray tracing",
5
5
  "engines": {
6
6
  "node": ">=18"
@@ -19,6 +19,16 @@
19
19
  "default": "./cjs/index.cjs"
20
20
  }
21
21
  },
22
+ "./testing": {
23
+ "import": {
24
+ "types": "./esm/src/testing/testing.d.ts",
25
+ "default": "./esm/testing.mjs"
26
+ },
27
+ "require": {
28
+ "types": "./cjs/src/testing/testing.d.ts",
29
+ "default": "./cjs/testing.cjs"
30
+ }
31
+ },
22
32
  "./package.json": "./package.json"
23
33
  },
24
34
  "files": [