import base64 import binascii from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import Any, ClassVar, Iterator from webapi.imports.connectors.errors import ConnectorError @dataclass(frozen=True) class SourceColumn: name: str inferred_type: str # "string" | "integer" | "float" | "boolean" | "date" | "datetime" | "binary" | "unknown" @dataclass(frozen=True) class PreviewResult: columns: list[SourceColumn] sample_rows: list[dict[str, Any]] total_rows: int | None = None @dataclass(frozen=True) class SourceTable: """One table a source offers: an Excel sheet, a section of an EDF file. `options` is what to send back to read that table.""" name: str options: dict[str, Any] = field(default_factory=dict) kind: str = "table" class Connector(ABC): """A data source that can be read as columns and rows. Adding a source means subclassing this (or `FileConnector` for an uploaded file), setting the class attributes below, implementing `from_payload`, and decorating the class with `@register_connector`. The import pipeline, the `/imports/connectors` catalog and the web client pick it up from there. """ kind: ClassVar[str] label: ClassVar[str] description: ClassVar[str] = "" category: ClassVar[str] # "file" | "database" | "document" | "signal" icon: ClassVar[str] = "table_view" extensions: ClassVar[tuple[str, ...]] = () @classmethod @abstractmethod def from_payload(cls, payload: dict[str, Any]) -> "Connector": """Builds a ready-to-read connector from the JSON a client sends in an import request's `payload`.""" @abstractmethod def preview(self, *, limit: int = 20) -> PreviewResult: ... @abstractmethod def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]: """`column_mapping`: source column -> target field. Yields one dict per row keyed by target field. Values are not validated here.""" def tables(self) -> list[SourceTable]: """The tables this source offers, when it has more than one.""" return [] def metadata(self) -> dict[str, Any]: """Source-specific facts worth showing (a CSV's delimiter, ...).""" return {} @classmethod def describe(cls) -> dict[str, Any]: return { "kind": cls.kind, "label": cls.label, "description": cls.description, "category": cls.category, "icon": cls.icon, "extensions": list(cls.extensions), } def decode_file(payload: dict[str, Any], key: str = "file_base64") -> bytes: try: return base64.b64decode(payload[key], validate=True) except KeyError as exc: raise ConnectorError(f"falta {key}") from exc except (binascii.Error, ValueError, TypeError) as exc: raise ConnectorError(f"{key} no es base64 vĂ¡lido: {exc}") from exc