Files
superbrain/main.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

95 lines
2.7 KiB
Go

package main
import (
"context"
"errors"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/http"
"github.com/andrew/superbrain/internal/notify"
"github.com/andrew/superbrain/internal/scripts"
"github.com/andrew/superbrain/internal/signals"
"log"
stdhttp "net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
if len(os.Args) > 1 && os.Args[1] == "--healthcheck" {
client := stdhttp.Client{Timeout: 3 * time.Second}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
res, err := client.Get("http://127.0.0.1:" + port + "/readyz")
if err != nil {
os.Exit(1)
}
res.Body.Close()
if res.StatusCode != 200 {
os.Exit(1)
}
return
}
cfg := config.Load()
if err := cfg.Validate(); err != nil {
log.Fatalf("config: %v", err)
}
d, err := db.New(cfg)
if err != nil {
log.Fatalf("db: %v", err)
}
defer d.Close()
// Tenancy phase 1: make sure the implicit tenant exists with the
// tier-derived plan and adopt any tenantless users (self-heal twin of
// migration 012). Best-effort: user creation re-ensures per transaction,
// so a failure here must not keep the API down.
if err := db.NewTenantRepo(d).Bootstrap(context.Background()); err != nil {
log.Printf("tenancy bootstrap: %v", err)
}
if len(os.Args) > 1 && os.Args[1] == "--seed" {
if err := scripts.Seed(context.Background(), d); err != nil {
log.Fatal(err)
}
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Shutdown order is owned by main (review OPS-01): drain in-flight HTTP
// requests first, then await the background loops, and only afterwards let
// the deferred db close run. Previously Shutdown raced ListenAndServe's
// return and the process exited mid-drain.
workersDone := make(chan struct{})
go func() {
defer close(workersDone)
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); signals.RunLoop(ctx, d) }()
// Notification engine (DESIGN_NOTIFICATIONS.md): scans rules and
// delivers through channels; shares the shutdown contract with
// signals — drain HTTP first, then both loops, then close the db.
go func() { defer wg.Done(); notify.RunLoop(ctx, d) }()
wg.Wait()
}()
srv := http.NewServer(cfg, d)
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, stdhttp.ErrServerClosed) {
log.Fatalf("server failed: %v", err)
}
}()
log.Printf("superbrain API listening on %s", srv.Addr)
<-ctx.Done()
stop()
shutdown, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(shutdown); err != nil {
log.Printf("shutdown: %v", err)
}
<-workersDone
}