time_utils.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #pragma once
  2. #include <nlohmann/json.hpp>
  3. #include <chrono>
  4. #include <string>
  5. #include <ctime>
  6. namespace smartbotic::common {
  7. class TimeUtils {
  8. public:
  9. using Clock = std::chrono::system_clock;
  10. using TimePoint = Clock::time_point;
  11. using Duration = Clock::duration;
  12. // Get current timestamp in milliseconds
  13. static int64_t nowMs();
  14. /**
  15. * A document's stored timestamp, in milliseconds.
  16. *
  17. * The database names document metadata one fixed way - _created_at,
  18. * _updated_at - and writes it in nanoseconds. Reading it with a guessed
  19. * spelling silently yields zero, which every screen renders as "unknown";
  20. * that was true of credentials, users, sessions and node definitions at
  21. * once. The unit is checked rather than divided blindly, because a value
  22. * already in milliseconds divided again lands in 1970.
  23. */
  24. static int64_t documentStamp(const nlohmann::json& document, const char* key);
  25. // Get current timestamp in seconds
  26. static int64_t nowSec();
  27. // Get current timestamp as TimePoint
  28. static TimePoint now();
  29. // Convert milliseconds to TimePoint
  30. static TimePoint fromMs(int64_t ms);
  31. // Convert TimePoint to milliseconds
  32. static int64_t toMs(TimePoint tp);
  33. // Format timestamp as ISO 8601 string
  34. static std::string toIso8601(int64_t ms);
  35. static std::string toIso8601(TimePoint tp);
  36. // Parse ISO 8601 string to milliseconds
  37. static int64_t parseIso8601(const std::string& str);
  38. // Check if timestamp has expired
  39. static bool isExpired(int64_t expiryMs);
  40. static bool isExpired(TimePoint expiry);
  41. // Add duration to timestamp
  42. static int64_t addMs(int64_t timestampMs, int64_t durationMs);
  43. static int64_t addSec(int64_t timestampMs, int64_t durationSec);
  44. };
  45. // RAII timer for measuring durations
  46. class ScopedTimer {
  47. public:
  48. explicit ScopedTimer(const std::string& name = "");
  49. ~ScopedTimer();
  50. int64_t elapsedMs() const;
  51. void reset();
  52. private:
  53. std::string name_;
  54. TimeUtils::TimePoint start_;
  55. };
  56. } // namespace smartbotic::common