handler.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. // Per-call Sources map — passed in, never mutates s.Dep.Sources. Avoids
  174. // concurrent map read/write between gRPC goroutines sharing Deps.
  175. sourceKey := src.CompanyID + ":" + src.SourceID
  176. callDeps := s.Dep // value copy; underlying pointers/maps are shared safely
  177. callDeps.Sources = map[string]pipeline.SourceConfig{sourceKey: *src}
  178. res := callDeps.Process(ctx, body, "" /* no HMAC for gRPC */)
  179. if !res.Accepted {
  180. code := errorCode(res.RejectReason)
  181. var retryAfter int32
  182. if res.RejectReason == "rate_limited_source" || res.RejectReason == "rate_limited_company" {
  183. if n, _ := parseRetryAfter(res.Detail); n > 0 {
  184. retryAfter = int32(n)
  185. }
  186. }
  187. return errorAck(alert.DedupeKey, code, res.Detail, retryAfter)
  188. }
  189. return &pbv1.Ack{
  190. AlertId: res.AlertID,
  191. DedupeKey: alert.DedupeKey,
  192. DedupeCount: res.DedupeCount,
  193. AcceptedAtMs: time.Now().UnixMilli(),
  194. Result: &pbv1.Ack_Ok{Ok: &pbv1.Ok{}},
  195. }
  196. }
  197. // alertToJSON converts a protobuf Alert to JSON bytes for the pipeline.
  198. func alertToJSON(a *pbv1.Alert) ([]byte, error) {
  199. m := map[string]any{
  200. "company_id": a.CompanyId,
  201. "source_id": a.SourceId,
  202. }
  203. if a.DedupeKey != "" {
  204. m["dedupe_key"] = a.DedupeKey
  205. }
  206. if a.Severity != "" {
  207. m["severity"] = a.Severity
  208. }
  209. if a.Category != "" {
  210. m["category"] = a.Category
  211. }
  212. if a.Title != "" {
  213. m["title"] = a.Title
  214. }
  215. if a.Body != "" {
  216. m["body"] = a.Body
  217. }
  218. if len(a.Data) > 0 {
  219. m["data"] = a.Data
  220. }
  221. if a.ClientTsMs > 0 {
  222. m["client_ts_ms"] = a.ClientTsMs
  223. }
  224. return json.Marshal(m)
  225. }
  226. func errorAck(dedupeKey string, code pbv1.Error_Code, message string, retryAfterMs int32) *pbv1.Ack {
  227. return &pbv1.Ack{
  228. DedupeKey: dedupeKey,
  229. Result: &pbv1.Ack_Error{
  230. Error: &pbv1.Error{
  231. Code: code,
  232. Message: message,
  233. RetryAfterMs: retryAfterMs,
  234. },
  235. },
  236. }
  237. }
  238. // errorCode maps pipeline reject reasons to gRPC Error codes.
  239. func errorCode(reason string) pbv1.Error_Code {
  240. switch reason {
  241. case "unknown_source", "bad_signature":
  242. return pbv1.Error_UNAUTHENTICATED
  243. case "rate_limited_source", "rate_limited_company":
  244. return pbv1.Error_RATE_LIMITED
  245. case "invalid", "invalid_json", "quarantined":
  246. return pbv1.Error_INVALID
  247. case "circuit_open", "broker_unavailable", "marshal_failed":
  248. return pbv1.Error_INTERNAL
  249. default:
  250. return pbv1.Error_UNKNOWN
  251. }
  252. }
  253. func parseRetryAfter(s string) (int, bool) {
  254. var n int
  255. var parsed bool
  256. for _, c := range s {
  257. if c >= '0' && c <= '9' {
  258. n = n*10 + int(c-'0')
  259. parsed = true
  260. } else {
  261. break
  262. }
  263. }
  264. return n, parsed
  265. }