import { PHZReader } from 'polar-content-capture/src/phz/PHZReader' ; import { ResourceEntry } from 'polar-content-capture/src/phz/ResourceEntry' ; import { Logger } from 'polar-shared/src/logger/Logger' ; import { CompressedReader } from 'polar-content-capture/src/phz/CompressedReader' ; const log = Logger . create ( ) ; export class CachingPHZReader implements CompressedReader { public path : string ; /**
     * The delegate PHZReader that actually performs the IO.
     *
     */ public delegate ? : PHZReader ; /**
     * The amount of time we should wait after init to close the file.
     */ public timeout : number ; /**
     * The number of times the reader has been re-opened.
     */ public reopened : number = 0 ; constructor ( path , timeout = 60000 ) { this . path = path ; this . timeout = timeout ; } return { Promise < void > } public async init ( ) { this . delegate = new PHZReader ( ) ; await this . delegate ! . init ( this . path ) ; const doAsync = async ( ) => { await this . close ( ) ; } ; setTimeout ( ( ) => { doAsync ( ) . catch ( err => console . error ( "Unable to init with timeout: " , err ) ) ; } , this . timeout ) ; } public async getMetadata ( ) { await this . openWhenNecessary ( ) ; return await this . delegate ! . getMetadata ( ) ; } /**
     * Get just the resources from the metadata.
     */ public async getResources ( ) { await this . openWhenNecessary ( ) ; return await this . delegate ! . getResources ( ) ; } /**
     * Read a resource from disk and call the callback with the new content once
     * it's ready for usage.
     *
     */ public async getResource ( resourceEntry ) { await this . openWhenNecessary ( ) ; return await this . delegate ! . getResource ( resourceEntry ) ; } public async getResourceAsStream ( resourceEntry ) { await this . openWhenNecessary ( ) ; return await this . delegate ! . getResourceAsStream ( resourceEntry ) ; } public async close ( ) { const delegate = this . delegate ; this . delegate = undefined ; await delegate ! . close ( ) ; } private async openWhenNecessary ( ) { if ( this . delegate ) { return ; } log . info ( "Caching PHZReader being re-opened: " + this . path ) ; ++ this . reopened ; await this . init ( ) ; } }