GRPCStatus.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 NIO
  18. import NIOHTTP1
  19. import NIOHTTP2
  20. /// Encapsulates the result of a gRPC call.
  21. ///
  22. /// We use a `class` here for a couple of reasons:
  23. /// - The size of the equivalent `struct` is larger than the value buffer in an existential
  24. /// container so would incur a heap allocation each time a `GRPCStatus` is passed to a function
  25. /// taking an `Error`.
  26. /// - We aren't using value semantics (since all properties are constant).
  27. public final class GRPCStatus: Error {
  28. /// The status code of the RPC.
  29. public let code: Code
  30. /// The status message of the RPC.
  31. public let message: String?
  32. /// Whether the status is '.ok'.
  33. public var isOk: Bool {
  34. return self.code == .ok
  35. }
  36. public init(code: Code, message: String?) {
  37. self.code = code
  38. self.message = message
  39. }
  40. // Frequently used "default" statuses.
  41. /// The default status to return for succeeded calls.
  42. ///
  43. /// - Important: This should *not* be used when checking whether a returned status has an 'ok'
  44. /// status code. Use `GRPCStatus.isOk` or check the code directly.
  45. public static let ok = GRPCStatus(code: .ok, message: "OK")
  46. /// "Internal server error" status.
  47. public static let processingError = GRPCStatus(
  48. code: .internalError,
  49. message: "unknown error processing request"
  50. )
  51. }
  52. extension GRPCStatus: Equatable {
  53. public static func == (lhs: GRPCStatus, rhs: GRPCStatus) -> Bool {
  54. return lhs.code == rhs.code && lhs.message == rhs.message
  55. }
  56. }
  57. extension GRPCStatus: CustomStringConvertible {
  58. public var description: String {
  59. if let message = message {
  60. return "\(self.code): \(message)"
  61. } else {
  62. return "\(self.code)"
  63. }
  64. }
  65. }
  66. extension GRPCStatus {
  67. /// Status codes for gRPC operations (replicated from `status_code_enum.h` in the
  68. /// [gRPC core library](https://github.com/grpc/grpc)).
  69. public struct Code: Hashable, CustomStringConvertible {
  70. public let rawValue: Int
  71. public init?(rawValue: Int) {
  72. switch rawValue {
  73. case 0 ... 16:
  74. self.rawValue = rawValue
  75. default:
  76. return nil
  77. }
  78. }
  79. private init(_ code: Int) {
  80. self.rawValue = code
  81. }
  82. /// Not an error; returned on success.
  83. public static let ok = Code(0)
  84. /// The operation was cancelled (typically by the caller).
  85. public static let cancelled = Code(1)
  86. /// Unknown error. An example of where this error may be returned is if a
  87. /// Status value received from another address space belongs to an error-space
  88. /// that is not known in this address space. Also errors raised by APIs that
  89. /// do not return enough error information may be converted to this error.
  90. public static let unknown = Code(2)
  91. /// Client specified an invalid argument. Note that this differs from
  92. /// FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  93. /// problematic regardless of the state of the system (e.g., a malformed file
  94. /// name).
  95. public static let invalidArgument = Code(3)
  96. /// Deadline expired before operation could complete. For operations that
  97. /// change the state of the system, this error may be returned even if the
  98. /// operation has completed successfully. For example, a successful response
  99. /// from a server could have been delayed long enough for the deadline to
  100. /// expire.
  101. public static let deadlineExceeded = Code(4)
  102. /// Some requested entity (e.g., file or directory) was not found.
  103. public static let notFound = Code(5)
  104. /// Some entity that we attempted to create (e.g., file or directory) already
  105. /// exists.
  106. public static let alreadyExists = Code(6)
  107. /// The caller does not have permission to execute the specified operation.
  108. /// PERMISSION_DENIED must not be used for rejections caused by exhausting
  109. /// some resource (use RESOURCE_EXHAUSTED instead for those errors).
  110. /// PERMISSION_DENIED must not be used if the caller can not be identified
  111. /// (use UNAUTHENTICATED instead for those errors).
  112. public static let permissionDenied = Code(7)
  113. /// Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  114. /// entire file system is out of space.
  115. public static let resourceExhausted = Code(8)
  116. /// Operation was rejected because the system is not in a state required for
  117. /// the operation's execution. For example, directory to be deleted may be
  118. /// non-empty, an rmdir operation is applied to a non-directory, etc.
  119. ///
  120. /// A litmus test that may help a service implementor in deciding
  121. /// between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  122. /// (a) Use UNAVAILABLE if the client can retry just the failing call.
  123. /// (b) Use ABORTED if the client should retry at a higher-level
  124. /// (e.g., restarting a read-modify-write sequence).
  125. /// (c) Use FAILED_PRECONDITION if the client should not retry until
  126. /// the system state has been explicitly fixed. E.g., if an "rmdir"
  127. /// fails because the directory is non-empty, FAILED_PRECONDITION
  128. /// should be returned since the client should not retry unless
  129. /// they have first fixed up the directory by deleting files from it.
  130. /// (d) Use FAILED_PRECONDITION if the client performs conditional
  131. /// REST Get/Update/Delete on a resource and the resource on the
  132. /// server does not match the condition. E.g., conflicting
  133. /// read-modify-write on the same resource.
  134. public static let failedPrecondition = Code(9)
  135. /// The operation was aborted, typically due to a concurrency issue like
  136. /// sequencer check failures, transaction aborts, etc.
  137. ///
  138. /// See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  139. /// and UNAVAILABLE.
  140. public static let aborted = Code(10)
  141. /// Operation was attempted past the valid range. E.g., seeking or reading
  142. /// past end of file.
  143. ///
  144. /// Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  145. /// if the system state changes. For example, a 32-bit file system will
  146. /// generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  147. /// range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  148. /// an offset past the current file size.
  149. ///
  150. /// There is a fair bit of overlap between FAILED_PRECONDITION and
  151. /// OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  152. /// when it applies so that callers who are iterating through a space can
  153. /// easily look for an OUT_OF_RANGE error to detect when they are done.
  154. public static let outOfRange = Code(11)
  155. /// Operation is not implemented or not supported/enabled in this service.
  156. public static let unimplemented = Code(12)
  157. /// Internal errors. Means some invariants expected by underlying System has
  158. /// been broken. If you see one of these errors, Something is very broken.
  159. public static let internalError = Code(13)
  160. /// The service is currently unavailable. This is a most likely a transient
  161. /// condition and may be corrected by retrying with a backoff.
  162. ///
  163. /// See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  164. /// and UNAVAILABLE.
  165. public static let unavailable = Code(14)
  166. /// Unrecoverable data loss or corruption.
  167. public static let dataLoss = Code(15)
  168. /// The request does not have valid authentication credentials for the
  169. /// operation.
  170. public static let unauthenticated = Code(16)
  171. public var description: String {
  172. switch self {
  173. case .ok:
  174. return "ok (\(self.rawValue))"
  175. case .cancelled:
  176. return "cancelled (\(self.rawValue))"
  177. case .unknown:
  178. return "unknown (\(self.rawValue))"
  179. case .invalidArgument:
  180. return "invalid argument (\(self.rawValue))"
  181. case .deadlineExceeded:
  182. return "deadline exceeded (\(self.rawValue))"
  183. case .notFound:
  184. return "not found (\(self.rawValue))"
  185. case .alreadyExists:
  186. return "already exists (\(self.rawValue))"
  187. case .permissionDenied:
  188. return "permission denied (\(self.rawValue))"
  189. case .resourceExhausted:
  190. return "resource exhausted (\(self.rawValue))"
  191. case .failedPrecondition:
  192. return "failed precondition (\(self.rawValue))"
  193. case .aborted:
  194. return "aborted (\(self.rawValue))"
  195. case .outOfRange:
  196. return "out of range (\(self.rawValue))"
  197. case .unimplemented:
  198. return "unimplemented (\(self.rawValue))"
  199. case .internalError:
  200. return "internal error (\(self.rawValue))"
  201. case .unavailable:
  202. return "unavailable (\(self.rawValue))"
  203. case .dataLoss:
  204. return "data loss (\(self.rawValue))"
  205. case .unauthenticated:
  206. return "unauthenticated (\(self.rawValue))"
  207. default:
  208. return String(describing: self.rawValue)
  209. }
  210. }
  211. }
  212. }
  213. /// This protocol serves as a customisation point for error types so that gRPC calls may be
  214. /// terminated with an appropriate status.
  215. public protocol GRPCStatusTransformable: Error {
  216. /// Make a `GRPCStatus` from the underlying error.
  217. ///
  218. /// - Returns: A `GRPCStatus` representing the underlying error.
  219. func makeGRPCStatus() -> GRPCStatus
  220. }
  221. extension GRPCStatus: GRPCStatusTransformable {
  222. public func makeGRPCStatus() -> GRPCStatus {
  223. return self
  224. }
  225. }
  226. extension NIOHTTP2Errors.StreamClosed: GRPCStatusTransformable {
  227. public func makeGRPCStatus() -> GRPCStatus {
  228. return .init(code: .unavailable, message: self.localizedDescription)
  229. }
  230. }
  231. extension NIOHTTP2Errors.IOOnClosedConnection: GRPCStatusTransformable {
  232. public func makeGRPCStatus() -> GRPCStatus {
  233. return .init(code: .unavailable, message: "The connection is closed")
  234. }
  235. }
  236. extension ChannelError: GRPCStatusTransformable {
  237. public func makeGRPCStatus() -> GRPCStatus {
  238. switch self {
  239. case .inputClosed, .outputClosed, .ioOnClosedChannel:
  240. return .init(code: .unavailable, message: "The connection is closed")
  241. default:
  242. return .processingError
  243. }
  244. }
  245. }