main.go 14 KB

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