/
index.js
222 lines (185 loc) · 5.72 KB
/
index.js
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*!
* firebase-cron <https://github.com/doowb/firebase-cron>
*
* Copyright (c) 2015-2018, Brian Woodward.
* Released under the MIT License.
*/
'use strict';
const moment = require('moment');
const parser = require('cron-parser');
/**
* Main `Cron` class for creating a new instance to manage cron jobs.
*
* ```js
* const Firebase = require('firebase');
* const ref = new Firebase('https://{your-firebase}.firebaseio.com');
* const queueRef = new Firebase('https://{your-firebase}.firebaseio.com/queue');
* const options = {endpoint: 'jobs'};
*
* const cron = new Cron(ref, queueRef, options);
* ```
*
* @param {Object} `ref` Instance of a [firebase][] reference pointing to the root of a [firebase][].
* @param {Object} `queue` Instance of a [firebase][] refernece pointing to a [firebase-queue][].
* @param {Object} `options` Options specifying where the cron jobs are stored.
* @param {String} `options.endpoint` Specific endpoint relative to the `ref` where the cron jobs are stored (defaults to `jobs`).
* @param {Number} `options.interval` Optional interval in milliseconds to use when calling `.run` (defaults to 1000).
* @api public
*/
function Cron(ref, queue, options) {
if (!(this instanceof Cron)) {
return new Cron(ref, queue, options);
}
this.options = Object.assign({
interval: 1000,
endpoint: 'jobs'
}, options);
if (!ref) {
throw new Error('expected `ref` to be a firebase reference.');
}
if (!queue) {
throw new Error('expected `queue` to be a firebase queue reference.');
}
this.root = ref;
this.queue = queue;
let offset = 0;
let remoteDate = null;
this.remoteDate = () => Date.now() + offset;
this.ref = this.root.child(this.options.endpoint);
this.root.child('/.info/serverTimeOffset').on('value', function(snapshot) {
offset = snapshot.val() || 0;
});
}
/**
* Add a new cron job.
*
* @param {String} `name` Name of the cron job.
* @param {String} `pattern` Cron job pattern. See [cron job patterns](http://crontab.org/) for specifics.
* @param {Object} `data` Data to be pushed onto the [firebase-queue][] when job is run.
* @returns {Promise} Returns a promise that is resolved when the job has been updated.
* @api public
*/
Cron.prototype.addJob = function(name, pattern, data) {
const schedule = parser.parseExpression(pattern, {currentDate: this.remoteDate()});
const job = {
pattern: pattern,
nextRun: +schedule.next().toDate(),
data: data
};
return this.ref.child(name).update(job);
};
/**
* Update a cron job.
*
* @param {String} `name` Name of the cron job.
* @param {String} `pattern` Cron job pattern. See [cron job patterns](http://crontab.org/) for specifics.
* @param {Object} `data` Data to be pushed onto the [firebase-queue][] when job is run.
* @returns {Promise} Returns a promise that is resolved when the job has been added.
* @api public
*/
Cron.prototype.updateJob = function(name, pattern, data) {
const schedule = parser.parseExpression(pattern, {currentDate: this.remoteDate()});
const job = {
pattern: pattern,
nextRun: +schedule.next().toDate(),
data: data
};
return this.ref.child(name).update(job);
};
/**
* Remove a cron job.
*
* @param {String} `name` Name of the cron job.
* @returns {Promise} Returns a promise that is resolved when the job has been removed.
* @api public
*/
Cron.prototype.deleteJob = function(name) {
return this.ref.child(name).remove();
};
/**
* Get a cron job.
*
* @param {String} `name` Name of the cron job.
* @returns {Promise} Returns a promise that is resolved with the job.
* @api public
*/
Cron.prototype.getJob = function(name) {
return this.ref.child(name).once('value')
.then(snap => snap.val());
};
/**
* Get all of the cron jobs.
*
* @returns {Promise} Returns a promise that is resolved with all of the jobs.
* @api public
*/
Cron.prototype.getJobs = function() {
return this.ref.once('value')
.then(snap => snap.val());
};
/**
* Get all of the scheduled/waiting jobs.
*
* @returns {Promise} Returns a promise that is resolved with the waiting jobs.
* @api public
*/
Cron.prototype.waitingJobs = function() {
const now = this.remoteDate();
return this.ref.orderByChild('nextRun').endAt(now).once('value')
.then(snap => snap.val());
};
/**
* Start running the cron manager.
*
* @param {Function} `cb` Callback function that is called each time manager checks for jobs to run.
* @param {Function} `error` Callback function that is called if an error occurrs.
* @api public
*/
Cron.prototype.run = function(cb, error) {
const self = this;
const interval = this.options.interval;
let id = null;
let running = true;
function stop() {
if (id) clearTimeout(id);
id = null;
};
function handleChanges(snapshot) {
if (!running) return;
const done = function(err) {
stop();
if (err) return error(err);
id = setTimeout(() => execute().then(done).catch(done), interval);
};
stop();
execute().then(done).catch(done);
}
function removeHandler() {
self.ref.off('value', handleChanges);
}
async function execute() {
const jobs = await self.waitingJobs();
cb(jobs);
if (!jobs) return;
for (const name in jobs) {
const job = jobs[name];
const lastRun = new Date(job.nextRun);
lastRun.setSeconds(lastRun.getSeconds() + 1);
const schedule = parser.parseExpression(job.pattern, {currentDate: lastRun});
job.nextRun = +schedule.next().toDate();
job.lastRun = +moment(lastRun);
await self.queue.child('tasks').push(job.data);
}
await self.ref.update(jobs);
}
this.ref.on('value', handleChanges);
return function() {
running = false;
removeHandler();
stop();
};
};
/**
* Exposes `Cron`
*/
module.exports = Cron;