Skip to content

Commit 5e80824

Browse files
committed
add soto example
1 parent 570b416 commit 5e80824

File tree

5 files changed

+278
-0
lines changed

5 files changed

+278
-0
lines changed

Examples/Soto/.gitignore

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
.DS_Store
2+
.aws-sam/
3+
.build
4+
samtemplate.toml
5+
*/build/*
6+
/.build
7+
/Packages
8+
xcuserdata/
9+
DerivedData/
10+
.swiftpm/configuration/registries.json
11+
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
12+
.netrc

Examples/Soto/Package.swift

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// swift-tools-version: 6.0
2+
// The swift-tools-version declares the minimum version of Swift required to build this package.
3+
4+
//===----------------------------------------------------------------------===//
5+
//
6+
// This source file is part of the AWS Lambda Swift
7+
// VSCode extension open source project.
8+
//
9+
// Copyright (c) 2024, the VSCode AWS Lambda Swift extension project authors.
10+
// Licensed under Apache License v2.0.
11+
//
12+
// See LICENSE.txt for license information
13+
// See CONTRIBUTORS.txt for the list of VSCode AWS Lambda Swift project authors
14+
//
15+
// SPDX-License-Identifier: Apache-2.0
16+
//
17+
//===----------------------------------------------------------------------===//
18+
19+
import PackageDescription
20+
21+
// needed for CI to test the local version of the library
22+
import class Foundation.ProcessInfo
23+
import struct Foundation.URL
24+
25+
#if os(macOS)
26+
let platforms: [PackageDescription.SupportedPlatform]? = [.macOS(.v15)]
27+
#else
28+
let platforms: [PackageDescription.SupportedPlatform]? = nil
29+
#endif
30+
31+
32+
let package = Package(
33+
name: "SotoLambdaExample",
34+
platforms: platforms,
35+
products: [
36+
.executable(name: "SotoLambdaExample", targets: ["SotoExample"])
37+
],
38+
dependencies: [
39+
.package(url: "https://github.com/soto-project/soto.git", from: "7.0.0"),
40+
41+
// dependency on swift-aws-lambda-runtime is added dynamically below
42+
// .package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", branch: "main")
43+
.package(url: "https://github.com/swift-server/swift-aws-lambda-events", branch: "main")
44+
],
45+
targets: [
46+
.executableTarget(
47+
name: "SotoExample",
48+
dependencies: [
49+
.product(name: "SotoS3", package: "soto"),
50+
.product(name: "AWSLambdaRuntime",package: "swift-aws-lambda-runtime"),
51+
.product(name: "AWSLambdaEvents",package: "swift-aws-lambda-events"),
52+
]
53+
)
54+
]
55+
)
56+
57+
if let localDepsPath = ProcessInfo.processInfo.environment["LAMBDA_USE_LOCAL_DEPS"],
58+
localDepsPath != "",
59+
let v = try? URL(fileURLWithPath: localDepsPath).resourceValues(forKeys: [.isDirectoryKey]),
60+
let _ = v.isDirectory
61+
{
62+
print("[INFO] Compiling against swift-aws-lambda-runtime located at \(localDepsPath)")
63+
package.dependencies += [
64+
.package(name: "swift-aws-lambda-runtime", path: localDepsPath)
65+
]
66+
67+
} else {
68+
print("[INFO] LAMBDA_USE_LOCAL_DEPS is not pointing to your local swift-aws-lambda-runtime code")
69+
print("[INFO] This project will compile against the main branch of the Lambda Runtime on GitHub")
70+
package.dependencies += [
71+
.package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", branch: "main")
72+
]
73+
}

Examples/Soto/README.md

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
sam deploy \
2+
--resolve-s3 \
3+
--template-file template.yaml \
4+
--stack-name AWSSDKExample \
5+
--capabilities CAPABILITY_IAM
6+
7+
# API Gateway
8+
9+
This is a simple example of an AWS Lambda function that uses the [AWS SDK for Swift](https://github.com/awslabs/aws-sdk-swift) to read data from Amazon S3.
10+
11+
## Code
12+
13+
The Lambda function reads all bucket names from your AWS account and return them as a String.
14+
15+
The code creates a `LambdaRuntime` struct. In it's simplest form, the initializer takes a function as argument. The function is the handler that will be invoked when the API Gateway receives an HTTP request.
16+
17+
The handler is `(event: APIGatewayV2Request, context: LambdaContext) -> APIGatewayV2Response`. The function takes two arguments:
18+
- the event argument is a `APIGatewayV2Request`. It is the parameter passed by the API Gateway. It contains all data passed in the HTTP request and some meta data.
19+
- the context argument is a `Lambda Context`. It is a description of the runtime context.
20+
21+
The function must return a `APIGatewayV2Response`.
22+
23+
`APIGatewayV2Request` and `APIGatewayV2Response` are defined in the [Swift AWS Lambda Events](https://github.com/swift-server/swift-aws-lambda-events) library.
24+
25+
The handler creates an S3 client and `ListBucketsInput` object. It passes the input object to the client and receives an output response.
26+
It then extract the list of bucket names from the output to create a `\n` separated list of names, as a `String`
27+
28+
## Build & Package
29+
30+
To build the package, type the following commands.
31+
32+
```bash
33+
swift build
34+
swift package archive --allow-network-access docker
35+
```
36+
37+
If there is no error, there is a ZIP file ready to deploy.
38+
The ZIP file is located at `.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/AWSSDKExample/AWSSDKExample.zip`
39+
40+
## Deploy
41+
42+
The deployment must include the Lambda function and an API Gateway. We use the [Serverless Application Model (SAM)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) to deploy the infrastructure.
43+
44+
**Prerequisites** : Install the [SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html)
45+
46+
The example directory contains a file named `template.yaml` that describes the deployment.
47+
48+
To actually deploy your Lambda function and create the infrastructure, type the following `sam` command.
49+
50+
```bash
51+
sam deploy \
52+
--resolve-s3 \
53+
--template-file template.yaml \
54+
--stack-name AWSSDKExample \
55+
--capabilities CAPABILITY_IAM
56+
```
57+
58+
At the end of the deployment, the script lists the API Gateway endpoint.
59+
The output is similar to this one.
60+
61+
```
62+
-----------------------------------------------------------------------------------------------------------------------------
63+
Outputs
64+
-----------------------------------------------------------------------------------------------------------------------------
65+
Key APIGAtewayEndpoint
66+
Description API Gateway endpoint URL"
67+
Value https://a5q74es3k2.execute-api.us-east-1.amazonaws.com
68+
-----------------------------------------------------------------------------------------------------------------------------
69+
```
70+
71+
## Invoke your Lambda function
72+
73+
To invoke the Lambda function, use this `curl` command line.
74+
75+
```bash
76+
curl https://a5q74es3k2.execute-api.us-east-1.amazonaws.com
77+
```
78+
79+
Be sure to replace the URL with the API Gateway endpoint returned in the previous step.
80+
81+
This should print text similar to
82+
83+
```bash
84+
my_bucket_1
85+
my_bucket_2
86+
```
87+
88+
## Undeploy
89+
90+
When done testing, you can delete the infrastructure with this command.
91+
92+
```bash
93+
sam delete
94+
```

Examples/Soto/Sources/main.swift

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the SwiftAWSLambdaRuntime open source project
4+
//
5+
// Copyright (c) 2024 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 AWSLambdaRuntime
16+
import AWSLambdaEvents
17+
18+
import SotoS3
19+
20+
let client = AWSClient()
21+
let s3 = S3(client: client, region: .useast1)
22+
23+
func handler(event: APIGatewayV2Request, context: LambdaContext) async throws -> APIGatewayV2Response {
24+
25+
var response: APIGatewayV2Response
26+
do {
27+
context.logger.debug("Reading list of buckets")
28+
29+
// read the list of buckets
30+
let bucketResponse = try await s3.listBuckets()
31+
let bucketList = bucketResponse.buckets?.compactMap { $0.name }
32+
response = APIGatewayV2Response(statusCode: .ok, body: bucketList?.joined(separator: "\n"))
33+
} catch {
34+
context.logger.error("\(error)")
35+
response = APIGatewayV2Response(statusCode: .internalServerError, body: "[ERROR] \(error)")
36+
}
37+
return response
38+
}
39+
40+
let runtime = LambdaRuntime.init(body: handler)
41+
try await runtime.run()

Examples/Soto/template.yaml

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#===----------------------------------------------------------------------===//
2+
#
3+
# This source file is part of the AWS Lambda Swift
4+
# VSCode extension open source project.
5+
#
6+
# Copyright (c) 2024, the VSCode AWS Lambda Swift extension project authors.
7+
# Licensed under Apache License v2.0.
8+
#
9+
# See LICENSE.txt for license information
10+
# See CONTRIBUTORS.txt for the list of VSCode AWS Lambda Swift project authors
11+
#
12+
# SPDX-License-Identifier: Apache-2.0
13+
#
14+
#===----------------------------------------------------------------------===//
15+
16+
AWSTemplateFormatVersion: '2010-09-09'
17+
Transform: AWS::Serverless-2016-10-31
18+
Description: SAM Template for AWS SDK Example
19+
20+
Resources:
21+
# Lambda function
22+
SotoExample:
23+
Type: AWS::Serverless::Function
24+
Properties:
25+
CodeUri: .build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/SotoExample/SotoExample.zip
26+
Timeout: 60
27+
Handler: swift.bootstrap
28+
Runtime: provided.al2
29+
MemorySize: 512
30+
Architectures:
31+
- arm64
32+
Environment:
33+
Variables:
34+
# by default, AWS Lambda runtime produces no log
35+
# use `LOG_LEVEL: debug` for for lifecycle and event handling information
36+
# use `LOG_LEVEL: trace` for detailed input event information
37+
LOG_LEVEL: trace
38+
39+
# Handles all methods of the REST API
40+
Events:
41+
Api:
42+
Type: HttpApi
43+
44+
# Add an IAM policy to this function.
45+
# It grants the function permissions to read the list of buckets in your account.
46+
Policies:
47+
- Statement:
48+
- Sid: ListAllS3BucketsInYourAccount
49+
Effect: Allow
50+
Action:
51+
- s3:ListAllMyBuckets
52+
Resource: '*'
53+
54+
# print API endpoint
55+
Outputs:
56+
SwiftAPIEndpoint:
57+
Description: "API Gateway endpoint URL for your application"
58+
Value: !Sub "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com"

0 commit comments

Comments
 (0)