Skip to content

Commit 59b97d3

Browse files
committed
Try to inline as much as possible
1 parent ab13e51 commit 59b97d3

16 files changed

+275
-258
lines changed

Sources/AWSLambdaRuntime/Lambda+Codable.swift

+2
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,15 @@ internal struct CodableVoidClosureWrapper<In: Decodable>: LambdaHandler {
8080

8181
/// Implementation of a`ByteBuffer` to `In` decoding
8282
extension EventLoopLambdaHandler where In: Decodable {
83+
@inlinable
8384
public func decode(buffer: ByteBuffer) throws -> In {
8485
try self.decoder.decode(In.self, from: buffer)
8586
}
8687
}
8788

8889
/// Implementation of `Out` to `ByteBuffer` encoding
8990
extension EventLoopLambdaHandler where Out: Encodable {
91+
@inlinable
9092
public func encode(allocator: ByteBufferAllocator, value: Out) throws -> ByteBuffer? {
9193
try self.encoder.encode(value, using: allocator)
9294
}

Sources/AWSLambdaRuntimeCore/HTTPClient.swift

+2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import NIOHTTP1
1919
/// A barebone HTTP client to interact with AWS Runtime Engine which is an HTTP server.
2020
/// Note that Lambda Runtime API dictate that only one requests runs at a time.
2121
/// This means we can avoid locks and other concurrency concern we would otherwise need to build into the client
22+
@usableFromInline
2223
internal final class HTTPClient {
2324
private let eventLoop: EventLoop
2425
private let configuration: Lambda.Configuration.RuntimeEngine
@@ -144,6 +145,7 @@ internal final class HTTPClient {
144145
var body: ByteBuffer?
145146
}
146147

148+
@usableFromInline
147149
internal enum Errors: Error {
148150
case connectionResetByPeer
149151
case timeout

Sources/AWSLambdaRuntimeCore/Lambda+LocalServer.swift

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ extension Lambda {
3535
/// - body: Code to run within the context of the mock server. Typically this would be a Lambda.run function call.
3636
///
3737
/// - note: This API is designed stricly for local testing and is behind a DEBUG flag
38+
@usableFromInline
3839
internal static func withLocalServer<Value>(invocationEndpoint: String? = nil, _ body: @escaping () -> Value) throws -> Value {
3940
let server = LocalLambda.Server(invocationEndpoint: invocationEndpoint)
4041
try server.start().wait()

Sources/AWSLambdaRuntimeCore/Lambda+String.swift

+2
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ internal struct StringVoidClosureWrapper: LambdaHandler {
8888

8989
extension EventLoopLambdaHandler where In == String {
9090
/// Implementation of a `ByteBuffer` to `String` decoding
91+
@inlinable
9192
public func decode(buffer: ByteBuffer) throws -> String {
9293
var buffer = buffer
9394
guard let string = buffer.readString(length: buffer.readableBytes) else {
@@ -99,6 +100,7 @@ extension EventLoopLambdaHandler where In == String {
99100

100101
extension EventLoopLambdaHandler where Out == String {
101102
/// Implementation of `String` to `ByteBuffer` encoding
103+
@inlinable
102104
public func encode(allocator: ByteBufferAllocator, value: String) throws -> ByteBuffer? {
103105
// FIXME: reusable buffer
104106
var buffer = allocator.buffer(capacity: value.utf8.count)

Sources/AWSLambdaRuntimeCore/Lambda.swift

+15-14
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,14 @@ import NIO
2525
public enum Lambda {
2626
public typealias Handler = ByteBufferLambdaHandler
2727

28-
/// `ByteBufferLambdaHandler` factory.
29-
///
30-
/// A function that takes a `InitializationContext` and returns an `EventLoopFuture` of a `ByteBufferLambdaHandler`
31-
public typealias HandlerFactory = (InitializationContext) -> EventLoopFuture<Handler>
32-
3328
/// Run a Lambda defined by implementing the `LambdaHandler` protocol.
3429
///
3530
/// - parameters:
3631
/// - handler: `ByteBufferLambdaHandler` based Lambda.
3732
///
3833
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the AWS Lambda Runtime Engine.
39-
public static func run(_ handler: Handler) {
34+
@inlinable
35+
public static func run<H: Handler>(_ handler: H) {
4036
if case .failure(let error) = self.run(handler: handler) {
4137
fatalError("\(error)")
4238
}
@@ -50,7 +46,8 @@ public enum Lambda {
5046
/// - factory: A `ByteBufferLambdaHandler` factory.
5147
///
5248
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the AWS Lambda Runtime Engine.
53-
public static func run(_ factory: @escaping HandlerFactory) {
49+
@inlinable
50+
public static func run<H: Handler>(_ factory: @escaping (InitializationContext) -> EventLoopFuture<H>) {
5451
if case .failure(let error) = self.run(factory: factory) {
5552
fatalError("\(error)")
5653
}
@@ -62,7 +59,8 @@ public enum Lambda {
6259
/// - factory: A `ByteBufferLambdaHandler` factory.
6360
///
6461
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the AWS Lambda Runtime Engine.
65-
public static func run(_ factory: @escaping (InitializationContext) throws -> Handler) {
62+
@inlinable
63+
public static func run<H: Handler>(_ factory: @escaping (InitializationContext) throws -> H) {
6664
if case .failure(let error) = self.run(factory: factory) {
6765
fatalError("\(error)")
6866
}
@@ -77,14 +75,16 @@ public enum Lambda {
7775
}
7876

7977
// for testing and internal use
80-
internal static func run(configuration: Configuration = .init(), handler: Handler) -> Result<Int, Error> {
78+
@inlinable
79+
internal static func run<H: Handler>(configuration: Configuration = .init(), handler: H) -> Result<Int, Error> {
8180
self.run(configuration: configuration, factory: { $0.eventLoop.makeSucceededFuture(handler) })
8281
}
8382

8483
// for testing and internal use
85-
internal static func run(configuration: Configuration = .init(), factory: @escaping (InitializationContext) throws -> Handler) -> Result<Int, Error> {
86-
self.run(configuration: configuration, factory: { context -> EventLoopFuture<Handler> in
87-
let promise = context.eventLoop.makePromise(of: Handler.self)
84+
@inlinable
85+
internal static func run<H: Handler>(configuration: Configuration = .init(), factory: @escaping (InitializationContext) throws -> H) -> Result<Int, Error> {
86+
self.run(configuration: configuration, factory: { context -> EventLoopFuture<H> in
87+
let promise = context.eventLoop.makePromise(of: H.self)
8888
// if we have a callback based handler factory, we offload the creation of the handler
8989
// onto the default offload queue, to ensure that the eventloop is never blocked.
9090
Lambda.defaultOffloadQueue.async {
@@ -99,8 +99,9 @@ public enum Lambda {
9999
}
100100

101101
// for testing and internal use
102-
internal static func run(configuration: Configuration = .init(), factory: @escaping HandlerFactory) -> Result<Int, Error> {
103-
let _run = { (configuration: Configuration, factory: @escaping HandlerFactory) -> Result<Int, Error> in
102+
@inlinable
103+
static func run<H: Handler>(configuration: Configuration = .init(), factory: @escaping (InitializationContext) -> EventLoopFuture<H>) -> Result<Int, Error> {
104+
let _run = { (configuration: Configuration, factory: @escaping (InitializationContext) -> EventLoopFuture<H>) -> Result<Int, Error> in
104105
Backtrace.install()
105106
var logger = Logger(label: "Lambda")
106107
logger.logLevel = configuration.general.logLevel

Sources/AWSLambdaRuntimeCore/LambdaConfiguration.swift

+20
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,17 @@ import Logging
1717
import NIO
1818

1919
extension Lambda {
20+
@usableFromInline
2021
internal struct Configuration: CustomStringConvertible {
22+
@usableFromInline
2123
let general: General
24+
25+
@usableFromInline
2226
let lifecycle: Lifecycle
27+
@usableFromInline
2328
let runtimeEngine: RuntimeEngine
2429

30+
@usableFromInline
2531
init() {
2632
self.init(general: .init(), lifecycle: .init(), runtimeEngine: .init())
2733
}
@@ -32,21 +38,30 @@ extension Lambda {
3238
self.runtimeEngine = runtimeEngine ?? RuntimeEngine()
3339
}
3440

41+
@usableFromInline
3542
struct General: CustomStringConvertible {
43+
@usableFromInline
3644
let logLevel: Logger.Level
3745

3846
init(logLevel: Logger.Level? = nil) {
3947
self.logLevel = logLevel ?? env("LOG_LEVEL").flatMap(Logger.Level.init) ?? .info
4048
}
4149

50+
@usableFromInline
4251
var description: String {
4352
"\(General.self)(logLevel: \(self.logLevel))"
4453
}
4554
}
4655

56+
@usableFromInline
4757
struct Lifecycle: CustomStringConvertible {
58+
@usableFromInline
4859
let id: String
60+
61+
@usableFromInline
4962
let maxTimes: Int
63+
64+
@usableFromInline
5065
let stopSignal: Signal
5166

5267
init(id: String? = nil, maxTimes: Int? = nil, stopSignal: Signal? = nil) {
@@ -56,16 +71,19 @@ extension Lambda {
5671
precondition(self.maxTimes >= 0, "maxTimes must be equal or larger than 0")
5772
}
5873

74+
@usableFromInline
5975
var description: String {
6076
"\(Lifecycle.self)(id: \(self.id), maxTimes: \(self.maxTimes), stopSignal: \(self.stopSignal))"
6177
}
6278
}
6379

80+
@usableFromInline
6481
struct RuntimeEngine: CustomStringConvertible {
6582
let ip: String
6683
let port: Int
6784
let requestTimeout: TimeAmount?
6885

86+
@usableFromInline
6987
init(address: String? = nil, keepAlive: Bool? = nil, requestTimeout: TimeAmount? = nil) {
7088
let ipPort = (address ?? env("AWS_LAMBDA_RUNTIME_API"))?.split(separator: ":") ?? ["127.0.0.1", "7000"]
7189
guard ipPort.count == 2, let port = Int(ipPort[1]) else {
@@ -76,11 +94,13 @@ extension Lambda {
7694
self.requestTimeout = requestTimeout ?? env("REQUEST_TIMEOUT").flatMap(Int64.init).flatMap { .milliseconds($0) }
7795
}
7896

97+
@usableFromInline
7998
var description: String {
8099
"\(RuntimeEngine.self)(ip: \(self.ip), port: \(self.port), requestTimeout: \(String(describing: self.requestTimeout))"
81100
}
82101
}
83102

103+
@usableFromInline
84104
var description: String {
85105
"\(Configuration.self)\n \(self.general))\n \(self.lifecycle)\n \(self.runtimeEngine)"
86106
}

Sources/AWSLambdaRuntimeCore/LambdaContext.swift

+2
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ extension Lambda {
3636
/// `ByteBufferAllocator` to allocate `ByteBuffer`
3737
public let allocator: ByteBufferAllocator
3838

39+
@usableFromInline
3940
internal init(logger: Logger, eventLoop: EventLoop, allocator: ByteBufferAllocator) {
4041
self.eventLoop = eventLoop
4142
self.logger = logger
@@ -141,6 +142,7 @@ extension Lambda {
141142
/// Most importantly the `EventLoop` must never be blocked.
142143
public let eventLoop: EventLoop
143144

145+
@usableFromInline
144146
internal init(logger: Logger, eventLoop: EventLoop) {
145147
self.eventLoop = eventLoop
146148
self.logger = logger

Sources/AWSLambdaRuntimeCore/LambdaHandler.swift

+14-25
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ public protocol LambdaHandler: EventLoopLambdaHandler {
4040
}
4141

4242
extension Lambda {
43+
@usableFromInline
4344
internal static let defaultOffloadQueue = DispatchQueue(label: "LambdaHandler.offload")
4445
}
4546

@@ -128,41 +129,28 @@ public protocol EventLoopLambdaHandler: ByteBufferLambdaHandler {
128129

129130
extension EventLoopLambdaHandler {
130131
/// Driver for `ByteBuffer` -> `In` decoding and `Out` -> `ByteBuffer` encoding
132+
@inlinable
131133
public func handle(context: Lambda.Context, event: ByteBuffer) -> EventLoopFuture<ByteBuffer?> {
132-
switch self.decodeIn(buffer: event) {
133-
case .failure(let error):
134-
return context.eventLoop.makeFailedFuture(CodecError.requestDecoding(error))
135-
case .success(let `in`):
136-
return self.handle(context: context, event: `in`).flatMapThrowing { out in
137-
switch self.encodeOut(allocator: context.allocator, value: out) {
138-
case .failure(let error):
139-
throw CodecError.responseEncoding(error)
140-
case .success(let buffer):
141-
return buffer
142-
}
143-
}
144-
}
145-
}
146-
147-
private func decodeIn(buffer: ByteBuffer) -> Result<In, Error> {
134+
let input: In
148135
do {
149-
return .success(try self.decode(buffer: buffer))
136+
input = try self.decode(buffer: event)
150137
} catch {
151-
return .failure(error)
138+
return context.eventLoop.makeFailedFuture(CodecError.requestDecoding(error))
152139
}
153-
}
154140

155-
private func encodeOut(allocator: ByteBufferAllocator, value: Out) -> Result<ByteBuffer?, Error> {
156-
do {
157-
return .success(try self.encode(allocator: allocator, value: value))
158-
} catch {
159-
return .failure(error)
141+
return self.handle(context: context, event: input).flatMapThrowing { output in
142+
do {
143+
return try self.encode(allocator: context.allocator, value: output)
144+
} catch {
145+
throw CodecError.responseEncoding(error)
146+
}
160147
}
161148
}
162149
}
163150

164151
/// Implementation of `ByteBuffer` to `Void` decoding
165152
extension EventLoopLambdaHandler where Out == Void {
153+
@inlinable
166154
public func encode(allocator: ByteBufferAllocator, value: Void) throws -> ByteBuffer? {
167155
nil
168156
}
@@ -200,7 +188,8 @@ extension ByteBufferLambdaHandler {
200188
}
201189
}
202190

203-
private enum CodecError: Error {
191+
@usableFromInline
192+
enum CodecError: Error {
204193
case requestDecoding(Error)
205194
case responseEncoding(Error)
206195
}

0 commit comments

Comments
 (0)