2
0

MethodConfiguration.swift 24 KB

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