Files
superbrain/internal/notify/engine.go
T
Andrew S Erwin 451312c3cf
release gate / check (push) Failing after 6m54s
Add notification engine phase 1: channels, rules, plan-gated delivery
When something happens in the brain, tell the user (PLAN_PRICING_TIERS
step 3). The engine is a SCANNER, not a hook system: producers are never
instrumented; exactly-once comes solely from UNIQUE(ruleId,dedupeKey) +
ON CONFLICT DO NOTHING, so rescans are free and restarts are safe.

Schema (migration 013 + schema.sql, converge-verified):
NotificationChannel (secrets encrypted at rest via internal/crypto, the
IMAP-password format), NotificationRule (one channel per rule in phase 1,
cooldown, version column), Notification (dedupe ledger + delivery state:
pending/sent/failed/suppressed, attempts, backoff timestamp).

internal/notify: two triggers — signal_created (fires only for signals
newer than the rule, never retro-notifying history) and bookmark_due
(lead-hours window, dedupe key carries the UTC due date so moving a
dueDate re-notifies and same-day rescans do not). Delivery claims rows in
one short transaction (FOR UPDATE SKIP LOCKED, batch 10) so multiple app
instances never double-send; exponential backoff to 5 attempts; per-rule
cooldown; per-owner pending cap. Channels: email (internal/mailer,
falls back to the account email), Slack webhook, Matrix room, Telegram
bot — webhooks dial through netguard inside outbound.Reserve budgets.
The plan gate re-checks at delivery: a downgraded tenant's rows become
'suppressed' instead of sending. Signal-app delivery deliberately absent
(needs a daemon; see plan doc hard truths).

API: channel/rule CRUD with the house version contract (409 on stale
base), write-only secrets (masked in every response; a PATCH echoing the
mask keeps the stored value), test-send endpoint with its own budget,
owner-scoped delivery history. Channel kinds gate on the ENTITLEMENT
CATALOG (403 'Not available on your plan') — never on TIER, per the
tenancy invariant.

Web: Settings -> Notifications tab (channels with per-kind forms and
Test button, rule builder, recent-delivery strip). Data loading uses the
house promise-chain shape; setState only in async callbacks (SSR lint).

Fixes along the way: mailer send budget raised 5->20/min (shared by
resets and notifications; 5/min would throttle a hosted instance) and
outbound gains ResetBudget() wired into the test harness — the global
'smtp' window made password-reset and notification tests collide when
the package ran as a whole.

Tests: full channel/rule/engine integration pass (masking + encryption
round-trip, masked-PATCH preservation, version contract, plan gating via
a forced 'free' tenant, dedupe across rescans, cooldown, real SMTP and
webhook delivery via loopback fakes, backoff recording, downgrade
suppression, history). Full suite green with -race; web lint/SSR-eslint/
build clean. Docs: API.md endpoint table, RUNNING.md, AGENTS.md
invariants, DESIGN_NOTIFICATIONS.md (local).
2026-10-26 14:43:15 -05:00

370 lines
13 KiB
Go

// Package notify is the notification engine (DESIGN_NOTIFICATIONS.md,
// phase 1): it scans for facts matching enabled rules (new signals, due
// bookmarks), records deduped Notification rows, and delivers them through
// the rule's channel.
//
// Design invariants:
// - Scanner, not hooks: producers are never instrumented; re-runs are
// free because UNIQUE("ruleId","dedupeKey") + ON CONFLICT DO NOTHING is
// the entire exactly-once story.
// - Anti-spam: per-rule cooldown, per-owner pending cap, per-row attempt
// cap with exponential backoff.
// - Plan gates: channels are validated against the owner's tenant plan at
// creation AND re-checked at delivery, so a downgraded plan stops
// sending (rows become 'suppressed', visible in history).
// - Every send is a server-initiated dial: email via internal/mailer,
// webhooks via the netguarded client in channels.go, all inside
// outbound.Reserve budgets.
package notify
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"log"
"math/rand/v2"
"strings"
"time"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/entitlements"
"github.com/andrew/superbrain/internal/outbound"
)
const (
tick = 60 * time.Second
maxAttempts = 5
maxBackoffMins = 240
ownerPendCap = 200 // per-owner pending+failed rows before new fires are suppressed
scanBatchLimit = 50 // facts considered per rule per tick
deliverBatch = 10 // rows claimed per delivery pass (one transaction)
sendTimeout = 20 * time.Second
staleDueHours = 14 * 24 // bookmarks due longer ago than this never fire
)
// RunLoop drives the engine until ctx is done. Mirrors signals.RunLoop:
// jittered ticks, failures logged not fatal, no work after cancellation.
func RunLoop(ctx context.Context, d *db.DB) {
// Small startup jitter so restarts don't align scans with the signals loop.
time.Sleep(time.Duration(rand.IntN(5000)) * time.Millisecond)
t := time.NewTicker(tick + time.Duration(rand.IntN(15000))*time.Millisecond)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if err := RunOnce(ctx, d); err != nil {
log.Printf("notify: tick failed: %v", err)
}
}
}
}
// RunOnce performs one scan+deliver pass. Exported for tests.
func RunOnce(ctx context.Context, d *db.DB) error {
if err := Scan(ctx, d); err != nil {
return fmt.Errorf("scan: %w", err)
}
return Deliver(ctx, d)
}
// Scan inserts deduped Notification rows for every enabled rule whose
// cooldown has elapsed and whose channel the owner's plan still allows.
func Scan(ctx context.Context, d *db.DB) error {
rows, err := d.QueryContext(ctx, `
SELECT r.id, r."ownerId", r.trigger, r.config, r."cooldownMinutes", r."lastFiredAt",
c.kind, u."tenantId"
FROM "NotificationRule" r
JOIN "NotificationChannel" c ON c.id = r."channelId"
JOIN "User" u ON u.id = r."ownerId"
WHERE r.enabled AND c.enabled`)
if err != nil {
return err
}
defer rows.Close()
type rule struct {
id, ownerID, trigger, kind string
config []byte
cooldown int
lastFired sql.NullTime
tenantID sql.NullString
}
var rules []rule
for rows.Next() {
var r rule
if err := rows.Scan(&r.id, &r.ownerID, &r.trigger, &r.config, &r.cooldown, &r.lastFired, &r.kind, &r.tenantID); err != nil {
return err
}
rules = append(rules, r)
}
if err := rows.Err(); err != nil {
return err
}
limitsCache := map[string]entitlements.Limits{}
tenants := db.NewTenantRepo(d)
pendCache := map[string]int{}
for _, r := range rules {
// Cooldown: skip the whole rule while it is still cooling.
if r.lastFired.Valid && time.Since(r.lastFired.Time) < time.Duration(r.cooldown)*time.Minute {
continue
}
// Plan gate at fire time (creation already checked; plans can change).
tid := r.tenantID.String
lim, ok := limitsCache[tid]
if !ok {
lim, err = tenants.Limits(ctx, tid)
if err != nil {
log.Printf("notify: limits for tenant %s: %v", tid, err)
continue
}
limitsCache[tid] = lim
}
if !lim.AllowChannel(r.kind) {
continue
}
// Per-owner pending cap: stop firing new notifications for owners
// with a stuck backlog instead of growing it without bound.
pend, ok := pendCache[r.ownerID]
if !ok {
if err := d.QueryRowContext(ctx,
`SELECT count(*) FROM "Notification" WHERE "ownerId"=$1 AND status IN ('pending','failed')`,
r.ownerID).Scan(&pend); err != nil {
return err
}
pendCache[r.ownerID] = pend
}
if pend >= ownerPendCap {
log.Printf("notify: owner %s at the pending cap (%d); rule %s skipped", r.ownerID, pend, r.id)
continue
}
var inserted int
switch r.trigger {
case "signal_created":
inserted, err = scanSignals(ctx, d, r.id)
case "bookmark_due":
inserted, err = scanDue(ctx, d, r.id, r.config)
default:
log.Printf("notify: rule %s has unknown trigger %q", r.id, r.trigger)
continue
}
if err != nil {
log.Printf("notify: scan rule %s: %v", r.id, err)
continue
}
if inserted > 0 {
pendCache[r.ownerID] = pend + inserted
if _, err := d.ExecContext(ctx,
`UPDATE "NotificationRule" SET "lastFiredAt"=now(),"updatedAt"=now() WHERE id=$1`, r.id); err != nil {
log.Printf("notify: lastFiredAt update for %s: %v", r.id, err)
}
}
}
return nil
}
// scanSignals fires for signals created since the rule itself was created —
// a new rule must not retro-notify the owner's whole history. Ids are
// deterministic per (rule, signal) so the conflict target is the only
// exactly-once mechanism needed.
func scanSignals(ctx context.Context, d *db.DB, ruleID string) (int, error) {
res, err := d.ExecContext(ctx, `
INSERT INTO "Notification"(id,"ruleId","ownerId","dedupeKey",title,body)
SELECT r.id||'-'||s.id, r.id, r."ownerId", 'signal:'||s.id,
left(s.title, 200), left(COALESCE(s.summary,''), 2000)
FROM "NotificationRule" r
JOIN LATERAL (
SELECT s.id, s.title, s.summary FROM "Signal" s
WHERE s."ownerId" = r."ownerId" AND s."createdAt" >= r."createdAt"
ORDER BY s."occurredAt" DESC LIMIT $2
) s ON true
WHERE r.id = $1
ON CONFLICT ("ruleId","dedupeKey") DO NOTHING`, ruleID, scanBatchLimit)
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
return int(n), nil
}
// scanDue fires for bookmarks due within the rule's lead window (default
// 24h) or overdue by less than staleDueHours. The dedupe key carries the
// due DATE (UTC), so moving a dueDate re-notifies and a same-day rescan
// does not.
func scanDue(ctx context.Context, d *db.DB, ruleID string, ruleConfig []byte) (int, error) {
leadHours := 24
var cfg struct {
LeadHours *int `json:"leadHours"`
}
if len(ruleConfig) > 0 {
_ = json.Unmarshal(ruleConfig, &cfg) // tolerate junk: defaults apply
}
if cfg.LeadHours != nil && *cfg.LeadHours >= 0 && *cfg.LeadHours <= 24*30 {
leadHours = *cfg.LeadHours
}
res, err := d.ExecContext(ctx, `
INSERT INTO "Notification"(id,"ruleId","ownerId","dedupeKey",title,body)
SELECT r.id||'-due-'||b.id||'-'||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD'),
r.id, r."ownerId",
'due:'||b.id||':'||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD'),
left('Bookmark due: '||COALESCE(NULLIF(b.title,''), b.url), 200),
CASE WHEN b."dueDate" <= now()
THEN 'Overdue since '||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI')||' UTC.'
ELSE 'Due '||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI')||' UTC.' END
FROM "NotificationRule" r
JOIN "Bookmark" b ON b."ownerId" = r."ownerId"
WHERE r.id = $1
AND b."dueDate" IS NOT NULL
AND b."dueDate" <= now() + make_interval(hours => $2)
AND b."dueDate" > now() - make_interval(hours => $3)
ON CONFLICT ("ruleId","dedupeKey") DO NOTHING`,
ruleID, leadHours, staleDueHours)
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
return int(n), nil
}
// Deliver claims due rows and pushes each through its channel. The whole
// pass runs in ONE transaction with FOR UPDATE SKIP LOCKED so multiple app
// instances never double-send; the batch is small (deliverBatch) and each
// send bounded (sendTimeout) to keep the transaction short. A crash
// mid-pass rolls the claim back and the next tick retries.
func Deliver(ctx context.Context, d *db.DB) error {
return db.Transaction(ctx, d, func(tx *sql.Tx) error {
rows, err := tx.QueryContext(ctx, `
SELECT n.id, n.title, n.body, n.attempts,
c.id, c."ownerId", c.kind, c.config, c.enabled, u."tenantId"
FROM "Notification" n
JOIN "NotificationRule" r ON r.id = n."ruleId"
JOIN "NotificationChannel" c ON c.id = r."channelId"
JOIN "User" u ON u.id = c."ownerId"
WHERE n.status IN ('pending','failed') AND n."nextAttemptAt" <= now() AND n.attempts < $1
ORDER BY n."nextAttemptAt"
LIMIT $2
FOR UPDATE OF n SKIP LOCKED`, maxAttempts, deliverBatch)
if err != nil {
return err
}
type item struct {
id, title, body, channelID, ownerID, kind string
attempts int
config []byte
channelEnabled bool
tenantID sql.NullString
}
var items []item
for rows.Next() {
var it item
if err := rows.Scan(&it.id, &it.title, &it.body, &it.attempts,
&it.channelID, &it.ownerID, &it.kind, &it.config, &it.channelEnabled, &it.tenantID); err != nil {
rows.Close()
return err
}
items = append(items, it)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
limitsCache := map[string]entitlements.Limits{}
tenants := db.NewTenantRepo(d)
secret := config.Load().EncryptionSecret()
for _, it := range items {
status, lastErr := "sent", ""
// A disabled channel or a plan that no longer allows it suppresses
// the row permanently (history shows why nothing was sent).
tid := it.tenantID.String
lim, ok := limitsCache[tid]
if !ok {
lim, err = tenants.Limits(ctx, tid)
if err != nil {
log.Printf("notify: limits for tenant %s: %v", tid, err)
continue // stay pending; retry next tick
}
limitsCache[tid] = lim
}
if !it.channelEnabled || !lim.AllowChannel(it.kind) {
status = "suppressed"
} else {
cfg, err := DecryptConfig(it.kind, it.config, secret)
if err != nil {
status, lastErr = "failed", err.Error()
} else {
release, _, ok := outbound.Reserve("notify:"+it.kind, 10, time.Minute)
if !ok {
continue // budget exhausted: stays pending, next tick retries
}
sendCtx, cancel := context.WithTimeout(ctx, sendTimeout)
err = Send(sendCtx, d, Channel{
ID: it.channelID, OwnerID: it.ownerID, Kind: it.kind, Config: cfg, Enabled: true,
}, it.title, it.body)
cancel()
release()
if err != nil {
status, lastErr = "failed", err.Error()
}
}
}
if err := recordDelivery(ctx, tx, it.id, status, it.attempts+1, lastErr); err != nil {
return err
}
if status == "failed" {
// Destination-level detail stays in the row; the log gets a
// classification only (never payloads or credentials).
log.Printf("notify: delivery %s failed: %s", it.id, classify(lastErr))
}
}
return nil
})
}
// recordDelivery applies the outcome: sent/suppressed rows close out;
// failures bump attempts and push nextAttemptAt out exponentially
// (10m, 20m, 40m, 80m, capped). Rows at maxAttempts stay 'failed' — the
// due query's attempts filter excludes them.
func recordDelivery(ctx context.Context, tx *sql.Tx, id, status string, attempts int, lastErr string) error {
if len(lastErr) > 500 {
lastErr = lastErr[:500]
}
backoffMins := 10 * (1 << min(max(attempts-1, 0), 4))
if backoffMins > maxBackoffMins {
backoffMins = maxBackoffMins
}
_, err := tx.ExecContext(ctx, `
UPDATE "Notification"
SET status=$2, attempts=$3, "lastError"=NULLIF($4,''),
"nextAttemptAt"=CASE WHEN $2 IN ('sent','suppressed') THEN "nextAttemptAt" ELSE now()+make_interval(mins => $5) END,
"sentAt"=CASE WHEN $2='sent' THEN now() ELSE "sentAt" END
WHERE id=$1`,
id, status, attempts, lastErr, backoffMins)
return err
}
// classify reduces an error to a log-safe category.
func classify(err string) string {
l := strings.ToLower(err)
switch {
case strings.Contains(l, "webhook answered"):
return err // already destination-safe (status + bounded snippet)
case strings.Contains(l, "netguard"):
return "blocked destination"
case strings.Contains(l, "no such host"), strings.Contains(l, "server misbehaving"):
return "dns failure"
case strings.Contains(l, "timeout"), strings.Contains(l, "deadline"):
return "timeout"
case strings.Contains(l, "mailer"), strings.Contains(l, "smtp"):
return "smtp failure"
default:
return "send failure"
}
}