mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
Merge pull request #328 from zurdi15/redis-patch
Fallback when Redis unavailable
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -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 <expires_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()
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
42
backend/utils/cache.py
Normal file
42
backend/utils/cache.py
Normal file
@@ -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"<FallbackCache {self.fallback}>"
|
||||
|
||||
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()
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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=<database password> # [Optional] Only needed if ROMM_DB_DRIVER=mariadb
|
||||
- REDIS_HOST=redis
|
||||
- REDIS_HOST=redis # [Optional]
|
||||
- REDIS_PORT=6379 # [Optional]
|
||||
- CLIENT_ID=<IGDB client id>
|
||||
- CLIENT_SECRET=<IGDB client secret>
|
||||
- STEAMGRIDDB_API_KEY=<SteamGridDB api key>
|
||||
- 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
|
||||
|
||||
Reference in New Issue
Block a user