Files
silo-server/internal/notifications/webhook_dispatcher.go
T
QuickandClaude Fable 5 b091f0c6c1 feat(notifications): in-app inbox, realtime, webhooks, web push + shared SMTP core
Implements the notification system foundation and all v1 delivery channels
that need no external infrastructure (specs 00/01/04/05 in
docs/superpowers/plans/notifications/):

Foundation (spec 01):
- episode_availability seeding + per-library seed markers: "newly available"
  means newly released to this server, so back-catalog imports and first
  scans never flood (verified on dev: 1.13M episodes seeded silently)
- release_events -> profile_series_interest fanout worker with settling
  delay, per-series burst caps, FOR UPDATE SKIP LOCKED multi-node claims,
  and a guarded last-notified cursor
- interest index maintained via a userstore provider decorator so every
  favorites/watchlist/progress mutation path (REST, jellycompat, imports,
  playback) feeds it; progress writes only recompute on state transitions
- durable per-profile inbox + read state, forward-sync cursor API,
  websocket channel with short-lived single-use handshake tickets
- web UI: sidebar badge, inbox page, toasts, per-profile preferences
- startup/daily tasks: availability seeding, interest rebuild, retention

Outbound webhooks (spec 04):
- Discord embeds (text-only per the v1 privacy contract) and generic
  JSON signed Stripe-style with per-webhook secrets
- HTTPS-only + private-destination guard enforced at registration and at
  connect time (DNS-rebinding mitigation); URLs/secrets encrypted at rest
- durable per-target outbox enqueued in the fanout transaction, lease-based
  claims, 24h exponential retry, 3x-consecutive-4xx auto-disable with an
  in-app notice (loop-guarded)

Web push (spec 05):
- VAPID keypair self-provisioned at startup (single atomic JSON setting,
  private half encrypted at rest) — no third-party accounts needed
- payloads E2E-encrypted (RFC 8291); 404/410 treated as unsubscribe
- service worker + subscribe flow in Settings -> Notifications

Shared SMTP core (internal/mail):
- feature-agnostic mail.Sender over live email.* settings, STARTTLS or
  implicit TLS, encrypted password, admin Email settings page with
  synchronous test send; no consumer yet by design (digest is v1.5)

APNs/FCM (specs 02/03) are deferred to v2; the capability endpoint reports
them unavailable so clients render truthfully.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 14:55:46 -04:00

141 lines
3.5 KiB
Go

package notifications
import (
"context"
"log/slog"
"sync"
"time"
)
const (
webhookDispatchWorkers = 16
webhookDispatchQueue = 256
webhookRetryInterval = 30 * time.Second
webhookRetryClaimLimit = 50
)
// WebhookDispatcher implements the channel Dispatcher interface for outbound
// webhooks. Dispatch never blocks the fanout loop on destination HTTP: it
// hands the delivery ID to a bounded worker pool that claims the delivery's
// pending outbox attempts and sends them. A full queue simply drops the
// hand-off — the durable `pending` rows are picked up by the retry worker's
// outbox recovery sweep, so delivery is delayed, never lost.
type WebhookDispatcher struct {
sender *webhookSender
queue chan string
logger *slog.Logger
}
func newWebhookDispatcher(sender *webhookSender) *WebhookDispatcher {
return &WebhookDispatcher{
sender: sender,
queue: make(chan string, webhookDispatchQueue),
logger: slog.Default().With("component", "notifications.webhooks.dispatch"),
}
}
// Dispatch queues the delivery's webhook attempts for immediate send.
func (d *WebhookDispatcher) Dispatch(_ context.Context, delivery DeliveryRow) error {
if d == nil {
return nil
}
if delivery.Type == DeliveryTypeWebhookAutoDisabled {
// Type deny list: an auto-disable notice must never re-dispatch as a
// webhook, or a broken webhook would loop forever.
return nil
}
select {
case d.queue <- delivery.ID:
default:
d.logger.Warn("webhook dispatch queue full; deferring to retry worker",
"delivery_id", delivery.ID)
}
return nil
}
// Run consumes the dispatch queue with a bounded worker pool until ctx is
// canceled. One slow destination cannot block other deliveries.
func (d *WebhookDispatcher) Run(ctx context.Context) {
var wg sync.WaitGroup
for range webhookDispatchWorkers {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case deliveryID := <-d.queue:
d.processDelivery(ctx, deliveryID)
}
}
}()
}
wg.Wait()
}
func (d *WebhookDispatcher) processDelivery(ctx context.Context, deliveryID string) {
attempts, err := d.sender.webhooks.ClaimPendingForDelivery(ctx, deliveryID)
if err != nil {
if ctx.Err() == nil {
d.logger.Warn("webhook attempt claim failed", "delivery_id", deliveryID, "error", err)
}
return
}
for _, attempt := range attempts {
if ctx.Err() != nil {
return
}
d.sender.processAttempt(ctx, attempt)
}
}
// WebhookRetryWorker drains due retries and recovers stale pending outbox
// rows whose post-commit dispatch never ran (process crash between the fanout
// commit and dispatch).
type WebhookRetryWorker struct {
sender *webhookSender
logger *slog.Logger
}
func newWebhookRetryWorker(sender *webhookSender) *WebhookRetryWorker {
return &WebhookRetryWorker{
sender: sender,
logger: slog.Default().With("component", "notifications.webhooks.retry"),
}
}
// Run polls for due attempts until ctx is canceled.
func (w *WebhookRetryWorker) Run(ctx context.Context) {
ticker := time.NewTicker(webhookRetryInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
}
if !w.sender.settings.WebhooksEnabled(ctx) {
continue
}
for {
attempts, err := w.sender.webhooks.ClaimDue(ctx, webhookRetryClaimLimit)
if err != nil {
if ctx.Err() == nil {
w.logger.Warn("webhook retry claim failed", "error", err)
}
break
}
if len(attempts) == 0 {
break
}
for _, attempt := range attempts {
if ctx.Err() != nil {
return
}
w.sender.processAttempt(ctx, attempt)
}
}
}
}