1
0
silverbullet/plugos/hooks/cron.ts

79 lines
2.1 KiB
TypeScript
Raw Normal View History

import { Hook, Manifest } from "../types.ts";
import { Cron } from "https://cdn.jsdelivr.net/gh/hexagon/croner@4/src/croner.js";
import { safeRun } from "../util.ts";
import { System } from "../system.ts";
2022-03-23 14:41:12 +00:00
export type CronHookT = {
2022-03-27 09:26:13 +00:00
cron?: string | string[];
2022-03-23 14:41:12 +00:00
};
export class CronHook implements Hook<CronHookT> {
apply(system: System<CronHookT>): void {
let tasks: Cron[] = [];
2022-03-23 14:41:12 +00:00
system.on({
2022-04-26 17:04:36 +00:00
plugLoaded: () => {
2022-03-23 14:41:12 +00:00
reloadCrons();
},
2022-04-26 17:04:36 +00:00
plugUnloaded() {
2022-03-23 14:41:12 +00:00
reloadCrons();
},
});
reloadCrons();
function reloadCrons() {
tasks.forEach((task) => task.stop());
tasks = [];
2022-10-15 17:02:56 +00:00
for (const 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,
)
) {
2022-03-27 09:26:13 +00:00
if (!functionDef.cron) {
continue;
}
const crons = Array.isArray(functionDef.cron)
? functionDef.cron
: [functionDef.cron];
for (const cronDef of crons) {
2022-03-23 14:41:12 +00:00
tasks.push(
new Cron(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);
}
});
}),
2022-03-23 14:41:12 +00:00
);
}
}
}
}
}
validateManifest(manifest: Manifest<CronHookT>): string[] {
2022-10-15 17:02:56 +00:00
const errors: string[] = [];
for (const functionDef of Object.values(manifest.functions)) {
2022-03-27 09:26:13 +00:00
if (!functionDef.cron) {
continue;
}
const crons = Array.isArray(functionDef.cron)
? functionDef.cron
: [functionDef.cron];
2022-10-15 17:02:56 +00:00
for (const _cronDef of crons) {
// if (!cron.validate(cronDef)) {
// errors.push(`Invalid cron expression ${cronDef}`);
// }
2022-03-23 14:41:12 +00:00
}
}
return errors;
}
}