import { SavedObjectsErrorHelpers } from '../../../../../../src/core/server' ; import { APM_STATIC_INDEX_PATTERN_ID } from '../../../common/index_pattern_constants' ; import { hasHistoricalAgentData } from '../../routes/historical_data/has_historical_agent_data' ; import { Setup } from '../../lib/helpers/setup_request' ; import { APMRouteHandlerResources } from '../../routes/typings' ; import { InternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client.js' ; import { withApmSpan } from '../../utils/with_apm_span' ; import { getApmDataViewTitle } from './get_apm_data_view_title' ; import { getApmDataViewAttributes } from './get_apm_data_view_attributes' ; interface ApmDataViewAttributes { title : string ; } export async function createStaticDataView ( { setup , config , savedObjectsClient , spaceId , } ) { return withApmSpan ( 'create_static_data_view' , async ( ) => { if ( ! config . autoCreateApmDataView ) { return false ; } const hasData = await hasHistoricalAgentData ( setup ) ; if ( ! hasData ) { return false ; } const apmDataViewTitle = getApmDataViewTitle ( setup . indices ) ; const forceOverwrite = await getForceOverwrite ( { apmDataViewTitle , savedObjectsClient , } ) ; try { await withApmSpan ( 'create_index_pattern_saved_object' , ( ) => savedObjectsClient . create ( 'index-pattern' , getApmDataViewAttributes ( apmDataViewTitle ) , { id : APM_STATIC_INDEX_PATTERN_ID , overwrite : forceOverwrite , namespace : spaceId , } ) ) ; return true ; } catch ( e ) { if ( SavedObjectsErrorHelpers . isConflictError ( e ) ) { return false ; } throw e ; } } ) ; } async function getForceOverwrite ( { savedObjectsClient , apmDataViewTitle , } ) { try { const existingDataView = await savedObjectsClient . get < ApmDataViewAttributes > ( 'index-pattern' , APM_STATIC_INDEX_PATTERN_ID ) ; return existingDataView . attributes . title !== apmDataViewTitle ; } catch ( e ) { if ( SavedObjectsErrorHelpers . isNotFoundError ( e ) ) { return false ; } throw e ; } }