blob: e6e54992d8809883c06b599990f4fe6f886c4938 [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"
Philipp Schrader790cb542023-07-05 21:06:52 -070012#include "flatbuffers/flatbuffers.h"
13#include "glog/logging.h"
14
Alex Perrycb7da4b2019-08-28 19:35:56 -070015#include "aos/configuration.h"
16#include "aos/configuration_generated.h"
Austin Schuh1af273d2020-03-07 20:11:34 -080017#include "aos/events/channel_preallocated_allocator.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080018#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080019#include "aos/events/event_loop_generated.h"
20#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "aos/flatbuffers.h"
Brian Silverman79ec7fc2020-06-08 20:11:22 -050022#include "aos/ftrace.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080023#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070024#include "aos/json_to_flatbuffer.h"
25#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080026#include "aos/util/phased_loop.h"
Austin Schuh4385b142021-03-14 21:31:13 -070027#include "aos/uuid.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070028
Austin Schuh39788ff2019-12-01 18:22:57 -080029DECLARE_bool(timing_reports);
30DECLARE_int32(timing_report_ms);
31
Alex Perrycb7da4b2019-08-28 19:35:56 -070032namespace aos {
33
Austin Schuh39788ff2019-12-01 18:22:57 -080034class EventLoop;
35class WatcherState;
36
Austin Schuh6231cc32019-12-07 13:06:15 -080037// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
38// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070039struct Context {
Austin Schuhad154822019-12-27 15:45:13 -080040 // Time that the message was sent on this node, or the timer was triggered.
41 monotonic_clock::time_point monotonic_event_time;
42 // Realtime the message was sent on this node. This is set to min_time for
43 // Timers and PhasedLoops.
44 realtime_clock::time_point realtime_event_time;
45
James Kuszmaulad523042022-10-05 16:47:33 -070046 // The rest are only valid for Watchers and Fetchers.
47
Austin Schuhad154822019-12-27 15:45:13 -080048 // For a single-node configuration, these two are identical to *_event_time.
49 // In a multinode configuration, these are the times that the message was
50 // sent on the original node.
51 monotonic_clock::time_point monotonic_remote_time;
52 realtime_clock::time_point realtime_remote_time;
53
Alex Perrycb7da4b2019-08-28 19:35:56 -070054 // Index in the queue.
55 uint32_t queue_index;
Austin Schuhad154822019-12-27 15:45:13 -080056 // Index into the remote queue. Useful to determine if data was lost. In a
57 // single-node configuration, this will match queue_index.
58 uint32_t remote_queue_index;
59
Alex Perrycb7da4b2019-08-28 19:35:56 -070060 // Size of the data sent.
61 size_t size;
62 // Pointer to the data.
Brian Silvermaneaa41d62020-07-08 19:47:35 -070063 const void *data;
Austin Schuh678078e2020-08-01 14:30:36 -070064
Brian Silverman4f4e0612020-08-12 19:54:41 -070065 // Index of the message buffer. This will be in [0, NumberBuffers) on
66 // read_method=PIN channels, and -1 for other channels.
67 //
68 // This only tells you about the underlying storage for this message, not
69 // anything about its position in the queue. This is only useful for advanced
70 // zero-copy use cases, on read_method=PIN channels.
71 //
72 // This will uniquely identify a message on this channel at a point in time.
73 // For senders, this point in time is while the sender has the message. With
74 // read_method==PIN, this point in time includes while the caller has access
75 // to this context. For other read_methods, this point in time may be before
76 // the caller has access to this context, which makes this pretty useless.
77 int buffer_index;
78
Austin Schuh8902fa52021-03-14 22:39:24 -070079 // UUID of the remote node which sent this message, or this node in the case
80 // of events which are local to this node.
Austin Schuha9012be2021-07-21 15:19:11 -070081 UUID source_boot_uuid = UUID::Zero();
Austin Schuh8902fa52021-03-14 22:39:24 -070082
Austin Schuhca75b6a2020-12-15 21:12:24 -080083 // Efficiently copies the flatbuffer into a FlatbufferVector, allocating
Austin Schuh678078e2020-08-01 14:30:36 -070084 // memory in the process. It is vital that T matches the type of the
85 // underlying flatbuffer.
86 template <typename T>
87 FlatbufferVector<T> CopyFlatBuffer() const {
Brian Silverman354697a2020-09-22 21:06:32 -070088 ResizeableBuffer buffer;
89 buffer.resize(size);
90 memcpy(buffer.data(), data, size);
91 return FlatbufferVector<T>(std::move(buffer));
Austin Schuh678078e2020-08-01 14:30:36 -070092 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070093};
94
95// Raw version of fetcher. Contains a local variable that the fetcher will
96// update. This is used for reflection and as an interface to implement typed
97// fetchers.
98class RawFetcher {
99 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800100 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700101 RawFetcher(const RawFetcher &) = delete;
102 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700104
Austin Schuh39788ff2019-12-01 18:22:57 -0800105 // Fetches the next message in the queue without blocking. Returns true if
106 // there was a new message and we got it.
107 bool FetchNext();
108
109 // Fetches the latest message without blocking.
110 bool Fetch();
111
112 // Returns the channel this fetcher uses.
113 const Channel *channel() const { return channel_; }
114 // Returns the context for the current message.
115 const Context &context() const { return context_; }
116
117 protected:
118 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700119 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800120
Alex Perrycb7da4b2019-08-28 19:35:56 -0700121 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800122
123 private:
124 friend class EventLoop;
125 // Implementation
126 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
127 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
128
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500129 EventLoop *const event_loop_;
130 const Channel *const channel_;
131 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800132
133 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500134 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700135};
136
Austin Schuhe0ab4de2023-05-03 08:05:08 -0700137using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
138
139// Holds storage for a span object and the data referenced by that span for
140// compatibility with SharedSpan users. If constructed with MakeSharedSpan, span
141// points to only the aligned segment of the entire data.
142struct AlignedOwningSpan {
143 AlignedOwningSpan(absl::Span<const uint8_t> new_span) : span(new_span) {}
144
145 AlignedOwningSpan(const AlignedOwningSpan &) = delete;
146 AlignedOwningSpan &operator=(const AlignedOwningSpan &) = delete;
147 absl::Span<const uint8_t> span;
148 char *data() { return reinterpret_cast<char *>(this + 1); }
149};
150
151// Constructs a span which owns its data through a shared_ptr. The owning span
152// points to a const view of the data; also returns a temporary mutable span
153// which is only valid while the const shared span is kept alive.
154std::pair<SharedSpan, absl::Span<uint8_t>> MakeSharedSpan(size_t size);
155
Alex Perrycb7da4b2019-08-28 19:35:56 -0700156// Raw version of sender. Sends a block of data. This is used for reflection
157// and as a building block to implement typed senders.
158class RawSender {
159 public:
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700160 using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
161
Brian Silverman183859c2022-05-14 02:03:06 -0700162 // This looks a little ugly with no space, but please leave it so clang-format
163 // doesn't keep changing it. Bug is filed at
164 // <https://github.com/llvm/llvm-project/issues/55457>.
165 enum class [[nodiscard]] Error{
milind1f1dca32021-07-03 13:50:07 -0700166 // Represents success and no error
167 kOk,
168
169 // Error for messages on channels being sent faster than their
170 // frequency and channel storage duration allow
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700171 kMessagesSentTooFast,
172 // Access to Redzone was attempted in Sender Queue
Brian Silverman183859c2022-05-14 02:03:06 -0700173 kInvalidRedzone,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700174 };
milind1f1dca32021-07-03 13:50:07 -0700175
Austin Schuh39788ff2019-12-01 18:22:57 -0800176 RawSender(EventLoop *event_loop, const Channel *channel);
177 RawSender(const RawSender &) = delete;
178 RawSender &operator=(const RawSender &) = delete;
179
180 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700181
Brian Silverman9809c5f2022-07-23 16:12:23 -0700182 // Returns the buffer to write new messages into. This is always valid, and
183 // may change after calling any of the Send functions.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700184 virtual void *data() = 0;
185 virtual size_t size() = 0;
milind1f1dca32021-07-03 13:50:07 -0700186
187 // Sends a message without copying it. The users starts by copying up to
188 // size() bytes into the data backed by data(). They then call Send to send.
189 // Returns Error::kOk on a successful send, or
190 // Error::kMessagesSentTooFast if messages were sent too fast. If provided,
191 // monotonic_remote_time, realtime_remote_time, and remote_queue_index are
192 // attached to the message and are available in the context on the read side.
193 // If they are not populated, the read side will get the sent times instead.
194 Error Send(size_t size);
195 Error Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
196 realtime_clock::time_point realtime_remote_time,
197 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700198
199 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800200 // The remote arguments have the same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700201 // Returns Error::kMessagesSentTooFast if messages were sent too fast
202 Error Send(const void *data, size_t size);
203 Error Send(const void *data, size_t size,
204 monotonic_clock::time_point monotonic_remote_time,
205 realtime_clock::time_point realtime_remote_time,
206 uint32_t remote_queue_index, const UUID &source_boot_uuid);
207
208 // CHECKs that no sending Error occurred and logs the channel_ data if
209 // one did
210 void CheckOk(const Error err);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700211
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700212 // Sends a single block of data by refcounting it to avoid copies. The data
213 // must not change after being passed into Send. The remote arguments have the
214 // same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700215 Error Send(const SharedSpan data);
216 Error Send(const SharedSpan data,
217 monotonic_clock::time_point monotonic_remote_time,
218 realtime_clock::time_point realtime_remote_time,
219 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700220
Austin Schuh54cf95f2019-11-29 13:14:18 -0800221 const Channel *channel() const { return channel_; }
222
Austin Schuhad154822019-12-27 15:45:13 -0800223 // Returns the time_points that the last message was sent at.
224 aos::monotonic_clock::time_point monotonic_sent_time() const {
225 return monotonic_sent_time_;
226 }
227 aos::realtime_clock::time_point realtime_sent_time() const {
228 return realtime_sent_time_;
229 }
230 // Returns the queue index that this was sent with.
231 uint32_t sent_queue_index() const { return sent_queue_index_; }
232
Brian Silvermana1652f32020-01-29 20:41:44 -0800233 // Returns the associated flatbuffers-style allocator. This must be
234 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800235 ChannelPreallocatedAllocator *fbb_allocator() {
236 fbb_allocator_ = ChannelPreallocatedAllocator(
237 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800238 return &fbb_allocator_;
239 }
240
Brian Silverman4f4e0612020-08-12 19:54:41 -0700241 // Index of the buffer which is currently exposed by data() and the various
242 // other accessors. This is the message the caller should be filling out.
243 virtual int buffer_index() = 0;
244
Alex Perrycb7da4b2019-08-28 19:35:56 -0700245 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800246 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700247 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800248
Austin Schuhb5c6f972021-03-14 21:53:07 -0700249 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
250 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800251 uint32_t sent_queue_index_ = 0xffffffff;
252
Austin Schuh39788ff2019-12-01 18:22:57 -0800253 private:
254 friend class EventLoop;
255
milind1f1dca32021-07-03 13:50:07 -0700256 virtual Error DoSend(const void *data, size_t size,
257 monotonic_clock::time_point monotonic_remote_time,
258 realtime_clock::time_point realtime_remote_time,
259 uint32_t remote_queue_index,
260 const UUID &source_boot_uuid) = 0;
261 virtual Error DoSend(size_t size,
262 monotonic_clock::time_point monotonic_remote_time,
263 realtime_clock::time_point realtime_remote_time,
264 uint32_t remote_queue_index,
265 const UUID &source_boot_uuid) = 0;
266 virtual Error DoSend(const SharedSpan data,
267 monotonic_clock::time_point monotonic_remote_time,
268 realtime_clock::time_point realtime_remote_time,
269 uint32_t remote_queue_index,
270 const UUID &source_boot_uuid);
Austin Schuh39788ff2019-12-01 18:22:57 -0800271
James Kuszmaul93abac12022-04-14 15:05:10 -0700272 void RecordSendResult(const Error error, size_t message_size);
273
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500274 EventLoop *const event_loop_;
275 const Channel *const channel_;
276 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277
Austin Schuh39788ff2019-12-01 18:22:57 -0800278 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500279 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800280
Austin Schuh1af273d2020-03-07 20:11:34 -0800281 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800282};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700283
milind1f1dca32021-07-03 13:50:07 -0700284// Needed for compatibility with glog
285std::ostream &operator<<(std::ostream &os, const RawSender::Error err);
286
Alex Perrycb7da4b2019-08-28 19:35:56 -0700287// Fetches the newest message from a channel.
288// This provides a polling based interface for channels.
289template <typename T>
290class Fetcher {
291 public:
292 Fetcher() {}
293
294 // Fetches the next message. Returns true if it fetched a new message. This
295 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800296 bool FetchNext() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800297 const bool result = CHECK_NOTNULL(fetcher_)->FetchNext();
Brian Silvermana1652f32020-01-29 20:41:44 -0800298 if (result) {
299 CheckChannelDataAlignment(fetcher_->context().data,
300 fetcher_->context().size);
301 }
302 return result;
303 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700304
305 // Fetches the most recent message. Returns true if it fetched a new message.
306 // This will return the latest message regardless of if it was sent before or
307 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800308 bool Fetch() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800309 const bool result = CHECK_NOTNULL(fetcher_)->Fetch();
Brian Silvermana1652f32020-01-29 20:41:44 -0800310 if (result) {
311 CheckChannelDataAlignment(fetcher_->context().data,
312 fetcher_->context().size);
313 }
314 return result;
315 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700316
317 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
318 // available message.
319 const T *get() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800320 return CHECK_NOTNULL(fetcher_)->context().data != nullptr
Austin Schuh39788ff2019-12-01 18:22:57 -0800321 ? flatbuffers::GetRoot<T>(
322 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700323 : nullptr;
324 }
325
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700326 // Returns the channel this fetcher uses
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800327 const Channel *channel() const { return CHECK_NOTNULL(fetcher_)->channel(); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700328
Alex Perrycb7da4b2019-08-28 19:35:56 -0700329 // Returns the context holding timestamps and other metadata about the
330 // message.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800331 const Context &context() const { return CHECK_NOTNULL(fetcher_)->context(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700332
333 const T &operator*() const { return *get(); }
334 const T *operator->() const { return get(); }
335
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800336 // Returns true if this fetcher is valid and connected to a channel. If you,
337 // e.g., are using TryMakeFetcher, then you must check valid() before
338 // attempting to use the Fetcher.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700339 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700340
Austin Schuhca75b6a2020-12-15 21:12:24 -0800341 // Copies the current flatbuffer into a FlatbufferVector.
342 FlatbufferVector<T> CopyFlatBuffer() const {
343 return context().template CopyFlatBuffer<T>();
344 }
345
Alex Perrycb7da4b2019-08-28 19:35:56 -0700346 private:
347 friend class EventLoop;
348 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
349 : fetcher_(::std::move(fetcher)) {}
350 ::std::unique_ptr<RawFetcher> fetcher_;
351};
352
353// Sends messages to a channel.
354template <typename T>
355class Sender {
356 public:
357 Sender() {}
358
359 // Represents a single message about to be sent to the queue.
360 // The lifecycle goes:
361 //
362 // Builder builder = sender.MakeBuilder();
363 // T::Builder t_builder = builder.MakeBuilder<T>();
364 // Populate(&t_builder);
365 // builder.Send(t_builder.Finish());
366 class Builder {
367 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800368 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800369 : fbb_(allocator->size(), allocator),
370 allocator_(allocator),
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800371 sender_(CHECK_NOTNULL(sender)) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800372 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800373 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700374 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800375 Builder() {}
376 Builder(const Builder &) = delete;
377 Builder(Builder &&) = default;
378
379 Builder &operator=(const Builder &) = delete;
380 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700381
382 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
383
384 template <typename T2>
385 typename T2::Builder MakeBuilder() {
386 return typename T2::Builder(fbb_);
387 }
388
milind1f1dca32021-07-03 13:50:07 -0700389 RawSender::Error Send(flatbuffers::Offset<T> offset) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700390 fbb_.Finish(offset);
milind1f1dca32021-07-03 13:50:07 -0700391 const auto err = sender_->Send(fbb_.GetSize());
Brian Silverman9dd793b2020-01-31 23:52:21 -0800392 // Ensure fbb_ knows it shouldn't access the memory any more.
393 fbb_ = flatbuffers::FlatBufferBuilder();
milind1f1dca32021-07-03 13:50:07 -0700394 return err;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395 }
396
milind1f1dca32021-07-03 13:50:07 -0700397 // Equivalent to RawSender::CheckOk
398 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
399
Alex Perrycb7da4b2019-08-28 19:35:56 -0700400 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800401 void CheckSent() {
402 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
403 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700404
Brian Silverman341b57e2020-06-23 16:23:18 -0700405 // Detaches a buffer, for later use calling Sender::Send directly.
406 //
407 // Note that the underlying memory remains with the Sender, so creating
408 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
409 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
410 fbb_.Finish(offset);
411 return fbb_.Release();
412 }
413
Alex Perrycb7da4b2019-08-28 19:35:56 -0700414 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700415 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800416 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417 RawSender *sender_;
418 };
419
420 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800421 //
422 // Only a single one of these may be "alive" for this object at any point in
423 // time. After calling Send on the result, it is no longer "alive". This means
424 // that you must manually reset a variable holding the return value (by
425 // assigning a default-constructed Builder to it) before calling this method
426 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700427 Builder MakeBuilder();
428
Austin Schuha28cbc32019-12-27 16:28:04 -0800429 // Sends a prebuilt flatbuffer.
James Kuszmaulad523042022-10-05 16:47:33 -0700430 // This will copy the data out of the provided flatbuffer, and so does not
431 // have to correspond to an existing Builder.
milind1f1dca32021-07-03 13:50:07 -0700432 RawSender::Error Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800433
Brian Silverman341b57e2020-06-23 16:23:18 -0700434 // Sends a prebuilt flatbuffer which was detached from a Builder created via
435 // MakeBuilder() on this object.
milind1f1dca32021-07-03 13:50:07 -0700436 RawSender::Error SendDetached(FlatbufferDetachedBuffer<T> detached);
437
438 // Equivalent to RawSender::CheckOk
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800439 void CheckOk(const RawSender::Error err) {
440 CHECK_NOTNULL(sender_)->CheckOk(err);
441 };
Brian Silverman341b57e2020-06-23 16:23:18 -0700442
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800443 // Returns the name of the underlying queue, if valid. You must check valid()
444 // first.
445 const Channel *channel() const { return CHECK_NOTNULL(sender_)->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446
James Kuszmaulad523042022-10-05 16:47:33 -0700447 // Returns true if the Sender is a valid Sender. If you, e.g., are using
448 // TryMakeSender, then you must check valid() before attempting to use the
449 // Sender.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800450 // TODO(austin): Deprecate the operator bool.
Austin Schuha0c41ba2020-09-10 22:59:14 -0700451 operator bool() const { return sender_ ? true : false; }
Austin Schuhe33c08d2022-02-03 18:15:21 -0800452 bool valid() const { return static_cast<bool>(sender_); }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800453
Austin Schuh7bc59052020-02-16 23:48:33 -0800454 // Returns the time_points that the last message was sent at.
455 aos::monotonic_clock::time_point monotonic_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800456 return CHECK_NOTNULL(sender_)->monotonic_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800457 }
458 aos::realtime_clock::time_point realtime_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800459 return CHECK_NOTNULL(sender_)->realtime_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800460 }
461 // Returns the queue index that this was sent with.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800462 uint32_t sent_queue_index() const {
463 return CHECK_NOTNULL(sender_)->sent_queue_index();
464 }
Austin Schuh7bc59052020-02-16 23:48:33 -0800465
Brian Silverman4f4e0612020-08-12 19:54:41 -0700466 // Returns the buffer index which MakeBuilder() will expose access to. This is
467 // the buffer the caller can fill out.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800468 int buffer_index() const { return CHECK_NOTNULL(sender_)->buffer_index(); }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700469
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470 private:
471 friend class EventLoop;
472 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
473 std::unique_ptr<RawSender> sender_;
474};
475
milind1f1dca32021-07-03 13:50:07 -0700476// Class for keeping a count of send failures on a certain channel
477class SendFailureCounter {
478 public:
479 inline void Count(const RawSender::Error err) {
480 failures_ += static_cast<size_t>(err != RawSender::Error::kOk);
481 just_failed_ = (err != RawSender::Error::kOk);
482 }
483
484 inline size_t failures() const { return failures_; }
485 inline bool just_failed() const { return just_failed_; }
486
487 private:
488 size_t failures_ = 0;
489 bool just_failed_ = false;
490};
491
Brian Silverman4f4e0612020-08-12 19:54:41 -0700492// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700493class TimerHandler {
494 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800495 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700496
497 // Timer should sleep until base, base + offset, base + offset * 2, ...
498 // If repeat_offset isn't set, the timer only expires once.
James Kuszmaul8866e642022-06-10 16:00:36 -0700499 // base must be greater than or equal to zero.
Philipp Schradera6712522023-07-05 20:25:11 -0700500 virtual void Schedule(monotonic_clock::time_point base,
501 monotonic_clock::duration repeat_offset =
502 ::aos::monotonic_clock::zero()) = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700503
504 // Stop future calls to callback().
505 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800506
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700507 // Check if the timer is disabled
508 virtual bool IsDisabled() = 0;
509
Austin Schuh1540c2f2019-11-29 21:59:29 -0800510 // Sets and gets the name of the timer. Set this if you want a descriptive
511 // name in the timing report.
512 void set_name(std::string_view name) { name_ = std::string(name); }
513 const std::string_view name() const { return name_; }
514
Austin Schuh39788ff2019-12-01 18:22:57 -0800515 protected:
516 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
517
Austin Schuh9b1d6282022-06-10 17:03:21 -0700518 template <typename T>
519 monotonic_clock::time_point Call(T get_time,
520 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800521
Austin Schuh1540c2f2019-11-29 21:59:29 -0800522 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800523 friend class EventLoop;
524
525 EventLoop *event_loop_;
526 // The function to call when Call is called.
527 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800528 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800529
530 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500531 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700532};
533
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800534// Interface for phased loops. They are built on timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700535class PhasedLoopHandler {
536 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800537 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800539 // Sets the interval and offset. Any changes to interval and offset only take
540 // effect when the handler finishes running or upon a call to Reschedule().
541 //
542 // The precise semantics of the monotonic_now parameter are defined in
543 // phased_loop.h. The way that it gets used in this interface is to control
544 // what the cycles elapsed counter will read on the following call to your
545 // handler. In an idealized simulation environment, if you call
546 // set_interval_and_offset() during the phased loop offset without setting
547 // monotonic_now, then you should always see a count of 1 on the next cycle.
548 //
549 // With the default behavior (this is called inside your handler and with
550 // monotonic_now = nullopt), the next phased loop call will occur at most
551 // interval time after the current time. Note that in many cases this will
552 // *not* be the preferred behavior (in most cases, you would likely aim to
553 // keep the average frequency of the calls reasonably consistent).
554 //
555 // A combination of the monotonic_now parameter and manually calling
556 // Reschedule() outside of the phased loop handler can be used to alter the
557 // behavior of cycles_elapsed. For the default behavior, you can set
558 // monotonic_now to the current time. If you call set_interval_and_offset()
559 // and Reschedule() with the same monotonic_now, that will cause the next
560 // callback to occur in the range (monotonic_now, monotonic_now + interval]
561 // and get called with a count of 1 (if the event is actually able to happen
562 // when it is scheduled to). E.g., if you are just adjusting the phased loop
563 // offset (but not the interval) and want to maintain a consistent frequency,
564 // you may call these functions with monotonic_now = now + interval / 2.
565 void set_interval_and_offset(
566 const monotonic_clock::duration interval,
567 const monotonic_clock::duration offset,
568 std::optional<monotonic_clock::time_point> monotonic_now = std::nullopt) {
569 phased_loop_.set_interval_and_offset(interval, offset, monotonic_now);
Austin Schuh39788ff2019-12-01 18:22:57 -0800570 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800571
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800572 // Reruns the scheduler for the phased loop, scheduling the next callback at
573 // the next available time after monotonic_now. This allows
574 // set_interval_and_offset() to be called and have the changes take effect
575 // before the next handler finishes. This will have no effect if run during
576 // the phased loop's own handler.
577 void Reschedule(monotonic_clock::time_point monotonic_now) {
578 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
579 Schedule(phased_loop_.sleep_time());
580 }
581
582 // Sets and gets the name of the timer. Set this if you want a descriptive
Austin Schuh1540c2f2019-11-29 21:59:29 -0800583 // name in the timing report.
584 void set_name(std::string_view name) { name_ = std::string(name); }
585 const std::string_view name() const { return name_; }
586
Austin Schuh39788ff2019-12-01 18:22:57 -0800587 protected:
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800588 void Call(std::function<monotonic_clock::time_point()> get_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800589
590 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
591 const monotonic_clock::duration interval,
592 const monotonic_clock::duration offset);
593
Austin Schuh1540c2f2019-11-29 21:59:29 -0800594 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800595 friend class EventLoop;
596
Austin Schuh39788ff2019-12-01 18:22:57 -0800597 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
598
599 EventLoop *event_loop_;
600 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800601 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800602 time::PhasedLoop phased_loop_;
603
604 int cycles_elapsed_ = 0;
605
606 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500607 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700608};
609
Austin Schuh3054f5f2021-07-21 15:38:01 -0700610// Note, it is supported to create only:
611// multiple fetchers, and (one sender or one watcher) per <name, type>
612// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700613class EventLoop {
614 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700615 // Holds configuration by reference for the lifetime of this object. It may
616 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800617 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618
Austin Schuh39788ff2019-12-01 18:22:57 -0800619 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700620
621 // Current time.
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800622 virtual monotonic_clock::time_point monotonic_now() const = 0;
623 virtual realtime_clock::time_point realtime_now() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700624
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700625 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800626 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800627 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800628 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800629 true);
630 }
milind1f1dca32021-07-03 13:50:07 -0700631 // Returns true if the channel exists in the configuration.
Austin Schuha0654152021-02-21 21:38:24 -0800632 template <typename T>
633 bool HasChannel(const std::string_view channel_name) {
634 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700635 }
636
Brian Silverman631b6262021-11-10 12:25:08 -0800637 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800638 // not readable on this node or does not exist. You must check valid() on the
639 // Fetcher before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800640 template <typename T>
641 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
642 const Channel *const channel = GetChannel<T>(channel_name);
643 if (channel == nullptr) {
644 return Fetcher<T>();
645 }
646
647 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
648 return Fetcher<T>();
649 }
650
651 return Fetcher<T>(MakeRawFetcher(channel));
652 }
653
Alex Perrycb7da4b2019-08-28 19:35:56 -0700654 // Makes a class that will always fetch the most recent value
655 // sent to the provided channel.
656 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800657 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800658 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700659 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
660 << T::GetFullyQualifiedName() << "\" } not found in config.";
661
Brian Silverman631b6262021-11-10 12:25:08 -0800662 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
663 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800664 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
665 << "\", \"type\": \"" << T::GetFullyQualifiedName()
666 << "\" } is not able to be fetched on this node. Check your "
667 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800668 }
669
Brian Silverman631b6262021-11-10 12:25:08 -0800670 return result;
671 }
672
673 // Like MakeSender, but returns an invalid sender if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800674 // not sendable on this node or does not exist. You must check valid() on the
675 // Sender before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800676 template <typename T>
677 Sender<T> TryMakeSender(const std::string_view channel_name) {
678 const Channel *channel = GetChannel<T>(channel_name);
679 if (channel == nullptr) {
680 return Sender<T>();
681 }
682
683 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
684 return Sender<T>();
685 }
686
687 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700688 }
689
690 // Makes class that allows constructing and sending messages to
691 // the provided channel.
692 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800693 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800694 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700695 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800696 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700697 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800698 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700699 ? absl::StrCat(" on node ", node()->name()->string_view())
700 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700701
Brian Silverman631b6262021-11-10 12:25:08 -0800702 Sender<T> result = TryMakeSender<T>(channel_name);
703 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800704 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
705 << "\", \"type\": \"" << T::GetFullyQualifiedName()
706 << "\" } is not able to be sent on this node. Check your "
707 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800708 }
709
Brian Silverman631b6262021-11-10 12:25:08 -0800710 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700711 }
712
713 // This will watch messages sent to the provided channel.
714 //
Brian Silverman454bc112020-03-05 14:21:25 -0800715 // w must have a non-polymorphic operator() (aka it can only be called with a
716 // single set of arguments; no overloading or templates). It must be callable
717 // with this signature:
718 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700719 //
Brian Silverman454bc112020-03-05 14:21:25 -0800720 // Lambdas are a common form for w. A std::function will work too.
721 //
722 // Note that bind expressions have polymorphic call operators, so they are not
723 // allowed.
724 //
725 // We template Watch as a whole instead of using std::function<void(const T
726 // &)> to allow deducing MessageType from lambdas and other things which are
727 // implicitly convertible to std::function, but not actually std::function
728 // instantiations. Template deduction guides might allow solving this
729 // differently in newer versions of C++, but those have their own corner
730 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700731 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800732 void MakeWatcher(const std::string_view channel_name, Watch &&w);
733
734 // Like MakeWatcher, but doesn't have access to the message data. This may be
735 // implemented to use less resources than an equivalent MakeWatcher.
736 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800737 // The function will still have access to context(), although that will have
738 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800739 template <typename MessageType>
740 void MakeNoArgWatcher(const std::string_view channel_name,
741 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700742
743 // The passed in function will be called when the event loop starts.
744 // Use this to run code once the thread goes into "real-time-mode",
745 virtual void OnRun(::std::function<void()> on_run) = 0;
746
Austin Schuh217a9782019-12-21 23:02:50 -0800747 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800748 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700749
Austin Schuh217a9782019-12-21 23:02:50 -0800750 // Returns the node that this event loop is running on. Returns nullptr if we
751 // are running in single-node mode.
752 virtual const Node *node() const = 0;
753
Alex Perrycb7da4b2019-08-28 19:35:56 -0700754 // Creates a timer that executes callback when the timer expires
755 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700756 // TODO(milind): callback should take the number of cycles elapsed as a
757 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700758 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
759
760 // Creates a timer that executes callback periodically at the specified
761 // interval and offset. Returns a PhasedLoopHandler for interacting with the
762 // timer.
763 virtual PhasedLoopHandler *AddPhasedLoop(
764 ::std::function<void(int)> callback,
765 const monotonic_clock::duration interval,
766 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
767
Austin Schuh217a9782019-12-21 23:02:50 -0800768 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700769
Austin Schuh3054f5f2021-07-21 15:38:01 -0700770 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700771 bool is_running() const { return is_running_.load(); }
772
773 // Sets the scheduler priority to run the event loop at. This may not be
774 // called after we go into "real-time-mode".
775 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700776 // Defaults to 0 if this loop will not run realtime.
777 virtual int runtime_realtime_priority() const = 0;
778
Austin Schuh070019a2022-12-20 22:23:09 -0800779 static cpu_set_t DefaultAffinity();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700780
Brian Silverman6a54ff32020-04-28 16:41:39 -0700781 // Sets the scheduler affinity to run the event loop with. This may only be
782 // called before Run().
783 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700784 // Defaults to DefaultAffinity() if this loop will not run pinned.
785 virtual const cpu_set_t &runtime_affinity() const = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700786
Austin Schuh217a9782019-12-21 23:02:50 -0800787 // Fetches new messages from the provided channel (path, type).
788 //
789 // Note: this channel must be a member of the exact configuration object this
790 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700791 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
792 const Channel *channel) = 0;
793
Austin Schuh217a9782019-12-21 23:02:50 -0800794 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700795 virtual void MakeRawWatcher(
796 const Channel *channel,
797 std::function<void(const Context &context, const void *message)>
798 watcher) = 0;
799
Brian Silverman454bc112020-03-05 14:21:25 -0800800 // Watches channel (name, type) for new messages, without needing to extract
801 // the message contents. Default implementation simply re-uses MakeRawWatcher.
802 virtual void MakeRawNoArgWatcher(
803 const Channel *channel,
804 std::function<void(const Context &context)> watcher) {
805 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800806 Context new_context = context;
807 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700808 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800809 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800810 });
811 }
812
Austin Schuh217a9782019-12-21 23:02:50 -0800813 // Creates a raw sender for the provided channel. This is used for reflection
814 // based sending.
815 // Note: this ignores any node constraints. Ignore at your own peril.
816 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
817
Austin Schuh6231cc32019-12-07 13:06:15 -0800818 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700819 const Context &context() const { return context_; }
820
821 // Returns the configuration that this event loop was built with.
822 const Configuration *configuration() const { return configuration_; }
823
Austin Schuh39788ff2019-12-01 18:22:57 -0800824 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800825 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800826
Brian Silverman4f4e0612020-08-12 19:54:41 -0700827 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800828 void SkipAosLog() { skip_logger_ = true; }
829
Brian Silverman4f4e0612020-08-12 19:54:41 -0700830 // Returns the number of buffers for this channel. This corresponds with the
831 // range of Context::buffer_index values for this channel.
832 virtual int NumberBuffers(const Channel *channel) = 0;
833
Austin Schuh20ac95d2020-12-05 17:24:19 -0800834 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800835 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800836
Alex Perrycb7da4b2019-08-28 19:35:56 -0700837 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800838 // Sets the name of the event loop. This is the application name.
839 virtual void set_name(const std::string_view name) = 0;
840
Alex Perrycb7da4b2019-08-28 19:35:56 -0700841 void set_is_running(bool value) { is_running_.store(value); }
842
Austin Schuh39788ff2019-12-01 18:22:57 -0800843 // Validates that channel exists inside configuration_ and finds its index.
844 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700845
Brian Silverman5120afb2020-01-31 17:44:35 -0800846 // Returns the state for the watcher on the corresponding channel. This
847 // watcher must exist before calling this.
848 WatcherState *GetWatcherState(const Channel *channel);
849
Brian Silverman6d2b3592020-06-18 14:40:15 -0700850 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800851 template <typename T>
852 static RawSender *GetRawSender(aos::Sender<T> *sender) {
853 return sender->sender_.get();
854 }
855
Brian Silverman6d2b3592020-06-18 14:40:15 -0700856 // Returns a Fetcher's protected RawFetcher.
857 template <typename T>
858 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
859 return fetcher->fetcher_.get();
860 }
861
Austin Schuh6231cc32019-12-07 13:06:15 -0800862 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700863 Context context_;
864
Austin Schuh39788ff2019-12-01 18:22:57 -0800865 friend class RawSender;
866 friend class TimerHandler;
867 friend class RawFetcher;
868 friend class PhasedLoopHandler;
869 friend class WatcherState;
870
871 // Methods used to implement timing reports.
872 void NewSender(RawSender *sender);
873 void DeleteSender(RawSender *sender);
874 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
875 PhasedLoopHandler *NewPhasedLoop(
876 std::unique_ptr<PhasedLoopHandler> phased_loop);
877 void NewFetcher(RawFetcher *fetcher);
878 void DeleteFetcher(RawFetcher *fetcher);
879 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
880
Brian Silverman0fc69932020-01-24 21:54:02 -0800881 // Tracks that we have a (single) watcher on the given channel.
882 void TakeWatcher(const Channel *channel);
883 // Tracks that we have at least one sender on the given channel.
884 void TakeSender(const Channel *channel);
885
Austin Schuh39788ff2019-12-01 18:22:57 -0800886 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800887 std::vector<RawFetcher *> fetchers_;
888
Austin Schuh39788ff2019-12-01 18:22:57 -0800889 std::vector<std::unique_ptr<TimerHandler>> timers_;
890 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800891 std::vector<std::unique_ptr<WatcherState>> watchers_;
892
Brian Silvermance418d02021-11-03 11:25:52 -0700893 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800894 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700895
Austin Schuh39788ff2019-12-01 18:22:57 -0800896 void UpdateTimingReport();
897 void MaybeScheduleTimingReports();
898
899 std::unique_ptr<RawSender> timing_report_sender_;
900
Austin Schuh7d87b672019-12-01 20:23:49 -0800901 // Tracks which event sources (timers and watchers) have data, and which
902 // don't. Added events may not change their event_time().
903 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
904 // t2 to run, t2 should then be picked up without a context switch.
905 void AddEvent(EventLoopEvent *event);
906 void RemoveEvent(EventLoopEvent *event);
907 size_t EventCount() const { return events_.size(); }
908 EventLoopEvent *PopEvent();
909 EventLoopEvent *PeekEvent() { return events_.front(); }
910 void ReserveEvents();
911
912 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700913 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800914
Tyler Chatow67ddb032020-01-12 14:30:04 -0800915 // If true, don't send AOS_LOG to /aos
916 bool skip_logger_ = false;
917
Austin Schuha9012be2021-07-21 15:19:11 -0700918 // Sets context_ for a timed event which is supposed to happen at the provided
919 // time.
920 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
Austin Schuh0debde12022-08-17 16:25:17 -0700921 // Clears context_ so it only has invalid times and elements in it.
922 void ClearContext();
Austin Schuha9012be2021-07-21 15:19:11 -0700923
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800924 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800925 virtual pid_t GetTid() = 0;
926
927 FlatbufferDetachedBuffer<timing::Report> timing_report_;
928
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800929 ::std::atomic<bool> is_running_{false};
930
Alex Perrycb7da4b2019-08-28 19:35:56 -0700931 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800932
933 // If true, don't send out timing reports.
934 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800935
milind1f1dca32021-07-03 13:50:07 -0700936 SendFailureCounter timing_report_failure_counter_;
937
Brian Silverman0fc69932020-01-24 21:54:02 -0800938 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700939};
940
Brian Silvermane1fe2512022-08-14 23:18:50 -0700941// Interface for terminating execution of an EventLoop.
942//
943// Prefer this over binding a lambda to an Exit() method when passing ownership
944// in complicated ways because implementations should have assertions to catch
945// it outliving the object it's referring to, instead of having a
946// use-after-free.
947//
948// This is not exposed by EventLoop directly because different EventLoop
949// implementations provide this functionality at different scopes, or possibly
950// not at all.
951class ExitHandle {
952 public:
953 ExitHandle() = default;
954 virtual ~ExitHandle() = default;
955
956 // Exits some set of event loops. Details depend on the implementation.
957 //
958 // This means no more events will be processed, but any currently being
959 // processed will finish.
960 virtual void Exit() = 0;
961};
962
Alex Perrycb7da4b2019-08-28 19:35:56 -0700963} // namespace aos
964
Austin Schuhb8075812020-10-19 09:36:49 -0700965#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700966
967#endif // AOS_EVENTS_EVENT_LOOP_H