ConnectionTest.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. @_spi(Package) @testable 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. )
  105. return stream.eventLoop.makeCompletedFuture {
  106. try sync.addHandler(handler)
  107. try sync.addHandler(EchoHandler())
  108. }
  109. }
  110. try sync.addHandler(h2)
  111. try sync.addHandler(mux)
  112. try sync.addHandlers(SucceedOnSettingsAck(promise: self.client))
  113. }
  114. }
  115. }
  116. let channel = try await bootstrap.bind(host: "127.0.0.1", port: 0).get()
  117. self.listener = channel
  118. return .ipv4(host: "127.0.0.1", port: channel.localAddress!.port!)
  119. }
  120. }
  121. }
  122. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  123. extension ConnectionTest {
  124. /// Succeeds a promise when a SETTINGS frame ack has been read.
  125. private final class SucceedOnSettingsAck: ChannelInboundHandler {
  126. typealias InboundIn = HTTP2Frame
  127. typealias InboundOut = HTTP2Frame
  128. private let promise: EventLoopPromise<Channel>
  129. init(promise: EventLoopPromise<Channel>) {
  130. self.promise = promise
  131. }
  132. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  133. let frame = self.unwrapInboundIn(data)
  134. switch frame.payload {
  135. case .settings(.ack):
  136. self.promise.succeed(context.channel)
  137. default:
  138. ()
  139. }
  140. context.fireChannelRead(data)
  141. }
  142. }
  143. private final class EchoHandler: ChannelInboundHandler {
  144. typealias InboundIn = RPCRequestPart
  145. typealias OutboundOut = RPCResponsePart
  146. private var received: Deque<RPCRequestPart> = []
  147. private var receivedEnd = false
  148. func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  149. if let event = event as? ChannelEvent, event == .inputClosed {
  150. self.receivedEnd = true
  151. }
  152. }
  153. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  154. self.received.append(self.unwrapInboundIn(data))
  155. }
  156. func channelReadComplete(context: ChannelHandlerContext) {
  157. while let part = self.received.popFirst() {
  158. switch part {
  159. case .metadata(let metadata):
  160. var filtered = Metadata()
  161. // Remove any pseudo-headers.
  162. for (key, value) in metadata where !key.hasPrefix(":") {
  163. switch value {
  164. case .string(let value):
  165. filtered.addString(value, forKey: key)
  166. case .binary(let value):
  167. filtered.addBinary(value, forKey: key)
  168. }
  169. }
  170. context.write(self.wrapOutboundOut(.metadata(filtered)), promise: nil)
  171. case .message(let message):
  172. context.write(self.wrapOutboundOut(.message(message)), promise: nil)
  173. }
  174. }
  175. if self.receivedEnd {
  176. let status = Status(code: .ok, message: "")
  177. context.write(self.wrapOutboundOut(.status(status, [:])), promise: nil)
  178. }
  179. context.flush()
  180. }
  181. }
  182. }