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
316 lines (265 loc) · 9.85 KB
/
DefaultEventQueue.ts
File metadata and controls
316 lines (265 loc) · 9.85 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
import { Configuration } from "../configuration/Configuration.js";
import { ILog } from "../logging/ILog.js";
import { Event } from "../models/Event.js";
import { IEventQueue } from "../queue/IEventQueue.js";
import { Response } from "../submission/Response.js";
interface EventQueueItem {
file: string,
event: Event
}
export class DefaultEventQueue implements IEventQueue {
/**
* A list of handlers that will be fired when events are submitted.
* @type {Array}
* @private
*/
private _handlers: Array<(events: Event[], response: Response) => Promise<void>> = [];
/**
* 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 = false;
/**
* Processes the queue every xx seconds.
* @type {Timer}
* @private
*/
private _queueTimerId = 0;
private readonly QUEUE_PREFIX: string = "q:";
private _lastFileTimestamp = 0;
private _queue: EventQueueItem[] = [];
private _loadPersistedEvents = true;
constructor(
private config: Configuration,
private maxItems: number = 250
) { }
public async enqueue(event: Event): Promise<void> {
const eventWillNotBeQueued = "The event will not be queued.";
const config: Configuration = this.config;
const log: ILog = config.services.log;
if (!config.enabled) {
log.info(`Configuration is disabled. ${eventWillNotBeQueued}`);
return;
}
if (!config.isValid) {
log.info(`Invalid Api Key. ${eventWillNotBeQueued}`);
return;
}
if (this.areQueuedItemsDiscarded()) {
log.info(`Queue items are currently being discarded. ${eventWillNotBeQueued}`);
return;
}
const file = await this.enqueueEvent(event);
const logText = `type=${<string>event.type} reference_id=${<string>event.reference_id} source=${<string>event.source} message=${<string>event.message}`;
log.info(`Enqueued event: ${file} (${logText})`);
}
public async process(): Promise<void> {
const queueNotProcessed = "The queue will not be processed";
const { log } = this.config.services;
if (this._processingQueue) {
return;
}
log.trace("Processing queue...");
if (!this.config.enabled) {
log.info(`Configuration is disabled: ${queueNotProcessed}`);
return;
}
if (!this.config.isValid) {
log.info(`Invalid Api Key: ${queueNotProcessed}`);
return;
}
this._processingQueue = true;
try {
if (this._loadPersistedEvents) {
if (this.config.usePersistedQueueStorage) {
await this.loadEvents();
}
this._loadPersistedEvents = false;
}
const items = this._queue.slice(0, this.config.submissionBatchSize);
if (!items || items.length === 0) {
this._processingQueue = false;
return;
}
log.info(`Sending ${items.length} events to ${this.config.serverUrl}`);
const events = items.map(i => i.event);
const response = await this.config.services.submissionClient.submitEvents(events);
await this.processSubmissionResponse(response, items);
await this.eventsPosted(events, response);
log.trace("Finished processing queue");
this._processingQueue = false;
} catch (ex) {
log.error(`Error processing queue: ${<string>ex?.message}`);
await this.suspendProcessing();
this._processingQueue = false;
}
}
public startup(): Promise<void> {
if (this._queueTimerId === 0) {
// TODO: Fix awaiting promise.
this._queueTimerId = setInterval(() => void this.onProcessQueue(), 10000);
}
return Promise.resolve();
}
public suspend(): Promise<void> {
clearInterval(this._queueTimerId);
this._queueTimerId = 0;
return Promise.resolve();
}
public async suspendProcessing(durationInMinutes?: number, discardFutureQueuedItems?: boolean, clearQueue?: boolean): Promise<void> {
const config: Configuration = this.config; // Optimization for minifier.
const currentDate = new Date();
if (!durationInMinutes || durationInMinutes <= 0) {
durationInMinutes = Math.ceil(currentDate.getMinutes() / 15) * 15 - currentDate.getMinutes();
}
config.services.log.info(`Suspending processing for ${durationInMinutes} minutes.`);
this._suspendProcessingUntil = new Date(currentDate.getTime() + (durationInMinutes * 60000));
if (discardFutureQueuedItems) {
this._discardQueuedItemsUntil = this._suspendProcessingUntil;
}
if (clearQueue) {
// Account is over the limit and we want to ensure that the sample size being sent in will contain newer errors.
await this.removeEvents(this._queue);
}
}
// TODO: See if this makes sense.
public onEventsPosted(handler: (events: Event[], response: Response) => Promise<void>): void {
handler && this._handlers.push(handler);
}
private async eventsPosted(events: Event[], response: Response): Promise<void> {
const handlers = this._handlers;
for (const handler of handlers) {
try {
await handler(events, response);
} catch (ex) {
this.config.services.log.error(`Error calling onEventsPosted handler: ${<string>ex?.message}`);
}
}
}
private areQueuedItemsDiscarded(): boolean {
return this._discardQueuedItemsUntil &&
this._discardQueuedItemsUntil > new Date() || false;
}
private isQueueProcessingSuspended(): boolean {
return this._suspendProcessingUntil &&
this._suspendProcessingUntil > new Date() || false;
}
private async onProcessQueue(): Promise<void> {
if (!this.isQueueProcessingSuspended() && !this._processingQueue) {
await this.process();
}
}
private async processSubmissionResponse(response: Response, items: EventQueueItem[]): Promise<void> {
const noSubmission = "The event will not be submitted";
const config: Configuration = this.config;
const log: ILog = config.services.log;
if (response.status === 202) {
log.info(`Sent ${items.length} events`);
await this.removeEvents(items);
return;
}
if (response.status === 429 || response.rateLimitRemaining === 0 || response.status === 503) {
// You are currently over your rate limit or the servers are under stress.
log.error("Server returned service unavailable");
await this.suspendProcessing();
return;
}
if (response.status === 402) {
// If the organization over the rate limit then discard the event.
log.info("Too many events have been submitted, please upgrade your plan");
await this.suspendProcessing(0, true, true);
return;
}
if (response.status === 401 || response.status === 403) {
// The api key was suspended or could not be authorized.
log.info(`Unable to authenticate, please check your configuration. ${noSubmission}`);
await this.suspendProcessing(15);
await this.removeEvents(items);
return;
}
if (response.status === 400 || response.status === 404) {
// The service end point could not be found.
log.error(`Error while trying to submit data: ${response.message}`);
await this.suspendProcessing(60 * 4);
await this.removeEvents(items);
return;
}
if (response.status === 413) {
const 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}`);
await this.removeEvents(items);
}
return;
}
log.error(`Error submitting events: ${response.message || "Please check the network tab for more info."}`);
await this.suspendProcessing();
}
private async loadEvents(): Promise<void> {
if (this.config.usePersistedQueueStorage) {
try {
const storage = this.config.services.storage;
const files: string[] = await storage.keys();
for (const file of files) {
if (file?.startsWith(this.QUEUE_PREFIX)) {
const json = await storage.getItem(file);
if (json)
this._queue.push({ file, event: JSON.parse(json) as Event });
}
}
} catch (ex) {
this.config.services.log.error(`Error loading queue items from storage: ${<string>ex?.message}`)
}
}
}
private async enqueueEvent(event: Event): Promise<string> {
this._lastFileTimestamp = Math.max(Date.now(), this._lastFileTimestamp + 1);
const file = `${this.QUEUE_PREFIX}${this._lastFileTimestamp}.json`;
const { storage, log } = this.config.services;
const useStorage: boolean = this.config.usePersistedQueueStorage;
if (this._queue.push({ file, event }) > this.maxItems) {
log.trace("Removing oldest queue entry: maxItems exceeded");
const item = this._queue.shift();
if (useStorage && item) {
await storage.removeItem(item.file);
}
}
if (useStorage) {
try {
await storage.setItem(file, JSON.stringify(event));
} catch (ex) {
log.error(`Error saving queue item to storage: ${<string>ex?.message}`)
}
}
return file;
}
private async removeEvents(items: EventQueueItem[]): Promise<void> {
const files = items.map(i => i.file);
if (this.config.usePersistedQueueStorage) {
for (const file of files) {
try {
await this.config.services.storage.removeItem(file);
} catch (ex) {
this.config.services.log.error(`Error removing queue item from storage: ${<string>ex?.message}`)
}
}
}
this._queue = this._queue.filter(i => !files.includes(i.file));
}
}