import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana' ; import { Logger } from '../../logging' ; import { GetAuthHeaders , Headers , isKibanaRequest , isRealRequest } from '../../http' ; import { ensureRawRequest , filterHeaders } from '../../http/router' ; import { ScopeableRequest } from '../types' ; import { ElasticsearchClient } from './types' ; import { configureClient } from './configure_client' ; import { ElasticsearchClientConfig } from './client_config' ; import { ScopedClusterClient , IScopedClusterClient } from './scoped_cluster_client' ; import { DEFAULT_HEADERS } from '../default_headers' ; const noop = ( ) => undefined ; public export interface IClusterClient { /**
     * A  ElasticsearchClient to be used to query the ES cluster on behalf of the Kibana internal user
      readonly asInternalUser : ElasticsearchClient ; /**
     * Creates a  IScopedClusterClient bound to given  ScopeableRequest asScoped : ( request : ScopeableRequest ) => IScopedClusterClient ; } /**
 * See  IClusterClient public export interface ICustomClusterClient extends IClusterClient { /**
     * Closes the cluster client. After that client cannot be used and one should
     * create a new client instance to be able to interact with Elasticsearch API.
     */ close : ( ) => Promise < void > ; } internal export class ClusterClient implements ICustomClusterClient { public readonly asInternalUser : KibanaClient ; private readonly rootScopedClient : KibanaClient ; private isClosed = false ; constructor ( private readonly config , logger , type , private readonly getAuthHeaders = noop , getExecutionContext = noop ) { this . asInternalUser = configureClient ( config , { logger , type , getExecutionContext } ) ; this . rootScopedClient = configureClient ( config , { logger , type , getExecutionContext , scoped : true , } ) ; } asScoped ( request ) { const scopedHeaders = this . getScopedHeaders ( request ) ; const scopedClient = this . rootScopedClient . child ( { headers : scopedHeaders , } ) ; return new ScopedClusterClient ( this . asInternalUser , scopedClient ) ; } public async close ( ) { if ( this . isClosed ) { return ; } this . isClosed = true ; await Promise . all ( [ this . asInternalUser . close ( ) , this . rootScopedClient . close ( ) ] ) ; } private getScopedHeaders ( request ) { let scopedHeaders ; if ( isRealRequest ( request ) ) { const requestHeaders = ensureRawRequest ( request ) . headers ?? { } ; const requestIdHeaders = isKibanaRequest ( request ) ? { 'x-opaque-id' : request . id } : { } ; const authHeaders = this . getAuthHeaders ( request ) ?? { } ; scopedHeaders = { ... filterHeaders ( requestHeaders , this . config . requestHeadersWhitelist ) , ... requestIdHeaders , ... authHeaders , } ; } else { scopedHeaders = filterHeaders ( request ?. headers ?? { } , this . config . requestHeadersWhitelist ) ; } return { ... DEFAULT_HEADERS , ... this . config . customHeaders , ... scopedHeaders , } ; } }