@@ -7,6 +7,7 @@ import { EntityValue, getResultSetSchema, LineColumnLocation, UrlValue, ColumnKi
77import { CodeQLCliServer } from "./cli" ;
88import { DatabaseItem , DatabaseManager } from "./databases" ;
99import * as helpers from './helpers' ;
10+ import { CachedOperation } from './helpers' ;
1011import * as messages from "./messages" ;
1112import { QueryServerClient } from "./queryserver-client" ;
1213import { compileAndRunQueryAgainstDatabase , QueryWithResults } from "./run-queries" ;
@@ -196,58 +197,3 @@ function fileRangeFromURI(uri: UrlValue, db: DatabaseItem): FileRange | undefine
196197 }
197198 }
198199}
199-
200- const CACHE_SIZE = 100 ;
201- class CachedOperation < U > {
202- private readonly operation : ( t : string ) => Promise < U > ;
203- private readonly cached : Map < string , U > ;
204- private readonly lru : string [ ] ;
205- private readonly inProgressCallbacks : Map < string , [ ( u : U ) => void , ( reason ?: any ) => void ] [ ] > ;
206-
207- constructor ( operation : ( t : string ) => Promise < U > ) {
208- this . operation = operation ;
209- this . lru = [ ] ;
210- this . inProgressCallbacks = new Map < string , [ ( u : U ) => void , ( reason ?: any ) => void ] [ ] > ( ) ;
211- this . cached = new Map < string , U > ( ) ;
212- }
213-
214- async get ( t : string ) : Promise < U > {
215- // Try and retrieve from the cache
216- const fromCache = this . cached . get ( t ) ;
217- if ( fromCache !== undefined ) {
218- // Move to end of lru list
219- this . lru . push ( this . lru . splice ( this . lru . findIndex ( v => v === t ) , 1 ) [ 0 ] )
220- return fromCache ;
221- }
222- // Otherwise check if in progress
223- const inProgressCallback = this . inProgressCallbacks . get ( t ) ;
224- if ( inProgressCallback !== undefined ) {
225- // If so wait for it to resolve
226- return await new Promise ( ( resolve , reject ) => {
227- inProgressCallback . push ( [ resolve , reject ] ) ;
228- } ) ;
229- }
230-
231- // Otherwise compute the new value, but leave a callback to allow sharing work
232- const callbacks : [ ( u : U ) => void , ( reason ?: any ) => void ] [ ] = [ ] ;
233- this . inProgressCallbacks . set ( t , callbacks ) ;
234- try {
235- const result = await this . operation ( t ) ;
236- callbacks . forEach ( f => f [ 0 ] ( result ) ) ;
237- this . inProgressCallbacks . delete ( t ) ;
238- if ( this . lru . length > CACHE_SIZE ) {
239- const toRemove = this . lru . shift ( ) ! ;
240- this . cached . delete ( toRemove ) ;
241- }
242- this . lru . push ( t ) ;
243- this . cached . set ( t , result ) ;
244- return result ;
245- } catch ( e ) {
246- // Rethrow error on all callbacks
247- callbacks . forEach ( f => f [ 1 ] ( e ) ) ;
248- throw e ;
249- } finally {
250- this . inProgressCallbacks . delete ( t ) ;
251- }
252- }
253- }
0 commit comments