-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdirWatch.js
160 lines (149 loc) · 5.57 KB
/
dirWatch.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
/*
© 2023–2024 CVS Health and/or one of its affiliates. All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
dirWatch.js
Module for watching a directory for jobs.
*/
// ########## IMPORTS
// Module to keep secrets.
require('dotenv').config();
// Module to read and write files.
const fs = require('fs/promises');
// Module to perform jobs.
const {doJob} = require('./run');
// Module to get dates from time stamps.
const {dateOf} = require('./procs/dateOf');
// ########## CONSTANTS
const jobDir = process.env.JOBDIR;
const reportDir = process.env.REPORTDIR;
// ########## FUNCTIONS
// Returns a string representing the date and time.
const nowString = () => (new Date()).toISOString().slice(2, 16);
// Writes a directory report.
const writeDirReport = async report => {
const jobID = report && report.id;
if (jobID) {
try {
const reportJSON = JSON.stringify(report, null, 2);
const reportName = `${jobID}.json`;
const rawDir = `${reportDir}/raw`;
await fs.mkdir(rawDir, {recursive: true});
await fs.writeFile(`${rawDir}/${reportName}`, `${reportJSON}\n`);
console.log(`Report ${jobID} saved in ${rawDir}`);
}
catch(error) {
console.log(`ERROR: Failed to save report ${jobID} in ${rawDir} (${error.message})`);
}
}
else {
console.log('ERROR: Job has no ID');
}
};
// Archives a job.
const archiveJob = async (job, isFile) => {
// Save the job in the done subdirectory.
const {id} = job;
const jobJSON = JSON.stringify(job, null, 2);
const doneDir = `${jobDir}/done`;
await fs.mkdir(doneDir, {recursive: true});
await fs.writeFile(`${doneDir}/${id}.json`, `${jobJSON}\n`);
// If the job had been saved as a file in the todo subdirectory:
if (isFile) {
// Delete the file.
await fs.rm(`${jobDir}/todo/${id}.json`);
}
console.log(`Job ${id} archived in ${doneDir} (${nowString()})`);
};
// Waits.
const wait = ms => {
return new Promise(resolve => {
setTimeout(() => {
resolve('');
}, ms);
});
};
/*
Checks for a directory job and, when found, performs and reports it.
Arguments:
0. Whether to continue watching after a job is run.
1: interval in seconds from a no-job check to the next check.
*/
exports.dirWatch = async (isForever, intervalInSeconds) => {
intervalInSeconds ||= 5;
intervalInSeconds = Math.max(intervalInSeconds, 5);
console.log(`Starting to watch directory ${jobDir}/todo for jobs`);
let notYetRun = true;
// As long as watching as to continue:
while (isForever || notYetRun) {
try {
// If there are any jobs in the watched directory:
const toDoFileNames = await fs.readdir(`${jobDir}/todo`);
const jobFileNames = toDoFileNames.filter(fileName => fileName.endsWith('.json'));
if (jobFileNames.length) {
// If the first one is ready to do:
const firstJobTimeStamp = jobFileNames[0].replace(/-.+$/, '');
if (Date.now() > dateOf(firstJobTimeStamp)) {
// Get it.
const jobJSON = await fs.readFile(`${jobDir}/todo/${jobFileNames[0]}`, 'utf8');
try {
const job = JSON.parse(jobJSON);
let report = JSON.parse(jobJSON);
// Ensure it has no server properties.
job.observe = false;
report.observe = false;
const {id} = job;
console.log(`\n\nDirectory job ${id} ready to do (${nowString()})`);
// Perform it and get a report.
report = await doJob(report);
console.log(`Job ${id} finished (${nowString()})`);
// Save the report.
await writeDirReport(report);
// Archive the job.
await archiveJob(job, true);
}
catch(error) {
console.log(`ERROR processing directory job (${error.message})`);
}
notYetRun = false;
}
// Otherwise, i.e. if the first one is not yet ready to do:
else {
// Report this.
console.log(`All jobs in ${jobDir} not yet ready to do (${nowString()})`);
// Wait for the specified interval.
await wait(1000 * intervalInSeconds);
}
}
// Otherwise, i.e. if there are no jobs in the watched directory:
else {
console.log(`No job in ${jobDir} (${nowString()})`);
// Wait for the specified interval.
await wait(1000 * intervalInSeconds);
}
}
// If a fatal error was thrown:
catch(error) {
// Report this.
console.log(`ERROR: Directory watching failed (${error.message}); watching aborted`);
// Quit watching.
break;
}
}
};