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 {
23public:
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 = (1 << 2), ///< File descriptor is in error state (always awaited)
32 };
33
34 /// File descriptor responsible for the event
36 /// Triggered event types
37 utils::Flags<Type> type{kNone};
38 /// Event epoch, for internal use
40 };
41
42 /// Event retrieval status
43 enum class [[nodiscard]] Status {
44 kSuccess, ///< Received an event
45 kInterrupt, ///< Received an interrupt request
46 kNoEvents, ///< No new events available or task has been cancelled
47 };
48
49 Poller();
50 ~Poller();
51
52 Poller(const Poller&) = delete;
53 Poller(Poller&&) = delete;
54
55 /// Updates a set of events to be monitored for the file descriptor.
56 ///
57 /// At most one set of events is reported for every `Add` invocation.
58 ///
59 /// @note Event::Type::kError is implicit when any other event type is
60 /// specified.
61 void Add(int fd, utils::Flags<Event::Type> events);
62
63 /// Disables event monitoring on a specific file descriptor.
64 ///
65 /// This function must be called before closing the socket.
66 void Remove(int fd);
67
68 /// Waits for the next event and stores it at the provided structure.
69 Status NextEvent(Event&, Deadline);
70
71 /// Outputs the next event if immediately available.
73
74 /// Emits an event for an invalid fd with empty event types set.
75 void Interrupt();
76
77 /// Clears all the watched events and file descriptors
78 void Reset();
79
80private:
81 explicit Poller(const std::shared_ptr<USERVER_NAMESPACE::concurrent::MpscQueue<Event>>&);
82
83 struct IoWatcher;
84
85 void RemoveImpl(IoWatcher& watcher);
86
87 template <typename EventSource>
88 Status EventsFilter(EventSource, Event&);
89
90 USERVER_NAMESPACE::concurrent::MpscQueue<Event>::Consumer event_consumer_;
91 USERVER_NAMESPACE::concurrent::MpscQueue<Event>::Producer event_producer_;
92 utils::FastPimpl<std::unordered_map<int, IoWatcher>, 56, alignof(double), false> watchers_;
93};
94
95} // namespace engine::io
96
97USERVER_NAMESPACE_END