ClientTransportTests.swift 12 KB

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