Add notification engine phase 1: channels, rules, plan-gated delivery
release gate / check (push) Failing after 6m54s

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).
This commit is contained in:
Andrew S Erwin
2026-10-26 14:43:15 -05:00
parent 1f38c4d56c
commit 451312c3cf
15 changed files with 2034 additions and 7 deletions
+562
View File
@@ -0,0 +1,562 @@
package handlers
// Notification channels, rules and history (DESIGN_NOTIFICATIONS.md).
// Owner-scoped like every user resource; mutating PATCHes carry the
// expected version (409 on stale base, the house mutation contract).
// Channel secrets are write-only: responses carry the masked projection,
// and a PATCH echoing the mask keeps the stored secret.
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/notify"
"github.com/andrew/superbrain/internal/outbound"
)
// errPlanGate answers 403 for features the tenant's plan does not include.
// The entitlement catalog (not TIER) is the gate — see AGENTS.md invariant.
func planGate(w http.ResponseWriter) {
respond(w, 403, Error{Error: "Not available on your plan"}, nil)
}
// userTenantAllows resolves the caller's plan via their tenant and reports
// whether a channel kind is included.
func userTenantAllows(r *http.Request, kind string) (bool, error) {
var tenantID *string
if e := database(r).QueryRowContext(r.Context(),
`SELECT "tenantId" FROM "User" WHERE id=$1`, user(r)).Scan(&tenantID); e != nil {
return false, e
}
tid := ""
if tenantID != nil {
tid = *tenantID
}
lim, e := db.NewTenantRepo(database(r)).Limits(r.Context(), tid)
if e != nil {
return false, e
}
return lim.AllowChannel(kind), nil
}
// channelConfigFields is the per-kind key allowlist: unknown submitted keys
// are dropped so stored configs stay auditable.
func channelConfigFields(kind string) []string {
switch kind {
case "email":
return []string{"address"}
case "slack":
return []string{"webhookUrl"}
case "matrix":
return []string{"homeserver", "roomId", "accessToken"}
case "telegram":
return []string{"botToken", "chatId"}
}
return nil
}
func cleanChannelConfig(kind string, raw any) (map[string]string, error) {
cfg := map[string]string{}
if raw == nil {
return cfg, nil
}
m, ok := raw.(map[string]any)
if !ok {
return nil, bad("Config must be an object")
}
for _, key := range channelConfigFields(kind) {
if v, ok := m[key]; ok {
s, ok := v.(string)
if !ok {
return nil, bad("Config values must be text")
}
s = strings.TrimSpace(s)
if len(s) > 2000 {
return nil, bad("Config value too long")
}
cfg[key] = s
}
}
return cfg, nil
}
// storedConfigJSON normalizes the jsonb config column (to_jsonb yields a
// map; direct reads may yield a string) into JSON text for the notify
// package's decrypt path.
func storedConfigJSON(row object) []byte {
switch c := row["config"].(type) {
case string:
if c == "" {
return []byte("{}")
}
return []byte(c)
case map[string]any:
raw, _ := json.Marshal(c)
return raw
}
return []byte("{}")
}
// channelProjection is the only shape channel data ever leaves the server
// in: plaintext non-secret config plus the mask over secret fields.
func channelProjection(row object) object {
kind := str(row, "kind")
cfg := map[string]string{}
if dec, err := notify.DecryptConfig(kind, storedConfigJSON(row), config.Load().EncryptionSecret()); err == nil {
cfg = notify.MaskConfig(kind, dec)
}
return object{
"id": row["id"], "kind": kind, "name": row["name"],
"enabled": row["enabled"], "version": row["version"],
"config": cfg, "createdAt": row["createdAt"],
}
}
// requiredVersion enforces the house mutation contract: every mutating
// PATCH sends the base version it edited from.
func requiredVersion(b object) (int, error) {
v, present := b["version"]
if !present {
return 0, bad("version is required; refetch the record and retry")
}
f, ok := v.(float64)
if !ok || f < 0 || f != math.Trunc(f) {
return 0, bad("version must be a non-negative integer")
}
return int(f), nil
}
// patchVersioned applies server-owned updates with the optimistic version
// guard and bumps version+updatedAt. Keys come from handler allowlists,
// never from request data; values are bind parameters. A row that moved on
// since the caller's read is a 409 (rows-affected 0 -> ErrNotFound from
// the RETURNING scan).
func patchVersioned(r *http.Request, table, id string, baseVersion int, updates object) (object, error) {
keys := make([]string, 0, len(updates))
for k := range updates {
keys = append(keys, k)
}
sort.Strings(keys)
sets := make([]string, 0, len(keys)+2)
args := make([]any, 0, len(keys)+3)
for _, k := range keys {
args = append(args, updates[k])
sets = append(sets, db.Quote(k)+fmt.Sprintf("=$%d", len(args)))
}
sets = append(sets, `version=version+1`, `"updatedAt"=now()`)
args = append(args, id, user(r), baseVersion)
q := `UPDATE ` + db.Quote(table) + ` SET ` + strings.Join(sets, ",") +
fmt.Sprintf(` WHERE id=$%d AND "ownerId"=$%d AND version=$%d RETURNING to_jsonb(`,
len(args)-2, len(args)-1, len(args)) + db.Quote(table) + `)`
row, err := db.One(r.Context(), database(r), q, args...)
if errors.Is(err, db.ErrNotFound) {
return nil, conflict("Modified elsewhere; reload to see the latest version")
}
return row, err
}
func truncate(s string, n int) string {
rs := []rune(s)
if len(rs) <= n {
return s
}
return string(rs[:n])
}
func HandleNotificationChannelsList(w http.ResponseWriter, r *http.Request) {
rows, e := db.Many(r.Context(), database(r),
`SELECT to_jsonb(t) FROM "NotificationChannel" t WHERE "ownerId"=$1 ORDER BY "createdAt"`, user(r))
if e != nil {
respond(w, 0, nil, e)
return
}
out := []object{}
for _, row := range rows {
out = append(out, channelProjection(row))
}
respond(w, 200, out, nil)
}
func HandleNotificationChannelsCreate(w http.ResponseWriter, r *http.Request) {
b, ok := read(w, r)
if !ok {
return
}
kind := str(b, "kind")
if !notify.ValidKind(kind) {
respond(w, 0, nil, bad("Unknown channel kind"))
return
}
name := strings.TrimSpace(str(b, "name"))
if name == "" || len([]rune(name)) > 120 {
respond(w, 0, nil, bad("Name is required (max 120 characters)"))
return
}
allow, e := userTenantAllows(r, kind)
if e != nil {
respond(w, 0, nil, e)
return
}
if !allow {
planGate(w)
return
}
cfg, e := cleanChannelConfig(kind, b["config"])
if e != nil {
respond(w, 0, nil, e)
return
}
if e := notify.ValidateConfig(kind, cfg); e != nil {
respond(w, 0, nil, bad(e.Error()))
return
}
enc, e := notify.EncryptConfig(kind, cfg, config.Load().EncryptionSecret())
if e != nil {
respond(w, 0, nil, e)
return
}
enabled := true
if v, ok := b["enabled"].(bool); ok {
enabled = v
}
row, e := db.Insert(r.Context(), database(r), "NotificationChannel", object{
"id": db.NewID(), "ownerId": user(r), "kind": kind, "name": name,
"config": enc, "enabled": enabled,
})
if e != nil {
respond(w, 0, nil, e)
return
}
respond(w, 201, channelProjection(row), nil)
}
func HandleNotificationChannelsUpdate(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
existing, e := owned(r, database(r), "NotificationChannel", id, "ownerId")
if e != nil {
respond(w, 0, nil, e)
return
}
b, ok := read(w, r)
if !ok {
return
}
baseVersion, e := requiredVersion(b)
if e != nil {
respond(w, 0, nil, e)
return
}
if stored, _ := existing["version"].(float64); int(stored) != baseVersion {
respond(w, 0, nil, conflict("Channel was modified elsewhere; reload to see the latest version"))
return
}
kind := str(existing, "kind")
updates := object{}
if _, present := b["name"]; present {
s := strings.TrimSpace(str(b, "name"))
if s == "" || len([]rune(s)) > 120 {
respond(w, 0, nil, bad("Name must be 1-120 characters"))
return
}
updates["name"] = s
}
if v, present := b["enabled"]; present {
ev, ok := v.(bool)
if !ok {
respond(w, 0, nil, bad("Enabled must be boolean"))
return
}
updates["enabled"] = ev
}
if _, present := b["config"]; present {
submitted, e := cleanChannelConfig(kind, b["config"])
if e != nil {
respond(w, 0, nil, e)
return
}
storedCfg, _ := notify.DecryptConfig(kind, storedConfigJSON(existing), config.Load().EncryptionSecret())
if storedCfg == nil {
storedCfg = map[string]string{}
}
merged := notify.MergeMasked(submitted, storedCfg, kind)
if e := notify.ValidateConfig(kind, merged); e != nil {
respond(w, 0, nil, bad(e.Error()))
return
}
enc, e := notify.EncryptConfig(kind, merged, config.Load().EncryptionSecret())
if e != nil {
respond(w, 0, nil, e)
return
}
updates["config"] = enc
}
if len(updates) == 0 {
respond(w, 0, nil, bad("Nothing to update"))
return
}
row, e := patchVersioned(r, "NotificationChannel", id, baseVersion, updates)
if e != nil {
respond(w, 0, nil, e)
return
}
respond(w, 200, channelProjection(row), nil)
}
func HandleNotificationChannelsDelete(w http.ResponseWriter, r *http.Request) {
respond(w, 200, object{"ok": true}, remove(r, "NotificationChannel", r.PathValue("id"), "ownerId"))
}
// HandleNotificationChannelsTest sends one message through the stored
// config right now (same path as the engine, budget included) so a bad
// webhook/token fails at setup time, not at 3am.
func HandleNotificationChannelsTest(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
row, e := owned(r, database(r), "NotificationChannel", id, "ownerId")
if e != nil {
respond(w, 0, nil, e)
return
}
kind := str(row, "kind")
cfg, e := notify.DecryptConfig(kind, storedConfigJSON(row), config.Load().EncryptionSecret())
if e != nil {
respond(w, 0, nil, bad("Stored credentials cannot be decrypted; re-enter them"))
return
}
release, retry, ok := outbound.Reserve("notify-test:"+kind+":"+user(r), 10, time.Minute)
if !ok {
w.Header().Set("Retry-After", strconv.Itoa(int(retry.Seconds())))
respond(w, 429, Error{Error: "Too many test sends, slow down"}, nil)
return
}
defer release()
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
ch := notify.Channel{ID: id, OwnerID: user(r), Kind: kind, Config: cfg, Enabled: true}
if e := notify.Send(ctx, database(r), ch, "Superbrain test notification",
"Your "+kind+" channel is set up correctly."); e != nil {
respond(w, 502, Error{Error: "Test delivery failed: " + truncate(e.Error(), 200)}, nil)
return
}
respond(w, 200, object{"ok": true}, nil)
}
func HandleNotificationRulesList(w http.ResponseWriter, r *http.Request) {
rows, e := db.Many(r.Context(), database(r), `
SELECT to_jsonb(r) || jsonb_build_object('channelKind', c.kind, 'channelName', c.name)
FROM "NotificationRule" r JOIN "NotificationChannel" c ON c.id=r."channelId"
WHERE r."ownerId"=$1 ORDER BY r."createdAt"`, user(r))
if e != nil {
respond(w, 0, nil, e)
return
}
out := []object{}
for _, row := range rows {
out = append(out, ruleProjection(row, str(row, "channelKind"), str(row, "channelName")))
}
respond(w, 200, out, nil)
}
func HandleNotificationRulesCreate(w http.ResponseWriter, r *http.Request) {
b, ok := read(w, r)
if !ok {
return
}
name := strings.TrimSpace(str(b, "name"))
if name == "" || len([]rune(name)) > 120 {
respond(w, 0, nil, bad("Name is required (max 120 characters)"))
return
}
trigger := str(b, "trigger")
if trigger != "signal_created" && trigger != "bookmark_due" {
respond(w, 0, nil, bad("Trigger must be signal_created or bookmark_due"))
return
}
channel, e := owned(r, database(r), "NotificationChannel", str(b, "channelId"), "ownerId")
if e != nil {
respond(w, 0, nil, bad("Channel not found"))
return
}
allow, e := userTenantAllows(r, str(channel, "kind"))
if e != nil {
respond(w, 0, nil, e)
return
}
if !allow {
planGate(w)
return
}
cfg := object{}
if trigger == "bookmark_due" {
lead := 24
if c, ok := b["config"].(map[string]any); ok {
if v, ok := c["leadHours"].(float64); ok && v >= 0 && v <= 24*30 {
lead = int(v)
}
}
cfg["leadHours"] = lead
}
raw, _ := json.Marshal(cfg)
cooldown := 60
if v, ok := b["cooldownMinutes"].(float64); ok && v >= 1 && v <= 7*24*60 {
cooldown = int(v)
}
enabled := true
if v, ok := b["enabled"].(bool); ok {
enabled = v
}
row, e := db.Insert(r.Context(), database(r), "NotificationRule", object{
"id": db.NewID(), "ownerId": user(r), "name": name, "trigger": trigger,
"config": string(raw), "channelId": str(b, "channelId"),
"cooldownMinutes": cooldown, "enabled": enabled,
})
if e != nil {
respond(w, 0, nil, e)
return
}
respond(w, 201, ruleProjection(row, str(channel, "kind"), str(channel, "name")), nil)
}
func HandleNotificationRulesUpdate(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
existing, e := owned(r, database(r), "NotificationRule", id, "ownerId")
if e != nil {
respond(w, 0, nil, e)
return
}
b, ok := read(w, r)
if !ok {
return
}
baseVersion, e := requiredVersion(b)
if e != nil {
respond(w, 0, nil, e)
return
}
if stored, _ := existing["version"].(float64); int(stored) != baseVersion {
respond(w, 0, nil, conflict("Rule was modified elsewhere; reload to see the latest version"))
return
}
updates := object{}
if _, present := b["name"]; present {
s := strings.TrimSpace(str(b, "name"))
if s == "" || len([]rune(s)) > 120 {
respond(w, 0, nil, bad("Name must be 1-120 characters"))
return
}
updates["name"] = s
}
if v, present := b["enabled"]; present {
ev, ok := v.(bool)
if !ok {
respond(w, 0, nil, bad("Enabled must be boolean"))
return
}
updates["enabled"] = ev
}
if v, present := b["cooldownMinutes"]; present {
cv, ok := v.(float64)
if !ok || cv < 1 || cv > 7*24*60 {
respond(w, 0, nil, bad("cooldownMinutes must be 1..10080"))
return
}
updates["cooldownMinutes"] = int(cv)
}
if _, present := b["channelId"]; present {
channel, e := owned(r, database(r), "NotificationChannel", str(b, "channelId"), "ownerId")
if e != nil {
respond(w, 0, nil, bad("Channel not found"))
return
}
allow, e := userTenantAllows(r, str(channel, "kind"))
if e != nil {
respond(w, 0, nil, e)
return
}
if !allow {
planGate(w)
return
}
updates["channelId"] = str(b, "channelId")
}
if _, present := b["config"]; present && str(existing, "trigger") == "bookmark_due" {
lead := 24
if c, ok := b["config"].(map[string]any); ok {
if lv, ok := c["leadHours"].(float64); ok && lv >= 0 && lv <= 24*30 {
lead = int(lv)
}
}
raw, _ := json.Marshal(object{"leadHours": lead})
updates["config"] = string(raw)
}
if len(updates) == 0 {
respond(w, 0, nil, bad("Nothing to update"))
return
}
row, e := patchVersioned(r, "NotificationRule", id, baseVersion, updates)
if e != nil {
respond(w, 0, nil, e)
return
}
kind, name := "", ""
if ch, e := owned(r, database(r), "NotificationChannel", str(row, "channelId"), "ownerId"); e == nil {
kind, name = str(ch, "kind"), str(ch, "name")
}
respond(w, 200, ruleProjection(row, kind, name), nil)
}
func HandleNotificationRulesDelete(w http.ResponseWriter, r *http.Request) {
respond(w, 200, object{"ok": true}, remove(r, "NotificationRule", r.PathValue("id"), "ownerId"))
}
// HandleNotificationsList is the owner's recent delivery history.
func HandleNotificationsList(w http.ResponseWriter, r *http.Request) {
rows, e := db.Many(r.Context(), database(r), `
SELECT to_jsonb(n) || jsonb_build_object('ruleName', r.name, 'channelKind', c.kind)
FROM "Notification" n
JOIN "NotificationRule" r ON r.id = n."ruleId"
JOIN "NotificationChannel" c ON c.id = r."channelId"
WHERE n."ownerId"=$1
ORDER BY n."createdAt" DESC LIMIT 100`, user(r))
if e != nil {
respond(w, 0, nil, e)
return
}
out := []object{}
for _, row := range rows {
out = append(out, object{
"id": row["id"], "title": row["title"], "body": row["body"],
"status": row["status"], "attempts": row["attempts"],
"ruleName": row["ruleName"], "channelKind": row["channelKind"],
"sentAt": row["sentAt"], "createdAt": row["createdAt"],
})
}
respond(w, 200, out, nil)
}
func ruleProjection(row object, channelKind, channelName string) object {
cfg := object{}
switch c := row["config"].(type) {
case map[string]any:
cfg = c
case string:
if c != "" {
_ = json.Unmarshal([]byte(c), &cfg)
}
}
return object{
"id": row["id"], "name": row["name"], "trigger": row["trigger"], "config": cfg,
"channelId": row["channelId"], "channelKind": channelKind, "channelName": channelName,
"cooldownMinutes": row["cooldownMinutes"], "enabled": row["enabled"],
"lastFiredAt": row["lastFiredAt"], "version": row["version"], "createdAt": row["createdAt"],
}
}
+5 -1
View File
@@ -6,6 +6,7 @@ import (
"github.com/andrew/superbrain/internal/auth"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/outbound"
"io"
"net/http"
"net/http/cookiejar"
@@ -29,9 +30,12 @@ func testServerDB(t *testing.T) (*httptest.Server, *db.DB) {
t.Skip("set TEST_DATABASE_URL to run PostgreSQL integration tests")
}
// The limiter stores are process-global and login has no loopback
// exemption (review SEC-1); give every test a clean slate.
// exemption (review SEC-1); give every test a clean slate. Same for the
// outbound budgets (mailer/notify/preview share one process-wide store).
auth.ResetRateLimits()
outbound.ResetBudget()
t.Cleanup(auth.ResetRateLimits)
t.Cleanup(outbound.ResetBudget)
t.Setenv("AUTH_SECRET", "integration-test-secret")
t.Setenv("NEXTAUTH_SECRET", "integration-test-secret")
t.Setenv("ADMIN_EMAILS", "")
+287
View File
@@ -0,0 +1,287 @@
package http
import (
"context"
"io"
"net"
"net/http"
"net/http/cookiejar"
"strings"
"sync"
"testing"
"time"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/notify"
)
// fakeWebhook captures one Slack-style POST for the delivery tests.
type fakeWebhook struct {
t *testing.T
srv *http.Server
ln net.Listener
mu sync.Mutex
bodies []string
}
func newFakeWebhook(t *testing.T) *fakeWebhook {
t.Helper()
ln, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal(e)
}
f := &fakeWebhook{t: t, ln: ln}
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
f.mu.Lock()
f.bodies = append(f.bodies, string(raw))
f.mu.Unlock()
w.WriteHeader(200)
})
f.srv = &http.Server{Handler: mux}
go f.srv.Serve(ln)
t.Cleanup(func() { f.srv.Close() })
return f
}
func (f *fakeWebhook) url() string { return "http://" + f.ln.Addr().String() + "/hook" }
func (f *fakeWebhook) received() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.bodies...)
}
// The full phase-1 surface: channel CRUD with write-only secrets, plan
// gating via the entitlement catalog, the version contract on rules, and
// engine behavior (dedupe, cooldown, delivery, backoff, suppression).
func TestNotificationsChannelsAndRules(t *testing.T) {
srv, d := testServerDB(t)
smtp := newFakeSMTP(t)
host, port, _ := net.SplitHostPort(smtp.ln.Addr().String())
t.Setenv("SMTP_HOST", host)
t.Setenv("SMTP_PORT", port)
t.Setenv("SMTP_FROM", "superbrain@superbrain.test")
t.Setenv("NEXTAUTH_URL", "https://superbrain.test")
jar, _ := cookiejar.New(nil)
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200)
// --- channel create: secrets are masked in every response ---
created := alice.request("POST", "/api/notifications/channels", map[string]any{
"kind": "email", "name": "My inbox", "config": map[string]any{"address": ""},
}, 201)
emailChID := created["id"].(string)
version := int(created["version"].(float64))
hook := newFakeWebhook(t)
slack := alice.request("POST", "/api/notifications/channels", map[string]any{
"kind": "slack", "name": "team", "config": map[string]any{"webhookUrl": hook.url()},
}, 201)
slackID := slack["id"].(string)
if cfg := slack["config"].(map[string]any); cfg["webhookUrl"] != notify.MaskValue {
t.Fatalf("secret leaked in create response: %v", cfg)
}
// The stored secret decrypts to the original (encryption round-trip).
var storedCfg string
if e := d.QueryRow(`SELECT config::text FROM "NotificationChannel" WHERE id=$1`, slackID).Scan(&storedCfg); e != nil {
t.Fatal(e)
}
if strings.Contains(storedCfg, hook.url()) {
t.Fatal("webhook URL stored in plaintext")
}
dec, e := notify.DecryptConfig("slack", []byte(storedCfg), "integration-test-secret")
if e != nil || dec["webhookUrl"] != hook.url() {
t.Fatalf("decrypt round-trip failed: %v %v", dec, e)
}
// --- PATCH contract: version required, stale rejected, mask keeps secret ---
alice.request("PATCH", "/api/notifications/channels/"+slackID, map[string]any{"name": "renamed"}, 400)
alice.request("PATCH", "/api/notifications/channels/"+slackID, map[string]any{"name": "renamed", "version": version + 5}, 409)
slackVersion := int(slack["version"].(float64))
patched := alice.request("PATCH", "/api/notifications/channels/"+slackID, map[string]any{
"name": "renamed", "version": slackVersion,
"config": map[string]any{"webhookUrl": notify.MaskValue},
}, 200)
if patched["name"] != "renamed" {
t.Fatal("rename not applied")
}
dec2, e := notify.DecryptConfig("slack", []byte(mustConfigJSON(t, d, slackID)), "integration-test-secret")
if e != nil || dec2["webhookUrl"] != hook.url() {
t.Fatalf("masked PATCH clobbered the stored secret: %v %v", dec2, e)
}
// Bad config shape is rejected.
alice.request("POST", "/api/notifications/channels", map[string]any{
"kind": "matrix", "name": "bad", "config": map[string]any{"homeserver": "notaurl", "roomId": "!x:y", "accessToken": "t"},
}, 400)
// --- plan gating via the entitlement catalog (never TIER directly) ---
// Default tenant is 'selfhosted' (everything allowed); force the free
// plan and telegram must be refused while email stays allowed.
if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, db.DefaultTenantID); e != nil {
t.Fatal(e)
}
alice.request("POST", "/api/notifications/channels", map[string]any{
"kind": "telegram", "name": "tg", "config": map[string]any{"botToken": "123:abc", "chatId": "42"},
}, 403)
alice.request("POST", "/api/notifications/channels", map[string]any{
"kind": "email", "name": "second inbox",
}, 201)
if _, e := d.Exec(`UPDATE "Tenant" SET plan='selfhosted' WHERE id=$1`, db.DefaultTenantID); e != nil {
t.Fatal(e)
}
// --- rules: create, version contract, list projection ---
due := time.Now().UTC().Add(6 * time.Hour).Format(time.RFC3339)
bm := alice.request("POST", "/api/bookmarks", map[string]any{
"url": "https://example.org/due-soon", "title": "Due soon", "dueDate": due,
}, 201)
_ = bm
rule := alice.request("POST", "/api/notifications/rules", map[string]any{
"name": "Due reminders", "trigger": "bookmark_due", "channelId": emailChID,
"config": map[string]any{"leadHours": 24}, "cooldownMinutes": 60,
}, 201)
ruleID := rule["id"].(string)
if rule["channelKind"] != "email" {
t.Fatalf("rule projection missing channel join: %v", rule)
}
alice.request("PATCH", "/api/notifications/rules/"+ruleID, map[string]any{"cooldownMinutes": float64(99999)}, 400)
alice.request("PATCH", "/api/notifications/rules/"+ruleID, map[string]any{"enabled": false}, 400)
upd := alice.request("PATCH", "/api/notifications/rules/"+ruleID, map[string]any{
"enabled": true, "version": int(rule["version"].(float64)),
}, 200)
_ = upd
// --- engine: scan fires exactly once, delivers through mailer ---
ctx := context.Background()
if e := notify.RunOnce(ctx, d); e != nil {
t.Fatal(e)
}
msg := smtp.waitForMessage(t, 1)
if msg[0] != "alice@superbrain.test" || !strings.Contains(msg[1], "Bookmark due: Due soon") {
t.Fatalf("unexpected notification mail: %v", msg)
}
var status string
if e := d.QueryRow(`SELECT status FROM "Notification" WHERE "ruleId"=$1`, ruleID).Scan(&status); e != nil || status != "sent" {
t.Fatalf("notification status = %s (%v), want sent", status, e)
}
// Rescan: the dedupe key makes the second pass a no-op.
if e := notify.RunOnce(ctx, d); e != nil {
t.Fatal(e)
}
if n := smtp.messages(); len(n) != 1 {
t.Fatalf("dedupe failed: %d mails", len(n))
}
// Cooldown: a NEW due bookmark does not fire while the rule cools.
alice.request("POST", "/api/bookmarks", map[string]any{
"url": "https://example.org/due-too", "title": "Due too",
"dueDate": time.Now().UTC().Add(2 * time.Hour).Format(time.RFC3339),
}, 201)
if e := notify.RunOnce(ctx, d); e != nil {
t.Fatal(e)
}
if n := smtp.messages(); len(n) != 1 {
t.Fatalf("cooldown ignored: %d mails", len(n))
}
if _, e := d.Exec(`UPDATE "NotificationRule" SET "lastFiredAt"=now()-interval '2 hours' WHERE id=$1`, ruleID); e != nil {
t.Fatal(e)
}
if e := notify.RunOnce(ctx, d); e != nil {
t.Fatal(e)
}
if n := smtp.messages(); len(n) != 2 {
t.Fatalf("after cooldown expiry: %d mails, want 2", len(n))
}
// --- webhook delivery through the netguarded client ---
slackRule := alice.request("POST", "/api/notifications/rules", map[string]any{
"name": "Signals to slack", "trigger": "signal_created", "channelId": slackID,
}, 201)
_ = slackRule
if _, e := d.Exec(`
INSERT INTO "Signal"(id,"sourceType",title,summary,"bookmarkId","ownerId")
SELECT 'sig-1','email','Invoice arrived','from billing', b.id, u.id
FROM "Bookmark" b, "User" u WHERE b.url='https://example.org/due-soon' AND u.email='alice@superbrain.test' LIMIT 1`); e != nil {
t.Fatal(e)
}
if e := notify.RunOnce(ctx, d); e != nil {
t.Fatal(e)
}
got := hook.received()
if len(got) != 1 || !strings.Contains(got[0], "Invoice arrived") {
t.Fatalf("webhook delivery missing: %v", got)
}
// --- failure path: attempts bump, backoff pushes the row out ---
deadLn, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal(e)
}
deadAddr := deadLn.Addr().String()
deadLn.Close()
dead := alice.request("POST", "/api/notifications/channels", map[string]any{
"kind": "slack", "name": "dead", "config": map[string]any{"webhookUrl": "http://" + deadAddr + "/hook"},
}, 201)
deadRule := alice.request("POST", "/api/notifications/rules", map[string]any{
"name": "dead hook", "trigger": "signal_created", "channelId": dead["id"].(string),
}, 201)
if _, e := d.Exec(`INSERT INTO "Signal"(id,"sourceType",title,"bookmarkId","ownerId")
SELECT 'sig-2','email','Second', b.id, u.id FROM "Bookmark" b, "User" u
WHERE b.url='https://example.org/due-soon' AND u.email='alice@superbrain.test' LIMIT 1`); e != nil {
t.Fatal(e)
}
if e := notify.RunOnce(ctx, d); e != nil {
t.Fatal(e)
}
var attempts int
var nextAt time.Time
var lastErr *string
if e := d.QueryRow(`SELECT attempts, "nextAttemptAt", "lastError" FROM "Notification" WHERE "ruleId"=$1`, deadRule["id"].(string)).
Scan(&attempts, &nextAt, &lastErr); e != nil {
t.Fatal(e)
}
if attempts != 1 || lastErr == nil || !nextAt.After(time.Now()) {
t.Fatalf("failure not recorded: attempts=%d nextAt=%v err=%v", attempts, nextAt, lastErr)
}
// --- suppression: a downgraded plan stops delivery (no send attempted) ---
if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, db.DefaultTenantID); e != nil {
t.Fatal(e)
}
if _, e := d.Exec(`UPDATE "Notification" SET status='pending', attempts=0, "nextAttemptAt"=now() WHERE "ruleId"=$1`, deadRule["id"].(string)); e != nil {
t.Fatal(e)
}
if e := notify.RunOnce(ctx, d); e != nil {
t.Fatal(e)
}
var suppressed string
if e := d.QueryRow(`SELECT status FROM "Notification" WHERE "ruleId"=$1`, deadRule["id"].(string)).Scan(&suppressed); e != nil || suppressed != "suppressed" {
t.Fatalf("downgraded plan must suppress delivery, got %q (%v)", suppressed, e)
}
// --- history endpoint (array response: fetch raw with the session jar) ---
req, _ := http.NewRequest("GET", srv.URL+"/api/notifications", nil)
res, e := (&http.Client{Jar: jar}).Do(req)
if e != nil {
t.Fatal(e)
}
defer res.Body.Close()
rawBody, _ := io.ReadAll(res.Body)
if res.StatusCode != 200 || !strings.Contains(string(rawBody), `"status":"sent"`) {
t.Fatalf("history missing delivered rows: %d %s", res.StatusCode, rawBody)
}
}
func mustConfigJSON(t *testing.T, d *db.DB, channelID string) string {
t.Helper()
var raw string
if e := d.QueryRow(`SELECT config::text FROM "NotificationChannel" WHERE id=$1`, channelID).Scan(&raw); e != nil {
t.Fatal(e)
}
return raw
}
+12
View File
@@ -115,6 +115,18 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
mux.HandleFunc("PATCH /api/signal-sources/{id}", authed(handlers.HandleSignalSourcesUpdate))
mux.HandleFunc("DELETE /api/signal-sources/{id}", authed(handlers.HandleSignalSourcesDelete))
// 4.7b Notifications (DESIGN_NOTIFICATIONS.md): channels, rules, history.
mux.HandleFunc("GET /api/notifications/channels", authed(handlers.HandleNotificationChannelsList))
mux.HandleFunc("POST /api/notifications/channels", authed(handlers.HandleNotificationChannelsCreate))
mux.HandleFunc("PATCH /api/notifications/channels/{id}", authed(handlers.HandleNotificationChannelsUpdate))
mux.HandleFunc("DELETE /api/notifications/channels/{id}", authed(handlers.HandleNotificationChannelsDelete))
mux.HandleFunc("POST /api/notifications/channels/{id}/test", authed(handlers.HandleNotificationChannelsTest))
mux.HandleFunc("GET /api/notifications/rules", authed(handlers.HandleNotificationRulesList))
mux.HandleFunc("POST /api/notifications/rules", authed(handlers.HandleNotificationRulesCreate))
mux.HandleFunc("PATCH /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesUpdate))
mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete))
mux.HandleFunc("GET /api/notifications", authed(handlers.HandleNotificationsList))
// 4.8 Alerts, contacts, email, dates, users
mux.HandleFunc("GET /api/alerts/check", authed(handlers.HandleAlertsCheck))
mux.HandleFunc("DELETE /api/alerts/{bookmarkId}", authed(handlers.HandleAlertsDismiss))
+6 -4
View File
@@ -81,10 +81,12 @@ func Send(ctx context.Context, to, subject, body string) error {
if to == "" {
return errors.New("mailer: missing recipient")
}
// Global send budget: password resets are rare and an unreachable or
// blackholed relay must not pile up goroutines (same shape as the IMAP
// and CardDAV callers).
release, _, ok := outbound.Reserve("smtp", 5, time.Minute)
// Global send budget: transactional mail is rare per user but a hosted
// (multi-tenant) instance can legitimately send bursts — password resets
// and notification deliveries share this one key. The bound exists so an
// unreachable or blackholed relay cannot pile up goroutines (same shape
// as the IMAP and CardDAV callers), not to ration legitimate mail.
release, _, ok := outbound.Reserve("smtp", 20, time.Minute)
if !ok {
return errors.New("mailer: send budget exhausted")
}
+296
View File
@@ -0,0 +1,296 @@
package notify
// Channel configuration: validation, at-rest encryption, API masking and
// the per-kind send adapters (DESIGN_NOTIFICATIONS.md).
//
// Secrets (webhook URLs, tokens) are encrypted with internal/crypto under
// the same EncryptionSecret as IMAP passwords — the version-byte format and
// legacy fallback live there; this package never sniffs ciphertext itself.
// GET responses only ever carry masked config; a PATCH that echoes the mask
// back keeps the stored secret (write-only fields).
//
// All HTTP sends dial through netguard (443/80 only, private ranges
// blocked unless the operator pinned the host via NETGUARD_TRUSTED_HOSTS —
// e.g. a LAN Matrix homeserver) inside outbound.Reserve budgets owned by
// the engine, never per-adapter.
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/mail"
"net/url"
"strings"
"time"
crypt "github.com/andrew/superbrain/internal/crypto"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/mailer"
"github.com/andrew/superbrain/internal/netguard"
)
// Kinds is the phase-1 channel set (mirrors the NotificationChannel CHECK).
var Kinds = []string{"email", "slack", "matrix", "telegram"}
// ValidKind reports whether kind is a known channel kind.
func ValidKind(kind string) bool {
for _, k := range Kinds {
if k == kind {
return true
}
}
return false
}
// secretFields are encrypted at rest and masked in every API response.
var secretFields = map[string][]string{
"email": {},
"slack": {"webhookUrl"},
"matrix": {"accessToken"},
"telegram": {"botToken"},
}
// MaskValue replaces a secret in API output. A PATCH carrying this exact
// value for a secret field means "keep what is stored".
const MaskValue = "••••••••"
// Channel is a decrypted, in-memory channel. Config values are plaintext;
// this struct must never be serialized to an API response directly.
type Channel struct {
ID string
OwnerID string
Kind string
Name string
Config map[string]string
Enabled bool
}
// ValidateConfig enforces per-kind shape. It runs on create AND update so a
// stored config can never drift into an undeliverable shape.
func ValidateConfig(kind string, cfg map[string]string) error {
if !ValidKind(kind) {
return errors.New("unknown channel kind")
}
req := func(key string) string { return strings.TrimSpace(cfg[key]) }
absURL := func(key, v string) error {
u, err := url.Parse(v)
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
return fmt.Errorf("%s must be an absolute http(s) URL", key)
}
return nil
}
switch kind {
case "email":
if a := req("address"); a != "" {
if parsed, err := mail.ParseAddress(a); err != nil || parsed.Address != a {
return errors.New("address must be a valid email")
}
}
case "slack":
if err := absURL("webhookUrl", req("webhookUrl")); err != nil {
return err
}
case "matrix":
if err := absURL("homeserver", req("homeserver")); err != nil {
return err
}
if req("roomId") == "" {
return errors.New("roomId is required")
}
if req("accessToken") == "" {
return errors.New("accessToken is required")
}
case "telegram":
if req("botToken") == "" {
return errors.New("botToken is required")
}
if req("chatId") == "" {
return errors.New("chatId is required")
}
}
return nil
}
// EncryptConfig returns the jsonb text to store: plaintext fields as-is,
// secret fields encrypted. Empty secrets stay empty (nothing to protect).
func EncryptConfig(kind string, cfg map[string]string, secret string) (string, error) {
out := map[string]any{}
for k, v := range cfg {
if isSecret(kind, k) && v != "" && v != MaskValue {
enc, err := crypt.Encrypt(v, secret)
if err != nil {
return "", err
}
out[k] = enc
continue
}
out[k] = v
}
raw, err := json.Marshal(out)
return string(raw), err
}
// DecryptConfig reverses EncryptConfig. A secret that fails to decrypt
// (e.g. after key loss) is surfaced as an error — delivery must fail loudly
// rather than send an empty credential.
func DecryptConfig(kind string, stored []byte, secret string) (map[string]string, error) {
var raw map[string]any
if err := json.Unmarshal(stored, &raw); err != nil {
return nil, err
}
out := make(map[string]string, len(raw))
for k, v := range raw {
s, _ := v.(string)
if isSecret(kind, k) && s != "" {
dec, err := crypt.Decrypt(s, secret)
if err != nil {
return nil, fmt.Errorf("channel secret %q cannot be decrypted: %w", k, err)
}
s = dec
}
out[k] = s
}
return out, nil
}
// MaskConfig produces the API-safe projection: secrets replaced by
// MaskValue, everything else as stored (decrypted plaintext for
// non-secret fields).
func MaskConfig(kind string, cfg map[string]string) map[string]string {
out := make(map[string]string, len(cfg))
for k, v := range cfg {
if isSecret(kind, k) && v != "" {
out[k] = MaskValue
continue
}
out[k] = v
}
return out
}
func isSecret(kind, key string) bool {
for _, f := range secretFields[kind] {
if f == key {
return true
}
}
return false
}
// MergeMasked implements the write-only-secret PATCH rule: a submitted
// config whose secret field carries MaskValue keeps the stored value.
func MergeMasked(submitted, stored map[string]string, kind string) map[string]string {
out := make(map[string]string, len(submitted))
for k, v := range submitted {
if isSecret(kind, k) && v == MaskValue {
out[k] = stored[k]
continue
}
out[k] = v
}
return out
}
// notifyClient mirrors the preview client: netguard dial, bounded
// redirects, shared idle-connection pool. One client for all webhook kinds.
var notifyClient = &http.Client{
Timeout: 20 * time.Second,
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
if netguard.AllowPrivate() {
return netguard.DialContext(ctx, network, address)
}
return netguard.DialContextPorts(ctx, network, address, 80, 443)
},
IdleConnTimeout: 30 * time.Second,
MaxIdleConns: 16,
MaxIdleConnsPerHost: 4,
},
CheckRedirect: func(r *http.Request, via []*http.Request) error {
if len(via) > 3 {
return errors.New("too many redirects")
}
return nil
},
}
// Send delivers one notification through the channel. The plaintext title
// and body are identical across kinds; only the payload envelope differs.
// Errors are returned for the engine to record (attempts, backoff) — this
// layer never retries on its own.
func Send(ctx context.Context, d *db.DB, ch Channel, title, body string) error {
text := title
if body != "" {
text += "\n" + body
}
switch ch.Kind {
case "email":
to := strings.TrimSpace(ch.Config["address"])
if to == "" {
// Default to the owner's account email.
var email *string
if err := d.QueryRowContext(ctx, `SELECT email FROM "User" WHERE id=$1`, ch.OwnerID).Scan(&email); err != nil {
return fmt.Errorf("owner email lookup: %w", err)
}
if email == nil || *email == "" {
return errors.New("channel has no address and the owner has no email")
}
to = *email
}
return mailer.Send(ctx, to, title, text)
case "slack":
return postJSON(ctx, ch.Config["webhookUrl"], nil, map[string]any{"text": text}, []int{200})
case "matrix":
base := strings.TrimRight(ch.Config["homeserver"], "/")
room := url.PathEscape(ch.Config["roomId"])
txn := url.PathEscape(fmt.Sprintf("sb%d", time.Now().UnixNano()))
endpoint := fmt.Sprintf("%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s", base, room, txn)
headers := http.Header{"Authorization": []string{"Bearer " + ch.Config["accessToken"]}}
return postJSON(ctx, endpoint, headers, map[string]any{"msgtype": "m.text", "body": text}, []int{200})
case "telegram":
endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", url.PathEscape(ch.Config["botToken"]))
return postJSON(ctx, endpoint, nil, map[string]any{"chat_id": ch.Config["chatId"], "text": text}, []int{200})
}
return fmt.Errorf("unknown channel kind %q", ch.Kind)
}
// postJSON sends one webhook payload. want lists accepted status codes;
// anything else is an error carrying the status (and a bounded body snippet
// for logs — never full bodies, which may echo secrets).
func postJSON(ctx context.Context, endpoint string, headers http.Header, payload any, want []int) error {
raw, err := json.Marshal(payload)
if err != nil {
return err
}
method := http.MethodPost
if headers != nil && headers.Get("Authorization") != "" && strings.Contains(endpoint, "/_matrix/") {
method = http.MethodPut // Matrix's send endpoint is a PUT keyed by txn id
}
req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(raw))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
for k, vs := range headers {
for _, v := range vs {
req.Header.Add(k, v)
}
}
res, err := notifyClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
for _, w := range want {
if res.StatusCode == w {
return nil
}
}
snippet := make([]byte, 200)
n, _ := res.Body.Read(snippet)
return fmt.Errorf("webhook answered %d: %s", res.StatusCode, strings.TrimSpace(string(snippet[:n])))
}
+369
View File
@@ -0,0 +1,369 @@
// 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"
}
}
+11
View File
@@ -73,3 +73,14 @@ func Reserve(key string, limit int, windowDur time.Duration) (release func(), re
shared.mu.Unlock()
}, 0, true
}
// ResetBudget clears all fixed-window counters. Tests only: the budget is
// process-global, and integration harnesses reset it per test server so
// sequential tests do not inherit each other's windows (same contract as
// auth.ResetRateLimits). In-flight accounting is left untouched — callers
// must have released their slots, which tests guarantee by completion.
func ResetBudget() {
shared.mu.Lock()
shared.keys = map[string]*window{}
shared.mu.Unlock()
}