2
0

resolution.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. intervalDef: configuration.Interval,
  25. retention: configuration.Retention,
  26. }, nil
  27. }
  28. // Retention is a getter which returns the retention of the Resolution
  29. func (r *Resolution) Retention() int {
  30. return r.retention
  31. }
  32. // Interval is a getter which returns the interval definition string of the Resolution
  33. func (r *Resolution) Interval() string {
  34. return r.intervalDef
  35. }
  36. // Current returns the time that the current interval began
  37. func (r *Resolution) Current() time.Time {
  38. return r.interval.Truncate(time.Now())
  39. }
  40. // Next returns the time that the next interval will start at
  41. func (r *Resolution) Next() time.Time {
  42. return r.interval.Add(r.interval.Truncate(time.Now()), 1)
  43. }
  44. // Limit returns the time that oldest interval in retention began
  45. func (r *Resolution) Limit() time.Time {
  46. return r.interval.Add(r.interval.Truncate(time.Now()), -(r.retention - 1))
  47. }
  48. // Get returns the interval start time for the given time
  49. func (r *Resolution) Get(t time.Time) time.Time {
  50. return r.interval.Truncate(t)
  51. }