userver: userver/storages/postgres/cluster.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
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 /// @param testsuite_tasks see @ref testsuite::TestsuiteTasks
102 /// @param config_source see @ref dynamic_config::Source
103 /// @param shard_number shard number
104 /// @note When `max_connection_pool_size` is reached, and no idle connections
105 /// available, `PoolError` is thrown for every new connection
106 /// request
108 DsnList dsns,
109 clients::dns::Resolver* resolver,
110 engine::TaskProcessor& bg_task_processor,
111 const ClusterSettings& cluster_settings,
112 DefaultCommandControls&& default_cmd_ctls,
113 const testsuite::PostgresControl& testsuite_pg_ctl,
114 const error_injection::Settings& ei_settings,
115 testsuite::TestsuiteTasks& testsuite_tasks,
116 dynamic_config::Source config_source,
117 int shard_number
118 );
119 ~Cluster();
120
121 /// Get cluster statistics
122 ///
123 /// The statistics object is too big to fit on stack
124 ClusterStatisticsPtr GetStatistics() const;
125
126 /// @name Transaction start
127 /// @{
128
129 /// Start a transaction in any available connection depending on transaction
130 /// options.
131 ///
132 /// If the transaction is RW, will start transaction in a connection
133 /// to master. If the transaction is RO, will start trying connections
134 /// starting with slaves.
135 /// @throws ClusterUnavailable if no hosts are available
136 Transaction Begin(const TransactionOptions&, OptionalCommandControl = {});
137
138 /// Start a transaction in a connection with specified host selection rules.
139 ///
140 /// If the requested host role is not available, may fall back to another
141 /// host role, see ClusterHostType.
142 /// If the transaction is RW, only master connection can be used.
143 /// @throws ClusterUnavailable if no hosts are available
144 Transaction Begin(ClusterHostTypeFlags, const TransactionOptions&, OptionalCommandControl = {});
145
146 /// Start a named transaction in any available connection depending on
147 /// transaction options.
148 ///
149 /// If the transaction is RW, will start transaction in a connection
150 /// to master. If the transaction is RO, will start trying connections
151 /// starting with slaves.
152 /// `name` is used to set command control in config at runtime.
153 /// @throws ClusterUnavailable if no hosts are available
154 Transaction Begin(std::string name, const TransactionOptions&);
155
156 /// Start a named transaction in a connection with specified host selection
157 /// rules.
158 ///
159 /// If the requested host role is not available, may fall back to another
160 /// host role, see ClusterHostType.
161 /// If the transaction is RW, only master connection can be used.
162 /// `name` is used to set command control in config at runtime.
163 /// @throws ClusterUnavailable if no hosts are available
164 Transaction Begin(std::string name, ClusterHostTypeFlags, const TransactionOptions&);
165 /// @}
166
167 /// Start a query queue with specified host selection rules and timeout for
168 /// acquiring a connection.
169 [[nodiscard]] QueryQueue CreateQueryQueue(ClusterHostTypeFlags flags);
170
171 /// Start a query queue with specified host selection rules and timeout for
172 /// acquiring a connection.
173 [[nodiscard]] QueryQueue CreateQueryQueue(ClusterHostTypeFlags flags, TimeoutDuration acquire_timeout);
174
175 /// @name Single-statement query in an auto-commit transaction
176 /// @{
177
178 /// @brief Execute a statement at host of specified type.
179 /// @note You must specify at least one role from ClusterHostType here
180 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
181 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
182 ///
183 /// @snippet storages/postgres/tests/landing_test.cpp Exec sample
184 ///
185 /// @warning Do NOT create a query string manually by embedding arguments!
186 /// It leads to vulnerabilities and bad performance. Either pass arguments
187 /// separately, or use storages::postgres::ParameterScope.
188 template <typename... Args>
189 ResultSet Execute(ClusterHostTypeFlags, const Query& query, const Args&... args);
190
191 /// @brief Execute a statement with specified host selection rules and command
192 /// control settings.
193 /// @note You must specify at least one role from ClusterHostType here
194 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
195 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
196 ///
197 /// @warning Do NOT create a query string manually by embedding arguments!
198 /// It leads to vulnerabilities and bad performance. Either pass arguments
199 /// separately, or use storages::postgres::ParameterScope.
200 template <typename... Args>
201 ResultSet Execute(ClusterHostTypeFlags, OptionalCommandControl, const Query& query, const Args&... args);
202
203 /// @brief Execute a statement with stored arguments and specified host
204 /// selection rules.
205 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
206 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
207 ///
208 /// @warning Do NOT create a query string manually by embedding arguments!
209 /// It leads to vulnerabilities and bad performance. Either pass arguments
210 /// separately, or use storages::postgres::ParameterScope.
211 ResultSet Execute(ClusterHostTypeFlags flags, const Query& query, const ParameterStore& store);
212
213 /// @brief Execute a statement with stored arguments, specified host selection
214 /// rules and command control settings.
215 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
216 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
217 ///
218 /// @warning Do NOT create a query string manually by embedding arguments!
219 /// It leads to vulnerabilities and bad performance. Either pass arguments
220 /// separately, or use storages::postgres::ParameterScope.
222 ClusterHostTypeFlags flags,
223 OptionalCommandControl statement_cmd_ctl,
224 const Query& query,
225 const ParameterStore& store
226 );
227 /// @}
228
229 /// @brief Listen for notifications on channel
230 /// @warning Each NotifyScope owns a single connection taken from the pool,
231 /// which effectively decreases the number of usable connections
232 NotifyScope Listen(std::string_view channel, OptionalCommandControl = {});
233
234 /// Replaces globally updated command control with a static user-provided one
236
237 /// Returns current default command control
239
240 void SetHandlersCommandControl(CommandControlByHandlerMap handlers_command_control);
241
242 void SetQueriesCommandControl(CommandControlByQueryMap queries_command_control);
243
244 /// @cond
245 /// Updates default command control from global config (if not set by user)
246 void ApplyGlobalCommandControlUpdate(CommandControl);
247 /// @endcond
248
249 /// Replaces cluster connection settings.
250 ///
251 /// Connections with an old settings will be dropped and reestablished.
253
254 void SetPoolSettings(const PoolSettings& settings);
255
256 void SetTopologySettings(const TopologySettings& settings);
257
258 void SetStatementMetricsSettings(const StatementMetricsSettings& settings);
259
260 void SetDsnList(const DsnList&);
261
262private:
263 detail::NonTransaction Start(ClusterHostTypeFlags, OptionalCommandControl);
264
265 OptionalCommandControl GetQueryCmdCtl(const std::string& query_name) const;
266 OptionalCommandControl GetHandlersCmdCtl(OptionalCommandControl cmd_ctl) const;
267
268 detail::ClusterImplPtr pimpl_;
269};
270
271template <typename... Args>
272ResultSet Cluster::Execute(ClusterHostTypeFlags flags, const Query& query, const Args&... args) {
273 return Execute(flags, OptionalCommandControl{}, query, args...);
274}
275
276template <typename... Args>
278 ClusterHostTypeFlags flags,
279 OptionalCommandControl statement_cmd_ctl,
280 const Query& query,
281 const Args&... args
282) {
283 if (!statement_cmd_ctl && query.GetName()) {
284 statement_cmd_ctl = GetQueryCmdCtl(query.GetName()->GetUnderlying());
285 }
286 statement_cmd_ctl = GetHandlersCmdCtl(statement_cmd_ctl);
287 auto ntrx = Start(flags, statement_cmd_ctl);
288 return ntrx.Execute(statement_cmd_ctl, query, args...);
289}
290
291} // namespace storages::postgres
292
293USERVER_NAMESPACE_END