Skip to content

Commit

Permalink
Merge pull request #875 from rommapp/hard-heartbeat-refactor
Browse files Browse the repository at this point in the history
Heartbeat response refactor
  • Loading branch information
zurdi15 authored May 24, 2024
2 parents a71563f + 3e062e4 commit 60df7d5
Show file tree
Hide file tree
Showing 17 changed files with 92 additions and 152 deletions.
5 changes: 2 additions & 3 deletions backend/endpoints/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from handler.metadata.igdb_handler import IGDB_API_ENABLED
from handler.metadata.moby_handler import MOBY_API_ENABLED
from fastapi import APIRouter
from handler.github_handler import github_handler
from utils import get_version

router = APIRouter()

Expand All @@ -24,8 +24,7 @@ def heartbeat() -> HeartbeatResponse:
"""

return {
"VERSION": github_handler.get_version(),
"NEW_VERSION": github_handler.check_new_version(),
"VERSION": get_version(),
"ANY_SOURCE_ENABLED": IGDB_API_ENABLED or MOBY_API_ENABLED,
"METADATA_SOURCES": {
"IGDB_API_ENABLED": IGDB_API_ENABLED,
Expand Down
1 change: 0 additions & 1 deletion backend/endpoints/responses/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ class MetadataSourcesDict(TypedDict):

class HeartbeatResponse(TypedDict):
VERSION: str
NEW_VERSION: str
WATCHER: WatcherDict
SCHEDULER: SchedulerDict
ANY_SOURCE_ENABLED: bool
Expand Down
4 changes: 2 additions & 2 deletions backend/endpoints/tests/test_heartbeat.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient

from main import app
from handler.github_handler import github_handler
from utils import get_version

client = TestClient(app)

Expand All @@ -11,7 +11,7 @@ def test_heartbeat():
assert response.status_code == 200

heartbeat = response.json()
assert heartbeat.get("VERSION") == github_handler.get_version()
assert heartbeat.get("VERSION") == get_version()
assert heartbeat.get("WATCHER").get("ENABLED")
assert heartbeat.get("WATCHER").get("TITLE") == "Rescan on filesystem change"
assert heartbeat.get("SCHEDULER").get("RESCAN").get("ENABLED")
Expand Down
12 changes: 6 additions & 6 deletions backend/handler/database/firmware_handler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from decorators.database import begin_session
from models.firmware import Firmware
from sqlalchemy import update, delete, and_
from sqlalchemy import update, delete, and_, select
from sqlalchemy.orm import Session

from .base_handler import DBBaseHandler
Expand All @@ -16,19 +16,19 @@ def get_firmware(
self, id: int = None, platform_id: int = None, session: Session = None
):
return (
session.get(Firmware, id)
session.scalar(select(Firmware).filter_by(id=id).limit(1))
if id
else session.query(Firmware).filter_by(platform_id=platform_id).all()
else select(Firmware).filter_by(platform_id=platform_id).all()
)

@begin_session
def get_firmware_by_filename(
self, platform_id: int, file_name: str, session: Session = None
):
return (
session.query(Firmware)
return session.scalar(
select(Firmware)
.filter_by(platform_id=platform_id, file_name=file_name)
.first()
.limit(1)
)

@begin_session
Expand Down
42 changes: 13 additions & 29 deletions backend/handler/database/platforms_handler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import functools
from sqlalchemy import delete, or_
from sqlalchemy.orm import Session, Query, joinedload
from sqlalchemy import delete, or_, select
from sqlalchemy.orm import Session

from decorators.database import begin_session
from models.platform import Platform
Expand All @@ -9,47 +8,32 @@
from .base_handler import DBBaseHandler


def with_query(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
session = kwargs.get("session")
if session is None:
raise ValueError("session is required")

kwargs["query"] = session.query(Platform).options(joinedload(Platform.roms))
return func(*args, **kwargs)

return wrapper


class DBPlatformsHandler(DBBaseHandler):
@begin_session
@with_query
def add_platform(
self, platform: Platform, query: Query = None, session: Session = None
self, platform: Platform, session: Session = None
) -> Platform | None:
session.merge(platform)
session.flush()

return query.filter(Platform.fs_slug == platform.fs_slug).first()
return session.merge(platform)

@begin_session
@with_query
def get_platforms(
self, id: int = None, query: Query = None, session: Session = None
self, id: int = None, session: Session = None
) -> list[Platform] | Platform | None:
return (
query.get(id)
session.scalar(select(Platform).filter_by(id=id).limit(1))
if id
else (session.scalars(query.order_by(Platform.name.asc())).unique().all())
else (
session.scalars(select(Platform).order_by(Platform.name.asc()))
.unique()
.all()
)
)

@begin_session
@with_query
def get_platform_by_fs_slug(
self, fs_slug: str, query: Query = None, session: Session = None
self, fs_slug: str, session: Session = None
) -> Platform | None:
return session.scalars(query.filter_by(fs_slug=fs_slug).limit(1)).first()
return session.scalar(select(Platform).filter_by(fs_slug=fs_slug).limit(1))

@begin_session
def delete_platform(self, id: int, session: Session = None) -> int:
Expand Down
60 changes: 0 additions & 60 deletions backend/handler/github_handler.py

This file was deleted.

2 changes: 1 addition & 1 deletion backend/logger/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from logger.stdout_formatter import StdoutFormatter

# Get logger
# Set up logger
log = logging.getLogger("romm")
log.setLevel(logging.DEBUG)

Expand Down
4 changes: 2 additions & 2 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@
from fastapi.middleware.cors import CORSMiddleware
from fastapi_pagination import add_pagination
from handler.database import db_user_handler
from handler.github_handler import github_handler
from handler.socket_handler import socket_handler
from handler.auth import auth_handler
from handler.auth.base_handler import ALGORITHM
from handler.auth.hybrid_auth import HybridAuthBackend
from handler.auth.middleware import CustomCSRFMiddleware, SessionMiddleware
from starlette.middleware.authentication import AuthenticationMiddleware
from utils import get_version


@asynccontextmanager
Expand All @@ -46,7 +46,7 @@ async def lifespan(app: FastAPI):
yield


app = FastAPI(title="RomM API", version=github_handler.get_version(), lifespan=lifespan)
app = FastAPI(title="RomM API", version=get_version(), lifespan=lifespan)

app.add_middleware(
CORSMiddleware,
Expand Down
3 changes: 0 additions & 3 deletions backend/models/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ class Platform(BaseModel):
name: str = Column(String(length=400))
logo_path: str = Column(String(length=1000), default="")

roms: Mapped[set[Rom]] = relationship(
"Rom", lazy="selectin", back_populates="platform"
)
firmware: Mapped[set[Firmware]] = relationship(
"Firmware", lazy="selectin", back_populates="platform"
)
Expand Down
2 changes: 1 addition & 1 deletion backend/models/rom.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class Rom(BaseModel):
nullable=False,
)

platform = relationship("Platform", lazy="selectin", back_populates="roms")
platform = relationship("Platform", lazy="immediate")

saves: Mapped[list[Save]] = relationship(
"Save",
Expand Down
8 changes: 8 additions & 0 deletions backend/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from __version__ import __version__

def get_version() -> str:
"""Returns current version tag"""
if not __version__ == "<version>":
return __version__

return "development"
33 changes: 12 additions & 21 deletions frontend/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -99,32 +99,16 @@ onBeforeUnmount(() => {
socket.off("scan:scanning_rom");
socket.off("scan:done");
socket.off("scan:done_ko");
document.removeEventListener("network-quiesced", fetchHomeData);
});
onMounted(() => {
api.get("/config").then(({ data: data }) => {
configStore.set(data);
});
});
function fetchHomeData() {
// Remove it so it's not called multiple times
document.removeEventListener("network-quiesced", fetchHomeData);
api.get("/heartbeat").then(({ data: data }) => {
heartbeat.set(data);
});
platformApi
.getPlatforms()
.then(({ data: platforms }) => {
platformsStore.set(platforms);
})
.catch((error) => {
console.error(error);
});
api.get("/config").then(({ data: data }) => {
configStore.set(data);
});
userApi
.fetchCurrentUser()
Expand All @@ -134,9 +118,16 @@ function fetchHomeData() {
.catch((error) => {
console.error(error);
});
}
document.addEventListener("network-quiesced", fetchHomeData);
platformApi
.getPlatforms()
.then(({ data: platforms }) => {
platformsStore.set(platforms);
})
.catch((error) => {
console.error(error);
});
});
</script>

<template>
Expand Down
1 change: 0 additions & 1 deletion frontend/src/__generated__/models/HeartbeatResponse.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 60df7d5

Please sign in to comment.