Status.swift 10 KB

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