Files
romm/backend/endpoints/roms/notes.py
Sam Dornan d120602342 perf(backend): check rom-note visibility without the related load (#4587)
* perf(backend): check rom-note visibility without the related load

The five `/api/roms/{id}/notes*` routes each opened with `get_rom(id)` to
reach two scalars: `id` for the 404 and `id` plus `platform_id` for
`assert_rom_visible`. `get_rom` runs the whole `with_details` eager load, so
every note read or write paid for the platform, files, metadata, saves,
states, screenshots, rom_users, siblings, collections and notes of the rom,
about 12 statements.

`DBRomsHandler.get_rom_visibility` selects those two columns and nothing
else, and `assert_rom_visible` now takes the `RomVisibility` row it returns
as well as a full `Rom`, so no other caller of the check changes.

Measured on a 3,000-rom library with 300 notes on the target rom, one admin
request:

  GET  /api/roms/{id}/notes/identifiers  17 statements / 30,059 bytes -> 5 / 8,066
  POST /api/roms/{id}/notes              17 statements / 23,209 bytes -> 5 / 1,216

The server-side `Questions` delta per request falls from 33 to 21.

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>

* test(roms): match the rom lookup across dialects

The notes-load guard pinned the exact SQL text of the visibility lookup,
including MariaDB's `?` bind placeholder. psycopg renders the same query
as `%(id_1)s::INTEGER`, so the assertion could never match on the
PostgreSQL leg of the CI matrix and all three tests would have failed
there. Compare a dialect-independent prefix instead.

Step 2 of the pr-ready gauntlet: correctness fix plus the comment and
docstring trims it flagged.

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

* test: drop the second copy of the statement-capture fixture

`test_released_days.py` carried its own `captured_sql`, the same
before_cursor_execute listener the notes-load guard now shares as
`executed_statements` from tests/conftest.py. Point that file at the
shared fixture and drop the now-unused imports.

Step 3 of the pr-ready gauntlet: reuse and simplification fixes.

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

* test: name the notes auth helper as the other endpoint tests do

Seven endpoint test modules already define `_auth` for the bearer header;
this file introduced a third name for the same one-liner.

Step 4 of the pr-ready gauntlet: review-polish consistency pass, after
trunk fmt and the affected-suite run.

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 11:30:33 -05:00

183 lines
5.1 KiB
Python

from typing import Annotated
from fastapi import Body, HTTPException
from fastapi import Path as PathVar
from fastapi import Query, Request, status
from decorators.auth import protected_route
from endpoints.responses.rom import UserNoteSchema
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_rom_visible
from handler.database import db_rom_handler
from utils.router import APIRouter
router = APIRouter()
DEFAULT_PUBLIC_ONLY = Query(False, description="Only return public notes")
DEFAULT_SEARCH = Query(None, description="Search notes by title or content")
DEFAULT_TAGS = Query(None, description="Filter by tags")
@protected_route(
router.get,
"/{id}/notes",
[Scope.ROMS_READ],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def get_rom_notes(
request: Request,
id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
public_only: bool = DEFAULT_PUBLIC_ONLY,
search: str = DEFAULT_SEARCH,
tags: list[str] = DEFAULT_TAGS,
) -> list[UserNoteSchema]:
"""Get all notes for a ROM."""
rom = db_rom_handler.get_rom_visibility(id)
if not rom:
raise RomNotFoundInDatabaseException(id)
assert_rom_visible(request, rom)
if tags is None:
tags = []
notes = db_rom_handler.get_rom_notes(
rom_id=id,
user_id=request.user.id,
public_only=public_only,
search=search,
tags=tags,
)
return [UserNoteSchema.from_rom_note(note) for note in notes]
@protected_route(
router.get,
"/{id}/notes/identifiers",
[Scope.ROMS_READ],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def get_rom_note_identifiers(
request: Request,
id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
) -> list[int]:
"""Get all note identifiers for a ROM."""
rom = db_rom_handler.get_rom_visibility(id)
if not rom:
raise RomNotFoundInDatabaseException(id)
assert_rom_visible(request, rom)
return db_rom_handler.get_rom_note_ids(
rom_id=id,
user_id=request.user.id,
)
@protected_route(
router.post,
"/{id}/notes",
[Scope.ROMS_USER_WRITE],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def create_rom_note(
request: Request,
id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
note_data: Annotated[dict, Body()],
) -> UserNoteSchema:
"""Create a new note for a ROM."""
rom = db_rom_handler.get_rom_visibility(id)
if not rom:
raise RomNotFoundInDatabaseException(id)
assert_rom_visible(request, rom)
note = db_rom_handler.create_rom_note(
rom_id=id,
user_id=request.user.id,
title=note_data["title"],
content=note_data.get("content", ""),
is_public=note_data.get("is_public", False),
tags=note_data.get("tags", []),
)
# Add author identity to the note data
note["username"] = request.user.username
note["user_avatar_path"] = request.user.avatar_path
note["user_updated_at"] = request.user.updated_at
return UserNoteSchema.model_validate(note)
@protected_route(
router.put,
"/{id}/notes/{note_id}",
[Scope.ROMS_USER_WRITE],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def update_rom_note(
request: Request,
id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
note_id: Annotated[int, PathVar(description="Note id.", ge=1)],
note_data: Annotated[dict, Body()],
) -> UserNoteSchema:
"""Update a ROM note."""
rom = db_rom_handler.get_rom_visibility(id)
if not rom:
raise RomNotFoundInDatabaseException(id)
assert_rom_visible(request, rom)
note = db_rom_handler.update_rom_note(
note_id=note_id,
user_id=request.user.id,
rom_id=rom.id,
**{
k: v
for k, v in note_data.items()
if k in ["title", "content", "is_public", "tags"]
},
)
if not note:
raise HTTPException(
status_code=404, detail="Note not found or not owned by user"
)
# Add author identity to the note data
note["username"] = request.user.username
note["user_avatar_path"] = request.user.avatar_path
note["user_updated_at"] = request.user.updated_at
return UserNoteSchema.model_validate(note)
@protected_route(
router.delete,
"/{id}/notes/{note_id}",
[Scope.ROMS_USER_WRITE],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def delete_rom_note(
request: Request,
id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
note_id: Annotated[int, PathVar(description="Note id.", ge=1)],
) -> dict:
"""Delete a ROM note."""
rom = db_rom_handler.get_rom_visibility(id)
if not rom:
raise RomNotFoundInDatabaseException(id)
assert_rom_visible(request, rom)
success = db_rom_handler.delete_rom_note(
note_id=note_id, user_id=request.user.id, rom_id=rom.id
)
if not success:
raise HTTPException(
status_code=404, detail="Note not found or not owned by user"
)
return {"message": "Note deleted successfully"}