The module path claimed a nonexistent GitHub repo. Point it (and the agent User-Agent contact URL, README/RUNNING clone URLs) at the real Gitea repository. Pure identifier rename: no runtime behavior change. Verified: build, vet, unit + full DB integration (-race), db-converge, web lint/SSR/build, browser regressions, e2e against rebuilt stack.
489 lines
18 KiB
Go
489 lines
18 KiB
Go
// Package notify is the notification engine (DESIGN_NOTIFICATIONS.md,
|
|
// phase 1): it scans for facts matching enabled rules (new signals, due
|
|
// bookmarks), records deduped Notification rows, and delivers them through
|
|
// the rule's channel.
|
|
//
|
|
// Design invariants:
|
|
// - Scanner, not hooks: producers are never instrumented; re-runs are
|
|
// free because UNIQUE("ruleId","dedupeKey") + ON CONFLICT DO NOTHING is
|
|
// the entire exactly-once story.
|
|
// - Anti-spam: per-rule cooldown, per-owner pending cap, per-row attempt
|
|
// cap with exponential backoff.
|
|
// - Plan gates: channels are validated against the owner's tenant plan at
|
|
// creation AND re-checked at delivery, so a downgraded plan stops
|
|
// sending (rows become 'suppressed', visible in history).
|
|
// - Every send is a server-initiated dial: email via internal/mailer,
|
|
// webhooks via the netguarded client in channels.go, all inside
|
|
// outbound.Reserve budgets.
|
|
package notify
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"math/rand/v2"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
|
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
|
"gitea.federated.computer/Federated_Computer/brain/internal/entitlements"
|
|
"gitea.federated.computer/Federated_Computer/brain/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
|
|
}
|
|
|
|
if r.trigger != "signal_created" && r.trigger != "bookmark_due" && r.trigger != "share_received" {
|
|
log.Printf("notify: rule %s has unknown trigger %q", r.id, r.trigger)
|
|
continue
|
|
}
|
|
// Recipients: the rule owner (empty string) plus any validated
|
|
// targets from the rule config. Targeted rows are delivered through
|
|
// EACH recipient's own channel of the rule's kind at delivery time.
|
|
recipients := append([]string{""}, ruleTargets(ctx, d, r.config, r.tenantID.String)...)
|
|
var inserted int
|
|
for _, recipient := range recipients {
|
|
var n int
|
|
switch r.trigger {
|
|
case "signal_created":
|
|
n, err = scanSignals(ctx, d, r.id, recipient)
|
|
case "bookmark_due":
|
|
n, err = scanDue(ctx, d, r.id, r.config, recipient)
|
|
case "share_received":
|
|
n, err = scanShares(ctx, d, r.id, recipient)
|
|
}
|
|
if err != nil {
|
|
log.Printf("notify: scan rule %s: %v", r.id, err)
|
|
continue
|
|
}
|
|
inserted += n
|
|
}
|
|
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.
|
|
// recipientSuffix namespaces dedupe keys and row ids per targeted
|
|
// recipient so owner and targets each get exactly one row per fact.
|
|
func recipientSuffix(recipient string) string {
|
|
if recipient == "" {
|
|
return ""
|
|
}
|
|
return ":u:" + recipient
|
|
}
|
|
|
|
func scanSignals(ctx context.Context, d *db.DB, ruleID, recipient string) (int, error) {
|
|
sfx := recipientSuffix(recipient)
|
|
res, err := d.ExecContext(ctx, `
|
|
INSERT INTO "Notification"(id,"ruleId","ownerId","recipientId","dedupeKey",title,body)
|
|
SELECT r.id||'-'||s.id||$4, r.id, r."ownerId", NULLIF($3,''), 'signal:'||s.id||$4,
|
|
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, recipient, sfx)
|
|
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, recipient string) (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
|
|
}
|
|
sfx := recipientSuffix(recipient)
|
|
res, err := d.ExecContext(ctx, `
|
|
INSERT INTO "Notification"(id,"ruleId","ownerId","recipientId","dedupeKey",title,body)
|
|
SELECT r.id||'-due-'||b.id||'-'||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD')||$5,
|
|
r.id, r."ownerId", NULLIF($4,''),
|
|
'due:'||b.id||':'||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD')||$5,
|
|
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, recipient, sfx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
n, _ := res.RowsAffected()
|
|
return int(n), nil
|
|
}
|
|
|
|
// scanShares fires when something is shared WITH the rule owner: a
|
|
// bookmark, tag or collection share row created since the rule existed.
|
|
// The share row is unique per (item, user), so the item id alone is a
|
|
// stable dedupe key; the sharer's name rides in the title.
|
|
func scanShares(ctx context.Context, d *db.DB, ruleID, recipient string) (int, error) {
|
|
sfx := recipientSuffix(recipient)
|
|
res, err := d.ExecContext(ctx, `
|
|
INSERT INTO "Notification"(id,"ruleId","ownerId","recipientId","dedupeKey",title,body)
|
|
SELECT r.id||'-share-'||s.type||'-'||s.itemid||$4, r.id, r."ownerId", NULLIF($3,''),
|
|
'share:'||s.type||':'||s.itemid||$4,
|
|
left(COALESCE(NULLIF(s.sharer,''),'Someone')||' shared a '||s.type||' with you: '||COALESCE(NULLIF(s.title,''),'untitled'), 200),
|
|
left(COALESCE(s.url,''), 2000)
|
|
FROM "NotificationRule" r
|
|
JOIN LATERAL (
|
|
SELECT 'bookmark' AS type, bs."bookmarkId" AS itemid, bs."createdAt",
|
|
COALESCE(b.title,'') AS title, b.url AS url, COALESCE(u.name,'') AS sharer
|
|
FROM "BookmarkShare" bs
|
|
JOIN "Bookmark" b ON b.id = bs."bookmarkId"
|
|
JOIN "User" u ON u.id = b."ownerId"
|
|
WHERE bs."userId" = r."ownerId" AND bs."createdAt" >= r."createdAt"
|
|
UNION ALL
|
|
SELECT 'tag', ts."tagId", ts."createdAt", t.name, '', COALESCE(u.name,'')
|
|
FROM "TagShare" ts
|
|
JOIN "Tag" t ON t.id = ts."tagId"
|
|
JOIN "User" u ON u.id = t."ownerId"
|
|
WHERE ts."userId" = r."ownerId" AND ts."createdAt" >= r."createdAt"
|
|
UNION ALL
|
|
SELECT 'collection', cs."collectionId", cs."createdAt", c.name, '', COALESCE(u.name,'')
|
|
FROM "CollectionShare" cs
|
|
JOIN "Collection" c ON c.id = cs."collectionId"
|
|
JOIN "User" u ON u.id = c."ownerId"
|
|
WHERE cs."userId" = r."ownerId" AND cs."createdAt" >= r."createdAt"
|
|
ORDER BY "createdAt" DESC LIMIT $2
|
|
) s ON true
|
|
WHERE r.id = $1
|
|
ON CONFLICT ("ruleId","dedupeKey") DO NOTHING`, ruleID, scanBatchLimit, recipient, sfx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
n, _ := res.RowsAffected()
|
|
return int(n), nil
|
|
}
|
|
|
|
// ruleTargets resolves a rule's configured targetUserIds to users that still
|
|
// exist in the owner's tenant (the write-time validation is authoritative;
|
|
// this re-check keeps deliveries honest across membership changes).
|
|
func ruleTargets(ctx context.Context, d *db.DB, ruleConfig []byte, tenantID string) []string {
|
|
var cfg struct {
|
|
TargetUserIDs []string `json:"targetUserIds"`
|
|
}
|
|
if len(ruleConfig) == 0 || json.Unmarshal(ruleConfig, &cfg) != nil || len(cfg.TargetUserIDs) == 0 {
|
|
return nil
|
|
}
|
|
rows, err := d.QueryContext(ctx,
|
|
`SELECT id FROM "User" WHERE id = ANY($1) AND COALESCE("tenantId",'') = $2`,
|
|
cfg.TargetUserIDs, tenantID)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
defer rows.Close()
|
|
var out []string
|
|
for rows.Next() {
|
|
var id string
|
|
if err := rows.Scan(&id); err == nil {
|
|
out = append(out, id)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// 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, n."recipientId",
|
|
c.id, c."ownerId", c.kind, c.config, c.enabled, u."tenantId", ru."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"
|
|
LEFT JOIN "User" ru ON ru.id = n."recipientId"
|
|
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, recipientID, recipientTenant sql.NullString
|
|
}
|
|
var items []item
|
|
for rows.Next() {
|
|
var it item
|
|
if err := rows.Scan(&it.id, &it.title, &it.body, &it.attempts, &it.recipientID,
|
|
&it.channelID, &it.ownerID, &it.kind, &it.config, &it.channelEnabled, &it.tenantID, &it.recipientTenant); 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", ""
|
|
// Targeted rows are delivered through the RECIPIENT's own
|
|
// enabled channel of the rule's kind (never the owner's), and
|
|
// the recipient's tenant plan gates the send.
|
|
channelID, channelOwner, cfgRaw, enabled := it.channelID, it.ownerID, it.config, it.channelEnabled
|
|
tid := it.tenantID.String
|
|
if it.recipientID.Valid && it.recipientID.String != it.ownerID {
|
|
tid = it.recipientTenant.String
|
|
var rCfg []byte
|
|
err := tx.QueryRowContext(ctx,
|
|
`SELECT id, "ownerId", config, enabled FROM "NotificationChannel"
|
|
WHERE "ownerId"=$1 AND kind=$2 ORDER BY "createdAt" LIMIT 1`,
|
|
it.recipientID.String, it.kind).Scan(&channelID, &channelOwner, &rCfg, &enabled)
|
|
cfgRaw = rCfg
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
status, lastErr = "suppressed", "recipient has no "+it.kind+" channel"
|
|
} else if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
// A disabled channel or a plan that no longer allows it suppresses
|
|
// the row permanently (history shows why nothing was sent).
|
|
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 status == "sent" && (!enabled || !lim.AllowChannel(it.kind)) {
|
|
status = "suppressed"
|
|
}
|
|
if status == "sent" {
|
|
cfg, err := DecryptConfig(it.kind, cfgRaw, 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
|
|
}
|
|
body := it.body
|
|
// Branding footer (Gitea #10): plan data decides, never
|
|
// a code fork — free hosted deliveries carry it.
|
|
if lim.ManagedFooter {
|
|
body += "\n\nManaged by David's Superbrain."
|
|
}
|
|
sendCtx, cancel := context.WithTimeout(ctx, sendTimeout)
|
|
err = Send(sendCtx, d, Channel{
|
|
ID: channelID, OwnerID: channelOwner, Kind: it.kind, Config: cfg, Enabled: true,
|
|
}, it.title, 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"
|
|
}
|
|
}
|