blob: ab5d8686f8ed3a7f94bf4de0dd9740162f80141c [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
45 // For a single-node configuration, these two are identical to *_event_time.
46 // In a multinode configuration, these are the times that the message was
47 // sent on the original node.
48 monotonic_clock::time_point monotonic_remote_time;
49 realtime_clock::time_point realtime_remote_time;
50
Austin Schuh6231cc32019-12-07 13:06:15 -080051 // The rest are only valid for Watchers and Fetchers.
Brian Silverman4f4e0612020-08-12 19:54:41 -070052
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() {
277 const bool result = fetcher_->FetchNext();
278 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() {
289 const bool result = fetcher_->Fetch();
290 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 {
Austin Schuh39788ff2019-12-01 18:22:57 -0800300 return fetcher_->context().data != nullptr
301 ? 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
307 const Channel *channel() const { return fetcher_->channel(); }
308
Alex Perrycb7da4b2019-08-28 19:35:56 -0700309 // Returns the context holding timestamps and other metadata about the
310 // message.
311 const Context &context() const { return fetcher_->context(); }
312
313 const T &operator*() const { return *get(); }
314 const T *operator->() const { return get(); }
315
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700316 // Returns true if this fetcher is valid and connected to a channel.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700317 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700318
Austin Schuhca75b6a2020-12-15 21:12:24 -0800319 // Copies the current flatbuffer into a FlatbufferVector.
320 FlatbufferVector<T> CopyFlatBuffer() const {
321 return context().template CopyFlatBuffer<T>();
322 }
323
Alex Perrycb7da4b2019-08-28 19:35:56 -0700324 private:
325 friend class EventLoop;
326 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
327 : fetcher_(::std::move(fetcher)) {}
328 ::std::unique_ptr<RawFetcher> fetcher_;
329};
330
331// Sends messages to a channel.
332template <typename T>
333class Sender {
334 public:
335 Sender() {}
336
337 // Represents a single message about to be sent to the queue.
338 // The lifecycle goes:
339 //
340 // Builder builder = sender.MakeBuilder();
341 // T::Builder t_builder = builder.MakeBuilder<T>();
342 // Populate(&t_builder);
343 // builder.Send(t_builder.Finish());
344 class Builder {
345 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800346 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800347 : fbb_(allocator->size(), allocator),
348 allocator_(allocator),
349 sender_(sender) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800350 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800351 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700352 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800353 Builder() {}
354 Builder(const Builder &) = delete;
355 Builder(Builder &&) = default;
356
357 Builder &operator=(const Builder &) = delete;
358 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700359
360 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
361
362 template <typename T2>
363 typename T2::Builder MakeBuilder() {
364 return typename T2::Builder(fbb_);
365 }
366
milind1f1dca32021-07-03 13:50:07 -0700367 RawSender::Error Send(flatbuffers::Offset<T> offset) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700368 fbb_.Finish(offset);
milind1f1dca32021-07-03 13:50:07 -0700369 const auto err = sender_->Send(fbb_.GetSize());
Brian Silverman9dd793b2020-01-31 23:52:21 -0800370 // Ensure fbb_ knows it shouldn't access the memory any more.
371 fbb_ = flatbuffers::FlatBufferBuilder();
milind1f1dca32021-07-03 13:50:07 -0700372 return err;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700373 }
374
milind1f1dca32021-07-03 13:50:07 -0700375 // Equivalent to RawSender::CheckOk
376 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
377
Alex Perrycb7da4b2019-08-28 19:35:56 -0700378 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800379 void CheckSent() {
380 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
381 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700382
Brian Silverman341b57e2020-06-23 16:23:18 -0700383 // Detaches a buffer, for later use calling Sender::Send directly.
384 //
385 // Note that the underlying memory remains with the Sender, so creating
386 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
387 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
388 fbb_.Finish(offset);
389 return fbb_.Release();
390 }
391
Alex Perrycb7da4b2019-08-28 19:35:56 -0700392 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700393 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800394 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395 RawSender *sender_;
396 };
397
398 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800399 //
400 // Only a single one of these may be "alive" for this object at any point in
401 // time. After calling Send on the result, it is no longer "alive". This means
402 // that you must manually reset a variable holding the return value (by
403 // assigning a default-constructed Builder to it) before calling this method
404 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700405 Builder MakeBuilder();
406
Austin Schuha28cbc32019-12-27 16:28:04 -0800407 // Sends a prebuilt flatbuffer.
milind1f1dca32021-07-03 13:50:07 -0700408 RawSender::Error Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800409
Brian Silverman341b57e2020-06-23 16:23:18 -0700410 // Sends a prebuilt flatbuffer which was detached from a Builder created via
411 // MakeBuilder() on this object.
milind1f1dca32021-07-03 13:50:07 -0700412 RawSender::Error SendDetached(FlatbufferDetachedBuffer<T> detached);
413
414 // Equivalent to RawSender::CheckOk
415 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
Brian Silverman341b57e2020-06-23 16:23:18 -0700416
Austin Schuh39788ff2019-12-01 18:22:57 -0800417 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800418 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700419
Austin Schuhe33c08d2022-02-03 18:15:21 -0800420 // TODO(austin): Deprecate the operator bool.
Austin Schuha0c41ba2020-09-10 22:59:14 -0700421 operator bool() const { return sender_ ? true : false; }
Austin Schuhe33c08d2022-02-03 18:15:21 -0800422 bool valid() const { return static_cast<bool>(sender_); }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800423
Austin Schuh7bc59052020-02-16 23:48:33 -0800424 // Returns the time_points that the last message was sent at.
425 aos::monotonic_clock::time_point monotonic_sent_time() const {
426 return sender_->monotonic_sent_time();
427 }
428 aos::realtime_clock::time_point realtime_sent_time() const {
429 return sender_->realtime_sent_time();
430 }
431 // Returns the queue index that this was sent with.
432 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
433
Brian Silverman4f4e0612020-08-12 19:54:41 -0700434 // Returns the buffer index which MakeBuilder() will expose access to. This is
435 // the buffer the caller can fill out.
436 int buffer_index() const { return sender_->buffer_index(); }
437
Alex Perrycb7da4b2019-08-28 19:35:56 -0700438 private:
439 friend class EventLoop;
440 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
441 std::unique_ptr<RawSender> sender_;
442};
443
milind1f1dca32021-07-03 13:50:07 -0700444// Class for keeping a count of send failures on a certain channel
445class SendFailureCounter {
446 public:
447 inline void Count(const RawSender::Error err) {
448 failures_ += static_cast<size_t>(err != RawSender::Error::kOk);
449 just_failed_ = (err != RawSender::Error::kOk);
450 }
451
452 inline size_t failures() const { return failures_; }
453 inline bool just_failed() const { return just_failed_; }
454
455 private:
456 size_t failures_ = 0;
457 bool just_failed_ = false;
458};
459
Brian Silverman4f4e0612020-08-12 19:54:41 -0700460// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700461class TimerHandler {
462 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800463 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700464
465 // Timer should sleep until base, base + offset, base + offset * 2, ...
466 // If repeat_offset isn't set, the timer only expires once.
James Kuszmaul8866e642022-06-10 16:00:36 -0700467 // base must be greater than or equal to zero.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700468 virtual void Setup(monotonic_clock::time_point base,
469 monotonic_clock::duration repeat_offset =
470 ::aos::monotonic_clock::zero()) = 0;
471
472 // Stop future calls to callback().
473 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800474
475 // Sets and gets the name of the timer. Set this if you want a descriptive
476 // name in the timing report.
477 void set_name(std::string_view name) { name_ = std::string(name); }
478 const std::string_view name() const { return name_; }
479
Austin Schuh39788ff2019-12-01 18:22:57 -0800480 protected:
481 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
482
Austin Schuh9b1d6282022-06-10 17:03:21 -0700483 template <typename T>
484 monotonic_clock::time_point Call(T get_time,
485 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800486
Austin Schuh1540c2f2019-11-29 21:59:29 -0800487 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800488 friend class EventLoop;
489
490 EventLoop *event_loop_;
491 // The function to call when Call is called.
492 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800493 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800494
495 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500496 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700497};
498
499// Interface for phased loops. They are built on timers.
500class PhasedLoopHandler {
501 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800502 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700503
504 // Sets the interval and offset. Any changes to interval and offset only take
505 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800506 void set_interval_and_offset(const monotonic_clock::duration interval,
507 const monotonic_clock::duration offset) {
508 phased_loop_.set_interval_and_offset(interval, offset);
509 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800510
511 // Sets and gets the name of the timer. Set this if you want a descriptive
512 // name in the timing report.
513 void set_name(std::string_view name) { name_ = std::string(name); }
514 const std::string_view name() const { return name_; }
515
Austin Schuh39788ff2019-12-01 18:22:57 -0800516 protected:
517 void Call(std::function<monotonic_clock::time_point()> get_time,
518 std::function<void(monotonic_clock::time_point)> schedule);
519
520 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
521 const monotonic_clock::duration interval,
522 const monotonic_clock::duration offset);
523
Austin Schuh1540c2f2019-11-29 21:59:29 -0800524 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800525 friend class EventLoop;
526
527 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
528 monotonic_clock::time_point monotonic_now) {
529 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
530 schedule(phased_loop_.sleep_time());
531 }
532
533 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
534
535 EventLoop *event_loop_;
536 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800537 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800538 time::PhasedLoop phased_loop_;
539
540 int cycles_elapsed_ = 0;
541
542 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500543 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544};
545
Austin Schuh3054f5f2021-07-21 15:38:01 -0700546// Note, it is supported to create only:
547// multiple fetchers, and (one sender or one watcher) per <name, type>
548// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700549class EventLoop {
550 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700551 // Holds configuration by reference for the lifetime of this object. It may
552 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800553 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700554
Austin Schuh39788ff2019-12-01 18:22:57 -0800555 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700556
557 // Current time.
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800558 virtual monotonic_clock::time_point monotonic_now() const = 0;
559 virtual realtime_clock::time_point realtime_now() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700561 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800562 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800563 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800564 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800565 true);
566 }
milind1f1dca32021-07-03 13:50:07 -0700567 // Returns true if the channel exists in the configuration.
Austin Schuha0654152021-02-21 21:38:24 -0800568 template <typename T>
569 bool HasChannel(const std::string_view channel_name) {
570 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700571 }
572
Brian Silverman631b6262021-11-10 12:25:08 -0800573 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
574 // not readable on this node or does not exist.
575 template <typename T>
576 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
577 const Channel *const channel = GetChannel<T>(channel_name);
578 if (channel == nullptr) {
579 return Fetcher<T>();
580 }
581
582 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
583 return Fetcher<T>();
584 }
585
586 return Fetcher<T>(MakeRawFetcher(channel));
587 }
588
Alex Perrycb7da4b2019-08-28 19:35:56 -0700589 // Makes a class that will always fetch the most recent value
590 // sent to the provided channel.
591 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800592 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800593 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700594 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
595 << T::GetFullyQualifiedName() << "\" } not found in config.";
596
Brian Silverman631b6262021-11-10 12:25:08 -0800597 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
598 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800599 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
600 << "\", \"type\": \"" << T::GetFullyQualifiedName()
601 << "\" } is not able to be fetched on this node. Check your "
602 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800603 }
604
Brian Silverman631b6262021-11-10 12:25:08 -0800605 return result;
606 }
607
608 // Like MakeSender, but returns an invalid sender if the given channel is
James Kuszmaulb8887592021-12-09 14:54:50 -0800609 // not sendable on this node or does not exist.
Brian Silverman631b6262021-11-10 12:25:08 -0800610 template <typename T>
611 Sender<T> TryMakeSender(const std::string_view channel_name) {
612 const Channel *channel = GetChannel<T>(channel_name);
613 if (channel == nullptr) {
614 return Sender<T>();
615 }
616
617 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
618 return Sender<T>();
619 }
620
621 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700622 }
623
624 // Makes class that allows constructing and sending messages to
625 // the provided channel.
626 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800627 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800628 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700629 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800630 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700631 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800632 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700633 ? absl::StrCat(" on node ", node()->name()->string_view())
634 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700635
Brian Silverman631b6262021-11-10 12:25:08 -0800636 Sender<T> result = TryMakeSender<T>(channel_name);
637 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800638 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
639 << "\", \"type\": \"" << T::GetFullyQualifiedName()
640 << "\" } is not able to be sent on this node. Check your "
641 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800642 }
643
Brian Silverman631b6262021-11-10 12:25:08 -0800644 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700645 }
646
647 // This will watch messages sent to the provided channel.
648 //
Brian Silverman454bc112020-03-05 14:21:25 -0800649 // w must have a non-polymorphic operator() (aka it can only be called with a
650 // single set of arguments; no overloading or templates). It must be callable
651 // with this signature:
652 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700653 //
Brian Silverman454bc112020-03-05 14:21:25 -0800654 // Lambdas are a common form for w. A std::function will work too.
655 //
656 // Note that bind expressions have polymorphic call operators, so they are not
657 // allowed.
658 //
659 // We template Watch as a whole instead of using std::function<void(const T
660 // &)> to allow deducing MessageType from lambdas and other things which are
661 // implicitly convertible to std::function, but not actually std::function
662 // instantiations. Template deduction guides might allow solving this
663 // differently in newer versions of C++, but those have their own corner
664 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700665 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800666 void MakeWatcher(const std::string_view channel_name, Watch &&w);
667
668 // Like MakeWatcher, but doesn't have access to the message data. This may be
669 // implemented to use less resources than an equivalent MakeWatcher.
670 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800671 // The function will still have access to context(), although that will have
672 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800673 template <typename MessageType>
674 void MakeNoArgWatcher(const std::string_view channel_name,
675 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700676
677 // The passed in function will be called when the event loop starts.
678 // Use this to run code once the thread goes into "real-time-mode",
679 virtual void OnRun(::std::function<void()> on_run) = 0;
680
Austin Schuh217a9782019-12-21 23:02:50 -0800681 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800682 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700683
Austin Schuh217a9782019-12-21 23:02:50 -0800684 // Returns the node that this event loop is running on. Returns nullptr if we
685 // are running in single-node mode.
686 virtual const Node *node() const = 0;
687
Alex Perrycb7da4b2019-08-28 19:35:56 -0700688 // Creates a timer that executes callback when the timer expires
689 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700690 // TODO(milind): callback should take the number of cycles elapsed as a
691 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700692 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
693
694 // Creates a timer that executes callback periodically at the specified
695 // interval and offset. Returns a PhasedLoopHandler for interacting with the
696 // timer.
697 virtual PhasedLoopHandler *AddPhasedLoop(
698 ::std::function<void(int)> callback,
699 const monotonic_clock::duration interval,
700 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
701
Austin Schuh217a9782019-12-21 23:02:50 -0800702 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700703
Austin Schuh3054f5f2021-07-21 15:38:01 -0700704 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700705 bool is_running() const { return is_running_.load(); }
706
707 // Sets the scheduler priority to run the event loop at. This may not be
708 // called after we go into "real-time-mode".
709 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700710 // Defaults to 0 if this loop will not run realtime.
711 virtual int runtime_realtime_priority() const = 0;
712
713 static cpu_set_t DefaultAffinity() {
714 cpu_set_t result;
715 for (int i = 0; i < CPU_SETSIZE; ++i) {
716 CPU_SET(i, &result);
717 }
718 return result;
719 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700720
Brian Silverman6a54ff32020-04-28 16:41:39 -0700721 // Sets the scheduler affinity to run the event loop with. This may only be
722 // called before Run().
723 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700724 // Defaults to DefaultAffinity() if this loop will not run pinned.
725 virtual const cpu_set_t &runtime_affinity() const = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700726
Austin Schuh217a9782019-12-21 23:02:50 -0800727 // Fetches new messages from the provided channel (path, type).
728 //
729 // Note: this channel must be a member of the exact configuration object this
730 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700731 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
732 const Channel *channel) = 0;
733
Austin Schuh217a9782019-12-21 23:02:50 -0800734 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700735 virtual void MakeRawWatcher(
736 const Channel *channel,
737 std::function<void(const Context &context, const void *message)>
738 watcher) = 0;
739
Brian Silverman454bc112020-03-05 14:21:25 -0800740 // Watches channel (name, type) for new messages, without needing to extract
741 // the message contents. Default implementation simply re-uses MakeRawWatcher.
742 virtual void MakeRawNoArgWatcher(
743 const Channel *channel,
744 std::function<void(const Context &context)> watcher) {
745 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800746 Context new_context = context;
747 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700748 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800749 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800750 });
751 }
752
Austin Schuh217a9782019-12-21 23:02:50 -0800753 // Creates a raw sender for the provided channel. This is used for reflection
754 // based sending.
755 // Note: this ignores any node constraints. Ignore at your own peril.
756 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
757
Austin Schuh6231cc32019-12-07 13:06:15 -0800758 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700759 const Context &context() const { return context_; }
760
761 // Returns the configuration that this event loop was built with.
762 const Configuration *configuration() const { return configuration_; }
763
Austin Schuh39788ff2019-12-01 18:22:57 -0800764 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800765 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800766
Brian Silverman4f4e0612020-08-12 19:54:41 -0700767 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800768 void SkipAosLog() { skip_logger_ = true; }
769
Brian Silverman4f4e0612020-08-12 19:54:41 -0700770 // Returns the number of buffers for this channel. This corresponds with the
771 // range of Context::buffer_index values for this channel.
772 virtual int NumberBuffers(const Channel *channel) = 0;
773
Austin Schuh20ac95d2020-12-05 17:24:19 -0800774 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800775 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800776
Alex Perrycb7da4b2019-08-28 19:35:56 -0700777 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800778 // Sets the name of the event loop. This is the application name.
779 virtual void set_name(const std::string_view name) = 0;
780
Alex Perrycb7da4b2019-08-28 19:35:56 -0700781 void set_is_running(bool value) { is_running_.store(value); }
782
Austin Schuh39788ff2019-12-01 18:22:57 -0800783 // Validates that channel exists inside configuration_ and finds its index.
784 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700785
Brian Silverman5120afb2020-01-31 17:44:35 -0800786 // Returns the state for the watcher on the corresponding channel. This
787 // watcher must exist before calling this.
788 WatcherState *GetWatcherState(const Channel *channel);
789
Brian Silverman6d2b3592020-06-18 14:40:15 -0700790 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800791 template <typename T>
792 static RawSender *GetRawSender(aos::Sender<T> *sender) {
793 return sender->sender_.get();
794 }
795
Brian Silverman6d2b3592020-06-18 14:40:15 -0700796 // Returns a Fetcher's protected RawFetcher.
797 template <typename T>
798 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
799 return fetcher->fetcher_.get();
800 }
801
Austin Schuh6231cc32019-12-07 13:06:15 -0800802 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700803 Context context_;
804
Austin Schuh39788ff2019-12-01 18:22:57 -0800805 friend class RawSender;
806 friend class TimerHandler;
807 friend class RawFetcher;
808 friend class PhasedLoopHandler;
809 friend class WatcherState;
810
811 // Methods used to implement timing reports.
812 void NewSender(RawSender *sender);
813 void DeleteSender(RawSender *sender);
814 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
815 PhasedLoopHandler *NewPhasedLoop(
816 std::unique_ptr<PhasedLoopHandler> phased_loop);
817 void NewFetcher(RawFetcher *fetcher);
818 void DeleteFetcher(RawFetcher *fetcher);
819 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
820
Brian Silverman0fc69932020-01-24 21:54:02 -0800821 // Tracks that we have a (single) watcher on the given channel.
822 void TakeWatcher(const Channel *channel);
823 // Tracks that we have at least one sender on the given channel.
824 void TakeSender(const Channel *channel);
825
Austin Schuh39788ff2019-12-01 18:22:57 -0800826 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800827 std::vector<RawFetcher *> fetchers_;
828
Austin Schuh39788ff2019-12-01 18:22:57 -0800829 std::vector<std::unique_ptr<TimerHandler>> timers_;
830 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800831 std::vector<std::unique_ptr<WatcherState>> watchers_;
832
Brian Silvermance418d02021-11-03 11:25:52 -0700833 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800834 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700835
Austin Schuh39788ff2019-12-01 18:22:57 -0800836 void UpdateTimingReport();
837 void MaybeScheduleTimingReports();
838
839 std::unique_ptr<RawSender> timing_report_sender_;
840
Austin Schuh7d87b672019-12-01 20:23:49 -0800841 // Tracks which event sources (timers and watchers) have data, and which
842 // don't. Added events may not change their event_time().
843 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
844 // t2 to run, t2 should then be picked up without a context switch.
845 void AddEvent(EventLoopEvent *event);
846 void RemoveEvent(EventLoopEvent *event);
847 size_t EventCount() const { return events_.size(); }
848 EventLoopEvent *PopEvent();
849 EventLoopEvent *PeekEvent() { return events_.front(); }
850 void ReserveEvents();
851
852 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700853 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800854
Tyler Chatow67ddb032020-01-12 14:30:04 -0800855 // If true, don't send AOS_LOG to /aos
856 bool skip_logger_ = false;
857
Austin Schuha9012be2021-07-21 15:19:11 -0700858 // Sets context_ for a timed event which is supposed to happen at the provided
859 // time.
860 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
Austin Schuh0debde12022-08-17 16:25:17 -0700861 // Clears context_ so it only has invalid times and elements in it.
862 void ClearContext();
Austin Schuha9012be2021-07-21 15:19:11 -0700863
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800864 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800865 virtual pid_t GetTid() = 0;
866
867 FlatbufferDetachedBuffer<timing::Report> timing_report_;
868
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800869 ::std::atomic<bool> is_running_{false};
870
Alex Perrycb7da4b2019-08-28 19:35:56 -0700871 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800872
873 // If true, don't send out timing reports.
874 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800875
milind1f1dca32021-07-03 13:50:07 -0700876 SendFailureCounter timing_report_failure_counter_;
877
Brian Silverman0fc69932020-01-24 21:54:02 -0800878 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700879};
880
Brian Silvermane1fe2512022-08-14 23:18:50 -0700881// Interface for terminating execution of an EventLoop.
882//
883// Prefer this over binding a lambda to an Exit() method when passing ownership
884// in complicated ways because implementations should have assertions to catch
885// it outliving the object it's referring to, instead of having a
886// use-after-free.
887//
888// This is not exposed by EventLoop directly because different EventLoop
889// implementations provide this functionality at different scopes, or possibly
890// not at all.
891class ExitHandle {
892 public:
893 ExitHandle() = default;
894 virtual ~ExitHandle() = default;
895
896 // Exits some set of event loops. Details depend on the implementation.
897 //
898 // This means no more events will be processed, but any currently being
899 // processed will finish.
900 virtual void Exit() = 0;
901};
902
Alex Perrycb7da4b2019-08-28 19:35:56 -0700903} // namespace aos
904
Austin Schuhb8075812020-10-19 09:36:49 -0700905#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700906
907#endif // AOS_EVENTS_EVENT_LOOP_H