GRPCStatus.swift 8.6 KB

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