location_service.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. """Storage location catalog — single write path for spool location fields (#1004)."""
  2. from __future__ import annotations
  3. import logging
  4. import re
  5. import time
  6. from dataclasses import dataclass
  7. import httpx
  8. from sqlalchemy import func, select, update
  9. from sqlalchemy.exc import IntegrityError
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.models.location import Location
  12. from backend.app.models.spool import Spool
  13. logger = logging.getLogger(__name__)
  14. DUPLICATE_LOCATION_NAME = "A location with this name already exists"
  15. # AMS residency markers, not storage locations. Bambuddy used to write the slot
  16. # a spool was loaded into -- "<printer> - AMS A1", "<printer> - AMS-HT A1" or
  17. # "<printer> - External Spool" -- straight into Spoolman's `location` field. That writer went away when Storage Location
  18. # became a place the user chooses (#1114), but the strings survive on people's
  19. # Spoolman spools, and importing them offers a printer slot as somewhere to put
  20. # a spool away. A slot is where a spool is loaded, not where it is stored, and
  21. # Bambuddy tracks that separately through slot assignments.
  22. _AMS_SLOT_LOCATION_RE = re.compile(
  23. r"^(?:.+\s-\s)?(?:AMS[- ]HT [A-Z]\d+|AMS [A-Z]\d+|External Spool)$",
  24. re.IGNORECASE,
  25. )
  26. def is_ams_slot_location(name: str) -> bool:
  27. """True when a location string names a printer slot rather than a storage place."""
  28. return bool(_AMS_SLOT_LOCATION_RE.match(name.strip()))
  29. def normalize_location_name(name: str) -> str:
  30. trimmed = name.strip()
  31. if not trimmed:
  32. raise ValueError("name must not be empty")
  33. return trimmed
  34. def location_name_key(name: str) -> str:
  35. """Case-insensitive lookup key stored on Location.name_key."""
  36. return normalize_location_name(name).lower()
  37. def assign_location_name(location: Location, name: str) -> None:
  38. normalized = normalize_location_name(name)
  39. location.name = normalized
  40. location.name_key = location_name_key(normalized)
  41. @dataclass(frozen=True)
  42. class SpoolLocationFields:
  43. """Canonical spool location state: FK + denormalized string for Spoolman/display."""
  44. location_id: int | None
  45. storage_location: str | None
  46. async def get_location_by_id(db: AsyncSession, location_id: int) -> Location | None:
  47. result = await db.execute(select(Location).where(Location.id == location_id))
  48. return result.scalar_one_or_none()
  49. async def get_location_by_name(db: AsyncSession, name: str) -> Location | None:
  50. key = location_name_key(name)
  51. result = await db.execute(select(Location).where(Location.name_key == key))
  52. return result.scalar_one_or_none()
  53. async def get_locations_by_name_keys(db: AsyncSession, keys: set[str]) -> dict[str, Location]:
  54. if not keys:
  55. return {}
  56. result = await db.execute(select(Location).where(Location.name_key.in_(keys)))
  57. return {loc.name_key: loc for loc in result.scalars().all()}
  58. async def _create_location_or_get_existing(db: AsyncSession, normalized: str) -> Location:
  59. """Insert a location row, returning the winner on concurrent name_key collision."""
  60. existing = await get_location_by_name(db, normalized)
  61. if existing:
  62. return existing
  63. location = Location()
  64. assign_location_name(location, normalized)
  65. try:
  66. async with db.begin_nested():
  67. db.add(location)
  68. await db.flush()
  69. return location
  70. except IntegrityError as exc:
  71. winner = await get_location_by_name(db, normalized)
  72. if winner:
  73. return winner
  74. raise ValueError(DUPLICATE_LOCATION_NAME) from exc
  75. async def _insert_location_if_absent(db: AsyncSession, name: str) -> bool:
  76. """Stage a new location row when absent. Returns True when one was added."""
  77. normalized = normalize_location_name(name)
  78. if await get_location_by_name(db, normalized):
  79. return False
  80. location = Location()
  81. assign_location_name(location, normalized)
  82. try:
  83. async with db.begin_nested():
  84. db.add(location)
  85. await db.flush()
  86. return True
  87. except IntegrityError:
  88. # Race: another writer inserted the same name between our check and
  89. # flush. The row already exists by definition — surface as "not added"
  90. # rather than re-raising. Anything else (NULL constraint, FK, check
  91. # constraint) would be a programming bug — re-fetch to verify so we
  92. # don't silently drop unrelated IntegrityErrors.
  93. if await get_location_by_name(db, normalized):
  94. return False
  95. logger.warning("IntegrityError on insert of location %r without surviving row", normalized)
  96. raise
  97. async def resolve_location_by_name(db: AsyncSession, name: str, *, create: bool = True) -> Location | None:
  98. """Find a location by name (case-insensitive), optionally creating it."""
  99. normalized = normalize_location_name(name)
  100. existing = await get_location_by_name(db, normalized)
  101. if existing:
  102. return existing
  103. if not create:
  104. return None
  105. return await _create_location_or_get_existing(db, normalized)
  106. async def resolve_spool_location_fields(
  107. db: AsyncSession,
  108. *,
  109. location_id: int | None = None,
  110. storage_location: str | None = None,
  111. fields_set: set[str],
  112. ) -> SpoolLocationFields | None:
  113. """Resolve location_id + storage_location from API input.
  114. ``location_id`` wins when both fields appear in ``fields_set``.
  115. Returns ``None`` when neither location field was provided.
  116. """
  117. if "location_id" in fields_set:
  118. if location_id is None:
  119. return SpoolLocationFields(location_id=None, storage_location=None)
  120. loc = await get_location_by_id(db, location_id)
  121. if not loc:
  122. raise ValueError(f"Location {location_id} not found")
  123. return SpoolLocationFields(location_id=loc.id, storage_location=loc.name)
  124. if "storage_location" in fields_set:
  125. if not storage_location:
  126. return SpoolLocationFields(location_id=None, storage_location=None)
  127. loc = await resolve_location_by_name(db, storage_location)
  128. if not loc:
  129. return SpoolLocationFields(location_id=None, storage_location=None)
  130. return SpoolLocationFields(location_id=loc.id, storage_location=loc.name)
  131. return None
  132. async def prepare_internal_spool_payload(db: AsyncSession, data: dict, fields_set: set[str]) -> dict:
  133. """Apply resolved location fields before creating or updating an internal spool."""
  134. payload = dict(data)
  135. resolved = await resolve_spool_location_fields(
  136. db,
  137. location_id=payload.get("location_id"),
  138. storage_location=payload.get("storage_location"),
  139. fields_set=fields_set,
  140. )
  141. if resolved is not None:
  142. payload["location_id"] = resolved.location_id
  143. payload["storage_location"] = resolved.storage_location
  144. return payload
  145. async def resolve_spoolman_location_string(
  146. db: AsyncSession,
  147. *,
  148. location_id: int | None = None,
  149. storage_location: str | None = None,
  150. fields_set: set[str],
  151. ) -> tuple[str | None, bool]:
  152. """Return (Spoolman location string, changed) for proxy writes."""
  153. resolved = await resolve_spool_location_fields(
  154. db,
  155. location_id=location_id,
  156. storage_location=storage_location,
  157. fields_set=fields_set,
  158. )
  159. if resolved is None:
  160. return None, False
  161. return resolved.storage_location, True
  162. async def count_internal_spools_at_location(db: AsyncSession, location_id: int) -> int:
  163. result = await db.execute(
  164. select(func.count())
  165. .select_from(Spool)
  166. .where(
  167. Spool.location_id == location_id,
  168. Spool.archived_at.is_(None),
  169. )
  170. )
  171. return int(result.scalar() or 0)
  172. async def enrich_spool_dicts_with_location_id(db: AsyncSession, spools: list[dict]) -> None:
  173. """Attach location_id to mapped Spoolman-style spool dicts in place."""
  174. keys = {location_name_key(s["storage_location"]) for s in spools if (s.get("storage_location") or "").strip()}
  175. if not keys:
  176. for s in spools:
  177. s["location_id"] = None
  178. return
  179. by_key = await get_locations_by_name_keys(db, keys)
  180. for s in spools:
  181. raw = (s.get("storage_location") or "").strip()
  182. if not raw:
  183. s["location_id"] = None
  184. continue
  185. loc = by_key.get(location_name_key(raw))
  186. s["location_id"] = loc.id if loc else None
  187. async def rename_location(db: AsyncSession, location: Location, new_name: str) -> Location:
  188. normalized = normalize_location_name(new_name)
  189. existing = await get_location_by_name(db, normalized)
  190. if existing and existing.id != location.id:
  191. raise ValueError(DUPLICATE_LOCATION_NAME)
  192. old_name = location.name
  193. # Mirror the SQL TRIM on the Python side so a legacy row whose
  194. # `storage_location` has trailing whitespace still matches against the
  195. # `old_name` we just lifted off the Location row. Without `.strip()` the
  196. # equality is asymmetric (SQL strips the column; Python doesn't) and
  197. # legacy rows quietly fall out of the rename cascade.
  198. old_name_key = old_name.strip().lower()
  199. assign_location_name(location, normalized)
  200. await db.execute(update(Spool).where(Spool.location_id == location.id).values(storage_location=normalized))
  201. # Keep legacy rows in sync when only storage_location was set.
  202. await db.execute(
  203. update(Spool)
  204. .where(
  205. Spool.location_id.is_(None),
  206. func.lower(func.trim(Spool.storage_location)) == old_name_key,
  207. )
  208. .values(storage_location=normalized, location_id=location.id)
  209. )
  210. try:
  211. await db.flush()
  212. except IntegrityError as exc:
  213. raise ValueError(DUPLICATE_LOCATION_NAME) from exc
  214. return location
  215. async def sync_locations_from_spoolman(db: AsyncSession, client) -> bool:
  216. """Import distinct Spoolman location strings into the local catalog.
  217. Returns True when new rows were staged (caller must commit). Logs and
  218. returns False on Spoolman fetch failures so the calling read path keeps
  219. serving the local catalog instead of 500ing; bare-Exception swallow used
  220. to be the shape here and hid both transport errors and shape regressions.
  221. """
  222. from backend.app.services.spoolman import SpoolmanClientError, SpoolmanUnavailableError
  223. try:
  224. names = await client.get_distinct_locations()
  225. except (SpoolmanUnavailableError, SpoolmanClientError, httpx.HTTPError) as exc:
  226. logger.warning("location sync from Spoolman failed: %s", exc)
  227. return False
  228. # Collapse case variants before insert — Spoolman may return both
  229. # "Drybox 1" and "DRYBOX 1" in the same payload.
  230. by_key: dict[str, str] = {}
  231. for raw in names:
  232. name = (raw or "").strip()
  233. if not name:
  234. continue
  235. if is_ams_slot_location(name):
  236. logger.debug("Skipping AMS slot marker %r from the Spoolman location import", name)
  237. continue
  238. key = location_name_key(name)
  239. if key not in by_key:
  240. by_key[key] = name
  241. changed = False
  242. for name in by_key.values():
  243. if await _insert_location_if_absent(db, name):
  244. changed = True
  245. return changed
  246. # Per-URL last-sync timestamp guard. Calling list_spools runs the sync, so on
  247. # a polling UI without this guard every refetch round-trips to Spoolman and
  248. # opens a write transaction — measurable latency and SQLite write contention.
  249. # 60s is long enough to absorb dashboard polling, short enough that a manual
  250. # spool rename in Spoolman shows up on the next minute's refresh.
  251. _SPOOLMAN_LOCATION_SYNC_TTL_SECONDS = 60.0
  252. _spoolman_location_sync_last_run: dict[str, float] = {}
  253. def _spoolman_location_sync_cache_clear() -> None:
  254. """Test hook: drop the TTL cache so each test starts from a clean slate."""
  255. _spoolman_location_sync_last_run.clear()
  256. async def maybe_sync_spoolman_locations(db: AsyncSession, *, client=None) -> bool:
  257. """Sync Spoolman location names into the local catalog when integration is enabled.
  258. Pass ``client`` when the caller has already resolved one (the GET /spools
  259. route does); otherwise the function falls back to ``init_spoolman_client``.
  260. Passing the route's client keeps test fixtures honest — without it, the
  261. fall-back path imports from ``backend.app.services.spoolman`` directly and
  262. bypasses any patch that targets the route module's alias, which causes
  263. real TCP connects to whatever ``spoolman_url`` happens to point at.
  264. """
  265. from backend.app.api.routes._spoolman_helpers import assert_safe_spoolman_url
  266. from backend.app.models.settings import Settings
  267. result = await db.execute(select(Settings))
  268. settings = {s.key: s.value for s in result.scalars().all()}
  269. if settings.get("spoolman_enabled", "false").lower() != "true":
  270. return False
  271. url = settings.get("spoolman_url", "").strip()
  272. if not url:
  273. return False
  274. # Debounce: skip the round-trip when we synced this URL recently.
  275. cache_key = url.rstrip("/")
  276. last_run = _spoolman_location_sync_last_run.get(cache_key, 0.0)
  277. now = time.monotonic()
  278. if now - last_run < _SPOOLMAN_LOCATION_SYNC_TTL_SECONDS:
  279. return False
  280. try:
  281. assert_safe_spoolman_url(url)
  282. except ValueError as exc:
  283. logger.warning("Spoolman URL rejected by SSRF guard during location sync: %s", exc)
  284. return False
  285. if client is None:
  286. from backend.app.services.spoolman import get_spoolman_client, init_spoolman_client
  287. client = await get_spoolman_client()
  288. if not client or client.base_url != cache_key:
  289. client = await init_spoolman_client(url)
  290. if not client:
  291. return False
  292. changed = await sync_locations_from_spoolman(db, client)
  293. _spoolman_location_sync_last_run[cache_key] = now
  294. return changed