dino-express
Version:
DinO enabled REST framework based on express
74 lines • 3.21 kB
JavaScript
"use strict";
// Copyright 2018 Quirino Brizi [quirino.brizi@gmail.com]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CO2EmissionMonitor = void 0;
const dino_core_1 = require("dino-core");
const co2_1 = require("@tgwf/co2");
const ObjectSizeCalculator_1 = require("../ObjectSizeCalculator");
class CO2EmissionMonitor extends dino_core_1.Monitor {
properties;
co2EmissionCalculator;
objectSizeCalculator;
constructor() {
super();
this.objectSizeCalculator = new ObjectSizeCalculator_1.ObjectSizeCalculator();
this.properties = new Map();
this.properties.set('model', '1byte');
this.properties.set('totalCO2GramsPerByte', 0);
this.properties.set('requests', {
total: 0,
totalCO2GramsPerByteRead: 0
});
this.properties.set('responses', {
total: 0,
totalCO2GramsPerByteWritten: 0
});
// eslint-disable-next-line new-cap
this.co2EmissionCalculator = new co2_1.co2({ model: '1byte' });
}
execute() {
return dino_core_1.State.from(this.properties);
}
getName() {
return 'CO2 Emissions';
}
requestMiddleware(req, _res, next) {
this.collectRequestInfoRequired(req);
next();
}
responseMiddleware(_req, res, next) {
this.collectResponseInfoRequired(res);
next();
}
collectRequestInfoRequired(req) {
const requests = this.properties.get('requests');
const bytes = dino_core_1.ObjectHelper.isDefined(req.socket) ? req.socket.bytesRead : this.objectSizeCalculator.calculateSize(req);
const co2Emission = this.co2EmissionCalculator.perByte(bytes);
requests.total += 1;
requests.totalCO2GramsPerByteRead += co2Emission;
this.properties.set('totalCO2GramsPerByte', this.properties.get('totalCO2GramsPerByte') + co2Emission);
}
collectResponseInfoRequired(res) {
const responses = this.properties.get('responses');
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const bytes = dino_core_1.ObjectHelper.isDefined(res.socket) ? res.socket.bytesWritten : this.objectSizeCalculator.calculateSize(res);
const co2Emission = this.co2EmissionCalculator.perByte(bytes);
responses.total += 1;
responses.totalCO2GramsPerByteWritten += co2Emission;
this.properties.set('totalCO2GramsPerByte', this.properties.get('totalCO2GramsPerByte') + co2Emission);
}
}
exports.CO2EmissionMonitor = CO2EmissionMonitor;
//# sourceMappingURL=co2.emission.monitor.js.map