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.

17.8 KB
Raw Blame
import {
  batch,
  createEffect,
  createMemo,
  createSignal,
  onCleanup,
  onMount,
  untrack,
} from 'solid-js';
import type { Accessor } from 'solid-js';
import { useLocation, useNavigate } from '@solidjs/router';

import { AlertsAPI } from '@/api/alerts';
import { eventBus } from '@/stores/events';
import { notificationStore } from '@/stores/notifications';
import type { Alert } from '@/types/api';
import type { Resource } from '@/types/resource';
import { STORAGE_KEYS } from '@/utils/localStorage';
import { logger } from '@/utils/logger';
import { ALERT_HISTORY_QUERY_PARAMS } from '@/routing/resourceLinks';
import {
  getAlertAdministrationClearHistoryError,
  getAlertAdministrationClearHistoryConfirmation,
} from '@/utils/alertAdministrationPresentation';

import {
  applyAlertHistoryWindow,
  buildAlertAxisTicks,
  buildAlertHistoryItems,
  buildAlertHistoryParams,
  buildAlertRangeSummary,
  buildAlertTrends,
  buildSelectedBucketDetails,
  filterAlertHistoryItems,
  formatAlertBucketRange,
  getAlertBucketDurationLabel,
  getIncidentRowKey,
  groupAlertHistoryItems,
  type AlertHistoryRange,
  type AlertSeverityFilter,
  type HistoryItem,
} from './alertHistoryModel';
import { useAlertIncidentTimelineState } from './useAlertIncidentTimelineState';
import { useAlertResourceIncidentsState } from './useAlertResourceIncidentsState';

export interface UseAlertHistoryStateProps {
  activeAlerts: Accessor<Record<string, Alert>>;
  getResource: (resourceId: string) => Resource | undefined;
  allResources: () => Resource[];
  /**
   * Whether the live alert list has arrived. Saved history holds resolved
   * alerts only, so a linked alert that is still firing is unknown until it
   * does; without this, History would widen or report it missing too early.
   */
  activeAlertsSettled?: () => boolean;
}

const DEFAULT_TIME_FILTER: AlertHistoryRange = '7d';
const DEFAULT_SEVERITY_FILTER: AlertSeverityFilter = 'all';

const parsePeriod = (raw: string | null | undefined): AlertHistoryRange =>
  raw === '24h' || raw === '7d' || raw === '30d' || raw === 'all' ? raw : DEFAULT_TIME_FILTER;

const parseSeverity = (raw: string | null | undefined): AlertSeverityFilter =>
  raw === 'info' || raw === 'warning' || raw === 'critical' ? raw : DEFAULT_SEVERITY_FILTER;

export function useAlertHistoryState(props: UseAlertHistoryStateProps) {
  const location = useLocation();
  const navigate = useNavigate();

  const timeFilter: Accessor<AlertHistoryRange> = () =>
    parsePeriod(new URLSearchParams(location.search).get(ALERT_HISTORY_QUERY_PARAMS.period));
  const severityFilter: Accessor<AlertSeverityFilter> = () =>
    parseSeverity(new URLSearchParams(location.search).get(ALERT_HISTORY_QUERY_PARAMS.severity));
  const searchTerm: Accessor<string> = () =>
    new URLSearchParams(location.search).get(ALERT_HISTORY_QUERY_PARAMS.query) ?? '';

  const updateSearchParam = (mutate: (params: URLSearchParams) => void): void => {
    const params = new URLSearchParams(location.search);
    mutate(params);
    const query = params.toString();
    navigate(`${location.pathname}${query ? `?${query}` : ''}`, { replace: true });
  };

  const setTimeFilter = (value: AlertHistoryRange): void => {
    updateSearchParam((params) => {
      if (value === DEFAULT_TIME_FILTER) {
        params.delete(ALERT_HISTORY_QUERY_PARAMS.period);
      } else {
        params.set(ALERT_HISTORY_QUERY_PARAMS.period, value);
      }
    });
  };

  const setSeverityFilter = (value: AlertSeverityFilter): void => {
    updateSearchParam((params) => {
      if (value === DEFAULT_SEVERITY_FILTER) {
        params.delete(ALERT_HISTORY_QUERY_PARAMS.severity);
      } else {
        params.set(ALERT_HISTORY_QUERY_PARAMS.severity, value);
      }
    });
  };

  const setSearchTerm = (value: string): void => {
    updateSearchParam((params) => {
      if (value === '') {
        params.delete(ALERT_HISTORY_QUERY_PARAMS.query);
      } else {
        params.set(ALERT_HISTORY_QUERY_PARAMS.query, value);
      }
    });
  };

  // A notification links to one alert (`buildAlertHistoryAlertPath`): History
  // narrows to that alert's occurrences until the operator shows all again.
  const focusedAlertId: Accessor<string> = () =>
    new URLSearchParams(location.search).get(ALERT_HISTORY_QUERY_PARAMS.alert)?.trim() ?? '';

  const clearFocusedAlert = (): void => {
    updateSearchParam((params) => params.delete(ALERT_HISTORY_QUERY_PARAMS.alert));
  };

  const [alertHistory, setAlertHistory] = createSignal<Alert[]>([]);
  const [loadedHistoryRange, setLoadedHistoryRange] = createSignal<AlertHistoryRange | null>(null);
  const [loading, setLoading] = createSignal(true);
  const [historyLoadError, setHistoryLoadError] = createSignal(false);
  const [selectedBarIndex, setSelectedBarIndex] = createSignal<number | null>(null);
  const resourceIncidentsState = useAlertResourceIncidentsState();

  const {
    incidentTimelines,
    incidentLoading,
    incidentErrors,
    expandedIncidents,
    incidentNoteDrafts,
    incidentNoteSaving,
    eventFilters,
    setEventFilters,
    resetState,
    loadIncidentTimeline,
    toggleIncidentTimeline,
    setIncidentNoteDraft,
    saveIncidentNote,
  } = useAlertIncidentTimelineState();

  const activeFilterCount = createMemo(() => {
    let count = 0;
    if (searchTerm().trim()) count++;
    if (timeFilter() !== '7d') count++;
    if (severityFilter() !== 'all') count++;
    return count;
  });

  const clearFilters = (): void => {
    updateSearchParam((params) => {
      params.delete(ALERT_HISTORY_QUERY_PARAMS.query);
      params.delete(ALERT_HISTORY_QUERY_PARAMS.period);
      params.delete(ALERT_HISTORY_QUERY_PARAMS.severity);
    });
    setSelectedBarIndex(null);
  };

  const userLocale =
    Intl.DateTimeFormat().resolvedOptions().locale ||
    (typeof navigator !== 'undefined' ? navigator.language : undefined) ||
    'en-US';

  // Row timestamps render clock time only; the date lives in the day group
  // header, which scrolls out of sight in a long history. Hovering a row gives
  // the absolute date and time so a reader never has to scroll back up to work
  // out which day they are looking at (#1687).
  const formatAlertRowTime = (startTime: string) =>
    new Date(startTime).toLocaleTimeString(userLocale, {
      hour: '2-digit',
      minute: '2-digit',
    });
  const formatAlertRowTimestamp = (startTime: string) =>
    new Date(startTime).toLocaleString(userLocale, {
      dateStyle: 'full',
      timeStyle: 'medium',
    });

  let fetchRequestId = 0;
  let historyContextVersion = 0;
  let disposed = false;
  let requestedRange: AlertHistoryRange | null = null;
  const fetchHistory = async (range: AlertHistoryRange) => {
    if (disposed) return;
    const requestId = ++fetchRequestId;
    if (requestedRange !== range) setHistoryLoadError(false);
    requestedRange = range;
    setLoading(true);

    try {
      const alertHistoryData = await AlertsAPI.getHistory(buildAlertHistoryParams(range));
      if (requestId === fetchRequestId) {
        batch(() => {
          setAlertHistory(alertHistoryData);
          setLoadedHistoryRange(range);
          setHistoryLoadError(false);
        });
      }
    } catch (error) {
      if (requestId === fetchRequestId) {
        setHistoryLoadError(true);
        logger.error('Failed to load history:', error);
      }
    } finally {
      if (requestId === fetchRequestId) {
        setLoading(false);
      }
    }
  };

  // An explicit retry is a read, not history deletion or notification replay.
  const retryHistory = () => {
    if (loading() || disposed) return;
    return fetchHistory(timeFilter());
  };

  let lastTimeFilterValue: string | null = null;
  createEffect(() => {
    const current = timeFilter();
    if (lastTimeFilterValue !== null && current !== lastTimeFilterValue) {
      setSelectedBarIndex(null);
    }
    lastTimeFilterValue = current;
  });

  let lastSeverityFilterValue: string | null = null;
  createEffect(() => {
    const current = severityFilter();
    if (lastSeverityFilterValue !== null && current !== lastSeverityFilterValue) {
      setSelectedBarIndex(null);
    }
    lastSeverityFilterValue = current;
  });

  onMount(() => {
    // Migrate legacy localStorage-backed filter prefs into the URL on first
    // visit after upgrade. Keeps the dead localStorage keys in place rather
    // than evicting them; harmless and avoids an eviction migration.
    if (typeof window !== 'undefined') {
      const params = new URLSearchParams(window.location.search);
      let mutated = false;

      if (!params.has(ALERT_HISTORY_QUERY_PARAMS.period)) {
        const legacy = window.localStorage.getItem('alertHistoryTimeFilter');
        const parsed = parsePeriod(legacy);
        if (parsed !== DEFAULT_TIME_FILTER && legacy === parsed) {
          params.set(ALERT_HISTORY_QUERY_PARAMS.period, parsed);
          mutated = true;
        }
      }

      if (!params.has(ALERT_HISTORY_QUERY_PARAMS.severity)) {
        const legacy = window.localStorage.getItem('alertHistorySeverityFilter');
        const parsed = parseSeverity(legacy);
        if (parsed !== DEFAULT_SEVERITY_FILTER && legacy === parsed) {
          params.set(ALERT_HISTORY_QUERY_PARAMS.severity, parsed);
          mutated = true;
        }
      }

      if (mutated) {
        navigate(`${location.pathname}?${params.toString()}`, { replace: true });
      }
    }

    void fetchHistory(timeFilter());

    const unsubscribeOrgSwitched = eventBus.on('org_switched', () => {
      historyContextVersion++;
      setAlertHistory([]);
      setLoadedHistoryRange(null);
      setHistoryLoadError(false);
      requestedRange = null;
      setSelectedBarIndex(null);
      resourceIncidentsState.resetResourceIncidentsState();
      resetState();
      void fetchHistory(timeFilter());
    });

    onCleanup(() => {
      disposed = true;
      unsubscribeOrgSwitched();
      fetchRequestId++;
    });
  });

  let skipInitialFetchEffect = true;
  createEffect(() => {
    const range = timeFilter();
    if (skipInitialFetchEffect) {
      skipInitialFetchEffect = false;
      return;
    }
    void fetchHistory(range);
  });

  const allHistoryData = createMemo<HistoryItem[]>(() => {
    return buildAlertHistoryItems({
      activeAlerts: props.activeAlerts() || {},
      // A failed larger-range read must not label a smaller snapshot as complete.
      // Keep the last snapshot for same-range retry, but never reuse it in another range.
      alertHistory: loadedHistoryRange() === timeFilter() ? alertHistory() : [],
      getResource: props.getResource,
      allResources: props.allResources(),
    });
  });

  const focusScopedItems = createMemo<HistoryItem[]>(() => {
    const focus = focusedAlertId();
    return focus ? allHistoryData().filter((item) => item.id === focus) : allHistoryData();
  });

  const historyReady = () =>
    (props.activeAlertsSettled?.() ?? true) &&
    !loading() &&
    !historyLoadError() &&
    loadedHistoryRange() === timeFilter();

  // The linked alert may be older than the range on show: widen to all of
  // history, deciding once per alert so a later range is the operator's.
  let rangeCheckedFor = '';
  createEffect(() => {
    const focus = focusedAlertId();
    if (!focus) {
      rangeCheckedFor = '';
      return;
    }
    if (!historyReady() || rangeCheckedFor === focus) return;
    rangeCheckedFor = focus;
    if (focusScopedItems().length > 0 || timeFilter() === 'all') return;
    untrack(() => setTimeFilter('all'));
  });

  const focusedAlertMissing = (): boolean =>
    focusedAlertId() !== '' &&
    historyReady() &&
    timeFilter() === 'all' &&
    focusScopedItems().length === 0;

  // Open the linked alert's latest occurrence once, preferring one still
  // active. The table shows the shared expansion inline; the cards show a
  // timeline only in their drawer, so they take a one-shot request that a
  // remounted list cannot replay after the operator closed it.
  const [focusedAlert, setFocusedAlert] = createSignal<HistoryItem | null>(null);
  const [focusRequest, setFocusRequest] = createSignal<{
    rowKey: string;
    alert: HistoryItem;
  } | null>(null);
  const takeFocusRequest = () => {
    const request = untrack(focusRequest);
    if (request) setFocusRequest(null);
    return request;
  };
  let openedFor = '';
  createEffect(() => {
    const focus = focusedAlertId();
    if (!focus) {
      openedFor = '';
      untrack(() => {
        setFocusedAlert(null);
        setFocusRequest(null);
      });
      return;
    }
    if (openedFor === focus || !historyReady()) return;
    const [latest] = [...focusScopedItems()]
      .filter((item) => item.source === 'alert')
      .sort(
        (left, right) =>
          Number(right.status === 'active') - Number(left.status === 'active') ||
          Date.parse(right.startTime) - Date.parse(left.startTime),
      );
    if (!latest) return;
    openedFor = focus;
    const rowKey = getIncidentRowKey(latest);
    untrack(() => {
      if (!expandedIncidents().has(rowKey)) {
        void toggleIncidentTimeline(rowKey, latest.id, latest.startTime);
      }
      setFocusedAlert(latest);
      setFocusRequest({ rowKey, alert: latest });
    });
  });

  const severityAndSearchFilteredItems = createMemo(() => {
    return filterAlertHistoryItems(focusScopedItems(), severityFilter(), searchTerm());
  });

  // Chip-count source for the severity facet: the same predicate the list
  // filters with, so each chip shows the row count its selection renders
  // (before any chart bar drill-down, which narrows further and explicitly).
  const countForSeverity = (value: AlertSeverityFilter): number =>
    filterAlertHistoryItems(focusScopedItems(), value, searchTerm()).length;

  const alertTrends = createMemo(() => {
    return buildAlertTrends(severityAndSearchFilteredItems(), timeFilter());
  });

  const alertData = createMemo(() => {
    return applyAlertHistoryWindow({
      filteredItems: severityAndSearchFilteredItems(),
      // A linked alert shows every loaded occurrence: one still firing may
      // have started before the range on show.
      timeFilter: focusedAlertId() ? 'all' : timeFilter(),
      selectedBarIndex: selectedBarIndex(),
      trends: alertTrends(),
    });
  });

  const groupedAlerts = createMemo(() => {
    return groupAlertHistoryItems(alertData());
  });

  const bucketDurationLabel = createMemo(() =>
    getAlertBucketDurationLabel(alertTrends().bucketSize),
  );

  const rangeSummary = createMemo(() => {
    return buildAlertRangeSummary(alertTrends(), userLocale);
  });

  const axisTicks = createMemo(() => buildAlertAxisTicks(alertTrends(), userLocale));

  const selectedBucketDetails = createMemo(() =>
    buildSelectedBucketDetails(selectedBarIndex(), alertTrends(), userLocale),
  );

  const clearAlertHistory = async () => {
    if (disposed) return;
    if (!confirm(getAlertAdministrationClearHistoryConfirmation())) {
      return;
    }

    const contextVersion = historyContextVersion;
    try {
      await AlertsAPI.clearHistory();
      if (disposed || contextVersion !== historyContextVersion) return;
      // Reads started before the clear completed may still contain deleted rows.
      fetchRequestId++;
      setLoading(false);
      setAlertHistory([]);
      setLoadedHistoryRange(timeFilter());
      setHistoryLoadError(false);
    } catch (error) {
      if (disposed || contextVersion !== historyContextVersion) return;
      logger.error(getAlertAdministrationClearHistoryError(), error);
      notificationStore.error(getAlertAdministrationClearHistoryError());
    }
  };

  return {
    focusedAlertId,
    focusedAlertMissing,
    clearFocusedAlert,
    focusRequest,
    takeFocusRequest,
    focusedAlert,
    STORAGE_KEYS,
    timeFilter,
    setTimeFilter,
    severityFilter,
    setSeverityFilter,
    searchTerm,
    setSearchTerm,
    alertHistory,
    loading,
    historyLoadError,
    retryHistory,
    selectedBarIndex,
    setSelectedBarIndex,
    resourceIncidentPanel: resourceIncidentsState.resourceIncidentPanel,
    setResourceIncidentPanel: resourceIncidentsState.setResourceIncidentPanel,
    resourceIncidents: resourceIncidentsState.resourceIncidents,
    resourceIncidentLoading: resourceIncidentsState.resourceIncidentLoading,
    resourceIncidentError: resourceIncidentsState.resourceIncidentError,
    expandedResourceIncidentIds: resourceIncidentsState.expandedResourceIncidentIds,
    resourceIncidentEventFilters: resourceIncidentsState.resourceIncidentEventFilters,
    setResourceIncidentEventFilters: resourceIncidentsState.setResourceIncidentEventFilters,
    activeFilterCount,
    countForSeverity,
    clearFilters,
    incidentTimelines,
    incidentLoading,
    incidentErrors,
    expandedIncidents,
    incidentNoteDrafts,
    incidentNoteSaving,
    historyIncidentEventFilters: eventFilters,
    setHistoryIncidentEventFilters: setEventFilters,
    loadIncidentTimeline,
    toggleIncidentTimeline,
    setIncidentNoteDraft,
    saveIncidentNote,
    // Exposed so the inline resource panel can resolve a display name without
    // threading the lookup down through the table and mobile list.
    getResource: props.getResource,
    // Exposed so the resource panel can describe its open occurrence from the
    // live alert instead of the message recorded when it opened.
    activeAlerts: props.activeAlerts,
    formatAlertRowTime,
    formatAlertRowTimestamp,
    openResourceIncidentPanel: resourceIncidentsState.openResourceIncidentPanel,
    refreshResourceIncidentPanel: resourceIncidentsState.refreshResourceIncidentPanel,
    toggleResourceIncidentDetails: resourceIncidentsState.toggleResourceIncidentDetails,
    alertData,
    groupedAlerts,
    alertTrends,
    bucketDurationLabel,
    rangeSummary,
    axisTicks,
    selectedBucketDetails,
    formatBucketRange: (startMs: number, endMs: number) =>
      formatAlertBucketRange(startMs, endMs, userLocale),
    getIncidentRowKey,
    clearAlertHistory,
  };
}

export type AlertHistoryState = ReturnType<typeof useAlertHistoryState>;