diff --git a/backend/endpoints/scan.py b/backend/endpoints/scan.py index 74ba7590b..56f1c9546 100644 --- a/backend/endpoints/scan.py +++ b/backend/endpoints/scan.py @@ -6,16 +6,19 @@ from logger.logger import log from utils import fs, fastapi from utils.exceptions import PlatformsNotFoundException, RomsNotFoundException from handler import dbh -from handler.socket_manager import socket_server -from worker import redis_conn, redis_url +from utils.socket import socket_server +from utils.cache import redis_client, redis_url, redis_connectable - -scan_queue = Queue(connection=redis_conn) +scan_queue = Queue(connection=redis_client) async def scan_platforms(paltforms: str, complete_rescan: bool): # Connect to external socketio server - sm = socketio.AsyncRedisManager(redis_url, write_only=True) + sm = ( + socketio.AsyncRedisManager(redis_url, write_only=True) + if redis_connectable + else socket_server + ) # Scanning file system try: @@ -77,5 +80,8 @@ async def scan_handler(_sid: str, platforms: str, complete_rescan: bool = True): log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning ")) fs.store_default_resources() - # Queue up a job for each platform - scan_queue.enqueue(scan_platforms, platforms, complete_rescan) + # Run in worker if redis is available + if redis_connectable: + scan_queue.enqueue(scan_platforms, platforms, complete_rescan) + else: + await scan_platforms(platforms, complete_rescan) diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index fe28b9d58..cfc97016c 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -25,18 +25,11 @@ async def search_rom_igdb( elif search_by.lower() == "name": matched_roms = igdbh.get_matched_roms_by_name(search_term, rom["p_igdb_id"]) else: - log.info( - emoji.emojize( - f":video_game: {rom['p_slug']}: {rom['file_name']}" - ) - ) + log.info(emoji.emojize(f":video_game: {rom['p_slug']}: {rom['file_name']}")) matched_roms = igdbh.get_matched_roms(rom["file_name"], rom["p_igdb_id"]) log.info("Results:") - [ - log.info(f"\t - {rom['r_name']}") - for rom in matched_roms - ] + [log.info(f"\t - {rom['r_name']}") for rom in matched_roms] return {"roms": matched_roms, "msg": "success"} diff --git a/backend/handler/igdb_handler.py b/backend/handler/igdb_handler.py index fa6460050..3c904259e 100644 --- a/backend/handler/igdb_handler.py +++ b/backend/handler/igdb_handler.py @@ -2,16 +2,15 @@ import sys import functools import pydash import requests -from redis import Redis +import time from unidecode import unidecode as uc from requests.exceptions import HTTPError, Timeout -from config import CLIENT_ID, CLIENT_SECRET, REDIS_HOST, REDIS_PORT +from config import CLIENT_ID, CLIENT_SECRET from utils import get_file_name_with_no_tags as get_search_term from logger.logger import log - -redis_client = Redis(host=REDIS_HOST, port=REDIS_PORT, db=0, decode_responses=True) +from utils.cache import cache class IGDBHandler: @@ -235,7 +234,9 @@ class TwitchAuth: sys.exit(2) # Set token in redis to expire in seconds - redis_client.set("twitch_token", token, ex=expires_in - 10) + cache.set("twitch_token", token, ex=expires_in - 10) + cache.set("twitch_token_expires_at", time.time() + expires_in - 10) + log.info("Twitch token fetched!") return token @@ -245,8 +246,11 @@ class TwitchAuth: if "pytest" in sys.modules: return "test_token" - token = redis_client.get("twitch_token") - if not token: + # Fetch the token cache + token = cache.get("twitch_token") + token_expires_at = cache.get("twitch_token_expires_at") + + if not token or time.time() > float(token_expires_at or 0): log.warning("Twitch token invalid: fetching a new one...") return self._update_twitch_token() diff --git a/backend/main.py b/backend/main.py index e1fe9818a..f8f9a1151 100644 --- a/backend/main.py +++ b/backend/main.py @@ -5,8 +5,8 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi_pagination import add_pagination from config import DEV_PORT, DEV_HOST -from handler.socket_manager import socket_app -from endpoints import search, platform, rom, scan # noqa +from endpoints import search, platform, rom, scan # noqa +from utils.socket import socket_app app = FastAPI() app.add_middleware( diff --git a/backend/utils/cache.py b/backend/utils/cache.py new file mode 100644 index 000000000..e83cd6fa2 --- /dev/null +++ b/backend/utils/cache.py @@ -0,0 +1,42 @@ +from redis import Redis, ConnectionError + +from config import REDIS_HOST, REDIS_PORT + +redis_client = Redis(host=REDIS_HOST, port=REDIS_PORT, db=0) +redis_url = f"redis://{REDIS_HOST}:{REDIS_PORT}" + +try: + redis_connectable = redis_client.ping() +except ConnectionError: + redis_connectable = False + + +class FallbackCache: + def __init__(self) -> None: + self.fallback = {} + + def get(self, key: str, *args, **kwargs) -> str: + return self.fallback.get(key, "") + + def set(self, key: str, value: str, *args, **kwargs) -> None: + self.fallback[key] = value + + def delete(self, key: str, *args, **kwargs) -> None: + self.fallback.pop(key, None) + + def exists(self, key: str, *args, **kwargs) -> bool: + return key in self.fallback + + def flushall(self) -> None: + self.fallback = {} + + def __repr__(self) -> str: + return f"" + + def __str__(self) -> str: + return repr(self) + + +# A seperate client that auto-decodes responses is needed +_cache_client = Redis(host=REDIS_HOST, port=REDIS_PORT, db=0, decode_responses=True) +cache = _cache_client if redis_connectable else FallbackCache() diff --git a/backend/handler/socket_manager.py b/backend/utils/socket.py similarity index 58% rename from backend/handler/socket_manager.py rename to backend/utils/socket.py index 53bda9c42..5739a7d06 100644 --- a/backend/handler/socket_manager.py +++ b/backend/utils/socket.py @@ -1,6 +1,6 @@ import socketio -from worker import redis_url +from utils.cache import redis_url, redis_connectable socket_server = socketio.AsyncServer( @@ -8,7 +8,7 @@ socket_server = socketio.AsyncServer( async_mode="asgi", logger=False, engineio_logger=False, - client_manager=socketio.AsyncRedisManager(redis_url), + client_manager=socketio.AsyncRedisManager(redis_url) if redis_connectable else None, ) socket_app = socketio.ASGIApp(socket_server) diff --git a/backend/worker.py b/backend/worker.py index ef96c2b37..5fc4b08c2 100755 --- a/backend/worker.py +++ b/backend/worker.py @@ -1,13 +1,15 @@ -import redis +import sys from rq import Worker, Queue, Connection -from config import REDIS_HOST, REDIS_PORT +from utils.cache import redis_client, redis_connectable listen = ["high", "default", "low"] -redis_url = f"redis://{REDIS_HOST}:{REDIS_PORT}" -redis_conn = redis.from_url(redis_url) if __name__ == "__main__": - with Connection(redis_conn): + # Exit if Redis is not connectable + if not redis_connectable: + sys.exit(0) + + with Connection(redis_client): worker = Worker(map(Queue, listen)) worker.work() diff --git a/env.template b/env.template index 89ac5d2a4..d96c71b7e 100644 --- a/env.template +++ b/env.template @@ -19,6 +19,6 @@ DB_USER=romm DB_PASSWD= DB_ROOT_PASSWD= -# Redis config +# Redis config (optional) REDIS_HOST=127.0.0.1 REDIS_PORT=6379 diff --git a/examples/docker-compose.example.yml b/examples/docker-compose.example.yml index 8b252dd7d..3aa039414 100644 --- a/examples/docker-compose.example.yml +++ b/examples/docker-compose.example.yml @@ -12,10 +12,11 @@ services: - DB_USER=romm-user # [Optional] Only needed if ROMM_DB_DRIVER=mariadb - DB_NAME=romm # [Optional] Only needed if ROMM_DB_DRIVER=mariadb. Can be optionally changed, and should match the MYSQL_DATABASE value in the mariadb container. - DB_PASSWD= # [Optional] Only needed if ROMM_DB_DRIVER=mariadb - - REDIS_HOST=redis + - REDIS_HOST=redis # [Optional] + - REDIS_PORT=6379 # [Optional] - CLIENT_ID= - CLIENT_SECRET= - - STEAMGRIDDB_API_KEY= + - STEAMGRIDDB_API_KEY= # [Optional] volumes: - '/path/to/library:/romm/library' - '/path/to/resources:/romm/resources' # [Optional] Path where roms metadata (cover) are stored