resolution.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package util
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. type ResolutionConfiguration struct {
  7. Interval string
  8. Retention int
  9. }
  10. // Resolution is a utility for maintaining a set of windows that span the time period defined by the interval and
  11. // with a count of retention.
  12. type Resolution struct {
  13. interval Interval
  14. intervalDef string
  15. retention int
  16. }
  17. func NewResolution(configuration ResolutionConfiguration) (*Resolution, error) {
  18. interval, err := NewInterval(configuration.Interval)
  19. if err != nil {
  20. return nil, fmt.Errorf("failed to create resolution: %w", err)
  21. }
  22. return &Resolution{
  23. interval: interval,
  24. retention: configuration.Retention,
  25. }, nil
  26. }
  27. // Retention is a getter which returns the retention of the Resolution
  28. func (r *Resolution) Retention() int {
  29. return r.retention
  30. }
  31. // Interval is a getter which returns the interval definition string of the Resolution
  32. func (r *Resolution) Interval() string {
  33. return r.intervalDef
  34. }
  35. // Current returns the time that the current interval began
  36. func (r *Resolution) Current() time.Time {
  37. return r.interval.Truncate(time.Now())
  38. }
  39. // Next returns the time that the next interval will start at
  40. func (r *Resolution) Next() time.Time {
  41. return r.interval.Add(r.interval.Truncate(time.Now()), 1)
  42. }
  43. // Limit returns the time that oldest interval in retention began
  44. func (r *Resolution) Limit() time.Time {
  45. return r.interval.Add(r.interval.Truncate(time.Now()), -(r.retention - 1))
  46. }
  47. // Get returns the interval start time for the given time
  48. func (r *Resolution) Get(t time.Time) time.Time {
  49. return r.interval.Truncate(t)
  50. }