1// Copyright (C) 2020 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import {Actions} from '../common/actions'; 16import {Engine} from '../common/engine'; 17import {QueryError} from '../common/query_result'; 18import {publishMetricResult} from '../frontend/publish'; 19 20import {Controller} from './controller'; 21import {globals} from './globals'; 22 23export class MetricsController extends Controller<'main'> { 24 private engine: Engine; 25 private currentlyRunningMetric?: string; 26 27 constructor(args: {engine: Engine}) { 28 super('main'); 29 this.engine = args.engine; 30 this.run(); 31 } 32 33 private async computeMetric(name: string) { 34 if (name === this.currentlyRunningMetric) return; 35 this.currentlyRunningMetric = name; 36 try { 37 const metricResult = await this.engine.computeMetric([name]); 38 publishMetricResult({ 39 name, 40 resultString: metricResult.metricsAsPrototext, 41 }); 42 } catch (e) { 43 if (e instanceof QueryError) { 44 // Reroute error to be displated differently when metric is run through 45 // metric page. 46 publishMetricResult({name, error: e.message}); 47 } else { 48 throw e; 49 } 50 } 51 globals.dispatch(Actions.resetMetricRequest({name})); 52 this.currentlyRunningMetric = undefined; 53 } 54 55 run() { 56 const {requestedMetric} = globals.state.metrics; 57 if (!requestedMetric) return; 58 this.computeMetric(requestedMetric); 59 } 60} 61