Skip to content

chore: Internally operate Minimongo collections over Zustand stores (as transition for stores-only) #35470

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Jun 4, 2025
Merged
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
2 changes: 1 addition & 1 deletion apps/meteor/app/authorization/client/hasPermission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const hasIsUserInRole = (
const createPermissionValidator =
(quantifier: (predicate: (permissionId: IPermission['_id']) => boolean) => boolean) =>
(permissionIds: IPermission['_id'][], scope: string | undefined, userId: IUser['_id'], scopedRoles?: IPermission['_id'][]): boolean => {
const user = Models.Users.findOneById(userId, { fields: { roles: 1 } });
const user = Models.Users.findOne({ _id: userId }, { fields: { roles: 1 } });

const checkEachPermission = quantifier.bind(permissionIds);

Expand Down
22 changes: 18 additions & 4 deletions apps/meteor/app/autotranslate/client/lib/autotranslate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,13 +146,27 @@ export const createAutoTranslateMessageStreamHandler = (): ((message: ITranslate
(!message.translations ||
(!hasTranslationLanguageInMessage(message, language) && !hasTranslationLanguageInAttachments(message.attachments, language)))
) {
// || (message.attachments && !_.find(message.attachments, attachment => { return attachment.translations && attachment.translations[language]; }))
Messages.update({ _id: message._id }, { $set: { autoTranslateFetching: true } });
Messages.store.update(
(record) => record._id === message._id,
(record) => ({
...record,
autoTranslateFetching: true,
}),
);
} else if (AutoTranslate.messageIdsToWait[message._id] !== undefined && subscription && subscription.autoTranslate !== true) {
Messages.update({ _id: message._id }, { $set: { autoTranslateShowInverse: true }, $unset: { autoTranslateFetching: true } });
Messages.store.update(
(record) => record._id === message._id,
({ autoTranslateFetching: _, ...record }) => ({
...record,
autoTranslateShowInverse: true,
}),
);
delete AutoTranslate.messageIdsToWait[message._id];
} else if (message.autoTranslateFetching === true) {
Messages.update({ _id: message._id }, { $unset: { autoTranslateFetching: true } });
Messages.store.update(
(record) => record._id === message._id,
({ autoTranslateFetching: _, ...record }) => record,
);
}
}
};
Expand Down
7 changes: 4 additions & 3 deletions apps/meteor/app/e2e/client/rocketchat.e2e.room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,10 @@ export class E2ERoom extends Emitter {
}

async decryptPendingMessages() {
return Messages.find({ rid: this.roomId, t: 'e2e', e2e: 'pending' }).forEach(async ({ _id, ...msg }) => {
Messages.update({ _id }, await this.decryptMessage({ _id, ...msg }));
});
await Messages.store.updateAsync(
(record) => record.rid === this.roomId && record.t === 'e2e' && record.e2e === 'pending',
(record) => this.decryptMessage(record),
);
}

// Initiates E2E Encryption
Expand Down
7 changes: 4 additions & 3 deletions apps/meteor/app/e2e/client/rocketchat.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -716,9 +716,10 @@ class E2E extends Emitter {
}

async decryptPendingMessages(): Promise<void> {
return Messages.find({ t: 'e2e', e2e: 'pending' }).forEach(async ({ _id, ...msg }: IMessage) => {
Messages.update({ _id }, await this.decryptMessage(msg as IE2EEMessage));
});
await Messages.store.updateAsync(
(record) => record.t === 'e2e' && record.e2e === 'pending',
(record) => this.decryptMessage(record),
);
}

async decryptSubscription(subscriptionId: ISubscription['_id']): Promise<void> {
Expand Down
5 changes: 3 additions & 2 deletions apps/meteor/app/livechat/client/lib/stream/queueManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { ILivechatDepartment, ILivechatInquiryRecord, IOmnichannelAgent, Se

import { useLivechatInquiryStore } from '../../../../../client/hooks/useLivechatInquiryStore';
import { queryClient } from '../../../../../client/lib/queryClient';
import { roomsQueryKeys } from '../../../../../client/lib/queryKeys';
import { callWithErrorHandling } from '../../../../../client/lib/utils/callWithErrorHandling';
import { mapMessageFromApi } from '../../../../../client/lib/utils/mapMessageFromApi';
import { settings } from '../../../../settings/client';
Expand Down Expand Up @@ -45,8 +46,8 @@ const processInquiryEvent = async (args: unknown): Promise<void> => {

const invalidateRoomQueries = async (rid: string) => {
await queryClient.invalidateQueries({ queryKey: ['rooms', { reference: rid, type: 'l' }] });
queryClient.removeQueries({ queryKey: ['rooms', rid] });
queryClient.removeQueries({ queryKey: ['/v1/rooms.info', rid] });
queryClient.removeQueries({ queryKey: roomsQueryKeys.room(rid) });
queryClient.removeQueries({ queryKey: roomsQueryKeys.info(rid) });
};

const removeInquiry = async (inquiry: ILivechatInquiryRecord) => {
Expand Down
119 changes: 50 additions & 69 deletions apps/meteor/app/models/client/models/CachedChatRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,75 +25,56 @@ class CachedChatRoom extends PrivateCachedCollection<IRoom> {
}

private mergeWithSubscription(room: IRoom): IRoom {
const sub = CachedChatSubscription.collection.findOne({ rid: room._id });
if (!sub) {
return room;
}

CachedChatSubscription.collection.update(
{
rid: room._id,
},
{
$set: {
encrypted: room.encrypted,
description: room.description,
cl: room.cl,
topic: room.topic,
announcement: room.announcement,
broadcast: room.broadcast,
archived: room.archived,
avatarETag: room.avatarETag,
retention: (room as IRoomWithRetentionPolicy | undefined)?.retention,
uids: room.uids,
usernames: room.usernames,
usersCount: room.usersCount,
lastMessage: room.lastMessage,
teamId: room.teamId,
teamMain: room.teamMain,
v: (room as IOmnichannelRoom | undefined)?.v,
transcriptRequest: (room as IOmnichannelRoom | undefined)?.transcriptRequest,
servedBy: (room as IOmnichannelRoom | undefined)?.servedBy,
onHold: (room as IOmnichannelRoom | undefined)?.onHold,
tags: (room as IOmnichannelRoom | undefined)?.tags,
closedAt: (room as IOmnichannelRoom | undefined)?.closedAt,
metrics: (room as IOmnichannelRoom | undefined)?.metrics,
muted: room.muted,
waitingResponse: (room as IOmnichannelRoom | undefined)?.waitingResponse,
responseBy: (room as IOmnichannelRoom | undefined)?.responseBy,
priorityId: (room as IOmnichannelRoom | undefined)?.priorityId,
priorityWeight: (room as IOmnichannelRoom | undefined)?.priorityWeight || LivechatPriorityWeight.NOT_SPECIFIED,
estimatedWaitingTimeQueue:
(room as IOmnichannelRoom | undefined)?.estimatedWaitingTimeQueue || DEFAULT_SLA_CONFIG.ESTIMATED_WAITING_TIME_QUEUE,
slaId: (room as IOmnichannelRoom | undefined)?.slaId,
livechatData: (room as IOmnichannelRoom | undefined)?.livechatData,
departmentId: (room as IOmnichannelRoom | undefined)?.departmentId,
ts: room.ts,
source: (room as IOmnichannelRoom | undefined)?.source,
queuedAt: (room as IOmnichannelRoom | undefined)?.queuedAt,
federated: room.federated,
...(() => {
const name = room.name || sub.name;
const fname = room.fname || sub.fname || name;
return {
lowerCaseName: String(!room.prid ? name : fname).toLowerCase(),
lowerCaseFName: String(fname).toLowerCase(),
};
})(),
},
},
);

CachedChatSubscription.collection.update(
{
rid: room._id,
lm: { $lt: room.lm },
},
{
$set: {
lm: room.lm,
},
},
CachedChatSubscription.collection.store.update(
(record) => record.rid === room._id,
(sub) => ({
...sub,
encrypted: room.encrypted,
description: room.description,
cl: room.cl,
topic: room.topic,
announcement: room.announcement,
broadcast: room.broadcast,
archived: room.archived,
avatarETag: room.avatarETag,
retention: (room as IRoomWithRetentionPolicy | undefined)?.retention,
uids: room.uids,
usernames: room.usernames,
usersCount: room.usersCount,
lastMessage: room.lastMessage,
teamId: room.teamId,
teamMain: room.teamMain,
v: (room as IOmnichannelRoom | undefined)?.v,
transcriptRequest: (room as IOmnichannelRoom | undefined)?.transcriptRequest,
servedBy: (room as IOmnichannelRoom | undefined)?.servedBy,
onHold: (room as IOmnichannelRoom | undefined)?.onHold,
tags: (room as IOmnichannelRoom | undefined)?.tags,
closedAt: (room as IOmnichannelRoom | undefined)?.closedAt,
metrics: (room as IOmnichannelRoom | undefined)?.metrics,
muted: room.muted,
waitingResponse: (room as IOmnichannelRoom | undefined)?.waitingResponse,
responseBy: (room as IOmnichannelRoom | undefined)?.responseBy,
priorityId: (room as IOmnichannelRoom | undefined)?.priorityId,
priorityWeight: (room as IOmnichannelRoom | undefined)?.priorityWeight || LivechatPriorityWeight.NOT_SPECIFIED,
estimatedWaitingTimeQueue:
(room as IOmnichannelRoom | undefined)?.estimatedWaitingTimeQueue || DEFAULT_SLA_CONFIG.ESTIMATED_WAITING_TIME_QUEUE,
slaId: (room as IOmnichannelRoom | undefined)?.slaId,
livechatData: (room as IOmnichannelRoom | undefined)?.livechatData,
departmentId: (room as IOmnichannelRoom | undefined)?.departmentId,
ts: room.ts ?? sub.ts,
source: (room as IOmnichannelRoom | undefined)?.source,
queuedAt: (room as IOmnichannelRoom | undefined)?.queuedAt,
federated: room.federated,
...(() => {
const name = room.name || sub.name;
const fname = room.fname || sub.fname || name;
return {
lowerCaseName: String(!room.prid ? name : fname).toLowerCase(),
lowerCaseFName: String(fname).toLowerCase(),
};
})(),
lm: (sub.lm?.getTime() ?? -1) < (room.lm?.getTime() ?? -1) ? room.lm : sub.lm,
}),
);

return room;
Expand Down
43 changes: 1 addition & 42 deletions apps/meteor/app/models/client/models/CachedChatSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,48 +33,7 @@ class CachedChatSubscription extends PrivateCachedCollection<SubscriptionWithRoo
}

private mergeWithRoom(subscription: ISubscription): SubscriptionWithRoom {
const options = {
fields: {
lm: 1,
lastMessage: 1,
uids: 1,
usernames: 1,
usersCount: 1,
topic: 1,
encrypted: 1,
description: 1,
announcement: 1,
broadcast: 1,
archived: 1,
avatarETag: 1,
retention: 1,
teamId: 1,
teamMain: 1,
msgs: 1,
onHold: 1,
metrics: 1,
muted: 1,
servedBy: 1,
ts: 1,
waitingResponse: 1,
v: 1,
transcriptRequest: 1,
tags: 1,
closedAt: 1,
responseBy: 1,
priorityId: 1,
priorityWeight: 1,
slaId: 1,
estimatedWaitingTimeQueue: 1,
livechatData: 1,
departmentId: 1,
source: 1,
queuedAt: 1,
federated: 1,
},
};

const room = CachedChatRoom.collection.findOne({ _id: subscription.rid }, options);
const room = CachedChatRoom.collection.store.find((record) => record._id === subscription.rid);

const lastRoomUpdate = room?.lm || subscription.ts || room?.ts;

Expand Down
20 changes: 4 additions & 16 deletions apps/meteor/app/models/client/models/Messages.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,8 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { Mongo } from 'meteor/mongo';

import type { MinimongoCollection } from '../../../../client/definitions/MinimongoCollection';

class ChatMessageCollection
extends Mongo.Collection<IMessage & { ignored?: boolean }>
implements MinimongoCollection<IMessage & { ignored?: boolean }>
{
constructor() {
super(null);
}

public declare _collection: MinimongoCollection<IMessage & { ignored?: boolean }>['_collection'];

public declare queries: MinimongoCollection<IMessage & { ignored?: boolean }>['queries'];
}
import { MinimongoCollection } from '../../../../client/lib/cachedCollections/MinimongoCollection';

/** @deprecated new code refer to Minimongo collections like this one; prefer fetching data from the REST API, listening to changes via streamer events, and storing the state in a Tanstack Query */
export const Messages = new ChatMessageCollection();
export const Messages = new MinimongoCollection<
IMessage & { ignored?: boolean; autoTranslateFetching?: boolean; autoTranslateShowInverse?: boolean }
>();
13 changes: 2 additions & 11 deletions apps/meteor/app/models/client/models/Roles.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import type { IRole, IUser } from '@rocket.chat/core-typings';
import { Mongo } from 'meteor/mongo';
import { ReactiveVar } from 'meteor/reactive-var';

import { Subscriptions } from './Subscriptions';
import { Users } from './Users';
import type { MinimongoCollection } from '../../../../client/definitions/MinimongoCollection';
import { MinimongoCollection } from '../../../../client/lib/cachedCollections/MinimongoCollection';

class RolesCollection extends Mongo.Collection<IRole> implements MinimongoCollection<IRole> {
class RolesCollection extends MinimongoCollection<IRole> {
ready = new ReactiveVar(false);

constructor() {
super(null);
}

isUserInRoles(userId: IUser['_id'], roles: IRole['_id'][] | IRole['_id'], scope?: string, ignoreSubscriptions = false) {
roles = Array.isArray(roles) ? roles : [roles];
return roles.some((roleId) => {
Expand All @@ -31,10 +26,6 @@ class RolesCollection extends Mongo.Collection<IRole> implements MinimongoCollec
}
});
}

public declare _collection: MinimongoCollection<IRole>['_collection'];

public declare queries: MinimongoCollection<IRole>['queries'];
}

/** @deprecated new code refer to Minimongo collections like this one; prefer fetching data from the REST API, listening to changes via streamer events, and storing the state in a Tanstack Query */
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/models/client/models/Subscriptions.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { IRole, IRoom, IUser } from '@rocket.chat/core-typings';
import mem from 'mem';
import { Meteor } from 'meteor/meteor';
import type { Filter } from 'mongodb';

import { CachedChatSubscription } from './CachedChatSubscription';
import { Users } from './Users';
import { isTruthy } from '../../../../lib/isTruthy';

/** @deprecated new code refer to Minimongo collections like this one; prefer fetching data from the REST API, listening to changes via streamer events, and storing the state in a Tanstack Query */
Expand Down Expand Up @@ -49,7 +49,7 @@ export const Subscriptions = Object.assign(CachedChatSubscription.collection, {
})
.filter(isTruthy);

return Meteor.users.find({ _id: { $in: uids } }, options);
return Users.find({ _id: { $in: uids } }, options);
},
{ maxAge: 1000, cacheKey: JSON.stringify },
),
Expand Down
39 changes: 10 additions & 29 deletions apps/meteor/app/models/client/models/Users.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,24 @@
import type { IRole, IUser } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';

class UsersCollection extends Mongo.Collection<IUser> {
constructor() {
super(null);
}

findOneById<TOptions extends Omit<Mongo.Options<IUser>, 'limit'>>(uid: IUser['_id'], options?: TOptions) {
const query: Mongo.Selector<IUser> = {
_id: uid,
};

return this.findOne(query, options);
}
import { MinimongoCollection } from '../../../../client/lib/cachedCollections/MinimongoCollection';

class UsersCollection extends MinimongoCollection<IUser> {
isUserInRole(uid: IUser['_id'], roleId: IRole['_id']) {
const user = this.findOneById(uid, { fields: { roles: 1 } });
const user = this.findOne({ _id: uid }, { fields: { roles: 1 } });
return user && Array.isArray(user.roles) && user.roles.includes(roleId);
}

findUsersInRoles(roles: IRole['_id'][] | IRole['_id'], _scope: string, options: any) {
roles = Array.isArray(roles) ? roles : [roles];

const query: Mongo.Selector<IUser> = {
roles: { $in: roles },
};

return this.find(query, options);
return this.find(
{
roles: { $in: roles },
},
options,
);
}
}

Object.assign(Meteor.users, {
_connection: undefined,
findOneById: UsersCollection.prototype.findOneById,
isUserInRole: UsersCollection.prototype.isUserInRole,
findUsersInRoles: UsersCollection.prototype.findUsersInRoles,
remove: UsersCollection.prototype.remove,
});

/** @deprecated new code refer to Minimongo collections like this one; prefer fetching data from the REST API, listening to changes via streamer events, and storing the state in a Tanstack Query */
export const Users = Meteor.users as unknown as UsersCollection;
export const Users = new UsersCollection();
Loading
Loading