16#include "sparta/utils/StringManager.hpp"
63 #define REGISTER_FOR_THIS(func) \
64 registerForThis<typename std::remove_reference<decltype(*this)>::type, \
65 &std::remove_reference<decltype(*this)>::type::func>(this);
72 #define DEREGISTER_FOR_THIS(func) \
73 deregisterForThis<typename std::remove_reference<decltype(*this)>::type, \
74 &std::remove_reference<decltype(*this)>::type::func>(this);
77 class MirrorNotificationSource;
184 ObservationStateCallbackPrivateInterface::registerObservationStateChangeCallback_(ns_,
this);
190 if (tree_node_weak_ptr_.expired() ==
false) {
191 ObservationStateCallbackPrivateInterface::deregisterObservationStateChangeCallback_(ns_,
this);
208 uint32_t observers)
const
210 callback_(ns, observers);
216 void dump(std::ostream& o)
const {
217 o <<
"<ObservationStateCallback type=" <<
static_cast<int>(type_) <<
" node=";
218 if(tree_node_weak_ptr_.expired()){
221 o << tree_node_weak_ptr_.lock()->getLocation();
236 ns.registerObservationStateChangeCallback_(cbobject);
243 ns.deregisterObservationStateChangeCallback_(cbobject);
277 const std::string& name,
278 const std::string& group,
280 const std::string& desc,
281 const std::string* notification_name_id,
282 const std::type_info& notification_tinfo) :
283 TreeNode(name, group, group_idx, desc),
289 if(
nullptr == parent){
291 <<
getLocation() <<
" must be constructed with a parent";
296 if(
nullptr == notification_name_id){
298 <<
getLocation() <<
" cannot be constructed with a null notification_name_id";
308 determineObs_Nodes_();
316 const std::string& name,
317 const std::string& group,
319 const std::string& desc,
320 const std::string& notification_name,
321 const std::type_info& notification_tinfo) :
323 StringManager::getStringManager().internString(notification_name),
356 << nm <<
"\" is a reserved word. ";
360 if(nm.size() > 0 && nm[0] ==
'_'){
362 << nm <<
"\" begins with an '_' which is not permitted";
365 if(nm.find(
"__") != std::string::npos){
367 << nm <<
"\" contains two adjacent underscores which is not permitted";
372 << nm <<
"\" begins with a '" << nm[nm.size()-1] <<
"' character which is not permitted. "
373 <<
"A Notification name must not begin with a decimal digit.";
377 if(pos != std::string::npos){
379 << nm <<
"\" contains a '" << nm[pos] <<
"', which is not permitted. "
380 <<
"A Notification name must contain only alphanumeric characters and underscores.";
503 const std::string* name_id,
518 dels_.push_back(*del);
524 if(not was_observed){
533 const std::string* name_id,
544 auto delitr = std::find(
dels_.begin(),
dels_.end(), *del);
545 if(delitr !=
dels_.end()){
552 bool remaining =
false;
554 if(d.getObservationPoint() == obs_node){
559 if(
false == remaining){
577 const std::string*
id,
578 const std::string*& match)
const override {
592 virtual std::string
stringize(
bool pretty=
false)
const override {
594 std::stringstream ss;
604 virtual void onAddedAsChild_() noexcept override final {
605 determineObs_Nodes_();
618 void determineObs_Nodes_() {
629 node = node->getParent();
644 void getPossibleNotifications_(std::vector<NotificationInfo>& infos)
const override {
651 void registerObservationStateChangeCallback_(ObservationStateCallback*
const hook) {
653 sparta_assert(in_observation_state_change_callback_ ==
false,
654 "cannot add observation state change callbacks from within a callback");
658 sparta_assert(std::find(obs_state_change_cbs_.begin(), obs_state_change_cbs_.end(), hook) == obs_state_change_cbs_.end(),
659 "Internal notification hook " << *hook
660 <<
" was installed a second time to notification source " << *
this);
663 obs_state_change_cbs_.emplace_back(hook);
669 void deregisterObservationStateChangeCallback_(ObservationStateCallback*
const hook) {
671 sparta_assert(in_observation_state_change_callback_ ==
false,
672 "cannot remove observation state change callbacks from within a callback");
674 const auto itr = std::find(obs_state_change_cbs_.begin(), obs_state_change_cbs_.end(), hook);
678 "Internal notification hook " << *hook
679 <<
" was not found while attemptint to deregister it from notification source " << *
this);
682 obs_state_change_cbs_.erase(itr);
692 sparta_assert(in_observation_state_change_callback_ ==
false,
693 "cannot recursively invoke observation state change callbacks from within a "
694 "callback. User may be changing Notification Observers in response to "
695 "changes in observation state. This is not allowed");
697 in_observation_state_change_callback_ =
true;
701 for(ObservationStateCallback
const * cb : obs_state_change_cbs_){
702 if(cb->getType() == to_call){
707 in_observation_state_change_callback_ =
false;
712 in_observation_state_change_callback_ =
false;
723 std::vector<ObservationStateCallback*> obs_state_change_cbs_;
733 bool in_observation_state_change_callback_ =
false;
745 template <
typename NotificationDataT>
770 const std::string& name,
771 const std::string& group,
773 const std::string& desc,
774 const std::string* notification_name_id) :
776 desc, notification_name_id,
777 typeid(NotificationDataT))
779 static_assert(std::is_same<
780 typename std::remove_cv<
781 typename std::remove_reference<
782 typename std::remove_pointer<NotificationDataT>::type
787 "NotificationDataT must NOT be a const, volatile, pointer, or reference"
788 "type. It violates at least one of these restrictions");
796 const std::string& name,
797 const std::string& group,
799 const std::string& desc,
800 const std::string& notification_name) :
806 StringManager::getStringManager().internString(notification_name))
813 const std::string& name,
814 const std::string& desc,
815 const std::string* notification_name_id) :
821 notification_name_id)
828 const std::string& name,
829 const std::string& desc,
830 const std::string& notification_name) :
836 StringManager::getStringManager().internString(notification_name))
843 const std::string& group,
845 const std::string& desc,
846 const std::string* notification_name_id) :
852 notification_name_id)
859 const std::string& group,
861 const std::string& desc,
862 const std::string& notification_name) :
868 StringManager::getStringManager().internString(notification_name))
927 template <
typename T,
void (T::*TMethod)(const TreeNode&, const TreeNode&, const_data_type&)>
933 template <
typename T,
void (T::*TMethod)(const_data_type&)>
946 template <
typename T,
void (T::*TMethod)(const TreeNode&, const TreeNode&, const_data_type&)>
952 template <
typename T,
void (T::*TMethod)(const_data_type&)>
1005 void setFormatString(
const std::string& format_str)
1012 auto specs = parseFormatSpecifiers_(format_str);
1013 if (!parsed_specs_.empty())
1019 parsed_specs_ = specs;
1022 format_str_ = format_str;
1025 bool hasFormatString()
const {
1026 return !format_str_.empty();
1036 template <
typename... Args>
1040 "setFormatString() must be called before postNotification() on " <<
getLocation());
1042 constexpr std::array<SpecType,
sizeof...(Args)> expected_types { specTypeFor_<Args>()... };
1044 if(parsed_specs_.size() !=
sizeof...(Args)){
1046 << format_str_ <<
"\" for " <<
getLocation() <<
" has " << parsed_specs_.size()
1047 <<
" specifier(s) but " <<
sizeof...(Args) <<
" argument(s) were given";
1050 for(std::size_t i = 0; i < parsed_specs_.size(); ++i){
1051 if(parsed_specs_[i] != expected_types[i]){
1054 <<
" has a type mismatch at specifier index " << i;
1059 const std::array<std::function<void(std::ostringstream&)>,
sizeof...(Args)> streamers {
1060 [&args](std::ostringstream& o){ o << args; }...
1063 std::ostringstream oss;
1064 std::size_t arg_idx = 0;
1065 for(std::size_t i = 0; i < format_str_.size(); ++i){
1066 if(format_str_[i] !=
'%'){
1067 oss << format_str_[i];
1071 const char spec = format_str_[++i];
1075 streamers[arg_idx++](oss);
1083 enum class SpecType { STRING, INT };
1086 template <
typename T>
1087 static constexpr SpecType specTypeFor_()
1089 using PlainT =
typename std::remove_cv<typename std::remove_reference<T>::type>::type;
1090 if constexpr (std::is_integral<PlainT>::value && !std::is_same<PlainT, bool>::value){
1091 return SpecType::INT;
1093 return SpecType::STRING;
1098 static std::vector<SpecType> parseFormatSpecifiers_(
const std::string& format_str)
1100 std::vector<SpecType> specs;
1101 for(std::size_t i = 0; i < format_str.size(); ++i){
1102 if(format_str[i] !=
'%'){
1106 if(i + 1 >= format_str.size()){
1107 throw SpartaException(
"Sprintf format string \"")
1108 << format_str <<
"\" ends with a lone '%' character";
1111 const char spec = format_str[++i];
1114 specs.push_back(SpecType::STRING);
1117 specs.push_back(SpecType::INT);
1122 throw SpartaException(
"Sprintf format string \"")
1123 << format_str <<
"\" contains unsupported specifier '%" << spec
1124 <<
"'. Only %s and %i are supported";
1130 std::string format_str_;
1131 std::vector<SpecType> parsed_specs_;
1156 bool hasActiveROI()
const
1162 utils::ValidValue<uint64_t> active_roi_;
1173 template<
typename NotificationDataT>
1176 typedef std::vector<NotificationSourceBase*> SrcList;
1194 const std::string& name,
1195 const std::string& group,
1197 const std::string& desc,
1198 const std::string* notification_name_id):
1200 notification_name_id,
1201 typeid(NotificationDataT))
1209 const std::string& name,
1210 const std::string& group,
1212 const std::string& desc,
1213 const std::string& notification_name) :
1217 typeid(NotificationDataT))
1222 const std::string& name,
1223 const std::string& desc,
1224 const std::string& notification_name) :
1230 StringManager::getStringManager().internString(notification_name))
1248 const uint32_t prev_size = concretes_.size();
1249 findMatchingSourcesBelowNode_(*node, concretes_);
1253 if (concretes_.size() - prev_size == 0)
1256 ex <<
getName() <<
"\" was unable to bind to any real NotificationSources"
1257 <<
" found under the nodes provided to addLink().";
1290 findMatchingSourcesBelowNode_(*n, bases);
1296 void notificationObserverAdded_(
const std::type_info& tinfo,
1297 const std::string* name_id,
1299 const delegate* del)
override final
1301 if (del->revealsOrigin())
1303 SpartaException ex(
"Cannot register for notification \"");
1304 ex << *name_id <<
"\"" <<
" because this notification source "
1305 <<
"is only shadowing a private concrete notification source. "
1306 <<
"The callback signature type would reveal access to a private node "
1307 <<
"and be misleading. We do not support this feature at this time.";
1311 if (concretes_.size() == 0)
1313 SpartaException ex (
"Cannot register for notification \"");
1314 ex << *name_id <<
"\" because this is a MirrorNotificationSource "
1315 <<
"that is not linked to any concrete sources. It is possible you "
1316 <<
"are registering for the notification too early and should be registering "
1317 <<
"during onBindTreeLate_()";
1320 for(
auto concrete : concretes_)
1322 concrete->notificationObserverAdded_(tinfo, name_id,
1328 void notificationObserverRemoved_(
const std::type_info& tinfo,
1329 const std::string* name_id,
1331 const delegate* del)
override final
1333 if (concretes_.size() == 0)
1335 SpartaException ex (
"Cannot deregister for notification \"");
1336 ex << *name_id <<
"\" because this is a MirrorNotificationSource "
1337 <<
"that is not linked to any concrete sources. It is possible you "
1338 <<
"are deregistering for the notification too early and should be registering "
1339 <<
"during onBindTreeLate_()";
1343 for(
auto concrete : concretes_)
1345 concrete->notificationObserverRemoved_(tinfo, name_id,
1351 bool canGenerateNotification_(
const std::type_info& tinfo,
1352 const std::string*
id,
1353 const std::string*& match)
const override final
1355 if (concretes_.size() == 0)
1359 bool can_generate =
true;
1360 for (
auto noti_src : concretes_)
1362 can_generate &= noti_src->canGenerateNotification_(tinfo,
id, match);
1364 return can_generate;
1373 void validateNode_() const override final
1375 if (concretes_.size() == 0)
1377 SpartaException ex(
"Unbound MirrorNotificationSource ");
1378 ex <<
getName() <<
" was never bound to concrete notification sources.";
1384 virtual std::string stringize(
bool pretty=
false) const override final {
1386 std::stringstream ss;
1390 ss << concretes_.size() <<
" sources ";
1392 catch (SpartaException&)
1394 ss <<
"[UNAVAILABLE]";
1402 inline std::ostream&
operator<<(std::ostream& o,
const NotificationSourceBase::ObservationStateCallback& osc)
1408 inline std::ostream&
operator<<(std::ostream& o,
const NotificationSourceBase::ObservationStateCallback* osc)
Set of macros for Sparta assertions. Caught by the framework.
#define sparta_assert(...)
Simple variadic assertion that will throw a sparta_exception if the condition fails.
Exception class for all of Sparta.
Basic Node framework in sparta device tree composite pattern.
#define RESERVED_WORDS
Reserved words in Python language, Python builtins, and other reservations. TreeNode names and groups...
#define ALPHANUM_CHARS
Enables tracing of TreeNode lifetimes in a set of output txt files.
#define DIGIT_CHARS
Digit characters (for valid TreeNode groups)
File that defines a ValidValue.
essentially a pass through notification source that is a placeholder in a shadow tree.
MirrorNotificationSource(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string *notification_name_id)
MirrorNotificationSource.
void addLink(TreeNode *node, const std::string &label) override final
MirrorNotificationSource(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string ¬ification_name)
Alternate construct that accepts a notification name string instead of an interned string pointer.
Controlled interface to NotificationSourceBase for regiistering and deregistering observation state c...
Callback for observation-state of a NotificationSourceBase.
void operator()(NotificationSourceBase const &ns, uint32_t observers) const
Invoked the callback function.
void dump(std::ostream &o) const
Dump string description to an ostream.
ObservationStateChange getType() const
Get tyhe type of change associated with this callback instance.
A TreeNode that generates a single specific type of notification which propagates up a tree of TreeNo...
virtual ~NotificationSourceBase()
Destructor.
static void validateNotificationName(const std::string &nm)
Validates the given notification name string.
bool observed_
Cached value of obs_nodes_.size() > 0 for faster queries.
friend class ObservationStateCallbackInterface
Allow controlled interaction with some members of this class.
bool canGenerateNotification_(const std::type_info &tinfo, const std::string *id, const std::string *&match) const override
Implements TreeNode::canGenerateNotification. Node subclasses which will post notifications must impl...
const std::string & getNotificationName() const
Returns the notification name string for slow string comparison or printing.
ObservationStateChange
Various hook types for which one can register internal callbacks on this notificaiton source.
@ SOLE_OBSERVER_REGISTERING
A sole observer is being registered to observe this notification source. This is a transition from 0 ...
@ OBSERVER_REGISTERING
An observer is being registered to observe this notification source. This may be the first,...
@ SOLE_OBSERVER_DEREGISTERING
A sole observer is being de-registered from observing this notification source. This is a transition ...
@ OBSERVER_DEREGISTERING
An observer is being de-registered from observing this notification source. This may be the first,...
uint32_t getNumObservers() const
Returns the number of delegates affected by postings of this notification.
std::vector< TreeNode * > obs_nodes_
Vector of TreeNodes at which the notification that this node can generate is being observed.
bool observed() const noexcept
Is this NotificationSourceBase being observed at this node or an ancestor of any distance.
virtual void notificationObserverRemoved_(const std::type_info &tinfo, const std::string *name_id, TreeNode *obs_node, const delegate *del) override
NotificationSourceBase(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string *notification_name_id, const std::type_info ¬ification_tinfo)
NotificationSourceBase.
virtual std::string stringize(bool pretty=false) const override
Create a string representation of this node.
std::function< void(NotificationSourceBase const &, uint32_t)> callback_t
Observation state change callback function signature.
const std::type_info & noti_tinfo_
Type of notification data.
virtual void notificationObserverAdded_(const std::type_info &tinfo, const std::string *name_id, TreeNode *obs_node, const delegate *del) override
uint64_t getNumPosts() const
Returns the number of notifications posted by this node.
NotificationSourceBase(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string ¬ification_name, const std::type_info ¬ification_tinfo)
Alternate construct that accepts a notification name string instead of an interned string pointer.
friend class MirrorNotificationSource
uint32_t getNumObservationPoints() const
Returns the number of observation points affecting this notification source.
const std::string getNotificationTypeName() const
Gets the demangled name of the C++ notification type which this NotificationSource can emit.
const std::vector< TreeNode * > & getObservationPoints() const
Returns the vector of observation points on this notification source.
const std::type_info & getNotificationType() const
Returns std::type_info from typeid() on the notification data type which this NotificationSource can ...
uint64_t num_posts_
Number of messages posted whether observed or not.
const std::string * noti_id_
Name of notification generated. Should be similar to node name.
std::vector< delegate > dels_
Vector of delegates directly observing this notification source.
const std::string * getNotificationID() const
Returns notification ID (string pointer from Notification ID interned in sparta::StringManager)
A TreeNode that generates a specific type of notification which propagates up a tree of TreeNodes (us...
void deregisterForThis(T *obj)
Deregisters a callback method that was registered with registerForThis.
~NotificationSource()
Destructor.
void postNotification(const NotificationDataT &data) const
Post with reference to data with parent as message origin.
void registerForThis(T *obj)
Registers a callback method to listen for the notification generated by this NotificationSource....
NotificationDataT data_type
Type of notification data generated by this instance.
NotificationSource(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string *notification_name_id)
NotificationSource.
NotificationDataT const const_data_type
Const qualified data type.
Notification source that announces the active report region of interest (ROI). Setting the active ROI...
uint64_t getActiveROI() const
void setActiveROI(uint64_t roi)
Remember the given ROI and post it to observers.
Used to construct and throw a standard C++ exception. Inherits from std::exception.
Accepts a sprintf-style format string like "%s_%i.json" and uses the arguments given to postNotificat...
void postNotification(Args... args) const
Formats the current format string (see setFormatString) with args and posts the resulting std::string...
Manages string internment for SPARTA. This allows strings to be compared by pointer once interned.
static StringManager & getStringManager()
Returns the StringManager singleton.
Temporary delegate for notificaiton invokation until the implementation is working....
Node in a composite tree representing a sparta Tree item.
std::string getLocation() const override final
static constexpr char GROUP_NAME_NONE[]
Group name indicating that a node belongs to no group.
static bool notificationCategoryMatch(const std::string *query_id, const std::string *node_id)
Checks if two notification categories match where one is an actual category.
void registerForNotification(T *obj, const std::string &name, bool ensure_possible=true)
Registers a callback method to listen for all notifications having the specified data type DataT and ...
TreeNode()=delete
Not default-constructable.
const ChildrenVector getChildren() const
Gets a vector of all children of this node in any group in the order in which they were added to this...
void addChild(TreeNode *child, bool inherit_phase=true)
Adds a TreeNode to this node as a child.
uint32_t group_idx_type
Index within a group.
void deregisterForNotification(T *obj, const std::string &name)
Removes at most one registration made with registerForNotification.
WeakPtr getWeakPtr()
Gets a weak pointer to this TreeNode. This weak pointer is guaranteed to expire when this TreeNode is...
static TreeNode * getVirtualGlobalNode()
Gets the virtual global node singleton. This node can have no parent and no children....
static constexpr group_idx_type GROUP_IDX_NONE
GroupIndex indicating that a node has no group index because it belongs to no group.
std::vector< delegate > DelegateVector
Vector of delegates representing a list of observers to notify.
const std::string & getName() const override
Gets the name of this node.
void setExpectedParent_(const TreeNode *parent)
Tracks a node as an expected parent without actually adding this node as a child. This is used almost...
std::weak_ptr< const TreeNode > ConstWeakPtr
Weak pointer to a const TreeNode. Acquire with getWeakPtr.
constexpr bool isValid() const
Is this value valid.
Macros for handling exponential backoff.
std::ostream & operator<<(std::ostream &o, const SimulationInfo &info)
ostream insertion operator for SimulationInfo
std::string demangle(const std::string &name) noexcept
Demangles a C++ symbol.
Type for indicating that ANY notification source type should be included in a search performed by loc...