process.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. }
  90. // ProcessAlert runs the full SPEC §22 protection chain on one
  91. // alert body. It is the single source of truth for the ingest
  92. // pipeline; both the HTTP POST handler and the MQTT subscriber
  93. // call it.
  94. //
  95. // Layer order (matches SPEC §22):
  96. // 1. payload-size cap (caller does this — http.go via
  97. // MaxBytesReader; mqtt.go via the
  98. // broker-side max-inflight setting)
  99. // 3. per-source rate limit
  100. // 4. per-company rate limit
  101. // 5. schema validate
  102. // 5b. parse JSON
  103. // (auth) HMAC verify — see verifyHMAC
  104. // 5c. dedupe
  105. // publish to NATS
  106. func (d *processDeps) ProcessAlert(ctx context.Context, body []byte, sigHeader string) Result {
  107. now := d.now()
  108. // 5. Parse + validate. We treat any parse failure as invalid.
  109. var a alert.Alert
  110. if err := json.Unmarshal(body, &a); err != nil {
  111. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  112. return Reject("invalid_json", 400, err.Error())
  113. }
  114. if err := a.Validate(); err != nil {
  115. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  116. return Reject("invalid", 400, err.Error())
  117. }
  118. // Look up source. M0: in-memory map. M2: DB.
  119. src, ok := d.Sources[a.CompanyID+":"+a.SourceID]
  120. if !ok {
  121. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  122. return Reject("unknown_source", 401,
  123. fmt.Sprintf("no such source %s/%s", a.CompanyID, a.SourceID))
  124. }
  125. // Auth. Stripe-style: X-BA-Signature: t=<unix>,v1=<hex>.
  126. // For HTTP it's a header; for MQTT it's a top-level field
  127. // on the envelope — both call sites pass the same string.
  128. if !verifyHMAC(sigHeader, src.HMACSecret, body, now) {
  129. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  130. return Reject("bad_signature", 401, "")
  131. }
  132. // 3. Per-source rate limit.
  133. if ok, ttl, err := d.Limiter.Allow(ctx, "source:"+a.CompanyID+":"+a.SourceID, src.RateLimitPerSec); err != nil {
  134. d.Logger.Warn("ratelimit redis error (failing open)", "err", err, "scope", "source")
  135. } else if !ok {
  136. d.Metrics.AlertsReceived.WithLabelValues("rate_limited").Inc()
  137. d.Metrics.RateLimitHits.WithLabelValues("source").Inc()
  138. _ = ttl
  139. return Reject("rate_limited_source", 429, strconv.Itoa(int(ttl.Seconds())))
  140. }
  141. // 4. Per-company rate limit.
  142. if ok, ttl, _ := d.Limiter.Allow(ctx, "company:"+a.CompanyID, d.CompanyRatePerSec); !ok {
  143. d.Metrics.AlertsReceived.WithLabelValues("rate_limited").Inc()
  144. d.Metrics.RateLimitHits.WithLabelValues("company").Inc()
  145. _ = ttl
  146. return Reject("rate_limited_company", 429, strconv.Itoa(int(ttl.Seconds())))
  147. }
  148. // 5c. Dedupe.
  149. isNew, count, err := d.Deduper.Check(ctx, a.SourceID, a.DedupeKey)
  150. if err != nil {
  151. d.Logger.Warn("dedupe redis error (failing open)", "err", err)
  152. isNew, count = true, 1
  153. }
  154. // Stamp server-side fields.
  155. a.ID = alert.NewID()
  156. a.ReceivedAt = now.UTC()
  157. a.DedupeCount = count
  158. // Publish to NATS.
  159. subject := broker.AlertsSubject(a.CompanyID)
  160. payload, err := json.Marshal(a)
  161. if err != nil {
  162. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  163. return Reject("marshal_failed", 500, err.Error())
  164. }
  165. start := time.Now()
  166. if err := d.JetStream.PublishAsync(subject, payload); err != nil {
  167. // Circuit breaker (M9) wraps this. For M0 we just fail loud.
  168. d.Metrics.AlertsReceived.WithLabelValues("circuit_open").Inc()
  169. return Reject("broker_unavailable", 503, err.Error())
  170. }
  171. d.Metrics.PublishLatency.Observe(time.Since(start).Seconds())
  172. d.Metrics.PayloadBytes.Observe(float64(len(payload)))
  173. if isNew {
  174. d.Metrics.AlertsReceived.WithLabelValues("accepted").Inc()
  175. } else {
  176. d.Metrics.AlertsReceived.WithLabelValues("deduped").Inc()
  177. }
  178. d.Logger.Info("alert accepted",
  179. "alert_id", a.ID,
  180. "company_id", a.CompanyID,
  181. "source_id", a.SourceID,
  182. "severity", string(a.Severity),
  183. "transport", d.Transport,
  184. "dedupe_count", count,
  185. )
  186. // M5: fan out to the live-tail hub (if configured). This
  187. // is best-effort and never blocks the producer — the hub's
  188. // Publish drops on slow consumers.
  189. if d.Tail != nil {
  190. ev := tailhub.FromAlert(&a, d.Transport)
  191. d.Tail.Publish(ev)
  192. }
  193. return Accept(a.ID, count, isNew)
  194. }
  195. func (d *processDeps) now() time.Time {
  196. if d.Now != nil {
  197. return d.Now()
  198. }
  199. return time.Now()
  200. }
  201. // natsPublisher is the minimal NATS interface. The HTTP and
  202. // MQTT paths share it; tests can swap in a fake.
  203. type natsPublisher interface {
  204. PublishAsync(subj string, data []byte) error
  205. }
  206. // jsPublisher adapts a nats.JetStreamContext to the natsPublisher interface.
  207. type jsPublisher struct {
  208. js nats.JetStreamContext
  209. }
  210. func (j *jsPublisher) PublishAsync(subj string, data []byte) error {
  211. _, err := j.js.PublishAsync(subj, data)
  212. return err
  213. }
  214. // newNatsPublisher is the constructor used by main.
  215. func newNatsPublisher(js nats.JetStreamContext) natsPublisher {
  216. return &jsPublisher{js: js}
  217. }