/
gotime.go
161 lines (132 loc) · 4.08 KB
/
gotime.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
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
package gotime
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/rs/zerolog"
)
// Store represents the shape of the storage system.
type Store interface {
Get(ctx context.Context) (id int64, notFound bool, err error)
Put(ctx context.Context, lastID int64) error
}
// NotifyFunc represents the function signature the poller notifies on a new
// item. If error is not nil, the item will be retried at some point in the
// future.
type NotifyFunc func(context.Context) error
// GoTime tracks when it's Go Time!
type GoTime struct {
logger zerolog.Logger
store Store
http *http.Client
notify NotifyFunc
startTimeVariance time.Duration
lastNotified time.Time
}
// New constructs a *GoTime.
//
// startTimeVariance sets the window around the stream's start time when
// a live steam will be considered a GoTime live stream. This is necessary
// because the current changelog APIs return whether any show is streaming
// rather thahn GoTime specifically.
//
// notify is called when streaming starts. notify should return true when a successful.
func New(s Store, c *http.Client, logger zerolog.Logger, startTimeVariance time.Duration, notify NotifyFunc) (*GoTime, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
lastTS, notFound, err := s.Get(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get last notitied timestamp: %w", err)
}
if notFound {
// doing this explicitly to make sure we are good
lastTS = 0
if err = s.Put(ctx, lastTS); err != nil {
return nil, fmt.Errorf("failed to initialize redis: %w", err)
}
}
t := time.Unix(unix(lastTS))
return &GoTime{
logger: logger,
store: s,
http: c,
notify: notify,
startTimeVariance: startTimeVariance,
lastNotified: t,
}, nil
}
func unix(i int64) (int64, int64) {
// convert milliseconds to whole seconds
// convert millisecond remainder from above conversion to nanoseconds
return i / 1000, (i % 1000) * int64(time.Millisecond)
}
// Poll conditionally calls notify if GoTime is currently streaming.
//
// For a notification to be posted: a notification must not have been successful
// in the last 24 hours, changelog is currently streaming, and there is
// a GoTime episode scheduled within +/-startTimeVariance.
func (gt *GoTime) Poll(ctx context.Context) error {
now := time.Now()
if gt.lastNotified.After(now.Add(-24 * time.Hour)) {
return nil
}
var status struct {
Streaming bool
}
err := gt.get(ctx, "https://changelog.com/live/status", &status)
if err != nil {
return err
}
if !status.Streaming {
return nil
}
var countdown struct {
Data time.Time
}
err = gt.get(ctx, "https://changelog.com/slack/countdown/gotime", &countdown)
if err != nil {
return err
}
nextScheduled := countdown.Data
if now.Before(nextScheduled.Add(-gt.startTimeVariance)) || now.After(nextScheduled.Add(gt.startTimeVariance)) {
return nil
}
gt.logger.Trace().
Msg("sending notification that it's Go Time")
if err := gt.notify(ctx); err != nil {
return fmt.Errorf("Go Time notification failed: %w", err)
}
gt.lastNotified = now
if err := gt.store.Put(ctx, now.UnixNano()/int64(time.Millisecond)); err != nil {
return fmt.Errorf("failed to persist timestamp to redis;: %w", err)
}
return nil
}
// get makes an HTTP request to url and unmarshals the JSON response into i.
func (gt *GoTime) get(ctx context.Context, url string, i interface{}) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
panic(err)
}
req = req.WithContext(ctx)
resp, err := gt.http.Do(req)
if err != nil {
return fmt.Errorf("making http request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("non-200 status code: %d - %s", resp.StatusCode, resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading response body: %v", err)
}
err = json.Unmarshal(body, i)
if err != nil {
return fmt.Errorf("unmarshaling response: %s", err)
}
return nil
}