|
| 1 | +import { Settings } from '@rocket.chat/models'; |
| 2 | +import type { UpdateResult } from 'mongodb'; |
| 3 | + |
1 | 4 | import { upsertPermissions } from '../../../app/authorization/server/functions/upsertPermissions'; |
| 5 | +import { settings } from '../../../app/settings/server'; |
2 | 6 | import { migrateDatabase, onServerVersionChange } from '../../lib/migrations'; |
3 | 7 | import { ensureCloudWorkspaceRegistered } from '../cloudRegistration'; |
4 | 8 |
|
5 | 9 | const { MIGRATION_VERSION = 'latest' } = process.env; |
6 | 10 |
|
7 | 11 | const [version, ...subcommands] = MIGRATION_VERSION.split(','); |
8 | 12 |
|
| 13 | +const maxAgeSettingMap = new Map([ |
| 14 | + ['RetentionPolicy_MaxAge_Channels', 'RetentionPolicy_TTL_Channels'], |
| 15 | + ['RetentionPolicy_MaxAge_Groups', 'RetentionPolicy_TTL_Groups'], |
| 16 | + ['RetentionPolicy_MaxAge_DMs', 'RetentionPolicy_TTL_DMs'], |
| 17 | +]); |
| 18 | + |
| 19 | +const moveRetentionSetting = async () => { |
| 20 | + const convertDaysToMs = (days: number) => days * 24 * 60 * 60 * 1000; |
| 21 | + |
| 22 | + const promises: Array<Promise<UpdateResult>> = []; |
| 23 | + await Settings.find( |
| 24 | + { _id: { $in: Array.from(maxAgeSettingMap.keys()) }, value: { $ne: -1 } }, |
| 25 | + { projection: { _id: 1, value: 1 } }, |
| 26 | + ).forEach(({ _id, value }) => { |
| 27 | + const newSettingId = maxAgeSettingMap.get(_id); |
| 28 | + if (!newSettingId) { |
| 29 | + throw new Error(`moveRetentionSetting - Setting ${_id} equivalent does not exist`); |
| 30 | + } |
| 31 | + |
| 32 | + const newValue = convertDaysToMs(Number(value)); |
| 33 | + |
| 34 | + promises.push( |
| 35 | + Settings.updateOne( |
| 36 | + { |
| 37 | + _id: maxAgeSettingMap.get(_id), |
| 38 | + }, |
| 39 | + { |
| 40 | + $set: { |
| 41 | + value: newValue, |
| 42 | + }, |
| 43 | + }, |
| 44 | + ), |
| 45 | + ); |
| 46 | + |
| 47 | + const currentCache = settings.getSetting(newSettingId); |
| 48 | + if (!currentCache) { |
| 49 | + return; |
| 50 | + } |
| 51 | + settings.set({ ...currentCache, value: newValue }); |
| 52 | + }); |
| 53 | + |
| 54 | + await Promise.all(promises); |
| 55 | + await Settings.updateMany({ _id: { $in: Array.from(maxAgeSettingMap.keys()) } }, { $set: { value: -1 } }); |
| 56 | +}; |
| 57 | + |
9 | 58 | export const performMigrationProcedure = async (): Promise<void> => { |
10 | 59 | await migrateDatabase(version === 'latest' ? version : parseInt(version), subcommands); |
11 | 60 | // perform operations when the server is starting with a different version |
12 | 61 | await onServerVersionChange(async () => { |
13 | 62 | await upsertPermissions(); |
14 | 63 | await ensureCloudWorkspaceRegistered(); |
| 64 | + await moveRetentionSetting(); |
15 | 65 | }); |
16 | 66 | }; |
0 commit comments