import { BigQuery } from '@google-cloud/bigquery' ; import * as express from 'express' ; import * as fs from 'fs' ; import * as path from 'path' ; import * as connections from './connection_metrics' ; import * as features from './feature_metrics' ; interface Config { datasetName : string ; connectionMetricsTableName : string ; featureMetricsTableName : string ; } function loadConfig ( ) { const configText = fs . readFileSync ( path . join ( __dirname , 'config.json' ) , { encoding : 'utf8' } ) ; return JSON . parse ( configText ) ; } const PORT = Number ( process . env . PORT ) || 8080 ; const config = loadConfig ( ) ; const bigqueryDataset = new BigQuery ( { projectId : 'uproxysite' } ) . dataset ( config . datasetName ) ; const connectionsTable = new connections . BigQueryConnectionsTable ( bigqueryDataset . table ( config . connectionMetricsTableName ) ) ; const featuresTable = new features . BigQueryFeaturesTable ( bigqueryDataset . table ( config . featureMetricsTableName ) ) ; const app = express ( ) ; app . use ( express . json ( ) ) ; app . post ( '/connections' , async ( req , res ) => { try { if ( ! connections . isValidConnectionMetricsReport ( req . body ) ) { res . status ( 400 ) . send ( 'Invalid request' ) ; return ; } await connections . postConnectionMetrics ( connectionsTable , req . body ) ; res . status ( 200 ) . send ( 'OK' ) ; } catch ( err ) { res . status ( 500 ) . send ( `Error: ${ err }` ) ; } } ) ; app . post ( '/features' , async ( req , res ) => { try { if ( ! features . isValidFeatureMetricsReport ( req . body ) ) { res . status ( 400 ) . send ( 'Invalid request' ) ; return ; } await features . postFeatureMetrics ( featuresTable , req . body ) ; res . status ( 200 ) . send ( 'OK' ) ; } catch ( err ) { res . status ( 500 ) . send ( `Error: ${ err }` ) ; } } ) ; app . listen ( PORT , ( ) => { console . log ( `Metrics server listening on port ${ PORT }` ) ; } ) ;