{"modulePath":"github.com/RandomCodeSpace/otelcontext","version":"v0.6.8","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package realtime\n\n## Constants\n\n```go\nconst DefaultPublishFloor = 2 * time.Second\n```\nDefaultPublishFloor is the minimum spacing between aggregate publications. Frozen at 2 s in #164: fast enough to feel live, slow enough that a busy engine cannot turn every commit into a broadcast.\n\n## Types\n\n```go\ntype AggregatePublisher interface {\n\t// Epoch identifies the process generation of Revision.\n\tEpoch() string\n\t// Revision is the aggregate engine's monotonic revision.\n\tRevision() uint64\n\t// Snapshot builds the coalesced payload for one service filter (empty\n\t// means all services). It is summary, recent traffic, service health and\n\t// topology — never the seven-day history.\n\tSnapshot(ctx context.Context, service string) *LiveSnapshot\n}\n```\nAggregatePublisher supplies revision-driven snapshots in aggregate mode. It is an interface so the hub needs neither the aggregate engine nor a live store to be tested.\n\n```go\ntype EnginePublisher struct {\n\t// contains filtered or unexported fields\n}\n```\nEnginePublisher is the AggregatePublisher backed by the aggregate engine.\n\nThe payload it builds is deliberately the COALESCED one #164 froze: summary, recent traffic, service health and topology over a short trailing window. The seven-day history is never in a WebSocket message — a client that wants it asks for it over HTTP once, not on every revision bump.\n\n```go\nfunc NewEnginePublisher(cfg EnginePublisherConfig) *EnginePublisher\n```\nNewEnginePublisher builds a publisher over the engine. It returns nil when no engine is configured, which is what keeps the caller's wiring a one-liner.\n\n```go\nfunc (p *EnginePublisher) Epoch() string\n```\nEpoch implements AggregatePublisher.\n\n```go\nfunc (p *EnginePublisher) Revision() uint64\n```\nRevision implements AggregatePublisher.\n\n```go\nfunc (p *EnginePublisher) Snapshot(ctx context.Context, service string) *LiveSnapshot\n```\nSnapshot implements AggregatePublisher.\n\n```go\ntype EnginePublisherConfig struct {\n\t// Engine is the aggregate query facade. Required.\n\tEngine *aggregate.Engine\n\t// Topology is the same mode-selected provider injected into REST, MCP and\n\t// GraphRAG. It is required and must be aggregate-owned.\n\tTopology topology.Provider\n\t// Window is the trailing range of the coalesced payload. Zero takes 15\n\t// minutes, matching the legacy snapshot window.\n\tWindow time.Duration\n\t// Tenant scopes every query. Empty takes storage.DefaultTenantID.\n\tTenant string\n\t// Edges is IGNORED since #194 finding 15: topology edges come from the\n\t// engine's own service-edge series, read in the same query as the nodes.\n\t// The field remains so existing wiring compiles.\n\t//\n\t// Deprecated: supply nothing; QueryTopology carries the edges.\n\tEdges func(ctx context.Context) []storage.ServiceMapEdge\n}\n```\nEnginePublisherConfig configures an EnginePublisher.\n\n```go\ntype EventHub struct {\n\t// contains filtered or unexported fields\n}\n```\nEventHub manages WebSocket clients and pushes live data snapshots filtered per-client's selected service. Debounces rapid ingestion bursts and only computes snapshots every flush interval.\n\n```go\nfunc NewEventHub(repo *storage.Repository, onConnect, onDisconnect func()) *EventHub\n```\nNewEventHub creates a new event notification hub.\n\n```go\nfunc (h *EventHub) ActiveClients() int64\n```\nActiveClients reports currently-connected event-WS clients.\n\n```go\nfunc (h *EventHub) BroadcastLog(l LogEntry)\n```\nBroadcastLog adds a log entry to the real-time buffer. In aggregate mode per-event broadcasts are disabled and this is a no-op: the coalesced revision-driven snapshot is the only data message clients receive.\n\n```go\nfunc (h *EventHub) BroadcastMetric(m MetricEntry)\n```\nBroadcastMetric adds a metric entry to the real-time buffer. Disabled in aggregate mode, for the same reason as BroadcastLog.\n\n```go\nfunc (h *EventHub) HandleWebSocket(w http.ResponseWriter, r *http.Request)\n```\nHandleWebSocket upgrades an HTTP request to a WebSocket connection, registers it as an event client, and listens for filter messages.\n\nThe connection is scoped to exactly one tenant, taken from the principal the handshake gate authenticated. Writes are serialized through one bounded queue and one writer goroutine per client, so a stalled reader can neither block the snapshot loop nor grow without bound.\n\n```go\nfunc (h *EventHub) NotifyRefresh()\n```\nnotifyRefresh marks that new data has arrived. The actual snapshot happens on the next snapshotTicker flush.\n\n```go\nfunc (h *EventHub) SetAggregatePublisher(p AggregatePublisher, floor time.Duration)\n```\nSetAggregatePublisher switches the hub to revision-driven publication. Pass a zero floor to take DefaultPublishFloor. Call once at startup, before the hub takes connections.\n\n```go\nfunc (h *EventHub) SetMaxClients(n int)\n```\nSetMaxClients caps simultaneous event-WS connections. 0 disables the cap. Call once at startup, before the hub takes traffic.\n\n```go\nfunc (h *EventHub) SetOriginPolicy(enforce bool, allowedHosts []string)\n```\nSetOriginPolicy configures WebSocket origin enforcement — see Hub.SetOriginPolicy. Call once at startup.\n\n```go\nfunc (h *EventHub) SetTopologyProvider(p topology.Provider)\n```\nSetTopologyProvider wires the mode-selected topology owner that answers host questions. Call once at startup, before the hub takes connections.\n\n```go\nfunc (h *EventHub) Start(ctx context.Context, snapshotInterval, batchInterval time.Duration)\n```\nStart begins the periodic flush loops. Call in a goroutine.\n\n```go\nfunc (h *EventHub) Stop()\n```\n\n```go\ntype Hub struct {\n\t// contains filtered or unexported fields\n}\n```\nHub is a buffered WebSocket broadcast hub.\n\nInstead of broadcasting each log individually (which would freeze the UI at high throughput), it buffers logs and flushes them as a JSON array when either:\n\n  - Buffer size \u003e= maxBufferSize (default: 100)\n  - Flush ticker fires (default: every 500ms)\n\n```go\nfunc NewHub(onConnectionChange func(count int)) *Hub\n```\nNewHub creates a new buffered WebSocket hub.\n\n```go\nfunc (h *Hub) ActiveClients() int64\n```\nActiveClients reports the count of currently-connected WebSocket clients. Updated atomically as connections are accepted and torn down.\n\n```go\nfunc (h *Hub) Broadcast(entry LogEntry)\n```\nBroadcast adds a log entry to the broadcast buffer. No-op in aggregate mode.\n\n```go\nfunc (h *Hub) BroadcastMetric(entry MetricEntry)\n```\nBroadcastMetric adds a metric entry to the broadcast buffer. No-op in aggregate mode.\n\n```go\nfunc (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request)\n```\nHandleWebSocket is the HTTP handler that upgrades connections to WebSocket.\n\n```go\nfunc (h *Hub) Run()\n```\nRun starts the hub's main event loop. Should be called in a goroutine.\n\n```go\nfunc (h *Hub) SetAggregateMode(on bool)\n```\nSetAggregateMode disables per-event log and metric broadcasts. Keepalive and connection handling are unaffected.\n\n```go\nfunc (h *Hub) SetDevMode(devMode bool)\n```\nSetDevMode controls whether cross-origin WebSocket connections are accepted. Should be true only in development environments.\n\n```go\nfunc (h *Hub) SetMaxClients(n int)\n```\nSetMaxClients caps simultaneous WebSocket connections. 0 disables the cap (default). Configure once at startup before HandleWebSocket starts taking traffic — the cap is read concurrently from each upgrade attempt.\n\n```go\nfunc (h *Hub) SetOriginPolicy(enforce bool, allowedHosts []string)\n```\nSetOriginPolicy configures WebSocket origin enforcement. When enforce is true the browser Origin header must match one of allowedHosts, or the request host when the list is empty. Call once at startup.\n\n```go\nfunc (h *Hub) SetTopologyProvider(provider topology.Provider, floor time.Duration)\n```\nSetTopologyProvider installs the construction-time provider used only for aggregate browser refresh notifications. Legacy raw batches are unchanged.\n\n```go\nfunc (h *Hub) SetWSMetrics(onMessageSent func(string), onSlowClientDrop func())\n```\nSetWSMetrics wires WebSocket metric callbacks.\n\n```go\nfunc (h *Hub) Stop()\n```\nStop gracefully shuts down the hub.\n\n```go\ntype HubBatch struct {\n\tType string `json:\"type\"` // \"logs\" or \"metrics\"\n\tData any    `json:\"data\"` // Slice of entries\n}\n```\nHubBatch is a unified payload for WebSocket broadcasts.\n\n```go\ntype LiveSnapshot struct {\n\tType       string                     `json:\"type\"`\n\tDashboard  *storage.DashboardStats    `json:\"dashboard\"`\n\tTraffic    []storage.TrafficPoint     `json:\"traffic\"`\n\tTraces     *storage.TracesResponse    `json:\"traces\"`\n\tServiceMap *storage.ServiceMapMetrics `json:\"service_map\"`\n\n\tEpoch        string `json:\"epoch,omitempty\"`\n\tRevision     uint64 `json:\"revision,omitempty\"`\n\tReset        bool   `json:\"reset,omitempty\"`\n\tCoverage     string `json:\"coverage,omitempty\"`\n\tCoverageNote string `json:\"coverage_note,omitempty\"`\n\tSource       string `json:\"source,omitempty\"`\n\tTruncated    bool   `json:\"truncated,omitempty\"`\n\n\tDroppedServices   uint64 `json:\"dropped_services,omitempty\"`\n\tDroppedOperations uint64 `json:\"dropped_operations,omitempty\"`\n\tDroppedEdges      uint64 `json:\"dropped_edges,omitempty\"`\n\tDroppedMetrics    uint64 `json:\"dropped_metrics,omitempty\"`\n}\n```\nLiveSnapshot is the data payload pushed to all event WS clients.\n\nThe identity and coverage fields are ADDITIVE and only populated in aggregate mode; \\`omitempty\\` keeps the legacy payload unchanged.\n\nA client replaces state by (series, window\\_start, revision) and RESETS wholesale when Epoch changes: the revision counter restarts at zero on every process generation, so revision alone cannot be trusted across a restart.\n\n```go\ntype LogEntry struct {\n\tTenant         string    `json:\"-\"`\n\tID             uint      `json:\"id\"`\n\tTraceID        string    `json:\"trace_id\"`\n\tSpanID         string    `json:\"span_id\"`\n\tSeverity       string    `json:\"severity\"`\n\tBody           string    `json:\"body\"`\n\tServiceName    string    `json:\"service_name\"`\n\tAttributesJSON string    `json:\"attributes_json\"`\n\tAIInsight      string    `json:\"ai_insight,omitempty\"`\n\tTimestamp      time.Time `json:\"timestamp\"`\n}\n```\nLogEntry is a lightweight struct for WebSocket broadcast payloads.\n\nTenant is transport-only: it decides which sockets may see the entry and is never serialized, so the wire payload is unchanged from before per-tenant scoping existed.\n\n```go\ntype MetricEntry struct {\n\tTenant      string         `json:\"-\"`\n\tName        string         `json:\"name\"`\n\tServiceName string         `json:\"service_name\"`\n\tValue       float64        `json:\"value\"`\n\tTimestamp   time.Time      `json:\"timestamp\"`\n\tAttributes  map[string]any `json:\"attributes\"`\n}\n```\nMetricEntry represents a raw metric point for real-time visualization. Tenant is transport-only — see LogEntry.\n\n","path":"github.com/RandomCodeSpace/otelcontext/internal/realtime","name":"realtime","synopsis":"","isRedistributable":true}
