userver: userver/storages/postgres/cluster.hpp Source File
Loading...
Searching...
No Matches
cluster.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/postgres/cluster.hpp
4/// @brief @copybrief storages::postgres::Cluster
5
6#include <memory>
7
8#include <userver/clients/dns/resolver_fwd.hpp>
9#include <userver/dynamic_config/source.hpp>
10#include <userver/engine/task/task_processor_fwd.hpp>
11#include <userver/engine/task/task_with_result.hpp>
12#include <userver/error_injection/settings_fwd.hpp>
13#include <userver/testsuite/postgres_control.hpp>
14#include <userver/testsuite/tasks.hpp>
15
16#include <userver/storages/postgres/cluster_types.hpp>
17#include <userver/storages/postgres/database.hpp>
18#include <userver/storages/postgres/detail/non_transaction.hpp>
19#include <userver/storages/postgres/notify.hpp>
20#include <userver/storages/postgres/options.hpp>
21#include <userver/storages/postgres/query.hpp>
22#include <userver/storages/postgres/query_queue.hpp>
23#include <userver/storages/postgres/statistics.hpp>
24#include <userver/storages/postgres/transaction.hpp>
25
26/// @page pg_topology uPg: Cluster topology discovery
27///
28/// @par Principles of PgaaS role determination
29/// - Every host except master is in recovery state from PostgreSQL's POV.
30/// This means the check 'select pg_is_in_recovery()' returns `false` for the
31/// master and `true` for every other host type.
32/// - Some hosts are in sync slave mode. This may be determined by executing
33/// 'show synchronous_standby_names' on the master.
34/// See
35/// https://www.postgresql.org/docs/current/runtime-config-replication.html#GUC-SYNCHRONOUS-STANDBY-NAMES
36/// for more information.
37///
38/// @par PgaaS sync slaves lag
39/// By default, PgaaS synchronous slaves are working with 'synchronous_commit'
40/// set to 'remote_apply'. Therefore, sync slave may be lagging behind the
41/// master and thus is not truly 'synchronous' from the reader's POV,
42/// but things may change with time.
43///
44/// @par Implementation
45/// Topology update runs every second.
46///
47/// Every host is assigned a connection with special ID (4100200300).
48/// Using this connection we check for host availability, writability
49/// (master detection) and perform RTT measurements.
50///
51/// After the initial check we know about master presence and RTT for each host.
52/// Master host is queried about synchronous replication status. We use this
53/// info to identify synchronous slaves and to detect "quorum commit" presence.
54///
55///
56/// ----------
57///
58/// @htmlonly <div class="bottom-nav"> @endhtmlonly
59/// ⇦ @ref pg_errors | @ref scripts/docs/en/userver/pg_connlimit_mode_auto.md ⇨
60/// @htmlonly </div> @endhtmlonly
61
62USERVER_NAMESPACE_BEGIN
63
64namespace components {
65class Postgres;
66} // namespace components
67
68namespace storages::postgres {
69
70namespace detail {
71
72class ClusterImpl;
73using ClusterImplPtr = std::unique_ptr<ClusterImpl>;
74
75} // namespace detail
76
77/// @ingroup userver_clients
78///
79/// @brief Interface for executing queries on a cluster of PostgreSQL servers
80///
81/// See @ref pg_user_row_types "Typed PostgreSQL results" for usage examples of
82/// the storages::postgres::ResultSet.
83///
84/// Usually retrieved from components::Postgres component.
85///
86/// @todo Add information about topology discovery
87class Cluster {
88public:
89 /// Cluster constructor
90 /// @param dsns List of DSNs to connect to
91 /// @param resolver asynchronous DNS resolver
92 /// @param bg_task_processor task processor for blocking connection operations
93 /// @param cluster_settings struct with settings fields:
94 /// task_data_keys_settings - settings for per-handler command controls
95 /// topology_settings - settings for host discovery
96 /// pool_settings - settings for connection pools
97 /// conn_settings - settings for individual connections
98 /// @param default_cmd_ctls default command execution options
99 /// @param testsuite_pg_ctl command execution options customizer for testsuite
100 /// @param ei_settings error injection settings
101 /// @note When `max_connection_pool_size` is reached, and no idle connections
102 /// available, `PoolError` is thrown for every new connection
103 /// request
105 DsnList dsns,
106 clients::dns::Resolver* resolver,
107 engine::TaskProcessor& bg_task_processor,
108 const ClusterSettings& cluster_settings,
109 DefaultCommandControls&& default_cmd_ctls,
110 const testsuite::PostgresControl& testsuite_pg_ctl,
111 const error_injection::Settings& ei_settings,
112 testsuite::TestsuiteTasks& testsuite_tasks,
113 dynamic_config::Source config_source,
114 int shard_number
115 );
116 ~Cluster();
117
118 /// Get cluster statistics
119 ///
120 /// The statistics object is too big to fit on stack
122
123 /// @name Transaction start
124 /// @{
125
126 /// Start a transaction in any available connection depending on transaction
127 /// options.
128 ///
129 /// If the transaction is RW, will start transaction in a connection
130 /// to master. If the transaction is RO, will start trying connections
131 /// starting with slaves.
132 /// @throws ClusterUnavailable if no hosts are available
133 Transaction Begin(const TransactionOptions&, OptionalCommandControl = {});
134
135 /// Start a transaction in a connection with specified host selection rules.
136 ///
137 /// If the requested host role is not available, may fall back to another
138 /// host role, see ClusterHostType.
139 /// If the transaction is RW, only master connection can be used.
140 /// @throws ClusterUnavailable if no hosts are available
141 Transaction Begin(ClusterHostTypeFlags, const TransactionOptions&, OptionalCommandControl = {});
142
143 /// Start a named transaction in any available connection depending on
144 /// transaction options.
145 ///
146 /// If the transaction is RW, will start transaction in a connection
147 /// to master. If the transaction is RO, will start trying connections
148 /// starting with slaves.
149 /// `name` is used to set command control in config at runtime.
150 /// @throws ClusterUnavailable if no hosts are available
151 Transaction Begin(std::string name, const TransactionOptions&);
152
153 /// Start a named transaction in a connection with specified host selection
154 /// rules.
155 ///
156 /// If the requested host role is not available, may fall back to another
157 /// host role, see ClusterHostType.
158 /// If the transaction is RW, only master connection can be used.
159 /// `name` is used to set command control in config at runtime.
160 /// @throws ClusterUnavailable if no hosts are available
161 Transaction Begin(std::string name, ClusterHostTypeFlags, const TransactionOptions&);
162 /// @}
163
164 /// Start a query queue with specified host selection rules and timeout for
165 /// acquiring a connection.
166 [[nodiscard]] QueryQueue CreateQueryQueue(ClusterHostTypeFlags flags);
167
168 /// Start a query queue with specified host selection rules and timeout for
169 /// acquiring a connection.
170 [[nodiscard]] QueryQueue CreateQueryQueue(ClusterHostTypeFlags flags, TimeoutDuration acquire_timeout);
171
172 /// @name Single-statement query in an auto-commit transaction
173 /// @{
174
175 /// @brief Execute a statement at host of specified type.
176 /// @note You must specify at least one role from ClusterHostType here
177 ///
178 /// @snippet storages/postgres/tests/landing_test.cpp Exec sample
179 ///
180 /// @warning Do NOT create a query string manually by embedding arguments!
181 /// It leads to vulnerabilities and bad performance. Either pass arguments
182 /// separately, or use storages::postgres::ParameterScope.
183 template <typename... Args>
184 ResultSet Execute(ClusterHostTypeFlags, const Query& query, const Args&... args);
185
186 /// @brief Execute a statement with specified host selection rules and command
187 /// control settings.
188 /// @note You must specify at least one role from ClusterHostType here
189 ///
190 /// @warning Do NOT create a query string manually by embedding arguments!
191 /// It leads to vulnerabilities and bad performance. Either pass arguments
192 /// separately, or use storages::postgres::ParameterScope.
193 template <typename... Args>
194 ResultSet Execute(ClusterHostTypeFlags, OptionalCommandControl, const Query& query, const Args&... args);
195
196 /// @brief Execute a statement with stored arguments and specified host
197 /// selection rules.
198 ///
199 /// @warning Do NOT create a query string manually by embedding arguments!
200 /// It leads to vulnerabilities and bad performance. Either pass arguments
201 /// separately, or use storages::postgres::ParameterScope.
202 ResultSet Execute(ClusterHostTypeFlags flags, const Query& query, const ParameterStore& store);
203
204 /// @brief Execute a statement with stored arguments, specified host selection
205 /// rules and command control settings.
206 ///
207 /// @warning Do NOT create a query string manually by embedding arguments!
208 /// It leads to vulnerabilities and bad performance. Either pass arguments
209 /// separately, or use storages::postgres::ParameterScope.
211 ClusterHostTypeFlags flags,
212 OptionalCommandControl statement_cmd_ctl,
213 const Query& query,
214 const ParameterStore& store
215 );
216 /// @}
217
218 /// @brief Listen for notifications on channel
219 /// @warning Each NotifyScope owns a single connection taken from the pool,
220 /// which effectively decreases the number of usable connections
221 NotifyScope Listen(std::string_view channel, OptionalCommandControl = {});
222
223 /// Replaces globally updated command control with a static user-provided one
225
226 /// Returns current default command control
228
229 void SetHandlersCommandControl(CommandControlByHandlerMap handlers_command_control);
230
231 void SetQueriesCommandControl(CommandControlByQueryMap queries_command_control);
232
233 /// @cond
234 /// Updates default command control from global config (if not set by user)
235 void ApplyGlobalCommandControlUpdate(CommandControl);
236 /// @endcond
237
238 /// Replaces cluster connection settings.
239 ///
240 /// Connections with an old settings will be dropped and reestablished.
242
243 void SetPoolSettings(const PoolSettings& settings);
244
245 void SetTopologySettings(const TopologySettings& settings);
246
247 void SetStatementMetricsSettings(const StatementMetricsSettings& settings);
248
249private:
250 detail::NonTransaction Start(ClusterHostTypeFlags, OptionalCommandControl);
251
252 OptionalCommandControl GetQueryCmdCtl(const std::string& query_name) const;
253 OptionalCommandControl GetHandlersCmdCtl(OptionalCommandControl cmd_ctl) const;
254
255 detail::ClusterImplPtr pimpl_;
256};
257
258template <typename... Args>
259ResultSet Cluster::Execute(ClusterHostTypeFlags flags, const Query& query, const Args&... args) {
260 return Execute(flags, OptionalCommandControl{}, query, args...);
261}
262
263template <typename... Args>
265 ClusterHostTypeFlags flags,
266 OptionalCommandControl statement_cmd_ctl,
267 const Query& query,
268 const Args&... args
269) {
270 if (!statement_cmd_ctl && query.GetName()) {
271 statement_cmd_ctl = GetQueryCmdCtl(query.GetName()->GetUnderlying());
272 }
273 statement_cmd_ctl = GetHandlersCmdCtl(statement_cmd_ctl);
274 auto ntrx = Start(flags, statement_cmd_ctl);
275 return ntrx.Execute(statement_cmd_ctl, query, args...);
276}
277
278} // namespace storages::postgres
279
280USERVER_NAMESPACE_END