CallOptions.swift 7.1 KB

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