GRPCStatus.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 = Self.processingError(cause: nil)
  96. public static func processingError(cause: Error?) -> GRPCStatus {
  97. return GRPCStatus(
  98. code: .internalError,
  99. message: "unknown error processing request",
  100. cause: cause
  101. )
  102. }
  103. }
  104. extension GRPCStatus: Equatable {
  105. public static func == (lhs: GRPCStatus, rhs: GRPCStatus) -> Bool {
  106. return lhs.code == rhs.code && lhs.message == rhs.message
  107. }
  108. }
  109. extension GRPCStatus: CustomStringConvertible {
  110. public var description: String {
  111. if let message = message {
  112. return "\(self.code): \(message)"
  113. } else {
  114. return "\(self.code)"
  115. }
  116. }
  117. }
  118. extension GRPCStatus {
  119. internal var testingOnly_storageObjectIdentifier: ObjectIdentifier {
  120. return ObjectIdentifier(self.storage)
  121. }
  122. }
  123. extension GRPCStatus {
  124. /// Status codes for gRPC operations (replicated from `status_code_enum.h` in the
  125. /// [gRPC core library](https://github.com/grpc/grpc)).
  126. public struct Code: Hashable, CustomStringConvertible {
  127. // `rawValue` must be an `Int` for API reasons and we don't need (or want) to store anything so
  128. // wide, a `UInt8` is fine.
  129. private let _rawValue: UInt8
  130. public var rawValue: Int {
  131. return Int(self._rawValue)
  132. }
  133. public init?(rawValue: Int) {
  134. switch rawValue {
  135. case 0 ... 16:
  136. self._rawValue = UInt8(truncatingIfNeeded: rawValue)
  137. default:
  138. return nil
  139. }
  140. }
  141. private init(_ code: UInt8) {
  142. self._rawValue = code
  143. }
  144. /// Not an error; returned on success.
  145. public static let ok = Code(0)
  146. /// The operation was cancelled (typically by the caller).
  147. public static let cancelled = Code(1)
  148. /// Unknown error. An example of where this error may be returned is if a
  149. /// Status value received from another address space belongs to an error-space
  150. /// that is not known in this address space. Also errors raised by APIs that
  151. /// do not return enough error information may be converted to this error.
  152. public static let unknown = Code(2)
  153. /// Client specified an invalid argument. Note that this differs from
  154. /// FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  155. /// problematic regardless of the state of the system (e.g., a malformed file
  156. /// name).
  157. public static let invalidArgument = Code(3)
  158. /// Deadline expired before operation could complete. For operations that
  159. /// change the state of the system, this error may be returned even if the
  160. /// operation has completed successfully. For example, a successful response
  161. /// from a server could have been delayed long enough for the deadline to
  162. /// expire.
  163. public static let deadlineExceeded = Code(4)
  164. /// Some requested entity (e.g., file or directory) was not found.
  165. public static let notFound = Code(5)
  166. /// Some entity that we attempted to create (e.g., file or directory) already
  167. /// exists.
  168. public static let alreadyExists = Code(6)
  169. /// The caller does not have permission to execute the specified operation.
  170. /// PERMISSION_DENIED must not be used for rejections caused by exhausting
  171. /// some resource (use RESOURCE_EXHAUSTED instead for those errors).
  172. /// PERMISSION_DENIED must not be used if the caller can not be identified
  173. /// (use UNAUTHENTICATED instead for those errors).
  174. public static let permissionDenied = Code(7)
  175. /// Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  176. /// entire file system is out of space.
  177. public static let resourceExhausted = Code(8)
  178. /// Operation was rejected because the system is not in a state required for
  179. /// the operation's execution. For example, directory to be deleted may be
  180. /// non-empty, an rmdir operation is applied to a non-directory, etc.
  181. ///
  182. /// A litmus test that may help a service implementor in deciding
  183. /// between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  184. /// (a) Use UNAVAILABLE if the client can retry just the failing call.
  185. /// (b) Use ABORTED if the client should retry at a higher-level
  186. /// (e.g., restarting a read-modify-write sequence).
  187. /// (c) Use FAILED_PRECONDITION if the client should not retry until
  188. /// the system state has been explicitly fixed. E.g., if an "rmdir"
  189. /// fails because the directory is non-empty, FAILED_PRECONDITION
  190. /// should be returned since the client should not retry unless
  191. /// they have first fixed up the directory by deleting files from it.
  192. /// (d) Use FAILED_PRECONDITION if the client performs conditional
  193. /// REST Get/Update/Delete on a resource and the resource on the
  194. /// server does not match the condition. E.g., conflicting
  195. /// read-modify-write on the same resource.
  196. public static let failedPrecondition = Code(9)
  197. /// The operation was aborted, typically due to a concurrency issue like
  198. /// sequencer check failures, transaction aborts, etc.
  199. ///
  200. /// See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  201. /// and UNAVAILABLE.
  202. public static let aborted = Code(10)
  203. /// Operation was attempted past the valid range. E.g., seeking or reading
  204. /// past end of file.
  205. ///
  206. /// Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  207. /// if the system state changes. For example, a 32-bit file system will
  208. /// generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  209. /// range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  210. /// an offset past the current file size.
  211. ///
  212. /// There is a fair bit of overlap between FAILED_PRECONDITION and
  213. /// OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  214. /// when it applies so that callers who are iterating through a space can
  215. /// easily look for an OUT_OF_RANGE error to detect when they are done.
  216. public static let outOfRange = Code(11)
  217. /// Operation is not implemented or not supported/enabled in this service.
  218. public static let unimplemented = Code(12)
  219. /// Internal errors. Means some invariants expected by underlying System has
  220. /// been broken. If you see one of these errors, Something is very broken.
  221. public static let internalError = Code(13)
  222. /// The service is currently unavailable. This is a most likely a transient
  223. /// condition and may be corrected by retrying with a backoff.
  224. ///
  225. /// See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  226. /// and UNAVAILABLE.
  227. public static let unavailable = Code(14)
  228. /// Unrecoverable data loss or corruption.
  229. public static let dataLoss = Code(15)
  230. /// The request does not have valid authentication credentials for the
  231. /// operation.
  232. public static let unauthenticated = Code(16)
  233. public var description: String {
  234. switch self {
  235. case .ok:
  236. return "ok (\(self._rawValue))"
  237. case .cancelled:
  238. return "cancelled (\(self._rawValue))"
  239. case .unknown:
  240. return "unknown (\(self._rawValue))"
  241. case .invalidArgument:
  242. return "invalid argument (\(self._rawValue))"
  243. case .deadlineExceeded:
  244. return "deadline exceeded (\(self._rawValue))"
  245. case .notFound:
  246. return "not found (\(self._rawValue))"
  247. case .alreadyExists:
  248. return "already exists (\(self._rawValue))"
  249. case .permissionDenied:
  250. return "permission denied (\(self._rawValue))"
  251. case .resourceExhausted:
  252. return "resource exhausted (\(self._rawValue))"
  253. case .failedPrecondition:
  254. return "failed precondition (\(self._rawValue))"
  255. case .aborted:
  256. return "aborted (\(self._rawValue))"
  257. case .outOfRange:
  258. return "out of range (\(self._rawValue))"
  259. case .unimplemented:
  260. return "unimplemented (\(self._rawValue))"
  261. case .internalError:
  262. return "internal error (\(self._rawValue))"
  263. case .unavailable:
  264. return "unavailable (\(self._rawValue))"
  265. case .dataLoss:
  266. return "data loss (\(self._rawValue))"
  267. case .unauthenticated:
  268. return "unauthenticated (\(self._rawValue))"
  269. default:
  270. return String(describing: self._rawValue)
  271. }
  272. }
  273. }
  274. }
  275. /// This protocol serves as a customisation point for error types so that gRPC calls may be
  276. /// terminated with an appropriate status.
  277. public protocol GRPCStatusTransformable: Error {
  278. /// Make a `GRPCStatus` from the underlying error.
  279. ///
  280. /// - Returns: A `GRPCStatus` representing the underlying error.
  281. func makeGRPCStatus() -> GRPCStatus
  282. }
  283. extension GRPCStatus: GRPCStatusTransformable {
  284. public func makeGRPCStatus() -> GRPCStatus {
  285. return self
  286. }
  287. }
  288. extension NIOHTTP2Errors.StreamClosed: GRPCStatusTransformable {
  289. public func makeGRPCStatus() -> GRPCStatus {
  290. return .init(code: .unavailable, message: self.localizedDescription, cause: self)
  291. }
  292. }
  293. extension NIOHTTP2Errors.IOOnClosedConnection: GRPCStatusTransformable {
  294. public func makeGRPCStatus() -> GRPCStatus {
  295. return .init(code: .unavailable, message: "The connection is closed", cause: self)
  296. }
  297. }
  298. extension ChannelError: GRPCStatusTransformable {
  299. public func makeGRPCStatus() -> GRPCStatus {
  300. switch self {
  301. case .inputClosed, .outputClosed, .ioOnClosedChannel:
  302. return .init(code: .unavailable, message: "The connection is closed", cause: self)
  303. default:
  304. var processingError = GRPCStatus.processingError
  305. processingError.cause = self
  306. return processingError
  307. }
  308. }
  309. }