Skip to content

Commit d0cddc5

Browse files
authored
Feed events to widgets as they are decrypted (even if out of order) (#28376)
* Refactor feeding of events to widgets This is a pure refactor with (hopefully) no behavior changes. * Feed events to widgets as they are decrypted (even if out of order) The code that feeds events to widgets tries to enforce that only events from the end of the timeline will be passed through. This is to prevent old, irrelevant events from being passed to widgets as the timeline is back-filled. However, since encrypted events need to be decrypted asynchronously, it's not possible to feed them to a widget in a strictly linear order without introducing some kind of blocking or unreliable delivery. This code has been dropping events when they're decrypted out of order, which we consider to be an undesirable behavior. The solution provided here is that, to reflect the asynchronous nature of decryption, encrypted events that arrive at the end of the timeline will be fed to a widget whenever they finish decrypting, even if this means feeding them out of order. For now we're not aware of any widgets that care about knowing the exact order of events in the timeline, but if such a need reveals itself later, we can explore adding ordering information to this part of the widget API. * Add braces to if
1 parent 9a6be72 commit d0cddc5

File tree

2 files changed

+143
-64
lines changed

2 files changed

+143
-64
lines changed

src/stores/widgets/StopGapWidget.ts

Lines changed: 95 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,10 @@ export class StopGapWidget extends EventEmitter {
154154
private kind: WidgetKind;
155155
private readonly virtual: boolean;
156156
private readUpToMap: { [roomId: string]: string } = {}; // room ID to event ID
157-
private stickyPromise?: () => Promise<void>; // This promise will be called and needs to resolve before the widget will actually become sticky.
157+
// This promise will be called and needs to resolve before the widget will actually become sticky.
158+
private stickyPromise?: () => Promise<void>;
159+
// Holds events that should be fed to the widget once they finish decrypting
160+
private readonly eventsToFeed = new WeakSet<MatrixEvent>();
158161

159162
public constructor(private appTileProps: IAppTileProps) {
160163
super();
@@ -465,12 +468,10 @@ export class StopGapWidget extends EventEmitter {
465468

466469
private onEvent = (ev: MatrixEvent): void => {
467470
this.client.decryptEventIfNeeded(ev);
468-
if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) return;
469471
this.feedEvent(ev);
470472
};
471473

472474
private onEventDecrypted = (ev: MatrixEvent): void => {
473-
if (ev.isDecryptionFailure()) return;
474475
this.feedEvent(ev);
475476
};
476477

@@ -480,72 +481,103 @@ export class StopGapWidget extends EventEmitter {
480481
await this.messaging?.feedToDevice(ev.getEffectiveEvent() as IRoomEvent, ev.isEncrypted());
481482
};
482483

483-
private feedEvent(ev: MatrixEvent): void {
484-
if (!this.messaging) return;
485-
486-
// Check to see if this event would be before or after our "read up to" marker. If it's
487-
// before, or we can't decide, then we assume the widget will have already seen the event.
488-
// If the event is after, or we don't have a marker for the room, then we'll send it through.
489-
//
490-
// This approach of "read up to" prevents widgets receiving decryption spam from startup or
491-
// receiving out-of-order events from backfill and such.
492-
//
493-
// Skip marker timeline check for events with relations to unknown parent because these
494-
// events are not added to the timeline here and will be ignored otherwise:
495-
// https://github.com/matrix-org/matrix-js-sdk/blob/d3dfcd924201d71b434af3d77343b5229b6ed75e/src/models/room.ts#L2207-L2213
496-
let isRelationToUnknown: boolean | undefined = undefined;
497-
const upToEventId = this.readUpToMap[ev.getRoomId()!];
498-
if (upToEventId) {
499-
// Small optimization for exact match (prevent search)
500-
if (upToEventId === ev.getId()) {
501-
return;
502-
}
484+
/**
485+
* Determines whether the event has a relation to an unknown parent.
486+
*/
487+
private relatesToUnknown(ev: MatrixEvent): boolean {
488+
// Replies to unknown events don't count
489+
if (!ev.relationEventId || ev.replyEventId) return false;
490+
const room = this.client.getRoom(ev.getRoomId());
491+
return room === null || !room.findEventById(ev.relationEventId);
492+
}
503493

504-
// should be true to forward the event to the widget
505-
let shouldForward = false;
506-
507-
const room = this.client.getRoom(ev.getRoomId()!);
508-
if (!room) return;
509-
// Timelines are most recent last, so reverse the order and limit ourselves to 100 events
510-
// to avoid overusing the CPU.
511-
const timeline = room.getLiveTimeline();
512-
const events = arrayFastClone(timeline.getEvents()).reverse().slice(0, 100);
513-
514-
for (const timelineEvent of events) {
515-
if (timelineEvent.getId() === upToEventId) {
516-
break;
517-
} else if (timelineEvent.getId() === ev.getId()) {
518-
shouldForward = true;
519-
break;
520-
}
521-
}
494+
/**
495+
* Determines whether the event comes from a room that we've been invited to
496+
* (in which case we likely don't have the full timeline).
497+
*/
498+
private isFromInvite(ev: MatrixEvent): boolean {
499+
const room = this.client.getRoom(ev.getRoomId());
500+
return room?.getMyMembership() === KnownMembership.Invite;
501+
}
522502

523-
if (!shouldForward) {
524-
// checks that the event has a relation to unknown event
525-
isRelationToUnknown =
526-
!ev.replyEventId && !!ev.relationEventId && !room.findEventById(ev.relationEventId);
527-
if (!isRelationToUnknown) {
528-
// Ignore the event: it is before our interest.
529-
return;
530-
}
531-
}
503+
/**
504+
* Advances the "read up to" marker for a room to a certain event. No-ops if
505+
* the event is before the marker.
506+
* @returns Whether the "read up to" marker was advanced.
507+
*/
508+
private advanceReadUpToMarker(ev: MatrixEvent): boolean {
509+
const evId = ev.getId();
510+
if (evId === undefined) return false;
511+
const roomId = ev.getRoomId();
512+
if (roomId === undefined) return false;
513+
const room = this.client.getRoom(roomId);
514+
if (room === null) return false;
515+
516+
const upToEventId = this.readUpToMap[ev.getRoomId()!];
517+
if (!upToEventId) {
518+
// There's no marker yet; start it at this event
519+
this.readUpToMap[roomId] = evId;
520+
return true;
532521
}
533522

534-
// Skip marker assignment if membership is 'invite', otherwise 'm.room.member' from
535-
// invitation room will assign it and new state events will be not forwarded to the widget
536-
// because of empty timeline for invitation room and assigned marker.
537-
const evRoomId = ev.getRoomId();
538-
const evId = ev.getId();
539-
if (evRoomId && evId) {
540-
const room = this.client.getRoom(evRoomId);
541-
if (room && room.getMyMembership() === KnownMembership.Join && !isRelationToUnknown) {
542-
this.readUpToMap[evRoomId] = evId;
523+
// Small optimization for exact match (skip the search)
524+
if (upToEventId === evId) return false;
525+
526+
// Timelines are most recent last, so reverse the order and limit ourselves to 100 events
527+
// to avoid overusing the CPU.
528+
const timeline = room.getLiveTimeline();
529+
const events = arrayFastClone(timeline.getEvents()).reverse().slice(0, 100);
530+
531+
for (const timelineEvent of events) {
532+
if (timelineEvent.getId() === upToEventId) {
533+
// The event must be somewhere before the "read up to" marker
534+
return false;
535+
} else if (timelineEvent.getId() === ev.getId()) {
536+
// The event is after the marker; advance it
537+
this.readUpToMap[roomId] = evId;
538+
return true;
543539
}
544540
}
545541

546-
const raw = ev.getEffectiveEvent();
547-
this.messaging.feedEvent(raw as IRoomEvent, this.eventListenerRoomId!).catch((e) => {
548-
logger.error("Error sending event to widget: ", e);
549-
});
542+
// We can't say for sure whether the widget has seen the event; let's
543+
// just assume that it has
544+
return false;
545+
}
546+
547+
private feedEvent(ev: MatrixEvent): void {
548+
if (this.messaging === null) return;
549+
if (
550+
// If we had decided earlier to feed this event to the widget, but
551+
// it just wasn't ready, give it another try
552+
this.eventsToFeed.delete(ev) ||
553+
// Skip marker timeline check for events with relations to unknown parent because these
554+
// events are not added to the timeline here and will be ignored otherwise:
555+
// https://github.com/matrix-org/matrix-js-sdk/blob/d3dfcd924201d71b434af3d77343b5229b6ed75e/src/models/room.ts#L2207-L2213
556+
this.relatesToUnknown(ev) ||
557+
// Skip marker timeline check for rooms where membership is
558+
// 'invite', otherwise the membership event from the invitation room
559+
// will advance the marker and new state events will not be
560+
// forwarded to the widget.
561+
this.isFromInvite(ev) ||
562+
// Check whether this event would be before or after our "read up to" marker. If it's
563+
// before, or we can't decide, then we assume the widget will have already seen the event.
564+
// If the event is after, or we don't have a marker for the room, then the marker will advance and we'll
565+
// send it through.
566+
// This approach of "read up to" prevents widgets receiving decryption spam from startup or
567+
// receiving ancient events from backfill and such.
568+
this.advanceReadUpToMarker(ev)
569+
) {
570+
// If the event is still being decrypted, remember that we want to
571+
// feed it to the widget (even if not strictly in the order given by
572+
// the timeline) and get back to it later
573+
if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) {
574+
this.eventsToFeed.add(ev);
575+
} else {
576+
const raw = ev.getEffectiveEvent();
577+
this.messaging.feedEvent(raw as IRoomEvent, this.eventListenerRoomId!).catch((e) => {
578+
logger.error("Error sending event to widget: ", e);
579+
});
580+
}
581+
}
550582
}
551583
}

test/unit-tests/stores/widgets/StopGapWidget-test.ts

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,14 @@ Please see LICENSE files in the repository root for full details.
88

99
import { mocked, MockedObject } from "jest-mock";
1010
import { last } from "lodash";
11-
import { MatrixEvent, MatrixClient, ClientEvent, EventTimeline } from "matrix-js-sdk/src/matrix";
11+
import {
12+
MatrixEvent,
13+
MatrixClient,
14+
ClientEvent,
15+
EventTimeline,
16+
EventType,
17+
MatrixEventEvent,
18+
} from "matrix-js-sdk/src/matrix";
1219
import { ClientWidgetApi, WidgetApiFromWidgetAction } from "matrix-widget-api";
1320
import { waitFor } from "jest-matrix-react";
1421

@@ -134,6 +141,46 @@ describe("StopGapWidget", () => {
134141
expect(messaging.feedEvent).toHaveBeenLastCalledWith(event2.getEffectiveEvent(), "!1:example.org");
135142
});
136143

144+
it("feeds decrypted events asynchronously", async () => {
145+
const event1Encrypted = new MatrixEvent({
146+
event_id: event1.getId(),
147+
type: EventType.RoomMessageEncrypted,
148+
sender: event1.sender?.userId,
149+
room_id: event1.getRoomId(),
150+
content: {},
151+
});
152+
const decryptingSpy1 = jest.spyOn(event1Encrypted, "isBeingDecrypted").mockReturnValue(true);
153+
client.emit(ClientEvent.Event, event1Encrypted);
154+
const event2Encrypted = new MatrixEvent({
155+
event_id: event2.getId(),
156+
type: EventType.RoomMessageEncrypted,
157+
sender: event2.sender?.userId,
158+
room_id: event2.getRoomId(),
159+
content: {},
160+
});
161+
const decryptingSpy2 = jest.spyOn(event2Encrypted, "isBeingDecrypted").mockReturnValue(true);
162+
client.emit(ClientEvent.Event, event2Encrypted);
163+
expect(messaging.feedEvent).not.toHaveBeenCalled();
164+
165+
// "Decrypt" the events, but in reverse order; first event 2…
166+
event2Encrypted.event.type = event2.getType();
167+
event2Encrypted.event.content = event2.getContent();
168+
decryptingSpy2.mockReturnValue(false);
169+
client.emit(MatrixEventEvent.Decrypted, event2Encrypted);
170+
expect(messaging.feedEvent).toHaveBeenCalledTimes(1);
171+
expect(messaging.feedEvent).toHaveBeenLastCalledWith(event2Encrypted.getEffectiveEvent(), "!1:example.org");
172+
// …then event 1
173+
event1Encrypted.event.type = event1.getType();
174+
event1Encrypted.event.content = event1.getContent();
175+
decryptingSpy1.mockReturnValue(false);
176+
client.emit(MatrixEventEvent.Decrypted, event1Encrypted);
177+
// The events should be fed in that same order so that event 2
178+
// doesn't have to be blocked on the decryption of event 1 (or
179+
// worse, dropped)
180+
expect(messaging.feedEvent).toHaveBeenCalledTimes(2);
181+
expect(messaging.feedEvent).toHaveBeenLastCalledWith(event1Encrypted.getEffectiveEvent(), "!1:example.org");
182+
});
183+
137184
it("should not feed incoming event if not in timeline", () => {
138185
const event = mkEvent({
139186
event: true,

0 commit comments

Comments
 (0)