Files
romm/backend/endpoints/firmware.py
Sam Dornan fd9a33bc35 fix(backend): return identifiers without building an ORM row per id (#4586)
* fix(backend): project the identifier endpoints onto the id column

The `/identifiers` routes for saves, states, firmware, platforms, smart
collections and rom notes each asked their handler for entities with
`only_fields=[Model.id]`. `load_only` narrows the selected columns but does
not cancel an eager relationship, so a `lazy="joined"` join still fired and a
full entity was still built for every row. The platforms route was the worst
of the six: `with_firmware` eager-loads every firmware row and its platform,
and `load_only` does not cancel that either.

Each handler grows a small query builder shared by its existing accessor and a
new `*_ids` accessor that projects onto the id column with
`with_only_columns`, which drops the entity and with it the eager joins. The
firmware accessor already applied `noload`, so its SQL is unchanged; it moves
to the projection only to stop building rows.

`/api/users/identifiers` and the two `/collections` callers that use more than
an id are left alone, because nothing eager fires for them.

The `executed_statements` fixture moves to `tests/conftest.py` so the new
endpoint tests can use it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Update backend/tests/endpoints/test_identifier_endpoints.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* style(backend): drop the leading blank line black rejects

Removing the module docstring in the GitHub edit left an empty first line,
which is the only thing black wanted to change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(backend): drive the note-identifier test through the endpoint

Greptile flagged the handler-level test for bypassing the route's auth,
404, and visibility checks. It now issues the request the frontend would
and asserts the id-only projection holds among the route's own reads.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* refactor(backend): fold the duplicate SQL-capture fixtures into the shared one

Step 3 of the PR-ready gauntlet (simplify). The shared
`executed_statements` fixture gains the two roms test files that still
declared byte-identical local copies, and the id-only assertions share one
statement parser instead of two.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(backend): tighten the get_platform_ids docstring to one line

Step 4 of the PR-ready gauntlet (review-polish).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-09-17 11:13:07 -05:00

344 lines
10 KiB
Python

from pathlib import Path
from typing import Annotated
from fastapi import Body, File, HTTPException, Query, Request, UploadFile, status
from fastapi.responses import FileResponse
from config import DISABLE_DOWNLOAD_ENDPOINT_AUTH
from decorators.auth import protected_route
from endpoints.responses import BulkOperationResponse
from endpoints.responses.firmware import AddFirmwareResponse, FirmwareSchema
from handler.auth.constants import Scope
from handler.auth.dependencies import (
assert_can,
assert_firmware_visible,
assert_platform_visible,
get_permissions,
)
from handler.database import db_firmware_handler, db_platform_handler
from handler.filesystem import fs_firmware_handler
from handler.scan_handler import scan_firmware
from logger.formatter import BLUE
from logger.formatter import highlight as hl
from logger.logger import log
from models.firmware import Firmware
from models.permission import PermAction, PermEntity
from utils.router import APIRouter
router = APIRouter(
prefix="/firmware",
tags=["firmware"],
)
@protected_route(router.post, "", [Scope.FIRMWARE_WRITE])
async def add_firmware(
request: Request,
platform_id: int,
files: list[UploadFile] = File(...), # noqa: B008
) -> AddFirmwareResponse:
"""Upload firmware files endpoint
Args:
request (Request): Fastapi Request object
platform_slug (str): Slug of the platform where to upload the files
files (list[UploadFile], optional): List of files to upload
Raises:
HTTPException
Returns:
AddFirmwareResponse: Standard message response
"""
db_platform = db_platform_handler.get_platform(platform_id)
if not db_platform:
error = f"Platform with ID {platform_id} not found"
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
# Platform-hide cascades to firmware; 404-mask uploads to hidden platforms.
assert_platform_visible(
request,
db_platform,
not_found_detail=f"Platform with ID {platform_id} not found",
)
uploaded_firmware = []
firmware_path = fs_firmware_handler.get_firmware_fs_structure(db_platform.fs_slug)
for file in files:
if not file.filename:
log.warning("Empty filename, skipping")
continue
log.info(
f"Uploading firmware {hl(file.filename)} to {hl(db_platform.custom_name or db_platform.name, color=BLUE)}"
)
await fs_firmware_handler.write_file(file=file, path=firmware_path)
db_firmware = db_firmware_handler.get_firmware_by_filename(
platform_id=db_platform.id, file_name=file.filename
)
# Scan or update firmware
scanned_firmware = await scan_firmware(
platform=db_platform,
file_name=file.filename,
firmware=db_firmware,
)
is_verified = Firmware.verify_file_hashes(
platform_slug=db_platform.slug,
file_name=file.filename,
file_size_bytes=scanned_firmware.file_size_bytes,
md5_hash=scanned_firmware.md5_hash,
sha1_hash=scanned_firmware.sha1_hash,
crc_hash=scanned_firmware.crc_hash,
)
if db_firmware:
db_firmware_handler.update_firmware(
db_firmware.id,
{
"file_size_bytes": scanned_firmware.file_size_bytes,
"is_verified": is_verified,
},
)
continue
scanned_firmware.platform_id = db_platform.id
scanned_firmware.is_verified = is_verified
db_firmware_handler.add_firmware(scanned_firmware)
uploaded_firmware.append(scanned_firmware)
return {
"uploaded": len(files),
"firmware": [
FirmwareSchema.model_validate(f)
for f in db_firmware_handler.list_firmware(
platform_ids=[platform_id] if platform_id else None
)
],
}
@protected_route(router.get, "", [Scope.FIRMWARE_READ])
def get_platform_firmware(
request: Request,
platform_id: int | None = None,
missing: Annotated[
bool | None,
Query(description="Whether the firmware is missing from the filesystem."),
] = None,
) -> list[FirmwareSchema]:
"""Get firmware endpoint
Args:
request (Request): Fastapi Request object
Returns:
list[FirmwareSchema]: Firmware stored in the database
"""
perms = get_permissions(request)
return [
FirmwareSchema.model_validate(f)
for f in db_firmware_handler.list_firmware(
platform_ids=[platform_id] if platform_id else None,
missing=missing,
hidden_platform_ids=perms.hidden_platform_ids,
)
]
@protected_route(router.get, "/identifiers", [Scope.FIRMWARE_READ])
def get_firmware_identifiers(
request: Request,
) -> list[int]:
"""Get firmware identifiers endpoint
Args:
request (Request): Fastapi Request object
Returns:
list[int]: List of firmware IDs
"""
perms = get_permissions(request)
return db_firmware_handler.list_firmware_ids(
hidden_platform_ids=perms.hidden_platform_ids,
)
@protected_route(
router.get,
"/{id}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
)
def get_firmware(request: Request, id: int) -> FirmwareSchema:
"""Get firmware endpoint
Args:
request (Request): Fastapi Request object
id (int): Firmware internal id
Returns:
FirmwareSchema: Firmware stored in the database
"""
firmware = db_firmware_handler.get_firmware(id)
if not firmware:
error = f"Firmware with ID {id} not found"
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
assert_firmware_visible(request, firmware)
return FirmwareSchema.model_validate(firmware)
def _resolve_firmware_content(request: Request, id: int) -> tuple[Firmware, Path]:
"""Resolve a firmware row and the readable file backing it.
Args:
request (Request): Fastapi Request object
id (int): Firmware internal id
Returns:
tuple[Firmware, Path]: The firmware row and its absolute path on disk
"""
firmware = db_firmware_handler.get_firmware(id)
if not firmware:
error = f"Firmware with ID {id} not found"
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
assert_firmware_visible(request, firmware)
firmware_path = fs_firmware_handler.validate_path(firmware.full_path)
# A row can outlive its file: the scan marks it missing, or it was moved
# away without one. Either way FileResponse would raise a 500.
if firmware.missing_from_fs or not firmware_path.is_file():
error = f"Firmware file '{firmware.file_name}' is missing from filesystem"
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
return firmware, firmware_path
@protected_route(
router.head,
"/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
)
def head_firmware_content(request: Request, id: int, file_name: str):
"""Head firmware content endpoint
Args:
request (Request): Fastapi Request object
id (int): Rom internal id
file_name (str): Required due to a bug in emulatorjs
Returns:
FileResponse: Returns the response with headers
"""
firmware, firmware_path = _resolve_firmware_content(request, id)
return FileResponse(
path=firmware_path,
filename=file_name,
headers={
"Content-Length": str(firmware.file_size_bytes),
},
)
@protected_route(
router.get,
"/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
)
def get_firmware_content(
request: Request,
id: int,
file_name: str,
):
"""Download firmware endpoint
Args:
request (Request): Fastapi Request object
id (int): Rom internal id
file_name (str): Required due to a bug in emulatorjs
Returns:
FileResponse: Returns the firmware file
"""
firmware, firmware_path = _resolve_firmware_content(request, id)
return FileResponse(path=firmware_path, filename=firmware.file_name)
@protected_route(router.post, "/delete", [Scope.FIRMWARE_WRITE])
async def delete_firmware(
request: Request,
firmware: Annotated[
list[int],
Body(
description="List of firmware ids to delete from database.",
embed=True,
),
],
delete_from_fs: Annotated[
list[int],
Body(
description="List of firmware ids to delete from filesystem.",
default_factory=list,
embed=True,
),
],
) -> BulkOperationResponse:
"""Delete firmware."""
perms = get_permissions(request)
assert_can(perms, PermEntity.FIRMWARE, PermAction.DELETE)
successful_items = 0
failed_ids = []
errors = []
for id in firmware:
fw = db_firmware_handler.get_firmware(id)
# Treat firmware on a hidden platform as non-existent for this caller.
if not fw or not perms.can_see_platform(fw.platform_id):
failed_ids.append(id)
errors.append(f"Firmware with ID {id} not found")
continue
try:
log.info(f"Deleting {hl(fw.file_name)} from database")
db_firmware_handler.delete_firmware(id)
if id in delete_from_fs:
log.info(f"Deleting {hl(fw.file_name)} from filesystem")
try:
file_path = f"{fw.file_path}/{fw.file_name}"
await fs_firmware_handler.remove_file(file_path=file_path)
except FileNotFoundError:
error = f"Firmware file {hl(fw.file_name)} not found for platform {hl(fw.platform.slug)}"
log.error(error)
errors.append(error)
failed_ids.append(id)
continue
successful_items += 1
except Exception as e:
failed_ids.append(id)
errors.append(f"Failed to delete firmware {id}: {str(e)}")
return {
"successful_items": successful_items,
"failed_ids": failed_ids,
"errors": errors,
}