diff --git a/internal/api/api.go b/internal/api/api.go index 61c2253..95370d1 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -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) diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 401837e..1f35678 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -1,7 +1,7 @@ // 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 -// 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 // 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". diff --git a/internal/store/store.go b/internal/store/store.go index b7365a9..8276d65 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -574,17 +574,20 @@ func (s *Store) UpdateNotificationSettings(ctx context.Context, settings Notific return settings, err } -func (s *Store) GoalNotificationSent(ctx context.Context, goalID int64, date time.Time) (bool, error) { - var sent bool - err := s.pool.QueryRow(ctx, `SELECT EXISTS ( - SELECT 1 FROM goal_notifications WHERE goal_id = $1 AND notification_date = $2::date - )`, goalID, date.Format(time.DateOnly)).Scan(&sent) - return sent, err +// ClaimGoalNotification records today's notification for a goal before it is +// sent, so concurrent checks send it at most once. It reports whether this +// call made the claim. +func (s *Store) ClaimGoalNotification(ctx context.Context, goalID int64, date time.Time) (bool, error) { + tag, err := s.pool.Exec(ctx, `INSERT INTO goal_notifications (goal_id, notification_date) + 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 { - _, err := s.pool.Exec(ctx, `INSERT INTO goal_notifications (goal_id, notification_date) - VALUES ($1, $2::date) ON CONFLICT (goal_id, notification_date) DO NOTHING`, goalID, date.Format(time.DateOnly)) +// ReleaseGoalNotification undoes a claim whose send failed, so a later check +// retries it. +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 }