Files
upstream-mirror 30810eecd7
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 2s
snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
2026-09-16 01:21:02 +05:00

183 lines
4.0 KiB
TypeScript

import type { INotification, INotificationItemPush, INotificationItemEmail, NotificationItem, IUser } from '@rocket.chat/core-typings';
import { NotificationQueue, Users } from '@rocket.chat/models';
import { tracerSpan } from '@rocket.chat/tracing';
import { Meteor } from 'meteor/meteor';
import { SystemLogger } from '../../logger/system';
import { sendEmailFromData } from '../message/email';
import { PushNotification } from '../push-config';
const {
NOTIFICATIONS_WORKER_TIMEOUT = 2000,
NOTIFICATIONS_BATCH_SIZE = 100,
NOTIFICATIONS_SCHEDULE_DELAY_ONLINE = 120,
NOTIFICATIONS_SCHEDULE_DELAY_AWAY = 0,
NOTIFICATIONS_SCHEDULE_DELAY_OFFLINE = 0,
} = process.env;
class NotificationClass {
private running = false;
private cyclePause = Number(NOTIFICATIONS_WORKER_TIMEOUT);
private maxBatchSize = Number(NOTIFICATIONS_BATCH_SIZE);
private maxScheduleDelaySeconds: { [key: string]: number } = {
online: Number(NOTIFICATIONS_SCHEDULE_DELAY_ONLINE),
away: Number(NOTIFICATIONS_SCHEDULE_DELAY_AWAY),
offline: Number(NOTIFICATIONS_SCHEDULE_DELAY_OFFLINE),
};
initWorker(): void {
this.running = true;
this.executeWorkerLater();
}
stopWorker(): void {
this.running = false;
}
executeWorkerLater(): void {
if (!this.running) {
return;
}
setTimeout(async () => {
try {
const continueLater = await tracerSpan(
'NotificationWorker',
{
attributes: {
workerTime: new Date().toISOString(),
},
},
() => this.worker(),
);
if (continueLater) {
this.executeWorkerLater();
}
} catch (err) {
SystemLogger.error({ msg: 'Error sending notification', err });
this.executeWorkerLater();
}
}, this.cyclePause);
}
async worker(counter = 0): Promise<boolean> {
const notification = await this.getNextNotification();
if (!notification) {
return true;
}
// Once we start notifying the user we anticipate all the schedules
const flush = await NotificationQueue.clearScheduleByUserId(notification.uid);
// start worker again if queue flushed
if (flush.modifiedCount) {
await NotificationQueue.unsetSendingById(notification._id);
return this.worker(counter);
}
try {
for (const item of notification.items) {
switch (item.type) {
case 'push':
await this.push(notification, item);
break;
case 'email':
await this.email(item);
break;
}
}
await NotificationQueue.removeById(notification._id);
} catch (err) {
SystemLogger.error({ err });
await NotificationQueue.setErrorById(notification._id, err instanceof Error ? err.message : String(err));
}
if (counter >= this.maxBatchSize) {
return true;
}
return this.worker(++counter);
}
getNextNotification(): Promise<INotification | null> {
const expired = new Date();
expired.setMinutes(expired.getMinutes() - 5);
return NotificationQueue.findNextInQueueOrExpired(expired);
}
async push({ uid, rid, mid }: INotification, item: INotificationItemPush): Promise<void> {
await PushNotification.send({
rid,
uid,
mid,
...item.data,
});
}
async email(item: INotificationItemEmail): Promise<void> {
return sendEmailFromData(item.data);
}
async scheduleItem({
uid,
rid,
mid,
items,
user,
}: {
uid: string;
rid: string;
mid: string;
items: NotificationItem[];
user?: Partial<IUser>;
}): Promise<void> {
const receiver =
user ||
(await Users.findOneById<Pick<IUser, 'statusConnection'>>(uid, {
projection: {
statusConnection: 1,
},
}));
if (!receiver) {
return;
}
const { statusConnection = 'offline' } = receiver;
let schedule: Date | undefined;
const delay = this.maxScheduleDelaySeconds[statusConnection];
if (delay < 0) {
return;
}
if (delay > 0) {
schedule = new Date();
schedule.setSeconds(schedule.getSeconds() + delay);
}
await NotificationQueue.insertOne({
uid,
rid,
mid,
ts: new Date(),
...(schedule && { schedule }),
items,
});
}
}
export const Notification = new NotificationClass();
Meteor.startup(() => {
Notification.initWorker();
});