From 202dfadfc233ecb386d0f49498e48a0a873d6e50 Mon Sep 17 00:00:00 2001 From: Kevin Aleman Date: Tue, 8 Nov 2022 20:08:03 -0600 Subject: [PATCH] change aggs to run on secondary --- .../models/server/models/LivechatInquiry.ts | 3 +- .../app/models/server/models/LivechatRooms.js | 257 +++++++++--------- .../ee/app/models/server/models/Users.ts | 82 +++--- .../server/database/readSecondaryPreferred.ts | 4 +- apps/meteor/server/models/raw/Analytics.ts | 111 ++++---- .../models/raw/LivechatAgentActivity.ts | 5 +- .../meteor/server/models/raw/LivechatRooms.js | 41 +-- apps/meteor/server/models/raw/Messages.ts | 56 ++-- apps/meteor/server/models/raw/Rooms.js | 3 +- 9 files changed, 295 insertions(+), 267 deletions(-) diff --git a/apps/meteor/app/models/server/models/LivechatInquiry.ts b/apps/meteor/app/models/server/models/LivechatInquiry.ts index a7d52cb97bdf..901b93e4cc80 100644 --- a/apps/meteor/app/models/server/models/LivechatInquiry.ts +++ b/apps/meteor/app/models/server/models/LivechatInquiry.ts @@ -1,6 +1,7 @@ import type { ILivechatInquiryRecord } from '@rocket.chat/core-typings'; import type { FindOptions, FindCursor, UpdateResult, DeleteResult } from 'mongodb'; +import { readSecondaryPreferred } from '../../../../server/database/readSecondaryPreferred'; import { Base } from './_Base'; export class LivechatInquiry extends Base { @@ -244,7 +245,7 @@ export class LivechatInquiry extends Base { aggregate.push({ $match: { _id } }); } - return collectionObj.aggregate(aggregate).toArray(); + return collectionObj.aggregate(aggregate, { readPreference: readSecondaryPreferred() }).toArray(); } removeDefaultAgentById(inquiryId: string): UpdateResult { diff --git a/apps/meteor/app/models/server/models/LivechatRooms.js b/apps/meteor/app/models/server/models/LivechatRooms.js index cef4529b21b0..1f202d3c9e70 100644 --- a/apps/meteor/app/models/server/models/LivechatRooms.js +++ b/apps/meteor/app/models/server/models/LivechatRooms.js @@ -4,6 +4,7 @@ import { Settings } from '@rocket.chat/models'; import { Base } from './_Base'; import Rooms from './Rooms'; +import { readSecondaryPreferred } from '../../../../server/database/readSecondaryPreferred'; export class LivechatRooms extends Base { constructor(...args) { @@ -494,152 +495,158 @@ export class LivechatRooms extends Base { } getAnalyticsMetricsBetweenDateWithMessages(t, date, { departmentId } = {}, extraQuery) { - return this.model.rawCollection().aggregate([ - { - $match: { - t, - ts: { - $gte: new Date(date.gte), // ISO Date, ts >= date.gte - $lt: new Date(date.lt), // ISODate, ts < date.lt + return this.model.rawCollection().aggregate( + [ + { + $match: { + t, + ts: { + $gte: new Date(date.gte), // ISO Date, ts >= date.gte + $lt: new Date(date.lt), // ISODate, ts < date.lt + }, + ...(departmentId && departmentId !== 'undefined' && { departmentId }), }, - ...(departmentId && departmentId !== 'undefined' && { departmentId }), }, - }, - { $addFields: { roomId: '$_id' } }, - { - $lookup: { - from: 'rocketchat_message', - // mongo doesn't like _id as variable name here :( - let: { roomId: '$roomId' }, - pipeline: [ - { - $match: { - $expr: { - $and: [ - { - $eq: ['$$roomId', '$rid'], - }, - { - // this is similar to do { $exists: false } - $lte: ['$t', null], - }, - ...(extraQuery ? [extraQuery] : []), - ], + { $addFields: { roomId: '$_id' } }, + { + $lookup: { + from: 'rocketchat_message', + // mongo doesn't like _id as variable name here :( + let: { roomId: '$roomId' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { + $eq: ['$$roomId', '$rid'], + }, + { + // this is similar to do { $exists: false } + $lte: ['$t', null], + }, + ...(extraQuery ? [extraQuery] : []), + ], + }, }, }, - }, - ], - as: 'messages', - }, - }, - { - $unwind: { - path: '$messages', - preserveNullAndEmptyArrays: true, + ], + as: 'messages', + }, }, - }, - { - $group: { - _id: { - _id: '$_id', - ts: '$ts', - departmentId: '$departmentId', - open: '$open', - servedBy: '$servedBy', - metrics: '$metrics', + { + $unwind: { + path: '$messages', + preserveNullAndEmptyArrays: true, }, - messagesCount: { - $sum: 1, + }, + { + $group: { + _id: { + _id: '$_id', + ts: '$ts', + departmentId: '$departmentId', + open: '$open', + servedBy: '$servedBy', + metrics: '$metrics', + }, + messagesCount: { + $sum: 1, + }, }, }, - }, - { - $project: { - _id: '$_id._id', - ts: '$_id.ts', - departmentId: '$_id.departmentId', - open: '$_id.open', - servedBy: '$_id.servedBy', - metrics: '$_id.metrics', - msgs: '$messagesCount', + { + $project: { + _id: '$_id._id', + ts: '$_id.ts', + departmentId: '$_id.departmentId', + open: '$_id.open', + servedBy: '$_id.servedBy', + metrics: '$_id.metrics', + msgs: '$messagesCount', + }, }, - }, - ]); + ], + { readPreference: readSecondaryPreferred() }, + ); } getAnalyticsBetweenDate(date, { departmentId } = {}) { - return this.model.rawCollection().aggregate([ - { - $match: { - t: 'l', - ts: { - $gte: new Date(date.gte), // ISO Date, ts >= date.gte - $lt: new Date(date.lt), // ISODate, ts < date.lt + return this.model.rawCollection().aggregate( + [ + { + $match: { + t: 'l', + ts: { + $gte: new Date(date.gte), // ISO Date, ts >= date.gte + $lt: new Date(date.lt), // ISODate, ts < date.lt + }, + ...(departmentId && departmentId !== 'undefined' && { departmentId }), }, - ...(departmentId && departmentId !== 'undefined' && { departmentId }), }, - }, - { $addFields: { roomId: '$_id' } }, - { - $lookup: { - from: 'rocketchat_message', - // mongo doesn't like _id as variable name here :( - let: { roomId: '$roomId' }, - pipeline: [ - { - $match: { - $expr: { - $and: [ - { - $eq: ['$$roomId', '$rid'], - }, - { - // this is similar to do { $exists: false } - $lte: ['$t', null], - }, - ], + { $addFields: { roomId: '$_id' } }, + { + $lookup: { + from: 'rocketchat_message', + // mongo doesn't like _id as variable name here :( + let: { roomId: '$roomId' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { + $eq: ['$$roomId', '$rid'], + }, + { + // this is similar to do { $exists: false } + $lte: ['$t', null], + }, + ], + }, }, }, - }, - ], - as: 'messages', - }, - }, - { - $unwind: { - path: '$messages', - preserveNullAndEmptyArrays: true, + ], + as: 'messages', + }, }, - }, - { - $group: { - _id: { - _id: '$_id', - ts: '$ts', - departmentId: '$departmentId', - open: '$open', - servedBy: '$servedBy', - metrics: '$metrics', - onHold: '$onHold', + { + $unwind: { + path: '$messages', + preserveNullAndEmptyArrays: true, }, - messagesCount: { - $sum: 1, + }, + { + $group: { + _id: { + _id: '$_id', + ts: '$ts', + departmentId: '$departmentId', + open: '$open', + servedBy: '$servedBy', + metrics: '$metrics', + onHold: '$onHold', + }, + messagesCount: { + $sum: 1, + }, }, }, - }, - { - $project: { - _id: '$_id._id', - ts: '$_id.ts', - departmentId: '$_id.departmentId', - open: '$_id.open', - servedBy: '$_id.servedBy', - metrics: '$_id.metrics', - msgs: '$messagesCount', - onHold: '$_id.onHold', + { + $project: { + _id: '$_id._id', + ts: '$_id.ts', + departmentId: '$_id.departmentId', + open: '$_id.open', + servedBy: '$_id.servedBy', + metrics: '$_id.metrics', + msgs: '$messagesCount', + onHold: '$_id.onHold', + }, }, - }, - ]); + ], + { readPreference: readSecondaryPreferred() }, + ); } closeByRoomId(roomId, closeInfo) { diff --git a/apps/meteor/ee/app/models/server/models/Users.ts b/apps/meteor/ee/app/models/server/models/Users.ts index 6bf132782a4b..d24ace1f5a56 100644 --- a/apps/meteor/ee/app/models/server/models/Users.ts +++ b/apps/meteor/ee/app/models/server/models/Users.ts @@ -1,5 +1,6 @@ import { overwriteClassOnLicense } from '../../../license/server'; import { Users } from '../../../../../app/models/server/models/Users'; +import { readSecondaryPreferred } from '../../../../../server/database/readSecondaryPreferred'; type AgentMetadata = { 'agentId'?: string; @@ -40,53 +41,56 @@ const getUnavailableAgents = function (_: any, departmentId: string, customFilte : []; return col - .aggregate([ - { - $match: { - status: { $exists: true, $ne: 'offline' }, - statusLivechat: 'available', - roles: 'livechat-agent', + .aggregate( + [ + { + $match: { + status: { $exists: true, $ne: 'offline' }, + statusLivechat: 'available', + roles: 'livechat-agent', + }, }, - }, - ...departmentFilter, - { - $lookup: { - from: 'rocketchat_subscription', - localField: '_id', - foreignField: 'u._id', - as: 'subs', + ...departmentFilter, + { + $lookup: { + from: 'rocketchat_subscription', + localField: '_id', + foreignField: 'u._id', + as: 'subs', + }, }, - }, - { - $project: { - 'agentId': '$_id', - 'livechat.maxNumberSimultaneousChat': 1, - 'username': 1, - 'lastAssignTime': 1, - 'lastRoutingTime': 1, - 'queueInfo.chats': { - $size: { - $filter: { - input: '$subs', - as: 'sub', - cond: { - $and: [{ $eq: ['$$sub.t', 'l'] }, { $eq: ['$$sub.open', true] }, { $ne: ['$$sub.onHold', true] }], + { + $project: { + 'agentId': '$_id', + 'livechat.maxNumberSimultaneousChat': 1, + 'username': 1, + 'lastAssignTime': 1, + 'lastRoutingTime': 1, + 'queueInfo.chats': { + $size: { + $filter: { + input: '$subs', + as: 'sub', + cond: { + $and: [{ $eq: ['$$sub.t', 'l'] }, { $eq: ['$$sub.open', true] }, { $ne: ['$$sub.onHold', true] }], + }, }, }, }, }, }, - }, - ...(customFilter ? [customFilter] : []), - { - $sort: { - 'queueInfo.chats': 1, - 'lastAssignTime': 1, - 'lastRoutingTime': 1, - 'username': 1, + ...(customFilter ? [customFilter] : []), + { + $sort: { + 'queueInfo.chats': 1, + 'lastAssignTime': 1, + 'lastRoutingTime': 1, + 'username': 1, + }, }, - }, - ]) + ], + { allowDiskUse: true, readPreference: readSecondaryPreferred() }, + ) .toArray(); }; diff --git a/apps/meteor/server/database/readSecondaryPreferred.ts b/apps/meteor/server/database/readSecondaryPreferred.ts index 0b9f7af1500a..4bf7e5a95918 100644 --- a/apps/meteor/server/database/readSecondaryPreferred.ts +++ b/apps/meteor/server/database/readSecondaryPreferred.ts @@ -1,8 +1,8 @@ import type { Db, ReadPreferenceLike } from 'mongodb'; import { ReadPreference } from 'mongodb'; -export function readSecondaryPreferred(db: Db, tags: any[] = []): ReadPreferenceLike { - const { readPreference } = db.options || {}; +export function readSecondaryPreferred(db?: Db, tags: any[] = []): ReadPreferenceLike { + const { readPreference } = db?.options || {}; if (tags.length) { return new ReadPreference(ReadPreference.SECONDARY_PREFERRED, tags); diff --git a/apps/meteor/server/models/raw/Analytics.ts b/apps/meteor/server/models/raw/Analytics.ts index 2455817687ac..b4542c869584 100644 --- a/apps/meteor/server/models/raw/Analytics.ts +++ b/apps/meteor/server/models/raw/Analytics.ts @@ -79,22 +79,25 @@ export class AnalyticsRaw extends BaseRaw implements IAnalyticsModel return this.col.aggregate<{ _id: IAnalytic['date']; messages: number; - }>([ - { - $match: { - type: 'messages', - date: { $gte: start, $lte: end }, + }>( + [ + { + $match: { + type: 'messages', + date: { $gte: start, $lte: end }, + }, }, - }, - { - $group: { - _id: '$date', - messages: { $sum: '$messages' }, + { + $group: { + _id: '$date', + messages: { $sum: '$messages' }, + }, }, - }, - ...(options.sort ? [{ $sort: options.sort }] : []), - ...(options.count ? [{ $limit: options.count }] : []), - ]); + ...(options.sort ? [{ $sort: options.sort }] : []), + ...(options.count ? [{ $limit: options.count }] : []), + ], + { readPreference: readSecondaryPreferred() }, + ); } getMessagesOrigin({ start, end }: { start: IAnalytic['date']; end: IAnalytic['date'] }): AggregationCursor<{ @@ -122,7 +125,7 @@ export class AnalyticsRaw extends BaseRaw implements IAnalyticsModel }, }, ]; - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } getMostPopularChannelsByMessagesSentQuantity({ @@ -139,31 +142,34 @@ export class AnalyticsRaw extends BaseRaw implements IAnalyticsModel messages: number; usernames: string[]; }> { - return this.col.aggregate([ - { - $match: { - type: 'messages', - date: { $gte: start, $lte: end }, + return this.col.aggregate( + [ + { + $match: { + type: 'messages', + date: { $gte: start, $lte: end }, + }, }, - }, - { - $group: { - _id: { t: '$room.t', name: '$room.name', usernames: '$room.usernames' }, - messages: { $sum: '$messages' }, + { + $group: { + _id: { t: '$room.t', name: '$room.name', usernames: '$room.usernames' }, + messages: { $sum: '$messages' }, + }, }, - }, - { - $project: { - _id: 0, - t: '$_id.t', - name: '$_id.name', - usernames: '$_id.usernames', - messages: 1, + { + $project: { + _id: 0, + t: '$_id.t', + name: '$_id.name', + usernames: '$_id.usernames', + messages: 1, + }, }, - }, - ...(options.sort ? [{ $sort: options.sort }] : []), - ...(options.count ? [{ $limit: options.count }] : []), - ]); + ...(options.sort ? [{ $sort: options.sort }] : []), + ...(options.count ? [{ $limit: options.count }] : []), + ], + { readPreference: readSecondaryPreferred() }, + ); } getTotalOfRegisteredUsersByDate({ @@ -181,22 +187,25 @@ export class AnalyticsRaw extends BaseRaw implements IAnalyticsModel return this.col.aggregate<{ _id: IAnalytic['date']; users: number; - }>([ - { - $match: { - type: 'users', - date: { $gte: start, $lte: end }, + }>( + [ + { + $match: { + type: 'users', + date: { $gte: start, $lte: end }, + }, }, - }, - { - $group: { - _id: '$date', - users: { $sum: '$users' }, + { + $group: { + _id: '$date', + users: { $sum: '$users' }, + }, }, - }, - ...(options.sort ? [{ $sort: options.sort }] : []), - ...(options.count ? [{ $limit: options.count }] : []), - ]); + ...(options.sort ? [{ $sort: options.sort }] : []), + ...(options.count ? [{ $limit: options.count }] : []), + ], + { readPreference: readSecondaryPreferred() }, + ); } findByTypeBeforeDate({ type, date }: { type: IAnalytic['type']; date: IAnalytic['date'] }): FindCursor { diff --git a/apps/meteor/server/models/raw/LivechatAgentActivity.ts b/apps/meteor/server/models/raw/LivechatAgentActivity.ts index 1f4dee69b4df..8e35807d1ae5 100644 --- a/apps/meteor/server/models/raw/LivechatAgentActivity.ts +++ b/apps/meteor/server/models/raw/LivechatAgentActivity.ts @@ -4,6 +4,7 @@ import type { AggregationCursor, Collection, Document, FindCursor, Db, ModifyRes import moment from 'moment'; import { BaseRaw } from './BaseRaw'; +import { readSecondaryPreferred } from '../../database/readSecondaryPreferred'; export class LivechatAgentActivityRaw extends BaseRaw implements ILivechatAgentActivityModel { constructor(db: Db, trash?: Collection>) { @@ -141,7 +142,7 @@ export class LivechatAgentActivityRaw extends BaseRaw im } params.push(group); params.push(project); - return this.col.aggregate(params).toArray(); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }).toArray(); } findAvailableServiceTimeHistory({ @@ -206,6 +207,6 @@ export class LivechatAgentActivityRaw extends BaseRaw im if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params, { allowDiskUse: true }); + return this.col.aggregate(params, { allowDiskUse: true, readPreference: readSecondaryPreferred() }); } } diff --git a/apps/meteor/server/models/raw/LivechatRooms.js b/apps/meteor/server/models/raw/LivechatRooms.js index 6006c1598300..814ebaff7a82 100644 --- a/apps/meteor/server/models/raw/LivechatRooms.js +++ b/apps/meteor/server/models/raw/LivechatRooms.js @@ -1,5 +1,6 @@ import { BaseRaw } from './BaseRaw'; import { getValue } from '../../../app/settings/server/raw'; +import { readSecondaryPreferred } from '../../database/readSecondaryPreferred'; export class LivechatRoomsRaw extends BaseRaw { constructor(db, trash) { @@ -105,7 +106,7 @@ export class LivechatRoomsRaw extends BaseRaw { }; const params = [...firstParams, usersGroup, project, facet]; - return this.col.aggregate(params).toArray(); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }).toArray(); } async findAllNumberOfAbandonedRooms({ start, end, departmentId, onlyCount = false, options = {} }) { @@ -149,7 +150,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } async findPercentageOfAbandonedRooms({ start, end, departmentId, onlyCount = false, options = {} }) { @@ -209,7 +210,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } findAllAverageOfChatDurationTime({ start, end, departmentId, onlyCount = false, options = {} }) { @@ -253,7 +254,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } findAllAverageWaitingTime({ start, end, departmentId, onlyCount = false, options = {} }) { @@ -299,7 +300,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } findAllRooms({ start, end, answered, departmentId, onlyCount = false, options = {} }) { @@ -342,7 +343,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } findAllServiceTime({ start, end, departmentId, onlyCount = false, options = {} }) { @@ -386,7 +387,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } findAllNumberOfTransferredRooms({ start, end, departmentId, options = {} }) { @@ -505,7 +506,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params, { allowDiskUse: true }).toArray(); + return this.col.aggregate(params, { allowDiskUse: true, readPreference: readSecondaryPreferred() }).toArray(); } countAllOpenChatsBetweenDate({ start, end, departmentId }) { @@ -594,7 +595,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (departmentId && departmentId !== 'undefined') { match.$match.departmentId = departmentId; } - return this.col.aggregate([match, group]).toArray(); + return this.col.aggregate([match, group], { readPreference: readSecondaryPreferred() }).toArray(); } countAllOnHoldChatsByAgentBetweenDate({ start, end, departmentId }) { @@ -619,7 +620,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (departmentId && departmentId !== 'undefined') { match.$match.departmentId = departmentId; } - return this.col.aggregate([match, group]).toArray(); + return this.col.aggregate([match, group], { readPreference: readSecondaryPreferred() }).toArray(); } countAllClosedChatsByAgentBetweenDate({ start, end, departmentId }) { @@ -641,7 +642,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (departmentId && departmentId !== 'undefined') { match.$match.departmentId = departmentId; } - return this.col.aggregate([match, group]).toArray(); + return this.col.aggregate([match, group], { readPreference: readSecondaryPreferred() }).toArray(); } countAllOpenChatsByDepartmentBetweenDate({ start, end, departmentId }) { @@ -687,7 +688,7 @@ export class LivechatRoomsRaw extends BaseRaw { match.$match.departmentId = departmentId; } const params = [match, lookup, unwind, group, project]; - return this.col.aggregate(params).toArray(); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }).toArray(); } countAllClosedChatsByDepartmentBetweenDate({ start, end, departmentId }) { @@ -733,7 +734,7 @@ export class LivechatRoomsRaw extends BaseRaw { match.$match.departmentId = departmentId; } const params = [match, lookup, unwind, group, project]; - return this.col.aggregate(params).toArray(); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }).toArray(); } calculateResponseTimingsBetweenDates({ start, end, departmentId }) { @@ -776,7 +777,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (departmentId && departmentId !== 'undefined') { match.$match.departmentId = departmentId; } - return this.col.aggregate([match, group, project]).toArray(); + return this.col.aggregate([match, group, project], { readPreference: readSecondaryPreferred() }).toArray(); } calculateReactionTimingsBetweenDates({ start, end, departmentId }) { @@ -819,7 +820,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (departmentId && departmentId !== 'undefined') { match.$match.departmentId = departmentId; } - return this.col.aggregate([match, group, project]).toArray(); + return this.col.aggregate([match, group, project], { readPreference: readSecondaryPreferred() }).toArray(); } calculateDurationTimingsBetweenDates({ start, end, departmentId }) { @@ -863,7 +864,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (departmentId && departmentId !== 'undefined') { match.$match.departmentId = departmentId; } - return this.col.aggregate([match, group, project]).toArray(); + return this.col.aggregate([match, group, project], { readPreference: readSecondaryPreferred() }).toArray(); } findAllAverageOfServiceTime({ start, end, departmentId, onlyCount = false, options = {} }) { @@ -910,7 +911,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } findByVisitorId(visitorId, options) { @@ -996,7 +997,7 @@ export class LivechatRoomsRaw extends BaseRaw { params.push({ $limit: options.limit }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } findRoomsWithCriteria({ @@ -1139,7 +1140,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } findAllAverageServiceTimeByAgents({ start, end, onlyCount = false, options = {} }) { @@ -1186,7 +1187,7 @@ export class LivechatRoomsRaw extends BaseRaw { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } setDepartmentByRoomId(roomId, departmentId) { diff --git a/apps/meteor/server/models/raw/Messages.ts b/apps/meteor/server/models/raw/Messages.ts index e5e587088fa4..b68ee8055486 100644 --- a/apps/meteor/server/models/raw/Messages.ts +++ b/apps/meteor/server/models/raw/Messages.ts @@ -16,6 +16,7 @@ import { escapeRegExp } from '@rocket.chat/string-helpers'; import { BaseRaw } from './BaseRaw'; import { escapeExternalFederationEventId } from '../../../app/federation-v2/server/infrastructure/rocket-chat/adapters/MessageConverter'; +import { readSecondaryPreferred } from '../../database/readSecondaryPreferred'; // @ts-ignore Circular reference on field 'attachments' export class MessagesRaw extends BaseRaw implements IMessagesModel { @@ -152,7 +153,7 @@ export class MessagesRaw extends BaseRaw implements IMessagesModel { const params = [...firstParams, group, project, sort]; if (onlyCount) { params.push({ $count: 'total' }); - return this.col.aggregate(params); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }); } if (options.offset) { params.push({ $skip: options.offset }); @@ -160,7 +161,7 @@ export class MessagesRaw extends BaseRaw implements IMessagesModel { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params, { allowDiskUse: true }); + return this.col.aggregate(params, { allowDiskUse: true, readPreference: readSecondaryPreferred() }); } getTotalOfMessagesSentByDate({ start, end, options = {} }: { start: Date; end: Date; options?: PaginatedRequest }): Promise { @@ -218,7 +219,7 @@ export class MessagesRaw extends BaseRaw implements IMessagesModel { if (options.count) { params.push({ $limit: options.count }); } - return this.col.aggregate(params).toArray(); + return this.col.aggregate(params, { readPreference: readSecondaryPreferred() }).toArray(); } findLivechatClosedMessages(rid: IRoom['_id'], options: FindOptions): FindPaginated> { @@ -394,33 +395,36 @@ export class MessagesRaw extends BaseRaw implements IMessagesModel { async findOneByFederationIdAndUsernameOnReactions(federationEventId: string, username: string): Promise { return ( await this.col - .aggregate([ - { - $match: { - t: { $ne: 'rm' }, + .aggregate( + [ + { + $match: { + t: { $ne: 'rm' }, + }, }, - }, - { - $project: { - document: '$$ROOT', - reactions: { $objectToArray: '$reactions' }, + { + $project: { + document: '$$ROOT', + reactions: { $objectToArray: '$reactions' }, + }, }, - }, - { - $unwind: { - path: '$reactions', + { + $unwind: { + path: '$reactions', + }, }, - }, - { - $match: { - $and: [ - { 'reactions.v.usernames': { $in: [username] } }, - { [`reactions.v.federationReactionEventIds.${escapeExternalFederationEventId(federationEventId)}`]: username }, - ], + { + $match: { + $and: [ + { 'reactions.v.usernames': { $in: [username] } }, + { [`reactions.v.federationReactionEventIds.${escapeExternalFederationEventId(federationEventId)}`]: username }, + ], + }, }, - }, - { $replaceRoot: { newRoot: '$document' } }, - ]) + { $replaceRoot: { newRoot: '$document' } }, + ], + { readPreference: readSecondaryPreferred() }, + ) .toArray() )[0] as IMessage; } diff --git a/apps/meteor/server/models/raw/Rooms.js b/apps/meteor/server/models/raw/Rooms.js index df99d042b75e..6cb866fb186f 100644 --- a/apps/meteor/server/models/raw/Rooms.js +++ b/apps/meteor/server/models/raw/Rooms.js @@ -2,6 +2,7 @@ import { ReadPreference } from 'mongodb'; import { escapeRegExp } from '@rocket.chat/string-helpers'; import { BaseRaw } from './BaseRaw'; +import { readSecondaryPreferred } from '../../database/readSecondaryPreferred'; export class RoomsRaw extends BaseRaw { constructor(db, trash) { @@ -57,7 +58,7 @@ export class RoomsRaw extends BaseRaw { { $project: { _id: '$_id', avgChatDuration: { $divide: ['$sumChatDuration', '$chats'] } } }, ]; - const [statistic] = await this.col.aggregate(aggregate).toArray(); + const [statistic] = await this.col.aggregate(aggregate, { readPreference: readSecondaryPreferred() }).toArray(); return statistic; }