stat.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #pragma once
  2. #include <util/generic/ptr.h>
  3. #include <util/stream/output.h>
  4. #include <library/cpp/deprecated/atomic/atomic.h>
  5. #include <library/cpp/deprecated/atomic/atomic_ops.h>
  6. namespace NNeh {
  7. class TStatCollector;
  8. /// NEH service workability statistics collector.
  9. ///
  10. /// Disabled by default, use `TServiceStat::ConfigureValidator` to set `maxContinuousErrors`
  11. /// different from zero.
  12. class TServiceStat: public TThrRefBase {
  13. public:
  14. static void ConfigureValidator(unsigned maxContinuousErrors, unsigned reSendValidatorPeriod) noexcept {
  15. AtomicSet(MaxContinuousErrors_, maxContinuousErrors);
  16. AtomicSet(ReSendValidatorPeriod_, reSendValidatorPeriod);
  17. }
  18. static bool Disabled() noexcept {
  19. return !AtomicGet(MaxContinuousErrors_);
  20. }
  21. enum EStatus {
  22. Ok,
  23. Fail,
  24. ReTry //time for sending request-validator to service
  25. };
  26. EStatus GetStatus();
  27. void DbgOut(IOutputStream&) const;
  28. protected:
  29. friend class TStatCollector;
  30. virtual void OnBegin();
  31. virtual void OnSuccess();
  32. virtual void OnCancel();
  33. virtual void OnFail();
  34. static TAtomic MaxContinuousErrors_;
  35. static TAtomic ReSendValidatorPeriod_;
  36. TAtomicCounter RequestsInProcess_;
  37. TAtomic LastContinuousErrors_ = 0;
  38. TAtomic SendValidatorCounter_ = 0;
  39. };
  40. using TServiceStatRef = TIntrusivePtr<TServiceStat>;
  41. //thread safe (race protected) service stat updater
  42. class TStatCollector {
  43. public:
  44. TStatCollector(TServiceStatRef& ss)
  45. : SS_(ss)
  46. {
  47. ss->OnBegin();
  48. }
  49. ~TStatCollector() {
  50. if (CanInformSS()) {
  51. SS_->OnFail();
  52. }
  53. }
  54. void OnCancel() noexcept {
  55. if (CanInformSS()) {
  56. SS_->OnCancel();
  57. }
  58. }
  59. void OnFail() noexcept {
  60. if (CanInformSS()) {
  61. SS_->OnFail();
  62. }
  63. }
  64. void OnSuccess() noexcept {
  65. if (CanInformSS()) {
  66. SS_->OnSuccess();
  67. }
  68. }
  69. private:
  70. inline bool CanInformSS() noexcept {
  71. return AtomicGet(CanInformSS_) && AtomicCas(&CanInformSS_, 0, 1);
  72. }
  73. TServiceStatRef SS_;
  74. TAtomic CanInformSS_ = 1;
  75. };
  76. TServiceStatRef GetServiceStat(TStringBuf addr);
  77. }