2
0

Status.swift 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. private init(_ wrapped: Wrapped) {
  132. self.wrapped = wrapped
  133. }
  134. public var description: String {
  135. String(describing: self.wrapped)
  136. }
  137. }
  138. }
  139. extension Status.Code {
  140. /// The operation completed successfully.
  141. public static let ok = Self(.ok)
  142. /// The operation was cancelled (typically by the caller).
  143. public static let cancelled = Self(.cancelled)
  144. /// Unknown error. An example of where this error may be returned is if a
  145. /// Status value received from another address space belongs to an error-space
  146. /// that is not known in this address space. Also errors raised by APIs that
  147. /// do not return enough error information may be converted to this error.
  148. public static let unknown = Self(.unknown)
  149. /// Client specified an invalid argument. Note that this differs from
  150. /// ``failedPrecondition``. ``invalidArgument`` indicates arguments that are
  151. /// problematic regardless of the state of the system (e.g., a malformed file
  152. /// name).
  153. public static let invalidArgument = Self(.invalidArgument)
  154. /// Deadline expired before operation could complete. For operations that
  155. /// change the state of the system, this error may be returned even if the
  156. /// operation has completed successfully. For example, a successful response
  157. /// from a server could have been delayed long enough for the deadline to
  158. /// expire.
  159. public static let deadlineExceeded = Self(.deadlineExceeded)
  160. /// Some requested entity (e.g., file or directory) was not found.
  161. public static let notFound = Self(.notFound)
  162. /// Some entity that we attempted to create (e.g., file or directory) already
  163. /// exists.
  164. public static let alreadyExists = Self(.alreadyExists)
  165. /// The caller does not have permission to execute the specified operation.
  166. /// ``permissionDenied`` must not be used for rejections caused by exhausting
  167. /// some resource (use ``resourceExhausted`` instead for those errors).
  168. /// ``permissionDenied`` must not be used if the caller can not be identified
  169. /// (use ``unauthenticated`` instead for those errors).
  170. public static let permissionDenied = Self(.permissionDenied)
  171. /// Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  172. /// entire file system is out of space.
  173. public static let resourceExhausted = Self(.resourceExhausted)
  174. /// Operation was rejected because the system is not in a state required for
  175. /// the operation's execution. For example, directory to be deleted may be
  176. /// non-empty, an rmdir operation is applied to a non-directory, etc.
  177. ///
  178. /// A litmus test that may help a service implementor in deciding
  179. /// between ``failedPrecondition``, ``aborted``, and ``unavailable``:
  180. /// - Use ``unavailable`` if the client can retry just the failing call.
  181. /// - Use ``aborted`` if the client should retry at a higher-level
  182. /// (e.g., restarting a read-modify-write sequence).
  183. /// - Use ``failedPrecondition`` if the client should not retry until
  184. /// the system state has been explicitly fixed. E.g., if an "rmdir"
  185. /// fails because the directory is non-empty, ``failedPrecondition``
  186. /// should be returned since the client should not retry unless
  187. /// they have first fixed up the directory by deleting files from it.
  188. /// - Use ``failedPrecondition`` if the client performs conditional
  189. /// REST Get/Update/Delete on a resource and the resource on the
  190. /// server does not match the condition. E.g., conflicting
  191. /// read-modify-write on the same resource.
  192. public static let failedPrecondition = Self(.failedPrecondition)
  193. /// The operation was aborted, typically due to a concurrency issue like
  194. /// sequencer check failures, transaction aborts, etc.
  195. ///
  196. /// See litmus test above for deciding between ``failedPrecondition``, ``aborted``,
  197. /// and ``unavailable``.
  198. public static let aborted = Self(.aborted)
  199. /// Operation was attempted past the valid range. E.g., seeking or reading
  200. /// past end of file.
  201. ///
  202. /// Unlike ``invalidArgument``, this error indicates a problem that may be fixed
  203. /// if the system state changes. For example, a 32-bit file system will
  204. /// generate ``invalidArgument`` if asked to read at an offset that is not in the
  205. /// range [0,2^32-1], but it will generate ``outOfRange`` if asked to read from
  206. /// an offset past the current file size.
  207. ///
  208. /// There is a fair bit of overlap between ``failedPrecondition`` and
  209. /// ``outOfRange``. We recommend using ``outOfRange`` (the more specific error)
  210. /// when it applies so that callers who are iterating through a space can
  211. /// easily look for an ``outOfRange`` error to detect when they are done.
  212. public static let outOfRange = Self(.outOfRange)
  213. /// Operation is not implemented or not supported/enabled in this service.
  214. public static let unimplemented = Self(.unimplemented)
  215. /// Internal errors. Means some invariants expected by underlying System has
  216. /// been broken. If you see one of these errors, Something is very broken.
  217. public static let internalError = Self(.internalError)
  218. /// The service is currently unavailable. This is a most likely a transient
  219. /// condition and may be corrected by retrying with a backoff.
  220. ///
  221. /// See litmus test above for deciding between ``failedPrecondition``, ``aborted``,
  222. /// and ``unavailable``.
  223. public static let unavailable = Self(.unavailable)
  224. /// Unrecoverable data loss or corruption.
  225. public static let dataLoss = Self(.dataLoss)
  226. /// The request does not have valid authentication credentials for the
  227. /// operation.
  228. public static let unauthenticated = Self(.unauthenticated)
  229. }