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.4 KB
Raw Blame
import type { JSX } from 'solid-js';

import type { PlatformTableColumnKind } from '@/features/platformPage/columnAlignment';
import {
  getPlatformTableWeightedColumnWidthStyle,
  PLATFORM_TABLE_NARROW_IDENTITY_WIDTH_PERCENT,
  PLATFORM_TABLE_PHONE_IDENTITY_WIDTH_PERCENT,
} from '@/features/platformPage/sharedPlatformPage';

export type ProxmoxBackupsTableLayoutMode =
  'compact' | 'basic' | 'operational' | 'expanded' | 'full';

export type BackupServerColumnId = 'datastore' | 'status' | 'used' | 'jobs' | 'backups' | 'dedup';

export type CoverageColumnId =
  'workload' | 'type' | 'targetId' | 'node' | 'posture' | 'latest' | 'task';

export type RecoverableColumnId =
  | 'workload'
  | 'type'
  | 'targetId'
  | 'source'
  | 'location'
  | 'created'
  | 'size'
  | 'state'
  | 'details';

export type BackupTableColumn<Id extends string> = {
  id: Id;
  label: string;
  kind: PlatformTableColumnKind;
};

const layoutForWidth = (
  width: number,
  breakpoints: readonly [number, number, number, number],
): ProxmoxBackupsTableLayoutMode => {
  if (!Number.isFinite(width) || width < breakpoints[0]) return 'compact';
  if (width < breakpoints[1]) return 'basic';
  if (width < breakpoints[2]) return 'operational';
  if (width < breakpoints[3]) return 'expanded';
  return 'full';
};

// These are table-container breakpoints, not viewport breakpoints. A 1536px
// browser with Pulse Assistant open leaves roughly 886px for the page and must
// select the same columns as any other 886px container.
export const getBackupServerLayoutForContainer = (width: number): ProxmoxBackupsTableLayoutMode =>
  layoutForWidth(width, [520, 720, 900, 1120]);

export const getCoverageLayoutForContainer = (width: number): ProxmoxBackupsTableLayoutMode =>
  layoutForWidth(width, [480, 720, 880, 1120]);

export const getRecoverableLayoutForContainer = (width: number): ProxmoxBackupsTableLayoutMode =>
  layoutForWidth(width, [480, 720, 880, 1120]);

export const BACKUP_SERVER_COLUMNS: readonly BackupTableColumn<BackupServerColumnId>[] = [
  { id: 'datastore', label: 'Datastore', kind: 'name' },
  { id: 'status', label: 'State', kind: 'text' },
  { id: 'used', label: 'Used', kind: 'numeric-value' },
  { id: 'jobs', label: 'Jobs', kind: 'text' },
  { id: 'backups', label: 'Backups', kind: 'numeric-value' },
  { id: 'dedup', label: 'Dedup', kind: 'numeric-value' },
];

const BACKUP_SERVER_VISIBLE: Record<
  ProxmoxBackupsTableLayoutMode,
  readonly BackupServerColumnId[]
> = {
  // Datastore exhaustion can stop all future backups, so every layout keeps
  // Used whole ("33.6%"). Server reachability is on each server's header row,
  // not repeated on its datastores. Job results (GC, prune, verify, sync) are
  // the next answer; phones have no Jobs column, so State carries a job
  // result, a job problem or a fill forecast instead. The backup count and
  // dedup follow as width allows; Coverage and By date already answer per
  // guest. Host CPU, memory, uptime and version live in the server's drawer.
  compact: ['datastore', 'status', 'used'],
  basic: ['datastore', 'used', 'jobs'],
  operational: ['datastore', 'used', 'jobs', 'backups'],
  expanded: ['datastore', 'used', 'jobs', 'backups', 'dedup'],
  full: ['datastore', 'used', 'jobs', 'backups', 'dedup'],
};

const BACKUP_SERVER_WEIGHTS: Record<
  ProxmoxBackupsTableLayoutMode,
  Partial<Record<BackupServerColumnId, number>>
> = {
  // State must fit a job problem ("Sync failed", "Verify late") or a fill
  // forecast ("Full in ~4d") because the phone layout has no Jobs column, and
  // capacity must fit "Unavailable". The datastore name keeps the shared 40%
  // identity anchor.
  compact: { datastore: 40, status: 30, used: 30 },
  // Jobs must fit "Verify failed" and Used must fit "Unavailable" or a fill
  // forecast pill, not just short values. The 30% identity anchor below still
  // owns the datastore column in this band.
  basic: { datastore: 30, used: 39, jobs: 31 },
  // Used carries a percentage plus the used/total pair or the forecast pill,
  // the longest value in the row, so it keeps the widest share.
  operational: { datastore: 36, used: 28, jobs: 23, backups: 13 },
  // At the 900px breakpoint Count needs 9% (81px) to fit "Unavailable".
  expanded: { datastore: 36, used: 26, jobs: 20, backups: 10, dedup: 8 },
  full: { datastore: 36, used: 26, jobs: 22, backups: 8, dedup: 8 },
};

export const getBackupServerColumns = (
  layout: ProxmoxBackupsTableLayoutMode,
): BackupTableColumn<BackupServerColumnId>[] => {
  const visible = new Set(BACKUP_SERVER_VISIBLE[layout]);
  return BACKUP_SERVER_COLUMNS.filter((column) => visible.has(column.id));
};

export const getBackupServerColumnWidthStyle = (
  columnId: BackupServerColumnId,
  layout: ProxmoxBackupsTableLayoutMode,
): JSX.CSSProperties =>
  getPlatformTableWeightedColumnWidthStyle(
    columnId,
    BACKUP_SERVER_WEIGHTS[layout],
    BACKUP_SERVER_VISIBLE[layout],
    layout === 'compact' || layout === 'basic'
      ? {
          columnId: 'datastore',
          widthPercent:
            layout === 'compact'
              ? PLATFORM_TABLE_NARROW_IDENTITY_WIDTH_PERCENT
              : PLATFORM_TABLE_PHONE_IDENTITY_WIDTH_PERCENT,
        }
      : undefined,
  );

export const COVERAGE_COLUMNS: readonly BackupTableColumn<CoverageColumnId>[] = [
  { id: 'workload', label: 'Workload', kind: 'name' },
  { id: 'type', label: 'Type', kind: 'text' },
  { id: 'targetId', label: 'Target ID', kind: 'text' },
  { id: 'node', label: 'Node', kind: 'text' },
  { id: 'posture', label: 'Posture', kind: 'text' },
  { id: 'latest', label: 'Last backup', kind: 'numeric-value' },
  { id: 'task', label: 'Task', kind: 'text' },
];

const COVERAGE_VISIBLE: Record<ProxmoxBackupsTableLayoutMode, readonly CoverageColumnId[]> = {
  // Every layout answers: which workload, what posture, how recent is the
  // newest independent backup, and did the latest task succeed? The
  // provider-by-provider ages (PBS snapshot, PVE file, guest snapshot) are
  // progressive detail in the expansion row at every width: side by side they
  // made a stale backup look fresh beside a recent guest snapshot, which does
  // not count as a backup. Target identity folds beneath the name on phones.
  compact: ['workload', 'posture', 'latest', 'task'],
  basic: ['workload', 'node', 'posture', 'latest', 'task'],
  operational: ['workload', 'type', 'node', 'posture', 'latest', 'task'],
  expanded: ['workload', 'type', 'node', 'posture', 'latest', 'task'],
  full: ['workload', 'type', 'targetId', 'node', 'posture', 'latest', 'task'],
};

const COVERAGE_WEIGHTS: Record<
  ProxmoxBackupsTableLayoutMode,
  Partial<Record<CoverageColumnId, number>>
> = {
  // Posture keeps its whole compact reason word, the age cell holds the
  // suffix-free compact age, and the job dot takes what a "Job" header needs.
  compact: { workload: 46, posture: 22, latest: 18, task: 14 },
  // Above the phone projection the identity columns (workload, node) take the
  // slack that the short type badge, target id, and age cells cannot use, so
  // names stay whole instead of truncating beside empty space.
  basic: { workload: 31, node: 18, posture: 22, latest: 15, task: 14 },
  operational: { workload: 27, type: 8, node: 17, posture: 17, latest: 15, task: 16 },
  expanded: { workload: 27, type: 8, node: 17, posture: 17, latest: 15, task: 16 },
  full: {
    workload: 24,
    type: 7,
    targetId: 9,
    node: 16,
    posture: 16,
    latest: 13,
    task: 15,
  },
};

export interface CoverageSourceVisibility {
  task: boolean;
}

export const getCoverageColumns = (
  layout: ProxmoxBackupsTableLayoutMode,
  sourceVisibility: CoverageSourceVisibility,
): BackupTableColumn<CoverageColumnId>[] => {
  const layoutColumns = new Set(COVERAGE_VISIBLE[layout]);
  return COVERAGE_COLUMNS.filter((column) => {
    if (!layoutColumns.has(column.id)) return false;
    if (column.id === 'task') return sourceVisibility.task;
    return true;
  });
};

// Coverage's phone rows carry only the name in their identity cell, and guest
// names often share a long prefix ("checkout-web-110"), so cutting their ends
// hides what tells them apart. The cells beside it hold short, fixed content,
// measured at 320px: a reason word with its dot ("No backup" is the longest),
// an "Unknown" age, the job dot under "Job". When the table knows its width
// they take exactly that and the name takes the rest, instead of a fixed share
// that wastes room at 360px and up. A 302px table still leaves the other cells
// whole.
const COVERAGE_COMPACT_CELL_WIDTH_PX: Partial<Record<CoverageColumnId, number>> = {
  posture: 80,
  latest: 52,
  task: 34,
};

const compactCoverageWidthStyle = (
  columnId: CoverageColumnId,
  visibleColumnIds: readonly CoverageColumnId[],
  containerWidth: number,
): JSX.CSSProperties => {
  const share = (px: number) => (px / containerWidth) * 100;
  if (columnId !== 'workload') {
    const px = COVERAGE_COMPACT_CELL_WIDTH_PX[columnId];
    return px ? { width: `${Number(share(px).toFixed(2))}%` } : {};
  }
  const taken = visibleColumnIds
    .filter((id) => id !== 'workload')
    .reduce((sum, id) => sum + share(COVERAGE_COMPACT_CELL_WIDTH_PX[id] ?? 0), 0);
  return { width: `${Number(Math.max(0, 100 - taken).toFixed(2))}%` };
};

export const getCoverageColumnWidthStyle = (
  columnId: CoverageColumnId,
  layout: ProxmoxBackupsTableLayoutMode,
  visibleColumnIds: readonly CoverageColumnId[],
  containerWidth?: number,
): JSX.CSSProperties =>
  layout === 'compact' && typeof containerWidth === 'number' && containerWidth > 0
    ? compactCoverageWidthStyle(columnId, visibleColumnIds, containerWidth)
    : getPlatformTableWeightedColumnWidthStyle(
        columnId,
        COVERAGE_WEIGHTS[layout],
        visibleColumnIds,
        layout === 'compact' || layout === 'basic'
          ? {
              columnId: 'workload',
              widthPercent:
                layout === 'compact'
                  ? PLATFORM_TABLE_NARROW_IDENTITY_WIDTH_PERCENT
                  : PLATFORM_TABLE_PHONE_IDENTITY_WIDTH_PERCENT,
            }
          : undefined,
      );

export const RECOVERABLE_COLUMNS: readonly BackupTableColumn<RecoverableColumnId>[] = [
  { id: 'workload', label: 'Workload', kind: 'name' },
  { id: 'type', label: 'Type', kind: 'text' },
  { id: 'targetId', label: 'Target ID', kind: 'text' },
  { id: 'source', label: 'Source', kind: 'text' },
  { id: 'location', label: 'Location', kind: 'text' },
  { id: 'created', label: 'Created', kind: 'numeric-value' },
  { id: 'size', label: 'Size', kind: 'metric-bar' },
  { id: 'state', label: 'State', kind: 'text' },
  { id: 'details', label: 'Details', kind: 'text' },
];

const RECOVERABLE_VISIBLE: Record<ProxmoxBackupsTableLayoutMode, readonly RecoverableColumnId[]> = {
  // Narrow restore-point rows keep the workload, age and state on one line.
  // Source, location, size and provider identifiers are drawer detail; the
  // row names a connection inline only when it tells namesakes apart.
  compact: ['workload', 'created', 'state'],
  basic: ['workload', 'created', 'state'],
  operational: ['workload', 'type', 'source', 'location', 'created', 'size', 'state'],
  expanded: ['workload', 'type', 'targetId', 'source', 'location', 'created', 'size', 'state'],
  full: RECOVERABLE_COLUMNS.map((column) => column.id),
};

const RECOVERABLE_WEIGHTS: Record<
  ProxmoxBackupsTableLayoutMode,
  Partial<Record<RecoverableColumnId, number>>
> = {
  // Grouping identity needs more room than a single name. Keep Unknown ages
  // and full state words readable rather than trading one hidden fact for another.
  compact: { workload: 53, created: 22, state: 25 },
  basic: { workload: 58, created: 20, state: 22 },
  operational: {
    workload: 24,
    type: 8,
    source: 13,
    location: 20,
    created: 14,
    size: 12,
    state: 9,
  },
  expanded: {
    workload: 18,
    type: 7,
    targetId: 10,
    source: 11,
    location: 18,
    created: 13,
    size: 13,
    state: 10,
  },
  full: {
    workload: 16.5,
    type: 6,
    targetId: 8.5,
    source: 10,
    location: 18,
    created: 11,
    size: 12,
    state: 8,
    details: 10,
  },
};

export const getRecoverableColumns = (
  layout: ProxmoxBackupsTableLayoutMode,
): BackupTableColumn<RecoverableColumnId>[] => {
  const visible = new Set(RECOVERABLE_VISIBLE[layout]);
  return RECOVERABLE_COLUMNS.filter((column) => visible.has(column.id));
};

export const getRecoverableColumnWidthStyle = (
  columnId: RecoverableColumnId,
  layout: ProxmoxBackupsTableLayoutMode,
): JSX.CSSProperties =>
  getPlatformTableWeightedColumnWidthStyle(
    columnId,
    RECOVERABLE_WEIGHTS[layout],
    RECOVERABLE_VISIBLE[layout],
  );

export const isCompactBackupIdentityLayout = (layout: ProxmoxBackupsTableLayoutMode): boolean =>
  layout === 'compact' || layout === 'basic';

export const isCoverageEvidenceColumnVisible = (
  layout: ProxmoxBackupsTableLayoutMode,
  column: 'location' | 'size' | 'details',
): boolean => {
  if (column === 'location') return layout !== 'compact';
  if (column === 'size')
    return layout === 'operational' || layout === 'expanded' || layout === 'full';
  return layout === 'expanded' || layout === 'full';
};

// What the backup health counts mean, stated from the server's own posture
// policy so "17 attention" is never a number without a rule. The causes mirror
// internal/recovery/posture.go. Null until the policy has loaded; the strip
// then shows no rule rather than a guessed one.
export const getBackupPostureRuleText = (
  policy: { freshnessWindowSeconds: number } | null | undefined,
): string | null => {
  const seconds = policy?.freshnessWindowSeconds ?? 0;
  if (!Number.isFinite(seconds) || seconds <= 0) return null;
  return `Attention: the newest backup is older than ${formatPostureWindow(seconds)}, a newer backup job failed, expected verification is missing or overdue, or Pulse can see only part of the backup history. Unprotected: Pulse sees the full history and no backup it can count. Guest snapshots alone do not count. Unknown: Pulse cannot read the backup history or has no backup source linked to the guest.`;
};

export const formatPostureWindow = (seconds: number): string => {
  if (seconds >= 86_400 && seconds % 86_400 === 0) {
    const days = seconds / 86_400;
    return days === 1 ? '1 day' : `${days} days`;
  }
  const hours = Math.max(1, Math.round(seconds / 3_600));
  return hours === 1 ? '1 hour' : `${hours} hours`;
};

export const COVERAGE_RESTORE_EVIDENCE_PAGE_SIZE = 8;

// Newest restore points for a coverage row's expansion. The newest point and
// the newest completed point of every source always make the cut, so neither a
// burst of recent guest snapshots nor a running or failed job can hide the
// latest usable PBS or PVE backup now that the table carries no per-source
// age columns. Undated entries cannot be ordered behind those points: retain
// one witness of each source/completion state so the reason for an Unknown
// age (or an incomplete observation) is inspectable in the initial preview.
export const selectCoverageRestoreEvidence = <
  T extends {
    id: string;
    sourceKind: string;
    createdMs?: number;
    running?: boolean;
    failed?: boolean;
  },
>(
  artifacts: readonly T[],
  limit = COVERAGE_RESTORE_EVIDENCE_PAGE_SIZE,
): T[] => {
  const newestFirst = [...artifacts].sort(
    (left, right) =>
      (right.createdMs ?? 0) - (left.createdMs ?? 0) || left.id.localeCompare(right.id),
  );
  const picked = new Set<string>();
  const newestSeen = new Set<string>();
  const completedSeen = new Set<string>();
  const undatedSeen = new Set<string>();
  for (const artifact of newestFirst) {
    if (!newestSeen.has(artifact.sourceKind)) {
      newestSeen.add(artifact.sourceKind);
      picked.add(artifact.id);
    }
    if (!artifact.running && !artifact.failed && !completedSeen.has(artifact.sourceKind)) {
      completedSeen.add(artifact.sourceKind);
      picked.add(artifact.id);
    }
    if (artifact.createdMs === undefined) {
      const state = artifact.running ? 'running' : artifact.failed ? 'failed' : 'completed';
      const key = `${artifact.sourceKind}:${state}`;
      if (!undatedSeen.has(key)) {
        undatedSeen.add(key);
        picked.add(artifact.id);
      }
    }
  }
  const cap = Math.max(limit, picked.size);
  for (const artifact of newestFirst) {
    if (picked.size >= cap) break;
    picked.add(artifact.id);
  }
  return newestFirst.filter((artifact) => picked.has(artifact.id));
};

export const COVERAGE_TASK_EVIDENCE_PAGE_SIZE = 8;

// Unknown/tied starts can leave an entire provider history as possible latest
// tasks. Bound the initial disclosure, but keep a witness of each outcome and
// known/unknown start group so an OK prefix cannot hide failure or uncertainty.
// Preserve the model's deterministic, explicitly non-chronological order.
export const selectCoverageTaskEvidence = <
  T extends { id: string; label: string; startedMs?: number; error?: string },
>(
  tasks: readonly T[],
  limit = COVERAGE_TASK_EVIDENCE_PAGE_SIZE,
): T[] => {
  const picked = new Set<string>();
  const groups = new Set<string>();
  for (const task of tasks) {
    const outcome = task.error?.trim()
      ? 'Failed'
      : ['Failed', 'Running', 'OK'].includes(task.label)
        ? task.label
        : 'other';
    const group = `${outcome}:${task.startedMs === undefined ? 'unknown' : 'known'}`;
    if (!groups.has(group)) {
      groups.add(group);
      picked.add(task.id);
    }
  }
  const cap = Math.max(limit, picked.size);
  for (const task of tasks) {
    if (picked.size >= cap) break;
    picked.add(task.id);
  }
  return tasks.filter((task) => picked.has(task.id));
};