import cacache from 'cacache' ; import { DateTime } from 'luxon' ; import upath from 'upath' ; import { logger } from '../../../logger' ; function getKey ( namespace , key ) { return `${ namespace }-${ key }` ; } let cacheFileName ; async function rm ( namespace , key ) { logger . trace ( { namespace , key } , 'Removing cache entry' ) ; await cacache . rm . entry ( cacheFileName , getKey ( namespace , key ) ) ; } export async function get < T = never > ( namespace , key ) { if ( ! cacheFileName ) { return undefined ; } try { const res = await cacache . get ( cacheFileName , getKey ( namespace , key ) ) ; const cachedValue = JSON . parse ( res . data . toString ( ) ) ; if ( cachedValue ) { if ( DateTime . local ( ) < DateTime . fromISO ( cachedValue . expiry ) ) { logger . trace ( { namespace , key } , 'Returning cached value' ) ; return cachedValue . value ; } await rm ( namespace , key ) ; } } catch ( err ) { logger . trace ( { namespace , key } , 'Cache miss' ) ; } return undefined ; } export async function set ( namespace , key , value , ttlMinutes = 5 ) { if ( ! cacheFileName ) { return ; } logger . trace ( { namespace , key , ttlMinutes } , 'Saving cached value' ) ; await cacache . put ( cacheFileName , getKey ( namespace , key ) , JSON . stringify ( { value , expiry : DateTime . local ( ) . plus ( { minutes : ttlMinutes } ) , } ) ) ; } export function init ( cacheDir ) { cacheFileName = upath . join ( cacheDir , '/renovate/renovate-cache-v1' ) ; logger . debug ( 'Initializing Renovate internal cache into ' + cacheFileName ) ; }