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.

15.1 KB
Raw Blame
import { For, Show, createMemo } from 'solid-js';

import { IncidentEventFilters } from '@/components/Alerts/IncidentEventFilters';
import { IncidentTimelineEventCard } from '@/components/Alerts/IncidentTimelineEventCard';
import { Card } from '@/components/shared/Card';
import type { Alert, Incident } from '@/types/api';
import type { Resource } from '@/types/resource';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { getPreferredInfrastructureDisplayName } from '@/utils/resourceIdentity';
import {
  formatIncidentEvidenceTime,
  INCIDENT_HISTORY_PARTIAL,
  getAlertIncidentLevelBadgeClass,
  getAlertIncidentStatusPresentation,
  getAlertIncidentTimelineHeadingClass,
  getAlertIncidentTimelineMetaRowClass,
  getAlertIncidentTimelineOutputClass,
  getAlertResourceIncidentAcknowledgedByLabel,
  getAlertResourceIncidentActivityChipClass,
  getAlertResourceIncidentActivitySummaryClass,
  getAlertResourceIncidentCardClass,
  getAlertResourceIncidentCountLabel,
  getAlertResourceIncidentEmptyState,
  getAlertResourceIncidentFilteredEventsEmptyState,
  getAlertResourceIncidentLoadingState,
  getAlertResourceIncidentLoadFailure,
  getAlertResourceIncidentPanelTitle,
  getAlertResourceIncidentRefreshLabel,
  getAlertResourceIncidentSummaryRowClass,
  getAlertResourceIncidentToggleButtonClass,
  getAlertResourceIncidentToggleLabel,
  getAlertResourceIncidentTruncatedEventsLabel,
  normalizeAlertIncidentStatus,
} from '@/utils/alertIncidentPresentation';

import { getMetricAlertPresentation } from './metricAlertPresentation';
import { filterIncidentEvents, summarizeIncidentEvents } from './types';
import type { AlertHistoryState } from './useAlertHistoryState';

interface AlertResourceIncidentsPanelProps {
  state: AlertHistoryState;
  getResource?: (resourceId: string) => Resource | undefined;
  onClose?: () => void;
  showCloseAction?: boolean;
  showTitle?: boolean;
}

export function AlertResourceIncidentsPanel(props: AlertResourceIncidentsPanelProps) {
  // The live reading turns stale when evaluations stop, so it rechecks on the
  // shared clock rather than only when the alert changes.
  const now = useRelativeTimeNow();
  return (
    <Show when={props.state.resourceIncidentPanel()}>
      {(selection) => {
        const resourceId = selection().resourceId;
        const incidents = () => props.state.resourceIncidents()[resourceId] || [];
        const isLoading = () => props.state.resourceIncidentLoading()[resourceId];
        const hasError = () => props.state.resourceIncidentError()[resourceId];
        const lookupResource = () => props.getResource ?? props.state.getResource;
        const resource = () => lookupResource()?.(resourceId);
        // An open occurrence's message is the breach that opened it. A
        // threshold alert can stay open below its trigger, so describe the
        // open occurrence from its live alert; closed ones keep their copy.
        // An occurrence is its alert id plus its start, as the incident store
        // keys it, so a cached row never takes a later recurrence's reading.
        const liveAlertFor = (incident: Incident): Alert | undefined => {
          if (normalizeAlertIncidentStatus(incident.status) !== 'open') return undefined;
          const openedAt = Date.parse(incident.openedAt);
          if (!Number.isFinite(openedAt)) return undefined;
          return Object.values(props.state.activeAlerts?.() ?? {}).find(
            (alert) =>
              alert?.id === incident.alertIdentifier && Date.parse(alert.startTime) === openedAt,
          );
        };
        const resourceDisplayName = () => {
          const current = resource();
          if (current) {
            return getPreferredInfrastructureDisplayName(current);
          }
          return selection().resourceName;
        };

        return (
          <Card padding="md">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
              <div>
                <Show when={props.showTitle ?? true}>
                  <h3 class="text-sm font-semibold text-base-content">
                    {getAlertResourceIncidentPanelTitle()}
                  </h3>
                </Show>
                <p class="text-xs text-muted">
                  {resourceDisplayName()}
                  <Show when={incidents().length > 0}>
                    <span> · {getAlertResourceIncidentCountLabel(incidents().length)}</span>
                  </Show>
                </p>
              </div>
              <div class="flex items-center gap-2">
                <button
                  type="button"
                  class="px-2 py-1 text-xs border rounded-md border-border text-muted hover:bg-surface-hover disabled:opacity-50"
                  disabled={isLoading()}
                  onClick={() => {
                    void props.state.refreshResourceIncidentPanel();
                  }}
                >
                  {getAlertResourceIncidentRefreshLabel(isLoading())}
                </button>
                <Show when={props.showCloseAction ?? true}>
                  <button
                    type="button"
                    class="px-2 py-1 text-xs border rounded-md border-border text-muted hover:bg-surface-hover"
                    onClick={() =>
                      props.onClose ? props.onClose() : props.state.setResourceIncidentPanel(null)
                    }
                  >
                    Close
                  </button>
                </Show>
              </div>
            </div>
            <Show when={isLoading()}>
              <p class="mt-2 text-xs text-muted">{getAlertResourceIncidentLoadingState().text}</p>
            </Show>
            <Show when={!isLoading() && hasError()}>
              <p class="mt-2 text-xs text-error" role="alert">
                {getAlertResourceIncidentLoadFailure()}. Use Refresh to try again.
              </p>
            </Show>
            <Show when={!isLoading()}>
              <Show when={incidents().length > 0}>
                <div class="mt-2">
                  <IncidentEventFilters
                    filters={props.state.resourceIncidentEventFilters}
                    setFilters={props.state.setResourceIncidentEventFilters}
                    variant="compact"
                    showQuickSelection
                  />
                </div>
              </Show>
              <Show
                when={incidents().length > 0}
                fallback={
                  <Show when={!hasError()}>
                    <p class="mt-2 text-xs text-muted">
                      {getAlertResourceIncidentEmptyState().text}
                    </p>
                  </Show>
                }
              >
                <div class="mt-3 space-y-3">
                  <For each={incidents()}>
                    {(incident) => {
                      const statusPresentation = getAlertIncidentStatusPresentation(
                        incident.status,
                        incident.acknowledged,
                      );
                      const events = incident.events || [];
                      const isExpanded = () =>
                        props.state.expandedResourceIncidentIds().has(incident.id);
                      const filteredEvents = createMemo(() =>
                        filterIncidentEvents(events, props.state.resourceIncidentEventFilters()),
                      );
                      const eventSummary = createMemo(() =>
                        summarizeIncidentEvents(filteredEvents()),
                      );
                      const recentEvents = createMemo(() =>
                        filteredEvents().length > 6
                          ? filteredEvents().slice(filteredEvents().length - 6)
                          : filteredEvents(),
                      );
                      const lastEvent = () =>
                        filteredEvents().length > 0
                          ? filteredEvents()[filteredEvents().length - 1]
                          : undefined;
                      const livePresentation = () => {
                        const alert = liveAlertFor(incident);
                        return alert ? getMetricAlertPresentation(alert, now()) : null;
                      };
                      const filteredLabel = () =>
                        filteredEvents().length !== events.length
                          ? `${filteredEvents().length}/${events.length}`
                          : `${events.length}`;

                      return (
                        <div class={getAlertResourceIncidentCardClass()}>
                          <div class="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                            <div class={getAlertIncidentTimelineMetaRowClass()}>
                              <span class={getAlertIncidentTimelineHeadingClass()}>
                                {incident.alertType}
                              </span>
                              <span class={getAlertIncidentLevelBadgeClass(incident.level)}>
                                {incident.level}
                              </span>
                              <span class={statusPresentation.className}>
                                {statusPresentation.label}
                              </span>
                              <Show when={formatIncidentEvidenceTime(incident.openedAt)}>
                                <span>opened {formatIncidentEvidenceTime(incident.openedAt)}</span>
                              </Show>
                              <Show when={incident.closedAt}>
                                <span>
                                  closed {new Date(incident.closedAt as string).toLocaleString()}
                                </span>
                              </Show>
                            </div>
                          </div>
                          <Show when={incident.history?.hasMoreChanges}>
                            <p class="text-xs text-muted" role="status">
                              {INCIDENT_HISTORY_PARTIAL}
                            </p>
                          </Show>
                          <Show
                            when={livePresentation()}
                            fallback={
                              <Show when={incident.message}>
                                <p class={getAlertIncidentTimelineOutputClass()}>
                                  {incident.message}
                                </p>
                              </Show>
                            }
                          >
                            {(live) => (
                              <p
                                class={getAlertIncidentTimelineOutputClass()}
                                title={live().lastBreach}
                              >
                                {live().summary}. {live().detail}
                              </p>
                            )}
                          </Show>
                          <Show when={incident.acknowledged && incident.ackUser}>
                            <p class={getAlertIncidentTimelineOutputClass()}>
                              {getAlertResourceIncidentAcknowledgedByLabel(incident.ackUser ?? '')}
                            </p>
                          </Show>
                          <Show when={events.length > 0}>
                            <div class={getAlertResourceIncidentSummaryRowClass()}>
                              <Show
                                when={filteredEvents().length > 0}
                                fallback={
                                  <span>
                                    {getAlertResourceIncidentFilteredEventsEmptyState().text}
                                  </span>
                                }
                              >
                                <div class={getAlertResourceIncidentActivitySummaryClass()}>
                                  <span class="text-[10px] font-medium uppercase tracking-wide text-muted">
                                    Activity
                                  </span>
                                  <For each={eventSummary()}>
                                    {(summary) => (
                                      <span class={getAlertResourceIncidentActivityChipClass()}>
                                        {summary.label} {summary.count}
                                      </span>
                                    )}
                                  </For>
                                  <span>
                                    {filteredEvents().length !== events.length
                                      ? `${filteredEvents().length}/${events.length} events`
                                      : `${events.length} event${events.length === 1 ? '' : 's'}`}
                                  </span>
                                  <Show when={lastEvent()}>
                                    <span>Latest: {lastEvent()?.summary}</span>
                                  </Show>
                                </div>
                              </Show>
                              <button
                                type="button"
                                class={getAlertResourceIncidentToggleButtonClass()}
                                onClick={() =>
                                  props.state.toggleResourceIncidentDetails(incident.id)
                                }
                              >
                                {getAlertResourceIncidentToggleLabel(isExpanded(), filteredLabel())}
                              </button>
                            </div>
                          </Show>
                          <Show when={isExpanded()}>
                            <div class="mt-2 space-y-2">
                              <Show
                                when={filteredEvents().length > 0}
                                fallback={
                                  <p class="text-[10px] text-muted">
                                    {getAlertResourceIncidentFilteredEventsEmptyState().text}
                                  </p>
                                }
                              >
                                <For each={recentEvents()}>
                                  {(event) => (
                                    <IncidentTimelineEventCard event={event} variant="alt" />
                                  )}
                                </For>
                                <Show when={filteredEvents().length > 0}>
                                  <p class="text-[10px] text-muted">
                                    {getAlertResourceIncidentTruncatedEventsLabel(
                                      recentEvents().length,
                                      filteredEvents().length,
                                    )}
                                  </p>
                                </Show>
                              </Show>
                            </div>
                          </Show>
                        </div>
                      );
                    }}
                  </For>
                </div>
              </Show>
            </Show>
          </Card>
        );
      }}
    </Show>
  );
}