Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Bound server state broadcast memory
rcourtmandcf541784deb
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 001c3e4893..7bd9b5d4e0 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -635,6 +635,13 @@ surface and no new `internal/api/` lifecycle handler.registrations are the only source that may display the operator-facingsuccess toast, while background agent registrations must update the ledgerwithout claiming the operator just added that node.+ Lifecycle-adjacent handlers that refresh browser state after agent reports+ or registration changes may emit canonical lifecycle events when the event+ contract requires it, but routine state refresh is an API/monitoring-owned+ current-state invalidation signal. Those handlers must not build or retain+ full frontend state in the lifecycle boundary, and lifecycle consumers must+ not treat a coalesced websocket state refresh as install, registration,+ command, or update proof.Shared `internal/api/` session and auth changes consumed by lifecycleroutes must preserve durable principal IDs as the authorization key. Agentlifecycle surfaces may display contact email when supplied by the shareddiff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex be4246cfe1..97447832f0 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -211,6 +211,11 @@ and severity-change re-notifications. Accepted alert dispatch must record`LastNotified` back onto the live active-alert state before persistence, evenwhen a restored or replayed alert is dispatched through a clone, so reloads donot reopen the same alert's notification window.+Recently resolved alerts are an operator-facing transition window, not an+unbounded history store. `recentlyResolved` must prune expired entries and cap+the newest retained entries on insert as well as during cleanup, so monitor+sync and websocket state snapshots remain bounded; durable resolved-alert+history belongs in the alert history store, not in this live transition cache.The browser thresholds surface is also platform-shaped: Proxmox, Docker,Kubernetes, TrueNAS, vSphere, PBS, PMG, and Systems. It must use the sharedFilterBar chip and "+ Filter" pattern for resource filtering, and alert tablesdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 2b51bcbd0c..6058dc9a13 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -159,6 +159,14 @@ checks. CSRF bootstrap checks may snapshot local auth, API-token, and proxysecret presence under that same lock, then evaluate SSO provider state outsidethe config lock.+WebSocket state refreshes triggered by API handlers are invalidation signals,+not a parallel API payload contract. `internal/api/agent_handlers_base.go` and+`internal/api/alerts.go` may check subscriber counts, then call+`BroadcastCurrentState` / `BroadcastCurrentStateToTenant`; they must not build+or retain full frontend-state payloads at the handler boundary. The WebSocket+hub owns tenant-aware state resolution after coalescing, through the same state+getter that backs the canonical `/api/state` payload.+Candidate import plans for PVE/PBS/PMG onboarding are API-contract consumers,not local UI estimates. Probe and Discovery candidates must build theirpreview through `frontend-modern/src/api/monitoredSystemLedger.ts` anddiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex ffbb74c6e1..47b166d9cd 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -184,6 +184,11 @@ truth for live infrastructure data.`/api/state` and websocket broadcasts must coalesce transient split hostresources before serialization so a single Proxmox node with a reportinghost agent remains one hybrid top-level system across rebuild ticks.+ High-frequency monitor ticker, mock-mode, and alert-resolution broadcast+ signals are current-state invalidations. They must call the WebSocket hub's+ lazy current-state broadcast path and let the hub resolve tenant-aware+ frontend state after coalescing; monitor callsites must not build or retain+ full frontend-state snapshots for supersedable broadcast signals.14. Add or change Proxmox-side LXC Docker detection or inventory through`internal/monitoring/docker_detection.go`,`internal/monitoring/monitor_pve_guest_poll.go`,diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 648a684bb8..98631dd4c9 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -148,6 +148,11 @@ regression protection.1. Add performance budgets through SLO or contract tests2. Add query-plan guardrails for DB-backed hot paths3. Optimize hot paths only when backed by benchmarks or proven query issues+ WebSocket state refreshes on monitor, agent-report, and alert mutation hot+ paths must enqueue coalesced current-state invalidations instead of building+ full frontend-state payloads at every signal. The hub owns delayed+ tenant-aware state resolution so superseded signals do not retain large+ state snapshots.The operations-loop status endpoint is performance-adjacent because itaggregates fleet, action-audit, workflow-starter, AI-usage, andexternal-agent activity evidence for every request. Starter and contextualdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 4aa4ed7012..78b324f2fc 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -588,6 +588,12 @@ recovery scope, or a storage/recovery-owned secret source.state payload must publish the same canonical resource types and displaylabels as `/api/resources` so storage and recovery do not momentarily switchbetween legacy and canonical infrastructure identities within one session.+ WebSocket current-state refreshes are an API/monitoring invalidation+ mechanism. Storage and recovery consumers may observe refreshed canonical+ resource, backup, and recovery state after the hub resolves the coalesced+ payload, but they must not treat the refresh event itself as backup+ evidence, recovery coverage proof, recovery-job state, or storage-health+ verification.Adjacent list surfaces that build `/api/resources` queries with standardbrowser encoders must also treat `%2C` separators the same as literalcomma-separated type filters, so storage and recovery consumers do not losediff --git a/internal/alerts/active_cleanup.go b/internal/alerts/active_cleanup.goindex a35c6e5b9d..bd42faa8c0 100644--- a/internal/alerts/active_cleanup.go+++ b/internal/alerts/active_cleanup.go@@ -139,13 +139,8 @@ func (m *Manager) Cleanup(maxAge time.Duration) {}}- fiveMinutesAgo := now.Add(-5 * time.Minute)m.resolvedMutex.Lock()- for alertID, resolved := range m.recentlyResolved {- if resolved.ResolvedTime.Before(fiveMinutesAgo) {- m.removeResolvedAlertUnlocked(alertID)- }- }+ m.pruneRecentlyResolvedUnlocked(now)m.resolvedMutex.Unlock()maxPendingAge := 10 * time.Minutediff --git a/internal/alerts/active_lifecycle.go b/internal/alerts/active_lifecycle.goindex 9e78910f22..8ef895e0f6 100644--- a/internal/alerts/active_lifecycle.go+++ b/internal/alerts/active_lifecycle.go@@ -2,6 +2,7 @@ package alertsimport ("fmt"+ "sort""strings""time"@@ -18,9 +19,45 @@ func (m *Manager) addRecentlyResolvedUnlocked(resolved *ResolvedAlert) {storageKey := activeAlertStorageKey(resolved.Alert, resolved.Alert.ID)m.recentlyResolved[storageKey] = resolvedm.registerResolvedAliasUnlocked(storageKey, resolved)+ m.pruneRecentlyResolvedUnlocked(time.Now())m.resolvedMutex.Unlock()}+func (m *Manager) pruneRecentlyResolvedUnlocked(now time.Time) {+ type candidate struct {+ key string+ resolvedAt time.Time+ }++ cutoff := now.Add(-recentlyResolvedRetention)+ candidates := make([]candidate, 0, len(m.recentlyResolved))+ for key, resolved := range m.recentlyResolved {+ if resolved == nil || resolved.ResolvedTime.Before(cutoff) {+ m.removeResolvedAlertUnlocked(key)+ continue+ }+ candidates = append(candidates, candidate{key: key, resolvedAt: resolved.ResolvedTime})+ }++ overflow := len(m.recentlyResolved) - maxRecentlyResolvedAlerts+ if overflow <= 0 {+ return+ }++ sort.Slice(candidates, func(i, j int) bool {+ return candidates[i].resolvedAt.Before(candidates[j].resolvedAt)+ })++ for _, candidate := range candidates {+ if overflow <= 0 {+ return+ }+ if _, removed := m.removeResolvedAlertUnlocked(candidate.key); removed {+ overflow--+ }+ }+}+// addRecentlyResolvedWithPrimaryLock records a resolved alert while preserving the caller's// ownership of m.mu. Callers must hold m.mu before invoking this helper.func (m *Manager) addRecentlyResolvedWithPrimaryLock(resolved *ResolvedAlert) {diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.goindex 7ee13e44a2..fb9397587d 100644--- a/internal/alerts/alerts_test.go+++ b/internal/alerts/alerts_test.go@@ -19255,3 +19255,42 @@ func addDeliveryDiagnosisAlert(manager *Manager, alert *Alert) *Alert {manager.activeAlerts[alert.ID] = alertreturn alert}++func TestRecentlyResolvedPrunesExpiredEntriesOnInsert(t *testing.T) {+ manager := NewManager()+ t.Cleanup(manager.Stop)++ manager.addRecentlyResolvedUnlocked(&ResolvedAlert{+ Alert: &Alert{ID: "expired-alert"},+ ResolvedTime: time.Now().Add(-recentlyResolvedRetention - time.Minute),+ })++ if resolved := manager.GetResolvedAlert("expired-alert"); resolved != nil {+ t.Fatalf("expired recently resolved alert was retained: %#v", resolved)+ }+}++func TestRecentlyResolvedCapsNewestEntries(t *testing.T) {+ manager := NewManager()+ t.Cleanup(manager.Stop)++ start := time.Now().Add(-time.Minute)+ for i := 0; i < maxRecentlyResolvedAlerts+3; i++ {+ manager.addRecentlyResolvedUnlocked(&ResolvedAlert{+ Alert: &Alert{ID: fmt.Sprintf("resolved-%04d", i)},+ ResolvedTime: start.Add(time.Duration(i) * time.Millisecond),+ })+ }++ resolved := manager.GetRecentlyResolved()+ if len(resolved) != maxRecentlyResolvedAlerts {+ t.Fatalf("recently resolved count = %d, want %d", len(resolved), maxRecentlyResolvedAlerts)+ }++ if manager.GetResolvedAlert("resolved-0000") != nil {+ t.Fatal("oldest overflow entry was retained")+ }+ if manager.GetResolvedAlert(fmt.Sprintf("resolved-%04d", maxRecentlyResolvedAlerts+2)) == nil {+ t.Fatal("newest recently resolved entry was pruned")+ }+}diff --git a/internal/alerts/constants.go b/internal/alerts/constants.goindex 84709da74a..82527ce4bf 100644--- a/internal/alerts/constants.go+++ b/internal/alerts/constants.go@@ -5,6 +5,8 @@ import "time"const (StaleTrackingThreshold = 24 * time.HourRateLimitCleanupWindow = 1 * time.Hour+ recentlyResolvedRetention = 5 * time.Minute+ maxRecentlyResolvedAlerts = 1024alertsDirPerm = 0o700alertsFilePerm = 0o600offlineRecoveryConfirmationsDefault = 3diff --git a/internal/api/agent_handlers_base.go b/internal/api/agent_handlers_base.goindex 66595e093e..d30dcf5d35 100644--- a/internal/api/agent_handlers_base.go+++ b/internal/api/agent_handlers_base.go@@ -91,10 +91,9 @@ func (b *baseAgentHandlers) broadcastState(ctx context.Context) {return}- state := monitor.BuildFrontendState()if orgID != "" {- go b.wsHub.BroadcastStateToTenant(orgID, state)+ b.wsHub.BroadcastCurrentStateToTenant(orgID)return}- go b.wsHub.BroadcastState(state)+ b.wsHub.BroadcastCurrentState()}diff --git a/internal/api/alerts.go b/internal/api/alerts.goindex 7bfc8fb555..cbc2335e9e 100644--- a/internal/api/alerts.go+++ b/internal/api/alerts.go@@ -128,12 +128,15 @@ func (h *AlertHandlers) broadcastStateForContext(ctx context.Context) {return}- frontendState := h.getMonitor(ctx).BuildFrontendState()+ monitor := h.getMonitor(ctx)+ if monitor == nil {+ return+ }if orgID != "" {- h.wsHub.BroadcastStateToTenant(orgID, frontendState)+ h.wsHub.BroadcastCurrentStateToTenant(orgID)return}- h.wsHub.BroadcastState(frontendState)+ h.wsHub.BroadcastCurrentState()}// validateAlertIdentifier validates an alert identifier for security.diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 761f885171..eba9507409 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -19655,3 +19655,51 @@ func TestContract_LocalAuthConfigReadsUseSharedLock(t *testing.T) {}}}++func TestContract_StateBroadcastsUseLazyCurrentStateInvalidation(t *testing.T) {+ expectations := map[string]struct {+ required []string+ forbidden []string+ }{+ "agent_handlers_base.go": {+ required: []string{+ "b.wsHub.BroadcastCurrentStateToTenant(orgID)",+ "b.wsHub.BroadcastCurrentState()",+ },+ forbidden: []string{+ "monitor.BuildFrontendState()",+ "BroadcastStateToTenant(orgID, state)",+ "BroadcastState(state)",+ },+ },+ "alerts.go": {+ required: []string{+ "h.wsHub.BroadcastCurrentStateToTenant(orgID)",+ "h.wsHub.BroadcastCurrentState()",+ },+ forbidden: []string{+ "h.getMonitor(ctx).BuildFrontendState()",+ "BroadcastStateToTenant(orgID, frontendState)",+ "BroadcastState(frontendState)",+ },+ },+ }++ for file, expectation := range expectations {+ sourceBytes, err := os.ReadFile(file)+ if err != nil {+ t.Fatalf("read %s: %v", file, err)+ }+ source := string(sourceBytes)+ for _, snippet := range expectation.required {+ if !strings.Contains(source, snippet) {+ t.Fatalf("%s must contain lazy state invalidation primitive %q", file, snippet)+ }+ }+ for _, snippet := range expectation.forbidden {+ if strings.Contains(source, snippet) {+ t.Fatalf("%s must not eagerly build or broadcast full state at mutation boundary: found %q", file, snippet)+ }+ }+ }+}diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 19b6aef130..50bfc52842 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -2437,3 +2437,41 @@ func TestAgentFleetDoctorStaysReadOnlyProjection(t *testing.T) {}}}++func TestStateBroadcastSignalsUseLazyCurrentState(t *testing.T) {+ monitorSourceBytes, err := os.ReadFile("monitor.go")+ if err != nil {+ t.Fatalf("read monitor.go: %v", err)+ }+ monitorSource := string(monitorSourceBytes)+ for _, required := range []string{+ "m.broadcastCurrentState(wsHub)",+ "m.broadcastCurrentState(hub)",+ "hub.BroadcastCurrentStateToTenant(orgID)",+ "hub.BroadcastCurrentState()",+ } {+ if !strings.Contains(monitorSource, required) {+ t.Fatalf("monitor.go must contain lazy state broadcast primitive %q", required)+ }+ }+ for _, forbidden := range []string{+ "m.buildBroadcastFrontendStateFromSnapshot(state)\n\t\t\tm.broadcastState(wsHub",+ "frontendState := m.buildBroadcastFrontendStateFromSnapshot(m.GetState())",+ } {+ if strings.Contains(monitorSource, forbidden) {+ t.Fatalf("monitor.go must not build full frontend state at high-frequency broadcast callsite %q", forbidden)+ }+ }++ alertSourceBytes, err := os.ReadFile("monitor_alerts.go")+ if err != nil {+ t.Fatalf("read monitor_alerts.go: %v", err)+ }+ alertSource := string(alertSourceBytes)+ if !strings.Contains(alertSource, "m.broadcastCurrentState(hub)") {+ t.Fatal("monitor_alerts.go must signal lazy current-state broadcasts")+ }+ if strings.Contains(alertSource, "m.BuildBroadcastFrontendState()") {+ t.Fatal("monitor_alerts.go must not build full frontend state for alert-driven broadcast signals")+ }+}diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 0f3101ebae..fc415c90f9 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1908,12 +1908,10 @@ func (m *Monitor) Start(ctx context.Context, wsHub *websocket.Hub) {Int("pbsBackups", len(state.Backups.PBS)).Int("physicalDisks", len(state.PhysicalDisks)).Msg("Broadcasting state update (ticker)")- if !stateBroadcasterHasSubscribers(wsHub, m.GetOrgID()) {+ if !currentStateBroadcasterHasSubscribers(wsHub, m.GetOrgID()) {continue}- frontendState := m.buildBroadcastFrontendStateFromSnapshot(state)- // Use tenant-aware broadcast method- m.broadcastState(wsHub, frontendState)+ m.broadcastCurrentState(wsHub)case <-ctx.Done():log.Info().Msg("monitoring loop stopped")@@ -3882,6 +3880,11 @@ type stateBroadcaster interface {BroadcastStateToTenant(orgID string, state interface{})}+type currentStateBroadcaster interface {+ BroadcastCurrentState()+ BroadcastCurrentStateToTenant(orgID string)+}+type stateSubscriberCounter interface {GetClientCount() intGetTenantClientCount(orgID string) int@@ -3904,6 +3907,23 @@ func stateBroadcasterHasSubscribers(hub stateBroadcaster, orgID string) bool {return counter.GetClientCount() > 0}+func currentStateBroadcasterHasSubscribers(hub currentStateBroadcaster, orgID string) bool {+ if isNilCurrentStateBroadcaster(hub) {+ return false+ }++ counter, ok := hub.(stateSubscriberCounter)+ if !ok {+ return true+ }++ orgID = strings.TrimSpace(orgID)+ if orgID != "" {+ return counter.GetTenantClientCount(orgID) > 0+ }+ return counter.GetClientCount() > 0+}+// broadcastState broadcasts state to WebSocket clients.// Monitors with an explicit org ID (including "default") are tenant-scoped.// Legacy monitors without an org ID broadcast globally.@@ -3923,6 +3943,22 @@ func (m *Monitor) broadcastState(hub stateBroadcaster, frontendState interface{}}}+func (m *Monitor) broadcastCurrentState(hub currentStateBroadcaster) {+ if isNilCurrentStateBroadcaster(hub) {+ return+ }++ orgID := strings.TrimSpace(m.GetOrgID())+ if !currentStateBroadcasterHasSubscribers(hub, orgID) {+ return+ }+ if orgID != "" {+ hub.BroadcastCurrentStateToTenant(orgID)+ } else {+ hub.BroadcastCurrentState()+ }+}+func isNilStateBroadcaster(hub stateBroadcaster) bool {if hub == nil {return true@@ -3937,6 +3973,20 @@ func isNilStateBroadcaster(hub stateBroadcaster) bool {}}+func isNilCurrentStateBroadcaster(hub currentStateBroadcaster) bool {+ if hub == nil {+ return true+ }++ value := reflect.ValueOf(hub)+ switch value.Kind() {+ case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:+ return value.IsNil()+ default:+ return false+ }+}+func (m *Monitor) broadcastEscalatedAlert(hub *websocket.Hub, alert *alerts.Alert) {if hub == nil || alert == nil {return@@ -3989,10 +4039,8 @@ func (m *Monitor) SetMockMode(enable bool) error {hub := m.wsHubm.mu.RUnlock()- if hub != nil && stateBroadcasterHasSubscribers(hub, m.GetOrgID()) {- frontendState := m.buildBroadcastFrontendStateFromSnapshot(m.GetState())- // Use tenant-aware broadcast method- m.broadcastState(hub, frontendState)+ if hub != nil {+ m.broadcastCurrentState(hub)}if enable && ctx != nil && keepRealPollingInMockMode() {diff --git a/internal/monitoring/monitor_alerts.go b/internal/monitoring/monitor_alerts.goindex e642caa699..b58adfb1a4 100644--- a/internal/monitoring/monitor_alerts.go+++ b/internal/monitoring/monitor_alerts.go@@ -278,13 +278,7 @@ func (m *Monitor) broadcastStateUpdate() {if hub == nil {return}- if !stateBroadcasterHasSubscribers(hub, m.GetOrgID()) {- return- }-- frontendState := m.BuildBroadcastFrontendState()- // Use tenant-aware broadcast method- m.broadcastState(hub, frontendState)+ m.broadcastCurrentState(hub)}// recordAuthFailure records an authentication failure for a nodediff --git a/internal/websocket/hub.go b/internal/websocket/hub.goindex c03bdd7531..518163d3d9 100644--- a/internal/websocket/hub.go+++ b/internal/websocket/hub.go@@ -373,6 +373,10 @@ type TenantBroadcast struct {Message Message}+type stateBroadcastRequest struct {+ orgID string+}+// OrgAuthChecker checks if a user/token can access an organization.type OrgAuthChecker interface {// CanAccessOrg checks if the given user (and optional token) can access the org.@@ -470,12 +474,19 @@ func (h *Hub) hasStateGetter() bool {// getStateForClient returns the state for a specific client based on their tenantfunc (h *Hub) getStateForClient(client *Client) interface{} {+ if client == nil {+ return h.getStateForOrg("")+ }+ return h.getStateForOrg(client.orgID)+}++func (h *Hub) getStateForOrg(orgID string) interface{} {h.mu.RLock()getState := h.getStateh.mu.RUnlock()if getState != nil {- return getState(normalizeOrgID(client.orgID))+ return getState(normalizeOrgID(orgID))}return nil@@ -922,6 +933,65 @@ func (h *Hub) popCoalescedMessage() *Message {return &msg}+func (h *Hub) messageHasCurrentStateRequest(msg Message) (stateBroadcastRequest, bool) {+ req, ok := msg.Data.(stateBroadcastRequest)+ return req, ok+}++func (h *Hub) hasRecipientsForMessage(msg Message, orgID string) bool {+ if _, ok := h.messageHasCurrentStateRequest(msg); !ok {+ return true+ }+ if orgID != "" {+ return h.GetTenantClientCount(orgID) > 0+ }+ return h.GetClientCount() > 0+}++func (h *Hub) prepareMessageForMarshal(msg Message, orgID string) (Message, bool) {+ req, ok := h.messageHasCurrentStateRequest(msg)+ if !ok {+ return msg, true+ }++ requestOrgID := strings.TrimSpace(req.orgID)+ if requestOrgID == "" {+ requestOrgID = orgID+ }++ h.mu.RLock()+ hasGetter := h.getState != nil+ h.mu.RUnlock()+ if !hasGetter {+ log.Warn().+ Str("component", websocketHubComponent).+ Str("action", "current_state_broadcast_skipped_missing_getter").+ Str("org_id", normalizeOrgID(requestOrgID)).+ Msg("Skipping current state broadcast because no state getter is configured")+ return Message{}, false+ }++ msg.Data = h.prepareStateForBroadcast(h.getStateForOrg(requestOrgID))+ return msg, true+}++func (h *Hub) marshalBroadcastMessage(msg Message, orgID string) ([]byte, bool) {+ prepared, ok := h.prepareMessageForMarshal(msg, orgID)+ if !ok {+ return nil, false+ }+ data, err := json.Marshal(prepared)+ if err != nil {+ if orgID != "" {+ log.Error().Err(err).Str("org_id", orgID).Str("type", prepared.Type).Msg("Failed to marshal tenant broadcast message")+ } else {+ log.Error().Err(err).Str("type", prepared.Type).Msg("Failed to marshal broadcast message")+ }+ return nil, false+ }+ return data, true+}+// runBroadcastSequencer handles sequenced broadcasts with coalescing for rapid state updatesfunc (h *Hub) runBroadcastSequencer() {for {@@ -944,10 +1014,11 @@ func (h *Hub) runBroadcastSequencer() {h.coalesceTimer = time.AfterFunc(h.coalesceWindow, func() {pending := h.popCoalescedMessage()if pending != nil {- if data, err := json.Marshal(*pending); err == nil {+ if !h.hasRecipientsForMessage(*pending, "") {+ return+ }+ if data, ok := h.marshalBroadcastMessage(*pending, ""); ok {h.dispatchToClients(data, "Client send channel full, dropping coalesced message and closing connection")- } else {- log.Error().Err(err).Str("type", pending.Type).Msg("Failed to marshal coalesced broadcast message")}}})@@ -955,10 +1026,8 @@ func (h *Hub) runBroadcastSequencer() {h.coalesceMutex.Unlock()} else {// Non-state messages (alerts, etc.) - send immediately- if data, err := json.Marshal(msg); err == nil {+ if data, ok := h.marshalBroadcastMessage(msg, ""); ok {h.dispatchToClients(data, "Client send channel full, dropping message and closing connection")- } else {- log.Error().Err(err).Str("type", msg.Type).Msg("Failed to marshal broadcast message")}}@@ -986,10 +1055,11 @@ func (h *Hub) runBroadcastSequencer() {h.coalesceMutex.Unlock()if pending != nil {- if data, err := json.Marshal(*pending); err == nil {+ if !h.hasRecipientsForMessage(*pending, orgID) {+ return+ }+ if data, ok := h.marshalBroadcastMessage(*pending, orgID); ok {h.dispatchToTenantClients(orgID, data, "Client send channel full, dropping tenant coalesced message and closing connection")- } else {- log.Error().Err(err).Str("org_id", orgID).Str("type", pending.Type).Msg("Failed to marshal tenant coalesced broadcast message")}}})@@ -997,10 +1067,8 @@ func (h *Hub) runBroadcastSequencer() {h.coalesceMutex.Unlock()} else {// Non-state messages - send immediately to tenant- if data, err := json.Marshal(tb.Message); err == nil {+ if data, ok := h.marshalBroadcastMessage(tb.Message, tb.OrgID); ok {h.dispatchToTenantClients(tb.OrgID, data, "Client send channel full, dropping tenant message and closing connection")- } else {- log.Error().Err(err).Str("org_id", tb.OrgID).Str("type", tb.Message.Type).Msg("Failed to marshal tenant broadcast message")}}@@ -1052,6 +1120,33 @@ func (h *Hub) BroadcastState(state interface{}) {}}+// BroadcastCurrentState coalesces a state-change signal and resolves the current+// tenant-aware state only when the broadcast window is ready to flush.+func (h *Hub) BroadcastCurrentState() {+ if h.isStopping() {+ log.Debug().Msg("Skipping current state broadcast while hub is stopping")+ return+ }++ log.Debug().Msg("broadcasting current state")+ msg := Message{+ Type: "rawData",+ Data: stateBroadcastRequest{},+ }++ select {+ case h.broadcastSeq <- msg:+ default:+ log.Warn().+ Str("component", websocketHubComponent).+ Str("action", "enqueue_state_dropped").+ Str("channel", "broadcast_seq").+ Int("channel_depth", len(h.broadcastSeq)).+ Int("channel_capacity", cap(h.broadcastSeq)).+ Msg("Broadcast sequencer channel full, dropping state update")+ }+}+// BroadcastStateToTenant broadcasts state update only to clients of a specific tenant.func (h *Hub) BroadcastStateToTenant(orgID string, state interface{}) {if h.isStopping() {@@ -1082,6 +1177,35 @@ func (h *Hub) BroadcastStateToTenant(orgID string, state interface{}) {}}+// BroadcastCurrentStateToTenant coalesces a tenant state-change signal and+// resolves that tenant's current state only when the broadcast window flushes.+func (h *Hub) BroadcastCurrentStateToTenant(orgID string) {+ orgID = normalizeOrgID(orgID)+ if h.isStopping() {+ log.Debug().Str("org_id", orgID).Msg("Skipping tenant current state broadcast while hub is stopping")+ return+ }++ log.Debug().Str("org_id", orgID).Msg("Broadcasting current state to tenant")+ msg := Message{+ Type: "rawData",+ Data: stateBroadcastRequest{orgID: orgID},+ }++ select {+ case h.tenantBroadcast <- TenantBroadcast{OrgID: orgID, Message: msg}:+ default:+ log.Warn().+ Str("component", websocketHubComponent).+ Str("action", "enqueue_tenant_state_dropped").+ Str("org_id", orgID).+ Str("channel", "tenant_broadcast").+ Int("channel_depth", len(h.tenantBroadcast)).+ Int("channel_capacity", cap(h.tenantBroadcast)).+ Msg("Tenant broadcast channel full, dropping state update")+ }+}+// dispatchToTenantClients sends a message only to clients of a specific tenant.func (h *Hub) dispatchToTenantClients(orgID string, data []byte, dropLog string) {h.mu.RLock()diff --git a/internal/websocket/hub_test.go b/internal/websocket/hub_test.goindex 73a0bf4759..2e2b8b2a4c 100644--- a/internal/websocket/hub_test.go+++ b/internal/websocket/hub_test.go@@ -1,6 +1,7 @@package websocketimport (+ "encoding/json""math""net/http""testing"@@ -935,3 +936,76 @@ func TestHub_CheckOrigin_UntrustedProxyIgnoresForwarded(t *testing.T) {t.Error("checkOrigin should reject forwarded headers from untrusted peers")}}++func TestBroadcastCurrentStateEnqueuesLazyStateRequest(t *testing.T) {+ getterCalls := 0+ hub := NewHub(func(orgID string) interface{} {+ getterCalls+++ return map[string]string{"org": orgID}+ })++ hub.BroadcastCurrentState()++ msg := <-hub.broadcastSeq+ if msg.Type != "rawData" {+ t.Fatalf("message type = %q, want rawData", msg.Type)+ }+ if _, ok := msg.Data.(stateBroadcastRequest); !ok {+ t.Fatalf("message data = %T, want stateBroadcastRequest", msg.Data)+ }+ if getterCalls != 0 {+ t.Fatalf("state getter called before coalesced flush: %d", getterCalls)+ }++ data, ok := hub.marshalBroadcastMessage(msg, "")+ if !ok {+ t.Fatal("expected lazy state request to marshal")+ }+ if getterCalls != 1 {+ t.Fatalf("state getter calls after marshal = %d, want 1", getterCalls)+ }++ var decoded Message+ if err := json.Unmarshal(data, &decoded); err != nil {+ t.Fatalf("unmarshal broadcast message: %v", err)+ }+ payload := decoded.Data.(map[string]interface{})+ if payload["org"] != "default" {+ t.Fatalf("lazy state org = %v, want default", payload["org"])+ }+}++func TestBroadcastCurrentStateToTenantResolvesTenantState(t *testing.T) {+ var requestedOrg string+ hub := NewHub(func(orgID string) interface{} {+ requestedOrg = orgID+ return map[string]string{"org": orgID}+ })++ hub.BroadcastCurrentStateToTenant("org-123")++ tb := <-hub.tenantBroadcast+ if tb.OrgID != "org-123" {+ t.Fatalf("tenant broadcast org = %q, want org-123", tb.OrgID)+ }+ if _, ok := tb.Message.Data.(stateBroadcastRequest); !ok {+ t.Fatalf("tenant message data = %T, want stateBroadcastRequest", tb.Message.Data)+ }++ data, ok := hub.marshalBroadcastMessage(tb.Message, tb.OrgID)+ if !ok {+ t.Fatal("expected tenant lazy state request to marshal")+ }+ if requestedOrg != "org-123" {+ t.Fatalf("state getter org = %q, want org-123", requestedOrg)+ }++ var decoded Message+ if err := json.Unmarshal(data, &decoded); err != nil {+ t.Fatalf("unmarshal tenant broadcast message: %v", err)+ }+ payload := decoded.Data.(map[string]interface{})+ if payload["org"] != "org-123" {+ t.Fatalf("lazy tenant state org = %v, want org-123", payload["org"])+ }+}diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.pyindex 70d5c5b512..672304eb38 100644--- a/scripts/release_control/subsystem_lookup_test.py+++ b/scripts/release_control/subsystem_lookup_test.py@@ -2917,7 +2917,7 @@ class SubsystemLookupTest(unittest.TestCase):{"heading": "## Shared Boundaries","path": "internal/api/access_control_handlers.go",- "line": 1131,+ "line": 1139,"heading_line": 137,}],