Migrate codebase from CommonJS to ES Modules
- Convert all require()/module.exports to import/export across 260+ files
- Add "type": "module" to package.json to enable ESM by default
- Add migrations/package.json with "type": "commonjs" to keep db-migrate compatible
- Convert eslint.config.js to ESM with sourceType: "module"
- Replace __dirname/__filename with import.meta.dirname/import.meta.filename
- Replace require.main === module with process.argv[1] === import.meta.filename
- Remove 'use strict' directives (implicit in ESM)
- Convert dynamic require() in switch statements to static import lookup maps
(dns.js, domains.js, backupformats.js, backupsites.js, network.js)
- Extract self-referencing exports.CONSTANT patterns into standalone const
declarations (apps.js, services.js, locks.js, users.js, mail.js, etc.)
- Lazify SERVICES object in services.js to avoid circular dependency TDZ issues
- Add clearMailQueue() to mailer.js for ESM-safe queue clearing in tests
- Add _setMockApp() to ldapserver.js for ESM-safe test mocking
- Add _setMockResolve() wrapper to dig.js for ESM-safe DNS mocking in tests
- Convert backupupload.js to use dynamic imports so --check exits before
loading the module graph (which requires BOX_ENV)
- Update check-install to use ESM import for infra_version.js
- Convert scripts/ (hotfix, release, remote_hotfix.js, find-unused-translations)
- All 1315 tests passing
Migration stats (AI-assisted using Cursor with Claude):
- Wall clock time: ~3-4 hours
- Assistant completions: ~80-100
- Estimated token usage: ~1-2M tokens
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-14 09:53:14 +01:00
|
|
|
import apps from './apps.js';
|
|
|
|
|
import assert from 'node:assert';
|
|
|
|
|
import BoxError from './boxerror.js';
|
2026-02-14 15:43:24 +01:00
|
|
|
import cloudron from './cloudron.js';
|
Migrate codebase from CommonJS to ES Modules
- Convert all require()/module.exports to import/export across 260+ files
- Add "type": "module" to package.json to enable ESM by default
- Add migrations/package.json with "type": "commonjs" to keep db-migrate compatible
- Convert eslint.config.js to ESM with sourceType: "module"
- Replace __dirname/__filename with import.meta.dirname/import.meta.filename
- Replace require.main === module with process.argv[1] === import.meta.filename
- Remove 'use strict' directives (implicit in ESM)
- Convert dynamic require() in switch statements to static import lookup maps
(dns.js, domains.js, backupformats.js, backupsites.js, network.js)
- Extract self-referencing exports.CONSTANT patterns into standalone const
declarations (apps.js, services.js, locks.js, users.js, mail.js, etc.)
- Lazify SERVICES object in services.js to avoid circular dependency TDZ issues
- Add clearMailQueue() to mailer.js for ESM-safe queue clearing in tests
- Add _setMockApp() to ldapserver.js for ESM-safe test mocking
- Add _setMockResolve() wrapper to dig.js for ESM-safe DNS mocking in tests
- Convert backupupload.js to use dynamic imports so --check exits before
loading the module graph (which requires BOX_ENV)
- Update check-install to use ESM import for infra_version.js
- Convert scripts/ (hotfix, release, remote_hotfix.js, find-unused-translations)
- All 1315 tests passing
Migration stats (AI-assisted using Cursor with Claude):
- Wall clock time: ~3-4 hours
- Assistant completions: ~80-100
- Estimated token usage: ~1-2M tokens
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-14 09:53:14 +01:00
|
|
|
import constants from './constants.js';
|
|
|
|
|
import { CronJob } from 'cron';
|
2026-03-12 22:55:28 +05:30
|
|
|
import logger from './logger.js';
|
2026-02-14 15:43:24 +01:00
|
|
|
import docker from './docker.js';
|
2026-04-01 09:40:28 +02:00
|
|
|
import safe from '@cloudron/safetydance';
|
2026-02-14 15:43:24 +01:00
|
|
|
import _ from './underscore.js';
|
Migrate codebase from CommonJS to ES Modules
- Convert all require()/module.exports to import/export across 260+ files
- Add "type": "module" to package.json to enable ESM by default
- Add migrations/package.json with "type": "commonjs" to keep db-migrate compatible
- Convert eslint.config.js to ESM with sourceType: "module"
- Replace __dirname/__filename with import.meta.dirname/import.meta.filename
- Replace require.main === module with process.argv[1] === import.meta.filename
- Remove 'use strict' directives (implicit in ESM)
- Convert dynamic require() in switch statements to static import lookup maps
(dns.js, domains.js, backupformats.js, backupsites.js, network.js)
- Extract self-referencing exports.CONSTANT patterns into standalone const
declarations (apps.js, services.js, locks.js, users.js, mail.js, etc.)
- Lazify SERVICES object in services.js to avoid circular dependency TDZ issues
- Add clearMailQueue() to mailer.js for ESM-safe queue clearing in tests
- Add _setMockApp() to ldapserver.js for ESM-safe test mocking
- Add _setMockResolve() wrapper to dig.js for ESM-safe DNS mocking in tests
- Convert backupupload.js to use dynamic imports so --check exits before
loading the module graph (which requires BOX_ENV)
- Update check-install to use ESM import for infra_version.js
- Convert scripts/ (hotfix, release, remote_hotfix.js, find-unused-translations)
- All 1315 tests passing
Migration stats (AI-assisted using Cursor with Claude):
- Wall clock time: ~3-4 hours
- Assistant completions: ~80-100
- Estimated token usage: ~1-2M tokens
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-14 09:53:14 +01:00
|
|
|
|
2026-03-12 23:23:23 +05:30
|
|
|
const { log } = logger('scheduler');
|
Migrate codebase from CommonJS to ES Modules
- Convert all require()/module.exports to import/export across 260+ files
- Add "type": "module" to package.json to enable ESM by default
- Add migrations/package.json with "type": "commonjs" to keep db-migrate compatible
- Convert eslint.config.js to ESM with sourceType: "module"
- Replace __dirname/__filename with import.meta.dirname/import.meta.filename
- Replace require.main === module with process.argv[1] === import.meta.filename
- Remove 'use strict' directives (implicit in ESM)
- Convert dynamic require() in switch statements to static import lookup maps
(dns.js, domains.js, backupformats.js, backupsites.js, network.js)
- Extract self-referencing exports.CONSTANT patterns into standalone const
declarations (apps.js, services.js, locks.js, users.js, mail.js, etc.)
- Lazify SERVICES object in services.js to avoid circular dependency TDZ issues
- Add clearMailQueue() to mailer.js for ESM-safe queue clearing in tests
- Add _setMockApp() to ldapserver.js for ESM-safe test mocking
- Add _setMockResolve() wrapper to dig.js for ESM-safe DNS mocking in tests
- Convert backupupload.js to use dynamic imports so --check exits before
loading the module graph (which requires BOX_ENV)
- Update check-install to use ESM import for infra_version.js
- Convert scripts/ (hotfix, release, remote_hotfix.js, find-unused-translations)
- All 1315 tests passing
Migration stats (AI-assisted using Cursor with Claude):
- Wall clock time: ~3-4 hours
- Assistant completions: ~80-100
- Estimated token usage: ~1-2M tokens
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-14 09:53:14 +01:00
|
|
|
|
2015-10-18 08:40:24 -07:00
|
|
|
|
2022-05-20 09:31:58 -07:00
|
|
|
const gState = {}; // appId -> { containerId, schedulerConfig (manifest+crontab), cronjobs }
|
2022-05-20 09:38:17 -07:00
|
|
|
const gSuspendedAppIds = new Set(); // suspended because some apptask is running
|
2015-10-18 08:40:24 -07:00
|
|
|
|
2020-11-25 22:25:36 -08:00
|
|
|
// TODO: this should probably also stop existing jobs to completely prevent race but the code is not re-entrant
|
2025-01-02 10:10:40 +01:00
|
|
|
function suspendAppJobs(appId) {
|
2026-03-12 22:55:28 +05:30
|
|
|
log(`suspendAppJobs: ${appId}`);
|
2020-11-25 22:16:20 -08:00
|
|
|
gSuspendedAppIds.add(appId);
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-02 10:10:40 +01:00
|
|
|
function resumeAppJobs(appId) {
|
2026-03-12 22:55:28 +05:30
|
|
|
log(`resumeAppJobs: ${appId}`);
|
2020-11-25 22:16:20 -08:00
|
|
|
gSuspendedAppIds.delete(appId);
|
|
|
|
|
}
|
2015-10-18 08:40:24 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
async function runTask(appId, taskName) {
|
2020-08-18 19:08:37 -07:00
|
|
|
assert.strictEqual(typeof appId, 'string');
|
|
|
|
|
assert.strictEqual(typeof taskName, 'string');
|
2015-10-20 01:00:31 -07:00
|
|
|
|
2020-08-18 19:08:37 -07:00
|
|
|
const JOB_MAX_TIME = 30 * 60 * 1000; // 30 minutes
|
|
|
|
|
const containerName = `${appId}-${taskName}`;
|
2015-10-20 10:16:59 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
if (gSuspendedAppIds.has(appId)) return;
|
2020-11-25 22:16:20 -08:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
const app = await apps.get(appId);
|
|
|
|
|
if (!app) throw new BoxError(BoxError.NOT_FOUND, 'App not found');
|
2015-10-20 01:00:31 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
if (app.installationState !== apps.ISTATE_INSTALLED || app.runState !== apps.RSTATE_RUNNING || app.health !== apps.HEALTH_HEALTHY) return;
|
2015-10-20 01:00:31 -07:00
|
|
|
|
2021-08-31 07:59:07 -07:00
|
|
|
const [error, data] = await safe(docker.inspect(containerName));
|
2024-02-08 10:53:59 +01:00
|
|
|
if (!error && data?.State?.Running === true) {
|
2021-08-25 19:41:46 -07:00
|
|
|
const jobStartTime = new Date(data.State.StartedAt); // iso 8601
|
2024-02-08 10:53:59 +01:00
|
|
|
if ((new Date() - jobStartTime) < JOB_MAX_TIME) return;
|
2026-03-12 22:55:28 +05:30
|
|
|
log(`runTask: ${containerName} is running too long, restarting`);
|
2021-08-25 19:41:46 -07:00
|
|
|
}
|
2015-10-20 01:00:31 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
await docker.restartContainer(containerName);
|
2015-10-18 08:40:24 -07:00
|
|
|
}
|
|
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
async function createJobs(app, schedulerConfig) {
|
2020-08-18 19:08:37 -07:00
|
|
|
assert.strictEqual(typeof app, 'object');
|
|
|
|
|
assert(schedulerConfig && typeof schedulerConfig === 'object');
|
2018-02-27 13:50:29 -08:00
|
|
|
|
2020-08-18 19:08:37 -07:00
|
|
|
const appId = app.id;
|
2022-05-20 09:31:58 -07:00
|
|
|
const jobs = {};
|
2025-01-02 10:10:40 +01:00
|
|
|
const tz = await cloudron.getTimeZone();
|
2020-08-18 19:08:37 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
for (const taskName of Object.keys(schedulerConfig)) {
|
2022-05-20 09:31:58 -07:00
|
|
|
const { schedule, command } = schedulerConfig[taskName];
|
2020-08-18 19:08:37 -07:00
|
|
|
const containerName = `${app.id}-${taskName}`;
|
|
|
|
|
|
2022-05-20 09:31:58 -07:00
|
|
|
// stopJobs only deletes jobs since previous sync. This means that when box code restarts, none of the containers
|
2020-08-18 23:53:14 -07:00
|
|
|
// are removed. The deleteContainer here ensures we re-create the cron containers with the latest config
|
2021-08-25 19:41:46 -07:00
|
|
|
await safe(docker.deleteContainer(containerName)); // ignore error
|
2026-03-12 22:55:28 +05:30
|
|
|
const [error] = await safe(docker.createSubcontainer(app, containerName, [ '/bin/sh', '-c', command ], {} /* options */), { debug: log });
|
2021-08-25 19:41:46 -07:00
|
|
|
if (error && error.reason !== BoxError.ALREADY_EXISTS) continue;
|
|
|
|
|
|
2026-03-12 22:55:28 +05:30
|
|
|
log(`createJobs: ${taskName} (${app.fqdn}) will run in container ${containerName}`);
|
2021-08-25 19:41:46 -07:00
|
|
|
|
2022-05-20 09:31:58 -07:00
|
|
|
let cronTime;
|
2022-05-20 10:57:44 -07:00
|
|
|
if (schedule === '@service') {
|
2022-05-20 09:31:58 -07:00
|
|
|
cronTime = new Date(Date.now() + 2*1000); // 2 seconds from now
|
|
|
|
|
} else {
|
|
|
|
|
// random is so that all crons start at once to decrease memory pressure
|
|
|
|
|
cronTime = (constants.TEST ? '*/5 ' : `${Math.floor(60*Math.random())} `) + schedule; // time ticks faster in tests
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-19 18:19:41 +02:00
|
|
|
const cronJob = CronJob.from({
|
2022-05-20 09:31:58 -07:00
|
|
|
cronTime,
|
2021-08-25 19:41:46 -07:00
|
|
|
onTick: async () => {
|
2026-02-18 08:18:37 +01:00
|
|
|
const [taskError] = await safe(runTask(appId, taskName)); // put the app id in closure, so we don't use the outdated app object by mistake
|
2026-03-12 22:55:28 +05:30
|
|
|
if (taskError) log(`could not run task ${taskName} : ${taskError.message}`);
|
2021-08-25 19:41:46 -07:00
|
|
|
},
|
2025-01-02 10:10:40 +01:00
|
|
|
start: true,
|
|
|
|
|
timeZone: tz
|
2021-08-25 19:41:46 -07:00
|
|
|
});
|
2020-08-18 19:08:37 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
jobs[taskName] = cronJob;
|
|
|
|
|
}
|
2015-10-20 01:00:31 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
return jobs;
|
2015-10-20 01:00:31 -07:00
|
|
|
}
|
|
|
|
|
|
2025-01-02 10:10:40 +01:00
|
|
|
async function deleteAppJobs(appId, appState) {
|
2015-10-18 08:40:24 -07:00
|
|
|
assert.strictEqual(typeof appId, 'string');
|
2015-10-20 01:00:31 -07:00
|
|
|
assert.strictEqual(typeof appState, 'object');
|
2015-10-18 08:40:24 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
if (!appState) return;
|
2015-10-20 01:00:31 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
for (const taskName of Object.keys(appState.schedulerConfig)) {
|
2020-08-18 22:35:08 -07:00
|
|
|
if (appState.cronJobs && appState.cronJobs[taskName]) appState.cronJobs[taskName].stop();
|
2015-10-20 10:16:59 -07:00
|
|
|
|
2020-08-18 19:08:37 -07:00
|
|
|
const containerName = `${appId}-${taskName}`;
|
2021-08-25 19:41:46 -07:00
|
|
|
const [error] = await safe(docker.deleteContainer(containerName));
|
2026-03-12 22:55:28 +05:30
|
|
|
if (error) log(`deleteAppJobs: failed to delete task container with name ${containerName} : ${error.message}`);
|
2025-01-02 10:10:40 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function deleteJobs() {
|
|
|
|
|
for (const appId of Object.keys(gState)) {
|
2026-03-12 22:55:28 +05:30
|
|
|
log(`deleteJobs: removing jobs of ${appId}`);
|
2025-01-02 10:10:40 +01:00
|
|
|
const [error] = await safe(deleteAppJobs(appId, gState[appId]));
|
2026-03-12 22:55:28 +05:30
|
|
|
if (error) log(`deleteJobs: error stopping jobs of removed app ${appId}: ${error.message}`);
|
2025-01-02 10:10:40 +01:00
|
|
|
delete gState[appId];
|
2021-08-25 19:41:46 -07:00
|
|
|
}
|
2020-08-18 19:08:37 -07:00
|
|
|
}
|
2015-10-18 08:40:24 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
async function sync() {
|
2021-06-03 12:20:44 -07:00
|
|
|
if (constants.TEST) return;
|
|
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
const allApps = await apps.list();
|
2015-10-18 08:40:24 -07:00
|
|
|
|
2021-09-27 14:21:42 -07:00
|
|
|
const allAppIds = allApps.map(app => app.id);
|
2021-08-25 19:41:46 -07:00
|
|
|
const removedAppIds = _.difference(Object.keys(gState), allAppIds);
|
2026-03-12 22:55:28 +05:30
|
|
|
if (removedAppIds.length !== 0) log(`sync: stopping jobs of removed apps ${JSON.stringify(removedAppIds)}`);
|
2015-10-18 08:40:24 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
for (const appId of removedAppIds) {
|
2026-03-12 22:55:28 +05:30
|
|
|
log(`sync: removing jobs of ${appId}`);
|
2025-01-02 10:10:40 +01:00
|
|
|
const [error] = await safe(deleteAppJobs(appId, gState[appId]));
|
2026-03-12 22:55:28 +05:30
|
|
|
if (error) log(`sync: error stopping jobs of removed app ${appId}: ${error.message}`);
|
2022-05-20 09:38:17 -07:00
|
|
|
delete gState[appId];
|
2021-08-25 19:41:46 -07:00
|
|
|
}
|
2018-02-27 13:21:38 -08:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
for (const app of allApps) {
|
|
|
|
|
const appState = gState[app.id] || null;
|
2021-09-27 14:21:42 -07:00
|
|
|
const schedulerConfig = apps.getSchedulerConfig(app);
|
2015-10-18 08:40:24 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
if (!appState && !schedulerConfig) continue; // nothing to do
|
|
|
|
|
if (appState && appState.cronJobs) { // we had created jobs for this app previously
|
|
|
|
|
if (_.isEqual(appState.schedulerConfig, schedulerConfig) && appState.containerId === app.containerId) continue; // nothing changed
|
|
|
|
|
}
|
2020-08-18 21:15:54 -07:00
|
|
|
|
2026-03-12 22:55:28 +05:30
|
|
|
log(`sync: clearing jobs of ${app.id} (${app.fqdn})`);
|
2015-12-23 13:23:47 -08:00
|
|
|
|
2025-01-02 10:10:40 +01:00
|
|
|
const [error] = await safe(deleteAppJobs(app.id, appState));
|
2026-03-12 22:55:28 +05:30
|
|
|
if (error) log(`sync: error stopping jobs of ${app.id} : ${error.message}`);
|
2015-10-20 00:02:25 -07:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
if (!schedulerConfig) { // updated app version removed scheduler addon
|
|
|
|
|
delete gState[app.id];
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2015-11-22 21:17:17 -08:00
|
|
|
|
2024-03-12 17:54:51 +01:00
|
|
|
if (gSuspendedAppIds.has(app.id)) continue; // do not create jobs of suspended apps
|
2024-03-11 23:34:03 +01:00
|
|
|
|
2021-08-25 19:41:46 -07:00
|
|
|
const cronJobs = await createJobs(app, schedulerConfig); // if docker is down, the next sync() will recreate everything for this app
|
|
|
|
|
gState[app.id] = { containerId: app.containerId, schedulerConfig, cronJobs };
|
|
|
|
|
}
|
2015-10-18 08:40:24 -07:00
|
|
|
}
|
2026-02-14 15:43:24 +01:00
|
|
|
|
|
|
|
|
export default {
|
|
|
|
|
sync,
|
|
|
|
|
deleteJobs,
|
|
|
|
|
|
|
|
|
|
suspendAppJobs,
|
|
|
|
|
resumeAppJobs
|
|
|
|
|
};
|