2
0

FakeChannel.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 Logging
  17. import NIOCore
  18. import NIOEmbedded
  19. import SwiftProtobuf
  20. // This type is deprecated, but we need to '@unchecked Sendable' to avoid warnings in our own code.
  21. @available(swift, deprecated: 5.6)
  22. extension FakeChannel: @unchecked Sendable {}
  23. /// A fake channel for use with generated test clients.
  24. ///
  25. /// The `FakeChannel` provides factories for calls which avoid most of the gRPC stack and don't do
  26. /// real networking. Each call relies on either a `FakeUnaryResponse` or a `FakeStreamingResponse`
  27. /// to get responses or errors. The fake response of each type should be registered with the channel
  28. /// prior to making a call via `makeFakeUnaryResponse` or `makeFakeStreamingResponse` respectively.
  29. ///
  30. /// Users will typically not be required to interact with the channel directly, instead they should
  31. /// do so via a generated test client.
  32. @available(
  33. swift,
  34. deprecated: 5.6,
  35. message: "GRPCChannel implementations must be Sendable but this implementation is not. Using a client and server on localhost is the recommended alternative."
  36. )
  37. public class FakeChannel: GRPCChannel {
  38. /// Fake response streams keyed by their path.
  39. private var responseStreams: [String: CircularBuffer<Any>]
  40. /// A logger.
  41. public let logger: Logger
  42. public init(logger: Logger = Logger(label: "io.grpc", factory: { _ in
  43. SwiftLogNoOpLogHandler()
  44. })) {
  45. self.responseStreams = [:]
  46. self.logger = logger
  47. }
  48. /// Make and store a fake unary response for the given path. Users should prefer making a response
  49. /// stream for their RPC directly via the appropriate method on their generated test client.
  50. public func makeFakeUnaryResponse<Request, Response>(
  51. path: String,
  52. requestHandler: @escaping (FakeRequestPart<Request>) -> Void
  53. ) -> FakeUnaryResponse<Request, Response> {
  54. let proxy = FakeUnaryResponse<Request, Response>(requestHandler: requestHandler)
  55. self.responseStreams[path, default: []].append(proxy)
  56. return proxy
  57. }
  58. /// Make and store a fake streaming response for the given path. Users should prefer making a
  59. /// response stream for their RPC directly via the appropriate method on their generated test
  60. /// client.
  61. public func makeFakeStreamingResponse<Request, Response>(
  62. path: String,
  63. requestHandler: @escaping (FakeRequestPart<Request>) -> Void
  64. ) -> FakeStreamingResponse<Request, Response> {
  65. let proxy = FakeStreamingResponse<Request, Response>(requestHandler: requestHandler)
  66. self.responseStreams[path, default: []].append(proxy)
  67. return proxy
  68. }
  69. /// Returns true if there are fake responses enqueued for the given path.
  70. public func hasFakeResponseEnqueued(forPath path: String) -> Bool {
  71. guard let noStreamsForPath = self.responseStreams[path]?.isEmpty else {
  72. return false
  73. }
  74. return !noStreamsForPath
  75. }
  76. public func makeCall<Request: Message, Response: Message>(
  77. path: String,
  78. type: GRPCCallType,
  79. callOptions: CallOptions,
  80. interceptors: [ClientInterceptor<Request, Response>]
  81. ) -> Call<Request, Response> {
  82. return self._makeCall(
  83. path: path,
  84. type: type,
  85. callOptions: callOptions,
  86. interceptors: interceptors
  87. )
  88. }
  89. public func makeCall<Request: GRPCPayload, Response: GRPCPayload>(
  90. path: String,
  91. type: GRPCCallType,
  92. callOptions: CallOptions,
  93. interceptors: [ClientInterceptor<Request, Response>]
  94. ) -> Call<Request, Response> {
  95. return self._makeCall(
  96. path: path,
  97. type: type,
  98. callOptions: callOptions,
  99. interceptors: interceptors
  100. )
  101. }
  102. private func _makeCall<Request: Message, Response: Message>(
  103. path: String,
  104. type: GRPCCallType,
  105. callOptions: CallOptions,
  106. interceptors: [ClientInterceptor<Request, Response>]
  107. ) -> Call<Request, Response> {
  108. let stream: _FakeResponseStream<Request, Response>? = self.dequeueResponseStream(forPath: path)
  109. let eventLoop = stream?.channel.eventLoop ?? EmbeddedEventLoop()
  110. return Call(
  111. path: path,
  112. type: type,
  113. eventLoop: eventLoop,
  114. options: callOptions,
  115. interceptors: interceptors,
  116. transportFactory: .fake(stream)
  117. )
  118. }
  119. private func _makeCall<Request: GRPCPayload, Response: GRPCPayload>(
  120. path: String,
  121. type: GRPCCallType,
  122. callOptions: CallOptions,
  123. interceptors: [ClientInterceptor<Request, Response>]
  124. ) -> Call<Request, Response> {
  125. let stream: _FakeResponseStream<Request, Response>? = self.dequeueResponseStream(forPath: path)
  126. let eventLoop = stream?.channel.eventLoop ?? EmbeddedEventLoop()
  127. return Call(
  128. path: path,
  129. type: type,
  130. eventLoop: eventLoop,
  131. options: callOptions,
  132. interceptors: interceptors,
  133. transportFactory: .fake(stream)
  134. )
  135. }
  136. public func close() -> EventLoopFuture<Void> {
  137. // We don't have anything to close.
  138. return EmbeddedEventLoop().makeSucceededFuture(())
  139. }
  140. }
  141. @available(swift, deprecated: 5.6)
  142. extension FakeChannel {
  143. /// Dequeue a proxy for the given path and casts it to the given type, if one exists.
  144. private func dequeueResponseStream<Stream>(
  145. forPath path: String,
  146. as: Stream.Type = Stream.self
  147. ) -> Stream? {
  148. guard var streams = self.responseStreams[path], !streams.isEmpty else {
  149. return nil
  150. }
  151. // This is fine: we know we're non-empty.
  152. let first = streams.removeFirst()
  153. self.responseStreams.updateValue(streams, forKey: path)
  154. return first as? Stream
  155. }
  156. private func makeRequestHead(path: String, callOptions: CallOptions) -> _GRPCRequestHead {
  157. return _GRPCRequestHead(
  158. scheme: "http",
  159. path: path,
  160. host: "localhost",
  161. options: callOptions,
  162. requestID: nil
  163. )
  164. }
  165. }