GRPCStatus.swift 8.1 KB

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