forked from exceptionless/Exceptionless.JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefaultEventQueue.ts
More file actions
220 lines (182 loc) · 6.77 KB
/
DefaultEventQueue.ts
File metadata and controls
220 lines (182 loc) · 6.77 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
import { Configuration } from '../configuration/Configuration';
import { ILog } from '../logging/ILog';
import { SubmissionResponse } from '../submission/SubmissionResponse';
import { IEvent } from '../models/IEvent';
import { IEventQueue } from '../queue/IEventQueue';
import { Utils } from '../Utils';
export class DefaultEventQueue implements IEventQueue {
/**
* The configuration object.
* @type {Configuration}
* @private
*/
private _config:Configuration;
/**
* Suspends processing until the specified time.
* @type {Date}
* @private
*/
private _suspendProcessingUntil:Date;
/**
* Discards queued items until the specified time.
* @type {Date}
* @private
*/
private _discardQueuedItemsUntil:Date;
/**
* Returns true if the queue is processing.
* @type {boolean}
* @private
*/
private _processingQueue:boolean = false;
/**
* Processes the queue every xx seconds.
* @type {Timer}
* @private
*/
private _queueTimer:any;
constructor(config:Configuration) {
this._config = config;
}
public enqueue(event:IEvent): void {
var config:Configuration = this._config; // Optimization for minifier.
this.ensureQueueTimer();
if (this.areQueuedItemsDiscarded()) {
config.log.info('Queue items are currently being discarded. The event will not be queued.');
return;
}
var key = `ex-q-${new Date().toJSON()}-${Utils.randomNumber()}`;
config.log.info(`Enqueuing event: ${key} type=${event.type} ${!!event.reference_id ? 'refid=' + event.reference_id : ''}`);
config.storage.save(key, event);
}
public process(): void {
function getEvents(events:{ path:string, value:IEvent }[]):IEvent[] {
var items:IEvent[] = [];
for (var index = 0; index < events.length; index++) {
items.push(events[index].value);
}
return items;
}
const queueNotProcessed:string = 'The queue will not be processed.'; // optimization for minifier.
var config:Configuration = this._config; // Optimization for minifier.
var log:ILog = config.log; // Optimization for minifier.
this.ensureQueueTimer();
if (this._processingQueue) {
return;
}
log.info('Processing queue...');
if (!config.enabled) {
log.info(`Configuration is disabled. ${queueNotProcessed}`);
return;
}
if (!config.isValid) {
log.info(`Invalid Api Key. ${queueNotProcessed}`);
return;
}
this._processingQueue = true;
try {
var events = config.storage.getList('ex-q', config.submissionBatchSize);
if (!events || events.length == 0) {
this._processingQueue = false;
return;
}
log.info(`Sending ${events.length} events to ${config.serverUrl}.`);
config.submissionClient.postEvents(getEvents(events), config, (response:SubmissionResponse) => {
this.processSubmissionResponse(response, events);
log.info('Finished processing queue.');
this._processingQueue = false;
});
} catch (ex) {
log.error(`Error processing queue: ${ex}`);
this.suspendProcessing();
this._processingQueue = false;
}
}
private processSubmissionResponse(response:SubmissionResponse, events:{ path:string, value:IEvent }[]): void {
const noSubmission:string = 'The event will not be submitted.'; // Optimization for minifier.
var config:Configuration = this._config; // Optimization for minifier.
var log:ILog = config.log; // Optimization for minifier.
if (response.success) {
log.info(`Sent ${events.length} events.`);
this.removeEvents(events);
return;
}
if (response.serviceUnavailable) {
// You are currently over your rate limit or the servers are under stress.
log.error('Server returned service unavailable.');
this.suspendProcessing();
return;
}
if (response.paymentRequired) {
// If the organization over the rate limit then discard the event.
log.info('Too many events have been submitted, please upgrade your plan.');
this.suspendProcessing(null, true, true);
return;
}
if (response.unableToAuthenticate) {
// The api key was suspended or could not be authorized.
log.info(`Unable to authenticate, please check your configuration. ${noSubmission}`);
this.suspendProcessing(15);
this.removeEvents(events);
return;
}
if (response.notFound || response.badRequest) {
// The service end point could not be found.
log.error(`Error while trying to submit data: ${response.message}`);
this.suspendProcessing(60 * 4);
this.removeEvents(events);
return;
}
if (response.requestEntityTooLarge) {
var message = 'Event submission discarded for being too large.';
if (config.submissionBatchSize > 1) {
log.error(`${message} Retrying with smaller batch size.`);
config.submissionBatchSize = Math.max(1, Math.round(config.submissionBatchSize / 1.5));
} else {
log.error(`${message} ${noSubmission}`);
this.removeEvents(events);
}
return;
}
if (!response.success) {
log.error(`Error submitting events: ${response.message || 'Please check the network tab for more info.'}`);
this.suspendProcessing();
}
}
private ensureQueueTimer(): void {
if (!this._queueTimer) {
this._queueTimer = setInterval(() => this.onProcessQueue(), 10000);
}
}
private onProcessQueue(): void {
if (!this.isQueueProcessingSuspended() && !this._processingQueue) {
this.process();
}
}
public suspendProcessing(durationInMinutes?:number, discardFutureQueuedItems?:boolean, clearQueue?:boolean): void {
var config:Configuration = this._config; // Optimization for minifier.
if (!durationInMinutes || durationInMinutes <= 0) {
durationInMinutes = 5;
}
config.log.info(`Suspending processing for ${durationInMinutes} minutes.`);
this._suspendProcessingUntil = new Date(new Date().getTime() + (durationInMinutes * 60000));
if (discardFutureQueuedItems) {
this._discardQueuedItemsUntil = new Date(new Date().getTime() + (durationInMinutes * 60000));
}
if (clearQueue) {
// Account is over the limit and we want to ensure that the sample size being sent in will contain newer errors.
this.removeEvents(config.storage.getList('ex-q'));
}
}
private removeEvents(events:{ path:string, value:IEvent }[]) {
for (var index = 0; index < (events || []).length; index++) {
this._config.storage.remove(events[index].path);
}
}
private isQueueProcessingSuspended(): boolean {
return this._suspendProcessingUntil && this._suspendProcessingUntil > new Date();
}
private areQueuedItemsDiscarded(): boolean {
return this._discardQueuedItemsUntil && this._discardQueuedItemsUntil > new Date();
}
}