blob: 23250e185012cc494ef724e936b1707daf0880e2 [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_EVENT_LOOP_H_
2#define AOS_EVENTS_EVENT_LOOP_H_
3
Brian Silverman6a54ff32020-04-28 16:41:39 -07004#include <sched.h>
5
Alex Perrycb7da4b2019-08-28 19:35:56 -07006#include <atomic>
milind1f1dca32021-07-03 13:50:07 -07007#include <ostream>
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08009#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -070010
Austin Schuh3054f5f2021-07-21 15:38:01 -070011#include "absl/container/btree_set.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070012#include "aos/configuration.h"
13#include "aos/configuration_generated.h"
Austin Schuh1af273d2020-03-07 20:11:34 -080014#include "aos/events/channel_preallocated_allocator.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080015#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080016#include "aos/events/event_loop_generated.h"
17#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070018#include "aos/flatbuffers.h"
Brian Silverman79ec7fc2020-06-08 20:11:22 -050019#include "aos/ftrace.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080020#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "aos/json_to_flatbuffer.h"
22#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080023#include "aos/util/phased_loop.h"
Austin Schuh4385b142021-03-14 21:31:13 -070024#include "aos/uuid.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070025#include "flatbuffers/flatbuffers.h"
26#include "glog/logging.h"
27
Austin Schuh39788ff2019-12-01 18:22:57 -080028DECLARE_bool(timing_reports);
29DECLARE_int32(timing_report_ms);
30
Alex Perrycb7da4b2019-08-28 19:35:56 -070031namespace aos {
32
Austin Schuh39788ff2019-12-01 18:22:57 -080033class EventLoop;
34class WatcherState;
35
Austin Schuh6231cc32019-12-07 13:06:15 -080036// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
37// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070038struct Context {
Austin Schuhad154822019-12-27 15:45:13 -080039 // Time that the message was sent on this node, or the timer was triggered.
40 monotonic_clock::time_point monotonic_event_time;
41 // Realtime the message was sent on this node. This is set to min_time for
42 // Timers and PhasedLoops.
43 realtime_clock::time_point realtime_event_time;
44
James Kuszmaulad523042022-10-05 16:47:33 -070045 // The rest are only valid for Watchers and Fetchers.
46
Austin Schuhad154822019-12-27 15:45:13 -080047 // For a single-node configuration, these two are identical to *_event_time.
48 // In a multinode configuration, these are the times that the message was
49 // sent on the original node.
50 monotonic_clock::time_point monotonic_remote_time;
51 realtime_clock::time_point realtime_remote_time;
52
Alex Perrycb7da4b2019-08-28 19:35:56 -070053 // Index in the queue.
54 uint32_t queue_index;
Austin Schuhad154822019-12-27 15:45:13 -080055 // Index into the remote queue. Useful to determine if data was lost. In a
56 // single-node configuration, this will match queue_index.
57 uint32_t remote_queue_index;
58
Alex Perrycb7da4b2019-08-28 19:35:56 -070059 // Size of the data sent.
60 size_t size;
61 // Pointer to the data.
Brian Silvermaneaa41d62020-07-08 19:47:35 -070062 const void *data;
Austin Schuh678078e2020-08-01 14:30:36 -070063
Brian Silverman4f4e0612020-08-12 19:54:41 -070064 // Index of the message buffer. This will be in [0, NumberBuffers) on
65 // read_method=PIN channels, and -1 for other channels.
66 //
67 // This only tells you about the underlying storage for this message, not
68 // anything about its position in the queue. This is only useful for advanced
69 // zero-copy use cases, on read_method=PIN channels.
70 //
71 // This will uniquely identify a message on this channel at a point in time.
72 // For senders, this point in time is while the sender has the message. With
73 // read_method==PIN, this point in time includes while the caller has access
74 // to this context. For other read_methods, this point in time may be before
75 // the caller has access to this context, which makes this pretty useless.
76 int buffer_index;
77
Austin Schuh8902fa52021-03-14 22:39:24 -070078 // UUID of the remote node which sent this message, or this node in the case
79 // of events which are local to this node.
Austin Schuha9012be2021-07-21 15:19:11 -070080 UUID source_boot_uuid = UUID::Zero();
Austin Schuh8902fa52021-03-14 22:39:24 -070081
Austin Schuhca75b6a2020-12-15 21:12:24 -080082 // Efficiently copies the flatbuffer into a FlatbufferVector, allocating
Austin Schuh678078e2020-08-01 14:30:36 -070083 // memory in the process. It is vital that T matches the type of the
84 // underlying flatbuffer.
85 template <typename T>
86 FlatbufferVector<T> CopyFlatBuffer() const {
Brian Silverman354697a2020-09-22 21:06:32 -070087 ResizeableBuffer buffer;
88 buffer.resize(size);
89 memcpy(buffer.data(), data, size);
90 return FlatbufferVector<T>(std::move(buffer));
Austin Schuh678078e2020-08-01 14:30:36 -070091 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070092};
93
94// Raw version of fetcher. Contains a local variable that the fetcher will
95// update. This is used for reflection and as an interface to implement typed
96// fetchers.
97class RawFetcher {
98 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080099 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700100 RawFetcher(const RawFetcher &) = delete;
101 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700103
Austin Schuh39788ff2019-12-01 18:22:57 -0800104 // Fetches the next message in the queue without blocking. Returns true if
105 // there was a new message and we got it.
106 bool FetchNext();
107
108 // Fetches the latest message without blocking.
109 bool Fetch();
110
111 // Returns the channel this fetcher uses.
112 const Channel *channel() const { return channel_; }
113 // Returns the context for the current message.
114 const Context &context() const { return context_; }
115
116 protected:
117 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700118 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800119
Alex Perrycb7da4b2019-08-28 19:35:56 -0700120 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800121
122 private:
123 friend class EventLoop;
124 // Implementation
125 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
126 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
127
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500128 EventLoop *const event_loop_;
129 const Channel *const channel_;
130 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800131
132 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500133 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700134};
135
136// Raw version of sender. Sends a block of data. This is used for reflection
137// and as a building block to implement typed senders.
138class RawSender {
139 public:
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700140 using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
141
Brian Silverman183859c2022-05-14 02:03:06 -0700142 // This looks a little ugly with no space, but please leave it so clang-format
143 // doesn't keep changing it. Bug is filed at
144 // <https://github.com/llvm/llvm-project/issues/55457>.
145 enum class [[nodiscard]] Error{
milind1f1dca32021-07-03 13:50:07 -0700146 // Represents success and no error
147 kOk,
148
149 // Error for messages on channels being sent faster than their
150 // frequency and channel storage duration allow
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700151 kMessagesSentTooFast,
152 // Access to Redzone was attempted in Sender Queue
Brian Silverman183859c2022-05-14 02:03:06 -0700153 kInvalidRedzone,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700154 };
milind1f1dca32021-07-03 13:50:07 -0700155
Austin Schuh39788ff2019-12-01 18:22:57 -0800156 RawSender(EventLoop *event_loop, const Channel *channel);
157 RawSender(const RawSender &) = delete;
158 RawSender &operator=(const RawSender &) = delete;
159
160 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700161
Brian Silverman9809c5f2022-07-23 16:12:23 -0700162 // Returns the buffer to write new messages into. This is always valid, and
163 // may change after calling any of the Send functions.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164 virtual void *data() = 0;
165 virtual size_t size() = 0;
milind1f1dca32021-07-03 13:50:07 -0700166
167 // Sends a message without copying it. The users starts by copying up to
168 // size() bytes into the data backed by data(). They then call Send to send.
169 // Returns Error::kOk on a successful send, or
170 // Error::kMessagesSentTooFast if messages were sent too fast. If provided,
171 // monotonic_remote_time, realtime_remote_time, and remote_queue_index are
172 // attached to the message and are available in the context on the read side.
173 // If they are not populated, the read side will get the sent times instead.
174 Error Send(size_t size);
175 Error Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
176 realtime_clock::time_point realtime_remote_time,
177 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700178
179 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800180 // The remote arguments have the same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700181 // Returns Error::kMessagesSentTooFast if messages were sent too fast
182 Error Send(const void *data, size_t size);
183 Error Send(const void *data, size_t size,
184 monotonic_clock::time_point monotonic_remote_time,
185 realtime_clock::time_point realtime_remote_time,
186 uint32_t remote_queue_index, const UUID &source_boot_uuid);
187
188 // CHECKs that no sending Error occurred and logs the channel_ data if
189 // one did
190 void CheckOk(const Error err);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700191
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700192 // Sends a single block of data by refcounting it to avoid copies. The data
193 // must not change after being passed into Send. The remote arguments have the
194 // same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700195 Error Send(const SharedSpan data);
196 Error Send(const SharedSpan data,
197 monotonic_clock::time_point monotonic_remote_time,
198 realtime_clock::time_point realtime_remote_time,
199 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700200
Austin Schuh54cf95f2019-11-29 13:14:18 -0800201 const Channel *channel() const { return channel_; }
202
Austin Schuhad154822019-12-27 15:45:13 -0800203 // Returns the time_points that the last message was sent at.
204 aos::monotonic_clock::time_point monotonic_sent_time() const {
205 return monotonic_sent_time_;
206 }
207 aos::realtime_clock::time_point realtime_sent_time() const {
208 return realtime_sent_time_;
209 }
210 // Returns the queue index that this was sent with.
211 uint32_t sent_queue_index() const { return sent_queue_index_; }
212
Brian Silvermana1652f32020-01-29 20:41:44 -0800213 // Returns the associated flatbuffers-style allocator. This must be
214 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800215 ChannelPreallocatedAllocator *fbb_allocator() {
216 fbb_allocator_ = ChannelPreallocatedAllocator(
217 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800218 return &fbb_allocator_;
219 }
220
Brian Silverman4f4e0612020-08-12 19:54:41 -0700221 // Index of the buffer which is currently exposed by data() and the various
222 // other accessors. This is the message the caller should be filling out.
223 virtual int buffer_index() = 0;
224
Alex Perrycb7da4b2019-08-28 19:35:56 -0700225 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800226 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700227 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800228
Austin Schuhb5c6f972021-03-14 21:53:07 -0700229 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
230 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800231 uint32_t sent_queue_index_ = 0xffffffff;
232
Austin Schuh39788ff2019-12-01 18:22:57 -0800233 private:
234 friend class EventLoop;
235
milind1f1dca32021-07-03 13:50:07 -0700236 virtual Error DoSend(const void *data, size_t size,
237 monotonic_clock::time_point monotonic_remote_time,
238 realtime_clock::time_point realtime_remote_time,
239 uint32_t remote_queue_index,
240 const UUID &source_boot_uuid) = 0;
241 virtual Error DoSend(size_t size,
242 monotonic_clock::time_point monotonic_remote_time,
243 realtime_clock::time_point realtime_remote_time,
244 uint32_t remote_queue_index,
245 const UUID &source_boot_uuid) = 0;
246 virtual Error DoSend(const SharedSpan data,
247 monotonic_clock::time_point monotonic_remote_time,
248 realtime_clock::time_point realtime_remote_time,
249 uint32_t remote_queue_index,
250 const UUID &source_boot_uuid);
Austin Schuh39788ff2019-12-01 18:22:57 -0800251
James Kuszmaul93abac12022-04-14 15:05:10 -0700252 void RecordSendResult(const Error error, size_t message_size);
253
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500254 EventLoop *const event_loop_;
255 const Channel *const channel_;
256 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700257
Austin Schuh39788ff2019-12-01 18:22:57 -0800258 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500259 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800260
Austin Schuh1af273d2020-03-07 20:11:34 -0800261 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800262};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700263
milind1f1dca32021-07-03 13:50:07 -0700264// Needed for compatibility with glog
265std::ostream &operator<<(std::ostream &os, const RawSender::Error err);
266
Alex Perrycb7da4b2019-08-28 19:35:56 -0700267// Fetches the newest message from a channel.
268// This provides a polling based interface for channels.
269template <typename T>
270class Fetcher {
271 public:
272 Fetcher() {}
273
274 // Fetches the next message. Returns true if it fetched a new message. This
275 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800276 bool FetchNext() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800277 const bool result = CHECK_NOTNULL(fetcher_)->FetchNext();
Brian Silvermana1652f32020-01-29 20:41:44 -0800278 if (result) {
279 CheckChannelDataAlignment(fetcher_->context().data,
280 fetcher_->context().size);
281 }
282 return result;
283 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284
285 // Fetches the most recent message. Returns true if it fetched a new message.
286 // This will return the latest message regardless of if it was sent before or
287 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800288 bool Fetch() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800289 const bool result = CHECK_NOTNULL(fetcher_)->Fetch();
Brian Silvermana1652f32020-01-29 20:41:44 -0800290 if (result) {
291 CheckChannelDataAlignment(fetcher_->context().data,
292 fetcher_->context().size);
293 }
294 return result;
295 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296
297 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
298 // available message.
299 const T *get() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800300 return CHECK_NOTNULL(fetcher_)->context().data != nullptr
Austin Schuh39788ff2019-12-01 18:22:57 -0800301 ? flatbuffers::GetRoot<T>(
302 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303 : nullptr;
304 }
305
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700306 // Returns the channel this fetcher uses
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800307 const Channel *channel() const { return CHECK_NOTNULL(fetcher_)->channel(); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700308
Alex Perrycb7da4b2019-08-28 19:35:56 -0700309 // Returns the context holding timestamps and other metadata about the
310 // message.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800311 const Context &context() const { return CHECK_NOTNULL(fetcher_)->context(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700312
313 const T &operator*() const { return *get(); }
314 const T *operator->() const { return get(); }
315
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800316 // Returns true if this fetcher is valid and connected to a channel. If you,
317 // e.g., are using TryMakeFetcher, then you must check valid() before
318 // attempting to use the Fetcher.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700319 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700320
Austin Schuhca75b6a2020-12-15 21:12:24 -0800321 // Copies the current flatbuffer into a FlatbufferVector.
322 FlatbufferVector<T> CopyFlatBuffer() const {
323 return context().template CopyFlatBuffer<T>();
324 }
325
Alex Perrycb7da4b2019-08-28 19:35:56 -0700326 private:
327 friend class EventLoop;
328 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
329 : fetcher_(::std::move(fetcher)) {}
330 ::std::unique_ptr<RawFetcher> fetcher_;
331};
332
333// Sends messages to a channel.
334template <typename T>
335class Sender {
336 public:
337 Sender() {}
338
339 // Represents a single message about to be sent to the queue.
340 // The lifecycle goes:
341 //
342 // Builder builder = sender.MakeBuilder();
343 // T::Builder t_builder = builder.MakeBuilder<T>();
344 // Populate(&t_builder);
345 // builder.Send(t_builder.Finish());
346 class Builder {
347 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800348 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800349 : fbb_(allocator->size(), allocator),
350 allocator_(allocator),
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800351 sender_(CHECK_NOTNULL(sender)) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800352 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800353 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800355 Builder() {}
356 Builder(const Builder &) = delete;
357 Builder(Builder &&) = default;
358
359 Builder &operator=(const Builder &) = delete;
360 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700361
362 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
363
364 template <typename T2>
365 typename T2::Builder MakeBuilder() {
366 return typename T2::Builder(fbb_);
367 }
368
milind1f1dca32021-07-03 13:50:07 -0700369 RawSender::Error Send(flatbuffers::Offset<T> offset) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700370 fbb_.Finish(offset);
milind1f1dca32021-07-03 13:50:07 -0700371 const auto err = sender_->Send(fbb_.GetSize());
Brian Silverman9dd793b2020-01-31 23:52:21 -0800372 // Ensure fbb_ knows it shouldn't access the memory any more.
373 fbb_ = flatbuffers::FlatBufferBuilder();
milind1f1dca32021-07-03 13:50:07 -0700374 return err;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375 }
376
milind1f1dca32021-07-03 13:50:07 -0700377 // Equivalent to RawSender::CheckOk
378 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
379
Alex Perrycb7da4b2019-08-28 19:35:56 -0700380 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800381 void CheckSent() {
382 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
383 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700384
Brian Silverman341b57e2020-06-23 16:23:18 -0700385 // Detaches a buffer, for later use calling Sender::Send directly.
386 //
387 // Note that the underlying memory remains with the Sender, so creating
388 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
389 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
390 fbb_.Finish(offset);
391 return fbb_.Release();
392 }
393
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800396 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700397 RawSender *sender_;
398 };
399
400 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800401 //
402 // Only a single one of these may be "alive" for this object at any point in
403 // time. After calling Send on the result, it is no longer "alive". This means
404 // that you must manually reset a variable holding the return value (by
405 // assigning a default-constructed Builder to it) before calling this method
406 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407 Builder MakeBuilder();
408
Austin Schuha28cbc32019-12-27 16:28:04 -0800409 // Sends a prebuilt flatbuffer.
James Kuszmaulad523042022-10-05 16:47:33 -0700410 // This will copy the data out of the provided flatbuffer, and so does not
411 // have to correspond to an existing Builder.
milind1f1dca32021-07-03 13:50:07 -0700412 RawSender::Error Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800413
Brian Silverman341b57e2020-06-23 16:23:18 -0700414 // Sends a prebuilt flatbuffer which was detached from a Builder created via
415 // MakeBuilder() on this object.
milind1f1dca32021-07-03 13:50:07 -0700416 RawSender::Error SendDetached(FlatbufferDetachedBuffer<T> detached);
417
418 // Equivalent to RawSender::CheckOk
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800419 void CheckOk(const RawSender::Error err) {
420 CHECK_NOTNULL(sender_)->CheckOk(err);
421 };
Brian Silverman341b57e2020-06-23 16:23:18 -0700422
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800423 // Returns the name of the underlying queue, if valid. You must check valid()
424 // first.
425 const Channel *channel() const { return CHECK_NOTNULL(sender_)->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426
James Kuszmaulad523042022-10-05 16:47:33 -0700427 // Returns true if the Sender is a valid Sender. If you, e.g., are using
428 // TryMakeSender, then you must check valid() before attempting to use the
429 // Sender.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800430 // TODO(austin): Deprecate the operator bool.
Austin Schuha0c41ba2020-09-10 22:59:14 -0700431 operator bool() const { return sender_ ? true : false; }
Austin Schuhe33c08d2022-02-03 18:15:21 -0800432 bool valid() const { return static_cast<bool>(sender_); }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800433
Austin Schuh7bc59052020-02-16 23:48:33 -0800434 // Returns the time_points that the last message was sent at.
435 aos::monotonic_clock::time_point monotonic_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800436 return CHECK_NOTNULL(sender_)->monotonic_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800437 }
438 aos::realtime_clock::time_point realtime_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800439 return CHECK_NOTNULL(sender_)->realtime_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800440 }
441 // Returns the queue index that this was sent with.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800442 uint32_t sent_queue_index() const {
443 return CHECK_NOTNULL(sender_)->sent_queue_index();
444 }
Austin Schuh7bc59052020-02-16 23:48:33 -0800445
Brian Silverman4f4e0612020-08-12 19:54:41 -0700446 // Returns the buffer index which MakeBuilder() will expose access to. This is
447 // the buffer the caller can fill out.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800448 int buffer_index() const { return CHECK_NOTNULL(sender_)->buffer_index(); }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700449
Alex Perrycb7da4b2019-08-28 19:35:56 -0700450 private:
451 friend class EventLoop;
452 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
453 std::unique_ptr<RawSender> sender_;
454};
455
milind1f1dca32021-07-03 13:50:07 -0700456// Class for keeping a count of send failures on a certain channel
457class SendFailureCounter {
458 public:
459 inline void Count(const RawSender::Error err) {
460 failures_ += static_cast<size_t>(err != RawSender::Error::kOk);
461 just_failed_ = (err != RawSender::Error::kOk);
462 }
463
464 inline size_t failures() const { return failures_; }
465 inline bool just_failed() const { return just_failed_; }
466
467 private:
468 size_t failures_ = 0;
469 bool just_failed_ = false;
470};
471
Brian Silverman4f4e0612020-08-12 19:54:41 -0700472// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700473class TimerHandler {
474 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800475 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700476
477 // Timer should sleep until base, base + offset, base + offset * 2, ...
478 // If repeat_offset isn't set, the timer only expires once.
James Kuszmaul8866e642022-06-10 16:00:36 -0700479 // base must be greater than or equal to zero.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 virtual void Setup(monotonic_clock::time_point base,
481 monotonic_clock::duration repeat_offset =
482 ::aos::monotonic_clock::zero()) = 0;
483
484 // Stop future calls to callback().
485 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800486
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700487 // Check if the timer is disabled
488 virtual bool IsDisabled() = 0;
489
Austin Schuh1540c2f2019-11-29 21:59:29 -0800490 // Sets and gets the name of the timer. Set this if you want a descriptive
491 // name in the timing report.
492 void set_name(std::string_view name) { name_ = std::string(name); }
493 const std::string_view name() const { return name_; }
494
Austin Schuh39788ff2019-12-01 18:22:57 -0800495 protected:
496 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
497
Austin Schuh9b1d6282022-06-10 17:03:21 -0700498 template <typename T>
499 monotonic_clock::time_point Call(T get_time,
500 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800501
Austin Schuh1540c2f2019-11-29 21:59:29 -0800502 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800503 friend class EventLoop;
504
505 EventLoop *event_loop_;
506 // The function to call when Call is called.
507 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800508 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800509
510 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500511 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700512};
513
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800514// Interface for phased loops. They are built on timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700515class PhasedLoopHandler {
516 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800517 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700518
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800519 // Sets the interval and offset. Any changes to interval and offset only take
520 // effect when the handler finishes running or upon a call to Reschedule().
521 //
522 // The precise semantics of the monotonic_now parameter are defined in
523 // phased_loop.h. The way that it gets used in this interface is to control
524 // what the cycles elapsed counter will read on the following call to your
525 // handler. In an idealized simulation environment, if you call
526 // set_interval_and_offset() during the phased loop offset without setting
527 // monotonic_now, then you should always see a count of 1 on the next cycle.
528 //
529 // With the default behavior (this is called inside your handler and with
530 // monotonic_now = nullopt), the next phased loop call will occur at most
531 // interval time after the current time. Note that in many cases this will
532 // *not* be the preferred behavior (in most cases, you would likely aim to
533 // keep the average frequency of the calls reasonably consistent).
534 //
535 // A combination of the monotonic_now parameter and manually calling
536 // Reschedule() outside of the phased loop handler can be used to alter the
537 // behavior of cycles_elapsed. For the default behavior, you can set
538 // monotonic_now to the current time. If you call set_interval_and_offset()
539 // and Reschedule() with the same monotonic_now, that will cause the next
540 // callback to occur in the range (monotonic_now, monotonic_now + interval]
541 // and get called with a count of 1 (if the event is actually able to happen
542 // when it is scheduled to). E.g., if you are just adjusting the phased loop
543 // offset (but not the interval) and want to maintain a consistent frequency,
544 // you may call these functions with monotonic_now = now + interval / 2.
545 void set_interval_and_offset(
546 const monotonic_clock::duration interval,
547 const monotonic_clock::duration offset,
548 std::optional<monotonic_clock::time_point> monotonic_now = std::nullopt) {
549 phased_loop_.set_interval_and_offset(interval, offset, monotonic_now);
Austin Schuh39788ff2019-12-01 18:22:57 -0800550 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800551
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800552 // Reruns the scheduler for the phased loop, scheduling the next callback at
553 // the next available time after monotonic_now. This allows
554 // set_interval_and_offset() to be called and have the changes take effect
555 // before the next handler finishes. This will have no effect if run during
556 // the phased loop's own handler.
557 void Reschedule(monotonic_clock::time_point monotonic_now) {
558 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
559 Schedule(phased_loop_.sleep_time());
560 }
561
562 // Sets and gets the name of the timer. Set this if you want a descriptive
Austin Schuh1540c2f2019-11-29 21:59:29 -0800563 // name in the timing report.
564 void set_name(std::string_view name) { name_ = std::string(name); }
565 const std::string_view name() const { return name_; }
566
Austin Schuh39788ff2019-12-01 18:22:57 -0800567 protected:
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800568 void Call(std::function<monotonic_clock::time_point()> get_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800569
570 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
571 const monotonic_clock::duration interval,
572 const monotonic_clock::duration offset);
573
Austin Schuh1540c2f2019-11-29 21:59:29 -0800574 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800575 friend class EventLoop;
576
Austin Schuh39788ff2019-12-01 18:22:57 -0800577 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
578
579 EventLoop *event_loop_;
580 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800581 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800582 time::PhasedLoop phased_loop_;
583
584 int cycles_elapsed_ = 0;
585
586 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500587 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700588};
589
Austin Schuh3054f5f2021-07-21 15:38:01 -0700590// Note, it is supported to create only:
591// multiple fetchers, and (one sender or one watcher) per <name, type>
592// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700593class EventLoop {
594 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700595 // Holds configuration by reference for the lifetime of this object. It may
596 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800597 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598
Austin Schuh39788ff2019-12-01 18:22:57 -0800599 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700600
601 // Current time.
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800602 virtual monotonic_clock::time_point monotonic_now() const = 0;
603 virtual realtime_clock::time_point realtime_now() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700604
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700605 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800606 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800607 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800608 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800609 true);
610 }
milind1f1dca32021-07-03 13:50:07 -0700611 // Returns true if the channel exists in the configuration.
Austin Schuha0654152021-02-21 21:38:24 -0800612 template <typename T>
613 bool HasChannel(const std::string_view channel_name) {
614 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700615 }
616
Brian Silverman631b6262021-11-10 12:25:08 -0800617 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800618 // not readable on this node or does not exist. You must check valid() on the
619 // Fetcher before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800620 template <typename T>
621 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
622 const Channel *const channel = GetChannel<T>(channel_name);
623 if (channel == nullptr) {
624 return Fetcher<T>();
625 }
626
627 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
628 return Fetcher<T>();
629 }
630
631 return Fetcher<T>(MakeRawFetcher(channel));
632 }
633
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634 // Makes a class that will always fetch the most recent value
635 // sent to the provided channel.
636 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800637 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800638 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700639 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
640 << T::GetFullyQualifiedName() << "\" } not found in config.";
641
Brian Silverman631b6262021-11-10 12:25:08 -0800642 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
643 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800644 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
645 << "\", \"type\": \"" << T::GetFullyQualifiedName()
646 << "\" } is not able to be fetched on this node. Check your "
647 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800648 }
649
Brian Silverman631b6262021-11-10 12:25:08 -0800650 return result;
651 }
652
653 // Like MakeSender, but returns an invalid sender if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800654 // not sendable on this node or does not exist. You must check valid() on the
655 // Sender before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800656 template <typename T>
657 Sender<T> TryMakeSender(const std::string_view channel_name) {
658 const Channel *channel = GetChannel<T>(channel_name);
659 if (channel == nullptr) {
660 return Sender<T>();
661 }
662
663 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
664 return Sender<T>();
665 }
666
667 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700668 }
669
670 // Makes class that allows constructing and sending messages to
671 // the provided channel.
672 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800673 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800674 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700675 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800676 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700677 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800678 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700679 ? absl::StrCat(" on node ", node()->name()->string_view())
680 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700681
Brian Silverman631b6262021-11-10 12:25:08 -0800682 Sender<T> result = TryMakeSender<T>(channel_name);
683 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800684 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
685 << "\", \"type\": \"" << T::GetFullyQualifiedName()
686 << "\" } is not able to be sent on this node. Check your "
687 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800688 }
689
Brian Silverman631b6262021-11-10 12:25:08 -0800690 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700691 }
692
693 // This will watch messages sent to the provided channel.
694 //
Brian Silverman454bc112020-03-05 14:21:25 -0800695 // w must have a non-polymorphic operator() (aka it can only be called with a
696 // single set of arguments; no overloading or templates). It must be callable
697 // with this signature:
698 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700699 //
Brian Silverman454bc112020-03-05 14:21:25 -0800700 // Lambdas are a common form for w. A std::function will work too.
701 //
702 // Note that bind expressions have polymorphic call operators, so they are not
703 // allowed.
704 //
705 // We template Watch as a whole instead of using std::function<void(const T
706 // &)> to allow deducing MessageType from lambdas and other things which are
707 // implicitly convertible to std::function, but not actually std::function
708 // instantiations. Template deduction guides might allow solving this
709 // differently in newer versions of C++, but those have their own corner
710 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700711 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800712 void MakeWatcher(const std::string_view channel_name, Watch &&w);
713
714 // Like MakeWatcher, but doesn't have access to the message data. This may be
715 // implemented to use less resources than an equivalent MakeWatcher.
716 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800717 // The function will still have access to context(), although that will have
718 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800719 template <typename MessageType>
720 void MakeNoArgWatcher(const std::string_view channel_name,
721 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700722
723 // The passed in function will be called when the event loop starts.
724 // Use this to run code once the thread goes into "real-time-mode",
725 virtual void OnRun(::std::function<void()> on_run) = 0;
726
Austin Schuh217a9782019-12-21 23:02:50 -0800727 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800728 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700729
Austin Schuh217a9782019-12-21 23:02:50 -0800730 // Returns the node that this event loop is running on. Returns nullptr if we
731 // are running in single-node mode.
732 virtual const Node *node() const = 0;
733
Alex Perrycb7da4b2019-08-28 19:35:56 -0700734 // Creates a timer that executes callback when the timer expires
735 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700736 // TODO(milind): callback should take the number of cycles elapsed as a
737 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700738 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
739
740 // Creates a timer that executes callback periodically at the specified
741 // interval and offset. Returns a PhasedLoopHandler for interacting with the
742 // timer.
743 virtual PhasedLoopHandler *AddPhasedLoop(
744 ::std::function<void(int)> callback,
745 const monotonic_clock::duration interval,
746 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
747
Austin Schuh217a9782019-12-21 23:02:50 -0800748 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700749
Austin Schuh3054f5f2021-07-21 15:38:01 -0700750 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700751 bool is_running() const { return is_running_.load(); }
752
753 // Sets the scheduler priority to run the event loop at. This may not be
754 // called after we go into "real-time-mode".
755 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700756 // Defaults to 0 if this loop will not run realtime.
757 virtual int runtime_realtime_priority() const = 0;
758
Austin Schuh070019a2022-12-20 22:23:09 -0800759 static cpu_set_t DefaultAffinity();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700760
Brian Silverman6a54ff32020-04-28 16:41:39 -0700761 // Sets the scheduler affinity to run the event loop with. This may only be
762 // called before Run().
763 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700764 // Defaults to DefaultAffinity() if this loop will not run pinned.
765 virtual const cpu_set_t &runtime_affinity() const = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700766
Austin Schuh217a9782019-12-21 23:02:50 -0800767 // Fetches new messages from the provided channel (path, type).
768 //
769 // Note: this channel must be a member of the exact configuration object this
770 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700771 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
772 const Channel *channel) = 0;
773
Austin Schuh217a9782019-12-21 23:02:50 -0800774 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700775 virtual void MakeRawWatcher(
776 const Channel *channel,
777 std::function<void(const Context &context, const void *message)>
778 watcher) = 0;
779
Brian Silverman454bc112020-03-05 14:21:25 -0800780 // Watches channel (name, type) for new messages, without needing to extract
781 // the message contents. Default implementation simply re-uses MakeRawWatcher.
782 virtual void MakeRawNoArgWatcher(
783 const Channel *channel,
784 std::function<void(const Context &context)> watcher) {
785 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800786 Context new_context = context;
787 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700788 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800789 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800790 });
791 }
792
Austin Schuh217a9782019-12-21 23:02:50 -0800793 // Creates a raw sender for the provided channel. This is used for reflection
794 // based sending.
795 // Note: this ignores any node constraints. Ignore at your own peril.
796 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
797
Austin Schuh6231cc32019-12-07 13:06:15 -0800798 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700799 const Context &context() const { return context_; }
800
801 // Returns the configuration that this event loop was built with.
802 const Configuration *configuration() const { return configuration_; }
803
Austin Schuh39788ff2019-12-01 18:22:57 -0800804 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800805 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800806
Brian Silverman4f4e0612020-08-12 19:54:41 -0700807 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800808 void SkipAosLog() { skip_logger_ = true; }
809
Brian Silverman4f4e0612020-08-12 19:54:41 -0700810 // Returns the number of buffers for this channel. This corresponds with the
811 // range of Context::buffer_index values for this channel.
812 virtual int NumberBuffers(const Channel *channel) = 0;
813
Austin Schuh20ac95d2020-12-05 17:24:19 -0800814 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800815 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800816
Alex Perrycb7da4b2019-08-28 19:35:56 -0700817 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800818 // Sets the name of the event loop. This is the application name.
819 virtual void set_name(const std::string_view name) = 0;
820
Alex Perrycb7da4b2019-08-28 19:35:56 -0700821 void set_is_running(bool value) { is_running_.store(value); }
822
Austin Schuh39788ff2019-12-01 18:22:57 -0800823 // Validates that channel exists inside configuration_ and finds its index.
824 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700825
Brian Silverman5120afb2020-01-31 17:44:35 -0800826 // Returns the state for the watcher on the corresponding channel. This
827 // watcher must exist before calling this.
828 WatcherState *GetWatcherState(const Channel *channel);
829
Brian Silverman6d2b3592020-06-18 14:40:15 -0700830 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800831 template <typename T>
832 static RawSender *GetRawSender(aos::Sender<T> *sender) {
833 return sender->sender_.get();
834 }
835
Brian Silverman6d2b3592020-06-18 14:40:15 -0700836 // Returns a Fetcher's protected RawFetcher.
837 template <typename T>
838 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
839 return fetcher->fetcher_.get();
840 }
841
Austin Schuh6231cc32019-12-07 13:06:15 -0800842 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700843 Context context_;
844
Austin Schuh39788ff2019-12-01 18:22:57 -0800845 friend class RawSender;
846 friend class TimerHandler;
847 friend class RawFetcher;
848 friend class PhasedLoopHandler;
849 friend class WatcherState;
850
851 // Methods used to implement timing reports.
852 void NewSender(RawSender *sender);
853 void DeleteSender(RawSender *sender);
854 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
855 PhasedLoopHandler *NewPhasedLoop(
856 std::unique_ptr<PhasedLoopHandler> phased_loop);
857 void NewFetcher(RawFetcher *fetcher);
858 void DeleteFetcher(RawFetcher *fetcher);
859 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
860
Brian Silverman0fc69932020-01-24 21:54:02 -0800861 // Tracks that we have a (single) watcher on the given channel.
862 void TakeWatcher(const Channel *channel);
863 // Tracks that we have at least one sender on the given channel.
864 void TakeSender(const Channel *channel);
865
Austin Schuh39788ff2019-12-01 18:22:57 -0800866 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800867 std::vector<RawFetcher *> fetchers_;
868
Austin Schuh39788ff2019-12-01 18:22:57 -0800869 std::vector<std::unique_ptr<TimerHandler>> timers_;
870 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800871 std::vector<std::unique_ptr<WatcherState>> watchers_;
872
Brian Silvermance418d02021-11-03 11:25:52 -0700873 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800874 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700875
Austin Schuh39788ff2019-12-01 18:22:57 -0800876 void UpdateTimingReport();
877 void MaybeScheduleTimingReports();
878
879 std::unique_ptr<RawSender> timing_report_sender_;
880
Austin Schuh7d87b672019-12-01 20:23:49 -0800881 // Tracks which event sources (timers and watchers) have data, and which
882 // don't. Added events may not change their event_time().
883 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
884 // t2 to run, t2 should then be picked up without a context switch.
885 void AddEvent(EventLoopEvent *event);
886 void RemoveEvent(EventLoopEvent *event);
887 size_t EventCount() const { return events_.size(); }
888 EventLoopEvent *PopEvent();
889 EventLoopEvent *PeekEvent() { return events_.front(); }
890 void ReserveEvents();
891
892 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700893 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800894
Tyler Chatow67ddb032020-01-12 14:30:04 -0800895 // If true, don't send AOS_LOG to /aos
896 bool skip_logger_ = false;
897
Austin Schuha9012be2021-07-21 15:19:11 -0700898 // Sets context_ for a timed event which is supposed to happen at the provided
899 // time.
900 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
Austin Schuh0debde12022-08-17 16:25:17 -0700901 // Clears context_ so it only has invalid times and elements in it.
902 void ClearContext();
Austin Schuha9012be2021-07-21 15:19:11 -0700903
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800904 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800905 virtual pid_t GetTid() = 0;
906
907 FlatbufferDetachedBuffer<timing::Report> timing_report_;
908
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800909 ::std::atomic<bool> is_running_{false};
910
Alex Perrycb7da4b2019-08-28 19:35:56 -0700911 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800912
913 // If true, don't send out timing reports.
914 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800915
milind1f1dca32021-07-03 13:50:07 -0700916 SendFailureCounter timing_report_failure_counter_;
917
Brian Silverman0fc69932020-01-24 21:54:02 -0800918 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700919};
920
Brian Silvermane1fe2512022-08-14 23:18:50 -0700921// Interface for terminating execution of an EventLoop.
922//
923// Prefer this over binding a lambda to an Exit() method when passing ownership
924// in complicated ways because implementations should have assertions to catch
925// it outliving the object it's referring to, instead of having a
926// use-after-free.
927//
928// This is not exposed by EventLoop directly because different EventLoop
929// implementations provide this functionality at different scopes, or possibly
930// not at all.
931class ExitHandle {
932 public:
933 ExitHandle() = default;
934 virtual ~ExitHandle() = default;
935
936 // Exits some set of event loops. Details depend on the implementation.
937 //
938 // This means no more events will be processed, but any currently being
939 // processed will finish.
940 virtual void Exit() = 0;
941};
942
Alex Perrycb7da4b2019-08-28 19:35:56 -0700943} // namespace aos
944
Austin Schuhb8075812020-10-19 09:36:49 -0700945#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700946
947#endif // AOS_EVENTS_EVENT_LOOP_H