_FakeResponseStream.swift 13 KB

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