ConnectionTest.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. handlEvents: (
  31. _ context: Context,
  32. _ event: Connection.Event
  33. ) async throws -> Void = { _, _ in },
  34. validateEvents: (_ context: Context, _ events: [Connection.Event]) -> Void
  35. ) async throws {
  36. let server = Server()
  37. let address = try await server.bind()
  38. try await withThrowingTaskGroup(of: Void.self) { group in
  39. let connection = Connection(
  40. address: address,
  41. http2Connector: connector,
  42. defaultCompression: .none,
  43. enabledCompression: .none
  44. )
  45. let context = Context(server: server, connection: connection)
  46. group.addTask { await connection.run() }
  47. var events: [Connection.Event] = []
  48. for await event in connection.events {
  49. events.append(event)
  50. try await handlEvents(context, event)
  51. }
  52. validateEvents(context, events)
  53. }
  54. }
  55. }
  56. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  57. extension ConnectionTest {
  58. /// A server which only expected to accept a single connection.
  59. final class Server {
  60. private let eventLoop: any EventLoop
  61. private var listener: (any Channel)?
  62. private let client: EventLoopPromise<Channel>
  63. init() {
  64. self.eventLoop = .singletonMultiThreadedEventLoopGroup.next()
  65. self.client = self.eventLoop.next().makePromise()
  66. }
  67. deinit {
  68. self.listener?.close(promise: nil)
  69. self.client.futureResult.whenSuccess { $0.close(mode: .all, promise: nil) }
  70. }
  71. var acceptedChannel: Channel {
  72. get throws {
  73. try self.client.futureResult.wait()
  74. }
  75. }
  76. func bind() async throws -> GRPCHTTP2Core.SocketAddress {
  77. precondition(self.listener == nil, "\(#function) must only be called once")
  78. let hasAcceptedChannel = try await self.eventLoop.submit {
  79. NIOLoopBoundBox(false, eventLoop: self.eventLoop)
  80. }.get()
  81. let bootstrap = ServerBootstrap(group: self.eventLoop).childChannelInitializer { channel in
  82. precondition(!hasAcceptedChannel.value, "already accepted a channel")
  83. hasAcceptedChannel.value = true
  84. return channel.eventLoop.makeCompletedFuture {
  85. let sync = channel.pipeline.syncOperations
  86. let h2 = NIOHTTP2Handler(mode: .server)
  87. let mux = HTTP2StreamMultiplexer(mode: .server, channel: channel) { stream in
  88. let sync = stream.pipeline.syncOperations
  89. let handler = GRPCServerStreamHandler(
  90. scheme: .http,
  91. acceptedEncodings: .none,
  92. maximumPayloadSize: .max
  93. )
  94. return stream.eventLoop.makeCompletedFuture {
  95. try sync.addHandler(handler)
  96. try sync.addHandler(EchoHandler())
  97. }
  98. }
  99. try sync.addHandler(h2)
  100. try sync.addHandler(mux)
  101. try sync.addHandlers(SucceedOnSettingsAck(promise: self.client))
  102. }
  103. }
  104. let channel = try await bootstrap.bind(host: "127.0.0.1", port: 0).get()
  105. self.listener = channel
  106. return .ipv4(host: "127.0.0.1", port: channel.localAddress!.port!)
  107. }
  108. }
  109. }
  110. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  111. extension ConnectionTest {
  112. /// Succeeds a promise when a SETTINGS frame ack has been read.
  113. private final class SucceedOnSettingsAck: ChannelInboundHandler {
  114. typealias InboundIn = HTTP2Frame
  115. typealias InboundOut = HTTP2Frame
  116. private let promise: EventLoopPromise<Channel>
  117. init(promise: EventLoopPromise<Channel>) {
  118. self.promise = promise
  119. }
  120. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  121. let frame = self.unwrapInboundIn(data)
  122. switch frame.payload {
  123. case .settings(.ack):
  124. self.promise.succeed(context.channel)
  125. default:
  126. ()
  127. }
  128. context.fireChannelRead(data)
  129. }
  130. }
  131. private final class EchoHandler: ChannelInboundHandler {
  132. typealias InboundIn = RPCRequestPart
  133. typealias OutboundOut = RPCResponsePart
  134. private var received: Deque<RPCRequestPart> = []
  135. private var receivedEnd = false
  136. func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  137. if let event = event as? ChannelEvent, event == .inputClosed {
  138. self.receivedEnd = true
  139. }
  140. }
  141. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  142. self.received.append(self.unwrapInboundIn(data))
  143. }
  144. func channelReadComplete(context: ChannelHandlerContext) {
  145. while let part = self.received.popFirst() {
  146. switch part {
  147. case .metadata(let metadata):
  148. var filtered = Metadata()
  149. // Remove any pseudo-headers.
  150. for (key, value) in metadata where !key.hasPrefix(":") {
  151. switch value {
  152. case .string(let value):
  153. filtered.addString(value, forKey: key)
  154. case .binary(let value):
  155. filtered.addBinary(value, forKey: key)
  156. }
  157. }
  158. context.write(self.wrapOutboundOut(.metadata(filtered)), promise: nil)
  159. case .message(let message):
  160. context.write(self.wrapOutboundOut(.message(message)), promise: nil)
  161. }
  162. }
  163. if self.receivedEnd {
  164. let status = Status(code: .ok, message: "")
  165. context.write(self.wrapOutboundOut(.status(status, [:])), promise: nil)
  166. }
  167. context.flush()
  168. }
  169. }
  170. }