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() } }