GRPCStatus.swift 10 KB

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