process.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // process.go is the shared alert-processing pipeline used by
  2. // both the HTTP handler (cmd/ingestd/http.go) and the MQTT
  3. // subscriber (cmd/ingestd/mqtt.go). It does the M0→M4 SPEC §22
  4. // work in one place: parse → validate → look up source → HMAC
  5. // verify → rate-limit (per-source, per-company) → dedupe → stamp
  6. // → publish to NATS → return a result struct the caller maps
  7. // to its own transport-level response.
  8. //
  9. // The function is pure (no global state, no transport types).
  10. // It returns Result{Accepted/Rejected/Error + reason + alert_id
  11. // + dedupe_count} so the HTTP handler can map to a status code
  12. // and the MQTT handler can map to a log line.
  13. package main
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "log/slog"
  19. "strconv"
  20. "time"
  21. "git3.techno-world.net/lrosales/broad-announce/internal/alert"
  22. "git3.techno-world.net/lrosales/broad-announce/internal/broker"
  23. "git3.techno-world.net/lrosales/broad-announce/internal/dedupe"
  24. "git3.techno-world.net/lrosales/broad-announce/internal/observability"
  25. "git3.techno-world.net/lrosales/broad-announce/internal/ratelimit"
  26. "git3.techno-world.net/lrosales/broad-announce/internal/tailhub"
  27. "github.com/nats-io/nats.go"
  28. )
  29. // Result is the outcome of a ProcessAlert call. The caller
  30. // (HTTP/MQTT) maps it to its transport's response shape.
  31. type Result struct {
  32. // Accepted is true if the alert passed all checks and was
  33. // published to NATS.
  34. Accepted bool
  35. // AlertID is the server-assigned id (empty on error paths).
  36. AlertID string
  37. // DedupeCount is the count returned by the dedupe layer.
  38. DedupeCount uint32
  39. // IsNew is true for the first alert in a dedupe window.
  40. IsNew bool
  41. // RejectReason is the SPEC §22 / auth reason; one of:
  42. // "payload_too_large", "bad_request", "invalid_json",
  43. // "invalid", "unknown_source", "bad_signature",
  44. // "rate_limited_source", "rate_limited_company",
  45. // "marshal_failed", "broker_unavailable"
  46. RejectReason string
  47. // HTTPStatus is the suggested HTTP status code (0 for
  48. // accepted / 202).
  49. HTTPStatus int
  50. // Detail is the free-form string the caller can show in
  51. // a response body or a log message.
  52. Detail string
  53. }
  54. // Accept is the canonical "ok" result.
  55. func Accept(id string, count uint32, isNew bool) Result {
  56. return Result{Accepted: true, AlertID: id, DedupeCount: count, IsNew: isNew, HTTPStatus: 202}
  57. }
  58. // Reject is the canonical "no" result.
  59. func Reject(reason string, status int, detail string) Result {
  60. return Result{RejectReason: reason, HTTPStatus: status, Detail: detail}
  61. }
  62. // processDeps is the process-pipeline dependency set. Smaller
  63. // than httpDeps — no HTTP-specific fields. Both httpDeps and
  64. // the MQTT subscriber construct one and call ProcessAlert.
  65. type processDeps struct {
  66. Logger *slog.Logger
  67. Metrics *observability.IngestdMetrics
  68. Limiter *ratelimit.Limiter
  69. Deduper *dedupe.Deduper
  70. JetStream natsPublisher
  71. // Sources is the (company_id, source_id) → SourceConfig map.
  72. // M0 reads it from env; M2 from Postgres. The MQTT subscriber
  73. // uses the same map keyed on the topic-parsed (co, src).
  74. Sources map[string]SourceConfig
  75. // Per-company default rate cap. HTTP and MQTT use the same
  76. // constant; once the per-company cap lives in DB, both
  77. // transports read it.
  78. CompanyRatePerSec int
  79. // Tail is an optional M5 live-tail hub. When non-nil, every
  80. // accepted alert is also published to in-process tail
  81. // subscribers. nil is fine (HTTP/MQTT tests don't need it).
  82. Tail *tailhub.Hub
  83. // Transport is the per-process transport label used in
  84. // structured log lines ("http" | "mqtt" | "ws"). The MQTT
  85. // path overrides this on the receiver's scoped copy.
  86. Transport string
  87. // Now is overridable in tests.
  88. Now func() time.Time
  89. // MaxSeen is the M6 per-source monotonic max tracker for
  90. // dedupe_count. processDeps owns one so all transports
  91. // (HTTP, MQTT, WS) share the same in-process state and
  92. // the same max-observed gauge.
  93. MaxSeen *observability.MaxSeen
  94. }
  95. // ProcessAlert runs the full SPEC §22 protection chain on one
  96. // alert body. It is the single source of truth for the ingest
  97. // pipeline; both the HTTP POST handler and the MQTT subscriber
  98. // call it.
  99. //
  100. // Layer order (matches SPEC §22):
  101. // 1. payload-size cap (caller does this — http.go via
  102. // MaxBytesReader; mqtt.go via the
  103. // broker-side max-inflight setting)
  104. // 3. per-source rate limit
  105. // 4. per-company rate limit
  106. // 5. schema validate
  107. // 5b. parse JSON
  108. // (auth) HMAC verify — see verifyHMAC
  109. // 5c. dedupe
  110. // publish to NATS
  111. func (d *processDeps) ProcessAlert(ctx context.Context, body []byte, sigHeader string) Result {
  112. now := d.now()
  113. // 5. Parse + validate. We treat any parse failure as invalid.
  114. var a alert.Alert
  115. if err := json.Unmarshal(body, &a); err != nil {
  116. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  117. return Reject("invalid_json", 400, err.Error())
  118. }
  119. if err := a.Validate(); err != nil {
  120. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  121. return Reject("invalid", 400, err.Error())
  122. }
  123. // Look up source. M0: in-memory map. M2: DB.
  124. src, ok := d.Sources[a.CompanyID+":"+a.SourceID]
  125. if !ok {
  126. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  127. return Reject("unknown_source", 401,
  128. fmt.Sprintf("no such source %s/%s", a.CompanyID, a.SourceID))
  129. }
  130. // Auth. Stripe-style: X-BA-Signature: t=<unix>,v1=<hex>.
  131. // For HTTP it's a header; for MQTT it's a top-level field
  132. // on the envelope — both call sites pass the same string.
  133. if !verifyHMAC(sigHeader, src.HMACSecret, body, now) {
  134. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  135. return Reject("bad_signature", 401, "")
  136. }
  137. // M6: Dedupe BEFORE rate limit. A duplicate (isNew=false)
  138. // is a Redis INCR + JSON marshal + NATS publish — it does
  139. // not warrant burning a rate-limit token. The rate limit
  140. // exists to backpressure "new alert" volume; the dedupe
  141. // itself is the canonical "do less work for repeats"
  142. // mechanism. We only burn a token on the first arrival
  143. // in a sliding window; the next 999 dupes pass through
  144. // the rate limit gates for free, the recipient sees one
  145. // consolidated message with `(×N)` appended.
  146. isNew, count, err := d.Deduper.Check(ctx, a.SourceID, a.DedupeKey)
  147. if err != nil {
  148. d.Logger.Warn("dedupe redis error (failing open)", "err", err)
  149. isNew, count = true, 1
  150. }
  151. if !isNew {
  152. // M6 metrics: tick the per-source collapse counter and
  153. // bump the max-observed gauge if this hit set a new
  154. // peak. We use a tiny in-process max tracker (Prom's
  155. // Gauge doesn't expose Get() — the canonical pattern
  156. // is to read via .Gauges() and pick out the value, but
  157. // that's a 2-step write+read; cleaner to just remember
  158. // the max in our own map and Set the gauge on growth).
  159. d.Metrics.DedupeCollapsed.WithLabelValues(a.SourceID).Inc()
  160. d.MaxSeen.RecordAndExport(a.SourceID, count,
  161. func(s string, v float64) {
  162. d.Metrics.DedupeCountMax.WithLabelValues(s).Set(v)
  163. })
  164. }
  165. // 3. Per-source rate limit (only charged for new alerts).
  166. if isNew {
  167. if ok, ttl, err := d.Limiter.Allow(ctx, "source:"+a.CompanyID+":"+a.SourceID, src.RateLimitPerSec); err != nil {
  168. d.Logger.Warn("ratelimit redis error (failing open)", "err", err, "scope", "source")
  169. } else if !ok {
  170. d.Metrics.AlertsReceived.WithLabelValues("rate_limited").Inc()
  171. d.Metrics.RateLimitHits.WithLabelValues("source").Inc()
  172. _ = ttl
  173. return Reject("rate_limited_source", 429, strconv.Itoa(int(ttl.Seconds())))
  174. }
  175. }
  176. // 4. Per-company rate limit (only charged for new alerts).
  177. if isNew {
  178. if ok, ttl, _ := d.Limiter.Allow(ctx, "company:"+a.CompanyID, d.CompanyRatePerSec); !ok {
  179. d.Metrics.AlertsReceived.WithLabelValues("rate_limited").Inc()
  180. d.Metrics.RateLimitHits.WithLabelValues("company").Inc()
  181. _ = ttl
  182. return Reject("rate_limited_company", 429, strconv.Itoa(int(ttl.Seconds())))
  183. }
  184. }
  185. // Stamp server-side fields.
  186. a.ID = alert.NewID()
  187. a.ReceivedAt = now.UTC()
  188. a.DedupeCount = count
  189. // Publish to NATS.
  190. subject := broker.AlertsSubject(a.CompanyID)
  191. payload, err := json.Marshal(a)
  192. if err != nil {
  193. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  194. return Reject("marshal_failed", 500, err.Error())
  195. }
  196. start := time.Now()
  197. if err := d.JetStream.PublishAsync(subject, payload); err != nil {
  198. // Circuit breaker (M9) wraps this. For M0 we just fail loud.
  199. d.Metrics.AlertsReceived.WithLabelValues("circuit_open").Inc()
  200. return Reject("broker_unavailable", 503, err.Error())
  201. }
  202. d.Metrics.PublishLatency.Observe(time.Since(start).Seconds())
  203. d.Metrics.PayloadBytes.Observe(float64(len(payload)))
  204. if isNew {
  205. d.Metrics.AlertsReceived.WithLabelValues("accepted").Inc()
  206. } else {
  207. d.Metrics.AlertsReceived.WithLabelValues("deduped").Inc()
  208. }
  209. d.Logger.Info("alert accepted",
  210. "alert_id", a.ID,
  211. "company_id", a.CompanyID,
  212. "source_id", a.SourceID,
  213. "severity", string(a.Severity),
  214. "transport", d.Transport,
  215. "dedupe_count", count,
  216. )
  217. // M5: fan out to the live-tail hub (if configured). This
  218. // is best-effort and never blocks the producer — the hub's
  219. // Publish drops on slow consumers.
  220. if d.Tail != nil {
  221. ev := tailhub.FromAlert(&a, d.Transport)
  222. d.Tail.Publish(ev)
  223. }
  224. return Accept(a.ID, count, isNew)
  225. }
  226. func (d *processDeps) now() time.Time {
  227. if d.Now != nil {
  228. return d.Now()
  229. }
  230. return time.Now()
  231. }
  232. // natsPublisher is the minimal NATS interface. The HTTP and
  233. // MQTT paths share it; tests can swap in a fake.
  234. type natsPublisher interface {
  235. PublishAsync(subj string, data []byte) error
  236. }
  237. // jsPublisher adapts a nats.JetStreamContext to the natsPublisher interface.
  238. type jsPublisher struct {
  239. js nats.JetStreamContext
  240. }
  241. func (j *jsPublisher) PublishAsync(subj string, data []byte) error {
  242. _, err := j.js.PublishAsync(subj, data)
  243. return err
  244. }
  245. // newNatsPublisher is the constructor used by main.
  246. func newNatsPublisher(js nats.JetStreamContext) natsPublisher {
  247. return &jsPublisher{js: js}
  248. }