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.

11.5 KB
Raw Blame
import { apiFetchJSON, type APIContextOptions } from '@/utils/apiClient';
import {
  normalizeMonitoredSystemLedgerPreviewResponse,
  type MonitoredSystemLedgerPreviewResponse,
  type MonitoredSystemLedgerRawPreviewResponse,
} from './monitoredSystemLedger';
import {
  arrayOrUndefined,
  finiteNumberOrUndefined,
  optionalTrimmedString,
  strictBoolean,
  trimmedString,
} from './responseUtils';

const TRUE_NAS_CONNECTIONS_PATH = '/api/truenas/connections';

const REDACTED_SECRET = '********';

type RawTrueNASConnection = Partial<TrueNASConnection>;

type RawTrueNASConnectionPollError = Partial<TrueNASConnectionPollError>;
type RawTrueNASConnectionPoll = Partial<TrueNASConnectionPollStatus>;
type RawTrueNASConnectionObservedSummary = Partial<TrueNASConnectionObservedSummary>;
type RawTrueNASConnectionTransportStatus = Partial<TrueNASConnectionTransportStatus>;

export interface TrueNASConnectionPollError {
  at?: string;
  message?: string;
  category?: string;
}

export interface TrueNASConnectionPollStatus {
  intervalSeconds?: number;
  lastAttemptAt?: string;
  lastSuccessAt?: string;
  consecutiveFailures?: number;
  lastError?: TrueNASConnectionPollError;
}

export interface TrueNASConnectionObservedSummary {
  host?: string;
  resourceId?: string;
  collectedAt?: string;
  systems: number;
  storagePools: number;
  datasets: number;
  apps: number;
  vms: number;
  shares: number;
  disks: number;
  recoveryArtifacts: number;
}

export interface TrueNASConnectionTransportStatus {
  mode: 'negotiating' | 'jsonrpc-websocket' | 'legacy-rest';
  endpoint?: string;
  tls: boolean;
  connected: boolean;
  authMechanism?: string;
  applianceVersion?: string;
  legacyReason?: string;
  reconnects?: number;
  lastError?: string;
  lastConnectedAt?: string;
}

export interface TrueNASConnection {
  id: string;
  name: string;
  host: string;
  port?: number;
  apiKey?: string;
  username?: string;
  password?: string;
  useHttps: boolean;
  insecureSkipVerify: boolean;
  fingerprint?: string;
  enabled: boolean;
  pollIntervalSeconds?: number;
  monitorDatasets: boolean;
  monitorPools: boolean;
  monitorReplication: boolean;
  poll?: TrueNASConnectionPollStatus;
  observed?: TrueNASConnectionObservedSummary;
  transport?: TrueNASConnectionTransportStatus;
}

export interface TrueNASConnectionInput {
  name?: string;
  host: string;
  port?: number;
  apiKey?: string;
  username?: string;
  password?: string;
  useHttps?: boolean;
  insecureSkipVerify?: boolean;
  fingerprint?: string;
  enabled?: boolean;
  pollIntervalSeconds?: number;
  monitorDatasets?: boolean;
  monitorPools?: boolean;
  monitorReplication?: boolean;
}

export interface TrueNASConnectionTestResult {
  success: boolean;
}

const normalizeTrueNASConnectionPollError = (
  error: RawTrueNASConnectionPollError | undefined,
): TrueNASConnectionPollError | undefined => {
  if (!error || typeof error !== 'object') return undefined;
  return {
    at: optionalTrimmedString(error.at),
    message: optionalTrimmedString(error.message),
    category: optionalTrimmedString(error.category),
  };
};

const normalizeTrueNASConnectionPoll = (
  poll: RawTrueNASConnectionPoll | undefined,
): TrueNASConnectionPollStatus | undefined => {
  if (!poll || typeof poll !== 'object') return undefined;
  return {
    intervalSeconds: finiteNumberOrUndefined(poll.intervalSeconds),
    lastAttemptAt: optionalTrimmedString(poll.lastAttemptAt),
    lastSuccessAt: optionalTrimmedString(poll.lastSuccessAt),
    consecutiveFailures: finiteNumberOrUndefined(poll.consecutiveFailures),
    lastError: normalizeTrueNASConnectionPollError(poll.lastError),
  };
};

const normalizeTrueNASConnectionObservedSummary = (
  observed: RawTrueNASConnectionObservedSummary | undefined,
): TrueNASConnectionObservedSummary | undefined => {
  if (!observed || typeof observed !== 'object') return undefined;
  return {
    host: optionalTrimmedString(observed.host),
    resourceId: optionalTrimmedString(observed.resourceId),
    collectedAt: optionalTrimmedString(observed.collectedAt),
    systems: finiteNumberOrUndefined(observed.systems) ?? 0,
    storagePools: finiteNumberOrUndefined(observed.storagePools) ?? 0,
    datasets: finiteNumberOrUndefined(observed.datasets) ?? 0,
    apps: finiteNumberOrUndefined(observed.apps) ?? 0,
    vms: finiteNumberOrUndefined(observed.vms) ?? 0,
    shares: finiteNumberOrUndefined(observed.shares) ?? 0,
    disks: finiteNumberOrUndefined(observed.disks) ?? 0,
    recoveryArtifacts: finiteNumberOrUndefined(observed.recoveryArtifacts) ?? 0,
  };
};

const normalizeTrueNASConnectionTransportStatus = (
  transport: RawTrueNASConnectionTransportStatus | undefined,
): TrueNASConnectionTransportStatus | undefined => {
  if (!transport || typeof transport !== 'object') return undefined;
  const rawMode = optionalTrimmedString(transport.mode);
  const mode =
    rawMode === 'jsonrpc-websocket' || rawMode === 'legacy-rest' ? rawMode : 'negotiating';
  return {
    mode,
    endpoint: optionalTrimmedString(transport.endpoint),
    tls: strictBoolean(transport.tls),
    connected: strictBoolean(transport.connected),
    authMechanism: optionalTrimmedString(transport.authMechanism),
    applianceVersion: optionalTrimmedString(transport.applianceVersion),
    legacyReason: optionalTrimmedString(transport.legacyReason),
    reconnects: finiteNumberOrUndefined(transport.reconnects),
    lastError: optionalTrimmedString(transport.lastError),
    lastConnectedAt: optionalTrimmedString(transport.lastConnectedAt),
  };
};

const normalizeTrueNASConnection = (connection: RawTrueNASConnection): TrueNASConnection => ({
  id: trimmedString(connection.id),
  name: optionalTrimmedString(connection.name) ?? '',
  host: trimmedString(connection.host),
  port: finiteNumberOrUndefined(connection.port),
  apiKey: optionalTrimmedString(connection.apiKey),
  username: optionalTrimmedString(connection.username),
  password: optionalTrimmedString(connection.password),
  useHttps: strictBoolean(connection.useHttps),
  insecureSkipVerify: strictBoolean(connection.insecureSkipVerify),
  fingerprint: optionalTrimmedString(connection.fingerprint),
  enabled: strictBoolean(connection.enabled),
  pollIntervalSeconds: finiteNumberOrUndefined(connection.pollIntervalSeconds),
  monitorDatasets: strictBoolean(connection.monitorDatasets),
  monitorPools: strictBoolean(connection.monitorPools),
  monitorReplication: strictBoolean(connection.monitorReplication),
  poll: normalizeTrueNASConnectionPoll(connection.poll),
  observed: normalizeTrueNASConnectionObservedSummary(connection.observed),
  transport: normalizeTrueNASConnectionTransportStatus(connection.transport),
});

const serializeTrueNASConnectionInput = (input: TrueNASConnectionInput) => ({
  ...(input.name !== undefined ? { name: input.name } : {}),
  host: input.host,
  ...(input.port !== undefined ? { port: input.port } : {}),
  ...(input.apiKey !== undefined ? { apiKey: input.apiKey } : {}),
  ...(input.username !== undefined ? { username: input.username } : {}),
  ...(input.password !== undefined ? { password: input.password } : {}),
  ...(input.useHttps !== undefined ? { useHttps: input.useHttps } : {}),
  ...(input.insecureSkipVerify !== undefined
    ? { insecureSkipVerify: input.insecureSkipVerify }
    : {}),
  ...(input.fingerprint !== undefined ? { fingerprint: input.fingerprint } : {}),
  ...(input.enabled !== undefined ? { enabled: input.enabled } : {}),
  ...(input.pollIntervalSeconds !== undefined
    ? { pollIntervalSeconds: input.pollIntervalSeconds }
    : {}),
  ...(input.monitorDatasets !== undefined ? { monitorDatasets: input.monitorDatasets } : {}),
  ...(input.monitorPools !== undefined ? { monitorPools: input.monitorPools } : {}),
  ...(input.monitorReplication !== undefined
    ? { monitorReplication: input.monitorReplication }
    : {}),
});

export const isRedactedTrueNASSecret = (value: string | null | undefined) =>
  (value || '').trim() === REDACTED_SECRET;

export class TrueNASAPI {
  static async listConnections(options?: APIContextOptions): Promise<TrueNASConnection[]> {
    const response = await (options === undefined
      ? apiFetchJSON<RawTrueNASConnection[]>(TRUE_NAS_CONNECTIONS_PATH)
      : apiFetchJSON<RawTrueNASConnection[]>(TRUE_NAS_CONNECTIONS_PATH, options));
    const list = arrayOrUndefined<RawTrueNASConnection>(response) ?? [];
    return list.map(normalizeTrueNASConnection);
  }

  static async createConnection(
    input: TrueNASConnectionInput,
    options?: APIContextOptions,
  ): Promise<TrueNASConnection> {
    const response = await apiFetchJSON<RawTrueNASConnection>(TRUE_NAS_CONNECTIONS_PATH, {
      ...options,
      method: 'POST',
      body: JSON.stringify(serializeTrueNASConnectionInput(input)),
    });
    return normalizeTrueNASConnection(response);
  }

  static async updateConnection(
    id: string,
    input: TrueNASConnectionInput,
    options?: APIContextOptions,
  ): Promise<TrueNASConnection> {
    const response = await apiFetchJSON<RawTrueNASConnection>(
      `${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}`,
      {
        ...options,
        method: 'PUT',
        body: JSON.stringify(serializeTrueNASConnectionInput(input)),
      },
    );
    return normalizeTrueNASConnection(response);
  }

  static async deleteConnection(
    id: string,
    options?: APIContextOptions,
  ): Promise<{ success: boolean; id: string }> {
    return apiFetchJSON(`${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}`, {
      ...options,
      method: 'DELETE',
    });
  }

  static async testConnection(
    input: TrueNASConnectionInput,
    options?: APIContextOptions,
  ): Promise<TrueNASConnectionTestResult> {
    const response = await apiFetchJSON<Partial<TrueNASConnectionTestResult>>(
      `${TRUE_NAS_CONNECTIONS_PATH}/test`,
      {
        ...options,
        method: 'POST',
        body: JSON.stringify(serializeTrueNASConnectionInput(input)),
      },
    );
    return {
      success: strictBoolean(response.success),
    };
  }

  static async testSavedConnection(
    id: string,
    input?: TrueNASConnectionInput,
    options?: APIContextOptions,
  ): Promise<TrueNASConnectionTestResult> {
    const response = await apiFetchJSON<Partial<TrueNASConnectionTestResult>>(
      `${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}/test`,
      {
        ...options,
        method: 'POST',
        ...(input !== undefined
          ? { body: JSON.stringify(serializeTrueNASConnectionInput(input)) }
          : {}),
      },
    );
    return {
      success: strictBoolean(response.success),
    };
  }

  static async previewConnection(
    input: TrueNASConnectionInput,
    options?: APIContextOptions,
  ): Promise<MonitoredSystemLedgerPreviewResponse> {
    const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
      `${TRUE_NAS_CONNECTIONS_PATH}/preview`,
      {
        ...options,
        method: 'POST',
        body: JSON.stringify(serializeTrueNASConnectionInput(input)),
      },
    );
    return normalizeMonitoredSystemLedgerPreviewResponse(response);
  }

  static async previewSavedConnection(
    id: string,
    input?: TrueNASConnectionInput,
    options?: APIContextOptions,
  ): Promise<MonitoredSystemLedgerPreviewResponse> {
    const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
      `${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}/preview`,
      {
        ...options,
        method: 'POST',
        ...(input !== undefined
          ? { body: JSON.stringify(serializeTrueNASConnectionInput(input)) }
          : {}),
      },
    );
    return normalizeMonitoredSystemLedgerPreviewResponse(response);
  }
}