userver: userver/storages/postgres/dist_lock_component_base.hpp Source File
Loading...
Searching...
No Matches
dist_lock_component_base.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/postgres/dist_lock_component_base.hpp
4/// @brief @copybrief storages::postgres::DistLockComponentBase
5
6#include <userver/components/component_base.hpp>
7#include <userver/dist_lock/dist_lock_settings.hpp>
8#include <userver/dist_lock/dist_locked_worker.hpp>
9#include <userver/dynamic_config/snapshot.hpp>
10#include <userver/dynamic_config/source.hpp>
11#include <userver/storages/postgres/dist_lock_strategy.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace storages::postgres {
16
17/// @ingroup userver_components userver_base_classes
18///
19/// @brief Base class for postgres-based distlock worker components
20///
21/// A component that implements a distlock with lock in Postgres. Inherit from
22/// DistLockComponentBase and implement DoWork(). Lock options are configured
23/// in static config. To customize a distlock for testsuite override DoWorkTestsuite().
24///
25/// By default the distlock is started and stopped automatically by the framework
26/// in all environments except testsuite. If manual control over the distlock startup
27/// and shutdown is needed pass DisableAutostartAtBase{} to the DistLockComponentBase .ctor.
28///
29/// The class must be used for infinite loop jobs. If you want a distributed
30/// periodic, you should look at locked_periodiccomponents::PgLockedPeriodic.
31///
32/// @see dist_lock::DistLockedTask
33/// @see locked_periodiccomponents::PgLockedPeriodic
34///
35/// ## Static configuration example:
36///
37/// ```yaml
38/// example-distlock:
39/// cluster: postgresql-service
40/// table: service.distlocks
41/// lockname: master
42/// pg-timeout: 1s
43/// lock-ttl: 10s
44/// autostart: true
45/// ```
46/// See config `POSTGRES_DISTLOCK_SETTINGS`, some of parameters can be dynamically overridden.
47///
48/// A nonempty `run_on_hosts` gives priority to the listed hosts. All other hosts
49/// automatically act as fallback hosts and may run the task when the lock stays idle.
50/// An explicitly empty `run_on_hosts` disables all hosts; omitting it allows every
51/// host to acquire the lock immediately.
52/// A fallback host must observe `fallback_heartbeat_checks` consecutive successful
53/// checks with no live lock. Acquisition additionally requires the lock row to
54/// record no activity for `fallback_heartbeat_checks * acquire_interval`.
55/// If the checks finish before that shared idle interval has elapsed, the host
56/// starts another sequence. With regular successful checks, failover can therefore
57/// take nearly twice this interval; errors and scheduling delays can extend it.
58/// The host may then run for `fallback_duration` (10 minutes by default);
59/// expiry is advisory, so
60/// @ref storages::postgres::DistLockComponentBase::DoWork must check
61/// @ref storages::postgres::DistLockComponentBase::IsCancelAdvised and finish its current iteration.
62///
63/// Idle checks share the lock row's history, so a successful lock acquisition by any
64/// host restarts the waiting period for all fallback hosts, including short payload
65/// invocations. With fallback enabled, all participants, including preferred hosts,
66/// retain one expired row per lock key on release. With fallback disabled, release
67/// keeps the original behavior and deletes the row.
68/// Both release operations check the key and the owner, whose ID identifies an
69/// individual locker instance. A delayed release cannot change another owner's lock.
70/// However, an older strategy can delete its own row and lose the shared history.
71/// To enable fallback safely, first deploy support for conditional history retention
72/// to all participants while fallback is disabled (`run_on_hosts` is omitted).
73/// After that rollout completes, enable the same nonempty `run_on_hosts` policy for
74/// all participants of the lock. History retention must not depend on whether a
75/// participant is a preferred or a fallback host.
76///
77/// ## Static options of storages::postgres::DistLockComponentBase :
78/// @include{doc} scripts/docs/en/components_schema/postgresql/src/storages/postgres/dist_lock_component_base.md
79///
80/// Options inherited from @ref components::ComponentBase :
81/// @include{doc} scripts/docs/en/components_schema/core/src/components/impl/component_base.md
82///
83/// ## Migration example
84///
85/// You have to create a SQL table for distlocks. An example of the migration
86/// script is as following:
87///
88/// ```SQL
89/// CREATE TABLE service.distlocks
90/// (
91/// key TEXT PRIMARY KEY,
92/// owner TEXT,
93/// expiration_time TIMESTAMPTZ
94/// );
95/// ```
96///
97/// @see @ref scripts/docs/en/userver/periodics.md
99public:
101
102 /// @brief Constructs the distlock base and enables automatic startup and shutdown of the distlock.
104 const components::ComponentConfig& component_config,
105 const components::ComponentContext& component_context
106 );
107
108 /// @brief Constructs the distlock base and disables automatic startup and shutdown of the distlock.
109 /// The dislock should be started and stopped manually via AutostartDistlock() and StopDistLock() calls.
111 const components::ComponentConfig& component_config,
112 const components::ComponentContext& component_context,
114 );
115
116 ~DistLockComponentBase() override;
117
118 dist_lock::DistLockedWorker& GetWorker();
119
120 /// @note In testsuite always returns `true`, because there is only one host.
121 bool OwnsLock() const noexcept;
122
123 static yaml_config::Schema GetStaticConfigSchema();
124
125protected:
126 /// Override this function with anything that must be done under the pg lock.
127 ///
128 /// ## Example implementation
129 ///
130 /// ```cpp
131 /// void MyDistLockComponent::DoWork()
132 /// {
133 /// // `IsCancelAdvised` is advisory/soft signal to stop the task.
134 /// // Check it in every independent processing iteration.
135 /// // Whereas @ref engine::current_task::ShouldCancel() checks as frequently,
136 /// // as you can to honor low-level task cancellation.
137 /// while (!IsCancelAdvised())
138 /// {
139 /// // Start a new trace_id
140 /// auto span = tracing::Span::MakeRootSpan("my-dist-lock");
141 ///
142 /// // If Foo() or other function in DoWork() throws an exception,
143 /// // DoWork() will be restarted in `restart-delay` seconds.
144 /// Foo();
145 ///
146 /// // Check for cancellation after cpu-intensive Foo().
147 /// // You must check for cancellation at least every `lock-ttl`
148 /// // seconds to have time to notice lock prolongation failure.
149 /// if (engine::ShouldCancel()) break;
150 ///
151 /// Bar();
152 /// }
153 /// }
154 /// ```
155 ///
156 /// @note `DoWork` must honour task cancellation and stop ASAP when
157 /// it is cancelled, otherwise brain split is possible (IOW, two different
158 /// users do work assuming both of them hold the lock, which is not true).
159 virtual void DoWork() = 0;
160
161 /// Override this function to provide custom testsuite handler.
162 virtual void DoWorkTestsuite() { DoWork(); }
163
164 /// Should be called in a .ctor of a derived class iff DisableAutostartAtBase{}
165 /// has been passed to the DistLockComponentBase .ctor.
167
168 /// Should be called in a .dtor of a derived class iff DisableAutostartAtBase{}
169 /// has been passed to the DistLockComponentBase .ctor.
171
172 /// Check this method when going for the next independent processing
173 /// iteration. Whereas @ref engine::current_task::ShouldCancel()
174 /// checks as frequently, as you can to honor low-level task cancellation.
175 bool IsCancelAdvised() const;
176
177private:
178 enum class AutostartDistlock : bool { kNo = false, kYes = true };
179
180 DistLockComponentBase(
181 const components::ComponentConfig& component_config,
182 const components::ComponentContext& component_context,
183 AutostartDistlock enable_autostart_at_base
184 );
185
186 dist_lock::DistLockSettings MakeSettings(const dynamic_config::Snapshot& config) const;
187
188 void OnConfigUpdate(const dynamic_config::Diff& diff);
189
190 dynamic_config::Source config_;
191 const std::string name_;
192 const std::string real_host_name_;
193 std::unique_ptr<dist_lock::DistLockedWorker> worker_;
194 bool autostart_;
195 bool testsuite_enabled_{false};
196 AutostartDistlock enable_autostart_at_base_;
197 dist_lock::DistLockSettings default_settings_;
198};
199
200} // namespace storages::postgres
201
202USERVER_NAMESPACE_END