Files

333 lines
13 KiB
Python

"""Aggregate log of every import attempt (validations and commits).
Each attempt becomes one JSON line in `importaciones.jsonl` under
`WEBAPI_REPORT_DIR`. A record only carries counts, field names, source
column names and value *shapes* ("9999-99-99" for a date in an unexpected
format): never a row, a file name, a connection string or an identifier.
A rejected catalog value is written verbatim only when at least
`WEBAPI_REPORT_MIN_COUNT` rows share it, so a rare (identifying) value never
appears.
`ImportAudit` collects the facts while the import runs; `JsonlAuditSink`
appends the finished record.
"""
from __future__ import annotations
import fcntl
import json
import os
import re
import time
import uuid
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any, Iterable
from webapi.imports.schemas.classify import ErrorCategory
if TYPE_CHECKING:
from webapi.imports.schemas.service import BatchValidationResult
from webapi.imports.services.import_service import ImportSource
SCHEMA_VERSION = 1
_SHAPE_MAX = 40
_MESSAGE_MAX = 300
_QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"")
# A "column name" that is really a value: a file without a header row makes
# its first record the header. Dates, numbers, codes such as "N-0001", long
# text or prose are logged by shape only.
_VALUE_LIKE = re.compile(r"^[\d\s./:-]+$|\d{4,}|^[A-Za-z]{0,3}[-_ ]?\d+$|@")
def report_dir() -> Path:
return Path(os.environ.get("WEBAPI_REPORT_DIR", "reportes"))
def min_count() -> int:
return int(os.environ.get("WEBAPI_REPORT_MIN_COUNT", "5"))
def value_shape(value: Any) -> str:
"""Letters become `A`, digits `9`; punctuation and spaces stay. Tells the
format of a value without its content."""
text = str(value)
shape = "".join("9" if c.isdigit() else "A" if c.isalpha() else c for c in text[:_SHAPE_MAX])
return shape + ("…" if len(text) > _SHAPE_MAX else "")
def column_label(name: Any) -> str:
"""A source column name as it can be logged: verbatim when it looks like a
header, its shape when it looks like data."""
text = str(name).strip()
if len(text) > _SHAPE_MAX or text.count(" ") > 3 or _VALUE_LIKE.search(text):
return value_shape(text)
return text
def sanitize_message(message: str) -> str:
"""Error messages from drivers and parsers may quote values (MySQL's
"Duplicate entry 'N-0001'"); quoted text is dropped."""
return _QUOTED.sub("'…'", str(message))[:_MESSAGE_MAX]
def _blank(value: Any) -> bool:
return value is None or (isinstance(value, str) and not value.strip())
def _source_origin(source: ImportSource) -> dict[str, Any]:
"""What kind of source it was, without names, hosts or credentials."""
payload = source.payload
origin: dict[str, Any] = {"tipo": source.source_type}
files = payload.get("files")
if isinstance(files, list):
names = [f.get("name") or "" for f in files if isinstance(f, dict)]
else:
names = [(payload.get("options") or {}).get("file_name") or payload.get("file_name") or ""]
extensions = sorted({Path(n).suffix.lower() for n in names if Path(n).suffix})
if extensions:
origin["extensiones"] = extensions
if isinstance(files, list):
origin["archivos"] = len(files)
if source.source_type == "sql":
server = payload.get("server") if isinstance(payload.get("server"), dict) else {}
scheme = str(payload.get("connection_string") or "").split(":", 1)[0].split("+", 1)[0]
origin["motor"] = server.get("engine") or scheme or None
origin["consulta_propia"] = bool(payload.get("query"))
return origin
@dataclass
class _FieldStats:
with_value: int = 0
empty: int = 0
errors: Counter = field(default_factory=Counter)
shapes: Counter = field(default_factory=Counter)
catalog_values: Counter = field(default_factory=Counter)
def as_dict(self, threshold: int) -> dict[str, Any]:
out: dict[str, Any] = {"con_valor": self.with_value, "vacios": self.empty}
if self.errors:
out["errores"] = dict(self.errors)
if self.shapes:
out["formatos_rechazados"] = dict(self.shapes.most_common(10))
frequent = {v: n for v, n in self.catalog_values.most_common(20) if n >= threshold}
if frequent:
out["valores_fuera_de_catalogo"] = frequent
rare = sum(n for n in self.catalog_values.values() if n < threshold)
if rare:
out["valores_fuera_de_catalogo_poco_frecuentes"] = rare
return out
class _SourceAudit:
def __init__(self, source: ImportSource):
self.source = source
self.fields: dict[str, _FieldStats] = defaultdict(_FieldStats)
self.rows: dict[str, Any] = {"leidas": 0}
self.links: dict[str, int] = {}
self.warnings: Counter = Counter()
def observe_rows(self, rows: Iterable[dict[str, Any] | None]) -> None:
mapped = set(self.source.column_mapping.values()) | set(self.source.defaults)
merged = 0
for row in rows:
self.rows["leidas"] += 1
if row is None:
merged += 1
continue
for name in mapped:
stats = self.fields[name]
if _blank(row.get(name)):
stats.empty += 1
else:
stats.with_value += 1
if merged:
self.rows["combinadas_con_otra_fuente"] = merged
def observe_validation(self, validation: BatchValidationResult) -> None:
self.rows["validas"] = validation.valid_count
self.rows["rechazadas_en_validacion"] = validation.error_count
for row_errors in validation.rejected:
for error in row_errors.errors:
stats = self.fields[error.field]
stats.errors[error.category.value] += 1
if _blank(error.raw_value):
continue
if error.category is ErrorCategory.OUT_OF_CATALOG and len(str(error.raw_value)) <= _SHAPE_MAX:
stats.catalog_values[str(error.raw_value).strip().upper()] += 1
elif error.category in (ErrorCategory.TYPE_INVALID, ErrorCategory.UNKNOWN, ErrorCategory.OUT_OF_CATALOG):
stats.shapes[value_shape(error.raw_value)] += 1
def observe_write(self, *, created: int, updated: int, conflicts: int, linked: dict[str, int]) -> None:
self.rows.update(insertadas=created, actualizadas=updated, rechazadas_por_conflicto=conflicts)
self.links = dict(linked)
def observe_warnings(self, warnings: Iterable[dict[str, Any]]) -> None:
for warning in warnings:
self.warnings[f"{warning.get('category')}:{warning.get('field')}"] += 1
def as_dict(self, threshold: int) -> dict[str, Any]:
spec_fields = self.source.spec.schema.model_fields
required = {name for name, info in spec_fields.items() if info.is_required()}
mapped = set(self.source.column_mapping.values())
fixed = set(self.source.defaults)
out: dict[str, Any] = {
"destino": self.source.target,
"origen": _source_origin(self.source),
"mapeo": {
"columnas_origen": sorted(column_label(c) for c in self.source.column_mapping),
"campos_mapeados": sorted(mapped),
"campos_con_valor_fijo": sorted(fixed),
"campos_sin_mapear": sorted(set(spec_fields) - mapped - fixed),
"requeridos_sin_mapear": sorted(required - mapped - fixed),
},
"filas": self.rows,
"campos": {name: stats.as_dict(threshold) for name, stats in sorted(self.fields.items())},
}
if self.links:
out["vinculos_resueltos"] = self.links
if self.warnings:
out["advertencias"] = dict(self.warnings)
return out
class ImportAudit:
"""The aggregate record of one attempt. `operation` is "validacion" or "carga"."""
def __init__(self, operation: str, options: dict[str, Any] | None = None):
self.id = str(uuid.uuid4())
self.operation = operation
self.options = options or {}
self.started = time.monotonic()
self.date = datetime.now(timezone.utc)
self.sources: list[_SourceAudit] = []
self.outcome = "en_curso"
self.error: dict[str, str] | None = None
def source(self, source: ImportSource) -> _SourceAudit:
audit = _SourceAudit(source)
self.sources.append(audit)
return audit
def succeed(self, outcome: str = "completada") -> None:
self.outcome = outcome
def fail(self, exc: BaseException, outcome: str = "fallida") -> None:
self.outcome = outcome
self.error = {"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))}
@property
def domain(self) -> str | None:
return self.sources[0].source.domain if self.sources else None
def as_dict(self) -> dict[str, Any]:
threshold = min_count()
record: dict[str, Any] = {
"version": SCHEMA_VERSION,
"id": self.id,
"fecha": self.date.isoformat(timespec="seconds"),
"operacion": self.operation,
"dominio": self.domain,
"resultado": self.outcome,
"duracion_s": round(time.monotonic() - self.started, 2),
"opciones": self.options,
"fuentes": [s.as_dict(threshold) for s in self.sources],
}
if self.error:
record["error"] = self.error
totals = Counter()
for s in self.sources:
for key, value in s.rows.items():
totals[key] += value
record["totales"] = dict(totals)
return record
class JsonlAuditSink:
"""One JSON object per line; appends are locked so several gunicorn
workers can share the file."""
def __init__(self, path: Path):
self.path = path
def write(self, record: dict[str, Any]) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
line = json.dumps(record, ensure_ascii=False, default=str) + "\n"
with open(self.path, "a", encoding="utf-8") as handle:
fcntl.flock(handle, fcntl.LOCK_EX)
try:
handle.write(line)
finally:
fcntl.flock(handle, fcntl.LOCK_UN)
def read(self) -> list[dict[str, Any]]:
if not self.path.exists():
return []
records = []
with open(self.path, encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
try:
records.append(json.loads(line))
except json.JSONDecodeError:
continue
return records
def default_sink() -> JsonlAuditSink:
return JsonlAuditSink(report_dir() / "importaciones.jsonl")
def record(audit: ImportAudit) -> None:
"""Writes the record; a full disk must not turn a successful import into an error."""
try:
default_sink().write(audit.as_dict())
except OSError:
pass
def summarize(records: list[dict[str, Any]]) -> dict[str, Any]:
"""Totals per target over every logged attempt: how many rows arrived,
how many were written, and which fields failed most and how."""
by_target: dict[str, dict[str, Any]] = {}
attempts = Counter()
for rec in records:
attempts[f"{rec.get('operacion')}:{rec.get('resultado')}"] += 1
for src in rec.get("fuentes", []):
target = by_target.setdefault(
src["destino"],
{"intentos": 0, "cargas_completadas": 0, "filas": Counter(), "errores_por_campo": defaultdict(Counter),
"formatos_rechazados": defaultdict(Counter), "requeridos_sin_mapear": Counter(), "origenes": Counter()},
)
target["intentos"] += 1
if rec.get("operacion") == "carga" and rec.get("resultado") == "completada":
target["cargas_completadas"] += 1
for key, value in src.get("filas", {}).items():
target["filas"][key] += value
target["origenes"][src.get("origen", {}).get("tipo") or "?"] += 1
for name in src.get("mapeo", {}).get("requeridos_sin_mapear", []):
target["requeridos_sin_mapear"][name] += 1
for name, stats in src.get("campos", {}).items():
target["errores_por_campo"][name].update(stats.get("errores", {}))
target["formatos_rechazados"][name].update(stats.get("formatos_rechazados", {}))
return {
"intentos": dict(attempts),
"ultimo": records[-1]["fecha"] if records else None,
"destinos": {
key: {
"intentos": t["intentos"],
"cargas_completadas": t["cargas_completadas"],
"filas_en_cargas_completadas": dict(t["filas"]),
"origenes": dict(t["origenes"]),
"requeridos_sin_mapear": dict(t["requeridos_sin_mapear"]),
"errores_por_campo": {k: dict(v) for k, v in t["errores_por_campo"].items() if v},
"formatos_rechazados": {k: dict(v.most_common(10)) for k, v in t["formatos_rechazados"].items() if v},
}
for key, t in sorted(by_target.items())
},
}