GRPCStatus.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * Copyright 2019, 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. import Foundation
  17. import NIOCore
  18. import NIOHTTP1
  19. import NIOHTTP2
  20. /// Encapsulates the result of a gRPC call.
  21. public struct GRPCStatus: Error {
  22. /// Storage for message/cause. In the happy case ('ok') there will not be a message or cause
  23. /// and this will reference a static storage containing nil values. Making it optional makes the
  24. /// setters for message and cause a little messy.
  25. private var storage: Storage
  26. /// The status code of the RPC.
  27. public var code: Code
  28. /// The status message of the RPC.
  29. public var message: String? {
  30. get {
  31. return self.storage.message
  32. }
  33. set {
  34. if isKnownUniquelyReferenced(&self.storage) {
  35. self.storage.message = newValue
  36. } else {
  37. self.storage = .makeStorage(message: newValue, cause: self.storage.cause)
  38. }
  39. }
  40. }
  41. /// The cause of an error (not 'ok') status. This value is never transmitted over the wire and is
  42. /// **not** included in equality checks.
  43. public var cause: Error? {
  44. get {
  45. return self.storage.cause
  46. }
  47. set {
  48. if isKnownUniquelyReferenced(&self.storage) {
  49. self.storage.cause = newValue
  50. } else {
  51. self.storage = .makeStorage(message: self.storage.message, cause: newValue)
  52. }
  53. }
  54. }
  55. // Backing storage for 'message' and 'cause'.
  56. private final class Storage {
  57. // On many happy paths there will be no message or cause, so we'll use this shared reference
  58. // instead of allocating a new storage each time.
  59. //
  60. // Alternatively: `GRPCStatus` could hold a storage optionally however doing so made the code
  61. // quite unreadable.
  62. private static let none = Storage(message: nil, cause: nil)
  63. private init(message: String?, cause: Error?) {
  64. self.message = message
  65. self.cause = cause
  66. }
  67. fileprivate var message: Optional<String>
  68. fileprivate var cause: Optional<Error>
  69. fileprivate static func makeStorage(message: String?, cause: Error?) -> Storage {
  70. if message == nil, cause == nil {
  71. return Storage.none
  72. } else {
  73. return Storage(message: message, cause: cause)
  74. }
  75. }
  76. }
  77. /// Whether the status is '.ok'.
  78. public var isOk: Bool {
  79. return self.code == .ok
  80. }
  81. public init(code: Code, message: String?) {
  82. self.init(code: code, message: message, cause: nil)
  83. }
  84. public init(code: Code, message: String? = nil, cause: Error? = nil) {
  85. self.code = code
  86. self.storage = .makeStorage(message: message, cause: cause)
  87. }
  88. // Frequently used "default" statuses.
  89. /// The default status to return for succeeded calls.
  90. ///
  91. /// - Important: This should *not* be used when checking whether a returned status has an 'ok'
  92. /// status code. Use `GRPCStatus.isOk` or check the code directly.
  93. public static let ok = GRPCStatus(code: .ok, message: nil)
  94. /// "Internal server error" status.
  95. public static let processingError = GRPCStatus(
  96. code: .internalError,
  97. message: "unknown error processing request"
  98. )
  99. }
  100. extension GRPCStatus: Equatable {
  101. public static func == (lhs: GRPCStatus, rhs: GRPCStatus) -> Bool {
  102. return lhs.code == rhs.code && lhs.message == rhs.message
  103. }
  104. }
  105. extension GRPCStatus: CustomStringConvertible {
  106. public var description: String {
  107. if let message = message {
  108. return "\(self.code): \(message)"
  109. } else {
  110. return "\(self.code)"
  111. }
  112. }
  113. }
  114. extension GRPCStatus {
  115. internal var testingOnly_storageObjectIdentifier: ObjectIdentifier {
  116. return ObjectIdentifier(self.storage)
  117. }
  118. }
  119. extension GRPCStatus {
  120. /// Status codes for gRPC operations (replicated from `status_code_enum.h` in the
  121. /// [gRPC core library](https://github.com/grpc/grpc)).
  122. public struct Code: Hashable, CustomStringConvertible {
  123. // `rawValue` must be an `Int` for API reasons and we don't need (or want) to store anything so
  124. // wide, a `UInt8` is fine.
  125. private let _rawValue: UInt8
  126. public var rawValue: Int {
  127. return Int(self._rawValue)
  128. }
  129. public init?(rawValue: Int) {
  130. switch rawValue {
  131. case 0 ... 16:
  132. self._rawValue = UInt8(truncatingIfNeeded: rawValue)
  133. default:
  134. return nil
  135. }
  136. }
  137. private init(_ code: UInt8) {
  138. self._rawValue = code
  139. }
  140. /// Not an error; returned on success.
  141. public static let ok = Code(0)
  142. /// The operation was cancelled (typically by the caller).
  143. public static let cancelled = Code(1)
  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 = Code(2)
  149. /// Client specified an invalid argument. Note that this differs from
  150. /// FAILED_PRECONDITION. INVALID_ARGUMENT 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 = Code(3)
  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 = Code(4)
  160. /// Some requested entity (e.g., file or directory) was not found.
  161. public static let notFound = Code(5)
  162. /// Some entity that we attempted to create (e.g., file or directory) already
  163. /// exists.
  164. public static let alreadyExists = Code(6)
  165. /// The caller does not have permission to execute the specified operation.
  166. /// PERMISSION_DENIED must not be used for rejections caused by exhausting
  167. /// some resource (use RESOURCE_EXHAUSTED instead for those errors).
  168. /// PERMISSION_DENIED must not be used if the caller can not be identified
  169. /// (use UNAUTHENTICATED instead for those errors).
  170. public static let permissionDenied = Code(7)
  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 = Code(8)
  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 FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  180. /// (a) Use UNAVAILABLE if the client can retry just the failing call.
  181. /// (b) Use ABORTED if the client should retry at a higher-level
  182. /// (e.g., restarting a read-modify-write sequence).
  183. /// (c) Use FAILED_PRECONDITION 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, FAILED_PRECONDITION
  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. /// (d) Use FAILED_PRECONDITION 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 = Code(9)
  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 FAILED_PRECONDITION, ABORTED,
  197. /// and UNAVAILABLE.
  198. public static let aborted = Code(10)
  199. /// Operation was attempted past the valid range. E.g., seeking or reading
  200. /// past end of file.
  201. ///
  202. /// Unlike INVALID_ARGUMENT, 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 INVALID_ARGUMENT if asked to read at an offset that is not in the
  205. /// range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  206. /// an offset past the current file size.
  207. ///
  208. /// There is a fair bit of overlap between FAILED_PRECONDITION and
  209. /// OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  210. /// when it applies so that callers who are iterating through a space can
  211. /// easily look for an OUT_OF_RANGE error to detect when they are done.
  212. public static let outOfRange = Code(11)
  213. /// Operation is not implemented or not supported/enabled in this service.
  214. public static let unimplemented = Code(12)
  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 = Code(13)
  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 FAILED_PRECONDITION, ABORTED,
  222. /// and UNAVAILABLE.
  223. public static let unavailable = Code(14)
  224. /// Unrecoverable data loss or corruption.
  225. public static let dataLoss = Code(15)
  226. /// The request does not have valid authentication credentials for the
  227. /// operation.
  228. public static let unauthenticated = Code(16)
  229. public var description: String {
  230. switch self {
  231. case .ok:
  232. return "ok (\(self._rawValue))"
  233. case .cancelled:
  234. return "cancelled (\(self._rawValue))"
  235. case .unknown:
  236. return "unknown (\(self._rawValue))"
  237. case .invalidArgument:
  238. return "invalid argument (\(self._rawValue))"
  239. case .deadlineExceeded:
  240. return "deadline exceeded (\(self._rawValue))"
  241. case .notFound:
  242. return "not found (\(self._rawValue))"
  243. case .alreadyExists:
  244. return "already exists (\(self._rawValue))"
  245. case .permissionDenied:
  246. return "permission denied (\(self._rawValue))"
  247. case .resourceExhausted:
  248. return "resource exhausted (\(self._rawValue))"
  249. case .failedPrecondition:
  250. return "failed precondition (\(self._rawValue))"
  251. case .aborted:
  252. return "aborted (\(self._rawValue))"
  253. case .outOfRange:
  254. return "out of range (\(self._rawValue))"
  255. case .unimplemented:
  256. return "unimplemented (\(self._rawValue))"
  257. case .internalError:
  258. return "internal error (\(self._rawValue))"
  259. case .unavailable:
  260. return "unavailable (\(self._rawValue))"
  261. case .dataLoss:
  262. return "data loss (\(self._rawValue))"
  263. case .unauthenticated:
  264. return "unauthenticated (\(self._rawValue))"
  265. default:
  266. return String(describing: self._rawValue)
  267. }
  268. }
  269. }
  270. }
  271. /// This protocol serves as a customisation point for error types so that gRPC calls may be
  272. /// terminated with an appropriate status.
  273. public protocol GRPCStatusTransformable: Error {
  274. /// Make a `GRPCStatus` from the underlying error.
  275. ///
  276. /// - Returns: A `GRPCStatus` representing the underlying error.
  277. func makeGRPCStatus() -> GRPCStatus
  278. }
  279. extension GRPCStatus: GRPCStatusTransformable {
  280. public func makeGRPCStatus() -> GRPCStatus {
  281. return self
  282. }
  283. }
  284. extension NIOHTTP2Errors.StreamClosed: GRPCStatusTransformable {
  285. public func makeGRPCStatus() -> GRPCStatus {
  286. return .init(code: .unavailable, message: self.localizedDescription, cause: self)
  287. }
  288. }
  289. extension NIOHTTP2Errors.IOOnClosedConnection: GRPCStatusTransformable {
  290. public func makeGRPCStatus() -> GRPCStatus {
  291. return .init(code: .unavailable, message: "The connection is closed", cause: self)
  292. }
  293. }
  294. extension ChannelError: GRPCStatusTransformable {
  295. public func makeGRPCStatus() -> GRPCStatus {
  296. switch self {
  297. case .inputClosed, .outputClosed, .ioOnClosedChannel:
  298. return .init(code: .unavailable, message: "The connection is closed", cause: self)
  299. default:
  300. var processingError = GRPCStatus.processingError
  301. processingError.cause = self
  302. return processingError
  303. }
  304. }
  305. }