diff --git a/server/db/schema.ts b/server/db/schema.ts index 3017c837..f7bc47e3 100644 --- a/server/db/schema.ts +++ b/server/db/schema.ts @@ -23,7 +23,9 @@ export const sites = sqliteTable("sites", { subnet: text("subnet").notNull(), megabytesIn: integer("bytesIn"), megabytesOut: integer("bytesOut"), - type: text("type").notNull() // "newt" or "wireguard" + lastBandwidthUpdate: text("lastBandwidthUpdate"), + type: text("type").notNull(), // "newt" or "wireguard" + online: integer("online", { mode: "boolean" }).notNull().default(false) }); export const resources = sqliteTable("resources", { diff --git a/server/routers/gerbil/receiveBandwidth.ts b/server/routers/gerbil/receiveBandwidth.ts index f63d3f22..266373a1 100644 --- a/server/routers/gerbil/receiveBandwidth.ts +++ b/server/routers/gerbil/receiveBandwidth.ts @@ -33,17 +33,30 @@ export const receiveBandwidth = async (req: Request, res: Response, next: NextFu logger.warn(`Site not found for public key: ${publicKey}`); continue; } + let online = site.online; + + // 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 + if (bytesIn > 0 || bytesOut > 0) { + online = true; + } else if (site.lastBandwidthUpdate) { + 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 db.update(sites) .set({ megabytesIn: (site.megabytesIn || 0) + bytesIn, megabytesOut: (site.megabytesOut || 0) + bytesOut, + lastBandwidthUpdate: new Date().toISOString(), + online, }) .where(eq(sites.siteId, site.siteId)); - logger.debug(`Updated bandwidth for site: ${site.siteId}: megabytesIn: ${(site.megabytesIn || 0) + bytesIn}, megabytesOut: ${(site.megabytesOut || 0) + bytesOut}`); - } return response(res, { diff --git a/server/routers/site/listSites.ts b/server/routers/site/listSites.ts index 40d84b88..a4f885e0 100644 --- a/server/routers/site/listSites.ts +++ b/server/routers/site/listSites.ts @@ -39,6 +39,7 @@ function querySites(orgId: string, accessibleSiteIds: number[]) { megabytesOut: sites.megabytesOut, orgName: orgs.name, type: sites.type, + online: sites.online, }) .from(sites) .leftJoin(orgs, eq(sites.orgId, orgs.orgId))