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.

18.4 KB
Raw Blame
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import {
  createComputed,
  For,
  Show,
  createEffect,
  createMemo,
  createSignal,
  type Component,
} from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
import { ResourceDetailDrawer } from '@/components/Infrastructure/ResourceDetailDrawer';
import { Button } from '@/components/shared/Button';
import { MetadataBadge } from '@/components/shared/MetadataBadge';
import { StatusDot } from '@/components/shared/StatusDot';
import type {
  AvailabilityHistoryBucket,
  AvailabilityHistoryTarget,
} from '@/api/availabilityHistory';
import type { Resource, ResourceAvailabilityMeta } from '@/types/resource';
import { formatRelativeTime } from '@/utils/format';
import {
  getAvailabilityProbeEndpointLabel,
  getAvailabilityProbePresentation,
} from '@/utils/availabilityProbePresentation';
import { getProbeSourceChipLabel, type ProbeAgentOption } from '@/utils/availabilityProbeAgents';
import { getStandaloneResourceStatusIndicator } from './standalonePageModel';

const AVAILABILITY_FLEET_DETAIL_ID = 'availability-fleet-detail';

type AvailabilityFleetHistoryState = 'reachable' | 'unreachable' | 'indeterminate' | 'unknown';

const statePresentation: Record<
  AvailabilityFleetHistoryState,
  { label: string; className: string }
> = {
  reachable: { label: 'Reachable', className: 'bg-emerald-500 dark:bg-emerald-400' },
  unreachable: { label: 'Unreachable', className: 'bg-rose-500 dark:bg-rose-400' },
  indeterminate: { label: 'Indeterminate', className: 'bg-amber-400 dark:bg-amber-300' },
  unknown: { label: 'Unknown', className: 'bg-slate-300 dark:bg-slate-600' },
};

const availabilityFor = (resource: Resource): ResourceAvailabilityMeta | undefined =>
  resource.availability ??
  (resource.platformData?.availability as ResourceAvailabilityMeta | undefined);

const historyState = (bucket: AvailabilityHistoryBucket): AvailabilityFleetHistoryState => {
  const durations: Array<[AvailabilityFleetHistoryState, number]> = [
    ['unreachable', bucket.unreachableSeconds],
    ['indeterminate', bucket.indeterminateSeconds],
    ['reachable', bucket.reachableSeconds],
    ['unknown', bucket.unknownSeconds],
  ];
  durations.sort((left, right) => right[1] - left[1]);
  return durations[0]?.[0] ?? 'unknown';
};

const formatPercent = (value: number): string =>
  `${value.toLocaleString(undefined, { maximumFractionDigits: 2 })}%`;

// An uptime percentage is only honest when most of the window had a
// determinate answer. availabilityPercent leaves out indeterminate time, so a
// window of mostly inconclusive UDP results could otherwise read 100 percent.
const MIN_UPTIME_COVERAGE_PERCENT = 90;
const MIN_DETERMINATE_SHARE = 0.9;

type UptimeVerdict =
  | { kind: 'ok'; percent: number }
  | { kind: 'thin'; observedMinutes: number }
  | { kind: 'inconclusive' };

const getUptimeVerdict = (summary: AvailabilityHistoryTarget['summary']): UptimeVerdict => {
  const observed =
    (summary?.reachableSeconds ?? 0) +
    (summary?.unreachableSeconds ?? 0) +
    (summary?.indeterminateSeconds ?? 0);
  if (
    !summary ||
    summary.coveragePercent < MIN_UPTIME_COVERAGE_PERCENT ||
    summary.availabilityPercent === undefined
  ) {
    return { kind: 'thin', observedMinutes: Math.round(observed / 60) };
  }
  const determinate = summary.reachableSeconds + summary.unreachableSeconds;
  if (observed <= 0 || determinate / observed < MIN_DETERMINATE_SHARE) {
    return { kind: 'inconclusive' };
  }
  return { kind: 'ok', percent: summary.availabilityPercent };
};

// Compact 24h uptime for the checks table, on the same coverage rule as the
// fleet view: below 90 percent observed there is no honest percentage yet.
export const getAvailabilityUptimeCell = (
  history: AvailabilityHistoryTarget | undefined,
): { label: string; title: string; tone: 'default' | 'warning' | 'danger' | 'muted' } => {
  if (!history?.summary) {
    return { label: '—', title: 'History unavailable', tone: 'muted' };
  }
  const verdict = getUptimeVerdict(history.summary);
  if (verdict.kind === 'thin') {
    return {
      label: '—',
      title: `Not enough history yet: ${verdict.observedMinutes.toLocaleString()}m observed in the last 24h`,
      tone: 'muted',
    };
  }
  if (verdict.kind === 'inconclusive') {
    return {
      label: '—',
      title: 'Most results in the last 24h were inconclusive, so there is no uptime figure',
      tone: 'muted',
    };
  }
  const percent = verdict.percent;
  return {
    label: formatPercent(percent),
    title: `Available ${formatPercent(percent)} of the last 24h (${formatPercent(history.summary.coveragePercent)} observed)`,
    tone: percent < 95 ? 'danger' : percent < 99 ? 'warning' : 'default',
  };
};

const availabilityText = (history: AvailabilityHistoryTarget | undefined): string => {
  if (!history?.summary) return 'History unavailable';
  const verdict = getUptimeVerdict(history.summary);
  if (verdict.kind === 'thin') {
    return `Insufficient coverage · ${verdict.observedMinutes.toLocaleString()}m observed`;
  }
  if (verdict.kind === 'inconclusive') return 'Mostly inconclusive results';
  return `${formatPercent(verdict.percent)} available · ${formatPercent(history.summary.coveragePercent)} observed`;
};

const latencyPaths = (
  buckets: readonly AvailabilityHistoryBucket[],
): { path: string; label: string }[] => {
  const values = buckets
    .map((bucket) => bucket.latencyMillis?.average)
    .filter((value): value is number => typeof value === 'number' && Number.isFinite(value));
  if (values.length === 0) return [];
  const min = Math.min(...values);
  const max = Math.max(...values);
  const spread = Math.max(1, max - min);
  const denominator = Math.max(1, buckets.length - 1);
  const paths: { path: string; label: string }[] = [];
  let points: string[] = [];
  const flush = () => {
    if (points.length > 0) {
      paths.push({ path: points.join(' '), label: `${min}–${max} ms reachable latency` });
      points = [];
    }
  };
  buckets.forEach((bucket, index) => {
    const latency = bucket.latencyMillis?.average;
    if (typeof latency !== 'number' || !Number.isFinite(latency)) {
      flush();
      return;
    }
    const x = (index / denominator) * 100;
    const y = 22 - ((latency - min) / spread) * 18;
    points.push(`${x.toFixed(2)},${y.toFixed(2)}`);
  });
  flush();
  return paths;
};

const AvailabilityStateStrip: Component<{ buckets: readonly AvailabilityHistoryBucket[] }> = (
  props,
) => {
  const states = createMemo(() => props.buckets.map(historyState));
  const description = createMemo(() => {
    const counts = new Map<AvailabilityFleetHistoryState, number>();
    for (const state of states()) counts.set(state, (counts.get(state) ?? 0) + 1);
    return (Object.keys(statePresentation) as AvailabilityFleetHistoryState[])
      .filter((state) => (counts.get(state) ?? 0) > 0)
      .map((state) => `${counts.get(state)} ${statePresentation[state].label.toLowerCase()}`)
      .join(', ');
  });
  return (
    <div
      class="flex h-3 w-full overflow-hidden rounded-xs bg-slate-200 dark:bg-slate-700"
      role="img"
      aria-label={`24-hour state history: ${description() || 'no observations'}`}
      data-testid="availability-state-strip"
    >
      <For each={states()}>
        {(state) => (
          <span
            class={`min-w-px flex-1 ${statePresentation[state].className}`}
            title={statePresentation[state].label}
          />
        )}
      </For>
    </div>
  );
};

const AvailabilityLatencyLine: Component<{ buckets: readonly AvailabilityHistoryBucket[] }> = (
  props,
) => {
  const paths = createMemo(() => latencyPaths(props.buckets));
  return (
    <Show
      when={paths().length > 0}
      fallback={
        <div class="flex h-7 items-center text-[10px] text-muted">No reachable latency</div>
      }
    >
      <svg
        viewBox="0 0 100 26"
        preserveAspectRatio="none"
        class="h-7 w-full overflow-visible"
        role="img"
        aria-label={paths()[0]?.label ?? 'Reachable latency'}
        data-testid="availability-latency-line"
      >
        <For each={paths()}>
          {(path) => (
            <polyline
              points={path.path}
              fill="none"
              stroke="currentColor"
              stroke-width="1.75"
              vector-effect="non-scaling-stroke"
              class="text-sky-500 dark:text-sky-300"
            />
          )}
        </For>
      </svg>
    </Show>
  );
};

export const AvailabilityFleetView: Component<{
  resources: readonly Resource[];
  historyByTarget: ReadonlyMap<string, AvailabilityHistoryTarget>;
  historyLoading: boolean;
  historyError?: string;
  probeAgentOptions?: readonly ProbeAgentOption[];
  onRetryHistory?: () => void;
}> = (props) => {
  const now = useRelativeTimeNow();
  // Live snapshots replace resource objects. Reconciled by id, each tile (and
  // an open drawer) keeps its identity and updates in place instead of
  // remounting, and losing the drawer's tab, on every poll.
  const [fleet, setFleet] = createStore<Resource[]>([]);
  createComputed(() => setFleet(reconcile([...props.resources], { key: 'id' })));
  const [selectedResourceId, setSelectedResourceId] = createSignal<string>();
  const selectedResource = createMemo(() =>
    props.resources.find((resource) => resource.id === selectedResourceId()),
  );
  // A removed check is no longer evidence for the open detail. Clear its
  // selection as well, so a later reappearance cannot silently reopen it.
  createEffect(() => {
    if (selectedResourceId() && !selectedResource()) setSelectedResourceId(undefined);
  });
  const resolveResourceLabel = (resourceId: string): string | undefined =>
    props.resources.find((resource) => resource.id === resourceId)?.name;
  // Tiles are disclosures for one drawer: a second click on the open tile
  // closes it, as a second click on a table row does.
  const toggleResource = (resourceId: string) =>
    setSelectedResourceId((current) => (current === resourceId ? undefined : resourceId));
  // Closing from the drawer's header removes the focused control, so focus
  // returns to the tile that opened it, as a table drawer returns it to its row.
  const closeResource = (resourceId: string) => {
    setSelectedResourceId(undefined);
    queueMicrotask(() =>
      Array.from(document.querySelectorAll<HTMLButtonElement>('[data-availability-fleet-tile]'))
        .find((tile) => tile.dataset.availabilityFleetTile === resourceId)
        ?.focus({ preventScroll: true }),
    );
  };

  return (
    <section aria-label="Availability fleet" class="space-y-3">
      <div class="flex flex-wrap items-center justify-between gap-2 rounded-md border border-border px-3 py-2 text-xs text-muted">
        <div class="flex flex-wrap items-center gap-x-3 gap-y-1" aria-label="State history legend">
          <For each={Object.values(statePresentation)}>
            {(presentation) => (
              <span class="inline-flex items-center gap-1.5">
                <span
                  class={`h-2.5 w-2.5 rounded-xs ${presentation.className}`}
                  aria-hidden="true"
                />
                {presentation.label}
              </span>
            )}
          </For>
          <span class="text-[10px]">24-hour evidence · reachable latency only</span>
        </div>
        <Show when={props.historyError}>
          <div class="flex items-center gap-2 text-rose-700 dark:text-rose-300">
            <span>History unavailable. Current health is unchanged.</span>
            <Show when={props.onRetryHistory}>
              <Button type="button" size="xs" variant="secondary" onClick={props.onRetryHistory}>
                <RefreshCwIcon class="h-3 w-3" />
                Retry
              </Button>
            </Show>
          </div>
        </Show>
      </div>

      {/* The open check's drawer is a full-width grid item right after its
          tile. Dense packing lets the rest of that tile's row fill in first,
          so the drawer opens directly beneath the tile at every column count
          instead of below the whole fleet. */}
      <div
        class="grid grid-flow-row-dense grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4"
        data-testid="availability-fleet-grid"
      >
        <For each={fleet}>
          {(resource) => {
            const availability = () => availabilityFor(resource);
            const probe = () => getAvailabilityProbePresentation(resource, new Date(now()));
            const indicator = () => getStandaloneResourceStatusIndicator(resource, now());
            const targetID = () => availability()?.targetId ?? resource.platformId ?? resource.id;
            const history = () => props.historyByTarget.get(targetID());
            const buckets = () => history()?.buckets ?? [];
            const source = () =>
              getProbeSourceChipLabel(
                props.probeAgentOptions ?? [],
                availability()?.probeAgentId,
              ) ?? 'Local Pulse';
            const endpoint = () => {
              const current = availability();
              return current
                ? getAvailabilityProbeEndpointLabel(current) || resource.name
                : resource.name;
            };
            const checked = () =>
              formatRelativeTime(availability()?.lastChecked, {
                compact: true,
                emptyText: 'Not checked',
                now: now(),
              });
            const isSelected = () => selectedResourceId() === resource.id;
            const latency = () => {
              const value = availability()?.latencyMillis;
              return typeof value === 'number' && Number.isFinite(value) && value > 0
                ? `${value.toLocaleString()} ms`
                : undefined;
            };

            return (
              <>
                <button
                  type="button"
                  class="group min-w-0 rounded-md border bg-surface p-3 text-left shadow-xs transition hover:border-blue-400/60 hover:bg-surface-hover focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500"
                  classList={{
                    'border-border': !isSelected(),
                    'border-blue-500 bg-surface-hover ring-1 ring-blue-500/40': isSelected(),
                  }}
                  aria-label={`Open details for ${resource.name}`}
                  aria-expanded={isSelected()}
                  aria-controls={AVAILABILITY_FLEET_DETAIL_ID}
                  data-availability-fleet-tile={resource.id}
                  onClick={() => toggleResource(resource.id)}
                >
                  <div class="flex items-start justify-between gap-3">
                    <div class="min-w-0">
                      <div class="flex min-w-0 items-center gap-2">
                        <StatusDot
                          size="sm"
                          variant={indicator().variant}
                          title={indicator().label}
                          ariaHidden
                        />
                        <span
                          class="truncate text-sm font-semibold text-base-content"
                          title={resource.name}
                        >
                          {resource.name}
                        </span>
                      </div>
                      <div class="mt-1 truncate text-[11px] text-muted" title={endpoint()}>
                        {endpoint()}
                      </div>
                    </div>
                    <span class={probe()?.toneClassName ?? 'text-muted'}>
                      {probe()?.resultLabel ?? indicator().label}
                    </span>
                  </div>

                  <div class="mt-2 flex flex-wrap items-center gap-1.5 text-[10px] text-muted">
                    <MetadataBadge tone="muted" size="xs" appearance="outline">
                      {probe()?.methodLabel ?? availability()?.protocol ?? 'Probe'}
                    </MetadataBadge>
                    <MetadataBadge tone="muted" size="xs" appearance="outline">
                      {source()}
                    </MetadataBadge>
                    <span>Checked {checked()}</span>
                    <Show when={latency()}>{(value) => <span>{value()}</span>}</Show>
                  </div>

                  <div class="mt-3 space-y-1.5">
                    <Show
                      when={!props.historyLoading}
                      fallback={
                        <div
                          class="h-3 animate-pulse rounded-xs bg-surface-hover"
                          aria-label="Loading history"
                        />
                      }
                    >
                      <AvailabilityStateStrip buckets={buckets()} />
                    </Show>
                    <AvailabilityLatencyLine buckets={buckets()} />
                    <div class="flex items-center justify-between gap-2 text-[10px] text-muted">
                      <span>{availabilityText(history())}</span>
                      <Show when={history()?.revisionBoundaries?.length}>
                        <span title="The check configuration changed during this window">
                          {history()?.revisionBoundaries?.length} revision
                          {history()?.revisionBoundaries?.length === 1 ? '' : 's'}
                        </span>
                      </Show>
                    </div>
                  </div>
                </button>
                {/* The same check reads the same here as in the table view: the
                  table-row drawer, headed by the dot its tile shows. Keyed by
                  id, so switching tiles resets the drawer's tabs. */}
                <Show when={isSelected()}>
                  <div
                    id={AVAILABILITY_FLEET_DETAIL_ID}
                    data-testid="availability-fleet-detail"
                    class="col-span-full rounded-sm border border-border bg-surface px-2 py-3 sm:px-4 sm:py-4"
                  >
                    <ResourceDetailDrawer
                      resource={resource}
                      statusIndicator={indicator()}
                      presentation="table-row"
                      resolveResourceLabel={resolveResourceLabel}
                      onClose={() => closeResource(resource.id)}
                    />
                  </div>
                </Show>
              </>
            );
          }}
        </For>
      </div>
    </section>
  );
};

export default AvailabilityFleetView;