forked from openaq/openaq-fetch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.js
More file actions
298 lines (258 loc) · 9.08 KB
/
errors.js
File metadata and controls
298 lines (258 loc) · 9.08 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//import { DataStream } from 'scramjet';
import sj from 'scramjet';
const { DataStream } = sj;
import log from './logger.js';
import { publish } from './notification.js';
// Symbol exports
export const MEASUREMENT_ERROR = Symbol('Measurement error');
export const MEASUREMENT_INVALID = Symbol('Measurement invalid');
export const ADAPTER_MODULE_INVALID = Symbol('Adapter module invalid');
export const ADAPTER_RESOLVE_ERROR = Symbol('Adapters resolving error');
export const ADAPTER_ERROR = Symbol('Adapter error');
export const ADAPTER_NOT_FOUND = Symbol('Adapter not found');
export const ADAPTER_NAME_INVALID = Symbol('Adapter name invalid');
export const DATA_URL_ERROR = Symbol('Source data url error');
export const DATA_PARSE_ERROR = Symbol('Source data parsing error');
export const AUTHENTICATION_ERROR = Symbol('User could not be authenticated');
export const FETCHER_ERROR = Symbol('Unknown fetcher error');
export const STREAM_END = Symbol('End stream');
const typeName = (symbol) => symbol.toString().substring(7, symbol.toString().length - 1);
/**
* An error type used to report adapter runtime
*
* Throwing this error means that the adapter will not output any additional data.
* Any other error class will be automatically wrapped in this also.
*/
export class AdapterError extends Error {
/**
* @param {Symbol} symbol error symbol
* @param {Source} source source on which the error occurred
* @param {Error} [cause] an underlying error to be included in stack
* @param {number} [exitCode] an exit code to return
*/
constructor (symbol, source, cause, exitCode = 100) {
const _typeName = typeName(symbol);
let msg = _typeName + (source ? ` (${source.file}/${source.adapter}/'${source.name}')` : '');
if (cause && cause.message) {
msg += ': ' + cause.message;
}
super(msg);
this.source = source;
this.type = symbol;
this.typeName = _typeName;
this.cause = cause;
this.exitCode = exitCode;
const stack = this.stack;
Object.defineProperty(this, 'stack', {
get: function () {
let err = stack;
if (this.cause && this.cause.stack) {
err += `\n -- caused by --\n${this.cause.stack}`;
}
return err;
}
});
this.constructor = AdapterError;
this.__proto__ = AdapterError.prototype; // eslint-disable-line
}
is (symbol) {
return this.type === symbol;
}
}
/**
* An error type used to report a failure of part of the fetch process.
*/
export class FetchError extends Error {
/**
* @param {Symbol} symbol error symbol
* @param {Source} source source on which the error occurred
* @param {Error} [cause] an underlying error to be included in stack
* @param {number} [extraMessage] some friendly message
*/
constructor (symbol, source, cause, extraMessage = '') {
const _typeName = typeName(symbol);
super(extraMessage || '');
this.source = source;
this.type = symbol;
this.typeName = _typeName;
this.cause = cause;
this.extraMessage = extraMessage;
const stack = this.stack;
Object.defineProperty(this, 'stack', {
get: function () {
let err = stack;
if (this.cause && this.cause.stack) {
err += `\n -- caused by --\n${this.cause.stack}`;
}
return err;
}
});
this.constructor = FetchError;
this.__proto__ = FetchError.prototype; // eslint-disable-line
}
is (symbol) {
return this.type === symbol;
}
}
/**
* An error type to report validation error on a single measurement.
*/
export class MeasurementValidationError extends FetchError {
/**
*
* @param {Source} source
* @param {String|JSONSchemaValidation} message
* @param {Measurement} instance
*/
constructor (source, message, instance) {
super(MEASUREMENT_INVALID, source, null);
if (typeof message === 'string') {
this.validation = {errors: [{
message,
instance,
toString () { return message; }
}]};
this.message += message;
} else {
this.validation = message;
}
this.constructor = MeasurementValidationError;
this.__proto__ = MeasurementValidationError.prototype; // eslint-disable-line
}
}
/**
* Forwards errors to parent stream
*
* @param {DataStream} stream measurements stream from one of the adapters
* @param {DataStream} parent parent stream
* @param {OpenAQEnv} env
*/
export function forwardErrors (stream, parentStream, sourceObject, failures, strict) {
return stream.catch(async (error) => {
if (strict) {
try { await parentStream.raise(error); } finally {}
} else {
log.warn(`Ignoring error in "${sourceObject.name}": ${error.message}`);
failures[error.message] = (failures[error.message] || 0) + 1;
}
return DataStream.filter;
});
}
/**
* Handles measurement errors by pushing the output to an cause log and resolving it if the cause is resolvable.
*
* @param {DataStream} stream
* @param {Object} failures
* @param {Source} source
*/
export function handleMeasurementErrors (stream, failures, source) {
return stream
.catch(({cause}) => {
if (cause instanceof FetchError) {
if (cause.exitCode) {
throw cause;
} else if (cause.validation && cause.validation.errors) {
cause.validation.errors.forEach(cause => {
log.warn(`Validation error in "${source && source.name}":`, cause.message, cause.instance);
failures[cause] = (failures[cause] || 0) + 1;
});
} else {
const message = `${cause.typeName}: ${cause.extraMessage || (cause.cause && cause.cause.message) || cause.message || 'Unknown'}`;
log.verbose(message);
failures[message] = (failures[message] || 0) + 1;
}
return DataStream.filter;
} else if (cause instanceof AdapterError) {
throw cause;
}
throw new AdapterError(ADAPTER_ERROR, source, cause, 0);
});
}
export async function handleWarnings (list, strict) {
if (strict) {
const e = await new Promise(resolve => process.on('warning', e => list.includes(e.name) && resolve(e)));
throw e;
} else {
return new Promise(() => 0); // never resolve
}
}
export async function handleUnresolvedPromises (strict) {
if (strict) {
const e = await new Promise(resolve => process.on('unhandledRejection', e => resolve(e)));
log.debug('Unresolved promise, exiting.');
throw e;
} else {
return new Promise(() => 0); // never resolve
}
}
export function handleFetchErrors () {
return (error) => {
const cause = error instanceof FetchError ? error : error.cause;
if (cause instanceof FetchError) {
if (cause.is(STREAM_END)) return cause.exitCode || 0;
log.error('Fetch error occurred', cause.stack);
} else if (cause instanceof AdapterError) {
log.error(`Adapter error occurred: ${error.message}`, cause.stack);
} else {
log.error(`Runtime error occurred in ${error.stream && error.stream.name}: ${error.stack}`);
}
return (cause && cause.exitCode) || 199;
};
}
export function rejectOnTimeout (timeout, value) {
return new Promise((resolve, reject) => setTimeout(() => reject(value), timeout));
}
export function resolveOnTimeout (timeout, value) {
return new Promise((resolve) => setTimeout(() => resolve(value), timeout));
}
async function publishAfterError(runningSources, fetchReport, env) {
const unfinished = [];
Object.entries(runningSources).forEach(([key, status]) => {
if(status != 'filtered' && !fetchReport.results[key]) {
fetchReport.results[key] = {
message: 'not finished',
count: 0,
locations: 0,
sourceName: key,
}
unfinished.push(key)
}
});
if (!env.dryrun) {
await publish(fetchReport.results, 'fetcher/success');
} else {
Object.values(fetchReport.results)
.filter(r =>r.parameters)
.map( r => log.info(`${r.locations} locations from ${r.from} - ${r.to} | Parameters for ${r.sourceName}`, r.parameters));
}
log.warn(`Still running sources at interruption: [${unfinished}]`);
}
export async function handleSigInt (runningSources, fetchReport, env) {
await (new Promise((resolve) => process.once('SIGINT', () => resolve())));
await publishAfterError(runningSources, fetchReport, env);
throw new Error('Process interruped');
}
export async function handleProcessTimeout (processTimeout, runningSources, fetchReport, env) {
await resolveOnTimeout(processTimeout);
await publishAfterError(runningSources, fetchReport, env);
throw new Error('Process timed out');
}
const cleanups = [];
export async function cleanup () {
for (let operation of cleanups) {
try {
log.debug(`Executing cleanup ${operation._name}`);
await operation();
log.debug(`Cleanup ${operation._name} completed`);
} catch (e) {
log.warn(`Exception "${e.message}" occured during cleanup "${operation._name}"`);
}
}
}
export async function ignore () {
console.log('ignoring', this);
}
cleanup.add = (operation) => {
operation._name = operation.name || (new Error().stack).split('\n')[2].replace(/^.*?at ([^\s]+)\s\(.*\/([^/]+)\).*$/, '$1 ($2)');
cleanups.push(operation);
};