userver: userver/engine/io/poller.hpp Source File
Loading...
Searching...
No Matches
poller.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/engine/io/poller.hpp
4/// @brief @copybrief engine::io::Poller
5
6#include <unordered_map>
7
8#include <userver/concurrent/mpsc_queue.hpp>
9#include <userver/engine/deadline.hpp>
10#include <userver/engine/io/common.hpp>
11#include <userver/utils/fast_pimpl.hpp>
12#include <userver/utils/flags.hpp>
13
14USERVER_NAMESPACE_BEGIN
15
16namespace engine::io {
17
18/// @brief I/O event monitor.
19/// @warning Generally not thread-safe, awaited events should not be changed
20/// during active waiting.
21/// @note Reports HUP as readiness.
22class Poller final {
23 public:
24 /// I/O event.
25 struct Event {
26 /// I/O event type.
27 enum Type {
28 kNone = 0, ///< No active event (or interruption)
29 kRead = (1 << 0), ///< File descriptor is ready for reading
30 kWrite = (1 << 1), ///< File descriptor is ready for writing
31 kError =
32 (1 << 2), ///< File descriptor is in error state (always awaited)
33 };
34
35 /// File descriptor responsible for the event
37 /// Triggered event types
38 utils::Flags<Type> type{kNone};
39 /// Event epoch, for internal use
41 };
42
43 /// Event retrieval status
44 enum class [[nodiscard]] Status {
45 kSuccess, ///< Received an event
46 kInterrupt, ///< Received an interrupt request
47 kNoEvents, ///< No new events available or task has been cancelled
48 };
49
50 Poller();
51 ~Poller();
52
53 Poller(const Poller&) = delete;
54 Poller(Poller&&) = delete;
55
56 /// Updates a set of events to be monitored for the file descriptor.
57 ///
58 /// At most one set of events is reported for every `Add` invocation.
59 ///
60 /// @note Event::Type::kError is implicit when any other event type is
61 /// specified.
62 void Add(int fd, utils::Flags<Event::Type> events);
63
64 /// Disables event monitoring on a specific file descriptor.
65 ///
66 /// This function must be called before closing the socket.
67 void Remove(int fd);
68
69 /// Waits for the next event and stores it at the provided structure.
70 Status NextEvent(Event&, Deadline);
71
72 /// Outputs the next event if immediately available.
74
75 /// Emits an event for an invalid fd with empty event types set.
76 void Interrupt();
77
78 /// Clears all the watched events and file descriptors
79 void Reset();
80
81 private:
82 explicit Poller(
83 const std::shared_ptr<USERVER_NAMESPACE::concurrent::MpscQueue<Event>>&);
84
85 struct IoWatcher;
86
87 void RemoveImpl(IoWatcher& watcher);
88
89 template <typename EventSource>
90 Status EventsFilter(EventSource, Event&);
91
92 USERVER_NAMESPACE::concurrent::MpscQueue<Event>::Consumer event_consumer_;
93 USERVER_NAMESPACE::concurrent::MpscQueue<Event>::Producer event_producer_;
94 utils::FastPimpl<std::unordered_map<int, IoWatcher>, 56, alignof(double),
95 false>
96 watchers_;
97};
98
99} // namespace engine::io
100
101USERVER_NAMESPACE_END