Store refactor: make it easier to test stores (#9290)

* refactor: convert RoomViewStore from flux Store to standard EventEmitter

Parts of a series of experimental changes to improve the design of stores.

* Use a gen5 store for RoomViewStore for now due to lock handling

* Revert "Use a gen5 store for RoomViewStore for now due to lock handling"

This reverts commit 1076af071d997d87b8ae0b0dcddfd1ae428665af.

* Add untilEmission and tweak untilDispatch; use it in RoomViewStore

* Add more RVS tests; remove custom room ID listener code and use EventEmitter

* Better comments

* Null guard `dis` as tests mock out `defaultDispatcher`

* Additional tests
This commit is contained in:
kegsay
2022-09-20 15:32:39 +00:00
committed by GitHub
parent 1f1a18f914
commit 06c4ba32cd
11 changed files with 289 additions and 129 deletions
+45 -40
View File
@@ -17,7 +17,6 @@ limitations under the License.
*/
import React, { ReactNode } from "react";
import { Store } from 'flux/utils';
import { MatrixError } from "matrix-js-sdk/src/http-api";
import { logger } from "matrix-js-sdk/src/logger";
import { ViewRoom as ViewRoomEvent } from "@matrix-org/analytics-events/types/typescript/ViewRoom";
@@ -26,13 +25,13 @@ import { JoinRule } from "matrix-js-sdk/src/@types/partials";
import { Room } from "matrix-js-sdk/src/models/room";
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { Optional } from "matrix-events-sdk";
import EventEmitter from "events";
import dis from '../dispatcher/dispatcher';
import { defaultDispatcher, MatrixDispatcher } from '../dispatcher/dispatcher';
import { MatrixClientPeg } from '../MatrixClientPeg';
import Modal from '../Modal';
import { _t } from '../languageHandler';
import { getCachedRoomIDForAlias, storeRoomAliasInCache } from '../RoomAliasCache';
import { ActionPayload } from "../dispatcher/payloads";
import { Action } from "../dispatcher/actions";
import { retry } from "../utils/promise";
import { TimelineRenderingType } from "../contexts/RoomContext";
@@ -50,6 +49,7 @@ import { ActiveRoomChangedPayload } from "../dispatcher/payloads/ActiveRoomChang
import SettingsStore from "../settings/SettingsStore";
import { SlidingSyncManager } from "../SlidingSyncManager";
import { awaitRoomDownSync } from "../utils/RoomUpgrade";
import { UPDATE_EVENT } from "./AsyncStore";
const NUM_JOIN_RETRY = 5;
@@ -90,47 +90,34 @@ const INITIAL_STATE = {
type Listener = (isActive: boolean) => void;
/**
* A class for storing application state for RoomView. This is the RoomView's interface
* with a subset of the js-sdk.
* ```
* A class for storing application state for RoomView.
*/
export class RoomViewStore extends Store<ActionPayload> {
export class RoomViewStore extends EventEmitter {
// Important: This cannot be a dynamic getter (lazily-constructed instance) because
// otherwise we'll miss view_room dispatches during startup, breaking relaunches of
// the app. We need to eagerly create the instance.
public static readonly instance = new RoomViewStore();
public static readonly instance = new RoomViewStore(defaultDispatcher);
private state = INITIAL_STATE; // initialize state
// Keep these out of state to avoid causing excessive/recursive updates
private roomIdActivityListeners: Record<string, Listener[]> = {};
private dis: MatrixDispatcher;
private dispatchToken: string;
public constructor() {
super(dis);
public constructor(dis: MatrixDispatcher) {
super();
this.resetDispatcher(dis);
}
public addRoomListener(roomId: string, fn: Listener): void {
if (!this.roomIdActivityListeners[roomId]) this.roomIdActivityListeners[roomId] = [];
this.roomIdActivityListeners[roomId].push(fn);
this.on(roomId, fn);
}
public removeRoomListener(roomId: string, fn: Listener): void {
if (this.roomIdActivityListeners[roomId]) {
const i = this.roomIdActivityListeners[roomId].indexOf(fn);
if (i > -1) {
this.roomIdActivityListeners[roomId].splice(i, 1);
}
} else {
logger.warn("Unregistering unrecognised listener (roomId=" + roomId + ")");
}
this.off(roomId, fn);
}
private emitForRoom(roomId: string, isActive: boolean): void {
if (!this.roomIdActivityListeners[roomId]) return;
for (const fn of this.roomIdActivityListeners[roomId]) {
fn.call(null, isActive);
}
this.emit(roomId, isActive);
}
private setState(newState: Partial<typeof INITIAL_STATE>): void {
@@ -156,17 +143,17 @@ export class RoomViewStore extends Store<ActionPayload> {
// Fired so we can reduce dependency on event emitters to this store, which is relatively
// central to the application and can easily cause import cycles.
dis.dispatch<ActiveRoomChangedPayload>({
this.dis.dispatch<ActiveRoomChangedPayload>({
action: Action.ActiveRoomChanged,
oldRoomId: lastRoomId,
newRoomId: this.state.roomId,
});
}
this.__emitChange();
this.emit(UPDATE_EVENT);
}
protected __onDispatch(payload): void { // eslint-disable-line @typescript-eslint/naming-convention
private onDispatch(payload): void { // eslint-disable-line @typescript-eslint/naming-convention
switch (payload.action) {
// view_room:
// - room_alias: '#somealias:matrix.org'
@@ -243,7 +230,7 @@ export class RoomViewStore extends Store<ActionPayload> {
// both room and search timeline rendering types, search will get auto-closed by RoomView at this time.
if ([TimelineRenderingType.Room, TimelineRenderingType.Search].includes(payload.context)) {
if (payload.event && payload.event.getRoomId() !== this.state.roomId) {
dis.dispatch<ViewRoomPayload>({
this.dis.dispatch<ViewRoomPayload>({
action: Action.ViewRoom,
room_id: payload.event.getRoomId(),
replyingToEvent: payload.event,
@@ -283,9 +270,9 @@ export class RoomViewStore extends Store<ActionPayload> {
});
}
if (SettingsStore.getValue("feature_sliding_sync") && this.state.roomId !== payload.room_id) {
if (this.state.roomId) {
if (this.state.subscribingRoomId && this.state.subscribingRoomId !== payload.room_id) {
// unsubscribe from this room, but don't await it as we don't care when this gets done.
SlidingSyncManager.instance.setRoomVisible(this.state.roomId, false);
SlidingSyncManager.instance.setRoomVisible(this.state.subscribingRoomId, false);
}
this.setState({
subscribingRoomId: payload.room_id,
@@ -306,11 +293,11 @@ export class RoomViewStore extends Store<ActionPayload> {
// Whilst we were subscribing another room was viewed, so stop what we're doing and
// unsubscribe
if (this.state.subscribingRoomId !== payload.room_id) {
SlidingSyncManager.instance.setRoomVisible(this.state.roomId, false);
SlidingSyncManager.instance.setRoomVisible(payload.room_id, false);
return;
}
// Re-fire the payload: we won't re-process it because the prev room ID == payload room ID now
dis.dispatch({
this.dis.dispatch({
...payload,
});
return;
@@ -346,7 +333,7 @@ export class RoomViewStore extends Store<ActionPayload> {
this.setState(newState);
if (payload.auto_join) {
dis.dispatch<JoinRoomPayload>({
this.dis.dispatch<JoinRoomPayload>({
...payload,
action: Action.JoinRoom,
roomId: payload.room_id,
@@ -378,7 +365,7 @@ export class RoomViewStore extends Store<ActionPayload> {
roomId = result.room_id;
} catch (err) {
logger.error("RVS failed to get room id for alias: ", err);
dis.dispatch<ViewRoomErrorPayload>({
this.dis.dispatch<ViewRoomErrorPayload>({
action: Action.ViewRoomError,
room_id: null,
room_alias: payload.room_alias,
@@ -389,7 +376,7 @@ export class RoomViewStore extends Store<ActionPayload> {
}
// Re-fire the payload with the newly found room_id
dis.dispatch({
this.dis.dispatch({
...payload,
room_id: roomId,
});
@@ -427,13 +414,13 @@ export class RoomViewStore extends Store<ActionPayload> {
// We do *not* clear the 'joining' flag because the Room object and/or our 'joined' member event may not
// have come down the sync stream yet, and that's the point at which we'd consider the user joined to the
// room.
dis.dispatch<JoinRoomReadyPayload>({
this.dis.dispatch<JoinRoomReadyPayload>({
action: Action.JoinRoomReady,
roomId,
metricsTrigger: payload.metricsTrigger,
});
} catch (err) {
dis.dispatch({
this.dis.dispatch({
action: Action.JoinRoomError,
roomId,
err,
@@ -493,6 +480,24 @@ export class RoomViewStore extends Store<ActionPayload> {
this.state = Object.assign({}, INITIAL_STATE);
}
/**
* Reset which dispatcher should be used to listen for actions. The old dispatcher will be
* unregistered.
* @param dis The new dispatcher to use.
*/
public resetDispatcher(dis: MatrixDispatcher) {
if (this.dispatchToken) {
this.dis.unregister(this.dispatchToken);
}
this.dis = dis;
if (dis) {
// Some tests mock the dispatcher file resulting in an empty defaultDispatcher
// so rather than dying here, just ignore it. When we no longer mock files like this,
// we should remove the null check.
this.dispatchToken = this.dis.register(this.onDispatch.bind(this));
}
}
// The room ID of the room currently being viewed
public getRoomId(): Optional<string> {
return this.state.roomId;
+2 -1
View File
@@ -39,6 +39,7 @@ import { SpaceWatcher } from "./SpaceWatcher";
import { IRoomTimelineActionPayload } from "../../actions/MatrixActionCreators";
import { RoomListStore as Interface, RoomListStoreEvent } from "./Interface";
import { SlidingRoomListStoreClass } from "./SlidingRoomListStore";
import { UPDATE_EVENT } from "../AsyncStore";
interface IState {
// state is tracked in underlying classes
@@ -104,7 +105,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> implements
this.readyStore.useUnitTestClient(forcedClient);
}
RoomViewStore.instance.addListener(() => this.handleRVSUpdate({}));
RoomViewStore.instance.addListener(UPDATE_EVENT, () => this.handleRVSUpdate({}));
this.algorithm.on(LIST_UPDATED_EVENT, this.onAlgorithmListUpdated);
this.algorithm.on(FILTER_CHANGED, this.onAlgorithmFilterUpdated);
this.setupWatchers();
+2 -1
View File
@@ -30,6 +30,7 @@ import SpaceStore from "../spaces/SpaceStore";
import { MetaSpace, SpaceKey, UPDATE_SELECTED_SPACE } from "../spaces";
import { LISTS_LOADING_EVENT } from "./RoomListStore";
import { RoomViewStore } from "../RoomViewStore";
import { UPDATE_EVENT } from "../AsyncStore";
interface IState {
// state is tracked in underlying classes
@@ -313,7 +314,7 @@ export class SlidingRoomListStoreClass extends AsyncStoreWithClient<IState> impl
logger.info("SlidingRoomListStore.onReady");
// permanent listeners: never get destroyed. Could be an issue if we want to test this in isolation.
SlidingSyncManager.instance.slidingSync.on(SlidingSyncEvent.List, this.onSlidingSyncListUpdate.bind(this));
RoomViewStore.instance.addListener(this.onRoomViewStoreUpdated.bind(this));
RoomViewStore.instance.addListener(UPDATE_EVENT, this.onRoomViewStoreUpdated.bind(this));
SpaceStore.instance.on(UPDATE_SELECTED_SPACE, this.onSelectedSpaceUpdated.bind(this));
if (SpaceStore.instance.activeSpace) {
this.onSelectedSpaceUpdated(SpaceStore.instance.activeSpace, false);