import { EventEmitter } from 'events' ; import * as ts from '@terascope/utils' ; import { createConnection } from '../connector-utils' ; import { createRootLogger } from './utils' ; import * as i from '../interfaces' ; export default function registerApis ( context ) { const foundationConfig = context . sysconfig . terafoundation ; const events = new EventEmitter ( ) ; context . logger = createRootLogger ( context ) ; const connections = Object . create ( null ) ; const foundationApis = { getConnection ( options ) { const { type , endpoint = 'default' , cached } = options ; const key = `${ type }:${ endpoint }` ; const { connectors } = foundationConfig ; if ( cached && Object . prototype . hasOwnProperty . call ( connections , key ) ) { return connections [ key ] ; } if ( Object . prototype . hasOwnProperty . call ( connectors , type ) ) { context . logger . info ( `creating connection for ${ type }` ) ; let moduleConfig = { } ; if ( Object . prototype . hasOwnProperty . call ( connectors [ type ] , endpoint ) ) { moduleConfig = Object . assign ( { } , foundationConfig . connectors [ type ] [ endpoint ] ) ; } else if ( endpoint ) { throw new Error ( `No ${ type } endpoint configuration found for ${ endpoint }` ) ; } const connection = createConnection ( type , moduleConfig , context . logger , options ) ; if ( cached ) { connections [ key ] = connection ; } return connection ; } throw new Error ( `No connection configuration found for ${ type }` ) ; } , makeLogger ( ... args ) { const childLogger = context . logger . child ( ts . isPlainObject ( args [ 0 ] ) ? args [ 0 ] : args [ 2 ] ) ; childLogger . flush = context . logger . flush ; return childLogger ; } , getSystemEvents ( ) { return events ; } , startWorkers ( num , envOptions ) { const { cluster } = context ; const env = { assignment : 'worker' , service_context : JSON . stringify ( { assignment : 'worker' } ) } ; if ( envOptions ) { Object . assign ( env , envOptions ) ; env . service_context = JSON . stringify ( envOptions ) ; } const workers = [ ] ; if ( cluster . isMaster ) { context . logger . info ( `Starting ${ num } ${ env . assignment }` ) ; ts . times ( num , ( ) => { const worker = cluster . fork ( env ) ; Object . assign ( worker , env ) ; workers . push ( worker ) ; } ) ; } return workers ; } } ; function _registerFoundationAPIs ( ) { registerAPI ( 'foundation' , foundationApis ) ; } function _registerLegacyAPIs ( ) { const { getSystemEvents , ... legacyApis } = foundationApis ; context . foundation = { ... legacyApis , getEventEmitter : getSystemEvents , } ; } function registerAPI ( name , api ) { if ( Object . prototype . hasOwnProperty . call ( context . apis , name ) ) { throw new Error ( `Registration of API endpoints for module ${ name } can only occur once` ) ; } else { context . apis [ name ] = api ; } } context . apis = { registerAPI } as any ; _registerFoundationAPIs ( ) ; _registerLegacyAPIs ( ) ; }