209 Commits
Author SHA1 Message Date
b1553d2766 Accept multiple POST /invoke requests to allow parallel testing (#585)
Closing
https://github.com/swift-server/swift-aws-lambda-runtime/issues/584

The LocalServer now queues concurrent `POST /invoke` requests from
testing client applications and ensures that the requests are delivered
to the Lambda Runtime one by one, just like the AWS Lambda Runtime
environment does.

The `Pool` has now two modes : pure FIFO (one element get exactly one
`next()`) and one mode where multiple elements can get pushed and
multiple `next(for requestId:String)` can be called concurrently.

The two modes are needed because invocations are 1:1 (one `POST /invoke`
is always by one matching `GET /next`) but responses are n:n (a response
can have multiple chunks and concurrent invocations can trigger multiple
`next(for requestId: String)`

I made a couple of additional changes while working on this PR 

- I moved the `Pool` code in a separate file for improved readability 

- I removed an instance of `DispatchTime` that was hiding in the code,
unnoticed until today

- I removed the `async` requirement on `Pool.push(_)` function. This was
not required (thank you @t089 for having reported this)

- I removed the `fatalError()` that was in the `Pool` implementation.
The pool now throws an error when `next()` is invoked concurrently,
making it easier to test.

- I added extensive unit tests to validate the Pool behavior 

- I added a test to verify that a rapid succession of client invocations
are correctly queued and return no error

- I moved a `continuation(resume:)` outside of a lock. Generally
speaking, it's a bad idea to resume continuation while owning a lock. I
suspect this is causing a error during test execution when we spawn and
tear down mutliple `Task` very quickly. In some rare occasions, the test
was failing with an invalid assertion in NIO :
`NIOCore/NIOAsyncWriter.swift:177: Fatal error: Deinited NIOAsyncWriter
without calling finish()`

---------

Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-22 07:52:31 +02:00
Sébastien StormacqandSebastien Stormacq e58d89148c Replace standard documents and processes with AWS ones (#574)
- Adjust notice, security reporting, code of conduct, contribution
process to the standard AWS documents
- Adjust GitHub issue templates to AWS standard ones.
- Adjust the license header in all source files

---------

Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
2025-10-21 23:27:30 +02:00
Sébastien StormacqandSebastien Stormacq 8168a5c22e fix ci : check libFoundation on HelloWorld example (#593)
Fix errors in the CI
The script that checks the presence of `libFoundation` in the binary
started to fail.
I can't think about a recent change that would cause this.

This PR change the test script to use the `HelloWorld` example instead
of `APIGAtewayV2`

Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
2025-10-20 20:01:46 +02:00
Sébastien StormacqandSebastien Stormacq dee635267b change references from /swift-server to /awslabs (#591)
Change Examples, README, and doc to refer to https://github.org/awslabs
instead of https://github.org/swift-server

---------

Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
2025-10-17 16:46:58 +02:00
Sébastien StormacqandSebastien Stormacq 8116ba3023 Allow multiple invocations of streaming Lambda functions with the local test server (#590)
The Local HTTP Server (used when testing) used to block after one
invocation of a streaming lambda function. Now you can invoke multiple
times your streaming function without having to restart the local HTTP
server.

### Motivation:

Bug https://github.com/swift-server/swift-aws-lambda-runtime/issues/588

### Modifications:

The flow to respond to streaming and non-streaming requests are
different. In the streaming request flow, we forgot to send an 202
accept response to the lambda runtime client after it posted the end
chunck of the response (in other words, `POST /response` never received
an HTTP 202 response.) This caused the Lambda Runtime to hang and never
issue the next `GET /next `request.

### Result:

You can now send multiple invocations to your streaming lambda.

---------

Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
2025-10-17 10:37:38 +02:00
Natan Rolnik e3b74f3a0e Add initializer with LambdaHandler directly with Decodable event and Void output (#589)
_Add convenience initializer for `LambdaRuntime` to accept
`LambdaHandler` instances with `Void` output_

### Motivation:

Following PR #581, which added convenience initializers for
`LambdaRuntime` to accept `LambdaHandler` instances with `Encodable`
outputs, there was still a gap for handlers that return `Void`. This is
useful, for example, for AWS event sources like SQS, where the
`AWSLambdaEvents` package provides `SQSEvent` but there's no
corresponding output type - handlers simply process messages and return
`Void`.

Without this initializer, developers had to manually wrap their handlers
with `LambdaCodableAdapter` and `LambdaHandlerAdapter`, which was
verbose and inconsistent with the new API (similar to what is described
in #581)

### Modifications:

1. Added a new `init(decoder:handler:)` convenience initializer to
`LambdaCodableAdapter` in `Lambda+JSON.swift` that accepts a
`JSONDecoder` for handlers with `Void` output.

2. Added a new convenience initializer to `LambdaRuntime` that accepts a
`LambdaHandler` instance with `Void` output directly, handling the
wrapping internally.

3. Updated documentation comments to distinguish between handlers with
`Void` and `Encodable` outputs.

### Result:

Developers can now initialize `LambdaRuntime` with handlers that return
`Void` using a clean, direct API. This is especially useful for event
sources like SQS:

```swift
import AWSLambdaEvents

struct MySQSHandler: LambdaHandler {
    func handle(_ event: SQSEvent, context: LambdaContext) async throws {
        // Process SQS messages
    }
}

let runtime = LambdaRuntime(lambdaHandler: MySQSHandler())
```

This provides API completeness, matching the convenience initializers
for handlers with `Encodable` outputs, and delivers better ergonomics
for common serverless patterns.
2025-10-16 21:34:49 +02:00
Ben Rosen 9487a09e3a Lambda Handler errors now reports the root error in field errorType rather than "FunctionError" constant (#587)
### Motivation:

Fix for Issue
[#580](https://github.com/swift-server/swift-aws-lambda-runtime/issues/580),
by making it so that the `errorType` in failed requests will be the type
of the error entity, rather than a hardcoded string of `FunctionError`.
This allows orchestration within step functions that perform retry/catch
logic based on different error output types.

### Modifications:

At a high level, the issue is that swift-aws-lambda-runtime, when an
error is thrown, outputs the errorType as hardcoded to FunctionError.
You can see that
[here](https://github.com/swift-server/swift-aws-lambda-runtime/blob/main/Sources/AWSLambdaRuntime/LambdaRuntimeClient%2BChannelHandler.swift#L337):

```
let errorResponse = ErrorResponse(errorType: Consts.functionError, errorMessage: "\(error)")
```

This PR changes this for all cases to output the type of the error,
rather than the hardcoded string:
```
let errorResponse = ErrorResponse(errorType: "\(type(of: error))", errorMessage: "\(error)")
```
Now, I will show 2 examples with this solution:
```
let runtime = LambdaRuntime {
    (event: Input, context: LambdaContext) in

    enum MyTestErrorType: Error {
        case testError
    }
    
    throw MyTestErrorType.testError
}

// outputs {"errorType":"MyTestErrorType","errorMessage":"testError"}
```
```
let dynamoDB: DynamoDB = DynamoDB(client: .init())

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

    let _ = try await dynamoDB.putItem(DynamoDB.PutItemInput(item: [:], tableName: ""))
    
    return Output()
}

// outputs {"errorType":"AWSClientError","errorMessage":"ValidationError: Length of PutItemInput.tableName (0) is less than minimum allowed value 1."}
```
2025-10-15 00:30:40 +02:00
Natan Rolnik 461c18af6f Add LambdaRuntime initializer with LambdaHandler directly with Codable support (#581)
_Add convenience initializer for `LambdaRuntime` to accept
`LambdaHandler` instances directly_

### Motivation:

When using the Swift AWS Lambda Runtime with custom handler types that
conform to `LambdaHandler`, developers previously had two options to
initialize `LambdaRuntime`:

1. Manually wrap their handler with `LambdaCodableAdapter` and
`LambdaHandlerAdapter`:
   ```swift
   let lambdaHandler = MyHandler()
   let handler = LambdaCodableAdapter(
       encoder: JSONEncoder(),
       decoder: JSONDecoder(),
       handler: LambdaHandlerAdapter(handler: lambdaHandler)
   )
   let runtime = LambdaRuntime(handler: handler)
   ```

2. Use a closure-based initializer that indirectly calls the handler:
   ```swift
   let lambdaHandler = MyHandler()
   let runtime = LambdaRuntime { event, context in
       try await lambdaHandler.handle(event, context: context)
   }
   ```

Both approaches are verbose and don't provide a clean, ergonomic API for
the common case of initializing `LambdaRuntime` with a custom
`LambdaHandler` instance. The closure approach also creates an
unnecessary indirection layer, wrapping the handler in a
`ClosureHandler` before adapting it, or using `LambdaCodableAdapter`.

### Modifications:

Added a new convenience initializer to `LambdaRuntime` in
`Lambda+JSON.swift` that accepts a `LambdaHandler` instance directly:

```swift
public convenience init<Event: Decodable, Output, LHandler: LambdaHandler>(
    decoder: JSONDecoder = JSONDecoder(),
    encoder: JSONEncoder = JSONEncoder(),
    logger: Logger = Logger(label: "LambdaRuntime"),
    lambdaHandler: sending LHandler
)
where
    Handler == LambdaCodableAdapter<
        LambdaHandlerAdapter<Event, Output, LHandler>,
        Event,
        Output,
        LambdaJSONEventDecoder,
        LambdaJSONOutputEncoder<Output>
    >,
    LHandler.Event == Event,
    LHandler.Output == Output
```

This initializer handles the wrapping of the `LambdaHandler` with the
necessary adapters internally, matching the pattern already established
for closure-based handlers.

### Result:

Developers can now initialize `LambdaRuntime` with a `LambdaHandler`
instance using a clean, direct API:

```swift
let lambdaHandler = MyHandler()
let runtime = LambdaRuntime(lambdaHandler: lambdaHandler)
```

This provides:
- **Better ergonomics**: More intuitive and less verbose API
- **Consistency**: Matches the pattern of accepting handlers directly,
similar to how `StreamingLambdaHandler` can be used
- **No extra indirection**: Avoids wrapping the handler in an
unnecessary `ClosureHandler` or `LambdaCodableAdapter`
- **Type safety**: Maintains full type inference for `Event` and
`Output` types from the handler
2025-10-09 19:20:19 +02:00
Sébastien StormacqandSebastien Stormacq 74e4efdbac Apply recommendation for security and reliability (#573)
Apply recommendations in code and documentation

- [CI] restrict permissions to read-all instead of the default write-all
- All examples README.md : add a note about Lambda functions
configuration with improved security and scalability changes for
production environment
- Swift docc documentation: add a note about Lambda functions
configuration with improved security and scalability changes for
production environment

---------

Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
2025-09-27 12:39:16 +02:00
Sébastien StormacqandSebastien Stormacq 02d483074d [Example] Use smaller containers in all examples (#571)
All the examples using SAM have a default Lambda runtime environment
memory size of 512Mb.

Lambda functions run in a microVM defined by its memory size. The memory
size influences the CPU power.
(see
https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html)

Increasing memory size increases runtime performance but also increase
costs.

As most of our examples are very simple and small functions, 512Mb
memory is not required. This PR reduces Lambda runtime execution
environment to 128Mb to reduce AWS costs.

Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
2025-09-26 10:10:12 +02:00
Sébastien Stormacq a1ab8df708 Update toolchain and doc for 6.2 (#564)
In preparation for the 2.0.0 GA release,

- Update `.swift-version`, `Package.swift` and all examples'
`package.swift` to Swift 6.2
- Update all references to `2.0.0-beta.3` to `2.0.0`. This includes the
doc and readme, but also the dependencies in the examples
`Package.swift`. This will temporary break the build of the examples,
until we tag v2.0.0. Note the CI will not be affected as its consumes
the local version of the library
- [CI] Use Swift-6.2-noble for all testing tasks
- Reinstate the script to generate the contributors list and update the
list
2025-09-23 21:12:33 +02:00
Sébastien Stormacq 1843cdcb3c [fix] The library must compile when no traits are enabled (#563)
Make required changed to ensure the library compiles when no traits are
enabled (fix:
https://github.com/swift-server/swift-aws-lambda-runtime/issues/562)

Add an example project that serves as test in the CI

### Motivation:

Recent changes introduced compilation errors when no traits are enabled.

### Modifications:

- `LambdaResponseStreamWriter.writeStatusAndHeaders()` moved to the
`FoundationSupport` directory where all classes and struct depending on
`Encodable` and `Decodable` are located, protected by `#if
FoundationJSONSupport`
- `LambdaRuntime.run()` method when ServiceLifeCycle is disabled in now
public (and therefore can not be `@inlinable` anymore)
- Add an example that disables all traits.
- Add this example to the CI 

### Result:

The Library now compiles when no default traits are enabled.
This is flagged `semver/major` because we change the public API
`LambdaRuntime.run()`
2025-09-16 11:05:45 +02:00
Sébastien Stormacq d8ee71fc09 add support for LOCAL_LAMBDA_PORT / HOST(#557)
Allows users to define on which port the Local server listens to, using
the `LOCAL_LAMBDA_PORT` environment variable.

While being at it, I also added `LOCAL_LAMBDA_HOST` if the user wants to
bind on a specific IP address.

I renamed `LOCAL_LAMBDA_SERVER_INVOCATION_ENDPOINT` to
`LOCAL_LAMBDA_INVOCATION_ENDPOINT` for consistency.

### Motivation:

Addresses
https://github.com/swift-server/swift-aws-lambda-runtime/issues/556

### Modifications:

- When run outside of the Lambda execution environment, check for the
value of `LOCAL_LAMBDA_PORT` and passes it down to the Lambda HTTP Local
Server and runtime client.

- Add a unit test 

### Result:

```
LAMBDA_USE_LOCAL_DEPS=../.. LOCAL_LAMBDA_PORT=8888 swift run                  

2025-09-01T21:55:22+0200 info LambdaRuntime: host="127.0.0.1" port=8888 [AWSLambdaRuntime] Server started and listening
```
2025-09-03 18:22:57 +02:00
Sébastien Stormacq d42ae6975e Refactor the Swift Settings in Package.swift (#558)
- Use the new Swift 6 `@available` macro to remove requirement on
`.platform` in Package.swift.
- DRY: define the swift settings once for all in `Package.swift`

### Motivation:

- Remove the requirement to build on macOS 15 in `Package.swift`. This
allows library builders and end users to be more flexible on their
dependency requirements.
- The code is optionally compiled on macOS 15 and Linux, but SPM don't
enforce it anymore.
- Avoid repeating ourself. Be sure the same settings are applied on all
targets.

### Modifications:

- Create a `var swiftSetting: [SwiftSettings]` and reuse it for all
targets.
- Use `AvailabilityMacro=LambdaSwift 2.0:macOS 15.0`
- Add this on top of the majority struct / classes
```swift
#if swift(>=6.1)
@available(LambdaSwift 2.0, *)
#endif
```
### Result:

When using Swift 6.1, there is no more SPM dependency on macOS 15
2025-09-03 18:00:24 +02:00
Sébastien Stormacq 53ec1cbf3a Split LambdaRuntimeClient in two files for easier reading (#554)
Split the long `LambdaRuntimeClient.swift` file in two parts: the
`LambdaRuntimeClient` and the `LambdaChannelHandler` for easier reading
and maintenance
2025-09-01 13:07:40 +02:00
Sébastien Stormacq efc4cd16bf Propagate Connection Closed Information up to top-level (fix #465) (#545)
This PR implements a mechanism to propagate connection loss information
from the Lambda runtime client to the runtime loop, enabling termination
without backtrace when the connection to the Lambda control plane (or a
Mock Server) is lost.

The changes are:

- When the connection is lost,
`ChannelHandlerDelegate.channelInnactive()` now correctly calls
`resume(throwing:)` on the ending continuation, for all states
(`.waitingForNextInvocation ` and `.sentResponse`). This eliminates the
hangs on connection lost..

- I added top-level error handling on `LambdaRuntime._run()` 

- Add a unit test to check that either
`LambdaruntimeError.connectionToControlPlaneLost`, a `ChannelError`, or
an `IOError` is thrown when the server closes the connection
2025-09-01 12:21:13 +02:00
Sébastien Stormacq 323b3f2ac2 fix: Fix deadline header with correct instant value (#551) (#552)
Instant's value now correctly prints as an EPOCH number

### Motivation:

A regression was introduced by
https://github.com/swift-server/swift-aws-lambda-runtime/pull/540. The
HTTP headers returned by `LocalServer` contained an invalid
representation of the Lamba Deadline.

See https://github.com/swift-server/swift-aws-lambda-runtime/issues/551

### Modifications:

- Add `CustomStringConvertible` to `LambdaClock.Instant` to just print
the `Int64` value
- add a unit test 

### Result:

The runtime works correctly with the new `LambdaClock`
2025-08-24 13:37:24 +02:00
Sébastien Stormacq 262c3b539a Revert streaming codable handler and provide it as an example, not an API (#549)
Revert streaming codable handler change and propose it as an example
instead of an handler API.

**Motivation:**
I made a mistake when submitting this PR 
https://github.com/swift-server/swift-aws-lambda-runtime/pull/532

It provides a Streaming+Codable handler that conveniently allows
developers to write handlers with `Codable` events for streaming
functions.

This is a mistake for three reasons:

- This is the only handler that assumes a Lamba Event structure as
input. I added a minimal `FunctionUrlRequest` and `FunctionURLResponse`
to avoid importing the AWS Lambda Events library. It is the first
handler to be event-specific. I don't think the runtime should introduce
event specific code.

- The handler only works when Lambda functions are exposed through
Function URLs. Streaming functions can also be invoke by API or CLI.

- The handler hides `FunctionURLRequest` details (HTTP headers, query
parameters, etc.) from developers

Developers were unaware they were trading flexibility for convenience

The lack of clear documentation about these limitations led to incorrect
usage patterns and frustrated developers who needed full request control
or were using other invocation methods.

**Modifications:**
- Removed the Streaming+Codable API from the library
- Moved the Streaming+Codable code to an example
- Added prominent warning section in the example README explaining the
limitations
- Clarified when to use Streaming+Codable vs ByteBuffer approaches
- Added decision rule framework to help developers choose the right
approach

**Result:**
The only API provided by the library to use Streaming Lambda functions
is exposing the raw `ByteBuffer` as input, there is no more `Codable`
handler for Streaming functions available in the API. I kept the
`Streaming+Codable` code an example.

After this change, developers have clear guidance on when to use each
streaming approach:

- Use streaming codable for Function URL + JSON payload + no request
details needed
- Use ByteBuffer StreamingLambdaHandler for full control, other
invocation methods, or request metadata access

This prevents misuse of the API and sets proper expectations about the
handler's capabilities and limitations, leading to better developer
experience and fewer integration issues.
2025-08-07 10:51:21 +02:00
Sébastien Stormacq 447c1e4db1 Remove dependency on DispatchWallTime (fix #384) (#540)
Fix
[#384](https://github.com/swift-server/swift-aws-lambda-runtime/issues/384)

Note: this PR introduces an API change that will break Lambda functions
using `LambdaContext`, we should integrate this change during the beta
otherwise it will require a major version bump.

### Motivation:

`DispatchWallTime` has no public API to extract the time in
milliseconds, making it a dead end.
Previous implementation used the internal representation of time inside
`DispatchWallTime` to extract the value, creating a risk if its
implementation will change in the future.
Moreover, the use of `DispatchWallTime` obliges users to import the
`Dispatch` library or `Foundation`.

Old Code:
```
extension DispatchWallTime {
    @usableFromInline
    init(millisSinceEpoch: Int64) {
        let nanoSinceEpoch = UInt64(millisSinceEpoch) * 1_000_000
        let seconds = UInt64(nanoSinceEpoch / 1_000_000_000)
        let nanoseconds = nanoSinceEpoch - (seconds * 1_000_000_000)
        self.init(timespec: timespec(tv_sec: Int(seconds), tv_nsec: Int(nanoseconds)))
    }

    var millisSinceEpoch: Int64 {
        Int64(bitPattern: self.rawValue) / -1_000_000
    }
}
```

Issue
[#384](https://github.com/swift-server/swift-aws-lambda-runtime/issues/384)
has a long discussion about possible replacements, including creating a
brand new `UTCClock`, which I think is an overkill for this project.

Instead, I propose this simple implementation, based on two assumptions:

- AWS always sends the time in milliseconds since Unix Epoch (1st Jan
1970) ([Lambda Runtime API
documentation](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next))
- AWS always uses UTC time (not only for Lambda, this is a general rule
for all AWS APIs) ([TZ=UTC on
Lambda](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html))

Therefore, this library just needs to store and make math on
milliseconds since epoch, without having to care about timezone.

I had two possibilities to implement the storage and the math on
milliseconds since Unix Epoch: either I could use an `UInt64` (as does
[the Rust
implementation](https://github.com/awslabs/aws-lambda-rust-runtime/blob/aff8d883c62997ef2615714dce9f7ddfd557147d/lambda-runtime/src/types.rs#L70))
or I could use a standard Swift type, such as `Duration`.

`Duration` is a good candidate for this because 1/ the time we receive
from the Lambda Service API is indeed a duration between 1/1/1970 and
the execution deadline for the Lambda function, expressed in
milliseconds, 2/ it gives a strong type that can be verified by the
compiler, and 3/ it is possible to do basic arithmetic operations and
compare two values.

As an additional benefit, it allows library users to not import
`Dispatch` or `Foundation`

### Modifications:

I made two changes:

1. I extend the `Duration` type to provide us with simple unix epoch
time manipulation functions and values.

```swift
extension Duration {
    /// Returns the time in milliseconds since the Unix epoch.
    @usableFromInline
    static var millisSinceEpoch: Duration {
        var ts = timespec()
        clock_gettime(CLOCK_REALTIME, &ts)
        return .milliseconds(Int64(ts.tv_sec) * 1000 + Int64(ts.tv_nsec) / 1_000_000)
    }

    /// Returns a Duration between Unix epoch and the distant future
    @usableFromInline
    static var distantFuture: Duration {
        // Use a very large value to represent the distant future
        millisSinceEpoch + Duration.seconds(.greatestFiniteMagnitude)
    }

    /// Returns the Duration in milliseconds
    @usableFromInline
    func milliseconds() -> Int64 {
        Int64(self / .milliseconds(1))
    }

    /// Create a Duration from milliseconds since Unix Epoch
    @usableFromInline
    init(millisSinceEpoch: Int64) {
        self = .milliseconds(millisSinceEpoch)
    }
}
```

3. I replaced all references to `DispatchWallTime` by `Duration` 

### Result:

No more `DispatchWallTime`
No dependencies on Foundation, as I use `clock_gettime()` to get the
epoch from the system clock.
2025-08-05 09:12:11 +02:00
Sébastien Stormacq 11bea7b2ee Performance Test the invocation loop (fix #377) (#542)
re-implement MAX_INVOCATIONS and fix shell script 
Fix https://github.com/swift-server/swift-aws-lambda-runtime/issues/377

### Motivation:

In v1, there was a script measuring the performance of the invocation
loop.
Re-instate this script to allow users and developers to measure the
performance impact of their changes.

### Modifications:

I re-implemented MAX_INVOCATIONS, to avoid the client looping against
the Mock Server. But this time, MAX_INVOCATIONS is handled on the
server, not on the client.

I slightly modified the script to work with v2 and the new MockServer.

### Result:

The script works.

This PR has a dependency on
https://github.com/swift-server/swift-aws-lambda-runtime/issues/465
2025-08-05 08:39:20 +02:00
Sébastien StormacqandKonrad `ktoso` Malawski bae9f27ccb Use a struct for ClientContext (fix #169) (#539)
Do not use a String for Lambdacontext.ClientContext, use a struct instead.
Fix for https://github.com/swift-server/swift-aws-lambda-runtime/issues/169

Note: this PR introduces an API change that will break function using
`LambdaContext`, we should integrate this change during the beta
otherwise it will require a major version bump.

### Motivation:

Let the compiler detect type errors for us

### Modifications:

- Create a struct for ClientContext and it's embedded ClientApplication
- add three unit test to validate the struct 

### Result:

No more String?

---------

Co-authored-by: Konrad `ktoso` Malawski <konrad.malawski@project13.pl>
2025-08-04 08:24:46 +02:00
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