1// Copyright (C) 2021 Storj Labs, Inc.
2// See LICENSE for copying information.
3
4package storage
5
6import (
7	"sort"
8	"time"
9)
10
11// Usage holds storage usage stamps and summary for a particular period.
12type Usage struct {
13	Stamps  []UsageStamp `json:"stamps"`
14	Summary float64      `json:"summary"`
15}
16
17// UsageStamp holds data at rest total for an interval beginning at interval start.
18type UsageStamp struct {
19	AtRestTotal   float64   `json:"atRestTotal"`
20	IntervalStart time.Time `json:"intervalStart"`
21}
22
23// UsageStampDailyCache caches storage usage stamps by interval date.
24type UsageStampDailyCache map[time.Time]UsageStamp
25
26// Add adds usage stamp to cache aggregating at rest data by date.
27func (cache *UsageStampDailyCache) Add(stamp UsageStamp) {
28	year, month, day := stamp.IntervalStart.UTC().Date()
29	intervalStart := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
30
31	cached := *cache
32
33	cacheStamp, ok := cached[intervalStart]
34	if ok {
35		cached[intervalStart] = UsageStamp{
36			AtRestTotal:   cacheStamp.AtRestTotal + stamp.AtRestTotal,
37			IntervalStart: intervalStart,
38		}
39	} else {
40		cached[intervalStart] = UsageStamp{
41			AtRestTotal:   stamp.AtRestTotal,
42			IntervalStart: intervalStart,
43		}
44	}
45
46	*cache = cached
47}
48
49// Sorted returns usage stamp slice sorted by interval start.
50func (cache *UsageStampDailyCache) Sorted() []UsageStamp {
51	var usage []UsageStamp
52
53	for _, stamp := range *cache {
54		usage = append(usage, stamp)
55	}
56	sort.Slice(usage, func(i, j int) bool {
57		return usage[i].IntervalStart.Before(usage[j].IntervalStart)
58	})
59
60	return usage
61}
62
63// DiskSpace stores all info about storagenode disk space usage.
64type DiskSpace struct {
65	Allocated int64 `json:"allocated"`
66	Used      int64 `json:"usedPieces"`
67	Trash     int64 `json:"usedTrash"`
68	Free      int64 `json:"free"`
69	Available int64 `json:"available"`
70	Overused  int64 `json:"overused"`
71}
72
73// Add combines disk space with another one.
74func (diskSpace *DiskSpace) Add(space DiskSpace) {
75	diskSpace.Allocated += space.Allocated
76	diskSpace.Used += space.Used
77	diskSpace.Trash += space.Trash
78	diskSpace.Free += space.Free
79	diskSpace.Available += space.Available
80	diskSpace.Overused += space.Overused
81}
82