ServiceConfig.swift 9.5 KB

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