Skip to content

Commit 0777c80

Browse files
ptoffysebsto
andauthored
Add S3EventNotifier example (#477)
Add `S3EventNotifier` example ### Motivation: There is currently no example regarding an AWS event triggered lambda, such as a lambda that gets invoked on an S3 object upload. I've had to look for a while to figure out that the `AWSLambdaEvents` exists and that it can be used for that (had to find out via a Java example! 😜) so I think this could be useful and a somewhat common use case ### Modifications: Added an example of a lambda that gets triggered when an object gets uploaded to an S3 bucket. I have not described how to set up the actual S3 event in AWS because I figured if you needed such a lambda you'd know, but I can describe that too in the README if needed --------- Co-authored-by: Sébastien Stormacq <[email protected]>
1 parent bd0ec62 commit 0777c80

File tree

6 files changed

+190
-2
lines changed

6 files changed

+190
-2
lines changed

.github/workflows/pull_request.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ jobs:
3636
# We pass the list of examples here, but we can't pass an array as argument
3737
# Instead, we pass a String with a valid JSON array.
3838
# The workaround is mentioned here https://github.com/orgs/community/discussions/11692
39-
examples: "[ 'APIGateway', 'APIGateway+LambdaAuthorizer', 'BackgroundTasks', 'HelloJSON', 'HelloWorld', 'ResourcesPackaging', 'S3_AWSSDK', 'S3_Soto', 'Streaming', 'Testing', 'Tutorial' ]"
39+
examples: "[ 'APIGateway', 'APIGateway+LambdaAuthorizer', 'BackgroundTasks', 'HelloJSON', 'HelloWorld', 'ResourcesPackaging', 'S3EventNotifier', 'S3_AWSSDK', 'S3_Soto', 'Streaming', 'Testing', 'Tutorial' ]"
4040
archive_plugin_examples: "[ 'HelloWorld', 'ResourcesPackaging' ]"
4141
archive_plugin_enabled: true
4242

Examples/README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ This directory contains example code for Lambda functions.
2828

2929
- **[HelloWorld](HelloWorld/README.md)**: a simple Lambda function (requires [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)).
3030

31+
- **[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.
32+
3133
- **[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/)).
3234

3335
- **[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:
6466

6567
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.
6668

67-
With these in hand, you can use AWS SigV4 to securely sign your requests and interact with AWS services from your Swift app.
69+
With these in hand, you can use AWS SigV4 to securely sign your requests and interact with AWS services from your Swift app.

Examples/S3EventNotifier/.gitignore

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
.DS_Store
2+
/.build
3+
/.index-build
4+
/Packages
5+
xcuserdata/
6+
DerivedData/
7+
.swiftpm/configuration/registries.json
8+
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
9+
.netrc
+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// swift-tools-version: 6.0
2+
import PackageDescription
3+
4+
// needed for CI to test the local version of the library
5+
import struct Foundation.URL
6+
7+
let package = Package(
8+
name: "S3EventNotifier",
9+
platforms: [.macOS(.v15)],
10+
dependencies: [
11+
.package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", branch: "main"),
12+
.package(url: "https://github.com/swift-server/swift-aws-lambda-events", branch: "main"),
13+
],
14+
targets: [
15+
.executableTarget(
16+
name: "S3EventNotifier",
17+
dependencies: [
18+
.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),
19+
.product(name: "AWSLambdaEvents", package: "swift-aws-lambda-events"),
20+
]
21+
)
22+
]
23+
)
24+
25+
if let localDepsPath = Context.environment["LAMBDA_USE_LOCAL_DEPS"],
26+
localDepsPath != "",
27+
let v = try? URL(fileURLWithPath: localDepsPath).resourceValues(forKeys: [.isDirectoryKey]),
28+
v.isDirectory == true
29+
{
30+
// when we use the local runtime as deps, let's remove the dependency added above
31+
let indexToRemove = package.dependencies.firstIndex { dependency in
32+
if case .sourceControl(
33+
name: _,
34+
location: "https://github.com/swift-server/swift-aws-lambda-runtime.git",
35+
requirement: _
36+
) = dependency.kind {
37+
return true
38+
}
39+
return false
40+
}
41+
if let indexToRemove {
42+
package.dependencies.remove(at: indexToRemove)
43+
}
44+
45+
// then we add the dependency on LAMBDA_USE_LOCAL_DEPS' path (typically ../..)
46+
print("[INFO] Compiling against swift-aws-lambda-runtime located at \(localDepsPath)")
47+
package.dependencies += [
48+
.package(name: "swift-aws-lambda-runtime", path: localDepsPath)
49+
]
50+
}

Examples/S3EventNotifier/README.md

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# S3 Event Notifier
2+
3+
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.
4+
5+
## Code
6+
7+
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:
8+
9+
```swift
10+
guard let s3NotificationRecord = event.records.first else {
11+
throw LambdaError.noNotificationRecord
12+
}
13+
14+
let bucket = s3NotificationRecord.s3.bucket.name
15+
let key = s3NotificationRecord.s3.object.key.replacingOccurrences(of: "+", with: " ")
16+
```
17+
18+
The key is URL encoded, so we replace the `+` with a space.
19+
20+
## Build & Package
21+
22+
To build & archive the package you can use the following commands:
23+
24+
```bash
25+
swift build
26+
swift package archive --allow-network-connections docker
27+
```
28+
29+
If there are no errors, a ZIP file should be ready to deploy, located at `.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/S3EventNotifier/S3EventNotifier.zip`.
30+
31+
## Deploy
32+
33+
> [!IMPORTANT]
34+
> 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).
35+
36+
To deploy the Lambda function, you can use the `aws` command line:
37+
38+
```bash
39+
REGION=eu-west-1
40+
aws lambda create-function \
41+
--region "${REGION}" \
42+
--function-name S3EventNotifier \
43+
--zip-file fileb://.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/S3EventNotifier/S3EventNotifier.zip \
44+
--runtime provided.al2 \
45+
--handler provided \
46+
--architectures arm64 \
47+
--role arn:aws:iam::<YOUR_ACCOUNT_ID>:role/lambda_basic_execution
48+
```
49+
50+
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`.
51+
52+
Be sure to define `REGION` with the region where you want to deploy your Lambda function and replace `<YOUR_ACCOUNT_ID>` with your actual AWS account ID (for example: 012345678901).
53+
54+
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:
55+
56+
```bash
57+
REGION=eu-west-1
58+
59+
aws s3api create-bucket \
60+
--region "${REGION}" \
61+
--bucket my-test-bucket \
62+
--create-bucket-configuration LocationConstraint="${REGION}"
63+
64+
aws lambda add-permission \
65+
--region "${REGION}" \
66+
--function-name S3EventNotifier \
67+
--statement-id S3InvokeFunction \
68+
--action lambda:InvokeFunction \
69+
--principal s3.amazonaws.com \
70+
--source-arn arn:aws:s3:::my-test-bucket
71+
72+
aws s3api put-bucket-notification-configuration \
73+
--region "${REGION}" \
74+
--bucket my-test-bucket \
75+
--notification-configuration '{
76+
"LambdaFunctionConfigurations": [{
77+
"LambdaFunctionArn": "arn:aws:lambda:${REGION}:<YOUR_ACCOUNT_ID>:function:S3EventNotifier",
78+
"Events": ["s3:ObjectCreated:*"]
79+
}]
80+
}'
81+
82+
touch testfile.txt && aws s3 cp testfile.txt s3://my-test-bucket/
83+
```
84+
85+
This will:
86+
- create a bucket named `my-test-bucket` in the `$REGION` region;
87+
- add a permission to the Lambda function to be invoked by Amazon S3;
88+
- configure the bucket to send `s3:ObjectCreated:*` events to the Lambda function named `S3EventNotifier`;
89+
- upload a file named `testfile.txt` to the bucket.
90+
91+
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 `<YOUR_ACCOUNT_ID>` with your actual AWS account ID.
92+
93+
> [!IMPORTANT]
94+
> 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.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the SwiftAWSLambdaRuntime open source project
4+
//
5+
// Copyright (c) 2025 Apple Inc. and the SwiftAWSLambdaRuntime project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
import AWSLambdaEvents
16+
import AWSLambdaRuntime
17+
import Foundation
18+
19+
let runtime = LambdaRuntime { (event: S3Event, context: LambdaContext) async throws in
20+
guard let s3NotificationRecord = event.records.first else {
21+
context.logger.error("No S3 notification record found in the event")
22+
return
23+
}
24+
25+
let bucket = s3NotificationRecord.s3.bucket.name
26+
let key = s3NotificationRecord.s3.object.key.replacingOccurrences(of: "+", with: " ")
27+
28+
context.logger.info("Received notification from S3 bucket '\(bucket)' for object with key '\(key)'")
29+
30+
// Here you could, for example, notify an API or a messaging service
31+
}
32+
33+
try await runtime.run()

0 commit comments

Comments
 (0)