CallOptions.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. /*
  2. * Copyright 2019, 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 struct Foundation.UUID
  17. import NIOCore
  18. import Logging
  19. import NIOHPACK
  20. import NIOHTTP1
  21. import NIOHTTP2
  22. /// Options to use for GRPC calls.
  23. public struct CallOptions: GRPCSendable {
  24. /// Additional metadata to send to the service.
  25. public var customMetadata: HPACKHeaders
  26. /// The time limit for the RPC.
  27. ///
  28. /// - Note: timeouts are treated as deadlines as soon as an RPC has been invoked.
  29. public var timeLimit: TimeLimit
  30. /// The compression used for requests, and the compression algorithms to advertise as acceptable
  31. /// for the remote peer to use for encoding responses.
  32. ///
  33. /// Compression may also be disabled at the message-level for streaming requests (i.e. client
  34. /// streaming and bidirectional streaming RPCs) by setting `compression` to ``Compression/disabled`` in
  35. /// ``StreamingRequestClientCall/sendMessage(_:compression:)-uvtc``,
  36. /// ``StreamingRequestClientCall/sendMessage(_:compression:promise:)`` ,
  37. /// ``StreamingRequestClientCall/sendMessages(_:compression:)-55vb3`` or
  38. /// ``StreamingRequestClientCall/sendMessage(_:compression:promise:)`.
  39. ///
  40. /// Note that enabling `compression` via the `sendMessage` or `sendMessages` methods only applies
  41. /// if encoding has been specified in these options.
  42. public var messageEncoding: ClientMessageEncoding
  43. /// Whether the call is cacheable.
  44. public var cacheable: Bool
  45. /// How IDs should be provided for requests. Defaults to ``RequestIDProvider-swift.struct/autogenerated``.
  46. ///
  47. /// The request ID is used for logging and will be added to the headers of a call if
  48. /// `requestIDHeader` is specified.
  49. ///
  50. /// - Important: When setting ``CallOptions`` at the client level, ``RequestIDProvider-swift.struct/userDefined(_:)`` should __not__ be
  51. /// used otherwise each request will have the same ID.
  52. public var requestIDProvider: RequestIDProvider
  53. /// The name of the header to use when adding a request ID to a call, e.g. "x-request-id". If the
  54. /// value is `nil` (the default) then no additional header will be added.
  55. ///
  56. /// Setting this value will add a request ID to the headers of the call these options are used
  57. /// with. The request ID will be provided by ``requestIDProvider-swift.property`` and will also be used in log
  58. /// messages associated with the call.
  59. public var requestIDHeader: String?
  60. /// A preference for the `EventLoop` that the call is executed on.
  61. ///
  62. /// The `EventLoop` resulting from the preference will be used to create any `EventLoopFuture`s
  63. /// associated with the call, such as the `response` for calls with a single response (i.e. unary
  64. /// and client streaming). For calls which stream responses (server streaming and bidirectional
  65. /// streaming) the response handler is executed on this event loop.
  66. ///
  67. /// Note that the underlying connection is not guaranteed to run on the same event loop.
  68. public var eventLoopPreference: EventLoopPreference
  69. /// A logger used for the call. Defaults to a no-op logger.
  70. ///
  71. /// If a ``requestIDProvider-swift.property`` exists then a request ID will automatically attached to the logger's
  72. /// metadata using the 'grpc-request-id' key.
  73. public var logger: Logger
  74. public init(
  75. customMetadata: HPACKHeaders = HPACKHeaders(),
  76. timeLimit: TimeLimit = .none,
  77. messageEncoding: ClientMessageEncoding = .disabled,
  78. requestIDProvider: RequestIDProvider = .autogenerated,
  79. requestIDHeader: String? = nil,
  80. cacheable: Bool = false,
  81. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  82. ) {
  83. self.init(
  84. customMetadata: customMetadata,
  85. timeLimit: timeLimit,
  86. messageEncoding: messageEncoding,
  87. requestIDProvider: requestIDProvider,
  88. requestIDHeader: requestIDHeader,
  89. eventLoopPreference: .indifferent,
  90. cacheable: cacheable,
  91. logger: logger
  92. )
  93. }
  94. public init(
  95. customMetadata: HPACKHeaders = HPACKHeaders(),
  96. timeLimit: TimeLimit = .none,
  97. messageEncoding: ClientMessageEncoding = .disabled,
  98. requestIDProvider: RequestIDProvider = .autogenerated,
  99. requestIDHeader: String? = nil,
  100. eventLoopPreference: EventLoopPreference,
  101. cacheable: Bool = false,
  102. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  103. ) {
  104. self.customMetadata = customMetadata
  105. self.messageEncoding = messageEncoding
  106. self.requestIDProvider = requestIDProvider
  107. self.requestIDHeader = requestIDHeader
  108. self.cacheable = cacheable
  109. self.timeLimit = timeLimit
  110. self.logger = logger
  111. self.eventLoopPreference = eventLoopPreference
  112. }
  113. }
  114. extension CallOptions {
  115. public struct RequestIDProvider: GRPCSendable {
  116. #if swift(>=5.6)
  117. public typealias RequestIDGenerator = @Sendable () -> String
  118. #else
  119. public typealias RequestIDGenerator = () -> String
  120. #endif // swift(>=5.6)
  121. private enum RequestIDSource: GRPCSendable {
  122. case none
  123. case `static`(String)
  124. case generated(RequestIDGenerator)
  125. }
  126. private var source: RequestIDSource
  127. private init(_ source: RequestIDSource) {
  128. self.source = source
  129. }
  130. @usableFromInline
  131. internal func requestID() -> String? {
  132. switch self.source {
  133. case .none:
  134. return nil
  135. case let .static(requestID):
  136. return requestID
  137. case let .generated(generator):
  138. return generator()
  139. }
  140. }
  141. /// No request IDs are generated.
  142. public static let none = RequestIDProvider(.none)
  143. /// Generate a new request ID for each RPC.
  144. public static let autogenerated = RequestIDProvider(.generated({ UUID().uuidString }))
  145. /// Specify an ID to be used.
  146. ///
  147. /// - Important: this should only be used when ``CallOptions`` are passed directly to the call.
  148. /// If it is used for the default options on a client then all calls with have the same ID.
  149. public static func userDefined(_ requestID: String) -> RequestIDProvider {
  150. return RequestIDProvider(.static(requestID))
  151. }
  152. /// Provide a factory to generate request IDs.
  153. public static func generated(
  154. _ requestIDFactory: @escaping RequestIDGenerator
  155. ) -> RequestIDProvider {
  156. return RequestIDProvider(.generated(requestIDFactory))
  157. }
  158. }
  159. }
  160. extension CallOptions {
  161. public struct EventLoopPreference: GRPCSendable {
  162. /// No preference. The framework will assign an `EventLoop`.
  163. public static let indifferent = EventLoopPreference(.indifferent)
  164. /// Use the provided `EventLoop` for the call.
  165. public static func exact(_ eventLoop: EventLoop) -> EventLoopPreference {
  166. return EventLoopPreference(.exact(eventLoop))
  167. }
  168. @usableFromInline
  169. internal enum Preference: GRPCSendable {
  170. case indifferent
  171. case exact(EventLoop)
  172. }
  173. @usableFromInline
  174. internal var _preference: Preference
  175. @inlinable
  176. internal init(_ preference: Preference) {
  177. self._preference = preference
  178. }
  179. }
  180. }
  181. extension CallOptions.EventLoopPreference {
  182. @inlinable
  183. internal var exact: EventLoop? {
  184. switch self._preference {
  185. case let .exact(eventLoop):
  186. return eventLoop
  187. case .indifferent:
  188. return nil
  189. }
  190. }
  191. }