Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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', 'HummingbirdLambda', 'ResourcesPackaging', 'S3EventNotifier', 'S3_AWSSDK', 'S3_Soto', 'Streaming', 'Streaming+Codable', 'ServiceLifecycle+Postgres', 'Testing', 'Tutorial' ]"
examples: "[ 'APIGateway', 'APIGateway+LambdaAuthorizer', 'BackgroundTasks', 'HelloJSON', 'HelloWorld', 'HelloWorldNoTraits', 'HummingbirdLambda', 'ResourcesPackaging', 'S3EventNotifier', 'S3_AWSSDK', 'S3_Soto', 'Streaming', 'Streaming+Codable', 'ServiceLifecycle+Postgres', 'Testing', 'Tutorial' ]"
archive_plugin_examples: "[ 'HelloWorld', 'ResourcesPackaging' ]"
archive_plugin_enabled: true

Expand Down
4 changes: 4 additions & 0 deletions Examples/HelloWorldNoTraits/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
response.json
samconfig.toml
template.yaml
Makefile
54 changes: 54 additions & 0 deletions Examples/HelloWorldNoTraits/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// swift-tools-version:6.1

import PackageDescription

// needed for CI to test the local version of the library
import struct Foundation.URL

let package = Package(
name: "swift-aws-lambda-runtime-example",
platforms: [.macOS(.v15)],
products: [
.executable(name: "MyLambda", targets: ["MyLambda"])
],
dependencies: [
// during CI, the dependency on local version of swift-aws-lambda-runtime is added dynamically below
.package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", from: "2.0.0-beta.3", traits: [])
],
targets: [
.executableTarget(
name: "MyLambda",
dependencies: [
.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime")
],
path: "Sources"
)
]
)

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, traits: [])
]
}
107 changes: 107 additions & 0 deletions Examples/HelloWorldNoTraits/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# Hello World, with no traits

This is an example of a low-level AWS Lambda function that takes a `ByteBuffer` as input parameter and writes its response on the provided `LambdaResponseStreamWriter`.

This function disables all the default traits: the support for JSON Encoder and Decoder from Foundation, the support for Swift Service Lifecycle, and for the local tetsing server.

The main reasons of the existence of this example are

1. to show how to write a low-level Lambda function that doesn't rely on JSON encodinga and decoding.
2. to show you how to disable traits when using the Lambda Runtime Library.
3. to add an integration test to our continous integration pipeline to make sure the library compiles with no traits enabled.

## Disabling all traits

Traits are functions of the AWS Lambda Runtime that you can disable at compile time to reduce the size of your binary, and therefore reduce the cold start time of your Lambda function.

The library supports three traits:

- "FoundationJSONSupport": adds the required API to encode and decode payloads with Foundation's `JSONEncoder` and `JSONDecoder`.

- "ServiceLifecycleSupport": adds support for the Swift Service Lifecycle library.

- "LocalServerSupport": adds support for testing your function locally with a built-in HTTP server.

This example disables all the traits. To disable one or several traits, modify `Package.swift`:

```swift
dependencies: [
.package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", from: "2.0.0-beta", traits: [])
],
```

## Code

The code creates a `LambdaRuntime` struct. In its simplest form, the initializer takes a function as argument. The function is the handler that will be invoked when an event triggers the Lambda function.

The handler signature is `(event: ByteBuffer, response: LambdaResponseStreamWriter, context: LambdaContext)`.

The function takes three arguments:
- the event argument is a `ByteBuffer`. It's the parameter passed when invoking the function. You are responsible of decoding this parameter, if necessary.
- the response writer provides you with functions to write the response stream back.
- the context argument is a `Lambda Context`. It is a description of the runtime context.

The function return value will be encoded as your Lambda function response.

## Test locally

You cannot test this function locally, because the "LocalServer" trait is disabled.

## Build & Package

To build & archive the package, type the following commands.

```bash
swift build
swift package archive --allow-network-connections docker
```

If there is no error, there is a ZIP file ready to deploy.
The ZIP file is located at `.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/MyLambda/MyLambda.zip`

## Deploy

Here is how to deploy using the `aws` command line.

```bash
aws lambda create-function \
--function-name MyLambda \
--zip-file fileb://.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/MyLambda/MyLambda.zip \
--runtime provided.al2 \
--handler provided \
--architectures arm64 \
--role arn:aws:iam::<YOUR_ACCOUNT_ID>: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 replace <YOUR_ACCOUNT_ID> with your actual AWS account ID (for example: 012345678901).

## Invoke your Lambda function

To invoke the Lambda function, use this `aws` command line.

```bash
aws lambda invoke \
--function-name MyLambda \
--payload $(echo "Seb" | base64) \
out.txt && cat out.txt && rm out.txt
```

This should output the following result.

```
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
"Hello World!"
```

## Undeploy

When done testing, you can delete the Lambda function with this command.

```bash
aws lambda delete-function --function-name MyLambda
```
22 changes: 22 additions & 0 deletions Examples/HelloWorldNoTraits/Sources/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//===----------------------------------------------------------------------===//
//
// 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 AWSLambdaRuntime
import NIOCore

let runtime = LambdaRuntime { event, response, context in
try await response.writeAndFinish(ByteBuffer(string: "Hello World!"))
}

try await runtime.run()
20 changes: 19 additions & 1 deletion Sources/AWSLambdaRuntime/FoundationSupport/Lambda+JSON.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,25 @@ extension LambdaCodableAdapter {
)
}
}

@available(LambdaSwift 2.0, *)
extension LambdaResponseStreamWriter {
/// Writes the HTTP status code and headers to the response stream.
///
/// This method serializes the status and headers as JSON and writes them to the stream,
/// followed by eight null bytes as a separator before the response body.
///
/// - Parameters:
/// - response: The status and headers response to write
/// - encoder: The encoder to use for serializing the response, use JSONEncoder by default
/// - Throws: An error if JSON serialization or writing fails
public func writeStatusAndHeaders(
_ response: StreamingLambdaStatusAndHeadersResponse,
encoder: JSONEncoder = JSONEncoder()
) async throws {
encoder.outputFormatting = .withoutEscapingSlashes
try await self.writeStatusAndHeaders(response, encoder: LambdaJSONOutputEncoder(encoder))
}
}
@available(LambdaSwift 2.0, *)
extension LambdaRuntime {
/// Initialize an instance with a `LambdaHandler` defined in the form of a closure **with a non-`Void` return type**.
Expand Down
20 changes: 0 additions & 20 deletions Sources/AWSLambdaRuntime/LambdaResponseStreamWriter+Headers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,23 +86,3 @@ extension LambdaResponseStreamWriter {
try await self.write(buffer, hasCustomHeaders: false)
}
}

@available(LambdaSwift 2.0, *)
extension LambdaResponseStreamWriter {
/// Writes the HTTP status code and headers to the response stream.
///
/// This method serializes the status and headers as JSON and writes them to the stream,
/// followed by eight null bytes as a separator before the response body.
///
/// - Parameters:
/// - response: The status and headers response to write
/// - encoder: The encoder to use for serializing the response, use JSONEncoder by default
/// - Throws: An error if JSON serialization or writing fails
public func writeStatusAndHeaders(
_ response: StreamingLambdaStatusAndHeadersResponse,
encoder: JSONEncoder = JSONEncoder()
) async throws {
encoder.outputFormatting = .withoutEscapingSlashes
try await self.writeStatusAndHeaders(response, encoder: LambdaJSONOutputEncoder(encoder))
}
}
4 changes: 1 addition & 3 deletions Sources/AWSLambdaRuntime/LambdaRuntime.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,12 @@ public final class LambdaRuntime<Handler>: Sendable where Handler: StreamingLamb
}

#if !ServiceLifecycleSupport
@inlinable
internal func run() async throws {
public func run() async throws {
try await _run()
}
#endif

/// Make sure only one run() is called at a time
// @inlinable
internal func _run() async throws {

// we use an atomic global variable to ensure only one LambdaRuntime is running at the time
Expand Down