ClientTransportTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /*
  2. * Copyright 2020, 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. @testable import GRPC
  17. import NIO
  18. import XCTest
  19. class ClientTransportTests: GRPCTestCase {
  20. override func setUp() {
  21. super.setUp()
  22. self.channel = EmbeddedChannel()
  23. }
  24. // MARK: - Setup Helpers
  25. private func makeDetails(type: GRPCCallType = .unary) -> CallDetails {
  26. return CallDetails(
  27. type: type,
  28. path: "/echo.Echo/Get",
  29. authority: "localhost",
  30. scheme: "https",
  31. options: .init(logger: self.logger)
  32. )
  33. }
  34. private var channel: EmbeddedChannel!
  35. private var transport: ClientTransport<String, String>!
  36. private var eventLoop: EventLoop {
  37. return self.channel.eventLoop
  38. }
  39. private func setUpTransport(
  40. details: CallDetails? = nil,
  41. interceptors: [ClientInterceptor<String, String>] = [],
  42. onError: @escaping (Error) -> Void = { _ in },
  43. onResponsePart: @escaping (GRPCClientResponsePart<String>) -> Void = { _ in }
  44. ) {
  45. self.transport = .init(
  46. details: details ?? self.makeDetails(),
  47. eventLoop: self.eventLoop,
  48. interceptors: interceptors,
  49. serializer: AnySerializer(wrapping: StringSerializer()),
  50. deserializer: AnyDeserializer(wrapping: StringDeserializer()),
  51. errorDelegate: nil,
  52. onError: onError,
  53. onResponsePart: onResponsePart
  54. )
  55. }
  56. private func configureTransport(additionalHandlers handlers: [ChannelHandler] = []) {
  57. self.transport.configure {
  58. var handlers = handlers
  59. handlers.append(
  60. GRPCClientReverseCodecHandler(
  61. serializer: StringSerializer(),
  62. deserializer: StringDeserializer()
  63. )
  64. )
  65. handlers.append($0)
  66. return self.channel.pipeline.addHandlers(handlers)
  67. }
  68. }
  69. private func configureTransport(_ body: @escaping (ChannelHandler) -> EventLoopFuture<Void>) {
  70. self.transport.configure(body)
  71. }
  72. private func connect(file: StaticString = #file, line: UInt = #line) throws {
  73. let address = try assertNoThrow(SocketAddress(unixDomainSocketPath: "/whatever"))
  74. assertThat(
  75. try self.channel.connect(to: address).wait(),
  76. .doesNotThrow(),
  77. file: file,
  78. line: line
  79. )
  80. }
  81. private func sendRequest(
  82. _ part: GRPCClientRequestPart<String>,
  83. promise: EventLoopPromise<Void>? = nil
  84. ) {
  85. self.transport.send(part, promise: promise)
  86. }
  87. private func cancel(promise: EventLoopPromise<Void>? = nil) {
  88. self.transport.cancel(promise: promise)
  89. }
  90. private func sendResponse(
  91. _ part: _GRPCClientResponsePart<String>,
  92. file: StaticString = #file,
  93. line: UInt = #line
  94. ) throws {
  95. assertThat(try self.channel.writeInbound(part), .doesNotThrow(), file: file, line: line)
  96. }
  97. }
  98. // MARK: - Tests
  99. extension ClientTransportTests {
  100. func testUnaryFlow() throws {
  101. let recorder = WriteRecorder<_GRPCClientRequestPart<String>>()
  102. let recorderInterceptor = RecordingInterceptor<String, String>()
  103. self.setUpTransport(interceptors: [recorderInterceptor])
  104. // Buffer up some parts.
  105. self.sendRequest(.metadata([:]))
  106. self.sendRequest(.message("0", .init(compress: false, flush: false)))
  107. // Configure the transport and connect. This will unbuffer the parts.
  108. self.configureTransport(additionalHandlers: [recorder])
  109. try self.connect()
  110. // Send the end, this shouldn't require buffering.
  111. self.sendRequest(.end)
  112. // We should have recorded 3 parts in the 'Channel' now.
  113. assertThat(recorder.writes, .hasCount(3))
  114. // Write some responses.
  115. try self.sendResponse(.initialMetadata([:]))
  116. try self.sendResponse(.message(.init("1", compressed: false)))
  117. try self.sendResponse(.trailingMetadata([:]))
  118. try self.sendResponse(.status(.ok))
  119. // The recording interceptor should now have three parts.
  120. assertThat(recorderInterceptor.responseParts, .hasCount(3))
  121. }
  122. func testCancelWhenIdle() throws {
  123. // Set up the transport, configure it and connect.
  124. self.setUpTransport(onError: { error in
  125. assertThat(error, .is(.instanceOf(GRPCError.RPCCancelledByClient.self)))
  126. })
  127. // Cancellation should succeed.
  128. let promise = self.eventLoop.makePromise(of: Void.self)
  129. self.cancel(promise: promise)
  130. assertThat(try promise.futureResult.wait(), .doesNotThrow())
  131. }
  132. func testCancelWhenAwaitingTransport() throws {
  133. // Set up the transport, configure it and connect.
  134. self.setUpTransport(onError: { error in
  135. assertThat(error, .is(.instanceOf(GRPCError.RPCCancelledByClient.self)))
  136. })
  137. // Start configuring the transport.
  138. let transportActivatedPromise = self.eventLoop.makePromise(of: Void.self)
  139. // Let's not leak this.
  140. defer {
  141. transportActivatedPromise.succeed(())
  142. }
  143. self.configureTransport { handler in
  144. self.channel.pipeline.addHandler(handler).flatMap {
  145. transportActivatedPromise.futureResult
  146. }
  147. }
  148. // Write a request.
  149. let p1 = self.eventLoop.makePromise(of: Void.self)
  150. self.sendRequest(.metadata([:]), promise: p1)
  151. let p2 = self.eventLoop.makePromise(of: Void.self)
  152. self.cancel(promise: p2)
  153. // Cancellation should succeed, and fail the write as a result.
  154. assertThat(try p2.futureResult.wait(), .doesNotThrow())
  155. assertThat(
  156. try p1.futureResult.wait(),
  157. .throws(.instanceOf(GRPCError.RPCCancelledByClient.self))
  158. )
  159. }
  160. func testCancelWhenActivating() throws {
  161. // Set up the transport, configure it and connect.
  162. // We use bidirectional streaming here so that we also flush after writing the metadata.
  163. self.setUpTransport(
  164. details: self.makeDetails(type: .bidirectionalStreaming),
  165. onError: { error in
  166. assertThat(error, .is(.instanceOf(GRPCError.RPCCancelledByClient.self)))
  167. }
  168. )
  169. // Write a request. This will buffer.
  170. let writePromise1 = self.eventLoop.makePromise(of: Void.self)
  171. self.sendRequest(.metadata([:]), promise: writePromise1)
  172. // Chain a cancel from the first write promise.
  173. let cancelPromise = self.eventLoop.makePromise(of: Void.self)
  174. writePromise1.futureResult.whenSuccess {
  175. self.cancel(promise: cancelPromise)
  176. }
  177. // Enqueue a second write.
  178. let writePromise2 = self.eventLoop.makePromise(of: Void.self)
  179. self.sendRequest(.message("foo", .init(compress: false, flush: false)), promise: writePromise2)
  180. // Now we can configure and connect to trigger the unbuffering.
  181. // We don't actually want to record writes, by the recorder will fulfill promises as we catch
  182. // them; and we need that.
  183. self.configureTransport(additionalHandlers: [WriteRecorder<_GRPCClientRequestPart<String>>()])
  184. try self.connect()
  185. // The first write should succeed.
  186. assertThat(try writePromise1.futureResult.wait(), .doesNotThrow())
  187. // As should the cancellation.
  188. assertThat(try cancelPromise.futureResult.wait(), .doesNotThrow())
  189. // The second write should fail: the cancellation happened first.
  190. assertThat(
  191. try writePromise2.futureResult.wait(),
  192. .throws(.instanceOf(GRPCError.RPCCancelledByClient.self))
  193. )
  194. }
  195. func testCancelWhenActive() throws {
  196. // Set up the transport, configure it and connect. We'll record request parts in the `Channel`.
  197. let recorder = WriteRecorder<_GRPCClientRequestPart<String>>()
  198. self.setUpTransport()
  199. self.configureTransport(additionalHandlers: [recorder])
  200. try self.connect()
  201. // We should have an active transport now.
  202. self.sendRequest(.metadata([:]))
  203. self.sendRequest(.message("0", .init(compress: false, flush: false)))
  204. // We should have picked these parts up in the recorder.
  205. assertThat(recorder.writes, .hasCount(2))
  206. // Let's cancel now.
  207. let promise = self.eventLoop.makePromise(of: Void.self)
  208. self.cancel(promise: promise)
  209. // Cancellation should succeed.
  210. assertThat(try promise.futureResult.wait(), .doesNotThrow())
  211. }
  212. func testCancelWhenClosing() throws {
  213. self.setUpTransport()
  214. // Hold the configuration until we succeed the promise.
  215. let configuredPromise = self.eventLoop.makePromise(of: Void.self)
  216. self.configureTransport { handler in
  217. self.channel.pipeline.addHandler(handler).flatMap {
  218. configuredPromise.futureResult
  219. }
  220. }
  221. }
  222. func testCancelWhenClosed() throws {
  223. // Setup and close immediately.
  224. self.setUpTransport()
  225. self.configureTransport()
  226. try self.connect()
  227. assertThat(try self.channel.close().wait(), .doesNotThrow())
  228. // Let's cancel now.
  229. let promise = self.eventLoop.makePromise(of: Void.self)
  230. self.cancel(promise: promise)
  231. // Cancellation should fail, we're already closed.
  232. assertThat(
  233. try promise.futureResult.wait(),
  234. .throws(.instanceOf(GRPCError.AlreadyComplete.self))
  235. )
  236. }
  237. func testErrorWhenActive() throws {
  238. // Setup the transport, we only expect an error back.
  239. self.setUpTransport(onError: { error in
  240. assertThat(error, .is(.instanceOf(DummyError.self)))
  241. })
  242. // Configure and activate.
  243. self.configureTransport()
  244. try self.connect()
  245. // Send a request.
  246. let p1 = self.eventLoop.makePromise(of: Void.self)
  247. self.sendRequest(.metadata([:]), promise: p1)
  248. // The transport is for a unary call, so we need to send '.end' to emit a flush and for the
  249. // promise to be completed.
  250. self.sendRequest(.end, promise: nil)
  251. assertThat(try p1.futureResult.wait(), .doesNotThrow())
  252. // Fire an error back. (We'll see an error on the response handler.)
  253. self.channel.pipeline.fireErrorCaught(DummyError())
  254. // Writes should now fail, we're closed.
  255. let p2 = self.eventLoop.makePromise(of: Void.self)
  256. self.sendRequest(.end, promise: p2)
  257. assertThat(try p2.futureResult.wait(), .throws(.instanceOf(GRPCError.AlreadyComplete.self)))
  258. }
  259. func testConfigurationFails() throws {
  260. self.setUpTransport()
  261. let p1 = self.eventLoop.makePromise(of: Void.self)
  262. self.sendRequest(.metadata([:]), promise: p1)
  263. let p2 = self.eventLoop.makePromise(of: Void.self)
  264. self.sendRequest(.message("0", .init(compress: false, flush: false)), promise: p2)
  265. // Fail to configure the transport. Our promises should fail.
  266. self.configureTransport { _ in
  267. self.eventLoop.makeFailedFuture(DummyError())
  268. }
  269. // The promises should fail.
  270. assertThat(try p1.futureResult.wait(), .throws())
  271. assertThat(try p2.futureResult.wait(), .throws())
  272. // Cancellation should also fail because we're already closed.
  273. let p3 = self.eventLoop.makePromise(of: Void.self)
  274. self.transport.cancel(promise: p3)
  275. assertThat(try p3.futureResult.wait(), .throws(.instanceOf(GRPCError.AlreadyComplete.self)))
  276. }
  277. }
  278. // MARK: - Helper Objects
  279. class WriteRecorder<Write>: ChannelOutboundHandler {
  280. typealias OutboundIn = Write
  281. var writes: [Write] = []
  282. func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  283. self.writes.append(self.unwrapOutboundIn(data))
  284. promise?.succeed(())
  285. }
  286. }
  287. private struct DummyError: Error {}
  288. internal struct StringSerializer: MessageSerializer {
  289. typealias Input = String
  290. func serialize(_ input: String, allocator: ByteBufferAllocator) throws -> ByteBuffer {
  291. return allocator.buffer(string: input)
  292. }
  293. }
  294. internal struct StringDeserializer: MessageDeserializer {
  295. typealias Output = String
  296. func deserialize(byteBuffer: ByteBuffer) throws -> String {
  297. var buffer = byteBuffer
  298. return buffer.readString(length: buffer.readableBytes)!
  299. }
  300. }
  301. internal struct ThrowingStringSerializer: MessageSerializer {
  302. typealias Input = String
  303. func serialize(_ input: String, allocator: ByteBufferAllocator) throws -> ByteBuffer {
  304. throw DummyError()
  305. }
  306. }
  307. internal struct ThrowingStringDeserializer: MessageDeserializer {
  308. typealias Output = String
  309. func deserialize(byteBuffer: ByteBuffer) throws -> String {
  310. throw DummyError()
  311. }
  312. }