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.

13.1 KB
Raw Blame
import type { AlertResolution } from '@/types/api';
import { getAlertSeverityBadgeClass } from '@/utils/alertSeverityPresentation';

export type AlertIncidentLevel = 'warning' | 'critical' | string | null | undefined;
export type AlertIncidentStatus = 'open' | 'acknowledged' | 'resolved' | 'unknown';

export interface AlertIncidentStatusPresentation {
  label: AlertIncidentStatus | string;
  className: string;
}

export interface AlertHistoryStatusPresentation {
  label: string;
  className: string;
  rowClassName: string;
}

export const ALERT_RESOURCE_INCIDENT_PANEL_TITLE = 'Resource incidents';
export const ALERT_INCIDENT_TIMELINE_DIALOG_TITLE = 'Incident timeline';
export const ALERT_RESOURCE_INCIDENT_LOADING_STATE = 'Loading incidents...';
export const ALERT_RESOURCE_INCIDENT_EMPTY_STATE = 'No incidents recorded for this resource yet.';
export const ALERT_RESOURCE_INCIDENT_REFRESH_LABEL = 'Refresh';
export const ALERT_RESOURCE_INCIDENT_REFRESHING_LABEL = 'Refreshing...';
export const ALERT_RESOURCE_INCIDENT_NO_EVENTS_FILTERED_STATE =
  'No events match the selected filters.';
export const ALERT_RESOURCE_INCIDENT_NOTE_PLACEHOLDER = 'Add a note for this incident...';
export const ALERT_RESOURCE_INCIDENT_SAVE_NOTE_LABEL = 'Save Note';
export const ALERT_RESOURCE_INCIDENT_SAVING_NOTE_LABEL = 'Saving...';
export const ALERT_RESOURCE_INCIDENT_LOAD_FAILURE = 'Failed to load resource incidents';
export const ALERT_RESOURCE_INCIDENT_TIMELINE_FAILURE = 'Failed to load incident timeline';
export const ALERT_RESOURCE_INCIDENT_NOTE_SAVED = 'Incident note saved';
export const ALERT_RESOURCE_INCIDENT_NOTE_SAVE_FAILURE = 'Failed to save incident note';
export const ALERT_RESOURCE_INCIDENT_VIEW_TITLE = 'View incidents for this resource';

const ALERT_INCIDENT_STATUS_BASE = 'px-2 py-0.5 rounded-sm';
const ALERT_INCIDENT_EVENT_FILTER_BUTTON_BASE =
  'px-2 py-0.5 rounded-sm border text-[10px] transition-colors';

export type AlertIncidentEventFilterVariant = 'compact' | 'panel';

export function normalizeAlertIncidentStatus(
  status?: string | null,
  acknowledged?: boolean,
): AlertIncidentStatus | string {
  const normalized = (status ?? '').trim().toLowerCase();
  if (normalized === 'open' && acknowledged) return 'acknowledged';
  if (normalized === 'open') return 'open';
  if (normalized === 'resolved' || normalized === 'closed') return 'resolved';
  return normalized || 'unknown';
}

export function getAlertIncidentStatusPresentation(
  status?: string | null,
  acknowledged?: boolean,
): AlertIncidentStatusPresentation {
  const label = normalizeAlertIncidentStatus(status, acknowledged);
  switch (label) {
    case 'acknowledged':
      return {
        label,
        className: `${ALERT_INCIDENT_STATUS_BASE} bg-emerald-100 dark:bg-emerald-900/25 text-emerald-700 dark:text-emerald-300`,
      };
    case 'open':
      return {
        label,
        className: `${ALERT_INCIDENT_STATUS_BASE} bg-red-100 dark:bg-red-900/25 text-red-700 dark:text-red-300`,
      };
    default:
      return {
        label,
        className: `${ALERT_INCIDENT_STATUS_BASE} bg-surface-hover text-base-content`,
      };
  }
}

export function getAlertIncidentLevelBadgeClass(level: AlertIncidentLevel): string {
  return getAlertSeverityBadgeClass(String(level ?? 'warning'));
}

// History status for an alert that closed because its Pulse agent took the
// metric over. The condition did not clear; the agent's own alert owns it.
export const ALERT_HISTORY_MOVED_STATUS = 'moved';

/**
 * The account of a close that was not a recovery, for history rows and their
 * tooltips. Returns undefined for an ordinary recovery so callers keep their
 * "resolved" wording.
 */
export function getAlertResolutionDetail(resolution?: AlertResolution | null): string | undefined {
  if (!resolution) return undefined;
  if (resolution.reason === 'moved_to_agent') {
    const successor = resolution.successorName?.trim() || 'its Pulse agent';
    return `Moved to ${successor}. This is not a recovery: check the agent for the current reading.`;
  }
  return resolution.summary?.trim() || undefined;
}

// A table row passes `compact` for an 11px badge with tighter padding, so the
// Status track needs about 108px for "moved to agent" instead of 119px.
export function getAlertHistoryStatusPresentation(
  status?: string | null,
  options: { compact?: boolean } = {},
): AlertHistoryStatusPresentation {
  const normalized = (status ?? '').trim().toLowerCase();
  const badge = options.compact ? 'text-[11px] px-1.5' : 'text-xs px-2';

  if (normalized === 'active') {
    return {
      label: 'active',
      className: `${badge} py-0.5 rounded-sm bg-red-100 dark:bg-red-900/25 text-red-700 dark:text-red-300 font-medium`,
      rowClassName: 'bg-red-50 dark:bg-red-900/25',
    };
  }

  if (normalized === 'acknowledged') {
    return {
      label: 'acknowledged',
      className: `${badge} py-0.5 rounded-sm bg-yellow-100 dark:bg-yellow-900/25 text-yellow-700 dark:text-yellow-300`,
      rowClassName: '',
    };
  }

  // Closed without recovering: neither a live problem on this row nor a
  // healthy outcome, so it gets its own neutral-blue badge.
  if (normalized === ALERT_HISTORY_MOVED_STATUS) {
    return {
      label: 'moved to agent',
      className: `${badge} py-0.5 rounded-sm bg-blue-100 dark:bg-blue-900/25 text-blue-700 dark:text-blue-300`,
      rowClassName: '',
    };
  }

  return {
    label: normalized || 'resolved',
    className: `${badge} py-0.5 rounded-sm bg-surface-hover text-base-content`,
    rowClassName: '',
  };
}

export function getAlertResourceIncidentLoadingState() {
  return {
    text: ALERT_RESOURCE_INCIDENT_LOADING_STATE,
  } as const;
}

export function getAlertResourceIncidentEmptyState() {
  return {
    text: ALERT_RESOURCE_INCIDENT_EMPTY_STATE,
  } as const;
}

export function getAlertResourceIncidentPanelTitle() {
  return ALERT_RESOURCE_INCIDENT_PANEL_TITLE;
}

export function getAlertIncidentTimelineDialogTitle() {
  return ALERT_INCIDENT_TIMELINE_DIALOG_TITLE;
}

export function getAlertHistoryInvestigationDialogTitle(kind: 'timeline' | 'resource') {
  return kind === 'timeline'
    ? getAlertIncidentTimelineDialogTitle()
    : getAlertResourceIncidentPanelTitle();
}

export function getAlertResourceIncidentCountLabel(count: number) {
  return `${count} incident${count === 1 ? '' : 's'}`;
}

export function getAlertResourceIncidentRefreshLabel(isLoading: boolean) {
  return isLoading
    ? ALERT_RESOURCE_INCIDENT_REFRESHING_LABEL
    : ALERT_RESOURCE_INCIDENT_REFRESH_LABEL;
}

export function getAlertResourceIncidentAcknowledgedByLabel(user: string) {
  return `Acknowledged by ${user}`;
}

export function getAlertResourceIncidentToggleLabel(isExpanded: boolean, filteredLabel: string) {
  return isExpanded ? 'Hide events' : `Events (${filteredLabel})`;
}

export function getAlertResourceIncidentFilteredEventsEmptyState() {
  return {
    text: ALERT_RESOURCE_INCIDENT_NO_EVENTS_FILTERED_STATE,
  } as const;
}

export function getAlertResourceIncidentRecentEventsSummary(count: number) {
  return `Showing last ${count} events`;
}

export function getAlertResourceIncidentNotePlaceholder() {
  return ALERT_RESOURCE_INCIDENT_NOTE_PLACEHOLDER;
}

export function getAlertResourceIncidentSaveNoteLabel(isSaving: boolean) {
  return isSaving
    ? ALERT_RESOURCE_INCIDENT_SAVING_NOTE_LABEL
    : ALERT_RESOURCE_INCIDENT_SAVE_NOTE_LABEL;
}

export function getAlertResourceIncidentLoadFailure() {
  return ALERT_RESOURCE_INCIDENT_LOAD_FAILURE;
}

export function getAlertResourceIncidentTimelineFailure() {
  return ALERT_RESOURCE_INCIDENT_TIMELINE_FAILURE;
}

export function getAlertResourceIncidentNoteSavedLabel() {
  return ALERT_RESOURCE_INCIDENT_NOTE_SAVED;
}

export function getAlertResourceIncidentNoteSaveFailure() {
  return ALERT_RESOURCE_INCIDENT_NOTE_SAVE_FAILURE;
}

export function getAlertResourceIncidentViewTitle() {
  return ALERT_RESOURCE_INCIDENT_VIEW_TITLE;
}

/**
 * Accessible names for the controls every alert history row repeats. A
 * shared "Timeline" or "Resource" tells a screen-reader user nothing about
 * which row it belongs to, and history repeats one alert over time, so the
 * timeline control also names when it started. Each name begins with the
 * visible label so speech input still finds it.
 */
export function getAlertHistoryTimelineActionLabel(options: {
  open: boolean;
  alertTitle: string;
  resourceName?: string;
  startedAt: string;
}): string {
  const subject = [options.alertTitle, options.resourceName && `on ${options.resourceName}`]
    .filter(Boolean)
    .join(' ');
  return `${options.open ? 'Hide timeline' : 'Timeline'} for ${subject}, ${options.startedAt}`;
}

export function getAlertHistoryResourceActionLabel(resourceName?: string): string {
  return `Resource incidents for ${resourceName?.trim() || 'this resource'}`;
}

export function getAlertIncidentEventFilterContainerClass(
  variant: AlertIncidentEventFilterVariant,
): string {
  if (variant === 'panel') {
    return 'flex flex-wrap items-center gap-1.5 rounded-sm border border-border p-2';
  }

  return 'flex flex-wrap items-center gap-2 text-[10px] text-muted';
}

export function getAlertIncidentEventFilterLabelClass(
  variant: AlertIncidentEventFilterVariant,
): string {
  if (variant === 'panel') {
    return 'mr-1 text-xs font-medium text-muted';
  }

  return 'uppercase tracking-wide text-[9px] text-muted';
}

export function getAlertIncidentEventFilterActionButtonClass(): string {
  return 'px-2 py-0.5 rounded-sm border border-border text-muted hover:bg-surface-hover';
}

export function getAlertIncidentEventFilterChipClass(
  selected: boolean,
  variant: AlertIncidentEventFilterVariant,
): string {
  if (selected) {
    return `${ALERT_INCIDENT_EVENT_FILTER_BUTTON_BASE} border-blue-300 bg-blue-100 text-blue-700 dark:border-blue-800 dark:bg-blue-900/25 dark:text-blue-300`;
  }

  if (variant === 'panel') {
    return `${ALERT_INCIDENT_EVENT_FILTER_BUTTON_BASE} font-medium border-border text-muted hover:bg-surface-alt`;
  }

  return `${ALERT_INCIDENT_EVENT_FILTER_BUTTON_BASE} border-border text-slate-500`;
}

export function getAlertIncidentAcknowledgedBadgeClass(): string {
  return 'px-2 py-0.5 rounded-sm bg-emerald-100 text-emerald-700 dark:bg-emerald-900/25 dark:text-emerald-300';
}

export function getAlertIncidentTimelineEventCardClass(variant: 'surface' | 'alt'): string {
  return `rounded-sm border border-border ${variant === 'alt' ? 'bg-surface-alt' : 'bg-surface'} p-2 whitespace-normal wrap-break-word`;
}

export function getAlertIncidentNoteTextareaClass(): string {
  return 'w-full rounded-sm border border-border bg-surface p-2 text-xs text-base-content';
}

export function getAlertIncidentNoteSaveButtonClass(): string {
  return 'px-3 py-1.5 text-xs font-medium border rounded-md transition-all bg-surface text-base-content border-border hover:bg-surface-hover disabled:opacity-50 disabled:cursor-not-allowed';
}

export function getAlertIncidentTimelineMetaRowClass(): string {
  return 'flex flex-wrap items-center gap-2 text-xs text-muted';
}

export function getAlertIncidentTimelineHeadingClass(): string {
  return 'font-medium text-base-content';
}

export function getAlertIncidentTimelineDetailClass(): string {
  return 'mt-1 text-xs text-base-content whitespace-pre-wrap';
}

export function getAlertIncidentTimelineCommandClass(): string {
  return 'mt-1 font-mono text-xs text-base-content';
}

export function getAlertIncidentTimelineOutputClass(): string {
  return 'mt-1 text-xs text-muted';
}

export function getAlertResourceIncidentCardClass(): string {
  return 'rounded-sm border border-border bg-surface p-3';
}

export function getAlertResourceIncidentSummaryRowClass(): string {
  return 'mt-2 flex flex-wrap items-center justify-between gap-2 text-xs text-muted';
}

export function getAlertResourceIncidentActivitySummaryClass(): string {
  return 'flex flex-wrap items-center gap-1.5';
}

export function getAlertResourceIncidentActivityChipClass(): string {
  return 'rounded-sm bg-surface-alt px-2 py-0.5 text-[10px] font-medium text-base-content';
}

export function getAlertResourceIncidentToggleButtonClass(): string {
  return 'px-2 py-1 text-[10px] border rounded-md border-border text-muted hover:bg-surface-hover';
}

export function getAlertResourceIncidentTruncatedEventsLabel(
  count: number,
  totalCount?: number,
): string {
  if (typeof totalCount === 'number') {
    if (totalCount <= count) {
      return `Showing ${totalCount} event${totalCount === 1 ? '' : 's'}`;
    }
    return `Showing last ${count} of ${totalCount} events`;
  }
  return `Showing last ${count} events`;
}

// A zero Go timestamp means the retained evidence does not establish a time.
export function formatIncidentEvidenceTime(value?: string | null): string | null {
  if (!value || value.startsWith('0001-')) return null;
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? null : date.toLocaleString();
}

export const INCIDENT_HISTORY_PARTIAL =
  'Only part of this history was returned. Earlier occurrences or events may be missing.';
export const INCIDENT_HISTORY_LEGACY = 'This timeline uses saved incident notes and snapshots.';
export const INCIDENT_EVIDENCE_DETAILS = 'Evidence details';
export const INCIDENT_TIME_UNAVAILABLE = 'Time unavailable';