-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathEventsCacheInMemory.ts
More file actions
77 lines (65 loc) · 1.8 KB
/
Copy pathEventsCacheInMemory.ts
File metadata and controls
77 lines (65 loc) · 1.8 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
import SplitIO from '../../../types/splitio';
import { IEventsCacheSync } from '../types';
const MAX_QUEUE_BYTE_SIZE = 5 * 1024 * 1024; // 5M
export class EventsCacheInMemory implements IEventsCacheSync {
public name = 'events';
private onFullQueue?: () => void;
private readonly maxQueue: number;
private queue: SplitIO.EventData[];
private queueByteSize: number;
/**
*
* @param eventsQueueSize - number of queued events to call onFullQueueCb.
* Default value is 0, that means no maximum value, in case we want to avoid this being triggered.
*/
constructor(eventsQueueSize: number = 0) {
this.maxQueue = eventsQueueSize;
this.queue = [];
this.queueByteSize = 0;
}
setOnFullQueueCb(cb: () => void) {
this.onFullQueue = cb;
}
/**
* Add a new event object at the end of the queue.
*/
track(data: SplitIO.EventData, size = 0) {
this.queueByteSize += size;
this.queue.push(data);
this._checkForFlush();
return true;
}
/**
* Clear the data stored on the cache.
*/
clear() {
this.queue = [];
this.queueByteSize = 0;
}
/**
* Pop the collected data, used as payload for posting.
*/
pop(toMerge?: SplitIO.EventData[]) {
const data = this.queue;
this.clear();
return toMerge ? toMerge.concat(data) : data;
}
/**
* Check if the cache is empty.
*/
isEmpty() {
return this.queue.length === 0;
}
/**
* Check if the cache queue is full and we need to flush it.
*/
private _checkForFlush() {
if (
(this.queueByteSize > MAX_QUEUE_BYTE_SIZE) ||
// 0 means no maximum value, in case we want to avoid this being triggered. Size limit is not affected by it.
(this.maxQueue > 0 && this.queue.length >= this.maxQueue)
) {
this.onFullQueue && this.onFullQueue();
}
}
}