blob: 88254649f4ea2167fd113452e910b12a751e48d6 [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_EVENT_LOOP_H_
2#define AOS_EVENTS_EVENT_LOOP_H_
3
Brian Silverman6a54ff32020-04-28 16:41:39 -07004#include <sched.h>
5
Alex Perrycb7da4b2019-08-28 19:35:56 -07006#include <atomic>
milind1f1dca32021-07-03 13:50:07 -07007#include <ostream>
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08009#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -070010
Austin Schuh3054f5f2021-07-21 15:38:01 -070011#include "absl/container/btree_set.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070012#include "aos/configuration.h"
13#include "aos/configuration_generated.h"
Austin Schuh1af273d2020-03-07 20:11:34 -080014#include "aos/events/channel_preallocated_allocator.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080015#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080016#include "aos/events/event_loop_generated.h"
17#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070018#include "aos/flatbuffers.h"
Brian Silverman79ec7fc2020-06-08 20:11:22 -050019#include "aos/ftrace.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080020#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "aos/json_to_flatbuffer.h"
22#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080023#include "aos/util/phased_loop.h"
Austin Schuh4385b142021-03-14 21:31:13 -070024#include "aos/uuid.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070025#include "flatbuffers/flatbuffers.h"
26#include "glog/logging.h"
27
Austin Schuh39788ff2019-12-01 18:22:57 -080028DECLARE_bool(timing_reports);
29DECLARE_int32(timing_report_ms);
30
Alex Perrycb7da4b2019-08-28 19:35:56 -070031namespace aos {
32
Austin Schuh39788ff2019-12-01 18:22:57 -080033class EventLoop;
34class WatcherState;
35
Austin Schuh6231cc32019-12-07 13:06:15 -080036// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
37// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070038struct Context {
Austin Schuhad154822019-12-27 15:45:13 -080039 // Time that the message was sent on this node, or the timer was triggered.
40 monotonic_clock::time_point monotonic_event_time;
41 // Realtime the message was sent on this node. This is set to min_time for
42 // Timers and PhasedLoops.
43 realtime_clock::time_point realtime_event_time;
44
James Kuszmaulad523042022-10-05 16:47:33 -070045 // The rest are only valid for Watchers and Fetchers.
46
Austin Schuhad154822019-12-27 15:45:13 -080047 // For a single-node configuration, these two are identical to *_event_time.
48 // In a multinode configuration, these are the times that the message was
49 // sent on the original node.
50 monotonic_clock::time_point monotonic_remote_time;
51 realtime_clock::time_point realtime_remote_time;
52
Alex Perrycb7da4b2019-08-28 19:35:56 -070053 // Index in the queue.
54 uint32_t queue_index;
Austin Schuhad154822019-12-27 15:45:13 -080055 // Index into the remote queue. Useful to determine if data was lost. In a
56 // single-node configuration, this will match queue_index.
57 uint32_t remote_queue_index;
58
Alex Perrycb7da4b2019-08-28 19:35:56 -070059 // Size of the data sent.
60 size_t size;
61 // Pointer to the data.
Brian Silvermaneaa41d62020-07-08 19:47:35 -070062 const void *data;
Austin Schuh678078e2020-08-01 14:30:36 -070063
Brian Silverman4f4e0612020-08-12 19:54:41 -070064 // Index of the message buffer. This will be in [0, NumberBuffers) on
65 // read_method=PIN channels, and -1 for other channels.
66 //
67 // This only tells you about the underlying storage for this message, not
68 // anything about its position in the queue. This is only useful for advanced
69 // zero-copy use cases, on read_method=PIN channels.
70 //
71 // This will uniquely identify a message on this channel at a point in time.
72 // For senders, this point in time is while the sender has the message. With
73 // read_method==PIN, this point in time includes while the caller has access
74 // to this context. For other read_methods, this point in time may be before
75 // the caller has access to this context, which makes this pretty useless.
76 int buffer_index;
77
Austin Schuh8902fa52021-03-14 22:39:24 -070078 // UUID of the remote node which sent this message, or this node in the case
79 // of events which are local to this node.
Austin Schuha9012be2021-07-21 15:19:11 -070080 UUID source_boot_uuid = UUID::Zero();
Austin Schuh8902fa52021-03-14 22:39:24 -070081
Austin Schuhca75b6a2020-12-15 21:12:24 -080082 // Efficiently copies the flatbuffer into a FlatbufferVector, allocating
Austin Schuh678078e2020-08-01 14:30:36 -070083 // memory in the process. It is vital that T matches the type of the
84 // underlying flatbuffer.
85 template <typename T>
86 FlatbufferVector<T> CopyFlatBuffer() const {
Brian Silverman354697a2020-09-22 21:06:32 -070087 ResizeableBuffer buffer;
88 buffer.resize(size);
89 memcpy(buffer.data(), data, size);
90 return FlatbufferVector<T>(std::move(buffer));
Austin Schuh678078e2020-08-01 14:30:36 -070091 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070092};
93
94// Raw version of fetcher. Contains a local variable that the fetcher will
95// update. This is used for reflection and as an interface to implement typed
96// fetchers.
97class RawFetcher {
98 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080099 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700100 RawFetcher(const RawFetcher &) = delete;
101 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700103
Austin Schuh39788ff2019-12-01 18:22:57 -0800104 // Fetches the next message in the queue without blocking. Returns true if
105 // there was a new message and we got it.
106 bool FetchNext();
107
108 // Fetches the latest message without blocking.
109 bool Fetch();
110
111 // Returns the channel this fetcher uses.
112 const Channel *channel() const { return channel_; }
113 // Returns the context for the current message.
114 const Context &context() const { return context_; }
115
116 protected:
117 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700118 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh39788ff2019-12-01 18:22:57 -0800119
Alex Perrycb7da4b2019-08-28 19:35:56 -0700120 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800121
122 private:
123 friend class EventLoop;
124 // Implementation
125 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
126 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
127
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500128 EventLoop *const event_loop_;
129 const Channel *const channel_;
130 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800131
132 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500133 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700134};
135
Austin Schuhe0ab4de2023-05-03 08:05:08 -0700136using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
137
138// Holds storage for a span object and the data referenced by that span for
139// compatibility with SharedSpan users. If constructed with MakeSharedSpan, span
140// points to only the aligned segment of the entire data.
141struct AlignedOwningSpan {
142 AlignedOwningSpan(absl::Span<const uint8_t> new_span) : span(new_span) {}
143
144 AlignedOwningSpan(const AlignedOwningSpan &) = delete;
145 AlignedOwningSpan &operator=(const AlignedOwningSpan &) = delete;
146 absl::Span<const uint8_t> span;
147 char *data() { return reinterpret_cast<char *>(this + 1); }
148};
149
150// Constructs a span which owns its data through a shared_ptr. The owning span
151// points to a const view of the data; also returns a temporary mutable span
152// which is only valid while the const shared span is kept alive.
153std::pair<SharedSpan, absl::Span<uint8_t>> MakeSharedSpan(size_t size);
154
Alex Perrycb7da4b2019-08-28 19:35:56 -0700155// Raw version of sender. Sends a block of data. This is used for reflection
156// and as a building block to implement typed senders.
157class RawSender {
158 public:
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700159 using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
160
Brian Silverman183859c2022-05-14 02:03:06 -0700161 // This looks a little ugly with no space, but please leave it so clang-format
162 // doesn't keep changing it. Bug is filed at
163 // <https://github.com/llvm/llvm-project/issues/55457>.
164 enum class [[nodiscard]] Error{
milind1f1dca32021-07-03 13:50:07 -0700165 // Represents success and no error
166 kOk,
167
168 // Error for messages on channels being sent faster than their
169 // frequency and channel storage duration allow
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700170 kMessagesSentTooFast,
171 // Access to Redzone was attempted in Sender Queue
Brian Silverman183859c2022-05-14 02:03:06 -0700172 kInvalidRedzone,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700173 };
milind1f1dca32021-07-03 13:50:07 -0700174
Austin Schuh39788ff2019-12-01 18:22:57 -0800175 RawSender(EventLoop *event_loop, const Channel *channel);
176 RawSender(const RawSender &) = delete;
177 RawSender &operator=(const RawSender &) = delete;
178
179 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700180
Brian Silverman9809c5f2022-07-23 16:12:23 -0700181 // Returns the buffer to write new messages into. This is always valid, and
182 // may change after calling any of the Send functions.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700183 virtual void *data() = 0;
184 virtual size_t size() = 0;
milind1f1dca32021-07-03 13:50:07 -0700185
186 // Sends a message without copying it. The users starts by copying up to
187 // size() bytes into the data backed by data(). They then call Send to send.
188 // Returns Error::kOk on a successful send, or
189 // Error::kMessagesSentTooFast if messages were sent too fast. If provided,
190 // monotonic_remote_time, realtime_remote_time, and remote_queue_index are
191 // attached to the message and are available in the context on the read side.
192 // If they are not populated, the read side will get the sent times instead.
193 Error Send(size_t size);
194 Error Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
195 realtime_clock::time_point realtime_remote_time,
196 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700197
198 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800199 // The remote arguments have the same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700200 // Returns Error::kMessagesSentTooFast if messages were sent too fast
201 Error Send(const void *data, size_t size);
202 Error Send(const void *data, size_t size,
203 monotonic_clock::time_point monotonic_remote_time,
204 realtime_clock::time_point realtime_remote_time,
205 uint32_t remote_queue_index, const UUID &source_boot_uuid);
206
207 // CHECKs that no sending Error occurred and logs the channel_ data if
208 // one did
209 void CheckOk(const Error err);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700211 // Sends a single block of data by refcounting it to avoid copies. The data
212 // must not change after being passed into Send. The remote arguments have the
213 // same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700214 Error Send(const SharedSpan data);
215 Error Send(const SharedSpan data,
216 monotonic_clock::time_point monotonic_remote_time,
217 realtime_clock::time_point realtime_remote_time,
218 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700219
Austin Schuh54cf95f2019-11-29 13:14:18 -0800220 const Channel *channel() const { return channel_; }
221
Austin Schuhad154822019-12-27 15:45:13 -0800222 // Returns the time_points that the last message was sent at.
223 aos::monotonic_clock::time_point monotonic_sent_time() const {
224 return monotonic_sent_time_;
225 }
226 aos::realtime_clock::time_point realtime_sent_time() const {
227 return realtime_sent_time_;
228 }
229 // Returns the queue index that this was sent with.
230 uint32_t sent_queue_index() const { return sent_queue_index_; }
231
Brian Silvermana1652f32020-01-29 20:41:44 -0800232 // Returns the associated flatbuffers-style allocator. This must be
233 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800234 ChannelPreallocatedAllocator *fbb_allocator() {
235 fbb_allocator_ = ChannelPreallocatedAllocator(
236 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800237 return &fbb_allocator_;
238 }
239
Brian Silverman4f4e0612020-08-12 19:54:41 -0700240 // Index of the buffer which is currently exposed by data() and the various
241 // other accessors. This is the message the caller should be filling out.
242 virtual int buffer_index() = 0;
243
Alex Perrycb7da4b2019-08-28 19:35:56 -0700244 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800245 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700246 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800247
Austin Schuhb5c6f972021-03-14 21:53:07 -0700248 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
249 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800250 uint32_t sent_queue_index_ = 0xffffffff;
251
Austin Schuh39788ff2019-12-01 18:22:57 -0800252 private:
253 friend class EventLoop;
254
milind1f1dca32021-07-03 13:50:07 -0700255 virtual Error DoSend(const void *data, size_t size,
256 monotonic_clock::time_point monotonic_remote_time,
257 realtime_clock::time_point realtime_remote_time,
258 uint32_t remote_queue_index,
259 const UUID &source_boot_uuid) = 0;
260 virtual Error DoSend(size_t size,
261 monotonic_clock::time_point monotonic_remote_time,
262 realtime_clock::time_point realtime_remote_time,
263 uint32_t remote_queue_index,
264 const UUID &source_boot_uuid) = 0;
265 virtual Error DoSend(const SharedSpan data,
266 monotonic_clock::time_point monotonic_remote_time,
267 realtime_clock::time_point realtime_remote_time,
268 uint32_t remote_queue_index,
269 const UUID &source_boot_uuid);
Austin Schuh39788ff2019-12-01 18:22:57 -0800270
James Kuszmaul93abac12022-04-14 15:05:10 -0700271 void RecordSendResult(const Error error, size_t message_size);
272
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500273 EventLoop *const event_loop_;
274 const Channel *const channel_;
275 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700276
Austin Schuh39788ff2019-12-01 18:22:57 -0800277 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500278 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800279
Austin Schuh1af273d2020-03-07 20:11:34 -0800280 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800281};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700282
milind1f1dca32021-07-03 13:50:07 -0700283// Needed for compatibility with glog
284std::ostream &operator<<(std::ostream &os, const RawSender::Error err);
285
Alex Perrycb7da4b2019-08-28 19:35:56 -0700286// Fetches the newest message from a channel.
287// This provides a polling based interface for channels.
288template <typename T>
289class Fetcher {
290 public:
291 Fetcher() {}
292
293 // Fetches the next message. Returns true if it fetched a new message. This
294 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800295 bool FetchNext() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800296 const bool result = CHECK_NOTNULL(fetcher_)->FetchNext();
Brian Silvermana1652f32020-01-29 20:41:44 -0800297 if (result) {
298 CheckChannelDataAlignment(fetcher_->context().data,
299 fetcher_->context().size);
300 }
301 return result;
302 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303
304 // Fetches the most recent message. Returns true if it fetched a new message.
305 // This will return the latest message regardless of if it was sent before or
306 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800307 bool Fetch() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800308 const bool result = CHECK_NOTNULL(fetcher_)->Fetch();
Brian Silvermana1652f32020-01-29 20:41:44 -0800309 if (result) {
310 CheckChannelDataAlignment(fetcher_->context().data,
311 fetcher_->context().size);
312 }
313 return result;
314 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700315
316 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
317 // available message.
318 const T *get() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800319 return CHECK_NOTNULL(fetcher_)->context().data != nullptr
Austin Schuh39788ff2019-12-01 18:22:57 -0800320 ? flatbuffers::GetRoot<T>(
321 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700322 : nullptr;
323 }
324
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700325 // Returns the channel this fetcher uses
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800326 const Channel *channel() const { return CHECK_NOTNULL(fetcher_)->channel(); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700327
Alex Perrycb7da4b2019-08-28 19:35:56 -0700328 // Returns the context holding timestamps and other metadata about the
329 // message.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800330 const Context &context() const { return CHECK_NOTNULL(fetcher_)->context(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331
332 const T &operator*() const { return *get(); }
333 const T *operator->() const { return get(); }
334
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800335 // Returns true if this fetcher is valid and connected to a channel. If you,
336 // e.g., are using TryMakeFetcher, then you must check valid() before
337 // attempting to use the Fetcher.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700338 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700339
Austin Schuhca75b6a2020-12-15 21:12:24 -0800340 // Copies the current flatbuffer into a FlatbufferVector.
341 FlatbufferVector<T> CopyFlatBuffer() const {
342 return context().template CopyFlatBuffer<T>();
343 }
344
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 private:
346 friend class EventLoop;
347 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
348 : fetcher_(::std::move(fetcher)) {}
349 ::std::unique_ptr<RawFetcher> fetcher_;
350};
351
352// Sends messages to a channel.
353template <typename T>
354class Sender {
355 public:
356 Sender() {}
357
358 // Represents a single message about to be sent to the queue.
359 // The lifecycle goes:
360 //
361 // Builder builder = sender.MakeBuilder();
362 // T::Builder t_builder = builder.MakeBuilder<T>();
363 // Populate(&t_builder);
364 // builder.Send(t_builder.Finish());
365 class Builder {
366 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800367 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800368 : fbb_(allocator->size(), allocator),
369 allocator_(allocator),
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800370 sender_(CHECK_NOTNULL(sender)) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800371 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800372 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700373 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800374 Builder() {}
375 Builder(const Builder &) = delete;
376 Builder(Builder &&) = default;
377
378 Builder &operator=(const Builder &) = delete;
379 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700380
381 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
382
383 template <typename T2>
384 typename T2::Builder MakeBuilder() {
385 return typename T2::Builder(fbb_);
386 }
387
milind1f1dca32021-07-03 13:50:07 -0700388 RawSender::Error Send(flatbuffers::Offset<T> offset) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700389 fbb_.Finish(offset);
milind1f1dca32021-07-03 13:50:07 -0700390 const auto err = sender_->Send(fbb_.GetSize());
Brian Silverman9dd793b2020-01-31 23:52:21 -0800391 // Ensure fbb_ knows it shouldn't access the memory any more.
392 fbb_ = flatbuffers::FlatBufferBuilder();
milind1f1dca32021-07-03 13:50:07 -0700393 return err;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394 }
395
milind1f1dca32021-07-03 13:50:07 -0700396 // Equivalent to RawSender::CheckOk
397 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
398
Alex Perrycb7da4b2019-08-28 19:35:56 -0700399 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800400 void CheckSent() {
401 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
402 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700403
Brian Silverman341b57e2020-06-23 16:23:18 -0700404 // Detaches a buffer, for later use calling Sender::Send directly.
405 //
406 // Note that the underlying memory remains with the Sender, so creating
407 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
408 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
409 fbb_.Finish(offset);
410 return fbb_.Release();
411 }
412
Alex Perrycb7da4b2019-08-28 19:35:56 -0700413 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700414 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800415 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700416 RawSender *sender_;
417 };
418
419 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800420 //
421 // Only a single one of these may be "alive" for this object at any point in
422 // time. After calling Send on the result, it is no longer "alive". This means
423 // that you must manually reset a variable holding the return value (by
424 // assigning a default-constructed Builder to it) before calling this method
425 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426 Builder MakeBuilder();
427
Austin Schuha28cbc32019-12-27 16:28:04 -0800428 // Sends a prebuilt flatbuffer.
James Kuszmaulad523042022-10-05 16:47:33 -0700429 // This will copy the data out of the provided flatbuffer, and so does not
430 // have to correspond to an existing Builder.
milind1f1dca32021-07-03 13:50:07 -0700431 RawSender::Error Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800432
Brian Silverman341b57e2020-06-23 16:23:18 -0700433 // Sends a prebuilt flatbuffer which was detached from a Builder created via
434 // MakeBuilder() on this object.
milind1f1dca32021-07-03 13:50:07 -0700435 RawSender::Error SendDetached(FlatbufferDetachedBuffer<T> detached);
436
437 // Equivalent to RawSender::CheckOk
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800438 void CheckOk(const RawSender::Error err) {
439 CHECK_NOTNULL(sender_)->CheckOk(err);
440 };
Brian Silverman341b57e2020-06-23 16:23:18 -0700441
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800442 // Returns the name of the underlying queue, if valid. You must check valid()
443 // first.
444 const Channel *channel() const { return CHECK_NOTNULL(sender_)->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700445
James Kuszmaulad523042022-10-05 16:47:33 -0700446 // Returns true if the Sender is a valid Sender. If you, e.g., are using
447 // TryMakeSender, then you must check valid() before attempting to use the
448 // Sender.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800449 // TODO(austin): Deprecate the operator bool.
Austin Schuha0c41ba2020-09-10 22:59:14 -0700450 operator bool() const { return sender_ ? true : false; }
Austin Schuhe33c08d2022-02-03 18:15:21 -0800451 bool valid() const { return static_cast<bool>(sender_); }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800452
Austin Schuh7bc59052020-02-16 23:48:33 -0800453 // Returns the time_points that the last message was sent at.
454 aos::monotonic_clock::time_point monotonic_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800455 return CHECK_NOTNULL(sender_)->monotonic_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800456 }
457 aos::realtime_clock::time_point realtime_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800458 return CHECK_NOTNULL(sender_)->realtime_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800459 }
460 // Returns the queue index that this was sent with.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800461 uint32_t sent_queue_index() const {
462 return CHECK_NOTNULL(sender_)->sent_queue_index();
463 }
Austin Schuh7bc59052020-02-16 23:48:33 -0800464
Brian Silverman4f4e0612020-08-12 19:54:41 -0700465 // Returns the buffer index which MakeBuilder() will expose access to. This is
466 // the buffer the caller can fill out.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800467 int buffer_index() const { return CHECK_NOTNULL(sender_)->buffer_index(); }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700468
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469 private:
470 friend class EventLoop;
471 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
472 std::unique_ptr<RawSender> sender_;
473};
474
milind1f1dca32021-07-03 13:50:07 -0700475// Class for keeping a count of send failures on a certain channel
476class SendFailureCounter {
477 public:
478 inline void Count(const RawSender::Error err) {
479 failures_ += static_cast<size_t>(err != RawSender::Error::kOk);
480 just_failed_ = (err != RawSender::Error::kOk);
481 }
482
483 inline size_t failures() const { return failures_; }
484 inline bool just_failed() const { return just_failed_; }
485
486 private:
487 size_t failures_ = 0;
488 bool just_failed_ = false;
489};
490
Brian Silverman4f4e0612020-08-12 19:54:41 -0700491// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492class TimerHandler {
493 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800494 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700495
496 // Timer should sleep until base, base + offset, base + offset * 2, ...
497 // If repeat_offset isn't set, the timer only expires once.
James Kuszmaul8866e642022-06-10 16:00:36 -0700498 // base must be greater than or equal to zero.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700499 virtual void Setup(monotonic_clock::time_point base,
500 monotonic_clock::duration repeat_offset =
501 ::aos::monotonic_clock::zero()) = 0;
502
503 // Stop future calls to callback().
504 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800505
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700506 // Check if the timer is disabled
507 virtual bool IsDisabled() = 0;
508
Austin Schuh1540c2f2019-11-29 21:59:29 -0800509 // Sets and gets the name of the timer. Set this if you want a descriptive
510 // name in the timing report.
511 void set_name(std::string_view name) { name_ = std::string(name); }
512 const std::string_view name() const { return name_; }
513
Austin Schuh39788ff2019-12-01 18:22:57 -0800514 protected:
515 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
516
Austin Schuh9b1d6282022-06-10 17:03:21 -0700517 template <typename T>
518 monotonic_clock::time_point Call(T get_time,
519 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800520
Austin Schuh1540c2f2019-11-29 21:59:29 -0800521 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800522 friend class EventLoop;
523
524 EventLoop *event_loop_;
525 // The function to call when Call is called.
526 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800527 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800528
529 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500530 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700531};
532
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800533// Interface for phased loops. They are built on timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700534class PhasedLoopHandler {
535 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800536 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800538 // Sets the interval and offset. Any changes to interval and offset only take
539 // effect when the handler finishes running or upon a call to Reschedule().
540 //
541 // The precise semantics of the monotonic_now parameter are defined in
542 // phased_loop.h. The way that it gets used in this interface is to control
543 // what the cycles elapsed counter will read on the following call to your
544 // handler. In an idealized simulation environment, if you call
545 // set_interval_and_offset() during the phased loop offset without setting
546 // monotonic_now, then you should always see a count of 1 on the next cycle.
547 //
548 // With the default behavior (this is called inside your handler and with
549 // monotonic_now = nullopt), the next phased loop call will occur at most
550 // interval time after the current time. Note that in many cases this will
551 // *not* be the preferred behavior (in most cases, you would likely aim to
552 // keep the average frequency of the calls reasonably consistent).
553 //
554 // A combination of the monotonic_now parameter and manually calling
555 // Reschedule() outside of the phased loop handler can be used to alter the
556 // behavior of cycles_elapsed. For the default behavior, you can set
557 // monotonic_now to the current time. If you call set_interval_and_offset()
558 // and Reschedule() with the same monotonic_now, that will cause the next
559 // callback to occur in the range (monotonic_now, monotonic_now + interval]
560 // and get called with a count of 1 (if the event is actually able to happen
561 // when it is scheduled to). E.g., if you are just adjusting the phased loop
562 // offset (but not the interval) and want to maintain a consistent frequency,
563 // you may call these functions with monotonic_now = now + interval / 2.
564 void set_interval_and_offset(
565 const monotonic_clock::duration interval,
566 const monotonic_clock::duration offset,
567 std::optional<monotonic_clock::time_point> monotonic_now = std::nullopt) {
568 phased_loop_.set_interval_and_offset(interval, offset, monotonic_now);
Austin Schuh39788ff2019-12-01 18:22:57 -0800569 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800570
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800571 // Reruns the scheduler for the phased loop, scheduling the next callback at
572 // the next available time after monotonic_now. This allows
573 // set_interval_and_offset() to be called and have the changes take effect
574 // before the next handler finishes. This will have no effect if run during
575 // the phased loop's own handler.
576 void Reschedule(monotonic_clock::time_point monotonic_now) {
577 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
578 Schedule(phased_loop_.sleep_time());
579 }
580
581 // Sets and gets the name of the timer. Set this if you want a descriptive
Austin Schuh1540c2f2019-11-29 21:59:29 -0800582 // name in the timing report.
583 void set_name(std::string_view name) { name_ = std::string(name); }
584 const std::string_view name() const { return name_; }
585
Austin Schuh39788ff2019-12-01 18:22:57 -0800586 protected:
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800587 void Call(std::function<monotonic_clock::time_point()> get_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800588
589 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
590 const monotonic_clock::duration interval,
591 const monotonic_clock::duration offset);
592
Austin Schuh1540c2f2019-11-29 21:59:29 -0800593 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800594 friend class EventLoop;
595
Austin Schuh39788ff2019-12-01 18:22:57 -0800596 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
597
598 EventLoop *event_loop_;
599 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800600 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800601 time::PhasedLoop phased_loop_;
602
603 int cycles_elapsed_ = 0;
604
605 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500606 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700607};
608
Austin Schuh3054f5f2021-07-21 15:38:01 -0700609// Note, it is supported to create only:
610// multiple fetchers, and (one sender or one watcher) per <name, type>
611// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700612class EventLoop {
613 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700614 // Holds configuration by reference for the lifetime of this object. It may
615 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800616 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700617
Austin Schuh39788ff2019-12-01 18:22:57 -0800618 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700619
620 // Current time.
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800621 virtual monotonic_clock::time_point monotonic_now() const = 0;
622 virtual realtime_clock::time_point realtime_now() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700623
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700624 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800625 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800626 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800627 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800628 true);
629 }
milind1f1dca32021-07-03 13:50:07 -0700630 // Returns true if the channel exists in the configuration.
Austin Schuha0654152021-02-21 21:38:24 -0800631 template <typename T>
632 bool HasChannel(const std::string_view channel_name) {
633 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700634 }
635
Brian Silverman631b6262021-11-10 12:25:08 -0800636 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800637 // not readable on this node or does not exist. You must check valid() on the
638 // Fetcher before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800639 template <typename T>
640 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
641 const Channel *const channel = GetChannel<T>(channel_name);
642 if (channel == nullptr) {
643 return Fetcher<T>();
644 }
645
646 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
647 return Fetcher<T>();
648 }
649
650 return Fetcher<T>(MakeRawFetcher(channel));
651 }
652
Alex Perrycb7da4b2019-08-28 19:35:56 -0700653 // Makes a class that will always fetch the most recent value
654 // sent to the provided channel.
655 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800656 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800657 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700658 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
659 << T::GetFullyQualifiedName() << "\" } not found in config.";
660
Brian Silverman631b6262021-11-10 12:25:08 -0800661 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
662 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800663 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
664 << "\", \"type\": \"" << T::GetFullyQualifiedName()
665 << "\" } is not able to be fetched on this node. Check your "
666 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800667 }
668
Brian Silverman631b6262021-11-10 12:25:08 -0800669 return result;
670 }
671
672 // Like MakeSender, but returns an invalid sender if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800673 // not sendable on this node or does not exist. You must check valid() on the
674 // Sender before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800675 template <typename T>
676 Sender<T> TryMakeSender(const std::string_view channel_name) {
677 const Channel *channel = GetChannel<T>(channel_name);
678 if (channel == nullptr) {
679 return Sender<T>();
680 }
681
682 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
683 return Sender<T>();
684 }
685
686 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700687 }
688
689 // Makes class that allows constructing and sending messages to
690 // the provided channel.
691 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800692 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800693 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700694 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800695 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700696 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800697 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700698 ? absl::StrCat(" on node ", node()->name()->string_view())
699 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700700
Brian Silverman631b6262021-11-10 12:25:08 -0800701 Sender<T> result = TryMakeSender<T>(channel_name);
702 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800703 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
704 << "\", \"type\": \"" << T::GetFullyQualifiedName()
705 << "\" } is not able to be sent on this node. Check your "
706 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800707 }
708
Brian Silverman631b6262021-11-10 12:25:08 -0800709 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700710 }
711
712 // This will watch messages sent to the provided channel.
713 //
Brian Silverman454bc112020-03-05 14:21:25 -0800714 // w must have a non-polymorphic operator() (aka it can only be called with a
715 // single set of arguments; no overloading or templates). It must be callable
716 // with this signature:
717 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700718 //
Brian Silverman454bc112020-03-05 14:21:25 -0800719 // Lambdas are a common form for w. A std::function will work too.
720 //
721 // Note that bind expressions have polymorphic call operators, so they are not
722 // allowed.
723 //
724 // We template Watch as a whole instead of using std::function<void(const T
725 // &)> to allow deducing MessageType from lambdas and other things which are
726 // implicitly convertible to std::function, but not actually std::function
727 // instantiations. Template deduction guides might allow solving this
728 // differently in newer versions of C++, but those have their own corner
729 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700730 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800731 void MakeWatcher(const std::string_view channel_name, Watch &&w);
732
733 // Like MakeWatcher, but doesn't have access to the message data. This may be
734 // implemented to use less resources than an equivalent MakeWatcher.
735 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800736 // The function will still have access to context(), although that will have
737 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800738 template <typename MessageType>
739 void MakeNoArgWatcher(const std::string_view channel_name,
740 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700741
742 // The passed in function will be called when the event loop starts.
743 // Use this to run code once the thread goes into "real-time-mode",
744 virtual void OnRun(::std::function<void()> on_run) = 0;
745
Austin Schuh217a9782019-12-21 23:02:50 -0800746 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800747 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700748
Austin Schuh217a9782019-12-21 23:02:50 -0800749 // Returns the node that this event loop is running on. Returns nullptr if we
750 // are running in single-node mode.
751 virtual const Node *node() const = 0;
752
Alex Perrycb7da4b2019-08-28 19:35:56 -0700753 // Creates a timer that executes callback when the timer expires
754 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700755 // TODO(milind): callback should take the number of cycles elapsed as a
756 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700757 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
758
759 // Creates a timer that executes callback periodically at the specified
760 // interval and offset. Returns a PhasedLoopHandler for interacting with the
761 // timer.
762 virtual PhasedLoopHandler *AddPhasedLoop(
763 ::std::function<void(int)> callback,
764 const monotonic_clock::duration interval,
765 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
766
Austin Schuh217a9782019-12-21 23:02:50 -0800767 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700768
Austin Schuh3054f5f2021-07-21 15:38:01 -0700769 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700770 bool is_running() const { return is_running_.load(); }
771
772 // Sets the scheduler priority to run the event loop at. This may not be
773 // called after we go into "real-time-mode".
774 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700775 // Defaults to 0 if this loop will not run realtime.
776 virtual int runtime_realtime_priority() const = 0;
777
Austin Schuh070019a2022-12-20 22:23:09 -0800778 static cpu_set_t DefaultAffinity();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700779
Brian Silverman6a54ff32020-04-28 16:41:39 -0700780 // Sets the scheduler affinity to run the event loop with. This may only be
781 // called before Run().
782 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700783 // Defaults to DefaultAffinity() if this loop will not run pinned.
784 virtual const cpu_set_t &runtime_affinity() const = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700785
Austin Schuh217a9782019-12-21 23:02:50 -0800786 // Fetches new messages from the provided channel (path, type).
787 //
788 // Note: this channel must be a member of the exact configuration object this
789 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700790 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
791 const Channel *channel) = 0;
792
Austin Schuh217a9782019-12-21 23:02:50 -0800793 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700794 virtual void MakeRawWatcher(
795 const Channel *channel,
796 std::function<void(const Context &context, const void *message)>
797 watcher) = 0;
798
Brian Silverman454bc112020-03-05 14:21:25 -0800799 // Watches channel (name, type) for new messages, without needing to extract
800 // the message contents. Default implementation simply re-uses MakeRawWatcher.
801 virtual void MakeRawNoArgWatcher(
802 const Channel *channel,
803 std::function<void(const Context &context)> watcher) {
804 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800805 Context new_context = context;
806 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700807 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800808 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800809 });
810 }
811
Austin Schuh217a9782019-12-21 23:02:50 -0800812 // Creates a raw sender for the provided channel. This is used for reflection
813 // based sending.
814 // Note: this ignores any node constraints. Ignore at your own peril.
815 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
816
Austin Schuh6231cc32019-12-07 13:06:15 -0800817 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700818 const Context &context() const { return context_; }
819
820 // Returns the configuration that this event loop was built with.
821 const Configuration *configuration() const { return configuration_; }
822
Austin Schuh39788ff2019-12-01 18:22:57 -0800823 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800824 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800825
Brian Silverman4f4e0612020-08-12 19:54:41 -0700826 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800827 void SkipAosLog() { skip_logger_ = true; }
828
Brian Silverman4f4e0612020-08-12 19:54:41 -0700829 // Returns the number of buffers for this channel. This corresponds with the
830 // range of Context::buffer_index values for this channel.
831 virtual int NumberBuffers(const Channel *channel) = 0;
832
Austin Schuh20ac95d2020-12-05 17:24:19 -0800833 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800834 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800835
Alex Perrycb7da4b2019-08-28 19:35:56 -0700836 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800837 // Sets the name of the event loop. This is the application name.
838 virtual void set_name(const std::string_view name) = 0;
839
Alex Perrycb7da4b2019-08-28 19:35:56 -0700840 void set_is_running(bool value) { is_running_.store(value); }
841
Austin Schuh39788ff2019-12-01 18:22:57 -0800842 // Validates that channel exists inside configuration_ and finds its index.
843 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700844
Brian Silverman5120afb2020-01-31 17:44:35 -0800845 // Returns the state for the watcher on the corresponding channel. This
846 // watcher must exist before calling this.
847 WatcherState *GetWatcherState(const Channel *channel);
848
Brian Silverman6d2b3592020-06-18 14:40:15 -0700849 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800850 template <typename T>
851 static RawSender *GetRawSender(aos::Sender<T> *sender) {
852 return sender->sender_.get();
853 }
854
Brian Silverman6d2b3592020-06-18 14:40:15 -0700855 // Returns a Fetcher's protected RawFetcher.
856 template <typename T>
857 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
858 return fetcher->fetcher_.get();
859 }
860
Austin Schuh6231cc32019-12-07 13:06:15 -0800861 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700862 Context context_;
863
Austin Schuh39788ff2019-12-01 18:22:57 -0800864 friend class RawSender;
865 friend class TimerHandler;
866 friend class RawFetcher;
867 friend class PhasedLoopHandler;
868 friend class WatcherState;
869
870 // Methods used to implement timing reports.
871 void NewSender(RawSender *sender);
872 void DeleteSender(RawSender *sender);
873 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
874 PhasedLoopHandler *NewPhasedLoop(
875 std::unique_ptr<PhasedLoopHandler> phased_loop);
876 void NewFetcher(RawFetcher *fetcher);
877 void DeleteFetcher(RawFetcher *fetcher);
878 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
879
Brian Silverman0fc69932020-01-24 21:54:02 -0800880 // Tracks that we have a (single) watcher on the given channel.
881 void TakeWatcher(const Channel *channel);
882 // Tracks that we have at least one sender on the given channel.
883 void TakeSender(const Channel *channel);
884
Austin Schuh39788ff2019-12-01 18:22:57 -0800885 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800886 std::vector<RawFetcher *> fetchers_;
887
Austin Schuh39788ff2019-12-01 18:22:57 -0800888 std::vector<std::unique_ptr<TimerHandler>> timers_;
889 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800890 std::vector<std::unique_ptr<WatcherState>> watchers_;
891
Brian Silvermance418d02021-11-03 11:25:52 -0700892 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800893 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700894
Austin Schuh39788ff2019-12-01 18:22:57 -0800895 void UpdateTimingReport();
896 void MaybeScheduleTimingReports();
897
898 std::unique_ptr<RawSender> timing_report_sender_;
899
Austin Schuh7d87b672019-12-01 20:23:49 -0800900 // Tracks which event sources (timers and watchers) have data, and which
901 // don't. Added events may not change their event_time().
902 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
903 // t2 to run, t2 should then be picked up without a context switch.
904 void AddEvent(EventLoopEvent *event);
905 void RemoveEvent(EventLoopEvent *event);
906 size_t EventCount() const { return events_.size(); }
907 EventLoopEvent *PopEvent();
908 EventLoopEvent *PeekEvent() { return events_.front(); }
909 void ReserveEvents();
910
911 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700912 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800913
Tyler Chatow67ddb032020-01-12 14:30:04 -0800914 // If true, don't send AOS_LOG to /aos
915 bool skip_logger_ = false;
916
Austin Schuha9012be2021-07-21 15:19:11 -0700917 // Sets context_ for a timed event which is supposed to happen at the provided
918 // time.
919 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
Austin Schuh0debde12022-08-17 16:25:17 -0700920 // Clears context_ so it only has invalid times and elements in it.
921 void ClearContext();
Austin Schuha9012be2021-07-21 15:19:11 -0700922
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800923 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800924 virtual pid_t GetTid() = 0;
925
926 FlatbufferDetachedBuffer<timing::Report> timing_report_;
927
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800928 ::std::atomic<bool> is_running_{false};
929
Alex Perrycb7da4b2019-08-28 19:35:56 -0700930 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800931
932 // If true, don't send out timing reports.
933 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800934
milind1f1dca32021-07-03 13:50:07 -0700935 SendFailureCounter timing_report_failure_counter_;
936
Brian Silverman0fc69932020-01-24 21:54:02 -0800937 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700938};
939
Brian Silvermane1fe2512022-08-14 23:18:50 -0700940// Interface for terminating execution of an EventLoop.
941//
942// Prefer this over binding a lambda to an Exit() method when passing ownership
943// in complicated ways because implementations should have assertions to catch
944// it outliving the object it's referring to, instead of having a
945// use-after-free.
946//
947// This is not exposed by EventLoop directly because different EventLoop
948// implementations provide this functionality at different scopes, or possibly
949// not at all.
950class ExitHandle {
951 public:
952 ExitHandle() = default;
953 virtual ~ExitHandle() = default;
954
955 // Exits some set of event loops. Details depend on the implementation.
956 //
957 // This means no more events will be processed, but any currently being
958 // processed will finish.
959 virtual void Exit() = 0;
960};
961
Alex Perrycb7da4b2019-08-28 19:35:56 -0700962} // namespace aos
963
Austin Schuhb8075812020-10-19 09:36:49 -0700964#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700965
966#endif // AOS_EVENTS_EVENT_LOOP_H