GRPCStatus.swift 13 KB

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