mirror of
https://github.com/Hestia-Homes/Model.git
synced 2026-06-08 11:17:27 +00:00
First slice of the per-stage batch-transaction refactor (ADR-0012). A UnitOfWork is the single transaction a stage runs its batch in: a context manager exposing the DB repos bound to one session, committing once on `commit()` and rolling back on exception or exit-without-commit (all-or-nothing per batch, fail noisily). - `UnitOfWork` (port): `property` / `epc` / `solar` / `baseline` repos + `commit()` / `rollback()`; `__exit__` rolls back uncommitted work. - `PostgresUnitOfWork(session_factory)`: opens a Session from an injected factory (a module-scoped engine + sessionmaker in prod, so the pool is reused across warm invocations), binds the Postgres repos to it, closes on exit. Not yet wired into any orchestrator — that lands in the Baseline / Ingestion refactor slices. 3 tests against ephemeral PG (commit durable across units; exception rolls back; no-commit persists nothing). pyright strict clean; AAA. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
from __future__ import annotations
|
|
|
|
from abc import ABC, abstractmethod
|
|
from types import TracebackType
|
|
from typing import Optional
|
|
|
|
from repositories.baseline.baseline_repository import BaselineRepository
|
|
from repositories.epc.epc_repository import EpcRepository
|
|
from repositories.property.property_repository import PropertyRepository
|
|
from repositories.solar.solar_repository import SolarRepository
|
|
|
|
|
|
class UnitOfWork(ABC):
|
|
"""A single batch transaction across the DB-backed repos (ADR-0012).
|
|
|
|
A context manager that exposes the repos bound to one session. A stage runs
|
|
its whole batch inside one unit and calls ``commit()`` once; leaving the
|
|
block without committing — including via an exception — rolls back, so a
|
|
failed batch persists nothing and the subtask fails noisily.
|
|
|
|
The non-DB dependencies (EPC/Solar fetchers, the geospatial S3 repo, the
|
|
Rebaseliner) are *not* part of the unit — only transactional DB work is.
|
|
"""
|
|
|
|
property: PropertyRepository
|
|
epc: EpcRepository
|
|
solar: SolarRepository
|
|
baseline: BaselineRepository
|
|
|
|
@abstractmethod
|
|
def commit(self) -> None: ...
|
|
|
|
@abstractmethod
|
|
def rollback(self) -> None: ...
|
|
|
|
def __enter__(self) -> "UnitOfWork":
|
|
return self
|
|
|
|
def __exit__(
|
|
self,
|
|
exc_type: Optional[type[BaseException]],
|
|
exc: Optional[BaseException],
|
|
tb: Optional[TracebackType],
|
|
) -> None:
|
|
# Roll back whatever was not explicitly committed (a no-op after a
|
|
# successful commit). All-or-nothing per batch.
|
|
self.rollback()
|