agent-claw: automated task changes

This commit is contained in:
daniel
2026-05-06 18:55:16 -05:00
parent 38905bb1e9
commit 732b00fb66
8494 changed files with 2018127 additions and 4 deletions

View File

@@ -0,0 +1,13 @@
{
"targets": {
"java": {
"package": "software.amazon.awscdk.services.lambda.eventsources"
},
"dotnet": {
"namespace": "Amazon.CDK.AWS.Lambda.EventSources"
},
"python": {
"module": "aws_cdk.aws_lambda_event_sources"
}
}
}

View File

@@ -0,0 +1,693 @@
# AWS Lambda Event Sources
An event source mapping is an AWS Lambda resource that reads from an event source and invokes a Lambda function.
You can use event source mappings to process items from a stream or queue in services that don't invoke Lambda
functions directly. Lambda provides event source mappings for the following services. Read more about lambda
event sources [here](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html).
This module includes classes that allow using various AWS services as event
sources for AWS Lambda via the high-level `lambda.addEventSource(source)` API.
NOTE: In most cases, it is also possible to use the resource APIs to invoke an
AWS Lambda function. This library provides a uniform API for all Lambda event
sources regardless of the underlying mechanism they use.
The following code sets up a lambda function with an SQS queue event source -
```ts
import { SqsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
declare const fn: lambda.Function;
const queue = new sqs.Queue(this, 'MyQueue');
const eventSource = new SqsEventSource(queue);
fn.addEventSource(eventSource);
const eventSourceId = eventSource.eventSourceMappingId;
const eventSourceMappingArn = eventSource.eventSourceMappingArn;
```
The `eventSourceId` property contains the event source id. This will be a
[token](https://docs.aws.amazon.com/cdk/latest/guide/tokens.html) that will resolve to the final value at the time of
deployment.
The `eventSourceMappingArn` property contains the event source mapping ARN. This will be a
[token](https://docs.aws.amazon.com/cdk/latest/guide/tokens.html) that will resolve to the final value at the time of
deployment.
## SQS
Amazon Simple Queue Service (Amazon SQS) allows you to build asynchronous
workflows. For more information about Amazon SQS, see Amazon Simple Queue
Service. You can configure AWS Lambda to poll for these messages as they arrive
and then pass the event to a Lambda function invocation. To view a sample event,
see [Amazon SQS Event](https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-sqs).
To set up Amazon Simple Queue Service as an event source for AWS Lambda, you
first create or update an Amazon SQS queue and select custom values for the
queue parameters. The following parameters will impact Amazon SQS's polling
behavior:
* __visibilityTimeout__: May impact the period between retries.
* __batchSize__: Determines how many records are buffered before invoking your lambda function.
* __maxBatchingWindow__: The maximum amount of time to gather records before invoking the lambda. This increases the likelihood of a full batch at the cost of delayed processing.
* __maxConcurrency__: The maximum concurrency setting limits the number of concurrent instances of the function that an Amazon SQS event source can invoke.
* __enabled__: If the SQS event source mapping should be enabled. The default is true.
```ts
import { SqsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
const queue = new sqs.Queue(this, 'MyQueue', {
visibilityTimeout: Duration.seconds(30), // default,
});
declare const fn: lambda.Function;
fn.addEventSource(new SqsEventSource(queue, {
batchSize: 10, // default
maxBatchingWindow: Duration.minutes(5),
reportBatchItemFailures: true, // default to false
}));
```
## S3
You can write Lambda functions to process S3 bucket events, such as the
object-created or object-deleted events. For example, when a user uploads a
photo to a bucket, you might want Amazon S3 to invoke your Lambda function so
that it reads the image and creates a thumbnail for the photo.
You can use the bucket notification configuration feature in Amazon S3 to
configure the event source mapping, identifying the bucket events that you want
Amazon S3 to publish and which Lambda function to invoke.
```ts
import * as s3 from 'aws-cdk-lib/aws-s3';
import { S3EventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
const bucket = new s3.Bucket(this, 'mybucket');
declare const fn: lambda.Function;
fn.addEventSource(new S3EventSource(bucket, {
events: [ s3.EventType.OBJECT_CREATED, s3.EventType.OBJECT_REMOVED ],
filters: [ { prefix: 'subdir/' } ], // optional
}));
```
In the example above, `S3EventSource` is accepting `Bucket` type as parameter.
However, Functions like `from_bucket_name` and `from_bucket_arn` will return `IBucket`
and is not compliant with `S3EventSource`. If this is the case, please consider using
`S3EventSourceV2` instead, this class accepts `IBucket`.
```ts
import * as s3 from 'aws-cdk-lib/aws-s3';
import { S3EventSourceV2 } from 'aws-cdk-lib/aws-lambda-event-sources';
const bucket = s3.Bucket.fromBucketName(this, 'Bucket', 'amzn-s3-demo-bucket');
declare const fn: lambda.Function;
fn.addEventSource(new S3EventSourceV2(bucket, {
events: [ s3.EventType.OBJECT_CREATED, s3.EventType.OBJECT_REMOVED ],
filters: [ { prefix: 'subdir/' } ], // optional
}));
```
## SNS
You can write Lambda functions to process Amazon Simple Notification Service
notifications. When a message is published to an Amazon SNS topic, the service
can invoke your Lambda function by passing the message payload as a parameter.
Your Lambda function code can then process the event, for example publish the
message to other Amazon SNS topics, or send the message to other AWS services.
This also enables you to trigger a Lambda function in response to Amazon
CloudWatch alarms and other AWS services that use Amazon SNS.
For an example event, see [Appendix: Message and JSON
Formats](https://docs.aws.amazon.com/sns/latest/dg/json-formats.html) and
[Amazon SNS Sample
Event](https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-sns).
For an example use case, see [Using AWS Lambda with Amazon SNS from Different
Accounts](https://docs.aws.amazon.com/lambda/latest/dg/with-sns.html).
```ts
import * as sns from 'aws-cdk-lib/aws-sns';
import { SnsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
declare const topic: sns.Topic;
const deadLetterQueue = new sqs.Queue(this, 'deadLetterQueue');
declare const fn: lambda.Function;
fn.addEventSource(new SnsEventSource(topic, {
filterPolicy: { },
deadLetterQueue: deadLetterQueue,
}));
```
When a user calls the SNS Publish API on a topic that your Lambda function is
subscribed to, Amazon SNS will call Lambda to invoke your function
asynchronously. Lambda will then return a delivery status. If there was an error
calling Lambda, Amazon SNS will retry invoking the Lambda function up to three
times. After three tries, if Amazon SNS still could not successfully invoke the
Lambda function, then Amazon SNS will send a delivery status failure message to
CloudWatch.
## DynamoDB Streams
You can write Lambda functions to process change events from a DynamoDB Table. An event is emitted to a DynamoDB stream (if configured) whenever a write (Put, Delete, Update)
operation is performed against the table. See [Using AWS Lambda with Amazon DynamoDB](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html) for more information about configuring Lambda function event sources with DynamoDB.
To process events with a Lambda function, first create or update a DynamoDB table and enable a `stream` specification. Then, create a `DynamoEventSource`
and add it to your Lambda function. The following parameters will impact Amazon DynamoDB's polling behavior:
* __batchSize__: Determines how many records are buffered before invoking your lambda function - could impact your function's memory usage (if too high) and ability to keep up with incoming data velocity (if too low).
* __bisectBatchOnError__: If a batch encounters an error, this will cause the batch to be split in two and have each new smaller batch retried, allowing the records in error to be isolated.
* __reportBatchItemFailures__: Allow functions to return partially successful responses for a batch of records.
* __maxBatchingWindow__: The maximum amount of time to gather records before invoking the lambda. This increases the likelihood of a full batch at the cost of delayed processing.
* __maxRecordAge__: The maximum age of a record that will be sent to the function for processing. Records that exceed the max age will be treated as failures.
* __onFailure__: In the event a record fails after all retries or if the record age has exceeded the configured value, the record will be sent to S3 bucket, SQS queue or SNS topic that is specified here
* __parallelizationFactor__: The number of batches to concurrently process on each shard.
* __retryAttempts__: The maximum number of times a record should be retried in the event of failure.
* __startingPosition__: Will determine where to being consumption, either at the most recent ('LATEST') record or the oldest record ('TRIM_HORIZON'). 'TRIM_HORIZON' will ensure you process all available data, while 'LATEST' will ignore all records that arrived prior to attaching the event source.
* __tumblingWindow__: The duration in seconds of a processing window when using streams.
* __enabled__: If the DynamoDB Streams event source mapping should be enabled. The default is true.
* __filters__: Filters to apply before sending a change event from a DynamoDB table to a Lambda function. Events that are filtered out are not sent to the Lambda function.
```ts
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { DynamoEventSource, SqsDlq } from 'aws-cdk-lib/aws-lambda-event-sources';
declare const table: dynamodb.Table;
const deadLetterQueue = new sqs.Queue(this, 'deadLetterQueue');
declare const fn: lambda.Function;
fn.addEventSource(new DynamoEventSource(table, {
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
batchSize: 5,
bisectBatchOnError: true,
onFailure: new SqsDlq(deadLetterQueue),
retryAttempts: 10,
}));
```
The following code sets up a Lambda function with a DynamoDB event source. A filter is applied to only send DynamoDB events to
the Lambda function when the `id` column is a boolean that equals `true`.
```ts
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { DynamoEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
declare const table: dynamodb.Table;
declare const fn: lambda.Function;
fn.addEventSource(new DynamoEventSource(table, {
startingPosition: lambda.StartingPosition.LATEST,
filters: [
lambda.FilterCriteria.filter({
eventName: lambda.FilterRule.isEqual('INSERT'),
dynamodb: {
NewImage: {
id: { BOOL: lambda.FilterRule.isEqual(true) },
},
},
}),
],
}));
```
## Kinesis
You can write Lambda functions to process streaming data in Amazon Kinesis Streams. For more information about Amazon Kinesis, see [Amazon Kinesis
Service](https://aws.amazon.com/kinesis/data-streams/). To learn more about configuring Lambda function event sources with kinesis and view a sample event,
see [Amazon Kinesis Event](https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html).
To set up Amazon Kinesis as an event source for AWS Lambda, you
first create or update an Amazon Kinesis stream and select custom values for the
event source parameters. The following parameters will impact Amazon Kinesis's polling
behavior:
* __batchSize__: Determines how many records are buffered before invoking your lambda function - could impact your function's memory usage (if too high) and ability to keep up with incoming data velocity (if too low).
* __bisectBatchOnError__: If a batch encounters an error, this will cause the batch to be split in two and have each new smaller batch retried, allowing the records in error to be isolated.
* __reportBatchItemFailures__: Allow functions to return partially successful responses for a batch of records.
* __maxBatchingWindow__: The maximum amount of time to gather records before invoking the lambda. This increases the likelihood of a full batch at the cost of possibly delaying processing.
* __maxRecordAge__: The maximum age of a record that will be sent to the function for processing. Records that exceed the max age will be treated as failures.
* __onFailure__: In the event a record fails and consumes all retries, the record will be sent to S3 bucket, SQS queue or SNS topic that is specified here
* __parallelizationFactor__: The number of batches to concurrently process on each shard.
* __retryAttempts__: The maximum number of times a record should be retried in the event of failure.
* __startingPosition__: Will determine where to begin consumption. 'LATEST' will start at the most recent record and ignore all records that arrived prior to attaching the event source, 'TRIM_HORIZON' will start at the oldest record and ensure you process all available data, while 'AT_TIMESTAMP' will start reading records from a specified time stamp.
* __startingPositionTimestamp__: The time stamp from which to start reading. Used in conjunction with __startingPosition__ when set to 'AT_TIMESTAMP'.
* __tumblingWindow__: The duration in seconds of a processing window when using streams.
* __enabled__: If the event source mapping should be enabled. The default is true.
```ts
import * as kinesis from 'aws-cdk-lib/aws-kinesis';
import { KinesisEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
const stream = new kinesis.Stream(this, 'MyStream');
declare const myFunction: lambda.Function;
myFunction.addEventSource(new KinesisEventSource(stream, {
batchSize: 100, // default
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
}));
```
To use a dedicated-throughput consumer with enhanced fan-out
```ts
import * as kinesis from 'aws-cdk-lib/aws-kinesis';
import { KinesisConsumerEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
const stream = new kinesis.Stream(this, 'MyStream');
const streamConsumer = new kinesis.StreamConsumer(this, 'MyStreamConsumer', {
stream,
streamConsumerName: 'MyStreamConsumer',
});
declare const myFunction: lambda.Function;
myFunction.addEventSource(new KinesisConsumerEventSource(streamConsumer, {
batchSize: 100, // default
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
}));
```
## Kafka
You can write Lambda functions to process data either from [Amazon MSK](https://docs.aws.amazon.com/lambda/latest/dg/with-msk.html) or a [self-managed Kafka](https://docs.aws.amazon.com/lambda/latest/dg/kafka-smaa.html) cluster. The following parameters will impact to the polling behavior:
* __startingPosition__: Will determine where to begin consumption. 'LATEST' will start at the most recent record and ignore all records that arrived prior to attaching the event source, 'TRIM_HORIZON' will start at the oldest record and ensure you process all available data, while 'AT_TIMESTAMP' will start reading records from a specified time stamp.
* __startingPositionTimestamp__: The time stamp from which to start reading. Used in conjunction with __startingPosition__ when set to 'AT_TIMESTAMP'.
* __batchSize__: Determines how many records are buffered before invoking your lambda function - could impact your function's memory usage (if too high) and ability to keep up with incoming data velocity (if too low).
* __maxBatchingWindow__: The maximum amount of time to gather records before invoking the lambda. This increases the likelihood of a full batch at the cost of possibly delaying processing.
* __onFailure__: In the event a record fails and consumes all retries, the record will be sent to SQS queue or SNS topic that is specified here
* __enabled__: If the Kafka event source mapping should be enabled. The default is true.
* __bisectBatchOnError__: If a batch encounters an error, this will cause the batch to be split in two and have each new smaller batch retried, allowing the records in error to be isolated. Available in provisioned mode only.
* __reportBatchItemFailures__: Allow functions to return partially successful responses for a batch of records. Available in provisioned mode only.
* __retryAttempts__: The maximum number of times a record should be retried in the event of failure. Available in provisioned mode only.
* __maxRecordAge__: The maximum age of a record that will be sent to the function for processing. Records that exceed the max age will be treated as failures. Available in provisioned mode only.
The following code sets up Amazon MSK as an event source for a lambda function. Credentials will need to be configured to access the
MSK cluster, as described in [Username/Password authentication](https://docs.aws.amazon.com/msk/latest/developerguide/msk-password.html).
```ts
import { Secret } from 'aws-cdk-lib/aws-secretsmanager';
import { ManagedKafkaEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
// Your MSK cluster arn
const clusterArn = 'arn:aws:kafka:us-east-1:0123456789019:cluster/SalesCluster/abcd1234-abcd-cafe-abab-9876543210ab-4';
// The Kafka topic you want to subscribe to
const topic = 'some-cool-topic';
// The secret that allows access to your MSK cluster
const secret = new Secret(this, 'Secret', { secretName: 'AmazonMSK_KafkaSecret' });
declare const myFunction: lambda.Function;
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic: topic,
secret: secret,
batchSize: 100, // default
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
bisectBatchOnError: true,
reportBatchItemFailures: true,
retryAttempts: 3,
maxRecordAge: Duration.hours(24),
provisionedPollerConfig: {
minimumPollers: 1,
maximumPollers: 3,
},
}));
```
The following code sets up a self managed Kafka cluster as an event source. Username and password based authentication
will need to be set up as described in [Managing access and permissions](https://docs.aws.amazon.com/lambda/latest/dg/smaa-permissions.html#smaa-permissions-add-secret).
```ts
import { Secret } from 'aws-cdk-lib/aws-secretsmanager';
import { SelfManagedKafkaEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
// The list of Kafka brokers
const bootstrapServers = ['kafka-broker:9092'];
// The Kafka topic you want to subscribe to
const topic = 'some-cool-topic';
// The secret that allows access to your self hosted Kafka cluster
declare const secret: Secret;
// (Optional) The consumer group id to use when connecting to the Kafka broker. If omitted the UUID of the event source mapping will be used.
const consumerGroupId = "my-consumer-group-id";
declare const myFunction: lambda.Function;
myFunction.addEventSource(new SelfManagedKafkaEventSource({
bootstrapServers: bootstrapServers,
topic: topic,
consumerGroupId: consumerGroupId,
secret: secret,
batchSize: 100, // default
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
bisectBatchOnError: true,
reportBatchItemFailures: true,
retryAttempts: 3,
maxRecordAge: Duration.hours(24),
provisionedPollerConfig: {
minimumPollers: 1,
maximumPollers: 3,
},
}));
```
If your self managed Kafka cluster is only reachable via VPC also configure `vpc` `vpcSubnets` and `securityGroup`.
You can specify [event filtering](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventfiltering.html#filtering-msk-smak)
for managed and self managed Kafka clusters using the `filters` property:
```ts
import { ManagedKafkaEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
// Your MSK cluster arn
const clusterArn = 'arn:aws:kafka:us-east-1:0123456789019:cluster/SalesCluster/abcd1234-abcd-cafe-abab-9876543210ab-4';
// The Kafka topic you want to subscribe to
const topic = 'some-cool-topic';
declare const myFunction: lambda.Function;
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic,
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
filters: [
lambda.FilterCriteria.filter({
stringEquals: lambda.FilterRule.isEqual('test'),
}),
],
}));
```
By default, Lambda will encrypt Filter Criteria using AWS managed keys. But if you want to use a self managed KMS key to encrypt the filters, You can specify the self managed key using the `filterEncryption` property.
```ts
import { ManagedKafkaEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
import { Key } from 'aws-cdk-lib/aws-kms';
// Your MSK cluster arn
const clusterArn = 'arn:aws:kafka:us-east-1:0123456789019:cluster/SalesCluster/abcd1234-abcd-cafe-abab-9876543210ab-4';
// The Kafka topic you want to subscribe to
const topic = 'some-cool-topic';
// Your self managed KMS key
const myKey = Key.fromKeyArn(
this,
'SourceBucketEncryptionKey',
'arn:aws:kms:us-east-1:123456789012:key/<key-id>',
);
declare const myFunction: lambda.Function;
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic,
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
filters: [
lambda.FilterCriteria.filter({
stringEquals: lambda.FilterRule.isEqual('test'),
}),
],
filterEncryption: myKey,
}));
```
### Failure Destinations
You can specify failure destinations for records that fail processing. Kafka event sources support Kafka Topic Destinations, S3 Bucket Destinations, SQS Queue and SNS topic:
#### Kafka Topic Destination
For Kafka event sources, you can send failed records to another Kafka topic using `KafkaDlq`:
```ts
import { ManagedKafkaEventSource, KafkaDlq } from 'aws-cdk-lib/aws-lambda-event-sources';
// Your MSK cluster arn
const clusterArn = 'arn:aws:kafka:us-east-1:0123456789019:cluster/SalesCluster/abcd1234-abcd-cafe-abab-9876543210ab-4';
// The Kafka topic you want to subscribe to
const topic = 'some-cool-topic';
declare const myFunction: lambda.Function;
// Create a Kafka DLQ destination
const kafkaDlq = new KafkaDlq('failure-topic');
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic,
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
onFailure: kafkaDlq,
provisionedPollerConfig: {
minimumPollers: 1,
maximumPollers: 1,
},
}));
```
The same approach works with self-managed Kafka:
```ts
import { SelfManagedKafkaEventSource, KafkaDlq } from 'aws-cdk-lib/aws-lambda-event-sources';
const bootstrapServers = ['kafka-broker:9092'];
const topic = 'some-cool-topic';
declare const myFunction: lambda.Function;
myFunction.addEventSource(new SelfManagedKafkaEventSource({
bootstrapServers,
topic,
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
onFailure: new KafkaDlq('error-topic'),
provisionedPollerConfig: {
minimumPollers: 1,
maximumPollers: 1,
},
}));
```
#### S3 Bucket Destination
You can also specify an S3 bucket as an "on failure" destination:
```ts
import { ManagedKafkaEventSource, S3OnFailureDestination } from 'aws-cdk-lib/aws-lambda-event-sources';
import { IBucket } from 'aws-cdk-lib/aws-s3';
// Your MSK cluster arn
const clusterArn = 'arn:aws:kafka:us-east-1:0123456789019:cluster/SalesCluster/abcd1234-abcd-cafe-abab-9876543210ab-4';
// The Kafka topic you want to subscribe to
const topic = 'some-cool-topic';
declare const bucket: IBucket;
declare const myFunction: lambda.Function;
const s3OnFailureDestination = new S3OnFailureDestination(bucket);
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic,
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
onFailure: s3OnFailureDestination,
}));
```
### Kafka Observability Features
AWS Lambda provides enhanced observability for Kafka event sources through logging and metrics configuration.
**Important**: Observability features (`LogLevel` and `MetricsConfig`) are only available when using provisioned mode.
#### Logging
You can configure the verbosity of logs generated by the polling infrastructure.
This is particularly useful for troubleshooting connection issues, monitoring
polling behavior, and understanding the internal operations of your event
source mapping.
```ts
import { ManagedKafkaEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
// Your MSK cluster arn
const clusterArn = 'arn:aws:kafka:us-east-1:0123456789019:cluster/SalesCluster/abcd1234-abcd-cafe-abab-9876543210ab-4';
declare const myFunction: lambda.Function;
// Configure INFO level logging for production monitoring
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic: 'production-events',
startingPosition: lambda.StartingPosition.LATEST,
// Provisioned mode is required for observability features
provisionedPollerConfig: {
minimumPollers: 1,
maximumPollers: 5,
},
logLevel: lambda.EventSourceMappingLogLevel.INFO
}));
```
#### Metrics Configuration
Enhanced metrics provide detailed insights into your Kafka event source performance.
Metrics include event processing rates, error counts, and Kafka-specific metrics
like consumer lag.
```ts
import { ManagedKafkaEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
// Your MSK cluster arn
const clusterArn = 'arn:aws:kafka:us-east-1:0123456789019:cluster/SalesCluster/abcd1234-abcd-cafe-abab-9876543210ab-4';
declare const myFunction: lambda.Function;
// Enable basic event and error metrics
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic: 'basic-monitoring',
startingPosition: lambda.StartingPosition.LATEST,
// Provisioned mode is required for observability features
provisionedPollerConfig: {
minimumPollers: 2,
maximumPollers: 10,
},
metricsConfig: {
metrics: [
lambda.MetricType.EVENT_COUNT,
lambda.MetricType.ERROR_COUNT
]
}
}));
```
Set configuration for provisioned pollers that read from the event source. When specified, allows control over
the minimum and maximum number of pollers that can be provisioned to process events from the source.
```ts
import { ManagedKafkaEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
// Your MSK cluster arn
declare const clusterArn: string;
// The Kafka topic you want to subscribe to
const topic = 'some-cool-topic';
declare const myFunction: lambda.Function;
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic,
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
provisionedPollerConfig: {
minimumPollers: 1,
maximumPollers: 3,
},
}));
```
You can reduce costs by sharing provisioned pollers across multiple Kafka event sources using the `pollerGroupName` property. This is particularly useful when you have multiple Kafka topics that don't require dedicated polling capacity.
```ts
import { ManagedKafkaEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
declare const clusterArn: string;
declare const ordersFunction: lambda.Function;
// Orders processing function
ordersFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic: 'orders-topic',
startingPosition: lambda.StartingPosition.LATEST,
provisionedPollerConfig: {
minimumPollers: 2,
maximumPollers: 10,
pollerGroupName: 'shared-kafka-pollers',
},
}));
```
Set a confluent or self-managed schema registry to de-serialize events from the event source.
Note: This will also work for `SelfManagedKafkaEventSource`.
```ts
import { ManagedKafkaEventSource, ConfluentSchemaRegistry } from 'aws-cdk-lib/aws-lambda-event-sources';
import { Secret } from 'aws-cdk-lib/aws-secretsmanager';
// Your MSK cluster arn
declare const clusterArn: string;
// The Kafka topic you want to subscribe to
const topic = 'some-cool-topic';
const secret = new Secret(this, 'Secret', { secretName: 'AmazonMSK_KafkaSecret' });
declare const myFunction: lambda.Function;
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic,
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
provisionedPollerConfig: {
minimumPollers: 1,
maximumPollers: 3,
},
schemaRegistryConfig: new ConfluentSchemaRegistry({
schemaRegistryUri: 'https://example.com',
eventRecordFormat: lambda.EventRecordFormat.JSON,
authenticationType: lambda.KafkaSchemaRegistryAccessConfigType.BASIC_AUTH,
secret: secret,
schemaValidationConfigs: [{ attribute: lambda.KafkaSchemaValidationAttribute.KEY }],
}),
}));
```
Set Glue schema registry to de-serialize events from the event source.
Note: This will also work for `SelfManagedKafkaEventSource`.
```ts
import { CfnRegistry } from 'aws-cdk-lib/aws-glue';
import { ManagedKafkaEventSource, GlueSchemaRegistry } from 'aws-cdk-lib/aws-lambda-event-sources';
// Your MSK cluster arn
declare const clusterArn: string;
// The Kafka topic you want to subscribe to
const topic = 'some-cool-topic';
// Your Glue Schema Registry
const glueRegistry = new CfnRegistry(this, 'Registry', {
name: 'schema-registry',
description: 'Schema registry for event source',
});
declare const myFunction: lambda.Function;
myFunction.addEventSource(new ManagedKafkaEventSource({
clusterArn,
topic,
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
provisionedPollerConfig: {
minimumPollers: 1,
maximumPollers: 3,
},
schemaRegistryConfig: new GlueSchemaRegistry({
schemaRegistry: glueRegistry,
eventRecordFormat: lambda.EventRecordFormat.JSON,
schemaValidationConfigs: [{ attribute: lambda.KafkaSchemaValidationAttribute.KEY }],
}),
}));
```
## Roadmap
Eventually, this module will support all the event sources described under
[Supported Event
Sources](https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html)
in the AWS Lambda Developer Guide.

View File

@@ -0,0 +1 @@
export * from './lib';

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
import * as apigw from '../../aws-apigateway';
import type * as lambda from '../../aws-lambda';
export declare class ApiEventSource implements lambda.IEventSource {
private readonly method;
private readonly path;
private readonly options?;
constructor(method: string, path: string, options?: apigw.MethodOptions | undefined);
bind(target: lambda.IFunction): void;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ApiEventSource=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var apigw=()=>{var tmp=require("../../aws-apigateway");return apigw=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};class ApiEventSource{method;path;options;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.ApiEventSource",version:"2.252.0"};constructor(method,path,options){this.method=method,this.path=path,this.options=options;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_apigateway_MethodOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,ApiEventSource),error}if(!path.startsWith("/"))throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`PathStart`,`Path must start with "/": ${path}`)}bind(target){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(target)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}const id=`${core_1().Names.nodeUniqueId(target.node)}:ApiEventSourceA7A86A4F`,stack=core_1().Stack.of(target);let api=stack.node.tryFindChild(id);api||(api=new(apigw()).RestApi(stack,id,{defaultIntegration:new(apigw()).LambdaIntegration(target)})),api.root.resourceForPath(this.path).addMethod(this.method,void 0,this.options)}}exports.ApiEventSource=ApiEventSource;

View File

@@ -0,0 +1,35 @@
import type { IEventSourceMapping, IFunction } from '../../aws-lambda/lib';
import type { ISchemaRegistry, KafkaSchemaRegistryAccessConfigType, KafkaSchemaRegistryConfig, SchemaRegistryProps } from '../../aws-lambda/lib/schema-registry';
import type { ISecret } from '../../aws-secretsmanager';
/**
* Properties for confluent schema registry configuration.
*/
export interface ConfluentSchemaRegistryProps extends SchemaRegistryProps {
/**
* The URI for your schema registry.
*
* @default - none
*/
readonly schemaRegistryUri: string;
/**
* The type of authentication for schema registry credentials.
* @default none
*/
readonly authenticationType: KafkaSchemaRegistryAccessConfigType;
/**
* The secret with the schema registry credentials.
* @default none
*/
readonly secret: ISecret;
}
/**
* Confluent schema registry configuration for a Lambda event source.
*/
export declare class ConfluentSchemaRegistry implements ISchemaRegistry {
private readonly props;
constructor(props: ConfluentSchemaRegistryProps);
/**
* Returns a schema registry configuration.
*/
bind(_target: IEventSourceMapping, targetHandler: IFunction): KafkaSchemaRegistryConfig;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ConfluentSchemaRegistry=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");class ConfluentSchemaRegistry{props;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.ConfluentSchemaRegistry",version:"2.252.0"};constructor(props){this.props=props;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_ConfluentSchemaRegistryProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,ConfluentSchemaRegistry),error}}bind(_target,targetHandler){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IEventSourceMapping(_target),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(targetHandler)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}return this.props.secret.grantRead(targetHandler),{schemaRegistryUri:this.props.schemaRegistryUri,eventRecordFormat:this.props.eventRecordFormat,accessConfigs:[{type:this.props.authenticationType,uri:this.props.secret.secretArn}],schemaValidationConfigs:this.props.schemaValidationConfigs}}}exports.ConfluentSchemaRegistry=ConfluentSchemaRegistry;

View File

@@ -0,0 +1,24 @@
import type { StreamEventSourceProps } from './stream';
import { StreamEventSource } from './stream';
import type * as dynamodb from '../../aws-dynamodb';
import type * as lambda from '../../aws-lambda';
export interface DynamoEventSourceProps extends StreamEventSourceProps {
}
/**
* Use an Amazon DynamoDB stream as an event source for AWS Lambda.
*/
export declare class DynamoEventSource extends StreamEventSource {
private readonly table;
private _eventSourceMappingId?;
private _eventSourceMappingArn?;
constructor(table: dynamodb.ITable, props: DynamoEventSourceProps);
bind(target: lambda.IFunction): void;
/**
* The identifier for this EventSourceMapping
*/
get eventSourceMappingId(): string;
/**
* The ARN for this EventSourceMapping
*/
get eventSourceMappingArn(): string;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DynamoEventSource=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var stream_1=()=>{var tmp=require("./stream");return stream_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};class DynamoEventSource extends stream_1().StreamEventSource{table;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.DynamoEventSource",version:"2.252.0"};_eventSourceMappingId=void 0;_eventSourceMappingArn=void 0;constructor(table,props){super(props),this.table=table;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_ITable(table),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_DynamoEventSourceProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,DynamoEventSource),error}if(this.props.batchSize!==void 0&&!core_1().Token.isUnresolved(this.props.batchSize)&&(this.props.batchSize<1||this.props.batchSize>1e4))throw new(core_1()).ValidationError((0,literal_string_1().lit)`MaximumBatchSizeInclusiveGiven`,`Maximum batch size must be between 1 and 10000 inclusive (given ${this.props.batchSize})`,table)}bind(target){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(target)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}if(!this.table.tableStreamArn)throw new(core_1()).ValidationError((0,literal_string_1().lit)`DynamoStreamsEnabledTable`,`DynamoDB Streams must be enabled on the table ${this.table.node.path}`,this.table);const eventSourceMapping=target.addEventSourceMapping(`DynamoDBEventSource:${core_1().Names.nodeUniqueId(this.table.node)}`,this.enrichMappingOptions({eventSourceArn:this.table.tableStreamArn,metricsConfig:this.props.metricsConfig,supportS3OnFailureDestination:!0}));this._eventSourceMappingId=eventSourceMapping.eventSourceMappingId,this._eventSourceMappingArn=eventSourceMapping.eventSourceMappingArn,this.table.grantStreamRead(target)}get eventSourceMappingId(){if(!this._eventSourceMappingId)throw new(core_1()).ValidationError((0,literal_string_1().lit)`DynamoEventSourceYetBound`,"DynamoEventSource is not yet bound to an event source mapping",this.table);return this._eventSourceMappingId}get eventSourceMappingArn(){if(!this._eventSourceMappingArn)throw new(core_1()).ValidationError((0,literal_string_1().lit)`DynamoEventSourceYetBound`,"DynamoEventSource is not yet bound to an event source mapping",this.table);return this._eventSourceMappingArn}}exports.DynamoEventSource=DynamoEventSource;

View File

@@ -0,0 +1,33 @@
import type { CfnRegistry } from '../../aws-glue';
import type { IEventSourceMapping, IFunction } from '../../aws-lambda/lib';
import type { ISchemaRegistry, KafkaSchemaRegistryConfig, SchemaRegistryProps } from '../../aws-lambda/lib/schema-registry';
/**
* Properties for glue schema registry configuration.
*/
export interface GlueSchemaRegistryProps extends SchemaRegistryProps {
/**
* The CfnRegistry reference of your glue schema registry. If used, schemaRegistryArn will be ignored.
*
* @default - none
*/
readonly schemaRegistry?: CfnRegistry;
/**
* The Arn of your glue schema registry.
*
* @default - none
*/
readonly schemaRegistryArn?: string;
}
/**
* Glue schema registry configuration for a Lambda event source.
*/
export declare class GlueSchemaRegistry implements ISchemaRegistry {
private readonly props;
constructor(props: GlueSchemaRegistryProps);
/**
* Returns a schema registry configuration.
*/
bind(_target: IEventSourceMapping, targetHandler: IFunction): KafkaSchemaRegistryConfig;
private getRegistryProps;
private getSchemaRegistryPolicies;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GlueSchemaRegistry=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var iam=()=>{var tmp=require("../../aws-iam");return iam=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};const GLUE_SCHEMA_REGISTRY_ARN_REGEX=/^arn:[^:]+:glue:[^:]+:[^:]+:registry\/([^\/]+)$/;class GlueSchemaRegistry{props;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.GlueSchemaRegistry",version:"2.252.0"};constructor(props){this.props=props;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_GlueSchemaRegistryProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,GlueSchemaRegistry),error}}bind(_target,targetHandler){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IEventSourceMapping(_target),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(targetHandler)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}const registryProps=this.getRegistryProps(this.props,_target);return this.getSchemaRegistryPolicies(registryProps.arn,registryProps.name).forEach(i=>targetHandler.addToRolePolicy(i)),{schemaRegistryUri:registryProps.arn,eventRecordFormat:this.props.eventRecordFormat,schemaValidationConfigs:this.props.schemaValidationConfigs}}getRegistryProps(props,_target){if(props.schemaRegistry)return{arn:props.schemaRegistry.attrArn,name:props.schemaRegistry.name};if(props.schemaRegistryArn){const glueRegistryMatch=props.schemaRegistryArn?.match(GLUE_SCHEMA_REGISTRY_ARN_REGEX);if(!glueRegistryMatch)throw new(core_1()).ValidationError((0,literal_string_1().lit)`SchemaRegistryArn`,`schemaRegistryArn ${this.props.schemaRegistryArn} must match ${GLUE_SCHEMA_REGISTRY_ARN_REGEX}`,_target);return{arn:props.schemaRegistryArn,name:glueRegistryMatch[1]}}throw new(core_1()).ValidationError((0,literal_string_1().lit)`OneSchemaRegistryArnSchema`,"one of schemaRegistryArn or schemaRegistry must be passed",_target)}getSchemaRegistryPolicies(glueRegistryArn,glueRegistryName){return[new(iam()).PolicyStatement({actions:["glue:GetRegistry"],resources:[glueRegistryArn]}),new(iam()).PolicyStatement({actions:["glue:GetSchemaVersion"],resources:[glueRegistryArn,core_1().Fn.sub("arn:${AWS::Partition}:glue:${AWS::Region}:${AWS::AccountId}:schema/${registryName}/*",{registryName:glueRegistryName})]})]}}exports.GlueSchemaRegistry=GlueSchemaRegistry;

View File

@@ -0,0 +1,14 @@
export * from './api';
export * from './dynamodb';
export * from './kafka';
export * from './kafka-dlq';
export * from './kinesis';
export * from './s3';
export * from './sns';
export * from './sns-dlq';
export * from './stream';
export * from './sqs';
export * from './sqs-dlq';
export * from './s3-onfailuire-destination';
export * from './confluent-schema-registry';
export * from './glue-schema-registry';

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,38 @@
import type { DlqDestinationConfig, IEventSourceDlq, IEventSourceMapping, IFunction } from '../../aws-lambda';
/**
* A Kafka topic dead letter queue destination configuration for a Lambda event source.
*
* This destination can only be used with Kafka-based event sources (MSK and self-managed Kafka).
* When used with other event source types, a validation error will be thrown.
*
* ## Kafka URI Format
*
* new KafkaDlq('my-topic');
*
* ## Topic Naming Requirements
*
* Kafka topic names must follow these rules:
* - Only alphanumeric characters, dots (.), underscores (_), and hyphens (-) are allowed
* - Cannot be empty
* - Must be a valid Kafka topic name
*
*/
export declare class KafkaDlq implements IEventSourceDlq {
private readonly topicName;
/**
* Creates a new Kafka DLQ destination.
*
* @throws {TypeError} When the topic name is empty or contains invalid characters
*/
constructor(topicName: string);
/**
* Returns a destination configuration for the DLQ.
*
* The returned configuration is used in the AWS Lambda EventSourceMapping's DestinationConfig
* to specify where failed records should be sent.
*
* @returns The DLQ destination configuration with the properly formatted Kafka URI
*
*/
bind(_target: IEventSourceMapping, _targetHandler: IFunction): DlqDestinationConfig;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KafkaDlq=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp};class KafkaDlq{static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.KafkaDlq",version:"2.252.0"};topicName;constructor(topicName){if(core_1().Token.isUnresolved(topicName))this.topicName=topicName;else{if(!topicName||topicName.trim().length===0)throw new TypeError("Topic name cannot be empty");const cleanTopicName=topicName.startsWith("kafka://")?topicName.substring(8):topicName;if(cleanTopicName.length===0)throw new TypeError("Topic name cannot be empty after removing kafka:// prefix");if(!/^[a-zA-Z0-9._-]+$/.test(cleanTopicName))throw new TypeError("Topic name contains invalid characters. Only alphanumeric characters, dots, underscores, and hyphens are allowed");this.topicName=topicName.startsWith("kafka://")?topicName:`kafka://${topicName}`}}bind(_target,_targetHandler){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IEventSourceMapping(_target),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(_targetHandler)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}return{destination:this.topicName}}}exports.KafkaDlq=KafkaDlq;

View File

@@ -0,0 +1,254 @@
import type { BaseStreamEventSourceProps } from './stream';
import { StreamEventSource } from './stream';
import type { ISecurityGroup, IVpc, SubnetSelection } from '../../aws-ec2';
import type { IKey } from '../../aws-kms';
import * as lambda from '../../aws-lambda';
import type { ISchemaRegistry } from '../../aws-lambda/lib/schema-registry';
import type * as secretsmanager from '../../aws-secretsmanager';
import type { Duration } from '../../core';
/**
* Properties for a Kafka event source
*/
export interface KafkaEventSourceProps extends BaseStreamEventSourceProps {
/**
* The Kafka topic to subscribe to
*/
readonly topic: string;
/**
* The secret with the Kafka credentials, see https://docs.aws.amazon.com/msk/latest/developerguide/msk-password.html for details
* This field is required if your Kafka brokers are accessed over the Internet
*
* @default none
*/
readonly secret?: secretsmanager.ISecret;
/**
* The identifier for the Kafka consumer group to join. The consumer group ID must be unique among all your Kafka event sources. After creating a Kafka event source mapping with the consumer group ID specified, you cannot update this value. The value must have a length between 1 and 200 and full the pattern '[a-zA-Z0-9-\/*:_+=.@-]*'.
* @see https://docs.aws.amazon.com/lambda/latest/dg/with-msk.html#services-msk-consumer-group-id
*
* @default - none
*/
readonly consumerGroupId?: string;
/**
* Add filter criteria to Event Source
* @see https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventfiltering.html
*
* @default - none
*/
readonly filters?: Array<{
[key: string]: any;
}>;
/**
* Add Customer managed KMS key to encrypt Filter Criteria.
* @see https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventfiltering.html
* By default, Lambda will encrypt Filter Criteria using AWS managed keys
* @see https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#aws-managed-cmk
*
* @default - none
*/
readonly filterEncryption?: IKey;
/**
* Add an on Failure Destination for this Kafka event.
*
* Supported destinations:
* - {@link KafkaDlq} - Send failed records to a Kafka topic
* - SNS topics - Send failed records to an SNS topic
* - SQS queues - Send failed records to an SQS queue
* - S3 buckets - Send failed records to an S3 bucket
*
* @default - discarded records are ignored
*/
readonly onFailure?: lambda.IEventSourceDlq;
/**
* The time from which to start reading, in Unix time seconds.
*
* @default - no timestamp
*/
readonly startingPositionTimestamp?: number;
/**
* Specific configuration settings for a Kafka schema registry.
*
* @default - none
*/
readonly schemaRegistryConfig?: ISchemaRegistry;
/**
* Configuration for logging verbosity from the event source mapping poller
*
* @default - No logging
*/
readonly logLevel?: lambda.EventSourceMappingLogLevel;
/**
* Configuration for enhanced monitoring metrics collection
*
* @default - Enhanced monitoring is disabled
*/
readonly metricsConfig?: lambda.MetricsConfig;
/***
* If the function returns an error, split the batch in two and retry.
*
* @default false
*/
readonly bisectBatchOnError?: boolean;
/**
* The maximum age of a record that Lambda sends to a function for processing.
*
* The default value is -1, which sets the maximum age to infinite.
* When the value is set to infinite, Lambda never discards old records.
* Record are valid until it expires in the event source.
*
* @default -1
*/
readonly maxRecordAge?: Duration;
/***
* Maximum number of retry attempts.
*
* Set to -1 for infinite retries (until the record expires in the event source).
*
* @default -1 (infinite retries)
*/
readonly retryAttempts?: number;
/***
* Allow functions to return partially successful responses for a batch of records.
*
* @default false
*/
readonly reportBatchItemFailures?: boolean;
}
/**
* Properties for a MSK event source
*/
export interface ManagedKafkaEventSourceProps extends KafkaEventSourceProps {
/**
* An MSK cluster construct
*/
readonly clusterArn: string;
}
/**
* The authentication method to use with SelfManagedKafkaEventSource
*/
export declare enum AuthenticationMethod {
/**
* SASL_SCRAM_512_AUTH authentication method for your Kafka cluster
*/
SASL_SCRAM_512_AUTH = "SASL_SCRAM_512_AUTH",
/**
* SASL_SCRAM_256_AUTH authentication method for your Kafka cluster
*/
SASL_SCRAM_256_AUTH = "SASL_SCRAM_256_AUTH",
/**
* BASIC_AUTH (SASL/PLAIN) authentication method for your Kafka cluster
*/
BASIC_AUTH = "BASIC_AUTH",
/**
* CLIENT_CERTIFICATE_TLS_AUTH (mTLS) authentication method for your Kafka cluster
*/
CLIENT_CERTIFICATE_TLS_AUTH = "CLIENT_CERTIFICATE_TLS_AUTH"
}
/**
* Properties for a self managed Kafka cluster event source.
* If your Kafka cluster is only reachable via VPC make sure to configure it.
*/
export interface SelfManagedKafkaEventSourceProps extends KafkaEventSourceProps {
/**
* The list of host and port pairs that are the addresses of the Kafka brokers in a "bootstrap" Kafka cluster that
* a Kafka client connects to initially to bootstrap itself. They are in the format `abc.xyz.com:xxxx`.
*/
readonly bootstrapServers: string[];
/**
* If your Kafka brokers are only reachable via VPC provide the VPC here
*
* @default none
*/
readonly vpc?: IVpc;
/**
* If your Kafka brokers are only reachable via VPC, provide the subnets selection here
*
* @default - none, required if setting vpc
*/
readonly vpcSubnets?: SubnetSelection;
/**
* If your Kafka brokers are only reachable via VPC, provide the security group here
*
* @default - none, required if setting vpc
*/
readonly securityGroup?: ISecurityGroup;
/**
* The authentication method for your Kafka cluster
*
* @default AuthenticationMethod.SASL_SCRAM_512_AUTH
*/
readonly authenticationMethod?: AuthenticationMethod;
/**
* The secret with the root CA certificate used by your Kafka brokers for TLS encryption
* This field is required if your Kafka brokers use certificates signed by a private CA
*
* @default - none
*/
readonly rootCACertificate?: secretsmanager.ISecret;
}
/**
* Use a MSK cluster as a streaming source for AWS Lambda
*
* @example
* import { ManagedKafkaEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
* import { StartingPosition, Function } from 'aws-cdk-lib/aws-lambda';
*
* // With provisioned pollers and poller group for cost optimization
* declare const myFunction: Function;
* myFunction.addEventSource(new ManagedKafkaEventSource({
* clusterArn: 'arn:aws:kafka:us-east-1:123456789012:cluster/my-cluster/abcd1234-abcd-cafe-abab-9876543210ab-4',
* topic: 'orders-topic',
* startingPosition: StartingPosition.LATEST,
* provisionedPollerConfig: {
* minimumPollers: 2,
* maximumPollers: 10,
* pollerGroupName: 'shared-kafka-pollers',
* },
* }));
*/
export declare class ManagedKafkaEventSource extends StreamEventSource {
private innerProps;
private _eventSourceMappingId?;
private _eventSourceMappingArn?;
constructor(props: ManagedKafkaEventSourceProps);
bind(target: lambda.IFunction): void;
private sourceAccessConfigurations;
/**
* The identifier for this EventSourceMapping
*/
get eventSourceMappingId(): string;
/**
* The ARN for this EventSourceMapping
*/
get eventSourceMappingArn(): string;
}
/**
* Use a self hosted Kafka installation as a streaming source for AWS Lambda.
*
* @example
* import { SelfManagedKafkaEventSource, AuthenticationMethod } from 'aws-cdk-lib/aws-lambda-event-sources';
* import { StartingPosition, Function } from 'aws-cdk-lib/aws-lambda';
* import { ISecret } from 'aws-cdk-lib/aws-secretsmanager';
*
* // With provisioned pollers and poller group for cost optimization
* declare const myFunction: Function;
* declare const kafkaCredentials: ISecret;
* myFunction.addEventSource(new SelfManagedKafkaEventSource({
* bootstrapServers: ['kafka-broker1.example.com:9092', 'kafka-broker2.example.com:9092'],
* topic: 'events-topic',
* secret: kafkaCredentials,
* startingPosition: StartingPosition.LATEST,
* authenticationMethod: AuthenticationMethod.SASL_SCRAM_512_AUTH,
* provisionedPollerConfig: {
* minimumPollers: 1,
* maximumPollers: 8,
* pollerGroupName: 'self-managed-kafka-group', // Group pollers to reduce costs
* },
* }));
*/
export declare class SelfManagedKafkaEventSource extends StreamEventSource {
private innerProps;
constructor(props: SelfManagedKafkaEventSourceProps);
bind(target: lambda.IFunction): void;
private mappingId;
private sourceAccessConfigurations;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,57 @@
import type * as constructs from 'constructs';
import type { StreamEventSourceProps } from './stream';
import { StreamEventSource } from './stream';
import type * as iam from '../../aws-iam';
import type * as kinesis from '../../aws-kinesis';
import type * as lambda from '../../aws-lambda';
export interface KinesisEventSourceProps extends StreamEventSourceProps {
/**
* The time from which to start reading, in Unix time seconds.
*
* @default - no timestamp
*/
readonly startingPositionTimestamp?: number;
}
/**
* Props for use with {@link KinesisEventSourceBase}
*/
interface KinesisSource {
readonly node: constructs.Node;
readonly sourceArn: string;
readonly eventSourceName: string;
grantRead(grantee: iam.IGrantable): iam.Grant;
}
/**
* Base class for {@link KinesisEventSource} and {@link KinesisConsumerEventSource}
*/
declare abstract class KinesisEventSourceBase extends StreamEventSource {
readonly source: KinesisSource;
private _eventSourceMappingId?;
private _eventSourceMappingArn?;
private startingPositionTimestamp?;
constructor(source: KinesisSource, props: KinesisEventSourceProps);
bind(target: lambda.IFunction): void;
/**
* The identifier for this EventSourceMapping
*/
get eventSourceMappingId(): string;
/**
* The ARN for this EventSourceMapping
*/
get eventSourceMappingArn(): string;
}
/**
* Use an Amazon Kinesis stream as an event source for AWS Lambda.
*/
export declare class KinesisEventSource extends KinesisEventSourceBase {
readonly stream: kinesis.IStream;
constructor(stream: kinesis.IStream, props: KinesisEventSourceProps);
}
/**
* Use an Amazon Kinesis stream consumer as an event source for AWS Lambda.
*/
export declare class KinesisConsumerEventSource extends KinesisEventSourceBase {
readonly streamConsumer: kinesis.IStreamConsumer;
constructor(streamConsumer: kinesis.IStreamConsumer, props: KinesisEventSourceProps);
}
export {};

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KinesisConsumerEventSource=exports.KinesisEventSource=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var stream_1=()=>{var tmp=require("./stream");return stream_1=()=>tmp,tmp},cdk=()=>{var tmp=require("../../core");return cdk=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};class KinesisEventSourceBase extends stream_1().StreamEventSource{source;_eventSourceMappingId=void 0;_eventSourceMappingArn=void 0;startingPositionTimestamp;constructor(source,props){super(props),this.source=source,this.startingPositionTimestamp=props.startingPositionTimestamp,this.props.batchSize!==void 0&&cdk().withResolved(this.props.batchSize,batchSize=>{if(batchSize<1||batchSize>1e4)throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`MustBeMaximumBatchSize`,`Maximum batch size must be between 1 and 10000 inclusive (given ${this.props.batchSize})`)})}bind(target){const eventSourceMapping=target.addEventSourceMapping(`${this.source.eventSourceName}:${cdk().Names.nodeUniqueId(this.source.node)}`,this.enrichMappingOptions({eventSourceArn:this.source.sourceArn,startingPositionTimestamp:this.startingPositionTimestamp,metricsConfig:this.props.metricsConfig,supportS3OnFailureDestination:!0}));this._eventSourceMappingId=eventSourceMapping.eventSourceMappingId,this._eventSourceMappingArn=eventSourceMapping.eventSourceMappingArn,this.source.grantRead(target)}get eventSourceMappingId(){if(!this._eventSourceMappingId)throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`BoundEventSourceMapping`,`${this.source.eventSourceName} is not yet bound to an event source mapping`);return this._eventSourceMappingId}get eventSourceMappingArn(){if(!this._eventSourceMappingArn)throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`BoundEventSourceMapping`,`${this.source.eventSourceName} is not yet bound to an event source mapping`);return this._eventSourceMappingArn}}class KinesisEventSource extends KinesisEventSourceBase{stream;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.KinesisEventSource",version:"2.252.0"};constructor(stream,props){super({...stream,eventSourceName:"KinesisEventSource",sourceArn:stream.streamArn,grantRead:stream.grantRead.bind(stream)},props),this.stream=stream;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_kinesis_IStream(stream),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_KinesisEventSourceProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,KinesisEventSource),error}}}exports.KinesisEventSource=KinesisEventSource;class KinesisConsumerEventSource extends KinesisEventSourceBase{streamConsumer;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.KinesisConsumerEventSource",version:"2.252.0"};constructor(streamConsumer,props){super({...streamConsumer,eventSourceName:"KinesisConsumerEventSource",sourceArn:streamConsumer.streamConsumerArn,grantRead:streamConsumer.grantRead.bind(streamConsumer)},props),this.streamConsumer=streamConsumer;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_kinesis_IStreamConsumer(streamConsumer),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_KinesisEventSourceProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,KinesisConsumerEventSource),error}}}exports.KinesisConsumerEventSource=KinesisConsumerEventSource;

View File

@@ -0,0 +1,13 @@
import type { DlqDestinationConfig, IEventSourceDlq, IEventSourceMapping, IFunction } from '../../aws-lambda';
import type * as s3 from '../../aws-s3';
/**
* An S3 dead letter bucket destination configuration for a Lambda event source
*/
export declare class S3OnFailureDestination implements IEventSourceDlq {
private readonly bucket;
constructor(bucket: s3.IBucket);
/**
* Returns a destination configuration for the DLQ
*/
bind(_target: IEventSourceMapping, targetHandler: IFunction): DlqDestinationConfig;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.S3OnFailureDestination=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");class S3OnFailureDestination{bucket;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.S3OnFailureDestination",version:"2.252.0"};constructor(bucket){this.bucket=bucket;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_IBucket(bucket)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,S3OnFailureDestination),error}}bind(_target,targetHandler){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IEventSourceMapping(_target),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(targetHandler)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}return this.bucket.grantReadWrite(targetHandler),{destination:this.bucket.bucketArn}}}exports.S3OnFailureDestination=S3OnFailureDestination;

View File

@@ -0,0 +1,33 @@
import type * as lambda from '../../aws-lambda';
import type * as s3 from '../../aws-s3';
export interface S3EventSourceProps {
/**
* The s3 event types that will trigger the notification.
*/
readonly events: s3.EventType[];
/**
* S3 object key filter rules to determine which objects trigger this event.
* Each filter must include a `prefix` and/or `suffix` that will be matched
* against the s3 object key. Refer to the S3 Developer Guide for details
* about allowed filter rules.
*/
readonly filters?: s3.NotificationKeyFilter[];
}
/**
* Use S3 bucket notifications as an event source for AWS Lambda.
*/
export declare class S3EventSource implements lambda.IEventSource {
readonly bucket: s3.Bucket;
private readonly props;
constructor(bucket: s3.Bucket, props: S3EventSourceProps);
bind(target: lambda.IFunction): void;
}
/**
* S3EventSourceV2 Use S3 bucket notifications as an event source for AWS Lambda.
*/
export declare class S3EventSourceV2 implements lambda.IEventSource {
private readonly bucket;
private readonly props;
constructor(bucket: s3.IBucket, props: S3EventSourceProps);
bind(target: lambda.IFunction): void;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.S3EventSourceV2=exports.S3EventSource=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var notifs=()=>{var tmp=require("../../aws-s3-notifications");return notifs=()=>tmp,tmp};class S3EventSource{bucket;props;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.S3EventSource",version:"2.252.0"};constructor(bucket,props){this.bucket=bucket,this.props=props;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_Bucket(bucket),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_S3EventSourceProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,S3EventSource),error}}bind(target){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(target)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}const filters=this.props.filters||[];for(const event of this.props.events)this.bucket.addEventNotification(event,new(notifs()).LambdaDestination(target),...filters)}}exports.S3EventSource=S3EventSource;class S3EventSourceV2{bucket;props;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.S3EventSourceV2",version:"2.252.0"};constructor(bucket,props){this.bucket=bucket,this.props=props;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_IBucket(bucket),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_S3EventSourceProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,S3EventSourceV2),error}}bind(target){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(target)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}const filters=this.props.filters||[];for(const event of this.props.events)this.bucket.addEventNotification(event,new(notifs()).LambdaDestination(target),...filters)}}exports.S3EventSourceV2=S3EventSourceV2;

View File

@@ -0,0 +1,13 @@
import type { DlqDestinationConfig, IEventSourceDlq, IEventSourceMapping, IFunction } from '../../aws-lambda';
import type * as sns from '../../aws-sns';
/**
* An SNS dead letter queue destination configuration for a Lambda event source
*/
export declare class SnsDlq implements IEventSourceDlq {
private readonly topic;
constructor(topic: sns.ITopic);
/**
* Returns a destination configuration for the DLQ
*/
bind(_target: IEventSourceMapping, targetHandler: IFunction): DlqDestinationConfig;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SnsDlq=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");class SnsDlq{topic;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.SnsDlq",version:"2.252.0"};constructor(topic){this.topic=topic;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_sns_ITopic(topic)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,SnsDlq),error}}bind(_target,targetHandler){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IEventSourceMapping(_target),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(targetHandler)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}return this.topic.grantPublish(targetHandler),{destination:this.topic.topicArn}}}exports.SnsDlq=SnsDlq;

View File

@@ -0,0 +1,17 @@
import type * as lambda from '../../aws-lambda';
import type * as sns from '../../aws-sns';
import * as subs from '../../aws-sns-subscriptions';
/**
* Properties forwarded to the Lambda Subscription.
*/
export interface SnsEventSourceProps extends subs.LambdaSubscriptionProps {
}
/**
* Use an Amazon SNS topic as an event source for AWS Lambda.
*/
export declare class SnsEventSource implements lambda.IEventSource {
readonly topic: sns.ITopic;
private readonly props?;
constructor(topic: sns.ITopic, props?: SnsEventSourceProps);
bind(target: lambda.IFunction): void;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SnsEventSource=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var subs=()=>{var tmp=require("../../aws-sns-subscriptions");return subs=()=>tmp,tmp};class SnsEventSource{topic;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.SnsEventSource",version:"2.252.0"};props;constructor(topic,props){this.topic=topic;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_sns_ITopic(topic),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_SnsEventSourceProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,SnsEventSource),error}this.props=props}bind(target){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(target)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}this.topic.addSubscription(new(subs()).LambdaSubscription(target,this.props))}}exports.SnsEventSource=SnsEventSource;

View File

@@ -0,0 +1,13 @@
import type { DlqDestinationConfig, IEventSourceDlq, IEventSourceMapping, IFunction } from '../../aws-lambda';
import type * as sqs from '../../aws-sqs';
/**
* An SQS dead letter queue destination configuration for a Lambda event source
*/
export declare class SqsDlq implements IEventSourceDlq {
private readonly queue;
constructor(queue: sqs.IQueue);
/**
* Returns a destination configuration for the DLQ
*/
bind(_target: IEventSourceMapping, targetHandler: IFunction): DlqDestinationConfig;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SqsDlq=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");class SqsDlq{queue;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.SqsDlq",version:"2.252.0"};constructor(queue){this.queue=queue;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_sqs_IQueue(queue)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,SqsDlq),error}}bind(_target,targetHandler){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IEventSourceMapping(_target),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(targetHandler)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}return this.queue.grantSendMessages(targetHandler),{destination:this.queue.queueArn}}}exports.SqsDlq=SqsDlq;

View File

@@ -0,0 +1,92 @@
import type { IKey } from '../../aws-kms';
import type * as lambda from '../../aws-lambda';
import type * as sqs from '../../aws-sqs';
import type { Duration } from '../../core';
export interface SqsEventSourceProps {
/**
* The largest number of records that AWS Lambda will retrieve from your event
* source at the time of invoking your function. Your function receives an
* event with all the retrieved records.
*
* Valid Range: Minimum value of 1. Maximum value of 10.
* If `maxBatchingWindow` is configured, this value can go up to 10,000.
*
* @default 10
*/
readonly batchSize?: number;
/**
* The maximum amount of time to gather records before invoking the function.
*
* Valid Range: Minimum value of 0 minutes. Maximum value of 5 minutes.
*
* @default - no batching window. The lambda function will be invoked immediately with the records that are available.
*/
readonly maxBatchingWindow?: Duration;
/**
* Allow functions to return partially successful responses for a batch of records.
*
* @see https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html#services-sqs-batchfailurereporting
*
* @default false
*/
readonly reportBatchItemFailures?: boolean;
/**
* If the SQS event source mapping should be enabled.
*
* @default true
*/
readonly enabled?: boolean;
/**
* Add filter criteria option
*
* @default - None
*/
readonly filters?: Array<{
[key: string]: any;
}>;
/**
* Add Customer managed KMS key to encrypt Filter Criteria.
* @see https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventfiltering.html
* By default, Lambda will encrypt Filter Criteria using AWS managed keys
* @see https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#aws-managed-cmk
*
* @default - none
*/
readonly filterEncryption?: IKey;
/**
* The maximum concurrency setting limits the number of concurrent instances of the function that an Amazon SQS event source can invoke.
*
* @see https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html#events-sqs-max-concurrency
*
* Valid Range: Minimum value of 2. Maximum value of 1000.
*
* @default - No specific limit.
*/
readonly maxConcurrency?: number;
/**
* Configuration for enhanced monitoring metrics collection
* When specified, enables collection of additional metrics for the stream event source
*
* @default - Enhanced monitoring is disabled
*/
readonly metricsConfig?: lambda.MetricsConfig;
}
/**
* Use an Amazon SQS queue as an event source for AWS Lambda.
*/
export declare class SqsEventSource implements lambda.IEventSource {
readonly queue: sqs.IQueue;
private readonly props;
private _eventSourceMappingId?;
private _eventSourceMappingArn?;
constructor(queue: sqs.IQueue, props?: SqsEventSourceProps);
bind(target: lambda.IFunction): void;
/**
* The identifier for this EventSourceMapping
*/
get eventSourceMappingId(): string;
/**
* The ARN for this EventSourceMapping
*/
get eventSourceMappingArn(): string;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SqsEventSource=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};class SqsEventSource{queue;props;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.SqsEventSource",version:"2.252.0"};_eventSourceMappingId=void 0;_eventSourceMappingArn=void 0;constructor(queue,props={}){this.queue=queue,this.props=props;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_sqs_IQueue(queue),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_SqsEventSourceProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,SqsEventSource),error}if(this.props.maxBatchingWindow!==void 0){if(queue.fifo)throw new(core_1()).ValidationError((0,literal_string_1().lit)`BatchingWindowSupportedQueues`,"Batching window is not supported for FIFO queues",queue);if(!this.props.maxBatchingWindow.isUnresolved()&&this.props.maxBatchingWindow.toSeconds()>300)throw new(core_1()).ValidationError((0,literal_string_1().lit)`MaximumBatchingWindowSecondsLess`,`Maximum batching window must be 300 seconds or less (given ${this.props.maxBatchingWindow.toHumanString()})`,queue)}if(this.props.batchSize!==void 0&&!core_1().Token.isUnresolved(this.props.batchSize)){if(this.props.maxBatchingWindow!==void 0&&(this.props.batchSize<1||this.props.batchSize>1e4))throw new(core_1()).ValidationError((0,literal_string_1().lit)`MaximumBatchSizeInclusiveGiven`,`Maximum batch size must be between 1 and 10000 inclusive (given ${this.props.batchSize}) when batching window is specified.`,queue);if(this.props.maxBatchingWindow===void 0&&(this.props.batchSize<1||this.props.batchSize>10))throw new(core_1()).ValidationError((0,literal_string_1().lit)`MaximumBatchSizeInclusiveGiven`,`Maximum batch size must be between 1 and 10 inclusive (given ${this.props.batchSize}) when batching window is not specified.`,queue)}}bind(target){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IFunction(target)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.bind),error}const eventSourceMapping=target.addEventSourceMapping(`SqsEventSource:${core_1().Names.nodeUniqueId(this.queue.node)}`,{batchSize:this.props.batchSize,maxBatchingWindow:this.props.maxBatchingWindow,maxConcurrency:this.props.maxConcurrency,reportBatchItemFailures:this.props.reportBatchItemFailures,enabled:this.props.enabled,eventSourceArn:this.queue.queueArn,filters:this.props.filters,filterEncryption:this.props.filterEncryption,metricsConfig:this.props.metricsConfig});this._eventSourceMappingId=eventSourceMapping.eventSourceMappingId,this._eventSourceMappingArn=eventSourceMapping.eventSourceMappingArn,target.role?this.queue.grantConsumeMessages(target):core_1().Annotations.of(target).addWarningV2("@aws-cdk/aws-lambda-event-sources:sqsFunctionImportWithoutRole",`Function '${target.node.path}' was imported without an IAM role so it was not granted access to consume messages from '${this.queue.node.path}'`)}get eventSourceMappingId(){if(!this._eventSourceMappingId)throw new(core_1()).ValidationError((0,literal_string_1().lit)`SqsEventSourceYetBound`,"SqsEventSource is not yet bound to an event source mapping",this.queue);return this._eventSourceMappingId}get eventSourceMappingArn(){if(!this._eventSourceMappingArn)throw new(core_1()).ValidationError((0,literal_string_1().lit)`SqsEventSourceYetBound`,"SqsEventSource is not yet bound to an event source mapping",this.queue);return this._eventSourceMappingArn}}exports.SqsEventSource=SqsEventSource;

View File

@@ -0,0 +1,172 @@
import type { IKey } from '../../aws-kms';
import type * as lambda from '../../aws-lambda';
import type { Duration } from '../../core';
/**
* The set of properties for streaming event sources shared by
* Dynamo, Kinesis and Kafka.
*/
export interface BaseStreamEventSourceProps {
/**
* The largest number of records that AWS Lambda will retrieve from your event
* source at the time of invoking your function. Your function receives an
* event with all the retrieved records.
*
* Valid Range:
* * Minimum value of 1
* * Maximum value of:
* * 1000 for `DynamoEventSource`
* * 10000 for `KinesisEventSource`, `ManagedKafkaEventSource` and `SelfManagedKafkaEventSource`
*
* @default 100
*/
readonly batchSize?: number;
/**
* Where to begin consuming the stream.
*/
readonly startingPosition: lambda.StartingPosition;
/**
* The maximum amount of time to gather records before invoking the function.
* Maximum of Duration.minutes(5).
*
* @see https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html#invocation-eventsourcemapping-batching
*
* @default - Duration.seconds(0) for Kinesis, DynamoDB, and SQS event sources, Duration.millis(500) for MSK, self-managed Kafka, and Amazon MQ.
*/
readonly maxBatchingWindow?: Duration;
/**
* If the stream event source mapping should be enabled.
*
* @default true
*/
readonly enabled?: boolean;
/**
* Configuration for provisioned pollers that read from the event source.
* When specified, allows control over the minimum and maximum number of pollers
* that can be provisioned to process events from the source.
* @default - no provisioned pollers
*/
readonly provisionedPollerConfig?: ProvisionedPollerConfig;
}
/**
* (Amazon MSK and self-managed Apache Kafka only) The provisioned mode configuration for the event source.
*/
export interface ProvisionedPollerConfig {
/**
* The minimum number of pollers that should be provisioned.
*
* @default 1
*/
readonly minimumPollers: number;
/**
* The maximum number of pollers that can be provisioned.
*
* @default 200
*/
readonly maximumPollers: number;
/**
* An optional identifier that groups multiple ESMs to share EPU capacity
* and reduce costs. ESMs with the same PollerGroupName share compute
* resources.
*
* @default - not set, dedicated compute resource per event source.
*/
readonly pollerGroupName?: string;
}
/**
* The set of properties for streaming event sources shared by
* Dynamo and Kinesis.
*/
export interface StreamEventSourceProps extends BaseStreamEventSourceProps {
/**
* If the function returns an error, split the batch in two and retry.
*
* @default false
*/
readonly bisectBatchOnError?: boolean;
/**
* The maximum age of a record that Lambda sends to a function for processing.
* Valid Range:
* * Minimum value of 60 seconds
* * Maximum value of 7 days
*
* The default value is -1, which sets the maximum age to infinite.
* When the value is set to infinite, Lambda never discards old records.
* Record are valid until it expires in the event source.
*
* @default -1
*/
readonly maxRecordAge?: Duration;
/**
* Maximum number of retry attempts.
*
* Set to -1 for infinite retries (until the record expires in the event source).
*
* Valid Range: -1 (infinite) or 0 to 10000
*
* @default -1 (infinite retries)
*/
readonly retryAttempts?: number;
/**
* The number of batches to process from each shard concurrently.
* Valid Range:
* * Minimum value of 1
* * Maximum value of 10
*
* @default 1
*/
readonly parallelizationFactor?: number;
/**
* Allow functions to return partially successful responses for a batch of records.
*
* @see https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html#services-ddb-batchfailurereporting
*
* @default false
*/
readonly reportBatchItemFailures?: boolean;
/**
* The size of the tumbling windows to group records sent to DynamoDB or Kinesis
* Valid Range: 0 - 15 minutes
*
* @default - None
*/
readonly tumblingWindow?: Duration;
/**
* An Amazon S3, Amazon SQS queue or Amazon SNS topic destination for discarded records.
*
* @default - discarded records are ignored
*/
readonly onFailure?: lambda.IEventSourceDlq;
/**
* Add filter criteria option
*
* @default - None
*/
readonly filters?: Array<{
[key: string]: any;
}>;
/**
* Add Customer managed KMS key to encrypt Filter Criteria.
* @see https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventfiltering.html
* By default, Lambda will encrypt Filter Criteria using AWS managed keys
* @see https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#aws-managed-cmk
*
* @default - none
*/
readonly filterEncryption?: IKey;
/**
* Configuration for enhanced monitoring metrics collection
* When specified, enables collection of additional metrics for the stream event source
*
* @default - Enhanced monitoring is disabled
*/
readonly metricsConfig?: lambda.MetricsConfig;
}
/**
* Use an stream as an event source for AWS Lambda.
*/
export declare abstract class StreamEventSource implements lambda.IEventSource {
protected readonly props: StreamEventSourceProps;
protected constructor(props: StreamEventSourceProps);
abstract bind(_target: lambda.IFunction): void;
protected enrichMappingOptions(options: lambda.EventSourceMappingOptions): lambda.EventSourceMappingOptions;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StreamEventSource=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var s3_onfailuire_destination_1=()=>{var tmp=require("./s3-onfailuire-destination");return s3_onfailuire_destination_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};class StreamEventSource{props;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_lambda_event_sources.StreamEventSource",version:"2.252.0"};constructor(props){this.props=props;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_event_sources_StreamEventSourceProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,StreamEventSource),error}if(props.provisionedPollerConfig){const{minimumPollers,maximumPollers}=props.provisionedPollerConfig,isMinimumPollersDefinedAndResolved=minimumPollers!=null&&!core_1().Token.isUnresolved(minimumPollers),isMaximumPollersDefinedAndResolved=maximumPollers!=null&&!core_1().Token.isUnresolved(maximumPollers);if(isMinimumPollersDefinedAndResolved&&(minimumPollers<1||minimumPollers>200))throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`MustBeMinimumProvisionedPollers`,"Minimum provisioned pollers must be between 1 and 200 inclusive");if(isMaximumPollersDefinedAndResolved&&(maximumPollers<1||maximumPollers>2e3))throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`MustBeMaximumProvisionedPollers`,"Maximum provisioned pollers must be between 1 and 2000 inclusive");if(isMinimumPollersDefinedAndResolved&&isMaximumPollersDefinedAndResolved&&minimumPollers>maximumPollers)throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`MustBeMinimumProvisionedPollers`,"Minimum provisioned pollers must be less than or equal to maximum provisioned pollers")}}enrichMappingOptions(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_EventSourceMappingOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.enrichMappingOptions),error}if(this.props.onFailure instanceof s3_onfailuire_destination_1().S3OnFailureDestination&&!options.supportS3OnFailureDestination)throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`OnfailureDestinationSupportedEvent`,"S3 onFailure Destination is not supported for this event source");return{...options,batchSize:this.props.batchSize||100,bisectBatchOnError:this.props.bisectBatchOnError,startingPosition:this.props.startingPosition,reportBatchItemFailures:this.props.reportBatchItemFailures,maxBatchingWindow:this.props.maxBatchingWindow,maxRecordAge:this.props.maxRecordAge,retryAttempts:this.props.retryAttempts,parallelizationFactor:this.props.parallelizationFactor,onFailure:this.props.onFailure,tumblingWindow:this.props.tumblingWindow,enabled:this.props.enabled,filters:this.props.filters,filterEncryption:this.props.filterEncryption}}}exports.StreamEventSource=StreamEventSource;