From 0efd67a88b3718e69be408935f5e875ba561d65a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 25 Jan 2024 00:21:04 -0500 Subject: [PATCH] Simplify websockets, remove document- channels and dynamic subscriptions --- app/components/InputSelect.tsx | 4 + app/components/WebsocketProvider.tsx | 41 ++++------ app/scenes/Document/components/DataLoader.tsx | 19 ----- app/types.ts | 2 + .../queues/processors/WebsocketsProcessor.ts | 78 +++++++++++-------- server/routes/api/documents/documents.ts | 6 -- server/services/websockets.ts | 20 +---- 7 files changed, 68 insertions(+), 102 deletions(-) diff --git a/app/components/InputSelect.tsx b/app/components/InputSelect.tsx index 82d976adbe..cbdf458779 100644 --- a/app/components/InputSelect.tsx +++ b/app/components/InputSelect.tsx @@ -106,6 +106,10 @@ const InputSelect = (props: Props) => { (option) => option.value === select.selectedValue ); + React.useEffect(() => { + select.setSelectedValue(value); + }, [value]); + React.useEffect(() => { if (previousValue.current === select.selectedValue) { return; diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx index 0e14f962fd..da58572264 100644 --- a/app/components/WebsocketProvider.tsx +++ b/app/components/WebsocketProvider.tsx @@ -1,13 +1,11 @@ import invariant from "invariant"; import find from "lodash/find"; -import isUndefined from "lodash/isUndefined"; import { action, observable } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; import { withTranslation, WithTranslation } from "react-i18next"; import { io, Socket } from "socket.io-client"; import { toast } from "sonner"; -import { Pagination } from "@shared/constants"; import { FileOperationState, FileOperationType } from "@shared/types"; import RootStore from "~/stores/RootStore"; import Collection from "~/models/Collection"; @@ -27,7 +25,6 @@ import { PartialWithId, WebsocketCollectionUpdateIndexEvent, WebsocketCollectionUserEvent, - WebsocketDocumentUserEvent, WebsocketEntitiesEvent, WebsocketEntityDeletedEvent, } from "~/types"; @@ -257,31 +254,24 @@ class WebsocketProvider extends React.Component { // received when a user is given access to a document this.socket.on( "documents.add_user", - async (event: WebsocketDocumentUserEvent) => { - // if the user is us then we go ahead and load the memberships from API. - if (auth.user && event.userId === auth.user.id) { - await userMemberships.fetchPage({ - limit: Pagination.defaultLimit, - }); - } + (event: PartialWithId) => { + userMemberships.add(event); } ); this.socket.on( "documents.remove_user", - async (event: WebsocketDocumentUserEvent) => { - if (auth.user && event.userId === auth.user.id) { - await userMemberships.fetchPage({ - limit: Pagination.defaultLimit, - }); - + (event: PartialWithId) => { + if (event.documentId && event.userId === auth.user?.id) { documents.remove(event.documentId); } - userMemberships.revoke({ - userId: event.userId, - documentId: event.documentId, - }); + if (event.userId) { + userMemberships.revoke({ + userId: event.userId, + documentId: event.documentId, + }); + } } ); @@ -407,7 +397,7 @@ class WebsocketProvider extends React.Component { this.socket.on( "collections.add_user", async (event: WebsocketCollectionUserEvent) => { - if (auth.user && event.userId === auth.user.id) { + if (event.userId === auth.user?.id) { await collections.fetch(event.collectionId, { force: true, }); @@ -426,7 +416,7 @@ class WebsocketProvider extends React.Component { this.socket.on( "collections.remove_user", async (event: WebsocketCollectionUserEvent) => { - if (auth.user && event.userId === auth.user.id) { + if (event.userId === auth.user?.id) { // check if we still have access to the collection try { await collections.fetch(event.collectionId, { @@ -506,7 +496,7 @@ class WebsocketProvider extends React.Component { ); this.socket.on("users.demote", async (event: PartialWithId) => { - if (auth.user && event.id === auth.user.id) { + if (event.id === auth.user?.id) { documents.all.forEach((document) => policies.remove(document.id)); await collections.fetchAll(); } @@ -515,10 +505,7 @@ class WebsocketProvider extends React.Component { this.socket.on( "userMemberships.update", async (event: PartialWithId) => { - const userMembership = userMemberships.get(event.id); - if (userMembership && !isUndefined(event.index)) { - userMembership.index = event.index; - } + userMemberships.add(event); } ); diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index 6ba238acff..348485576f 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -8,7 +8,6 @@ import Revision from "~/models/Revision"; import Error402 from "~/scenes/Error402"; import Error404 from "~/scenes/Error404"; import ErrorOffline from "~/scenes/ErrorOffline"; -import { WebsocketContext } from "~/components/WebsocketProvider"; import useCurrentTeam from "~/hooks/useCurrentTeam"; import useCurrentUser from "~/hooks/useCurrentUser"; import usePolicy from "~/hooks/usePolicy"; @@ -52,22 +51,6 @@ type Props = RouteComponentProps & { children: Children; }; -const useDocumentWebsocket = (documentId: string | undefined) => { - const socket = React.useContext(WebsocketContext); - - React.useEffect(() => { - if (socket && documentId) { - socket.emit("join", { documentId }); - - return () => { - socket.emit("leave", { documentId }); - }; - } - - return undefined; - }, [socket, documentId]); -}; - function DataLoader({ match, children }: Props) { const { ui, views, shares, comments, documents, revisions, subscriptions } = useStores(); @@ -217,8 +200,6 @@ function DataLoader({ match, children }: Props) { } }, [can.read, can.update, document, isEditRoute, comments, team, shares, ui]); - useDocumentWebsocket(document?.id); - if (error) { return error instanceof OfflineError ? ( diff --git a/app/types.ts b/app/types.ts index 9918a7bed7..c032194b2c 100644 --- a/app/types.ts +++ b/app/types.ts @@ -6,6 +6,7 @@ import { CollectionPermission, DocumentPermission, } from "@shared/types"; +import { UserPermission } from "@server/models"; import RootStore from "~/stores/RootStore"; import Document from "./models/Document"; import FileOperation from "./models/FileOperation"; @@ -201,6 +202,7 @@ export type WebsocketEvent = | PartialWithId | PartialWithId | PartialWithId + | PartialWithId | WebsocketCollectionUserEvent | WebsocketCollectionUpdateIndexEvent | WebsocketEntityDeletedEvent diff --git a/server/queues/processors/WebsocketsProcessor.ts b/server/queues/processors/WebsocketsProcessor.ts index 227487e7b5..35f7c25322 100644 --- a/server/queues/processors/WebsocketsProcessor.ts +++ b/server/queues/processors/WebsocketsProcessor.ts @@ -14,6 +14,7 @@ import { Team, Subscription, Notification, + UserPermission, } from "@server/models"; import { presentComment, @@ -25,6 +26,7 @@ import { presentStar, presentSubscription, presentTeam, + presentMembership, } from "@server/presenters"; import presentNotification from "@server/presenters/notification"; import { Event } from "../../types"; @@ -43,7 +45,7 @@ export default class WebsocketsProcessor { return; } - const channels = this.getDocumentEventChannels(event, document); + const channels = await this.getDocumentEventChannels(event, document); return socketio.to(channels).emit("entities", { event: event.name, documentIds: [ @@ -78,7 +80,7 @@ export default class WebsocketsProcessor { return; } const data = await presentDocument(document); - const channels = this.getDocumentEventChannels(event, document); + const channels = await this.getDocumentEventChannels(event, document); return socketio.to(channels).emit(event.name, data); } @@ -88,7 +90,7 @@ export default class WebsocketsProcessor { return; } - const channels = this.getDocumentEventChannels(event, document); + const channels = await this.getDocumentEventChannels(event, document); return socketio.to(channels).emit("entities", { event: event.name, documentIds: [ @@ -137,37 +139,32 @@ export default class WebsocketsProcessor { } case "documents.add_user": { - const channels = [ - `user-${event.userId}`, - `document-${event.documentId}`, - ]; + const [document, membership] = await Promise.all([ + Document.findByPk(event.documentId), + UserPermission.findByPk(event.modelId), + ]); + if (!document || !membership) { + return; + } - // the user being added isn't yet in the websocket channel for the document - // so they need to be notified separately - socketio.to(channels).emit(event.name, { - event: event.name, - userId: event.userId, - documentId: event.documentId, - }); - // tell any user clients to connect to the websocket channel for the document - return socketio.to(`user-${event.userId}`).emit("join", { - event: event.name, - documentId: event.documentId, - }); + const channels = await this.getDocumentEventChannels(event, document); + socketio.to(channels).emit(event.name, presentMembership(membership)); + return; } case "documents.remove_user": { - // let everyone with access to the document know a user was removed - socketio.to(`document-${event.documentId}`).emit(event.name, { - event: event.name, + const document = await Document.findByPk(event.documentId); + if (!document) { + return; + } + + const channels = await this.getDocumentEventChannels(event, document); + socketio.to([...channels, `user-${event.userId}`]).emit(event.name, { + id: event.modelId, userId: event.userId, documentId: event.documentId, }); - // tell any user clients to disconnect from the websocket channel for the document - return socketio.to(`user-${event.userId}`).emit("leave", { - event: event.name, - documentId: event.documentId, - }); + return; } case "collections.create": { @@ -416,7 +413,10 @@ export default class WebsocketsProcessor { return; } - const channels = this.getDocumentEventChannels(event, comment.document); + const channels = await this.getDocumentEventChannels( + event, + comment.document + ); return socketio.to(channels).emit(event.name, presentComment(comment)); } @@ -434,7 +434,10 @@ export default class WebsocketsProcessor { return; } - const channels = this.getDocumentEventChannels(event, comment.document); + const channels = await this.getDocumentEventChannels( + event, + comment.document + ); return socketio.to(channels).emit(event.name, { modelId: event.modelId, }); @@ -681,8 +684,11 @@ export default class WebsocketsProcessor { } } - private getDocumentEventChannels(event: Event, document: Document): string[] { - const channels = [`document-${document.id}`]; + private async getDocumentEventChannels( + event: Event, + document: Document + ): Promise { + const channels = []; if (event.actorId) { channels.push(`user-${event.actorId}`); @@ -692,6 +698,16 @@ export default class WebsocketsProcessor { channels.push(`collection-${document.collectionId}`); } + const memberships = await UserPermission.findAll({ + where: { + documentId: document.id, + }, + }); + + for (const membership of memberships) { + channels.push(`user-${membership.userId}`); + } + return channels; } } diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index a39029c9cc..844cae8614 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -1552,9 +1552,6 @@ router.post( documentId: document.id, teamId: document.teamId, actorId: actor.id, - data: { - name: user.name, - }, ip: ctx.request.ip, }, { @@ -1618,9 +1615,6 @@ router.post( documentId: document.id, teamId: document.teamId, actorId: actor.id, - data: { - name: user.name, - }, ip: ctx.request.ip, }, { transaction } diff --git a/server/services/websockets.ts b/server/services/websockets.ts index a673f87836..dbbc8f6d17 100644 --- a/server/services/websockets.ts +++ b/server/services/websockets.ts @@ -9,7 +9,7 @@ import Logger from "@server/logging/Logger"; import Metrics from "@server/logging/Metrics"; import * as Tracing from "@server/logging/tracer"; import { traceFunction } from "@server/logging/tracing"; -import { Collection, Document, User } from "@server/models"; +import { Collection, User } from "@server/models"; import { can } from "@server/policies"; import Redis from "@server/storage/redis"; import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; @@ -184,19 +184,6 @@ async function authenticated(io: IO.Server, socket: SocketWithAuth) { Metrics.increment("websockets.collections.join"); } } - - // user is joining a document channel, because their permissions have - // changed, granting them access. - if (event.documentId) { - const document = await Document.findByPk(event.documentId, { - userId: user.id, - }); - - if (can(user, "read", document)) { - await socket.join(`document-${event.documentId}`); - Metrics.increment("websockets.documents.join"); - } - } }); // allow the client to request to leave rooms @@ -205,11 +192,6 @@ async function authenticated(io: IO.Server, socket: SocketWithAuth) { await socket.leave(`collection-${event.collectionId}`); Metrics.increment("websockets.collections.leave"); } - - if (event.documentId) { - await socket.leave(`document-${event.documentId}`); - Metrics.increment("websockets.documents.leave"); - } }); // join all of the rooms at once