Skip to content

Commit

Permalink
Throttle re-renders for rapidly-updating messages
Browse files Browse the repository at this point in the history
  • Loading branch information
trevor-signal committed Nov 1, 2023
1 parent 9206b99 commit 0da867a
Showing 1 changed file with 46 additions and 21 deletions.
67 changes: 46 additions & 21 deletions ts/services/MessageCache.ts
Expand Up @@ -2,6 +2,8 @@
// SPDX-License-Identifier: AGPL-3.0-only

import cloneDeep from 'lodash/cloneDeep';
import { throttle } from 'lodash';
import LRU from 'lru-cache';
import type { MessageAttributesType } from '../model-types.d';
import type { MessageModel } from '../models/messages';
import * as Errors from '../types/errors';
Expand All @@ -17,6 +19,7 @@ import { softAssert, strictAssert } from '../util/assert';
import { isStory } from '../messages/helpers';
import { getStoryDataFromMessageAttributes } from './storyLoader';

const MAX_THROTTLED_REDUX_UPDATERS = 200;
export class MessageCache {
private state = {
messages: new Map<string, MessageAttributesType>(),
Expand Down Expand Up @@ -198,36 +201,58 @@ export class MessageCache {

this.markModelStale(nextMessageAttributes);

if (window.reduxActions) {
if (isStory(nextMessageAttributes)) {
const storyData = getStoryDataFromMessageAttributes({
...nextMessageAttributes,
});
this.throttledUpdateRedux(nextMessageAttributes);

if (!storyData) {
return;
}
if (skipSaveToDatabase) {
return;
}
drop(
window.Signal.Data.saveMessage(messageAttributes, {
ourAci: window.textsecure.storage.user.getCheckedAci(),
})
);
}

window.reduxActions.stories.storyChanged(storyData);
private throttledReduxUpdaters = new LRU<string, typeof this.updateRedux>({
max: MAX_THROTTLED_REDUX_UPDATERS,
});

private throttledUpdateRedux(attributes: MessageAttributesType) {
let updater = this.throttledReduxUpdaters.get(attributes.id);
if (!updater) {
updater = throttle(this.updateRedux.bind(this), 200, {
leading: true,
trailing: true,
});
this.throttledReduxUpdaters.set(attributes.id, updater);
}

updater(attributes);
}

// We don't want messageChanged to run
private updateRedux(attributes: MessageAttributesType) {
if (!window.reduxActions) {
return;
}
if (isStory(attributes)) {
const storyData = getStoryDataFromMessageAttributes({
...attributes,
});

if (!storyData) {
return;
}

window.reduxActions.conversations.messageChanged(
messageId,
nextMessageAttributes.conversationId,
nextMessageAttributes
);
}
window.reduxActions.stories.storyChanged(storyData);

if (skipSaveToDatabase) {
// We don't want messageChanged to run
return;
}
drop(
window.Signal.Data.saveMessage(messageAttributes, {
ourAci: window.textsecure.storage.user.getCheckedAci(),
})

window.reduxActions.conversations.messageChanged(
attributes.id,
attributes.conversationId,
attributes
);
}

Expand Down

0 comments on commit 0da867a

Please sign in to comment.