MethodConfig.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. /*
  2. * Copyright 2023, 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. /// Configuration values for executing an RPC.
  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 MethodConfig: Hashable, Sendable {
  21. public struct Name: Sendable, Hashable {
  22. /// The name of the service, including the namespace.
  23. ///
  24. /// If the service is empty then `method` must also be empty and the configuration specifies
  25. /// defaults for all methods.
  26. ///
  27. /// - Precondition: If `service` is empty then `method` must also be empty.
  28. public var service: String {
  29. didSet { try! self.validate() }
  30. }
  31. /// The name of the method.
  32. ///
  33. /// If the method is empty then the configuration will be the default for all methods in the
  34. /// specified service.
  35. public var method: String
  36. /// Create a new name.
  37. ///
  38. /// If the service is empty then `method` must also be empty and the configuration specifies
  39. /// defaults for all methods. If only `method` is empty then the configuration applies to
  40. /// all methods in the `service`.
  41. ///
  42. /// - Parameters:
  43. /// - service: The name of the service, including the namespace.
  44. /// - method: The name of the method.
  45. public init(service: String, method: String = "") {
  46. self.service = service
  47. self.method = method
  48. try! self.validate()
  49. }
  50. private func validate() throws {
  51. if self.service.isEmpty && !self.method.isEmpty {
  52. throw RuntimeError(
  53. code: .invalidArgument,
  54. message: "'method' must be empty if 'service' is empty."
  55. )
  56. }
  57. }
  58. }
  59. /// The names of methods which this configuration applies to.
  60. public var names: [Name]
  61. /// Whether RPCs for this method should wait until the connection is ready.
  62. ///
  63. /// If `false` the RPC will abort immediately if there is a transient failure connecting to
  64. /// the server. Otherwise gRPC will attempt to connect until the deadline is exceeded.
  65. public var waitForReady: Bool?
  66. /// The default timeout for the RPC.
  67. ///
  68. /// If no reply is received in the specified amount of time the request is aborted
  69. /// with an ``RPCError`` with code ``RPCError/Code/deadlineExceeded``.
  70. ///
  71. /// The actual deadline used will be the minimum of the value specified here
  72. /// and the value set by the application by the client API. If either one isn't set
  73. /// then the other value is used. If neither is set then the request has no deadline.
  74. ///
  75. /// The timeout applies to the overall execution of an RPC. If, for example, a retry
  76. /// policy is set then the timeout begins when the first attempt is started and _isn't_ reset
  77. /// when subsequent attempts start.
  78. public var timeout: Duration?
  79. /// The maximum allowed payload size in bytes for an individual message.
  80. ///
  81. /// If a client attempts to send an object larger than this value, it will not be sent and the
  82. /// client will see an error. Note that 0 is a valid value, meaning that the request message
  83. /// must be empty.
  84. ///
  85. /// Note that if compression is used the uncompressed message size is validated.
  86. public var maxRequestMessageBytes: Int?
  87. /// The maximum allowed payload size in bytes for an individual response message.
  88. ///
  89. /// If a server attempts to send an object larger than this value, it will not
  90. /// be sent, and an error will be sent to the client instead. Note that 0 is a valid value,
  91. /// meaning that the response message must be empty.
  92. ///
  93. /// Note that if compression is used the uncompressed message size is validated.
  94. public var maxResponseMessageBytes: Int?
  95. /// The policy determining how many times, and when, the RPC is executed.
  96. ///
  97. /// There are two policy types:
  98. /// 1. Retry
  99. /// 2. Hedging
  100. ///
  101. /// The retry policy allows an RPC to be retried a limited number of times if the RPC
  102. /// fails with one of the configured set of status codes. RPCs are only retried if they
  103. /// fail immediately, that is, the first response part received from the server is a
  104. /// status code.
  105. ///
  106. /// The hedging policy allows an RPC to be executed multiple times concurrently. Typically
  107. /// each execution will be staggered by some delay. The first successful response will be
  108. /// reported to the client. Hedging is only suitable for idempotent RPCs.
  109. public var executionPolicy: RPCExecutionPolicy?
  110. /// Create an execution configuration.
  111. ///
  112. /// - Parameters:
  113. /// - names: The names of methods this configuration applies to.
  114. /// - waitForReady: Whether RPCs sent to this method should wait until the connection is ready.
  115. /// - timeout: The default timeout for the RPC.
  116. /// - maxRequestMessageBytes: The maximum allowed size of a request message in bytes.
  117. /// - maxResponseMessageBytes: The maximum allowed size of a response message in bytes.
  118. /// - executionPolicy: The execution policy to use for the RPC.
  119. public init(
  120. names: [Name],
  121. waitForReady: Bool? = nil,
  122. timeout: Duration? = nil,
  123. maxRequestMessageBytes: Int? = nil,
  124. maxResponseMessageBytes: Int? = nil,
  125. executionPolicy: RPCExecutionPolicy? = nil
  126. ) {
  127. self.names = names
  128. self.waitForReady = waitForReady
  129. self.timeout = timeout
  130. self.maxRequestMessageBytes = maxRequestMessageBytes
  131. self.maxResponseMessageBytes = maxResponseMessageBytes
  132. self.executionPolicy = executionPolicy
  133. }
  134. }
  135. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  136. public struct RPCExecutionPolicy: Hashable, Sendable {
  137. @usableFromInline
  138. enum Wrapped: Hashable, Sendable {
  139. /// Policy for retrying an RPC.
  140. ///
  141. /// See ``RetryPolicy`` for more details.
  142. case retry(RetryPolicy)
  143. /// Policy for hedging an RPC.
  144. ///
  145. /// See ``HedgingPolicy`` for more details.
  146. case hedge(HedgingPolicy)
  147. }
  148. @usableFromInline
  149. let wrapped: Wrapped
  150. private init(_ wrapped: Wrapped) {
  151. self.wrapped = wrapped
  152. }
  153. /// Returns the retry policy, if it was set.
  154. public var retry: RetryPolicy? {
  155. switch self.wrapped {
  156. case .retry(let policy):
  157. return policy
  158. case .hedge:
  159. return nil
  160. }
  161. }
  162. /// Returns the hedging policy, if it was set.
  163. public var hedge: HedgingPolicy? {
  164. switch self.wrapped {
  165. case .hedge(let policy):
  166. return policy
  167. case .retry:
  168. return nil
  169. }
  170. }
  171. /// Create a new retry policy.``
  172. public static func retry(_ policy: RetryPolicy) -> Self {
  173. Self(.retry(policy))
  174. }
  175. /// Create a new hedging policy.``
  176. public static func hedge(_ policy: HedgingPolicy) -> Self {
  177. Self(.hedge(policy))
  178. }
  179. }
  180. /// Policy for retrying an RPC.
  181. ///
  182. /// gRPC retries RPCs when the first response from the server is a status code which matches
  183. /// one of the configured retryable status codes. If the server begins processing the RPC and
  184. /// first responds with metadata and later responds with a retryable status code then the RPC
  185. /// won't be retried.
  186. ///
  187. /// Execution attempts are limited by ``maximumAttempts`` which includes the original attempt. The
  188. /// maximum number of attempts is limited to five.
  189. ///
  190. /// Subsequent attempts are executed after some delay. The first _retry_, or second attempt, will
  191. /// be started after a randomly chosen delay between zero and ``initialBackoff``. More generally,
  192. /// the nth retry will happen after a randomly chosen delay between zero
  193. /// and `min(initialBackoff * backoffMultiplier^(n-1), maximumBackoff)`.
  194. ///
  195. /// For more information see [gRFC A6 Client
  196. /// Retries](https://github.com/grpc/proposal/blob/master/A6-client-retries.md).
  197. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  198. public struct RetryPolicy: Hashable, Sendable {
  199. /// The maximum number of RPC attempts, including the original attempt.
  200. ///
  201. /// Must be greater than one, values greater than five are treated as five.
  202. public var maximumAttempts: Int {
  203. didSet { self.maximumAttempts = try! validateMaxAttempts(self.maximumAttempts) }
  204. }
  205. /// The initial backoff duration.
  206. ///
  207. /// The initial retry will occur after a random amount of time up to this value.
  208. ///
  209. /// - Precondition: Must be greater than zero.
  210. public var initialBackoff: Duration {
  211. willSet { try! Self.validateInitialBackoff(newValue) }
  212. }
  213. /// The maximum amount of time to backoff for.
  214. ///
  215. /// - Precondition: Must be greater than zero.
  216. public var maximumBackoff: Duration {
  217. willSet { try! Self.validateMaxBackoff(newValue) }
  218. }
  219. /// The multiplier to apply to backoff.
  220. ///
  221. /// - Precondition: Must be greater than zero.
  222. public var backoffMultiplier: Double {
  223. willSet { try! Self.validateBackoffMultiplier(newValue) }
  224. }
  225. /// The set of status codes which may be retried.
  226. ///
  227. /// - Precondition: Must not be empty.
  228. public var retryableStatusCodes: Set<Status.Code> {
  229. willSet { try! Self.validateRetryableStatusCodes(newValue) }
  230. }
  231. /// Create a new retry policy.
  232. ///
  233. /// - Parameters:
  234. /// - maximumAttempts: The maximum number of attempts allowed for the RPC.
  235. /// - initialBackoff: The initial backoff period for the first retry attempt. Must be
  236. /// greater than zero.
  237. /// - maximumBackoff: The maximum period of time to wait between attempts. Must be greater than
  238. /// zero.
  239. /// - backoffMultiplier: The exponential backoff multiplier. Must be greater than zero.
  240. /// - retryableStatusCodes: The set of status codes which may be retried. Must not be empty.
  241. /// - Precondition: `maximumAttempts`, `initialBackoff`, `maximumBackoff` and `backoffMultiplier`
  242. /// must be greater than zero.
  243. /// - Precondition: `retryableStatusCodes` must not be empty.
  244. public init(
  245. maximumAttempts: Int,
  246. initialBackoff: Duration,
  247. maximumBackoff: Duration,
  248. backoffMultiplier: Double,
  249. retryableStatusCodes: Set<Status.Code>
  250. ) {
  251. self.maximumAttempts = try! validateMaxAttempts(maximumAttempts)
  252. try! Self.validateInitialBackoff(initialBackoff)
  253. self.initialBackoff = initialBackoff
  254. try! Self.validateMaxBackoff(maximumBackoff)
  255. self.maximumBackoff = maximumBackoff
  256. try! Self.validateBackoffMultiplier(backoffMultiplier)
  257. self.backoffMultiplier = backoffMultiplier
  258. try! Self.validateRetryableStatusCodes(retryableStatusCodes)
  259. self.retryableStatusCodes = retryableStatusCodes
  260. }
  261. private static func validateInitialBackoff(_ value: Duration) throws {
  262. if value <= .zero {
  263. throw RuntimeError(
  264. code: .invalidArgument,
  265. message: "initialBackoff must be greater than zero"
  266. )
  267. }
  268. }
  269. private static func validateMaxBackoff(_ value: Duration) throws {
  270. if value <= .zero {
  271. throw RuntimeError(
  272. code: .invalidArgument,
  273. message: "maximumBackoff must be greater than zero"
  274. )
  275. }
  276. }
  277. private static func validateBackoffMultiplier(_ value: Double) throws {
  278. if value <= 0 {
  279. throw RuntimeError(
  280. code: .invalidArgument,
  281. message: "backoffMultiplier must be greater than zero"
  282. )
  283. }
  284. }
  285. private static func validateRetryableStatusCodes(_ value: Set<Status.Code>) throws {
  286. if value.isEmpty {
  287. throw RuntimeError(code: .invalidArgument, message: "retryableStatusCodes mustn't be empty")
  288. }
  289. }
  290. }
  291. /// Policy for hedging an RPC.
  292. ///
  293. /// Hedged RPCs may execute more than once on a server so only idempotent methods should
  294. /// be hedged.
  295. ///
  296. /// gRPC executes the RPC at most ``maximumAttempts`` times, staggering each attempt
  297. /// by ``hedgingDelay``.
  298. ///
  299. /// For more information see [gRFC A6 Client
  300. /// Retries](https://github.com/grpc/proposal/blob/master/A6-client-retries.md).
  301. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  302. public struct HedgingPolicy: Hashable, Sendable {
  303. /// The maximum number of RPC attempts, including the original attempt.
  304. ///
  305. /// Values greater than five are treated as five.
  306. ///
  307. /// - Precondition: Must be greater than one.
  308. public var maximumAttempts: Int {
  309. didSet { self.maximumAttempts = try! validateMaxAttempts(self.maximumAttempts) }
  310. }
  311. /// The first RPC will be sent immediately, but each subsequent RPC will be sent at intervals
  312. /// of `hedgingDelay`. Set this to zero to immediately send all RPCs.
  313. public var hedgingDelay: Duration {
  314. willSet { try! Self.validateHedgingDelay(newValue) }
  315. }
  316. /// The set of status codes which indicate other hedged RPCs may still succeed.
  317. ///
  318. /// If a non-fatal status code is returned by the server, hedged RPCs will continue.
  319. /// Otherwise, outstanding requests will be cancelled and the error returned to the
  320. /// application layer.
  321. public var nonFatalStatusCodes: Set<Status.Code>
  322. /// Create a new hedging policy.
  323. ///
  324. /// - Parameters:
  325. /// - maximumAttempts: The maximum number of attempts allowed for the RPC.
  326. /// - hedgingDelay: The delay between each hedged RPC.
  327. /// - nonFatalStatusCodes: The set of status codes which indicate other hedged RPCs may still
  328. /// succeed.
  329. /// - Precondition: `maximumAttempts` must be greater than zero.
  330. public init(
  331. maximumAttempts: Int,
  332. hedgingDelay: Duration,
  333. nonFatalStatusCodes: Set<Status.Code>
  334. ) {
  335. self.maximumAttempts = try! validateMaxAttempts(maximumAttempts)
  336. try! Self.validateHedgingDelay(hedgingDelay)
  337. self.hedgingDelay = hedgingDelay
  338. self.nonFatalStatusCodes = nonFatalStatusCodes
  339. }
  340. private static func validateHedgingDelay(_ value: Duration) throws {
  341. if value < .zero {
  342. throw RuntimeError(
  343. code: .invalidArgument,
  344. message: "hedgingDelay must be greater than or equal to zero"
  345. )
  346. }
  347. }
  348. }
  349. private func validateMaxAttempts(_ value: Int) throws -> Int {
  350. guard value > 1 else {
  351. throw RuntimeError(
  352. code: .invalidArgument,
  353. message: "max_attempts must be greater than one (was \(value))"
  354. )
  355. }
  356. return min(value, 5)
  357. }
  358. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  359. extension Duration {
  360. fileprivate init(googleProtobufDuration duration: String) throws {
  361. guard duration.utf8.last == UInt8(ascii: "s"),
  362. let fractionalSeconds = Double(duration.dropLast())
  363. else {
  364. throw RuntimeError(code: .invalidArgument, message: "Invalid google.protobuf.duration")
  365. }
  366. let seconds = fractionalSeconds.rounded(.down)
  367. let attoseconds = (fractionalSeconds - seconds) / 1e18
  368. self.init(secondsComponent: Int64(seconds), attosecondsComponent: Int64(attoseconds))
  369. }
  370. }
  371. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  372. extension MethodConfig: Codable {
  373. private enum CodingKeys: String, CodingKey {
  374. case name
  375. case waitForReady
  376. case timeout
  377. case maxRequestMessageBytes
  378. case maxResponseMessageBytes
  379. case retryPolicy
  380. case hedgingPolicy
  381. }
  382. public init(from decoder: any Decoder) throws {
  383. let container = try decoder.container(keyedBy: CodingKeys.self)
  384. self.names = try container.decode([Name].self, forKey: .name)
  385. let waitForReady = try container.decodeIfPresent(Bool.self, forKey: .waitForReady)
  386. self.waitForReady = waitForReady
  387. let timeout = try container.decodeIfPresent(GoogleProtobufDuration.self, forKey: .timeout)
  388. self.timeout = timeout?.duration
  389. let maxRequestSize = try container.decodeIfPresent(Int.self, forKey: .maxRequestMessageBytes)
  390. self.maxRequestMessageBytes = maxRequestSize
  391. let maxResponseSize = try container.decodeIfPresent(Int.self, forKey: .maxResponseMessageBytes)
  392. self.maxResponseMessageBytes = maxResponseSize
  393. if let policy = try container.decodeIfPresent(HedgingPolicy.self, forKey: .hedgingPolicy) {
  394. self.executionPolicy = .hedge(policy)
  395. } else if let policy = try container.decodeIfPresent(RetryPolicy.self, forKey: .retryPolicy) {
  396. self.executionPolicy = .retry(policy)
  397. } else {
  398. self.executionPolicy = nil
  399. }
  400. }
  401. public func encode(to encoder: any Encoder) throws {
  402. var container = encoder.container(keyedBy: CodingKeys.self)
  403. try container.encode(self.names, forKey: .name)
  404. try container.encodeIfPresent(
  405. self.timeout.map { GoogleProtobufDuration(duration: $0) },
  406. forKey: .timeout
  407. )
  408. try container.encodeIfPresent(self.maxRequestMessageBytes, forKey: .maxRequestMessageBytes)
  409. try container.encodeIfPresent(self.maxResponseMessageBytes, forKey: .maxResponseMessageBytes)
  410. switch self.executionPolicy?.wrapped {
  411. case .retry(let policy):
  412. try container.encode(policy, forKey: .retryPolicy)
  413. case .hedge(let policy):
  414. try container.encode(policy, forKey: .hedgingPolicy)
  415. case .none:
  416. ()
  417. }
  418. }
  419. }
  420. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  421. extension MethodConfig.Name: Codable {
  422. private enum CodingKeys: String, CodingKey {
  423. case service
  424. case method
  425. }
  426. public init(from decoder: Decoder) throws {
  427. let container = try decoder.container(keyedBy: CodingKeys.self)
  428. let service = try container.decodeIfPresent(String.self, forKey: .service)
  429. self.service = service ?? ""
  430. let method = try container.decodeIfPresent(String.self, forKey: .method)
  431. self.method = method ?? ""
  432. try self.validate()
  433. }
  434. public func encode(to encoder: any Encoder) throws {
  435. var container = encoder.container(keyedBy: CodingKeys.self)
  436. try container.encode(self.method, forKey: .method)
  437. try container.encode(self.service, forKey: .service)
  438. }
  439. }
  440. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  441. extension RetryPolicy: Codable {
  442. private enum CodingKeys: String, CodingKey {
  443. case maxAttempts
  444. case initialBackoff
  445. case maxBackoff
  446. case backoffMultiplier
  447. case retryableStatusCodes
  448. }
  449. public init(from decoder: any Decoder) throws {
  450. let container = try decoder.container(keyedBy: CodingKeys.self)
  451. let maxAttempts = try container.decode(Int.self, forKey: .maxAttempts)
  452. self.maximumAttempts = try validateMaxAttempts(maxAttempts)
  453. let initialBackoff = try container.decode(String.self, forKey: .initialBackoff)
  454. self.initialBackoff = try Duration(googleProtobufDuration: initialBackoff)
  455. try Self.validateInitialBackoff(self.initialBackoff)
  456. let maxBackoff = try container.decode(String.self, forKey: .maxBackoff)
  457. self.maximumBackoff = try Duration(googleProtobufDuration: maxBackoff)
  458. try Self.validateMaxBackoff(self.maximumBackoff)
  459. self.backoffMultiplier = try container.decode(Double.self, forKey: .backoffMultiplier)
  460. try Self.validateBackoffMultiplier(self.backoffMultiplier)
  461. let codes = try container.decode([GoogleRPCCode].self, forKey: .retryableStatusCodes)
  462. self.retryableStatusCodes = Set(codes.map { $0.code })
  463. try Self.validateRetryableStatusCodes(self.retryableStatusCodes)
  464. }
  465. public func encode(to encoder: any Encoder) throws {
  466. var container = encoder.container(keyedBy: CodingKeys.self)
  467. try container.encode(self.maximumAttempts, forKey: .maxAttempts)
  468. try container.encode(
  469. GoogleProtobufDuration(duration: self.initialBackoff),
  470. forKey: .initialBackoff
  471. )
  472. try container.encode(GoogleProtobufDuration(duration: self.maximumBackoff), forKey: .maxBackoff)
  473. try container.encode(self.backoffMultiplier, forKey: .backoffMultiplier)
  474. try container.encode(
  475. self.retryableStatusCodes.map { $0.googleRPCCode },
  476. forKey: .retryableStatusCodes
  477. )
  478. }
  479. }
  480. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  481. extension HedgingPolicy: Codable {
  482. private enum CodingKeys: String, CodingKey {
  483. case maxAttempts
  484. case hedgingDelay
  485. case nonFatalStatusCodes
  486. }
  487. public init(from decoder: any Decoder) throws {
  488. let container = try decoder.container(keyedBy: CodingKeys.self)
  489. let maxAttempts = try container.decode(Int.self, forKey: .maxAttempts)
  490. self.maximumAttempts = try validateMaxAttempts(maxAttempts)
  491. let delay = try container.decode(String.self, forKey: .hedgingDelay)
  492. self.hedgingDelay = try Duration(googleProtobufDuration: delay)
  493. let statusCodes = try container.decode([GoogleRPCCode].self, forKey: .nonFatalStatusCodes)
  494. self.nonFatalStatusCodes = Set(statusCodes.map { $0.code })
  495. }
  496. public func encode(to encoder: any Encoder) throws {
  497. var container = encoder.container(keyedBy: CodingKeys.self)
  498. try container.encode(self.maximumAttempts, forKey: .maxAttempts)
  499. try container.encode(GoogleProtobufDuration(duration: self.hedgingDelay), forKey: .hedgingDelay)
  500. try container.encode(
  501. self.nonFatalStatusCodes.map { $0.googleRPCCode },
  502. forKey: .nonFatalStatusCodes
  503. )
  504. }
  505. }
  506. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  507. struct GoogleProtobufDuration: Codable {
  508. var duration: Duration
  509. init(duration: Duration) {
  510. self.duration = duration
  511. }
  512. init(from decoder: any Decoder) throws {
  513. let container = try decoder.singleValueContainer()
  514. let duration = try container.decode(String.self)
  515. guard duration.utf8.last == UInt8(ascii: "s"),
  516. let fractionalSeconds = Double(duration.dropLast())
  517. else {
  518. throw RuntimeError(code: .invalidArgument, message: "Invalid google.protobuf.duration")
  519. }
  520. let seconds = fractionalSeconds.rounded(.down)
  521. let attoseconds = (fractionalSeconds - seconds) * 1e18
  522. self.duration = Duration(
  523. secondsComponent: Int64(seconds),
  524. attosecondsComponent: Int64(attoseconds)
  525. )
  526. }
  527. func encode(to encoder: any Encoder) throws {
  528. var container = encoder.singleValueContainer()
  529. var seconds = Double(self.duration.components.seconds)
  530. seconds += Double(self.duration.components.attoseconds) / 1e18
  531. let durationString = "\(seconds)s"
  532. try container.encode(durationString)
  533. }
  534. }
  535. struct GoogleRPCCode: Codable {
  536. var code: Status.Code
  537. init(code: Status.Code) {
  538. self.code = code
  539. }
  540. init(from decoder: Decoder) throws {
  541. let container = try decoder.singleValueContainer()
  542. let code: Status.Code?
  543. if let caseName = try? container.decode(String.self) {
  544. code = Status.Code(googleRPCCode: caseName)
  545. } else if let rawValue = try? container.decode(Int.self) {
  546. code = Status.Code(rawValue: rawValue)
  547. } else {
  548. code = nil
  549. }
  550. if let code = code {
  551. self.code = code
  552. } else {
  553. throw RuntimeError(code: .invalidArgument, message: "Invalid google.rpc.code")
  554. }
  555. }
  556. func encode(to encoder: Encoder) throws {
  557. var container = encoder.singleValueContainer()
  558. try container.encode(self.code.googleRPCCode)
  559. }
  560. }
  561. extension Status.Code {
  562. fileprivate init?(googleRPCCode code: String) {
  563. switch code {
  564. case "OK":
  565. self = .ok
  566. case "CANCELLED":
  567. self = .cancelled
  568. case "UNKNOWN":
  569. self = .unknown
  570. case "INVALID_ARGUMENT":
  571. self = .invalidArgument
  572. case "DEADLINE_EXCEEDED":
  573. self = .deadlineExceeded
  574. case "NOT_FOUND":
  575. self = .notFound
  576. case "ALREADY_EXISTS":
  577. self = .alreadyExists
  578. case "PERMISSION_DENIED":
  579. self = .permissionDenied
  580. case "RESOURCE_EXHAUSTED":
  581. self = .resourceExhausted
  582. case "FAILED_PRECONDITION":
  583. self = .failedPrecondition
  584. case "ABORTED":
  585. self = .aborted
  586. case "OUT_OF_RANGE":
  587. self = .outOfRange
  588. case "UNIMPLEMENTED":
  589. self = .unimplemented
  590. case "INTERNAL":
  591. self = .internalError
  592. case "UNAVAILABLE":
  593. self = .unavailable
  594. case "DATA_LOSS":
  595. self = .dataLoss
  596. case "UNAUTHENTICATED":
  597. self = .unauthenticated
  598. default:
  599. return nil
  600. }
  601. }
  602. fileprivate var googleRPCCode: String {
  603. switch self.wrapped {
  604. case .ok:
  605. return "OK"
  606. case .cancelled:
  607. return "CANCELLED"
  608. case .unknown:
  609. return "UNKNOWN"
  610. case .invalidArgument:
  611. return "INVALID_ARGUMENT"
  612. case .deadlineExceeded:
  613. return "DEADLINE_EXCEEDED"
  614. case .notFound:
  615. return "NOT_FOUND"
  616. case .alreadyExists:
  617. return "ALREADY_EXISTS"
  618. case .permissionDenied:
  619. return "PERMISSION_DENIED"
  620. case .resourceExhausted:
  621. return "RESOURCE_EXHAUSTED"
  622. case .failedPrecondition:
  623. return "FAILED_PRECONDITION"
  624. case .aborted:
  625. return "ABORTED"
  626. case .outOfRange:
  627. return "OUT_OF_RANGE"
  628. case .unimplemented:
  629. return "UNIMPLEMENTED"
  630. case .internalError:
  631. return "INTERNAL"
  632. case .unavailable:
  633. return "UNAVAILABLE"
  634. case .dataLoss:
  635. return "DATA_LOSS"
  636. case .unauthenticated:
  637. return "UNAUTHENTICATED"
  638. }
  639. }
  640. }