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
1 change: 1 addition & 0 deletions .licenseignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,4 @@ Sources/AWSLambdaPluginHelper/GeneratedClients/**
**/*.txt
*.toml
.kiro/*
aws-doc/*
1 change: 1 addition & 0 deletions .swiftformatignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Sources/AWSLambdaPluginHelper/lambda-init/Template.swift
Sources/AWSLambdaPluginHelper/GeneratedClients
aws-doc/
25 changes: 14 additions & 11 deletions Examples/Streaming+Codable/Sources/LambdaStreaming+Codable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ public protocol StreamingLambdaHandlerWithEvent: _Lambda_SendableMetatype {
/// - If ``LambdaResponseStreamWriter/finish()`` has already been called before the error is thrown, the
/// error will be logged.
nonisolated(nonsending)
mutating func handle(
_ event: Event,
responseWriter: some LambdaResponseStreamWriter,
context: LambdaContext
) async throws
mutating func handle(
_ event: Event,
responseWriter: some LambdaResponseStreamWriter,
context: LambdaContext
) async throws
}

/// Adapts a ``StreamingLambdaHandlerWithEvent`` to work as a ``StreamingLambdaHandler``
Expand Down Expand Up @@ -131,11 +131,12 @@ public struct StreamingFromEventClosureHandler<Event: Decodable>: StreamingLambd
/// - responseWriter: The response writer for streaming output.
/// - context: The Lambda context.
nonisolated(nonsending)
public func handle(
_ event: Event,
responseWriter: some LambdaResponseStreamWriter,
context: LambdaContext
) async throws {
public func handle(
_ event: Event,
responseWriter: some LambdaResponseStreamWriter,
context: LambdaContext
) async throws
{
try await self.body(event, responseWriter, context)
}
}
Expand All @@ -162,7 +163,9 @@ extension LambdaRuntime {
public convenience init<Event: Decodable>(
decoder: JSONDecoder = JSONDecoder(),
logger: Logger = Logger.current,
streamingBody: nonisolated(nonsending) @Sendable @escaping (Event, LambdaResponseStreamWriter, LambdaContext) async throws -> Void
streamingBody:
nonisolated(nonsending) @Sendable @escaping (Event, LambdaResponseStreamWriter, LambdaContext) async throws
-> Void
)
where
Handler == StreamingLambdaCodableAdapter<
Expand Down
1 change: 1 addition & 0 deletions aws-doc/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This is the source for the AWS documentation pages at https://docs.aws.amazon.com/lambda/latest/dg/lambda-programming-languages.html
28 changes: 28 additions & 0 deletions aws-doc/lambda-swift.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Building Lambda functions with Swift

Because Swift compiles to native code, you don't need a dedicated runtime to run Swift code on Lambda. Instead, use the Swift runtime client to build your project locally, and then deploy it to Lambda using an OS-only runtime. When you use an OS-only runtime, Lambda automatically keeps the operating system up to date with the latest patches.

## Tools and libraries for Swift

- **AWS SDK for Swift**: The [AWS SDK for Swift](https://github.com/awslabs/aws-sdk-swift) provides Swift APIs to interact with Amazon Web Services infrastructure services.
- **Swift runtime client for Lambda**: The [Swift runtime client](https://github.com/awslabs/swift-aws-lambda-runtime) makes it easy to run Lambda functions written in Swift.
- **Swift AWS Lambda Events**: This [library](https://github.com/awslabs/swift-aws-lambda-events) provides type definitions for common event source integrations.
- **Swift OpenAPI Lambda**: This [library](https://github.com/awslabs/swift-openapi-lambda) provides an AWS Lambda transport for Swift OpenAPI, allowing you to expose OpenAPI-based services as Lambda functions.

## Sample Lambda applications for Swift

- [Simple Lambda function](https://github.com/awslabs/swift-aws-lambda-runtime/blob/main/Examples/HelloJSON): A Swift function that shows how to process basic JSON events.
- [Lambda function with background tasks](https://github.com/awslabs/swift-aws-lambda-runtime/tree/main/Examples/BackgroundTasks): A Swift function that shows how to perform background processing after sending a response.
- [Lambda function with streaming responses](https://github.com/awslabs/swift-aws-lambda-runtime/tree/main/Examples/Streaming%2BAPIGateway): A Swift function that streams responses back to the client.
- [Lambda HTTP events](https://github.com/awslabs/swift-aws-lambda-runtime/tree/main/Examples/APIGatewayV2): A Swift function that handles API Gateway HTTP events.
- [Lambda function with Service Lifecycle](https://github.com/awslabs/swift-aws-lambda-runtime/tree/main/Examples/ServiceLifecycle%2BPostgres): A Swift project that initializes shared resources using Swift Service Lifecycle before creating the Lambda function.

## Topics

- [Define Lambda function handlers in Swift](swift-handler.md)
- [Using the Lambda context object to retrieve Swift function information](swift-context.md)
- [Processing HTTP events with Swift](swift-http-events.md)
- [Deploy Swift Lambda functions with .zip file archives](swift-package.md)
- [Working with layers for Swift Lambda functions](swift-layers.md)
- [Log and monitor Swift Lambda functions](swift-logging.md)

71 changes: 71 additions & 0 deletions aws-doc/swift-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Using the Lambda context object to retrieve Swift function information

When Lambda runs your function, it passes a context object to the handler. This object provides properties with information about the invocation, function, and execution environment.

## Context properties

- **requestID**: The AWS request ID generated by the Lambda service.
- **traceID**: The AWS X-Ray tracing header.
- **tenantID**: The tenant ID, if present. This field is `nil` unless a tenant ID is provided by the Lambda service.
- **invokedFunctionARN**: The Amazon Resource Name (ARN) of the Lambda function, version, or alias that's specified in the invocation.
- **deadline**: The timestamp that the function times out, as a `LambdaClock.Instant`.
- **cognitoIdentity**: For invocations from the AWS Mobile SDK, data about the Amazon Cognito identity provider. This field is `nil` unless the invocation request to the Lambda APIs was made using AWS credentials issued by Amazon Cognito identity pools.
- **clientContext**: For invocations from the AWS Mobile SDK, data about the client application and device. This field is `nil` unless the function is invoked using an AWS Mobile SDK.
- **logger**: A `Logger` instance to produce log output. The `LogLevel` can be configured using the `LOG_LEVEL` environment variable.
- **logGroupName**: The name of the Amazon CloudWatch Logs group for the function.
- **logStreamName**: The name of the Amazon CloudWatch Logs stream for the current invocation of the function.

## Accessing invoke context information

Lambda functions have access to metadata about their environment and the invocation request. The `LambdaContext` object is passed directly to your handler as a parameter:

```swift
import AWSLambdaRuntime
import Foundation

let runtime = LambdaRuntime {
(event: Request, context: LambdaContext) in

let invokedFunctionARN = context.invokedFunctionARN
return Response(message: "Hello, this is function \(invokedFunctionARN)!")
}

try await runtime.run()
```

## Getting the remaining time

The context object provides a method to retrieve how much time remains before the function times out. You can use this to ensure your function completes critical operations before the timeout:

```swift
let runtime = LambdaRuntime {
(event: Request, context: LambdaContext) in

let remainingTime = context.getRemainingTime()
context.logger.info("Time remaining: \(remainingTime)")

// Perform time-sensitive operations
return Response(message: "Completed")
}

try await runtime.run()
```

## Using the context logger

The `LambdaContext` includes a pre-configured `Logger` instance that automatically includes the AWS request ID and trace ID in every log message. Use this logger instead of `print()` statements:

```swift
let runtime = LambdaRuntime {
(event: Request, context: LambdaContext) in

context.logger.info("Processing request \(context.requestID)")
context.logger.debug("Event received: \(event)")

return Response(message: "Done")
}

try await runtime.run()
```

For more information about logging, see [Log and monitor Swift Lambda functions](swift-logging.md).
Loading