MethodConfig.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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 ``maxAttempts`` 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), maxBackoff)`.
  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 maxAttempts: Int {
  203. didSet { self.maxAttempts = try! validateMaxAttempts(self.maxAttempts) }
  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 maxBackoff: 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. /// - maxAttempts: 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. /// - maxBackoff: 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: `maxAttempts`, `initialBackoff`, `maxBackoff` and `backoffMultiplier`
  242. /// must be greater than zero.
  243. /// - Precondition: `retryableStatusCodes` must not be empty.
  244. public init(
  245. maxAttempts: Int,
  246. initialBackoff: Duration,
  247. maxBackoff: Duration,
  248. backoffMultiplier: Double,
  249. retryableStatusCodes: Set<Status.Code>
  250. ) {
  251. self.maxAttempts = try! validateMaxAttempts(maxAttempts)
  252. try! Self.validateInitialBackoff(initialBackoff)
  253. self.initialBackoff = initialBackoff
  254. try! Self.validateMaxBackoff(maxBackoff)
  255. self.maxBackoff = maxBackoff
  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: "maxBackoff 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 ``maxAttempts`` 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 maxAttempts: Int {
  309. didSet { self.maxAttempts = try! validateMaxAttempts(self.maxAttempts) }
  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. /// - maxAttempts: 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: `maxAttempts` must be greater than zero.
  330. public init(
  331. maxAttempts: Int,
  332. hedgingDelay: Duration,
  333. nonFatalStatusCodes: Set<Status.Code>
  334. ) {
  335. self.maxAttempts = try! validateMaxAttempts(maxAttempts)
  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(self.waitForReady, forKey: .waitForReady)
  405. try container.encodeIfPresent(
  406. self.timeout.map { GoogleProtobufDuration(duration: $0) },
  407. forKey: .timeout
  408. )
  409. try container.encodeIfPresent(self.maxRequestMessageBytes, forKey: .maxRequestMessageBytes)
  410. try container.encodeIfPresent(self.maxResponseMessageBytes, forKey: .maxResponseMessageBytes)
  411. switch self.executionPolicy?.wrapped {
  412. case .retry(let policy):
  413. try container.encode(policy, forKey: .retryPolicy)
  414. case .hedge(let policy):
  415. try container.encode(policy, forKey: .hedgingPolicy)
  416. case .none:
  417. ()
  418. }
  419. }
  420. }
  421. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  422. extension MethodConfig.Name: Codable {
  423. private enum CodingKeys: String, CodingKey {
  424. case service
  425. case method
  426. }
  427. public init(from decoder: any Decoder) throws {
  428. let container = try decoder.container(keyedBy: CodingKeys.self)
  429. let service = try container.decodeIfPresent(String.self, forKey: .service)
  430. self.service = service ?? ""
  431. let method = try container.decodeIfPresent(String.self, forKey: .method)
  432. self.method = method ?? ""
  433. try self.validate()
  434. }
  435. public func encode(to encoder: any Encoder) throws {
  436. var container = encoder.container(keyedBy: CodingKeys.self)
  437. try container.encode(self.method, forKey: .method)
  438. try container.encode(self.service, forKey: .service)
  439. }
  440. }
  441. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  442. extension RetryPolicy: Codable {
  443. private enum CodingKeys: String, CodingKey {
  444. case maxAttempts
  445. case initialBackoff
  446. case maxBackoff
  447. case backoffMultiplier
  448. case retryableStatusCodes
  449. }
  450. public init(from decoder: any Decoder) throws {
  451. let container = try decoder.container(keyedBy: CodingKeys.self)
  452. let maxAttempts = try container.decode(Int.self, forKey: .maxAttempts)
  453. self.maxAttempts = try validateMaxAttempts(maxAttempts)
  454. let initialBackoff = try container.decode(String.self, forKey: .initialBackoff)
  455. self.initialBackoff = try Duration(googleProtobufDuration: initialBackoff)
  456. try Self.validateInitialBackoff(self.initialBackoff)
  457. let maxBackoff = try container.decode(String.self, forKey: .maxBackoff)
  458. self.maxBackoff = try Duration(googleProtobufDuration: maxBackoff)
  459. try Self.validateMaxBackoff(self.maxBackoff)
  460. self.backoffMultiplier = try container.decode(Double.self, forKey: .backoffMultiplier)
  461. try Self.validateBackoffMultiplier(self.backoffMultiplier)
  462. let codes = try container.decode([GoogleRPCCode].self, forKey: .retryableStatusCodes)
  463. self.retryableStatusCodes = Set(codes.map { $0.code })
  464. try Self.validateRetryableStatusCodes(self.retryableStatusCodes)
  465. }
  466. public func encode(to encoder: any Encoder) throws {
  467. var container = encoder.container(keyedBy: CodingKeys.self)
  468. try container.encode(self.maxAttempts, forKey: .maxAttempts)
  469. try container.encode(
  470. GoogleProtobufDuration(duration: self.initialBackoff),
  471. forKey: .initialBackoff
  472. )
  473. try container.encode(GoogleProtobufDuration(duration: self.maxBackoff), forKey: .maxBackoff)
  474. try container.encode(self.backoffMultiplier, forKey: .backoffMultiplier)
  475. try container.encode(
  476. self.retryableStatusCodes.map { $0.googleRPCCode },
  477. forKey: .retryableStatusCodes
  478. )
  479. }
  480. }
  481. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  482. extension HedgingPolicy: Codable {
  483. private enum CodingKeys: String, CodingKey {
  484. case maxAttempts
  485. case hedgingDelay
  486. case nonFatalStatusCodes
  487. }
  488. public init(from decoder: any Decoder) throws {
  489. let container = try decoder.container(keyedBy: CodingKeys.self)
  490. let maxAttempts = try container.decode(Int.self, forKey: .maxAttempts)
  491. self.maxAttempts = try validateMaxAttempts(maxAttempts)
  492. let delay = try container.decode(String.self, forKey: .hedgingDelay)
  493. self.hedgingDelay = try Duration(googleProtobufDuration: delay)
  494. let statusCodes = try container.decode([GoogleRPCCode].self, forKey: .nonFatalStatusCodes)
  495. self.nonFatalStatusCodes = Set(statusCodes.map { $0.code })
  496. }
  497. public func encode(to encoder: any Encoder) throws {
  498. var container = encoder.container(keyedBy: CodingKeys.self)
  499. try container.encode(self.maxAttempts, forKey: .maxAttempts)
  500. try container.encode(GoogleProtobufDuration(duration: self.hedgingDelay), forKey: .hedgingDelay)
  501. try container.encode(
  502. self.nonFatalStatusCodes.map { $0.googleRPCCode },
  503. forKey: .nonFatalStatusCodes
  504. )
  505. }
  506. }
  507. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  508. struct GoogleProtobufDuration: Codable {
  509. var duration: Duration
  510. init(duration: Duration) {
  511. self.duration = duration
  512. }
  513. init(from decoder: any Decoder) throws {
  514. let container = try decoder.singleValueContainer()
  515. let duration = try container.decode(String.self)
  516. guard duration.utf8.last == UInt8(ascii: "s"),
  517. let fractionalSeconds = Double(duration.dropLast())
  518. else {
  519. throw RuntimeError(code: .invalidArgument, message: "Invalid google.protobuf.duration")
  520. }
  521. let seconds = fractionalSeconds.rounded(.down)
  522. let attoseconds = (fractionalSeconds - seconds) * 1e18
  523. self.duration = Duration(
  524. secondsComponent: Int64(seconds),
  525. attosecondsComponent: Int64(attoseconds)
  526. )
  527. }
  528. func encode(to encoder: any Encoder) throws {
  529. var container = encoder.singleValueContainer()
  530. var seconds = Double(self.duration.components.seconds)
  531. seconds += Double(self.duration.components.attoseconds) / 1e18
  532. let durationString = "\(seconds)s"
  533. try container.encode(durationString)
  534. }
  535. }
  536. struct GoogleRPCCode: Codable {
  537. var code: Status.Code
  538. init(code: Status.Code) {
  539. self.code = code
  540. }
  541. init(from decoder: any Decoder) throws {
  542. let container = try decoder.singleValueContainer()
  543. let code: Status.Code?
  544. if let caseName = try? container.decode(String.self) {
  545. code = Status.Code(googleRPCCode: caseName)
  546. } else if let rawValue = try? container.decode(Int.self) {
  547. code = Status.Code(rawValue: rawValue)
  548. } else {
  549. code = nil
  550. }
  551. if let code = code {
  552. self.code = code
  553. } else {
  554. throw RuntimeError(code: .invalidArgument, message: "Invalid google.rpc.code")
  555. }
  556. }
  557. func encode(to encoder: any Encoder) throws {
  558. var container = encoder.singleValueContainer()
  559. try container.encode(self.code.googleRPCCode)
  560. }
  561. }
  562. extension Status.Code {
  563. fileprivate init?(googleRPCCode code: String) {
  564. switch code {
  565. case "OK":
  566. self = .ok
  567. case "CANCELLED":
  568. self = .cancelled
  569. case "UNKNOWN":
  570. self = .unknown
  571. case "INVALID_ARGUMENT":
  572. self = .invalidArgument
  573. case "DEADLINE_EXCEEDED":
  574. self = .deadlineExceeded
  575. case "NOT_FOUND":
  576. self = .notFound
  577. case "ALREADY_EXISTS":
  578. self = .alreadyExists
  579. case "PERMISSION_DENIED":
  580. self = .permissionDenied
  581. case "RESOURCE_EXHAUSTED":
  582. self = .resourceExhausted
  583. case "FAILED_PRECONDITION":
  584. self = .failedPrecondition
  585. case "ABORTED":
  586. self = .aborted
  587. case "OUT_OF_RANGE":
  588. self = .outOfRange
  589. case "UNIMPLEMENTED":
  590. self = .unimplemented
  591. case "INTERNAL":
  592. self = .internalError
  593. case "UNAVAILABLE":
  594. self = .unavailable
  595. case "DATA_LOSS":
  596. self = .dataLoss
  597. case "UNAUTHENTICATED":
  598. self = .unauthenticated
  599. default:
  600. return nil
  601. }
  602. }
  603. fileprivate var googleRPCCode: String {
  604. switch self.wrapped {
  605. case .ok:
  606. return "OK"
  607. case .cancelled:
  608. return "CANCELLED"
  609. case .unknown:
  610. return "UNKNOWN"
  611. case .invalidArgument:
  612. return "INVALID_ARGUMENT"
  613. case .deadlineExceeded:
  614. return "DEADLINE_EXCEEDED"
  615. case .notFound:
  616. return "NOT_FOUND"
  617. case .alreadyExists:
  618. return "ALREADY_EXISTS"
  619. case .permissionDenied:
  620. return "PERMISSION_DENIED"
  621. case .resourceExhausted:
  622. return "RESOURCE_EXHAUSTED"
  623. case .failedPrecondition:
  624. return "FAILED_PRECONDITION"
  625. case .aborted:
  626. return "ABORTED"
  627. case .outOfRange:
  628. return "OUT_OF_RANGE"
  629. case .unimplemented:
  630. return "UNIMPLEMENTED"
  631. case .internalError:
  632. return "INTERNAL"
  633. case .unavailable:
  634. return "UNAVAILABLE"
  635. case .dataLoss:
  636. return "DATA_LOSS"
  637. case .unauthenticated:
  638. return "UNAUTHENTICATED"
  639. }
  640. }
  641. }