MethodConfig.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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/0b30c8c05277ab78ec72e77c9cbf66a26684673d/grpc/service_config/service_config.proto
  19. public struct MethodConfig: Hashable, Sendable {
  20. /// The name of a method to which the method config applies.
  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. /// Whether an RPC should be retried or hedged.
  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/0e1807a6e30a1a915c0dcadc873bca92b9fa9720/A6-client-retries.md).
  197. public struct RetryPolicy: Hashable, Sendable {
  198. /// The maximum number of RPC attempts, including the original attempt.
  199. ///
  200. /// Must be greater than one, values greater than five are treated as five.
  201. public var maxAttempts: Int {
  202. didSet { self.maxAttempts = try! validateMaxAttempts(self.maxAttempts) }
  203. }
  204. /// The initial backoff duration.
  205. ///
  206. /// The initial retry will occur after a random amount of time up to this value.
  207. ///
  208. /// - Precondition: Must be greater than zero.
  209. public var initialBackoff: Duration {
  210. willSet { try! Self.validateInitialBackoff(newValue) }
  211. }
  212. /// The maximum amount of time to backoff for.
  213. ///
  214. /// - Precondition: Must be greater than zero.
  215. public var maxBackoff: Duration {
  216. willSet { try! Self.validateMaxBackoff(newValue) }
  217. }
  218. /// The multiplier to apply to backoff.
  219. ///
  220. /// - Precondition: Must be greater than zero.
  221. public var backoffMultiplier: Double {
  222. willSet { try! Self.validateBackoffMultiplier(newValue) }
  223. }
  224. /// The set of status codes which may be retried.
  225. ///
  226. /// - Precondition: Must not be empty.
  227. public var retryableStatusCodes: Set<Status.Code> {
  228. willSet { try! Self.validateRetryableStatusCodes(newValue) }
  229. }
  230. /// Create a new retry policy.
  231. ///
  232. /// - Parameters:
  233. /// - maxAttempts: The maximum number of attempts allowed for the RPC.
  234. /// - initialBackoff: The initial backoff period for the first retry attempt. Must be
  235. /// greater than zero.
  236. /// - maxBackoff: The maximum period of time to wait between attempts. Must be greater than
  237. /// zero.
  238. /// - backoffMultiplier: The exponential backoff multiplier. Must be greater than zero.
  239. /// - retryableStatusCodes: The set of status codes which may be retried. Must not be empty.
  240. /// - Precondition: `maxAttempts`, `initialBackoff`, `maxBackoff` and `backoffMultiplier`
  241. /// must be greater than zero.
  242. /// - Precondition: `retryableStatusCodes` must not be empty.
  243. public init(
  244. maxAttempts: Int,
  245. initialBackoff: Duration,
  246. maxBackoff: Duration,
  247. backoffMultiplier: Double,
  248. retryableStatusCodes: Set<Status.Code>
  249. ) {
  250. self.maxAttempts = try! validateMaxAttempts(maxAttempts)
  251. try! Self.validateInitialBackoff(initialBackoff)
  252. self.initialBackoff = initialBackoff
  253. try! Self.validateMaxBackoff(maxBackoff)
  254. self.maxBackoff = maxBackoff
  255. try! Self.validateBackoffMultiplier(backoffMultiplier)
  256. self.backoffMultiplier = backoffMultiplier
  257. try! Self.validateRetryableStatusCodes(retryableStatusCodes)
  258. self.retryableStatusCodes = retryableStatusCodes
  259. }
  260. private static func validateInitialBackoff(_ value: Duration) throws {
  261. if value <= .zero {
  262. throw RuntimeError(
  263. code: .invalidArgument,
  264. message: "initialBackoff must be greater than zero"
  265. )
  266. }
  267. }
  268. private static func validateMaxBackoff(_ value: Duration) throws {
  269. if value <= .zero {
  270. throw RuntimeError(
  271. code: .invalidArgument,
  272. message: "maxBackoff must be greater than zero"
  273. )
  274. }
  275. }
  276. private static func validateBackoffMultiplier(_ value: Double) throws {
  277. if value <= 0 {
  278. throw RuntimeError(
  279. code: .invalidArgument,
  280. message: "backoffMultiplier must be greater than zero"
  281. )
  282. }
  283. }
  284. private static func validateRetryableStatusCodes(_ value: Set<Status.Code>) throws {
  285. if value.isEmpty {
  286. throw RuntimeError(code: .invalidArgument, message: "retryableStatusCodes mustn't be empty")
  287. }
  288. }
  289. }
  290. /// Policy for hedging an RPC.
  291. ///
  292. /// Hedged RPCs may execute more than once on a server so only idempotent methods should
  293. /// be hedged.
  294. ///
  295. /// gRPC executes the RPC at most ``maxAttempts`` times, staggering each attempt
  296. /// by ``hedgingDelay``.
  297. ///
  298. /// For more information see [gRFC A6 Client
  299. /// Retries](https://github.com/grpc/proposal/blob/0e1807a6e30a1a915c0dcadc873bca92b9fa9720/A6-client-retries.md).
  300. public struct HedgingPolicy: Hashable, Sendable {
  301. /// The maximum number of RPC attempts, including the original attempt.
  302. ///
  303. /// Values greater than five are treated as five.
  304. ///
  305. /// - Precondition: Must be greater than one.
  306. public var maxAttempts: Int {
  307. didSet { self.maxAttempts = try! validateMaxAttempts(self.maxAttempts) }
  308. }
  309. /// The first RPC will be sent immediately, but each subsequent RPC will be sent at intervals
  310. /// of `hedgingDelay`. Set this to zero to immediately send all RPCs.
  311. public var hedgingDelay: Duration {
  312. willSet { try! Self.validateHedgingDelay(newValue) }
  313. }
  314. /// The set of status codes which indicate other hedged RPCs may still succeed.
  315. ///
  316. /// If a non-fatal status code is returned by the server, hedged RPCs will continue.
  317. /// Otherwise, outstanding requests will be cancelled and the error returned to the
  318. /// application layer.
  319. public var nonFatalStatusCodes: Set<Status.Code>
  320. /// Create a new hedging policy.
  321. ///
  322. /// - Parameters:
  323. /// - maxAttempts: The maximum number of attempts allowed for the RPC.
  324. /// - hedgingDelay: The delay between each hedged RPC.
  325. /// - nonFatalStatusCodes: The set of status codes which indicate other hedged RPCs may still
  326. /// succeed.
  327. /// - Precondition: `maxAttempts` must be greater than zero.
  328. public init(
  329. maxAttempts: Int,
  330. hedgingDelay: Duration,
  331. nonFatalStatusCodes: Set<Status.Code>
  332. ) {
  333. self.maxAttempts = try! validateMaxAttempts(maxAttempts)
  334. try! Self.validateHedgingDelay(hedgingDelay)
  335. self.hedgingDelay = hedgingDelay
  336. self.nonFatalStatusCodes = nonFatalStatusCodes
  337. }
  338. private static func validateHedgingDelay(_ value: Duration) throws {
  339. if value < .zero {
  340. throw RuntimeError(
  341. code: .invalidArgument,
  342. message: "hedgingDelay must be greater than or equal to zero"
  343. )
  344. }
  345. }
  346. }
  347. private func validateMaxAttempts(_ value: Int) throws -> Int {
  348. guard value > 1 else {
  349. throw RuntimeError(
  350. code: .invalidArgument,
  351. message: "max_attempts must be greater than one (was \(value))"
  352. )
  353. }
  354. return min(value, 5)
  355. }
  356. extension MethodConfig: Codable {
  357. private enum CodingKeys: String, CodingKey {
  358. case name
  359. case waitForReady
  360. case timeout
  361. case maxRequestMessageBytes
  362. case maxResponseMessageBytes
  363. case retryPolicy
  364. case hedgingPolicy
  365. }
  366. public init(from decoder: any Decoder) throws {
  367. let container = try decoder.container(keyedBy: CodingKeys.self)
  368. self.names = try container.decode([Name].self, forKey: .name)
  369. let waitForReady = try container.decodeIfPresent(Bool.self, forKey: .waitForReady)
  370. self.waitForReady = waitForReady
  371. let timeout = try container.decodeIfPresent(GoogleProtobufDuration.self, forKey: .timeout)
  372. self.timeout = timeout?.duration
  373. let maxRequestSize = try container.decodeIfPresent(Int.self, forKey: .maxRequestMessageBytes)
  374. self.maxRequestMessageBytes = maxRequestSize
  375. let maxResponseSize = try container.decodeIfPresent(Int.self, forKey: .maxResponseMessageBytes)
  376. self.maxResponseMessageBytes = maxResponseSize
  377. if let policy = try container.decodeIfPresent(HedgingPolicy.self, forKey: .hedgingPolicy) {
  378. self.executionPolicy = .hedge(policy)
  379. } else if let policy = try container.decodeIfPresent(RetryPolicy.self, forKey: .retryPolicy) {
  380. self.executionPolicy = .retry(policy)
  381. } else {
  382. self.executionPolicy = nil
  383. }
  384. }
  385. public func encode(to encoder: any Encoder) throws {
  386. var container = encoder.container(keyedBy: CodingKeys.self)
  387. try container.encode(self.names, forKey: .name)
  388. try container.encodeIfPresent(self.waitForReady, forKey: .waitForReady)
  389. try container.encodeIfPresent(
  390. self.timeout.map { GoogleProtobufDuration(duration: $0) },
  391. forKey: .timeout
  392. )
  393. try container.encodeIfPresent(self.maxRequestMessageBytes, forKey: .maxRequestMessageBytes)
  394. try container.encodeIfPresent(self.maxResponseMessageBytes, forKey: .maxResponseMessageBytes)
  395. switch self.executionPolicy?.wrapped {
  396. case .retry(let policy):
  397. try container.encode(policy, forKey: .retryPolicy)
  398. case .hedge(let policy):
  399. try container.encode(policy, forKey: .hedgingPolicy)
  400. case .none:
  401. ()
  402. }
  403. }
  404. }
  405. extension MethodConfig.Name: Codable {
  406. private enum CodingKeys: String, CodingKey {
  407. case service
  408. case method
  409. }
  410. public init(from decoder: any Decoder) throws {
  411. let container = try decoder.container(keyedBy: CodingKeys.self)
  412. let service = try container.decodeIfPresent(String.self, forKey: .service)
  413. self.service = service ?? ""
  414. let method = try container.decodeIfPresent(String.self, forKey: .method)
  415. self.method = method ?? ""
  416. try self.validate()
  417. }
  418. public func encode(to encoder: any Encoder) throws {
  419. var container = encoder.container(keyedBy: CodingKeys.self)
  420. try container.encode(self.method, forKey: .method)
  421. try container.encode(self.service, forKey: .service)
  422. }
  423. }
  424. extension RetryPolicy: Codable {
  425. private enum CodingKeys: String, CodingKey {
  426. case maxAttempts
  427. case initialBackoff
  428. case maxBackoff
  429. case backoffMultiplier
  430. case retryableStatusCodes
  431. }
  432. public init(from decoder: any Decoder) throws {
  433. let container = try decoder.container(keyedBy: CodingKeys.self)
  434. let maxAttempts = try container.decode(Int.self, forKey: .maxAttempts)
  435. self.maxAttempts = try validateMaxAttempts(maxAttempts)
  436. let initialBackoff = try container.decode(GoogleProtobufDuration.self, forKey: .initialBackoff)
  437. self.initialBackoff = initialBackoff.duration
  438. try Self.validateInitialBackoff(self.initialBackoff)
  439. let maxBackoff = try container.decode(GoogleProtobufDuration.self, forKey: .maxBackoff)
  440. self.maxBackoff = maxBackoff.duration
  441. try Self.validateMaxBackoff(self.maxBackoff)
  442. self.backoffMultiplier = try container.decode(Double.self, forKey: .backoffMultiplier)
  443. try Self.validateBackoffMultiplier(self.backoffMultiplier)
  444. let codes = try container.decode([GoogleRPCCode].self, forKey: .retryableStatusCodes)
  445. self.retryableStatusCodes = Set(codes.map { $0.code })
  446. try Self.validateRetryableStatusCodes(self.retryableStatusCodes)
  447. }
  448. public func encode(to encoder: any Encoder) throws {
  449. var container = encoder.container(keyedBy: CodingKeys.self)
  450. try container.encode(self.maxAttempts, forKey: .maxAttempts)
  451. try container.encode(
  452. GoogleProtobufDuration(duration: self.initialBackoff),
  453. forKey: .initialBackoff
  454. )
  455. try container.encode(GoogleProtobufDuration(duration: self.maxBackoff), forKey: .maxBackoff)
  456. try container.encode(self.backoffMultiplier, forKey: .backoffMultiplier)
  457. try container.encode(
  458. self.retryableStatusCodes.map { $0.googleRPCCode },
  459. forKey: .retryableStatusCodes
  460. )
  461. }
  462. }
  463. extension HedgingPolicy: Codable {
  464. private enum CodingKeys: String, CodingKey {
  465. case maxAttempts
  466. case hedgingDelay
  467. case nonFatalStatusCodes
  468. }
  469. public init(from decoder: any Decoder) throws {
  470. let container = try decoder.container(keyedBy: CodingKeys.self)
  471. let maxAttempts = try container.decode(Int.self, forKey: .maxAttempts)
  472. self.maxAttempts = try validateMaxAttempts(maxAttempts)
  473. let delay = try container.decode(GoogleProtobufDuration.self, forKey: .hedgingDelay)
  474. self.hedgingDelay = delay.duration
  475. let statusCodes = try container.decode([GoogleRPCCode].self, forKey: .nonFatalStatusCodes)
  476. self.nonFatalStatusCodes = Set(statusCodes.map { $0.code })
  477. }
  478. public func encode(to encoder: any Encoder) throws {
  479. var container = encoder.container(keyedBy: CodingKeys.self)
  480. try container.encode(self.maxAttempts, forKey: .maxAttempts)
  481. try container.encode(GoogleProtobufDuration(duration: self.hedgingDelay), forKey: .hedgingDelay)
  482. try container.encode(
  483. self.nonFatalStatusCodes.map { $0.googleRPCCode },
  484. forKey: .nonFatalStatusCodes
  485. )
  486. }
  487. }
  488. struct GoogleProtobufDuration: Codable {
  489. var duration: Duration
  490. init(duration: Duration) {
  491. self.duration = duration
  492. }
  493. init(from decoder: any Decoder) throws {
  494. let container = try decoder.singleValueContainer()
  495. let duration = try container.decode(String.self)
  496. guard duration.utf8.last == UInt8(ascii: "s"),
  497. let fractionalSeconds = Double(duration.dropLast())
  498. else {
  499. throw RuntimeError(code: .invalidArgument, message: "Invalid google.protobuf.duration")
  500. }
  501. let seconds = fractionalSeconds.rounded(.down)
  502. let attoseconds = (fractionalSeconds - seconds) * 1e18
  503. self.duration = Duration(
  504. secondsComponent: Int64(seconds),
  505. attosecondsComponent: Int64(attoseconds)
  506. )
  507. }
  508. func encode(to encoder: any Encoder) throws {
  509. var container = encoder.singleValueContainer()
  510. var seconds = Double(self.duration.components.seconds)
  511. seconds += Double(self.duration.components.attoseconds) / 1e18
  512. let durationString = "\(seconds)s"
  513. try container.encode(durationString)
  514. }
  515. }
  516. struct GoogleRPCCode: Codable {
  517. var code: Status.Code
  518. init(code: Status.Code) {
  519. self.code = code
  520. }
  521. init(from decoder: any Decoder) throws {
  522. let container = try decoder.singleValueContainer()
  523. let code: Status.Code?
  524. if let caseName = try? container.decode(String.self) {
  525. code = Status.Code(googleRPCCode: caseName)
  526. } else if let rawValue = try? container.decode(Int.self) {
  527. code = Status.Code(rawValue: rawValue)
  528. } else {
  529. code = nil
  530. }
  531. if let code = code {
  532. self.code = code
  533. } else {
  534. throw RuntimeError(code: .invalidArgument, message: "Invalid google.rpc.code")
  535. }
  536. }
  537. func encode(to encoder: any Encoder) throws {
  538. var container = encoder.singleValueContainer()
  539. try container.encode(self.code.googleRPCCode)
  540. }
  541. }
  542. extension Status.Code {
  543. fileprivate init?(googleRPCCode code: String) {
  544. switch code {
  545. case "OK":
  546. self = .ok
  547. case "CANCELLED":
  548. self = .cancelled
  549. case "UNKNOWN":
  550. self = .unknown
  551. case "INVALID_ARGUMENT":
  552. self = .invalidArgument
  553. case "DEADLINE_EXCEEDED":
  554. self = .deadlineExceeded
  555. case "NOT_FOUND":
  556. self = .notFound
  557. case "ALREADY_EXISTS":
  558. self = .alreadyExists
  559. case "PERMISSION_DENIED":
  560. self = .permissionDenied
  561. case "RESOURCE_EXHAUSTED":
  562. self = .resourceExhausted
  563. case "FAILED_PRECONDITION":
  564. self = .failedPrecondition
  565. case "ABORTED":
  566. self = .aborted
  567. case "OUT_OF_RANGE":
  568. self = .outOfRange
  569. case "UNIMPLEMENTED":
  570. self = .unimplemented
  571. case "INTERNAL":
  572. self = .internalError
  573. case "UNAVAILABLE":
  574. self = .unavailable
  575. case "DATA_LOSS":
  576. self = .dataLoss
  577. case "UNAUTHENTICATED":
  578. self = .unauthenticated
  579. default:
  580. return nil
  581. }
  582. }
  583. fileprivate var googleRPCCode: String {
  584. switch self.wrapped {
  585. case .ok:
  586. return "OK"
  587. case .cancelled:
  588. return "CANCELLED"
  589. case .unknown:
  590. return "UNKNOWN"
  591. case .invalidArgument:
  592. return "INVALID_ARGUMENT"
  593. case .deadlineExceeded:
  594. return "DEADLINE_EXCEEDED"
  595. case .notFound:
  596. return "NOT_FOUND"
  597. case .alreadyExists:
  598. return "ALREADY_EXISTS"
  599. case .permissionDenied:
  600. return "PERMISSION_DENIED"
  601. case .resourceExhausted:
  602. return "RESOURCE_EXHAUSTED"
  603. case .failedPrecondition:
  604. return "FAILED_PRECONDITION"
  605. case .aborted:
  606. return "ABORTED"
  607. case .outOfRange:
  608. return "OUT_OF_RANGE"
  609. case .unimplemented:
  610. return "UNIMPLEMENTED"
  611. case .internalError:
  612. return "INTERNAL"
  613. case .unavailable:
  614. return "UNAVAILABLE"
  615. case .dataLoss:
  616. return "DATA_LOSS"
  617. case .unauthenticated:
  618. return "UNAUTHENTICATED"
  619. }
  620. }
  621. }