diff --git a/src/mqtt.js b/src/mqtt.js index e7c7cfa..429b468 100644 --- a/src/mqtt.js +++ b/src/mqtt.js @@ -78,6 +78,11 @@ const optionsList = [ type: Number, description: "Nodes that haven't been heard from in this many seconds will be purged from the database.", }, + { + name: "purge-positions-after-seconds", + type: Number, + description: "Positions older than this many seconds will be purged from the database.", + }, ]; // parse command line args @@ -114,6 +119,7 @@ const decryptionKeys = options["decryption-keys"] ?? [ ]; const purgeIntervalSeconds = options["purge-interval-seconds"] ?? 10; const purgeNodesUnheardForSeconds = options["purge-nodes-unheard-for-seconds"] ?? null; +const purgePositionsAfterSeconds = options["purge-positions-after-seconds"] ?? null; // create mqtt client const client = mqtt.connect(mqttBrokerUrl, { @@ -139,6 +145,7 @@ const Waypoint = root.lookupType("Waypoint"); if(purgeIntervalSeconds){ setInterval(async () => { await purgeUnheardNodes(); + await purgeOldPositions(); }, purgeIntervalSeconds * 1000); } @@ -168,6 +175,32 @@ async function purgeUnheardNodes() { } +/** + * Purges all positions from the database that are older than the configured timeframe. + */ +async function purgeOldPositions() { + + // make sure seconds provided + if(!purgePositionsAfterSeconds){ + return; + } + + // delete all positions that are older than the configured purge time + try { + await prisma.position.deleteMany({ + where: { + created_at: { + // last updated before x seconds ago + lt: new Date(Date.now() - purgePositionsAfterSeconds * 1000), + }, + } + }); + } catch(e) { + // do nothing + } + +} + function createNonce(packetId, fromNode) { // Expand packetId to 64 bits