import { CoreSetup } from 'opensearch-dashboards/server' ; import { Usage } from './register' ; const SAVED_OBJECT_ID = 'search-telemetry' ; export interface SearchUsage { trackError ( ) : Promise < void > ; trackSuccess ( duration ) : Promise < void > ; } export function usageProvider ( core ) { const getTracker = ( eventType ) => { return async ( duration ? ) => { const repository = await core . getStartServices ( ) . then ( ( [ coreStart ] ) => coreStart . savedObjects . createInternalRepository ( ) ) ; let attributes ; let doesSavedObjectExist = true ; try { const response = await repository . get < Usage > ( SAVED_OBJECT_ID , SAVED_OBJECT_ID ) ; attributes = response . attributes ; } catch ( e ) { doesSavedObjectExist = false ; attributes = { successCount : 0 , errorCount : 0 , averageDuration : 0 , } ; } attributes [ eventType ] ++ ; if ( eventType === 'successCount' ) { attributes . averageDuration = ( ( duration ?? 0 ) + ( attributes . averageDuration ?? 0 ) ) / ( attributes . successCount ?? 1 ) ; } try { if ( doesSavedObjectExist ) { await repository . update ( SAVED_OBJECT_ID , SAVED_OBJECT_ID , attributes ) ; } else { await repository . create ( SAVED_OBJECT_ID , attributes , { id : SAVED_OBJECT_ID } ) ; } } catch ( e ) { } } ; } ; return { trackError : ( ) => getTracker ( 'errorCount' ) ( ) , trackSuccess : getTracker ( 'successCount' ) , } ; }