ConnectionTest.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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: 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<Channel>
  64. private let mode: Mode
  65. enum Mode {
  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: 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 {
  86. NIOLoopBoundBox(false, eventLoop: self.eventLoop)
  87. }.get()
  88. let bootstrap = ServerBootstrap(group: self.eventLoop).childChannelInitializer { channel in
  89. precondition(!hasAcceptedChannel.value, "already accepted a channel")
  90. hasAcceptedChannel.value = true
  91. switch self.mode {
  92. case .closeOnAccept:
  93. return channel.close()
  94. case .regular:
  95. return channel.eventLoop.makeCompletedFuture {
  96. let sync = channel.pipeline.syncOperations
  97. let h2 = NIOHTTP2Handler(mode: .server)
  98. let mux = HTTP2StreamMultiplexer(mode: .server, channel: channel) { stream in
  99. let sync = stream.pipeline.syncOperations
  100. let handler = GRPCServerStreamHandler(
  101. scheme: .http,
  102. acceptedEncodings: .none,
  103. maximumPayloadSize: .max,
  104. methodDescriptorPromise: channel.eventLoop.makePromise(of: MethodDescriptor.self)
  105. )
  106. return stream.eventLoop.makeCompletedFuture {
  107. try sync.addHandler(handler)
  108. try sync.addHandler(EchoHandler())
  109. }
  110. }
  111. try sync.addHandler(h2)
  112. try sync.addHandler(mux)
  113. try sync.addHandlers(SucceedOnSettingsAck(promise: self.client))
  114. }
  115. }
  116. }
  117. let channel = try await bootstrap.bind(host: "127.0.0.1", port: 0).get()
  118. self.listener = channel
  119. return .ipv4(host: "127.0.0.1", port: channel.localAddress!.port!)
  120. }
  121. }
  122. }
  123. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  124. extension ConnectionTest {
  125. /// Succeeds a promise when a SETTINGS frame ack has been read.
  126. private final class SucceedOnSettingsAck: ChannelInboundHandler {
  127. typealias InboundIn = HTTP2Frame
  128. typealias InboundOut = HTTP2Frame
  129. private let promise: EventLoopPromise<Channel>
  130. init(promise: EventLoopPromise<Channel>) {
  131. self.promise = promise
  132. }
  133. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  134. let frame = self.unwrapInboundIn(data)
  135. switch frame.payload {
  136. case .settings(.ack):
  137. self.promise.succeed(context.channel)
  138. default:
  139. ()
  140. }
  141. context.fireChannelRead(data)
  142. }
  143. }
  144. final class EchoHandler: ChannelInboundHandler {
  145. typealias InboundIn = RPCRequestPart
  146. typealias OutboundOut = RPCResponsePart
  147. private var received: Deque<RPCRequestPart> = []
  148. private var receivedEnd = false
  149. func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  150. if let event = event as? ChannelEvent, event == .inputClosed {
  151. self.receivedEnd = true
  152. }
  153. }
  154. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  155. self.received.append(self.unwrapInboundIn(data))
  156. }
  157. func channelReadComplete(context: ChannelHandlerContext) {
  158. while let part = self.received.popFirst() {
  159. switch part {
  160. case .metadata(let metadata):
  161. var filtered = Metadata()
  162. // Remove any pseudo-headers.
  163. for (key, value) in metadata where !key.hasPrefix(":") {
  164. switch value {
  165. case .string(let value):
  166. filtered.addString(value, forKey: key)
  167. case .binary(let value):
  168. filtered.addBinary(value, forKey: key)
  169. }
  170. }
  171. context.write(self.wrapOutboundOut(.metadata(filtered)), promise: nil)
  172. case .message(let message):
  173. context.write(self.wrapOutboundOut(.message(message)), promise: nil)
  174. }
  175. }
  176. if self.receivedEnd {
  177. let status = Status(code: .ok, message: "")
  178. context.write(self.wrapOutboundOut(.status(status, [:])), promise: nil)
  179. }
  180. context.flush()
  181. }
  182. }
  183. }