sse

package
v0.0.0-...-284c1ef Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: AGPL-3.0 Imports: 14 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Server-Sent Events (SSE) Infrastructure

This package provides a comprehensive Server-Sent Events implementation for PandaFuzz's real-time event streaming capabilities.

Overview

The SSE infrastructure replaces WebSocket implementation with a more efficient, HTTP-based real-time event system that provides:

  • Real-time event broadcasting to multiple clients
  • Topic-based subscriptions
  • Advanced event filtering
  • Automatic reconnection with event replay
  • Rate limiting and buffer management
  • Comprehensive metrics and monitoring
  • Production-ready scalability

Architecture

Core Components
  1. Manager (manager.go) - Central orchestrator for SSE connections and event broadcasting
  2. Client (client.go) - Individual SSE client connection handler
  3. Events (events.go) - Structured event types for all PandaFuzz resources
  4. Filters (filters.go) - Advanced event filtering system
  5. Types (types.go) - Supporting types, metrics, and error definitions

Quick Start

package main

import (
    "context"
    "net/http"
    
    "github.com/ethpandaops/pandafuzz/pkg/api/v1/sse"
    "github.com/sirupsen/logrus"
)

func main() {
    logger := logrus.New()
    
    // Create and start SSE manager
    config := sse.DefaultConfig()
    manager := sse.NewManager(config, logger)
    
    ctx := context.Background()
    manager.Start(ctx)
    defer manager.Stop()
    
    // Set up SSE endpoint
    http.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
        clientID := "client_" + generateID()
        client := sse.NewClient(clientID, w, r, sse.DefaultClientConfig(), logger)
        
        manager.Register(client)
        defer manager.Unregister(client)
        
        client.ServeSSE() // Blocks until connection closes
    })
    
    // Broadcast events
    botEvent := sse.CreateBotRegisteredEvent(botID, "example-bot", []string{"fuzzing"})
    manager.Broadcast(botEvent)
    
    http.ListenAndServe(":8080", nil)
}

Event Types

The SSE system supports structured events for all PandaFuzz resources:

Bot Events
  • bot.registered - Bot agent registration
  • bot.unregistered - Bot agent disconnection
  • bot.heartbeat - Periodic bot status updates
  • bot.status_changed - Bot status transitions
  • bot.job_assigned - Job assignment to bot
  • bot.job_completed - Job completion by bot
  • bot.error - Bot error conditions
Job Events
  • job.created - New job creation
  • job.started - Job execution start
  • job.progress - Job progress updates
  • job.completed - Job completion
  • job.failed - Job failure
  • job.cancelled - Job cancellation
  • job.timeout - Job timeout
  • job.restarted - Job restart
Campaign Events
  • campaign.created - Campaign creation
  • campaign.started - Campaign start
  • campaign.paused - Campaign pause
  • campaign.resumed - Campaign resume
  • campaign.completed - Campaign completion
  • campaign.failed - Campaign failure
  • campaign.deleted - Campaign deletion
  • campaign.updated - Campaign updates
Crash Events
  • crash.detected - New crash discovery
  • crash.analyzed - Crash analysis completion
  • crash.duplicate - Duplicate crash detection
  • crash.minimized - Crash minimization
  • crash.reproduced - Crash reproduction
  • crash.classified - Crash classification
Corpus Events
  • corpus.sync - Corpus synchronization
  • corpus.updated - Corpus updates
  • corpus.quarantined - Corpus quarantine
  • corpus.restored - Corpus restoration
  • corpus.deleted - Corpus deletion
  • corpus.created - Corpus creation
System Events
  • system.heartbeat - System health checks
  • system.alert - System alerts
  • system.maintenance - Maintenance notifications
  • client.connected - Client connections
  • client.disconnected - Client disconnections
  • client.reconnected - Client reconnections

Event Filtering

The SSE system provides powerful filtering capabilities:

Type Filtering

Filter events by specific types:

/events?types=job.started,job.completed,crash.detected
Resource Filtering

Filter events by specific resources:

/events?bot_id=550e8400-e29b-41d4-a716-446655440000
/events?campaign_id=fedcba98-7654-3210-fedc-ba9876543210
/events?job_id=01234567-89ab-cdef-0123-456789abcdef
Pattern Filtering

Filter events using regex patterns:

/events?pattern=^(job|crash)\.
Severity Filtering

Filter events by minimum severity level:

/events?min_severity=warning
Compound Filtering

Combine multiple filters:

/events?types=job.progress&campaign_id=550e8400-e29b-41d4-a716-446655440000&min_severity=info

Client Usage

JavaScript/Browser
const eventSource = new EventSource('/events?types=job.progress,crash.detected');

eventSource.addEventListener('job.progress', function(event) {
    const data = JSON.parse(event.data);
    console.log('Job progress:', data.progress + '%');
    updateProgressBar(data.job_id, data.progress);
});

eventSource.addEventListener('crash.detected', function(event) {
    const data = JSON.parse(event.data);
    console.log('Crash detected:', data.crash_type);
    showCrashAlert(data);
});

eventSource.onerror = function(event) {
    console.error('SSE connection error:', event);
};
cURL
# Subscribe to all events
curl -N -H "Accept: text/event-stream" http://localhost:8080/events

# Subscribe to specific event types
curl -N -H "Accept: text/event-stream" "http://localhost:8080/events?types=job.started,job.completed"

# Subscribe to events for specific campaign
curl -N -H "Accept: text/event-stream" "http://localhost:8080/events?campaign_id=550e8400-e29b-41d4-a716-446655440000"

Advanced Features

Automatic Reconnection

Clients can reconnect and receive missed events using the Last-Event-ID header:

const eventSource = new EventSource('/events');
// Browser automatically handles reconnection with Last-Event-ID
Topic Subscriptions

Subscribe clients to specific topics for targeted event delivery:

// Subscribe client to bot events topic
manager.Subscribe("client_123", "bot-events")

// Broadcast only to subscribers of bot-events topic
manager.BroadcastToTopic("bot-events", botEvent)
Rate Limiting

Configure per-client rate limiting:

clientConfig := sse.ClientConfig{
    MaxEventsPerSec: 10,    // Max 10 events per second
    BurstSize:      20,     // Allow bursts up to 20 events
    BufferSize:     100,    // Client event buffer size
}
Metrics and Monitoring

Access comprehensive metrics:

metrics := manager.GetMetrics()
fmt.Printf("Active clients: %d\n", metrics.GetActiveClients())
fmt.Printf("Events sent: %d\n", metrics.GetEventsSent())
fmt.Printf("Events per second: %.2f\n", metrics.GetEventsPerSecond())

// Get detailed statistics
stats := manager.GetManagerStats()

Configuration

Manager Configuration
config := sse.Config{
    MaxClients:          1000,                // Maximum concurrent clients
    ClientTimeout:       5 * time.Minute,    // Client connection timeout
    WriteTimeout:        10 * time.Second,   // Write operation timeout
    HeartbeatInterval:   30 * time.Second,   // Heartbeat frequency
    EventBufferSize:     1000,               // Manager event buffer
    ClientBufferSize:    100,                // Per-client event buffer
    BroadcastBufferSize: 10000,              // Broadcast queue size
    MaxEventsPerSecond:  100,                // Global rate limit
    BurstSize:           200,                // Global burst size
    CleanupInterval:     1 * time.Minute,    // Cleanup frequency
    MaxEventHistory:     10000,              // Event history size
}
Client Configuration
clientConfig := sse.ClientConfig{
    BufferSize:        100,               // Client event buffer
    WriteTimeout:      10 * time.Second, // Write timeout
    MaxEventsPerSec:   10,               // Client rate limit
    BurstSize:         20,               // Client burst size
    EnableCompression: false,            // Enable gzip compression
}

Error Handling

The SSE system provides comprehensive error handling:

// Manager errors
if err := manager.Start(ctx); err != nil {
    switch err {
    case sse.ErrManagerAlreadyRunning:
        // Handle already running
    default:
        // Handle other errors
    }
}

// Client errors
if err := client.SendEvent(event); err != nil {
    switch err {
    case sse.ErrClientClosed:
        // Client disconnected
    case sse.ErrRateLimited:
        // Rate limit exceeded
    case sse.ErrBufferFull:
        // Client buffer full
    }
}

Testing

Run the comprehensive test suite:

# Run all tests
go test ./pkg/api/v1/sse/

# Run tests with race detection
go test -race ./pkg/api/v1/sse/

# Run benchmarks
go test -bench=. ./pkg/api/v1/sse/

# Run specific test
go test -run TestManager_Lifecycle ./pkg/api/v1/sse/

Performance Considerations

  • Memory Usage: Each client uses ~1KB of memory plus buffer size
  • CPU Usage: Minimal overhead with efficient channel operations
  • Network: Events are JSON-encoded, consider compression for large payloads
  • Scaling: Tested with 1000+ concurrent clients per instance
  • Latency: Sub-millisecond event delivery under normal conditions

Production Deployment

Load Balancing

For multiple instances, use sticky sessions:

upstream sse_backend {
    ip_hash;  # Sticky sessions
    server sse1.example.com:8080;
    server sse2.example.com:8080;
}

location /events {
    proxy_pass http://sse_backend;
    proxy_set_header Connection '';
    proxy_http_version 1.1;
    proxy_buffering off;
    proxy_cache off;
}
Monitoring

Monitor key metrics:

  • Active client count
  • Events per second
  • Client connection/disconnection rate
  • Event buffer utilization
  • Error rates
Security
  • Use HTTPS in production
  • Implement authentication/authorization
  • Rate limit based on client identity
  • Monitor for abuse patterns

Integration with PandaFuzz

The SSE infrastructure integrates seamlessly with PandaFuzz's existing architecture:

  1. API v1 Integration: Implements the /events endpoint from the OpenAPI specification
  2. Event Generation: Master and bot components generate events automatically
  3. Web UI: React frontend consumes real-time events for live updates
  4. Monitoring: Provides real-time visibility into system state

Migration from WebSockets

The SSE system provides several advantages over WebSockets:

  1. Simpler Protocol: Standard HTTP-based, easier to debug and monitor
  2. Better Caching: Works with HTTP caches and CDNs
  3. Automatic Reconnection: Built-in browser support for reconnection
  4. Firewall Friendly: Uses standard HTTP, fewer network issues
  5. Event Replay: Automatic handling of missed events on reconnection

Examples

See example_usage.go for complete working examples including:

  • Basic SSE server setup
  • Event generation and broadcasting
  • Client connection handling
  • Filter usage demonstrations
  • JavaScript client examples

Documentation

Index

Constants

View Source
const (
	// Bot events
	EventBotRegistered    = "bot.registered"
	EventBotUnregistered  = "bot.unregistered"
	EventBotHeartbeat     = "bot.heartbeat"
	EventBotStatusChanged = "bot.status_changed"
	EventBotJobAssigned   = "bot.job_assigned"
	EventBotJobCompleted  = "bot.job_completed"
	EventBotError         = "bot.error"

	// Job events
	EventJobCreated   = "job.created"
	EventJobStarted   = "job.started"
	EventJobProgress  = "job.progress"
	EventJobCompleted = "job.completed"
	EventJobFailed    = "job.failed"
	EventJobCancelled = "job.cancelled"
	EventJobTimeout   = "job.timeout"
	EventJobRestarted = "job.restarted"

	// Campaign events
	EventCampaignCreated   = "campaign.created"
	EventCampaignStarted   = "campaign.started"
	EventCampaignPaused    = "campaign.paused"
	EventCampaignResumed   = "campaign.resumed"
	EventCampaignCompleted = "campaign.completed"
	EventCampaignFailed    = "campaign.failed"
	EventCampaignDeleted   = "campaign.deleted"
	EventCampaignUpdated   = "campaign.updated"

	// Corpus events
	EventCorpusSync        = "corpus.sync"
	EventCorpusUpdated     = "corpus.updated"
	EventCorpusQuarantined = "corpus.quarantined"
	EventCorpusRestored    = "corpus.restored"
	EventCorpusDeleted     = "corpus.deleted"
	EventCorpusCreated     = "corpus.created"

	// Crash events
	EventCrashDetected   = "crash.detected"
	EventCrashAnalyzed   = "crash.analyzed"
	EventCrashDuplicate  = "crash.duplicate"
	EventCrashMinimized  = "crash.minimized"
	EventCrashReproduced = "crash.reproduced"
	EventCrashClassified = "crash.classified"

	// System events
	EventSystemHeartbeat    = "system.heartbeat"
	EventSystemAlert        = "system.alert"
	EventSystemMaintenance  = "system.maintenance"
	EventClientConnected    = "client.connected"
	EventClientDisconnected = "client.disconnected"
	EventClientReconnected  = "client.reconnected"
)

Event type constants for consistency

Variables

View Source
var (
	ErrManagerAlreadyRunning   = errors.New("SSE manager is already running")
	ErrManagerNotRunning       = errors.New("SSE manager is not running")
	ErrManagerStopped          = errors.New("SSE manager has been stopped")
	ErrMaxClientsReached       = errors.New("maximum number of clients reached")
	ErrRegistrationQueueFull   = errors.New("client registration queue is full")
	ErrUnregistrationQueueFull = errors.New("client unregistration queue is full")
	ErrBroadcastQueueFull      = errors.New("broadcast queue is full")
	ErrClientNotFound          = errors.New("client not found")
	ErrClientClosed            = errors.New("client connection is closed")
	ErrRateLimited             = errors.New("event dropped due to rate limiting")
	ErrBufferFull              = errors.New("client buffer is full")
)

Common errors

Functions

func ParseUUIDFromString

func ParseUUIDFromString(uuidStr string) (*openapi_types.UUID, error)

ParseUUIDFromString safely parses a UUID string

Types

type AllowAllFilter

type AllowAllFilter struct{}

AllowAllFilter is a filter that allows all events

func (*AllowAllFilter) Matches

func (f *AllowAllFilter) Matches(event Event) bool

Matches always returns true

func (*AllowAllFilter) String

func (f *AllowAllFilter) String() string

String returns a string representation of the filter

type BaseEvent

type BaseEvent struct {
	ID        string                 `json:"id"`
	Type      string                 `json:"type"`
	Timestamp time.Time              `json:"timestamp"`
	Data      map[string]interface{} `json:"data"`
}

BaseEvent provides common functionality for all events

func NewBaseEvent

func NewBaseEvent(eventType string, data map[string]interface{}) *BaseEvent

NewBaseEvent creates a new base event with generated ID and current timestamp

func (*BaseEvent) GetData

func (e *BaseEvent) GetData() string

GetData returns the event data as JSON string

func (*BaseEvent) GetID

func (e *BaseEvent) GetID() string

GetID returns the event ID

func (*BaseEvent) GetType

func (e *BaseEvent) GetType() string

GetType returns the event type

type BotEvent

type BotEvent struct {
	*BaseEvent
	BotID      openapi_types.UUID  `json:"bot_id"`
	BotName    string              `json:"bot_name,omitempty"`
	CampaignID *openapi_types.UUID `json:"campaign_id,omitempty"`
}

BotEvent represents bot-related events

func CreateBotRegisteredEvent

func CreateBotRegisteredEvent(botID openapi_types.UUID, botName string, capabilities []string) *BotEvent

CreateBotRegisteredEvent creates a bot registration event

func CreateBotStatusChangedEvent

func CreateBotStatusChangedEvent(botID openapi_types.UUID, oldStatus, newStatus string) *BotEvent

CreateBotStatusChangedEvent creates a bot status change event

func NewBotEvent

func NewBotEvent(eventType string, botID openapi_types.UUID, data map[string]interface{}) *BotEvent

NewBotEvent creates a new bot event

type CampaignEvent

type CampaignEvent struct {
	*BaseEvent
	CampaignID openapi_types.UUID `json:"campaign_id"`
	State      string             `json:"state,omitempty"`
}

CampaignEvent represents campaign-related events

func CreateCampaignStateChangeEvent

func CreateCampaignStateChangeEvent(campaignID openapi_types.UUID, oldState, newState string) *CampaignEvent

CreateCampaignStateChangeEvent creates a campaign state change event

func NewCampaignEvent

func NewCampaignEvent(eventType string, campaignID openapi_types.UUID, data map[string]interface{}) *CampaignEvent

NewCampaignEvent creates a new campaign event

type Client

type Client struct {
	// Identity
	ID string

	// HTTP connection
	ResponseWriter http.ResponseWriter
	Request        *http.Request

	// Event channel
	Send chan Event

	// Subscriptions and filters
	Topics  map[string]bool
	Filters []Filter

	// SSE state
	LastEventID string
	Connected   time.Time
	// contains filtered or unexported fields
}

Client represents an SSE client connection

func NewClient

func NewClient(id string, w http.ResponseWriter, r *http.Request, config ClientConfig, logger logrus.FieldLogger) *Client

NewClient creates a new SSE client with the given configuration

func (*Client) AddFilter

func (c *Client) AddFilter(filter Filter)

AddFilter adds an event filter to the client

func (*Client) Close

func (c *Client) Close()

Close gracefully closes the client connection

func (*Client) GetInfo

func (c *Client) GetInfo() ClientInfo

GetInfo returns client information for monitoring

func (*Client) IsAlive

func (c *Client) IsAlive() bool

IsAlive checks if the client connection is still active

func (*Client) RemoveFilter

func (c *Client) RemoveFilter(filterIndex int)

RemoveFilter removes an event filter from the client

func (*Client) SendEvent

func (c *Client) SendEvent(event Event) error

SendEvent sends an event to the client (non-blocking)

func (*Client) ServeSSE

func (c *Client) ServeSSE()

ServeSSE starts the SSE connection and serves events

type ClientConfig

type ClientConfig struct {
	BufferSize        int           `json:"buffer_size" yaml:"buffer_size"`
	WriteTimeout      time.Duration `json:"write_timeout" yaml:"write_timeout"`
	MaxEventsPerSec   int           `json:"max_events_per_sec" yaml:"max_events_per_sec"`
	BurstSize         int           `json:"burst_size" yaml:"burst_size"`
	EnableCompression bool          `json:"enable_compression" yaml:"enable_compression"`
}

ClientConfig holds per-client configuration

func DefaultClientConfig

func DefaultClientConfig() ClientConfig

DefaultClientConfig returns sensible defaults for SSE clients

type ClientInfo

type ClientInfo struct {
	ID          string    `json:"id"`
	Connected   time.Time `json:"connected"`
	LastEventID string    `json:"last_event_id"`
	Topics      []string  `json:"topics"`
	IsAlive     bool      `json:"is_alive"`
	EventsSent  int64     `json:"events_sent"`
}

ClientInfo provides information about a client for status purposes

type CompoundFilter

type CompoundFilter struct {
	Filters []Filter
	Logic   string // "AND" or "OR"
}

CompoundFilter combines multiple filters with AND logic

func NewCompoundFilter

func NewCompoundFilter(logic string, filters ...Filter) *CompoundFilter

NewCompoundFilter creates a new compound filter

func (*CompoundFilter) Matches

func (f *CompoundFilter) Matches(event Event) bool

Matches checks if the event passes all filters (AND) or any filter (OR)

func (*CompoundFilter) String

func (f *CompoundFilter) String() string

String returns a string representation of the filter

type Config

type Config struct {
	// Client configuration
	MaxClients        int           `json:"max_clients" yaml:"max_clients"`
	ClientTimeout     time.Duration `json:"client_timeout" yaml:"client_timeout"`
	WriteTimeout      time.Duration `json:"write_timeout" yaml:"write_timeout"`
	HeartbeatInterval time.Duration `json:"heartbeat_interval" yaml:"heartbeat_interval"`

	// Buffer configuration
	EventBufferSize     int `json:"event_buffer_size" yaml:"event_buffer_size"`
	ClientBufferSize    int `json:"client_buffer_size" yaml:"client_buffer_size"`
	BroadcastBufferSize int `json:"broadcast_buffer_size" yaml:"broadcast_buffer_size"`

	// Rate limiting
	MaxEventsPerSecond int `json:"max_events_per_second" yaml:"max_events_per_second"`
	BurstSize          int `json:"burst_size" yaml:"burst_size"`

	// Cleanup configuration
	CleanupInterval time.Duration `json:"cleanup_interval" yaml:"cleanup_interval"`
	MaxEventHistory int           `json:"max_event_history" yaml:"max_event_history"`
}

Config holds SSE manager configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults for SSE manager

type ConnectionInfo

type ConnectionInfo struct {
	RemoteAddr  string            `json:"remote_addr"`
	UserAgent   string            `json:"user_agent"`
	Headers     map[string]string `json:"headers"`
	ConnectedAt time.Time         `json:"connected_at"`
	LastEventID string            `json:"last_event_id"`
	BytesSent   int64             `json:"bytes_sent"`
	EventsSent  int64             `json:"events_sent"`
}

ConnectionInfo provides detailed connection information

type CorpusEvent

type CorpusEvent struct {
	*BaseEvent
	CorpusID   *openapi_types.UUID `json:"corpus_id,omitempty"`
	JobID      *openapi_types.UUID `json:"job_id,omitempty"`
	CampaignID *openapi_types.UUID `json:"campaign_id,omitempty"`
	Operation  string              `json:"operation,omitempty"`
}

CorpusEvent represents corpus-related events

func CreateCorpusSyncEvent

func CreateCorpusSyncEvent(jobID, campaignID openapi_types.UUID, operation string, count int) *CorpusEvent

CreateCorpusSyncEvent creates a corpus synchronization event

func NewCorpusEvent

func NewCorpusEvent(eventType string, data map[string]interface{}) *CorpusEvent

NewCorpusEvent creates a new corpus event

type CrashEvent

type CrashEvent struct {
	*BaseEvent
	CrashID    openapi_types.UUID `json:"crash_id"`
	JobID      openapi_types.UUID `json:"job_id"`
	CampaignID openapi_types.UUID `json:"campaign_id"`
	CrashType  string             `json:"crash_type,omitempty"`
	Severity   string             `json:"severity,omitempty"`
}

CrashEvent represents crash-related events

func CreateCrashDetectedEvent

func CreateCrashDetectedEvent(crashID, jobID, campaignID openapi_types.UUID, crashType, stackTrace string) *CrashEvent

CreateCrashDetectedEvent creates a crash detection event

func NewCrashEvent

func NewCrashEvent(eventType string, crashID, jobID, campaignID openapi_types.UUID, data map[string]interface{}) *CrashEvent

NewCrashEvent creates a new crash event

type Event

type Event interface {
	GetID() string
	GetType() string
	GetData() string
}

Event represents a Server-Sent Event

type EventHistory

type EventHistory struct {
	// contains filtered or unexported fields
}

EventHistory stores recent events for replay functionality

func NewEventHistory

func NewEventHistory(maxSize int) *EventHistory

NewEventHistory creates a new event history with specified size

func (*EventHistory) Add

func (eh *EventHistory) Add(event Event)

Add stores an event in the history

func (*EventHistory) GetEventsAfter

func (eh *EventHistory) GetEventsAfter(eventID string) []StoredEvent

GetEventsAfter returns events after the specified event ID

type Filter

type Filter interface {
	Matches(event Event) bool
	String() string
}

Filter represents an event filtering interface

func ParseFiltersFromParams

func ParseFiltersFromParams(params map[string]string) Filter

ParseFiltersFromParams parses filters from HTTP query parameters

type FilterBuilder

type FilterBuilder struct {
	// contains filtered or unexported fields
}

FilterBuilder helps build complex filters from query parameters

func NewFilterBuilder

func NewFilterBuilder() *FilterBuilder

NewFilterBuilder creates a new filter builder

func (*FilterBuilder) AddPatternFilter

func (fb *FilterBuilder) AddPatternFilter(pattern string) *FilterBuilder

AddPatternFilter adds a pattern filter

func (*FilterBuilder) AddResourceFilter

func (fb *FilterBuilder) AddResourceFilter(resourceType, resourceID string) *FilterBuilder

AddResourceFilter adds a resource filter

func (*FilterBuilder) AddSeverityFilter

func (fb *FilterBuilder) AddSeverityFilter(minSeverity string) *FilterBuilder

AddSeverityFilter adds a severity filter

func (*FilterBuilder) AddTypeFilter

func (fb *FilterBuilder) AddTypeFilter(types string) *FilterBuilder

AddTypeFilter adds a type filter from comma-separated event types

func (*FilterBuilder) Build

func (fb *FilterBuilder) Build() Filter

Build creates a compound filter with AND logic

func (*FilterBuilder) BuildOr

func (fb *FilterBuilder) BuildOr() Filter

BuildOr creates a compound filter with OR logic

type HealthStatus

type HealthStatus struct {
	Status    string          `json:"status"` // "healthy", "degraded", "unhealthy"
	Timestamp time.Time       `json:"timestamp"`
	Uptime    string          `json:"uptime"`
	Metrics   MetricsSnapshot `json:"metrics"`
	Issues    []string        `json:"issues,omitempty"`
	Details   map[string]any  `json:"details,omitempty"`
}

HealthStatus represents the health of the SSE system

type JobEvent

type JobEvent struct {
	*BaseEvent
	JobID      openapi_types.UUID  `json:"job_id"`
	BotID      *openapi_types.UUID `json:"bot_id,omitempty"`
	CampaignID openapi_types.UUID  `json:"campaign_id"`
	Status     string              `json:"status,omitempty"`
}

JobEvent represents job-related events

func CreateJobCompletedEvent

func CreateJobCompletedEvent(jobID, campaignID openapi_types.UUID, duration time.Duration, results map[string]interface{}) *JobEvent

CreateJobCompletedEvent creates a job completion event

func CreateJobProgressEvent

func CreateJobProgressEvent(jobID, campaignID openapi_types.UUID, progress float64, details map[string]interface{}) *JobEvent

CreateJobProgressEvent creates a job progress event

func NewJobEvent

func NewJobEvent(eventType string, jobID, campaignID openapi_types.UUID, data map[string]interface{}) *JobEvent

NewJobEvent creates a new job event

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager handles SSE client connections and event broadcasting

func NewManager

func NewManager(config Config, logger logrus.FieldLogger) *Manager

NewManager creates a new SSE manager with the given configuration

func (*Manager) Broadcast

func (m *Manager) Broadcast(event Event) error

Broadcast sends an event to all connected clients

func (*Manager) BroadcastToTopic

func (m *Manager) BroadcastToTopic(topic string, event Event) error

BroadcastToTopic sends an event to all clients subscribed to a specific topic

func (*Manager) GetClients

func (m *Manager) GetClients() []ClientInfo

GetClients returns information about all connected clients

func (*Manager) GetMetrics

func (m *Manager) GetMetrics() *Metrics

GetMetrics returns current metrics

func (*Manager) Register

func (m *Manager) Register(client *Client) error

Register adds a new SSE client to the manager

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start begins the SSE manager's main event loop

func (*Manager) Stop

func (m *Manager) Stop() error

Stop gracefully shuts down the SSE manager

func (*Manager) Subscribe

func (m *Manager) Subscribe(clientID string, topic string) error

Subscribe adds a client to a topic subscription

func (*Manager) Unregister

func (m *Manager) Unregister(client *Client) error

Unregister removes an SSE client from the manager

func (*Manager) Unsubscribe

func (m *Manager) Unsubscribe(clientID string, topic string) error

Unsubscribe removes a client from a topic subscription

type ManagerStats

type ManagerStats struct {
	Status        string          `json:"status"`
	Uptime        string          `json:"uptime"`
	Metrics       MetricsSnapshot `json:"metrics"`
	Topics        []TopicStats    `json:"topics"`
	Clients       []ClientInfo    `json:"clients"`
	Configuration Config          `json:"configuration"`
	Health        HealthStatus    `json:"health"`
}

ManagerStats provides comprehensive statistics about the SSE manager

type Metrics

type Metrics struct {
	// contains filtered or unexported fields
}

Metrics holds various metrics for the SSE manager

func NewMetrics

func NewMetrics() *Metrics

NewMetrics creates a new metrics instance

func (*Metrics) DecrementActiveClients

func (m *Metrics) DecrementActiveClients()

DecrementActiveClients decrements the active clients counter

func (*Metrics) GetActiveClients

func (m *Metrics) GetActiveClients() int64

GetActiveClients returns the current number of active clients

func (*Metrics) GetEventsDropped

func (m *Metrics) GetEventsDropped() int64

GetEventsDropped returns the total number of events dropped

func (*Metrics) GetEventsPerSecond

func (m *Metrics) GetEventsPerSecond() float64

GetEventsPerSecond returns the average events per second

func (*Metrics) GetEventsSent

func (m *Metrics) GetEventsSent() int64

GetEventsSent returns the total number of events sent

func (*Metrics) GetTotalClients

func (m *Metrics) GetTotalClients() int64

GetTotalClients returns the total number of clients that have connected

func (*Metrics) GetUptime

func (m *Metrics) GetUptime() time.Duration

GetUptime returns the uptime of the metrics tracker

func (*Metrics) IncrementActiveClients

func (m *Metrics) IncrementActiveClients()

IncrementActiveClients increments the active clients counter

func (*Metrics) IncrementEventsDropped

func (m *Metrics) IncrementEventsDropped()

IncrementEventsDropped increments the events dropped counter

func (*Metrics) IncrementEventsSent

func (m *Metrics) IncrementEventsSent()

IncrementEventsSent increments the events sent counter

func (*Metrics) Snapshot

func (m *Metrics) Snapshot() MetricsSnapshot

Snapshot creates a metrics snapshot

type MetricsSnapshot

type MetricsSnapshot struct {
	ActiveClients   int64     `json:"active_clients"`
	TotalClients    int64     `json:"total_clients"`
	EventsSent      int64     `json:"events_sent"`
	EventsDropped   int64     `json:"events_dropped"`
	EventsPerSecond float64   `json:"events_per_second"`
	Uptime          string    `json:"uptime"`
	Timestamp       time.Time `json:"timestamp"`
}

MetricsSnapshot represents a point-in-time snapshot of metrics

type PatternFilter

type PatternFilter struct {
	Pattern *regexp.Regexp
}

PatternFilter filters events using regex patterns on event types

func NewPatternFilter

func NewPatternFilter(pattern string) (*PatternFilter, error)

NewPatternFilter creates a new pattern filter with the given regex

func (*PatternFilter) Matches

func (f *PatternFilter) Matches(event Event) bool

Matches checks if the event type matches the pattern

func (*PatternFilter) String

func (f *PatternFilter) String() string

String returns a string representation of the filter

type ResourceFilter

type ResourceFilter struct {
	ResourceType string // "bot", "job", "campaign", "crash", "corpus"
	ResourceID   string
}

ResourceFilter filters events by resource ID (bot, job, campaign, etc.)

func NewResourceFilter

func NewResourceFilter(resourceType, resourceID string) *ResourceFilter

NewResourceFilter creates a new resource filter

func (*ResourceFilter) Matches

func (f *ResourceFilter) Matches(event Event) bool

Matches checks if the event relates to the specified resource

func (*ResourceFilter) String

func (f *ResourceFilter) String() string

String returns a string representation of the filter

type SeverityFilter

type SeverityFilter struct {
	MinSeverity string
	Levels      map[string]int
}

SeverityFilter filters events by severity level

func NewSeverityFilter

func NewSeverityFilter(minSeverity string) *SeverityFilter

NewSeverityFilter creates a new severity filter

func (*SeverityFilter) Matches

func (f *SeverityFilter) Matches(event Event) bool

Matches checks if the event severity meets the minimum level

func (*SeverityFilter) String

func (f *SeverityFilter) String() string

String returns a string representation of the filter

type StoredEvent

type StoredEvent struct {
	Event     Event     `json:"event"`
	Timestamp time.Time `json:"timestamp"`
	ID        string    `json:"id"`
}

StoredEvent represents an event stored in history

type SystemEvent

type SystemEvent struct {
	*BaseEvent
	Component string `json:"component,omitempty"`
	Severity  string `json:"severity,omitempty"`
}

SystemEvent represents system-level events

func CreateSystemAlertEvent

func CreateSystemAlertEvent(component, severity, message string, details map[string]interface{}) *SystemEvent

CreateSystemAlertEvent creates a system alert event

func NewSystemEvent

func NewSystemEvent(eventType string, data map[string]interface{}) *SystemEvent

NewSystemEvent creates a new system event

type TopicStats

type TopicStats struct {
	Name         string    `json:"name"`
	Subscribers  int       `json:"subscribers"`
	EventsSent   int64     `json:"events_sent"`
	LastActivity time.Time `json:"last_activity"`
}

TopicStats provides statistics for a topic

type TypeFilter

type TypeFilter struct {
	EventTypes map[string]bool
}

TypeFilter filters events by their type

func NewTypeFilter

func NewTypeFilter(eventTypes []string) *TypeFilter

NewTypeFilter creates a new type filter with the given event types

func (*TypeFilter) Matches

func (f *TypeFilter) Matches(event Event) bool

Matches checks if the event type is in the allowed types

func (*TypeFilter) String

func (f *TypeFilter) String() string

String returns a string representation of the filter

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL