import { ToolingLog } from '@osd/dev-utils' ; import { cloneDeep } from 'lodash' ; export interface IndexStats { skipped : boolean ; deleted : boolean ; created : boolean ; archived : boolean ; waitForSnapshot : number ; configDocs : { upgraded : number ; tagged : number ; upToDate : number ; } ; docs : { indexed : number ; archived : number ; } ; } export type Stats = ReturnType < typeof createStats > ; export function createStats ( name , log ) { const info = ( msg , ... args ) => log . info ( `[${ name }] ${ msg }` , ... args ) ; const debug = ( msg , ... args ) => log . debug ( `[${ name }] ${ msg }` , ... args ) ; const indices = { } ; const getOrCreate = ( index ) => { if ( ! indices [ index ] ) { indices [ index ] = { skipped : false , deleted : false , created : false , archived : false , waitForSnapshot : 0 , configDocs : { upgraded : 0 , tagged : 0 , upToDate : 0 , } , docs : { indexed : 0 , archived : 0 , } , } ; } return indices [ index ] ; } ; return new ( class Stats { param index public skippedIndex ( index ) { getOrCreate ( index ) . skipped = true ; info ( 'Skipped restore for existing index %j' , index ) ; } param index public waitingForInProgressSnapshot ( index ) { getOrCreate ( index ) . waitForSnapshot += 1 ; info ( 'Waiting for snapshot of %j to complete' , index ) ; } param index public deletedIndex ( index ) { getOrCreate ( index ) . deleted = true ; info ( 'Deleted existing index %j' , index ) ; } param index public createdIndex ( index , metadata = { } ) { getOrCreate ( index ) . created = true ; info ( 'Created index %j' , index ) ; Object . keys ( metadata ) . forEach ( ( key ) => { debug ( '%j %s %j' , index , key , metadata [ key ] ) ; } ) ; } param index public archivedIndex ( index , metadata = { } ) { getOrCreate ( index ) . archived = true ; info ( 'Archived %j' , index ) ; Object . keys ( metadata ) . forEach ( ( key ) => { debug ( '%j %s %j' , index , key , metadata [ key ] ) ; } ) ; } param index public indexedDoc ( index ) { getOrCreate ( index ) . docs . indexed += 1 ; } param index public archivedDoc ( index ) { getOrCreate ( index ) . docs . archived += 1 ; } /**
         * Get a plain object version of the stats by index
         */ public toJSON ( ) { return cloneDeep ( indices ) ; } param fn public forEachIndex ( fn ) { const clone = this . toJSON ( ) ; Object . keys ( clone ) . forEach ( ( index ) => { fn ( index , clone [ index ] ) ; } ) ; } } ) ( ) ; }