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:
+60
-46
@@ -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,71 +604,85 @@ 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{
|
for _, result := range results {
|
||||||
|
if result.Met || !goalAtRisk(result, elapsed) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
response.AtRisk++
|
||||||
|
if !response.Configured {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
claimed, err := s.store.ClaimGoalNotification(r.Context(), result.ID, from)
|
||||||
|
if err != nil {
|
||||||
|
s.internalError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
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))
|
||||||
|
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
|
||||||
|
}
|
||||||
|
response.Errors = append(response.Errors, err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
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,
|
Timeout: 10 * time.Second,
|
||||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||||
return http.ErrUseLastResponse
|
return http.ErrUseLastResponse
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
for _, result := range results {
|
|
||||||
if result.Met || !goalAtRisk(result, elapsed) {
|
func sendNtfy(ctx context.Context, server, topic, body string) error {
|
||||||
continue
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||||
}
|
server+"/"+url.PathEscape(topic), strings.NewReader(body))
|
||||||
response["at_risk"] = response["at_risk"].(int) + 1
|
|
||||||
if !settings.Enabled || settings.NtfyTopic == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
sent, err := s.store.GoalNotificationSent(r.Context(), result.ID, from)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.internalError(w, r, err)
|
return err
|
||||||
return
|
|
||||||
}
|
}
|
||||||
if sent {
|
|
||||||
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("Content-Type", "text/plain; charset=utf-8")
|
||||||
req.Header.Set("Title", "Goal at risk")
|
req.Header.Set("Title", "Goal at risk")
|
||||||
req.Header.Set("Priority", "warning")
|
req.Header.Set("Priority", "warning")
|
||||||
resp, requestErr := client.Do(req)
|
resp, err := ntfyClient.Do(req)
|
||||||
if requestErr == nil {
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
resp.Body.Close()
|
resp.Body.Close()
|
||||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
if err := s.store.RecordGoalNotification(r.Context(), result.ID, from); err != nil {
|
return fmt.Errorf("ntfy returned %s", resp.Status)
|
||||||
s.internalError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
response["sent"] = response["sent"].(int) + 1
|
return nil
|
||||||
continue
|
|
||||||
}
|
|
||||||
requestErr = fmt.Errorf("ntfy returned %s", resp.Status)
|
|
||||||
}
|
|
||||||
err = requestErr
|
|
||||||
}
|
|
||||||
response["errors"] = append(response["errors"].([]string), err.Error())
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, response)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateNtfyServer(raw string) (string, error) {
|
func validateNtfyServer(raw string) (string, error) {
|
||||||
|
|||||||
@@ -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
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user