blob: 1ff0fb78181fe51954b2f71fe417af084ad6a1ed [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 Schuh82ea7382023-07-14 15:17:34 -070018#include "aos/events/context.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080019#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080020#include "aos/events/event_loop_generated.h"
21#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070022#include "aos/flatbuffers.h"
James Kuszmaulb1c11052023-11-06 13:20:53 -080023#include "aos/flatbuffers/builder.h"
Brian Silverman79ec7fc2020-06-08 20:11:22 -050024#include "aos/ftrace.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080025#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070026#include "aos/json_to_flatbuffer.h"
27#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080028#include "aos/util/phased_loop.h"
Austin Schuh4385b142021-03-14 21:31:13 -070029#include "aos/uuid.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070030
Austin Schuh39788ff2019-12-01 18:22:57 -080031DECLARE_bool(timing_reports);
32DECLARE_int32(timing_report_ms);
33
Alex Perrycb7da4b2019-08-28 19:35:56 -070034namespace aos {
35
Austin Schuh39788ff2019-12-01 18:22:57 -080036class EventLoop;
37class WatcherState;
38
Alex Perrycb7da4b2019-08-28 19:35:56 -070039// Raw version of fetcher. Contains a local variable that the fetcher will
40// update. This is used for reflection and as an interface to implement typed
41// fetchers.
42class RawFetcher {
43 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080044 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070045 RawFetcher(const RawFetcher &) = delete;
46 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080047 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070048
Austin Schuh39788ff2019-12-01 18:22:57 -080049 // Fetches the next message in the queue without blocking. Returns true if
50 // there was a new message and we got it.
51 bool FetchNext();
Austin Schuh98ed26f2023-07-19 14:12:28 -070052 // Fetches the next message if there is one, and the provided function returns
53 // true. The data and buffer_index are the only pieces of the Context which
54 // are zeroed out. The function must be valid.
55 bool FetchNextIf(std::function<bool(const Context &context)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080056
57 // Fetches the latest message without blocking.
58 bool Fetch();
Austin Schuh98ed26f2023-07-19 14:12:28 -070059 // Fetches the latest message conditionally without blocking. fn must be
60 // valid.
61 bool FetchIf(std::function<bool(const Context &context)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080062
63 // Returns the channel this fetcher uses.
64 const Channel *channel() const { return channel_; }
65 // Returns the context for the current message.
66 const Context &context() const { return context_; }
67
68 protected:
69 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -070070 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh39788ff2019-12-01 18:22:57 -080071
Alex Perrycb7da4b2019-08-28 19:35:56 -070072 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080073
74 private:
75 friend class EventLoop;
76 // Implementation
77 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
Austin Schuh98ed26f2023-07-19 14:12:28 -070078 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNextIf(
79 std::function<bool(const Context &)> fn) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -080080 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
Austin Schuh98ed26f2023-07-19 14:12:28 -070081 virtual std::pair<bool, monotonic_clock::time_point> DoFetchIf(
82 std::function<bool(const Context &)> fn) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -080083
Brian Silverman79ec7fc2020-06-08 20:11:22 -050084 EventLoop *const event_loop_;
85 const Channel *const channel_;
86 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -080087
88 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -050089 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070090};
91
Austin Schuhe0ab4de2023-05-03 08:05:08 -070092using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
93
94// Holds storage for a span object and the data referenced by that span for
95// compatibility with SharedSpan users. If constructed with MakeSharedSpan, span
96// points to only the aligned segment of the entire data.
97struct AlignedOwningSpan {
98 AlignedOwningSpan(absl::Span<const uint8_t> new_span) : span(new_span) {}
99
100 AlignedOwningSpan(const AlignedOwningSpan &) = delete;
101 AlignedOwningSpan &operator=(const AlignedOwningSpan &) = delete;
102 absl::Span<const uint8_t> span;
103 char *data() { return reinterpret_cast<char *>(this + 1); }
104};
105
106// Constructs a span which owns its data through a shared_ptr. The owning span
107// points to a const view of the data; also returns a temporary mutable span
108// which is only valid while the const shared span is kept alive.
109std::pair<SharedSpan, absl::Span<uint8_t>> MakeSharedSpan(size_t size);
110
Alex Perrycb7da4b2019-08-28 19:35:56 -0700111// Raw version of sender. Sends a block of data. This is used for reflection
112// and as a building block to implement typed senders.
113class RawSender {
114 public:
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700115 using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
116
Austin Schuh50e3dca2023-07-23 14:34:27 -0700117 enum class [[nodiscard]] Error {
118 // Represents success and no error
119 kOk,
milind1f1dca32021-07-03 13:50:07 -0700120
Austin Schuh50e3dca2023-07-23 14:34:27 -0700121 // Error for messages on channels being sent faster than their
122 // frequency and channel storage duration allow
123 kMessagesSentTooFast,
124 // Access to Redzone was attempted in Sender Queue
125 kInvalidRedzone,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700126 };
milind1f1dca32021-07-03 13:50:07 -0700127
Austin Schuh39788ff2019-12-01 18:22:57 -0800128 RawSender(EventLoop *event_loop, const Channel *channel);
129 RawSender(const RawSender &) = delete;
130 RawSender &operator=(const RawSender &) = delete;
131
132 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700133
Brian Silverman9809c5f2022-07-23 16:12:23 -0700134 // Returns the buffer to write new messages into. This is always valid, and
135 // may change after calling any of the Send functions.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700136 virtual void *data() = 0;
137 virtual size_t size() = 0;
milind1f1dca32021-07-03 13:50:07 -0700138
139 // Sends a message without copying it. The users starts by copying up to
140 // size() bytes into the data backed by data(). They then call Send to send.
141 // Returns Error::kOk on a successful send, or
142 // Error::kMessagesSentTooFast if messages were sent too fast. If provided,
143 // monotonic_remote_time, realtime_remote_time, and remote_queue_index are
144 // attached to the message and are available in the context on the read side.
145 // If they are not populated, the read side will get the sent times instead.
146 Error Send(size_t size);
147 Error Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
148 realtime_clock::time_point realtime_remote_time,
149 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700150
151 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800152 // The remote arguments have the same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700153 // Returns Error::kMessagesSentTooFast if messages were sent too fast
154 Error Send(const void *data, size_t size);
155 Error Send(const void *data, size_t size,
156 monotonic_clock::time_point monotonic_remote_time,
157 realtime_clock::time_point realtime_remote_time,
158 uint32_t remote_queue_index, const UUID &source_boot_uuid);
159
160 // CHECKs that no sending Error occurred and logs the channel_ data if
161 // one did
162 void CheckOk(const Error err);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700163
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700164 // Sends a single block of data by refcounting it to avoid copies. The data
165 // must not change after being passed into Send. The remote arguments have the
166 // same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700167 Error Send(const SharedSpan data);
168 Error Send(const SharedSpan data,
169 monotonic_clock::time_point monotonic_remote_time,
170 realtime_clock::time_point realtime_remote_time,
171 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Austin Schuh54cf95f2019-11-29 13:14:18 -0800172 const Channel *channel() const { return channel_; }
173
Austin Schuhad154822019-12-27 15:45:13 -0800174 // Returns the time_points that the last message was sent at.
175 aos::monotonic_clock::time_point monotonic_sent_time() const {
176 return monotonic_sent_time_;
177 }
178 aos::realtime_clock::time_point realtime_sent_time() const {
179 return realtime_sent_time_;
180 }
181 // Returns the queue index that this was sent with.
182 uint32_t sent_queue_index() const { return sent_queue_index_; }
183
Brian Silvermana1652f32020-01-29 20:41:44 -0800184 // Returns the associated flatbuffers-style allocator. This must be
185 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800186 ChannelPreallocatedAllocator *fbb_allocator() {
James Kuszmaulb1c11052023-11-06 13:20:53 -0800187 CHECK(!static_allocator_.has_value())
188 << ": May not mix-and-match static and raw flatbuffer builders.";
189 if (fbb_allocator_.has_value()) {
190 CHECK(!fbb_allocator_.value().allocated())
191 << ": May not have multiple active allocators on a single sender.";
192 }
193 return &fbb_allocator_.emplace(reinterpret_cast<uint8_t *>(data()), size(),
194 channel());
195 }
196
197 fbs::SpanAllocator *static_allocator() {
198 CHECK(!fbb_allocator_.has_value())
199 << ": May not mix-and-match static and raw flatbuffer builders.";
200 return &static_allocator_.emplace(
201 std::span<uint8_t>{reinterpret_cast<uint8_t *>(data()), size()});
Brian Silvermana1652f32020-01-29 20:41:44 -0800202 }
203
Brian Silverman4f4e0612020-08-12 19:54:41 -0700204 // Index of the buffer which is currently exposed by data() and the various
205 // other accessors. This is the message the caller should be filling out.
206 virtual int buffer_index() = 0;
207
Alex Perrycb7da4b2019-08-28 19:35:56 -0700208 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800209 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700210 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800211
Austin Schuhb5c6f972021-03-14 21:53:07 -0700212 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
213 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800214 uint32_t sent_queue_index_ = 0xffffffff;
215
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 private:
217 friend class EventLoop;
218
milind1f1dca32021-07-03 13:50:07 -0700219 virtual Error DoSend(const void *data, size_t size,
220 monotonic_clock::time_point monotonic_remote_time,
221 realtime_clock::time_point realtime_remote_time,
222 uint32_t remote_queue_index,
223 const UUID &source_boot_uuid) = 0;
224 virtual Error DoSend(size_t size,
225 monotonic_clock::time_point monotonic_remote_time,
226 realtime_clock::time_point realtime_remote_time,
227 uint32_t remote_queue_index,
228 const UUID &source_boot_uuid) = 0;
229 virtual Error DoSend(const SharedSpan data,
230 monotonic_clock::time_point monotonic_remote_time,
231 realtime_clock::time_point realtime_remote_time,
232 uint32_t remote_queue_index,
233 const UUID &source_boot_uuid);
Austin Schuh39788ff2019-12-01 18:22:57 -0800234
James Kuszmaul93abac12022-04-14 15:05:10 -0700235 void RecordSendResult(const Error error, size_t message_size);
236
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500237 EventLoop *const event_loop_;
238 const Channel *const channel_;
239 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700240
Austin Schuh39788ff2019-12-01 18:22:57 -0800241 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500242 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800243
James Kuszmaulb1c11052023-11-06 13:20:53 -0800244 // Depending on which API is being used, we will populate either
245 // fbb_allocator_ (for use with FlatBufferBuilders) or the SpanAllocator (for
246 // use with the static flatbuffer API).
247 std::optional<ChannelPreallocatedAllocator> fbb_allocator_;
248 std::optional<fbs::SpanAllocator> static_allocator_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800249};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700250
milind1f1dca32021-07-03 13:50:07 -0700251// Needed for compatibility with glog
252std::ostream &operator<<(std::ostream &os, const RawSender::Error err);
253
Alex Perrycb7da4b2019-08-28 19:35:56 -0700254// Fetches the newest message from a channel.
255// This provides a polling based interface for channels.
256template <typename T>
257class Fetcher {
258 public:
259 Fetcher() {}
260
261 // Fetches the next message. Returns true if it fetched a new message. This
262 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800263 bool FetchNext() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800264 const bool result = CHECK_NOTNULL(fetcher_)->FetchNext();
Brian Silvermana1652f32020-01-29 20:41:44 -0800265 if (result) {
266 CheckChannelDataAlignment(fetcher_->context().data,
267 fetcher_->context().size);
268 }
269 return result;
270 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700271
Austin Schuh98ed26f2023-07-19 14:12:28 -0700272 // Fetches the next message if there is one, and the provided function returns
273 // true. The data and buffer_index are the only pieces of the Context which
274 // are zeroed out. The function must be valid.
275 bool FetchNextIf(std::function<bool(const Context &)> fn) {
276 const bool result = CHECK_NOTNULL(fetcher_)->FetchNextIf(std::move(fn));
277 if (result) {
278 CheckChannelDataAlignment(fetcher_->context().data,
279 fetcher_->context().size);
280 }
281 return result;
282 }
283
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284 // Fetches the most recent message. Returns true if it fetched a new message.
285 // This will return the latest message regardless of if it was sent before or
286 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800287 bool Fetch() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800288 const bool result = CHECK_NOTNULL(fetcher_)->Fetch();
Brian Silvermana1652f32020-01-29 20:41:44 -0800289 if (result) {
290 CheckChannelDataAlignment(fetcher_->context().data,
291 fetcher_->context().size);
292 }
293 return result;
294 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700295
Austin Schuh98ed26f2023-07-19 14:12:28 -0700296 // Fetches the most recent message conditionally. Returns true if it fetched a
297 // new message. This will return the latest message regardless of if it was
298 // sent before or after the fetcher was created. The function must be valid.
299 bool FetchIf(std::function<bool(const Context &)> fn) {
300 const bool result = CHECK_NOTNULL(fetcher_)->FetchIf(std::move(fn));
301 if (result) {
302 CheckChannelDataAlignment(fetcher_->context().data,
303 fetcher_->context().size);
304 }
305 return result;
306 }
307
Alex Perrycb7da4b2019-08-28 19:35:56 -0700308 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
309 // available message.
310 const T *get() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800311 return CHECK_NOTNULL(fetcher_)->context().data != nullptr
Austin Schuh39788ff2019-12-01 18:22:57 -0800312 ? flatbuffers::GetRoot<T>(
313 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700314 : nullptr;
315 }
316
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700317 // Returns the channel this fetcher uses
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800318 const Channel *channel() const { return CHECK_NOTNULL(fetcher_)->channel(); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700319
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320 // Returns the context holding timestamps and other metadata about the
321 // message.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800322 const Context &context() const { return CHECK_NOTNULL(fetcher_)->context(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700323
324 const T &operator*() const { return *get(); }
325 const T *operator->() const { return get(); }
326
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800327 // Returns true if this fetcher is valid and connected to a channel. If you,
328 // e.g., are using TryMakeFetcher, then you must check valid() before
329 // attempting to use the Fetcher.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700330 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700331
Austin Schuhca75b6a2020-12-15 21:12:24 -0800332 // Copies the current flatbuffer into a FlatbufferVector.
333 FlatbufferVector<T> CopyFlatBuffer() const {
334 return context().template CopyFlatBuffer<T>();
335 }
336
Alex Perrycb7da4b2019-08-28 19:35:56 -0700337 private:
338 friend class EventLoop;
339 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
340 : fetcher_(::std::move(fetcher)) {}
341 ::std::unique_ptr<RawFetcher> fetcher_;
342};
343
344// Sends messages to a channel.
James Kuszmaulb1c11052023-11-06 13:20:53 -0800345// The type T used with the Sender may either be a raw flatbuffer type (e.g.,
346// aos::examples::Ping) or the static flatbuffer type (e.g.
347// aos::examples::PingStatic). The Builder type that you use must correspond
348// with the flatbuffer type being used.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700349template <typename T>
350class Sender {
351 public:
352 Sender() {}
353
James Kuszmaulb1c11052023-11-06 13:20:53 -0800354 // Represents a single message that is about to be sent on the channel.
355 // Uses the static flatbuffer API rather than the FlatBufferBuilder paradigm.
356 //
357 // Typical usage pattern is:
358 //
359 // Sender<PingStatic>::Builder builder = sender.MakeStaticBuilder()
360 // builder.get()->set_value(971);
361 // builder.CheckOk(builder.Send());
362 class StaticBuilder {
363 public:
364 StaticBuilder(RawSender *sender, fbs::SpanAllocator *allocator)
365 : builder_(allocator), sender_(CHECK_NOTNULL(sender)) {}
366 StaticBuilder(const StaticBuilder &) = delete;
367 StaticBuilder(StaticBuilder &&) = default;
368
369 StaticBuilder &operator=(const StaticBuilder &) = delete;
370 StaticBuilder &operator=(StaticBuilder &&) = default;
371
372 fbs::Builder<T> *builder() {
373 DCHECK(builder_.has_value());
374 return &builder_.value();
375 }
376
377 T *get() { return builder()->get(); }
James Kuszmauldde65632023-12-07 16:12:26 -0800378 T &operator*() { return *get(); }
379 T *operator->() { return get(); }
James Kuszmaulb1c11052023-11-06 13:20:53 -0800380
381 RawSender::Error Send() {
382 const auto err = sender_->Send(builder_.value().buffer().size());
383 builder_.reset();
384 return err;
385 }
386
387 // Equivalent to RawSender::CheckOk
388 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
389
390 private:
391 std::optional<fbs::Builder<T>> builder_;
392 RawSender *sender_;
393 };
394
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395 // Represents a single message about to be sent to the queue.
396 // The lifecycle goes:
397 //
398 // Builder builder = sender.MakeBuilder();
399 // T::Builder t_builder = builder.MakeBuilder<T>();
400 // Populate(&t_builder);
401 // builder.Send(t_builder.Finish());
402 class Builder {
403 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800404 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800405 : fbb_(allocator->size(), allocator),
406 allocator_(allocator),
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800407 sender_(CHECK_NOTNULL(sender)) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800408 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800409 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700410 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800411 Builder() {}
412 Builder(const Builder &) = delete;
413 Builder(Builder &&) = default;
414
415 Builder &operator=(const Builder &) = delete;
416 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417
418 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
419
420 template <typename T2>
421 typename T2::Builder MakeBuilder() {
422 return typename T2::Builder(fbb_);
423 }
424
milind1f1dca32021-07-03 13:50:07 -0700425 RawSender::Error Send(flatbuffers::Offset<T> offset) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426 fbb_.Finish(offset);
milind1f1dca32021-07-03 13:50:07 -0700427 const auto err = sender_->Send(fbb_.GetSize());
Brian Silverman9dd793b2020-01-31 23:52:21 -0800428 // Ensure fbb_ knows it shouldn't access the memory any more.
429 fbb_ = flatbuffers::FlatBufferBuilder();
milind1f1dca32021-07-03 13:50:07 -0700430 return err;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700431 }
432
milind1f1dca32021-07-03 13:50:07 -0700433 // Equivalent to RawSender::CheckOk
434 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
435
Alex Perrycb7da4b2019-08-28 19:35:56 -0700436 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800437 void CheckSent() {
438 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
439 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440
Brian Silverman341b57e2020-06-23 16:23:18 -0700441 // Detaches a buffer, for later use calling Sender::Send directly.
442 //
443 // Note that the underlying memory remains with the Sender, so creating
444 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
445 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
446 fbb_.Finish(offset);
447 return fbb_.Release();
448 }
449
Alex Perrycb7da4b2019-08-28 19:35:56 -0700450 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800452 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700453 RawSender *sender_;
454 };
455
456 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800457 //
458 // Only a single one of these may be "alive" for this object at any point in
459 // time. After calling Send on the result, it is no longer "alive". This means
460 // that you must manually reset a variable holding the return value (by
461 // assigning a default-constructed Builder to it) before calling this method
462 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700463 Builder MakeBuilder();
James Kuszmaulb1c11052023-11-06 13:20:53 -0800464 StaticBuilder MakeStaticBuilder() {
465 return StaticBuilder(sender_.get(), sender_->static_allocator());
466 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467
Austin Schuha28cbc32019-12-27 16:28:04 -0800468 // Sends a prebuilt flatbuffer.
James Kuszmaulad523042022-10-05 16:47:33 -0700469 // This will copy the data out of the provided flatbuffer, and so does not
470 // have to correspond to an existing Builder.
milind1f1dca32021-07-03 13:50:07 -0700471 RawSender::Error Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800472
Brian Silverman341b57e2020-06-23 16:23:18 -0700473 // Sends a prebuilt flatbuffer which was detached from a Builder created via
474 // MakeBuilder() on this object.
milind1f1dca32021-07-03 13:50:07 -0700475 RawSender::Error SendDetached(FlatbufferDetachedBuffer<T> detached);
476
477 // Equivalent to RawSender::CheckOk
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800478 void CheckOk(const RawSender::Error err) {
479 CHECK_NOTNULL(sender_)->CheckOk(err);
480 };
Brian Silverman341b57e2020-06-23 16:23:18 -0700481
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800482 // Returns the name of the underlying queue, if valid. You must check valid()
483 // first.
484 const Channel *channel() const { return CHECK_NOTNULL(sender_)->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700485
James Kuszmaulad523042022-10-05 16:47:33 -0700486 // Returns true if the Sender is a valid Sender. If you, e.g., are using
487 // TryMakeSender, then you must check valid() before attempting to use the
488 // Sender.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800489 // TODO(austin): Deprecate the operator bool.
Austin Schuha0c41ba2020-09-10 22:59:14 -0700490 operator bool() const { return sender_ ? true : false; }
Austin Schuhe33c08d2022-02-03 18:15:21 -0800491 bool valid() const { return static_cast<bool>(sender_); }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800492
Austin Schuh7bc59052020-02-16 23:48:33 -0800493 // Returns the time_points that the last message was sent at.
494 aos::monotonic_clock::time_point monotonic_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800495 return CHECK_NOTNULL(sender_)->monotonic_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800496 }
497 aos::realtime_clock::time_point realtime_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800498 return CHECK_NOTNULL(sender_)->realtime_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800499 }
500 // Returns the queue index that this was sent with.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800501 uint32_t sent_queue_index() const {
502 return CHECK_NOTNULL(sender_)->sent_queue_index();
503 }
Austin Schuh7bc59052020-02-16 23:48:33 -0800504
Brian Silverman4f4e0612020-08-12 19:54:41 -0700505 // Returns the buffer index which MakeBuilder() will expose access to. This is
506 // the buffer the caller can fill out.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800507 int buffer_index() const { return CHECK_NOTNULL(sender_)->buffer_index(); }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700508
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509 private:
510 friend class EventLoop;
511 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
512 std::unique_ptr<RawSender> sender_;
513};
514
milind1f1dca32021-07-03 13:50:07 -0700515// Class for keeping a count of send failures on a certain channel
516class SendFailureCounter {
517 public:
518 inline void Count(const RawSender::Error err) {
519 failures_ += static_cast<size_t>(err != RawSender::Error::kOk);
520 just_failed_ = (err != RawSender::Error::kOk);
521 }
522
523 inline size_t failures() const { return failures_; }
524 inline bool just_failed() const { return just_failed_; }
525
526 private:
527 size_t failures_ = 0;
528 bool just_failed_ = false;
529};
530
Brian Silverman4f4e0612020-08-12 19:54:41 -0700531// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700532class TimerHandler {
533 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800534 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700535
536 // Timer should sleep until base, base + offset, base + offset * 2, ...
537 // If repeat_offset isn't set, the timer only expires once.
James Kuszmaul8866e642022-06-10 16:00:36 -0700538 // base must be greater than or equal to zero.
Philipp Schradera6712522023-07-05 20:25:11 -0700539 virtual void Schedule(monotonic_clock::time_point base,
540 monotonic_clock::duration repeat_offset =
541 ::aos::monotonic_clock::zero()) = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542
543 // Stop future calls to callback().
544 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800545
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700546 // Check if the timer is disabled
547 virtual bool IsDisabled() = 0;
548
Austin Schuh1540c2f2019-11-29 21:59:29 -0800549 // Sets and gets the name of the timer. Set this if you want a descriptive
550 // name in the timing report.
551 void set_name(std::string_view name) { name_ = std::string(name); }
552 const std::string_view name() const { return name_; }
553
Austin Schuh39788ff2019-12-01 18:22:57 -0800554 protected:
555 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
556
Austin Schuh9b1d6282022-06-10 17:03:21 -0700557 template <typename T>
558 monotonic_clock::time_point Call(T get_time,
559 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800560
Austin Schuh1540c2f2019-11-29 21:59:29 -0800561 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800562 friend class EventLoop;
563
564 EventLoop *event_loop_;
565 // The function to call when Call is called.
566 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800567 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800568
569 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500570 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700571};
572
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800573// Interface for phased loops. They are built on timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700574class PhasedLoopHandler {
575 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800576 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700577
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800578 // Sets the interval and offset. Any changes to interval and offset only take
579 // effect when the handler finishes running or upon a call to Reschedule().
580 //
581 // The precise semantics of the monotonic_now parameter are defined in
582 // phased_loop.h. The way that it gets used in this interface is to control
583 // what the cycles elapsed counter will read on the following call to your
584 // handler. In an idealized simulation environment, if you call
585 // set_interval_and_offset() during the phased loop offset without setting
586 // monotonic_now, then you should always see a count of 1 on the next cycle.
587 //
588 // With the default behavior (this is called inside your handler and with
589 // monotonic_now = nullopt), the next phased loop call will occur at most
590 // interval time after the current time. Note that in many cases this will
591 // *not* be the preferred behavior (in most cases, you would likely aim to
592 // keep the average frequency of the calls reasonably consistent).
593 //
594 // A combination of the monotonic_now parameter and manually calling
595 // Reschedule() outside of the phased loop handler can be used to alter the
596 // behavior of cycles_elapsed. For the default behavior, you can set
597 // monotonic_now to the current time. If you call set_interval_and_offset()
598 // and Reschedule() with the same monotonic_now, that will cause the next
599 // callback to occur in the range (monotonic_now, monotonic_now + interval]
600 // and get called with a count of 1 (if the event is actually able to happen
601 // when it is scheduled to). E.g., if you are just adjusting the phased loop
602 // offset (but not the interval) and want to maintain a consistent frequency,
603 // you may call these functions with monotonic_now = now + interval / 2.
604 void set_interval_and_offset(
605 const monotonic_clock::duration interval,
606 const monotonic_clock::duration offset,
607 std::optional<monotonic_clock::time_point> monotonic_now = std::nullopt) {
608 phased_loop_.set_interval_and_offset(interval, offset, monotonic_now);
Austin Schuh39788ff2019-12-01 18:22:57 -0800609 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800610
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800611 // Reruns the scheduler for the phased loop, scheduling the next callback at
612 // the next available time after monotonic_now. This allows
613 // set_interval_and_offset() to be called and have the changes take effect
614 // before the next handler finishes. This will have no effect if run during
615 // the phased loop's own handler.
616 void Reschedule(monotonic_clock::time_point monotonic_now) {
617 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
618 Schedule(phased_loop_.sleep_time());
619 }
620
621 // Sets and gets the name of the timer. Set this if you want a descriptive
Austin Schuh1540c2f2019-11-29 21:59:29 -0800622 // name in the timing report.
623 void set_name(std::string_view name) { name_ = std::string(name); }
624 const std::string_view name() const { return name_; }
625
Austin Schuh39788ff2019-12-01 18:22:57 -0800626 protected:
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800627 void Call(std::function<monotonic_clock::time_point()> get_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800628
629 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
630 const monotonic_clock::duration interval,
631 const monotonic_clock::duration offset);
632
Austin Schuh1540c2f2019-11-29 21:59:29 -0800633 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800634 friend class EventLoop;
635
Austin Schuh39788ff2019-12-01 18:22:57 -0800636 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
637
638 EventLoop *event_loop_;
639 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800640 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800641 time::PhasedLoop phased_loop_;
642
643 int cycles_elapsed_ = 0;
644
645 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500646 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700647};
648
Austin Schuh3054f5f2021-07-21 15:38:01 -0700649// Note, it is supported to create only:
650// multiple fetchers, and (one sender or one watcher) per <name, type>
651// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700652class EventLoop {
653 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700654 // Holds configuration by reference for the lifetime of this object. It may
655 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800656 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700657
Austin Schuh39788ff2019-12-01 18:22:57 -0800658 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700659
660 // Current time.
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800661 virtual monotonic_clock::time_point monotonic_now() const = 0;
662 virtual realtime_clock::time_point realtime_now() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700663
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700664 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800665 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800666 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800667 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800668 true);
669 }
milind1f1dca32021-07-03 13:50:07 -0700670 // Returns true if the channel exists in the configuration.
Austin Schuha0654152021-02-21 21:38:24 -0800671 template <typename T>
672 bool HasChannel(const std::string_view channel_name) {
673 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700674 }
675
Brian Silverman631b6262021-11-10 12:25:08 -0800676 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800677 // not readable on this node or does not exist. You must check valid() on the
678 // Fetcher before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800679 template <typename T>
680 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
681 const Channel *const channel = GetChannel<T>(channel_name);
682 if (channel == nullptr) {
683 return Fetcher<T>();
684 }
685
686 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
687 return Fetcher<T>();
688 }
689
690 return Fetcher<T>(MakeRawFetcher(channel));
691 }
692
Alex Perrycb7da4b2019-08-28 19:35:56 -0700693 // Makes a class that will always fetch the most recent value
694 // sent to the provided channel.
695 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800696 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800697 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700698 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
699 << T::GetFullyQualifiedName() << "\" } not found in config.";
700
Brian Silverman631b6262021-11-10 12:25:08 -0800701 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
702 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800703 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
704 << "\", \"type\": \"" << T::GetFullyQualifiedName()
705 << "\" } is not able to be fetched 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;
710 }
711
712 // Like MakeSender, but returns an invalid sender if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800713 // not sendable on this node or does not exist. You must check valid() on the
714 // Sender before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800715 template <typename T>
716 Sender<T> TryMakeSender(const std::string_view channel_name) {
717 const Channel *channel = GetChannel<T>(channel_name);
718 if (channel == nullptr) {
719 return Sender<T>();
720 }
721
722 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
723 return Sender<T>();
724 }
725
726 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700727 }
728
729 // Makes class that allows constructing and sending messages to
730 // the provided channel.
731 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800732 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800733 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700734 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800735 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700736 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800737 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700738 ? absl::StrCat(" on node ", node()->name()->string_view())
739 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700740
Brian Silverman631b6262021-11-10 12:25:08 -0800741 Sender<T> result = TryMakeSender<T>(channel_name);
742 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800743 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
744 << "\", \"type\": \"" << T::GetFullyQualifiedName()
745 << "\" } is not able to be sent on this node. Check your "
746 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800747 }
748
Brian Silverman631b6262021-11-10 12:25:08 -0800749 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700750 }
751
752 // This will watch messages sent to the provided channel.
753 //
Brian Silverman454bc112020-03-05 14:21:25 -0800754 // w must have a non-polymorphic operator() (aka it can only be called with a
755 // single set of arguments; no overloading or templates). It must be callable
756 // with this signature:
757 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700758 //
Brian Silverman454bc112020-03-05 14:21:25 -0800759 // Lambdas are a common form for w. A std::function will work too.
760 //
761 // Note that bind expressions have polymorphic call operators, so they are not
762 // allowed.
763 //
764 // We template Watch as a whole instead of using std::function<void(const T
765 // &)> to allow deducing MessageType from lambdas and other things which are
766 // implicitly convertible to std::function, but not actually std::function
767 // instantiations. Template deduction guides might allow solving this
768 // differently in newer versions of C++, but those have their own corner
769 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700770 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800771 void MakeWatcher(const std::string_view channel_name, Watch &&w);
772
773 // Like MakeWatcher, but doesn't have access to the message data. This may be
774 // implemented to use less resources than an equivalent MakeWatcher.
775 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800776 // The function will still have access to context(), although that will have
777 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800778 template <typename MessageType>
779 void MakeNoArgWatcher(const std::string_view channel_name,
780 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700781
782 // The passed in function will be called when the event loop starts.
783 // Use this to run code once the thread goes into "real-time-mode",
784 virtual void OnRun(::std::function<void()> on_run) = 0;
785
Austin Schuh217a9782019-12-21 23:02:50 -0800786 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800787 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700788
Austin Schuh217a9782019-12-21 23:02:50 -0800789 // Returns the node that this event loop is running on. Returns nullptr if we
790 // are running in single-node mode.
791 virtual const Node *node() const = 0;
792
Alex Perrycb7da4b2019-08-28 19:35:56 -0700793 // Creates a timer that executes callback when the timer expires
794 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700795 // TODO(milind): callback should take the number of cycles elapsed as a
796 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700797 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
798
799 // Creates a timer that executes callback periodically at the specified
800 // interval and offset. Returns a PhasedLoopHandler for interacting with the
801 // timer.
802 virtual PhasedLoopHandler *AddPhasedLoop(
803 ::std::function<void(int)> callback,
804 const monotonic_clock::duration interval,
805 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
806
Austin Schuh217a9782019-12-21 23:02:50 -0800807 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700808
Austin Schuh3054f5f2021-07-21 15:38:01 -0700809 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700810 bool is_running() const { return is_running_.load(); }
811
812 // Sets the scheduler priority to run the event loop at. This may not be
813 // called after we go into "real-time-mode".
814 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700815 // Defaults to 0 if this loop will not run realtime.
816 virtual int runtime_realtime_priority() const = 0;
817
Austin Schuh070019a2022-12-20 22:23:09 -0800818 static cpu_set_t DefaultAffinity();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700819
Brian Silverman6a54ff32020-04-28 16:41:39 -0700820 // Sets the scheduler affinity to run the event loop with. This may only be
821 // called before Run().
822 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700823 // Defaults to DefaultAffinity() if this loop will not run pinned.
824 virtual const cpu_set_t &runtime_affinity() const = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700825
Austin Schuh217a9782019-12-21 23:02:50 -0800826 // Fetches new messages from the provided channel (path, type).
827 //
828 // Note: this channel must be a member of the exact configuration object this
829 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700830 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
831 const Channel *channel) = 0;
832
Austin Schuh217a9782019-12-21 23:02:50 -0800833 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700834 virtual void MakeRawWatcher(
835 const Channel *channel,
836 std::function<void(const Context &context, const void *message)>
837 watcher) = 0;
838
Brian Silverman454bc112020-03-05 14:21:25 -0800839 // Watches channel (name, type) for new messages, without needing to extract
840 // the message contents. Default implementation simply re-uses MakeRawWatcher.
841 virtual void MakeRawNoArgWatcher(
842 const Channel *channel,
843 std::function<void(const Context &context)> watcher) {
844 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800845 Context new_context = context;
846 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700847 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800848 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800849 });
850 }
851
Austin Schuh217a9782019-12-21 23:02:50 -0800852 // Creates a raw sender for the provided channel. This is used for reflection
853 // based sending.
854 // Note: this ignores any node constraints. Ignore at your own peril.
855 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
856
Austin Schuh6231cc32019-12-07 13:06:15 -0800857 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700858 const Context &context() const { return context_; }
859
860 // Returns the configuration that this event loop was built with.
861 const Configuration *configuration() const { return configuration_; }
862
Austin Schuh39788ff2019-12-01 18:22:57 -0800863 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800864 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800865
Brian Silverman4f4e0612020-08-12 19:54:41 -0700866 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800867 void SkipAosLog() { skip_logger_ = true; }
868
Brian Silverman4f4e0612020-08-12 19:54:41 -0700869 // Returns the number of buffers for this channel. This corresponds with the
870 // range of Context::buffer_index values for this channel.
871 virtual int NumberBuffers(const Channel *channel) = 0;
872
Austin Schuh20ac95d2020-12-05 17:24:19 -0800873 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800874 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800875
James Kuszmaul762e8692023-07-31 14:57:53 -0700876 // Sets the version string that will be used in any newly constructed
877 // EventLoop objects. This can be overridden for individual EventLoop's by
878 // calling EventLoop::SetVersionString(). The version string is populated into
879 // the timing report message. Makes a copy of the provided string_view.
880 static void SetDefaultVersionString(std::string_view version);
881
882 // Overrides the version string for this event loop. Makes a copy of the
883 // provided string_view.
884 void SetVersionString(std::string_view version);
885
James Kuszmaulb740f452023-11-14 17:44:29 -0800886 std::optional<std::string_view> VersionString() const {
887 return version_string_;
888 }
889
Alex Perrycb7da4b2019-08-28 19:35:56 -0700890 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800891 // Sets the name of the event loop. This is the application name.
892 virtual void set_name(const std::string_view name) = 0;
893
Alex Perrycb7da4b2019-08-28 19:35:56 -0700894 void set_is_running(bool value) { is_running_.store(value); }
895
Austin Schuh39788ff2019-12-01 18:22:57 -0800896 // Validates that channel exists inside configuration_ and finds its index.
897 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700898
Brian Silverman5120afb2020-01-31 17:44:35 -0800899 // Returns the state for the watcher on the corresponding channel. This
900 // watcher must exist before calling this.
901 WatcherState *GetWatcherState(const Channel *channel);
902
Brian Silverman6d2b3592020-06-18 14:40:15 -0700903 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800904 template <typename T>
905 static RawSender *GetRawSender(aos::Sender<T> *sender) {
906 return sender->sender_.get();
907 }
908
Brian Silverman6d2b3592020-06-18 14:40:15 -0700909 // Returns a Fetcher's protected RawFetcher.
910 template <typename T>
911 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
912 return fetcher->fetcher_.get();
913 }
914
Austin Schuh6231cc32019-12-07 13:06:15 -0800915 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700916 Context context_;
917
Austin Schuh39788ff2019-12-01 18:22:57 -0800918 friend class RawSender;
919 friend class TimerHandler;
920 friend class RawFetcher;
921 friend class PhasedLoopHandler;
922 friend class WatcherState;
923
924 // Methods used to implement timing reports.
925 void NewSender(RawSender *sender);
926 void DeleteSender(RawSender *sender);
927 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
928 PhasedLoopHandler *NewPhasedLoop(
929 std::unique_ptr<PhasedLoopHandler> phased_loop);
930 void NewFetcher(RawFetcher *fetcher);
931 void DeleteFetcher(RawFetcher *fetcher);
932 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
933
Brian Silverman0fc69932020-01-24 21:54:02 -0800934 // Tracks that we have a (single) watcher on the given channel.
935 void TakeWatcher(const Channel *channel);
936 // Tracks that we have at least one sender on the given channel.
937 void TakeSender(const Channel *channel);
938
Austin Schuh39788ff2019-12-01 18:22:57 -0800939 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800940 std::vector<RawFetcher *> fetchers_;
941
Austin Schuh39788ff2019-12-01 18:22:57 -0800942 std::vector<std::unique_ptr<TimerHandler>> timers_;
943 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800944 std::vector<std::unique_ptr<WatcherState>> watchers_;
945
Brian Silvermance418d02021-11-03 11:25:52 -0700946 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800947 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700948
Austin Schuh39788ff2019-12-01 18:22:57 -0800949 void UpdateTimingReport();
950 void MaybeScheduleTimingReports();
951
952 std::unique_ptr<RawSender> timing_report_sender_;
953
Austin Schuh7d87b672019-12-01 20:23:49 -0800954 // Tracks which event sources (timers and watchers) have data, and which
955 // don't. Added events may not change their event_time().
956 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
957 // t2 to run, t2 should then be picked up without a context switch.
958 void AddEvent(EventLoopEvent *event);
959 void RemoveEvent(EventLoopEvent *event);
960 size_t EventCount() const { return events_.size(); }
961 EventLoopEvent *PopEvent();
962 EventLoopEvent *PeekEvent() { return events_.front(); }
963 void ReserveEvents();
964
965 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700966 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800967
Tyler Chatow67ddb032020-01-12 14:30:04 -0800968 // If true, don't send AOS_LOG to /aos
969 bool skip_logger_ = false;
970
Austin Schuha9012be2021-07-21 15:19:11 -0700971 // Sets context_ for a timed event which is supposed to happen at the provided
972 // time.
973 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
Austin Schuh0debde12022-08-17 16:25:17 -0700974 // Clears context_ so it only has invalid times and elements in it.
975 void ClearContext();
Austin Schuha9012be2021-07-21 15:19:11 -0700976
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800977 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800978 virtual pid_t GetTid() = 0;
979
James Kuszmaul762e8692023-07-31 14:57:53 -0700980 // Default version string to be used in the timing report for any newly
981 // created EventLoop objects.
982 static std::optional<std::string> default_version_string_;
983
984 // Timing report version string for this event loop.
985 std::optional<std::string> version_string_;
986
Austin Schuh39788ff2019-12-01 18:22:57 -0800987 FlatbufferDetachedBuffer<timing::Report> timing_report_;
988
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800989 ::std::atomic<bool> is_running_{false};
990
Alex Perrycb7da4b2019-08-28 19:35:56 -0700991 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800992
993 // If true, don't send out timing reports.
994 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800995
milind1f1dca32021-07-03 13:50:07 -0700996 SendFailureCounter timing_report_failure_counter_;
997
Brian Silverman0fc69932020-01-24 21:54:02 -0800998 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700999};
1000
Brian Silvermane1fe2512022-08-14 23:18:50 -07001001// Interface for terminating execution of an EventLoop.
1002//
1003// Prefer this over binding a lambda to an Exit() method when passing ownership
1004// in complicated ways because implementations should have assertions to catch
1005// it outliving the object it's referring to, instead of having a
1006// use-after-free.
1007//
1008// This is not exposed by EventLoop directly because different EventLoop
1009// implementations provide this functionality at different scopes, or possibly
1010// not at all.
1011class ExitHandle {
1012 public:
1013 ExitHandle() = default;
1014 virtual ~ExitHandle() = default;
1015
1016 // Exits some set of event loops. Details depend on the implementation.
1017 //
1018 // This means no more events will be processed, but any currently being
1019 // processed will finish.
1020 virtual void Exit() = 0;
1021};
1022
Alex Perrycb7da4b2019-08-28 19:35:56 -07001023} // namespace aos
1024
Austin Schuhb8075812020-10-19 09:36:49 -07001025#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -07001026
1027#endif // AOS_EVENTS_EVENT_LOOP_H