/
state.go
121 lines (106 loc) · 2.47 KB
/
state.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
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
package main
import (
"encoding/json"
"fmt"
"time"
"github.com/akerl/go-lambda/s3"
"gopkg.in/yaml.v2"
)
const maxBlind = 99_999
type state struct {
Timer time.Time `json:"timer"`
Interval int `json:"interval"`
Small int `json:"small"`
Big int `json:"big"`
PauseTime time.Time `json:"pausetime"`
}
type stateUpdate struct {
Interval int `form:"interval" json:"interval"`
Small int `form:"small" json:"small"`
Big int `form:"big" json:"big"`
Pause bool `form:"pause" json:"pause"`
Resume bool `form:"resume" json:"resume"`
}
type serializedState struct {
Timer string `json:"timer"`
Small int `json:"small"`
Big int `json:"big"`
Paused bool `json:"paused"`
}
func (s *state) ToJSON() ([]byte, error) {
return json.Marshal(serializedState{
Timer: s.Timer.Format(time.RFC3339),
Small: s.Small,
Big: s.Big,
Paused: !s.PauseTime.IsZero(),
})
}
func readState() (state, error) {
var s state
contents, err := s3.GetObject(c.StateBucket, c.StateKey)
if err != nil {
return s, err
}
err = yaml.Unmarshal(contents, &s)
return s, err
}
func writeState(s state) error {
contents, err := yaml.Marshal(s)
if err != nil {
return err
}
return s3.PutObject(c.StateBucket, c.StateKey, string(contents))
}
func checkState() (state, error) {
s, err := readState()
if err != nil {
return s, err
}
if !s.PauseTime.IsZero() {
delta := s.Timer.Sub(s.PauseTime)
s.Timer = time.Now().Add(delta)
} else if s.Timer.Before(time.Now()) {
s.Small = s.Small * 2
s.Big = s.Big * 2
if s.Big > maxBlind {
s.Small = 25
s.Big = 50
}
s.Timer = time.Now().Add(time.Minute * time.Duration(s.Interval))
err = writeState(s)
if err != nil {
return s, err
}
}
return s, nil
}
func updateState(su stateUpdate) error { //revive:disable-line:cyclomatic
s, err := readState()
if err != nil {
return fmt.Errorf("failed to read state")
}
if su.Pause && s.PauseTime.IsZero() {
s.PauseTime = time.Now()
} else if su.Resume && !s.PauseTime.IsZero() {
delta := s.Timer.Sub(s.PauseTime)
s.Timer = time.Now().Add(delta)
s.PauseTime = time.Time{}
} else if su.Pause || su.Resume {
return nil
} else {
if su.Interval != 0 {
if su.Interval != -1 {
s.Interval = su.Interval
}
s.Timer = time.Now().Add(time.Minute * time.Duration(s.Interval))
s.PauseTime = time.Time{}
}
if su.Small != 0 {
s.Small = su.Small
}
if su.Big != 0 {
s.Big = su.Big
}
}
return writeState(s)
}