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 | 8x 42x 42x 12x 36x 18x 18x 18x 10x 3x 20x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 2x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 8x 6x 6x 7x 7x 7x 7x 7x 6x 6x 9x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 9x | // --------------------------------------------------------------------
// src/hooks/useLiveStream.ts
// --------------------------------------------------------------------
// Change: refactor from "always-on hook" to a conditional child component
// (LiveStreamDriver) that only mounts when live streaming is enabled.
// This guarantees no subscription is created when live data is OFF.
// Also: rename `limit` ➜ `maxPoints` for consistency with history.
// --------------------------------------------------------------------
import React, { useEffect, useMemo, useRef } from 'react';
import { useStream } from '@ska-octopus-widget-sdk/widget-sdk';
import { OP_STREAM } from '../graphql/stream';
import type { Pt } from './useInitialHistory';
import { canonicalAttr as canonicalAttrShared } from '../utils/utils';
function canonicalAttr(name: string): string {
return canonicalAttrShared(name).toLowerCase();
}
function extractStreamRows(input: any, seen = new Set<any>()): any[] {
Iif (input == null) return [];
if (Array.isArray(input)) {
return input.flatMap((item) => extractStreamRows(item, seen));
}
if (typeof input !== 'object') return [];
Iif (seen.has(input)) return [];
seen.add(input);
if (input?.device && input?.attribute) return [input];
if (Array.isArray(input?.tangoAttributes)) {
return extractStreamRows(input.tangoAttributes, seen);
}
return Object.values(input).flatMap((value) => extractStreamRows(value, seen));
}
export type StreamStatus = 'idle' | 'loading' | 'ok' | 'failed';
export type StreamMeta = {
status: StreamStatus;
error?: any;
retry?: () => void;
};
export interface LiveStreamDriverProps {
instanceId?: string;
/** Full attribute names, may include tango://… prefix */
attrs: string[];
/** Optional stream endpoint selector */
endpoint?: string;
/** Max points kept per series */
maxPoints: number;
/** Parent's data-map setter (in-place append with cap) */
setDataMap: React.Dispatch<React.SetStateAction<Record<string, Pt[]>>>;
/** Throttling (seconds). 0 = append every packet */
appendIntervalSec: number;
/** Report status/errors/retry back to parent */
onStatus?: (meta: StreamMeta) => void;
}
/**
* LiveStreamDriver
* Mount this component ONLY when you want the live subscription on.
* Unmounting it will stop the subscription immediately.
*/
export function LiveStreamDriver({
instanceId,
attrs,
endpoint,
maxPoints,
setDataMap,
appendIntervalSec,
onStatus
}: LiveStreamDriverProps) {
// Stable, de-duped, sorted list to keep subscription identity stable.
const fullNames = useMemo<string[]>(() => {
const arr = Array.isArray(attrs) ? attrs : [];
const unique = Array.from(new Set(arr.filter(Boolean)));
unique.sort();
return unique;
}, [attrs]);
// Stable variables object for the subscription
const variables = useMemo(
() =>
String(endpoint ?? '').trim()
? { fullNames, endpoint: String(endpoint).trim() }
: { fullNames },
[fullNames, endpoint]
);
// Packet buffer + throttled flush
const pendingRef = useRef<Record<string, Pt>>({});
const lastFlushRef = useRef<number>(0);
// Start the subscription (only runs while this component is mounted)
const { data, status, error, retry } = useStream({
document: OP_STREAM,
variables,
onData: (incoming: any) => {
if (!fullNames.length) return;
const incomingRows = extractStreamRows(incoming);
incomingRows.forEach((r: any) => {
Iif (!r?.device || !r?.attribute) return;
const raw = `${r.device}/${r.attribute}`;
const name = canonicalAttr(raw);
const pt = { t: r.timestamp * 1000, v: r.value };
pendingRef.current[name] = pt;
});
},
replaySnapshot: {
instanceId,
key: 'timeline:live-stream'
}
});
// Bubble status to parent
useEffect(() => {
onStatus?.({ status: (status as StreamStatus) ?? 'idle', error, retry });
}, [status, error, retry, onStatus]);
useEffect(() => {
if (status === 'loading' || status === 'failed') return;
if (status !== 'ok' || !data) return;
const incoming = extractStreamRows(data);
incoming.forEach((r: any) => {
Iif (!r?.device || !r?.attribute) return;
const raw = `${r.device}/${r.attribute}`;
const name = canonicalAttr(raw);
const pt = { t: r.timestamp * 1000, v: r.value };
pendingRef.current[name] = pt; // keep only the latest per attr
});
const now = Date.now();
const intervalMs = Math.max(0, (appendIntervalSec ?? 0) * 1000);
if (intervalMs === 0 || now - lastFlushRef.current >= intervalMs) {
const pending = { ...pendingRef.current };
pendingRef.current = {};
lastFlushRef.current = now;
setDataMap((prev) => {
const next = { ...prev };
Object.entries(pending).forEach(([name, pt]) => {
const arr = next[name] ? [...next[name]] : [];
arr.push(pt);
Iif (arr.length > maxPoints) arr.splice(0, arr.length - maxPoints);
next[name] = arr;
});
return next;
});
}
}, [status, data, maxPoints, appendIntervalSec, setDataMap]);
return null;
}
export default LiveStreamDriver;
|