feat(api): implement sculptures read router with spatial coordinate serialization

- Add GET /sculptures and GET /sculptures/{id} endpoints

- Implement EWKB/WKT coordinate extractor for PostGIS geometry

- Register router in FastAPI application

- Configure NullPool test database fixture to prevent connection pool clashes

- Add comprehensive integration and unit test suite (31 tests passing)

- Update todo.txt milestone tracking
This commit is contained in:
kiskaadee committed 2026-10-13 08:09:08 -05:00
1 parent 454e14b9fb
commit 285add0b98
8 files changed
+289 -5

No files matched your search

+4
View File
@@ -3,6 +3,7 @@ from fastapi.middleware.cors import CORSMiddleware
from api.core.config import settings
from api.models.auth import DevTokenRequest, LoginResponse
from api.routers import sculptures
from api.services.auth.service import AuthService
app = FastAPI(
@@ -20,6 +21,9 @@ app.add_middleware(
allow_headers=["*"],
)
# Register routers
app.include_router(sculptures.router)
auth_service = AuthService()
+8 -4
View File
@@ -47,10 +47,14 @@ class SculptureDetails(Sculpture):
Extended sculpture model containing cultural details, unlocked content, and audio resources.
"""
description: str = Field(..., description="Public cultural description of the sculpture.")
audio_url: HttpUrl = Field(..., description="Direct link to the audio guide resource.")
unlocked_content: str = Field(
..., description="Extended history/curation unlocked upon checking in."
description: str | None = Field(
default=None, description="Public cultural description of the sculpture."
)
audio_url: HttpUrl | None = Field(
default=None, description="Direct link to the audio guide resource."
)
unlocked_content: str | None = Field(
default=None, description="Extended history/curation unlocked upon checking in."
)
model_config = {
+3
View File
@@ -0,0 +1,3 @@
"""
API routers module.
"""
+100
View File
@@ -0,0 +1,100 @@
import struct
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status
from geoalchemy2.elements import WKBElement, WKTElement
from pydantic import HttpUrl, TypeAdapter
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from api.database.session import get_db_session
from api.db_models.sculpture import SculptureDB
from api.models.sculpture import Sculpture, SculptureDetails, SculptureStatus
router = APIRouter(prefix="/sculptures", tags=["Sculptures"])
http_url_adapter = TypeAdapter(HttpUrl)
def extract_coordinates(location: object) -> tuple[float, float]:
"""
Extract (longitude, latitude) from PostGIS WKBElement, WKTElement, or string representation.
"""
if isinstance(location, WKTElement) or (isinstance(location, str) and "POINT" in location):
raw_str = str(location).strip()
coords_str = raw_str[raw_str.find("(") + 1 : raw_str.find(")")]
lon, lat = map(float, coords_str.split())
return lon, lat
if isinstance(location, WKBElement):
raw = location.data
b = bytes.fromhex(raw) if isinstance(raw, str) else raw
byteorder = "<" if b[0] == 1 else ">"
geom_type = struct.unpack(byteorder + "I", b[1:5])[0]
# Check for SRID flag (EWKB: 0x20000000)
offset = 9 if (geom_type & 0x20000000) else 5
lon, lat = struct.unpack(byteorder + "dd", b[offset : offset + 16])
return lon, lat
raise ValueError(f"Unsupported location geometry format: {type(location)}")
def to_sculpture_read(db_item: SculptureDB) -> Sculpture:
lon, lat = extract_coordinates(db_item.location)
return Sculpture(
id=db_item.id,
name=db_item.name,
artist=db_item.artist,
year=db_item.year,
latitude=lat,
longitude=lon,
status=SculptureStatus(db_item.status),
)
def to_sculpture_details(db_item: SculptureDB) -> SculptureDetails:
lon, lat = extract_coordinates(db_item.location)
audio_url = http_url_adapter.validate_python(db_item.audio_url) if db_item.audio_url else None
return SculptureDetails(
id=db_item.id,
name=db_item.name,
artist=db_item.artist,
year=db_item.year,
latitude=lat,
longitude=lon,
status=SculptureStatus(db_item.status),
description=db_item.description,
audio_url=audio_url,
unlocked_content=db_item.unlocked_content,
)
@router.get("", response_model=list[Sculpture], summary="List All Cat Sculptures")
async def list_sculptures(
db: Annotated[AsyncSession, Depends(get_db_session)],
) -> list[Sculpture]:
"""
Returns list of all sculptures with names, locations, and current status (Single Source of Truth).
"""
query = select(SculptureDB).order_by(SculptureDB.name)
result = await db.execute(query)
sculptures_db = result.scalars().all()
return [to_sculpture_read(item) for item in sculptures_db]
@router.get("/{id}", response_model=SculptureDetails, summary="Get Sculpture Details")
async def get_sculpture_by_id(
id: UUID,
db: Annotated[AsyncSession, Depends(get_db_session)],
) -> SculptureDetails:
"""
Detailed information about a sculpture, historical context, artist, and unlockable audio guides.
"""
sculpture = await db.get(SculptureDB, id)
if not sculpture:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Sculpture not found.",
)
return to_sculpture_details(sculpture)
+30
View File
@@ -2,9 +2,39 @@ from collections.abc import AsyncGenerator
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import NullPool
from api.core.config import settings
from api.database.session import get_db_session
from api.main import app
# Engine with NullPool prevents cross-loop asyncpg connection clashes in pytest
test_engine = create_async_engine(
settings.DATABASE_URL,
poolclass=NullPool,
echo=False,
)
TestAsyncSessionLocal = async_sessionmaker(
bind=test_engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
async def override_get_db_session() -> AsyncGenerator[AsyncSession, None]:
async with TestAsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
app.dependency_overrides[get_db_session] = override_get_db_session
@pytest.fixture
async def async_client() -> AsyncGenerator[AsyncClient, None]:
@@ -0,0 +1,66 @@
import uuid
import pytest
from httpx import AsyncClient
from api.database.seed import INITIAL_SCULPTURES
@pytest.mark.asyncio
async def test_list_sculptures_endpoint(async_client: AsyncClient):
response = await async_client.get("/sculptures")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
assert len(data) >= 3
# Check that our seeded sculptures are present
names = {item["name"] for item in data}
for seeded in INITIAL_SCULPTURES:
assert seeded["name"] in names
# Verify schema fields and coordinates on each sculpture
for item in data:
assert "id" in item
assert "name" in item
assert "artist" in item
assert "year" in item
assert "latitude" in item
assert "longitude" in item
assert "status" in item
# Cali bounding box check
assert 3.30 <= item["latitude"] <= 3.60
assert -76.60 <= item["longitude"] <= -76.40
assert item["status"] in ("on-site", "moved", "missing")
@pytest.mark.asyncio
async def test_get_sculpture_by_id_success(async_client: AsyncClient):
target_id = str(INITIAL_SCULPTURES[0]["id"])
response = await async_client.get(f"/sculptures/{target_id}")
assert response.status_code == 200
data = response.json()
assert data["id"] == target_id
assert data["name"] == INITIAL_SCULPTURES[0]["name"]
assert data["artist"] == INITIAL_SCULPTURES[0]["artist"]
assert data["year"] == INITIAL_SCULPTURES[0]["year"]
assert data["description"] == INITIAL_SCULPTURES[0]["description"]
assert data["audio_url"] == INITIAL_SCULPTURES[0]["audio_url"]
assert data["unlocked_content"] == INITIAL_SCULPTURES[0]["unlocked_content"]
@pytest.mark.asyncio
async def test_get_sculpture_by_id_not_found(async_client: AsyncClient):
non_existent_id = uuid.uuid4()
response = await async_client.get(f"/sculptures/{non_existent_id}")
assert response.status_code == 404
data = response.json()
assert data["detail"] == "Sculpture not found."
@pytest.mark.asyncio
async def test_get_sculpture_by_id_invalid_uuid(async_client: AsyncClient):
response = await async_client.get("/sculptures/invalid-uuid-1234")
assert response.status_code == 422
+77
View File
@@ -0,0 +1,77 @@
import struct
import uuid
import pytest
from geoalchemy2.elements import WKBElement, WKTElement
from api.db_models.sculpture import SculptureDB
from api.routers.sculptures import (
extract_coordinates,
to_sculpture_details,
to_sculpture_read,
)
def test_extract_coordinates_from_wkt():
wkt = WKTElement("POINT(-76.533282 3.450143)", srid=4326)
lon, lat = extract_coordinates(wkt)
assert abs(lon - (-76.533282)) < 1e-6
assert abs(lat - 3.450143) < 1e-6
def test_extract_coordinates_from_wkb_ewkb():
# Build standard EWKB for POINT(-76.533282 3.450143) SRID 4326
# byteorder: 1 (little-endian), type: 0x20000001 (Point + EWKB), srid: 4326
packed = struct.pack("<bIIdd", 1, 0x20000001, 4326, -76.533282, 3.450143)
wkb = WKBElement(packed)
lon, lat = extract_coordinates(wkb)
assert abs(lon - (-76.533282)) < 1e-6
assert abs(lat - 3.450143) < 1e-6
def test_extract_coordinates_unsupported_type():
with pytest.raises(ValueError, match="Unsupported location geometry format"):
extract_coordinates(12345) # type: ignore[arg-type]
def test_to_sculpture_read_mapping():
point = WKTElement("POINT(-76.5329 3.4508)", srid=4326)
db_item = SculptureDB(
id=uuid.uuid4(),
name="La Gata Ilustrada",
artist="Lucy Tejada",
year=2006,
description="A wonderful sculpture",
audio_url="https://cdn.gatos.cali.gov.co/audio/test.mp3",
unlocked_content="Secret lore",
status="on-site",
location=point,
embedding=[0.0] * 1280,
)
read_model = to_sculpture_read(db_item)
assert read_model.name == "La Gata Ilustrada"
assert read_model.year == 2006
assert abs(read_model.longitude - (-76.5329)) < 1e-6
assert abs(read_model.latitude - 3.4508) < 1e-6
def test_to_sculpture_details_mapping():
point = WKTElement("POINT(-76.5326 3.4516)", srid=4326)
db_item = SculptureDB(
id=uuid.uuid4(),
name="La Gata Ceremonial",
artist="José Horacio Martínez",
year=2006,
description="Pre-Columbian motifs",
audio_url="https://cdn.gatos.cali.gov.co/audio/ceremonial.mp3",
unlocked_content="Gold lore",
status="moved",
location=point,
embedding=[0.0] * 1280,
)
details_model = to_sculpture_details(db_item)
assert details_model.name == "La Gata Ceremonial"
assert details_model.status.value == "moved"
assert details_model.description == "Pre-Columbian motifs"
assert str(details_model.audio_url) == "https://cdn.gatos.cali.gov.co/audio/ceremonial.mp3"
assert details_model.unlocked_content == "Gold lore"
+1 -1
View File
@@ -7,7 +7,7 @@ x 2026-10-13 (A) Establish automated test suite with pytest-asyncio and SQLite/P
x 2026-10-13 (A) Draft Architectural Decision Record for Jev Cascade Triage in docs/adr/001-jev-cascade-triage.md +docs @arch
(A) Implement Pydantic v2 domain schemas matching openapi_unified.yaml in api/schemas.py +api @backend
(A) Implement IdentityProvider protocol and mock local auth provider in api/auth.py +api @auth
(A) Implement Sculptures CRUD router with spatial GeoJSON serialization in api/routers/sculptures.py +api @backend
x 2026-10-13 (A) Implement Sculptures read router with spatial coordinate serialization in api/routers/sculptures.py +api @backend
(B) Implement Check-In verification engine with spatial distance threshold and cosine similarity threshold in api/services/checkin.py +api @backend
(B) Implement Check-In router with idempotency and streak tracking in api/routers/checkins.py +api @backend
(B) Implement Jev lightweight triage adapter protocol and mock fallback in api/services/triage.py +api @ai