@@ -7,6 +7,7 @@ export class CachedOperation<S extends unknown[], U> {
77 private readonly operation : ( t : string , ...args : S ) => Promise < U > ;
88 private readonly cached : Map < string , U > ;
99 private readonly lru : string [ ] ;
10+ private generation : number ;
1011 private readonly inProgressCallbacks : Map <
1112 string ,
1213 Array < [ ( u : U ) => void , ( reason ?: Error ) => void ] >
@@ -17,6 +18,7 @@ export class CachedOperation<S extends unknown[], U> {
1718 private cacheSize = 100 ,
1819 ) {
1920 this . operation = operation ;
21+ this . generation = 0 ;
2022 this . lru = [ ] ;
2123 this . inProgressCallbacks = new Map <
2224 string ,
@@ -46,14 +48,19 @@ export class CachedOperation<S extends unknown[], U> {
4648 inProgressCallback . push ( [ resolve , reject ] ) ;
4749 } ) ;
4850 }
49-
51+ const origGeneration = this . generation ;
5052 // Otherwise compute the new value, but leave a callback to allow sharing work
5153 const callbacks : Array < [ ( u : U ) => void , ( reason ?: Error ) => void ] > = [ ] ;
5254 this . inProgressCallbacks . set ( t , callbacks ) ;
5355 try {
5456 const result = await this . operation ( t , ...args ) ;
5557 callbacks . forEach ( ( f ) => f [ 0 ] ( result ) ) ;
5658 this . inProgressCallbacks . delete ( t ) ;
59+ if ( this . generation !== origGeneration ) {
60+ // Cache was reset in the meantime so don't trust this
61+ // result enough to cache it.
62+ return result ;
63+ }
5764 if ( this . lru . length > this . cacheSize ) {
5865 const toRemove = this . lru . shift ( ) ! ;
5966 this . cached . delete ( toRemove ) ;
@@ -69,4 +76,11 @@ export class CachedOperation<S extends unknown[], U> {
6976 this . inProgressCallbacks . delete ( t ) ;
7077 }
7178 }
79+
80+ reset ( ) {
81+ this . cached . clear ( ) ;
82+ this . lru . length = 0 ;
83+ this . generation ++ ;
84+ this . inProgressCallbacks . clear ( ) ;
85+ }
7286}
0 commit comments