4 Registers background jobs to run periodically while the server is
8 var Config
= require("./config");
9 var db
= require("./database");
10 var Promise
= require("bluebird");
12 const LOGGER
= require('@calzoneman/jsli')('bgtask');
17 function initAliasCleanup() {
18 var CLEAN_INTERVAL
= parseInt(Config
.get("aliases.purge-interval"));
19 var CLEAN_EXPIRE
= parseInt(Config
.get("aliases.max-age"));
21 setInterval(function () {
22 db
.cleanOldAliases(CLEAN_EXPIRE
, function (err
) {
23 LOGGER
.info("Cleaned old aliases");
30 /* Password reset cleanup */
31 function initPasswordResetCleanup() {
32 var CLEAN_INTERVAL
= 8*60*60*1000;
34 setInterval(function () {
35 db
.cleanOldPasswordResets(function (err
) {
42 function initChannelDumper(Server
) {
43 const chanPath
= Config
.get('channel-path');
44 var CHANNEL_SAVE_INTERVAL
= parseInt(Config
.get("channel-save-interval"))
46 setInterval(function () {
47 if (Server
.channels
.length
=== 0) {
51 var wait
= CHANNEL_SAVE_INTERVAL
/ Server
.channels
.length
;
52 LOGGER
.info(`Saving channels with delay ${wait}`);
53 Promise
.reduce(Server
.channels
, (_
, chan
) => {
54 return Promise
.delay(wait
).then(async () => {
55 if (!chan
.dead
&& chan
.users
&& chan
.users
.length
> 0) {
57 await chan
.saveState();
58 LOGGER
.info(`Saved /${chanPath}/${chan.name}`);
61 'Failed to save /%s/%s: %s',
63 chan
? chan
.name
: '<undefined>',
69 LOGGER
.error(`Failed to save channel: ${error.stack}`);
71 }, 0).catch(error
=> {
72 LOGGER
.error(`Failed to save channels: ${error.stack}`);
74 }, CHANNEL_SAVE_INTERVAL
);
77 function initAccountCleanup() {
80 let rows
= await db
.users
.findAccountsPendingDeletion();
81 for (let row
of rows
) {
83 await db
.users
.purgeAccount(row
.id
);
84 LOGGER
.info('Purged account from request %j', row
);
86 LOGGER
.error('Error purging account %j: %s', row
, error
.stack
);
90 LOGGER
.error('Error purging deleted accounts: %s', error
.stack
);
95 module
.exports = function (Server
) {
96 if (init
=== Server
) {
97 LOGGER
.warn("Attempted to re-init background tasks");
103 initChannelDumper(Server
);
104 initPasswordResetCleanup();
105 initAccountCleanup();