UNPKG

@extra/proxy-router

Version:
78 lines 3.12 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProxyRouterStats = void 0; class ProxyRouterStats { constructor(proxyServer) { this.proxyServer = proxyServer; /** Log of all connections (id, proxyName, host) */ this.connectionLog = []; this.connectionStats = new Map(); } /** @internal */ addConnection(id, proxy, host) { this.connectionLog.push({ id, proxy, host }); } /** @internal */ addStats(connectionId, stats) { this.connectionStats.set(connectionId, stats); } /** Get bytes transferred by proxy */ get byProxy() { this.getStatsFromActiveConnections(); // Get unique proxy names from our actual connection logs const proxyNames = Array.from(new Set(this.connectionLog.map(({ proxy }) => proxy))); const getConnectionIdsForProxy = (proxyName) => this.connectionLog .filter(({ proxy }) => proxy === proxyName) .map(({ id }) => id); const trafficByProxy = Object.fromEntries(proxyNames .map((proxyName) => { const ids = getConnectionIdsForProxy(proxyName); const stats = ids.map((id) => this.connectionStats.get(id)); const totalBytes = stats .map((stat) => this.calculateProxyBytes(stat)) .reduce((a, b) => a + b); return [proxyName, totalBytes]; }) // Sort by most bytes on top .sort((a, b) => b[1] - a[1])); return trafficByProxy; } /** Get bytes transferred by host */ get byHost() { this.getStatsFromActiveConnections(); // Get unique proxy names from our actual connection logs const hostNames = Array.from(new Set(this.connectionLog.map(({ host }) => host))); const getConnectionIdsForHost = (hostName) => this.connectionLog .filter(({ host }) => host === hostName) .map(({ id }) => id); const trafficByHost = Object.fromEntries(hostNames .map((hostName) => { const ids = getConnectionIdsForHost(hostName); const stats = ids.map((id) => this.connectionStats.get(id)); const totalBytes = stats .map((stat) => this.calculateProxyBytes(stat)) .reduce((a, b) => a + b); return [hostName, totalBytes]; }) // Sort by most bytes on top .sort((a, b) => b[1] - a[1])); return trafficByHost; } getStatsFromActiveConnections() { // collect stats for active connections this.proxyServer.getConnectionIds().forEach((connectionId) => { const stats = this.proxyServer.getConnectionStats(connectionId); if (stats) { this.connectionStats.set(connectionId, stats); } }); } calculateProxyBytes(stats) { if (!stats) { return 0; } return (stats.trgRxBytes || 0) + (stats.trgTxBytes || 0); } } exports.ProxyRouterStats = ProxyRouterStats; //# sourceMappingURL=stats.js.map