Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

3.8 KB
Raw Blame
import { createAlertAcknowledgementRequests } from './alertAcknowledgementRequests';
import { createWebSocketStore, type ActiveAlertsHydrationStatus } from './websocket';
import { createSignal, createRoot } from 'solid-js';
import { createStore } from 'solid-js/store';
import { getPulseWebSocketUrl } from '@/utils/url';
import type { Alert, ResolvedAlert, State } from '@/types/api';

// Store the instance on window to survive hot reloads
declare global {
  interface Window {
    __pulseWsStore?: ReturnType<typeof createWebSocketStore>;
    __pulseWsShutdownBound?: boolean;
  }
}

const isJSDOMTestRuntime = () =>
  import.meta.env.MODE === 'test' &&
  typeof window !== 'undefined' &&
  /jsdom/i.test(window.navigator.userAgent);

const createNoopWebSocketStore = (): ReturnType<typeof createWebSocketStore> => {
  const [connected] = createSignal(false);
  const [reconnecting] = createSignal(false);
  const [initialDataReceived] = createSignal(true);
  const [activeAlertsHydrationStatus] = createSignal<ActiveAlertsHydrationStatus>('ready');
  const [updateProgress] = createSignal<unknown>(null);
  const [resourceChange] = createSignal<{
    version: number;
    changedIds: ReadonlySet<string> | null;
    changedKeys: import('@/utils/resourceStateAdapters').ResourceChangedKeys | null;
  }>({ version: 0, changedIds: null, changedKeys: null });
  // The no-op app's request owner lives as long as this store; shutdown ends
  // it, as the real store's shutdown does.
  const alertAcknowledgementRequests = createAlertAcknowledgementRequests();
  const [state] = createStore<State>({
    connectedInfrastructure: [],
    metrics: [],
    performance: {
      apiCallDuration: {},
      lastPollDuration: 0,
      pollingStartTime: '',
      totalApiCalls: 0,
      failedApiCalls: 0,
      cacheHits: 0,
      cacheMisses: 0,
    },
    connectionHealth: {},
    stats: {
      startTime: new Date().toISOString(),
      uptime: 0,
      pollingCycles: 0,
      webSocketClients: 0,
      version: '2.0.0',
    },
    activeAlerts: [],
    recentlyResolved: [],
    lastUpdate: 0,
    pveTagColors: {},
    pveTagStyles: {},
    resources: [],
  });

  return {
    state,
    activeAlerts: {} as Record<string, Alert>,
    recentlyResolved: {} as Record<string, ResolvedAlert>,
    connected,
    reconnecting,
    initialDataReceived,
    resourceSnapshotReceived: () => false,
    activeAlertsHydrationStatus,
    updateProgress,
    resourceChange,
    changedResourceIdsSince: () => null,
    changedResourceMetaSince: () => null,
    shutdown: () => alertAcknowledgementRequests.reset(),
    refreshActiveAlerts: async () => false,
    reconnect: () => {},
    switchUrl: () => {},
    markDockerRuntimesTokenRevoked: () => {},
    markAgentsTokenRevoked: () => {},
    alertAcknowledgementRequests,
    removeAlerts: () => {},
    updateAlert: () => {},
  };
};

// Ends this window's app store: it shuts down, and the next caller gets a new
// one. The page does this on unload; a test that used the shared store does it
// when it finishes, so nothing it left pending reaches the next test.
export function shutdownGlobalWebSocketStore() {
  window.__pulseWsStore?.shutdown();
  delete window.__pulseWsStore;
}

const bindGlobalShutdownHandler = () => {
  if (window.__pulseWsShutdownBound) return;

  window.addEventListener('beforeunload', shutdownGlobalWebSocketStore, { once: true });
  window.__pulseWsShutdownBound = true;
};

export function getGlobalWebSocketStore(): ReturnType<typeof createWebSocketStore> {
  if (!window.__pulseWsStore) {
    if (isJSDOMTestRuntime()) {
      window.__pulseWsStore = createNoopWebSocketStore();
      return window.__pulseWsStore;
    }

    const wsUrl = getPulseWebSocketUrl();

    createRoot(() => {
      window.__pulseWsStore = createWebSocketStore(wsUrl);
    });
    bindGlobalShutdownHandler();
  }

  return window.__pulseWsStore!;
}