_FakeResponseStream.swift 12 KB

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