blob: e53bc21cb4a3628d7bd219e466ec9ffa94b621f9 [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 enum class [[nodiscard]] Error{
milind1f1dca32021-07-03 13:50:07 -0700163 // Represents success and no error
164 kOk,
165
166 // Error for messages on channels being sent faster than their
167 // frequency and channel storage duration allow
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700168 kMessagesSentTooFast,
169 // Access to Redzone was attempted in Sender Queue
Brian Silverman183859c2022-05-14 02:03:06 -0700170 kInvalidRedzone,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700171 };
milind1f1dca32021-07-03 13:50:07 -0700172
Austin Schuh39788ff2019-12-01 18:22:57 -0800173 RawSender(EventLoop *event_loop, const Channel *channel);
174 RawSender(const RawSender &) = delete;
175 RawSender &operator=(const RawSender &) = delete;
176
177 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700178
Brian Silverman9809c5f2022-07-23 16:12:23 -0700179 // Returns the buffer to write new messages into. This is always valid, and
180 // may change after calling any of the Send functions.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700181 virtual void *data() = 0;
182 virtual size_t size() = 0;
milind1f1dca32021-07-03 13:50:07 -0700183
184 // Sends a message without copying it. The users starts by copying up to
185 // size() bytes into the data backed by data(). They then call Send to send.
186 // Returns Error::kOk on a successful send, or
187 // Error::kMessagesSentTooFast if messages were sent too fast. If provided,
188 // monotonic_remote_time, realtime_remote_time, and remote_queue_index are
189 // attached to the message and are available in the context on the read side.
190 // If they are not populated, the read side will get the sent times instead.
191 Error Send(size_t size);
192 Error Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
193 realtime_clock::time_point realtime_remote_time,
194 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700195
196 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800197 // The remote arguments have the same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700198 // Returns Error::kMessagesSentTooFast if messages were sent too fast
199 Error Send(const void *data, size_t size);
200 Error Send(const void *data, size_t size,
201 monotonic_clock::time_point monotonic_remote_time,
202 realtime_clock::time_point realtime_remote_time,
203 uint32_t remote_queue_index, const UUID &source_boot_uuid);
204
205 // CHECKs that no sending Error occurred and logs the channel_ data if
206 // one did
207 void CheckOk(const Error err);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700208
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700209 // Sends a single block of data by refcounting it to avoid copies. The data
210 // must not change after being passed into Send. The remote arguments have the
211 // same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700212 Error Send(const SharedSpan data);
213 Error Send(const SharedSpan data,
214 monotonic_clock::time_point monotonic_remote_time,
215 realtime_clock::time_point realtime_remote_time,
216 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Austin Schuh54cf95f2019-11-29 13:14:18 -0800217 const Channel *channel() const { return channel_; }
218
Austin Schuhad154822019-12-27 15:45:13 -0800219 // Returns the time_points that the last message was sent at.
220 aos::monotonic_clock::time_point monotonic_sent_time() const {
221 return monotonic_sent_time_;
222 }
223 aos::realtime_clock::time_point realtime_sent_time() const {
224 return realtime_sent_time_;
225 }
226 // Returns the queue index that this was sent with.
227 uint32_t sent_queue_index() const { return sent_queue_index_; }
228
Brian Silvermana1652f32020-01-29 20:41:44 -0800229 // Returns the associated flatbuffers-style allocator. This must be
230 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800231 ChannelPreallocatedAllocator *fbb_allocator() {
232 fbb_allocator_ = ChannelPreallocatedAllocator(
233 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800234 return &fbb_allocator_;
235 }
236
Brian Silverman4f4e0612020-08-12 19:54:41 -0700237 // Index of the buffer which is currently exposed by data() and the various
238 // other accessors. This is the message the caller should be filling out.
239 virtual int buffer_index() = 0;
240
Alex Perrycb7da4b2019-08-28 19:35:56 -0700241 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800242 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700243 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800244
Austin Schuhb5c6f972021-03-14 21:53:07 -0700245 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
246 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800247 uint32_t sent_queue_index_ = 0xffffffff;
248
Austin Schuh39788ff2019-12-01 18:22:57 -0800249 private:
250 friend class EventLoop;
251
milind1f1dca32021-07-03 13:50:07 -0700252 virtual Error DoSend(const void *data, size_t size,
253 monotonic_clock::time_point monotonic_remote_time,
254 realtime_clock::time_point realtime_remote_time,
255 uint32_t remote_queue_index,
256 const UUID &source_boot_uuid) = 0;
257 virtual Error DoSend(size_t size,
258 monotonic_clock::time_point monotonic_remote_time,
259 realtime_clock::time_point realtime_remote_time,
260 uint32_t remote_queue_index,
261 const UUID &source_boot_uuid) = 0;
262 virtual Error DoSend(const SharedSpan data,
263 monotonic_clock::time_point monotonic_remote_time,
264 realtime_clock::time_point realtime_remote_time,
265 uint32_t remote_queue_index,
266 const UUID &source_boot_uuid);
Austin Schuh39788ff2019-12-01 18:22:57 -0800267
James Kuszmaul93abac12022-04-14 15:05:10 -0700268 void RecordSendResult(const Error error, size_t message_size);
269
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500270 EventLoop *const event_loop_;
271 const Channel *const channel_;
272 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700273
Austin Schuh39788ff2019-12-01 18:22:57 -0800274 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500275 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800276
Austin Schuh1af273d2020-03-07 20:11:34 -0800277 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800278};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700279
milind1f1dca32021-07-03 13:50:07 -0700280// Needed for compatibility with glog
281std::ostream &operator<<(std::ostream &os, const RawSender::Error err);
282
Alex Perrycb7da4b2019-08-28 19:35:56 -0700283// Fetches the newest message from a channel.
284// This provides a polling based interface for channels.
285template <typename T>
286class Fetcher {
287 public:
288 Fetcher() {}
289
290 // Fetches the next message. Returns true if it fetched a new message. This
291 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800292 bool FetchNext() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800293 const bool result = CHECK_NOTNULL(fetcher_)->FetchNext();
Brian Silvermana1652f32020-01-29 20:41:44 -0800294 if (result) {
295 CheckChannelDataAlignment(fetcher_->context().data,
296 fetcher_->context().size);
297 }
298 return result;
299 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700300
301 // Fetches the most recent message. Returns true if it fetched a new message.
302 // This will return the latest message regardless of if it was sent before or
303 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800304 bool Fetch() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800305 const bool result = CHECK_NOTNULL(fetcher_)->Fetch();
Brian Silvermana1652f32020-01-29 20:41:44 -0800306 if (result) {
307 CheckChannelDataAlignment(fetcher_->context().data,
308 fetcher_->context().size);
309 }
310 return result;
311 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700312
313 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
314 // available message.
315 const T *get() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800316 return CHECK_NOTNULL(fetcher_)->context().data != nullptr
Austin Schuh39788ff2019-12-01 18:22:57 -0800317 ? flatbuffers::GetRoot<T>(
318 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700319 : nullptr;
320 }
321
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700322 // Returns the channel this fetcher uses
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800323 const Channel *channel() const { return CHECK_NOTNULL(fetcher_)->channel(); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700324
Alex Perrycb7da4b2019-08-28 19:35:56 -0700325 // Returns the context holding timestamps and other metadata about the
326 // message.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800327 const Context &context() const { return CHECK_NOTNULL(fetcher_)->context(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700328
329 const T &operator*() const { return *get(); }
330 const T *operator->() const { return get(); }
331
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800332 // Returns true if this fetcher is valid and connected to a channel. If you,
333 // e.g., are using TryMakeFetcher, then you must check valid() before
334 // attempting to use the Fetcher.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700335 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700336
Austin Schuhca75b6a2020-12-15 21:12:24 -0800337 // Copies the current flatbuffer into a FlatbufferVector.
338 FlatbufferVector<T> CopyFlatBuffer() const {
339 return context().template CopyFlatBuffer<T>();
340 }
341
Alex Perrycb7da4b2019-08-28 19:35:56 -0700342 private:
343 friend class EventLoop;
344 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
345 : fetcher_(::std::move(fetcher)) {}
346 ::std::unique_ptr<RawFetcher> fetcher_;
347};
348
349// Sends messages to a channel.
350template <typename T>
351class Sender {
352 public:
353 Sender() {}
354
355 // Represents a single message about to be sent to the queue.
356 // The lifecycle goes:
357 //
358 // Builder builder = sender.MakeBuilder();
359 // T::Builder t_builder = builder.MakeBuilder<T>();
360 // Populate(&t_builder);
361 // builder.Send(t_builder.Finish());
362 class Builder {
363 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800364 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800365 : fbb_(allocator->size(), allocator),
366 allocator_(allocator),
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800367 sender_(CHECK_NOTNULL(sender)) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800368 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800369 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700370 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800371 Builder() {}
372 Builder(const Builder &) = delete;
373 Builder(Builder &&) = default;
374
375 Builder &operator=(const Builder &) = delete;
376 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700377
378 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
379
380 template <typename T2>
381 typename T2::Builder MakeBuilder() {
382 return typename T2::Builder(fbb_);
383 }
384
milind1f1dca32021-07-03 13:50:07 -0700385 RawSender::Error Send(flatbuffers::Offset<T> offset) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700386 fbb_.Finish(offset);
milind1f1dca32021-07-03 13:50:07 -0700387 const auto err = sender_->Send(fbb_.GetSize());
Brian Silverman9dd793b2020-01-31 23:52:21 -0800388 // Ensure fbb_ knows it shouldn't access the memory any more.
389 fbb_ = flatbuffers::FlatBufferBuilder();
milind1f1dca32021-07-03 13:50:07 -0700390 return err;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391 }
392
milind1f1dca32021-07-03 13:50:07 -0700393 // Equivalent to RawSender::CheckOk
394 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
395
Alex Perrycb7da4b2019-08-28 19:35:56 -0700396 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800397 void CheckSent() {
398 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
399 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700400
Brian Silverman341b57e2020-06-23 16:23:18 -0700401 // Detaches a buffer, for later use calling Sender::Send directly.
402 //
403 // Note that the underlying memory remains with the Sender, so creating
404 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
405 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
406 fbb_.Finish(offset);
407 return fbb_.Release();
408 }
409
Alex Perrycb7da4b2019-08-28 19:35:56 -0700410 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800412 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700413 RawSender *sender_;
414 };
415
416 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800417 //
418 // Only a single one of these may be "alive" for this object at any point in
419 // time. After calling Send on the result, it is no longer "alive". This means
420 // that you must manually reset a variable holding the return value (by
421 // assigning a default-constructed Builder to it) before calling this method
422 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700423 Builder MakeBuilder();
424
Austin Schuha28cbc32019-12-27 16:28:04 -0800425 // Sends a prebuilt flatbuffer.
James Kuszmaulad523042022-10-05 16:47:33 -0700426 // This will copy the data out of the provided flatbuffer, and so does not
427 // have to correspond to an existing Builder.
milind1f1dca32021-07-03 13:50:07 -0700428 RawSender::Error Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800429
Brian Silverman341b57e2020-06-23 16:23:18 -0700430 // Sends a prebuilt flatbuffer which was detached from a Builder created via
431 // MakeBuilder() on this object.
milind1f1dca32021-07-03 13:50:07 -0700432 RawSender::Error SendDetached(FlatbufferDetachedBuffer<T> detached);
433
434 // Equivalent to RawSender::CheckOk
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800435 void CheckOk(const RawSender::Error err) {
436 CHECK_NOTNULL(sender_)->CheckOk(err);
437 };
Brian Silverman341b57e2020-06-23 16:23:18 -0700438
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800439 // Returns the name of the underlying queue, if valid. You must check valid()
440 // first.
441 const Channel *channel() const { return CHECK_NOTNULL(sender_)->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700442
James Kuszmaulad523042022-10-05 16:47:33 -0700443 // Returns true if the Sender is a valid Sender. If you, e.g., are using
444 // TryMakeSender, then you must check valid() before attempting to use the
445 // Sender.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800446 // TODO(austin): Deprecate the operator bool.
Austin Schuha0c41ba2020-09-10 22:59:14 -0700447 operator bool() const { return sender_ ? true : false; }
Austin Schuhe33c08d2022-02-03 18:15:21 -0800448 bool valid() const { return static_cast<bool>(sender_); }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800449
Austin Schuh7bc59052020-02-16 23:48:33 -0800450 // Returns the time_points that the last message was sent at.
451 aos::monotonic_clock::time_point monotonic_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800452 return CHECK_NOTNULL(sender_)->monotonic_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800453 }
454 aos::realtime_clock::time_point realtime_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800455 return CHECK_NOTNULL(sender_)->realtime_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800456 }
457 // Returns the queue index that this was sent with.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800458 uint32_t sent_queue_index() const {
459 return CHECK_NOTNULL(sender_)->sent_queue_index();
460 }
Austin Schuh7bc59052020-02-16 23:48:33 -0800461
Brian Silverman4f4e0612020-08-12 19:54:41 -0700462 // Returns the buffer index which MakeBuilder() will expose access to. This is
463 // the buffer the caller can fill out.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800464 int buffer_index() const { return CHECK_NOTNULL(sender_)->buffer_index(); }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700465
Alex Perrycb7da4b2019-08-28 19:35:56 -0700466 private:
467 friend class EventLoop;
468 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
469 std::unique_ptr<RawSender> sender_;
470};
471
milind1f1dca32021-07-03 13:50:07 -0700472// Class for keeping a count of send failures on a certain channel
473class SendFailureCounter {
474 public:
475 inline void Count(const RawSender::Error err) {
476 failures_ += static_cast<size_t>(err != RawSender::Error::kOk);
477 just_failed_ = (err != RawSender::Error::kOk);
478 }
479
480 inline size_t failures() const { return failures_; }
481 inline bool just_failed() const { return just_failed_; }
482
483 private:
484 size_t failures_ = 0;
485 bool just_failed_ = false;
486};
487
Brian Silverman4f4e0612020-08-12 19:54:41 -0700488// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700489class TimerHandler {
490 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800491 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492
493 // Timer should sleep until base, base + offset, base + offset * 2, ...
494 // If repeat_offset isn't set, the timer only expires once.
James Kuszmaul8866e642022-06-10 16:00:36 -0700495 // base must be greater than or equal to zero.
Philipp Schradera6712522023-07-05 20:25:11 -0700496 virtual void Schedule(monotonic_clock::time_point base,
497 monotonic_clock::duration repeat_offset =
498 ::aos::monotonic_clock::zero()) = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700499
500 // Stop future calls to callback().
501 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800502
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700503 // Check if the timer is disabled
504 virtual bool IsDisabled() = 0;
505
Austin Schuh1540c2f2019-11-29 21:59:29 -0800506 // Sets and gets the name of the timer. Set this if you want a descriptive
507 // name in the timing report.
508 void set_name(std::string_view name) { name_ = std::string(name); }
509 const std::string_view name() const { return name_; }
510
Austin Schuh39788ff2019-12-01 18:22:57 -0800511 protected:
512 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
513
Austin Schuh9b1d6282022-06-10 17:03:21 -0700514 template <typename T>
515 monotonic_clock::time_point Call(T get_time,
516 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800517
Austin Schuh1540c2f2019-11-29 21:59:29 -0800518 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800519 friend class EventLoop;
520
521 EventLoop *event_loop_;
522 // The function to call when Call is called.
523 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800524 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800525
526 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500527 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700528};
529
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800530// Interface for phased loops. They are built on timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700531class PhasedLoopHandler {
532 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800533 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700534
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800535 // Sets the interval and offset. Any changes to interval and offset only take
536 // effect when the handler finishes running or upon a call to Reschedule().
537 //
538 // The precise semantics of the monotonic_now parameter are defined in
539 // phased_loop.h. The way that it gets used in this interface is to control
540 // what the cycles elapsed counter will read on the following call to your
541 // handler. In an idealized simulation environment, if you call
542 // set_interval_and_offset() during the phased loop offset without setting
543 // monotonic_now, then you should always see a count of 1 on the next cycle.
544 //
545 // With the default behavior (this is called inside your handler and with
546 // monotonic_now = nullopt), the next phased loop call will occur at most
547 // interval time after the current time. Note that in many cases this will
548 // *not* be the preferred behavior (in most cases, you would likely aim to
549 // keep the average frequency of the calls reasonably consistent).
550 //
551 // A combination of the monotonic_now parameter and manually calling
552 // Reschedule() outside of the phased loop handler can be used to alter the
553 // behavior of cycles_elapsed. For the default behavior, you can set
554 // monotonic_now to the current time. If you call set_interval_and_offset()
555 // and Reschedule() with the same monotonic_now, that will cause the next
556 // callback to occur in the range (monotonic_now, monotonic_now + interval]
557 // and get called with a count of 1 (if the event is actually able to happen
558 // when it is scheduled to). E.g., if you are just adjusting the phased loop
559 // offset (but not the interval) and want to maintain a consistent frequency,
560 // you may call these functions with monotonic_now = now + interval / 2.
561 void set_interval_and_offset(
562 const monotonic_clock::duration interval,
563 const monotonic_clock::duration offset,
564 std::optional<monotonic_clock::time_point> monotonic_now = std::nullopt) {
565 phased_loop_.set_interval_and_offset(interval, offset, monotonic_now);
Austin Schuh39788ff2019-12-01 18:22:57 -0800566 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800567
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800568 // Reruns the scheduler for the phased loop, scheduling the next callback at
569 // the next available time after monotonic_now. This allows
570 // set_interval_and_offset() to be called and have the changes take effect
571 // before the next handler finishes. This will have no effect if run during
572 // the phased loop's own handler.
573 void Reschedule(monotonic_clock::time_point monotonic_now) {
574 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
575 Schedule(phased_loop_.sleep_time());
576 }
577
578 // Sets and gets the name of the timer. Set this if you want a descriptive
Austin Schuh1540c2f2019-11-29 21:59:29 -0800579 // name in the timing report.
580 void set_name(std::string_view name) { name_ = std::string(name); }
581 const std::string_view name() const { return name_; }
582
Austin Schuh39788ff2019-12-01 18:22:57 -0800583 protected:
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800584 void Call(std::function<monotonic_clock::time_point()> get_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800585
586 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
587 const monotonic_clock::duration interval,
588 const monotonic_clock::duration offset);
589
Austin Schuh1540c2f2019-11-29 21:59:29 -0800590 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800591 friend class EventLoop;
592
Austin Schuh39788ff2019-12-01 18:22:57 -0800593 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
594
595 EventLoop *event_loop_;
596 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800597 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800598 time::PhasedLoop phased_loop_;
599
600 int cycles_elapsed_ = 0;
601
602 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500603 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700604};
605
Austin Schuh3054f5f2021-07-21 15:38:01 -0700606// Note, it is supported to create only:
607// multiple fetchers, and (one sender or one watcher) per <name, type>
608// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700609class EventLoop {
610 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700611 // Holds configuration by reference for the lifetime of this object. It may
612 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800613 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700614
Austin Schuh39788ff2019-12-01 18:22:57 -0800615 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700616
617 // Current time.
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800618 virtual monotonic_clock::time_point monotonic_now() const = 0;
619 virtual realtime_clock::time_point realtime_now() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700620
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700621 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800622 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800623 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800624 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800625 true);
626 }
milind1f1dca32021-07-03 13:50:07 -0700627 // Returns true if the channel exists in the configuration.
Austin Schuha0654152021-02-21 21:38:24 -0800628 template <typename T>
629 bool HasChannel(const std::string_view channel_name) {
630 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700631 }
632
Brian Silverman631b6262021-11-10 12:25:08 -0800633 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800634 // not readable on this node or does not exist. You must check valid() on the
635 // Fetcher before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800636 template <typename T>
637 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
638 const Channel *const channel = GetChannel<T>(channel_name);
639 if (channel == nullptr) {
640 return Fetcher<T>();
641 }
642
643 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
644 return Fetcher<T>();
645 }
646
647 return Fetcher<T>(MakeRawFetcher(channel));
648 }
649
Alex Perrycb7da4b2019-08-28 19:35:56 -0700650 // Makes a class that will always fetch the most recent value
651 // sent to the provided channel.
652 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800653 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800654 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700655 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
656 << T::GetFullyQualifiedName() << "\" } not found in config.";
657
Brian Silverman631b6262021-11-10 12:25:08 -0800658 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
659 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800660 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
661 << "\", \"type\": \"" << T::GetFullyQualifiedName()
662 << "\" } is not able to be fetched on this node. Check your "
663 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800664 }
665
Brian Silverman631b6262021-11-10 12:25:08 -0800666 return result;
667 }
668
669 // Like MakeSender, but returns an invalid sender if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800670 // not sendable on this node or does not exist. You must check valid() on the
671 // Sender before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800672 template <typename T>
673 Sender<T> TryMakeSender(const std::string_view channel_name) {
674 const Channel *channel = GetChannel<T>(channel_name);
675 if (channel == nullptr) {
676 return Sender<T>();
677 }
678
679 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
680 return Sender<T>();
681 }
682
683 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700684 }
685
686 // Makes class that allows constructing and sending messages to
687 // the provided channel.
688 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800689 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800690 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700691 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800692 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700693 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800694 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700695 ? absl::StrCat(" on node ", node()->name()->string_view())
696 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700697
Brian Silverman631b6262021-11-10 12:25:08 -0800698 Sender<T> result = TryMakeSender<T>(channel_name);
699 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800700 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
701 << "\", \"type\": \"" << T::GetFullyQualifiedName()
702 << "\" } is not able to be sent on this node. Check your "
703 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800704 }
705
Brian Silverman631b6262021-11-10 12:25:08 -0800706 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700707 }
708
709 // This will watch messages sent to the provided channel.
710 //
Brian Silverman454bc112020-03-05 14:21:25 -0800711 // w must have a non-polymorphic operator() (aka it can only be called with a
712 // single set of arguments; no overloading or templates). It must be callable
713 // with this signature:
714 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700715 //
Brian Silverman454bc112020-03-05 14:21:25 -0800716 // Lambdas are a common form for w. A std::function will work too.
717 //
718 // Note that bind expressions have polymorphic call operators, so they are not
719 // allowed.
720 //
721 // We template Watch as a whole instead of using std::function<void(const T
722 // &)> to allow deducing MessageType from lambdas and other things which are
723 // implicitly convertible to std::function, but not actually std::function
724 // instantiations. Template deduction guides might allow solving this
725 // differently in newer versions of C++, but those have their own corner
726 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700727 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800728 void MakeWatcher(const std::string_view channel_name, Watch &&w);
729
730 // Like MakeWatcher, but doesn't have access to the message data. This may be
731 // implemented to use less resources than an equivalent MakeWatcher.
732 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800733 // The function will still have access to context(), although that will have
734 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800735 template <typename MessageType>
736 void MakeNoArgWatcher(const std::string_view channel_name,
737 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700738
739 // The passed in function will be called when the event loop starts.
740 // Use this to run code once the thread goes into "real-time-mode",
741 virtual void OnRun(::std::function<void()> on_run) = 0;
742
Austin Schuh217a9782019-12-21 23:02:50 -0800743 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800744 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700745
Austin Schuh217a9782019-12-21 23:02:50 -0800746 // Returns the node that this event loop is running on. Returns nullptr if we
747 // are running in single-node mode.
748 virtual const Node *node() const = 0;
749
Alex Perrycb7da4b2019-08-28 19:35:56 -0700750 // Creates a timer that executes callback when the timer expires
751 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700752 // TODO(milind): callback should take the number of cycles elapsed as a
753 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700754 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
755
756 // Creates a timer that executes callback periodically at the specified
757 // interval and offset. Returns a PhasedLoopHandler for interacting with the
758 // timer.
759 virtual PhasedLoopHandler *AddPhasedLoop(
760 ::std::function<void(int)> callback,
761 const monotonic_clock::duration interval,
762 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
763
Austin Schuh217a9782019-12-21 23:02:50 -0800764 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700765
Austin Schuh3054f5f2021-07-21 15:38:01 -0700766 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700767 bool is_running() const { return is_running_.load(); }
768
769 // Sets the scheduler priority to run the event loop at. This may not be
770 // called after we go into "real-time-mode".
771 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700772 // Defaults to 0 if this loop will not run realtime.
773 virtual int runtime_realtime_priority() const = 0;
774
Austin Schuh070019a2022-12-20 22:23:09 -0800775 static cpu_set_t DefaultAffinity();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700776
Brian Silverman6a54ff32020-04-28 16:41:39 -0700777 // Sets the scheduler affinity to run the event loop with. This may only be
778 // called before Run().
779 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700780 // Defaults to DefaultAffinity() if this loop will not run pinned.
781 virtual const cpu_set_t &runtime_affinity() const = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700782
Austin Schuh217a9782019-12-21 23:02:50 -0800783 // Fetches new messages from the provided channel (path, type).
784 //
785 // Note: this channel must be a member of the exact configuration object this
786 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700787 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
788 const Channel *channel) = 0;
789
Austin Schuh217a9782019-12-21 23:02:50 -0800790 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700791 virtual void MakeRawWatcher(
792 const Channel *channel,
793 std::function<void(const Context &context, const void *message)>
794 watcher) = 0;
795
Brian Silverman454bc112020-03-05 14:21:25 -0800796 // Watches channel (name, type) for new messages, without needing to extract
797 // the message contents. Default implementation simply re-uses MakeRawWatcher.
798 virtual void MakeRawNoArgWatcher(
799 const Channel *channel,
800 std::function<void(const Context &context)> watcher) {
801 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800802 Context new_context = context;
803 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700804 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800805 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800806 });
807 }
808
Austin Schuh217a9782019-12-21 23:02:50 -0800809 // Creates a raw sender for the provided channel. This is used for reflection
810 // based sending.
811 // Note: this ignores any node constraints. Ignore at your own peril.
812 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
813
Austin Schuh6231cc32019-12-07 13:06:15 -0800814 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700815 const Context &context() const { return context_; }
816
817 // Returns the configuration that this event loop was built with.
818 const Configuration *configuration() const { return configuration_; }
819
Austin Schuh39788ff2019-12-01 18:22:57 -0800820 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800821 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800822
Brian Silverman4f4e0612020-08-12 19:54:41 -0700823 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800824 void SkipAosLog() { skip_logger_ = true; }
825
Brian Silverman4f4e0612020-08-12 19:54:41 -0700826 // Returns the number of buffers for this channel. This corresponds with the
827 // range of Context::buffer_index values for this channel.
828 virtual int NumberBuffers(const Channel *channel) = 0;
829
Austin Schuh20ac95d2020-12-05 17:24:19 -0800830 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800831 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800832
Alex Perrycb7da4b2019-08-28 19:35:56 -0700833 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800834 // Sets the name of the event loop. This is the application name.
835 virtual void set_name(const std::string_view name) = 0;
836
Alex Perrycb7da4b2019-08-28 19:35:56 -0700837 void set_is_running(bool value) { is_running_.store(value); }
838
Austin Schuh39788ff2019-12-01 18:22:57 -0800839 // Validates that channel exists inside configuration_ and finds its index.
840 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700841
Brian Silverman5120afb2020-01-31 17:44:35 -0800842 // Returns the state for the watcher on the corresponding channel. This
843 // watcher must exist before calling this.
844 WatcherState *GetWatcherState(const Channel *channel);
845
Brian Silverman6d2b3592020-06-18 14:40:15 -0700846 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800847 template <typename T>
848 static RawSender *GetRawSender(aos::Sender<T> *sender) {
849 return sender->sender_.get();
850 }
851
Brian Silverman6d2b3592020-06-18 14:40:15 -0700852 // Returns a Fetcher's protected RawFetcher.
853 template <typename T>
854 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
855 return fetcher->fetcher_.get();
856 }
857
Austin Schuh6231cc32019-12-07 13:06:15 -0800858 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700859 Context context_;
860
Austin Schuh39788ff2019-12-01 18:22:57 -0800861 friend class RawSender;
862 friend class TimerHandler;
863 friend class RawFetcher;
864 friend class PhasedLoopHandler;
865 friend class WatcherState;
866
867 // Methods used to implement timing reports.
868 void NewSender(RawSender *sender);
869 void DeleteSender(RawSender *sender);
870 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
871 PhasedLoopHandler *NewPhasedLoop(
872 std::unique_ptr<PhasedLoopHandler> phased_loop);
873 void NewFetcher(RawFetcher *fetcher);
874 void DeleteFetcher(RawFetcher *fetcher);
875 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
876
Brian Silverman0fc69932020-01-24 21:54:02 -0800877 // Tracks that we have a (single) watcher on the given channel.
878 void TakeWatcher(const Channel *channel);
879 // Tracks that we have at least one sender on the given channel.
880 void TakeSender(const Channel *channel);
881
Austin Schuh39788ff2019-12-01 18:22:57 -0800882 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800883 std::vector<RawFetcher *> fetchers_;
884
Austin Schuh39788ff2019-12-01 18:22:57 -0800885 std::vector<std::unique_ptr<TimerHandler>> timers_;
886 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800887 std::vector<std::unique_ptr<WatcherState>> watchers_;
888
Brian Silvermance418d02021-11-03 11:25:52 -0700889 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800890 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700891
Austin Schuh39788ff2019-12-01 18:22:57 -0800892 void UpdateTimingReport();
893 void MaybeScheduleTimingReports();
894
895 std::unique_ptr<RawSender> timing_report_sender_;
896
Austin Schuh7d87b672019-12-01 20:23:49 -0800897 // Tracks which event sources (timers and watchers) have data, and which
898 // don't. Added events may not change their event_time().
899 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
900 // t2 to run, t2 should then be picked up without a context switch.
901 void AddEvent(EventLoopEvent *event);
902 void RemoveEvent(EventLoopEvent *event);
903 size_t EventCount() const { return events_.size(); }
904 EventLoopEvent *PopEvent();
905 EventLoopEvent *PeekEvent() { return events_.front(); }
906 void ReserveEvents();
907
908 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700909 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800910
Tyler Chatow67ddb032020-01-12 14:30:04 -0800911 // If true, don't send AOS_LOG to /aos
912 bool skip_logger_ = false;
913
Austin Schuha9012be2021-07-21 15:19:11 -0700914 // Sets context_ for a timed event which is supposed to happen at the provided
915 // time.
916 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
Austin Schuh0debde12022-08-17 16:25:17 -0700917 // Clears context_ so it only has invalid times and elements in it.
918 void ClearContext();
Austin Schuha9012be2021-07-21 15:19:11 -0700919
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800920 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800921 virtual pid_t GetTid() = 0;
922
923 FlatbufferDetachedBuffer<timing::Report> timing_report_;
924
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800925 ::std::atomic<bool> is_running_{false};
926
Alex Perrycb7da4b2019-08-28 19:35:56 -0700927 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800928
929 // If true, don't send out timing reports.
930 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800931
milind1f1dca32021-07-03 13:50:07 -0700932 SendFailureCounter timing_report_failure_counter_;
933
Brian Silverman0fc69932020-01-24 21:54:02 -0800934 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700935};
936
Brian Silvermane1fe2512022-08-14 23:18:50 -0700937// Interface for terminating execution of an EventLoop.
938//
939// Prefer this over binding a lambda to an Exit() method when passing ownership
940// in complicated ways because implementations should have assertions to catch
941// it outliving the object it's referring to, instead of having a
942// use-after-free.
943//
944// This is not exposed by EventLoop directly because different EventLoop
945// implementations provide this functionality at different scopes, or possibly
946// not at all.
947class ExitHandle {
948 public:
949 ExitHandle() = default;
950 virtual ~ExitHandle() = default;
951
952 // Exits some set of event loops. Details depend on the implementation.
953 //
954 // This means no more events will be processed, but any currently being
955 // processed will finish.
956 virtual void Exit() = 0;
957};
958
Alex Perrycb7da4b2019-08-28 19:35:56 -0700959} // namespace aos
960
Austin Schuhb8075812020-10-19 09:36:49 -0700961#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700962
963#endif // AOS_EVENTS_EVENT_LOOP_H