handleReceiveBandwidthMessage.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import db from "@server/db";
  2. import { MessageHandler } from "../ws";
  3. import { clients, Newt } from "@server/db/schema";
  4. import { eq } from "drizzle-orm";
  5. import logger from "@server/logger";
  6. interface PeerBandwidth {
  7. publicKey: string;
  8. bytesIn: number;
  9. bytesOut: number;
  10. }
  11. export const handleReceiveBandwidthMessage: MessageHandler = async (context) => {
  12. const { message, client, sendToClient } = context;
  13. const newt = client as Newt;
  14. const bandwidthData: PeerBandwidth[] = message.data;
  15. if (!Array.isArray(bandwidthData)) {
  16. throw new Error("Invalid bandwidth data");
  17. }
  18. await db.transaction(async (trx) => {
  19. for (const peer of bandwidthData) {
  20. const { publicKey, bytesIn, bytesOut } = peer;
  21. // Find the site by public key
  22. const [client] = await trx
  23. .select()
  24. .from(clients)
  25. .where(eq(clients.pubKey, publicKey))
  26. .limit(1);
  27. if (!client) {
  28. continue;
  29. }
  30. let online = client.online;
  31. // 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
  32. if (bytesIn > 0 || bytesOut > 0) {
  33. online = true;
  34. } else if (client.lastBandwidthUpdate) {
  35. const lastBandwidthUpdate = new Date(
  36. client.lastBandwidthUpdate
  37. );
  38. const currentTime = new Date();
  39. const diff =
  40. currentTime.getTime() - lastBandwidthUpdate.getTime();
  41. if (diff < 300000) {
  42. online = false;
  43. }
  44. }
  45. // Update the site's bandwidth usage
  46. await trx
  47. .update(clients)
  48. .set({
  49. megabytesOut: (client.megabytesIn || 0) + bytesIn,
  50. megabytesIn: (client.megabytesOut || 0) + bytesOut,
  51. lastBandwidthUpdate: new Date().toISOString(),
  52. online
  53. })
  54. .where(eq(clients.clientId, client.clientId));
  55. }
  56. });
  57. logger.info("Handling register olm message!");
  58. };