@@ -3,11 +3,18 @@ import { ILog } from "../logging/ILog.js";
33import { Event } from "../models/Event.js" ;
44import { IEventQueue } from "../queue/IEventQueue.js" ;
55import { Response } from "../submission/Response.js" ;
6- import { allowProcessToExitWithoutWaitingForTimerOrInterval } from "../Utils.js" ;
6+ import { allowProcessToExitWithoutWaitingForTimerOrInterval , guid } from "../Utils.js" ;
77
88interface EventQueueItem {
99 file : string ;
1010 event : Event ;
11+ /** True when the event was written to (or loaded from) persisted storage. */
12+ persisted ?: boolean ;
13+ }
14+
15+ interface SubmissionResult {
16+ continueProcessing : boolean ;
17+ retryWithBatchSize ?: number ;
1118}
1219
1320export class DefaultEventQueue implements IEventQueue {
@@ -47,6 +54,7 @@ export class DefaultEventQueue implements IEventQueue {
4754 private _queueIntervalId : ReturnType < typeof setInterval > | undefined ;
4855
4956 private readonly QUEUE_PREFIX : string = "q:" ;
57+ private readonly DEFAULT_SUSPENSION_MINUTES : number = 5 ;
5058 private _lastFileTimestamp = 0 ;
5159 private _queue : EventQueueItem [ ] = [ ] ;
5260 private _loadPersistedEvents = true ;
@@ -100,6 +108,11 @@ export class DefaultEventQueue implements IEventQueue {
100108 return ;
101109 }
102110
111+ if ( this . isQueueProcessingSuspended ( ) ) {
112+ log . trace ( `Queue processing is suspended: ${ queueNotProcessed } ` ) ;
113+ return ;
114+ }
115+
103116 this . _processingQueue = true ;
104117 try {
105118 if ( this . _loadPersistedEvents ) {
@@ -110,22 +123,32 @@ export class DefaultEventQueue implements IEventQueue {
110123 this . _loadPersistedEvents = false ;
111124 }
112125
113- const items = this . _queue . slice ( 0 , this . config . submissionBatchSize ) ;
114- if ( ! items || items . length === 0 ) {
115- this . _processingQueue = false ;
116- return ;
126+ // Send batches until the queue is empty or a submission fails. Events enqueued while sending are picked up too.
127+ let batchSize = Math . max ( 1 , this . config . submissionBatchSize ) ;
128+ while ( this . _queue . length > 0 && ! this . isQueueProcessingSuspended ( ) ) {
129+ const items = await this . getNextBatch ( batchSize ) ;
130+ if ( items . length === 0 ) {
131+ continue ;
132+ }
133+
134+ log . info ( `Sending ${ items . length } events to ${ this . config . serverUrl } ` ) ;
135+ const events = items . map ( ( i ) => i . event ) ;
136+ const response = await this . config . services . submissionClient . submitEvents ( events ) ;
137+ const result = await this . processSubmissionResponse ( response , items , batchSize ) ;
138+ await this . eventsPosted ( events , response ) ;
139+
140+ if ( result . retryWithBatchSize ) {
141+ batchSize = result . retryWithBatchSize ;
142+ } else if ( ! result . continueProcessing ) {
143+ break ;
144+ }
117145 }
118146
119- log . info ( `Sending ${ items . length } events to ${ this . config . serverUrl } ` ) ;
120- const events = items . map ( ( i ) => i . event ) ;
121- const response = await this . config . services . submissionClient . submitEvents ( events ) ;
122- await this . processSubmissionResponse ( response , items ) ;
123- await this . eventsPosted ( events , response ) ;
124147 log . trace ( "Finished processing queue" ) ;
125- this . _processingQueue = false ;
126148 } catch ( ex ) {
127149 log . error ( `Error processing queue: ${ ex instanceof Error ? ex . message : ex + "" } ` ) ;
128150 await this . suspendProcessing ( ) ;
151+ } finally {
129152 this . _processingQueue = false ;
130153 }
131154 }
@@ -151,7 +174,7 @@ export class DefaultEventQueue implements IEventQueue {
151174
152175 const currentDate = new Date ( ) ;
153176 if ( ! durationInMinutes || durationInMinutes <= 0 ) {
154- durationInMinutes = Math . ceil ( currentDate . getMinutes ( ) / 15 ) * 15 - currentDate . getMinutes ( ) ;
177+ durationInMinutes = this . DEFAULT_SUSPENSION_MINUTES ;
155178 }
156179
157180 config . services . log . info ( `Suspending processing for ${ durationInMinutes } minutes.` ) ;
@@ -197,98 +220,197 @@ export class DefaultEventQueue implements IEventQueue {
197220 }
198221 }
199222
200- private async processSubmissionResponse ( response : Response , items : EventQueueItem [ ] ) : Promise < void > {
223+ private async processSubmissionResponse ( response : Response , items : EventQueueItem [ ] , batchSize : number ) : Promise < SubmissionResult > {
201224 const noSubmission = "The event will not be submitted" ;
202225 const config : Configuration = this . config ;
203226 const log : ILog = config . services . log ;
204227
205- if ( response . status === 202 ) {
228+ if ( response . success ) {
206229 log . info ( `Sent ${ items . length } events` ) ;
207230 await this . removeEvents ( items ) ;
208- return ;
231+ return {
232+ continueProcessing : response . rateLimitRemaining !== 0
233+ } ;
209234 }
210235
211- if ( response . status === 429 || response . rateLimitRemaining === 0 || response . status === 503 ) {
236+ if ( response . status === 429 || response . status === 503 ) {
212237 // You are currently over your rate limit or the servers are under stress.
213238 log . error ( "Server returned service unavailable" ) ;
214239 await this . suspendProcessing ( ) ;
215- return ;
240+ return {
241+ continueProcessing : false
242+ } ;
216243 }
217244
218245 if ( response . status === 402 ) {
219246 // If the organization over the rate limit then discard the event.
220247 log . info ( "Too many events have been submitted, please upgrade your plan" ) ;
221248 await this . suspendProcessing ( 0 , true , true ) ;
222- return ;
249+ return {
250+ continueProcessing : false
251+ } ;
223252 }
224253
225254 if ( response . status === 401 || response . status === 403 ) {
226255 // The api key was suspended or could not be authorized.
227256 log . info ( `Unable to authenticate, please check your configuration. ${ noSubmission } ` ) ;
228257 await this . suspendProcessing ( 15 ) ;
229258 await this . removeEvents ( items ) ;
230- return ;
259+ return {
260+ continueProcessing : false
261+ } ;
231262 }
232263
233264 if ( response . status === 400 || response . status === 404 ) {
234265 // The service end point could not be found.
235266 log . error ( `Error while trying to submit data: ${ response . message } ` ) ;
236267 await this . suspendProcessing ( 60 * 4 ) ;
237268 await this . removeEvents ( items ) ;
238- return ;
269+ return {
270+ continueProcessing : false
271+ } ;
239272 }
240273
241274 if ( response . status === 413 ) {
242275 const message = "Event submission discarded for being too large." ;
243- if ( config . submissionBatchSize > 1 ) {
276+ if ( items . length > 1 ) {
244277 log . error ( `${ message } Retrying with smaller batch size.` ) ;
245- config . submissionBatchSize = Math . max ( 1 , Math . round ( config . submissionBatchSize / 1.5 ) ) ;
246- } else {
247- log . error ( ` ${ message } ${ noSubmission } ` ) ;
248- await this . removeEvents ( items ) ;
278+ return {
279+ continueProcessing : true ,
280+ retryWithBatchSize : Math . max ( 1 , Math . round ( Math . min ( batchSize , items . length ) / 1.5 ) )
281+ } ;
249282 }
250283
251- return ;
284+ log . error ( `${ message } ${ noSubmission } ` ) ;
285+ await this . removeEvents ( items ) ;
286+ return {
287+ continueProcessing : true
288+ } ;
252289 }
253290
254291 log . error ( `Error submitting events: ${ response . message || "Please check the network tab for more info." } ` ) ;
255292 await this . suspendProcessing ( ) ;
293+ return {
294+ continueProcessing : false
295+ } ;
296+ }
297+
298+ /**
299+ * Returns the next batch of queued events. When the queue is persisted, events that another client instance
300+ * sharing the same storage (for example, another browser tab) has already sent and removed are skipped.
301+ */
302+ private async getNextBatch ( batchSize : number ) : Promise < EventQueueItem [ ] > {
303+ const items = this . _queue . slice ( 0 , batchSize ) ;
304+ if ( ! this . config . usePersistedQueueStorage ) {
305+ return items ;
306+ }
307+
308+ const { log, storage } = this . config . services ;
309+ const available : EventQueueItem [ ] = [ ] ;
310+ const removed : EventQueueItem [ ] = [ ] ;
311+ for ( const item of items ) {
312+ if ( ! item . persisted ) {
313+ available . push ( item ) ;
314+ continue ;
315+ }
316+
317+ try {
318+ if ( ( await storage . getItem ( item . file ) ) === null ) {
319+ removed . push ( item ) ;
320+ continue ;
321+ }
322+ } catch ( ex ) {
323+ log . error ( `Error reading queue item from storage: ${ ex instanceof Error ? ex . message : ex + "" } ` ) ;
324+ }
325+
326+ available . push ( item ) ;
327+ }
328+
329+ if ( removed . length > 0 ) {
330+ log . trace ( `Skipping ${ removed . length } queued events that were already submitted` ) ;
331+ this . _queue = this . _queue . filter ( ( i ) => ! removed . includes ( i ) ) ;
332+ }
333+
334+ return available ;
256335 }
257336
258337 private async loadEvents ( ) : Promise < void > {
259- if ( this . config . usePersistedQueueStorage ) {
260- const { log, storage } = this . config . services ;
338+ if ( ! this . config . usePersistedQueueStorage ) {
339+ return ;
340+ }
341+
342+ const { log, storage } = this . config . services ;
343+ let files : string [ ] ;
344+ try {
345+ files = await storage . keys ( ) ;
346+ } catch ( ex ) {
347+ log . error ( `Error loading queue items from storage: ${ ex instanceof Error ? ex . message : ex + "" } ` ) ;
348+ return ;
349+ }
350+
351+ const queuedFiles = new Set ( this . _queue . map ( ( i ) => i . file ) ) ;
352+ const loaded : EventQueueItem [ ] = [ ] ;
353+ for ( const file of files ) {
354+ if ( ! file ?. startsWith ( this . QUEUE_PREFIX ) || queuedFiles . has ( file ) ) {
355+ continue ;
356+ }
261357
262358 try {
263- const files : string [ ] = await storage . keys ( ) ;
264-
265- for ( const file of files ) {
266- if ( file ?. startsWith ( this . QUEUE_PREFIX ) ) {
267- const json = await storage . getItem ( file ) ;
268- if ( json ) {
269- this . _queue . push ( {
270- file,
271- event : JSON . parse ( json ) as Event
272- } ) ;
273- }
274- }
359+ const json = await storage . getItem ( file ) ;
360+ if ( json ) {
361+ loaded . push ( {
362+ file,
363+ event : JSON . parse ( json ) as Event ,
364+ persisted : true
365+ } ) ;
275366 }
276367 } catch ( ex ) {
277- log . error ( `Error loading queue items from storage: ${ ex instanceof Error ? ex . message : ex + "" } ` ) ;
368+ log . error ( `Removing unreadable queue item "${ file } " from storage: ${ ex instanceof Error ? ex . message : ex + "" } ` ) ;
369+ await this . removeStorageItem ( file ) ;
278370 }
279371 }
372+
373+ if ( loaded . length === 0 ) {
374+ return ;
375+ }
376+
377+ // Events persisted by an earlier session are older than anything queued in this one.
378+ loaded . sort ( ( a , b ) => this . getFileTimestamp ( a . file ) - this . getFileTimestamp ( b . file ) ) ;
379+ this . _queue = [ ...loaded , ...this . _queue ] ;
380+ log . info ( `Loaded ${ loaded . length } queued events from storage` ) ;
381+
382+ const overflow = this . _queue . length - this . maxItems ;
383+ if ( overflow > 0 ) {
384+ log . trace ( "Removing oldest queue entries: maxItems exceeded" ) ;
385+ await this . removeEvents ( this . _queue . slice ( 0 , overflow ) ) ;
386+ }
387+ }
388+
389+ private getFileTimestamp ( file : string ) : number {
390+ const timestamp = parseInt ( file . slice ( this . QUEUE_PREFIX . length ) , 10 ) ;
391+ return isNaN ( timestamp ) ? 0 : timestamp ;
392+ }
393+
394+ private async removeStorageItem ( file : string ) : Promise < void > {
395+ try {
396+ await this . config . services . storage . removeItem ( file ) ;
397+ } catch ( ex ) {
398+ this . config . services . log . error ( `Error removing queue item from storage: ${ ex instanceof Error ? ex . message : ex + "" } ` ) ;
399+ }
280400 }
281401
282402 private async enqueueEvent ( event : Event ) : Promise < string > {
283403 this . _lastFileTimestamp = Math . max ( Date . now ( ) , this . _lastFileTimestamp + 1 ) ;
284- const file = `${ this . QUEUE_PREFIX } ${ this . _lastFileTimestamp } .json` ;
404+ // The random suffix keeps client instances that share storage (for example, browser tabs) from overwriting each other's entries.
405+ const file = `${ this . QUEUE_PREFIX } ${ this . _lastFileTimestamp } -${ guid ( ) . slice ( 0 , 8 ) } .json` ;
285406
286407 const { log, storage } = this . config . services ;
287408 const useStorage : boolean = this . config . usePersistedQueueStorage ;
288409 if (
289410 this . _queue . push ( {
290411 file,
291- event
412+ event,
413+ persisted : useStorage
292414 } ) > this . maxItems
293415 ) {
294416 log . trace ( "Removing oldest queue entry: maxItems exceeded" ) ;
0 commit comments