Skip to content

Commit

Permalink
Use a Map.
Browse files Browse the repository at this point in the history
  • Loading branch information
sbruens committed Oct 17, 2024
1 parent 94c2219 commit 98a4ce3
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions src/shadowbox/server/shared_metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,27 +101,33 @@ export class PrometheusUsageMetrics implements UsageMetrics {
)
`);

const usage: {[key: string]: LocationUsage} = {};
for (const entry of queryResponse.result) {
const country = entry.metric['location'] || '';
const asn = entry.metric['asn'] ? Number(entry.metric['asn']) : undefined;
const usage = new Map<string, LocationUsage>();
for (const result of queryResponse.result) {
const country = result.metric['location'] || '';
const asn = result.metric['asn'] ? Number(result.metric['asn']) : undefined;

// Create or update the entry for the country+ASN combination.
// Get or create an entry for the country+ASN combination.
const key = `${country}-${asn}`;
usage[key] = {
country,
asn,
inboundBytes: usage[key]?.inboundBytes || 0,
tunnelTimeSec: usage[key]?.tunnelTimeSec || 0,
};
let entry: LocationUsage;
if (usage.has(key)) {
entry = usage.get(key);
} else {
entry = {
country,
asn,
inboundBytes: 0,
tunnelTimeSec: 0,
};
}

if (entry.metric['metric_type'] === 'inbound_bytes') {
usage[key].inboundBytes = Math.round(parseFloat(entry.value[1]));
} else if (entry.metric['metric_type'] === 'tunnel_time') {
usage[key].tunnelTimeSec = Math.round(parseFloat(entry.value[1]));
if (result.metric['metric_type'] === 'inbound_bytes') {
entry.inboundBytes = Math.round(parseFloat(result.value[1]));
} else if (result.metric['metric_type'] === 'tunnel_time') {
entry.tunnelTimeSec = Math.round(parseFloat(result.value[1]));
}
usage.set(key, entry);
}
return Object.values(usage);
return Array.from(usage.values());
}

reset() {
Expand Down

0 comments on commit 98a4ce3

Please sign in to comment.