All files / src DataPipelineWidget.tsx

73.52% Statements 50/68
79.16% Branches 19/24
83.33% Functions 10/12
74.57% Lines 44/59

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                                                        2x     27x   27x 27x 27x 27x     27x 27x               27x                                 27x                   27x   27x 27x     27x 27x 27x     27x 9x 9x 9x   9x 9x                 9x 9x 9x 9x               27x 9x   9x 1x 1x         27x 27x             27x           27x 9x 2x 2x 2x     27x     27x 3x           24x   27x                                                                  
// src/DataPipelineWidget.tsx
import { useEffect, useMemo, useState, useCallback } from 'react';
import { CircularProgress, LinearProgress, Typography } from '@mui/material';
import { useApolloClient } from '@apollo/client';
 
import {
  useStream,
  DataLoadFailed,
  useWidgetRefreshRate
} from '@ska-octopus-widget-sdk/widget-sdk';
 
import { DATA_PIPELINE_STREAM_SUB, TRIGGER_DATA_PIPELINE_QUERY } from './graphql/pipeline';
import SunburstWidget, { SunburstData } from './SunburstWidget';
import styles from './DataPipelineWidget.module.css';
 
/* ---------- local types ----------------------------------------- */
interface Project {
  name: string;
  last_activity_at: string;
  pipeline_status: string;
}
interface StreamMsg {
  processed: number;
  total: number;
  project?: Project;
}
 
/* ---------- helpers --------------------------------------------- */
const norm = (s: string) => String(s).trim().toLowerCase().replace(/\s+/g, '_');
 
function buildSunburst(projects: Project[]): SunburstData {
  const rootLabel = 'Data Pipeline';
 
  const ids: string[] = ['root'];
  const labels: string[] = [rootLabel];
  const parents: string[] = [''];
  const values: number[] = [projects.length];
 
  // Count projects by status and keep per‑status project lists
  const buckets = new Map<string, { label: string; projects: Project[] }>();
  for (const p of projects) {
    const key = norm(p.pipeline_status);
    const entry = buckets.get(key) ?? { label: p.pipeline_status, projects: [] };
    entry.projects.push(p);
    buckets.set(key, entry);
  }
 
  // Add status nodes
  for (const [key, entry] of buckets.entries()) {
    const stateId = `state:${key}`;
    ids.push(stateId);
    labels.push(entry.label);
    parents.push('root');
    values.push(entry.projects.length);
 
    // Add project leaves
    for (const prj of entry.projects) {
      const leafId = `project:${norm(prj.name)}@${stateId}`;
      ids.push(leafId);
      labels.push(prj.name);
      parents.push(stateId);
      values.push(1);
    }
  }
 
  return { ids, labels, parents, values };
}
 
export interface DataPipelineWidgetProps {
  instanceId?: string;
}
 
/* ---------- component ------------------------------------------- */
export default function DataPipelineWidget({ instanceId }: DataPipelineWidgetProps) {
  /* one channel per widget instance (stable) */
  const channel = useMemo(() => `DPP_${Math.random().toString(36).slice(2)}`, []);
 
  const refresh = useWidgetRefreshRate(instanceId ?? 'dataPipeline');
  const apollo = useApolloClient();
 
  /* local state ------------------------------------------------- */
  const [projects, setProjects] = useState<Project[]>([]);
  const [processed, setProcessed] = useState(0);
  const [total, setTotal] = useState(0);
 
  /* helper: (re)trigger the backend job ------------------------- */
  const callTrigger = useCallback(async () => {
    setProjects([]);
    setProcessed(0);
    setTotal(0);
 
    try {
      const { data } = await apollo.query<{
        dataPipeline: Project[];
      }>({
        query: TRIGGER_DATA_PIPELINE_QUERY,
        variables: { progressChannel: channel },
        fetchPolicy: 'network-only'
      });
 
      // Fast path: backend replied with the full list synchronously
      Eif (Array.isArray(data?.dataPipeline)) {
        setProjects(data.dataPipeline);
        setProcessed(data.dataPipeline.length);
        setTotal(data.dataPipeline.length);
      }
    } catch {
      /* the stream will surface any meaningful backend errors */
    }
  }, [apollo, channel]);
 
  /* first trigger + periodic retrigger -------------------------- */
  useEffect(() => {
    callTrigger(); // initial
 
    if (refresh && refresh > 0) {
      const id = window.setInterval(callTrigger, refresh * 1000);
      return () => clearInterval(id);
    }
  }, [callTrigger, refresh]);
 
  /* subscription – generic JSON payloads from pubsub ------------ */
  const streamVariables = useMemo(() => ({ channel }), [channel]);
  const mapFn = useCallback((d: any) => d.pubsub as StreamMsg, []);
 
  const {
    data: msg,
    status: streamStatus,
    error: streamError,
    retry: retryStream
  } = useStream<StreamMsg, { channel: string }>({
    document: DATA_PIPELINE_STREAM_SUB,
    variables: streamVariables,
    map: mapFn
  });
 
  useEffect(() => {
    if (!msg) return;
    setProcessed(msg.processed);
    setTotal(msg.total);
    Iif (msg.project) setProjects((p) => [...p, msg.project]);
  }, [msg]);
 
  const sunburstData = useMemo(() => buildSunburst(projects), [projects]);
 
  /* ---------- error ------------------------------------------- */
  if (streamStatus === 'failed') {
    return (
      <DataLoadFailed message="Subscription failed" error={streamError} handleRetry={retryStream} />
    );
  }
 
  /* ---------- UI ---------------------------------------------- */
  const stillLoading = processed < total || total === 0;
 
  return (
    <div className={styles.container}>
      {stillLoading && (
        <>
          <Typography gutterBottom className={styles.loadingText}>
            🔄 Loading data pipeline…
          </Typography>
 
          {total > 0 ? (
            <>
              <LinearProgress
                variant="determinate"
                value={(processed / total) * 100}
                className={styles.linearProgress}
              />
              <Typography variant="caption" align="right" className={styles.progressCaption}>
                {processed} / {total} projects
              </Typography>
            </>
          ) : (
            <div className={styles.spinnerWrapper}>
              <CircularProgress size={24} />
            </div>
          )}
        </>
      )}
 
      <div className={`${styles.content} ${stillLoading ? styles.contentLoading : ''}`}>
        <SunburstWidget title="Data Pipeline" data={sunburstData} />
      </div>
    </div>
  );
}