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 {
29 public:
30 using Callback = std::function<void()>;
31
32 DistLockedWorker(engine::TaskProcessor& task_processor,
33 std::shared_ptr<CoordinationClient> coordination_client,
34 std::string_view coordination_node,
35 std::string_view semaphore_name, DistLockSettings settings,
36 Callback callback);
37
38 ~DistLockedWorker();
39
40 void Start();
41
42 void Stop() noexcept;
43
44 /// @brief Run the callback once under distlock, useful in tests.
45 /// @warning Must not be run alongside a normal task launched via Start.
46 void RunOnce();
47
48 bool OwnsLock() const noexcept;
49
50 friend void DumpMetric(utils::statistics::Writer& writer,
51 const DistLockedWorker& worker);
52
53 private:
54 void Run(bool run_once);
55
56 engine::TaskProcessor& task_processor_;
57 const std::shared_ptr<CoordinationClient> coordination_client_;
58 const std::string coordination_node_;
59 const std::string semaphore_name_;
60 const DistLockSettings settings_;
61 const Callback callback_;
62
63 utils::UniqueRef<impl::dist_lock::Statistics> stats_;
64 std::atomic<bool> owns_lock_{false};
65
66 // Must be the last field, since it accesses other fields while alive.
67 engine::TaskWithResult<void> worker_task_;
68};
69
70} // namespace ydb
71
72USERVER_NAMESPACE_END