diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 72c2a24c..9c1e88a3 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -36,7 +36,7 @@ jobs: # We pass the list of examples here, but we can't pass an array as argument # Instead, we pass a String with a valid JSON array. # The workaround is mentioned here https://github.com/orgs/community/discussions/11692 - examples: "[ 'APIGateway', 'APIGateway+LambdaAuthorizer', 'BackgroundTasks', 'HelloJSON', 'HelloWorld', 'ResourcesPackaging', 'S3_AWSSDK', 'S3_Soto', 'Streaming', 'Testing', 'Tutorial' ]" + examples: "[ 'APIGateway', 'APIGateway+LambdaAuthorizer', 'BackgroundTasks', 'HelloJSON', 'HelloWorld', 'ResourcesPackaging', 'S3EventNotifier', 'S3_AWSSDK', 'S3_Soto', 'Streaming', 'Testing', 'Tutorial' ]" archive_plugin_examples: "[ 'HelloWorld', 'ResourcesPackaging' ]" archive_plugin_enabled: true diff --git a/Examples/README.md b/Examples/README.md index 53ccc8bd..973df897 100644 --- a/Examples/README.md +++ b/Examples/README.md @@ -28,6 +28,8 @@ This directory contains example code for Lambda functions. - **[HelloWorld](HelloWorld/README.md)**: a simple Lambda function (requires [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)). +- **[S3EventNotifier](S3EventNotifier/README.md)**: a Lambda function that receives object-upload notifications from an [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) bucket. + - **[S3_AWSSDK](S3_AWSSDK/README.md)**: a Lambda function that uses the [AWS SDK for Swift](https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/getting-started.html) to invoke an [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) API (requires [AWS SAM](https://aws.amazon.com/serverless/sam/)). - **[S3_Soto](S3_Soto/README.md)**: a Lambda function that uses [Soto](https://github.com/soto-project/soto) to invoke an [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) API (requires [AWS SAM](https://aws.amazon.com/serverless/sam/)). @@ -64,4 +66,4 @@ To obtain these keys, you need an AWS account: 4. **(Optional) Generate Temporary Security Credentials**: If you’re using temporary credentials (which are more secure for short-term access), use AWS Security Token Service (STS). You can call the `GetSessionToken` or `AssumeRole` API to generate temporary credentials, including a session token. -With these in hand, you can use AWS SigV4 to securely sign your requests and interact with AWS services from your Swift app. \ No newline at end of file +With these in hand, you can use AWS SigV4 to securely sign your requests and interact with AWS services from your Swift app. diff --git a/Examples/S3EventNotifier/.gitignore b/Examples/S3EventNotifier/.gitignore new file mode 100644 index 00000000..10edc03d --- /dev/null +++ b/Examples/S3EventNotifier/.gitignore @@ -0,0 +1,9 @@ +.DS_Store +/.build +/.index-build +/Packages +xcuserdata/ +DerivedData/ +.swiftpm/configuration/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc diff --git a/Examples/S3EventNotifier/Package.swift b/Examples/S3EventNotifier/Package.swift new file mode 100644 index 00000000..6554b385 --- /dev/null +++ b/Examples/S3EventNotifier/Package.swift @@ -0,0 +1,50 @@ +// swift-tools-version: 6.0 +import PackageDescription + +// needed for CI to test the local version of the library +import struct Foundation.URL + +let package = Package( + name: "S3EventNotifier", + platforms: [.macOS(.v15)], + dependencies: [ + .package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", branch: "main"), + .package(url: "https://github.com/swift-server/swift-aws-lambda-events", branch: "main"), + ], + targets: [ + .executableTarget( + name: "S3EventNotifier", + dependencies: [ + .product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"), + .product(name: "AWSLambdaEvents", package: "swift-aws-lambda-events"), + ] + ) + ] +) + +if let localDepsPath = Context.environment["LAMBDA_USE_LOCAL_DEPS"], + localDepsPath != "", + let v = try? URL(fileURLWithPath: localDepsPath).resourceValues(forKeys: [.isDirectoryKey]), + v.isDirectory == true +{ + // when we use the local runtime as deps, let's remove the dependency added above + let indexToRemove = package.dependencies.firstIndex { dependency in + if case .sourceControl( + name: _, + location: "https://github.com/swift-server/swift-aws-lambda-runtime.git", + requirement: _ + ) = dependency.kind { + return true + } + return false + } + if let indexToRemove { + package.dependencies.remove(at: indexToRemove) + } + + // then we add the dependency on LAMBDA_USE_LOCAL_DEPS' path (typically ../..) + print("[INFO] Compiling against swift-aws-lambda-runtime located at \(localDepsPath)") + package.dependencies += [ + .package(name: "swift-aws-lambda-runtime", path: localDepsPath) + ] +} diff --git a/Examples/S3EventNotifier/README.md b/Examples/S3EventNotifier/README.md new file mode 100644 index 00000000..3ccee239 --- /dev/null +++ b/Examples/S3EventNotifier/README.md @@ -0,0 +1,94 @@ +# S3 Event Notifier + +This example demonstrates how to write a Lambda that is invoked by an event originating from Amazon S3, such as a new object being uploaded to a bucket. + +## Code + +In this example the Lambda function receives an `S3Event` object defined in the `AWSLambdaEvents` library as input object. The `S3Event` object contains all the information about the S3 event that triggered the function, but what we are interested in is the bucket name and the object key, which are inside of a notification `Record`. The object contains an array of records, however since the Lambda function is triggered by a single event, we can safely assume that there is only one record in the array: the first one. Inside of this record, we can find the bucket name and the object key: + +```swift +guard let s3NotificationRecord = event.records.first else { + throw LambdaError.noNotificationRecord +} + +let bucket = s3NotificationRecord.s3.bucket.name +let key = s3NotificationRecord.s3.object.key.replacingOccurrences(of: "+", with: " ") +``` + +The key is URL encoded, so we replace the `+` with a space. + +## Build & Package + +To build & archive the package you can use the following commands: + +```bash +swift build +swift package archive --allow-network-connections docker +``` + +If there are no errors, a ZIP file should be ready to deploy, located at `.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/S3EventNotifier/S3EventNotifier.zip`. + +## Deploy + +> [!IMPORTANT] +> The Lambda function and the S3 bucket must be located in the same AWS Region. In the code below, we use `eu-west-1` (Ireland). + +To deploy the Lambda function, you can use the `aws` command line: + +```bash +REGION=eu-west-1 +aws lambda create-function \ + --region "${REGION}" \ + --function-name S3EventNotifier \ + --zip-file fileb://.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/S3EventNotifier/S3EventNotifier.zip \ + --runtime provided.al2 \ + --handler provided \ + --architectures arm64 \ + --role arn:aws:iam:::role/lambda_basic_execution +``` + +The `--architectures` flag is only required when you build the binary on an Apple Silicon machine (Apple M1 or more recent). It defaults to `x64`. + +Be sure to define `REGION` with the region where you want to deploy your Lambda function and replace `` with your actual AWS account ID (for example: 012345678901). + +Besides deploying the Lambda function you also need to create the S3 bucket and configure it to send events to the Lambda function. You can do this using the following commands: + +```bash +REGION=eu-west-1 + +aws s3api create-bucket \ + --region "${REGION}" \ + --bucket my-test-bucket \ + --create-bucket-configuration LocationConstraint="${REGION}" + +aws lambda add-permission \ + --region "${REGION}" \ + --function-name S3EventNotifier \ + --statement-id S3InvokeFunction \ + --action lambda:InvokeFunction \ + --principal s3.amazonaws.com \ + --source-arn arn:aws:s3:::my-test-bucket + +aws s3api put-bucket-notification-configuration \ + --region "${REGION}" \ + --bucket my-test-bucket \ + --notification-configuration '{ + "LambdaFunctionConfigurations": [{ + "LambdaFunctionArn": "arn:aws:lambda:${REGION}::function:S3EventNotifier", + "Events": ["s3:ObjectCreated:*"] + }] + }' + +touch testfile.txt && aws s3 cp testfile.txt s3://my-test-bucket/ +``` + +This will: + - create a bucket named `my-test-bucket` in the `$REGION` region; + - add a permission to the Lambda function to be invoked by Amazon S3; + - configure the bucket to send `s3:ObjectCreated:*` events to the Lambda function named `S3EventNotifier`; + - upload a file named `testfile.txt` to the bucket. + +Replace `my-test-bucket` with your bucket name (bucket names are unique globaly and this one is already taken). Also replace `REGION` environment variable with the AWS Region where you deployed the Lambda function and `` with your actual AWS account ID. + +> [!IMPORTANT] +> The Lambda function and the S3 bucket must be located in the same AWS Region. Adjust the code above according to your closest AWS Region. \ No newline at end of file diff --git a/Examples/S3EventNotifier/Sources/main.swift b/Examples/S3EventNotifier/Sources/main.swift new file mode 100644 index 00000000..9a55974e --- /dev/null +++ b/Examples/S3EventNotifier/Sources/main.swift @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftAWSLambdaRuntime open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftAWSLambdaRuntime project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import AWSLambdaEvents +import AWSLambdaRuntime +import Foundation + +let runtime = LambdaRuntime { (event: S3Event, context: LambdaContext) async throws in + guard let s3NotificationRecord = event.records.first else { + context.logger.error("No S3 notification record found in the event") + return + } + + let bucket = s3NotificationRecord.s3.bucket.name + let key = s3NotificationRecord.s3.object.key.replacingOccurrences(of: "+", with: " ") + + context.logger.info("Received notification from S3 bucket '\(bucket)' for object with key '\(key)'") + + // Here you could, for example, notify an API or a messaging service +} + +try await runtime.run()