Files
pipelines/internal/pipeline/chat_notifications.go
T
alan 9f13c93be6 Chat reliability: durable ntfy outbox, queue recovery retries, unattended cap
- Chat phone pushes (attention items, auto-switch notices) go through a
  durable chat_notifications outbox with leases, bounded attempts and
  backoff, retried by a worker; pushes cleared in the app first are never
  published, and a publication racing a clear is cleared again.
- Queued/scheduled chat prompts are deleted on recovery only when they can
  never be rebuilt; transient failures keep the rows and retry with backoff.
- Unattended chats with live work always keep notifying; the idle cap rises
  from 16 to 64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:26:46 +00:00

116 lines
5.5 KiB
Go

package pipeline
import (
"context"
"database/sql"
"errors"
"time"
)
// ChatNotification is one chat phone push (ntfy) in the durable outbox. It
// follows the run notification outbox (run_notifications.go): a row is leased
// for a bounded attempt, a crash during a lease is recovered when the lease
// expires, and attempts are bounded. ID is the chat's app notification id, so
// an enqueue is idempotent and a notification the operator already cleared in
// the app is never published late.
type ChatNotification struct {
ID, SessionID, Title, Body, Click string
// SequenceID is the ntfy sequence id the push is published with (so a later
// clear dismisses it on the phone); "" publishes without one.
SequenceID string
Priority int
Attempts int
}
// ChatNotificationAttempts bounds publication attempts per chat push.
const ChatNotificationAttempts = 5
// chatNotificationLease is how long one claimed attempt owns its row.
const chatNotificationLease = 60
// chatNotificationRetention bounds how long settled rows are kept.
const chatNotificationRetention = 7 * 24 * time.Hour
func (s *Store) initChatNotifications() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_notifications (
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, click TEXT NOT NULL,
sequence_id TEXT NOT NULL DEFAULT '', priority INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
next_attempt INTEGER NOT NULL DEFAULT 0, diagnostic TEXT NOT NULL DEFAULT '', message_id TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS chat_notifications_due ON chat_notifications(status,next_attempt);`)
return err
}
// EnqueueChatNotification records one chat push once (by id) and prunes
// settled rows past retention.
func (s *Store) EnqueueChatNotification(ctx context.Context, n ChatNotification, now time.Time) error {
if _, err := s.db.ExecContext(ctx, `DELETE FROM chat_notifications WHERE created_at<? AND status NOT IN ('pending','sending')`, now.Add(-chatNotificationRetention).Unix()); err != nil {
return err
}
_, err := s.db.ExecContext(ctx, `INSERT INTO chat_notifications(id,session_id,title,body,click,sequence_id,priority,created_at)
VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING`, n.ID, n.SessionID, n.Title, n.Body, n.Click, n.SequenceID, n.Priority, now.Unix())
return err
}
// ClaimChatNotification atomically leases one due push. A push whose app
// notification was cleared before it went out (the operator already answered
// in the app) is settled as cleared instead of published.
func (s *Store) ClaimChatNotification(ctx context.Context, now int64) (*ChatNotification, error) {
if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='cleared',diagnostic='cleared in the app before publication'
WHERE status IN ('pending','sending') AND next_attempt<=? AND EXISTS(SELECT 1 FROM app_notifications a WHERE a.id=chat_notifications.id AND a.cleared_at<>0)`, now); err != nil {
return nil, err
}
if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='failed',diagnostic='publisher acknowledgement unknown after final lease expired'
WHERE status='sending' AND attempts>=? AND next_attempt<=?`, ChatNotificationAttempts, now); err != nil {
return nil, err
}
n := new(ChatNotification)
err := s.db.QueryRowContext(ctx, `UPDATE chat_notifications SET status='sending',attempts=attempts+1,next_attempt=?
WHERE rowid=(SELECT rowid FROM chat_notifications WHERE status IN ('pending','sending') AND attempts<? AND next_attempt<=? ORDER BY next_attempt,rowid LIMIT 1)
RETURNING id,session_id,title,body,click,sequence_id,priority,attempts`, now+chatNotificationLease, ChatNotificationAttempts, now).Scan(&n.ID, &n.SessionID, &n.Title, &n.Body, &n.Click, &n.SequenceID, &n.Priority, &n.Attempts)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return n, nil
}
// FinishChatNotification settles a claimed attempt: sent, or pending again
// after an exponential backoff (5 s, 10 s, 20 s, ...) until attempts run out.
func (s *Store) FinishChatNotification(ctx context.Context, n ChatNotification, now int64, messageID string, failure error) error {
status, diagnostic, next := "sent", "", now
if failure != nil {
status, diagnostic = "pending", failure.Error()
next = now + int64(5)<<min(n.Attempts-1, 8)
if n.Attempts >= ChatNotificationAttempts {
status = "failed"
}
}
_, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status=?,diagnostic=?,message_id=?,next_attempt=?
WHERE id=? AND status='sending' AND attempts=?`, status, diagnostic, messageID, next, n.ID, n.Attempts)
return err
}
// ChatNotificationStatus reports one push's outbox status ("" when absent)
// and attempts.
func (s *Store) ChatNotificationStatus(ctx context.Context, id string) (string, int, error) {
var status string
var attempts int
err := s.db.QueryRowContext(ctx, `SELECT status,attempts FROM chat_notifications WHERE id=?`, id).Scan(&status, &attempts)
if errors.Is(err, sql.ErrNoRows) {
return "", 0, nil
}
return status, attempts, err
}
// ChatNotificationCleared reports whether id's app notification has been
// cleared; a publication that raced a clear then clears the phone too.
func (s *Store) ChatNotificationCleared(ctx context.Context, id string) (bool, error) {
var cleared bool
err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM app_notifications WHERE id=? AND cleared_at<>0)`, id).Scan(&cleared)
return cleared, err
}