All files / src/hooks useInitialHistory.ts

73.13% Statements 98/134
56.96% Branches 45/79
86.66% Functions 26/30
78.76% Lines 89/113

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259                                  38x 38x 59x 59x 59x 59x 59x   38x               15x                                               43x 43x 43x     43x 20x 14x 14x       43x     43x   43x     43x   41x 41x   41x 3x 3x 3x       41x 3x 3x     38x 41x   41x   52x   41x     15x 15x 15x   15x 5x       14x 1x   13x   14x     41x 38x 38x 38x   44x                   38x     41x                                               41x 59x 41x         38x   38x   14x   14x 16x 15x   15x 15x         14x   14x 14x 1x 1x   1x 1x 1x     13x 13x 13x                                     43x 13x 13x         43x 13x 13x 13x               43x 14x 14x         43x 13x 13x         43x 1x 1x     43x    
// --------------------------------------------------------------------
// src/hooks/useInitialHistory.ts
// --------------------------------------------------------------------
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { ApolloClient, NormalizedCacheObject } from '@apollo/client';
import { OP } from '../graphql/operations';
import { type EndpointByAttribute, type HdbByEndpoint } from '../timeline/currentValueQueries';
import { canonicalAttr as canonicalAttrShared } from '../utils/utils';
 
export type Pt = { t: number; v: any };
export type HistStatus = 'idle' | 'loading' | 'refreshing' | 'succeeded' | 'failed';
 
function buildHdbGroups(
  attrs: string[],
  endpointByAttribute: EndpointByAttribute,
  hdbByEndpoint: HdbByEndpoint
): Map<number, string[]> {
  const groups = new Map<number, string[]>();
  for (const attr of attrs) {
    const key = canonicalAttrShared(attr).toLowerCase();
    const ep = endpointByAttribute[key] ?? '';
    const hdb = ep && ep in hdbByEndpoint ? hdbByEndpoint[ep] : 0;
    if (!groups.has(hdb)) groups.set(hdb, []);
    groups.get(hdb)!.push(attr);
  }
  return groups;
}
 
/* ------------------------------------------------------------------ */
/* Helper – normalize transport prefixes to “device/attr”.             */
/* Keeps history and live-stream keys identical.                       */
/* ------------------------------------------------------------------ */
function canonicalAttr(name: string): string {
  return canonicalAttrShared(name).toLowerCase();
}
 
/**
 * Fetch the complete (possibly downsampled) history inside `[start, end]`.
 *
 * • Initial mount uses a **hard** load (shows "Loading..." if empty).
 * • Later changes (range, attributes, maxPoints/downsample, manual refresh) use a **soft**
 *   refresh — keeps current data visible while new data is fetched, then swaps.
 * • Each successful fetch **overwrites** the previous data so live packets
 *   start populating a fresh canvas (no mixing of old/new attrs).
 */
export function useInitialHistory(
  client: ApolloClient<NormalizedCacheObject> | null,
  attrs: string[],
  maxPoints: number,
  start: number,
  end: number,
  rangeMs: number, // <- presetMs from useEffectiveTimeRange
  downsample: 'minmax' | 'avg' | 'lttb' | 'none',
  endpointByAttribute: EndpointByAttribute = {},
  hdbByEndpoint: HdbByEndpoint = {},
  paused = false
) {
  const [dataMap, setDataMap] = useState<Record<string, Pt[]>>({});
  const [status, setStatus] = useState<HistStatus>('idle');
  const [error, setError] = useState<string | null>(null);
 
  // Stable signature of the attribute list (order/dupes ignored)
  const attrsSig = useMemo(() => {
    const cleaned = (attrs ?? []).filter(Boolean).map((a) => a.trim());
    const uniqueSorted = Array.from(new Set(cleaned)).sort();
    return JSON.stringify(uniqueSorted);
  }, [attrs]);
 
  // Stable signature of hdb routing — changes when endpoint sources resolve
  const hdbSig = useMemo(() => JSON.stringify(hdbByEndpoint), [hdbByEndpoint]);
 
  // Prevent stale responses racing in: bump on every fetch, read the latest value via ref
  const reqTokenRef = useRef(0);
  // Tracks whether the hdbSig effect has already run once (to skip the initial mount fire)
  const hdbSigSeenOnce = useRef(false);
 
  /* ----------------------------- fetch ----------------------------- */
  const fetchHistory = useCallback(
    async (s: number, e: number, mode: 'hard' | 'soft') => {
      Iif (paused) return;
      Iif (!client) return;
 
      const softReset = () => {
        setDataMap({});
        setStatus('succeeded');
        setError(null);
      };
 
      // If no attributes, just reset and mark as succeeded
      if (!attrs || attrs.length === 0) {
        softReset();
        return;
      }
 
      setStatus(mode === 'hard' ? 'loading' : 'refreshing');
      setError(null);
 
      const myToken = ++reqTokenRef.current;
 
      const isStale = () => reqTokenRef.current !== myToken;
 
      const toPts = (history: any[]): Pt[] =>
        (history ?? [])
          .map((h) => {
            const rawTs = (h as any).timestamp;
            const ts = typeof rawTs === 'number' ? rawTs : parseFloat(rawTs);
            return { t: ts * 1000, v: (h as any).value };
          })
          .filter((p) => Number.isFinite(p.t))
          .sort((a, b) => a.t - b.t)
          .reduce<Pt[]>((acc, p) => {
            // HDB++ can return duplicate timestamps (especially with minmax-like data).
            // Keep the latest sample for a given timestamp to avoid zero-width artifacts.
            if (acc.length > 0 && acc[acc.length - 1].t === p.t) {
              acc[acc.length - 1] = p;
            } else {
              acc.push(p);
            }
            return acc;
          }, []);
 
      const runHdbQueries = async (requestedAttrs: string[]) => {
        const hdbGroups = buildHdbGroups(requestedAttrs, endpointByAttribute, hdbByEndpoint);
        const groupEntries = Array.from(hdbGroups.entries());
        const results = await Promise.allSettled(
          groupEntries.map(([hdb, groupAttrs]) =>
            client.query({
              query: OP,
              variables: { attributes: groupAttrs, start: s, end: e, maxPoints, downsample, hdb },
              fetchPolicy: 'network-only',
              // Treat GraphQL errors (e.g. "attribute not found in HDB") as empty
              // data rather than hard failures so other groups still render.
              errorPolicy: 'ignore'
            })
          )
        );
        return { groupEntries, results };
      };
 
      const attemptPartialFetch = async () => {
        const partialMap: Record<string, Pt[]> = {};
        const requestedAttrs = attrs.map((name) => String(name ?? '').trim()).filter(Boolean);
        if (requestedAttrs.length === 0) return null;
 
        const { results } = await runHdbQueries(requestedAttrs);
 
        results.forEach((res) => {
          if (res.status !== 'fulfilled') return;
          (res.value?.data?.hdbppHistory ?? []).forEach(
            ({ attribute, history }: { attribute: string; history: any[] }) => {
              const key = canonicalAttr(attribute);
              partialMap[key] = toPts(history ?? []);
            }
          );
        });
 
        if (Object.keys(partialMap).length === 0) {
          return null;
        }
 
        return { map: partialMap };
      };
 
      try {
        const requestedAttrs = attrs.map((name) => String(name ?? '').trim()).filter(Boolean);
        Iif (requestedAttrs.length === 0) {
          softReset();
          return;
        }
 
        const { results } = await runHdbQueries(requestedAttrs);
 
        if (isStale()) return;
 
        const map: Record<string, Pt[]> = {};
 
        results.forEach((res) => {
          if (res.status !== 'fulfilled') return;
          (res.value?.data?.hdbppHistory ?? []).forEach(
            ({ attribute, history }: { attribute: string; history: any[] }) => {
              const short = canonicalAttr(attribute);
              map[short] = toPts(history);
            }
          );
        });
 
        Iif (isStale()) return;
 
        const allFailed = results.every((r) => r.status === 'rejected');
        if (allFailed && Object.keys(map).length === 0) {
          const firstRejection = results.find(
            (r): r is PromiseRejectedResult => r.status === 'rejected'
          );
          setError(firstRejection?.reason?.message ?? 'Failed to load history');
          setStatus('failed');
          return;
        }
 
        setDataMap(map); // overwrite – start fresh
        setStatus('succeeded');
        setError(null);
      } catch (e: any) {
        if (isStale()) return;
 
        const partial = await attemptPartialFetch();
        if (partial) {
          setDataMap(partial.map);
          setStatus('succeeded');
          setError(null);
        } else {
          setError(e?.message ?? String(e));
          setStatus('failed');
        }
      }
    },
    [client, attrs, maxPoints, downsample, endpointByAttribute, hdbByEndpoint, paused]
  );
 
  /* ---------------------- initial mount fetch --------------------- */
  useEffect(() => {
    Iif (paused) return;
    fetchHistory(start, end, 'hard');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [paused]);
 
  /* --- re-fetch when HDB routing changes (endpoint sources resolved) -- */
  useEffect(() => {
    Eif (!hdbSigSeenOnce.current) {
      hdbSigSeenOnce.current = true;
      return; // skip the initial mount fire; the paused effect handles it
    }
    if (paused) return;
    fetchHistory(start, end, 'soft');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hdbSig]);
 
  /* ------- re-fetch on window size change (soft) ------------------ */
  useEffect(() => {
    Iif (paused) return;
    fetchHistory(start, end, 'soft');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [rangeMs, paused]);
 
  /* ------- re-fetch on attributes/maxPoints/downsample (soft) ----- */
  useEffect(() => {
    Iif (paused) return;
    fetchHistory(start, end, 'soft');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [attrsSig, maxPoints, downsample, paused]);
 
  /* manual retry hook (soft) */
  const refetch = useCallback(() => {
    Iif (paused) return;
    fetchHistory(start, end, 'soft');
  }, [fetchHistory, start, end, paused]);
 
  return { dataMap, setDataMap, status, error, refetch };
}