MethodConfig.swift 24 KB

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