ConnectionTest.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import DequeModule
  17. import GRPCCore
  18. import GRPCHTTP2Core
  19. import NIOCore
  20. import NIOHTTP2
  21. import NIOPosix
  22. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  23. enum ConnectionTest {
  24. struct Context {
  25. var server: Server
  26. var connection: Connection
  27. }
  28. static func run(
  29. connector: any HTTP2Connector,
  30. server mode: Server.Mode = .regular,
  31. handlEvents: (
  32. _ context: Context,
  33. _ event: Connection.Event
  34. ) async throws -> Void = { _, _ in },
  35. validateEvents: (_ context: Context, _ events: [Connection.Event]) throws -> Void
  36. ) async throws {
  37. let server = Server(mode: mode)
  38. let address = try await server.bind()
  39. try await withThrowingTaskGroup(of: Void.self) { group in
  40. let connection = Connection(
  41. address: address,
  42. http2Connector: connector,
  43. defaultCompression: .none,
  44. enabledCompression: .none
  45. )
  46. let context = Context(server: server, connection: connection)
  47. group.addTask { await connection.run() }
  48. var events: [Connection.Event] = []
  49. for await event in connection.events {
  50. events.append(event)
  51. try await handlEvents(context, event)
  52. }
  53. try validateEvents(context, events)
  54. }
  55. }
  56. }
  57. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  58. extension ConnectionTest {
  59. /// A server which only expected to accept a single connection.
  60. final class Server {
  61. private let eventLoop: any EventLoop
  62. private var listener: (any Channel)?
  63. private let client: EventLoopPromise<any Channel>
  64. private let mode: Mode
  65. enum Mode: Sendable {
  66. case regular
  67. case closeOnAccept
  68. }
  69. init(mode: Mode) {
  70. self.mode = mode
  71. self.eventLoop = .singletonMultiThreadedEventLoopGroup.next()
  72. self.client = self.eventLoop.next().makePromise()
  73. }
  74. deinit {
  75. self.listener?.close(promise: nil)
  76. self.client.futureResult.whenSuccess { $0.close(mode: .all, promise: nil) }
  77. }
  78. var acceptedChannel: any Channel {
  79. get throws {
  80. try self.client.futureResult.wait()
  81. }
  82. }
  83. func bind() async throws -> GRPCHTTP2Core.SocketAddress {
  84. precondition(self.listener == nil, "\(#function) must only be called once")
  85. let hasAcceptedChannel = try await self.eventLoop.submit { [loop = self.eventLoop] in
  86. NIOLoopBoundBox(false, eventLoop: loop)
  87. }.get()
  88. let bootstrap = ServerBootstrap(
  89. group: self.eventLoop
  90. ).childChannelInitializer { [mode = self.mode, client = self.client] channel in
  91. precondition(!hasAcceptedChannel.value, "already accepted a channel")
  92. hasAcceptedChannel.value = true
  93. switch mode {
  94. case .closeOnAccept:
  95. return channel.close()
  96. case .regular:
  97. return channel.eventLoop.makeCompletedFuture {
  98. let sync = channel.pipeline.syncOperations
  99. let h2 = NIOHTTP2Handler(mode: .server)
  100. let mux = HTTP2StreamMultiplexer(mode: .server, channel: channel) { stream in
  101. let sync = stream.pipeline.syncOperations
  102. let handler = GRPCServerStreamHandler(
  103. scheme: .http,
  104. acceptedEncodings: .none,
  105. maximumPayloadSize: .max,
  106. methodDescriptorPromise: channel.eventLoop.makePromise(of: MethodDescriptor.self)
  107. )
  108. return stream.eventLoop.makeCompletedFuture {
  109. try sync.addHandler(handler)
  110. try sync.addHandler(EchoHandler())
  111. }
  112. }
  113. try sync.addHandler(h2)
  114. try sync.addHandler(mux)
  115. try sync.addHandlers(SucceedOnSettingsAck(promise: client))
  116. }
  117. }
  118. }
  119. let channel = try await bootstrap.bind(host: "127.0.0.1", port: 0).get()
  120. self.listener = channel
  121. return .ipv4(host: "127.0.0.1", port: channel.localAddress!.port!)
  122. }
  123. }
  124. }
  125. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  126. extension ConnectionTest {
  127. /// Succeeds a promise when a SETTINGS frame ack has been read.
  128. private final class SucceedOnSettingsAck: ChannelInboundHandler {
  129. typealias InboundIn = HTTP2Frame
  130. typealias InboundOut = HTTP2Frame
  131. private let promise: EventLoopPromise<any Channel>
  132. init(promise: EventLoopPromise<any Channel>) {
  133. self.promise = promise
  134. }
  135. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  136. let frame = self.unwrapInboundIn(data)
  137. switch frame.payload {
  138. case .settings(.ack):
  139. self.promise.succeed(context.channel)
  140. default:
  141. ()
  142. }
  143. context.fireChannelRead(data)
  144. }
  145. }
  146. final class EchoHandler: ChannelInboundHandler {
  147. typealias InboundIn = RPCRequestPart
  148. typealias OutboundOut = RPCResponsePart
  149. private var received: Deque<RPCRequestPart> = []
  150. private var receivedEnd = false
  151. func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  152. if let event = event as? ChannelEvent, event == .inputClosed {
  153. self.receivedEnd = true
  154. }
  155. }
  156. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  157. self.received.append(self.unwrapInboundIn(data))
  158. }
  159. func channelReadComplete(context: ChannelHandlerContext) {
  160. while let part = self.received.popFirst() {
  161. switch part {
  162. case .metadata(let metadata):
  163. var filtered = Metadata()
  164. // Remove any pseudo-headers.
  165. for (key, value) in metadata where !key.hasPrefix(":") {
  166. switch value {
  167. case .string(let value):
  168. filtered.addString(value, forKey: key)
  169. case .binary(let value):
  170. filtered.addBinary(value, forKey: key)
  171. }
  172. }
  173. context.write(self.wrapOutboundOut(.metadata(filtered)), promise: nil)
  174. case .message(let message):
  175. context.write(self.wrapOutboundOut(.message(message)), promise: nil)
  176. }
  177. }
  178. if self.receivedEnd {
  179. let status = Status(code: .ok, message: "")
  180. context.write(self.wrapOutboundOut(.status(status, [:])), promise: nil)
  181. }
  182. context.flush()
  183. }
  184. }
  185. }