Claim goal notifications before sending them
The check read "already sent?" and recorded the send afterwards, so two overlapping checks could both notify. Claim the (goal, day) row first with ON CONFLICT DO NOTHING and release it if ntfy fails, so a later check retries. The handler now returns a typed result instead of a map[string]any, and shares one ntfy client. Fix two comments that still said nginx. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+54
-40
@@ -142,7 +142,7 @@ func (s *Server) adminAPI(next http.Handler) http.Handler {
|
||||
|
||||
// adminPage sends visitors without the site's admin session to its login
|
||||
// page, which returns them here afterwards. The redirect is made in the
|
||||
// browser because only it knows the /tracker/ prefix nginx strips.
|
||||
// browser because only it knows the /tracker/ prefix the proxy strips.
|
||||
func (s *Server) adminPage(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.admin.IsAdmin(w, r) {
|
||||
@@ -604,73 +604,87 @@ func (s *Server) checkGoalNotifications(w http.ResponseWriter, r *http.Request)
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
response := map[string]any{
|
||||
"date": from.Format(time.DateOnly),
|
||||
"evaluated": len(results),
|
||||
"at_risk": 0,
|
||||
"sent": 0,
|
||||
"configured": settings.Enabled && settings.NtfyTopic != "",
|
||||
"errors": []string{},
|
||||
response := goalCheckResult{
|
||||
Date: from.Format(time.DateOnly),
|
||||
Evaluated: len(results),
|
||||
Configured: settings.Enabled && settings.NtfyTopic != "",
|
||||
Errors: []string{},
|
||||
}
|
||||
ntfyServer, err := validateNtfyServer(settings.NtfyServer)
|
||||
if err != nil {
|
||||
if settings.Enabled && settings.NtfyTopic != "" {
|
||||
if response.Configured {
|
||||
writeError(w, http.StatusInternalServerError, "invalid configured ntfy server")
|
||||
return
|
||||
}
|
||||
ntfyServer = settings.NtfyServer
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
for _, result := range results {
|
||||
if result.Met || !goalAtRisk(result, elapsed) {
|
||||
continue
|
||||
}
|
||||
response["at_risk"] = response["at_risk"].(int) + 1
|
||||
if !settings.Enabled || settings.NtfyTopic == "" {
|
||||
response.AtRisk++
|
||||
if !response.Configured {
|
||||
continue
|
||||
}
|
||||
sent, err := s.store.GoalNotificationSent(r.Context(), result.ID, from)
|
||||
claimed, err := s.store.ClaimGoalNotification(r.Context(), result.ID, from)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
if sent {
|
||||
if !claimed {
|
||||
continue
|
||||
}
|
||||
body := fmt.Sprintf("Goal at risk: %s%s, actual %s of %s", result.Kind,
|
||||
formatGoalLabel(result.Label), durationString(result.ActualS), durationString(result.TargetS))
|
||||
req, err := http.NewRequestWithContext(r.Context(), http.MethodPost,
|
||||
ntfyServer+"/"+url.PathEscape(settings.NtfyTopic),
|
||||
strings.NewReader(body))
|
||||
if err == nil {
|
||||
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
|
||||
req.Header.Set("Title", "Goal at risk")
|
||||
req.Header.Set("Priority", "warning")
|
||||
resp, requestErr := client.Do(req)
|
||||
if requestErr == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
if err := s.store.RecordGoalNotification(r.Context(), result.ID, from); err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
response["sent"] = response["sent"].(int) + 1
|
||||
continue
|
||||
}
|
||||
requestErr = fmt.Errorf("ntfy returned %s", resp.Status)
|
||||
if err := sendNtfy(r.Context(), ntfyServer, settings.NtfyTopic, body); err != nil {
|
||||
if err := s.store.ReleaseGoalNotification(r.Context(), result.ID, from); err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
err = requestErr
|
||||
response.Errors = append(response.Errors, err.Error())
|
||||
continue
|
||||
}
|
||||
response["errors"] = append(response["errors"].([]string), err.Error())
|
||||
response.Sent++
|
||||
}
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
type goalCheckResult struct {
|
||||
Date string `json:"date"`
|
||||
Evaluated int `json:"evaluated"`
|
||||
AtRisk int `json:"at_risk"`
|
||||
Sent int `json:"sent"`
|
||||
Configured bool `json:"configured"`
|
||||
Errors []string `json:"errors"`
|
||||
}
|
||||
|
||||
var ntfyClient = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
|
||||
func sendNtfy(ctx context.Context, server, topic, body string) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
server+"/"+url.PathEscape(topic), strings.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
|
||||
req.Header.Set("Title", "Goal at risk")
|
||||
req.Header.Set("Priority", "warning")
|
||||
resp, err := ntfyClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("ntfy returned %s", resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateNtfyServer(raw string) (string, error) {
|
||||
server := strings.TrimRight(strings.TrimSpace(raw), "/")
|
||||
u, err := url.Parse(server)
|
||||
|
||||
Reference in New Issue
Block a user