-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTimeUtils.go
More file actions
339 lines (316 loc) · 11.8 KB
/
TimeUtils.go
File metadata and controls
339 lines (316 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
* Copyright (c) 2024. Devtron Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package utils
import (
"fmt"
"strings"
"time"
)
type TimeRangeRequest struct {
From *time.Time `json:"from" schema:"from"`
To *time.Time `json:"to" schema:"to"`
TimeWindow *TimeWindows `json:"timeWindow" schema:"timeWindow" validate:"omitempty,oneof=today yesterday week month quarter lastWeek lastMonth lastQuarter last24Hours last7Days last30Days last90Days"`
}
func NewTimeRangeRequest(from *time.Time, to *time.Time) *TimeRangeRequest {
return &TimeRangeRequest{
From: from,
To: to,
}
}
func NewTimeWindowRequest(timeWindow TimeWindows) *TimeRangeRequest {
return &TimeRangeRequest{
TimeWindow: &timeWindow,
}
}
// TimeWindows is a string type that represents different time windows
type TimeWindows string
func (timeRange TimeWindows) String() string {
return string(timeRange)
}
// Define constants for different time windows
const (
Today TimeWindows = "today"
Yesterday TimeWindows = "yesterday"
Week TimeWindows = "week"
Month TimeWindows = "month"
Quarter TimeWindows = "quarter"
LastWeek TimeWindows = "lastWeek"
LastMonth TimeWindows = "lastMonth"
Year TimeWindows = "year"
LastQuarter TimeWindows = "lastQuarter"
Last24Hours TimeWindows = "last24Hours"
Last7Days TimeWindows = "last7Days"
Last30Days TimeWindows = "last30Days"
Last90Days TimeWindows = "last90Days"
)
func (timeRange *TimeRangeRequest) ParseAndValidateTimeRange() (*TimeRangeRequest, error) {
if timeRange == nil {
return NewTimeRangeRequest(&time.Time{}, &time.Time{}), fmt.Errorf("invalid time range request. either from/to or timeWindow must be provided")
}
now := time.Now()
// If timeWindow is provided, it takes preference over from/to
if timeRange.TimeWindow != nil {
switch *timeRange.TimeWindow {
case Today:
start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
return NewTimeRangeRequest(&start, &now), nil
case Yesterday:
start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Add(-24 * time.Hour)
end := start.Add(24 * time.Hour)
return NewTimeRangeRequest(&start, &end), nil
case Week:
// Current week (Monday to Sunday)
weekday := int(now.Weekday())
if weekday == 0 { // Sunday
weekday = 7
}
start := now.AddDate(0, 0, -(weekday - 1)).Truncate(24 * time.Hour)
return NewTimeRangeRequest(&start, &now), nil
case Month:
start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
return NewTimeRangeRequest(&start, &now), nil
case Quarter:
quarter := ((int(now.Month()) - 1) / 3) + 1
quarterStart := time.Month((quarter-1)*3 + 1)
start := time.Date(now.Year(), quarterStart, 1, 0, 0, 0, 0, now.Location())
return NewTimeRangeRequest(&start, &now), nil
case LastWeek:
weekday := int(now.Weekday())
if weekday == 0 { // Sunday
weekday = 7
}
thisWeekStart := now.AddDate(0, 0, -(weekday - 1)).Truncate(24 * time.Hour)
lastWeekStart := thisWeekStart.AddDate(0, 0, -7)
lastWeekEnd := thisWeekStart.Add(-time.Second)
return NewTimeRangeRequest(&lastWeekStart, &lastWeekEnd), nil
case LastMonth:
thisMonthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
lastMonthStart := thisMonthStart.AddDate(0, -1, 0)
lastMonthEnd := thisMonthStart.Add(-time.Second)
return NewTimeRangeRequest(&lastMonthStart, &lastMonthEnd), nil
case LastQuarter:
// Calculate current quarter
currentQuarter := ((int(now.Month()) - 1) / 3) + 1
// Calculate previous quarter
var prevQuarter int
var prevYear int
if currentQuarter == 1 {
// If current quarter is Q1, previous quarter is Q4 of previous year
prevQuarter = 4
prevYear = now.Year() - 1
} else {
// Otherwise, previous quarter is in the same year
prevQuarter = currentQuarter - 1
prevYear = now.Year()
}
// Calculate start and end of previous quarter
prevQuarterStartMonth := time.Month((prevQuarter-1)*3 + 1)
prevQuarterStart := time.Date(prevYear, prevQuarterStartMonth, 1, 0, 0, 0, 0, now.Location())
// End of previous quarter is the start of current quarter minus 1 second
currentQuarterStartMonth := time.Month((currentQuarter-1)*3 + 1)
currentQuarterStart := time.Date(now.Year(), currentQuarterStartMonth, 1, 0, 0, 0, 0, now.Location())
if currentQuarter == 1 {
// If current quarter is Q1, we need to calculate Q4 end of previous year
currentQuarterStart = time.Date(now.Year(), time.January, 1, 0, 0, 0, 0, now.Location())
}
prevQuarterEnd := currentQuarterStart.Add(-time.Second)
return NewTimeRangeRequest(&prevQuarterStart, &prevQuarterEnd), nil
case Year:
start := time.Date(now.Year(), 1, 1, 0, 0, 0, 0, now.Location())
return NewTimeRangeRequest(&start, &now), nil
case Last24Hours:
start := now.Add(-24 * time.Hour)
return NewTimeRangeRequest(&start, &now), nil
case Last7Days:
start := now.AddDate(0, 0, -7)
return NewTimeRangeRequest(&start, &now), nil
case Last30Days:
start := now.AddDate(0, 0, -30)
return NewTimeRangeRequest(&start, &now), nil
case Last90Days:
start := now.AddDate(0, 0, -90)
return NewTimeRangeRequest(&start, &now), nil
default:
return NewTimeRangeRequest(&time.Time{}, &time.Time{}), fmt.Errorf("unsupported time window: %q", *timeRange.TimeWindow)
}
}
// Use from/to dates if provided
if timeRange.From != nil && timeRange.To != nil {
if timeRange.From.After(*timeRange.To) {
return NewTimeRangeRequest(&time.Time{}, &time.Time{}), fmt.Errorf("from date cannot be after to date")
}
return NewTimeRangeRequest(timeRange.From, timeRange.To), nil
} else {
return NewTimeRangeRequest(&time.Time{}, &time.Time{}), fmt.Errorf("from and to dates are required if time window is not provided")
}
}
// TimeBoundariesRequest represents the request for time boundary frames
type TimeBoundariesRequest struct {
TimeWindowBoundaries []string `json:"timeWindowBoundaries" schema:"timeWindowBoundaries" validate:"omitempty,min=1"`
TimeWindow *TimeWindows `json:"timeWindow" schema:"timeWindow" validate:"omitempty,oneof=week month quarter year"` // week, month, quarter, year
Iterations int `json:"iterations" schema:"iterations" validate:"omitempty,min=1"`
}
// TimeWindowBoundaries represents the start and end times for a time window
type TimeWindowBoundaries struct {
StartTime time.Time
EndTime time.Time
}
func (timeBoundaries *TimeBoundariesRequest) ParseAndValidateTimeBoundaries() ([]TimeWindowBoundaries, error) {
if timeBoundaries == nil {
return []TimeWindowBoundaries{}, fmt.Errorf("invalid time boundaries request")
}
// If timeWindow is provided, it takes preference over timeWindowBoundaries
if timeBoundaries.TimeWindow != nil {
switch *timeBoundaries.TimeWindow {
case Week:
return GetWeeklyTimeBoundaries(timeBoundaries.Iterations), nil
case Month:
return GetMonthlyTimeBoundaries(timeBoundaries.Iterations), nil
case Quarter:
return GetQuarterlyTimeBoundaries(timeBoundaries.Iterations), nil
case Year:
return GetYearlyTimeBoundaries(timeBoundaries.Iterations), nil
default:
return []TimeWindowBoundaries{}, fmt.Errorf("unsupported time window: %q", *timeBoundaries.TimeWindow)
}
} else if len(timeBoundaries.TimeWindowBoundaries) != 0 {
// Validate time window
return DecodeAndValidateTimeWindowBoundaries(timeBoundaries.TimeWindowBoundaries)
} else {
return []TimeWindowBoundaries{}, fmt.Errorf("time window boundaries are required if time window is not provided")
}
}
func GetWeeklyTimeBoundaries(iterations int) []TimeWindowBoundaries {
if iterations <= 0 {
return []TimeWindowBoundaries{}
}
boundaries := make([]TimeWindowBoundaries, iterations)
now := time.Now()
weekday := int(now.Weekday())
if weekday == 0 {
weekday = 7
}
// Get start of this week (Monday)
weekStart := now.AddDate(0, 0, -(weekday - 1))
// Set time to midnight
weekStart = time.Date(weekStart.Year(), weekStart.Month(), weekStart.Day(), 0, 0, 0, 0, weekStart.Location())
for i := 0; i < iterations; i++ {
start := weekStart.AddDate(0, 0, -7*i)
end := start.AddDate(0, 0, 7)
// For the current week, if now < end, set end = now
if i == 0 && now.Before(end) {
end = now
}
boundaries[i] = TimeWindowBoundaries{
StartTime: start,
EndTime: end,
}
}
return boundaries
}
func GetMonthlyTimeBoundaries(iterations int) []TimeWindowBoundaries {
if iterations <= 0 {
return []TimeWindowBoundaries{}
}
boundaries := make([]TimeWindowBoundaries, iterations)
now := time.Now()
// Get start of this month (1st)
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
for i := 0; i < iterations; i++ {
start := monthStart.AddDate(0, -i, 0)
end := start.AddDate(0, 1, 0)
// For the current month, if now < end, set end = now
if i == 0 && now.Before(end) {
end = now
}
boundaries[i] = TimeWindowBoundaries{
StartTime: start,
EndTime: end,
}
}
return boundaries
}
func GetQuarterlyTimeBoundaries(iterations int) []TimeWindowBoundaries {
if iterations <= 0 {
return []TimeWindowBoundaries{}
}
boundaries := make([]TimeWindowBoundaries, iterations)
now := time.Now()
quarter := ((int(now.Month()) - 1) / 3) + 1
quarterMonth := time.Month((quarter-1)*3 + 1)
// Get start of this quarter (1st of the month)
quarterStart := time.Date(now.Year(), quarterMonth, 1, 0, 0, 0, 0, now.Location())
for i := 0; i < iterations; i++ {
start := quarterStart.AddDate(0, -3*i, 0)
end := start.AddDate(0, 3, 0)
// For the current quarter, if now < end, set end = now
if i == 0 && now.Before(end) {
end = now
}
boundaries[i] = TimeWindowBoundaries{
StartTime: start,
EndTime: end,
}
}
return boundaries
}
func GetYearlyTimeBoundaries(iterations int) []TimeWindowBoundaries {
if iterations <= 0 {
return []TimeWindowBoundaries{}
}
boundaries := make([]TimeWindowBoundaries, iterations)
now := time.Now()
// Get start of this year (1st of January)
yearStart := time.Date(now.Year(), 1, 1, 0, 0, 0, 0, now.Location())
for i := 0; i < iterations; i++ {
start := yearStart.AddDate(-i, 0, 0)
end := start.AddDate(1, 0, 0)
// For the current year, if now < end, set end = now
if i == 0 && now.Before(end) {
end = now
}
boundaries[i] = TimeWindowBoundaries{
StartTime: start,
EndTime: end,
}
}
return boundaries
}
func DecodeAndValidateTimeWindowBoundaries(timeWindowBoundaries []string) ([]TimeWindowBoundaries, error) {
boundaries := make([]TimeWindowBoundaries, 0, len(timeWindowBoundaries))
for _, boundary := range timeWindowBoundaries {
parts := strings.Split(boundary, "|")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid time window boundary format: %q", boundary)
}
startTime, err := time.Parse(time.RFC3339, parts[0])
if err != nil {
return nil, fmt.Errorf("invalid start time format: %q. expected format: %q", parts[0], time.RFC3339)
}
endTime, err := time.Parse(time.RFC3339, parts[1])
if err != nil {
return nil, fmt.Errorf("invalid end time format: %q. expected format: %q", parts[1], time.RFC3339)
}
if startTime.After(endTime) {
return nil, fmt.Errorf("start time cannot be after end time: %q", boundary)
}
boundaries = append(boundaries, TimeWindowBoundaries{
StartTime: startTime,
EndTime: endTime,
})
}
return boundaries, nil
}