Repository navigation
feat: Alert Policies for Quiet Hours and Rate Limits - #80
Conversation
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…afety Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds per-destination Quiet Hours (drop or defer+digest) and Rate Limiting (hour/day sliding windows): DB models and migration, admin API validation/persistence, dispatcher decisioning and logging, background digest flusher, sender note plumbing, frontend types/UI/validation, tests, and documentation. ChangesNotification Quiet Hours and Rate Limiting
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 9
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@server/internal/handlers/admin_notifications_test.go`:
- Around line 259-343: Add a new test TestUpdateNotificationDest_WithPolicy that
seeds a notification via newNotificationTestDB, then issues a PUT to
UpdateNotificationDest using adminNotificationRequest with a JSON body
containing the full quiet_hours_* and rate_limit_* fields (e.g.
quiet_hours_enabled/start/end/mode and rate_limit_enabled/count/unit) to
exercise the Updates map path, then fetch/decode the updated
models.NotificationDest and assert that QuietHoursEnabled, QuietHoursStart,
QuietHoursEnd, QuietHoursMode, RateLimitEnabled, RateLimitCount and
RateLimitUnit match the sent values; use the same helpers as other tests
(newNotificationTestDB, adminNotificationRequest) and mirror the pattern from
TestCreateNotificationDest_WithPolicy for status code and field assertions.
In `@server/internal/models/notification_log.go`:
- Around line 5-20: NotificationLog grows without retention; implement a sweeper
similar to StartOIDCStateSweeper that periodically deletes old NotificationLog
rows beyond the retention horizon (e.g. >24h) while preserving pending held
entries (NotificationLog where Decision == "held" and FlushedAt == nil); add a
StartNotificationLogSweeper function in db.go that runs on a ticker, executes a
single DELETE query filtering by CreatedAt < now - retention AND NOT
(Decision="held" AND FlushedAt IS NULL), logs errors, and hook it into startup
alongside StartOIDCStateSweeper.
In `@server/internal/notify/digest_test.go`:
- Around line 32-33: The two test calls to d.logDecision currently ignore the
returned error; capture the error from each call (e.g., err :=
d.logDecision(...)) and handle it—in tests this should be a fatal assertion like
if err != nil { t.Fatalf("logDecision failed: %v", err) } (or use
require.NoError(t, err) if testify is already used). Update both d.logDecision
invocations (the ones with ids "i1" and "i2") to check the error and fail the
test on non-nil error.
- Line 60: The call to d.logDecision in the test is ignoring its error return;
update the invocation of d.logDecision (the helper under test) to capture and
assert the error (e.g., err := d.logDecision(...); fail the test if err != nil)
so the test consistently checks and fails on unexpected errors; apply the same
pattern used elsewhere in the test suite for error assertions to keep CI linters
happy.
In `@server/internal/notify/digest.go`:
- Around line 78-85: The digest currently computes ids from held and builds a
note using len(held) but then lists the fetched incidents (variable incidents)
which can be fewer if some Incident rows were deleted; update the note to use
len(incidents) (the actual fetched slice) instead of len(held) so the count
matches the listed items, or explicitly handle missing incidents by filtering
held and adjusting the message to reflect "X of Y held" using both
len(incidents) and len(held) in the digest generation (refer to variables held,
ids, incidents and the DB lookup via f.db and models.Incident).
In `@server/internal/notify/discord_test.go`:
- Line 118: The test currently calls ExportedSendDiscord with empty note strings
so the new Suppressed branch in sendDiscord is never exercised; add a targeted
test that passes a non-empty note string and asserts the produced Discord embed
contains a "Suppressed" field and the note text. Update or add a test (e.g.,
TestSendDiscord_AppendsSuppressedNote) that starts an httptest.Server capturing
request body, calls ExportedSendDiscord with a models.Incident and the note "(+2
suppressed in the last hour)", checks no error, and asserts the captured body
contains both "Suppressed" and the note text to cover the Suppressed branch in
sendDiscord.
In `@server/internal/notify/notify.go`:
- Around line 86-90: When d.decide(d.db, dest) returns an error, don’t return
early; instead log the error, set the decision to a persistent failure marker
(e.g., DecisionFailed or a new constant) and append the error text to note, then
continue the normal send/audit path so a NotificationLog row is always written;
update the code around d.decide to use the DecisionFailed symbol (or create it)
and ensure the existing NotificationLog writer (e.g., writeNotificationLog /
whatever function writes NotificationLog rows) is invoked with the decision and
note even on decide errors, and if desired still attempt sending for critical
alerts based on dest/priority.
In `@server/internal/notify/policy.go`:
- Around line 70-88: The current rate check in decide (which calls
sentCountSince and droppedRateSinceLastSent and returns decisionSent) is racy
under concurrent Send/evaluateAndSend calls; to enforce a hard cap either
serialize per-destination decisions or push the check+write into the DB:
implement a per-destination keyed mutex (map[id]mutex or sync.Map of mutexes)
and acquire that lock at the start of decide and hold it until after the code
that logs the decisionSent row in evaluateAndSend, or refactor so the
rateWindow/count check and insertion of the decisionSent row occur inside a
single DB transaction/atomic conditional insert (e.g., SELECT COUNT... FOR
UPDATE then INSERT if count < limit). Ensure the lock or transaction surrounds
the sentCountSince check and the eventual write of decisionSent to prevent
in-flight overshoot.
In `@web/src/api/client.ts`:
- Line 746: The normalization sets const rateCount = typeof
data.rate_limit_count === 'number' ? data.rate_limit_count : 0 which can produce
0 while notificationPolicy.ts requires count >= 1 when rate_limit_enabled is
true; change the fallback to 1 (or otherwise coerce to Math.max(1,
providedValue)) so that rateCount aligns with the validation, and ensure any
usages that rely on rate_limit_enabled and rateCount (look for references to
rate_limit_enabled and rateCount in this module) will receive a valid minimum
value.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 94ba39c5-84b8-49ab-bea0-4a93cb5619fb
📒 Files selected for processing (29)
docs/site/docs/integrations/notifications.mdserver/internal/db/db.goserver/internal/handlers/admin_notifications.goserver/internal/handlers/admin_notifications_test.goserver/internal/models/notification_dest.goserver/internal/models/notification_dest_test.goserver/internal/models/notification_log.goserver/internal/models/notification_log_test.goserver/internal/notify/digest.goserver/internal/notify/digest_test.goserver/internal/notify/discord.goserver/internal/notify/discord_test.goserver/internal/notify/notify.goserver/internal/notify/notify_clock_test.goserver/internal/notify/notify_test.goserver/internal/notify/ntfy.goserver/internal/notify/ntfy_test.goserver/internal/notify/policy.goserver/internal/notify/policy_test.goserver/internal/notify/send_test.goserver/internal/notify/slack.goserver/internal/notify/slack_test.goserver/internal/notify/window.goserver/internal/notify/window_test.goserver/main.goweb/src/api/client.tsweb/src/pages/AdminPage.tsxweb/src/pages/notificationPolicy.tsweb/tests/admin-notifications-policy.test.ts
| // NotificationLog records every per-destination send decision made by the | ||
| // dispatcher. It powers sliding-window rate counting, the suppressed-count | ||
| // note, the deferred-digest hold queue, and "why was/wasn't I paged?" | ||
| // observability. | ||
| type NotificationLog struct { | ||
| ID string `gorm:"primaryKey" json:"id"` | ||
| DestID string `gorm:"index:idx_notiflog_dest_created;index:idx_notiflog_dest_decision" json:"dest_id"` | ||
| IncidentID string `json:"incident_id"` | ||
| Event string `json:"event"` | ||
| // Decision is one of: sent, held, dropped_rate, dropped_quiet, failed, digest. | ||
| Decision string `gorm:"index:idx_notiflog_dest_decision" json:"decision"` | ||
| Note string `json:"note"` | ||
| CreatedAt time.Time `gorm:"index:idx_notiflog_dest_created" json:"created_at"` | ||
| // FlushedAt is set on held rows when they are rolled into a digest. | ||
| FlushedAt *time.Time `gorm:"index:idx_notiflog_dest_decision" json:"flushed_at,omitempty"` | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Heads up: this log table has no purge protocol.
NotificationLog records every dispatch decision (sent/held/dropped/digest) with no retention or pruning. On a busy deployment this grows without bound — and unlike OIDCState, there's no sweeper to keep it trimmed. I'd recommend a periodic cleanup goroutine that deletes rows older than your rate-limit/digest horizon (e.g. anything older than a day that isn't a pending held row), mirroring the existing StartOIDCStateSweeper pattern in db.go.
Want me to draft a StartNotificationLogSweeper modeled on the OIDC sweeper?
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@server/internal/models/notification_log.go` around lines 5 - 20,
NotificationLog grows without retention; implement a sweeper similar to
StartOIDCStateSweeper that periodically deletes old NotificationLog rows beyond
the retention horizon (e.g. >24h) while preserving pending held entries
(NotificationLog where Decision == "held" and FlushedAt == nil); add a
StartNotificationLogSweeper function in db.go that runs on a ticker, executes a
single DELETE query filtering by CreatedAt < now - retention AND NOT
(Decision="held" AND FlushedAt IS NULL), logs errors, and hook it into startup
alongside StartOIDCStateSweeper.
| ids := make([]string, 0, len(held)) | ||
| for _, h := range held { | ||
| ids = append(ids, h.IncidentID) | ||
| } | ||
| var incidents []models.Incident | ||
| if err := f.db.Where("id IN ?", ids).Find(&incidents).Error; err != nil { | ||
| return err | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | 💤 Low value
Incident-to-held-log count mismatch possible if incidents are deleted.
Chief, if an Incident row is deleted after its notification was held but before this digest runs, incidents will have fewer entries than held. The digest note (line 98) will say "digest of N held" but the message body will list fewer incidents. This is a minor inconsistency but won't cause failures.
Consider using len(incidents) in the note for accuracy, or documenting this edge case as acceptable behavior.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@server/internal/notify/digest.go` around lines 78 - 85, The digest currently
computes ids from held and builds a note using len(held) but then lists the
fetched incidents (variable incidents) which can be fewer if some Incident rows
were deleted; update the note to use len(incidents) (the actual fetched slice)
instead of len(held) so the count matches the listed items, or explicitly handle
missing incidents by filtering held and adjusting the message to reflect "X of Y
held" using both len(incidents) and len(held) in the digest generation (refer to
variables held, ids, incidents and the DB lookup via f.db and models.Incident).
| if dest.RateLimitEnabled && dest.RateLimitCount > 0 { | ||
| window := rateWindow(dest.RateLimitUnit) | ||
| count, err := d.sentCountSince(db, dest.ID, now.Add(-window)) | ||
| if err != nil { | ||
| return "", "", err | ||
| } | ||
| if count >= int64(dest.RateLimitCount) { | ||
| return decisionDroppedRate, "", nil | ||
| } | ||
| suppressed, err := d.droppedRateSinceLastSent(db, dest.ID) | ||
| if err != nil { | ||
| return "", "", err | ||
| } | ||
| if suppressed > 0 { | ||
| note = fmt.Sprintf("(+%d suppressed in the last %s)", suppressed, dest.RateLimitUnit) | ||
| } | ||
| } | ||
|
|
||
| return decisionSent, note, nil |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Heads up, Chief — the rate limiter is a soft limit under concurrent bursts.
decide reads sentCountSince here, but the corresponding decisionSent row isn't written until evaluateAndSend finishes the outbound send. Since Send fans out per destination across goroutines (and multiple incidents can fire near-simultaneously), several dispatches for the same destination can each observe count < RateLimitCount and all proceed before any of them logs a sent row. Net effect: the cap can be exceeded by roughly the number of in-flight sends.
For an alerting system a small overshoot is usually tolerable, so this isn't a blocker — but if you need a hard cap, serialize per-destination decisions (e.g., a per-dest mutex/keyed lock around decide→log) or enforce it at the DB layer within a transaction.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@server/internal/notify/policy.go` around lines 70 - 88, The current rate
check in decide (which calls sentCountSince and droppedRateSinceLastSent and
returns decisionSent) is racy under concurrent Send/evaluateAndSend calls; to
enforce a hard cap either serialize per-destination decisions or push the
check+write into the DB: implement a per-destination keyed mutex (map[id]mutex
or sync.Map of mutexes) and acquire that lock at the start of decide and hold it
until after the code that logs the decisionSent row in evaluateAndSend, or
refactor so the rateWindow/count check and insertion of the decisionSent row
occur inside a single DB transaction/atomic conditional insert (e.g., SELECT
COUNT... FOR UPDATE then INSERT if count < limit). Ensure the lock or
transaction surrounds the sentCountSince check and the eventual write of
decisionSent to prevent in-flight overshoot.
Reserve the rate slot under a per-destination lock (decide + sent-row insert held together) so concurrent sends cannot both pass the cap; HTTP delivery stays outside the lock. On a decide() error, deliver best-effort instead of silently dropping the notification. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds StartNotificationLogSweeper (mirrors StartOIDCStateSweeper): hourly DELETE of rows older than 48h, preserving pending held rows awaiting a deferred digest. Wired into startup alongside the OIDC sweeper. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
… fixes - TestUpdateNotificationDest_WithPolicy exercises the Updates-map path - TestSendDiscord_AppendsSuppressedNote covers the Suppressed embed field - digest_test now asserts logDecision errors - normalizeNotificationDest rate count fallback aligns with the >=1 minimum Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
♻️ Duplicate comments (1)
server/internal/notify/notify.go (1)
135-138:⚠️ Potential issue | 🟠 Major | ⚡ Quick winKeep the alert path fail-open when the reservation write breaks.
Line 135 still turns a transient
notification_logsinsert failure into a dropped notification. The send never happens, and there’s no fallback audit row. After unlocking, fall back tod.deliver(dest, inc, event, incURL, note)so a DB hiccup degrades rate enforcement instead of swallowing the alert.Proposed fix
if err := d.db.Create(row).Error; err != nil { mu.Unlock() - log.Printf("notify: reserve sent for %q: %v", dest.Name, err) + log.Printf("notify: reserve sent for %q: %v (sending anyway)", dest.Name, err) + d.deliver(dest, inc, event, incURL, note) return }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@server/internal/notify/notify.go` around lines 135 - 138, The reservation insert failure currently unlocks the mutex and returns early, dropping the notification; instead, after mu.Unlock() call d.deliver(dest, inc, event, incURL, note) so the alert still sends when the DB write fails (failing open). Locate the block where d.db.Create(row).Error is checked in notify.go, keep the mu.Unlock(), then invoke d.deliver(dest, inc, event, incURL, note) and return its result (or ignore its error if the surrounding function expects no error) so rate enforcement degrades but the notification is still delivered.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@server/internal/notify/notify.go`:
- Around line 135-138: The reservation insert failure currently unlocks the
mutex and returns early, dropping the notification; instead, after mu.Unlock()
call d.deliver(dest, inc, event, incURL, note) so the alert still sends when the
DB write fails (failing open). Locate the block where d.db.Create(row).Error is
checked in notify.go, keep the mu.Unlock(), then invoke d.deliver(dest, inc,
event, incURL, note) and return its result (or ignore its error if the
surrounding function expects no error) so rate enforcement degrades but the
notification is still delivered.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 76169cbb-e2fd-4206-8b03-5d3002385929
📒 Files selected for processing (9)
server/internal/db/db.goserver/internal/db/db_test.goserver/internal/handlers/admin_notifications_test.goserver/internal/notify/digest_test.goserver/internal/notify/discord_test.goserver/internal/notify/notify.goserver/internal/notify/send_test.goserver/main.goweb/src/api/client.ts
A failed reservation insert previously dropped the notification; now it falls through to deliver() so the alert still sends (rate enforcement degrades), matching the decide()-error fail-open path. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
What it does: Every notification destination (ntfy/Discord/Slack) now has two independent, opt-in controls:
Quiet hours — a daily window (server timezone, wraps midnight). Per-destination mode: Drop (silently skip) or Defer & digest (hold overnight, send one rollup when the window ends; survives restarts via a startup flush).
Rate limit — max N per hour or day (sliding window). Overflow is dropped, and the next allowed notification carries a (+N suppressed) note.
Summary by CodeRabbit
New Features
Documentation
UI