import crypto from 'crypto' ; import { head } from 'ramda' ; import * as semver from 'semver' ; import { AppMetaInfo , Apps } from '..' ; import { CacheLayer } from '../caches' ; import { Logger } from '../service/logger' ; export const getMetaInfoKey = ( account , workspace ) => `${ account }-${ workspace }-meta-infos` ; const hashMD5 = ( text ) => crypto . createHash ( 'md5' ) . update ( text ) . digest ( 'hex' ) ; export const updateMetaInfoCache = async ( cacheStorage , account , workspace , dependencies , logger ) => { if ( workspace !== 'master' ) { return ; } const key = getMetaInfoKey ( account , workspace ) ; const hash = hashMD5 ( dependencies . toString ( ) ) ; try { const storedDependencies = await cacheStorage . get ( key ) || '' ; if ( hash !== hashMD5 ( storedDependencies . toString ( ) ) ) { await cacheStorage . set ( key , dependencies ) ; } } catch ( error ) { logger . error ( { error , message : 'Apps disk cache update failed' } ) ; } return ; } ; const getFallbackKey = ( appName , major ) => `${ appName }@${ major }` ; export const saveVersion = async ( app , cacheStorage ) => { const [ appName , version ] = app . split ( '@' ) ; const major = head ( version . split ( '.' ) ) || '' ; const fallbackKey = getFallbackKey ( appName , major ) ; if ( cacheStorage . has ( fallbackKey ) ) { const savedVersion = await cacheStorage . get ( fallbackKey ) ; if ( savedVersion && ( version === `${ major }.x` || semver . gt ( version , savedVersion ) ) ) { await cacheStorage . set ( fallbackKey , version ) ; } } else { await cacheStorage . set ( fallbackKey , version ) ; } } ; export const getFallbackFile = async ( app , path , cacheStorage , apps ) : Promise < { data : Buffer ; headers : any ; } > => { const [ appName , version ] = app . split ( '@' ) ; const major = head ( version . split ( '.' ) ) || '' ; const fallbackKey = getFallbackKey ( appName , major ) ; const fallbackVersion = await cacheStorage . get ( fallbackKey ) ; if ( fallbackVersion ) { const appFallbackVersion = `${ appName }@${ fallbackVersion }` ; return apps . getAppFile ( appFallbackVersion , path ) ; } throw Error ( 'Fallback version was not found' ) ; } ;