handler.go 8.0 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. ackCh <- &pbv1.Ack{
  96. AlertId: alert.DedupeKey,
  97. DedupeKey: alert.DedupeKey,
  98. Result: &pbv1.Ack_Error{
  99. Error: &pbv1.Error{
  100. Code: pbv1.Error_RATE_LIMITED,
  101. Message: "per-stream rate limit exceeded",
  102. RetryAfterMs: int32(retryAfter.Milliseconds()),
  103. },
  104. },
  105. }
  106. continue
  107. }
  108. // Acquire semaphore slot. If full, backpressure immediately.
  109. select {
  110. case sem <- struct{}{}:
  111. // Proceed.
  112. default:
  113. s.Dep.Metrics.GRPCRateLimited.WithLabelValues(src.SourceID).Inc()
  114. ackCh <- &pbv1.Ack{
  115. AlertId: alert.DedupeKey,
  116. DedupeKey: alert.DedupeKey,
  117. Result: &pbv1.Ack_Error{
  118. Error: &pbv1.Error{
  119. Code: pbv1.Error_RATE_LIMITED,
  120. Message: "in-flight capacity reached",
  121. RetryAfterMs: 5, // 5ms backoff, client should retry
  122. },
  123. },
  124. }
  125. continue
  126. }
  127. wg.Add(1)
  128. go func(alert *pbv1.Alert) {
  129. defer func() {
  130. <-sem
  131. wg.Done()
  132. }()
  133. start := time.Now()
  134. ack := s.processAlert(ctx, alert, src)
  135. // Record ack latency metric.
  136. s.Dep.Metrics.GRPCAckLatency.WithLabelValues(src.SourceID).Observe(
  137. time.Since(start).Seconds())
  138. // Send Ack to client. Non-blocking — if the channel is full the
  139. // recv loop has a backlog and we should not block the goroutine.
  140. select {
  141. case ackCh <- ack:
  142. default:
  143. // Channel full; log and drop.
  144. s.Dep.Logger.Info("grpc ack channel full, dropping", "alert_id", ack.AlertId)
  145. }
  146. }(alert)
  147. }
  148. }()
  149. // recv loop: forward Acks from goroutines to the client.
  150. // Also watches for goroutine errors.
  151. for ack := range ackCh {
  152. if err := stream.Send(ack); err != nil {
  153. return err
  154. }
  155. }
  156. // Check if the stream exited due to a goroutine error.
  157. if se := streamErr.Load().(error); se != nil {
  158. return se
  159. }
  160. return nil
  161. }
  162. // processAlert runs the shared pipeline on a single gRPC Alert and returns
  163. // the corresponding Ack. sig="" because gRPC auth is handled by authenticate()
  164. // before entering this function.
  165. func (s *Server) processAlert(ctx context.Context, alert *pbv1.Alert, src *pipeline.SourceConfig) *pbv1.Ack {
  166. body, err := alertToJSON(alert)
  167. if err != nil {
  168. return errorAck(alert.DedupeKey, pbv1.Error_INVALID, "marshal failed: "+err.Error(), 0)
  169. }
  170. // Override the Sources map for this call to use the authenticated source.
  171. // This ensures company_id/source_id from the API key match the alert body.
  172. sourceKey := src.CompanyID + ":" + src.SourceID
  173. origSources := s.Dep.Sources
  174. s.Dep.Sources = map[string]pipeline.SourceConfig{sourceKey: *src}
  175. res := s.Dep.Process(ctx, body, "" /* no HMAC for gRPC */)
  176. // Restore the original Sources map.
  177. s.Dep.Sources = origSources
  178. if !res.Accepted {
  179. code := errorCode(res.RejectReason)
  180. var retryAfter int32
  181. if res.RejectReason == "rate_limited_source" || res.RejectReason == "rate_limited_company" {
  182. if n, _ := parseRetryAfter(res.Detail); n > 0 {
  183. retryAfter = int32(n)
  184. }
  185. }
  186. return errorAck(alert.DedupeKey, code, res.Detail, retryAfter)
  187. }
  188. return &pbv1.Ack{
  189. AlertId: res.AlertID,
  190. DedupeKey: alert.DedupeKey,
  191. DedupeCount: res.DedupeCount,
  192. AcceptedAtMs: time.Now().UnixMilli(),
  193. Result: &pbv1.Ack_Ok{Ok: &pbv1.Ok{}},
  194. }
  195. }
  196. // alertToJSON converts a protobuf Alert to JSON bytes for the pipeline.
  197. func alertToJSON(a *pbv1.Alert) ([]byte, error) {
  198. m := map[string]any{
  199. "company_id": a.CompanyId,
  200. "source_id": a.SourceId,
  201. }
  202. if a.DedupeKey != "" {
  203. m["dedupe_key"] = a.DedupeKey
  204. }
  205. if a.Severity != "" {
  206. m["severity"] = a.Severity
  207. }
  208. if a.Category != "" {
  209. m["category"] = a.Category
  210. }
  211. if a.Title != "" {
  212. m["title"] = a.Title
  213. }
  214. if a.Body != "" {
  215. m["body"] = a.Body
  216. }
  217. if len(a.Data) > 0 {
  218. m["data"] = a.Data
  219. }
  220. if a.ClientTsMs > 0 {
  221. m["client_ts_ms"] = a.ClientTsMs
  222. }
  223. return json.Marshal(m)
  224. }
  225. func errorAck(dedupeKey string, code pbv1.Error_Code, message string, retryAfterMs int32) *pbv1.Ack {
  226. return &pbv1.Ack{
  227. DedupeKey: dedupeKey,
  228. Result: &pbv1.Ack_Error{
  229. Error: &pbv1.Error{
  230. Code: code,
  231. Message: message,
  232. RetryAfterMs: retryAfterMs,
  233. },
  234. },
  235. }
  236. }
  237. // errorCode maps pipeline reject reasons to gRPC Error codes.
  238. func errorCode(reason string) pbv1.Error_Code {
  239. switch reason {
  240. case "unknown_source", "bad_signature":
  241. return pbv1.Error_UNAUTHENTICATED
  242. case "rate_limited_source", "rate_limited_company":
  243. return pbv1.Error_RATE_LIMITED
  244. case "invalid", "invalid_json", "quarantined":
  245. return pbv1.Error_INVALID
  246. case "circuit_open", "broker_unavailable", "marshal_failed":
  247. return pbv1.Error_INTERNAL
  248. default:
  249. return pbv1.Error_UNKNOWN
  250. }
  251. }
  252. func parseRetryAfter(s string) (int, bool) {
  253. var n int
  254. var parsed bool
  255. for _, c := range s {
  256. if c >= '0' && c <= '9' {
  257. n = n*10 + int(c-'0')
  258. parsed = true
  259. } else {
  260. break
  261. }
  262. }
  263. return n, parsed
  264. }