status.h 34 KB

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