Add notification engine phase 1: channels, rules, plan-gated delivery
release gate / check (push) Failing after 6m54s
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:
@@ -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])))
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user