Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions cmd/collector/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ func run(cfg config.CollectorCLIConfig, logger *slog.Logger) error {

g, gctx := errgroup.WithContext(ctx)
g.Go(server.Serve)
g.Go(func() error {
if err := server.RunFlows(gctx); !errors.Is(err, context.Canceled) {
return err
}
return nil
})
g.Go(func() error {
if err := analyzer.Run(gctx); !errors.Is(err, context.Canceled) {
return err
Expand Down
129 changes: 129 additions & 0 deletions internal/collector/flows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package collector

import (
"context"
"encoding/json"
"fmt"
"sync"
"time"

"github.com/cap-theorem/spectral/internal/wire"
)

const FlowsPath = "/v1/flows"

const (
maxFlowsPerReport = 4096
maxPendingFlows = 50_000
flowSubBuffer = 32
FlowFlushInterval = 100 * time.Millisecond
)

type FlowReport struct {
ID wire.NodeID `json:"id"`
Flows []Flow `json:"flows"`
}

type Flow struct {
To wire.NodeID `json:"to"`
Kind string `json:"kind"`
Count uint32 `json:"count"`
}

func (r FlowReport) Validate() error {
if r.ID == (wire.NodeID{}) {
return fmt.Errorf("%w: id is required", ErrInvalidReport)
}
if len(r.Flows) > maxFlowsPerReport {
return fmt.Errorf("%w: %d flows exceeds limit %d", ErrInvalidReport, len(r.Flows), maxFlowsPerReport)
}
for _, f := range r.Flows {
if f.To == (wire.NodeID{}) || f.To == r.ID {
return fmt.Errorf("%w: flow target must be another node's id", ErrInvalidReport)
}
if f.Kind == "" || f.Count == 0 {
return fmt.Errorf("%w: flow needs a kind and a count", ErrInvalidReport)
}
}
return nil
}

type FlowEvent struct {
From wire.NodeID `json:"from"`
To wire.NodeID `json:"to"`
Kind string `json:"kind"`
Count uint32 `json:"count"`
}

type FlowBatch struct {
At time.Time `json:"at"`
Flows []FlowEvent `json:"flows"`
}

type flowHub struct {
mu sync.Mutex
pending []FlowEvent
dropped int
subs map[chan []byte]struct{}
}

func newFlowHub() *flowHub {
return &flowHub{subs: make(map[chan []byte]struct{})}
}

func (h *flowHub) add(r FlowReport) {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.subs) == 0 {
return
}
for _, f := range r.Flows {
if len(h.pending) >= maxPendingFlows {
h.dropped++
continue
}
h.pending = append(h.pending, FlowEvent{From: r.ID, To: f.To, Kind: f.Kind, Count: f.Count})
}
}

func (h *flowHub) flush(now time.Time) {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.pending) == 0 {
return
}
b, _ := json.Marshal(FlowBatch{At: now, Flows: h.pending})
h.pending = nil
for ch := range h.subs {
select {
case ch <- b:
default:
}
}
}

func (h *flowHub) subscribe() (<-chan []byte, func()) {
h.mu.Lock()
defer h.mu.Unlock()
ch := make(chan []byte, flowSubBuffer)
h.subs[ch] = struct{}{}
cancel := func() {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.subs, ch)
}
return ch, cancel
}

func (h *flowHub) run(ctx context.Context, every time.Duration) error {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case now := <-t.C:
h.flush(now)
}
}
}
119 changes: 119 additions & 0 deletions internal/collector/flows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package collector

import (
"bufio"
"bytes"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"uuid"
)

func TestFlowReportValidate(t *testing.T) {
x, y := uuid.NewV4(), uuid.NewV4()
for name, r := range map[string]FlowReport{
"no id": {Flows: []Flow{{To: y, Kind: "ping", Count: 1}}},
"self": {ID: x, Flows: []Flow{{To: x, Kind: "ping", Count: 1}}},
"no target": {ID: x, Flows: []Flow{{Kind: "ping", Count: 1}}},
"no kind": {ID: x, Flows: []Flow{{To: y, Count: 1}}},
"zero count": {ID: x, Flows: []Flow{{To: y, Kind: "ping"}}},
} {
if r.Validate() == nil {
t.Errorf("%s: valid", name)
}
}
if err := (FlowReport{ID: x, Flows: []Flow{{To: y, Kind: "ping", Count: 3}}}).Validate(); err != nil {
t.Fatal(err)
}
}

func TestFlowHubSkipsWithoutSubscribers(t *testing.T) {
h := newFlowHub()
h.add(FlowReport{ID: uuid.NewV4(), Flows: []Flow{{To: uuid.NewV4(), Kind: "ping", Count: 1}}})
if len(h.pending) != 0 {
t.Fatal("buffered flows with nobody watching")
}
}

func TestFlowHubSlowSubscriberMissesBatches(t *testing.T) {
h := newFlowHub()
ch, cancel := h.subscribe()
defer cancel()
r := FlowReport{ID: uuid.NewV4(), Flows: []Flow{{To: uuid.NewV4(), Kind: "ping", Count: 1}}}
for range flowSubBuffer + 5 {
h.add(r)
h.flush(time.Now())
}
if len(ch) != flowSubBuffer {
t.Fatalf("buffered %d batches, want %d", len(ch), flowSubBuffer)
}
if len(h.subs) != 1 {
t.Fatal("slow subscriber was dropped")
}
}

func TestServerFlowsStream(t *testing.T) {
g := NewGraph()
a := NewAnalyzer(AnalyzerConfig{StaleAfter: time.Minute}, g, slog.New(slog.DiscardHandler))
s := NewServer(ServerConfig{}, g, a, Metrics{}, slog.New(slog.DiscardHandler))
srv := httptest.NewServer(s.Handler())
t.Cleanup(srv.Close)

resp, err := http.Get(srv.URL + "/v1/flows/stream")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
t.Fatal("flow stream not readable cross-origin")
}
lines := bufio.NewScanner(resp.Body)
if !lines.Scan() || lines.Text() != ": flows" {
t.Fatalf("first line %q", lines.Text())
}

x, y := uuid.NewV4(), uuid.NewV4()
post := func(r FlowReport) int {
b, _ := json.Marshal(r)
resp, err := http.Post(srv.URL+FlowsPath, "application/json", bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
return resp.StatusCode
}
if code := post(FlowReport{ID: x, Flows: []Flow{{To: x, Kind: "ping", Count: 1}}}); code != http.StatusBadRequest {
t.Fatalf("self flow: status %d", code)
}
if code := post(FlowReport{ID: x, Flows: []Flow{{To: y, Kind: "heartbeat", Count: 2}}}); code != http.StatusNoContent {
t.Fatalf("flow: status %d", code)
}
s.flows.flush(time.Now())

var event, data string
for lines.Scan() {
line := lines.Text()
if v, ok := strings.CutPrefix(line, "event: "); ok {
event = v
}
if v, ok := strings.CutPrefix(line, "data: "); ok {
data = v
break
}
}
if event != "flows" {
t.Fatalf("event %q", event)
}
var b FlowBatch
if err := json.Unmarshal([]byte(data), &b); err != nil {
t.Fatal(err)
}
want := FlowEvent{From: x, To: y, Kind: "heartbeat", Count: 2}
if len(b.Flows) != 1 || b.Flows[0] != want {
t.Fatalf("batch = %+v", b)
}
}
54 changes: 53 additions & 1 deletion internal/collector/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ type Server struct {
logger *slog.Logger
server *http.Server
streams context.Context
flows *flowHub
}

func NewServer(cfg ServerConfig, g *Graph, a *Analyzer, m Metrics, logger *slog.Logger) *Server {
s := &Server{graph: g, analyzer: a, metrics: m, logger: logger}
s := &Server{graph: g, analyzer: a, metrics: m, logger: logger, flows: newFlowHub()}

// No request logging: ingest is most of the traffic.
r := chi.NewRouter()
Expand All @@ -40,6 +41,7 @@ func NewServer(cfg ServerConfig, g *Graph, a *Analyzer, m Metrics, logger *slog.
r.Group(func(r chi.Router) {
r.Use(middleware.Timeout(5 * time.Second))
r.Post(ReportPath, s.handleReport)
r.Post(FlowsPath, s.handleFlows)
r.Get("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
})
// Read-only, so any origin may read it (e.g. a frontend dev server).
Expand All @@ -48,6 +50,7 @@ func NewServer(cfg ServerConfig, g *Graph, a *Analyzer, m Metrics, logger *slog.
r.With(middleware.Timeout(5*time.Second)).Get("/v1/summary", s.handleSummary)
r.With(middleware.Timeout(5*time.Second), middleware.Compress(5, "application/json")).Get("/v1/graph", s.handleGraph)
r.Get("/v1/graph/stream", s.handleStream)
r.Get("/v1/flows/stream", s.handleFlowStream)
})

s.server = &http.Server{
Expand Down Expand Up @@ -76,6 +79,8 @@ func (s *Server) Serve() error {
return err
}

func (s *Server) RunFlows(ctx context.Context) error { return s.flows.run(ctx, FlowFlushInterval) }

func (s *Server) Shutdown(ctx context.Context) error { return s.server.Shutdown(ctx) }

func (s *Server) Close() error { return s.server.Close() }
Expand All @@ -102,6 +107,53 @@ func (s *Server) handleReport(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}

func (s *Server) handleFlows(w http.ResponseWriter, r *http.Request) {
var rep FlowReport
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxReportBytes)).Decode(&rep); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
if err := rep.Validate(); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
s.flows.add(rep)
w.WriteHeader(http.StatusNoContent)
}

func (s *Server) handleFlowStream(w http.ResponseWriter, r *http.Request) {
batches, cancel := s.flows.subscribe()
defer cancel()

rc := http.NewResponseController(w)
_ = rc.SetWriteDeadline(time.Time{})
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusOK)
if _, err := fmt.Fprint(w, ": flows\n\n"); err != nil || rc.Flush() != nil {
return
}

ping := time.NewTicker(15 * time.Second)
defer ping.Stop()
for {
select {
case <-r.Context().Done():
return
case <-s.streams.Done():
return
case b := <-batches:
if _, err := fmt.Fprintf(w, "event: flows\ndata: %s\n\n", b); err != nil || rc.Flush() != nil {
return
}
case <-ping.C:
if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil || rc.Flush() != nil {
return
}
}
}
}

func (s *Server) handleSummary(w http.ResponseWriter, _ *http.Request) {
sum := s.analyzer.Latest()
if sum == nil {
Expand Down
11 changes: 11 additions & 0 deletions internal/daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,10 @@ func Run(cfg config.DaemonCLIConfig, logger *slog.Logger) error {
nodeCtx, stopNode := context.WithCancel(context.Background())

var reports chan collector.Report
var flows chan collector.FlowReport
if cfg.CollectorURL != "" {
reports = make(chan collector.Report, 1)
flows = make(chan collector.FlowReport, 4)
}

node := node.NewNode(
Expand All @@ -87,6 +89,7 @@ func Run(cfg config.DaemonCLIConfig, logger *slog.Logger) error {
PongsReceived: pongsReceived,
},
Telemetry: reports,
Flows: flows,
},
tr,
logger.With("component", "node"),
Expand Down Expand Up @@ -115,6 +118,14 @@ func Run(cfg config.DaemonCLIConfig, logger *slog.Logger) error {
g.Go(supervise("telemetry", stopping, func() error {
return exporter.Run(stopping)
}))
flowExporter := telemetry.NewFlowExporter(
telemetry.ExporterConfig{CollectorURL: cfg.CollectorURL},
flows,
logger.With("component", "flows"),
)
g.Go(supervise("flows", stopping, func() error {
return flowExporter.Run(stopping)
}))
}

var shutdownErr error
Expand Down
Loading