Status.swift 12 KB

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