Files
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

87 lines
2.4 KiB
Go

// Package outbound bounds server-initiated network work — URL previews,
// CardDAV syncs, IMAP test/check passes and manual signal checks — so an
// authenticated user cannot open unbounded outbound connections, exhaust
// file descriptors or saturate egress (review M-2).
//
// Two layers are shared by every caller:
// - a global in-flight cap (defaultConcurrent), and
// - a per-identity fixed-window rate (the caller supplies the limit/window,
// since a preview is cheaper than an IMAP search).
//
// Exhaustion is immediate: previews degrade to no metadata and interactive
// endpoints answer 429 with Retry-After. Nothing queues behind the budget.
package outbound
import (
"sync"
"time"
)
const defaultConcurrent = 8
type window struct {
count int
reset time.Time
}
type budget struct {
mu sync.Mutex
inFlight int
max int
keys map[string]*window
}
var shared = &budget{max: defaultConcurrent, keys: map[string]*window{}}
// Reserve claims one outbound slot for key. The returned release MUST be
// called when the work finishes. When ok is false, retry is a conservative
// Retry-After duration.
func Reserve(key string, limit int, windowDur time.Duration) (release func(), retry time.Duration, ok bool) {
if key == "" {
key = "anonymous"
}
shared.mu.Lock()
defer shared.mu.Unlock()
if shared.inFlight >= shared.max {
return nil, time.Second, false
}
now := time.Now()
if len(shared.keys) > 4096 {
for k, w := range shared.keys {
if now.After(w.reset) {
delete(shared.keys, k)
}
}
}
w := shared.keys[key]
if w == nil || now.After(w.reset) {
w = &window{reset: now.Add(windowDur)}
shared.keys[key] = w
}
if limit > 0 && w.count >= limit {
left := w.reset.Sub(now)
if left < 0 {
left = 0
}
return nil, left.Truncate(time.Second) + time.Second, false
}
w.count++
shared.inFlight++
return func() {
shared.mu.Lock()
shared.inFlight--
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()
}