Sen API
Sen Libraries
Loading...
Searching...
No Matches
component_api.h
Go to the documentation of this file.
1// === component_api.h =================================================================================================
2// Sen Infrastructure
3// Released under the Apache License v2.0 (SPDX-License-Identifier Apache-2.0).
4// See the LICENSE.txt file for more information.
5// © Airbus SAS, Airbus Helicopters, and Airbus Defence and Space SAU/GmbH/SAS.
6// =====================================================================================================================
7
8#ifndef SEN_KERNEL_COMPONENT_API_H
9#define SEN_KERNEL_COMPONENT_API_H
10
11// sen
16#include "sen/core/base/span.h"
19#include "sen/core/meta/var.h"
22#include "sen/core/obj/object.h"
26
27// kernel
28#include "sen/kernel/kernel.h"
30#include "sen/kernel/tracer.h"
32
33// generated code
34#include "stl/sen/kernel/basic_types.stl.h"
35
36// spdlog
37#include <spdlog/logger.h>
38
39// std
40#include <atomic>
41#include <cstdint>
42#include <cstring>
43#include <filesystem>
44#include <functional>
45#include <memory>
46#include <optional>
47#include <string>
48#include <string_view>
49#include <type_traits>
50#include <utility>
51#include <vector>
52
53namespace sen::kernel
54{
55
58
61
63class RunApi;
64class KernelApi;
65
66namespace impl
67{
68
69class Runner;
70class KernelImpl;
71
72[[nodiscard]] FuncResult execLoop(Runner* runner, Duration cycleTime, std::function<void()>&& workFunction);
73
74void installTransportFactory(KernelImpl* kernel, TransportFactory&& factory, uint32_t transportVersion);
75
76void remoteProcessDetected(RunApi& api, const ProcessInfo& processInfo);
77
78void remoteProcessLost(RunApi& api, const ProcessInfo& processInfo);
79
80[[nodiscard]] std::shared_ptr<ObjectSource> getSource(Runner* runner, const BusAddress& address);
81
82[[nodiscard]] SessionsDiscoverer& getSessionsDiscoverer(Runner* runner);
83
84[[nodiscard]] const ProcessInfo* fetchOwnerInfo(const Object* object);
85
86[[nodiscard]] ::sen::impl::WorkQueue* getWorkQueue(Runner* runner);
87
88[[nodiscard]] std::shared_ptr<spdlog::logger> getOrCreateLogger(const std::string& loggerName);
89
90void applyToAllLoggers(std::function<void(std::shared_ptr<spdlog::logger>)>&& func);
91
92} // namespace impl
93
96{
97 std::string name;
98 uint32_t group = 0;
99 bool requiresRealTime = false;
100 std::optional<Duration> cycleTime;
101 std::size_t objectCount = 0;
102};
103
106{
107 RunMode runMode = RunMode::realTime;
109 std::vector<ComponentMonitoringInfo> components;
110};
111
114{
115public:
116 KernelApi(Kernel& kernel, impl::Runner* runner) noexcept;
117
118public:
120 [[nodiscard]] CustomTypeRegistry& getTypes() noexcept;
121
124 void requestKernelStop(int exitCode = 0);
125
127 [[nodiscard]] std::shared_ptr<ObjectSource> getSource(const BusAddress& address);
128
131 [[nodiscard]] std::shared_ptr<ObjectSource> getSource(const std::string& address);
132
134 [[nodiscard]] SessionsDiscoverer& getSessionsDiscoverer() noexcept;
135
138 [[nodiscard]] const ProcessInfo* fetchOwnerInfo(const Object* object) const noexcept;
139
141 [[nodiscard]] const std::string& getAppName() const noexcept;
142
144 [[nodiscard]] ::sen::impl::WorkQueue* getWorkQueue() const noexcept;
145
153 template <typename T, typename Bus>
154 [[nodiscard]] std::shared_ptr<Subscription<T>> selectAllFrom(const Bus& bus);
155
158 template <typename T, typename Bus>
159 [[nodiscard]] std::shared_ptr<Subscription<T>> selectAllFrom(
160 const Bus& bus,
161 typename sen::ObjectList<T>::Callback onAdded,
162 typename sen::ObjectList<T>::Callback onRemoved = nullptr);
163
167 template <typename T, typename Bus>
168 [[nodiscard]] std::shared_ptr<Subscription<T>> selectFrom(const Bus& bus,
169 const std::string& query,
170 typename sen::ObjectList<T>::Callback onAdded = nullptr,
171 typename sen::ObjectList<T>::Callback onRemoved = nullptr);
172
175 [[nodiscard]] std::filesystem::path getConfigFilePath() const noexcept { return kernel_.getConfigPath(); }
176
179 [[nodiscard]] static std::shared_ptr<spdlog::logger> getOrCreateLogger(const std::string& loggerName);
180
182 static void applyToAllLoggers(std::function<void(std::shared_ptr<spdlog::logger>)>&& func);
183
184private:
185 template <typename T>
186 [[nodiscard]] std::string buildQuery(const BusAddress& address) const;
187
188 template <typename T>
189 [[nodiscard]] std::string buildQuery(std::string_view bus) const;
190
191private:
192 Kernel& kernel_;
193 impl::Runner* runner_;
194};
195
198{
199public:
200 explicit ConfigGetter(const VarMap& config) noexcept;
201
202public:
204 [[nodiscard]] const VarMap& getConfig() const noexcept;
205
206private:
207 const VarMap& config_;
208};
209
212{
213public:
214 SEN_NOCOPY_NOMOVE(RegistrationApi)
215
216public:
217 RegistrationApi(Kernel& kernel, impl::Runner* runner, const VarMap& config) noexcept;
218 ~RegistrationApi() noexcept = default;
219};
220
222class PreloadApi: public ConfigGetter, public KernelApi
223{
224 SEN_NOCOPY_NOMOVE(PreloadApi)
225
226public:
227 PreloadApi(Kernel& kernel, impl::Runner* runner, const VarMap& config) noexcept;
228
229 ~PreloadApi() noexcept = default;
230
231public:
233 void installTransportFactory(TransportFactory&& factory, uint32_t transportVersion) const;
234
236 void installTracerFactory(TracerFactory&& factory) const;
237
238private:
239 Kernel& kernel_;
240};
241
243class LoadApi: public ConfigGetter, public KernelApi
244{
245 SEN_NOCOPY_NOMOVE(LoadApi)
246
247public:
248 LoadApi(Kernel& kernel, impl::Runner* runner, const VarMap& config) noexcept;
249
250 ~LoadApi() noexcept = default;
251};
252
254class InitApi: public ConfigGetter, public KernelApi
255{
256 SEN_NOCOPY_NOMOVE(InitApi)
257
258public:
259 InitApi(Kernel& kernel, impl::Runner* runner, const VarMap& config) noexcept;
260
261 ~InitApi() noexcept = default;
262};
263
265class RunApi: public ConfigGetter, public KernelApi
266{
267public:
268 SEN_NOCOPY_NOMOVE(RunApi)
269
270public:
272 impl::KernelImpl& kernelImpl,
273 impl::Runner* runner,
274 std::atomic_bool& stopRequested,
275 const VarMap& config,
276 Guarded<TimeStamp>& timePoint) noexcept;
277
278 ~RunApi() noexcept = default;
279
280public:
282 [[nodiscard]] const std::atomic_bool& stopRequested() const noexcept;
283
288
290 void update();
291
296 void commit();
297
302 [[nodiscard]] FuncResult execLoop(Duration cycleTime,
303 std::function<void()>&& func = nullptr,
304 bool logOverruns = true);
305
307 [[nodiscard]] TimeStamp getStartTime() const noexcept;
308
310 [[nodiscard]] TimeStamp getTime() const noexcept;
311
313 [[nodiscard]] std::optional<Duration> getTargetCycleTime() const noexcept;
314
317
321 [[nodiscard]] Span<const ComponentInfo> getImportedPackages() const noexcept;
322
328 [[nodiscard]] Span<const ComponentInfo> getLoadedComponents() const noexcept;
329
332 [[nodiscard]] std::optional<uint32_t> getTransportProtocolVersion() const noexcept;
333
335 [[nodiscard]] Tracer& getTracer() const noexcept;
336
337private:
338 friend void impl::remoteProcessDetected(RunApi& api, const ProcessInfo& processInfo);
339
340 friend void impl::remoteProcessLost(RunApi& api, const ProcessInfo& processInfo);
341
342private:
343 impl::KernelImpl& kernelImpl_;
344 impl::Runner* runner_;
345 std::atomic_bool& stopRequested_;
346 Guarded<TimeStamp>& timePoint_;
347};
348
350class UnloadApi: public ConfigGetter, public KernelApi
351{
352 SEN_NOCOPY_NOMOVE(UnloadApi)
353
354public:
355 UnloadApi(Kernel& kernel, const VarMap& config, impl::Runner* runner) noexcept;
356 ~UnloadApi() noexcept = default;
357};
358
359//----------------------------------------------------------------------------------------------------------------------
360// Inline implementation
361//----------------------------------------------------------------------------------------------------------------------
362
363template <typename T, typename Bus>
364inline std::shared_ptr<Subscription<T>> KernelApi::selectAllFrom(const Bus& bus)
365{
366 auto sub = std::make_shared<Subscription<T>>();
367 sub->attachTo(getSource(bus), Interest::make(buildQuery<T>(bus), getTypes()), true);
368 return sub;
369}
370
371template <typename T, typename Bus>
372inline std::shared_ptr<Subscription<T>> KernelApi::selectAllFrom(const Bus& bus,
373 typename ObjectList<T>::Callback onAdded,
374 typename ObjectList<T>::Callback onRemoved)
375{
376 auto sub = std::make_shared<Subscription<T>>();
377 // Install callbacks before subscribing so they fire for objects already present.
378 if (onAdded)
379 {
380 std::ignore = sub->list.onAdded(std::move(onAdded));
381 }
382 if (onRemoved)
383 {
384 std::ignore = sub->list.onRemoved(std::move(onRemoved));
385 }
386 sub->attachTo(getSource(bus), Interest::make(buildQuery<T>(bus), getTypes()), true);
387 return sub;
388}
389
390template <typename T, typename Bus>
391inline std::shared_ptr<Subscription<T>> KernelApi::selectFrom(const Bus& bus,
392 const std::string& query,
393 typename sen::ObjectList<T>::Callback onAdded,
394 typename sen::ObjectList<T>::Callback onRemoved)
395{
396 auto sub = std::make_shared<Subscription<T>>();
397
398 // Install callbacks before subscribing so they fire for objects already present.
399 if (onAdded)
400 {
401 std::ignore = sub->list.onAdded(std::move(onAdded));
402 }
403 if (onRemoved)
404 {
405 std::ignore = sub->list.onRemoved(std::move(onRemoved));
406 }
407 sub->attachTo(getSource(bus), Interest::make(query, getTypes()), true);
408 return sub;
409}
410
411namespace impl
412{
413
417template <typename T>
418[[nodiscard]] inline std::string_view queryTypeName()
419{
420 if constexpr (std::is_same_v<T, Object>)
421 {
422 return "*";
423 }
424 else
425 {
426 static_assert(std::is_same_v<decltype(T::meta()), ::sen::ConstTypeHandle<::sen::ClassType>>,
427 "a subscription type must be a Sen object class");
428 return T::meta()->getQualifiedName();
429 }
430}
431
432} // namespace impl
433
434template <typename T>
435inline std::string KernelApi::buildQuery(const BusAddress& address) const
436{
437 std::string query = "SELECT ";
438 query.append(impl::queryTypeName<T>());
439 query.append(" FROM ");
440 query.append(address.sessionName);
441 query.append(".");
442 query.append(address.busName);
443
444 return query;
445}
446
447template <typename T>
448inline std::string KernelApi::buildQuery(std::string_view bus) const
449{
450 std::string query = "SELECT ";
451 query.append(impl::queryTypeName<T>());
452 query.append(" FROM ");
453 query.append(bus);
454
455 return query;
456}
457
458} // namespace sen::kernel
459
460#endif // SEN_KERNEL_COMPONENT_API_H
Base class for event or method callbacks. It stores the queue where to push the response....
Definition callback.h:146
A registry of custom types.
Definition type_registry.h:36
A time duration.
Definition duration.h:25
static std::shared_ptr< Interest > make(std::string_view query, const CustomTypeRegistry &typeRegistry)
Make an interest from a query. Throws std::exception if not well formed.
A sen object.
Definition object.h:76
A list of objects that is managed by some source based on user-expressed interests.
Definition object_list.h:30
std::function< void(const Iterators &iterators)> Callback
Definition object_list.h:70
Allows adding and receiving objects.
Definition object_source.h:35
Result<T, E> is a template type that can be used to return and propagate errors. The intent is to rep...
Definition result.h:135
Contiguous view of elements of type T. Inspired by http://www.open-std.org/jtc1/sc22/wg21/docs/papers...
Definition span.h:34
A point in time.
Definition timestamp.h:26
ConfigGetter(const VarMap &config) noexcept
const VarMap & getConfig() const noexcept
Gets the configuration associated with this component.
~InitApi() noexcept=default
InitApi(Kernel &kernel, impl::Runner *runner, const VarMap &config) noexcept
User-facing kernel functions.
Definition component_api.h:114
::sen::impl::WorkQueue * getWorkQueue() const noexcept
The work queue of this runner.
KernelApi(Kernel &kernel, impl::Runner *runner) noexcept
std::shared_ptr< Subscription< T > > selectFrom(const Bus &bus, const std::string &query, typename sen::ObjectList< T >::Callback onAdded=nullptr, typename sen::ObjectList< T >::Callback onRemoved=nullptr)
Subscription against an arbitrary Sen query (with WHERE conditions). Example: selectFrom<Shape>(bus,...
Definition component_api.h:391
std::shared_ptr< ObjectSource > getSource(const BusAddress &address)
Gets an object source, where objects can be found and published.
std::filesystem::path getConfigFilePath() const noexcept
Gets the path to the configuration file used to construct the kernel. It might be empty if the kernel...
Definition component_api.h:175
CustomTypeRegistry & getTypes() noexcept
The types registered into the kernel.
static std::shared_ptr< spdlog::logger > getOrCreateLogger(const std::string &loggerName)
Registers a new logger in the kernel if it does not exist, or returns the existing one by name....
SessionsDiscoverer & getSessionsDiscoverer() noexcept
Object that allows discovering sessions and buses.
const ProcessInfo * fetchOwnerInfo(const Object *object) const noexcept
Gets information about the process where an object is. Returns nullptr if the object resides in the c...
const std::string & getAppName() const noexcept
Gets the (optional) application name passed to the kernel as a configuration parameter.
static void applyToAllLoggers(std::function< void(std::shared_ptr< spdlog::logger >)> &&func)
Applies the input function to all loggers kept in the logger registry. Used by the logmaster componen...
void requestKernelStop(int exitCode=0)
Issues an asynchronous request to stop the kernel. The request is ignored if a previous stop request ...
std::shared_ptr< Subscription< T > > selectAllFrom(const Bus &bus)
Subscribe to every object of type T on bus. The returned Subscription owns the kernel-side wiring; de...
Definition component_api.h:364
Main entry point of a sen microkernel.
Definition kernel.h:40
~LoadApi() noexcept=default
LoadApi(Kernel &kernel, impl::Runner *runner, const VarMap &config) noexcept
PreloadApi(Kernel &kernel, impl::Runner *runner, const VarMap &config) noexcept
~PreloadApi() noexcept=default
void installTracerFactory(TracerFactory &&factory) const
Installs a tracer factory.
void installTransportFactory(TransportFactory &&factory, uint32_t transportVersion) const
Installs a transport factory for the kernel to use for sessions.
RegistrationApi(Kernel &kernel, impl::Runner *runner, const VarMap &config) noexcept
~RegistrationApi() noexcept=default
What can be done while a component is running.
Definition component_api.h:266
Span< const ComponentInfo > getLoadedComponents() const noexcept
Build information for every component loaded into the kernel, excluding pipeline components (which ar...
TimeStamp getStartTime() const noexcept
The initial simulation time for the objects in the component.
Span< const ComponentInfo > getImportedPackages() const noexcept
Build information for all imported packages (from pipeline components). The returned span references ...
void commit()
Send changes, so that they become visible to other participants. This includes object additions and r...
Tracer & getTracer() const noexcept
Create a scoped zone used for tracing runtime performance.
void drainInputs()
Perform any request coming from the outside and drainInputs all the local data structures with their ...
~RunApi() noexcept=default
std::optional< Duration > getTargetCycleTime() const noexcept
If present, it returns the configured cycle time for iterations.
std::optional< uint32_t > getTransportProtocolVersion() const noexcept
Version of the currently installed transport protocol. Empty when no transport is installed....
FuncResult execLoop(Duration cycleTime, std::function< void()> &&func=nullptr, bool logOverruns=true)
A basic execution loop. Func is an optional callback that will be invoked on each cycle....
RunApi(Kernel &kernel, impl::KernelImpl &kernelImpl, impl::Runner *runner, std::atomic_bool &stopRequested, const VarMap &config, Guarded< TimeStamp > &timePoint) noexcept
KernelMonitoringInfo fetchMonitoringInfo() const
Monitoring information.
friend void impl::remoteProcessLost(RunApi &api, const ProcessInfo &processInfo)
const std::atomic_bool & stopRequested() const noexcept
True if stop has been requested by the runtime.
void update()
This calls update() on all the objects registered by the component.
friend void impl::remoteProcessDetected(RunApi &api, const ProcessInfo &processInfo)
TimeStamp getTime() const noexcept
The (potentially virtualized) time.
Definition source_info.h:99
Interface implemented by tracers. You can use it to trace the behavior of your code....
Definition tracer.h:28
UnloadApi(Kernel &kernel, const VarMap &config, impl::Runner *runner) noexcept
~UnloadApi() noexcept=default
std::function< std::unique_ptr< Transport >(const std::string &, std::unique_ptr< Tracer > tracer)> TransportFactory
A function that creates a transport given a session name.
Definition include/sen/kernel/transport.h:203
Global transport statistics.
Definition include/sen/kernel/transport.h:146
std::map< std::string, Var, std::less<> > VarMap
A map of vars to represent structures.
Definition var.h:107
TypeHandle< const T > ConstTypeHandle
Definition type.h:319
Strong type for the unique identifier for a transport timer.
Definition native_object_impl.h:39
uint32_t group
Definition component_api.h:98
Result< OpState, ExecError > PassResult
The result of operations that may be called multiple times.
Definition component_api.h:60
std::function< std::unique_ptr< Tracer >(std::string_view)> TracerFactory
A factory function for tracers.
Definition tracer.h:119
Result< void, ExecError > FuncResult
The result of operations that are called once.
Definition component_api.h:57
std::optional< Duration > cycleTime
Definition component_api.h:100
std::vector< ComponentMonitoringInfo > components
Definition component_api.h:109
std::size_t objectCount
Definition component_api.h:101
std::string name
Definition component_api.h:97
RunMode runMode
Definition component_api.h:107
bool requiresRealTime
Definition component_api.h:99
TransportStats transportStats
Definition component_api.h:108
Runtime monitoring information about a single component runner.
Definition component_api.h:96
Kernel runtime monitoring information.
Definition component_api.h:106
Definition assert.h:17
STL namespace.
Guarded is a lightweight wrapper class that can be used to protect an objet of type T from concurrent...
Definition mutex_utils.h:49
A list of objects and a reference to its source (to keep it alive).
Definition subscription.h:29