summaryrefslogtreecommitdiff
path: root/backend/src
diff options
context:
space:
mode:
Diffstat (limited to 'backend/src')
-rw-r--r--backend/src/database/postgres.ts2
-rw-r--r--backend/src/simulation/robotMovementSimulator.ts27
2 files changed, 24 insertions, 5 deletions
diff --git a/backend/src/database/postgres.ts b/backend/src/database/postgres.ts
index 6f6b682..e2493a9 100644
--- a/backend/src/database/postgres.ts
+++ b/backend/src/database/postgres.ts
@@ -8,7 +8,7 @@ const pool = new Pool({
port: process.env.DB_PORT ? parseInt(process.env.DB_PORT) : 5432,
});
-/* Too strict for Docker:
+/* Too strict for Docker, use docker compose healthcheck instead:
pool.connect((error, _client, release) => {
if (error) {
console.error("Verbindung zur Datenbank fehlgeschlagen: ", error);
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);