helper.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package model
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/opencost/opencost/core/pkg/model/pb"
  6. "github.com/opencost/opencost/core/pkg/opencost"
  7. "github.com/opencost/opencost/core/pkg/util/timeutil"
  8. )
  9. // ConvertWindow validates and converts a protobuf window to a closed opencost.Window or returns an error
  10. func ConvertWindow(window *pb.Window) (opencost.Window, error) {
  11. if window == nil {
  12. return opencost.Window{}, fmt.Errorf("cannot convert nil window")
  13. }
  14. var res time.Duration
  15. switch window.Resolution {
  16. case pb.Resolution_RESOLUTION_1D:
  17. res = timeutil.Day
  18. case pb.Resolution_RESOLUTION_1H:
  19. res = time.Hour
  20. case pb.Resolution_RESOLUTION_10M:
  21. res = time.Minute * 10
  22. default:
  23. return opencost.Window{}, fmt.Errorf("invalid window resolution %v", window.Resolution)
  24. }
  25. start := window.Start.AsTime().UTC()
  26. if !start.Equal(start.Truncate(res)) {
  27. return opencost.Window{}, fmt.Errorf("invalid start time for resolution '%s': %s", window.Resolution, start.Format(time.RFC3339))
  28. }
  29. win := opencost.NewClosedWindow(start, start.Add(res))
  30. return win, nil
  31. }