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({ 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..2d789087 100644 --- a/src/redux/csState.ts +++ b/src/redux/csState.ts @@ -81,6 +81,48 @@ 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; + } +} + +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, @@ -112,49 +154,30 @@ 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<{ - 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); } }, @@ -213,7 +236,9 @@ export const { valuesChanged, connectionClosed, connectionChanged, + connectionsChanged, subscribe, + subscribeBatch, unsubscribe, writePv, deviceQueried, diff --git a/src/redux/pvSubscriptions.ts b/src/redux/pvSubscriptions.ts new file mode 100644 index 00000000..6b4f301e --- /dev/null +++ b/src/redux/pvSubscriptions.ts @@ -0,0 +1,121 @@ +import { Middleware } from "@reduxjs/toolkit"; +import { useCallback, useRef, useSyncExternalStore } from "react"; +import { useStore } from "react-redux"; +import { + connectionChanged, + connectionsChanged, + connectionClosed, + CsState, + PvArrayResults, + pvStateComparator, + subscribe, + subscribeBatch, + 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 (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) || + connectionChanged.match(action) || + connectionClosed.match(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) { + 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/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; } 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/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 7eb22508..77086d0f 100644 --- a/src/redux/throttleMiddleware.ts +++ b/src/redux/throttleMiddleware.ts @@ -1,13 +1,21 @@ 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: ReturnType[]; + private queue: Map>; + private connQueue: Map> = + new Map(); private started: boolean; private updateMillis: number; constructor(updateMillis: number) { - this.queue = []; + this.queue = new Map(); this.started = false; this.updateMillis = updateMillis; } @@ -20,13 +28,52 @@ 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 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.queue.length > 0) { - store.dispatch(valuesChanged([...this.queue])); - this.queue = []; + 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(); } } } @@ -42,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); } 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; 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 => { diff --git a/src/ui/widgets/Readback/__snapshots__/readback.test.tsx.snap b/src/ui/widgets/Readback/__snapshots__/readback.test.tsx.snap index 9ad10aac..145ac005 100644 --- a/src/ui/widgets/Readback/__snapshots__/readback.test.tsx.snap +++ b/src/ui/widgets/Readback/__snapshots__/readback.test.tsx.snap @@ -3,42 +3,13 @@ exports[` > alarm-sensitive foreground colour 1`] = `
- -