handler.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package grpcserver
  2. import (
  3. "context"
  4. "encoding/json"
  5. "io"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. pbv1 "git3.techno-world.net/lrosales/broad-announce/gen/go/broadannounce/v1"
  10. "git3.techno-world.net/lrosales/broad-announce/internal/pipeline"
  11. )
  12. // Server implements broadannounce.v1.IngestServer.
  13. type Server struct {
  14. pbv1.UnimplementedIngestServer
  15. // Dep is the shared pipeline dependencies. All goroutines write to it
  16. // concurrently — it is safe for concurrent use.
  17. Dep pipeline.Deps
  18. MaxInflight int // max concurrent in-flight messages per stream (default 256)
  19. Logger interface{ Info(msg string, args ...any) }
  20. }
  21. // StreamAlerts is a bidirectional stream: client sends zero or more Alerts,
  22. // server sends exactly one Ack per Alert received.
  23. //
  24. // Bounded concurrency: each message runs in a goroutine controlled by a
  25. // semaphore channel of size MaxInflight. This is how we achieve 10k+/s on
  26. // a single stream — the bottleneck is the Redis dedupe + NATS publish (~2ms),
  27. // so 256-way concurrency gives us ~128k msg/s theoretical max.
  28. //
  29. // Backpressure: if the sem is full, we immediately send Error.RATE_LIMITED
  30. // without entering the pipeline. The client is expected to honour retry_after_ms.
  31. func (s *Server) StreamAlerts(stream pbv1.Ingest_StreamAlertsServer) error {
  32. ctx := stream.Context()
  33. // Authenticate the stream.
  34. src, err := authenticate(ctx, s.Dep.Sources)
  35. if err != nil {
  36. return err
  37. }
  38. sourceKey := src.CompanyID + ":" + src.SourceID
  39. // Per-stream semaphore: bounds concurrent processing to MaxInflight.
  40. if s.MaxInflight <= 0 {
  41. s.MaxInflight = 256
  42. }
  43. sem := make(chan struct{}, s.MaxInflight)
  44. // Per-stream ackCh: each goroutine sends its Ack here; the recv loop
  45. // forwards to the client. Buffer = MaxInflight so goroutines never block
  46. // on sending (only on the semaphore).
  47. ackCh := make(chan *pbv1.Ack, s.MaxInflight)
  48. // Track active goroutines for graceful shutdown.
  49. var wg sync.WaitGroup
  50. // streamErr holds the first non-nil error from goroutines or the recv loop.
  51. var streamErr atomic.Value // holds error
  52. setErr := func(err error) {
  53. if err != nil {
  54. streamErr.CompareAndSwap(nil, err)
  55. }
  56. }
  57. // Increment active-streams gauge.
  58. s.Dep.Metrics.StreamsActive.Add(1)
  59. defer s.Dep.Metrics.StreamsActive.Add(-1)
  60. // goroutine: receive loop — reads from client, dispatches to pipeline.
  61. go func() {
  62. for {
  63. alert, err := stream.Recv()
  64. if err == io.EOF {
  65. // Client called CloseSend. Drain in-flight, then exit.
  66. close(ackCh)
  67. wg.Wait()
  68. return
  69. }
  70. if err != nil {
  71. setErr(err)
  72. close(ackCh)
  73. wg.Wait()
  74. return
  75. }
  76. // Validate we have a non-empty Alert before spending goroutines.
  77. if alert.CompanyId == "" || alert.SourceId == "" {
  78. ackCh <- &pbv1.Ack{
  79. DedupeKey: alert.DedupeKey,
  80. Result: &pbv1.Ack_Error{
  81. Error: &pbv1.Error{
  82. Code: pbv1.Error_INVALID,
  83. Message: "company_id and source_id are required",
  84. },
  85. },
  86. }
  87. continue
  88. }
  89. // Per-stream rate limit (before entering the pipeline).
  90. // This is a fast rejection path that doesn't consume goroutines.
  91. rateLimitKey := "grpc_source:" + sourceKey
  92. allowed, retryAfter, _ := s.Dep.Limiter.Allow(ctx, rateLimitKey, src.RateLimitPerSec)
  93. if !allowed {
  94. s.Dep.Metrics.GRPCRateLimited.WithLabelValues(src.SourceID).Inc()
  95. s.Dep.Metrics.AlertsReceived.WithLabelValues("grpc", "rate_limited").Inc()
  96. ackCh <- &pbv1.Ack{
  97. AlertId: alert.DedupeKey,
  98. DedupeKey: alert.DedupeKey,
  99. Result: &pbv1.Ack_Error{
  100. Error: &pbv1.Error{
  101. Code: pbv1.Error_RATE_LIMITED,
  102. Message: "per-stream rate limit exceeded",
  103. RetryAfterMs: int32(retryAfter.Milliseconds()),
  104. },
  105. },
  106. }
  107. continue
  108. }
  109. // Acquire semaphore slot. If full, backpressure immediately.
  110. select {
  111. case sem <- struct{}{}:
  112. // Proceed.
  113. default:
  114. s.Dep.Metrics.GRPCRateLimited.WithLabelValues(src.SourceID).Inc()
  115. s.Dep.Metrics.AlertsReceived.WithLabelValues("grpc", "rate_limited").Inc()
  116. ackCh <- &pbv1.Ack{
  117. AlertId: alert.DedupeKey,
  118. DedupeKey: alert.DedupeKey,
  119. Result: &pbv1.Ack_Error{
  120. Error: &pbv1.Error{
  121. Code: pbv1.Error_RATE_LIMITED,
  122. Message: "in-flight capacity reached",
  123. RetryAfterMs: 5, // 5ms backoff, client should retry
  124. },
  125. },
  126. }
  127. continue
  128. }
  129. wg.Add(1)
  130. go func(alert *pbv1.Alert) {
  131. defer func() {
  132. <-sem
  133. wg.Done()
  134. }()
  135. start := time.Now()
  136. ack := s.processAlert(ctx, alert, src)
  137. // Record ack latency metric.
  138. s.Dep.Metrics.GRPCAckLatency.WithLabelValues(src.SourceID).Observe(
  139. time.Since(start).Seconds())
  140. // Send Ack to client. Non-blocking — if the channel is full the
  141. // recv loop has a backlog and we should not block the goroutine.
  142. select {
  143. case ackCh <- ack:
  144. default:
  145. // Channel full; log and drop.
  146. s.Dep.Logger.Info("grpc ack channel full, dropping", "alert_id", ack.AlertId)
  147. }
  148. }(alert)
  149. }
  150. }()
  151. // recv loop: forward Acks from goroutines to the client.
  152. // Also watches for goroutine errors.
  153. for ack := range ackCh {
  154. if err := stream.Send(ack); err != nil {
  155. return err
  156. }
  157. }
  158. // Check if the stream exited due to a goroutine error.
  159. if se := streamErr.Load().(error); se != nil {
  160. return se
  161. }
  162. return nil
  163. }
  164. // processAlert runs the shared pipeline on a single gRPC Alert and returns
  165. // the corresponding Ack. sig="" because gRPC auth is handled by authenticate()
  166. // before entering this function.
  167. func (s *Server) processAlert(ctx context.Context, alert *pbv1.Alert, src *pipeline.SourceConfig) *pbv1.Ack {
  168. body, err := alertToJSON(alert)
  169. if err != nil {
  170. return errorAck(alert.DedupeKey, pbv1.Error_INVALID, "marshal failed: "+err.Error(), 0)
  171. }
  172. // Override the Sources map for this call to use the authenticated source.
  173. // This ensures company_id/source_id from the API key match the alert body.
  174. sourceKey := src.CompanyID + ":" + src.SourceID
  175. origSources := s.Dep.Sources
  176. s.Dep.Sources = map[string]pipeline.SourceConfig{sourceKey: *src}
  177. res := s.Dep.Process(ctx, body, "" /* no HMAC for gRPC */)
  178. // Restore the original Sources map.
  179. s.Dep.Sources = origSources
  180. if !res.Accepted {
  181. code := errorCode(res.RejectReason)
  182. var retryAfter int32
  183. if res.RejectReason == "rate_limited_source" || res.RejectReason == "rate_limited_company" {
  184. if n, _ := parseRetryAfter(res.Detail); n > 0 {
  185. retryAfter = int32(n)
  186. }
  187. }
  188. return errorAck(alert.DedupeKey, code, res.Detail, retryAfter)
  189. }
  190. return &pbv1.Ack{
  191. AlertId: res.AlertID,
  192. DedupeKey: alert.DedupeKey,
  193. DedupeCount: res.DedupeCount,
  194. AcceptedAtMs: time.Now().UnixMilli(),
  195. Result: &pbv1.Ack_Ok{Ok: &pbv1.Ok{}},
  196. }
  197. }
  198. // alertToJSON converts a protobuf Alert to JSON bytes for the pipeline.
  199. func alertToJSON(a *pbv1.Alert) ([]byte, error) {
  200. m := map[string]any{
  201. "company_id": a.CompanyId,
  202. "source_id": a.SourceId,
  203. }
  204. if a.DedupeKey != "" {
  205. m["dedupe_key"] = a.DedupeKey
  206. }
  207. if a.Severity != "" {
  208. m["severity"] = a.Severity
  209. }
  210. if a.Category != "" {
  211. m["category"] = a.Category
  212. }
  213. if a.Title != "" {
  214. m["title"] = a.Title
  215. }
  216. if a.Body != "" {
  217. m["body"] = a.Body
  218. }
  219. if len(a.Data) > 0 {
  220. m["data"] = a.Data
  221. }
  222. if a.ClientTsMs > 0 {
  223. m["client_ts_ms"] = a.ClientTsMs
  224. }
  225. return json.Marshal(m)
  226. }
  227. func errorAck(dedupeKey string, code pbv1.Error_Code, message string, retryAfterMs int32) *pbv1.Ack {
  228. return &pbv1.Ack{
  229. DedupeKey: dedupeKey,
  230. Result: &pbv1.Ack_Error{
  231. Error: &pbv1.Error{
  232. Code: code,
  233. Message: message,
  234. RetryAfterMs: retryAfterMs,
  235. },
  236. },
  237. }
  238. }
  239. // errorCode maps pipeline reject reasons to gRPC Error codes.
  240. func errorCode(reason string) pbv1.Error_Code {
  241. switch reason {
  242. case "unknown_source", "bad_signature":
  243. return pbv1.Error_UNAUTHENTICATED
  244. case "rate_limited_source", "rate_limited_company":
  245. return pbv1.Error_RATE_LIMITED
  246. case "invalid", "invalid_json", "quarantined":
  247. return pbv1.Error_INVALID
  248. case "circuit_open", "broker_unavailable", "marshal_failed":
  249. return pbv1.Error_INTERNAL
  250. default:
  251. return pbv1.Error_UNKNOWN
  252. }
  253. }
  254. func parseRetryAfter(s string) (int, bool) {
  255. var n int
  256. var parsed bool
  257. for _, c := range s {
  258. if c >= '0' && c <= '9' {
  259. n = n*10 + int(c-'0')
  260. parsed = true
  261. } else {
  262. break
  263. }
  264. }
  265. return n, parsed
  266. }