main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. // Command deliverd-fcm consumes deliveries.fcm.<company_id> subjects
  2. // and posts each alert to the FCM HTTP v1 endpoint. M3 splits
  3. // this out of the original `cmd/deliverd` (which is now two
  4. // per-channel binaries: deliverd-fcm and deliverd-telegram).
  5. // That gives us the option to scale, restart, and deploy each
  6. // channel independently — your Q2 answer.
  7. //
  8. // M0: per-channel worker binary that connects to NATS, /health, /metrics.
  9. // M1: deliverd-fcm — consumes deliveries.fcm.*, posts to fakefcmd,
  10. // records a row in Postgres per attempt.
  11. // M3: rename only. No behavior change. The HTTP target URL is
  12. // BA_FAKECMD_URL (dev) or BA_FCM_BASE_URL (prod); M11+ will
  13. // add real FCM auth.
  14. // M8: in-process retry with exp backoff (10 attempts, default)
  15. // and a DLQ insert on terminal failure. See SPEC §9.
  16. package main
  17. import (
  18. "bytes"
  19. "context"
  20. "encoding/json"
  21. "fmt"
  22. "io"
  23. "log/slog"
  24. "net/http"
  25. "os"
  26. "os/signal"
  27. "strings"
  28. "syscall"
  29. "time"
  30. "git3.techno-world.net/lrosales/broad-announce/internal/broker"
  31. "git3.techno-world.net/lrosales/broad-announce/internal/config"
  32. "git3.techno-world.net/lrosales/broad-announce/internal/dlq"
  33. "git3.techno-world.net/lrosales/broad-announce/internal/httpserver"
  34. "git3.techno-world.net/lrosales/broad-announce/internal/observability"
  35. "git3.techno-world.net/lrosales/broad-announce/internal/postgres"
  36. "git3.techno-world.net/lrosales/broad-announce/internal/retry"
  37. "github.com/nats-io/nats.go/jetstream"
  38. )
  39. // deliverdMetrics is the package-level metrics instance.
  40. // Wired in main() from observability.NewDeliverdMetrics.
  41. var deliverdMetrics *observability.DeliverdMetrics
  42. // M2: only the FCM channel. M3+ adds telegram, sms, etc.
  43. const fcmChannel = "fcm"
  44. type deliveryEnvelope struct {
  45. Alert json.RawMessage `json:"alert"`
  46. IndividualID string `json:"individual_id"`
  47. Channel string `json:"channel"`
  48. Endpoint string `json:"endpoint"`
  49. Locale string `json:"locale,omitempty"`
  50. }
  51. func main() {
  52. cfg, err := config.LoadCommon("deliverd")
  53. if err != nil {
  54. os.Stderr.WriteString("config: " + err.Error() + "\n")
  55. os.Exit(1)
  56. }
  57. logger := observability.Init(cfg.Env, cfg.LogLevel, "deliverd")
  58. logger.Info("starting",
  59. "env", cfg.Env,
  60. "addr", cfg.HTTPAddr,
  61. "max_attempts", cfg.DeliverdMaxAttempts,
  62. "retry_base_ms", cfg.DeliverdRetryBaseMs,
  63. "retry_max_ms", cfg.DeliverdRetryMaxMs,
  64. "retry_budget_ms", cfg.DeliverdRetryBudgetMs,
  65. )
  66. ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
  67. defer stop()
  68. br, err := broker.Connect(ctx, cfg.NATSURL)
  69. if err != nil {
  70. logger.Error("nats connect", "err", err)
  71. os.Exit(1)
  72. }
  73. defer br.Close()
  74. pool, err := postgres.Connect(ctx, cfg.PostgresDSN)
  75. if err != nil {
  76. logger.Error("postgres connect", "err", err)
  77. os.Exit(1)
  78. }
  79. defer pool.Close()
  80. // M1 only: fakefcmd URL. M3+ uses the real FCM HTTP v1 endpoint.
  81. fakefcmdURL := os.Getenv("BA_FAKECMD_URL")
  82. if fakefcmdURL == "" {
  83. fakefcmdURL = "http://fakefcmd:8820"
  84. }
  85. logger.Info("fcm target", "url", fakefcmdURL)
  86. httpClient := &http.Client{Timeout: 10 * time.Second}
  87. // M8: build the retry config from env. Defaults match
  88. // internal/retry.Default() so the .env.example can stay
  89. // sparse; ops can override per-deploy.
  90. retryCfg := retry.Config{
  91. MaxAttempts: cfg.DeliverdMaxAttempts,
  92. BaseDelay: time.Duration(cfg.DeliverdRetryBaseMs) * time.Millisecond,
  93. MaxDelay: time.Duration(cfg.DeliverdRetryMaxMs) * time.Millisecond,
  94. Budget: time.Duration(cfg.DeliverdRetryBudgetMs) * time.Millisecond,
  95. }
  96. js := br.JS()
  97. stream, err := js.Stream(ctx, "DELIVERIES")
  98. if err != nil {
  99. logger.Error("nats stream DELIVERIES", "err", err)
  100. os.Exit(1)
  101. }
  102. consumer, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
  103. Name: "deliverd-fcm",
  104. Durable: "deliverd-fcm",
  105. FilterSubjects: []string{"deliveries.fcm.>"},
  106. AckPolicy: jetstream.AckExplicitPolicy,
  107. })
  108. if err != nil {
  109. logger.Error("nats consumer", "err", err)
  110. os.Exit(1)
  111. }
  112. runCtx, runCancel := context.WithCancel(ctx)
  113. defer runCancel()
  114. // M9: deliverd metrics. One registry for both fcm and telegram
  115. // deliverds so they get separate service labels.
  116. reg, _ := observability.NewRegistry("deliverd")
  117. deliverdMetrics = observability.NewDeliverdMetrics(reg, "deliverd")
  118. go consume(runCtx, logger, consumer, pool, httpClient, fakefcmdURL, retryCfg)
  119. srv := httpserver.New(httpserver.Config{
  120. Addr: cfg.HTTPAddr,
  121. ServiceName: "deliverd",
  122. ShutdownGrace: cfg.ShutdownGrace,
  123. }, logger, observability.MetricsHandler(reg))
  124. errCh := make(chan error, 1)
  125. go func() { errCh <- srv.Start() }()
  126. select {
  127. case <-ctx.Done():
  128. logger.Info("shutdown signal received")
  129. case err := <-errCh:
  130. if err != nil {
  131. logger.Error("http server", "err", err)
  132. os.Exit(1)
  133. }
  134. }
  135. runCancel()
  136. time.Sleep(500 * time.Millisecond)
  137. if err := srv.Shutdown(ctx); err != nil {
  138. logger.Warn("graceful shutdown", "err", err)
  139. }
  140. logger.Info("bye")
  141. }
  142. func consume(ctx context.Context, logger *slog.Logger, c jetstream.Consumer, pool *postgres.Pool, httpClient *http.Client, fakefcmdURL string, retryCfg retry.Config) {
  143. for {
  144. if ctx.Err() != nil {
  145. return
  146. }
  147. batch, err := c.Fetch(16, jetstream.FetchMaxWait(2*time.Second))
  148. if err != nil {
  149. if ctx.Err() != nil {
  150. return
  151. }
  152. logger.Warn("nats fetch", "err", err)
  153. time.Sleep(500 * time.Millisecond)
  154. continue
  155. }
  156. for m := range batch.Messages() {
  157. handleOne(ctx, logger, m, pool, httpClient, fakefcmdURL, retryCfg)
  158. if batch.Error() != nil {
  159. logger.Warn("batch error", "err", batch.Error())
  160. break
  161. }
  162. }
  163. }
  164. }
  165. // handleOne processes a single delivery. M8 split the
  166. // work into three steps:
  167. // 1. Parse the envelope; if it's malformed, Ack and
  168. // bail (no DLQ for un-parseable data — there's no
  169. // payload to replay anyway).
  170. // 2. Run the retry loop. Each attempt POSTs to the
  171. // target and writes a `deliveries` audit row. On
  172. // the final failure, write a `deliveries_dlq` row.
  173. // 3. Ack the NATS message; the work is done one way
  174. // or another (sent, or durably parked in the DLQ).
  175. func handleOne(ctx context.Context, logger *slog.Logger, m jetstream.Msg, pool *postgres.Pool, httpClient *http.Client, fakefcmdURL string, retryCfg retry.Config) {
  176. var env deliveryEnvelope
  177. if err := json.Unmarshal(m.Data(), &env); err != nil {
  178. logger.Warn("malformed delivery envelope", "err", err, "subject", m.Subject())
  179. _ = m.Ack() // poison message; we don't have a DLQ for malformed yet
  180. return
  181. }
  182. // Parse out the alert_id and company_id from the inner alert JSON.
  183. var alertHeader struct {
  184. ID string `json:"id"`
  185. CompanyID string `json:"company_id"`
  186. Title string `json:"title"`
  187. Body string `json:"body"`
  188. Data map[string]string `json:"data"`
  189. Category string `json:"category"`
  190. Severity string `json:"severity"`
  191. DedupeCount uint32 `json:"dedupe_count"`
  192. }
  193. _ = json.Unmarshal(env.Alert, &alertHeader)
  194. companyID := alertHeader.CompanyID
  195. if companyID == "" {
  196. // subject is "deliveries.fcm.<company_id>"
  197. parts := strings.SplitN(m.Subject(), ".", 3)
  198. if len(parts) == 3 {
  199. companyID = parts[2]
  200. }
  201. }
  202. if companyID == "" || env.Endpoint == "" || alertHeader.ID == "" {
  203. logger.Warn("delivery envelope missing fields", "subject", m.Subject(), "company", companyID, "endpoint_present", env.Endpoint != "", "alert_id", alertHeader.ID)
  204. _ = m.Ack()
  205. return
  206. }
  207. // Build the FCM HTTP v1 message body once. Same shape
  208. // across attempts. M6 dedupe_count flow-through is
  209. // unchanged.
  210. notificationTitle := alertHeader.Title
  211. if alertHeader.DedupeCount > 1 {
  212. notificationTitle = fmt.Sprintf("%s (×%d)", alertHeader.Title, alertHeader.DedupeCount)
  213. }
  214. fcmBody, _ := json.Marshal(map[string]any{
  215. "message": map[string]any{
  216. "token": env.Endpoint,
  217. "notification": map[string]any{
  218. "title": notificationTitle,
  219. "body": alertHeader.Body,
  220. },
  221. "data": mergeData(alertHeader.Data, map[string]string{
  222. "company_id": companyID,
  223. "alert_id": alertHeader.ID,
  224. "severity": alertHeader.Severity,
  225. "category": alertHeader.Category,
  226. "dedupe_count": fmt.Sprintf("%d", alertHeader.DedupeCount),
  227. "individual_id": env.IndividualID,
  228. "locale": env.Locale,
  229. "deep_link": fmt.Sprintf("broadannounce://alert/%s", alertHeader.ID),
  230. }),
  231. "android": map[string]any{
  232. "priority": androidPriority(alertHeader.Severity),
  233. "notification": map[string]any{
  234. "sound": androidSound(alertHeader.Category, alertHeader.Severity),
  235. "channel_id": "alerts." + channelForSeverity(alertHeader.Severity),
  236. },
  237. },
  238. },
  239. })
  240. url := fakefcmdURL + "/v1/projects/fakefcmd/messages:send"
  241. // M9: track attempt start time for DLQ latency metric.
  242. firstAttemptTime := time.Now()
  243. // M8: retry loop. Each attempt: POST, persist a
  244. // deliveries row with status sent/failed and the
  245. // attempt counter, return the error to the helper.
  246. // On success, the loop exits early and we write one
  247. // final 'sent' row. On exhaustion, we write a DLQ
  248. // row and a final 'dlq' audit row.
  249. //
  250. // The ctx is the per-message context; we want a
  251. // per-attempt timeout, so we use a child ctx.
  252. var lastErr error
  253. var sent bool
  254. res := retry.Run(ctx, retryCfg, func(attemptCtx context.Context, attempt int) error {
  255. // Per-attempt timeout: 10s. The retry.Config
  256. // budget is the outer wall-clock cap.
  257. attemptCtx, cancel := context.WithTimeout(attemptCtx, 10*time.Second)
  258. defer cancel()
  259. req, _ := http.NewRequestWithContext(attemptCtx, "POST", url, bytes.NewReader(fcmBody))
  260. req.Header.Set("Content-Type", "application/json")
  261. resp, err := httpClient.Do(req)
  262. status := "failed"
  263. lastErrStr := ""
  264. if err != nil {
  265. lastErrStr = err.Error()
  266. } else {
  267. respBody, _ := io.ReadAll(resp.Body)
  268. _ = resp.Body.Close()
  269. if resp.StatusCode/100 == 2 {
  270. status = "sent"
  271. sent = true
  272. } else {
  273. lastErrStr = fmt.Sprintf("status %d: %s", resp.StatusCode, truncate(string(respBody), 200))
  274. }
  275. }
  276. // Per-attempt deliveries row. M1 pattern: one row
  277. // per attempt for the audit trail. The M8 status
  278. // enum is unchanged (pending|sent|failed|dlq).
  279. _, dbErr := pool.Exec(attemptCtx, `
  280. INSERT INTO deliveries
  281. (alert_id, company_id, individual_id, channel, target, status, attempts, last_error, payload, sent_at)
  282. VALUES ($1, $2, $3, $4, $5, $6, $7, NULLIF($8, ''), $9,
  283. CASE WHEN $6 = 'sent' THEN now() ELSE NULL END)
  284. `, alertHeader.ID, companyID, env.IndividualID, fcmChannel, env.Endpoint, status, attempt, lastErrStr, json.RawMessage(m.Data()))
  285. if dbErr != nil {
  286. logger.Warn("delivery row insert", "err", dbErr, "attempt", attempt)
  287. }
  288. // M9: record per-channel delivery attempt metric.
  289. if deliverdMetrics != nil {
  290. deliverdMetrics.DeliveryAttempts.WithLabelValues(fcmChannel, status).Inc()
  291. }
  292. if status == "sent" {
  293. logger.Info("delivery sent",
  294. "alert_id", alertHeader.ID,
  295. "company", companyID,
  296. "individual", env.IndividualID,
  297. "channel", fcmChannel,
  298. "attempt", attempt,
  299. )
  300. return nil
  301. }
  302. // M8: surface the last error to the retry helper
  303. // so it logs and (on exhaustion) gets written to
  304. // the DLQ row. We use a PermanentError for 4xx
  305. // (other than 408/429) so the retry helper
  306. // short-circuits — FCM's 4xx means the token is
  307. // bad, retrying won't help.
  308. if resp != nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != 408 && resp.StatusCode != 429 {
  309. logger.Warn("permanent fcm error",
  310. "alert_id", alertHeader.ID,
  311. "status", resp.StatusCode,
  312. "err", lastErrStr,
  313. "attempt", attempt,
  314. )
  315. lastErr = &retry.PermanentError{Err: fmt.Errorf("fcm permanent %s", lastErrStr)}
  316. return lastErr
  317. }
  318. logger.Warn("delivery attempt failed",
  319. "alert_id", alertHeader.ID,
  320. "company", companyID,
  321. "channel", fcmChannel,
  322. "attempt", attempt,
  323. "err", lastErrStr,
  324. )
  325. lastErr = fmt.Errorf("%s", lastErrStr)
  326. return lastErr
  327. })
  328. if sent {
  329. _ = m.Ack()
  330. return
  331. }
  332. // All attempts exhausted (or permanent error). Write
  333. // a DLQ row so an operator can replay. Use the
  334. // original NATS subject so replay doesn't need to
  335. // re-derive it from the payload.
  336. dlqID, dlqErr := dlq.Write(ctx, pool, dlq.Entry{
  337. AlertID: alertHeader.ID,
  338. CompanyID: companyID,
  339. IndividualID: env.IndividualID,
  340. Channel: fcmChannel,
  341. Target: env.Endpoint,
  342. OriginalSubject: m.Subject(),
  343. Attempts: res.Attempts,
  344. LastError: errString(lastErr),
  345. Payload: json.RawMessage(m.Data()),
  346. })
  347. if dlqErr != nil {
  348. // The DLQ write itself failed. Log loud; we
  349. // still Ack the NATS message (the original
  350. // delivery is lost, but the live `deliveries`
  351. // audit row has the failure recorded). An
  352. // operator alert can be wired in M9.
  353. logger.Error("dlq insert FAILED",
  354. "err", dlqErr,
  355. "alert_id", alertHeader.ID,
  356. "company", companyID,
  357. )
  358. } else {
  359. logger.Warn("delivery → DLQ",
  360. "dlq_id", dlqID,
  361. "alert_id", alertHeader.ID,
  362. "company", companyID,
  363. "channel", fcmChannel,
  364. "attempts", res.Attempts,
  365. "err", errString(lastErr),
  366. )
  367. // M9: record DLQ metric and latency.
  368. if deliverdMetrics != nil {
  369. deliverdMetrics.DLQTotal.WithLabelValues(fcmChannel).Inc()
  370. deliverdMetrics.DLQLatency.Observe(time.Since(firstAttemptTime).Seconds())
  371. deliverdMetrics.RetryAttempts.WithLabelValues(fcmChannel).Add(float64(res.Attempts))
  372. }
  373. }
  374. _ = m.Ack()
  375. }
  376. func mergeData(base, add map[string]string) map[string]string {
  377. if base == nil {
  378. base = map[string]string{}
  379. }
  380. for k, v := range add {
  381. if _, ok := base[k]; !ok {
  382. base[k] = v
  383. }
  384. }
  385. return base
  386. }
  387. func androidPriority(sev string) string {
  388. if sev == "critical" || sev == "inminent_colapse" {
  389. return "HIGH"
  390. }
  391. return "NORMAL"
  392. }
  393. // androidSound picks a sound file. SPEC §4 says the Android app
  394. // uses data.category to pick siren_<category>.ogg; the per-severity
  395. // override for inminent_colapse wins.
  396. func androidSound(category, sev string) string {
  397. if sev == "inminent_colapse" {
  398. return "klaxon"
  399. }
  400. if category == "" {
  401. return "default"
  402. }
  403. return "siren_" + category
  404. }
  405. func channelForSeverity(sev string) string {
  406. switch sev {
  407. case "critical":
  408. return "critical"
  409. case "inminent_colapse":
  410. return "imminent"
  411. case "warning":
  412. return "warning"
  413. default:
  414. return "info"
  415. }
  416. }
  417. func errString(err error) string {
  418. if err == nil {
  419. return ""
  420. }
  421. return err.Error()
  422. }
  423. // truncate keeps a status-line response body to N bytes
  424. // for the deliveries.last_error column. We never want a
  425. // multi-MB error body in the audit row.
  426. func truncate(s string, n int) string {
  427. if len(s) <= n {
  428. return s
  429. }
  430. return s[:n] + "…"
  431. }