userver: userver/storages/redis/subscription_token.hpp Source File
Loading...
Searching...
No Matches
subscription_token.hpp
1#pragma once
2
3/// @file userver/storages/redis/subscriptioin_token.hpp
4/// @brief @copybrief storages::redis::SubscriptionToken
5
6#include <functional>
7#include <memory>
8#include <string>
9
10USERVER_NAMESPACE_BEGIN
11
12namespace redis {
13struct CommandControl;
14class SubscribeSentinel;
15} // namespace redis
16
17namespace storages::redis {
18
19namespace impl {
20
21class SubscriptionTokenImplBase {
22 public:
23 SubscriptionTokenImplBase() = default;
24
25 SubscriptionTokenImplBase(SubscriptionTokenImplBase&&) = delete;
26 SubscriptionTokenImplBase& operator=(SubscriptionTokenImplBase&&) = delete;
27
28 SubscriptionTokenImplBase(const SubscriptionTokenImplBase&) = delete;
29 SubscriptionTokenImplBase& operator=(const SubscriptionTokenImplBase&&) =
30 delete;
31
32 virtual ~SubscriptionTokenImplBase();
33
34 virtual void SetMaxQueueLength(size_t length) = 0;
35
36 virtual void Unsubscribe() = 0;
37};
38
39} // namespace impl
40
41/// @brief RAII subscription guard, that is usually retrieved from
42/// storages::redis::SubscribeClient.
43///
44/// See storages::redis::MockSubscriptionTokenImpl for hints on mocking and
45/// testing.
46class [[nodiscard]] SubscriptionToken final {
47 public:
48 using OnMessageCb = std::function<void(const std::string& channel,
49 const std::string& message)>;
50 using OnPmessageCb =
51 std::function<void(const std::string& pattern, const std::string& channel,
52 const std::string& message)>;
53
54 SubscriptionToken();
55 SubscriptionToken(SubscriptionToken&&) noexcept;
56
57 /// This constructor can be used in tests/mocks to create your own
58 /// subscription token
60 std::unique_ptr<impl::SubscriptionTokenImplBase>&& implementation);
61
62 ~SubscriptionToken();
63
64 SubscriptionToken& operator=(SubscriptionToken&&) noexcept;
65
66 /// There is a MPSC queue inside the connection. This parameter requlates
67 /// its maximum length. If it overflows, new messages are discarded.
68 void SetMaxQueueLength(size_t length);
69
70 /// Unsubscribe from the channel. This method is synchronous, once it
71 /// returned, no new calls to callback will be made.
72 void Unsubscribe();
73
74 /// Checks that token is not empty. Empty token has no implementation
75 /// inside. This method is mostly useful in unit tests. All methods
76 /// of this class work correctly on empty tokens.
77 bool IsEmpty() const noexcept { return impl_ == nullptr; }
78
79 private:
80 std::unique_ptr<impl::SubscriptionTokenImplBase> impl_;
81};
82
83} // namespace storages::redis
84
85USERVER_NAMESPACE_END