forked from exceptionless/Exceptionless.JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexceptionless.ts
More file actions
606 lines (505 loc) · 18.5 KB
/
exceptionless.ts
File metadata and controls
606 lines (505 loc) · 18.5 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
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
/// <reference path="typings/tsd.d.ts" />
// TODO: We'll need a poly fill for promises.
module Exceptionless {
export class ExceptionlessClient {
public config:Configuration;
constructor(apiKey:string, serverUrl?:string) {
this.config = new Configuration(apiKey, serverUrl);
}
public register(handler: () => void) {}
//log(source:string, message:string, level?:string) {
// if (!source) {
// source = (<any>(arguments.callee.caller)).name;
// }
//
// var event:IEvent = { type: 'log', source: source, message: message };
// if (level) {
// event.data['@level'] = level;
// }
//
// this.submit(event);
//}
//
//feature(feature:string) {
// if (feature) {
// this.submit({type: 'usage', source: feature});
// }
//}
//
//error(exception:Error) {
// // TODO:
//}
submit(event:IEvent, pluginContextData?:IContextData) {
if (!this.config.enabled) {
this.config.log.info('Event submission is currently disabled');
return;
}
this.config.queue.enqueue(event);
}
}
export class Configuration {
apiKey:string;
serverUrl:string;
enabled = true;
log:ILog = new NullLog();
submissionBatchSize = 50;
submissionClient:ISubmissionClient = new SubmissionClient();
storage:IStorage<any> = new InMemoryStorage<any>();
queue:IEventQueue;
constructor(apiKey:string, serverUrl?:string) {
this.setApiKey(apiKey);
this.serverUrl = serverUrl || 'https://collector.exceptionless.io';
this.queue = new EventQueue(this);
}
public setApiKey(apiKey:string) {
this.apiKey = apiKey;
this.enabled = !!apiKey;
}
public getQueueName(): string {
return !!this.apiKey ? 'ex-' + this.apiKey.slice(0, 8) : null;
}
}
export interface ILog {
info(message:string);
warn(message:string);
error(message:string);
}
export class NullLog implements ILog {
public info(message) {}
public warn(message) {}
public error(message) {}
}
export class ConsoleLog implements ILog {
public info(message) {
console.log('[INFO] Exceptionless:' + message)
}
public warn(message) {
console.log('[Warn] Exceptionless:' + message)
}
public error(message) {
console.log('[Error] Exceptionless:' + message)
}
}
export interface IEventQueue {
enqueue(event:IEvent);
process();
suspendProcessing(durationInMinutes?:number, discardFutureQueuedItems?:boolean, clearQueue?:boolean);
}
export class EventQueue implements IEventQueue {
private _config:Configuration;
private _areQueuedItemsDiscarded = false;
private _suspendProcessingUntil:Date;
private _discardQueuedItemsUntil:Date;
private _processingQueue = false;
private _queueTimer = setInterval(() => this.onProcessQueue(), 10000);
constructor(config:Configuration) {
this._config = config;
}
public enqueue(event:IEvent) {
if (this.areQueuedItemsDiscarded()) {
this._config.log.info('Queue items are currently being discarded. The event will not be queued.');
return;
}
var key = this.queuePath() + '-' + new Date().toJSON() + '-' + Math.floor(Math.random() * 9007199254740992);
return this._config.storage.save(key, event);
}
public process() {
if (this._processingQueue) {
return;
}
this._config.log.info('Processing queue...');
if (!this._config.enabled) {
this._config.log.info('Configuration is disabled. The queue will not be processed.');
return;
}
this._processingQueue = true;
try {
var events = this._config.storage.get(this.queuePath(), this._config.submissionBatchSize);
if (events.length == 0) {
this._config.log.info('There are currently no queued events to process.');
return;
}
this._config.submissionClient.submit(events, this._config)
.then(
(response:SubmissionResponse) => {
if (response.success) {
this._config.log.info('Sent ' + events.length + ' events to "' + this._config.serverUrl + '".');
} else if (response.serviceUnavailable) {
// You are currently over your rate limit or the servers are under stress.
this._config.log.error('Server returned service unavailable.');
this.suspendProcessing();
this.requeueEvents(events);
} else if (response.paymentRequired) {
// If the organization over the rate limit then discard the event.
this._config.log.info('Too many events have been submitted, please upgrade your plan.');
this.suspendProcessing(null, true, true);
} else if (response.unableToAuthenticate) {
// The api key was suspended or could not be authorized.
this._config.log.info('Unable to authenticate, please check your configuration. The event will not be submitted.');
this.suspendProcessing(15);
} else if (response.notFound || response.badRequest) {
// The service end point could not be found.
this._config.log.error('Error while trying to submit data: ' + response.message);
this.suspendProcessing(60 * 4);
} else if (response.requestEntityTooLarge) {
if (this._config.submissionBatchSize > 1) {
this._config.log.error('Event submission discarded for being too large. The event will be retried with a smaller events size.');
this._config.submissionBatchSize = Math.max(1, Math.round(this._config.submissionBatchSize / 1.5));
this.requeueEvents(events);
} else {
this._config.log.error('Event submission discarded for being too large. The event will not be submitted.');
}
} else if (!response.success) {
this._config.log.error('An error occurred while submitting events: ' + response.message);
this.suspendProcessing();
this.requeueEvents(events);
}
},
(response:SubmissionResponse) => {
this._config.log.error('An error occurred while submitting events: ' + response.message);
this.suspendProcessing();
this.requeueEvents(events);
})
.then(() => {
this._config.log.info('Finished processing queue.');
this._processingQueue = false;
});
} catch (ex) {
this._config.log.error('An error occurred while processing the queue: ' + ex);
this.suspendProcessing();
} finally {
this._config.log.info('Finished processing queue.');
this._processingQueue = false;
}
}
private onProcessQueue() {
return false;
if (!this.isQueueProcessingSuspended() && !this._processingQueue) {
this.process();
}
}
public suspendProcessing(durationInMinutes?:number, discardFutureQueuedItems?:boolean, clearQueue?:boolean) {
if (!durationInMinutes || durationInMinutes <= 0) {
durationInMinutes = 5;
}
this._config.log.info('Suspending processing for ' + durationInMinutes + 'minutes.');
this._suspendProcessingUntil = new Date(new Date().getTime() + (durationInMinutes * 60000));
//_queueTimer.Change(duration.Value, _processQueueInterval);
if (discardFutureQueuedItems) {
this._discardQueuedItemsUntil = new Date(new Date().getTime() + (durationInMinutes * 60000));
}
if (!clearQueue) {
return;
}
// Account is over the limit and we want to ensure that the sample size being sent in will contain newer errors.
try {
this._config.storage.clear(this.queuePath());
} catch (Exception) { }
}
private requeueEvents(events:IEvent[]) {
for (var event in events || []) {
this.enqueue(event);
}
}
private isQueueProcessingSuspended(): boolean {
return this._suspendProcessingUntil && this._suspendProcessingUntil > new Date();
}
private areQueuedItemsDiscarded(): boolean {
return this._discardQueuedItemsUntil && this._discardQueuedItemsUntil > new Date();
}
private queuePath(): string {
return this._config.getQueueName() + '-q'
}
}
export interface ISubmissionClient {
submit(events:IEvent[], config:Configuration): Promise<SubmissionResponse>;
submitDescription(referenceId:string, description:IUserDescription, config:Configuration): Promise<SubmissionResponse>;
getSettings(config:Configuration): Promise<SettingsResponse>;
}
export class SubmissionClient implements ISubmissionClient {
public submit(events:IEvent[], config:Configuration): Promise<SubmissionResponse> {
var url = config.serverUrl + '/api/v2/events?access_token=' + encodeURIComponent(config.apiKey);
return this.sendRequest('POST', url, JSON.stringify(events)).then(
xhr => { return new SubmissionResponse(xhr.status, this.getResponseMessage(xhr)); },
xhr => { return new SubmissionResponse(xhr.status || 500, this.getResponseMessage(xhr)); }
);
}
public submitDescription(referenceId:string, description:IUserDescription, config:Configuration): Promise<SubmissionResponse> {
var url = config.serverUrl + '/api/v2/events/by-ref/' + encodeURIComponent(referenceId) + '/user-description?access_token=' + encodeURIComponent(config.apiKey);
return this.sendRequest('POST', url, JSON.stringify(description)).then(
xhr => { return new SubmissionResponse(xhr.status, this.getResponseMessage(xhr)); },
xhr => { return new SubmissionResponse(xhr.status || 500, this.getResponseMessage(xhr)); }
);
}
public getSettings(config:Configuration): Promise<SettingsResponse> {
var url = config.serverUrl + '/api/v2/projects/config?access_token=' + encodeURIComponent(config.apiKey);
return this.sendRequest('GET', url).then(
xhr => {
if (xhr.status !== 200) {
return new SettingsResponse(false, null, -1, null, 'Unable to retrieve configuration settings: ' + this.getResponseMessage(xhr));
}
var settings;
try {
settings = JSON.parse(xhr.responseText);
} catch (e) {
config.log.error('An error occurred while parsing the settings response text: "' + xhr.responseText + '"');
}
if (!settings || !settings.settings || !settings.version) {
return new SettingsResponse(true, null, -1, null, 'Invalid configuration settings.');
}
return new SettingsResponse(true, settings.settings, settings.version);
},
xhr => {
return new SettingsResponse(false, null, -1, null, this.getResponseMessage(xhr));
}
);
}
private getResponseMessage(xhr:XMLHttpRequest): string {
if (!xhr || (xhr.status >= 200 && xhr.status <= 299)) {
return null;
}
if (xhr.status === 0) {
return 'Unable to connect to server.';
}
if (xhr.responseBody) {
return xhr.responseBody.message;
}
if (xhr.responseText) {
try {
return JSON.parse(xhr.responseText).message;
} catch (e) {
return xhr.responseText;
}
}
return xhr.statusText;
}
private createRequest(method:string, url:string): XMLHttpRequest {
var xhr:any = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != 'undefined') {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
if (xhr) {
if (method === 'POST' && xhr.setRequestHeader) {
xhr.setRequestHeader('Content-Type', 'application/json');
}
xhr.timeout = 10000;
}
return xhr;
}
private sendRequest(method:string, url:string, data?:string): Promise<any> {
var xhr = this.createRequest(method || 'POST', url);
return new Promise((resolve, reject) => {
if (!xhr) {
return reject({ status: 503, message: 'CORS not supported.' });
}
if ('withCredentials' in xhr) {
xhr.onreadystatechange = () => {
// xhr not ready.
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status <= 299) {
resolve(xhr);
} else {
reject(xhr);
}
};
}
xhr.ontimeout = () => reject(xhr);
xhr.onerror = () => reject(xhr);
xhr.onload = () => resolve(xhr);
xhr.send(data);
});
}
}
export class SubmissionResponse {
success = false;
badRequest = false;
serviceUnavailable = false;
paymentRequired = false;
unableToAuthenticate = false;
notFound = false;
requestEntityTooLarge = false;
statusCode:number;
message:string;
constructor(statusCode:number, message?:string) {
this.statusCode = statusCode;
this.message = message;
this.success = statusCode >= 200 && statusCode <= 299;
this.badRequest = statusCode === 400;
this.serviceUnavailable = statusCode === 503;
this.paymentRequired = statusCode === 402;
this.unableToAuthenticate = statusCode === 401 || statusCode === 403;
this.notFound = statusCode === 404;
this.requestEntityTooLarge = statusCode === 413;
}
}
export class SettingsResponse {
success = false;
settings:any;
settingsVersion = -1;
message:string;
exception:any;
constructor(success:boolean, settings:any, settingsVersion:number = -1, exception:any = null, message:string = null) {
this.success = success;
this.settings = settings;
this.settingsVersion = settingsVersion;
this.exception = exception;
this.message = message;
}
}
export interface IStorage<T>{
save<T>(path:string, value:T): boolean;
get(searchPattern?:string, limit?:number): T[];
clear(searchPattern?:string);
count(searchPattern?:string): number;
}
export class InMemoryStorage<T> implements IStorage<T> {
private _items = {};
public save<T>(path:string, value:T): boolean {
this._items[path] = value;
return true;
}
public get(searchPattern?:string, limit?:number): T[] {
var results = [];
var regex = new RegExp(searchPattern || '.*');
for (var key in this._items) {
if (results.length >= limit) {
break;
}
if (regex.test(key)) {
results.push(this._items[key]);
delete this._items[key];
}
}
return results;
}
public clear(searchPattern?:string) {
if (!searchPattern) {
this._items = {};
return;
}
var regex = new RegExp(searchPattern);
for (var key in this._items) {
if (regex.test(key)) {
delete this._items[key];
}
}
}
public count(searchPattern?:string): number {
var regex = new RegExp(searchPattern || '.*');
var results = [];
for (var key in this._items) {
if (regex.test(key)) {
results.push(key);
}
}
return results.length;
}
}
export interface IEvent {
type?: string;
source?: string;
date?: Date;
tags?: string[];
message?: string;
geo?: string;
value?: number;
data?: any;
reference_id?: string;
session_id?: string;
}
export class EventBuilder {
target: IEvent;
client: ExceptionlessClient;
pluginContextData: IContextData;
constructor(event:IEvent, client:ExceptionlessClient, pluginContextData?:IContextData) {
this.target = event;
this.client = client;
this.pluginContextData = pluginContextData;
}
public setType(type:string): EventBuilder {
this.target.type = type;
return this;
}
public setSource(source:string): EventBuilder {
this.target.source = source;
return this;
}
public setSessionId(sessionId:string): EventBuilder {
if (!this.isValidIdentifier(sessionId)) {
throw new Error("SessionId must contain between 8 and 100 alphanumeric or '-' characters.");
}
this.target.session_id = sessionId;
return this;
}
public setReferenceId(referenceId:string): EventBuilder {
if (!this.isValidIdentifier(referenceId)) {
throw new Error("SessionId must contain between 8 and 100 alphanumeric or '-' characters.");
}
this.target.reference_id = referenceId;
return this;
}
private isValidIdentifier(value:string): boolean {
if (value == null) {
return true;
}
if (value.length < 8 || value.length > 100) {
return false;
}
//for (int index = 0; index < value.Length; index++) {
// if (!Char.IsLetterOrDigit(value[index]) && value[index] != '-')
// return false;
//}
return true;
}
public setMessage(message:string): EventBuilder {
this.target.message = message;
return this;
}
public setGeo(latitude: number, longitude: number): EventBuilder {
if (latitude < -90.0 || latitude > 90.0)
throw new Error('Must be a valid latitude value between -90.0 and 90.0.');
if (longitude < -180.0 || longitude > 180.0)
throw new Error('Must be a valid longitude value between -180.0 and 180.0.');
this.target.geo = latitude + ',' + longitude;
return this;
}
public setValue(value:number): EventBuilder {
this.target.value = value;
return this;
}
public addTags(tags:string[]): EventBuilder {
if (tags == null || tags.length === 0) {
return this;
}
//this.target.tags.AddRange(tags.Where(t => !String.IsNullOrWhiteSpace(t)).Select(t => t.Trim()));
return this;
}
public setProperty(name:string, value:any): EventBuilder {
this.target.data[name] = value;
return this;
}
public setCritical(critical:boolean): EventBuilder {
// check to see if it already contains the critical tag.
if (critical) {
this.target.tags.push('Critical');
}
return this;
}
public submit(): void {
this.client.submit(this.target, this.pluginContextData);
}
}
export interface IContextData {}
export interface IUserDescription {
email_address?: string;
description?: string;
data?: any;
}
}