Files
pipelines/internal/server/chat_ntfy_outbox.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

129 lines
4.5 KiB
Go

package server
import (
"context"
"log"
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// Chat phone pushes (attention items and Claude auto-switch notices) go
// through a durable outbox like run notifications: the push is recorded first,
// one attempt is made at once, and a background worker retries a failed or
// interrupted attempt with backoff, also after a restart. A push whose app
// notification the operator already cleared is never published late, and a
// publication that raced a clear is cleared on the phone again, so the ntfy
// sequence-id/clear behaviour (chat_ntfy_clear.go) holds.
// chatNotificationOutbox is the durable chat push outbox; *pipeline.Store
// implements it.
type chatNotificationOutbox interface {
EnqueueChatNotification(ctx context.Context, n pipeline.ChatNotification, now time.Time) error
ClaimChatNotification(ctx context.Context, now int64) (*pipeline.ChatNotification, error)
FinishChatNotification(ctx context.Context, n pipeline.ChatNotification, now int64, messageID string, failure error) error
ChatNotificationCleared(ctx context.Context, id string) (bool, error)
Done() <-chan struct{}
}
// chatOutboxInterval is how often the worker looks for due retries.
var chatOutboxInterval = time.Second
// chatOutboxSkew shifts the outbox clock; tests move it past a backoff.
var chatOutboxSkew atomic.Int64
func chatOutboxNow() time.Time { return time.Now().Add(time.Duration(chatOutboxSkew.Load())) }
// startChatNotificationOutbox wires the durable outbox and starts its retry
// worker for the life of ctx.
func (h *chatHub) startChatNotificationOutbox(ctx context.Context, outbox chatNotificationOutbox) {
h.outbox = outbox
go func() {
ticker := time.NewTicker(chatOutboxInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-outbox.Done():
return
case <-ticker.C:
h.deliverChatNotifications(ctx, 16)
}
}
}()
}
// pushChatNtfy publishes one chat phone push. With an outbox it is recorded
// durably and attempted at once; without one (a store-less hub) it is a single
// direct attempt, as before.
func (h *chatHub) pushChatNtfy(ctx context.Context, n pipeline.ChatNotification) {
if h.outbox != nil {
err := h.outbox.EnqueueChatNotification(ctx, n, chatOutboxNow())
if err == nil {
h.deliverChatNotifications(ctx, 1)
return
}
log.Printf("enqueue chat notification %s: %v; publishing directly", n.ID, err)
}
if _, err := chatAttentionPublish(chatNtfyContext(ctx, n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(n)...); err != nil {
log.Printf("chat notification session=%s: %v", n.SessionID, err)
}
}
func chatNtfyContext(ctx context.Context, n pipeline.ChatNotification) context.Context {
if n.SequenceID != "" {
ctx = stage.WithNtfySequenceID(ctx, n.SequenceID)
}
if n.Priority > 0 {
ctx = stage.WithNtfyPriority(ctx, n.Priority)
}
return ctx
}
// chatNtfyViews derives the push's actions at delivery, so a changed web
// origin applies to a retried push.
func chatNtfyViews(n pipeline.ChatNotification) []stage.NtfyView {
_, views := chatAttentionLinks(n.SessionID)
return views
}
// deliverChatNotifications attempts up to limit due pushes.
func (h *chatHub) deliverChatNotifications(ctx context.Context, limit int) {
outbox := h.outbox
if outbox == nil {
return
}
for i := 0; i < limit && ctx.Err() == nil; i++ {
n, err := outbox.ClaimChatNotification(ctx, chatOutboxNow().Unix())
if err != nil {
log.Printf("claim chat notification: %v", err)
return
}
if n == nil {
return
}
publish, cancel := context.WithTimeout(ctx, 30*time.Second)
result, publishErr := chatAttentionPublish(chatNtfyContext(publish, *n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(*n)...)
cancel()
if publishErr != nil {
log.Printf("chat notification session=%s attempt=%d: %v", n.SessionID, n.Attempts, publishErr)
}
messageID, _ := result["message_id"].(string)
save, done := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
if err := outbox.FinishChatNotification(save, *n, chatOutboxNow().Unix(), messageID, publishErr); err != nil {
log.Printf("save chat notification %s: %v", n.ID, err)
}
// The operator may have cleared it in the app while it was being
// published, after the clear went to ntfy: clear it there again.
if publishErr == nil && n.SequenceID != "" {
if cleared, err := outbox.ChatNotificationCleared(save, n.ID); err == nil && cleared {
clearChatNtfy([]string{n.ID})
}
}
done()
}
}