userver: userver/ydb/dist_lock/worker.hpp Source File
Loading...
Searching...
No Matches
worker.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/ydb/dist_lock/worker.hpp
4/// @brief @copybrief ydb::DistLockedWorker
5
6#include <atomic>
7#include <functional>
8#include <memory>
9#include <string>
10
11#include <userver/engine/task/task_with_result.hpp>
12#include <userver/utils/not_null.hpp>
13#include <userver/utils/statistics/fwd.hpp>
14#include <userver/ydb/coordination.hpp>
15#include <userver/ydb/dist_lock/settings.hpp>
16
17USERVER_NAMESPACE_BEGIN
18
19namespace ydb {
20
21namespace impl::dist_lock {
22struct Statistics;
23} // namespace impl::dist_lock
24
25/// A high-level primitive that perpetually tries to acquire a distributed lock
26/// and runs user callback in a separate task while the lock is held.
27/// Cancels the task when the lock is lost.
28class DistLockedWorker final {
29public:
30 using Callback = std::function<void()>;
31
32 DistLockedWorker(
33 engine::TaskProcessor& task_processor,
34 std::shared_ptr<CoordinationClient> coordination_client,
35 std::string_view coordination_node,
36 std::string_view semaphore_name,
37 DistLockSettings settings,
38 Callback callback
39 );
40
41 ~DistLockedWorker();
42
43 void Start();
44
45 void Stop() noexcept;
46
47 /// @brief Run the callback once under distlock, useful in tests.
48 /// @warning Must not be run alongside a normal task launched via Start.
49 void RunOnce();
50
51 bool OwnsLock() const noexcept;
52
53 friend void DumpMetric(utils::statistics::Writer& writer, const DistLockedWorker& worker);
54
55private:
56 void Run(bool run_once);
57
58 engine::TaskProcessor& task_processor_;
59 const std::shared_ptr<CoordinationClient> coordination_client_;
60 const std::string coordination_node_;
61 const std::string semaphore_name_;
62 const DistLockSettings settings_;
63 const Callback callback_;
64
65 utils::UniqueRef<impl::dist_lock::Statistics> stats_;
66 std::atomic<bool> owns_lock_{false};
67
68 // Must be the last field, since it accesses other fields while alive.
69 engine::TaskWithResult<void> worker_task_;
70};
71
72} // namespace ydb
73
74USERVER_NAMESPACE_END