diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md index f9f94bfab1..7cfbe3dd19 100644 --- a/docs/release-control/v6/internal/subsystems/notifications.md +++ b/docs/release-control/v6/internal/subsystems/notifications.md @@ -62,8 +62,34 @@ settlement/reopen and checks one attempt and one audit. An independent HTML-subs parser verifies literal content and link decoding; it is not the Telegram service. A real HTTP 400 control still dead-letters once, without splitting, replaying or fabricating acceptance. User-owned templates retain their own parse mode and text. -This repairs built-in formatting, not arbitrary provider failures or Telegram's -message-length limit, installed-provider acceptance or reporter recovery. +This formatting repair did not establish installed-provider acceptance or +reporter recovery. + +### Bound built-in Telegram messages before sending + +The built-in Telegram destination plans firing and recovery group sizes against +the provider's 4,096-character post-entity-parsing limit, conservatively +counting UTF-16 units and reserving space for the built-in heading and details. +Small groups keep their existing formatting. Each occurrence stays in exactly +one part, with the original destination, firing/recovery identity, retry budget +and operational links. A singleton that cannot fit abbreviates its presentation +before HTML/JSON escaping; its stored fields and dashboard pointer are not cut. + +The active queue partitions only unattempted pending rows, after quiet-hours +and cancellation checks and before claim. It atomically retains all parts, with +no audit, acceptance or spent attempt for partitioning. Each part settles only +its own provider outcome. Attempted rows and existing dead letters are not +automatically retried or repartitioned. Body overrides and destinations which +derive their URL from the full group keep their existing routing and grouping; +the transport does not reinterpret an arbitrary provider rejection as a size +error. Local rate-slot exhaustion leaves normal built-in Telegram rows due +after the current rate window, without spending an attempt; provider replies +retain their existing classification, retry and settlement rules. + +`telegram_text_budget_test.go` exercises an independent receiver's parsed-text +budget, occurrence links and attempts, oversize singleton abbreviation, +recovery grouping, persistent reopening and the local-rate boundary. This is +source validation, not a Telegram-server or reporter-host acceptance result. ### Request-owned HTTP transports release completed connections diff --git a/internal/notifications/delivery_settlement.go b/internal/notifications/delivery_settlement.go index 9cf4c6b29f..027bb4da4e 100644 --- a/internal/notifications/delivery_settlement.go +++ b/internal/notifications/delivery_settlement.go @@ -539,6 +539,15 @@ func (q *NotificationQueue) deferSettlement(row *QueuedNotification, claimed boo } func (q *NotificationQueue) deferWithReason(row *QueuedNotification, claimed bool, message string, previousAttempt ...*time.Time) error { + return q.deferWithReasonUntil(row, claimed, message, time.Now().Add(30*time.Second), previousAttempt...) +} + +func (q *NotificationQueue) deferTelegramRateHold(row *QueuedNotification, reset time.Time, previousAttempt *time.Time) error { + // SQLite timestamps use seconds; the limiter does not reset at equality. + return q.deferWithReasonUntil(row, true, telegramRateHoldMessage, reset.Truncate(time.Second).Add(time.Second), previousAttempt) +} + +func (q *NotificationQueue) deferWithReasonUntil(row *QueuedNotification, claimed bool, message string, retryAt time.Time, previousAttempt ...*time.Time) error { q.mu.Lock() defer q.mu.Unlock() state := operationaltrust.NotificationQueued @@ -572,7 +581,7 @@ func (q *NotificationQueue) deferWithReason(row *QueuedNotification, claimed boo if err != nil { return err } - _, err = q.db.Exec(`UPDATE notification_queue SET status='pending',attempts=MAX(0,attempts-?),last_attempt=CASE WHEN ? THEN ? ELSE last_attempt END,last_error=?,next_retry_at=?,completed_at=NULL,operational_links=? WHERE id=? AND (status IN ('pending','sending') OR (? AND status IN ('cancelled','failed','dlq')))`, decrement, decrement, previousSeconds, message, time.Now().Add(30*time.Second).Unix(), string(encoded), row.ID, row.ProviderAcceptedAt != nil) + _, err = q.db.Exec(`UPDATE notification_queue SET status='pending',attempts=MAX(0,attempts-?),last_attempt=CASE WHEN ? THEN ? ELSE last_attempt END,last_error=?,next_retry_at=?,completed_at=NULL,operational_links=?,method=CASE WHEN ? AND method LIKE 'resolved-group%' THEN 'telegram-sized' ELSE method END WHERE id=? AND (status IN ('pending','sending') OR (? AND status IN ('cancelled','failed','dlq')))`, decrement, decrement, previousSeconds, message, retryAt.Unix(), string(encoded), message == telegramRateHoldMessage, row.ID, row.ProviderAcceptedAt != nil) if err != nil { return fmt.Errorf("defer notification settlement: %w", err) } diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go index f46c3cf11d..a1cd3727f5 100644 --- a/internal/notifications/notifications.go +++ b/internal/notifications/notifications.go @@ -2592,12 +2592,19 @@ func (n *NotificationManager) dispatchNotificationJobAsync(job notificationDeliv if !n.IsEnabled() { return } - if err := n.deliverNotificationJob(job); err != nil { - n.logNotificationJobError(job, err, failureMessage) - return + batches := [][]*alerts.Alert{job.Alerts} + if job.WebhookConfig != nil && sizesTelegramDeliveries(*job.WebhookConfig) && len(job.Alerts) > 1 { + batches = telegramAlertBatches(job.Alerts, job.Event) } - if err := n.recordSuccessfulDelivery(job, time.Now()); err != nil { - n.logNotificationJobError(job, err, "failed to retain successful notification delivery") + for _, batch := range batches { + job.Alerts = batch + if err := n.deliverNotificationJob(job); err != nil { + n.logNotificationJobError(job, err, failureMessage) + continue + } + if err := n.recordSuccessfulDelivery(job, time.Now()); err != nil { + n.logNotificationJobError(job, err, "failed to retain successful notification delivery") + } } }) } @@ -3384,7 +3391,13 @@ func (n *NotificationManager) renderWebhookPayloadJSON(webhook WebhookConfig, da } if templateStr, ok := webhookServiceTemplate(webhook, mode); ok { - jsonData, err := n.generatePayloadFromTemplateWithService(templateStr, data, webhook.Service) + var jsonData []byte + var err error + if webhook.Service == "telegram" { + jsonData, err = n.renderBuiltInTelegram(templateStr, data, mode) + } else { + jsonData, err = n.generatePayloadFromTemplateWithService(templateStr, data, webhook.Service) + } if err != nil { return nil, fmt.Errorf("generate webhook payload for service %s: %w", webhook.Service, err) } @@ -3452,6 +3465,17 @@ func withNtfyAlertHeaders(webhook WebhookConfig, alertList []*alerts.Alert) Webh } // sendGroupedWebhook sends a grouped webhook notification +func groupedWebhookAlertLine(alert *alerts.Alert) string { + label := alert.ResourceName + if alert.Node != "" { + label += " on " + alert.Node + } + if alert.Message != "" { + return fmt.Sprintf("• %s: %s", label, alert.Message) + } + return fmt.Sprintf("• %s: %.1f%%", label, alert.Value) +} + func (n *NotificationManager) sendGroupedWebhook(webhook WebhookConfig, alertList []*alerts.Alert) error { if len(alertList) == 0 { return fmt.Errorf("no alerts to send") @@ -3469,15 +3493,7 @@ func (n *NotificationManager) sendGroupedWebhook(webhook WebhookConfig, alertLis if alertList[i] == nil { continue } - alertLabel := alertList[i].ResourceName - if alertList[i].Node != "" { - alertLabel += " on " + alertList[i].Node - } - if alertList[i].Message != "" { - otherAlerts = append(otherAlerts, fmt.Sprintf("• %s: %s", alertLabel, alertList[i].Message)) - } else { - otherAlerts = append(otherAlerts, fmt.Sprintf("• %s: %.1f%%", alertLabel, alertList[i].Value)) - } + otherAlerts = append(otherAlerts, groupedWebhookAlertLine(alertList[i])) } if len(otherAlerts) > 0 { if webhook.Service == "discord" { @@ -3735,6 +3751,12 @@ func (n *NotificationManager) sendResolvedWebhookNtfy(webhook WebhookConfig, ale // checkWebhookRateLimit checks if a webhook can be sent based on rate limits func (n *NotificationManager) checkWebhookRateLimit(webhookURL string) bool { + return n.takeWebhookRateSlot(webhookURL).IsZero() +} + +// takeWebhookRateSlot reports the reset time when no slot was available. +// A zero time means one slot was consumed. +func (n *NotificationManager) takeWebhookRateSlot(webhookURL string) time.Time { n.webhookRateMu.Lock() defer n.webhookRateMu.Unlock() @@ -3748,7 +3770,7 @@ func (n *NotificationManager) checkWebhookRateLimit(webhookURL string) bool { lastSent: now, sentCount: 1, } - return true + return time.Time{} } // Check if we're still in the rate limit window @@ -3756,7 +3778,7 @@ func (n *NotificationManager) checkWebhookRateLimit(webhookURL string) bool { // Window expired, reset counter limit.lastSent = now limit.sentCount = 1 - return true + return time.Time{} } // Still in window, check if we've exceeded the limit @@ -3765,13 +3787,13 @@ func (n *NotificationManager) checkWebhookRateLimit(webhookURL string) bool { Str("webhookURL", RedactWebhookURLSecrets(webhookURL)). Int("sentCount", limit.sentCount). Dur("window", WebhookRateLimitWindow). - Msg("webhook rate limit exceeded, dropping request") - return false + Msg("webhook rate limit exceeded") + return limit.lastSent.Add(WebhookRateLimitWindow) } // Increment counter and allow limit.sentCount++ - return true + return time.Time{} } func (n *NotificationManager) cleanupWebhookRateLimitsLocked(now time.Time) { @@ -3895,7 +3917,10 @@ func (n *NotificationManager) sendWebhookRequest(webhook WebhookConfig, jsonData } // Check rate limit before sending - if !n.checkWebhookRateLimit(webhook.URL) { + if retryAt := n.takeWebhookRateSlot(webhook.URL); !retryAt.IsZero() { + if usesBuiltInTelegramBody(webhook) { + return &telegramRateHold{retryAt: retryAt} + } log.Warn(). Str("webhook", webhook.Name). Str("url", RedactWebhookURLSecrets(webhook.URL)). diff --git a/internal/notifications/queue.go b/internal/notifications/queue.go index 5505b58537..396dd10ae0 100644 --- a/internal/notifications/queue.go +++ b/internal/notifications/queue.go @@ -1129,6 +1129,12 @@ func (nq *NotificationQueue) claimPendingForDelivery(notif *QueuedNotification) return false, err } notif.ProviderAcceptedAt = ack + if ack == nil { + ready, err := nq.prepareTelegramBatchLocked(notif, now) + if err != nil || !ready { + return false, err + } + } var links []operationaltrust.NotificationLink if ack != nil { links, _, err = nq.acceptedLinksLocked(notif.ID) @@ -2067,6 +2073,16 @@ func (nq *NotificationQueue) processNotification(notif *QueuedNotification) { } err = processor(notif) + var telegramWait *telegramRateHold + if errors.As(err, &telegramWait) { + // No HTTP attempt was made. Keep the row and its remaining attempt + // budget until the local sender can admit another request. + if deferErr := nq.deferTelegramRateHold(notif, telegramWait.retryAt, previousAttempt); deferErr != nil { + log.Error().Err(deferErr).Str("id", notif.ID).Msg("Failed to retain Telegram rate hold") + } + healthChanged = true + return + } if errors.Is(err, errNotificationSettlementPending) { if settleErr := nq.deferSettlement(notif, true, previousAttempt); settleErr != nil { log.Error().Err(settleErr).Str("id", notif.ID).Msg("Failed to retain pending notification settlement") diff --git a/internal/notifications/telegram_queue.go b/internal/notifications/telegram_queue.go new file mode 100644 index 0000000000..8cbf070790 --- /dev/null +++ b/internal/notifications/telegram_queue.go @@ -0,0 +1,154 @@ +package notifications + +import ( + "bytes" + "database/sql" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "github.com/rcourtman/pulse-go-rewrite/internal/alerts" + "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust" +) + +const telegramRateHoldMessage = "Waiting for the local Telegram webhook send limit" + +type telegramRateHold struct{ retryAt time.Time } + +func (*telegramRateHold) Error() string { return telegramRateHoldMessage } + +// prepareTelegramBatchLocked runs before the first attempt, under the same +// queue lock and delivery gates as claim. Do not partition sent, attempted, or +// operator-retried work: their retained attempts belong to the original batch. +func (q *NotificationQueue) prepareTelegramBatchLocked(row *QueuedNotification, now time.Time) (bool, error) { + kind, event := normalizeQueueType(row.Type) + if kind != "webhook" || len(row.Alerts) < 2 || row.Attempts != 0 || row.LastAttempt != nil { + return true, nil + } + var hook WebhookConfig + if err := json.Unmarshal(row.Config, &hook); err != nil || !hook.Enabled || !sizesTelegramDeliveries(hook) { + return true, nil // retain existing validation and failure behaviour + } + + // The pending snapshot can predate a concurrent cancellation or hold. + current, err := q.scanNotification(q.db.QueryRow(` + SELECT id, type, method, status, alerts, config, attempts, max_attempts, + last_attempt, last_error, created_at, next_retry_at, completed_at, + payload_bytes, operational_links, receipt_epoch + FROM notification_queue WHERE id = ? AND status = 'pending'`, row.ID)) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("reload Telegram batch: %w", err) + } + if (current.NextRetryAt != nil && current.NextRetryAt.After(now)) || + current.Attempts != 0 || current.LastAttempt != nil || + current.Type != row.Type || !bytes.Equal(current.Config, row.Config) { + return false, nil + } + *row = *current + batches := telegramAlertBatches(current.Alerts, event) + if len(batches) <= 1 { + return true, nil + } + if err := q.persistTelegramBatchesLocked(current, batches); err != nil { + return false, err + } + *row = *current + select { + case q.notifyChan <- struct{}{}: // children are independently due + default: + } + return true, nil +} + +// Retain the original ID for the first batch and preserve config and attempt +// budget for each child. No provider call occurs unless the entire partition +// is durable. Each successful response can settle only its own membership. +func (q *NotificationQueue) persistTelegramBatchesLocked(row *QueuedNotification, batches [][]*alerts.Alert) error { + tx, err := q.db.Begin() + if err != nil { + return fmt.Errorf("begin Telegram batch partition: %w", err) + } + defer tx.Rollback() + ids := make([]string, len(batches)) + ids[0] = row.ID + for i := 1; i < len(ids); i++ { + ids[i] = fmt.Sprintf("%s:telegram:%d", row.ID, i) + } + links, err := telegramBatchLinks(row.Links, batches, ids) + if err != nil { + return err + } + method := row.Method + if strings.HasPrefix(method, "resolved-group") { + method = "telegram-sized" // this recovery group has reached its deadline + } + for i, batch := range batches { + body, err := json.Marshal(batch) + if err != nil { + return fmt.Errorf("encode Telegram batch: %w", err) + } + linkBody, err := json.Marshal(links[i]) + if err != nil { + return fmt.Errorf("encode Telegram batch links: %w", err) + } + if i == 0 { + _, err = tx.Exec(`UPDATE notification_queue SET alerts = ?, operational_links = ?, method = ? WHERE id = ?`, string(body), string(linkBody), method, row.ID) + } else { + _, err = tx.Exec(`INSERT INTO notification_queue + (id, type, method, status, alerts, operational_links, config, attempts, + max_attempts, last_attempt, last_error, created_at, next_retry_at, + completed_at, payload_bytes, receipt_epoch) + SELECT ?, type, method, status, ?, ?, config, attempts, + max_attempts, last_attempt, last_error, created_at, next_retry_at, + completed_at, payload_bytes, receipt_epoch + FROM notification_queue WHERE id = ?`, ids[i], string(body), string(linkBody), row.ID) + } + if err != nil { + return fmt.Errorf("persist Telegram batch partition: %w", err) + } + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit Telegram batch partition: %w", err) + } + row.Alerts = batches[0] + row.Links = links[0] + row.Method = method + return nil +} + +func telegramBatchLinks(links []operationaltrust.NotificationLink, batches [][]*alerts.Alert, ids []string) ([][]operationaltrust.NotificationLink, error) { + result := make([][]operationaltrust.NotificationLink, len(batches)) + if len(links) == 0 { + return result, nil + } + type key struct{ record, transition string } + owners := make(map[key]int, len(links)) + for i, batch := range batches { + for _, alert := range batch { + if alert.OperationalRecord == nil || alert.LatestTransition == nil { + continue + } + k := key{alert.OperationalRecord.ID, alert.LatestTransition.ID} + if prior, ok := owners[k]; ok && prior != i { + owners[k] = -1 + } else { + owners[k] = i + } + } + } + for _, link := range links { + i, ok := owners[key{link.OperationalRecordID, link.TransitionID}] + if !ok || i < 0 { + return nil, fmt.Errorf("Telegram batch partition has an ambiguous operational link") + } + link = link.Clone() + link.NotificationID = ids[i] + result[i] = append(result[i], link) + } + return result, nil +} diff --git a/internal/notifications/telegram_text_budget.go b/internal/notifications/telegram_text_budget.go new file mode 100644 index 0000000000..65f7b37095 --- /dev/null +++ b/internal/notifications/telegram_text_budget.go @@ -0,0 +1,176 @@ +package notifications + +import ( + "encoding/json" + "fmt" + "html" + "strings" + "unicode/utf16" + + "github.com/rcourtman/pulse-go-rewrite/internal/alerts" +) + +// Telegram's sendMessage budget is after HTML entity parsing. Count in UTF-16 +// units so supplementary characters cannot make an ostensibly short batch too big. +const telegramTextLimit = 4096 + +// Headroom for fixed labels, heading, link text, group counts, dates, duration, +// and two fixed-decimal float64 values (each can take over 300 characters). +// Variable labels and the actual group message are counted separately. +const telegramFixedTextBudget = 1024 + +func usesBuiltInTelegramBody(webhook WebhookConfig) bool { + return webhook.Service == "telegram" && strings.TrimSpace(webhook.Template) == "" +} + +func sizesTelegramDeliveries(webhook WebhookConfig) bool { + // The URL template can depend on any field of the original group and + // determine the recipient. Never recalculate it with a different group. + return usesBuiltInTelegramBody(webhook) && !strings.Contains(webhook.URL, "{{") +} + +func telegramTextUnits(s string) int { + units := 0 + for _, r := range s { + units += utf16.RuneLen(r) + } + return units +} + +func telegramDetailsBound(level, kind, name, node string, resolved bool) int { + n := telegramFixedTextBudget + telegramTextUnits(kind) + telegramTextUnits(name) + telegramTextUnits(node) + if resolved { + return n + telegramTextUnits(name) // also in the heading + } + return n + telegramTextUnits(level) +} + +// telegramAlertBatches keeps alert membership and order, never edits a stored +// alert, and plans one provider attempt per batch. A message that cannot share +// space is a single delivery; the single-alert renderer fits its presentation. +func telegramAlertBatches(list []*alerts.Alert, event notificationEvent) [][]*alerts.Alert { + if len(list) <= 1 { + return [][]*alerts.Alert{list} + } + for _, alert := range list { + if alert == nil { + return [][]*alerts.Alert{list} // leave invalid retained rows to the existing path + } + } + var batches [][]*alerts.Alert + resolved := event == eventResolved + for start := 0; start < len(list); { + leader := list[start] + units := telegramDetailsBound(string(leader.Level), leader.Type, leader.ResourceName, leader.Node, resolved) + if resolved { + units += telegramTextUnits(resolvedAlertListEntry(leader)) + } else { + units += telegramTextUnits(leader.Message) + } + end := start + 1 + for ; end < len(list); end++ { + var entry string + if resolved { + entry = resolvedAlertListEntry(list[end]) + } else { + entry = groupedWebhookAlertLine(list[end]) + } + units += telegramTextUnits(entry) + 2 // newline or a semicolon and space + if units > telegramTextLimit { + break + } + } + batches = append(batches, list[start:end]) + start = end + } + return batches +} + +func telegramVisibleUnits(body []byte) (int, error) { + var payload struct { + Text string `json:"text"` + } + if err := json.Unmarshal(body, &payload); err != nil { + return 0, err + } + // Only the fixed Telegram template adds markup. Its literal text may + // contain "<" or "&" after decoding, so do not strip tags from decoded text. + units := 0 + for rest := payload.Text; ; { + literal, tag, found := strings.Cut(rest, "<") + units += telegramTextUnits(html.UnescapeString(literal)) + if !found { + return units, nil + } + if _, rest, found = strings.Cut(tag, ">"); !found { + return 0, fmt.Errorf("unterminated built-in Telegram tag") + } + } +} + +func ellipsizeTelegramText(s string, budget int) string { + if telegramTextUnits(s) <= budget { + return s + } + if budget < 1 { + return "" + } + units := 0 + for i, r := range s { + units += utf16.RuneLen(r) + if units >= budget { + return s[:i] + "…" + } + } + return s +} + +// Render an oversized singleton without changing its occurrence, route, URL +// template inputs, or stored evidence. Never cut rendered HTML or JSON. +func (n *NotificationManager) renderBuiltInTelegram(template string, data WebhookPayloadData, mode webhookRenderMode) ([]byte, error) { + render := func(values WebhookPayloadData) ([]byte, error) { + return n.generatePayloadFromTemplateWithService(template, values, "telegram") + } + resolved := mode == webhookRenderModeResolved + if data.AlertCount > 1 || + telegramDetailsBound(data.Level, data.Type, data.ResourceName, data.Node, resolved)+telegramTextUnits(data.Message) <= telegramTextLimit { + return render(data) + } + + message := data.Message + data.Message = "" + // No individual label longer than the whole budget can fit unchanged. + // Bound the size of the measurement in that case without trimming normal labels. + data.ResourceName = ellipsizeTelegramText(data.ResourceName, telegramTextLimit) + data.Node = ellipsizeTelegramText(data.Node, telegramTextLimit) + data.Type = ellipsizeTelegramText(data.Type, telegramTextLimit) + data.Level = ellipsizeTelegramText(data.Level, telegramTextLimit) + measure := func() (int, error) { + body, err := render(data) + if err != nil { + return 0, err + } + return telegramVisibleUnits(body) + } + fixed, err := measure() + if err != nil { + return nil, err + } + if fixed >= telegramTextLimit { + // Pathological labels alone fill the message. Keep identifying + // prefixes and reserve room for the message and dashboard pointer. + data.ResourceName = ellipsizeTelegramText(data.ResourceName, 256) + data.Node = ellipsizeTelegramText(data.Node, 256) + data.Type = ellipsizeTelegramText(data.Type, 256) + data.Level = ellipsizeTelegramText(data.Level, 256) + fixed, err = measure() + if err != nil { + return nil, err + } + if fixed >= telegramTextLimit { + return nil, fmt.Errorf("built-in Telegram details exceed the text budget") + } + } + data.Message = ellipsizeTelegramText(message, telegramTextLimit-fixed) + return render(data) +} diff --git a/internal/notifications/telegram_text_budget_test.go b/internal/notifications/telegram_text_budget_test.go new file mode 100644 index 0000000000..d58451fda3 --- /dev/null +++ b/internal/notifications/telegram_text_budget_test.go @@ -0,0 +1,343 @@ +package notifications + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + "sync" + "testing" + "time" + "unicode/utf16" + + "github.com/rcourtman/pulse-go-rewrite/internal/alerts" + "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust" + "github.com/stretchr/testify/require" +) + +type telegramSizeObservation struct { + content telegramLiteralContent + status int + units int +} + +func telegramSizeReceiver(t *testing.T, reject string) (string, func() []telegramSizeObservation) { + t.Helper() + var mu sync.Mutex + var requests []telegramSizeObservation + server := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload telegramLiteralPayload + err := json.NewDecoder(r.Body).Decode(&payload) + content, parseErr := parseTelegramLiteralContent(payload) + units := len(utf16.Encode([]rune(content.text))) // independent of the planner + status := http.StatusOK + if err != nil || parseErr != nil || units > 4096 || payload.ChatID != "-1001234" || + (reject != "" && strings.Contains(content.text, reject)) { + status = http.StatusBadRequest + } + mu.Lock() + requests = append(requests, telegramSizeObservation{content, status, units}) + mu.Unlock() + w.WriteHeader(status) + })) + t.Cleanup(server.Close) + return server.URL + "/sendMessage?chat_id=-1001234", func() []telegramSizeObservation { + mu.Lock() + defer mu.Unlock() + return append([]telegramSizeObservation(nil), requests...) + } +} + +func telegramSizeManager(t *testing.T, dir, url string) (*NotificationManager, WebhookConfig) { + t.Helper() + m := NewNotificationManagerWithDeferredQueue("https://pulse.example.test", dir) + t.Cleanup(m.Stop) + require.NoError(t, m.UpdateAllowedPrivateCIDRs("127.0.0.1/32")) + hook := WebhookConfig{ID: "telegram", Name: "Synthetic Telegram", Service: "telegram", Enabled: true, URL: url} + m.AddWebhook(hook) + m.SetGroupingConfig(true, 60, false, false) + return m, hook +} + +func awaitTelegramSizeQueue(t *testing.T, q *NotificationQueue, sent, dead, held int) { + t.Helper() + require.Eventually(t, func() bool { + stats, err := q.GetQueueStats() + return err == nil && stats["sent"] == sent && stats["dlq"] == dead && + stats["pending"] == held && stats["sending"] == 0 + }, 10*time.Second, 5*time.Millisecond) +} + +// The receiver enforces just the built-in provider's documented text budget +// after entity parsing; it is not a model of Telegram's network or service. +func TestTelegramOversizedGroupDeliversEveryMember(t *testing.T) { + url, received := telegramSizeReceiver(t, "") + m, _ := telegramSizeManager(t, t.TempDir(), url) + batch := telegramReportedAlerts() + for _, alert := range batch { + alert.Message += " " + strings.Repeat("<&🧪>_", 185) + " end of " + alert.ID + "." + m.SendAlert(alert) + } + m.sendGroupedAlerts() + original, err := m.queue.GetPending(10) + require.NoError(t, err) + require.Len(t, original, 1, "normal grouping still selects one delivery") + require.NoError(t, m.StartQueueProcessing()) + awaitTelegramSizeQueue(t, m.queue, 2, 0, 0) + + requests := received() + require.Len(t, requests, 2) + for _, request := range requests { + require.Equal(t, http.StatusOK, request.status) + require.LessOrEqual(t, request.units, 4096) + require.Equal(t, 2, request.content.bold) + require.Len(t, request.content.links, 1) + } + for _, alert := range batch { + matches := 0 + for _, request := range requests { + matches += strings.Count(request.content.text, alert.Message) + } + require.Equal(t, 1, matches, "each firing member's full literal message is delivered once") + } + require.Empty(t, mustTelegramDLQ(t, m.queue)) +} + +func mustTelegramDLQ(t *testing.T, q *NotificationQueue) []*QueuedNotification { + t.Helper() + rows, err := q.GetDLQ(10) + require.NoError(t, err) + return rows +} + +func TestTelegramOversizedSingletonFitsBeforeEscaping(t *testing.T) { + url, received := telegramSizeReceiver(t, "") + m, hook := telegramSizeManager(t, t.TempDir(), url) + alert := telegramReportedAlerts()[0] + alert.Message = "poll_nodes failed & " + strings.Repeat("🧪<&>_\n", 1000) + original := alert.Clone() + require.NoError(t, m.sendGroupedWebhook(hook, []*alerts.Alert{alert})) + require.Equal(t, original, alert) + firing := received()[0] + require.Equal(t, http.StatusOK, firing.status) + require.GreaterOrEqual(t, firing.units, 4095) + require.Contains(t, firing.content.text, "poll_nodes failed &") + require.Contains(t, firing.content.text, "…\n\nDetails:") + require.Len(t, firing.content.links, 1) + require.Contains(t, firing.content.links[0], alert.ID) + require.NotContains(t, firing.content.text, "�", "do not cut an astral character or an HTML entity") + + longLabel := "long resource <&> " + strings.Repeat("🧪", 5000) + alert.ResourceName, alert.Node = longLabel, longLabel + original = alert.Clone() + require.NoError(t, m.sendResolvedWebhook(hook, []*alerts.Alert{alert}, time.Now())) + require.Equal(t, original, alert) + recovery := received()[1] + require.Equal(t, http.StatusOK, recovery.status) + require.Contains(t, recovery.content.text, "Resolved: long resource <&>") + require.Contains(t, recovery.content.text, "…") + require.NotContains(t, recovery.content.text, "�") +} + +func TestTelegramPartsKeepRateHoldAndProviderRejectionIndependent(t *testing.T) { + url, received := telegramSizeReceiver(t, "reject-this-part") + dir := t.TempDir() + m, hook := telegramSizeManager(t, dir, url) + start := time.Now().Add(-time.Minute) + var batch []*alerts.Alert + for _, id := range []string{"first-part", "reject-this-part", "third-part"} { + alert := quietReplayAlert(id, alerts.AlertLevelWarning, start) + alert.Message = id + " " + strings.Repeat("🧪<&", 550) + batch = append(batch, alert) + m.SendAlert(alert) + } + m.sendGroupedAlerts() + q := m.GetQueue() + pending, err := q.GetPending(10) + require.NoError(t, err) + require.Len(t, pending, 1) + original := pending[0] + for i := 0; i < WebhookRateLimitMax-1; i++ { + require.True(t, m.checkWebhookRateLimit(url)) + } + require.NoError(t, m.StartQueueProcessing()) + // The first part receives the one remaining slot. The other parts + // independently reach the same provider-free hold, not the DLQ. + awaitTelegramSizeQueue(t, q, 1, 0, 2) + require.Eventually(t, func() bool { + var held int + err := q.db.QueryRow("SELECT count(*) FROM notification_queue WHERE status='pending' AND last_error=?", telegramRateHoldMessage).Scan(&held) + return err == nil && held == 2 + }, 10*time.Second, 5*time.Millisecond) + require.Len(t, received(), 1) + for i := 1; i < len(batch); i++ { + row := loadQuietReplay(t, q, fmt.Sprintf("%s:telegram:%d", original.ID, i)) + require.Equal(t, QueueStatusPending, row.Status) + require.Zero(t, row.Attempts) + require.Nil(t, row.LastAttempt) + require.NotNil(t, row.NextRetryAt) + require.True(t, row.NextRetryAt.After(time.Now().Add(30*time.Second))) + require.Equal(t, original.Config, row.Config) + require.Equal(t, original.ReceiptEpoch, row.ReceiptEpoch) + require.Len(t, row.Links, 1) + require.Equal(t, row.ID, row.Links[0].NotificationID) + require.Equal(t, batch[i].OperationalRecord.ID, row.Links[0].OperationalRecordID) + require.Equal(t, original.Links[0].DestinationID, row.Links[0].DestinationID) + } + var audits int + require.NoError(t, q.db.QueryRow("SELECT count(*) FROM notification_audit").Scan(&audits)) + require.Equal(t, 1, audits, "local gating is not a provider attempt") + m.Stop() + + // Reopen committed work. Advance only the fixture's pending timestamps: + // deadline and attempts were asserted before reopening, with no 60 s sleep. + m, _ = telegramSizeManager(t, dir, url) + q = m.GetQueue() + _, err = q.db.Exec("UPDATE notification_queue SET next_retry_at=? WHERE status='pending'", time.Now().Add(-time.Second).Unix()) + require.NoError(t, err) + require.NoError(t, m.StartQueueProcessing()) + awaitTelegramSizeQueue(t, q, 2, 1, 0) + requests := received() + require.Len(t, requests, 3, "already-accepted first part was not resubmitted") + dlq := mustTelegramDLQ(t, q) + require.Len(t, dlq, 1) + require.Len(t, dlq[0].Alerts, 1) + require.Equal(t, "reject-this-part", dlq[0].Alerts[0].ID) + require.Equal(t, 1, dlq[0].Attempts) + for i, alert := range batch { + _, found, err := q.deliveryReceipt(alert, notificationDeliveryDestinationKey(notificationDeliveryJob{Type: "webhook", Event: eventAlert, WebhookConfig: &hook})) + require.NoError(t, err) + require.Equal(t, i != 1, found, "only an accepted part may own a recovery") + } +} + +func TestTelegramSizedRecoveriesKeepTheirWindowAndReceipts(t *testing.T) { + url, received := telegramSizeReceiver(t, "") + m, hook := telegramSizeManager(t, t.TempDir(), url) + m.SetNotifyOnResolve(true) + m.SetGroupingConfig(true, 3, false, false) + var batch []*alerts.Alert + start := time.Now().Add(-time.Minute) + for _, id := range []string{"alpha-recovered", "beta-recovered", "gamma-recovered"} { + a := quietReplayAlert(id, alerts.AlertLevelWarning, start) + a.ResourceName = id + a.Node = strings.Repeat("🧪<&", 475) // two resolved entries cannot fit in one + batch = append(batch, a) + m.SendAlert(a) + } + m.sendGroupedAlerts() + q := m.GetQueue() + require.NoError(t, m.StartQueueProcessing()) + // The firing layout includes the leader node and the secondary nodes. + awaitTelegramSizeQueue(t, q, 3, 0, 0) + for _, a := range batch { + require.False(t, m.CancelResolvedAlert(a)) + m.SendResolvedAlert(&alerts.ResolvedAlert{Alert: a, ResolvedTime: time.Now()}) + } + stats, err := q.GetQueueStats() + require.NoError(t, err) + require.Equal(t, 1, stats["pending"], "the recovery window should still coalesce") + require.Len(t, received(), 3, "no early recovery") + early, err := q.GetPending(10) + require.NoError(t, err) + require.Empty(t, early) + awaitTelegramSizeQueue(t, q, 6, 0, 0) + requests := received() + for _, a := range batch { + occurrences := 0 + for _, request := range requests { + require.Equal(t, http.StatusOK, request.status) + if strings.Contains(request.content.text, "Resolved: "+a.ResourceName) { + occurrences++ + } + } + require.Equal(t, 1, occurrences) + _, found, err := q.deliveryReceipt(a, notificationDeliveryDestinationKey(notificationDeliveryJob{Type: "webhook", WebhookConfig: &hook})) + require.NoError(t, err) + require.False(t, found, "recovery must consume exactly its own receipt") + } +} + +func TestTelegramSizingPreservesExistingDestinationAndAttemptContracts(t *testing.T) { + for _, tc := range []struct { + name, service, url, template string + attempted bool + }{ + {name: "user body", service: "telegram", url: "https://example.test/sendMessage", template: `{"text":"{{.Message | jsonString}}"}`}, + {name: "templated recipient", service: "telegram", url: "https://example.test/sendMessage?chat_id={{.AlertCount}}"}, + {name: "generic", service: "generic", url: "https://example.test/sendMessage"}, + {name: "attempted", service: "telegram", url: "https://example.test/sendMessage", attempted: true}, + } { + t.Run(tc.name, func(t *testing.T) { + q, err := NewInMemoryNotificationQueue() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, q.Stop()) }) + hook := WebhookConfig{ID: "configured", Service: tc.service, URL: tc.url, Enabled: true, Template: tc.template} + raw, err := json.Marshal(hook) + require.NoError(t, err) + batch := telegramReportedAlerts() + for _, a := range batch { + a.Message += strings.Repeat("🧪<&", 800) + } + row := &QueuedNotification{Type: "webhook", Alerts: batch, Config: raw, MaxAttempts: 3} + require.NoError(t, q.Enqueue(row)) + if tc.attempted { + require.NoError(t, q.IncrementAttemptAndSetStatus(row.ID, QueueStatusPending)) + } + pending, err := q.GetPending(10) + require.NoError(t, err) + require.Len(t, pending, 1) + claimed, err := q.claimPendingForDelivery(pending[0]) + require.NoError(t, err) + require.True(t, claimed) + require.Len(t, pending[0].Alerts, len(batch)) + require.Equal(t, row.Config, pending[0].Config) + other, err := q.GetPending(10) + require.NoError(t, err) + require.Empty(t, other, "nothing silently reroutes or resends a previously attempted group") + }) + } +} + +func TestTelegramBatchLinkCannotBelongToTwoParts(t *testing.T) { + start := time.Now() + one := quietReplayAlert("shared-link", alerts.AlertLevelWarning, start) + two := quietReplayAlert("shared-link", alerts.AlertLevelWarning, start) + two.StartTime = start.Add(time.Second) + link := operationaltrust.NotificationLink{ + OperationalRecordID: one.OperationalRecord.ID, TransitionID: one.LatestTransition.ID, + } + _, err := telegramBatchLinks([]operationaltrust.NotificationLink{link}, [][]*alerts.Alert{{one}, {two}}, []string{"first", "second"}) + require.ErrorContains(t, err, "ambiguous operational link") +} + +func TestTelegramQueuePartitionFailureLeavesOriginalUnattempted(t *testing.T) { + q, err := NewInMemoryNotificationQueue() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, q.Stop()) }) + batch := telegramReportedAlerts() + for _, a := range batch { + a.Message += strings.Repeat("🧪<&", 800) + } + hook := WebhookConfig{ID: "telegram", Service: "telegram", Enabled: true, URL: "https://example.test/sendMessage?chat_id=-1001234"} + raw, err := json.Marshal(hook) + require.NoError(t, err) + row := &QueuedNotification{Type: "webhook", Alerts: batch, Config: raw, MaxAttempts: 3} + require.NoError(t, q.Enqueue(row)) + _, err = q.db.Exec(`CREATE TRIGGER abort_fixture BEFORE INSERT ON notification_queue + WHEN NEW.id LIKE '%:telegram:2' BEGIN SELECT RAISE(ABORT,'fixture partition refused'); END;`) + require.NoError(t, err) + pending, err := q.GetPending(10) + require.NoError(t, err) + require.Len(t, pending, 1) + claimed, err := q.claimPendingForDelivery(pending[0]) + require.ErrorContains(t, err, "fixture partition refused") + require.False(t, claimed) + pending, err = q.GetPending(10) + require.NoError(t, err) + require.Len(t, pending, 1) + require.Equal(t, row.ID, pending[0].ID) + require.Len(t, pending[0].Alerts, len(batch)) + require.Zero(t, pending[0].Attempts) + require.Nil(t, pending[0].LastAttempt) +}