GRPCStatus.swift 13 KB

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