userver: userver/utils/trx_tracker.hpp Source File
Loading...
Searching...
No Matches
trx_tracker.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file
4/// @brief Tracking for heavy operations while having active transactions.
5
6#include <userver/utils/impl/source_location.hpp>
7#include <userver/utils/statistics/rate.hpp>
8
9USERVER_NAMESPACE_BEGIN
10
11/// @brief Tracking for heavy operations while having active transactions.
12///
13/// Some operations, like http requests, are heavy and can take
14/// too long during an incident. If they are called during an active
15/// database transaction, connection will be held for longer and
16/// connection pool will be exhausted. Transaction tracker prevents this
17/// by holding counter of active transactions in TaskLocalVariable
18/// and checking for active transactions in heavy operaions.
19///
20/// ## Example usage:
21///
22/// @snippet utils/trx_tracker_test.cpp Sample TransactionTracker usage
23namespace utils::trx_tracker {
24
25/// @brief Increment transaction counter.
27
28/// @brief Decrement transaction counter.
29///
30/// If called before StartTransaction, the behavior is undefined.
31void EndTransaction() noexcept;
32
33/// @brief Check for active transactions.
34void CheckNoTransactions(utils::impl::SourceLocation location = utils::impl::SourceLocation::Current());
35
36/// @brief Disable check for active transactions.
37///
38/// To conciously call a heavy operation in active transaction,
39/// check can be disabled by creating an instance of this class.
40/// Checks will be disabled until every instance either has
41/// Reenable() method called or is destroyed.
42class CheckDisabler final {
43public:
44 /// @brief Disable check for active transactions.
46
47 /// @brief Reenable check for active transactions on destruction.
49
50 CheckDisabler(const CheckDisabler&) = delete;
51 CheckDisabler(CheckDisabler&&) = delete;
52 CheckDisabler operator=(const CheckDisabler&) = delete;
53 CheckDisabler operator=(CheckDisabler&&) = delete;
54
55 /// @brief Manually reenable check for active transactions.
56 void Reenable() noexcept;
57
58private:
59 bool reenabled_ = false;
60};
61
62/// @brief Statistics for transaction tracker.
63struct TransactionTrackerStatistics final {
64 /// @brief How many times check for active transactions was triggered.
65 utils::statistics::Rate triggers{0};
66};
67
68/// @brief Get statistics for transaction tracker.
69TransactionTrackerStatistics GetStatistics() noexcept;
70
71/// @brief Reset statistics for transaction tracker.
73
74} // namespace utils::trx_tracker
75
76USERVER_NAMESPACE_END