RPCError.swift 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. /// An error representing the outcome of an RPC.
  17. ///
  18. /// See also ``Status``.
  19. public struct RPCError: @unchecked Sendable, Hashable, Error {
  20. // @unchecked because it relies on heap allocated storage and 'isKnownUniquelyReferenced'
  21. private var storage: Storage
  22. private mutating func ensureStorageIsUnique() {
  23. if !isKnownUniquelyReferenced(&self.storage) {
  24. self.storage = self.storage.copy()
  25. }
  26. }
  27. /// A code representing the high-level domain of the error.
  28. public var code: Code {
  29. get { self.storage.code }
  30. set {
  31. self.ensureStorageIsUnique()
  32. self.storage.code = newValue
  33. }
  34. }
  35. /// A message providing additional context about the error.
  36. public var message: String {
  37. get { self.storage.message }
  38. set {
  39. self.ensureStorageIsUnique()
  40. self.storage.message = newValue
  41. }
  42. }
  43. /// Metadata associated with the error.
  44. ///
  45. /// Any metadata included in the error thrown from a service will be sent back to the client and
  46. /// conversely any ``RPCError`` received by the client may include metadata sent by a service.
  47. ///
  48. /// Note that clients and servers may synthesise errors which may not include metadata.
  49. public var metadata: Metadata {
  50. get { self.storage.metadata }
  51. set {
  52. self.ensureStorageIsUnique()
  53. self.storage.metadata = newValue
  54. }
  55. }
  56. /// Create a new RPC error.
  57. ///
  58. /// - Parameters:
  59. /// - code: The status code.
  60. /// - message: A message providing additional context about the code.
  61. /// - metadata: Any metadata to attach to the error.
  62. public init(code: Code, message: String, metadata: Metadata = [:]) {
  63. self.storage = Storage(code: code, message: message, metadata: metadata)
  64. }
  65. /// Create a new RPC error from the provided ``Status``.
  66. ///
  67. /// Returns `nil` if the provided ``Status`` has code ``Status/Code-swift.struct/ok``.
  68. ///
  69. /// - Parameter status: The status to convert.
  70. public init?(status: Status) {
  71. guard let code = Code(statusCode: status.code) else { return nil }
  72. self.init(code: code, message: status.message, metadata: [:])
  73. }
  74. }
  75. extension RPCError: CustomStringConvertible {
  76. public var description: String {
  77. "\(self.code): \"\(self.message)\""
  78. }
  79. }
  80. extension RPCError {
  81. private final class Storage: Hashable {
  82. var code: RPCError.Code
  83. var message: String
  84. var metadata: Metadata
  85. init(code: RPCError.Code, message: String, metadata: Metadata) {
  86. self.code = code
  87. self.message = message
  88. self.metadata = metadata
  89. }
  90. func copy() -> Self {
  91. Self(code: self.code, message: self.message, metadata: self.metadata)
  92. }
  93. func hash(into hasher: inout Hasher) {
  94. hasher.combine(self.code)
  95. hasher.combine(self.message)
  96. hasher.combine(self.metadata)
  97. }
  98. static func == (lhs: RPCError.Storage, rhs: RPCError.Storage) -> Bool {
  99. return lhs.code == rhs.code && lhs.message == rhs.message && lhs.metadata == rhs.metadata
  100. }
  101. }
  102. }
  103. extension RPCError {
  104. public struct Code: Hashable, Sendable, CustomStringConvertible {
  105. /// The numeric value of the error code.
  106. public var rawValue: Int { Int(self.wrapped.rawValue) }
  107. private var wrapped: Status.Code.Wrapped
  108. private init(_ wrapped: Status.Code.Wrapped) {
  109. self.wrapped = wrapped
  110. }
  111. internal init?(statusCode: Status.Code) {
  112. if statusCode == .ok {
  113. return nil
  114. } else {
  115. self.wrapped = statusCode.wrapped
  116. }
  117. }
  118. public var description: String {
  119. String(describing: self.wrapped)
  120. }
  121. }
  122. }
  123. extension RPCError.Code {
  124. /// The operation was cancelled (typically by the caller).
  125. public static let cancelled = Self(.cancelled)
  126. /// Unknown error. An example of where this error may be returned is if a
  127. /// Status value received from another address space belongs to an error-space
  128. /// that is not known in this address space. Also errors raised by APIs that
  129. /// do not return enough error information may be converted to this error.
  130. public static let unknown = Self(.unknown)
  131. /// Client specified an invalid argument. Note that this differs from
  132. /// ``failedPrecondition``. ``invalidArgument`` indicates arguments that are
  133. /// problematic regardless of the state of the system (e.g., a malformed file
  134. /// name).
  135. public static let invalidArgument = Self(.invalidArgument)
  136. /// Deadline expired before operation could complete. For operations that
  137. /// change the state of the system, this error may be returned even if the
  138. /// operation has completed successfully. For example, a successful response
  139. /// from a server could have been delayed long enough for the deadline to
  140. /// expire.
  141. public static let deadlineExceeded = Self(.deadlineExceeded)
  142. /// Some requested entity (e.g., file or directory) was not found.
  143. public static let notFound = Self(.notFound)
  144. /// Some entity that we attempted to create (e.g., file or directory) already
  145. /// exists.
  146. public static let alreadyExists = Self(.alreadyExists)
  147. /// The caller does not have permission to execute the specified operation.
  148. /// ``permissionDenied`` must not be used for rejections caused by exhausting
  149. /// some resource (use ``resourceExhausted`` instead for those errors).
  150. /// ``permissionDenied`` must not be used if the caller can not be identified
  151. /// (use ``unauthenticated`` instead for those errors).
  152. public static let permissionDenied = Self(.permissionDenied)
  153. /// Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  154. /// entire file system is out of space.
  155. public static let resourceExhausted = Self(.resourceExhausted)
  156. /// Operation was rejected because the system is not in a state required for
  157. /// the operation's execution. For example, directory to be deleted may be
  158. /// non-empty, an rmdir operation is applied to a non-directory, etc.
  159. ///
  160. /// A litmus test that may help a service implementor in deciding
  161. /// between ``failedPrecondition``, ``aborted``, and ``unavailable``:
  162. /// - Use ``unavailable`` if the client can retry just the failing call.
  163. /// - Use ``aborted`` if the client should retry at a higher-level
  164. /// (e.g., restarting a read-modify-write sequence).
  165. /// - Use ``failedPrecondition`` if the client should not retry until
  166. /// the system state has been explicitly fixed. E.g., if an "rmdir"
  167. /// fails because the directory is non-empty, ``failedPrecondition``
  168. /// should be returned since the client should not retry unless
  169. /// they have first fixed up the directory by deleting files from it.
  170. /// - Use ``failedPrecondition`` if the client performs conditional
  171. /// REST Get/Update/Delete on a resource and the resource on the
  172. /// server does not match the condition. E.g., conflicting
  173. /// read-modify-write on the same resource.
  174. public static let failedPrecondition = Self(.failedPrecondition)
  175. /// The operation was aborted, typically due to a concurrency issue like
  176. /// sequencer check failures, transaction aborts, etc.
  177. ///
  178. /// See litmus test above for deciding between ``failedPrecondition``, ``aborted``,
  179. /// and ``unavailable``.
  180. public static let aborted = Self(.aborted)
  181. /// Operation was attempted past the valid range. E.g., seeking or reading
  182. /// past end of file.
  183. ///
  184. /// Unlike ``invalidArgument``, this error indicates a problem that may be fixed
  185. /// if the system state changes. For example, a 32-bit file system will
  186. /// generate ``invalidArgument`` if asked to read at an offset that is not in the
  187. /// range [0,2^32-1], but it will generate ``outOfRange`` if asked to read from
  188. /// an offset past the current file size.
  189. ///
  190. /// There is a fair bit of overlap between ``failedPrecondition`` and
  191. /// ``outOfRange``. We recommend using ``outOfRange`` (the more specific error)
  192. /// when it applies so that callers who are iterating through a space can
  193. /// easily look for an ``outOfRange`` error to detect when they are done.
  194. public static let outOfRange = Self(.outOfRange)
  195. /// Operation is not implemented or not supported/enabled in this service.
  196. public static let unimplemented = Self(.unimplemented)
  197. /// Internal errors. Means some invariants expected by underlying System has
  198. /// been broken. If you see one of these errors, Something is very broken.
  199. public static let internalError = Self(.internalError)
  200. /// The service is currently unavailable. This is a most likely a transient
  201. /// condition and may be corrected by retrying with a backoff.
  202. ///
  203. /// See litmus test above for deciding between ``failedPrecondition``, ``aborted``,
  204. /// and ``unavailable``.
  205. public static let unavailable = Self(.unavailable)
  206. /// Unrecoverable data loss or corruption.
  207. public static let dataLoss = Self(.dataLoss)
  208. /// The request does not have valid authentication credentials for the
  209. /// operation.
  210. public static let unauthenticated = Self(.unauthenticated)
  211. }