Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
2020d6b
return HTTP accepted on error
sebsto Aug 1, 2025
6e01c6e
force exit() when we loose connection to Lambda service
sebsto Aug 1, 2025
166cd46
propagate the connection closed info through a Future
sebsto Aug 3, 2025
a69ed54
fix typos
sebsto Aug 3, 2025
04d9fc7
fix unit tests
sebsto Aug 3, 2025
092da82
Merge branch 'main' into sebsto/shutdown_on_lost_connection
sebsto Aug 3, 2025
5efb706
Merge branch 'main' into sebsto/shutdown_on_lost_connection
sebsto Aug 4, 2025
1d98a7c
Merge branch 'main' into sebsto/shutdown_on_lost_connection
sebsto Aug 5, 2025
4b23d4f
Merge branch 'main' into sebsto/shutdown_on_lost_connection
sebsto Aug 5, 2025
5822e0a
Merge branch 'main' into sebsto/shutdown_on_lost_connection
sebsto Aug 5, 2025
025a0e5
simplify by checking connection state in the `nextInvocation()` call
sebsto Aug 7, 2025
ce8b567
introducing a new connection state "lostConnection"
sebsto Aug 7, 2025
be4cb20
add state change
sebsto Aug 7, 2025
b37ea0e
fix lost continuation
sebsto Aug 7, 2025
cd00948
fix compilation error
sebsto Aug 7, 2025
008c542
DRY: move the error handling to the _run() function
sebsto Aug 7, 2025
9dcb4b3
fix a case where continuation was resumed twice
sebsto Aug 7, 2025
f2d94a2
fix unit test
sebsto Aug 7, 2025
852391e
swift format
sebsto Aug 7, 2025
b13bf5c
remove comment on max payload size
sebsto Aug 7, 2025
1aa07b1
Merge branch 'main' into sebsto/shutdown_on_lost_connection
sebsto Aug 24, 2025
9c283c3
further simplify by removing the new state `lostConnection`
sebsto Aug 24, 2025
a620a2f
remove unecessary code
sebsto Aug 24, 2025
f671228
restrict access to channel handler state variable
sebsto Aug 25, 2025
b0234f5
add a unit test to verify that an error is thrown when the connection…
sebsto Aug 27, 2025
482e09e
swift-format
sebsto Aug 27, 2025
156e6c7
make sure connectionToControlPlaneLost error is triggered by the test
sebsto Aug 27, 2025
a0b1d57
give more time to the server to close the connection
sebsto Aug 27, 2025
54459e0
add catch for IOError
sebsto Aug 27, 2025
89cd259
swift-format
sebsto Aug 27, 2025
6b07955
remove compilation warning
sebsto Aug 27, 2025
86ccbf4
improve test with a timeout
sebsto Aug 28, 2025
cbf9c5e
remove debugging print statements
sebsto Aug 28, 2025
9a70915
add logger trace
sebsto Aug 28, 2025
c54cb2f
fulfill continuation in channelInactive() rather than channel.closeF…
sebsto Aug 29, 2025
ccb3d14
remove private(set) on LambdaChannelHandler.state
sebsto Aug 29, 2025
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 Sources/AWSLambdaRuntime/Lambda+LocalServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ internal struct LambdaHTTPServer {
await self.responsePool.push(
LocalServerResponse(
id: requestId,
status: .ok,
status: .accepted,
// the local server has no mecanism to collect headers set by the lambda function
headers: HTTPHeaders(),
body: body,
Expand Down
16 changes: 16 additions & 0 deletions Sources/AWSLambdaRuntime/Lambda.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@ public enum Lambda {
var logger = logger
do {
while !Task.isCancelled {

if let runtimeClient = runtimeClient as? LambdaRuntimeClient,
let futureConnectionClosed = await runtimeClient.futureConnectionClosed
{
// Wait for the futureConnectionClosed to complete,
// which will happen when the Lambda HTTP Server (or MockServer) closes the connection
// This allows us to exit the run loop gracefully.
// The futureConnectionClosed is always an error, let it throw to terminate the Lambda run loop.
let _ = try await futureConnectionClosed.get()
}

logger.trace("Waiting for next invocation")
let (invocation, writer) = try await runtimeClient.nextInvocation()
logger[metadataKey: "aws-request-id"] = "\(invocation.metadata.requestID)"

Expand Down Expand Up @@ -76,14 +88,18 @@ public enum Lambda {
logger: logger
)
)
logger.trace("Handler finished processing invocation")
} catch {
logger.trace("Handler failed processing invocation", metadata: ["Handler error": "\(error)"])
try await writer.reportError(error)
continue
}
logger.handler.metadata.removeValue(forKey: "aws-request-id")
}
} catch is CancellationError {
// don't allow cancellation error to propagate further
}

}

/// The default EventLoop the Lambda is scheduled on.
Expand Down
15 changes: 14 additions & 1 deletion Sources/AWSLambdaRuntime/LambdaRuntime+ServiceLifecycle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,20 @@ import ServiceLifecycle
extension LambdaRuntime: Service {
public func run() async throws {
try await cancelWhenGracefulShutdown {
try await self._run()
do {
try await self._run()
} catch {
// catch top level errors that have not been handled until now
// this avoids the runtime to crash and generate a backtrace
self.logger.error("LambdaRuntime.run() failed with error", metadata: ["error": "\(error)"])
if let error = error as? LambdaRuntimeError,
error.code != .connectionToControlPlaneLost
{
// if the error is a LambdaRuntimeError but not a connection error,
// we rethrow it to preserve existing behaviour
throw error
}
}
}
}
}
Expand Down
15 changes: 14 additions & 1 deletion Sources/AWSLambdaRuntime/LambdaRuntime.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,20 @@ public final class LambdaRuntime<Handler>: Sendable where Handler: StreamingLamb
#if !ServiceLifecycleSupport
@inlinable
internal func run() async throws {
try await _run()
do {
try await _run()
} catch {
// catch top level errors that have not been handled until now
// this avoids the runtime to crash and generate a backtrace
self.logger.error("LambdaRuntime.run() failed with error", metadata: ["error": "\(error)"])
if let error = error as? LambdaRuntimeError,
error.code != .connectionToControlPlaneLost
{
// if the error is a LambdaRuntimeError but not a connection error,
// we rethrow it to preserve existing behaviour
throw error
}
}
}
#endif

Expand Down
18 changes: 16 additions & 2 deletions Sources/AWSLambdaRuntime/LambdaRuntimeClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ final actor LambdaRuntimeClient: LambdaRuntimeClientProtocol {
case closed
}

@usableFromInline
var futureConnectionClosed: EventLoopFuture<LambdaRuntimeError>? = nil

private let eventLoop: any EventLoop
private let logger: Logger
private let configuration: Configuration
Expand All @@ -118,10 +121,8 @@ final actor LambdaRuntimeClient: LambdaRuntimeClientProtocol {
} catch {
result = .failure(error)
}

await runtime.close()

//try? await runtime.close()
return try result.get()
}

Expand Down Expand Up @@ -330,6 +331,8 @@ final actor LambdaRuntimeClient: LambdaRuntimeClientProtocol {
try channel.pipeline.syncOperations.addHTTPClientHandlers()
// Lambda quotas... An invocation payload is maximal 6MB in size:
// https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html
// TODO: should we enforce this here ? What about streaming functions that
// support up to 20Mb responses ?
try channel.pipeline.syncOperations.addHandler(
NIOHTTPClientResponseAggregator(maxContentLength: 6 * 1024 * 1024)
)
Expand Down Expand Up @@ -364,6 +367,16 @@ final actor LambdaRuntimeClient: LambdaRuntimeClientProtocol {
channel.closeFuture.whenComplete { result in
self.assumeIsolated { runtimeClient in
runtimeClient.channelClosed(channel)

// at this stage, we lost the connection to the Lambda Service,
// this is very unlikely to happen when running in a lambda function deployed in the cloud
// however, this happens when performance testing against the MockServer
// shutdown this runtime.
// The Lambda service will create a new runtime environment anyway
runtimeClient.logger.trace("Connection to Lambda Service HTTP Server lost, exiting")
runtimeClient.futureConnectionClosed = runtimeClient.eventLoop.makeFailedFuture(
LambdaRuntimeError(code: .connectionToControlPlaneLost)
)
}
}

Expand All @@ -382,6 +395,7 @@ final actor LambdaRuntimeClient: LambdaRuntimeClientProtocol {
return handler
}
} catch {

switch self.connectionState {
case .disconnected, .connected:
fatalError("Unexpected state: \(self.connectionState)")
Expand Down
2 changes: 1 addition & 1 deletion Sources/MockServer/MockHTTPServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ struct HttpServer {
} else if requestHead.uri.hasSuffix("/response") {
responseStatus = .accepted
} else if requestHead.uri.hasSuffix("/error") {
responseStatus = .ok
responseStatus = .accepted
} else {
responseStatus = .notFound
}
Expand Down