From 64bd4887f07425646da17c518b343ac944aea3f1 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Mon, 7 Aug 2023 20:05:14 -0400 Subject: [PATCH 1/4] Patch out redis when not running --- backend/endpoints/scan.py | 21 ++++++++++----- backend/endpoints/search.py | 11 ++------ backend/handler/igdb_handler.py | 20 +++++++++------ backend/handler/socket_manager.py | 4 +-- backend/main.py | 2 +- backend/utils/cache.py | 40 +++++++++++++++++++++++++++++ backend/worker.py | 11 ++++---- env.template | 2 +- examples/docker-compose.example.yml | 5 ++-- 9 files changed, 81 insertions(+), 35 deletions(-) create mode 100644 backend/utils/cache.py diff --git a/backend/endpoints/scan.py b/backend/endpoints/scan.py index 74ba7590b..0c72b56b7 100644 --- a/backend/endpoints/scan.py +++ b/backend/endpoints/scan.py @@ -7,15 +7,16 @@ 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 - - -scan_queue = Queue(connection=redis_conn) +from utils.cache import redis_client, redis_url, redis_connectable 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 +78,11 @@ 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 = Queue(connection=redis_client) + + # Queue up a job for all platform + 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..27e54979c 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,9 +246,12 @@ 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() > token_expires_at: log.warning("Twitch token invalid: fetching a new one...") return self._update_twitch_token() - return token + return self.oauth_token diff --git a/backend/handler/socket_manager.py b/backend/handler/socket_manager.py index 53bda9c42..5739a7d06 100644 --- a/backend/handler/socket_manager.py +++ b/backend/handler/socket_manager.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/main.py b/backend/main.py index e1fe9818a..25c4cb039 100644 --- a/backend/main.py +++ b/backend/main.py @@ -6,7 +6,7 @@ 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 app = FastAPI() app.add_middleware( diff --git a/backend/utils/cache.py b/backend/utils/cache.py new file mode 100644 index 000000000..2b418427b --- /dev/null +++ b/backend/utils/cache.py @@ -0,0 +1,40 @@ +from redis import Redis, ConnectionError + +from config import REDIS_HOST, REDIS_PORT + +redis_client = Redis(host=REDIS_HOST, port=REDIS_PORT, db=0) # decode_responses +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) + + +cache = redis_client if redis_connectable else FallbackCache() diff --git a/backend/worker.py b/backend/worker.py index ef96c2b37..c0280fc70 100755 --- a/backend/worker.py +++ b/backend/worker.py @@ -1,13 +1,14 @@ -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): + if not redis_connectable: + sys.exit(2) + + 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 From 76774a7577fe357e12d4c0f08d017fba03261e24 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Mon, 7 Aug 2023 20:32:22 -0400 Subject: [PATCH 2/4] Move sockets to utils --- backend/endpoints/scan.py | 7 +++---- backend/handler/igdb_handler.py | 4 ++-- backend/main.py | 2 +- backend/utils/cache.py | 3 ++- backend/{handler/socket_manager.py => utils/socket.py} | 0 5 files changed, 8 insertions(+), 8 deletions(-) rename backend/{handler/socket_manager.py => utils/socket.py} (100%) diff --git a/backend/endpoints/scan.py b/backend/endpoints/scan.py index 0c72b56b7..56f1c9546 100644 --- a/backend/endpoints/scan.py +++ b/backend/endpoints/scan.py @@ -6,9 +6,11 @@ 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 utils.socket import socket_server from utils.cache import redis_client, redis_url, redis_connectable +scan_queue = Queue(connection=redis_client) + async def scan_platforms(paltforms: str, complete_rescan: bool): # Connect to external socketio server @@ -80,9 +82,6 @@ async def scan_handler(_sid: str, platforms: str, complete_rescan: bool = True): # Run in worker if redis is available if redis_connectable: - scan_queue = Queue(connection=redis_client) - - # Queue up a job for all platform scan_queue.enqueue(scan_platforms, platforms, complete_rescan) else: await scan_platforms(platforms, complete_rescan) diff --git a/backend/handler/igdb_handler.py b/backend/handler/igdb_handler.py index 27e54979c..1a0a93777 100644 --- a/backend/handler/igdb_handler.py +++ b/backend/handler/igdb_handler.py @@ -250,8 +250,8 @@ class TwitchAuth: token = cache.get("twitch_token") token_expires_at = cache.get("twitch_token_expires_at") - if not token or time.time() > token_expires_at: + if not token or time.time() > float(token_expires_at): log.warning("Twitch token invalid: fetching a new one...") return self._update_twitch_token() - return self.oauth_token + return token diff --git a/backend/main.py b/backend/main.py index 25c4cb039..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 utils.socket import socket_app app = FastAPI() app.add_middleware( diff --git a/backend/utils/cache.py b/backend/utils/cache.py index 2b418427b..5b277f59e 100644 --- a/backend/utils/cache.py +++ b/backend/utils/cache.py @@ -37,4 +37,5 @@ class FallbackCache: return repr(self) -cache = redis_client if redis_connectable else FallbackCache() +_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 100% rename from backend/handler/socket_manager.py rename to backend/utils/socket.py From 2bb5316e26cd2d89803442616175cbb925b9f206 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Mon, 7 Aug 2023 20:36:59 -0400 Subject: [PATCH 3/4] Changes from self review --- backend/utils/cache.py | 3 ++- backend/worker.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/backend/utils/cache.py b/backend/utils/cache.py index 5b277f59e..e83cd6fa2 100644 --- a/backend/utils/cache.py +++ b/backend/utils/cache.py @@ -2,7 +2,7 @@ from redis import Redis, ConnectionError from config import REDIS_HOST, REDIS_PORT -redis_client = Redis(host=REDIS_HOST, port=REDIS_PORT, db=0) # decode_responses +redis_client = Redis(host=REDIS_HOST, port=REDIS_PORT, db=0) redis_url = f"redis://{REDIS_HOST}:{REDIS_PORT}" try: @@ -37,5 +37,6 @@ class FallbackCache: 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/worker.py b/backend/worker.py index c0280fc70..5fc4b08c2 100755 --- a/backend/worker.py +++ b/backend/worker.py @@ -6,8 +6,9 @@ from utils.cache import redis_client, redis_connectable listen = ["high", "default", "low"] if __name__ == "__main__": + # Exit if Redis is not connectable if not redis_connectable: - sys.exit(2) + sys.exit(0) with Connection(redis_client): worker = Worker(map(Queue, listen)) From e596a4d0ac3abcddbc27819c4fa06cdba2abc1df Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 9 Aug 2023 00:50:40 +0200 Subject: [PATCH 4/4] fixed cached token --- backend/handler/igdb_handler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/handler/igdb_handler.py b/backend/handler/igdb_handler.py index 1a0a93777..3c904259e 100644 --- a/backend/handler/igdb_handler.py +++ b/backend/handler/igdb_handler.py @@ -250,7 +250,7 @@ class TwitchAuth: token = cache.get("twitch_token") token_expires_at = cache.get("twitch_token_expires_at") - if not token or time.time() > float(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()