Files
WebApi/webapi/imports/services/import_service.py
T

314 lines
13 KiB
Python

"""Runs one configured source, or a batch of them, end to end: resolve the
target entity, build the connector, read and validate the rows and, for
`commit_sources`, write the accepted ones through `Repository`.
A batch composes the database from several sources (files, SQL tables or
queries, PDFs, documents, EEG files), each feeding one target entity. All
sources of a batch target the same domain and the batch is written in one
transaction: it lands completely or not at all.
"""
from dataclasses import dataclass, field
from typing import Any, Iterator
from sqlalchemy.exc import SQLAlchemyError
from persistance.repository import ConflictPolicy
from webapi.imports.audit import ImportAudit
from webapi.imports.connectors import Connector, ConnectorError, build_connector
from webapi.imports.schemas.registry import ENTITY_REGISTRY, EntitySpec
from webapi.imports.schemas.service import BatchValidationResult, validate_rows
from webapi.imports.services.link_resolver import LinkResolver, dependency_rank
class ImportRequestError(Exception):
"""A structurally invalid import request, such as an unknown target, a
bad connection string or an invalid on_conflict. Mapped to HTTP 400."""
class DatabaseRefused(ImportRequestError):
"""The database rejected the batch at write time; nothing was written."""
@dataclass(frozen=True)
class ImportSource:
"""One parsed and structurally validated entry of a request's `sources`."""
source_type: str
target: str
spec: EntitySpec
column_mapping: dict[str, str]
defaults: dict[str, Any]
payload: dict[str, Any]
label: str | None = None
@classmethod
def parse(cls, raw: Any) -> "ImportSource":
if not isinstance(raw, dict):
raise ImportRequestError("cada fuente debe ser un objeto")
target = raw.get("target")
if not target:
raise ImportRequestError("a la fuente le falta 'target'")
spec = ENTITY_REGISTRY.get(target)
if spec is None:
raise ImportRequestError(f"destino desconocido: {target!r}")
fields = set(spec.schema.model_fields)
mapping = raw.get("column_mapping") or {}
defaults = raw.get("defaults") or {}
if not isinstance(mapping, dict) or not isinstance(defaults, dict):
raise ImportRequestError("'column_mapping' y 'defaults' deben ser objetos")
unknown = sorted((set(mapping.values()) | set(defaults)) - fields)
if unknown:
raise ImportRequestError(f"{target} no tiene los campos {unknown}")
targets = list(mapping.values())
duplicated = sorted({t for t in targets if targets.count(t) > 1})
if duplicated:
raise ImportRequestError(f"más de una columna de origen asignada a {duplicated}")
if not mapping and not defaults:
raise ImportRequestError(f"la fuente de {target} no asigna ninguna columna")
payload = raw.get("payload")
if not isinstance(payload, dict):
raise ImportRequestError("a la fuente le falta 'payload'")
return cls(
source_type=raw.get("source_type", ""),
target=target,
spec=spec,
column_mapping=mapping,
defaults=defaults,
payload=payload,
label=raw.get("label"),
)
@property
def domain(self) -> str:
return self.target.split(".", 1)[0]
def connector(self) -> Connector:
payload = self.payload
if self.source_type == "document":
# A document source extracts the fields of the entity it feeds.
payload = {**payload, "target": payload.get("target") or self.target}
try:
return build_connector(self.source_type, payload)
except ConnectorError as exc:
raise ImportRequestError(str(exc)) from exc
def rows(self) -> Iterator[dict[str, Any]]:
"""Mapped rows, with `defaults` filling any field the source left
empty or didn't map at all (a constant "dependencia" for a file that
has none, a fallback for blank cells)."""
try:
for row in self.connector().read_rows(self.column_mapping):
for field_name, value in self.defaults.items():
if _is_blank(row.get(field_name)):
row[field_name] = value
yield row
except ConnectorError as exc:
raise ImportRequestError(str(exc)) from exc
def validate(self) -> BatchValidationResult:
return validate_rows(self.spec.schema, self.rows())
def _is_blank(value: Any) -> bool:
return value is None or (isinstance(value, str) and not value.strip())
def serialize_errors(validation: BatchValidationResult) -> list[dict[str, Any]]:
return [
{
"row_index": row_errors.row_index,
"field": e.field,
"category": e.category.value,
"message": e.message,
"raw_value": _jsonable(e.raw_value),
}
for row_errors in validation.rejected
for e in row_errors.errors
]
def _jsonable(value: Any) -> Any:
if value is None or isinstance(value, (str, int, float, bool)):
return value
return str(value)
def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None) -> BatchValidationResult:
source = ImportSource.parse(raw_source)
if audit is None:
return source.validate()
tracked = audit.source(source)
rows = list(source.rows())
tracked.observe_rows(rows)
validation = validate_rows(source.spec.schema, rows)
tracked.observe_validation(validation)
return validation
@dataclass
class SourceCommitResult:
target: str
label: str | None
total: int
created: int
updated: int
rejected: int
errors: list[dict[str, Any]]
linked: dict[str, int]
merged: int = 0
warnings: list[dict[str, Any]] = field(default_factory=list)
def _parse_batch(raw_sources: Any) -> list[ImportSource]:
if not isinstance(raw_sources, list) or not raw_sources:
raise ImportRequestError("'sources' debe ser una lista no vacía")
sources = [ImportSource.parse(raw) for raw in raw_sources]
domains = sorted({source.domain for source in sources})
if len(domains) > 1:
raise ImportRequestError(
f"un lote no puede mezclar dominios ({', '.join(domains)}): todas las fuentes deben ir al mismo"
)
return sources
def merge_duplicates(sources: list[ImportSource], rows: list[list[dict[str, Any] | None]]) -> tuple[dict[int, int], dict[int, list]]:
"""Combines rows that describe the same record (same target entity and
natural key) across the sources of a batch, before validation: a
patient's demographics from a CSV completed with the birth date read
from a scanned form. The first row seen is kept and completed with the
fields it lacks; merged rows become `None`. A field two sources disagree
on keeps the first value and is reported as a warning on the later one.
Returns per-source merge counts and warnings."""
first_seen: dict[tuple[str, tuple], tuple[int, dict[str, Any]]] = {}
merged: dict[int, int] = {}
warnings: dict[int, list] = {}
for position, source in enumerate(sources):
keys = source.spec.conflict_fields
if not keys:
continue
for index, row in enumerate(rows[position]):
key_values = tuple(_key_part(row.get(k)) for k in keys)
if any(v is None for v in key_values):
continue
first = first_seen.setdefault((source.target, key_values), (position, row))
if first[1] is row:
continue
first_position, first_row = first
for name, value in row.items():
if _is_blank(value):
continue
current = first_row.get(name)
if _is_blank(current):
first_row[name] = value
elif _key_part(current) != _key_part(value):
warnings.setdefault(position, []).append(
{
"row_index": index,
"field": name,
"category": "merge_conflict",
"message": f"se conservó {current!r} de {sources[first_position].label or 'otra fuente'}",
"raw_value": _jsonable(value),
}
)
rows[position][index] = None
merged[position] = merged.get(position, 0) + 1
return merged, warnings
def _key_part(value: Any) -> Any:
"""Normalized for comparison across sources: a CSV key is the string "5001"
where a typed source gives the int 5001."""
if _is_blank(value):
return None
return str(value).strip().upper()
def commit_sources(
raw_sources: Any, *, on_conflict: str, merge: bool = False, audit: ImportAudit | None = None
) -> list[SourceCommitResult]:
"""Writes a batch in one transaction. With `merge`, rows of different
sources sharing a natural key are combined first (see `merge_duplicates`)."""
try:
policy = ConflictPolicy(on_conflict)
except ValueError as exc:
raise ImportRequestError(f"on_conflict inválido: {on_conflict!r}") from exc
sources = _parse_batch(raw_sources)
tracked = [audit.source(source) for source in sources] if audit else []
if policy is ConflictPolicy.UPSERT:
keyless = sorted({s.target for s in sources if not s.spec.conflict_fields})
if keyless:
raise ImportRequestError(f"{', '.join(keyless)} no tiene llave natural: on_conflict=upsert no aplica")
# Read + validate everything before opening the write transaction, so a
# slow source (OCR, a remote SQL table) never holds database locks.
rows: list[list[dict[str, Any] | None]] = [list(source.rows()) for source in sources]
merged, merge_warnings = merge_duplicates(sources, rows) if merge else ({}, {})
validated = [(source, validate_rows(source.spec.schema, source_rows)) for source, source_rows in zip(sources, rows)]
for position, source_audit in enumerate(tracked):
source_audit.observe_rows(rows[position])
source_audit.observe_validation(validated[position][1])
source_audit.observe_warnings(merge_warnings.get(position, []))
session = sources[0].spec.repository.open_session()
links = LinkResolver(session)
results: dict[int, SourceCommitResult] = {}
# Parents first (Paciente, then OrdenesEstudio, then the rest), so a
# child's FK lookup finds a parent loaded by another source of the same
# batch. Results are still reported in the caller's order.
write_order = sorted(range(len(validated)), key=lambda i: dependency_rank(validated[i][0].target))
try:
for position in write_order:
source, validation = validated[position]
linked: dict[str, int] = {}
for row in validation.accepted_rows:
for fk_field in links.resolve(source.target, row.data):
linked[fk_field] = linked.get(fk_field, 0) + 1
objs = [source.spec.model(**row.data) for row in validation.accepted_rows]
write = source.spec.repository.bulk_upsert(
objs, conflict_fields=source.spec.conflict_fields, on_conflict=policy, session=session
)
conflict_errors = [
{
"row_index": validation.accepted_rows[outcome.index].row_index,
"field": ",".join(source.spec.conflict_fields or ()),
"category": "conflict",
"message": outcome.error or "conflicto",
"raw_value": _jsonable(
validation.accepted_rows[outcome.index].data.get((source.spec.conflict_fields or ("",))[0])
),
}
for outcome in write.outcomes
if outcome.status == "rejected"
]
errors = sorted(serialize_errors(validation) + conflict_errors, key=lambda e: e["row_index"])
results[position] = SourceCommitResult(
target=source.target,
label=source.label,
total=validation.total_rows,
created=write.created_count,
updated=write.updated_count,
rejected=write.rejected_count + validation.error_count,
errors=errors,
linked=linked,
merged=merged.get(position, 0),
warnings=merge_warnings.get(position, []),
)
if tracked:
tracked[position].observe_write(
created=write.created_count, updated=write.updated_count,
conflicts=write.rejected_count, linked=linked,
)
session.commit()
except SQLAlchemyError as exc:
session.rollback()
detail = exc.orig if hasattr(exc, "orig") else exc
raise DatabaseRefused(
f"la base de datos rechazó el lote y no se escribió nada: {exc.__class__.__name__}: {detail}"
) from exc
finally:
session.close()
return [results[i] for i in range(len(validated))]