handler.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. //
  62. // Shutdown order is critical: we MUST wait for in-flight workers (wg.Wait)
  63. // BEFORE closing ackCh, otherwise any worker that finishes processAlert
  64. // after close will panic with "send on closed channel" — even a select
  65. // with a default branch does NOT save you from sending on a closed channel
  66. // in Go; the default branch only protects a full buffer, not a closed one.
  67. //
  68. // After wg.Wait() returns, no goroutine can possibly send to ackCh, so
  69. // close(ackCh) is safe. The outer recv loop ranges ackCh, drains the
  70. // remaining buffered acks, and exits when the channel closes.
  71. go func() {
  72. for {
  73. alert, err := stream.Recv()
  74. if err == io.EOF {
  75. // Client called CloseSend. Drain workers first, then close.
  76. wg.Wait()
  77. close(ackCh)
  78. return
  79. }
  80. if err != nil {
  81. setErr(err)
  82. wg.Wait()
  83. close(ackCh)
  84. return
  85. }
  86. // Validate we have a non-empty Alert before spending goroutines.
  87. if alert.CompanyId == "" || alert.SourceId == "" {
  88. ackCh <- &pbv1.Ack{
  89. DedupeKey: alert.DedupeKey,
  90. Result: &pbv1.Ack_Error{
  91. Error: &pbv1.Error{
  92. Code: pbv1.Error_INVALID,
  93. Message: "company_id and source_id are required",
  94. },
  95. },
  96. }
  97. continue
  98. }
  99. // Per-stream rate limit (before entering the pipeline).
  100. // This is a fast rejection path that doesn't consume goroutines.
  101. rateLimitKey := "grpc_source:" + sourceKey
  102. allowed, retryAfter, _ := s.Dep.Limiter.Allow(ctx, rateLimitKey, src.RateLimitPerSec)
  103. if !allowed {
  104. s.Dep.Metrics.GRPCRateLimited.WithLabelValues(src.SourceID).Inc()
  105. s.Dep.Metrics.AlertsReceived.WithLabelValues("grpc", "rate_limited").Inc()
  106. ackCh <- &pbv1.Ack{
  107. AlertId: alert.DedupeKey,
  108. DedupeKey: alert.DedupeKey,
  109. Result: &pbv1.Ack_Error{
  110. Error: &pbv1.Error{
  111. Code: pbv1.Error_RATE_LIMITED,
  112. Message: "per-stream rate limit exceeded",
  113. RetryAfterMs: int32(retryAfter.Milliseconds()),
  114. },
  115. },
  116. }
  117. continue
  118. }
  119. // Acquire semaphore slot. If full, backpressure immediately.
  120. select {
  121. case sem <- struct{}{}:
  122. // Proceed.
  123. default:
  124. s.Dep.Metrics.GRPCRateLimited.WithLabelValues(src.SourceID).Inc()
  125. s.Dep.Metrics.AlertsReceived.WithLabelValues("grpc", "rate_limited").Inc()
  126. ackCh <- &pbv1.Ack{
  127. AlertId: alert.DedupeKey,
  128. DedupeKey: alert.DedupeKey,
  129. Result: &pbv1.Ack_Error{
  130. Error: &pbv1.Error{
  131. Code: pbv1.Error_RATE_LIMITED,
  132. Message: "in-flight capacity reached",
  133. RetryAfterMs: 5, // 5ms backoff, client should retry
  134. },
  135. },
  136. }
  137. continue
  138. }
  139. wg.Add(1)
  140. go func(alert *pbv1.Alert) {
  141. defer func() {
  142. <-sem
  143. wg.Done()
  144. }()
  145. start := time.Now()
  146. ack := s.processAlert(ctx, alert, src)
  147. // Record ack latency metric.
  148. s.Dep.Metrics.GRPCAckLatency.WithLabelValues(src.SourceID).Observe(
  149. time.Since(start).Seconds())
  150. // Send Ack to client. Non-blocking — if the channel is full the
  151. // recv loop has a backlog and we should not block the goroutine.
  152. select {
  153. case ackCh <- ack:
  154. default:
  155. // Channel full; log and drop.
  156. s.Dep.Logger.Info("grpc ack channel full, dropping", "alert_id", ack.AlertId)
  157. }
  158. }(alert)
  159. }
  160. }()
  161. // recv loop: forward Acks from goroutines to the client.
  162. // Also watches for goroutine errors.
  163. for ack := range ackCh {
  164. if err := stream.Send(ack); err != nil {
  165. return err
  166. }
  167. }
  168. // Check if the stream exited due to a goroutine error.
  169. // atomic.Value.Load returns nil if nothing was ever stored; the
  170. // type assertion nil.(error) panics with "interface conversion:
  171. // interface is nil, not error", so we must guard with a nil check
  172. // and a type assertion that reports ok.
  173. if v := streamErr.Load(); v != nil {
  174. if se, ok := v.(error); ok && se != nil {
  175. return se
  176. }
  177. }
  178. return nil
  179. }
  180. // processAlert runs the shared pipeline on a single gRPC Alert and returns
  181. // the corresponding Ack. sig="" because gRPC auth is handled by authenticate()
  182. // before entering this function.
  183. func (s *Server) processAlert(ctx context.Context, alert *pbv1.Alert, src *pipeline.SourceConfig) *pbv1.Ack {
  184. body, err := alertToJSON(alert)
  185. if err != nil {
  186. return errorAck(alert.DedupeKey, pbv1.Error_INVALID, "marshal failed: "+err.Error(), 0)
  187. }
  188. // Override the Sources map for this call to use the authenticated source.
  189. // Per-call Sources map — passed in, never mutates s.Dep.Sources. Avoids
  190. // concurrent map read/write between gRPC goroutines sharing Deps.
  191. sourceKey := src.CompanyID + ":" + src.SourceID
  192. callDeps := s.Dep // value copy; underlying pointers/maps are shared safely
  193. callDeps.Sources = map[string]pipeline.SourceConfig{sourceKey: *src}
  194. res := callDeps.Process(ctx, body, "" /* no HMAC for gRPC */)
  195. if !res.Accepted {
  196. code := errorCode(res.RejectReason)
  197. var retryAfter int32
  198. if res.RejectReason == "rate_limited_source" || res.RejectReason == "rate_limited_company" {
  199. if n, _ := parseRetryAfter(res.Detail); n > 0 {
  200. retryAfter = int32(n)
  201. }
  202. }
  203. return errorAck(alert.DedupeKey, code, res.Detail, retryAfter)
  204. }
  205. return &pbv1.Ack{
  206. AlertId: res.AlertID,
  207. DedupeKey: alert.DedupeKey,
  208. DedupeCount: res.DedupeCount,
  209. AcceptedAtMs: time.Now().UnixMilli(),
  210. Result: &pbv1.Ack_Ok{Ok: &pbv1.Ok{}},
  211. }
  212. }
  213. // alertToJSON converts a protobuf Alert to JSON bytes for the pipeline.
  214. func alertToJSON(a *pbv1.Alert) ([]byte, error) {
  215. m := map[string]any{
  216. "company_id": a.CompanyId,
  217. "source_id": a.SourceId,
  218. }
  219. if a.DedupeKey != "" {
  220. m["dedupe_key"] = a.DedupeKey
  221. }
  222. if a.Severity != "" {
  223. m["severity"] = a.Severity
  224. }
  225. if a.Category != "" {
  226. m["category"] = a.Category
  227. }
  228. if a.Title != "" {
  229. m["title"] = a.Title
  230. }
  231. if a.Body != "" {
  232. m["body"] = a.Body
  233. }
  234. if len(a.Data) > 0 {
  235. m["data"] = a.Data
  236. }
  237. if a.ClientTsMs > 0 {
  238. m["client_ts_ms"] = a.ClientTsMs
  239. }
  240. return json.Marshal(m)
  241. }
  242. func errorAck(dedupeKey string, code pbv1.Error_Code, message string, retryAfterMs int32) *pbv1.Ack {
  243. return &pbv1.Ack{
  244. DedupeKey: dedupeKey,
  245. Result: &pbv1.Ack_Error{
  246. Error: &pbv1.Error{
  247. Code: code,
  248. Message: message,
  249. RetryAfterMs: retryAfterMs,
  250. },
  251. },
  252. }
  253. }
  254. // errorCode maps pipeline reject reasons to gRPC Error codes.
  255. func errorCode(reason string) pbv1.Error_Code {
  256. switch reason {
  257. case "unknown_source", "bad_signature":
  258. return pbv1.Error_UNAUTHENTICATED
  259. case "rate_limited_source", "rate_limited_company":
  260. return pbv1.Error_RATE_LIMITED
  261. case "invalid", "invalid_json", "quarantined":
  262. return pbv1.Error_INVALID
  263. case "circuit_open", "broker_unavailable", "marshal_failed":
  264. return pbv1.Error_INTERNAL
  265. default:
  266. return pbv1.Error_UNKNOWN
  267. }
  268. }
  269. func parseRetryAfter(s string) (int, bool) {
  270. var n int
  271. var parsed bool
  272. for _, c := range s {
  273. if c >= '0' && c <= '9' {
  274. n = n*10 + int(c-'0')
  275. parsed = true
  276. } else {
  277. break
  278. }
  279. }
  280. return n, parsed
  281. }