import { VehicleEvent , Device , Telemetry } from '@mds-core/mds-types' ; import logger from '@mds-core/mds-logger' ; import { dropTables , updateSchema } from './migration' ; import { MDSPostgresClient } from './sql-utils' ; import { getReadOnlyClient , getWriteableClient , makeReadOnlyQuery } from './client' ; import * as devices from './devices' ; import * as events from './events' ; import * as policies from './policies' ; import * as geographies from './geographies' ; import * as audit from './audits' ; import * as trips from './trips' ; import * as telemetry from './telemetry' ; import * as stops from './stops' ; import * as attachments from './attachments' ; const { writeDevice } = devices ; const { writeTelemetry } = telemetry ; const { writeEvent } = events ; async function initialize ( ) { const client = await getWriteableClient ( ) ; await dropTables ( client ) ; await updateSchema ( client ) ; await getReadOnlyClient ( ) ; return 'postgres' ; } async function health ( ) { logger . info ( 'postgres health check' ) ; const currentQueriesSQL = `SELECT query
    FROM pg_stat_activity
    WHERE query <> '<IDLE>' AND query NOT ILIKE '%pg_stat_activity%' AND query <> ''
    ORDER BY query_start desc` ; const currentQueriesResult = await makeReadOnlyQuery ( currentQueriesSQL ) ; const cacheHitQuery = `SELECT sum(heap_blks_read) as heap_read, sum(heap_blks_hit)
      as heap_hit, (sum(heap_blks_hit) - sum(heap_blks_read)) / sum(heap_blks_hit + 1)
      as ratio
      FROM pg_statio_user_tables;` ; const [ cacheHitResult ] = await makeReadOnlyQuery ( cacheHitQuery ) ; return { using : 'postgres' , stats : { current_running_queries : currentQueriesResult . length , cache_hit_result : cacheHitResult } } ; } async function startup ( ) { await Promise . all ( [ getWriteableClient ( ) , getReadOnlyClient ( ) ] ) ; } async function shutdown ( ) { try { const writeableClient = await getWriteableClient ( ) ; await writeableClient . end ( ) ; const readOnlyClient = await getReadOnlyClient ( ) ; await readOnlyClient . end ( ) ; } catch ( err ) { logger . error ( 'error during disconnection' , err . stack ) ; } } async function seed ( data ) { if ( data ) { logger . info ( 'postgres seed start' ) ; if ( data . devices ) { await Promise . all ( data . devices . map ( async ( device ) => writeDevice ( device ) ) ) ; } logger . info ( 'postgres devices seeded' ) ; if ( data . events ) await Promise . all ( data . events . map ( async ( event ) => writeEvent ( event ) ) ) ; logger . info ( 'postgres events seeded' ) ; if ( data . telemetry ) { await writeTelemetry ( data . telemetry ) ; } logger . info ( 'postgres seed done' ) ; return Promise . resolve ( ) ; } return Promise . resolve ( 'no data' ) ; } export default { initialize , health , seed , startup , shutdown , ... devices , ... events , ... policies , ... geographies , ... audit , ... trips , ... telemetry , ... stops , ... attachments } ;