|
| 1 | +/* |
| 2 | + * Copyright 2023, 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 | + |
| 17 | +/// An error representing the outcome of an RPC. |
| 18 | +/// |
| 19 | +/// See also ``Status``. |
| 20 | +public struct RPCError: @unchecked Sendable, Hashable, Error { |
| 21 | + // @unchecked because it relies on heap allocated storage and 'isKnownUniquelyReferenced' |
| 22 | + |
| 23 | + private var storage: Storage |
| 24 | + private mutating func ensureStorageIsUnique() { |
| 25 | + if !isKnownUniquelyReferenced(&self.storage) { |
| 26 | + self.storage = self.storage.copy() |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + /// A code representing the high-level domain of the error. |
| 31 | + public var code: Code { |
| 32 | + get { self.storage.code } |
| 33 | + set { |
| 34 | + self.ensureStorageIsUnique() |
| 35 | + self.storage.code = newValue |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /// A message providing additional context about the error. |
| 40 | + public var message: String { |
| 41 | + get { self.storage.message } |
| 42 | + set { |
| 43 | + self.ensureStorageIsUnique() |
| 44 | + self.storage.message = newValue |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + /// Metadata associated with the error. |
| 49 | + /// |
| 50 | + /// Any metadata included in the error thrown from a service will be sent back to the client and |
| 51 | + /// conversely any ``RPCError`` received by the client may include metadata sent by a service. |
| 52 | + /// |
| 53 | + /// Note that clients and servers may synthesise errors which may not include metadata. |
| 54 | + public var metadata: Metadata { |
| 55 | + get { self.storage.metadata } |
| 56 | + set { |
| 57 | + self.ensureStorageIsUnique() |
| 58 | + self.storage.metadata = newValue |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + /// Create a new RPC error. |
| 63 | + /// |
| 64 | + /// - Parameters: |
| 65 | + /// - code: The status code. |
| 66 | + /// - message: A message providing additional context about the code. |
| 67 | + /// - metadata: Any metadata to attach to the error. |
| 68 | + public init(code: Code, message: String, metadata: Metadata = [:]) { |
| 69 | + self.storage = Storage(code: code, message: message, metadata: metadata) |
| 70 | + } |
| 71 | + |
| 72 | + /// Create a new RPC error from the provided ``Status``. |
| 73 | + /// |
| 74 | + /// Returns `nil` if the provided ``Status`` has code ``Status/Code-swift.struct/ok``. |
| 75 | + /// |
| 76 | + /// - Parameter status: The status to convert. |
| 77 | + public init?(status: Status) { |
| 78 | + guard let code = Code(statusCode: status.code) else { return nil } |
| 79 | + self.init(code: code, message: status.message, metadata: [:]) |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +extension RPCError: CustomStringConvertible { |
| 84 | + public var description: String { |
| 85 | + "\(self.code): \"\(self.message)\"" |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +extension RPCError { |
| 90 | + private final class Storage: Hashable { |
| 91 | + var code: RPCError.Code |
| 92 | + var message: String |
| 93 | + var metadata: Metadata |
| 94 | + |
| 95 | + init(code: RPCError.Code, message: String, metadata: Metadata) { |
| 96 | + self.code = code |
| 97 | + self.message = message |
| 98 | + self.metadata = metadata |
| 99 | + } |
| 100 | + |
| 101 | + func copy() -> Self { |
| 102 | + Self(code: self.code, message: self.message, metadata: self.metadata) |
| 103 | + } |
| 104 | + |
| 105 | + func hash(into hasher: inout Hasher) { |
| 106 | + hasher.combine(self.code) |
| 107 | + hasher.combine(self.message) |
| 108 | + hasher.combine(self.metadata) |
| 109 | + } |
| 110 | + |
| 111 | + static func == (lhs: RPCError.Storage, rhs: RPCError.Storage) -> Bool { |
| 112 | + return lhs.code == rhs.code && lhs.message == rhs.message && lhs.metadata == rhs.metadata |
| 113 | + } |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +extension RPCError { |
| 118 | + public struct Code: Hashable, Sendable, CustomStringConvertible { |
| 119 | + /// The numeric value of the error code. |
| 120 | + public var rawValue: Int { Int(self.wrapped.rawValue) } |
| 121 | + |
| 122 | + private var wrapped: Status.Code.Wrapped |
| 123 | + private init(_ wrapped: Status.Code.Wrapped) { |
| 124 | + self.wrapped = wrapped |
| 125 | + } |
| 126 | + |
| 127 | + internal init?(statusCode: Status.Code) { |
| 128 | + if statusCode == .ok { |
| 129 | + return nil |
| 130 | + } else { |
| 131 | + self.wrapped = statusCode.wrapped |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + public var description: String { |
| 136 | + String(describing: self.wrapped) |
| 137 | + } |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +extension RPCError.Code { |
| 142 | + /// The operation was cancelled (typically by the caller). |
| 143 | + public static let cancelled = Self(.cancelled) |
| 144 | + |
| 145 | + /// Unknown error. An example of where this error may be returned is if a |
| 146 | + /// Status value received from another address space belongs to an error-space |
| 147 | + /// that is not known in this address space. Also errors raised by APIs that |
| 148 | + /// do not return enough error information may be converted to this error. |
| 149 | + public static let unknown = Self(.unknown) |
| 150 | + |
| 151 | + /// Client specified an invalid argument. Note that this differs from |
| 152 | + /// ``failedPrecondition``. ``invalidArgument`` indicates arguments that are |
| 153 | + /// problematic regardless of the state of the system (e.g., a malformed file |
| 154 | + /// name). |
| 155 | + public static let invalidArgument = Self(.invalidArgument) |
| 156 | + |
| 157 | + /// Deadline expired before operation could complete. For operations that |
| 158 | + /// change the state of the system, this error may be returned even if the |
| 159 | + /// operation has completed successfully. For example, a successful response |
| 160 | + /// from a server could have been delayed long enough for the deadline to |
| 161 | + /// expire. |
| 162 | + public static let deadlineExceeded = Self(.deadlineExceeded) |
| 163 | + |
| 164 | + /// Some requested entity (e.g., file or directory) was not found. |
| 165 | + public static let notFound = Self(.notFound) |
| 166 | + |
| 167 | + /// Some entity that we attempted to create (e.g., file or directory) already |
| 168 | + /// exists. |
| 169 | + public static let alreadyExists = Self(.alreadyExists) |
| 170 | + |
| 171 | + /// The caller does not have permission to execute the specified operation. |
| 172 | + /// ``permissionDenied`` must not be used for rejections caused by exhausting |
| 173 | + /// some resource (use ``resourceExhausted`` instead for those errors). |
| 174 | + /// ``permissionDenied`` must not be used if the caller can not be identified |
| 175 | + /// (use ``unauthenticated`` instead for those errors). |
| 176 | + public static let permissionDenied = Self(.permissionDenied) |
| 177 | + |
| 178 | + /// Some resource has been exhausted, perhaps a per-user quota, or perhaps the |
| 179 | + /// entire file system is out of space. |
| 180 | + public static let resourceExhausted = Self(.resourceExhausted) |
| 181 | + |
| 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 ``failedPrecondition``, ``aborted``, and ``unavailable``: |
| 188 | + /// - Use ``unavailable`` if the client can retry just the failing call. |
| 189 | + /// - Use ``aborted`` if the client should retry at a higher-level |
| 190 | + /// (e.g., restarting a read-modify-write sequence). |
| 191 | + /// - Use ``failedPrecondition`` 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, ``failedPrecondition`` |
| 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 | + /// - Use ``failedPrecondition`` 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 = Self(.failedPrecondition) |
| 201 | + |
| 202 | + /// The operation was aborted, typically due to a concurrency issue like |
| 203 | + /// sequencer check failures, transaction aborts, etc. |
| 204 | + /// |
| 205 | + /// See litmus test above for deciding between ``failedPrecondition``, ``aborted``, |
| 206 | + /// and ``unavailable``. |
| 207 | + public static let aborted = Self(.aborted) |
| 208 | + |
| 209 | + /// Operation was attempted past the valid range. E.g., seeking or reading |
| 210 | + /// past end of file. |
| 211 | + /// |
| 212 | + /// Unlike ``invalidArgument``, this error indicates a problem that may be fixed |
| 213 | + /// if the system state changes. For example, a 32-bit file system will |
| 214 | + /// generate ``invalidArgument`` if asked to read at an offset that is not in the |
| 215 | + /// range [0,2^32-1], but it will generate ``outOfRange`` if asked to read from |
| 216 | + /// an offset past the current file size. |
| 217 | + /// |
| 218 | + /// There is a fair bit of overlap between ``failedPrecondition`` and |
| 219 | + /// ``outOfRange``. We recommend using ``outOfRange`` (the more specific error) |
| 220 | + /// when it applies so that callers who are iterating through a space can |
| 221 | + /// easily look for an ``outOfRange`` error to detect when they are done. |
| 222 | + public static let outOfRange = Self(.outOfRange) |
| 223 | + |
| 224 | + /// Operation is not implemented or not supported/enabled in this service. |
| 225 | + public static let unimplemented = Self(.unimplemented) |
| 226 | + |
| 227 | + /// Internal errors. Means some invariants expected by underlying System has |
| 228 | + /// been broken. If you see one of these errors, Something is very broken. |
| 229 | + public static let internalError = Self(.internalError) |
| 230 | + |
| 231 | + /// The service is currently unavailable. This is a most likely a transient |
| 232 | + /// condition and may be corrected by retrying with a backoff. |
| 233 | + /// |
| 234 | + /// See litmus test above for deciding between ``failedPrecondition``, ``aborted``, |
| 235 | + /// and ``unavailable``. |
| 236 | + public static let unavailable = Self(.unavailable) |
| 237 | + |
| 238 | + /// Unrecoverable data loss or corruption. |
| 239 | + public static let dataLoss = Self(.dataLoss) |
| 240 | + |
| 241 | + /// The request does not have valid authentication credentials for the |
| 242 | + /// operation. |
| 243 | + public static let unauthenticated = Self(.unauthenticated) |
| 244 | +} |
0 commit comments