summaryrefslogtreecommitdiff
path: root/backend/src/simulation
diff options
context:
space:
mode:
Diffstat (limited to 'backend/src/simulation')
-rw-r--r--backend/src/simulation/robotMovementSimulator.ts27
1 files changed, 23 insertions, 4 deletions
diff --git a/backend/src/simulation/robotMovementSimulator.ts b/backend/src/simulation/robotMovementSimulator.ts
index 2299f43..d3a2564 100644
--- a/backend/src/simulation/robotMovementSimulator.ts
+++ b/backend/src/simulation/robotMovementSimulator.ts
@@ -1,6 +1,7 @@
import { QueryResult } from "pg";
import { Server } from "socket.io";
import db from "../database/postgres.js";
+import redisClient from "../database/redis.js";
import {
Robot,
RobotPosition,
@@ -8,6 +9,9 @@ import {
SimulationResponse,
} from "../types/robot.js";
+const CACHE_TTL = 10;
+const ROBOTS_CACHE_KEY = "allMyRobots";
+
// Coordinates for the boundaries of the frontend map
const LEIPZIG_AREA = {
WEST: 12.22,
@@ -70,10 +74,19 @@ async function updateRobotPositions(io: Server) {
try {
client = await db.connect();
- const allRobotsQuery: QueryResult<Robot> = await client.query(
- "SELECT * FROM robots ORDER BY id;"
- );
- const allRobots = allRobotsQuery.rows;
+ let allRobots;
+ const cachedData = await redisClient.get(ROBOTS_CACHE_KEY);
+
+ // Check Redis for cached data, otherwise query database
+ if (cachedData) {
+ allRobots = JSON.parse(cachedData);
+ } else {
+ const allRobotsQuery: QueryResult<Robot> = await client.query(
+ "SELECT * FROM robots ORDER BY id;"
+ );
+
+ allRobots = allRobotsQuery.rows;
+ }
// Update database
await client.query("BEGIN");
@@ -142,6 +155,12 @@ async function updateRobotPositions(io: Server) {
await client.query("COMMIT");
+ // Keep robots in Redis cache indefinitely while simulation is running to avoid db query on every tick
+ // Once the simulation stops, keep the cache alive for 10 seconds
+ await redisClient.set(ROBOTS_CACHE_KEY, JSON.stringify(updatedRobots), {
+ EX: movingRobots.size === 0 ? CACHE_TTL : undefined,
+ });
+
// Websocket broadcast, make sure robots stay in correct order
updatedRobots.sort((a, b) => a.id - b.id);