Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drop sync and closure APIs #222

Merged
merged 10 commits into from
Aug 24, 2021
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import Logging
// MARK: - Run Lambda

@main
struct CurrencyExchangeHandler: AsyncLambdaHandler {
struct CurrencyExchangeHandler: LambdaHandler {
typealias In = Request
typealias Out = [Exchange]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import AWSLambdaRuntime
// MARK: - Run Lambda

@main
struct ErrorsHappenHandler: AsyncLambdaHandler {
struct ErrorsHappenHandler: LambdaHandler {
typealias In = Request
typealias Out = Response

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import AWSLambdaRuntime

// introductory example, the obligatory "hello, world!"
@main
struct HelloWorldHandler: AsyncLambdaHandler {
struct HelloWorldHandler: LambdaHandler {
typealias In = String
typealias Out = String

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import Shared
// set LOCAL_LAMBDA_SERVER_ENABLED env variable to "true" to start
// a local server simulator which will allow local debugging
@main
struct MyLambdaHandler: AsyncLambdaHandler {
struct MyLambdaHandler: LambdaHandler {
typealias In = Request
typealias Out = Response

Expand Down
59 changes: 0 additions & 59 deletions Sources/AWSLambdaRuntime/Lambda+Codable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,65 +19,6 @@ import class Foundation.JSONEncoder
import NIOCore
import NIOFoundationCompat

/// Extension to the `Lambda` companion to enable execution of Lambdas that take and return `Codable` events.
extension Lambda {
/// An asynchronous Lambda Closure that takes a `In: Decodable` and returns a `Result<Out: Encodable, Error>` via a completion handler.
public typealias CodableClosure<In: Decodable, Out: Encodable> = (Lambda.Context, In, @escaping (Result<Out, Error>) -> Void) -> Void

/// Run a Lambda defined by implementing the `CodableClosure` function.
///
/// - parameters:
/// - closure: `CodableClosure` based Lambda.
///
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the AWS Lambda Runtime Engine.
public static func run<In: Decodable, Out: Encodable>(_ closure: @escaping CodableClosure<In, Out>) {
self.run(CodableClosureWrapper(closure))
}

/// An asynchronous Lambda Closure that takes a `In: Decodable` and returns a `Result<Void, Error>` via a completion handler.
public typealias CodableVoidClosure<In: Decodable> = (Lambda.Context, In, @escaping (Result<Void, Error>) -> Void) -> Void

/// Run a Lambda defined by implementing the `CodableVoidClosure` function.
///
/// - parameters:
/// - closure: `CodableVoidClosure` based Lambda.
///
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the AWS Lambda Runtime Engine.
public static func run<In: Decodable>(_ closure: @escaping CodableVoidClosure<In>) {
self.run(CodableVoidClosureWrapper(closure))
}
}

internal struct CodableClosureWrapper<In: Decodable, Out: Encodable>: LambdaHandler {
typealias In = In
typealias Out = Out

private let closure: Lambda.CodableClosure<In, Out>

init(_ closure: @escaping Lambda.CodableClosure<In, Out>) {
self.closure = closure
}

func handle(context: Lambda.Context, event: In, callback: @escaping (Result<Out, Error>) -> Void) {
self.closure(context, event, callback)
}
}

internal struct CodableVoidClosureWrapper<In: Decodable>: LambdaHandler {
typealias In = In
typealias Out = Void

private let closure: Lambda.CodableVoidClosure<In>

init(_ closure: @escaping Lambda.CodableVoidClosure<In>) {
self.closure = closure
}

func handle(context: Lambda.Context, event: In, callback: @escaping (Result<Out, Error>) -> Void) {
self.closure(context, event, callback)
}
}

// MARK: - Codable support

/// Implementation of a`ByteBuffer` to `In` decoding
Expand Down
73 changes: 0 additions & 73 deletions Sources/AWSLambdaRuntimeCore/Lambda+String.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,79 +13,6 @@
//===----------------------------------------------------------------------===//
import NIOCore

/// Extension to the `Lambda` companion to enable execution of Lambdas that take and return `String` events.
extension Lambda {
/// An asynchronous Lambda Closure that takes a `String` and returns a `Result<String, Error>` via a completion handler.
public typealias StringClosure = (Lambda.Context, String, @escaping (Result<String, Error>) -> Void) -> Void

/// Run a Lambda defined by implementing the `StringClosure` function.
///
/// - parameters:
/// - closure: `StringClosure` based Lambda.
///
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the AWS Lambda Runtime Engine.
public static func run(_ closure: @escaping StringClosure) {
if case .failure(let error) = self.run(closure: closure) {
fatalError("\(error)")
}
}

/// An asynchronous Lambda Closure that takes a `String` and returns a `Result<Void, Error>` via a completion handler.
public typealias StringVoidClosure = (Lambda.Context, String, @escaping (Result<Void, Error>) -> Void) -> Void

/// Run a Lambda defined by implementing the `StringVoidClosure` function.
///
/// - parameters:
/// - closure: `StringVoidClosure` based Lambda.
///
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the AWS Lambda Runtime Engine.
public static func run(_ closure: @escaping StringVoidClosure) {
if case .failure(let error) = self.run(closure: closure) {
fatalError("\(error)")
}
}

// for testing
internal static func run(configuration: Configuration = .init(), closure: @escaping StringClosure) -> Result<Int, Error> {
self.run(configuration: configuration, handler: StringClosureWrapper(closure))
}

// for testing
internal static func run(configuration: Configuration = .init(), closure: @escaping StringVoidClosure) -> Result<Int, Error> {
self.run(configuration: configuration, handler: StringVoidClosureWrapper(closure))
}
}

internal struct StringClosureWrapper: LambdaHandler {
typealias In = String
typealias Out = String

private let closure: Lambda.StringClosure

init(_ closure: @escaping Lambda.StringClosure) {
self.closure = closure
}

func handle(context: Lambda.Context, event: In, callback: @escaping (Result<Out, Error>) -> Void) {
self.closure(context, event, callback)
}
}

internal struct StringVoidClosureWrapper: LambdaHandler {
typealias In = String
typealias Out = Void

private let closure: Lambda.StringVoidClosure

init(_ closure: @escaping Lambda.StringVoidClosure) {
self.closure = closure
}

func handle(context: Lambda.Context, event: In, callback: @escaping (Result<Out, Error>) -> Void) {
self.closure(context, event, callback)
}
}

extension EventLoopLambdaHandler where In == String {
/// Implementation of a `ByteBuffer` to `String` decoding
@inlinable
Expand Down
48 changes: 8 additions & 40 deletions Sources/AWSLambdaRuntimeCore/Lambda.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,6 @@ public enum Lambda {
/// A function that takes a `InitializationContext` and returns an `EventLoopFuture` of a `ByteBufferLambdaHandler`
public typealias HandlerFactory = (InitializationContext) -> EventLoopFuture<Handler>

/// Run a Lambda defined by implementing the `LambdaHandler` protocol.
///
/// - parameters:
/// - handler: `ByteBufferLambdaHandler` based Lambda.
///
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the AWS Lambda Runtime Engine.
public static func run(_ handler: Handler) {
if case .failure(let error) = self.run(handler: handler) {
fatalError("\(error)")
}
}

/// Run a Lambda defined by implementing the `LambdaHandler` protocol provided via a `LambdaHandlerFactory`.
/// Use this to initialize all your resources that you want to cache between invocations. This could be database connections and HTTP clients for example.
/// It is encouraged to use the given `EventLoop`'s conformance to `EventLoopGroup` when initializing NIO dependencies. This will improve overall performance.
Expand All @@ -58,18 +46,6 @@ public enum Lambda {
}
}

/// Run a Lambda defined by implementing the `LambdaHandler` protocol provided via a factory, typically a constructor.
///
/// - parameters:
/// - factory: A `ByteBufferLambdaHandler` factory.
///
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the AWS Lambda Runtime Engine.
public static func run(_ factory: @escaping (InitializationContext) throws -> Handler) {
if case .failure(let error) = self.run(factory: factory) {
fatalError("\(error)")
}
}

/// Utility to access/read environment variables
public static func env(_ name: String) -> String? {
guard let value = getenv(name) else {
Expand All @@ -78,27 +54,19 @@ public enum Lambda {
return String(cString: value)
}

#if swift(>=5.5)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we just require 5.5? feels wrong to drop support for closures and support < 5.5

Copy link
Member Author

@fabianfett fabianfett Aug 20, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We talked about this last time. We wanted to stay with 5.2 to allow existing frameworks (Vapor, Noze, Hummingbird, Smoke, and friends) to integrate with Lambda without needing to bump their requirements. For integration into those frameworks developers will nearly always use the Lambda.Lifecycle APIs.

Normal Lambda users should require 5.5 and just use the async APIs.

I guess with this we will do what most of the Swift Server ecosystem is going todo... Make async/await the normal, leave escape hatch for advanced use cases using futures.

// for testing and internal use
internal static func run(configuration: Configuration = .init(), handler: Handler) -> Result<Int, Error> {
self.run(configuration: configuration, factory: { $0.eventLoop.makeSucceededFuture(handler) })
}

// for testing and internal use
internal static func run(configuration: Configuration = .init(), factory: @escaping (InitializationContext) throws -> Handler) -> Result<Int, Error> {
self.run(configuration: configuration, factory: { context -> EventLoopFuture<Handler> in
let promise = context.eventLoop.makePromise(of: Handler.self)
// if we have a callback based handler factory, we offload the creation of the handler
// onto the default offload queue, to ensure that the eventloop is never blocked.
Lambda.defaultOffloadQueue.async {
do {
promise.succeed(try factory(context))
} catch {
promise.fail(error)
}
@available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
internal static func run<Handler: LambdaHandler>(configuration: Configuration = .init(), handlerType: Handler.Type) -> Result<Int, Error> {
self.run(configuration: configuration, factory: { context -> EventLoopFuture<ByteBufferLambdaHandler> in
let promise = context.eventLoop.makePromise(of: ByteBufferLambdaHandler.self)
promise.completeWithTask {
try await Handler(context: context)
}
return promise.futureResult
})
}
#endif

// for testing and internal use
internal static func run(configuration: Configuration = .init(), factory: @escaping HandlerFactory) -> Result<Int, Error> {
Expand Down
72 changes: 53 additions & 19 deletions Sources/AWSLambdaRuntimeCore/LambdaContext.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,23 @@ extension Lambda {
/// `ByteBufferAllocator` to allocate `ByteBuffer`
public let allocator: ByteBufferAllocator

internal init(logger: Logger, eventLoop: EventLoop, allocator: ByteBufferAllocator) {
init(logger: Logger, eventLoop: EventLoop, allocator: ByteBufferAllocator) {
self.eventLoop = eventLoop
self.logger = logger
self.allocator = allocator
}

/// This interface is not part of the public API and must not be used by adopters. This API is not part of semver versioning.
public static func __forTestsOnly(
logger: Logger,
eventLoop: EventLoop
) -> InitializationContext {
InitializationContext(
logger: logger,
eventLoop: eventLoop,
allocator: ByteBufferAllocator()
)
}
}
}

Expand Down Expand Up @@ -138,24 +150,26 @@ extension Lambda {
self.storage.allocator
}

internal init(requestID: String,
traceID: String,
invokedFunctionARN: String,
deadline: DispatchWallTime,
cognitoIdentity: String? = nil,
clientContext: String? = nil,
logger: Logger,
eventLoop: EventLoop,
allocator: ByteBufferAllocator) {
self.storage = _Storage(requestID: requestID,
traceID: traceID,
invokedFunctionARN: invokedFunctionARN,
deadline: deadline,
cognitoIdentity: cognitoIdentity,
clientContext: clientContext,
logger: logger,
eventLoop: eventLoop,
allocator: allocator)
init(requestID: String,
traceID: String,
invokedFunctionARN: String,
deadline: DispatchWallTime,
cognitoIdentity: String? = nil,
clientContext: String? = nil,
logger: Logger,
eventLoop: EventLoop,
allocator: ByteBufferAllocator) {
self.storage = _Storage(
requestID: requestID,
traceID: traceID,
invokedFunctionARN: invokedFunctionARN,
deadline: deadline,
cognitoIdentity: cognitoIdentity,
clientContext: clientContext,
logger: logger,
eventLoop: eventLoop,
allocator: allocator
)
}

public func getRemainingTime() -> TimeAmount {
Expand All @@ -169,6 +183,26 @@ extension Lambda {
public var debugDescription: String {
"\(Self.self)(requestID: \(self.requestID), traceID: \(self.traceID), invokedFunctionARN: \(self.invokedFunctionARN), cognitoIdentity: \(self.cognitoIdentity ?? "nil"), clientContext: \(self.clientContext ?? "nil"), deadline: \(self.deadline))"
}

/// This interface is not part of the public API and must not be used by adopters. This API is not part of semver versioning.
public static func __forTestsOnly(
requestID: String,
traceID: String,
invokedFunctionARN: String,
timeout: DispatchTimeInterval,
logger: Logger,
eventLoop: EventLoop
) -> Context {
Context(
requestID: requestID,
traceID: traceID,
invokedFunctionARN: invokedFunctionARN,
deadline: .now() + timeout,
logger: logger,
eventLoop: eventLoop,
allocator: ByteBufferAllocator()
)
}
}
}

Expand Down
Loading