CallOptions.swift 7.5 KB

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