userver: userver/storages/postgres/options.hpp Source File
Loading...
Searching...
No Matches
options.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/postgres/options.hpp
4/// @brief Options
5
6#include <chrono>
7#include <cstdint>
8#include <iosfwd>
9#include <optional>
10#include <string>
11#include <unordered_map>
12#include <unordered_set>
13
14#include <userver/congestion_control/controllers/linear.hpp>
15#include <userver/storages/postgres/postgres_fwd.hpp>
16#include <userver/utils/impl/transparent_hash.hpp>
17#include <userver/utils/str_icase.hpp>
18#include <userver/utils/string_literal.hpp>
19
20USERVER_NAMESPACE_BEGIN
21
22namespace storages::postgres {
23
24/*! [Isolation levels] */
25/// @brief SQL transaction isolation level
26/// @see https://www.postgresql.org/docs/current/static/sql-set-transaction.html
28 kReadCommitted, //!< READ COMMITTED
29 kRepeatableRead, //!< REPEATABLE READ
30 kSerializable, //!< SERIALIZABLE
31 kReadUncommitted //!< READ UNCOMMITTED @warning In Postgres READ UNCOMMITTED
32 //!< is treated as READ COMMITTED
33};
34/*! [Isolation levels] */
35
36std::ostream& operator<<(std::ostream&, IsolationLevel);
37
38/// @brief PostgreSQL transaction options
39///
40/// A transaction can be started using all isolation levels and modes
41/// supported by PostgreSQL server as specified in it's documentation.
42///
43/// Default isolation level is READ COMMITTED, default mode is READ WRITE.
44/// @code
45/// // Read-write read committed transaction.
46/// TransactionOptions opts;
47/// @endcode
48///
49/// Transaction class provides constants Transaction::RW, Transaction::RO and
50/// Transaction::Deferrable for convenience.
51///
52/// Other variants can be created with TransactionOptions constructors
53/// that are constexpr.
54///
55/// @see https://www.postgresql.org/docs/current/static/sql-set-transaction.html
57 /*! [Transaction modes] */
58 enum Mode : std::uint16_t {
59 kReadWrite = 0,
60 kReadOnly = 1,
61 kDeferrable = 3 //!< Deferrable transaction is read only
62 };
63 /*! [Transaction modes] */
65 Mode mode = kReadWrite;
66
67 constexpr TransactionOptions() = default;
68 constexpr explicit TransactionOptions(IsolationLevel lvl)
69 : isolation_level{lvl}
70 {}
71 constexpr TransactionOptions(IsolationLevel lvl, Mode m)
72 : isolation_level{lvl},
73 mode{m}
74 {}
75 constexpr explicit TransactionOptions(Mode m)
76 : mode{m}
77 {}
78
79 bool IsReadOnly() const { return mode & kReadOnly; }
80
81 /// The deferrable property has effect only if the transaction is also
82 /// serializable and read only
84};
85
86constexpr inline bool operator==(TransactionOptions lhs, TransactionOptions rhs) {
87 return lhs.isolation_level == rhs.isolation_level && lhs.mode == rhs.mode;
88}
89USERVER_NAMESPACE::utils::StringLiteral BeginStatement(TransactionOptions opts) noexcept;
90
91/// A structure to control timeouts for PosrgreSQL queries
92///
93/// There are two parameters, `execute` and `statement`.
94///
95/// `execute` parameter controls the overall time the driver spends executing a
96/// query, that includes:
97/// * connecting to PostgreSQL server, if there are no connections available and
98/// connection pool still has space for new connections;
99/// * waiting for a connection to become idle if there are no idle connections
100/// and connection pool already has reached it's max size;
101/// * preparing a statement if the statement is run for the first time on the
102/// connection;
103/// * binding parameters and executing the statement;
104/// * waiting for the first results to arrive from the server. If the result set
105/// is big, only time to the first data packet is taken into account.
106///
107/// `statement` is rather straightforward, it's the PostgreSQL server-side
108/// parameter, and it controls the time the database backend can spend executing
109/// a single statement. It is very costly to change the statement timeout
110/// often, as it requires a roundtrip to the database to change the setting.
111/// @see https://www.postgresql.org/docs/12/runtime-config-client.html
112///
113/// `execute` timeout should always be greater than the `statement` timeout!
114///
115/// In case of a timeout, either back-end or overall, the client gets an
116/// exception and the driver tries to clean up the connection for further reuse.
118 /// Overall timeout for a command being executed
119 TimeoutDuration network_timeout_ms{};
120 /// PostgreSQL server-side timeout
121 TimeoutDuration statement_timeout_ms{};
122
123 enum class PreparedStatementsOptionOverride { kNoOverride, kEnabled, kDisabled };
124
125 PreparedStatementsOptionOverride prepared_statements_enabled{PreparedStatementsOptionOverride::kNoOverride};
126
127 constexpr CommandControl(
128 TimeoutDuration network_timeout_ms,
129 TimeoutDuration statement_timeout_ms,
130 PreparedStatementsOptionOverride prepared_statements_enabled = PreparedStatementsOptionOverride::kNoOverride
131 )
132 : network_timeout_ms(network_timeout_ms),
133 statement_timeout_ms(statement_timeout_ms),
134 prepared_statements_enabled(prepared_statements_enabled)
135 {}
136
137 constexpr CommandControl WithExecuteTimeout(TimeoutDuration n) const noexcept { return {n, statement_timeout_ms}; }
138
139 constexpr CommandControl WithStatementTimeout(TimeoutDuration s) const noexcept { return {network_timeout_ms, s}; }
140
141 bool operator==(const CommandControl& rhs) const {
143 prepared_statements_enabled == rhs.prepared_statements_enabled;
144 }
145
146 bool operator!=(const CommandControl& rhs) const { return !(*this == rhs); }
147};
148
149/// @brief storages::postgres::CommandControl that may not be set
150using OptionalCommandControl = std::optional<CommandControl>;
151
152using CommandControlByMethodMap = USERVER_NAMESPACE::utils::impl::TransparentMap<std::string, CommandControl>;
153using CommandControlByHandlerMap =
154 USERVER_NAMESPACE::utils::impl::TransparentMap<std::string, CommandControlByMethodMap>;
155using CommandControlByQueryMap = USERVER_NAMESPACE::utils::impl::TransparentMap<std::string, CommandControl>;
156
157OptionalCommandControl GetHandlerOptionalCommandControl(
158 const CommandControlByHandlerMap& map,
159 std::string_view path,
160 std::string_view method
161);
162
163OptionalCommandControl GetQueryOptionalCommandControl(const CommandControlByQueryMap& map, std::string_view query_name);
164
165/// Default initial pool connection count
166inline constexpr std::size_t kDefaultPoolMinSize = 4;
167
168/// Default maximum replication lag
169inline constexpr auto kDefaultMaxReplicationLag = std::chrono::seconds{60};
170
171/// Default pool connections limit
172inline constexpr std::size_t kDefaultPoolMaxSize = 15;
173
174/// Default size of queue for clients waiting for connections
175inline constexpr std::size_t kDefaultPoolMaxQueueSize = 200;
176
177/// Default limit for concurrent establishing connections number
178inline constexpr std::size_t kDefaultConnectingLimit = 0;
179
180/// @brief PostgreSQL topology options
181///
182/// Dynamic option @ref POSTGRES_TOPOLOGY_SETTINGS
184 /// Maximum replication lag. Once the replica lag exceeds this value it will be automatically disabled.
186
187 /// List of manually disabled replicas (FQDNs).
188 std::unordered_set<std::string, USERVER_NAMESPACE::utils::StrIcaseHash, USERVER_NAMESPACE::utils::StrIcaseEqual>
190};
191
192/// @brief PostgreSQL connection pool options
193///
194/// Dynamic option @ref POSTGRES_CONNECTION_POOL_SETTINGS
195struct PoolSettings final {
196 /// Number of connections created initially
198
199 /// Maximum number of created connections
201
202 /// Maximum number of clients waiting for a connection
204
205 /// Limits number of concurrent establishing connections (0 - unlimited)
207
208 bool operator==(const PoolSettings& rhs) const {
209 return min_size == rhs.min_size && max_size == rhs.max_size && max_queue_size == rhs.max_queue_size &&
211 }
212};
213
214// Configs with a suffix `Dynamic` are need to compatibility with static:
215// We must update only fields that were updated in a dynamic config (not a full config!).
216struct PoolSettingsDynamic final {
217 std::optional<std::size_t> min_size;
218 std::optional<std::size_t> max_size;
219 std::optional<std::size_t> max_queue_size;
220 std::optional<std::size_t> connecting_limit;
221};
222
223/// Default size limit for prepared statements cache
224inline constexpr std::size_t kDefaultMaxPreparedCacheSize = 200;
225
226/// Pipeline mode configuration
227///
228/// Dynamic option @ref POSTGRES_CONNECTION_PIPELINE_EXPERIMENT
229enum class PipelineMode { kDisabled, kEnabled };
230
231/// Whether to omit excessive D(escribe) message
232/// when executing prepared statements
233///
234/// Dynamic option @ref POSTGRES_OMIT_DESCRIBE_IN_EXECUTE
235enum class OmitDescribeInExecuteMode { kDisabled, kEnabled };
236
237/// PostgreSQL connection options
238///
239/// Dynamic option @ref POSTGRES_CONNECTION_SETTINGS
241 enum PreparedStatementOptions {
242 kCachePreparedStatements,
243 kNoPreparedStatements,
244 };
245 enum UserTypesOptions {
246 kUserTypesEnabled,
247 kUserTypesEnforced,
248 kPredefinedTypesOnly,
249 };
250 enum CheckQueryParamsOptions {
251 kIgnoreUnused,
252 kCheckUnused,
253 };
254 enum DiscardOnConnectOptions {
255 kDiscardNone,
256 kDiscardAll,
257 };
258 enum StatementLogMode {
259 kLogSkip,
260 kLog,
261 };
262 using SettingsVersion = std::size_t;
263
264 /// Cache prepared statements or not
265 PreparedStatementOptions prepared_statements = kCachePreparedStatements;
266
267 /// Enables the usage of user-defined types
268 UserTypesOptions user_types = kUserTypesEnabled;
269
270 /// Checks for not-NULL query params that are not used in query
271 CheckQueryParamsOptions ignore_unused_query_params = kCheckUnused;
272
273 /// Limits the size or prepared statements cache
275
276 /// Turns on connection pipeline mode
278
279 /// Enables protocol-level optimization when executing prepared statements
281
282 /// This many connection errors in 15 seconds block new connections opening
283 std::size_t recent_errors_threshold = 2;
284
285 /// The maximum lifetime of the connection after which it will be closed
286 std::optional<std::chrono::seconds> max_ttl{};
287
288 /// Execute discard all after establishing a new connection
289 DiscardOnConnectOptions discard_on_connect = kDiscardAll;
290
291 /// Statement logging in span tags
292 StatementLogMode statement_log_mode = kLog;
293
294 bool deadline_propagation_enabled = true;
295
296 /// Helps keep track of the changes in settings
297 SettingsVersion version{0U};
298
299 bool operator==(const ConnectionSettings& rhs) const {
300 return !RequiresConnectionReset(rhs) && recent_errors_threshold == rhs.recent_errors_threshold;
301 }
302
303 bool operator!=(const ConnectionSettings& rhs) const { return !(*this == rhs); }
304
305 bool RequiresConnectionReset(const ConnectionSettings& rhs) const {
306 // TODO: max_prepared_cache_size check could be relaxed
312 }
313};
314
315struct ConnectionSettingsDynamic final {
316 std::optional<ConnectionSettings::PreparedStatementOptions> prepared_statements{};
317 std::optional<ConnectionSettings::UserTypesOptions> user_types{};
318 std::optional<std::size_t> max_prepared_cache_size{};
319 std::optional<std::size_t> recent_errors_threshold{};
320 std::optional<ConnectionSettings::CheckQueryParamsOptions> ignore_unused_query_params{};
321 std::optional<std::chrono::seconds> max_ttl{};
322 std::optional<ConnectionSettings::DiscardOnConnectOptions> discard_on_connect{};
323 std::optional<bool> deadline_propagation_enabled{};
324};
325
326/// @brief PostgreSQL statements metrics options
327///
328/// Dynamic option @ref POSTGRES_STATEMENT_METRICS_SETTINGS
329struct StatementMetricsSettings final {
330 /// Store metrics in LRU of this size
331 std::size_t max_statements{0};
332
333 bool operator==(const StatementMetricsSettings& other) const { return max_statements == other.max_statements; }
334};
335
336/// Initialization modes
337enum class InitMode {
338 kSync = 0,
339 kAsync,
340};
341
342enum class ConnlimitMode {
343 kManual = 0,
344 kAuto,
345};
346
347/// Settings for storages::postgres::Cluster
349 /// settings for statements metrics
350 StatementMetricsSettings statement_metrics_settings;
351
352 /// settings for host discovery
354
355 /// settings for connection pools
356 PoolSettings pool_settings;
357
358 /// settings for individual connections
360
361 /// initialization mode
363
364 /// database name
365 std::string db_name;
366
367 /// connection limit change mode
368 ConnlimitMode connlimit_mode = ConnlimitMode::kAuto;
369
370 /// congestion control settings
371 congestion_control::v2::LinearController::StaticConfig cc_config;
372};
373
374} // namespace storages::postgres
375
376USERVER_NAMESPACE_END