handler.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. // atomic.Value.Load returns nil if nothing was ever stored; the
  160. // type assertion nil.(error) panics with "interface conversion:
  161. // interface is nil, not error", so we must guard with a nil check
  162. // and a type assertion that reports ok.
  163. if v := streamErr.Load(); v != nil {
  164. if se, ok := v.(error); ok && se != nil {
  165. return se
  166. }
  167. }
  168. return nil
  169. }
  170. // processAlert runs the shared pipeline on a single gRPC Alert and returns
  171. // the corresponding Ack. sig="" because gRPC auth is handled by authenticate()
  172. // before entering this function.
  173. func (s *Server) processAlert(ctx context.Context, alert *pbv1.Alert, src *pipeline.SourceConfig) *pbv1.Ack {
  174. body, err := alertToJSON(alert)
  175. if err != nil {
  176. return errorAck(alert.DedupeKey, pbv1.Error_INVALID, "marshal failed: "+err.Error(), 0)
  177. }
  178. // Override the Sources map for this call to use the authenticated source.
  179. // Per-call Sources map — passed in, never mutates s.Dep.Sources. Avoids
  180. // concurrent map read/write between gRPC goroutines sharing Deps.
  181. sourceKey := src.CompanyID + ":" + src.SourceID
  182. callDeps := s.Dep // value copy; underlying pointers/maps are shared safely
  183. callDeps.Sources = map[string]pipeline.SourceConfig{sourceKey: *src}
  184. res := callDeps.Process(ctx, body, "" /* no HMAC for gRPC */)
  185. if !res.Accepted {
  186. code := errorCode(res.RejectReason)
  187. var retryAfter int32
  188. if res.RejectReason == "rate_limited_source" || res.RejectReason == "rate_limited_company" {
  189. if n, _ := parseRetryAfter(res.Detail); n > 0 {
  190. retryAfter = int32(n)
  191. }
  192. }
  193. return errorAck(alert.DedupeKey, code, res.Detail, retryAfter)
  194. }
  195. return &pbv1.Ack{
  196. AlertId: res.AlertID,
  197. DedupeKey: alert.DedupeKey,
  198. DedupeCount: res.DedupeCount,
  199. AcceptedAtMs: time.Now().UnixMilli(),
  200. Result: &pbv1.Ack_Ok{Ok: &pbv1.Ok{}},
  201. }
  202. }
  203. // alertToJSON converts a protobuf Alert to JSON bytes for the pipeline.
  204. func alertToJSON(a *pbv1.Alert) ([]byte, error) {
  205. m := map[string]any{
  206. "company_id": a.CompanyId,
  207. "source_id": a.SourceId,
  208. }
  209. if a.DedupeKey != "" {
  210. m["dedupe_key"] = a.DedupeKey
  211. }
  212. if a.Severity != "" {
  213. m["severity"] = a.Severity
  214. }
  215. if a.Category != "" {
  216. m["category"] = a.Category
  217. }
  218. if a.Title != "" {
  219. m["title"] = a.Title
  220. }
  221. if a.Body != "" {
  222. m["body"] = a.Body
  223. }
  224. if len(a.Data) > 0 {
  225. m["data"] = a.Data
  226. }
  227. if a.ClientTsMs > 0 {
  228. m["client_ts_ms"] = a.ClientTsMs
  229. }
  230. return json.Marshal(m)
  231. }
  232. func errorAck(dedupeKey string, code pbv1.Error_Code, message string, retryAfterMs int32) *pbv1.Ack {
  233. return &pbv1.Ack{
  234. DedupeKey: dedupeKey,
  235. Result: &pbv1.Ack_Error{
  236. Error: &pbv1.Error{
  237. Code: code,
  238. Message: message,
  239. RetryAfterMs: retryAfterMs,
  240. },
  241. },
  242. }
  243. }
  244. // errorCode maps pipeline reject reasons to gRPC Error codes.
  245. func errorCode(reason string) pbv1.Error_Code {
  246. switch reason {
  247. case "unknown_source", "bad_signature":
  248. return pbv1.Error_UNAUTHENTICATED
  249. case "rate_limited_source", "rate_limited_company":
  250. return pbv1.Error_RATE_LIMITED
  251. case "invalid", "invalid_json", "quarantined":
  252. return pbv1.Error_INVALID
  253. case "circuit_open", "broker_unavailable", "marshal_failed":
  254. return pbv1.Error_INTERNAL
  255. default:
  256. return pbv1.Error_UNKNOWN
  257. }
  258. }
  259. func parseRetryAfter(s string) (int, bool) {
  260. var n int
  261. var parsed bool
  262. for _, c := range s {
  263. if c >= '0' && c <= '9' {
  264. n = n*10 + int(c-'0')
  265. parsed = true
  266. } else {
  267. break
  268. }
  269. }
  270. return n, parsed
  271. }