Repository navigation
Expand file tree
/
Copy pathpush.go
More file actions
253 lines (231 loc) · 7.1 KB
/
Copy pathpush.go
File metadata and controls
253 lines (231 loc) · 7.1 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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"time"
"github.com/ProgenyAlpha/periscope/internal/forecast"
"github.com/ProgenyAlpha/periscope/internal/store"
webpush "github.com/SherClockHolmes/webpush-go"
)
// ensureVAPIDKeys generates a VAPID key pair if missing, stores in KV, and returns them.
func ensureVAPIDKeys(db *sql.DB) (pub, priv string, err error) {
pubRaw := store.KVGet(db, "config:vapid-public")
privRaw := store.KVGet(db, "config:vapid-private")
if pubRaw != nil && privRaw != nil {
var p, k string
if json.Unmarshal(pubRaw, &p) == nil && json.Unmarshal(privRaw, &k) == nil && p != "" && k != "" {
return p, k, nil
}
}
priv, pub, err = webpush.GenerateVAPIDKeys()
if err != nil {
return "", "", fmt.Errorf("generate VAPID keys: %w", err)
}
pubJSON, _ := json.Marshal(pub)
privJSON, _ := json.Marshal(priv)
store.KVSet(db, "config:vapid-public", string(pubJSON))
store.KVSet(db, "config:vapid-private", string(privJSON))
slog.Info("generated new VAPID key pair")
return pub, priv, nil
}
// shortEndpoint truncates a push endpoint for logging. Slicing [:40] outright
// panicked the whole request goroutine: /api/push/subscribe stores any
// non-empty endpoint, so a one-character one reached this log line.
func shortEndpoint(endpoint string) string {
if len(endpoint) > 40 {
return endpoint[:40]
}
return endpoint
}
// sendPushNotification sends a push notification to all subscribers.
func sendPushNotification(db *sql.DB, title, body string) error {
pub, priv, err := ensureVAPIDKeys(db)
if err != nil {
return err
}
subs, err := store.PushGetAll(db)
if err != nil {
return err
}
if len(subs) == 0 {
slog.Debug("no push subscribers, skipping")
return nil
}
payload, _ := json.Marshal(map[string]string{"title": title, "body": body})
sent, failed := 0, 0
for _, sub := range subs {
s := &webpush.Subscription{
Endpoint: sub.Endpoint,
Keys: webpush.Keys{
Auth: sub.Auth,
P256dh: sub.P256dh,
},
}
resp, err := webpush.SendNotification(payload, s, &webpush.Options{
Subscriber: "mailto:periscope@localhost",
VAPIDPublicKey: pub,
VAPIDPrivateKey: priv,
TTL: 60,
HTTPClient: &http.Client{Timeout: 10 * time.Second},
})
if err != nil {
slog.Warn("push send failed", "endpoint", shortEndpoint(sub.Endpoint), "err", err)
failed++
continue
}
resp.Body.Close()
if resp.StatusCode == http.StatusGone {
if err := store.PushUnsubscribe(db, sub.Endpoint); err != nil {
slog.Error("could not prune stale push endpoint", "endpoint", shortEndpoint(sub.Endpoint), "err", err)
}
slog.Info("pruned stale push endpoint", "endpoint", shortEndpoint(sub.Endpoint))
failed++
} else {
sent++
}
}
slog.Info("push notification sent", "ok", sent, "failed", failed)
return nil
}
// checkAndNotify evaluates rate limit thresholds and sends push alerts with cooldown.
func checkAndNotify(app *App, usage map[string]any) {
pct5hr, _ := usage["pct5hr"].(float64)
if pct5hr < 0 {
// No 5h window: the weekly limit is the one that can bind.
checkWeeklyNotify(app, usage)
return
}
if pct5hr >= 90 {
if !pushCooldownExpired(app.DB, "push:cooldown:5hr-critical", 30*time.Minute) {
return
}
sendPushNotification(app.DB, "Periscope", fmt.Sprintf("5hr limit at %.0f%%", pct5hr))
setPushCooldown(app.DB, "push:cooldown:5hr-critical")
} else if pct5hr >= 80 {
if !pushCooldownExpired(app.DB, "push:cooldown:5hr-warning", 30*time.Minute) {
return
}
sendPushNotification(app.DB, "Periscope", fmt.Sprintf("Approaching 5hr limit: %.0f%%", pct5hr))
setPushCooldown(app.DB, "push:cooldown:5hr-warning")
} else if pct5hr > 0 && pct5hr < 20 {
// Check if this is a reset (was previously high)
lastRaw := store.KVGet(app.DB, "push:last-pct5hr")
if lastRaw != nil {
var lastPct float64
if json.Unmarshal(lastRaw, &lastPct) == nil && lastPct >= 80 {
if pushCooldownExpired(app.DB, "push:cooldown:5hr-reset", 30*time.Minute) {
sendPushNotification(app.DB, "Periscope", "5hr window reset")
setPushCooldown(app.DB, "push:cooldown:5hr-reset")
}
}
}
}
// Track last pct5hr for reset detection
if pct5hr > 0 {
pctJSON, _ := json.Marshal(pct5hr)
store.KVSet(app.DB, "push:last-pct5hr", string(pctJSON))
}
}
func pushCooldownExpired(db *sql.DB, key string, duration time.Duration) bool {
raw := store.KVGet(db, key)
if raw == nil {
return true
}
var ts string
if json.Unmarshal(raw, &ts) != nil {
return true
}
t, err := time.Parse(time.RFC3339, ts)
if err != nil {
return true
}
return time.Since(t) >= duration
}
func setPushCooldown(db *sql.DB, key string) {
ts, _ := json.Marshal(time.Now().Format(time.RFC3339))
store.KVSet(db, key, string(ts))
}
// weeklyPushState is what the weekly alerts remember between polls: which
// reset period they last spoke about and the highest threshold already sent.
type weeklyPushState struct {
Reset string `json:"reset"`
Level int `json:"level"`
}
const (
weeklyWarnPct = 80
weeklyCriticalPct = 90
// A reset time read from two different endpoints can differ by seconds or
// fractions, so two stamps this close describe the same period.
weeklySamePeriod = 6 * time.Hour
)
// weeklyPushPlan decides which weekly alerts to send for one reading. Each
// threshold fires once per reset period, a drop from a high reading to a low
// one announces the reset once, and anything else stays quiet.
func weeklyPushPlan(state weeklyPushState, lastPct, pct float64, reset string) (msgs []string, next weeklyPushState) {
next = state
if !sameWeeklyPeriod(state.Reset, reset) {
next = weeklyPushState{Reset: reset}
}
level := 0
switch {
case pct >= weeklyCriticalPct:
level = weeklyCriticalPct
case pct >= weeklyWarnPct:
level = weeklyWarnPct
}
if level > next.Level {
if level == weeklyCriticalPct {
msgs = append(msgs, fmt.Sprintf("Weekly limit at %.0f%%", pct))
} else {
msgs = append(msgs, fmt.Sprintf("Approaching weekly limit: %.0f%%", pct))
}
next.Level = level
}
if lastPct >= weeklyWarnPct && pct >= 0 && pct < 20 {
msgs = append(msgs, "Weekly window reset")
}
return msgs, next
}
func sameWeeklyPeriod(a, b string) bool {
if a == b {
return true
}
ta, errA := time.Parse(time.RFC3339, a)
tb, errB := time.Parse(time.RFC3339, b)
if errA != nil || errB != nil {
return false
}
d := ta.Sub(tb)
if d < 0 {
d = -d
}
return d < weeklySamePeriod
}
func checkWeeklyNotify(app *App, usage map[string]any) {
pct := forecast.FloatOrDefault(usage["pctWeekly"], -1)
if pct < 0 {
return
}
reset, _ := usage["resetWeekly"].(string)
var state weeklyPushState
if raw := store.KVGet(app.DB, "push:weekly-state"); raw != nil {
json.Unmarshal(raw, &state)
}
lastPct := -1.0
if raw := store.KVGet(app.DB, "push:last-pctWeekly"); raw != nil {
json.Unmarshal(raw, &lastPct)
}
msgs, next := weeklyPushPlan(state, lastPct, pct, reset)
for _, m := range msgs {
sendPushNotification(app.DB, "Periscope", m)
}
if next != state {
b, _ := json.Marshal(next)
store.KVSet(app.DB, "push:weekly-state", string(b))
}
b, _ := json.Marshal(pct)
store.KVSet(app.DB, "push:last-pctWeekly", string(b))
}