-
Notifications
You must be signed in to change notification settings - Fork 32
/
offset.go
53 lines (42 loc) · 1.25 KB
/
offset.go
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
package resource
import (
"fmt"
"hash/fnv"
"math"
"os"
"time"
"github.com/concourse/time-resource/lord"
)
const BUILD_TEAM_NAME = "BUILD_TEAM_NAME"
const BUILD_PIPELINE_NAME = "BUILD_PIPELINE_NAME"
const BUILD_PIPELINE_INSTANCE_VARS = "BUILD_PIPELINE_INSTANCE_VARS"
const maxHashValue = int64(math.MaxUint32)
var msPerMinute = time.Minute.Milliseconds()
func Offset(tl lord.TimeLord, reference time.Time) time.Time {
str := fmt.Sprintf(
"%s/%s/%s",
os.Getenv(BUILD_TEAM_NAME),
os.Getenv(BUILD_PIPELINE_NAME),
os.Getenv(BUILD_PIPELINE_INSTANCE_VARS),
)
hasher := fnv.New32a()
if _, err := hasher.Write([]byte(str)); err != nil {
fmt.Fprintln(os.Stderr, "hash error:", err.Error())
os.Exit(1)
}
hash := int64(hasher.Sum32())
start, stop := tl.LatestRangeBefore(reference)
rangeDuration := stop.Sub(start)
if tl.Interval != nil {
if intervalDuration := time.Duration(*tl.Interval); intervalDuration < rangeDuration {
rangeDuration = intervalDuration
start = reference.Truncate(rangeDuration)
}
}
if rangeDuration <= time.Minute {
return start
}
hashPerMinute := maxHashValue / (rangeDuration.Milliseconds() / msPerMinute)
offsetDuration := time.Duration(hash/hashPerMinute) * time.Minute
return start.Add(offsetDuration)
}