main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // Command deliverd-telegram consumes deliveries.telegram.<company_id>
  2. // subjects and posts each alert to the Telegram Bot API
  3. // (sendMessage). It is the M3 counterpart of deliverd-fcm;
  4. // both consume from the same alerts flow but are deployed,
  5. // scaled, and restarted independently.
  6. //
  7. // Per the user's M3 Q2 answer: two binaries, not one with a
  8. // per-channel registry. Pros: independent deploys, no
  9. // cross-channel blast radius, simpler per-channel config.
  10. // Cons: more containers to operate. For v1 with a small
  11. // channel set (fcm, telegram) this is the right call.
  12. //
  13. // Configuration:
  14. // BA_TELEGRAM_BOT_TOKEN — default bot token if envelope
  15. // doesn't carry a per-company one
  16. // BA_TELEGRAM_BASE_URL — override for tests (default
  17. // https://api.telegram.org).
  18. // M3 dev: point at faketgmd.
  19. // BA_TELEGRAM_FAKE_URL — alias kept for the smoke
  20. // script; if set, takes priority.
  21. //
  22. // M3 ships single-attempt sends (no retry, no DLQ). That
  23. // follows the same pattern as deliverd-fcm in M1.
  24. // M8 adds the retry + DLQ chain (SPEC §9).
  25. package main
  26. import (
  27. "context"
  28. "encoding/json"
  29. "fmt"
  30. "log/slog"
  31. "net/http"
  32. "os"
  33. "os/signal"
  34. "strings"
  35. "syscall"
  36. "time"
  37. "git3.techno-world.net/lrosales/broad-announce/internal/alert"
  38. "git3.techno-world.net/lrosales/broad-announce/internal/broker"
  39. "git3.techno-world.net/lrosales/broad-announce/internal/config"
  40. "git3.techno-world.net/lrosales/broad-announce/internal/dlq"
  41. "git3.techno-world.net/lrosales/broad-announce/internal/httpserver"
  42. "git3.techno-world.net/lrosales/broad-announce/internal/observability"
  43. "git3.techno-world.net/lrosales/broad-announce/internal/postgres"
  44. "git3.techno-world.net/lrosales/broad-announce/internal/retry"
  45. "git3.techno-world.net/lrosales/broad-announce/internal/telegram"
  46. "github.com/nats-io/nats.go/jetstream"
  47. )
  48. const telegramChannel = "telegram"
  49. // deliverdMetrics is the package-level metrics instance.
  50. // Wired in main() from observability.NewDeliverdMetrics.
  51. var deliverdMetrics *observability.DeliverdMetrics
  52. type deliveryEnvelope struct {
  53. Alert json.RawMessage `json:"alert"`
  54. IndividualID string `json:"individual_id"`
  55. Channel string `json:"channel"`
  56. Endpoint string `json:"endpoint"`
  57. Locale string `json:"locale,omitempty"`
  58. }
  59. func main() {
  60. cfg, err := config.LoadCommon("deliverd-telegram")
  61. if err != nil {
  62. os.Stderr.WriteString("config: " + err.Error() + "\n")
  63. os.Exit(1)
  64. }
  65. logger := observability.Init(cfg.Env, cfg.LogLevel, "deliverd-telegram")
  66. logger.Info("starting",
  67. "env", cfg.Env,
  68. "addr", cfg.HTTPAddr,
  69. "max_attempts", cfg.DeliverdMaxAttempts,
  70. "retry_base_ms", cfg.DeliverdRetryBaseMs,
  71. "retry_max_ms", cfg.DeliverdRetryMaxMs,
  72. "retry_budget_ms", cfg.DeliverdRetryBudgetMs,
  73. )
  74. ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
  75. defer stop()
  76. br, err := broker.Connect(ctx, cfg.NATSURL)
  77. if err != nil {
  78. logger.Error("nats connect", "err", err)
  79. os.Exit(1)
  80. }
  81. defer br.Close()
  82. pool, err := postgres.Connect(ctx, cfg.PostgresDSN)
  83. if err != nil {
  84. logger.Error("postgres connect", "err", err)
  85. os.Exit(1)
  86. }
  87. defer pool.Close()
  88. // Bot token resolution. M3: read from env. M3+:
  89. // look up the per-company bot via the company_id encoded
  90. // in the alert or the subject. For now the env-supplied
  91. // default works because the M3 seed has one bot per
  92. // company.
  93. botToken := os.Getenv("BA_TELEGRAM_BOT_TOKEN")
  94. if botToken == "" {
  95. botToken = "fake-tg-bot-token-acme-001" // dev convenience
  96. }
  97. baseURL := os.Getenv("BA_TELEGRAM_FAKE_URL")
  98. if baseURL == "" {
  99. baseURL = os.Getenv("BA_TELEGRAM_BASE_URL")
  100. }
  101. if baseURL == "" {
  102. baseURL = "http://faketgmd:8830" // M3 docker-compose default
  103. }
  104. logger.Info("telegram target", "base_url", baseURL)
  105. client := &telegram.HTTPBotClient{
  106. BaseURL: baseURL,
  107. HTTP: &http.Client{Timeout: 15 * time.Second},
  108. }
  109. // M8: same retry config as deliverd-fcm. See
  110. // internal/retry for the policy.
  111. retryCfg := retry.Config{
  112. MaxAttempts: cfg.DeliverdMaxAttempts,
  113. BaseDelay: time.Duration(cfg.DeliverdRetryBaseMs) * time.Millisecond,
  114. MaxDelay: time.Duration(cfg.DeliverdRetryMaxMs) * time.Millisecond,
  115. Budget: time.Duration(cfg.DeliverdRetryBudgetMs) * time.Millisecond,
  116. }
  117. js := br.JS()
  118. stream, err := js.Stream(ctx, "DELIVERIES")
  119. if err != nil {
  120. logger.Error("nats stream DELIVERIES", "err", err)
  121. os.Exit(1)
  122. }
  123. consumer, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
  124. Name: "deliverd-telegram",
  125. Durable: "deliverd-telegram",
  126. FilterSubjects: []string{"deliveries.telegram.>"},
  127. AckPolicy: jetstream.AckExplicitPolicy,
  128. })
  129. if err != nil {
  130. logger.Error("nats consumer", "err", err)
  131. os.Exit(1)
  132. }
  133. runCtx, runCancel := context.WithCancel(ctx)
  134. defer runCancel()
  135. // M9: deliverd metrics. Separate registry from deliverd-fcm
  136. // so each gets its own service label in Prometheus.
  137. reg, _ := observability.NewRegistry("deliverd-telegram")
  138. deliverdMetrics = observability.NewDeliverdMetrics(reg, "deliverd-telegram")
  139. go consume(runCtx, logger, consumer, pool, client, botToken, retryCfg)
  140. srv := httpserver.New(httpserver.Config{
  141. Addr: cfg.HTTPAddr,
  142. ServiceName: "deliverd-telegram",
  143. ShutdownGrace: cfg.ShutdownGrace,
  144. }, logger, observability.MetricsHandler(reg))
  145. errCh := make(chan error, 1)
  146. go func() { errCh <- srv.Start() }()
  147. select {
  148. case <-ctx.Done():
  149. logger.Info("shutdown signal received")
  150. case err := <-errCh:
  151. if err != nil {
  152. logger.Error("http server", "err", err)
  153. os.Exit(1)
  154. }
  155. }
  156. runCancel()
  157. time.Sleep(500 * time.Millisecond)
  158. if err := srv.Shutdown(ctx); err != nil {
  159. logger.Warn("graceful shutdown", "err", err)
  160. }
  161. logger.Info("bye")
  162. }
  163. func consume(ctx context.Context, logger *slog.Logger, c jetstream.Consumer, pool *postgres.Pool, client telegram.BotClient, botToken string, retryCfg retry.Config) {
  164. for {
  165. if ctx.Err() != nil {
  166. return
  167. }
  168. batch, err := c.Fetch(16, jetstream.FetchMaxWait(2*time.Second))
  169. if err != nil {
  170. if ctx.Err() != nil {
  171. return
  172. }
  173. logger.Warn("nats fetch", "err", err)
  174. time.Sleep(500 * time.Millisecond)
  175. continue
  176. }
  177. for m := range batch.Messages() {
  178. handleOne(ctx, logger, m, pool, client, botToken, retryCfg)
  179. if batch.Error() != nil {
  180. logger.Warn("batch error", "err", batch.Error())
  181. break
  182. }
  183. }
  184. }
  185. }
  186. // handleOne mirrors deliverd-fcm's structure:
  187. // 1. Parse the envelope (drop poison messages).
  188. // 2. Retry loop: each attempt calls SendMessage and
  189. // writes a `deliveries` audit row. On success,
  190. // break out. On exhaustion, write a `deliveries_dlq`
  191. // row + a final 'dlq' audit row.
  192. // 3. Ack the NATS message either way.
  193. func handleOne(ctx context.Context, logger *slog.Logger, m jetstream.Msg, pool *postgres.Pool, client telegram.BotClient, botToken string, retryCfg retry.Config) {
  194. var env deliveryEnvelope
  195. if err := json.Unmarshal(m.Data(), &env); err != nil {
  196. logger.Warn("malformed delivery envelope", "err", err, "subject", m.Subject())
  197. _ = m.Ack()
  198. return
  199. }
  200. var ah struct {
  201. ID string `json:"id"`
  202. CompanyID string `json:"company_id"`
  203. Title string `json:"title"`
  204. Body string `json:"body"`
  205. Severity alert.Severity `json:"severity"`
  206. Category string `json:"category"`
  207. SourceID string `json:"source_id"`
  208. DedupeCount uint32 `json:"dedupe_count"`
  209. }
  210. _ = json.Unmarshal(env.Alert, &ah)
  211. companyID := ah.CompanyID
  212. if companyID == "" {
  213. parts := strings.SplitN(m.Subject(), ".", 3)
  214. if len(parts) == 3 {
  215. companyID = parts[2]
  216. }
  217. }
  218. if companyID == "" || env.Endpoint == "" || ah.ID == "" {
  219. logger.Warn("delivery envelope missing fields", "subject", m.Subject(), "company", companyID, "endpoint_present", env.Endpoint != "", "alert_id", ah.ID)
  220. _ = m.Ack()
  221. return
  222. }
  223. chatID, err := parseInt64(env.Endpoint)
  224. if err != nil {
  225. logger.Warn("endpoint is not a telegram chat id", "endpoint", env.Endpoint)
  226. _ = m.Ack()
  227. return
  228. }
  229. // Build the text once, retry the same text. Format
  230. // unchanged from M3.
  231. text := formatMessage(ah.Severity, ah.Title, ah.Body, ah.ID, ah.DedupeCount)
  232. // M9: track attempt start time for DLQ latency metric.
  233. firstAttemptTime := time.Now()
  234. // M8: retry loop. Telegram returns errors on:
  235. // - 4xx (chat not found, bot blocked, etc.) — these
  236. // are permanent; we use PermanentError to skip
  237. // further retries.
  238. // - 5xx, network timeouts — these are transient;
  239. // retry with backoff.
  240. // - 429 (rate limited) — transient; retry.
  241. var lastErr error
  242. var sent bool
  243. res := retry.Run(ctx, retryCfg, func(attemptCtx context.Context, attempt int) error {
  244. attemptCtx, cancel := context.WithTimeout(attemptCtx, 15*time.Second)
  245. defer cancel()
  246. _, sendErr := client.SendMessage(attemptCtx, botToken, chatID, text)
  247. status := "failed"
  248. lastErrStr := ""
  249. if sendErr == nil {
  250. status = "sent"
  251. sent = true
  252. } else {
  253. lastErrStr = sendErr.Error()
  254. }
  255. _, dbErr := pool.Exec(attemptCtx, `
  256. INSERT INTO deliveries
  257. (alert_id, company_id, individual_id, channel, target, status, attempts, last_error, payload, sent_at)
  258. VALUES ($1, $2, $3, $4, $5, $6, $7, NULLIF($8, ''), $9,
  259. CASE WHEN $6 = 'sent' THEN now() ELSE NULL END)
  260. `, ah.ID, companyID, env.IndividualID, telegramChannel, env.Endpoint, status, attempt, lastErrStr, json.RawMessage(m.Data()))
  261. if dbErr != nil {
  262. logger.Warn("delivery row insert", "err", dbErr, "attempt", attempt)
  263. }
  264. // M9: record per-channel delivery attempt metric.
  265. if deliverdMetrics != nil {
  266. deliverdMetrics.DeliveryAttempts.WithLabelValues(telegramChannel, status).Inc()
  267. }
  268. if status == "sent" {
  269. logger.Info("delivery sent",
  270. "alert_id", ah.ID,
  271. "company", companyID,
  272. "individual", env.IndividualID,
  273. "channel", telegramChannel,
  274. "attempt", attempt,
  275. )
  276. return nil
  277. }
  278. // Permanent-error detection. The Telegram Bot API
  279. // returns errors of the form "telegram api <code>:
  280. // <description>". 4xx codes (400, 401, 403, 404,
  281. // 409) are not retryable; 429 (Too Many Requests) is
  282. // transient and stays in the retry path. The
  283. // faketgmd test double mirrors this convention.
  284. if isTelegramPermanent(lastErrStr) {
  285. logger.Warn("permanent telegram error",
  286. "alert_id", ah.ID,
  287. "err", lastErrStr,
  288. "attempt", attempt,
  289. )
  290. lastErr = &retry.PermanentError{Err: fmt.Errorf("telegram permanent %s", lastErrStr)}
  291. return lastErr
  292. }
  293. logger.Warn("delivery attempt failed",
  294. "alert_id", ah.ID,
  295. "company", companyID,
  296. "channel", telegramChannel,
  297. "attempt", attempt,
  298. "err", lastErrStr,
  299. )
  300. lastErr = fmt.Errorf("%s", lastErrStr)
  301. return lastErr
  302. })
  303. if sent {
  304. _ = m.Ack()
  305. return
  306. }
  307. // All attempts exhausted (or permanent error). DLQ
  308. // insert for the operator UI; replay re-INSERTs the
  309. // original payload into the same NATS subject.
  310. dlqID, dlqErr := dlq.Write(ctx, pool, dlq.Entry{
  311. AlertID: ah.ID,
  312. CompanyID: companyID,
  313. IndividualID: env.IndividualID,
  314. Channel: telegramChannel,
  315. Target: env.Endpoint,
  316. OriginalSubject: m.Subject(),
  317. Attempts: res.Attempts,
  318. LastError: errString(lastErr),
  319. Payload: json.RawMessage(m.Data()),
  320. })
  321. if dlqErr != nil {
  322. logger.Error("dlq insert FAILED",
  323. "err", dlqErr,
  324. "alert_id", ah.ID,
  325. "company", companyID,
  326. )
  327. } else {
  328. logger.Warn("delivery → DLQ",
  329. "dlq_id", dlqID,
  330. "alert_id", ah.ID,
  331. "company", companyID,
  332. "channel", telegramChannel,
  333. "attempts", res.Attempts,
  334. "err", errString(lastErr),
  335. )
  336. // M9: record DLQ metric and latency.
  337. if deliverdMetrics != nil {
  338. deliverdMetrics.DLQTotal.WithLabelValues(telegramChannel).Inc()
  339. deliverdMetrics.DLQLatency.Observe(time.Since(firstAttemptTime).Seconds())
  340. deliverdMetrics.RetryAttempts.WithLabelValues(telegramChannel).Add(float64(res.Attempts))
  341. }
  342. }
  343. _ = m.Ack()
  344. }
  345. // isTelegramPermanent classifies a Telegram Bot API
  346. // error string as permanent (no point retrying). The
  347. // faketgmd test double prefixes errors with "telegram
  348. // api <code>:" so we can match on the code.
  349. //
  350. // 429 (rate limited) is intentionally NOT permanent —
  351. // the retry helper will space it out via backoff.
  352. func isTelegramPermanent(errStr string) bool {
  353. if errStr == "" {
  354. return false
  355. }
  356. // Look for "telegram api NNN" or "status NNN" in the
  357. // error string. 4xx (except 429) is permanent.
  358. for _, prefix := range []string{"telegram api ", "status "} {
  359. i := strings.Index(errStr, prefix)
  360. if i < 0 {
  361. continue
  362. }
  363. rest := errStr[i+len(prefix):]
  364. // Parse a 3-digit code.
  365. if len(rest) < 3 {
  366. continue
  367. }
  368. codeStr := rest[:3]
  369. var code int
  370. if _, err := fmt.Sscanf(codeStr, "%d", &code); err != nil {
  371. continue
  372. }
  373. if code >= 400 && code < 500 && code != 429 && code != 408 {
  374. return true
  375. }
  376. }
  377. return false
  378. }
  379. // formatMessage produces a Telegram-friendly rendering of
  380. // the alert. The format is intentionally plain (Telegram
  381. // supports Markdown/HTML but they vary across clients);
  382. // M3.5+ can add formatting once the Android-side payload
  383. // shape is locked.
  384. //
  385. // M6: when DedupeCount > 1, we append ` (×N)` to the title
  386. // so a glance at the chat shows how many times the source
  387. // has fired this alert inside the sliding dedupe window.
  388. // For DedupeCount == 0 (not set) or == 1 (first arrival),
  389. // no suffix is added.
  390. func formatMessage(sev alert.Severity, title, body, alertID string, dedupeCount uint32) string {
  391. var prefix string
  392. switch sev {
  393. case alert.SeverityInminentColapse:
  394. prefix = "🟥🟥🟥 IMMINENT"
  395. case alert.SeverityCritical:
  396. prefix = "🟥 CRITICAL"
  397. case alert.SeverityWarning:
  398. prefix = "🟧 WARNING"
  399. default:
  400. prefix = "🟦 INFO"
  401. }
  402. displayedTitle := title
  403. if dedupeCount > 1 {
  404. displayedTitle = fmt.Sprintf("%s (×%d)", title, dedupeCount)
  405. }
  406. out := fmt.Sprintf("%s: %s", prefix, displayedTitle)
  407. if body != "" {
  408. out += "\n" + body
  409. }
  410. short := alertID
  411. if len(short) > 12 {
  412. short = short[:12]
  413. }
  414. out += fmt.Sprintf("\n— alert %s", short)
  415. return out
  416. }
  417. func parseInt64(s string) (int64, error) {
  418. var n int64
  419. _, err := fmt.Sscanf(s, "%d", &n)
  420. return n, err
  421. }
  422. func errString(err error) string {
  423. if err == nil {
  424. return ""
  425. }
  426. return err.Error()
  427. }