userver: userver/dist_lock/dist_lock_strategy.hpp Source File
Loading...
Searching...
No Matches
dist_lock_strategy.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/dist_lock/dist_lock_strategy.hpp
4/// @brief @copybrief dist_lock::DistLockStrategyBase
5
6#include <chrono>
7#include <exception>
8#include <string>
9
10USERVER_NAMESPACE_BEGIN
11
12namespace dist_lock {
13
14/// Indicates that lock cannot be acquired because it's busy.
15class LockIsAcquiredByAnotherHostException : public std::exception {};
16
17/// @ingroup userver_base_classes userver_concurrency
18///
19/// @brief Interface for distributed lock strategies
20///
21/// ## Example
22///
23/// @snippet core/src/dist_lock/dist_lock_test.cpp Sample distlock strategy
25public:
26 virtual ~DistLockStrategyBase() = default;
27
28 /// Acquires the distributed lock.
29 ///
30 /// @param lock_ttl The duration for which the lock must be held.
31 /// @param locker_id Globally unique ID of the locking entity.
32 /// @throws LockIsAcquiredByAnotherHostError when the lock is busy
33 /// @throws anything else when the locking fails, strategy is responsible for
34 /// cleanup, Release won't be invoked.
35 virtual void Acquire(std::chrono::milliseconds lock_ttl, const std::string& locker_id) = 0;
36
37 /// Prolongs (refreshes the TTL of) a lock already held by @a locker_id.
38 ///
39 /// Called instead of Acquire() on every refresh while the lock is held, so
40 /// backends may implement a cheaper query than the full Acquire().
41 ///
42 /// @param lock_ttl The new duration for which the lock must be held.
43 /// @param locker_id Globally unique ID of the locking entity, must be the
44 /// same as in Acquire().
45 /// @throws LockIsAcquiredByAnotherHostException when the lock is no longer
46 /// held by @a locker_id (ownership was lost)
47 /// @throws anything else when the prolongation fails, strategy is responsible
48 /// for cleanup, Release won't be invoked.
49 /// @note The default implementation simply calls Acquire(), preserving the
50 /// legacy behaviour for strategies that do not override it.
51 virtual void Prolong(std::chrono::milliseconds lock_ttl, const std::string& locker_id) {
52 Acquire(lock_ttl, locker_id);
53 }
54
55 /// Releases the lock.
56 ///
57 /// @param locker_id Globally unique ID of the locking entity, must be the
58 /// same as in Acquire().
59 /// @note Exceptions are ignored.
60 virtual void Release(const std::string& locker_id) = 0;
61};
62
63} // namespace dist_lock
64
65USERVER_NAMESPACE_END