Claim goal notifications before sending them
Test and publish / test (push) Successful in 17s
Test and publish / publish (push) Failing after 23s

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:
2026-11-26 15:15:31 +00:00
co-authored by Claude Opus 5.5
parent c85e6dfbb0
commit b20ea0adf9
3 changed files with 67 additions and 50 deletions
+51 -37
View File
@@ -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 // adminPage sends visitors without the site's admin session to its login
// page, which returns them here afterwards. The redirect is made in the // 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 { func (s *Server) adminPage(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.admin.IsAdmin(w, r) { 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) s.internalError(w, r, err)
return return
} }
response := map[string]any{ response := goalCheckResult{
"date": from.Format(time.DateOnly), Date: from.Format(time.DateOnly),
"evaluated": len(results), Evaluated: len(results),
"at_risk": 0, Configured: settings.Enabled && settings.NtfyTopic != "",
"sent": 0, Errors: []string{},
"configured": settings.Enabled && settings.NtfyTopic != "",
"errors": []string{},
} }
ntfyServer, err := validateNtfyServer(settings.NtfyServer) ntfyServer, err := validateNtfyServer(settings.NtfyServer)
if err != nil { if err != nil {
if settings.Enabled && settings.NtfyTopic != "" { if response.Configured {
writeError(w, http.StatusInternalServerError, "invalid configured ntfy server") writeError(w, http.StatusInternalServerError, "invalid configured ntfy server")
return return
} }
ntfyServer = settings.NtfyServer ntfyServer = settings.NtfyServer
} }
client := &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
for _, result := range results { for _, result := range results {
if result.Met || !goalAtRisk(result, elapsed) { if result.Met || !goalAtRisk(result, elapsed) {
continue continue
} }
response["at_risk"] = response["at_risk"].(int) + 1 response.AtRisk++
if !settings.Enabled || settings.NtfyTopic == "" { if !response.Configured {
continue continue
} }
sent, err := s.store.GoalNotificationSent(r.Context(), result.ID, from) claimed, err := s.store.ClaimGoalNotification(r.Context(), result.ID, from)
if err != nil { if err != nil {
s.internalError(w, r, err) s.internalError(w, r, err)
return return
} }
if sent { if !claimed {
continue continue
} }
body := fmt.Sprintf("Goal at risk: %s%s, actual %s of %s", result.Kind, body := fmt.Sprintf("Goal at risk: %s%s, actual %s of %s", result.Kind,
formatGoalLabel(result.Label), durationString(result.ActualS), durationString(result.TargetS)) formatGoalLabel(result.Label), durationString(result.ActualS), durationString(result.TargetS))
req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, if err := sendNtfy(r.Context(), ntfyServer, settings.NtfyTopic, body); err != nil {
ntfyServer+"/"+url.PathEscape(settings.NtfyTopic), if err := s.store.ReleaseGoalNotification(r.Context(), result.ID, from); err != nil {
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) s.internalError(w, r, err)
return return
} }
response["sent"] = response["sent"].(int) + 1 response.Errors = append(response.Errors, err.Error())
continue continue
} }
requestErr = fmt.Errorf("ntfy returned %s", resp.Status) response.Sent++
}
err = requestErr
}
response["errors"] = append(response["errors"].([]string), err.Error())
} }
writeJSON(w, http.StatusOK, response) 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) { func validateNtfyServer(raw string) (string, error) {
server := strings.TrimRight(strings.TrimSpace(raw), "/") server := strings.TrimRight(strings.TrimSpace(raw), "/")
u, err := url.Parse(server) u, err := url.Parse(server)
+1 -1
View File
@@ -1,7 +1,7 @@
// Package auth decides whether a request comes from the site's admin. // Package auth decides whether a request comes from the site's admin.
// //
// Like the job tracker, the activity tracker has no users or passwords of its // Like the job tracker, the activity tracker has no users or passwords of its
// own. It runs behind the main site's nginx at /tracker/ and borrows that // own. It runs behind the main site's Caddy at /tracker/ and borrows that
// site's session: the browser already carries the site's HTTP-only auth // site's session: the browser already carries the site's HTTP-only auth
// cookies (Path=/) on every request, so the tracker forwards the Cookie header // cookies (Path=/) on every request, so the tracker forwards the Cookie header
// to the site backend's GET /auth/validate-admin and treats a 2xx as "admin". // to the site backend's GET /auth/validate-admin and treats a 2xx as "admin".
+12 -9
View File
@@ -574,17 +574,20 @@ func (s *Store) UpdateNotificationSettings(ctx context.Context, settings Notific
return settings, err return settings, err
} }
func (s *Store) GoalNotificationSent(ctx context.Context, goalID int64, date time.Time) (bool, error) { // ClaimGoalNotification records today's notification for a goal before it is
var sent bool // sent, so concurrent checks send it at most once. It reports whether this
err := s.pool.QueryRow(ctx, `SELECT EXISTS ( // call made the claim.
SELECT 1 FROM goal_notifications WHERE goal_id = $1 AND notification_date = $2::date func (s *Store) ClaimGoalNotification(ctx context.Context, goalID int64, date time.Time) (bool, error) {
)`, goalID, date.Format(time.DateOnly)).Scan(&sent) tag, err := s.pool.Exec(ctx, `INSERT INTO goal_notifications (goal_id, notification_date)
return sent, err VALUES ($1, $2::date) ON CONFLICT (goal_id, notification_date) DO NOTHING`, goalID, date.Format(time.DateOnly))
return tag.RowsAffected() == 1, err
} }
func (s *Store) RecordGoalNotification(ctx context.Context, goalID int64, date time.Time) error { // ReleaseGoalNotification undoes a claim whose send failed, so a later check
_, err := s.pool.Exec(ctx, `INSERT INTO goal_notifications (goal_id, notification_date) // retries it.
VALUES ($1, $2::date) ON CONFLICT (goal_id, notification_date) DO NOTHING`, goalID, date.Format(time.DateOnly)) func (s *Store) ReleaseGoalNotification(ctx context.Context, goalID int64, date time.Time) error {
_, err := s.pool.Exec(ctx, `DELETE FROM goal_notifications
WHERE goal_id = $1 AND notification_date = $2::date`, goalID, date.Format(time.DateOnly))
return err return err
} }