2022-03-23 14:41:12 +00:00
|
|
|
import { Feature, Manifest } from "../types";
|
|
|
|
import cron, { ScheduledTask } from "node-cron";
|
|
|
|
import { safeRun } from "../util";
|
|
|
|
import { System } from "../system";
|
|
|
|
|
|
|
|
export type CronHook = {
|
2022-03-27 09:26:13 +00:00
|
|
|
cron?: string | string[];
|
2022-03-23 14:41:12 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export class NodeCronFeature implements Feature<CronHook> {
|
|
|
|
apply(system: System<CronHook>): void {
|
|
|
|
let tasks: ScheduledTask[] = [];
|
|
|
|
system.on({
|
|
|
|
plugLoaded: (name, plug) => {
|
|
|
|
reloadCrons();
|
|
|
|
},
|
|
|
|
plugUnloaded(name, plug) {
|
|
|
|
reloadCrons();
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
reloadCrons();
|
|
|
|
|
|
|
|
function reloadCrons() {
|
|
|
|
tasks.forEach((task) => task.stop());
|
|
|
|
tasks = [];
|
|
|
|
for (let plug of system.loadedPlugs.values()) {
|
2022-03-27 09:26:13 +00:00
|
|
|
if (!plug.manifest) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
for (const [name, functionDef] of Object.entries(
|
|
|
|
plug.manifest.functions
|
|
|
|
)) {
|
|
|
|
if (!functionDef.cron) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
const crons = Array.isArray(functionDef.cron)
|
|
|
|
? functionDef.cron
|
|
|
|
: [functionDef.cron];
|
2022-03-23 14:41:12 +00:00
|
|
|
for (let cronDef of crons) {
|
|
|
|
tasks.push(
|
2022-03-27 09:26:13 +00:00
|
|
|
cron.schedule(cronDef, () => {
|
|
|
|
console.log("Now acting on cron", cronDef);
|
2022-03-23 14:41:12 +00:00
|
|
|
safeRun(async () => {
|
|
|
|
try {
|
2022-03-27 09:26:13 +00:00
|
|
|
await plug.invoke(name, [cronDef]);
|
2022-03-23 14:41:12 +00:00
|
|
|
} catch (e: any) {
|
|
|
|
console.error("Execution of cron function failed", e);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
validateManifest(manifest: Manifest<CronHook>): string[] {
|
|
|
|
let errors = [];
|
2022-03-27 09:26:13 +00:00
|
|
|
for (const [name, functionDef] of Object.entries(manifest.functions)) {
|
|
|
|
if (!functionDef.cron) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
const crons = Array.isArray(functionDef.cron)
|
|
|
|
? functionDef.cron
|
|
|
|
: [functionDef.cron];
|
2022-03-23 14:41:12 +00:00
|
|
|
for (let cronDef of crons) {
|
2022-03-27 09:26:13 +00:00
|
|
|
if (!cron.validate(cronDef)) {
|
|
|
|
errors.push(`Invalid cron expression ${cronDef}`);
|
2022-03-23 14:41:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return errors;
|
|
|
|
}
|
|
|
|
}
|