import type { ProsodyFilePaths } from './config/paths' ; type Rotate = ( file : string , options : { count ? : number ; compress ? : boolean ; } , cb : Function ) => void ; const rotate = require ( 'log-rotate' ) ; interface ProsodyLogRotate { timer : NodeJS . Timeout ; lastRotation : number ; } type ReloadProsody = ( options : RegisterServerOptions ) => Promise < boolean > ; let logRotate ; async function _rotate ( options , path ) { const p = new Promise < void > ( ( resolve ) => { rotate ( path , { count : 14 , compress : false } , ( err ) => { if ( err ) { options . peertubeHelpers . logger . error ( 'Failed to rotate file ' + path , err ) ; return resolve ( ) ; } return resolve ( ) ; } ) ; } ) ; return p ; } function startProsodyLogRotate ( options , paths , reload ) { const logger = options . peertubeHelpers . logger ; const checkInterval = process . env . NODE_ENV === 'test' ? 60 * 1000 : 60 * 60 * 1000 ; const rotateEvery = process . env . NODE_ENV === 'test' ? 2 * 60 * 1000 : 24 * 60 * 60 * 1000 ; if ( logRotate ) { stopProsodyLogRotate ( options ) ; } logger . info ( 'Starting Prosody log rotation' ) ; const timer = setInterval ( ( ) => { logger . debug ( 'Checking if Prosody logs need to be rotated' ) ; if ( ! logRotate ) { logger . error ( 'Seems that we dont need to rotate Prosody logs, but the timer was called.' ) ; return ; } if ( logRotate . lastRotation + rotateEvery - 1000 > Date . now ( ) ) { logger . debug ( 'To soon to rotate.' ) ; return ; } logger . info ( 'Rotating Prosody log files.' ) ; logRotate . lastRotation = Date . now ( ) ; const p = Promise . all ( [ _rotate ( options , paths . log ) , _rotate ( options , paths . error ) ] ) ; p . then ( ( ) => { reload ( options ) . then ( ( ) => { logger . debug ( 'Prosody reloaded' ) ; } , ( ) => { logger . error ( 'Prosody failed to reload' ) ; } ) ; } , ( err ) => { logger . error ( 'Failed rotating logs' , err ) ; } ) ; } , checkInterval ) ; logRotate = { timer : timer , lastRotation : Date . now ( ) } ; } function stopProsodyLogRotate ( options ) { const logger = options . peertubeHelpers . logger ; if ( logRotate === undefined ) { return ; } logger . info ( 'Stoping Prosody log rotation' ) ; clearInterval ( logRotate . timer ) ; } export { startProsodyLogRotate , stopProsodyLogRotate } ;