CallOptions.swift 7.5 KB

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