main.go 13 KB

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