11import { BaseEvent } from "./types.js" ;
2+ import { LRUCache } from "lru-cache" ;
23
34/**
45 * Singleton class for in-memory telemetry event caching
56 * Provides a central storage for telemetry events that couldn't be sent
7+ * Uses LRU cache to automatically drop oldest events when limit is exceeded
68 */
79export class EventCache {
810 private static instance : EventCache ;
9- private events : BaseEvent [ ] = [ ] ;
11+ private static readonly MAX_EVENTS = 1000 ;
1012
11- private constructor ( ) { }
13+ private cache : LRUCache < number , BaseEvent > ;
14+ private nextId = 0 ;
15+
16+ private constructor ( ) {
17+ this . cache = new LRUCache ( {
18+ max : EventCache . MAX_EVENTS ,
19+ // Using FIFO eviction strategy for events
20+ allowStale : false ,
21+ updateAgeOnGet : false ,
22+ } ) ;
23+ }
1224
1325 /**
1426 * Gets the singleton instance of EventCache
@@ -26,21 +38,25 @@ export class EventCache {
2638 * @returns Array of cached BaseEvent objects
2739 */
2840 public getEvents ( ) : BaseEvent [ ] {
29- return [ ... this . events ] ;
41+ return Array . from ( this . cache . values ( ) ) ;
3042 }
3143
3244 /**
33- * Sets the cached events, replacing any existing events
34- * @param events - The events to cache
45+ * Appends new events to the cached events
46+ * LRU cache automatically handles dropping oldest events when limit is exceeded
47+ * @param events - The events to append
3548 */
36- public setEvents ( events : BaseEvent [ ] ) : void {
37- this . events = [ ...events ] ;
49+ public appendEvents ( events : BaseEvent [ ] ) : void {
50+ for ( const event of events ) {
51+ this . cache . set ( this . nextId ++ , event ) ;
52+ }
3853 }
3954
4055 /**
4156 * Clears all cached events
4257 */
4358 public clearEvents ( ) : void {
44- this . events = [ ] ;
59+ this . cache . clear ( ) ;
60+ this . nextId = 0 ;
4561 }
4662}
0 commit comments