@aligent/aws-wrappers 0.5.7 → 0.5.9
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 +106 -4
- package/cjs/index.cjs +393 -66
- package/cjs/package.json +16 -14
- package/cjs/src/eventbridge/eventbridge.d.ts +58 -0
- package/cjs/src/eventbridge/eventbridge.d.ts.map +1 -0
- package/cjs/src/index.d.ts +4 -0
- package/cjs/src/index.d.ts.map +1 -1
- package/cjs/src/lambda/lambda.d.ts +54 -0
- package/cjs/src/lambda/lambda.d.ts.map +1 -0
- package/cjs/src/s3/s3.d.ts +26 -4
- package/cjs/src/s3/s3.d.ts.map +1 -1
- package/cjs/src/scheduler/scheduler.d.ts +3 -2
- package/cjs/src/scheduler/scheduler.d.ts.map +1 -1
- package/cjs/src/ssm/ssm.d.ts +18 -3
- package/cjs/src/ssm/ssm.d.ts.map +1 -1
- package/cjs/src/util/batch-operation-error.d.ts +33 -4
- package/cjs/src/util/batch-operation-error.d.ts.map +1 -1
- package/cjs/src/util/lambda-function-error.d.ts +36 -0
- package/cjs/src/util/lambda-function-error.d.ts.map +1 -0
- package/docs/index/classes/APIGatewayService.md +6 -6
- package/docs/index/classes/APIGatewayV2Service.md +5 -5
- package/docs/index/classes/BatchOperationError.md +10 -6
- package/docs/index/classes/DynamoDBService.md +34 -12
- package/docs/index/classes/EventBridgeService.md +99 -0
- package/docs/index/classes/LambdaFunctionError.md +283 -0
- package/docs/index/classes/LambdaService.md +95 -0
- package/docs/index/classes/S3Service.md +42 -19
- package/docs/index/classes/SNSService.md +4 -4
- package/docs/index/classes/SQSService.md +7 -7
- package/docs/index/classes/SSMService.md +35 -10
- package/docs/index/classes/SchedulerService.md +14 -13
- package/docs/index/classes/SecretsManagerService.md +10 -8
- package/docs/index/classes/StepFunctionsService.md +6 -6
- package/docs/index/interfaces/BatchFailedEntry.md +6 -5
- package/docs/index/interfaces/EmptyBucketPageResult.md +23 -0
- package/docs/index/modules.md +4 -0
- package/docs/testing/testing/functions/createMockService.md +5 -1
- package/esm/index.mjs +391 -67
- package/esm/package.json +16 -14
- package/esm/src/eventbridge/eventbridge.d.ts +58 -0
- package/esm/src/eventbridge/eventbridge.d.ts.map +1 -0
- package/esm/src/index.d.ts +4 -0
- package/esm/src/index.d.ts.map +1 -1
- package/esm/src/lambda/lambda.d.ts +54 -0
- package/esm/src/lambda/lambda.d.ts.map +1 -0
- package/esm/src/s3/s3.d.ts +26 -4
- package/esm/src/s3/s3.d.ts.map +1 -1
- package/esm/src/scheduler/scheduler.d.ts +3 -2
- package/esm/src/scheduler/scheduler.d.ts.map +1 -1
- package/esm/src/ssm/ssm.d.ts +18 -3
- package/esm/src/ssm/ssm.d.ts.map +1 -1
- package/esm/src/util/batch-operation-error.d.ts +33 -4
- package/esm/src/util/batch-operation-error.d.ts.map +1 -1
- package/esm/src/util/lambda-function-error.d.ts +36 -0
- package/esm/src/util/lambda-function-error.d.ts.map +1 -0
- package/package.json +16 -14
package/esm/index.mjs
CHANGED
|
@@ -4,6 +4,8 @@ import xray from 'aws-xray-sdk-core';
|
|
|
4
4
|
import { APIGatewayClient, paginateGetRestApis, paginateGetApiKeys, GetApiKeyCommand, paginateGetResources } from '@aws-sdk/client-api-gateway';
|
|
5
5
|
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
|
|
6
6
|
import { DynamoDBDocumentClient, GetCommand, PutCommand, UpdateCommand, DeleteCommand, QueryCommand, ScanCommand, BatchGetCommand, BatchWriteCommand, paginateQuery, paginateScan } from '@aws-sdk/lib-dynamodb';
|
|
7
|
+
import { EventBridgeClient, PutEventsCommand } from '@aws-sdk/client-eventbridge';
|
|
8
|
+
import { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda';
|
|
7
9
|
import { S3Client, PutObjectCommand, GetObjectCommand, HeadObjectCommand, CopyObjectCommand, paginateListObjectsV2, DeleteObjectCommand, DeleteObjectsCommand } from '@aws-sdk/client-s3';
|
|
8
10
|
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
|
9
11
|
import { SchedulerClient, CreateScheduleCommand, GetScheduleCommand, UpdateScheduleCommand, DeleteScheduleCommand, paginateListSchedules, CreateScheduleGroupCommand, GetScheduleGroupCommand, DeleteScheduleGroupCommand, paginateListScheduleGroups } from '@aws-sdk/client-scheduler';
|
|
@@ -511,6 +513,86 @@ class DynamoDBService {
|
|
|
511
513
|
}
|
|
512
514
|
}
|
|
513
515
|
|
|
516
|
+
/**
|
|
517
|
+
* Thrown by the batch methods once every chunk has been sent and at least one
|
|
518
|
+
* entry was rejected.
|
|
519
|
+
*
|
|
520
|
+
* `results` holds the raw SDK output of every chunk, so the outputs of the
|
|
521
|
+
* entries that succeeded (message ids, sequence numbers) stay readable. The
|
|
522
|
+
* exceptions are `S3.emptyBucket`, whose `results` are per-page deleted keys,
|
|
523
|
+
* and `SSM.getParameters`, whose `results` are empty.
|
|
524
|
+
* `failed` is the normalised list of rejected entries across all chunks.
|
|
525
|
+
*
|
|
526
|
+
* Match on `name` rather than `instanceof` if both the CJS and ESM builds of
|
|
527
|
+
* this package may be loaded in one process.
|
|
528
|
+
*/
|
|
529
|
+
class BatchOperationError extends Error {
|
|
530
|
+
results;
|
|
531
|
+
failed;
|
|
532
|
+
name = 'BatchOperationError';
|
|
533
|
+
constructor(results, failed) {
|
|
534
|
+
super(`Batch operation failed for ${failed.length} entries (${distinctCodes(failed).join(', ')})`);
|
|
535
|
+
this.results = results;
|
|
536
|
+
this.failed = failed;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* SQS and SNS report rejected entries under `Failed` on an otherwise
|
|
541
|
+
* successful response, so a resolved chunk does not mean every entry was
|
|
542
|
+
* accepted. Extracts those entries and delegates to {@link throwIfAny}.
|
|
543
|
+
*
|
|
544
|
+
* Only id, code and message are copied out — never the entry itself — so
|
|
545
|
+
* neither the error nor the warning can leak a payload.
|
|
546
|
+
*/
|
|
547
|
+
function throwIfAnyFailed(logger, operation, results) {
|
|
548
|
+
const failed = results.flatMap(result => (result.Failed ?? []).map(({ Id, Code, Message }) => ({
|
|
549
|
+
id: Id,
|
|
550
|
+
code: Code,
|
|
551
|
+
message: Message,
|
|
552
|
+
})));
|
|
553
|
+
return throwIfAny(logger, operation, results, failed);
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* S3 reports undeleted keys under `Errors` on an otherwise successful
|
|
557
|
+
* `DeleteObjects` response. Same contract as {@link throwIfAnyFailed}; the
|
|
558
|
+
* key is carried as the failed entry's `id`, and `VersionId` is dropped.
|
|
559
|
+
*/
|
|
560
|
+
function throwIfAnyDeleteErrors(logger, operation, results) {
|
|
561
|
+
const failed = results.flatMap(result => (result.Errors ?? []).map(({ Key, Code, Message }) => ({
|
|
562
|
+
id: Key,
|
|
563
|
+
code: Code,
|
|
564
|
+
message: Message,
|
|
565
|
+
})));
|
|
566
|
+
return throwIfAny(logger, operation, results, failed);
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Warn-and-throw step for services whose responses don't use the SQS/SNS
|
|
570
|
+
* `Failed` shape and so extract their own rejected entries (`EventBridge.putEvents`),
|
|
571
|
+
* or whose `results` aren't a plain list of SDK outputs (`S3.emptyBucket`).
|
|
572
|
+
* Returns `results` untouched when `failed` is empty.
|
|
573
|
+
*
|
|
574
|
+
* Callers must build `failed` by copying id, code and message explicitly —
|
|
575
|
+
* never by spreading the SDK entry — because it goes straight into the error
|
|
576
|
+
* and the warning.
|
|
577
|
+
*/
|
|
578
|
+
function throwIfAny(logger, operation, results, failed) {
|
|
579
|
+
if (failed.length === 0)
|
|
580
|
+
return results;
|
|
581
|
+
logger.warn(`${operation} had rejected entries`, {
|
|
582
|
+
failedCount: failed.length,
|
|
583
|
+
codes: distinctCodes(failed),
|
|
584
|
+
});
|
|
585
|
+
throw new BatchOperationError(results, failed);
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Distinct error codes in first-seen order, for the error message and the
|
|
589
|
+
* warning log line.
|
|
590
|
+
*/
|
|
591
|
+
function distinctCodes(failed) {
|
|
592
|
+
const codes = failed.flatMap(entry => (entry.code === undefined ? [] : [entry.code]));
|
|
593
|
+
return [...new Set(codes)];
|
|
594
|
+
}
|
|
595
|
+
|
|
514
596
|
/**
|
|
515
597
|
* Split a list into consecutive chunks of at most `size` items, mirroring the
|
|
516
598
|
* per-request caps the AWS APIs enforce on batch operations.
|
|
@@ -523,6 +605,235 @@ function chunk(items, size) {
|
|
|
523
605
|
return chunks;
|
|
524
606
|
}
|
|
525
607
|
|
|
608
|
+
const PUT_EVENTS_LIMIT = 10;
|
|
609
|
+
/**
|
|
610
|
+
* `Detail`, `Resources` and the entries themselves are payload carriers, so
|
|
611
|
+
* the INFO line carries only the endpoint id and how many entries were sent.
|
|
612
|
+
*/
|
|
613
|
+
function summariseEntries$1({ EndpointId, Entries }) {
|
|
614
|
+
return { EndpointId, entryCount: Entries?.length ?? 0 };
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Chunks are full except the last, so the caller's original index of a
|
|
618
|
+
* rejected entry is the chunk's offset (chunk number times the chunk size)
|
|
619
|
+
* plus its position within the chunk.
|
|
620
|
+
*/
|
|
621
|
+
function extractPutEventsFailures(results) {
|
|
622
|
+
return results.flatMap((result, chunkIndex) => extractChunkFailures(result, chunkIndex * PUT_EVENTS_LIMIT));
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* `PutEvents` reports a rejected entry by an error code on the result entry at
|
|
626
|
+
* the same position as the request entry.
|
|
627
|
+
*
|
|
628
|
+
* Copies only code and message out, never the request entry, so neither the
|
|
629
|
+
* error nor the warning can carry event detail.
|
|
630
|
+
*/
|
|
631
|
+
function extractChunkFailures(result, offset) {
|
|
632
|
+
return (result.Entries ?? [])
|
|
633
|
+
.map(({ ErrorCode, ErrorMessage }, position) => ({
|
|
634
|
+
id: String(offset + position),
|
|
635
|
+
code: ErrorCode,
|
|
636
|
+
message: ErrorMessage,
|
|
637
|
+
}))
|
|
638
|
+
.filter(({ code }) => code !== undefined);
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Wrapper around the AWS EventBridge client providing structured Powertools
|
|
642
|
+
* logging and X-Ray tracing by default.
|
|
643
|
+
*
|
|
644
|
+
* Where a method's input carries payloads, secret material or PII, the INFO
|
|
645
|
+
* log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
|
|
646
|
+
* `TRACE`) log full SDK inputs.
|
|
647
|
+
*
|
|
648
|
+
* Covers `putEvents` only. Named `EventBridgeService` for the event bus API;
|
|
649
|
+
* schedules live in `SchedulerService`.
|
|
650
|
+
*/
|
|
651
|
+
class EventBridgeService {
|
|
652
|
+
client;
|
|
653
|
+
logger;
|
|
654
|
+
/**
|
|
655
|
+
* @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
|
|
656
|
+
* which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
|
|
657
|
+
* @param opts.client - Optional pre-configured `EventBridgeClient`. When
|
|
658
|
+
* supplied, the wrapper does not apply X-Ray instrumentation.
|
|
659
|
+
*/
|
|
660
|
+
constructor(opts) {
|
|
661
|
+
this.client = opts?.client ?? xray.captureAWSv3Client(new EventBridgeClient());
|
|
662
|
+
this.logger = opts?.logger ?? new Logger();
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Publish events to an event bus. The EventBridge API caps `PutEvents` at
|
|
666
|
+
* 10 entries per request, so this method auto-chunks the caller's `Entries`
|
|
667
|
+
* and sends one request per chunk, returning the array of outputs. The
|
|
668
|
+
* remaining request fields (such as `EndpointId`) are carried onto every
|
|
669
|
+
* chunk.
|
|
670
|
+
*
|
|
671
|
+
* Chunking is by count only. The 256 KB request size limit is not enforced
|
|
672
|
+
* here: a chunk that exceeds it fails at the SDK as a request-level error.
|
|
673
|
+
*
|
|
674
|
+
* Every chunk is sent before the outcome is judged. If EventBridge rejected
|
|
675
|
+
* any entry (it reports an error code on the result entry), a
|
|
676
|
+
* {@link BatchOperationError} is then thrown carrying the per-chunk results
|
|
677
|
+
* and the failed entries. For this method each failed entry's `id` is
|
|
678
|
+
* always set, to the entry's index in the caller's original `Entries` list
|
|
679
|
+
* across all chunks, as a string. Only `id`, `code` and `message` are
|
|
680
|
+
* copied out, so event detail never reaches the error.
|
|
681
|
+
*
|
|
682
|
+
* No retries are performed. Request-level SDK exceptions (throttling,
|
|
683
|
+
* access denied, oversize request) are not wrapped: they propagate
|
|
684
|
+
* unchanged and immediately, so earlier chunks may already have been
|
|
685
|
+
* published.
|
|
686
|
+
*
|
|
687
|
+
* At INFO level the log line includes only the endpoint id and the entry
|
|
688
|
+
* count, because `Detail`, `Resources` and the entries themselves are
|
|
689
|
+
* payload carriers.
|
|
690
|
+
*
|
|
691
|
+
* @param input - PutEventsCommandInput including Entries.
|
|
692
|
+
*/
|
|
693
|
+
async putEvents(input) {
|
|
694
|
+
const entries = input.Entries ?? [];
|
|
695
|
+
this.logger.info('Putting EventBridge events', {
|
|
696
|
+
input: redactInput(this.logger, input, summariseEntries$1),
|
|
697
|
+
});
|
|
698
|
+
const results = [];
|
|
699
|
+
for (const batch of chunk(entries, PUT_EVENTS_LIMIT)) {
|
|
700
|
+
results.push(await this.client.send(new PutEventsCommand({ ...input, Entries: batch })));
|
|
701
|
+
}
|
|
702
|
+
return throwIfAny(this.logger, 'EventBridge putEvents', results, extractPutEventsFailures(results));
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* Thrown by `LambdaService.invoke` when a synchronous invocation reached the
|
|
708
|
+
* function but the function itself failed. Lambda reports that as an HTTP 200
|
|
709
|
+
* carrying a function error marker, so the SDK does not throw.
|
|
710
|
+
*
|
|
711
|
+
* `functionError` is the SDK's marker (`Handled` or `Unhandled`).
|
|
712
|
+
* `errorType` and `errorMessage` are parsed from the response payload when it
|
|
713
|
+
* has the usual `{ errorType, errorMessage }` JSON shape, otherwise undefined.
|
|
714
|
+
*
|
|
715
|
+
* Deliberately excludes the raw SDK output and the stack trace: either can
|
|
716
|
+
* contain the caller's payload or PII.
|
|
717
|
+
*
|
|
718
|
+
* Match on `name` rather than `instanceof` if both the CJS and ESM builds of
|
|
719
|
+
* this package may be loaded in one process.
|
|
720
|
+
*/
|
|
721
|
+
class LambdaFunctionError extends Error {
|
|
722
|
+
functionName;
|
|
723
|
+
functionError;
|
|
724
|
+
name = 'LambdaFunctionError';
|
|
725
|
+
errorType;
|
|
726
|
+
errorMessage;
|
|
727
|
+
constructor(functionName, functionError, payload) {
|
|
728
|
+
super(`Lambda function ${functionName ?? '(unnamed)'} failed (${functionError})`);
|
|
729
|
+
this.functionName = functionName;
|
|
730
|
+
this.functionError = functionError;
|
|
731
|
+
this.errorType = payload.errorType;
|
|
732
|
+
this.errorMessage = payload.errorMessage;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Reads `errorType` and `errorMessage` out of a function error payload.
|
|
737
|
+
* Anything that is not a JSON object with string fields yields undefined for
|
|
738
|
+
* that field rather than failing, because the payload is whatever the invoked
|
|
739
|
+
* function (or runtime) chose to return.
|
|
740
|
+
*/
|
|
741
|
+
function parseFunctionErrorPayload(payload) {
|
|
742
|
+
const empty = { errorType: undefined, errorMessage: undefined };
|
|
743
|
+
if (payload === undefined)
|
|
744
|
+
return empty;
|
|
745
|
+
let parsed;
|
|
746
|
+
try {
|
|
747
|
+
parsed = JSON.parse(new TextDecoder().decode(payload));
|
|
748
|
+
}
|
|
749
|
+
catch {
|
|
750
|
+
return empty;
|
|
751
|
+
}
|
|
752
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
753
|
+
return empty;
|
|
754
|
+
const { errorType, errorMessage } = parsed;
|
|
755
|
+
return {
|
|
756
|
+
errorType: typeof errorType === 'string' ? errorType : undefined,
|
|
757
|
+
errorMessage: typeof errorMessage === 'string' ? errorMessage : undefined,
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* `Invoke` inputs carry the invocation `Payload` and the base64 `ClientContext`
|
|
763
|
+
* handed to the function, both of which routinely contain caller data and PII.
|
|
764
|
+
* Everything else identifies the target or how to call it.
|
|
765
|
+
*/
|
|
766
|
+
const INVOKE_SAFE_FIELDS = [
|
|
767
|
+
'FunctionName',
|
|
768
|
+
'InvocationType',
|
|
769
|
+
'Qualifier',
|
|
770
|
+
'LogType',
|
|
771
|
+
'TenantId',
|
|
772
|
+
];
|
|
773
|
+
/**
|
|
774
|
+
* Wrapper around the AWS Lambda client providing structured Powertools logging
|
|
775
|
+
* and X-Ray tracing by default.
|
|
776
|
+
*
|
|
777
|
+
* Where a method's input carries payloads, secret material or PII, the INFO
|
|
778
|
+
* log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
|
|
779
|
+
* `TRACE`) log full SDK inputs.
|
|
780
|
+
*
|
|
781
|
+
* Covers `invoke` only.
|
|
782
|
+
*/
|
|
783
|
+
class LambdaService {
|
|
784
|
+
client;
|
|
785
|
+
logger;
|
|
786
|
+
/**
|
|
787
|
+
* @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
|
|
788
|
+
* which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
|
|
789
|
+
* @param opts.client - Optional pre-configured `LambdaClient`. When
|
|
790
|
+
* supplied, the wrapper does not apply X-Ray instrumentation.
|
|
791
|
+
*/
|
|
792
|
+
constructor(opts) {
|
|
793
|
+
this.client = opts?.client ?? xray.captureAWSv3Client(new LambdaClient());
|
|
794
|
+
this.logger = opts?.logger ?? new Logger();
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Invoke a Lambda function. The input is the SDK input unchanged and the
|
|
798
|
+
* output is the SDK output unchanged: `Payload` stays a `Uint8Array` you
|
|
799
|
+
* decode yourself. Choose synchronous, asynchronous or dry-run invocation
|
|
800
|
+
* with `InvocationType`; omitting it means synchronous (`RequestResponse`).
|
|
801
|
+
*
|
|
802
|
+
* Lambda answers HTTP 200 even when the invoked function threw, flagging it
|
|
803
|
+
* with `FunctionError` on the response. If that marker is present this
|
|
804
|
+
* method warns and throws a {@link LambdaFunctionError} carrying the
|
|
805
|
+
* function name, the marker, and the error type and message parsed from the
|
|
806
|
+
* payload when it has the usual JSON shape. The raw output and the stack
|
|
807
|
+
* trace are deliberately left off the error.
|
|
808
|
+
*
|
|
809
|
+
* The marker only appears on synchronous responses, so the check is
|
|
810
|
+
* unconditional: asynchronous (`Event`) and `DryRun` responses return
|
|
811
|
+
* without throwing. Failures of asynchronous invocations are therefore not
|
|
812
|
+
* observable here; they belong to dead-letter queues and destinations on
|
|
813
|
+
* the invoked function. No status code check is added; service-level
|
|
814
|
+
* errors such as throttling are thrown by the SDK and propagate unwrapped.
|
|
815
|
+
*
|
|
816
|
+
* At INFO level the log line includes only the function name, invocation
|
|
817
|
+
* type, qualifier, log type and tenant id. `Payload` and `ClientContext` are
|
|
818
|
+
* omitted, and responses are never logged.
|
|
819
|
+
*
|
|
820
|
+
* @param input - InvokeCommandInput including FunctionName.
|
|
821
|
+
*/
|
|
822
|
+
async invoke(input) {
|
|
823
|
+
this.logger.info('Invoking Lambda function', {
|
|
824
|
+
input: redactInput(this.logger, input, INVOKE_SAFE_FIELDS),
|
|
825
|
+
});
|
|
826
|
+
const output = await this.client.send(new InvokeCommand(input));
|
|
827
|
+
if (output.FunctionError === undefined)
|
|
828
|
+
return output;
|
|
829
|
+
this.logger.warn('Lambda invoke function error', {
|
|
830
|
+
functionName: input.FunctionName,
|
|
831
|
+
functionError: output.FunctionError,
|
|
832
|
+
});
|
|
833
|
+
throw new LambdaFunctionError(input.FunctionName, output.FunctionError, parseFunctionErrorPayload(output.Payload));
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
526
837
|
const DEFAULT_PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
|
|
527
838
|
const DELETE_OBJECTS_BATCH_LIMIT = 1000;
|
|
528
839
|
/**
|
|
@@ -715,6 +1026,12 @@ class S3Service {
|
|
|
715
1026
|
* Delete multiple objects from S3, auto-chunking the request into batches
|
|
716
1027
|
* of 1000 keys (the S3-enforced DeleteObjects limit). Returns one output
|
|
717
1028
|
* per chunk.
|
|
1029
|
+
*
|
|
1030
|
+
* Every chunk is sent before the outcome is judged. If S3 reported a
|
|
1031
|
+
* per-key delete error, a {@link BatchOperationError} is then thrown
|
|
1032
|
+
* carrying the per-chunk results and the failed keys. Request-level SDK
|
|
1033
|
+
* exceptions (throttling, access denied) propagate unchanged and
|
|
1034
|
+
* immediately, so earlier chunks may already have been deleted.
|
|
718
1035
|
*/
|
|
719
1036
|
async deleteObjects(bucket, keys) {
|
|
720
1037
|
this.logger.info('Deleting S3 objects', {
|
|
@@ -730,13 +1047,20 @@ class S3Service {
|
|
|
730
1047
|
Delete: { Objects: batch.map(Key => ({ Key })) },
|
|
731
1048
|
})));
|
|
732
1049
|
}
|
|
733
|
-
return results;
|
|
1050
|
+
return throwIfAnyDeleteErrors(this.logger, 'S3 deleteObjects', results);
|
|
734
1051
|
}
|
|
735
1052
|
/**
|
|
736
1053
|
* Delete every object in an **unversioned** bucket. Streams the listing
|
|
737
|
-
* page-by-page and delegates each page's deletion to `deleteObjects`, so
|
|
738
|
-
*
|
|
739
|
-
*
|
|
1054
|
+
* page-by-page and delegates each page's deletion to `deleteObjects`, so no
|
|
1055
|
+
* more than one page (~1000 keys) of SDK responses is held at a time. The
|
|
1056
|
+
* only thing that grows with the bucket is the list of deleted keys this
|
|
1057
|
+
* method returns.
|
|
1058
|
+
*
|
|
1059
|
+
* A page with per-key delete errors does not stop the run: every page is
|
|
1060
|
+
* attempted, then one {@link BatchOperationError} is thrown carrying every
|
|
1061
|
+
* failed key in `failed` and, per page, the keys that were deleted in
|
|
1062
|
+
* `results`. Request-level SDK exceptions propagate unchanged and
|
|
1063
|
+
* immediately, so earlier pages may already have been deleted.
|
|
740
1064
|
*
|
|
741
1065
|
* **Versioned buckets are out of scope.** This paginates `ListObjectsV2`,
|
|
742
1066
|
* which reports only current object versions — never noncurrent versions or
|
|
@@ -747,20 +1071,39 @@ class S3Service {
|
|
|
747
1071
|
* versioned bucket requires `ListObjectVersions` and per-version deletes;
|
|
748
1072
|
* use `S3Client` directly for that.
|
|
749
1073
|
*
|
|
750
|
-
* @returns The keys
|
|
1074
|
+
* @returns The keys that were deleted.
|
|
1075
|
+
* @throws {BatchOperationError} If S3 could not delete one or more keys.
|
|
751
1076
|
*/
|
|
752
1077
|
async emptyBucket(bucket) {
|
|
753
1078
|
this.logger.info('Emptying S3 bucket', { input: { bucket } });
|
|
754
1079
|
const paginator = paginateListObjectsV2({ client: this.client }, { Bucket: bucket });
|
|
755
|
-
const
|
|
1080
|
+
const pages = [];
|
|
1081
|
+
const failed = [];
|
|
756
1082
|
for await (const page of paginator) {
|
|
757
1083
|
const keys = (page.Contents ?? []).flatMap(o => (o.Key ? [o.Key] : []));
|
|
758
1084
|
if (keys.length === 0)
|
|
759
1085
|
continue;
|
|
1086
|
+
const outcome = await this.deletePage(bucket, keys);
|
|
1087
|
+
pages.push({ deletedKeys: outcome.deletedKeys });
|
|
1088
|
+
failed.push(...outcome.failed);
|
|
1089
|
+
}
|
|
1090
|
+
throwIfAny(this.logger, 'S3 emptyBucket', pages, failed);
|
|
1091
|
+
return pages.flatMap(page => page.deletedKeys);
|
|
1092
|
+
}
|
|
1093
|
+
async deletePage(bucket, keys) {
|
|
1094
|
+
try {
|
|
760
1095
|
await this.deleteObjects(bucket, keys);
|
|
761
|
-
deletedKeys
|
|
1096
|
+
return { deletedKeys: keys, failed: [] };
|
|
1097
|
+
}
|
|
1098
|
+
catch (error) {
|
|
1099
|
+
if (!(error instanceof BatchOperationError))
|
|
1100
|
+
throw error;
|
|
1101
|
+
const failedKeys = new Set(error.failed.map(entry => entry.id));
|
|
1102
|
+
return {
|
|
1103
|
+
deletedKeys: keys.filter(key => !failedKeys.has(key)),
|
|
1104
|
+
failed: error.failed,
|
|
1105
|
+
};
|
|
762
1106
|
}
|
|
763
|
-
return deletedKeys;
|
|
764
1107
|
}
|
|
765
1108
|
}
|
|
766
1109
|
|
|
@@ -792,8 +1135,9 @@ function stripTargetInput(input) {
|
|
|
792
1135
|
* `TRACE`) log full SDK inputs.
|
|
793
1136
|
*
|
|
794
1137
|
* Covers CRUD on schedules and their groups. Named `SchedulerService` (not
|
|
795
|
-
* `EventBridgeSchedulerService`) so it doesn't collide with
|
|
796
|
-
* over the separate EventBridge bus/rules API
|
|
1138
|
+
* `EventBridgeSchedulerService`) so it doesn't collide with `EventBridgeService`,
|
|
1139
|
+
* the wrapper over the separate EventBridge bus/rules API
|
|
1140
|
+
* (`@aws-sdk/client-eventbridge`).
|
|
797
1141
|
*
|
|
798
1142
|
* `FlexibleTimeWindow` is required by `CreateSchedule` and is passed through
|
|
799
1143
|
* untouched — the wrapper bakes in no default, so the caller must state their
|
|
@@ -1111,59 +1455,6 @@ class StepFunctionsService {
|
|
|
1111
1455
|
}
|
|
1112
1456
|
}
|
|
1113
1457
|
|
|
1114
|
-
/**
|
|
1115
|
-
* Thrown by the batch methods once every chunk has been sent and at least one
|
|
1116
|
-
* entry was rejected.
|
|
1117
|
-
*
|
|
1118
|
-
* `results` holds the raw SDK output of every chunk, so the outputs of the
|
|
1119
|
-
* entries that succeeded (message ids, sequence numbers) stay readable.
|
|
1120
|
-
* `failed` is the normalised list of rejected entries across all chunks.
|
|
1121
|
-
*
|
|
1122
|
-
* Match on `name` rather than `instanceof` if both the CJS and ESM builds of
|
|
1123
|
-
* this package may be loaded in one process.
|
|
1124
|
-
*/
|
|
1125
|
-
class BatchOperationError extends Error {
|
|
1126
|
-
results;
|
|
1127
|
-
failed;
|
|
1128
|
-
name = 'BatchOperationError';
|
|
1129
|
-
constructor(results, failed) {
|
|
1130
|
-
super(`Batch operation failed for ${failed.length} entries (${distinctCodes(failed).join(', ')})`);
|
|
1131
|
-
this.results = results;
|
|
1132
|
-
this.failed = failed;
|
|
1133
|
-
}
|
|
1134
|
-
}
|
|
1135
|
-
/**
|
|
1136
|
-
* SQS and SNS report rejected entries under `Failed` on an otherwise
|
|
1137
|
-
* successful response, so a resolved chunk does not mean every entry was
|
|
1138
|
-
* accepted. Returns `results` untouched when nothing failed; otherwise warns
|
|
1139
|
-
* and throws a {@link BatchOperationError}.
|
|
1140
|
-
*
|
|
1141
|
-
* Only id, code and message are copied out — never the entry itself — so
|
|
1142
|
-
* neither the error nor the warning can leak a payload.
|
|
1143
|
-
*/
|
|
1144
|
-
function throwIfAnyFailed(logger, operation, results) {
|
|
1145
|
-
const failed = results.flatMap(result => (result.Failed ?? []).map(({ Id, Code, Message }) => ({
|
|
1146
|
-
id: Id,
|
|
1147
|
-
code: Code,
|
|
1148
|
-
message: Message,
|
|
1149
|
-
})));
|
|
1150
|
-
if (failed.length === 0)
|
|
1151
|
-
return results;
|
|
1152
|
-
logger.warn(`${operation} had rejected entries`, {
|
|
1153
|
-
failedCount: failed.length,
|
|
1154
|
-
codes: distinctCodes(failed),
|
|
1155
|
-
});
|
|
1156
|
-
throw new BatchOperationError(results, failed);
|
|
1157
|
-
}
|
|
1158
|
-
/**
|
|
1159
|
-
* Distinct error codes in first-seen order, for the error message and the
|
|
1160
|
-
* warning log line.
|
|
1161
|
-
*/
|
|
1162
|
-
function distinctCodes(failed) {
|
|
1163
|
-
const codes = failed.flatMap(entry => (entry.code === undefined ? [] : [entry.code]));
|
|
1164
|
-
return [...new Set(codes)];
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
1458
|
/**
|
|
1168
1459
|
* Truncate a UTF-8 string to fit within `maxBytes` when encoded as UTF-8.
|
|
1169
1460
|
*
|
|
@@ -1467,6 +1758,19 @@ class SQSService {
|
|
|
1467
1758
|
}
|
|
1468
1759
|
|
|
1469
1760
|
const GET_PARAMETERS_LIMIT = 10;
|
|
1761
|
+
/**
|
|
1762
|
+
* One failed entry per alias whose path SSM reported as invalid, so two
|
|
1763
|
+
* aliases sharing a missing path are both named.
|
|
1764
|
+
*/
|
|
1765
|
+
function missingParameters(aliases, invalidPaths) {
|
|
1766
|
+
return Object.entries(aliases)
|
|
1767
|
+
.filter(([, path]) => invalidPaths.has(path))
|
|
1768
|
+
.map(([alias, path]) => ({
|
|
1769
|
+
id: path,
|
|
1770
|
+
code: 'ParameterNotFound',
|
|
1771
|
+
message: `Parameter not found for alias "${alias}"`,
|
|
1772
|
+
}));
|
|
1773
|
+
}
|
|
1470
1774
|
/**
|
|
1471
1775
|
* Fields safe to log at INFO level for `putParameter`. Omits `Value` (the
|
|
1472
1776
|
* parameter content itself).
|
|
@@ -1517,6 +1821,9 @@ class SSMService {
|
|
|
1517
1821
|
* @param name - The parameter name (or ARN).
|
|
1518
1822
|
* @returns The parameter value, or `undefined` if the parameter has no
|
|
1519
1823
|
* value set.
|
|
1824
|
+
* @throws When the parameter does not exist (the SDK's
|
|
1825
|
+
* `ParameterNotFound`). {@link SSMService.getParameters} instead returns
|
|
1826
|
+
* `undefined` for a missing parameter unless `required` is set.
|
|
1520
1827
|
*/
|
|
1521
1828
|
async getParameter(name) {
|
|
1522
1829
|
this.logger.info('Fetching SSM parameter', { input: { name } });
|
|
@@ -1541,16 +1848,27 @@ class SSMService {
|
|
|
1541
1848
|
* the underlying parameter names and sends one request per chunk,
|
|
1542
1849
|
* merging the results before building the alias-keyed return value.
|
|
1543
1850
|
*
|
|
1851
|
+
* Unlike {@link SSMService.getParameter}, which throws when the parameter
|
|
1852
|
+
* does not exist, a missing parameter here maps to `undefined` — so a
|
|
1853
|
+
* typo'd path surfaces later as an undefined value. Pass
|
|
1854
|
+
* `{ required: true }` to fail fast instead: every chunk is still sent,
|
|
1855
|
+
* then a {@link BatchOperationError} is thrown whose `failed` entries
|
|
1856
|
+
* carry each missing path as `id`, the code `ParameterNotFound`, and the
|
|
1857
|
+
* alias in `message`. Request-level SDK exceptions are not wrapped.
|
|
1858
|
+
*
|
|
1544
1859
|
* @param aliases - Record mapping each desired local alias to its SSM
|
|
1545
1860
|
* parameter name (or ARN).
|
|
1861
|
+
* @param opts.required - Throw when any requested parameter does not
|
|
1862
|
+
* exist. Defaults to `false`.
|
|
1546
1863
|
* @returns A record keyed by the same aliases, mapping each to the
|
|
1547
|
-
* parameter's value, or `undefined` when the parameter is missing
|
|
1548
|
-
* no value.
|
|
1864
|
+
* parameter's value, or `undefined` when the parameter is missing (unless
|
|
1865
|
+
* `required` is set) or has no value.
|
|
1549
1866
|
*/
|
|
1550
|
-
async getParameters(aliases) {
|
|
1867
|
+
async getParameters(aliases, opts) {
|
|
1551
1868
|
this.logger.info('Fetching SSM parameters', { input: { aliases } });
|
|
1552
1869
|
const names = Object.values(aliases);
|
|
1553
1870
|
const byPath = new Map();
|
|
1871
|
+
const invalidPaths = new Set();
|
|
1554
1872
|
for (const batch of chunk(names, GET_PARAMETERS_LIMIT)) {
|
|
1555
1873
|
const response = await this.client.send(new GetParametersCommand({
|
|
1556
1874
|
Names: batch,
|
|
@@ -1560,6 +1878,12 @@ class SSMService {
|
|
|
1560
1878
|
if (parameter.Name !== undefined)
|
|
1561
1879
|
byPath.set(parameter.Name, parameter.Value);
|
|
1562
1880
|
}
|
|
1881
|
+
for (const name of response.InvalidParameters ?? [])
|
|
1882
|
+
invalidPaths.add(name);
|
|
1883
|
+
}
|
|
1884
|
+
if (opts?.required) {
|
|
1885
|
+
// No per-chunk results: the SDK output of a failed lookup adds nothing
|
|
1886
|
+
throwIfAny(this.logger, 'SSM getParameters', [], missingParameters(aliases, invalidPaths));
|
|
1563
1887
|
}
|
|
1564
1888
|
const result = {};
|
|
1565
1889
|
for (const alias of Object.keys(aliases)) {
|
|
@@ -1611,4 +1935,4 @@ class SSMService {
|
|
|
1611
1935
|
}
|
|
1612
1936
|
}
|
|
1613
1937
|
|
|
1614
|
-
export { APIGatewayService, APIGatewayV2Service, BatchOperationError, DynamoDBService, S3Service, SNSService, SQSService, SSMService, SchedulerService, SecretsManagerService, StepFunctionsService };
|
|
1938
|
+
export { APIGatewayService, APIGatewayV2Service, BatchOperationError, DynamoDBService, EventBridgeService, LambdaFunctionError, LambdaService, S3Service, SNSService, SQSService, SSMService, SchedulerService, SecretsManagerService, StepFunctionsService };
|
package/esm/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aligent/aws-wrappers",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.9",
|
|
4
4
|
"description": "Opinionated AWS SDK wrappers with Powertools logging and X-Ray tracing",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=18"
|
|
@@ -43,19 +43,21 @@
|
|
|
43
43
|
"directory": "packages/aws-wrappers"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@aws-lambda-powertools/logger": "^2.
|
|
47
|
-
"@aws-sdk/client-api-gateway": "^3.
|
|
48
|
-
"@aws-sdk/client-apigatewayv2": "^3.
|
|
49
|
-
"@aws-sdk/client-dynamodb": "^3.
|
|
50
|
-
"@aws-sdk/client-
|
|
51
|
-
"@aws-sdk/client-
|
|
52
|
-
"@aws-sdk/client-
|
|
53
|
-
"@aws-sdk/client-
|
|
54
|
-
"@aws-sdk/client-
|
|
55
|
-
"@aws-sdk/client-
|
|
56
|
-
"@aws-sdk/client-
|
|
57
|
-
"@aws-sdk/
|
|
58
|
-
"@aws-sdk/
|
|
46
|
+
"@aws-lambda-powertools/logger": "^2.36.0",
|
|
47
|
+
"@aws-sdk/client-api-gateway": "^3.1160.0",
|
|
48
|
+
"@aws-sdk/client-apigatewayv2": "^3.1160.0",
|
|
49
|
+
"@aws-sdk/client-dynamodb": "^3.1160.0",
|
|
50
|
+
"@aws-sdk/client-eventbridge": "^3.1160.0",
|
|
51
|
+
"@aws-sdk/client-lambda": "^3.1160.0",
|
|
52
|
+
"@aws-sdk/client-s3": "^3.1160.0",
|
|
53
|
+
"@aws-sdk/client-scheduler": "^3.1160.0",
|
|
54
|
+
"@aws-sdk/client-secrets-manager": "^3.1160.0",
|
|
55
|
+
"@aws-sdk/client-sfn": "^3.1160.0",
|
|
56
|
+
"@aws-sdk/client-sns": "^3.1160.0",
|
|
57
|
+
"@aws-sdk/client-sqs": "^3.1160.0",
|
|
58
|
+
"@aws-sdk/client-ssm": "^3.1160.0",
|
|
59
|
+
"@aws-sdk/lib-dynamodb": "^3.1160.0",
|
|
60
|
+
"@aws-sdk/s3-request-presigner": "^3.1160.0",
|
|
59
61
|
"aws-xray-sdk-core": "^3.12.0"
|
|
60
62
|
},
|
|
61
63
|
"author": "Aligent",
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { LoggerInterface } from '@aws-lambda-powertools/logger/types';
|
|
2
|
+
import { EventBridgeClient, PutEventsCommandInput, PutEventsCommandOutput } from '@aws-sdk/client-eventbridge';
|
|
3
|
+
/**
|
|
4
|
+
* Wrapper around the AWS EventBridge client providing structured Powertools
|
|
5
|
+
* logging and X-Ray tracing by default.
|
|
6
|
+
*
|
|
7
|
+
* Where a method's input carries payloads, secret material or PII, the INFO
|
|
8
|
+
* log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
|
|
9
|
+
* `TRACE`) log full SDK inputs.
|
|
10
|
+
*
|
|
11
|
+
* Covers `putEvents` only. Named `EventBridgeService` for the event bus API;
|
|
12
|
+
* schedules live in `SchedulerService`.
|
|
13
|
+
*/
|
|
14
|
+
export declare class EventBridgeService {
|
|
15
|
+
private readonly client;
|
|
16
|
+
private readonly logger;
|
|
17
|
+
/**
|
|
18
|
+
* @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
|
|
19
|
+
* which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
|
|
20
|
+
* @param opts.client - Optional pre-configured `EventBridgeClient`. When
|
|
21
|
+
* supplied, the wrapper does not apply X-Ray instrumentation.
|
|
22
|
+
*/
|
|
23
|
+
constructor(opts?: {
|
|
24
|
+
logger?: LoggerInterface;
|
|
25
|
+
client?: EventBridgeClient;
|
|
26
|
+
});
|
|
27
|
+
/**
|
|
28
|
+
* Publish events to an event bus. The EventBridge API caps `PutEvents` at
|
|
29
|
+
* 10 entries per request, so this method auto-chunks the caller's `Entries`
|
|
30
|
+
* and sends one request per chunk, returning the array of outputs. The
|
|
31
|
+
* remaining request fields (such as `EndpointId`) are carried onto every
|
|
32
|
+
* chunk.
|
|
33
|
+
*
|
|
34
|
+
* Chunking is by count only. The 256 KB request size limit is not enforced
|
|
35
|
+
* here: a chunk that exceeds it fails at the SDK as a request-level error.
|
|
36
|
+
*
|
|
37
|
+
* Every chunk is sent before the outcome is judged. If EventBridge rejected
|
|
38
|
+
* any entry (it reports an error code on the result entry), a
|
|
39
|
+
* {@link BatchOperationError} is then thrown carrying the per-chunk results
|
|
40
|
+
* and the failed entries. For this method each failed entry's `id` is
|
|
41
|
+
* always set, to the entry's index in the caller's original `Entries` list
|
|
42
|
+
* across all chunks, as a string. Only `id`, `code` and `message` are
|
|
43
|
+
* copied out, so event detail never reaches the error.
|
|
44
|
+
*
|
|
45
|
+
* No retries are performed. Request-level SDK exceptions (throttling,
|
|
46
|
+
* access denied, oversize request) are not wrapped: they propagate
|
|
47
|
+
* unchanged and immediately, so earlier chunks may already have been
|
|
48
|
+
* published.
|
|
49
|
+
*
|
|
50
|
+
* At INFO level the log line includes only the endpoint id and the entry
|
|
51
|
+
* count, because `Detail`, `Resources` and the entries themselves are
|
|
52
|
+
* payload carriers.
|
|
53
|
+
*
|
|
54
|
+
* @param input - PutEventsCommandInput including Entries.
|
|
55
|
+
*/
|
|
56
|
+
putEvents(input: PutEventsCommandInput): Promise<PutEventsCommandOutput[]>;
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=eventbridge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"eventbridge.d.ts","sourceRoot":"","sources":["../../../../src/eventbridge/eventbridge.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EACH,iBAAiB,EAEjB,qBAAqB,EACrB,sBAAsB,EAEzB,MAAM,6BAA6B,CAAC;AA4CrC;;;;;;;;;;GAUG;AACH,qBAAa,kBAAkB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAoB;IAC3C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkB;IAEzC;;;;;OAKG;gBACS,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,eAAe,CAAC;QAAC,MAAM,CAAC,EAAE,iBAAiB,CAAA;KAAE;IAK3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACG,SAAS,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC,sBAAsB,EAAE,CAAC;CAkBnF"}
|