@@ -92,29 +92,33 @@ public enum Lambda {
92
92
// for testing and internal use
93
93
@discardableResult
94
94
internal static func run( configuration: Configuration = . init( ) , factory: @escaping HandlerFactory ) -> Result < Int , Error > {
95
- do {
96
- let eventLoopGroup = MultiThreadedEventLoopGroup ( numberOfThreads: 1 ) // only need one thread, will improve performance
97
- defer { try ! eventLoopGroup. syncShutdownGracefully ( ) }
98
- let result = try self . runAsync ( eventLoopGroup: eventLoopGroup, configuration: configuration, factory: factory) . wait ( )
99
- return . success( result)
100
- } catch {
101
- return . failure( error)
102
- }
103
- }
104
-
105
- internal static func runAsync( eventLoopGroup: EventLoopGroup , configuration: Configuration , factory: @escaping HandlerFactory ) -> EventLoopFuture < Int > {
106
95
Backtrace . install ( )
107
96
var logger = Logger ( label: " Lambda " )
108
97
logger. logLevel = configuration. general. logLevel
109
- let lifecycle = Lifecycle ( eventLoop: eventLoopGroup. next ( ) , logger: logger, configuration: configuration, factory: factory)
110
- let signalSource = trap ( signal: configuration. lifecycle. stopSignal) { signal in
111
- logger. info ( " intercepted signal: \( signal) " )
112
- lifecycle. shutdown ( )
113
- }
114
- return lifecycle. start ( ) . flatMap {
115
- return lifecycle. shutdownFuture. always { _ in
98
+
99
+ var r : Result < Int , Error > ?
100
+ MultiThreadedEventLoopGroup . withCurrentThreadAsEventLoop { eventLoop in
101
+ let lifecycle = Lifecycle ( eventLoop: eventLoop, logger: logger, configuration: configuration, factory: factory)
102
+ let signalSource = trap ( signal: configuration. lifecycle. stopSignal) { signal in
103
+ logger. info ( " intercepted signal: \( signal) " )
104
+ lifecycle. shutdown ( )
105
+ }
106
+
107
+ _ = lifecycle. start ( ) . flatMap {
108
+ lifecycle. shutdownFuture
109
+ }
110
+ . always { result in
116
111
signalSource. cancel ( )
112
+ eventLoop. shutdownGracefully { _ in
113
+ logger. info ( " shutdown " )
114
+ }
115
+
116
+ r = result
117
117
}
118
118
}
119
+
120
+ logger. info ( " shutdown completed " )
121
+
122
+ return r!
119
123
}
120
124
}
0 commit comments