status.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. // Copyright 2019 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: status.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file defines the Abseil `status` library, consisting of:
  20. //
  21. // * An `y_absl::Status` class for holding error handling information
  22. // * A set of canonical `y_absl::StatusCode` error codes, and associated
  23. // utilities for generating and propagating status codes.
  24. // * A set of helper functions for creating status codes and checking their
  25. // values
  26. //
  27. // Within Google, `y_absl::Status` is the primary mechanism for communicating
  28. // errors in C++, and is used to represent error state in both in-process
  29. // library calls as well as RPC calls. Some of these errors may be recoverable,
  30. // but others may not. Most functions that can produce a recoverable error
  31. // should be designed to return an `y_absl::Status` (or `y_absl::StatusOr`).
  32. //
  33. // Example:
  34. //
  35. // y_absl::Status myFunction(y_absl::string_view fname, ...) {
  36. // ...
  37. // // encounter error
  38. // if (error condition) {
  39. // return y_absl::InvalidArgumentError("bad mode");
  40. // }
  41. // // else, return OK
  42. // return y_absl::OkStatus();
  43. // }
  44. //
  45. // An `y_absl::Status` is designed to either return "OK" or one of a number of
  46. // different error codes, corresponding to typical error conditions.
  47. // In almost all cases, when using `y_absl::Status` you should use the canonical
  48. // error codes (of type `y_absl::StatusCode`) enumerated in this header file.
  49. // These canonical codes are understood across the codebase and will be
  50. // accepted across all API and RPC boundaries.
  51. #ifndef Y_ABSL_STATUS_STATUS_H_
  52. #define Y_ABSL_STATUS_STATUS_H_
  53. #include <cassert>
  54. #include <cstdint>
  55. #include <ostream>
  56. #include <util/generic/string.h>
  57. #include <utility>
  58. #include "y_absl/base/attributes.h"
  59. #include "y_absl/base/config.h"
  60. #include "y_absl/base/macros.h"
  61. #include "y_absl/base/nullability.h"
  62. #include "y_absl/base/optimization.h"
  63. #include "y_absl/functional/function_ref.h"
  64. #include "y_absl/status/internal/status_internal.h"
  65. #include "y_absl/strings/cord.h"
  66. #include "y_absl/strings/string_view.h"
  67. #include "y_absl/types/optional.h"
  68. namespace y_absl {
  69. Y_ABSL_NAMESPACE_BEGIN
  70. // y_absl::StatusCode
  71. //
  72. // An `y_absl::StatusCode` is an enumerated type indicating either no error ("OK")
  73. // or an error condition. In most cases, an `y_absl::Status` indicates a
  74. // recoverable error, and the purpose of signalling an error is to indicate what
  75. // action to take in response to that error. These error codes map to the proto
  76. // RPC error codes indicated in https://cloud.google.com/apis/design/errors.
  77. //
  78. // The errors listed below are the canonical errors associated with
  79. // `y_absl::Status` and are used throughout the codebase. As a result, these
  80. // error codes are somewhat generic.
  81. //
  82. // In general, try to return the most specific error that applies if more than
  83. // one error may pertain. For example, prefer `kOutOfRange` over
  84. // `kFailedPrecondition` if both codes apply. Similarly prefer `kNotFound` or
  85. // `kAlreadyExists` over `kFailedPrecondition`.
  86. //
  87. // Because these errors may cross RPC boundaries, these codes are tied to the
  88. // `google.rpc.Code` definitions within
  89. // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  90. // The string value of these RPC codes is denoted within each enum below.
  91. //
  92. // If your error handling code requires more context, you can attach payloads
  93. // to your status. See `y_absl::Status::SetPayload()` and
  94. // `y_absl::Status::GetPayload()` below.
  95. enum class StatusCode : int {
  96. // StatusCode::kOk
  97. //
  98. // kOK (gRPC code "OK") does not indicate an error; this value is returned on
  99. // success. It is typical to check for this value before proceeding on any
  100. // given call across an API or RPC boundary. To check this value, use the
  101. // `y_absl::Status::ok()` member function rather than inspecting the raw code.
  102. kOk = 0,
  103. // StatusCode::kCancelled
  104. //
  105. // kCancelled (gRPC code "CANCELLED") indicates the operation was cancelled,
  106. // typically by the caller.
  107. kCancelled = 1,
  108. // StatusCode::kUnknown
  109. //
  110. // kUnknown (gRPC code "UNKNOWN") indicates an unknown error occurred. In
  111. // general, more specific errors should be raised, if possible. Errors raised
  112. // by APIs that do not return enough error information may be converted to
  113. // this error.
  114. kUnknown = 2,
  115. // StatusCode::kInvalidArgument
  116. //
  117. // kInvalidArgument (gRPC code "INVALID_ARGUMENT") indicates the caller
  118. // specified an invalid argument, such as a malformed filename. Note that use
  119. // of such errors should be narrowly limited to indicate the invalid nature of
  120. // the arguments themselves. Errors with validly formed arguments that may
  121. // cause errors with the state of the receiving system should be denoted with
  122. // `kFailedPrecondition` instead.
  123. kInvalidArgument = 3,
  124. // StatusCode::kDeadlineExceeded
  125. //
  126. // kDeadlineExceeded (gRPC code "DEADLINE_EXCEEDED") indicates a deadline
  127. // expired before the operation could complete. For operations that may change
  128. // state within a system, this error may be returned even if the operation has
  129. // completed successfully. For example, a successful response from a server
  130. // could have been delayed long enough for the deadline to expire.
  131. kDeadlineExceeded = 4,
  132. // StatusCode::kNotFound
  133. //
  134. // kNotFound (gRPC code "NOT_FOUND") indicates some requested entity (such as
  135. // a file or directory) was not found.
  136. //
  137. // `kNotFound` is useful if a request should be denied for an entire class of
  138. // users, such as during a gradual feature rollout or undocumented allow list.
  139. // If a request should be denied for specific sets of users, such as through
  140. // user-based access control, use `kPermissionDenied` instead.
  141. kNotFound = 5,
  142. // StatusCode::kAlreadyExists
  143. //
  144. // kAlreadyExists (gRPC code "ALREADY_EXISTS") indicates that the entity a
  145. // caller attempted to create (such as a file or directory) is already
  146. // present.
  147. kAlreadyExists = 6,
  148. // StatusCode::kPermissionDenied
  149. //
  150. // kPermissionDenied (gRPC code "PERMISSION_DENIED") indicates that the caller
  151. // does not have permission to execute the specified operation. Note that this
  152. // error is different than an error due to an *un*authenticated user. This
  153. // error code does not imply the request is valid or the requested entity
  154. // exists or satisfies any other pre-conditions.
  155. //
  156. // `kPermissionDenied` must not be used for rejections caused by exhausting
  157. // some resource. Instead, use `kResourceExhausted` for those errors.
  158. // `kPermissionDenied` must not be used if the caller cannot be identified.
  159. // Instead, use `kUnauthenticated` for those errors.
  160. kPermissionDenied = 7,
  161. // StatusCode::kResourceExhausted
  162. //
  163. // kResourceExhausted (gRPC code "RESOURCE_EXHAUSTED") indicates some resource
  164. // has been exhausted, perhaps a per-user quota, or perhaps the entire file
  165. // system is out of space.
  166. kResourceExhausted = 8,
  167. // StatusCode::kFailedPrecondition
  168. //
  169. // kFailedPrecondition (gRPC code "FAILED_PRECONDITION") indicates that the
  170. // operation was rejected because the system is not in a state required for
  171. // the operation's execution. For example, a directory to be deleted may be
  172. // non-empty, an "rmdir" operation is applied to a non-directory, etc.
  173. //
  174. // Some guidelines that may help a service implementer in deciding between
  175. // `kFailedPrecondition`, `kAborted`, and `kUnavailable`:
  176. //
  177. // (a) Use `kUnavailable` if the client can retry just the failing call.
  178. // (b) Use `kAborted` if the client should retry at a higher transaction
  179. // level (such as when a client-specified test-and-set fails, indicating
  180. // the client should restart a read-modify-write sequence).
  181. // (c) Use `kFailedPrecondition` if the client should not retry until
  182. // the system state has been explicitly fixed. For example, if a "rmdir"
  183. // fails because the directory is non-empty, `kFailedPrecondition`
  184. // should be returned since the client should not retry unless
  185. // the files are deleted from the directory.
  186. kFailedPrecondition = 9,
  187. // StatusCode::kAborted
  188. //
  189. // kAborted (gRPC code "ABORTED") indicates the operation was aborted,
  190. // typically due to a concurrency issue such as a sequencer check failure or a
  191. // failed transaction.
  192. //
  193. // See the guidelines above for deciding between `kFailedPrecondition`,
  194. // `kAborted`, and `kUnavailable`.
  195. kAborted = 10,
  196. // StatusCode::kOutOfRange
  197. //
  198. // kOutOfRange (gRPC code "OUT_OF_RANGE") indicates the operation was
  199. // attempted past the valid range, such as seeking or reading past an
  200. // end-of-file.
  201. //
  202. // Unlike `kInvalidArgument`, this error indicates a problem that may
  203. // be fixed if the system state changes. For example, a 32-bit file
  204. // system will generate `kInvalidArgument` if asked to read at an
  205. // offset that is not in the range [0,2^32-1], but it will generate
  206. // `kOutOfRange` if asked to read from an offset past the current
  207. // file size.
  208. //
  209. // There is a fair bit of overlap between `kFailedPrecondition` and
  210. // `kOutOfRange`. We recommend using `kOutOfRange` (the more specific
  211. // error) when it applies so that callers who are iterating through
  212. // a space can easily look for an `kOutOfRange` error to detect when
  213. // they are done.
  214. kOutOfRange = 11,
  215. // StatusCode::kUnimplemented
  216. //
  217. // kUnimplemented (gRPC code "UNIMPLEMENTED") indicates the operation is not
  218. // implemented or supported in this service. In this case, the operation
  219. // should not be re-attempted.
  220. kUnimplemented = 12,
  221. // StatusCode::kInternal
  222. //
  223. // kInternal (gRPC code "INTERNAL") indicates an internal error has occurred
  224. // and some invariants expected by the underlying system have not been
  225. // satisfied. This error code is reserved for serious errors.
  226. kInternal = 13,
  227. // StatusCode::kUnavailable
  228. //
  229. // kUnavailable (gRPC code "UNAVAILABLE") indicates the service is currently
  230. // unavailable and that this is most likely a transient condition. An error
  231. // such as this can be corrected by retrying with a backoff scheme. Note that
  232. // it is not always safe to retry non-idempotent operations.
  233. //
  234. // See the guidelines above for deciding between `kFailedPrecondition`,
  235. // `kAborted`, and `kUnavailable`.
  236. kUnavailable = 14,
  237. // StatusCode::kDataLoss
  238. //
  239. // kDataLoss (gRPC code "DATA_LOSS") indicates that unrecoverable data loss or
  240. // corruption has occurred. As this error is serious, proper alerting should
  241. // be attached to errors such as this.
  242. kDataLoss = 15,
  243. // StatusCode::kUnauthenticated
  244. //
  245. // kUnauthenticated (gRPC code "UNAUTHENTICATED") indicates that the request
  246. // does not have valid authentication credentials for the operation. Correct
  247. // the authentication and try again.
  248. kUnauthenticated = 16,
  249. // StatusCode::DoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_
  250. //
  251. // NOTE: this error code entry should not be used and you should not rely on
  252. // its value, which may change.
  253. //
  254. // The purpose of this enumerated value is to force people who handle status
  255. // codes with `switch()` statements to *not* simply enumerate all possible
  256. // values, but instead provide a "default:" case. Providing such a default
  257. // case ensures that code will compile when new codes are added.
  258. kDoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_ = 20
  259. };
  260. // StatusCodeToString()
  261. //
  262. // Returns the name for the status code, or "" if it is an unknown value.
  263. TString StatusCodeToString(StatusCode code);
  264. // operator<<
  265. //
  266. // Streams StatusCodeToString(code) to `os`.
  267. std::ostream& operator<<(std::ostream& os, StatusCode code);
  268. // y_absl::StatusToStringMode
  269. //
  270. // An `y_absl::StatusToStringMode` is an enumerated type indicating how
  271. // `y_absl::Status::ToString()` should construct the output string for a non-ok
  272. // status.
  273. enum class StatusToStringMode : int {
  274. // ToString will not contain any extra data (such as payloads). It will only
  275. // contain the error code and message, if any.
  276. kWithNoExtraData = 0,
  277. // ToString will contain the payloads.
  278. kWithPayload = 1 << 0,
  279. // ToString will include all the extra data this Status has.
  280. kWithEverything = ~kWithNoExtraData,
  281. // Default mode used by ToString. Its exact value might change in the future.
  282. kDefault = kWithPayload,
  283. };
  284. // y_absl::StatusToStringMode is specified as a bitmask type, which means the
  285. // following operations must be provided:
  286. inline constexpr StatusToStringMode operator&(StatusToStringMode lhs,
  287. StatusToStringMode rhs) {
  288. return static_cast<StatusToStringMode>(static_cast<int>(lhs) &
  289. static_cast<int>(rhs));
  290. }
  291. inline constexpr StatusToStringMode operator|(StatusToStringMode lhs,
  292. StatusToStringMode rhs) {
  293. return static_cast<StatusToStringMode>(static_cast<int>(lhs) |
  294. static_cast<int>(rhs));
  295. }
  296. inline constexpr StatusToStringMode operator^(StatusToStringMode lhs,
  297. StatusToStringMode rhs) {
  298. return static_cast<StatusToStringMode>(static_cast<int>(lhs) ^
  299. static_cast<int>(rhs));
  300. }
  301. inline constexpr StatusToStringMode operator~(StatusToStringMode arg) {
  302. return static_cast<StatusToStringMode>(~static_cast<int>(arg));
  303. }
  304. inline StatusToStringMode& operator&=(StatusToStringMode& lhs,
  305. StatusToStringMode rhs) {
  306. lhs = lhs & rhs;
  307. return lhs;
  308. }
  309. inline StatusToStringMode& operator|=(StatusToStringMode& lhs,
  310. StatusToStringMode rhs) {
  311. lhs = lhs | rhs;
  312. return lhs;
  313. }
  314. inline StatusToStringMode& operator^=(StatusToStringMode& lhs,
  315. StatusToStringMode rhs) {
  316. lhs = lhs ^ rhs;
  317. return lhs;
  318. }
  319. // y_absl::Status
  320. //
  321. // The `y_absl::Status` class is generally used to gracefully handle errors
  322. // across API boundaries (and in particular across RPC boundaries). Some of
  323. // these errors may be recoverable, but others may not. Most
  324. // functions which can produce a recoverable error should be designed to return
  325. // either an `y_absl::Status` (or the similar `y_absl::StatusOr<T>`, which holds
  326. // either an object of type `T` or an error).
  327. //
  328. // API developers should construct their functions to return `y_absl::OkStatus()`
  329. // upon success, or an `y_absl::StatusCode` upon another type of error (e.g
  330. // an `y_absl::StatusCode::kInvalidArgument` error). The API provides convenience
  331. // functions to construct each status code.
  332. //
  333. // Example:
  334. //
  335. // y_absl::Status myFunction(y_absl::string_view fname, ...) {
  336. // ...
  337. // // encounter error
  338. // if (error condition) {
  339. // // Construct an y_absl::StatusCode::kInvalidArgument error
  340. // return y_absl::InvalidArgumentError("bad mode");
  341. // }
  342. // // else, return OK
  343. // return y_absl::OkStatus();
  344. // }
  345. //
  346. // Users handling status error codes should prefer checking for an OK status
  347. // using the `ok()` member function. Handling multiple error codes may justify
  348. // use of switch statement, but only check for error codes you know how to
  349. // handle; do not try to exhaustively match against all canonical error codes.
  350. // Errors that cannot be handled should be logged and/or propagated for higher
  351. // levels to deal with. If you do use a switch statement, make sure that you
  352. // also provide a `default:` switch case, so that code does not break as other
  353. // canonical codes are added to the API.
  354. //
  355. // Example:
  356. //
  357. // y_absl::Status result = DoSomething();
  358. // if (!result.ok()) {
  359. // LOG(ERROR) << result;
  360. // }
  361. //
  362. // // Provide a default if switching on multiple error codes
  363. // switch (result.code()) {
  364. // // The user hasn't authenticated. Ask them to reauth
  365. // case y_absl::StatusCode::kUnauthenticated:
  366. // DoReAuth();
  367. // break;
  368. // // The user does not have permission. Log an error.
  369. // case y_absl::StatusCode::kPermissionDenied:
  370. // LOG(ERROR) << result;
  371. // break;
  372. // // Propagate the error otherwise.
  373. // default:
  374. // return true;
  375. // }
  376. //
  377. // An `y_absl::Status` can optionally include a payload with more information
  378. // about the error. Typically, this payload serves one of several purposes:
  379. //
  380. // * It may provide more fine-grained semantic information about the error to
  381. // facilitate actionable remedies.
  382. // * It may provide human-readable contextual information that is more
  383. // appropriate to display to an end user.
  384. //
  385. // Example:
  386. //
  387. // y_absl::Status result = DoSomething();
  388. // // Inform user to retry after 30 seconds
  389. // // See more error details in googleapis/google/rpc/error_details.proto
  390. // if (y_absl::IsResourceExhausted(result)) {
  391. // google::rpc::RetryInfo info;
  392. // info.retry_delay().seconds() = 30;
  393. // // Payloads require a unique key (a URL to ensure no collisions with
  394. // // other payloads), and an `y_absl::Cord` to hold the encoded data.
  395. // y_absl::string_view url = "type.googleapis.com/google.rpc.RetryInfo";
  396. // result.SetPayload(url, info.SerializeAsCord());
  397. // return result;
  398. // }
  399. //
  400. // For documentation see https://abseil.io/docs/cpp/guides/status.
  401. //
  402. // Returned Status objects may not be ignored. status_internal.h has a forward
  403. // declaration of the form
  404. // class Y_ABSL_MUST_USE_RESULT Status;
  405. class Y_ABSL_ATTRIBUTE_TRIVIAL_ABI Status final {
  406. public:
  407. // Constructors
  408. // This default constructor creates an OK status with no message or payload.
  409. // Avoid this constructor and prefer explicit construction of an OK status
  410. // with `y_absl::OkStatus()`.
  411. Status();
  412. // Creates a status in the canonical error space with the specified
  413. // `y_absl::StatusCode` and error message. If `code == y_absl::StatusCode::kOk`, // NOLINT
  414. // `msg` is ignored and an object identical to an OK status is constructed.
  415. //
  416. // The `msg` string must be in UTF-8. The implementation may complain (e.g., // NOLINT
  417. // by printing a warning) if it is not.
  418. Status(y_absl::StatusCode code, y_absl::string_view msg);
  419. Status(const Status&);
  420. Status& operator=(const Status& x);
  421. // Move operators
  422. // The moved-from state is valid but unspecified.
  423. Status(Status&&) noexcept;
  424. Status& operator=(Status&&);
  425. ~Status();
  426. // Status::Update()
  427. //
  428. // Updates the existing status with `new_status` provided that `this->ok()`.
  429. // If the existing status already contains a non-OK error, this update has no
  430. // effect and preserves the current data. Note that this behavior may change
  431. // in the future to augment a current non-ok status with additional
  432. // information about `new_status`.
  433. //
  434. // `Update()` provides a convenient way of keeping track of the first error
  435. // encountered.
  436. //
  437. // Example:
  438. // // Instead of "if (overall_status.ok()) overall_status = new_status"
  439. // overall_status.Update(new_status);
  440. //
  441. void Update(const Status& new_status);
  442. void Update(Status&& new_status);
  443. // Status::ok()
  444. //
  445. // Returns `true` if `this->code()` == `y_absl::StatusCode::kOk`,
  446. // indicating the absence of an error.
  447. // Prefer checking for an OK status using this member function.
  448. Y_ABSL_MUST_USE_RESULT bool ok() const;
  449. // Status::code()
  450. //
  451. // Returns the canonical error code of type `y_absl::StatusCode` of this status.
  452. y_absl::StatusCode code() const;
  453. // Status::raw_code()
  454. //
  455. // Returns a raw (canonical) error code corresponding to the enum value of
  456. // `google.rpc.Code` definitions within
  457. // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto.
  458. // These values could be out of the range of canonical `y_absl::StatusCode`
  459. // enum values.
  460. //
  461. // NOTE: This function should only be called when converting to an associated
  462. // wire format. Use `Status::code()` for error handling.
  463. int raw_code() const;
  464. // Status::message()
  465. //
  466. // Returns the error message associated with this error code, if available.
  467. // Note that this message rarely describes the error code. It is not unusual
  468. // for the error message to be the empty string. As a result, prefer
  469. // `operator<<` or `Status::ToString()` for debug logging.
  470. y_absl::string_view message() const;
  471. friend bool operator==(const Status&, const Status&);
  472. friend bool operator!=(const Status&, const Status&);
  473. // Status::ToString()
  474. //
  475. // Returns a string based on the `mode`. By default, it returns combination of
  476. // the error code name, the message and any associated payload messages. This
  477. // string is designed simply to be human readable and its exact format should
  478. // not be load bearing. Do not depend on the exact format of the result of
  479. // `ToString()` which is subject to change.
  480. //
  481. // The printed code name and the message are generally substrings of the
  482. // result, and the payloads to be printed use the status payload printer
  483. // mechanism (which is internal).
  484. TString ToString(
  485. StatusToStringMode mode = StatusToStringMode::kDefault) const;
  486. // Support `y_absl::StrCat`, `y_absl::StrFormat`, etc.
  487. template <typename Sink>
  488. friend void AbslStringify(Sink& sink, const Status& status) {
  489. sink.Append(status.ToString(StatusToStringMode::kWithEverything));
  490. }
  491. // Status::IgnoreError()
  492. //
  493. // Ignores any errors. This method does nothing except potentially suppress
  494. // complaints from any tools that are checking that errors are not dropped on
  495. // the floor.
  496. void IgnoreError() const;
  497. // swap()
  498. //
  499. // Swap the contents of one status with another.
  500. friend void swap(Status& a, Status& b);
  501. //----------------------------------------------------------------------------
  502. // Payload Management APIs
  503. //----------------------------------------------------------------------------
  504. // A payload may be attached to a status to provide additional context to an
  505. // error that may not be satisfied by an existing `y_absl::StatusCode`.
  506. // Typically, this payload serves one of several purposes:
  507. //
  508. // * It may provide more fine-grained semantic information about the error
  509. // to facilitate actionable remedies.
  510. // * It may provide human-readable contextual information that is more
  511. // appropriate to display to an end user.
  512. //
  513. // A payload consists of a [key,value] pair, where the key is a string
  514. // referring to a unique "type URL" and the value is an object of type
  515. // `y_absl::Cord` to hold the contextual data.
  516. //
  517. // The "type URL" should be unique and follow the format of a URL
  518. // (https://en.wikipedia.org/wiki/URL) and, ideally, provide some
  519. // documentation or schema on how to interpret its associated data. For
  520. // example, the default type URL for a protobuf message type is
  521. // "type.googleapis.com/packagename.messagename". Other custom wire formats
  522. // should define the format of type URL in a similar practice so as to
  523. // minimize the chance of conflict between type URLs.
  524. // Users should ensure that the type URL can be mapped to a concrete
  525. // C++ type if they want to deserialize the payload and read it effectively.
  526. //
  527. // To attach a payload to a status object, call `Status::SetPayload()`,
  528. // passing it the type URL and an `y_absl::Cord` of associated data. Similarly,
  529. // to extract the payload from a status, call `Status::GetPayload()`. You
  530. // may attach multiple payloads (with differing type URLs) to any given
  531. // status object, provided that the status is currently exhibiting an error
  532. // code (i.e. is not OK).
  533. // Status::GetPayload()
  534. //
  535. // Gets the payload of a status given its unique `type_url` key, if present.
  536. y_absl::optional<y_absl::Cord> GetPayload(y_absl::string_view type_url) const;
  537. // Status::SetPayload()
  538. //
  539. // Sets the payload for a non-ok status using a `type_url` key, overwriting
  540. // any existing payload for that `type_url`.
  541. //
  542. // NOTE: This function does nothing if the Status is ok.
  543. void SetPayload(y_absl::string_view type_url, y_absl::Cord payload);
  544. // Status::ErasePayload()
  545. //
  546. // Erases the payload corresponding to the `type_url` key. Returns `true` if
  547. // the payload was present.
  548. bool ErasePayload(y_absl::string_view type_url);
  549. // Status::ForEachPayload()
  550. //
  551. // Iterates over the stored payloads and calls the
  552. // `visitor(type_key, payload)` callable for each one.
  553. //
  554. // NOTE: The order of calls to `visitor()` is not specified and may change at
  555. // any time.
  556. //
  557. // NOTE: Any mutation on the same 'y_absl::Status' object during visitation is
  558. // forbidden and could result in undefined behavior.
  559. void ForEachPayload(
  560. y_absl::FunctionRef<void(y_absl::string_view, const y_absl::Cord&)> visitor)
  561. const;
  562. private:
  563. friend Status CancelledError();
  564. // Creates a status in the canonical error space with the specified
  565. // code, and an empty error message.
  566. explicit Status(y_absl::StatusCode code);
  567. // Underlying constructor for status from a rep_.
  568. explicit Status(uintptr_t rep) : rep_(rep) {}
  569. static void Ref(uintptr_t rep);
  570. static void Unref(uintptr_t rep);
  571. // REQUIRES: !ok()
  572. // Ensures rep is not inlined or shared with any other Status.
  573. static y_absl::Nonnull<status_internal::StatusRep*> PrepareToModify(
  574. uintptr_t rep);
  575. // MSVC 14.0 limitation requires the const.
  576. static constexpr const char kMovedFromString[] =
  577. "Status accessed after move.";
  578. static y_absl::Nonnull<const TString*> EmptyString();
  579. static y_absl::Nonnull<const TString*> MovedFromString();
  580. // Returns whether rep contains an inlined representation.
  581. // See rep_ for details.
  582. static constexpr bool IsInlined(uintptr_t rep);
  583. // Indicates whether this Status was the rhs of a move operation. See rep_
  584. // for details.
  585. static constexpr bool IsMovedFrom(uintptr_t rep);
  586. static constexpr uintptr_t MovedFromRep();
  587. // Convert between error::Code and the inlined uintptr_t representation used
  588. // by rep_. See rep_ for details.
  589. static constexpr uintptr_t CodeToInlinedRep(y_absl::StatusCode code);
  590. static constexpr y_absl::StatusCode InlinedRepToCode(uintptr_t rep);
  591. // Converts between StatusRep* and the external uintptr_t representation used
  592. // by rep_. See rep_ for details.
  593. static uintptr_t PointerToRep(status_internal::StatusRep* r);
  594. static y_absl::Nonnull<const status_internal::StatusRep*> RepToPointer(
  595. uintptr_t r);
  596. static TString ToStringSlow(uintptr_t rep, StatusToStringMode mode);
  597. // Status supports two different representations.
  598. // - When the low bit is set it is an inlined representation.
  599. // It uses the canonical error space, no message or payload.
  600. // The error code is (rep_ >> 2).
  601. // The (rep_ & 2) bit is the "moved from" indicator, used in IsMovedFrom().
  602. // - When the low bit is off it is an external representation.
  603. // In this case all the data comes from a heap allocated Rep object.
  604. // rep_ is a status_internal::StatusRep* pointer to that structure.
  605. uintptr_t rep_;
  606. friend class status_internal::StatusRep;
  607. };
  608. // OkStatus()
  609. //
  610. // Returns an OK status, equivalent to a default constructed instance. Prefer
  611. // usage of `y_absl::OkStatus()` when constructing such an OK status.
  612. Status OkStatus();
  613. // operator<<()
  614. //
  615. // Prints a human-readable representation of `x` to `os`.
  616. std::ostream& operator<<(std::ostream& os, const Status& x);
  617. // IsAborted()
  618. // IsAlreadyExists()
  619. // IsCancelled()
  620. // IsDataLoss()
  621. // IsDeadlineExceeded()
  622. // IsFailedPrecondition()
  623. // IsInternal()
  624. // IsInvalidArgument()
  625. // IsNotFound()
  626. // IsOutOfRange()
  627. // IsPermissionDenied()
  628. // IsResourceExhausted()
  629. // IsUnauthenticated()
  630. // IsUnavailable()
  631. // IsUnimplemented()
  632. // IsUnknown()
  633. //
  634. // These convenience functions return `true` if a given status matches the
  635. // `y_absl::StatusCode` error code of its associated function.
  636. Y_ABSL_MUST_USE_RESULT bool IsAborted(const Status& status);
  637. Y_ABSL_MUST_USE_RESULT bool IsAlreadyExists(const Status& status);
  638. Y_ABSL_MUST_USE_RESULT bool IsCancelled(const Status& status);
  639. Y_ABSL_MUST_USE_RESULT bool IsDataLoss(const Status& status);
  640. Y_ABSL_MUST_USE_RESULT bool IsDeadlineExceeded(const Status& status);
  641. Y_ABSL_MUST_USE_RESULT bool IsFailedPrecondition(const Status& status);
  642. Y_ABSL_MUST_USE_RESULT bool IsInternal(const Status& status);
  643. Y_ABSL_MUST_USE_RESULT bool IsInvalidArgument(const Status& status);
  644. Y_ABSL_MUST_USE_RESULT bool IsNotFound(const Status& status);
  645. Y_ABSL_MUST_USE_RESULT bool IsOutOfRange(const Status& status);
  646. Y_ABSL_MUST_USE_RESULT bool IsPermissionDenied(const Status& status);
  647. Y_ABSL_MUST_USE_RESULT bool IsResourceExhausted(const Status& status);
  648. Y_ABSL_MUST_USE_RESULT bool IsUnauthenticated(const Status& status);
  649. Y_ABSL_MUST_USE_RESULT bool IsUnavailable(const Status& status);
  650. Y_ABSL_MUST_USE_RESULT bool IsUnimplemented(const Status& status);
  651. Y_ABSL_MUST_USE_RESULT bool IsUnknown(const Status& status);
  652. // AbortedError()
  653. // AlreadyExistsError()
  654. // CancelledError()
  655. // DataLossError()
  656. // DeadlineExceededError()
  657. // FailedPreconditionError()
  658. // InternalError()
  659. // InvalidArgumentError()
  660. // NotFoundError()
  661. // OutOfRangeError()
  662. // PermissionDeniedError()
  663. // ResourceExhaustedError()
  664. // UnauthenticatedError()
  665. // UnavailableError()
  666. // UnimplementedError()
  667. // UnknownError()
  668. //
  669. // These convenience functions create an `y_absl::Status` object with an error
  670. // code as indicated by the associated function name, using the error message
  671. // passed in `message`.
  672. Status AbortedError(y_absl::string_view message);
  673. Status AlreadyExistsError(y_absl::string_view message);
  674. Status CancelledError(y_absl::string_view message);
  675. Status DataLossError(y_absl::string_view message);
  676. Status DeadlineExceededError(y_absl::string_view message);
  677. Status FailedPreconditionError(y_absl::string_view message);
  678. Status InternalError(y_absl::string_view message);
  679. Status InvalidArgumentError(y_absl::string_view message);
  680. Status NotFoundError(y_absl::string_view message);
  681. Status OutOfRangeError(y_absl::string_view message);
  682. Status PermissionDeniedError(y_absl::string_view message);
  683. Status ResourceExhaustedError(y_absl::string_view message);
  684. Status UnauthenticatedError(y_absl::string_view message);
  685. Status UnavailableError(y_absl::string_view message);
  686. Status UnimplementedError(y_absl::string_view message);
  687. Status UnknownError(y_absl::string_view message);
  688. // ErrnoToStatusCode()
  689. //
  690. // Returns the StatusCode for `error_number`, which should be an `errno` value.
  691. // See https://en.cppreference.com/w/cpp/error/errno_macros and similar
  692. // references.
  693. y_absl::StatusCode ErrnoToStatusCode(int error_number);
  694. // ErrnoToStatus()
  695. //
  696. // Convenience function that creates a `y_absl::Status` using an `error_number`,
  697. // which should be an `errno` value.
  698. Status ErrnoToStatus(int error_number, y_absl::string_view message);
  699. //------------------------------------------------------------------------------
  700. // Implementation details follow
  701. //------------------------------------------------------------------------------
  702. inline Status::Status() : Status(y_absl::StatusCode::kOk) {}
  703. inline Status::Status(y_absl::StatusCode code) : Status(CodeToInlinedRep(code)) {}
  704. inline Status::Status(const Status& x) : Status(x.rep_) { Ref(rep_); }
  705. inline Status& Status::operator=(const Status& x) {
  706. uintptr_t old_rep = rep_;
  707. if (x.rep_ != old_rep) {
  708. Ref(x.rep_);
  709. rep_ = x.rep_;
  710. Unref(old_rep);
  711. }
  712. return *this;
  713. }
  714. inline Status::Status(Status&& x) noexcept : Status(x.rep_) {
  715. x.rep_ = MovedFromRep();
  716. }
  717. inline Status& Status::operator=(Status&& x) {
  718. uintptr_t old_rep = rep_;
  719. if (x.rep_ != old_rep) {
  720. rep_ = x.rep_;
  721. x.rep_ = MovedFromRep();
  722. Unref(old_rep);
  723. }
  724. return *this;
  725. }
  726. inline void Status::Update(const Status& new_status) {
  727. if (ok()) {
  728. *this = new_status;
  729. }
  730. }
  731. inline void Status::Update(Status&& new_status) {
  732. if (ok()) {
  733. *this = std::move(new_status);
  734. }
  735. }
  736. inline Status::~Status() { Unref(rep_); }
  737. inline bool Status::ok() const {
  738. return rep_ == CodeToInlinedRep(y_absl::StatusCode::kOk);
  739. }
  740. inline y_absl::StatusCode Status::code() const {
  741. return status_internal::MapToLocalCode(raw_code());
  742. }
  743. inline int Status::raw_code() const {
  744. if (IsInlined(rep_)) return static_cast<int>(InlinedRepToCode(rep_));
  745. return static_cast<int>(RepToPointer(rep_)->code());
  746. }
  747. inline y_absl::string_view Status::message() const {
  748. return !IsInlined(rep_)
  749. ? RepToPointer(rep_)->message()
  750. : (IsMovedFrom(rep_) ? y_absl::string_view(kMovedFromString)
  751. : y_absl::string_view());
  752. }
  753. inline bool operator==(const Status& lhs, const Status& rhs) {
  754. if (lhs.rep_ == rhs.rep_) return true;
  755. if (Status::IsInlined(lhs.rep_)) return false;
  756. if (Status::IsInlined(rhs.rep_)) return false;
  757. return *Status::RepToPointer(lhs.rep_) == *Status::RepToPointer(rhs.rep_);
  758. }
  759. inline bool operator!=(const Status& lhs, const Status& rhs) {
  760. return !(lhs == rhs);
  761. }
  762. inline TString Status::ToString(StatusToStringMode mode) const {
  763. return ok() ? "OK" : ToStringSlow(rep_, mode);
  764. }
  765. inline void Status::IgnoreError() const {
  766. // no-op
  767. }
  768. inline void swap(y_absl::Status& a, y_absl::Status& b) {
  769. using std::swap;
  770. swap(a.rep_, b.rep_);
  771. }
  772. inline y_absl::optional<y_absl::Cord> Status::GetPayload(
  773. y_absl::string_view type_url) const {
  774. if (IsInlined(rep_)) return y_absl::nullopt;
  775. return RepToPointer(rep_)->GetPayload(type_url);
  776. }
  777. inline void Status::SetPayload(y_absl::string_view type_url, y_absl::Cord payload) {
  778. if (ok()) return;
  779. status_internal::StatusRep* rep = PrepareToModify(rep_);
  780. rep->SetPayload(type_url, std::move(payload));
  781. rep_ = PointerToRep(rep);
  782. }
  783. inline bool Status::ErasePayload(y_absl::string_view type_url) {
  784. if (IsInlined(rep_)) return false;
  785. status_internal::StatusRep* rep = PrepareToModify(rep_);
  786. auto res = rep->ErasePayload(type_url);
  787. rep_ = res.new_rep;
  788. return res.erased;
  789. }
  790. inline void Status::ForEachPayload(
  791. y_absl::FunctionRef<void(y_absl::string_view, const y_absl::Cord&)> visitor)
  792. const {
  793. if (IsInlined(rep_)) return;
  794. RepToPointer(rep_)->ForEachPayload(visitor);
  795. }
  796. constexpr bool Status::IsInlined(uintptr_t rep) { return (rep & 1) != 0; }
  797. constexpr bool Status::IsMovedFrom(uintptr_t rep) { return (rep & 2) != 0; }
  798. constexpr uintptr_t Status::CodeToInlinedRep(y_absl::StatusCode code) {
  799. return (static_cast<uintptr_t>(code) << 2) + 1;
  800. }
  801. constexpr y_absl::StatusCode Status::InlinedRepToCode(uintptr_t rep) {
  802. Y_ABSL_ASSERT(IsInlined(rep));
  803. return static_cast<y_absl::StatusCode>(rep >> 2);
  804. }
  805. constexpr uintptr_t Status::MovedFromRep() {
  806. return CodeToInlinedRep(y_absl::StatusCode::kInternal) | 2;
  807. }
  808. inline y_absl::Nonnull<const status_internal::StatusRep*> Status::RepToPointer(
  809. uintptr_t rep) {
  810. assert(!IsInlined(rep));
  811. return reinterpret_cast<const status_internal::StatusRep*>(rep);
  812. }
  813. inline uintptr_t Status::PointerToRep(
  814. y_absl::Nonnull<status_internal::StatusRep*> rep) {
  815. return reinterpret_cast<uintptr_t>(rep);
  816. }
  817. inline void Status::Ref(uintptr_t rep) {
  818. if (!IsInlined(rep)) RepToPointer(rep)->Ref();
  819. }
  820. inline void Status::Unref(uintptr_t rep) {
  821. if (!IsInlined(rep)) RepToPointer(rep)->Unref();
  822. }
  823. inline Status OkStatus() { return Status(); }
  824. // Creates a `Status` object with the `y_absl::StatusCode::kCancelled` error code
  825. // and an empty message. It is provided only for efficiency, given that
  826. // message-less kCancelled errors are common in the infrastructure.
  827. inline Status CancelledError() { return Status(y_absl::StatusCode::kCancelled); }
  828. // Retrieves a message's status as a null terminated C string. The lifetime of
  829. // this string is tied to the lifetime of the status object itself.
  830. //
  831. // If the status's message is empty, the empty string is returned.
  832. //
  833. // StatusMessageAsCStr exists for C support. Use `status.message()` in C++.
  834. y_absl::Nonnull<const char*> StatusMessageAsCStr(
  835. const Status& status Y_ABSL_ATTRIBUTE_LIFETIME_BOUND);
  836. Y_ABSL_NAMESPACE_END
  837. } // namespace y_absl
  838. #endif // Y_ABSL_STATUS_STATUS_H_