145 lines
4.3 KiB
TypeScript
145 lines
4.3 KiB
TypeScript
import { Cron } from 'croner';
|
|
import type { JobDefinition, JobEvent } from './definition.ts';
|
|
|
|
export type Executor = (job: JobDefinition, signal: AbortSignal) => Promise<void>;
|
|
|
|
export type SchedulerOptions = {
|
|
log: (message: string) => void;
|
|
/** Receives "then" targets this scheduler does not run itself, for example builtin jobs of another app. */
|
|
triggerOther?: (id: string) => void;
|
|
};
|
|
|
|
export class JobTimeoutError extends Error {}
|
|
export class JobCancelledError extends Error {}
|
|
|
|
type Run = { controller: AbortController; done: Promise<void> };
|
|
|
|
/**
|
|
* Runs jobs on their schedules and events. Without parallel, a new trigger
|
|
* cancels a running run and starts over once it has stopped; triggers that
|
|
* arrive meanwhile collapse into that one restart.
|
|
*/
|
|
export class Scheduler
|
|
{
|
|
private readonly jobs: Map<string, JobDefinition>;
|
|
private readonly executor: Executor;
|
|
private readonly options: SchedulerOptions;
|
|
private readonly runs = new Map<string, Set<Run>>();
|
|
private readonly restarting = new Set<string>();
|
|
private readonly stoppers: (() => void)[] = [];
|
|
private stopped = false;
|
|
|
|
constructor(jobs: JobDefinition[], executor: Executor, options: SchedulerOptions)
|
|
{
|
|
this.jobs = new Map(jobs.map((job) => [job.id, job]));
|
|
this.executor = executor;
|
|
this.options = options;
|
|
}
|
|
|
|
start(): void
|
|
{
|
|
for (const job of this.jobs.values())
|
|
{
|
|
if (!job.enabled) continue;
|
|
|
|
if (job.every !== undefined)
|
|
{
|
|
const timer = setInterval(() => this.trigger(job.id), job.every);
|
|
this.stoppers.push(() => clearInterval(timer));
|
|
}
|
|
|
|
if (job.cron !== undefined)
|
|
{
|
|
const cron = new Cron(job.cron, () => { this.trigger(job.id); });
|
|
this.stoppers.push(() => cron.stop());
|
|
}
|
|
|
|
if (job.on.includes('start')) this.trigger(job.id);
|
|
}
|
|
}
|
|
|
|
/** Triggers every enabled job that listens to the event. */
|
|
emit(event: JobEvent): void {
|
|
for (const job of this.jobs.values()) if (job.on.includes(event)) this.trigger(job.id);
|
|
}
|
|
|
|
/** Starts a job. Returns false for unknown or disabled jobs. */
|
|
trigger(id: string): boolean
|
|
{
|
|
const job = this.jobs.get(id);
|
|
if (!job || !job.enabled || this.stopped) return false;
|
|
|
|
const runs = this.runs.get(id);
|
|
if (job.parallel || !runs || runs.size === 0)
|
|
{
|
|
this.launch(job);
|
|
return true;
|
|
}
|
|
|
|
if (this.restarting.has(id)) return true;
|
|
this.restarting.add(id);
|
|
|
|
for (const run of runs) run.controller.abort(new JobCancelledError('restarted by a new trigger'));
|
|
void Promise.allSettled([...runs].map((run) => run.done)).then(() =>
|
|
{
|
|
this.restarting.delete(id);
|
|
if (!this.stopped) this.launch(job);
|
|
});
|
|
return true;
|
|
}
|
|
|
|
/** Cancels all runs of a job. Returns whether anything was running. */
|
|
cancel(id: string): boolean
|
|
{
|
|
const runs = this.runs.get(id);
|
|
if (!runs || runs.size === 0) return false;
|
|
|
|
for (const run of runs) run.controller.abort(new JobCancelledError('cancelled'));
|
|
return true;
|
|
}
|
|
|
|
running(): string[] {
|
|
return [...this.runs].filter(([, runs]) => runs.size > 0).map(([id]) => id);
|
|
}
|
|
|
|
stop(): void
|
|
{
|
|
this.stopped = true;
|
|
for (const stop of this.stoppers) stop();
|
|
for (const id of this.runs.keys()) this.cancel(id);
|
|
}
|
|
|
|
private launch(job: JobDefinition): void
|
|
{
|
|
const controller = new AbortController();
|
|
const timer = setTimeout(() => controller.abort(new JobTimeoutError(`timed out after ${job.timeout} ms`)), job.timeout);
|
|
|
|
const runs = this.runs.get(job.id) ?? new Set<Run>();
|
|
this.runs.set(job.id, runs);
|
|
|
|
const run: Run = { controller, done: Promise.resolve() };
|
|
run.done = this.executor(job, controller.signal)
|
|
.then(() =>
|
|
{
|
|
for (const next of job.then)
|
|
{
|
|
if (this.jobs.has(next)) this.trigger(next);
|
|
else if (this.options.triggerOther) this.options.triggerOther(next);
|
|
}
|
|
})
|
|
.catch((error: unknown) =>
|
|
{
|
|
const reason = controller.signal.aborted ? controller.signal.reason : error;
|
|
if (reason instanceof JobCancelledError) return;
|
|
this.options.log(`job "${job.id}" failed: ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
})
|
|
.finally(() =>
|
|
{
|
|
clearTimeout(timer);
|
|
runs.delete(run);
|
|
});
|
|
|
|
runs.add(run);
|
|
}
|
|
}
|