All files / src/hooks useInitialHistory.ts

94.28% Statements 99/105
71.15% Branches 37/52
100% Functions 20/20
98.95% Lines 95/96

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                              35x                                         21x 21x 21x 21x     21x 9x 7x 7x       21x     21x   20x   20x 3x 3x 3x 3x       20x 3x 3x     17x 20x 20x   20x 20x   20x   20x     18x 18x 18x   18x 6x   20x 6x 6x 6x   6x 12x 12x                       6x 12x 6x 6x 6x 6x 3x           6x       6x 3x 3x           3x 3x 3x 3x             6x 3x     3x     20x 20x             20x           11x   11x 11x   9x 9x         20x 20x 8x 8x           8x 3x 3x 3x             11x 11x 11x 11x   6x   6x 6x 3x 3x 3x 3x   3x 3x               21x 6x         21x 7x         21x 6x         21x 1x     21x    
// --------------------------------------------------------------------
// src/hooks/useInitialHistory.ts
// --------------------------------------------------------------------
import { useCallback, useEffect, useMemo, useState } from 'react';
import type { ApolloClient, NormalizedCacheObject } from '@apollo/client';
import { OP, CURR_VALUE_OP } from '../graphql/operations';
 
export type Pt = { t: number; v: any };
export type HistStatus = 'idle' | 'loading' | 'refreshing' | 'succeeded' | 'failed';
 
/* ------------------------------------------------------------------ */
/* Helper – turn “tango://host:port/device/attr” ➜ “device/attr”.     */
/* Keeps history and live-stream keys identical.                       */
/* ------------------------------------------------------------------ */
function canonicalAttr(name: string): string {
  return name.replace(/^tango:\/\/[^/]+\/(.+)$/, '$1');
}
 
/**
 * 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'
) {
  const [dataMap, setDataMap] = useState<Record<string, Pt[]>>({});
  const [status, setStatus] = useState<HistStatus>('idle');
  const [error, setError] = useState<string | null>(null);
  const [missingAttributes, setMissingAttributes] = useState<string[]>([]);
 
  // 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]);
 
  // Prevent stale responses racing in: bump token per request
  const [reqToken, setReqToken] = useState(0);
 
  /* ----------------------------- fetch ----------------------------- */
  const fetchHistory = useCallback(
    async (s: number, e: number, mode: 'hard' | 'soft') => {
      Iif (!client) return;
 
      const softReset = () => {
        setDataMap({});
        setStatus('succeeded');
        setError(null);
        setMissingAttributes([]);
      };
 
      // If no attributes, just reset and mark as succeeded
      if (!attrs || attrs.length === 0) {
        softReset();
        return;
      }
 
      setStatus(mode === 'hard' ? 'loading' : 'refreshing');
      setError(null);
      setMissingAttributes([]);
 
      const myToken = reqToken + 1;
      setReqToken(myToken);
 
      const isStale = () => myToken !== reqToken + 1 && myToken !== reqToken;
 
      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);
 
      const attemptPartialFetch = async () => {
        const partialMap: Record<string, Pt[]> = {};
        const zeroHistory: string[] = [];
        const failures = new Set<string>();
 
        for (const fullName of attrs) {
          try {
            const { data } = await client.query({
              query: OP,
              variables: {
                attributes: [fullName],
                start: s,
                end: e,
                maxPoints,
                downsample
              },
              fetchPolicy: 'network-only'
            });
 
            const row = data?.hdbppHistory?.[0];
            if (row?.attribute) {
              const key = canonicalAttr(row.attribute);
              const pts = toPts(row.history ?? []);
              partialMap[key] = pts;
              if (pts.length === 0) {
                zeroHistory.push(fullName);
              }
            } else E{
              failures.add(fullName);
            }
          } catch {
            failures.add(fullName);
          }
        }
 
        if (zeroHistory.length) {
          try {
            const { data: curr } = await client.query({
              query: CURR_VALUE_OP,
              variables: { fullNames: zeroHistory },
              fetchPolicy: 'network-only'
            });
 
            (curr?.attributes ?? []).forEach((row: any) => {
              Iif (!row?.name) return;
              const raw = row.device ? `${row.device}/${row.name}` : row.name;
              partialMap[canonicalAttr(raw)] = [{ t: s * 1000, v: row.value }];
            });
          } catch {
            // ignore current-value fallback failures
          }
        }
 
        if (Object.keys(partialMap).length === 0) {
          return null;
        }
 
        return { map: partialMap, missing: Array.from(failures) };
      };
 
      try {
        const vars = {
          attributes: attrs,
          start: s,
          end: e,
          maxPoints,
          downsample
        };
        const { data } = await client.query({
          query: OP,
          variables: vars,
          fetchPolicy: 'network-only'
        });
 
        Iif (isStale()) return;
 
        const map: Record<string, Pt[]> = {};
        (data?.hdbppHistory ?? []).forEach(
          ({ attribute, history }: { attribute: string; history: any[] }) => {
            const short = canonicalAttr(attribute);
            map[short] = toPts(history);
          }
        );
 
        // Backfill attrs that came back empty with current values
        const missing = attrs.filter((a) => (map[canonicalAttr(a)]?.length ?? 0) === 0);
        if (missing.length) {
          try {
            const { data: curr } = await client.query({
              query: CURR_VALUE_OP,
              variables: { fullNames: missing },
              fetchPolicy: 'network-only'
            });
 
            (curr?.attributes ?? []).forEach((row: any) => {
              Iif (!row?.name) return;
              const raw = row.device ? `${row.device}/${row.name}` : row.name;
              map[canonicalAttr(raw)] = [{ t: s * 1000, v: row.value }];
            });
          } catch {
            // ignore current-value fallback failures
          }
        }
 
        setDataMap(map); // overwrite – start fresh
        setStatus('succeeded');
        setError(null);
        setMissingAttributes([]);
      } catch (e: any) {
        Iif (isStale()) return;
 
        const partial = await attemptPartialFetch();
        if (partial) {
          setDataMap(partial.map);
          setStatus('succeeded');
          setError(null);
          setMissingAttributes(partial.missing);
        } else {
          setError(e?.message ?? String(e));
          setStatus('failed');
        }
      }
    },
    [client, attrs, maxPoints, downsample, reqToken]
  );
 
  /* ---------------------- initial mount fetch --------------------- */
  useEffect(() => {
    fetchHistory(start, end, 'hard');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
 
  /* ------- re-fetch on window size change (soft) ------------------ */
  useEffect(() => {
    fetchHistory(start, end, 'soft');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [rangeMs]);
 
  /* ------- re-fetch on attributes/maxPoints/downsample (soft) ----- */
  useEffect(() => {
    fetchHistory(start, end, 'soft');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [attrsSig, maxPoints, downsample]);
 
  /* manual retry hook (soft) */
  const refetch = useCallback(() => {
    fetchHistory(start, end, 'soft');
  }, [fetchHistory, start, end]);
 
  return { dataMap, setDataMap, status, error, refetch, missingAttributes };
}