Improve bandiwdth update

This commit is contained in:
Owen
2025-06-27 10:36:58 -04:00
parent 8f1cfd8037
commit 073c318f12

View File

@@ -1,6 +1,6 @@
import { Request, Response, NextFunction } from "express"; import { Request, Response, NextFunction } from "express";
import { eq } from "drizzle-orm"; import { eq, and, lt, inArray } from "drizzle-orm";
import { sites, } from "@server/db"; import { sites } from "@server/db";
import { db } from "@server/db"; import { db } from "@server/db";
import logger from "@server/logger"; import logger from "@server/logger";
import createHttpError from "http-errors"; import createHttpError from "http-errors";
@@ -25,54 +25,94 @@ export const receiveBandwidth = async (
throw new Error("Invalid bandwidth data"); throw new Error("Invalid bandwidth data");
} }
await db.transaction(async (trx) => { const currentTime = new Date();
for (const peer of bandwidthData) { const oneMinuteAgo = new Date(currentTime.getTime() - 60000); // 1 minute ago
const { publicKey, bytesIn, bytesOut } = peer;
const [site] = await trx await db.transaction(async (trx) => {
// First, handle sites that are actively reporting bandwidth
const activePeers = bandwidthData.filter(peer => peer.bytesIn > 0 || peer.bytesOut > 0);
if (activePeers.length > 0) {
// Get all active sites in one query
const activeSites = await trx
.select() .select()
.from(sites) .from(sites)
.where(eq(sites.pubKey, publicKey)) .where(inArray(sites.pubKey, activePeers.map(p => p.publicKey)));
.limit(1);
if (!site) { // Create a map for quick lookup
continue; const siteMap = new Map();
} activeSites.forEach(site => {
let online = site.online; siteMap.set(site.pubKey, site);
});
// if the bandwidth for the site is > 0 then set it to online. if it has been less than 0 (no update) for 5 minutes then set it to offline // Update sites with actual bandwidth usage
if (bytesIn > 0 || bytesOut > 0) { for (const peer of activePeers) {
online = true; const site = siteMap.get(peer.publicKey);
} else if (site.lastBandwidthUpdate) { if (!site) continue;
const lastBandwidthUpdate = new Date(
site.lastBandwidthUpdate
);
const currentTime = new Date();
const diff =
currentTime.getTime() - lastBandwidthUpdate.getTime();
if (diff < 300000) {
online = false;
}
}
// Update the site's bandwidth usage
await trx await trx
.update(sites) .update(sites)
.set({ .set({
megabytesOut: (site.megabytesOut || 0) + bytesIn, megabytesOut: (site.megabytesOut || 0) + peer.bytesIn,
megabytesIn: (site.megabytesIn || 0) + bytesOut, megabytesIn: (site.megabytesIn || 0) + peer.bytesOut,
lastBandwidthUpdate: new Date().toISOString(), lastBandwidthUpdate: currentTime.toISOString(),
online online: true
}) })
.where(eq(sites.siteId, site.siteId)); .where(eq(sites.siteId, site.siteId));
} }
}
// Handle sites that reported zero bandwidth but need online status updated
const zeroBandwidthPeers = bandwidthData.filter(peer => peer.bytesIn === 0 && peer.bytesOut === 0);
if (zeroBandwidthPeers.length > 0) {
const zeroBandwidthSites = await trx
.select()
.from(sites)
.where(inArray(sites.pubKey, zeroBandwidthPeers.map(p => p.publicKey)));
for (const site of zeroBandwidthSites) {
let newOnlineStatus = site.online;
// Check if site should go offline based on last bandwidth update WITH DATA
if (site.lastBandwidthUpdate) {
const lastUpdateWithData = new Date(site.lastBandwidthUpdate);
if (lastUpdateWithData < oneMinuteAgo) {
newOnlineStatus = false;
}
} else {
// No previous data update recorded, set to offline
newOnlineStatus = false;
}
// Always update lastBandwidthUpdate to show this instance is receiving reports
// Only update online status if it changed
if (site.online !== newOnlineStatus) {
await trx
.update(sites)
.set({
lastBandwidthUpdate: currentTime.toISOString(),
online: newOnlineStatus
})
.where(eq(sites.siteId, site.siteId));
} else {
// Just update the heartbeat timestamp
await trx
.update(sites)
.set({
lastBandwidthUpdate: currentTime.toISOString()
})
.where(eq(sites.siteId, site.siteId));
}
}
}
}); });
return response(res, { return response(res, {
data: {}, data: {},
success: true, success: true,
error: false, error: false,
message: "Organization retrieved successfully", message: "Bandwidth data updated successfully",
status: HttpCode.OK status: HttpCode.OK
}); });
} catch (error) { } catch (error) {