-
Notifications
You must be signed in to change notification settings - Fork 2
/
base_logger.js
372 lines (324 loc) · 9.64 KB
/
base_logger.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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// © 2016-2024 Graylog, Inc.
const os = require('os');
const zlib = require('zlib');
const axios = require('axios');
const usageLoggers = require('./usage_loggers');
const DEFAULT_MAX_TRANSMIT = 128;
/**
* Basic usage logger to embed or extend.
*/
class BaseLogger {
/**
* Initialize logger.
*/
constructor(agent, options = {}) {
this._agent = agent;
this._host = BaseLogger.host_lookup();
this._queue = null;
this._url = null;
this._version = BaseLogger.version_lookup();
// read provided options
const { enabled } = options;
const enabled_exists = typeof enabled === 'boolean';
const { queue } = options;
const queue_exists = typeof queue === 'object' && Array.isArray(queue);
const url = typeof options === 'string' ? options : options.url;
const url_exists = typeof url === 'string';
// skip compression
const { skip_compression } = options;
const { skip_submission } = options;
const { max_transmit } = options;
// set options in priority order
this._enabled = !enabled_exists || (enabled_exists && enabled === true);
this._skip_compression = typeof skip_compression === 'boolean' ? skip_compression : false;
this._skip_submission = typeof skip_submission === 'boolean' ? skip_submission : false;
if (queue_exists) {
this._queue = queue;
} else if (url_exists) {
this._url = url;
} else {
this._url = usageLoggers.urlByDefault();
this._enabled = typeof this._url === 'string' && this._url.length > 0;
}
// validate url when present
if (typeof this._url === 'undefined' || (this._url !== null && !BaseLogger.valid_url(this._url))) {
this._url = null;
this._enabled = false;
}
// parse and cache url properties
if (this._url !== null) {
try {
this._url_options = {
url: this._url,
method: 'POST',
headers: {
'Content-Encoding': this._skip_compression ? 'identity' : 'deflated',
'Content-Type': 'application/json; charset=UTF-8',
'User-Agent': `Resurface/${this.version} (${this._agent})`,
},
};
} catch (e) {
this._url = null;
this._url_options = null;
this._enabled = false;
}
}
// create transmission queue
this._max_transmit = typeof max_transmit === 'number' ? max_transmit : DEFAULT_MAX_TRANSMIT;
this._transmit_queue = [];
// finalize internal properties
this._enableable = this._queue !== null || this._url !== null;
this._submit_failures = new Uint32Array(new ArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
this._submit_successes = new Uint32Array(new ArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
// mark immutable properties
Object.defineProperty(this, '_agent', {
configurable: false,
writable: false,
});
Object.defineProperty(this, '_host', {
configurable: false,
writable: false,
});
Object.defineProperty(this, '_queue', {
configurable: false,
writable: false,
});
Object.defineProperty(this, '_submit_failures', {
configurable: false,
writable: false,
});
Object.defineProperty(this, '_submit_successes', {
configurable: false,
writable: false,
});
Object.defineProperty(this, '_url', {
configurable: false,
writable: false,
});
Object.defineProperty(this, '_url_options', {
configurable: false,
writable: false,
});
Object.defineProperty(this, '_version', {
configurable: false,
writable: false,
});
Object.defineProperty(this, '_max_transmit', { configurable: false, writable: false });
}
/**
* Returns agent string identifying this logger.
*/
get agent() {
return this._agent;
}
/**
* Disable this logger.
*/
disable() {
this._enabled = false;
return this;
}
/**
* Enable this logger.
*/
enable() {
this._enabled = this._enableable;
return this;
}
/**
* Returns true if this logger can ever be enabled.
*/
get enableable() {
return this._enableable;
}
/**
* Returns true if this logger is currently enabled.
*/
get enabled() {
return this._enableable && this._enabled && usageLoggers.enabled;
}
/**
* Returns cached host identifier.
*/
get host() {
return this._host;
}
/**
* Returns high-resolution time in milliseconds.
*/
static get hrmillis() {
const [seconds, nanos] = process.hrtime();
return seconds * 1000 + nanos / 1000000;
}
/**
* Returns queue destination where messages are sent.
*/
get queue() {
return this._queue;
}
/**
* Returns true if message compression is being skipped.
*/
get skip_compression() {
return this._skip_compression;
}
/**
* Sets if message compression will be skipped.
*/
set skip_compression(value) {
this._skip_compression = value;
this._url_options.headers['Content-Encoding'] = value ? 'identity' : 'deflated';
}
/**
* Returns true if message submission is being skipped.
*/
get skip_submission() {
return this._skip_submission;
}
/**
* Sets if message submission will be skipped.
*/
set skip_submission(value) {
this._skip_submission = value;
}
/**
* Returns promise to submit JSON message to intended destination.
*/
submit(msg) {
if (msg === null || this._skip_submission || !this.enabled) {
return new Promise((resolve) => resolve(true));
}
if (this._queue !== null) {
this._queue.push(msg);
Atomics.add(this._submit_successes, 0, 1);
return new Promise((resolve) => resolve(true));
}
return new Promise((resolve, reject) => {
try {
if (this._skip_compression) {
this.hermes(msg).then(resolve(true));
} else {
zlib.deflate(msg, (err, buffer) => {
if (err != null) {
Atomics.add(this._submit_failures, 0, 1);
reject(err);
} else {
this.hermes(buffer).then(resolve(true));
}
});
}
} catch (e) {
Atomics.add(this._submit_failures, 0, 1);
resolve(true);
}
});
}
/**
* Creates promise to submit JSON message to intended destination.
*/
async hermes(message) {
while (this._transmit_queue.length >= this._max_transmit) Promise.race(this._transmit_queue);
this._transmit_queue = await Promise.all(this._transmit_queue);
const p = axios
.post(this.url, message, this._url_options)
.then((response) => {
if (response.status === 204) {
Atomics.add(this._submit_successes, 0, 1);
} else {
Atomics.add(this._submit_failures, 0, 1);
}
this._transmit_queue.splice(this._transmit_queue.indexOf(p), 1);
})
.catch(() => Atomics.add(this._submit_failures, 0, 1));
this._transmit_queue.push(p);
}
/**
* Returns count of submissions that failed.
*/
get submit_failures() {
return Atomics.load(this._submit_failures, 0);
}
/**
* Returns count of submissions that succeeded.
*/
get submit_successes() {
return Atomics.load(this._submit_successes, 0);
}
/**
* Returns url destination where messages are sent.
*/
get url() {
return this._url;
}
/**
* Checks if provided value is a valid URL string.
* Copied from https://github.com/ogt/valid-url/blob/8d1fc52b21ceab99b68f415838035859b7237949/index.js#L22
*/
static valid_url(value) {
if (!value) return false;
// check for illegal characters
if (/[^a-z0-9:/?#[\]@!$&'()*+,;=.\-_~%]/i.test(value)) return false;
// check for hex escapes that aren't complete
if (/%[^0-9a-f]/i.test(value)) return false;
if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value)) return false;
return this.check_url_fragments(value);
}
static check_url_fragments(value) {
// from RFC 3986
const splitted = value.match(/(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);
const scheme = splitted[1];
const authority = splitted[2];
const path = splitted[3];
const query = splitted[4];
const fragment = splitted[5];
// scheme and path are required, though the path can be empty
if (!(scheme && scheme.length && path.length >= 0)) return false;
// if authority is present, the path must be empty or begin with a /
if (authority && authority.length) {
if (!(path.length === 0 || /^\//.test(path))) return false;
} else if (/^\/\//.test(path)) {
// if authority is not present, the path must not start with //
return false;
}
// scheme must begin with a letter, then consist of letters, digits, +, ., or -
if (!/^[a-z][a-z0-9+\-.]*$/.test(scheme.toLowerCase())) return false;
return this.assemble_url(scheme, authority, query, fragment, path);
}
static assemble_url(scheme, authority, query, fragment, path) {
let out = '';
// re-assemble the URL per section 5.3 in RFC 3986
out += `${scheme}:`;
if (authority && authority.length) {
out += `//${authority}`;
}
out += path;
if (query && query.length) out += `?${query}`;
if (fragment && fragment.length) out += `#${fragment}`;
return out;
}
/**
* Returns cached version number.
*/
get version() {
return this._version;
}
/**
* Retrieves host identifier.
*/
static host_lookup() {
const dyno = process.env.DYNO;
if (typeof dyno !== 'undefined') return dyno;
try {
return os.hostname();
} catch (e) {
return 'unknown';
}
}
/**
* Retrieves version number from package file.
*/
static version_lookup() {
return require('../package.json').version;
}
}
module.exports = BaseLogger;