Commit Graph
188 Commits
Author SHA1 Message Date
Sébastien Stormacq 0a6af5b4e1 prepare 2.0.0-beta.1 (#538)
Change dependencies in `Examples/*` and documentation to `from:
"2.0.0-beta.1"`
2025-07-30 19:08:39 +04:00
Sébastien Stormacq e6ba07fd06 [example] Add example for Swift Service Lifecycle (#522)
Now that task cancellation works, re publishing this PR with a new
example for Swift Service Lifecycle
2025-07-30 06:40:55 +04:00
Sébastien Stormacq 36dadf9c26 [doc] fix header level warnings from CI soundness/doc scripts (#537)
```
note: The majority of content should be under level-3 headers under the "Overview" section
  --> Deployment.md:22:1-22:17
20 |   * [Third-party tools](#third-party-tools)
21 |
22 + ## Prerequisites
   | ╰─suggestion: Change the title to "Overview"
23 |
24 | 1. Your AWS Account

```

and many others.

Action: I lowered all titles one level down.
2025-07-25 20:13:07 +04:00
Sébastien Stormacq 9287d56e60 [core] Implement Lambda streaming with custom HTTP headers (#521)
Fix https://github.com/swift-server/swift-aws-lambda-runtime/issues/520
2025-07-24 15:03:29 +04:00
Sébastien StormacqandTim Condon 412a345bdd [core] Add user-facing API for Streaming Lambda functions that receive JSON events (#532)
Add user-facing API for Streaming Lambda functions that receives JSON
events

### Motivation:

Streaming Lambda functions developed by developers had no choice but to
implement a handler that receives incoming data as a `ByteBuffer`. While
this is useful for low-level development, I assume most developers will
want to receive a JSON event to trigger their streaming Lambda function.

Going efficiently from a `ByteBuffer` to a Swift struct requires some
code implemented in the `JSON+ByteBuffer.swift` file of the librray. We
propose to further help developers by providing them with a new
`handler()` function that directly receives their `Decodable` type.

### Modifications:

This PR adds a public facing API (+ unit test + updated README) allowing
developers to write a handler method accepting any `Decodable` struct as
input.

```swift
import AWSLambdaRuntime
import NIOCore

// Define your input event structure
struct StreamingRequest: Decodable {
    let count: Int
    let message: String
    let delayMs: Int?
}

// Use the new streaming handler with JSON decoding
let runtime = LambdaRuntime { (event: StreamingRequest, responseWriter, context: LambdaContext) in
    context.logger.info("Received request to send \(event.count) messages")
    
    // Stream the messages
    for i in 1...event.count {
        let response = "Message \(i)/\(event.count): \(event.message)\n"
        try await responseWriter.write(ByteBuffer(string: response))
        
        // Optional delay between messages
        if let delay = event.delayMs, delay > 0 {
            try await Task.sleep(for: .milliseconds(delay))
        }
    }
    
    // Finish the stream
    try await responseWriter.finish()
    
    // Optional: Execute background work after response is sent
    context.logger.info("Background work: processing completed")
}

try await runtime.run()
```

This interface provides:
- **Type-safe JSON input**: Automatic decoding of JSON events into Swift
structs
- **Streaming responses**: Full control over when and how to stream data
back to clients
- **Background work support**: Ability to execute code after the
response stream is finished
- **Familiar API**: Uses the same closure-based pattern as regular
Lambda handlers

Because streaming Lambda functions can be invoked either directly
through the API or through Lambda Function URL, this PR adds the
decoding logic to support both types, shielding developers from working
with Function URL requests and base64 encoding.

We understand these choice will have an impact on the raw performance
for event handling. Those advanced users that want to get the maximum
might use the existing `handler(_ event: ByteBuffer, writer:
LambaStreamingWriter)` function to implement their own custom decoding
logic.

This PR provides a balance between ease of use for 80% of the users vs
ultimate performance, without closing the door for the 20% who need it.

### Result:

Lambda function developers can now use arbitrary `Decodable` Swift
struct or Lambda events to trigger their streaming functions. 🎉

---------

Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>
2025-07-23 19:03:25 +04:00
Sébastien Stormacq f1514b13d1 [core] Add support for streaming function to the local server (#531)
The local server used for testing functions locally (`swift run`) now
support streaming lambda functions

Fix https://github.com/swift-server/swift-aws-lambda-runtime/issues/528
2025-07-23 10:08:14 +04:00
Sébastien StormacqandCopilot cb85fdd782 fix [core] trace level shows the first kb of the payload before being decoded (#534)
Add a log statement in the Lambda loop, before calling the user's
handler to show the raw payload before any attempt to decode it.

This was available in Runtime v1 and is now ported to v2.
This fixes
https://github.com/swift-server/swift-aws-lambda-runtime/issues/404

### Motivation:

This is useful when handling custom event and there is a Decoding error.
It allows to see the exact payload received by the handler before any
attempt to decode it.

### Modifications:

Add a log.trace statement with metatadata. Metadata are computed only
when the log level is trace or below.

### Result:

```
2025-07-21T08:58:33+0200 trace LambdaRuntime : Event's first bytes={"name": "me", "age": 50} aws-request-id=769127502334125 [AWSLambdaRuntime] sending invocation event to lambda handler
```

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-22 07:31:00 +02:00
Sébastien Stormacq db7e7897eb [test] Add a test for cancellable (#529)
- Add a test on `LambdaRuntime` for cancellable.
- Move the service life cycle test to its own file
2025-07-21 15:15:55 +02:00
Sébastien Stormacq e786f2f620 fix: [core] Hard code version number in user agent string (#98) (#533)
Add a hard coded version number to the user agent string, for an
eventual identification by the Lambda service

### Motivation:

It's [an
issue](https://github.com/swift-server/swift-aws-lambda-runtime/issues/108)
that was open more than 5 years ago and was never addressed. At the
time, the consensus was to pickup a version number for the Package.swift
file and the maintainer at the time decided to wait for Swift to
implement this.
Five years later, and several major version of Swift later, this is
still not available. I decided to move on and implement a less optimal
solution. This can be replaced in the future if package version ever
becomes part of Package.swift.

### Modifications:

Add a version enum to isolate the versioning in one place. I decided to
keep it simple and not over engineering it with major, minor, patch and
pre-release. At the time, it's a simple string. This is all what we need
for usage in the user agent string.

### Result:

User agent now identifies as `Swift-Lambda/2,0` instead of
`Swift-Lambda/unknown`
2025-07-21 15:15:02 +02:00
Sébastien Stormacq 4a7d95e4a3 fix: remove unused code in v2 (#427) 2025-07-04 16:41:07 +02:00
344d30b401 [core] Only one LambdaRuntime.run() can be called at a time (fix #507) (#508)
This is a proposal to fix issue #507 

**changes**
- `LambdaRuntime.init()` uses a `Mutex<Bool>` to make sure only one
instance is created
- `LambdaRuntime.init()` can now throw an error in case an instance
already exists (I did not use `fatalError()` to make it easier to test)
- All `convenience init()` methods catch possible errors instead of
re-throwing it to a void breaking the user-facing API
- Renamed existing `LambdaRuntimeError` to `LambdaRuntimeClientError`
- Introduced a new type `LambdaRuntimeError` to represent the double
initialization error

---------

Co-authored-by: Fabian Fett <fabianfett@apple.com>
Co-authored-by: Adam Fowler <adamfowler71@gmail.com>
2025-07-04 13:55:58 +00:00
Sébastien Stormacq de38324789 [core] Give user the possibility to pass their logger to the lambda runtime (#523)
Allow user to give their logger to the LambdaRuntime.

### Motivation:

Overloaded versions of `LambdaRuntime.init` don't allow to pass a logger

### Modifications:

Add a `logger` parameter to overloaded versions of `LambdaRuntime.init`

### Result:

It is now possible to write 

```
        let runtime = LambdaRuntime(logger: Logger(label: "MyLogger"), body: handler)
```
2025-07-01 20:44:59 +02:00
Adam Fowler b2811a5e1a Add support for local server graceful shutdown (#519)
- Add ServiceLifecycle version of `LambdaRuntime.run` that wraps
internal `_run` call in `cancelOnGracefulShutdown`
- Add cancellation handlers for shutting down existing connections in
Local lambda
- Added test for lambda graceful shutdown

### Motivation:

Ensure local lambda supports graceful shutdown
2025-06-29 09:05:15 +02:00
Adam Fowler b3fbee6b58 Add SendableMetatype conformance (#518)
Add SendableMetatype conformance to StreamingLambdaHandler

### Motivation:

Swift 6.2 introduced new protocol SendableMetatype for Types that are
Sendable

### Modifications:

Added `_Lambda_SendableMetatype` typealias for SendableMetatype in Swift
6.2

and 

```swift
public protocol StreamingLambdaHandler: _Lambda_SendableMetatype {
```

### Result:

No more compile warnings
2025-06-28 19:09:51 +02:00
Sébastien Stormacq a616996722 [test] add a unit test for the LambdaHTTPServer Pool (#500) 2025-06-28 14:11:28 +02:00
Sébastien Stormacq 7edd4f8108 [core] Fix LocalServer failure to handle large body request (Issue #481) (#504)
Fix https://github.com/swift-server/swift-aws-lambda-runtime/issues/481
2025-06-01 18:31:02 +02:00
Fabian Fett 5924fb6e75 Add inlinable where potentially usefull (#511)
Allow the compiler to specialize more code by applying `@inlinable` to
generic code.
2025-03-21 12:49:08 +01:00
Sébastien Stormacq c3380a0025 [tutorial] fix light image 03-04-01 (#502)
The light mode of image 03-04-01 was not used in the tutorial,
defaulting to dark background all the time.
This is fixed now
2025-03-17 10:56:10 +01:00
Fabian Fett eb634fa9ab Remove unnecessary handler constraints (#499) 2025-03-07 10:31:49 +01:00
Fabian Fett 3ce0a873e3 Attach requestID to logger (#497) 2025-03-07 07:34:05 +01:00
Sébastien Stormacq ae06d59539 cleanup unused code (#498) 2025-03-07 06:48:00 +01:00
Sébastien Stormacq bba711bd18 remove mentions of LambdaRuntImeCore (#495)
Cleanup code from mentions of `LambdaRuntimeCore`
2025-03-06 18:50:32 +01:00
Sébastien Stormacq bf02bcec9a declare user agent string only once (#493)
The user-agent string was repeated at 5+ different places in the source
code.
I defined it as a constant in the `ControlPlaneRequest` struct where
other similar constant have been defined and make sure the rest of the
code only uses that constant.

This should address
https://github.com/swift-server/swift-aws-lambda-runtime/issues/492
2025-03-06 16:52:42 +01:00
Fabian Fett 0a75e0f9cc Use package traits when using Swift 6.1 (#490) 2025-03-06 09:52:23 +01:00
Fabian Fett 03876f6eed [TestServer] Fix 488 and add simple test lambda (#489)
Fixes: #488
2025-03-04 08:20:06 +01:00
61cd5d54da [core] Add cancellation handling for nextInvocation() (#459)
Allow `LambdaChannelHandler.nextInvocation` to be cancelled.

### Motivation:

If we want to use ServiceLifecycle with the lambda runtime the lambda
runtime needs to be cancellable either via a ServiceLifecycle graceful
shutdown or via Task cancellation. To avoid bringing in the
ServiceLifecycle dependency this PR adds cancellation via Task
cancellation handler.

### Modifications:

Add `withTaskCancellationHandler` to nextInvocation which calls close on
cancel.
In `LambdaChannelHandler.channelInactive` resume continuation if state
is `waitingForNextInvocation`
Added `LambdaRuntimeClientTests.testCancellation`

### Result:

You can now cancel the runtime while it is waiting for the next
invocation.

---------

Co-authored-by: Fabian Fett <fabianfett@apple.com>
Co-authored-by: Sébastien Stormacq <sebastien.stormacq@gmail.com>
2025-02-27 17:03:41 +01:00
Fabian Fett 5de00c96c8 Fixes for Local Lambda Server (#486) 2025-02-27 16:08:39 +01:00
Fabian Fett d7780480f2 Enable Swift 6 mode! (#482) 2025-02-20 16:17:23 +01:00
Sébastien Stormacq 7aa746f07e [core] LocalServer - report the error to the continuation (#471)
fix https://github.com/swift-server/swift-aws-lambda-runtime/issues/470
2025-01-22 18:53:57 +01:00
Sébastien Stormacq 02821fe8f7 [test] Update mock server for Swift 6 compliance (#463)
Rewrite to MockServer (used only for performance testing and part of a
separate target) to comply with Swift 6 language mode and concurrency.

The new MockServer now uses `NIOAsyncChannel` and structured
concurrency.

Instead of adding support to
[MAX_REQUEST](https://github.com/swift-server/swift-aws-lambda-runtime/blob/11756b4e00ca75894826b41666bdae506b6eb496/Sources/AWSLambdaRuntimeCore/LambdaConfiguration.swift#L53)
environment variable like v1 did, we implemented support for
`MAX_REQUEST` environment variable in the MockServer itself. It closes
the connection and shutdown the server after servicing MAX_INVOCATIONS
Lambda requests). This allow to add the MAX_REQUEST penalty on the
MockServer and not on the LambdaRuntimeClient.

However, currently, the LambdaRuntimeClient does not shutdown when the
MockServer ends. I created
https://github.com/swift-server/swift-aws-lambda-runtime/issues/465 to
track this issue.

See https://github.com/swift-server/swift-aws-lambda-runtime/issues/377
2025-01-22 12:02:01 +00:00
Sébastien Stormacq ed84609bc4 [core] Update Local Server for Swift 6 compliance (#464)
This PR updates the 4 years old Lambda Local Server for Swift 6
concurrency.

This contributes to
https://github.com/swift-server/swift-aws-lambda-runtime/issues/462
2025-01-22 11:59:10 +00:00
Sébastien Stormacq 752bd41792 move doc images under Resources directory (#460)
Standardize the place where doc resources are located
2025-01-12 17:21:33 +01:00
Sébastien Stormacq 8f7788ffd4 [doc] update deployment guide (#455)
Add a note in the deployment guide to inform Linux user they must have
correct permissions to use docker on their system.

### Motivation:

Build instructions fail on a fresh Ubuntu installation. See this error
report.
https://github.com/swift-server/swift-aws-lambda-runtime/issues/449

### Modifications:

Add a note in the deployment guide that Linux user must add their user
in the `docker` group.

### Result:

Hopefully, Linux users will not experience error at first use of `swift
package archive`
2025-01-06 16:35:06 +01:00
Sébastien Stormacq 2669009d3b Update the tutorial for v2 (#450)
Update the text, code sample, and screenshots for runtime v2

Address
https://github.com/swift-server/swift-aws-lambda-runtime/issues/371
2025-01-04 10:54:37 +01:00
Sébastien Stormacq 430af04828 Update quick-setup.md (#451)
fix typos
2025-01-03 12:28:20 +01:00
Sébastien Stormacq eb9512d053 [doc] update quicksetup guide for v2 (#446)
Update the quick-setup.md docc file to reflect the Runtime v2 API
2025-01-01 21:29:17 +01:00
Sébastien Stormacq f65ec32c4d [doc] add a deployment guide and update the readme (#432)
As discussed with @0xTim 
This PR 
- adds a minimal example of deployment using SAM in the README 
- adds a `Deployment.md` Swift Docc file to cover deployment with the
AWS console, CLI, SAM, and CDK. It mentions and contains a call to
contributions to further examples for third-party tools such as the
Serverless Framework, Terraform, or Pulumi.
2024-12-25 07:43:51 +01:00
Sébastien Stormacq 5ec9a90766 [doc] add 'path: Source' to the quick setup guide (#440)
Fix the `Package.Swift` in the quick setup doc file
This is a follow up and a miss from
https://github.com/swift-server/swift-aws-lambda-runtime/pull/439
2024-12-22 11:16:16 +01:00
Sébastien Stormacq e5404c95cb [examples] Fix path settings in the examples' Package.swift (#439)
All the `Package.swift` files from the examples use `path: "."` instead
of `path: "Sources"` which triggers error messages when users add a
`Tests` directory.
2024-12-22 07:36:32 +01:00
Tobias 25eb6e16de Explicitly only use FoundationEssentials where possible (#436)
We want that the runtime only depends on `FoundationEssentials` where
available (ie. on linux) to ensure small binary size.

### Motivation:

Smaller binary size is good for lambda deployment and cold-start times.
The runtime should only depend on `FoundationEssentials`.

### Modifications:

- replace `import Foundation` with `import FoundationEssentials` if
`FoundationEssentials` is available.
- I also applied the same treatment to tests to ensure that catch error
where tests run on linux and we use API that is only available in
`Foundation` which easily happens when you develop on macOS (where
always full `Foundation` is available).

### Result:

This should allow builds without linking full `Foundation`.
2024-12-20 15:21:33 +01:00
Sébastien Stormacq 23da9bf1ad Ensure LOG_LEVEL is correctly picked up (#435)
Fix issue #434
2024-12-19 18:49:35 +01:00
Sébastien Stormacq 64a4d829f0 Fix CI (#429)
* disable yaml linter

* add semver label check

* re-enable soundness checks (shell, python, and yaml)

* disable checks on docc shell command

* fix errors
2024-11-26 18:32:24 +01:00
Sébastien Stormacq 21e224ea8d Update local server for Swift 6 compliance (#428)
* Update local server to Swift 6

* fix compilation error for local server in release mode

* [CI] fix error for integration plugin test
2024-11-16 10:22:01 +01:00
Sébastien Stormacq 8724c47211 re-enable HTTP server for local testing (#426) 2024-11-14 13:18:01 +01:00
Sébastien StormacqandTim Condon c22f5271a0 add HelloJSON example + README (#424)
* add HelloJSON example + README

* multiple corrections of typos and grammatical errors

Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>
2024-11-13 13:53:19 +01:00
Sébastien Stormacq ca82709a9b Add an example and README for background tasks (#418)
* add an example for background tasks

* swift-format

* add CI

* add background task section in the main readme

* minor formatting changes
2024-11-07 11:33:34 +01:00
Sébastien StormacqandTim Condon 1f80164eb2 add summary + link to API design doc in the readme (#414)
* add summary + link to API design doc in the readme

* typo

Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>

* typo

Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>

---------

Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>
2024-11-07 10:06:30 +01:00
Sébastien Stormacq 7016dfc0fd Set the log level to LOG_LEVEL env variable (#417)
* set the log level to LOG_LEVEL env variable

* remove need for `var logger`

* swift-format

* [ci] update static sdk to 6.0.2
2024-11-07 09:49:11 +01:00
Sébastien Stormacq 4992ba5bd8 change flag name from --allow-network-access to --allow-network-connections as documented by SPM (#407) 2024-10-18 14:51:23 +02:00
aryan-25andFabian Fett 83bd667cce v2 API Proposal Document (#339)
Co-authored-by: Fabian Fett <fabianfett@apple.com>
2024-10-09 10:05:02 +02:00