_FakeResponseStream.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. import NIO
  17. import NIOHPACK
  18. public enum FakeRequestPart<Request> {
  19. case metadata(HPACKHeaders)
  20. case message(Request)
  21. case end
  22. }
  23. extension FakeRequestPart: Equatable where Request: Equatable {}
  24. /// Sending on a fake response stream would have resulted in a protocol violation (such as
  25. /// sending initial metadata multiple times or sending messages after the stream has closed).
  26. public struct FakeResponseProtocolViolation: Error, Hashable {
  27. /// The reason that sending the message would have resulted in a protocol violation.
  28. public var reason: String
  29. init(_ reason: String) {
  30. self.reason = reason
  31. }
  32. }
  33. /// A fake response stream into which users may inject response parts for use in unit tests.
  34. ///
  35. /// Users may not interact with this class directly but may do so via one of its subclasses
  36. /// `FakeUnaryResponse` and `FakeStreamingResponse`.
  37. public class _FakeResponseStream<Request, Response> {
  38. private enum StreamEvent {
  39. case responsePart(_GRPCClientResponsePart<Response>)
  40. case error(Error)
  41. }
  42. /// The channel to use for communication.
  43. internal let channel: EmbeddedChannel
  44. /// A buffer to hold responses in before the proxy is activated.
  45. private var responseBuffer: CircularBuffer<StreamEvent>
  46. /// The current state of the proxy.
  47. private var activeState: ActiveState
  48. /// The state of sending response parts.
  49. private var sendState: SendState
  50. private enum ActiveState {
  51. case inactive
  52. case active
  53. }
  54. private enum SendState {
  55. // Nothing has been sent; we can send initial metadata to become 'sending' or trailing metadata
  56. // to start 'closing'.
  57. case idle
  58. // We're sending messages. We can send more messages in this state or trailing metadata to
  59. // transition to 'closing'.
  60. case sending
  61. // We're closing: we've sent trailing metadata, we may only send a status now to close.
  62. case closing
  63. // Closed, nothing more can be sent.
  64. case closed
  65. }
  66. internal init(requestHandler: @escaping (FakeRequestPart<Request>) -> Void) {
  67. self.activeState = .inactive
  68. self.sendState = .idle
  69. self.responseBuffer = CircularBuffer()
  70. self.channel = EmbeddedChannel(handler: WriteCapturingHandler(requestHandler: requestHandler))
  71. }
  72. /// Activate the test proxy; this should be called
  73. internal func activate() {
  74. switch self.activeState {
  75. case .inactive:
  76. // Activate the channel. This will allow any request parts to be sent.
  77. self.channel.pipeline.fireChannelActive()
  78. // Unbuffer any response parts.
  79. while !self.responseBuffer.isEmpty {
  80. self.write(self.responseBuffer.removeFirst())
  81. }
  82. // Now we're active.
  83. self.activeState = .active
  84. case .active:
  85. ()
  86. }
  87. }
  88. /// Write or buffer the response part, depending on the our current state.
  89. internal func _sendResponsePart(_ part: _GRPCClientResponsePart<Response>) throws {
  90. try self.send(.responsePart(part))
  91. }
  92. internal func _sendError(_ error: Error) throws {
  93. try self.send(.error(error))
  94. }
  95. private func send(_ event: StreamEvent) throws {
  96. switch self.validate(event) {
  97. case .valid:
  98. self.writeOrBuffer(event)
  99. case let .validIfSentAfter(extraPart):
  100. self.writeOrBuffer(extraPart)
  101. self.writeOrBuffer(event)
  102. case let .invalid(reason):
  103. throw FakeResponseProtocolViolation(reason)
  104. }
  105. }
  106. /// Validate events the user wants to send on the stream.
  107. private func validate(_ event: StreamEvent) -> Validation {
  108. switch (event, self.sendState) {
  109. case (.responsePart(.initialMetadata), .idle):
  110. self.sendState = .sending
  111. return .valid
  112. case (.responsePart(.initialMetadata), .sending),
  113. (.responsePart(.initialMetadata), .closing),
  114. (.responsePart(.initialMetadata), .closed):
  115. // We can only send initial metadata from '.idle'.
  116. return .invalid(reason: "Initial metadata has already been sent")
  117. case (.responsePart(.message), .idle):
  118. // This is fine: we don't force the user to specify initial metadata so we send some on their
  119. // behalf.
  120. self.sendState = .sending
  121. return .validIfSentAfter(.responsePart(.initialMetadata([:])))
  122. case (.responsePart(.message), .sending):
  123. return .valid
  124. case (.responsePart(.message), .closing),
  125. (.responsePart(.message), .closed):
  126. // We can't send messages once we're closing or closed.
  127. return .invalid(reason: "Messages can't be sent after the stream has been closed")
  128. case (.responsePart(.trailingMetadata), .idle),
  129. (.responsePart(.trailingMetadata), .sending):
  130. self.sendState = .closing
  131. return .valid
  132. case (.responsePart(.trailingMetadata), .closing),
  133. (.responsePart(.trailingMetadata), .closed):
  134. // We're already closing or closed.
  135. return .invalid(reason: "Trailing metadata can't be sent after the stream has been closed")
  136. case (.responsePart(.status), .idle),
  137. (.error, .idle),
  138. (.responsePart(.status), .sending),
  139. (.error, .sending),
  140. (.responsePart(.status), .closed),
  141. (.error, .closed):
  142. // We can only error/close if we're closing (i.e. have already sent trailers which we enforce
  143. // from the API in the subclasses).
  144. return .invalid(reason: "Status/error can only be sent after trailing metadata has been sent")
  145. case (.responsePart(.status), .closing),
  146. (.error, .closing):
  147. self.sendState = .closed
  148. return .valid
  149. }
  150. }
  151. private enum Validation {
  152. /// Sending the part is valid.
  153. case valid
  154. /// Sending the part, if it is sent after the given part.
  155. case validIfSentAfter(_ part: StreamEvent)
  156. /// Sending the part would be a protocol violation.
  157. case invalid(reason: String)
  158. }
  159. private func writeOrBuffer(_ event: StreamEvent) {
  160. switch self.activeState {
  161. case .inactive:
  162. self.responseBuffer.append(event)
  163. case .active:
  164. self.write(event)
  165. }
  166. }
  167. private func write(_ part: StreamEvent) {
  168. switch part {
  169. case let .error(error):
  170. self.channel.pipeline.fireErrorCaught(error)
  171. case let .responsePart(responsePart):
  172. // We tolerate errors here: an error will be thrown if the write results in an error which
  173. // isn't caught in the channel. Errors in the channel get funnelled into the transport held
  174. // by the actual call object and handled there.
  175. _ = try? self.channel.writeInbound(responsePart)
  176. }
  177. }
  178. }
  179. // MARK: - Unary Response
  180. /// A fake unary response to be used with a generated test client.
  181. ///
  182. /// Users typically create fake responses via helper methods on their generated test clients
  183. /// corresponding to the RPC which they intend to test.
  184. ///
  185. /// For unary responses users may call one of two functions for each RPC:
  186. /// - `sendMessage(_:initialMetadata:trailingMetadata:status)`, or
  187. /// - `sendError(status:trailingMetadata)`
  188. ///
  189. /// `sendMessage` sends a normal unary response with the provided message and allows the caller to
  190. /// also specify initial metadata, trailing metadata and the status. Both metadata arguments are
  191. /// empty by default and the status defaults to one with an 'ok' status code.
  192. ///
  193. /// `sendError` may be used to terminate an RPC without providing a response. As for `sendMessage`,
  194. /// the `trailingMetadata` defaults to being empty.
  195. public class FakeUnaryResponse<Request, Response>: _FakeResponseStream<Request, Response> {
  196. override public init(requestHandler: @escaping (FakeRequestPart<Request>) -> Void = { _ in }) {
  197. super.init(requestHandler: requestHandler)
  198. }
  199. /// Send a response message to the client.
  200. ///
  201. /// - Parameters:
  202. /// - response: The message to send.
  203. /// - initialMetadata: The initial metadata to send. By default the metadata will be empty.
  204. /// - trailingMetadata: The trailing metadata to send. By default the metadata will be empty.
  205. /// - status: The status to send. By default this has an '.ok' status code.
  206. /// - Throws: FakeResponseProtocolViolation if sending the message would violate the gRPC
  207. /// protocol, e.g. sending messages after the RPC has ended.
  208. public func sendMessage(
  209. _ response: Response,
  210. initialMetadata: HPACKHeaders = [:],
  211. trailingMetadata: HPACKHeaders = [:],
  212. status: GRPCStatus = .ok
  213. ) throws {
  214. try self._sendResponsePart(.initialMetadata(initialMetadata))
  215. try self._sendResponsePart(.message(.init(response, compressed: false)))
  216. try self._sendResponsePart(.trailingMetadata(trailingMetadata))
  217. try self._sendResponsePart(.status(status))
  218. }
  219. /// Send an error to the client.
  220. ///
  221. /// - Parameters:
  222. /// - error: The error to send.
  223. /// - trailingMetadata: The trailing metadata to send. By default the metadata will be empty.
  224. public func sendError(_ error: Error, trailingMetadata: HPACKHeaders = [:]) throws {
  225. try self._sendResponsePart(.trailingMetadata(trailingMetadata))
  226. try self._sendError(error)
  227. }
  228. }
  229. // MARK: - Streaming Response
  230. /// A fake streaming response to be used with a generated test client.
  231. ///
  232. /// Users typically create fake responses via helper methods on their generated test clients
  233. /// corresponding to the RPC which they intend to test.
  234. ///
  235. /// For streaming responses users have a number of methods available to them:
  236. /// - `sendInitialMetadata(_:)`
  237. /// - `sendMessage(_:)`
  238. /// - `sendEnd(status:trailingMetadata:)`
  239. /// - `sendError(_:trailingMetadata)`
  240. ///
  241. /// `sendInitialMetadata` may be called to send initial metadata to the client, however, it
  242. /// must be called first in order for the metadata to be sent. If it is not called, empty
  243. /// metadata will be sent automatically if necessary.
  244. ///
  245. /// `sendMessage` may be called to send a response message on the stream. This may be called
  246. /// multiple times. Messages will be ignored if this is called after `sendEnd` or `sendError`.
  247. ///
  248. /// `sendEnd` indicates that the response stream has closed. It – or `sendError` - must be called
  249. /// once. The `status` defaults to a value with the `ok` code and `trailingMetadata` is empty by
  250. /// default.
  251. ///
  252. /// `sendError` may be called at any time to indicate an error on the response stream.
  253. /// Like `sendEnd`, `trailingMetadata` is empty by default.
  254. public class FakeStreamingResponse<Request, Response>: _FakeResponseStream<Request, Response> {
  255. override public init(requestHandler: @escaping (FakeRequestPart<Request>) -> Void = { _ in }) {
  256. super.init(requestHandler: requestHandler)
  257. }
  258. /// Send initial metadata to the client.
  259. ///
  260. /// Note that calling this function is not required; empty initial metadata will be sent
  261. /// automatically if necessary.
  262. ///
  263. /// - Parameter metadata: The metadata to send
  264. /// - Throws: FakeResponseProtocolViolation if sending initial metadata would violate the gRPC
  265. /// protocol, e.g. sending metadata too many times, or out of order.
  266. public func sendInitialMetadata(_ metadata: HPACKHeaders) throws {
  267. try self._sendResponsePart(.initialMetadata(metadata))
  268. }
  269. /// Send a response message to the client.
  270. ///
  271. /// - Parameter response: The response to send.
  272. /// - Throws: FakeResponseProtocolViolation if sending the message would violate the gRPC
  273. /// protocol, e.g. sending messages after the RPC has ended.
  274. public func sendMessage(_ response: Response) throws {
  275. try self._sendResponsePart(.message(.init(response, compressed: false)))
  276. }
  277. /// Send the RPC status and trailing metadata to the client.
  278. ///
  279. /// - Parameters:
  280. /// - status: The status to send. By default the status code will be '.ok'.
  281. /// - trailingMetadata: The trailing metadata to send. Empty by default.
  282. /// - Throws: FakeResponseProtocolViolation if ending the RPC would violate the gRPC
  283. /// protocol, e.g. sending end after the RPC has already completed.
  284. public func sendEnd(status: GRPCStatus = .ok, trailingMetadata: HPACKHeaders = [:]) throws {
  285. try self._sendResponsePart(.trailingMetadata(trailingMetadata))
  286. try self._sendResponsePart(.status(status))
  287. }
  288. /// Send an error to the client.
  289. ///
  290. /// - Parameters:
  291. /// - error: The error to send.
  292. /// - trailingMetadata: The trailing metadata to send. By default the metadata will be empty.
  293. /// - Throws: FakeResponseProtocolViolation if sending the error would violate the gRPC
  294. /// protocol, e.g. erroring after the RPC has already completed.
  295. public func sendError(_ error: Error, trailingMetadata: HPACKHeaders = [:]) throws {
  296. try self._sendResponsePart(.trailingMetadata(trailingMetadata))
  297. try self._sendError(error)
  298. }
  299. }