ServiceConfig.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. * Copyright 2024, 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. /// Service configuration values.
  17. ///
  18. /// See also: https://github.com/grpc/grpc-proto/blob/master/grpc/service_config/service_config.proto
  19. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  20. public struct ServiceConfig: Hashable, Sendable {
  21. /// Per-method configuration.
  22. public var methodConfig: [MethodConfig]
  23. /// Load balancing policies.
  24. ///
  25. /// The client iterates through the list in order and picks the first configuration it supports.
  26. /// If no policies are supported then the configuration is considered to be invalid.
  27. public var loadBalancingConfig: [LoadBalancingConfig]
  28. /// The policy for throttling retries.
  29. ///
  30. /// If ``RetryThrottling`` is provided, gRPC will automatically throttle retry attempts
  31. /// and hedged RPCs when the client's ratio of failures to successes exceeds a threshold.
  32. ///
  33. /// For each server name, the gRPC client will maintain a `token_count` which is initially set
  34. /// to ``RetryThrottling-swift.struct/maxTokens``. Every outgoing RPC (regardless of service or
  35. /// method invoked) will change `token_count` as follows:
  36. ///
  37. /// - Every failed RPC will decrement the `token_count` by 1.
  38. /// - Every successful RPC will increment the `token_count` by
  39. /// ``RetryThrottling-swift.struct/tokenRatio``.
  40. ///
  41. /// If `token_count` is less than or equal to `max_tokens / 2`, then RPCs will not be retried
  42. /// and hedged RPCs will not be sent.
  43. public var retryThrottling: RetryThrottling?
  44. /// Creates a new ``ServiceConfig``.
  45. ///
  46. /// - Parameters:
  47. /// - methodConfig: Per-method configuration.
  48. /// - loadBalancingConfig: Load balancing policies. Clients use the the first supported
  49. /// policy when iterating the list in order.
  50. /// - retryThrottling: Policy for throttling retries.
  51. public init(
  52. methodConfig: [MethodConfig] = [],
  53. loadBalancingConfig: [LoadBalancingConfig] = [],
  54. retryThrottling: RetryThrottling? = nil
  55. ) {
  56. self.methodConfig = methodConfig
  57. self.loadBalancingConfig = loadBalancingConfig
  58. self.retryThrottling = retryThrottling
  59. }
  60. }
  61. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  62. extension ServiceConfig: Codable {
  63. private enum CodingKeys: String, CodingKey {
  64. case methodConfig
  65. case loadBalancingConfig
  66. case retryThrottling
  67. }
  68. public init(from decoder: any Decoder) throws {
  69. let container = try decoder.container(keyedBy: CodingKeys.self)
  70. let methodConfig = try container.decodeIfPresent(
  71. [MethodConfig].self,
  72. forKey: .methodConfig
  73. )
  74. self.methodConfig = methodConfig ?? []
  75. let loadBalancingConfiguration = try container.decodeIfPresent(
  76. [LoadBalancingConfig].self,
  77. forKey: .loadBalancingConfig
  78. )
  79. self.loadBalancingConfig = loadBalancingConfiguration ?? []
  80. self.retryThrottling = try container.decodeIfPresent(
  81. RetryThrottling.self,
  82. forKey: .retryThrottling
  83. )
  84. }
  85. public func encode(to encoder: any Encoder) throws {
  86. var container = encoder.container(keyedBy: CodingKeys.self)
  87. try container.encode(self.methodConfig, forKey: .methodConfig)
  88. try container.encode(self.loadBalancingConfig, forKey: .loadBalancingConfig)
  89. try container.encodeIfPresent(self.retryThrottling, forKey: .retryThrottling)
  90. }
  91. }
  92. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  93. extension ServiceConfig {
  94. /// Configuration used by clients for load-balancing.
  95. public struct LoadBalancingConfig: Hashable, Sendable {
  96. private enum Value: Hashable, Sendable {
  97. case pickFirst(PickFirst)
  98. case roundRobin(RoundRobin)
  99. }
  100. private var value: Value?
  101. private init(_ value: Value) {
  102. self.value = value
  103. }
  104. /// Creates a pick-first load balancing policy.
  105. ///
  106. /// - Parameter shuffleAddressList: Whether resolved addresses should be shuffled before
  107. /// attempting to connect to them.
  108. public static func pickFirst(shuffleAddressList: Bool) -> Self {
  109. Self(.pickFirst(PickFirst(shuffleAddressList: shuffleAddressList)))
  110. }
  111. /// Creates a pick-first load balancing policy.
  112. ///
  113. /// - Parameter pickFirst: The pick-first load balancing policy.
  114. public static func pickFirst(_ pickFirst: PickFirst) -> Self {
  115. Self(.pickFirst(pickFirst))
  116. }
  117. /// Creates a round-robin load balancing policy.
  118. public static var roundRobin: Self {
  119. Self(.roundRobin(RoundRobin()))
  120. }
  121. /// The pick-first policy, if configured.
  122. public var pickFirst: PickFirst? {
  123. get {
  124. switch self.value {
  125. case .pickFirst(let value):
  126. return value
  127. default:
  128. return nil
  129. }
  130. }
  131. set {
  132. self.value = newValue.map { .pickFirst($0) }
  133. }
  134. }
  135. /// The round-robin policy, if configured.
  136. public var roundRobin: RoundRobin? {
  137. get {
  138. switch self.value {
  139. case .roundRobin(let value):
  140. return value
  141. default:
  142. return nil
  143. }
  144. }
  145. set {
  146. self.value = newValue.map { .roundRobin($0) }
  147. }
  148. }
  149. }
  150. }
  151. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  152. extension ServiceConfig.LoadBalancingConfig {
  153. /// Configuration for the pick-first load balancing policy.
  154. public struct PickFirst: Hashable, Sendable, Codable {
  155. /// Whether the resolved addresses should be shuffled before attempting to connect to them.
  156. public var shuffleAddressList: Bool
  157. /// Creates a new pick-first load balancing policy.
  158. /// - Parameter shuffleAddressList: Whether the resolved addresses should be shuffled before
  159. /// attempting to connect to them.
  160. public init(shuffleAddressList: Bool = false) {
  161. self.shuffleAddressList = shuffleAddressList
  162. }
  163. public init(from decoder: any Decoder) throws {
  164. let container = try decoder.container(keyedBy: CodingKeys.self)
  165. let shuffle = try container.decodeIfPresent(Bool.self, forKey: .shuffleAddressList) ?? false
  166. self.shuffleAddressList = shuffle
  167. }
  168. }
  169. /// Configuration for the round-robin load balancing policy.
  170. public struct RoundRobin: Hashable, Sendable, Codable {
  171. /// Creates a new round-robin load balancing policy.
  172. public init() {}
  173. }
  174. }
  175. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  176. extension ServiceConfig.LoadBalancingConfig: Codable {
  177. private enum CodingKeys: String, CodingKey {
  178. case roundRobin = "round_robin"
  179. case pickFirst = "pick_first"
  180. }
  181. public init(from decoder: any Decoder) throws {
  182. let container = try decoder.container(keyedBy: CodingKeys.self)
  183. if let value = try container.decodeIfPresent(RoundRobin.self, forKey: .roundRobin) {
  184. self.value = .roundRobin(value)
  185. } else if let value = try container.decodeIfPresent(PickFirst.self, forKey: .pickFirst) {
  186. self.value = .pickFirst(value)
  187. } else {
  188. self.value = nil
  189. }
  190. }
  191. public func encode(to encoder: any Encoder) throws {
  192. var container = encoder.container(keyedBy: CodingKeys.self)
  193. switch self.value {
  194. case .pickFirst(let value):
  195. try container.encode(value, forKey: .pickFirst)
  196. case .roundRobin(let value):
  197. try container.encode(value, forKey: .roundRobin)
  198. case .none:
  199. ()
  200. }
  201. }
  202. }
  203. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  204. extension ServiceConfig {
  205. public struct RetryThrottling: Hashable, Sendable, Codable {
  206. /// The initial, and maximum number of tokens.
  207. ///
  208. /// - Precondition: Must be greater than zero.
  209. public var maxTokens: Int
  210. /// The amount of tokens to add on each successful RPC.
  211. ///
  212. /// Typically this will be some number between 0 and 1, e.g., 0.1. Up to three decimal places
  213. /// are supported.
  214. ///
  215. /// - Precondition: Must be greater than zero.
  216. public var tokenRatio: Double
  217. /// Creates a new retry throttling policy.
  218. ///
  219. /// - Parameters:
  220. /// - maxTokens: The initial, and maximum number of tokens. Must be greater than zero.
  221. /// - tokenRatio: The amount of tokens to add on each successful RPC. Must be greater
  222. /// than zero.
  223. public init(maxTokens: Int, tokenRatio: Double) throws {
  224. self.maxTokens = maxTokens
  225. self.tokenRatio = tokenRatio
  226. try self.validateMaxTokens()
  227. try self.validateTokenRatio()
  228. }
  229. public init(from decoder: any Decoder) throws {
  230. let container = try decoder.container(keyedBy: CodingKeys.self)
  231. self.maxTokens = try container.decode(Int.self, forKey: .maxTokens)
  232. self.tokenRatio = try container.decode(Double.self, forKey: .tokenRatio)
  233. try self.validateMaxTokens()
  234. try self.validateTokenRatio()
  235. }
  236. private func validateMaxTokens() throws {
  237. if self.maxTokens <= 0 {
  238. throw RuntimeError(code: .invalidArgument, message: "maxTokens must be greater than zero")
  239. }
  240. }
  241. private func validateTokenRatio() throws {
  242. if self.tokenRatio <= 0 {
  243. throw RuntimeError(code: .invalidArgument, message: "tokenRatio must be greater than zero")
  244. }
  245. }
  246. }
  247. }