CallOptions.swift 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 Logging
  17. import NIOCore
  18. import NIOHPACK
  19. import NIOHTTP1
  20. import NIOHTTP2
  21. import struct Foundation.UUID
  22. /// Options to use for GRPC calls.
  23. public struct CallOptions: Sendable {
  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: Sendable {
  116. public typealias RequestIDGenerator = @Sendable () -> String
  117. private enum RequestIDSource: Sendable {
  118. case none
  119. case `static`(String)
  120. case generated(RequestIDGenerator)
  121. }
  122. private var source: RequestIDSource
  123. private init(_ source: RequestIDSource) {
  124. self.source = source
  125. }
  126. @usableFromInline
  127. internal func requestID() -> String? {
  128. switch self.source {
  129. case .none:
  130. return nil
  131. case let .static(requestID):
  132. return requestID
  133. case let .generated(generator):
  134. return generator()
  135. }
  136. }
  137. /// No request IDs are generated.
  138. public static let none = RequestIDProvider(.none)
  139. /// Generate a new request ID for each RPC.
  140. public static let autogenerated = RequestIDProvider(.generated({ UUID().uuidString }))
  141. /// Specify an ID to be used.
  142. ///
  143. /// - Important: this should only be used when ``CallOptions`` are passed directly to the call.
  144. /// If it is used for the default options on a client then all calls with have the same ID.
  145. public static func userDefined(_ requestID: String) -> RequestIDProvider {
  146. return RequestIDProvider(.static(requestID))
  147. }
  148. /// Provide a factory to generate request IDs.
  149. public static func generated(
  150. _ requestIDFactory: @escaping RequestIDGenerator
  151. ) -> RequestIDProvider {
  152. return RequestIDProvider(.generated(requestIDFactory))
  153. }
  154. }
  155. }
  156. extension CallOptions {
  157. public struct EventLoopPreference: Sendable {
  158. /// No preference. The framework will assign an `EventLoop`.
  159. public static let indifferent = EventLoopPreference(.indifferent)
  160. /// Use the provided `EventLoop` for the call.
  161. public static func exact(_ eventLoop: EventLoop) -> EventLoopPreference {
  162. return EventLoopPreference(.exact(eventLoop))
  163. }
  164. @usableFromInline
  165. internal enum Preference: Sendable {
  166. case indifferent
  167. case exact(EventLoop)
  168. }
  169. @usableFromInline
  170. internal var _preference: Preference
  171. @inlinable
  172. internal init(_ preference: Preference) {
  173. self._preference = preference
  174. }
  175. }
  176. }
  177. extension CallOptions.EventLoopPreference {
  178. @inlinable
  179. internal var exact: EventLoop? {
  180. switch self._preference {
  181. case let .exact(eventLoop):
  182. return eventLoop
  183. case .indifferent:
  184. return nil
  185. }
  186. }
  187. }