custom_action.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #pragma once
  2. #include "probe.h"
  3. #include <library/cpp/lwtrace/protos/lwtrace.pb.h>
  4. #include <util/generic/hash.h>
  5. #include <functional>
  6. namespace NLWTrace {
  7. class TSession;
  8. // Custom action can save any stuff (derived from IResource) in TSession object
  9. // IMPORTANT: Derived class will be used from multiple threads! (see example3)
  10. class IResource: public TAtomicRefCount<IResource> {
  11. public:
  12. virtual ~IResource() {
  13. }
  14. };
  15. using TResourcePtr = TIntrusivePtr<IResource>;
  16. // Trace resources that is used to hold/get/create any stuff
  17. class TTraceResources: public THashMap<TString, TResourcePtr> {
  18. public:
  19. template <class T>
  20. T& Get(const TString& name) {
  21. auto iter = find(name);
  22. if (iter == end()) {
  23. iter = insert(value_type(name, TResourcePtr(new T()))).first;
  24. }
  25. return *static_cast<T*>(iter->second.Get());
  26. }
  27. template <class T>
  28. const T* GetOrNull(const TString& name) const {
  29. auto iter = find(name);
  30. if (iter == end()) {
  31. return nullptr;
  32. }
  33. return *iter->second;
  34. }
  35. };
  36. // Base class of all custom actions
  37. class TCustomActionExecutor: public IExecutor {
  38. protected:
  39. TProbe* const Probe;
  40. bool Destructive;
  41. public:
  42. TCustomActionExecutor(TProbe* probe, bool destructive)
  43. : IExecutor()
  44. , Probe(probe)
  45. , Destructive(destructive)
  46. {
  47. }
  48. bool IsDestructive() {
  49. return Destructive;
  50. }
  51. };
  52. // Factory to produce custom action executors
  53. class TCustomActionFactory {
  54. public:
  55. using TCallback = std::function<TCustomActionExecutor*(TProbe* probe, const TCustomAction& action, TSession* trace)>;
  56. TCustomActionExecutor* Create(TProbe* probe, const TCustomAction& action, TSession* trace) const;
  57. void Register(const TString& name, const TCallback& callback);
  58. private:
  59. THashMap<TString, TCallback> Callbacks;
  60. };
  61. }