From 745a27e8b70b03f1355e8d91a8e0a9e01d58c9ff Mon Sep 17 00:00:00 2001 From: Tom Cobb Date: Mon, 9 Nov 2026 13:48:45 +0000 Subject: [PATCH 1/8] Dispatch connectionChanged only when a PV's connection state changes serviceConnection dispatched connectionChanged for every PVWS message, so each value update also ran every mounted selector. It now remembers the last connected/readonly pair per PV and dispatches only when it differs. Measured (jsdom, real display stack, 1000 widgets at 100 msg/s): from saturated and falling behind (probe latency 10.7 s) to 57% of a core with a 92 ms probe. Assisted-by: Claude Opus 5 --- src/connection/serviceConnection.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/connection/serviceConnection.ts b/src/connection/serviceConnection.ts index 799e4a4e..7cc846d0 100644 --- a/src/connection/serviceConnection.ts +++ b/src/connection/serviceConnection.ts @@ -23,11 +23,15 @@ const onErrorMessageCallback = showError(`${message}`); }; +// Last connection state dispatched per PV, so an unchanged state is not re-dispatched. +const lastConnection = new Map(); + const onConnectionClosedCallback = (dispatch: Dispatch) => (pvName: string | undefined) => { if (!pvName) { return; } + lastConnection.delete(pvName); dispatch(connectionClosed({ pvName })); }; @@ -46,6 +50,14 @@ const onConnectionChangedCallback = if (!pvName) { return; } + // isReadonly is undefined on PVWS updates after the first: the reducer keeps the old value. + const prev = lastConnection.get(pvName); + const prevReadonly = prev?.split("|")[1]; + const key = `${isConnected}|${isReadonly ?? prevReadonly}`; + if (prev === key) { + return; + } + lastConnection.set(pvName, key); dispatch( connectionChanged({ From 4ca8ac12440cd48dd9d17c8dfb97febf2f8a61e1 Mon Sep 17 00:00:00 2001 From: Tom Cobb Date: Mon, 9 Nov 2026 13:48:57 +0000 Subject: [PATCH 2/8] Short-circuit fileComparator when the screen is unchanged fileComparator compared two JSON.stringify results on every dispatch. Return early when before and after are the same reference. Measured (jsdom, 1000 widgets): little change in steady state once connectionChanged is deduplicated, but startup falls from 22-27 s to 15-16 s. Assisted-by: Claude Opus 5 --- src/redux/slices/fileCacheSlice.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/redux/slices/fileCacheSlice.ts b/src/redux/slices/fileCacheSlice.ts index a01f4dd6..7beffd7f 100644 --- a/src/redux/slices/fileCacheSlice.ts +++ b/src/redux/slices/fileCacheSlice.ts @@ -565,6 +565,9 @@ export const fileComparator = ( before: WidgetDescription, after: WidgetDescription ): boolean => { + if (before === after) { + return true; + } if (!before || !after) { return false; } From c396cd007d373959ab6f38db8eb19876d0628136 Mon Sep 17 00:00:00 2001 From: Tom Cobb Date: Mon, 9 Nov 2026 13:54:33 +0000 Subject: [PATCH 3/8] Subscribe PV-reading hooks to their own PVs only Add a small keyed notifier (pvSubscriptions) that calls only the listeners of the PVs in each PV action, and use it through useSyncExternalStore in useConnection, useRules and useScripts instead of useSelector(selectPvStates), which ran for every mounted widget on every dispatch. Measured (jsdom, 1000 widgets at 100 msg/s): 51% to 37% of a core, and startup 15 s to 10 s. When the page is saturated (100 widgets at 1000 msg/s) CPU rises from 82% to 109% but probe latency falls from 420 ms to 274 ms, because updates that used to be dropped are now rendered. Assisted-by: Claude Opus 5 --- src/redux/pvSubscriptions.ts | 105 ++++++++++++++++++++++++++++++++ src/redux/store.ts | 4 +- src/ui/hooks/useConnection.ts | 20 ++---- src/ui/hooks/useRules.ts | 12 +--- src/ui/hooks/useScripts.test.ts | 5 +- src/ui/hooks/useScripts.ts | 11 +--- 6 files changed, 120 insertions(+), 37 deletions(-) create mode 100644 src/redux/pvSubscriptions.ts diff --git a/src/redux/pvSubscriptions.ts b/src/redux/pvSubscriptions.ts new file mode 100644 index 00000000..c1accc78 --- /dev/null +++ b/src/redux/pvSubscriptions.ts @@ -0,0 +1,105 @@ +import { Middleware } from "@reduxjs/toolkit"; +import { useCallback, useRef, useSyncExternalStore } from "react"; +import { useStore } from "react-redux"; +import { + connectionChanged, + connectionClosed, + CsState, + PvArrayResults, + pvStateComparator, + subscribe, + unsubscribe, + valueChanged, + valuesChanged +} from "./csState"; + +// Per-PV change notification: a hook reading PV state is told only about the PVs it reads, +// instead of re-running its selector on every dispatch. +type Listener = () => void; +const listeners = new Map>(); +// effective PV name -> the PV names widgets used for it, when they differ +const aliases = new Map>(); + +function subscribePvs(pvNames: string[], listener: Listener): () => void { + for (const pv of pvNames) { + let set = listeners.get(pv); + if (!set) { + set = new Set(); + listeners.set(pv, set); + } + set.add(listener); + } + return () => { + for (const pv of pvNames) { + const set = listeners.get(pv); + set?.delete(listener); + if (set?.size === 0) { + listeners.delete(pv); + } + } + }; +} + +function notify(pvNames: Iterable): void { + const toCall = new Set(); + const add = (pv: string) => listeners.get(pv)?.forEach(l => toCall.add(l)); + for (const pv of pvNames) { + add(pv); + aliases.get(pv)?.forEach(add); + } + toCall.forEach(l => l()); +} + +export const pvNotifyMiddleware: Middleware = () => next => action => { + const result = next(action); + if (valuesChanged.match(action)) { + notify(new Set(action.payload.map(a => a.payload.pvName))); + } else if ( + valueChanged.match(action) || + connectionChanged.match(action) || + connectionClosed.match(action) || + unsubscribe.match(action) + ) { + notify([action.payload.pvName]); + } else if (subscribe.match(action)) { + const { pvName, effectivePvName } = action.payload; + if (effectivePvName && effectivePvName !== pvName) { + let set = aliases.get(effectivePvName); + if (!set) { + set = new Set(); + aliases.set(effectivePvName, set); + } + set.add(pvName); + } + notify([pvName]); + } + return result; +}; + +function pvStatesOf(state: CsState, pvNames: string[]): PvArrayResults { + const results: PvArrayResults = {}; + for (const pvName of pvNames) { + const effectivePvName = state.effectivePvNameMap[pvName] || pvName; + results[pvName] = [state.valueCache[effectivePvName], effectivePvName]; + } + return results; +} + +/* The PV states of pvNames, re-rendering only when one of them changes. */ +export function usePvStates(pvNames: string[]): PvArrayResults { + const store = useStore(); + const key = pvNames.join("\u0000"); + const cache = useRef<{ key: string; results: PvArrayResults } | null>(null); + // eslint-disable-next-line react-hooks/exhaustive-deps + const sub = useCallback((l: Listener) => subscribePvs(pvNames, l), [key]); + const getSnapshot = () => { + const results = pvStatesOf((store.getState() as any).cs, pvNames); + const c = cache.current; + if (c && c.key === key && pvStateComparator(c.results, results)) { + return c.results; + } + cache.current = { key, results }; + return results; + }; + return useSyncExternalStore(sub, getSnapshot); +} diff --git a/src/redux/store.ts b/src/redux/store.ts index 56a7da84..92eaec62 100644 --- a/src/redux/store.ts +++ b/src/redux/store.ts @@ -12,6 +12,7 @@ import styleReducer from "./slices/styleSlice"; import { connectionMiddleware } from "./connectionMiddleware"; import { throttleMiddleware, UpdateThrottle } from "./throttleMiddleware"; import { CsWebLibConfig } from "./csWebLibConfig"; +import { pvNotifyMiddleware } from "./pvSubscriptions"; // Store singleton let storeInstance: ReturnType | null = null; @@ -64,7 +65,8 @@ const createStoreInstance = (config?: CsWebLibConfig) => { ) ) ) - ); + ) + .concat(pvNotifyMiddleware); }, devTools: isDevMode }); diff --git a/src/ui/hooks/useConnection.ts b/src/ui/hooks/useConnection.ts index 5859858b..62f3f37a 100644 --- a/src/ui/hooks/useConnection.ts +++ b/src/ui/hooks/useConnection.ts @@ -1,13 +1,7 @@ import React from "react"; import { useSubscription } from "./useSubscription"; -import { useSelector } from "react-redux"; -import { - CsState, - PvDataCollection, - selectPvStates, - pvStateComparator, - PvArrayResults -} from "../../redux/csState"; +import { usePvStates } from "../../redux/pvSubscriptions"; +import { PvDataCollection } from "../../redux/csState"; import { SubscriptionType } from "../../connection/plugin"; import { DType } from "../../types/dtypes"; @@ -24,10 +18,7 @@ export function useConnection( const pvNameArray = pvName === undefined ? [] : [pvName]; const typeArray = type === undefined ? [] : [type]; useSubscription(id, pvNameArray, typeArray); - const pvResults = useSelector( - (state): PvArrayResults => selectPvStates(state, pvNameArray), - pvStateComparator - ); + const pvResults = usePvStates(pvNameArray); let connected = false; let readonly = false; let value = undefined; @@ -56,10 +47,7 @@ export const useConnectionMultiplePv = ( useSubscription(id, pvNameArray, typeArray); - const pvResults = useSelector( - (state: CsState): PvArrayResults => selectPvStates(state, pvNameArray), - pvStateComparator - ); + const pvResults = usePvStates(pvNameArray); return { pvData: pvNameArray.map(pvName => { diff --git a/src/ui/hooks/useRules.ts b/src/ui/hooks/useRules.ts index f3056baf..21eb0a6f 100644 --- a/src/ui/hooks/useRules.ts +++ b/src/ui/hooks/useRules.ts @@ -1,12 +1,7 @@ import log from "loglevel"; import { useSubscription } from "./useSubscription"; -import { useSelector } from "react-redux"; -import { - selectPvStates, - pvStateComparator, - PvArrayResults -} from "../../redux/csState"; +import { usePvStates } from "../../redux/pvSubscriptions"; import { AnyProps } from "../widgets/widgetProps"; import { @@ -51,10 +46,7 @@ export function useRules(props: AnyProps): AnyProps { // Subscribe to all PVs. useSubscription(props.id, allPvs, allTypes); // Get results from all PVs. - const results = useSelector( - (state): PvArrayResults => selectPvStates(state, allPvs), - pvStateComparator - ); + const results = usePvStates(allPvs); for (const rule of rules) { const { name, pvs, prop, outExp, expressions } = rule; diff --git a/src/ui/hooks/useScripts.test.ts b/src/ui/hooks/useScripts.test.ts index 681cd31c..22b905b0 100644 --- a/src/ui/hooks/useScripts.test.ts +++ b/src/ui/hooks/useScripts.test.ts @@ -3,6 +3,7 @@ import { renderHook } from "@testing-library/react"; import { useScripts } from "./useScripts"; import { useSubscription } from "./useSubscription"; import { useSelector } from "react-redux"; +import { usePvStates } from "../../redux/pvSubscriptions"; import { executeDynamicScriptInSandbox } from "../widgets/EmbeddedDisplay/scripts/scriptExecutor"; import { newPV } from "../../types/pv"; import { Script } from "../../types/props"; @@ -10,6 +11,7 @@ import { newDType } from "../../types/dtypes"; vi.mock("./useSubscription"); vi.mock("react-redux"); +vi.mock("../../redux/pvSubscriptions"); vi.mock("../widgets/EmbeddedDisplay/scripts/scriptExecutor"); describe("useScripts", () => { @@ -19,7 +21,8 @@ describe("useScripts", () => { beforeEach(() => { vi.clearAllMocks(); - (useSelector as ReturnType).mockImplementation(selector => { + (useSelector as ReturnType).mockReturnValue(true); + (usePvStates as ReturnType).mockImplementation(() => { return { "ca://pv1": [ { diff --git a/src/ui/hooks/useScripts.ts b/src/ui/hooks/useScripts.ts index 35c85ea1..a5aaf4ab 100644 --- a/src/ui/hooks/useScripts.ts +++ b/src/ui/hooks/useScripts.ts @@ -2,11 +2,7 @@ import log from "loglevel"; import { useSubscription } from "./useSubscription"; import { useSelector } from "react-redux"; -import { - selectPvStates, - pvStateComparator, - PvArrayResults -} from "../../redux/csState"; +import { usePvStates } from "../../redux/pvSubscriptions"; import { dTypeCoerceString, dTypeGetDoubleValue } from "../../types/dtypes"; import { SubscriptionType } from "../../connection/plugin"; @@ -38,10 +34,7 @@ export const useScripts = ( useSubscription(widgetId, allPvs, allTypes); // Get results from all PVs. - const pvDataMap = useSelector( - (state): PvArrayResults => selectPvStates(state, allPvs), - pvStateComparator - ); + const pvDataMap = usePvStates(allPvs); const enableDynamicScripts = useSelector(selectEnableDynamicScripts); const hasScripts = !!scripts?.length; From cef279e893aa6eeb229e9699fe78bdd716af7a9d Mon Sep 17 00:00:00 2001 From: Tom Cobb Date: Mon, 9 Nov 2026 13:55:47 +0000 Subject: [PATCH 4/8] Keep one merged update per PV in the throttle queue The throttle queued every update between flushes. Keep the latest value per PV, merged with the earlier metadata, so a PV updated many times in 100 ms is reduced once. Measured (jsdom, 1000 widgets, all the rate on 10 PVs): no measurable effect (52-54% of a core without, 52% with). Candidate for dropping. Assisted-by: Claude Opus 5 --- src/redux/throttleMiddleware.ts | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/redux/throttleMiddleware.ts b/src/redux/throttleMiddleware.ts index 7eb22508..cd0d6e5f 100644 --- a/src/redux/throttleMiddleware.ts +++ b/src/redux/throttleMiddleware.ts @@ -1,13 +1,14 @@ import { MiddlewareAPI, Middleware } from "@reduxjs/toolkit"; import { valueChanged, valuesChanged } from "./csState"; +import { mergeDType } from "../types/dtypes"; export class UpdateThrottle { - private queue: ReturnType[]; + private queue: Map>; private started: boolean; private updateMillis: number; constructor(updateMillis: number) { - this.queue = []; + this.queue = new Map(); this.started = false; this.updateMillis = updateMillis; } @@ -20,13 +21,25 @@ export class UpdateThrottle { setInterval(() => this.sendQueue(store), this.updateMillis); this.started = true; } - this.queue.push(action); + const { pvName, value } = action.payload; + const queued = this.queue.get(pvName); + if (queued) { + // Merge so that metadata from an earlier update in the same batch is kept. + const prev = queued.payload.value; + const merged = { + ...mergeDType(prev, value), + partial: prev.partial && value.partial + }; + this.queue.set(pvName, valueChanged({ pvName, value: merged })); + } else { + this.queue.set(pvName, action); + } } public sendQueue(store: MiddlewareAPI): void { - if (this.queue.length > 0) { - store.dispatch(valuesChanged([...this.queue])); - this.queue = []; + if (this.queue.size > 0) { + store.dispatch(valuesChanged([...this.queue.values()])); + this.queue = new Map(); } } } From 9e89a517d893e38b57be3c9647ca95352a75d267 Mon Sep 17 00:00:00 2001 From: Tom Cobb Date: Mon, 9 Nov 2026 13:55:47 +0000 Subject: [PATCH 5/8] Use a plain textarea in the readback widget A multiline MUI TextField always renders TextareaAutosize, which calls getComputedStyle and reads scrollHeight after every render. Pass inputComponent: "textarea" so a text update no longer measures itself. Measured (jsdom, which exaggerates this cost): 1000 widgets at 1000 msg/s from saturated (108%, probe 4.2 s) to 41% with a 100 ms probe; 100 widgets at 100 msg/s from 32% to 6%; startup at 1000 widgets from 10 s to 3 s. The cost in Chromium was not measured separately. Assisted-by: Claude Opus 5 --- .../Readback/__snapshots__/readback.test.tsx.snap | 9 +-------- src/ui/widgets/Readback/readback.tsx | 4 +++- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/src/ui/widgets/Readback/__snapshots__/readback.test.tsx.snap b/src/ui/widgets/Readback/__snapshots__/readback.test.tsx.snap index 9ad10aac..9a3c498c 100644 --- a/src/ui/widgets/Readback/__snapshots__/readback.test.tsx.snap +++ b/src/ui/widgets/Readback/__snapshots__/readback.test.tsx.snap @@ -13,17 +13,10 @@ exports[` > alarm-sensitive foreground colour 1`] = ` class="MuiInputBase-input MuiOutlinedInput-input MuiInputBase-inputMultiline Mui-readOnly MuiInputBase-readOnly css-ecmmtb-MuiInputBase-input-MuiOutlinedInput-input" id=":r5:" readonly="" - style="height: 0px; overflow: hidden;" + type="text" > hello - - + hello diff --git a/src/ui/widgets/Readback/readback.test.tsx b/src/ui/widgets/Readback/readback.test.tsx index 82a9fb45..b69f51ba 100644 --- a/src/ui/widgets/Readback/readback.test.tsx +++ b/src/ui/widgets/Readback/readback.test.tsx @@ -61,9 +61,9 @@ describe("", (): void => { } as Partial as PvDatum ] }; - const { getByRole } = render(ReadbackRenderer(props)); + const { getByText } = render(ReadbackRenderer(props)); // Check for precision. - expect(getByRole("textbox").textContent).toBe("3.14"); + expect(getByText("3.14")).toBeInTheDocument(); }); test("string value with units", (): void => { @@ -128,6 +128,9 @@ describe("", (): void => { }; const { getByText } = render(ReadbackRenderer(props)); - expect(getByText("hello")).toBeDisabled(); + expect(getByText("hello").parentElement).toHaveAttribute( + "aria-disabled", + "true" + ); }); }); diff --git a/src/ui/widgets/Readback/readback.tsx b/src/ui/widgets/Readback/readback.tsx index 8ae31baf..b74d3be7 100644 --- a/src/ui/widgets/Readback/readback.tsx +++ b/src/ui/widgets/Readback/readback.tsx @@ -25,7 +25,6 @@ import { dTypeGetDisplay, AlarmQuality } from "../../../types/dtypes"; -import { TextField as MuiTextField, styled } from "@mui/material"; import { calculateRotationTransform, getPvValueAndName } from "../utils"; import { WIDGET_DEFAULT_SIZES } from "../EmbeddedDisplay/bobParser"; import { useStyle } from "../../hooks/useStyle"; @@ -54,33 +53,6 @@ const ReadbackProps = { width: StringOrNumPropOpt }; -const TextField = styled(MuiTextField)({ - // MUI Textfield contains a fieldset with a legend that needs to be removed - "& .css-w4cd9x": { - lineHeight: "0px" - }, - "& .MuiInputBase-root": { - height: "100%", - width: "100%", - padding: "0px" - }, - "& .MuiInputBase-input": { - padding: "0px", - lineHeight: 1.2, - textOverflow: "clip", - whiteSpace: "pre-wrap", - height: "100%", - width: "100%" - }, - "& .MuiOutlinedInput-root": { - "& .MuiOutlinedInput-notchedOutline": { - borderRadius: "4px", - borderWidth: "0px", - inset: "0px" - } - } -}); - // Needs to be exported for testing export type ReadbackComponentProps = InferWidgetProps & PVComponent; @@ -191,54 +163,41 @@ export const ReadbackComponent = ( ); return ( - +
+ > + {displayedValue} +
+ ); }; From 9e8e3bfb9ae2a5c9bc4425210fcd45db4d61920b Mon Sep 17 00:00:00 2001 From: Tom Cobb Date: Mon, 9 Nov 2026 13:57:47 +0000 Subject: [PATCH 7/8] Batch the subscribe actions of one React commit useSubscription queued each widget's subscribe as its own action. Queue them and flush as one subscribeBatch action on a microtask, so the reducers and subscribers run once per commit. Measured (jsdom, startup only): 5000 widgets from 72 s to 38 s, steady state unchanged. Assisted-by: Claude Opus 5 --- src/redux/connectionMiddleware.ts | 22 ++++++++++++++- src/redux/csState.ts | 47 ++++++++++++++++++------------- src/redux/pvSubscriptions.ts | 13 +++++++++ src/ui/hooks/useSubscription.ts | 23 +++++++++++++-- 4 files changed, 83 insertions(+), 22 deletions(-) diff --git a/src/redux/connectionMiddleware.ts b/src/redux/connectionMiddleware.ts index ac573a81..ff965b76 100644 --- a/src/redux/connectionMiddleware.ts +++ b/src/redux/connectionMiddleware.ts @@ -8,6 +8,7 @@ import { selectSubscriptions, setPvwsSettings, subscribe, + subscribeBatch, unsubscribe, writePv } from "./csState"; @@ -33,8 +34,27 @@ export const connectionMiddleware = ); } + const effectiveName = (pvName: string, type: any): string => { + try { + return getServiceConnection().subscribe(pvName, type); + } catch (error) { + showError(`Failed to subscribe to pv ${pvName}`); + log.error(`Failed to subscribe to pv ${pvName}`); + log.error(error); + return pvName; + } + }; + return next => async action => { - if (subscribe.match(action)) { + if (subscribeBatch.match(action)) { + action = { + ...action, + payload: action.payload.map(p => ({ + ...p, + effectivePvName: effectiveName(p.pvName, p.type) + })) + }; + } else if (subscribe.match(action)) { const { pvName, type } = action.payload; // Are we already subscribed? let effectivePvName = pvName; diff --git a/src/redux/csState.ts b/src/redux/csState.ts index 4aabd7f2..cca2fda2 100644 --- a/src/redux/csState.ts +++ b/src/redux/csState.ts @@ -81,6 +81,26 @@ function updateValueCache( valueCache[pvName] = { ...existing, value: mergedValue }; } +export type SubscribePayload = { + componentId: string; + pvName: string; + effectivePvName?: string; + type: SubscriptionType; +}; + +function addSubscription(state: CsState, payload: SubscribePayload): void { + const { componentId, pvName } = payload; + const effectivePvName = payload?.effectivePvName || pvName; + const list = state.subscriptions[effectivePvName] ?? []; + if (!list.includes(componentId)) { + list.push(componentId); + state.subscriptions[effectivePvName] = list; + } + if (pvName !== effectivePvName) { + state.effectivePvNameMap[pvName] = effectivePvName; + } +} + const csSlice = createSlice({ name: "cs", initialState: initialCsState, @@ -133,28 +153,16 @@ const csSlice = createSlice({ }; }, - subscribe( - state, - action: PayloadAction<{ - componentId: string; - pvName: string; - effectivePvName?: string; - type: SubscriptionType; - }> - ) { + subscribe(state, action: PayloadAction) { // the connection middleware intercepts this action and injects the effectivePvName before forwarding it log.debug(action); - const { componentId, pvName } = action.payload; - const effectivePvName = action.payload?.effectivePvName || pvName; - - const list = state.subscriptions[effectivePvName] ?? []; - if (!list.includes(componentId)) { - list.push(componentId); - state.subscriptions[effectivePvName] = list; - } + addSubscription(state, action.payload); + }, - if (pvName !== effectivePvName) { - state.effectivePvNameMap[pvName] = effectivePvName; + subscribeBatch(state, action: PayloadAction) { + log.debug(action); + for (const payload of action.payload) { + addSubscription(state, payload); } }, @@ -214,6 +222,7 @@ export const { connectionClosed, connectionChanged, subscribe, + subscribeBatch, unsubscribe, writePv, deviceQueried, diff --git a/src/redux/pvSubscriptions.ts b/src/redux/pvSubscriptions.ts index c1accc78..fa7d088d 100644 --- a/src/redux/pvSubscriptions.ts +++ b/src/redux/pvSubscriptions.ts @@ -8,6 +8,7 @@ import { PvArrayResults, pvStateComparator, subscribe, + subscribeBatch, unsubscribe, valueChanged, valuesChanged @@ -61,6 +62,18 @@ export const pvNotifyMiddleware: Middleware = () => next => action => { unsubscribe.match(action) ) { notify([action.payload.pvName]); + } else if (subscribeBatch.match(action)) { + for (const { pvName, effectivePvName } of action.payload) { + if (effectivePvName && effectivePvName !== pvName) { + let set = aliases.get(effectivePvName); + if (!set) { + set = new Set(); + aliases.set(effectivePvName, set); + } + set.add(pvName); + } + } + notify(action.payload.map(p => p.pvName)); } else if (subscribe.match(action)) { const { pvName, effectivePvName } = action.payload; if (effectivePvName && effectivePvName !== pvName) { diff --git a/src/ui/hooks/useSubscription.ts b/src/ui/hooks/useSubscription.ts index 304ba964..5a20dcf4 100644 --- a/src/ui/hooks/useSubscription.ts +++ b/src/ui/hooks/useSubscription.ts @@ -4,11 +4,30 @@ import { DType } from "../../types/dtypes"; import { SubscriptionType } from "../../connection/plugin"; import { store } from "../../redux/store"; import { - subscribe, + subscribeBatch, + SubscribePayload, unsubscribe, writePv as writePvAction } from "../../redux/csState"; +// Subscribe actions from one React commit are sent as one batch, so a screen of N widgets +// mounts with one dispatch instead of N (each of which runs every mounted selector). +let pending: SubscribePayload[] = []; +let flushDispatch: ((a: any) => void) | null = null; +function queueSubscribe(dispatch: (a: any) => void, p: SubscribePayload) { + pending.push(p); + if (!flushDispatch) { + flushDispatch = dispatch; + const flush = dispatch; + queueMicrotask(() => { + const batch = pending; + pending = []; + flushDispatch = null; + flush(subscribeBatch(batch)); + }); + } +} + export function useSubscription( componentId: string, pvNames: string[], @@ -30,7 +49,7 @@ export function useSubscription( // - returns a function that takes no arguments and returns nothing useEffect((): (() => void) => { pvsAndTypes.forEach(([pvName, type]): void => { - dispatch(subscribe({ componentId, pvName, type })); + queueSubscribe(dispatch, { componentId, pvName, type }); }); return (): void => { pvNames.forEach((pvName): void => { From 7273d1c0f08b7e8ca36bde177ed63cda41526e4c Mon Sep 17 00:00:00 2001 From: Tom Cobb Date: Mon, 9 Nov 2026 13:58:26 +0000 Subject: [PATCH 8/8] Send connectionChanged through the throttle as one batch At startup every PV's first connectionChanged was its own dispatch. Route them through the 100 ms throttle and dispatch one connectionsChanged action per flush. Measured (jsdom, startup only): 5000 widgets from 38 s to 7 s, 1000 widgets from 2.5 s to 0.9 s with the previous commit, steady state unchanged. Assisted-by: Claude Opus 5 --- src/redux/csState.ts | 48 ++++++++++++++++++---------- src/redux/pvSubscriptions.ts | 5 ++- src/redux/throttleMiddleware.test.ts | 12 +++++-- src/redux/throttleMiddleware.ts | 38 +++++++++++++++++++++- 4 files changed, 83 insertions(+), 20 deletions(-) diff --git a/src/redux/csState.ts b/src/redux/csState.ts index cca2fda2..2d789087 100644 --- a/src/redux/csState.ts +++ b/src/redux/csState.ts @@ -101,6 +101,28 @@ function addSubscription(state: CsState, payload: SubscribePayload): void { } } +type ConnectionChangedActionType = PayloadAction<{ + pvName: string; + value: { isConnected: boolean; isReadonly?: boolean }; +}>; + +function updateConnection( + state: CsState, + action: ConnectionChangedActionType +): void { + const { pvName, value } = action.payload; + const existing = state.valueCache[pvName] ?? { + connected: false, + readonly: true, + initializingPvName: pvName + }; + state.valueCache[pvName] = { + ...existing, + connected: value.isConnected, + readonly: value.isReadonly ?? existing.readonly + }; +} + const csSlice = createSlice({ name: "cs", initialState: initialCsState, @@ -132,25 +154,18 @@ const csSlice = createSlice({ delete state.valueCache[pvName]; } }, - connectionChanged( + connectionsChanged( state, - action: PayloadAction<{ - pvName: string; - value: { isConnected: boolean; isReadonly?: boolean }; - }> + action: PayloadAction> ) { log.debug(action); - const { pvName, value } = action.payload; - const existing = state.valueCache[pvName] ?? { - connected: false, - readonly: true, - initializingPvName: pvName - }; - state.valueCache[pvName] = { - ...existing, - connected: value.isConnected, - readonly: value.isReadonly ?? existing.readonly - }; + for (const a of action.payload) { + updateConnection(state, a); + } + }, + connectionChanged(state, action: ConnectionChangedActionType) { + log.debug(action); + updateConnection(state, action); }, subscribe(state, action: PayloadAction) { @@ -221,6 +236,7 @@ export const { valuesChanged, connectionClosed, connectionChanged, + connectionsChanged, subscribe, subscribeBatch, unsubscribe, diff --git a/src/redux/pvSubscriptions.ts b/src/redux/pvSubscriptions.ts index fa7d088d..6b4f301e 100644 --- a/src/redux/pvSubscriptions.ts +++ b/src/redux/pvSubscriptions.ts @@ -3,6 +3,7 @@ import { useCallback, useRef, useSyncExternalStore } from "react"; import { useStore } from "react-redux"; import { connectionChanged, + connectionsChanged, connectionClosed, CsState, PvArrayResults, @@ -53,7 +54,9 @@ function notify(pvNames: Iterable): void { export const pvNotifyMiddleware: Middleware = () => next => action => { const result = next(action); - if (valuesChanged.match(action)) { + if (connectionsChanged.match(action)) { + notify(action.payload.map(a => a.payload.pvName)); + } else if (valuesChanged.match(action)) { notify(new Set(action.payload.map(a => a.payload.pvName))); } else if ( valueChanged.match(action) || diff --git a/src/redux/throttleMiddleware.test.ts b/src/redux/throttleMiddleware.test.ts index ae16852a..63451e61 100644 --- a/src/redux/throttleMiddleware.test.ts +++ b/src/redux/throttleMiddleware.test.ts @@ -71,7 +71,7 @@ describe("throttleMidddlware", (): void => { expect(mockNext).not.toHaveBeenCalled(); }); - it("doesn't dispatch when receiving ConnectionChanged", (): void => { + it("queues ConnectionChanged and dispatches one batch", (): void => { const middleware = throttleMiddleware(updater); // nextHandler takes next() and returns the actual middleware function const nextHandler = middleware(mockStore); @@ -83,7 +83,15 @@ describe("throttleMidddlware", (): void => { payload: { pvName: "pv", value: { isReadonly: false, isConnected: true } } }; actionHandler(connectionAction); + // The connection update is queued, not dispatched or passed on. expect(mockStore.dispatch).toHaveBeenCalledTimes(0); - expect(mockNext).toHaveBeenCalledWith(connectionAction); + expect(mockNext).not.toHaveBeenCalled(); + + // manually trigger the dispatch + updater.sendQueue(mockStore); + expect(mockStore.dispatch).toHaveBeenCalledTimes(1); + expect(mockStore.dispatch.mock.calls[0][0].type).toEqual( + "cs/connectionsChanged" + ); }); }); diff --git a/src/redux/throttleMiddleware.ts b/src/redux/throttleMiddleware.ts index cd0d6e5f..77086d0f 100644 --- a/src/redux/throttleMiddleware.ts +++ b/src/redux/throttleMiddleware.ts @@ -1,9 +1,16 @@ import { MiddlewareAPI, Middleware } from "@reduxjs/toolkit"; -import { valueChanged, valuesChanged } from "./csState"; +import { + connectionChanged, + connectionsChanged, + valueChanged, + valuesChanged +} from "./csState"; import { mergeDType } from "../types/dtypes"; export class UpdateThrottle { private queue: Map>; + private connQueue: Map> = + new Map(); private started: boolean; private updateMillis: number; @@ -36,7 +43,34 @@ export class UpdateThrottle { } } + public queueConnection( + action: ReturnType, + store: MiddlewareAPI + ): void { + if (!this.started) { + setInterval(() => this.sendQueue(store), this.updateMillis); + this.started = true; + } + const prev = this.connQueue.get(action.payload.pvName); + const readonly = + action.payload.value.isReadonly ?? prev?.payload.value.isReadonly; + this.connQueue.set( + action.payload.pvName, + connectionChanged({ + pvName: action.payload.pvName, + value: { + isConnected: action.payload.value.isConnected, + isReadonly: readonly + } + }) + ); + } + public sendQueue(store: MiddlewareAPI): void { + if (this.connQueue.size > 0) { + store.dispatch(connectionsChanged([...this.connQueue.values()])); + this.connQueue = new Map(); + } if (this.queue.size > 0) { store.dispatch(valuesChanged([...this.queue.values()])); this.queue = new Map(); @@ -55,6 +89,8 @@ export const throttleMiddleware = action => { if (valueChanged.match(action)) { updater.queueUpdate(action, store); + } else if (connectionChanged.match(action)) { + updater.queueConnection(action, store); } else { return next(action); }