-
Notifications
You must be signed in to change notification settings - Fork 55
/
scheduler.ts
162 lines (138 loc) · 4.77 KB
/
scheduler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import humanInterval from "human-interval";
import fetch from "node-fetch";
import { getPrettyTime } from "./shared/utils/date";
class TaskDef {
name: string;
function: () => Promise<void>;
interval: number;
runAtStart: boolean;
runningPromise: Promise<void> = null;
successfulRunCount: number = 0;
failedRunCount: number = 0;
latestError: string | Error = null;
healthchecksConfig?: HealthchecksConfig;
get runCount() {
return this.successfulRunCount + this.failedRunCount;
}
constructor(name: string, fn: () => Promise<void>, interval: number, runAtStart?: boolean, healthchecksConfig?: HealthchecksConfig) {
if (healthchecksConfig && !healthchecksConfig.id) {
console.warn("Healthchecks config provided without an id.");
}
this.name = name;
this.function = fn;
this.interval = interval;
this.runAtStart = runAtStart;
this.healthchecksConfig = healthchecksConfig?.id ? healthchecksConfig : null;
}
}
interface SchedulerConfig {
errorHandler?: (task: TaskDef, error: Error) => void;
healthchecksEnabled?: boolean;
}
interface HealthchecksConfig {
id: string;
measureDuration?: boolean;
}
export class Scheduler {
private tasks: Map<string, TaskDef> = new Map();
private config: SchedulerConfig = {};
constructor(config?: SchedulerConfig) {
this.config = {
...config,
errorHandler: config?.errorHandler || ((task, err) => console.error(`Task "${task.name}" failed: ${err}`))
};
}
public registerTask(
name: string,
fn: () => Promise<void>,
interval: number | string,
runAtStart: boolean = true,
healthchecksConfig?: HealthchecksConfig
): void {
if (this.tasks.has(name)) {
throw new Error(`Task with name "${name}" already exists`);
}
if (typeof interval === "string" && isNaN(humanInterval(interval))) {
throw new Error(`Invalid interval "${interval}"`);
}
const intervalMs = typeof interval === "string" ? humanInterval(interval) : interval;
console.log(`Registered task "${name}" to run every ${getPrettyTime(intervalMs)}`);
this.tasks.set(name, new TaskDef(name, fn, intervalMs, runAtStart, healthchecksConfig));
}
public start(): void {
for (const task of this.tasks.values()) {
if (task.runAtStart) {
this.runTask(task);
}
setInterval(() => {
const runningTask = this.tasks.get(task.name);
if (runningTask.runningPromise) {
console.log(`Skipping task "${task.name}" because it is already running`);
return;
}
console.log(`Starting task "${task.name}"`);
this.runTask(runningTask);
}, task.interval);
}
}
private runTask(runningTask: TaskDef): void {
let pingStartPromise = Promise.resolve();
if (this.config.healthchecksEnabled && runningTask.healthchecksConfig?.measureDuration) {
pingStartPromise = this.healthchecksPingStart(runningTask);
}
runningTask.runningPromise = runningTask
.function()
.then(() => {
console.log(`Task "${runningTask.name}" completed successfully`);
runningTask.successfulRunCount++;
if (this.config.healthchecksEnabled && runningTask.healthchecksConfig) {
pingStartPromise.finally(() => this.healthchecksPingSuccess(runningTask));
}
})
.catch(err => {
runningTask.failedRunCount++;
runningTask.latestError = err;
this.config.errorHandler(runningTask, err);
if (this.config.healthchecksEnabled && runningTask.healthchecksConfig) {
pingStartPromise.finally(() => this.healthchecksPingFailure(runningTask));
}
})
.finally(() => {
runningTask.runningPromise = null;
});
}
async healthchecksPingStart(runningTask: TaskDef): Promise<void> {
try {
await fetch(`https://hc-ping.com/${runningTask.healthchecksConfig.id}/start`);
} catch (err) {
console.error(err);
}
}
async healthchecksPingSuccess(runningTask: TaskDef): Promise<void> {
try {
await fetch(`https://hc-ping.com/${runningTask.healthchecksConfig.id}`);
} catch (err) {
console.error(err);
}
}
async healthchecksPingFailure(runningTask: TaskDef): Promise<void> {
try {
await fetch(`https://hc-ping.com/${runningTask.healthchecksConfig.id}/fail`);
} catch (err) {
console.error(err);
}
}
public getTasksStatus() {
return Array.from(this.tasks.values()).map(task => ({
name: task.name,
isRunning: !!task.runningPromise,
function: task.function,
interval: getPrettyTime(task.interval),
runCount: task.runCount,
successfulRunCount: task.successfulRunCount,
failedRunCount: task.failedRunCount,
latestError: task.latestError || null,
healthchecksConfig: !!task.healthchecksConfig
}));
}
}