Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/connection/serviceConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>();

const onConnectionClosedCallback =
(dispatch: Dispatch) => (pvName: string | undefined) => {
if (!pvName) {
return;
}
lastConnection.delete(pvName);
dispatch(connectionClosed({ pvName }));
};

Expand All @@ -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({
Expand Down
22 changes: 21 additions & 1 deletion src/redux/connectionMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
selectSubscriptions,
setPvwsSettings,
subscribe,
subscribeBatch,
unsubscribe,
writePv
} from "./csState";
Expand All @@ -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;
Expand Down
95 changes: 60 additions & 35 deletions src/redux/csState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<Array<ConnectionChangedActionType>>
) {
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<SubscribePayload>) {
// 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<SubscribePayload[]>) {
log.debug(action);
for (const payload of action.payload) {
addSubscription(state, payload);
}
},

Expand Down Expand Up @@ -213,7 +236,9 @@ export const {
valuesChanged,
connectionClosed,
connectionChanged,
connectionsChanged,
subscribe,
subscribeBatch,
unsubscribe,
writePv,
deviceQueried,
Expand Down
121 changes: 121 additions & 0 deletions src/redux/pvSubscriptions.ts
Original file line number Diff line number Diff line change
@@ -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<string, Set<Listener>>();
// effective PV name -> the PV names widgets used for it, when they differ
const aliases = new Map<string, Set<string>>();

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<string>): void {
const toCall = new Set<Listener>();
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);
}
3 changes: 3 additions & 0 deletions src/redux/slices/fileCacheSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,9 @@ export const fileComparator = (
before: WidgetDescription,
after: WidgetDescription
): boolean => {
if (before === after) {
return true;
}
if (!before || !after) {
return false;
}
Expand Down
4 changes: 3 additions & 1 deletion src/redux/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof configureStore> | null = null;
Expand Down Expand Up @@ -64,7 +65,8 @@ const createStoreInstance = (config?: CsWebLibConfig) => {
)
)
)
);
)
.concat(pvNotifyMiddleware);
},
devTools: isDevMode
});
Expand Down
12 changes: 10 additions & 2 deletions src/redux/throttleMiddleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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"
);
});
});
Loading
Loading