Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(ingest): add Power BI connector for REST metadata (#1572) (#1594)

Kevin251ecf75b971
diff --git a/docs/docs.json b/docs/docs.json
index 4d8df8a1..c5bb271b 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -108,7 +108,8 @@
"integrations/snowflake",
"integrations/databricks",
"integrations/salesforce",
- "integrations/redshift"
+ "integrations/redshift",
+ "integrations/powerbi"
]
},
{
diff --git a/docs/integrations/powerbi.md b/docs/integrations/powerbi.md
new file mode 100644
index 00000000..813d7d72
--- /dev/null
+++ b/docs/integrations/powerbi.md
@@ -0,0 +1,93 @@
+---
+title: "Power BI Integration"
+description: "Ingest workspace, dataset, report and dataflow metadata from the Power BI REST API into Semantica's KG pipeline."
+icon: "chart-simple"
+---
+
+> Pull Power BI metadata into Semantica using the REST API with Azure AD OAuth2 client-credentials authentication.
+
+
+## Installation
+
+```bash
+pip install semantica
+```
+
+`requests` ships with Semantica as a core dependency, so this connector works as soon as the package is installed — there is no extra to install. The module is a lazy export: `import semantica.ingest` does not load it until you first touch `PowerBIIngestor`.
+
+<Note>
+This connector reads **metadata** — workspaces, datasets, reports and dataflows. It does not execute DAX queries or export dataset rows; the Power BI REST API exposes catalog information, not table data.
+</Note>
+
+
+## Basic Usage
+
+```python
+import os
+from semantica.ingest import PowerBIIngestor
+
+ingestor = PowerBIIngestor(
+ tenant_id=os.getenv("POWERBI_TENANT_ID"),
+ client_id=os.getenv("POWERBI_CLIENT_ID"),
+ client_secret=os.getenv("POWERBI_CLIENT_SECRET"),
+)
+
+data = ingestor.ingest_workspace_metadata()
+documents = ingestor.export_as_documents(data)
+
+print(f"{len(documents)} documents — {data.metadata['dataset_count']} dataset(s)")
+```
+
+<Tip>
+Use environment variables (or a `.env` file with `python-dotenv`) to keep credentials out of source code. `PowerBIIngestor()` with no arguments reads from `POWERBI_*` environment variables automatically.
+</Tip>
+
+
+## Authentication
+
+The connector uses the Azure AD OAuth2 **client-credentials** flow. Register an application in Azure AD, grant it access to the Power BI service, and supply its tenant, client ID and secret.
+
+Required configuration:
+
+| Setting | Argument | Environment variable |
+| --- | --- | --- |
+| Azure AD tenant ID | `tenant_id` | `POWERBI_TENANT_ID` |
+| Application (client) ID | `client_id` | `POWERBI_CLIENT_ID` |
+| Client secret | `client_secret` | `POWERBI_CLIENT_SECRET` |
+| Workspace / group ID (optional) | `workspace_id` | `POWERBI_WORKSPACE_ID` |
+
+Missing any of the first three raises `ValidationError` before any network call is made. Tokens are cached and refreshed automatically shortly before expiry. The client secret is never written to logs.
+
+
+## Scoping to One Workspace
+
+Pass a workspace (group) ID to read a single workspace; omit it to walk every workspace the service principal can see, collecting datasets, reports and dataflows from each and tagging every record with the `workspace_id` it came from. That per-workspace walk is deliberate: the unscoped `myorg` endpoints only cover My workspace, and dataflows have no unscoped endpoint.
+
+```python
+data = ingestor.ingest_workspace_metadata(workspace_id="00000000-0000-0000-0000-000000000000")
+```
+
+Select only the resources you need with `include` (an empty list pulls nothing):
+
+```python
+data = ingestor.ingest_workspace_metadata(include=["datasets", "reports"])
+```
+
+
+## Document Output
+
+`export_as_documents` returns the standard `{"id", "text", "metadata"}` shape, so the output feeds directly into `GraphBuilder`:
+
+```python
+from semantica.kg import GraphBuilder
+
+documents = ingestor.export_as_documents(data)
+graph = GraphBuilder().build(documents)
+```
+
+Each document's `metadata` carries `source: "powerbi"`, a `resource_type` of `workspace`, `dataset`, `report` or `dataflow`, plus the original API fields.
+
+
+## Security
+
+Every outbound HTTP call — including the token request — goes through Semantica's shared SSRF guard, so a user-supplied endpoint cannot reach private, loopback or link-local address space. Set `allow_private_ips=True` only for self-hosted deployments that genuinely need it.
diff --git a/semantica/ingest/__init__.py b/semantica/ingest/__init__.py
index f9d752cb..3a0bbef7 100644
--- a/semantica/ingest/__init__.py
+++ b/semantica/ingest/__init__.py
@@ -133,6 +133,11 @@ import importlib
from typing import TYPE_CHECKING, Any, Dict, Tuple
if TYPE_CHECKING:
+ from .powerbi_ingestor import (
+ PowerBIConnector,
+ PowerBIData,
+ PowerBIIngestor,
+ )
from .salesforce_ingestor import (
SalesforceConnector,
SalesforceData,
@@ -251,6 +256,10 @@ _LAZY_EXPORTS: Dict[str, Tuple[str, str]] = {
"RedshiftIngestor": (".redshift_ingestor", "RedshiftIngestor"),
"RedshiftData": (".redshift_ingestor", "RedshiftData"),
"RedshiftConnector": (".redshift_ingestor", "RedshiftConnector"),
+ # Power BI ingestion
+ "PowerBIIngestor": (".powerbi_ingestor", "PowerBIIngestor"),
+ "PowerBIData": (".powerbi_ingestor", "PowerBIData"),
+ "PowerBIConnector": (".powerbi_ingestor", "PowerBIConnector"),
}
_OPTIONAL_DEPENDENCY_MESSAGES = {
@@ -467,6 +476,10 @@ __all__ = [
"RedshiftIngestor",
"RedshiftData",
"RedshiftConnector",
+ # Power BI ingestion
+ "PowerBIIngestor",
+ "PowerBIData",
+ "PowerBIConnector",
# Registry and Methods
"MethodRegistry",
"method_registry",
diff --git a/semantica/ingest/powerbi_ingestor.py b/semantica/ingest/powerbi_ingestor.py
new file mode 100644
index 00000000..2c988957
--- /dev/null
+++ b/semantica/ingest/powerbi_ingestor.py
@@ -0,0 +1,813 @@
+"""Power BI ingestion module.
+
+Pulls workspace, dataset, report and dataflow metadata from the Power BI
+REST API and flattens it into document dicts that feed straight into
+``GraphBuilder``.
+
+The Power BI REST API is plain OAuth2 + JSON, so this connector needs
+nothing beyond ``requests`` — the same shape as the SAP connector.
+
+Design notes
+------------
+Three classes, matching the Snowflake/Salesforce/Redshift ingestors:
+
+- ``PowerBIData``: holds one ingestion run's worth of metadata
+ (``workspaces``, ``datasets``, ``reports``, ``dataflows``, ``metadata``,
+ ``ingested_at``). No network dependency — always importable.
+
+- ``PowerBIConnector``: owns the Azure AD OAuth2 client-credentials token
+ lifecycle and the ``requests`` session. Raises ``ValidationError`` when
+ the credentials are incomplete. Every outbound call goes through
+ ``request_with_ssrf_guard``.
+
+- ``PowerBIIngestor``: orchestrates ingestion and exposes
+ ``export_as_documents``.
+
+Authentication
+--------------
+Azure AD OAuth2 client-credentials::
+
+ connector = PowerBIConnector(
+ tenant_id="00000000-0000-0000-0000-000000000000",
+ client_id="...",
+ client_secret="...",
+ )
+
+Credentials may also come from the environment:
+
+* ``POWERBI_TENANT_ID``
+* ``POWERBI_CLIENT_ID``
+* ``POWERBI_CLIENT_SECRET``
+* ``POWERBI_WORKSPACE_ID`` (optional)
+
+The client secret is kept in a private attribute and is never logged.
+
+Dependencies
+------------
+``requests`` is a core Semantica dependency, so no extra is needed::
+
+ pip install semantica
+
+The module is registered as a lazy export in ``__init__.py``, so a
+top-level ``import semantica.ingest`` does not import it until one of the
+classes below is first accessed.
+"""
+
+from __future__ import annotations
+
+import os
+import time
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Sequence
+from urllib.parse import urlparse
+
+import requests
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from ..utils.progress_tracker import get_progress_tracker
+from .ssrf import parse_bool, request_with_ssrf_guard
+
+__all__ = [
+ "PowerBIData",
+ "PowerBIConnector",
+ "PowerBIIngestor",
+]
+
+_DEFAULT_API_BASE = "https://api.powerbi.com/v1.0/myorg"
+_DEFAULT_TOKEN_URL = "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
+_DEFAULT_SCOPE = "https://analysis.windows.net/powerbi/api/.default"
+
+# Resources the ingestor can pull, in the order they are exported.
+_RESOURCE_KEYS = ("workspaces", "datasets", "reports", "dataflows")
+
+_logger = get_logger("powerbi_ingestor")
+
+
+def _origin(url: str) -> tuple:
+ """Return the ``(scheme, host, effective port)`` triple for *url*.
+
+ Used to keep pagination on one origin: every hop re-sends the bearer
+ token, so a next link must not be allowed to move it elsewhere.
+ """
+ parsed = urlparse(url or "")
+ scheme = (parsed.scheme or "").lower()
+ default_port = 443 if scheme == "https" else 80
+ return scheme, (parsed.hostname or "").lower(), parsed.port or default_port
+
+
+def _decode_json(response: Any) -> Any:
+ """Decode a response body, falling back to raw text when it is not JSON.
+
+ Azure's front door answers 502/503 with an HTML error page. Calling
+ ``response.json()`` before checking the status would raise
+ ``JSONDecodeError`` and hide the status code the caller has to report.
+ """
+ try:
+ return response.json()
+ except ValueError:
+ return response.text
+
+
+# ---------------------------------------------------------------------------
+# PowerBIData
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class PowerBIData:
+ """Metadata returned from the Power BI REST API.
+
+ Attributes:
+ workspaces: Workspace (group) summaries, one dict per workspace.
+ datasets: Dataset summaries.
+ reports: Report summaries.
+ dataflows: Dataflow summaries.
+ metadata: Run metadata (API base, workspace, per-resource counts).
+ ingested_at: Timestamp recorded when this object was created.
+ """
+
+ workspaces: List[Dict[str, Any]]
+ datasets: List[Dict[str, Any]]
+ reports: List[Dict[str, Any]]
+ dataflows: List[Dict[str, Any]]
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ ingested_at: datetime = field(default_factory=datetime.now)
+
+
+# ---------------------------------------------------------------------------
+# PowerBIConnector
+# ---------------------------------------------------------------------------
+
+
+class PowerBIConnector:
+ """Manages the Power BI REST client and OAuth2 token lifecycle.
+
+ Responsibilities:
+
+ * Resolves credentials from constructor arguments, falling back to
+ ``POWERBI_*`` environment variables.
+ * Validates that a usable credential set is configured *before* any
+ network call is made.
+ * Acquires and caches an Azure AD client-credentials token, refreshing
+ it shortly before expiry.
+ * Exposes :meth:`test_connection` and :meth:`close`.
+
+ Every outbound HTTP call — including the token request — goes through
+ :func:`~semantica.ingest.ssrf.request_with_ssrf_guard`, so a
+ user-supplied endpoint cannot reach private/loopback/link-local space.
+
+ Raises:
+ ImportError: When ``requests`` is not installed.
+ ValidationError: When required credentials are incomplete.
+ """
+
+ def __init__(
+ self,
+ tenant_id: Optional[str] = None,
+ client_id: Optional[str] = None,
+ client_secret: Optional[str] = None,
+ workspace_id: Optional[str] = None,
+ api_base: Optional[str] = None,
+ token_url: Optional[str] = None,
+ scope: Optional[str] = None,
+ allow_private_ips: Optional[bool] = None,
+ timeout: int = 30,
+ **config: Any,
+ ) -> None:
+ """Initialise the connector and validate credentials.
+
+ Args:
+ tenant_id: Azure AD tenant ID. Defaults to ``POWERBI_TENANT_ID``.
+ client_id: Registered application (client) ID. Defaults to
+ ``POWERBI_CLIENT_ID``.
+ client_secret: Application secret. Defaults to
+ ``POWERBI_CLIENT_SECRET``. Never logged.
+ workspace_id: Optional default workspace (group) ID used when a
+ method is called without an explicit workspace.
+ api_base: Power BI API base URL. Defaults to
+ ``https://api.powerbi.com/v1.0/myorg``.
+ token_url: Azure AD token endpoint template. ``{tenant_id}`` is
+ substituted with the configured tenant.
+ scope: OAuth2 scope. Defaults to the Power BI ``.default`` scope.
+ allow_private_ips: Allow requests to private networks (for
+ self-hosted gateways behind a VPN).
+ timeout: Per-request timeout in seconds.
+ **config: Extra configuration kept for callers.
+
+ Raises:
+ ImportError: When ``requests`` is not installed.
+ ValidationError: When required credentials are incomplete.
+ """
+ self.logger = _logger
+
+ self.tenant_id = tenant_id or os.getenv("POWERBI_TENANT_ID")
+ self.client_id = client_id or os.getenv("POWERBI_CLIENT_ID")
+ # Secrets stay private and are never included in log messages.
+ self._client_secret = client_secret or os.getenv("POWERBI_CLIENT_SECRET")
+ self.workspace_id = workspace_id or os.getenv("POWERBI_WORKSPACE_ID")
+
+ self.api_base = (api_base or _DEFAULT_API_BASE).rstrip("/")
+ self.token_url_template = token_url or _DEFAULT_TOKEN_URL
+ self.scope = scope or _DEFAULT_SCOPE
+ # Routed through parse_bool(): "false" and "0" arriving as strings
+ # from an env or CLI config are truthy in Python, and a raw
+ # assignment would quietly turn every SSRF check below into a no-op.
+ self.allow_private_ips = parse_bool(allow_private_ips, default=False)
+ self.timeout = timeout
+ self.config: Dict[str, Any] = config
+
+ self._session: Optional[Any] = requests.Session() if requests else None
+ self._access_token: Optional[str] = None
+ self._token_expiry: float = 0.0
+
+ self._validate_auth()
+
+ self.logger.debug(
+ "Power BI connector initialised (tenant=%s, workspace=%s)",
+ self.tenant_id,
+ self.workspace_id,
+ )
+
+ # ------------------------------------------------------------------
+ # Validation
+ # ------------------------------------------------------------------
+
+ def _validate_auth(self) -> None:
+ """Raise when the configured credentials cannot authenticate.
+
+ Raises:
+ ValidationError: If tenant_id, client_id or client_secret is
+ missing.
+ """
+ if not self.tenant_id:
+ raise ValidationError(
+ "Power BI tenant_id is required. Provide via 'tenant_id' or "
+ "POWERBI_TENANT_ID environment variable."
+ )
+ if not self.client_id:
+ raise ValidationError(
+ "Power BI client_id is required. Provide via 'client_id' or "
+ "POWERBI_CLIENT_ID environment variable."
+ )
+ if not self._client_secret:
+ raise ValidationError(
+ "Power BI client_secret is required. Provide via "
+ "'client_secret' or POWERBI_CLIENT_SECRET environment variable."
+ )
+
+ # ------------------------------------------------------------------
+ # Token handling
+ # ------------------------------------------------------------------
+
+ @property
+ def token_url(self) -> str:
+ """Azure AD token endpoint for the configured tenant."""
+ return self.token_url_template.format(tenant_id=self.tenant_id)
+
+ def _request_token(self) -> str:
+ """Acquire an OAuth2 access token via client-credentials.
+
+ Returns:
+ The access token string.
+
+ Raises:
+ ProcessingError: If the token endpoint call fails or returns no
+ token.
+ """
+ data = {
+ "grant_type": "client_credentials",
+ "client_id": self.client_id,
+ "client_secret": self._client_secret,
+ "scope": self.scope,
+ }
+
+ try:
+ response = request_with_ssrf_guard(
+ "POST",
+ self.token_url,
+ session=self._session,
+ allow_private_ips=self.allow_private_ips,
+ data=data,
+ timeout=self.timeout,
+ )
+ body = _decode_json(response)
+ if response.status_code >= 400:
+ raise ProcessingError(
+ f"Power BI token endpoint returned {response.status_code}: "
+ f"{str(body)[:200]}"
+ )
+ if not isinstance(body, dict):
+ raise ProcessingError(
+ "Power BI token endpoint returned a non-JSON body."
+ )
+ token = body.get("access_token")
+ if not token:
+ raise ProcessingError(
+ "Power BI token endpoint returned no access_token."
+ )
+ expires_in = int(body.get("expires_in") or 3600)
+ self._access_token = token
+ # Refresh a minute early so an in-flight request cannot race
+ # against expiry.
+ self._token_expiry = time.monotonic() + max(expires_in - 60, 0)
+ return token
+ except ProcessingError:
+ raise
+ except Exception as exc:
+ raise ProcessingError(
+ f"Failed to acquire Power BI access token: {type(exc).__name__}"
+ ) from exc
+
+ def _ensure_token(self) -> str:
+ """Return a valid access token, refreshing when needed."""
+ if self._access_token and time.monotonic() < self._token_expiry:
+ return self._access_token
+ return self._request_token()
+
+ def _auth_headers(self) -> Dict[str, str]:
+ """Build the Authorization header for an API call."""
+ return {
+ "Authorization": f"Bearer {self._ensure_token()}",
+ "Accept": "application/json",
+ }
+
+ # ------------------------------------------------------------------
+ # HTTP
+ # ------------------------------------------------------------------
+
+ def _url(self, path: str) -> str:
+ """Join *path* onto the configured API base."""
+ return f"{self.api_base}/{path.lstrip('/')}"
+
+ def _same_origin(self, url: str) -> bool:
+ """True when *url* shares the origin of the configured API base."""
+ return _origin(url) == _origin(self.api_base)
+
+ def get(
+ self,
+ path: str,
+ params: Optional[Dict[str, Any]] = None,
+ ) -> Any:
+ """GET a Power BI endpoint and return the decoded JSON body.
+
+ Follows ``@odata.nextLink`` pagination up to a bounded number of
+ hops, unwrapping the ``value`` list the API returns for collections.
+
+ Args:
+ path: Path relative to the API base, e.g. ``"groups"``.
+ params: Optional query parameters for the first request.
+
+ Returns:
+ The decoded JSON body. For collection responses this is the
+ accumulated ``value`` list.
+
+ Raises:
+ ProcessingError: If the request or JSON decoding fails.
+ """
+ url = self._url(path)
+ items: List[Any] = []
+ saw_value = False
+ hops = 0
+
+ while url:
+ # Rebuilt on every hop: a large collection can outlive the token
+ # lifetime, and _ensure_token() refreshes it when that happens.
+ headers = self._auth_headers()
+ try:
+ response = request_with_ssrf_guard(
+ "GET",
+ url,
+ session=self._session,
+ allow_private_ips=self.allow_private_ips,
+ headers=headers,
+ params=params if hops == 0 else None,
+ timeout=self.timeout,
+ )
+ body = _decode_json(response)
+ if response.status_code >= 400:
+ raise ProcessingError(
+ f"Power BI API returned {response.status_code} for "
+ f"{path}: {str(body)[:200]}"
+ )
+ except ProcessingError:
+ raise
+ except Exception as exc:
+ raise ProcessingError(
+ f"Failed to call Power BI API '{path}': {type(exc).__name__}"
+ ) from exc
+
+ if not isinstance(body, (dict, list)):
+ # 2xx carrying an HTML body — an SSO redirect or a captive
+ # portal — would otherwise be unpacked character by character
+ # by list() in the collection helpers instead of failing.
+ raise ProcessingError(
+ f"Power BI API returned a non-JSON body for '{path}'."
+ )
+ if isinstance(body, dict):
+ if "value" in body:
+ saw_value = True
+ items.extend(body.get("value") or [])
+ next_url = body.get("@odata.nextLink") or ""
+ if next_url and not self._same_origin(next_url):
+ raise ProcessingError(
+ f"Power BI pagination for '{path}' returned a next "
+ f"link on another origin ({_origin(next_url)[1]}); "
+ "refusing to send the access token there."
+ )
+ url = next_url
+ else:
+ return body
+ else:
+ return body
+
+ hops += 1
+ if hops >= 100: # bounded follow — defensive against loops
+ self.logger.warning(
+ "Power BI pagination for '%s' exceeded 100 hops; stopping.",
+ path,
+ )
+ break
+
+ return items if saw_value else []
+
+ # ------------------------------------------------------------------
+ # Resource helpers
+ # ------------------------------------------------------------------
+
+ def _workspace_path(self, resource: str, workspace_id: Optional[str]) -> str:
+ """Return the API path for *resource*, scoped to a workspace if given."""
+ target = workspace_id or self.workspace_id
+ if target:
+ return f"groups/{target}/{resource}"
+ return resource
+
+ def get_workspaces(self) -> List[Dict[str, Any]]:
+ """Return workspace (group) summaries visible to the principal."""
+ return list(self.get("groups") or [])
+
+ def get_datasets(self, workspace_id: Optional[str] = None) -> List[Dict[str, Any]]:
+ """Return dataset summaries, optionally scoped to one workspace."""
+ path = self._workspace_path("datasets", workspace_id)
+ return list(self.get(path) or [])
+
+ def get_reports(self, workspace_id: Optional[str] = None) -> List[Dict[str, Any]]:
+ """Return report summaries, optionally scoped to one workspace."""
+ path = self._workspace_path("reports", workspace_id)
+ return list(self.get(path) or [])
+
+ def get_dataflows(self, workspace_id: Optional[str] = None) -> List[Dict[str, Any]]:
+ """Return dataflow summaries, optionally scoped to one workspace."""
+ path = self._workspace_path("dataflows", workspace_id)
+ return list(self.get(path) or [])
+
+ # ------------------------------------------------------------------
+ # Lifecycle
+ # ------------------------------------------------------------------
+
+ def test_connection(self) -> bool:
+ """Verify credentials by acquiring a token and reading one endpoint.
+
+ When a default workspace is configured the probe targets that
+ workspace, because a principal granted access to a single workspace
+ cannot list groups and would otherwise fail a check its credentials
+ actually pass.
+
+ Returns:
+ ``True`` when both steps succeed, ``False`` otherwise.
+ """
+ try:
+ self._ensure_token()
+ if self.workspace_id:
+ self.get(f"groups/{self.workspace_id}")
+ else:
+ self.get_workspaces()
+ return True
+ except Exception as exc:
+ self.logger.debug("Power BI connection test failed: %s", type(exc).__name__)
+ return False
+
+ def close(self) -> None:
+ """Close the underlying HTTP session."""
+ if self._session is not None:
+ try:
+ self._session.close()
+ except Exception: # noqa: BLE001
+ pass
+ self._session = None
+
+
+# ---------------------------------------------------------------------------
+# PowerBIIngestor
+# ---------------------------------------------------------------------------
+
+
+class PowerBIIngestor:
+ """Power BI metadata ingestor for the Semantica framework.
+
+ Wraps :class:`PowerBIConnector` and exposes workspace-metadata ingestion
+ plus document export.
+
+ Args:
+ tenant_id: Azure AD tenant ID.
+ client_id: Registered application (client) ID.
+ client_secret: Application secret.
+ workspace_id: Optional default workspace (group) ID.
+ api_base: Power BI API base URL.
+ allow_private_ips: Allow private-network requests.
+ timeout: Per-request timeout in seconds.
+ connector: An existing :class:`PowerBIConnector` to reuse.
+ config: Optional extra configuration forwarded to the connector.
+ **kwargs: Additional keyword arguments merged into ``config``.
+
+ Example::
+
+ from semantica.ingest import PowerBIIngestor
+
+ ingestor = PowerBIIngestor(
+ tenant_id="...", client_id="...", client_secret="..."
+ )
+ data = ingestor.ingest_workspace_metadata()
+ documents = ingestor.export_as_documents(data)
+ """
+
+ def __init__(
+ self,
+ tenant_id: Optional[str] = None,
+ client_id: Optional[str] = None,
+ client_secret: Optional[str] = None,
+ workspace_id: Optional[str] = None,
+ api_base: Optional[str] = None,
+ allow_private_ips: Optional[bool] = None,
+ timeout: int = 30,
+ connector: Optional[PowerBIConnector] = None,
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> None:
+ self.logger = _logger
+
+ self.config: Dict[str, Any] = config or {}
+ self.config.update(kwargs)
+ # Taken out here so it reaches the connector once, through the
+ # connector's own parse_bool() path, rather than being passed both
+ # explicitly and again inside **self.config.
+ allow_private_ips = parse_bool(
+ self.config.pop("allow_private_ips", allow_private_ips), default=False
+ )
+
+ self.connector: PowerBIConnector = connector or PowerBIConnector(
+ tenant_id=tenant_id,
+ client_id=client_id,
+ client_secret=client_secret,
+ workspace_id=workspace_id,
+ api_base=api_base,
+ allow_private_ips=allow_private_ips,
+ timeout=timeout,
+ **self.config,
+ )
+
+ self.progress_tracker = get_progress_tracker()
+ if not self.progress_tracker.enabled:
+ self.progress_tracker.enabled = True
+
+ self.logger.debug("Power BI ingestor initialised.")
+
+ # ------------------------------------------------------------------
+ # Context manager
+ # ------------------------------------------------------------------
+
+ def __enter__(self) -> "PowerBIIngestor":
+ return self
+
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
+ self.close()
+
+ def close(self) -> None:
+ """Close the underlying connector."""
+ self.connector.close()
+
+ # ------------------------------------------------------------------
+ # Ingestion
+ # ------------------------------------------------------------------
+
+ def _fetch_child(
+ self, resource: str, workspace_id: Optional[str]
+ ) -> List[Dict[str, Any]]:
+ """Call the connector helper matching *resource* for one workspace."""
+ if resource == "datasets":
+ return self.connector.get_datasets(workspace_id)
+ if resource == "reports":
+ return self.connector.get_reports(workspace_id)
+ return self.connector.get_dataflows(workspace_id)
+
+ def ingest_workspace_metadata(
+ self,
+ workspace_id: Optional[str] = None,
+ include: Optional[Sequence[str]] = None,
+ ) -> PowerBIData:
+ """Pull workspace, dataset, report and dataflow metadata.
+
+ Args:
+ workspace_id: Workspace (group) to read. Defaults to the
+ connector's configured workspace; when that is unset the
+ workspaces themselves are listed and datasets, reports and
+ dataflows are collected across each of them, each record
+ tagged with the ``workspace_id`` it came from.
+ include: Subset of ``("workspaces", "datasets", "reports",
+ "dataflows")`` to pull. Defaults to all four; pass an empty
+ sequence to pull nothing.
+
+ Returns:
+ :class:`PowerBIData` with the requested collections populated.
+
+ Raises:
+ ValidationError: If *include* names an unknown resource.
+ ProcessingError: If any API call fails.
+ """
+ wanted = _RESOURCE_KEYS if include is None else tuple(include)
+ unknown = [name for name in wanted if name not in _RESOURCE_KEYS]
+ if unknown:
+ raise ValidationError(
+ f"Unknown Power BI resource(s): {', '.join(unknown)}. "
+ f"Expected any of: {', '.join(_RESOURCE_KEYS)}."
+ )
+
+ tracking_id = self.progress_tracker.start_tracking(
+ file=workspace_id or self.connector.workspace_id or "myorg",
+ module="ingest",
+ submodule="PowerBIIngestor",
+ message="Pulling Power BI metadata",
+ )
+
+ collected: Dict[str, List[Dict[str, Any]]] = {key: [] for key in _RESOURCE_KEYS}
+
+ try:
+ scope = workspace_id or self.connector.workspace_id
+
+ if "workspaces" in wanted:
+ if scope:
+ # A single workspace was requested — describe just it.
+ workspace = self.connector.get(f"groups/{scope}")
+ collected["workspaces"] = [workspace] if workspace else []
+ else:
+ collected["workspaces"] = self.connector.get_workspaces()
+
+ children = [k for k in ("datasets", "reports", "dataflows") if k in wanted]
+ if children:
+ if scope:
+ # Tag the same way the multi-workspace walk below does:
+ # Power BI does not consistently echo workspaceId on the
+ # child endpoints, and GraphBuilder needs the link.
+ for key in children:
+ for item in self._fetch_child(key, scope):
+ if isinstance(item, dict):
+ item.setdefault("workspace_id", scope)
+ collected[key].append(item)
+ else:
+ # With no workspace configured the unscoped endpoints only
+ # cover "My workspace", and dataflows have no unscoped
+ # endpoint at all. Walk the visible workspaces instead and
+ # tag each record with the workspace it came from.
+ workspaces = collected["workspaces"]
+ if not workspaces and "workspaces" not in wanted:
+ workspaces = self.connector.get_workspaces()
+ for workspace in workspaces:
+ if not isinstance(workspace, dict):
+ continue
+ group_id = workspace.get("id")
+ if not group_id:
+ continue
+ for key in children:
+ for item in self._fetch_child(key, group_id):
+ if isinstance(item, dict):
+ item.setdefault("workspace_id", group_id)
+ collected[key].append(item)
+
+ data = PowerBIData(
+ workspaces=collected["workspaces"],
+ datasets=collected["datasets"],
+ reports=collected["reports"],
+ dataflows=collected["dataflows"],
+ metadata={
+ "api_base": self.connector.api_base,
+ "workspace_id": workspace_id or self.connector.workspace_id,
+ "workspace_count": len(collected["workspaces"]),
+ "dataset_count": len(collected["datasets"]),
+ "report_count": len(collected["reports"]),
+ "dataflow_count": len(collected["dataflows"]),
+ },
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=(
+ f"Pulled {len(data.workspaces)} workspace(s), "
+ f"{len(data.datasets)} dataset(s), "
+ f"{len(data.reports)} report(s), "
+ f"{len(data.dataflows)} dataflow(s)"
+ ),
+ )
+ self.logger.info(
+ "Power BI ingestion completed: %d workspace(s), %d dataset(s), "
+ "%d report(s), %d dataflow(s)",
+ len(data.workspaces),
+ len(data.datasets),
+ len(data.reports),
+ len(data.dataflows),
+ )
+ return data
+
+ except (ValidationError, ProcessingError):
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message="Power BI ingestion failed"
+ )
+ raise
+ except Exception as exc:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(exc)
+ )
+ self.logger.error(
+ "Failed to ingest Power BI metadata: %s", type(exc).__name__
+ )
+ raise ProcessingError(
+ f"Failed to ingest Power BI metadata: {type(exc).__name__}"
+ ) from exc
+
+ # ------------------------------------------------------------------
+ # Document export
+ # ------------------------------------------------------------------
+
+ def export_as_documents(
+ self,
+ data: PowerBIData,
+ ) -> List[Dict[str, Any]]:
+ """Convert :class:`PowerBIData` to the Semantica document format.
+
+ Produces the same ``{"id", "text", "metadata"}`` shape used by the
+ Snowflake and Redshift ingestors, so the result is directly usable
+ with ``GraphBuilder``.
+
+ Args:
+ data: A :class:`PowerBIData` returned by
+ :meth:`ingest_workspace_metadata`.
+
+ Returns:
+ List of document dictionaries::
+
+ [
+ {
+ "id": str,
+ "text": str,
+ "metadata": {
+ "source": "powerbi",
+ "resource_type": "dataset" | "report" | ...,
+ ...original fields...
+ },
+ },
+ ...
+ ]
+ """
+ documents: List[Dict[str, Any]] = []
+
+ for resource_type in _RESOURCE_KEYS:
+ singular = resource_type[:-1] # datasets -> dataset
+ for index, item in enumerate(getattr(data, resource_type) or []):
+ if not isinstance(item, dict):
+ continue
+ text = self._describe(item, singular)
+ # Copy the item first and set the connector-owned keys after,
+ # so a "source" or "resource_type" coming from Power BI
+ # cannot clobber them.
+ metadata: Dict[str, Any] = dict(item)
+ metadata["source"] = "powerbi"
+ metadata["resource_type"] = singular
+ documents.append(
+ {
+ "id": str(item.get("id") or f"{singular}-{index}"),
+ "text": text,
+ "metadata": metadata,
+ }
+ )
+
+ self.logger.debug(
+ "export_as_documents: exported %d document(s)", len(documents)
+ )
+ return documents
+
+ @staticmethod
+ def _describe(item: Dict[str, Any], resource_type: str) -> str:
+ """Build a one-paragraph text description of a Power BI object."""
+ name = item.get("name") or item.get("displayName") or item.get("id")
+ parts = [f"{name} (Power BI {resource_type})"]
+
+ description = item.get("description")
+ if description:
+ parts.append(str(description))
+
+ for key in ("workspaceId", "datasetId", "reportType", "configuredBy"):
+ if item.get(key) is not None:
+ parts.append(f"{key}: {item[key]}")
+
+ return "\n".join(parts)
diff --git a/tests/ingest/test_powerbi_ingestor.py b/tests/ingest/test_powerbi_ingestor.py
new file mode 100644
index 00000000..5c6b86f2
--- /dev/null
+++ b/tests/ingest/test_powerbi_ingestor.py
@@ -0,0 +1,466 @@
+"""Unit tests for the Power BI ingestor.
+
+The HTTP layer is mocked by patching ``request_with_ssrf_guard`` in the
+ingestor module. Tests assert on the *call signature* (method first, url
+second) so a mistake in argument order fails here instead of at runtime.
+"""
+
+import unittest
+from unittest.mock import patch
+
+from semantica.ingest import powerbi_ingestor as pbi
+from semantica.ingest.powerbi_ingestor import (
+ PowerBIConnector,
+ PowerBIData,
+ PowerBIIngestor,
+)
+from semantica.utils.exceptions import ProcessingError, ValidationError
+
+GUARD = "semantica.ingest.powerbi_ingestor.request_with_ssrf_guard"
+
+CREDS = {
+ "tenant_id": "tenant-1",
+ "client_id": "client-1",
+ "client_secret": "secret-1",
+}
+
+
+class FakeResponse:
+ """Minimal stand-in for ``requests.Response``.
+
+ ``json_error`` makes :meth:`json` raise, which is how a real response
+ behaves when the body is an HTML error page rather than JSON.
+ """
+
+ def __init__(self, payload, status_code=200, text=None, json_error=None):
+ self._payload = payload
+ self.status_code = status_code
+ self.text = text if text is not None else str(payload)
+ self._json_error = json_error
+
+ def json(self):
+ if self._json_error is not None:
+ raise self._json_error
+ return self._payload
+
+
+def token_response():
+ return FakeResponse({"access_token": "tok-123", "expires_in": 3600})
+
+
+class TestLazyExports(unittest.TestCase):
+ def test_classes_are_module_level_attributes(self):
+ self.assertTrue(hasattr(pbi, "PowerBIData"))
+ self.assertTrue(hasattr(pbi, "PowerBIConnector"))
+ self.assertTrue(hasattr(pbi, "PowerBIIngestor"))
+
+ def test_module_all_lists_three_classes(self):
+ self.assertEqual(
+ set(pbi.__all__),
+ {"PowerBIData", "PowerBIConnector", "PowerBIIngestor"},
+ )
+
+ def test_lazy_export_resolves_via_package(self):
+ import semantica.ingest as ingest_pkg
+
+ self.assertIs(ingest_pkg.PowerBIIngestor, PowerBIIngestor)
+ self.assertIs(ingest_pkg.PowerBIData, PowerBIData)
+
+
+class TestCredentialValidation(unittest.TestCase):
+ def test_missing_tenant_raises(self):
+ with self.assertRaises(ValidationError):
+ PowerBIConnector(client_id="c", client_secret="s")
+
+ def test_missing_client_id_raises(self):
+ with self.assertRaises(ValidationError):
+ PowerBIConnector(tenant_id="t", client_secret="s")
+
+ def test_missing_client_secret_raises(self):
+ with self.assertRaises(ValidationError):
+ PowerBIConnector(tenant_id="t", client_id="c")
+
+ def test_allow_private_ips_string_false_is_not_truthy(self):
+ connector = PowerBIConnector(**CREDS, allow_private_ips="false")
+ self.assertFalse(connector.allow_private_ips)
+ connector.close()
+
+ def test_allow_private_ips_string_true_opt_in(self):
+ connector = PowerBIConnector(**CREDS, allow_private_ips="true")
+ self.assertTrue(connector.allow_private_ips)
+ connector.close()
+
+ def test_allow_private_ips_defaults_to_false(self):
+ connector = PowerBIConnector(**CREDS)
+ self.assertFalse(connector.allow_private_ips)
+ connector.close()
+
+ def test_full_credentials_construct(self):
+ connector = PowerBIConnector(**CREDS)
+ self.assertEqual(connector.tenant_id, "tenant-1")
+ connector.close()
+
+ def test_secret_not_exposed_as_public_attribute(self):
+ connector = PowerBIConnector(**CREDS)
+ self.assertNotIn("secret-1", str(vars(connector).get("client_id", "")))
+ self.assertIsNone(vars(connector).get("client_secret"))
+ connector.close()
+
+
+class TestTokenAcquisition(unittest.TestCase):
+ def test_token_request_uses_post_and_token_url(self):
+ connector = PowerBIConnector(**CREDS)
+ with patch(GUARD, return_value=token_response()) as guard:
+ token = connector._request_token()
+ self.assertEqual(token, "tok-123")
+ args, kwargs = guard.call_args
+ self.assertEqual(args[0], "POST")
+ self.assertIn("oauth2/v2.0/token", args[1])
+ self.assertEqual(kwargs["data"]["grant_type"], "client_credentials")
+ self.assertEqual(kwargs["data"]["client_id"], "client-1")
+ self.assertEqual(kwargs["data"]["client_secret"], "secret-1")
+ connector.close()
+
+ def test_token_is_cached(self):
+ connector = PowerBIConnector(**CREDS)
+ with patch(GUARD, return_value=token_response()) as guard:
+ connector._ensure_token()
+ connector._ensure_token()
+ self.assertEqual(guard.call_count, 1)
+ connector.close()
+
+ def test_token_endpoint_error_raises(self):
+ connector = PowerBIConnector(**CREDS)
+ with patch(GUARD, return_value=FakeResponse({"error": "nope"}, 401)):
+ with self.assertRaises(ProcessingError):
+ connector._request_token()
+ connector.close()
+
+ def test_token_missing_field_raises(self):
+ connector = PowerBIConnector(**CREDS)
+ with patch(GUARD, return_value=FakeResponse({"expires_in": 3600})):
+ with self.assertRaises(ProcessingError):
+ connector._request_token()
+ connector.close()
+
+
+class TestApiCalls(unittest.TestCase):
+ def setUp(self):
+ self.connector = PowerBIConnector(**CREDS)
+
+ def tearDown(self):
+ self.connector.close()
+
+ def test_get_uses_get_method_and_full_url(self):
+ with patch(GUARD) as guard:
+ guard.side_effect = [token_response(), FakeResponse({"value": []})]
+ self.connector.get("groups")
+ args, kwargs = guard.call_args
+ self.assertEqual(args[0], "GET")
+ self.assertEqual(args[1], "https://api.powerbi.com/v1.0/myorg/groups")
+ self.assertIn("Authorization", kwargs["headers"])
+ self.assertTrue(kwargs["headers"]["Authorization"].startswith("Bearer "))
+
+ def test_collection_response_is_unwrapped(self):
+ payload = {"value": [{"id": "ws-1", "name": "Sales"}]}
+ with patch(GUARD) as guard:
+ guard.side_effect = [token_response(), FakeResponse(payload)]
+ result = self.connector.get_workspaces()
+ self.assertEqual(result, [{"id": "ws-1", "name": "Sales"}])
+
+ def test_object_response_returned_as_dict(self):
+ with patch(GUARD) as guard:
+ guard.side_effect = [
+ token_response(),
+ FakeResponse({"id": "ws-9", "name": "Only"}),
+ ]
+ result = self.connector.get("groups/ws-9")
+ self.assertEqual(result, {"id": "ws-9", "name": "Only"})
+
+ def test_pagination_follows_next_link(self):
+ first = {
+ "value": [{"id": "a"}],
+ "@odata.nextLink": "https://api.powerbi.com/v1.0/myorg/datasets?skip=1",
+ }
+ second = {"value": [{"id": "b"}]}
+ with patch(GUARD) as guard:
+ guard.side_effect = [
+ token_response(),
+ FakeResponse(first),
+ FakeResponse(second),
+ ]
+ result = self.connector.get("datasets")
+ self.assertEqual([item["id"] for item in result], ["a", "b"])
+ self.assertEqual(guard.call_count, 3)
+
+ def test_pagination_rejects_cross_origin_next_link(self):
+ first = {
+ "value": [{"id": "a"}],
+ "@odata.nextLink": "https://evil.example.com/next",
+ }
+ with patch(GUARD) as guard:
+ guard.side_effect = [token_response(), FakeResponse(first)]
+ with self.assertRaises(ProcessingError):
+ self.connector.get("datasets")
+ self.assertEqual(guard.call_count, 2) # token + first page only
+
+ def test_workspace_scoped_paths(self):
+ with patch(GUARD) as guard:
+ guard.side_effect = [
+ token_response(),
+ FakeResponse({"value": []}),
+ ]
+ self.connector.get_datasets("ws-42")
+ args, _ = guard.call_args
+ self.assertEqual(
+ args[1], "https://api.powerbi.com/v1.0/myorg/groups/ws-42/datasets"
+ )
+
+ def test_unscoped_paths(self):
+ with patch(GUARD) as guard:
+ guard.side_effect = [token_response(), FakeResponse({"value": []})]
+ self.connector.get_reports()
+ args, _ = guard.call_args
+ self.assertEqual(args[1], "https://api.powerbi.com/v1.0/myorg/reports")
+
+ def test_http_error_raises(self):
+ with patch(GUARD) as guard:
+ guard.side_effect = [
+ token_response(),
+ FakeResponse({"error": "boom"}, 403),
+ ]
+ with self.assertRaises(ProcessingError):
+ self.connector.get_workspaces()
+
+ def test_test_connection_true(self):
+ with patch(GUARD) as guard:
+ guard.side_effect = [token_response(), FakeResponse({"value": []})]
+ self.assertTrue(self.connector.test_connection())
+
+ def test_test_connection_false_on_error(self):
+ with patch(GUARD) as guard:
+ guard.side_effect = [token_response(), FakeResponse({}, 500)]
+ self.assertFalse(self.connector.test_connection())
+
+ def test_test_connection_probes_configured_workspace(self):
+ connector = PowerBIConnector(**CREDS, workspace_id="ws-7")
+ with patch(GUARD) as guard:
+ guard.side_effect = [
+ token_response(),
+ FakeResponse({"id": "ws-7", "name": "Only"}),
+ ]
+ self.assertTrue(connector.test_connection())
+ args, _ = guard.call_args
+ self.assertEqual(args[1], "https://api.powerbi.com/v1.0/myorg/groups/ws-7")
+ connector.close()
+
+ def test_non_json_gateway_error_keeps_status_code(self):
+ with patch(GUARD) as guard:
+ guard.side_effect = [
+ token_response(),
+ FakeResponse(
+ None,
+ status_code=502,
+ text="<html>bad gateway</html>",
+ json_error=ValueError("Expecting value"),
+ ),
+ ]
+ with self.assertRaises(ProcessingError) as ctx:
+ self.connector.get_workspaces()
+ self.assertIn("502", str(ctx.exception))
+
+ def test_non_json_success_body_is_rejected(self):
+ # A 200 carrying an SSO redirect page must not be unpacked as a
+ # sequence of characters and read back as an empty workspace list.
+ with patch(GUARD) as guard:
+ guard.side_effect = [
+ token_response(),
+ FakeResponse(
+ None,
+ status_code=200,
+ text="<html>sign in</html>",
+ json_error=ValueError("Expecting value"),
+ ),
+ ]
+ with self.assertRaises(ProcessingError) as ctx:
+ self.connector.get_workspaces()
+ self.assertIn("non-JSON", str(ctx.exception))
+
+ def test_pagination_rebuilds_headers_each_hop(self):
+ first = {
+ "value": [{"id": "a"}],
+ "@odata.nextLink": "https://api.powerbi.com/v1.0/myorg/datasets?skip=1",
+ }
+ with patch(GUARD) as guard:
+ guard.side_effect = [
+ token_response(),
+ FakeResponse(first),
+ FakeResponse({"value": [{"id": "b"}]}),
+ ]
+ with patch.object(
+ self.connector, "_auth_headers", wraps=self.connector._auth_headers
+ ) as headers_spy:
+ self.connector.get("datasets")
+ # One build per hop, so a token that expires mid-pagination is
+ # refreshed rather than replayed on the next request.
+ self.assertEqual(headers_spy.call_count, 2)
+
+
+class TestIngestor(unittest.TestCase):
+ def setUp(self):
+ self.patcher = patch(GUARD)
+ self.guard = self.patcher.start()
+ self.guard.side_effect = [
+ token_response(),
+ FakeResponse({"value": [{"id": "ws-1", "name": "Sales"}]}),
+ FakeResponse({"value": [{"id": "ds-1", "name": "Orders"}]}),
+ FakeResponse({"value": [{"id": "rp-1", "name": "Q3"}]}),
+ FakeResponse({"value": []}),
+ ]
+ self.ingestor = PowerBIIngestor(**CREDS)
+
+ def tearDown(self):
+ self.ingestor.close()
+ self.patcher.stop()
+
+ def test_ingest_returns_powerbi_data(self):
+ data = self.ingestor.ingest_workspace_metadata()
+ self.assertIsInstance(data, PowerBIData)
+ self.assertEqual(len(data.workspaces), 1)
+ self.assertEqual(len(data.datasets), 1)
+ self.assertEqual(len(data.reports), 1)
+ self.assertEqual(len(data.dataflows), 0)
+
+ def test_metadata_counts(self):
+ data = self.ingestor.ingest_workspace_metadata()
+ self.assertEqual(data.metadata["dataset_count"], 1)
+ self.assertEqual(data.metadata["report_count"], 1)
+ self.assertEqual(data.metadata["dataflow_count"], 0)
+
+ def test_include_subset_skips_unwanted_calls(self):
+ self.guard.side_effect = [
+ token_response(),
+ FakeResponse({"value": [{"id": "ws-1", "name": "Sales"}]}),
+ FakeResponse({"value": [{"id": "ds-1", "name": "Orders"}]}),
+ ]
+ data = self.ingestor.ingest_workspace_metadata(include=["datasets"])
+ self.assertEqual(len(data.datasets), 1)
+ self.assertEqual(data.workspaces, [])
+ self.assertEqual(data.reports, [])
+ self.assertEqual(data.dataflows, [])
+
+ def test_empty_include_pulls_nothing(self):
+ self.guard.side_effect = [token_response()]
+ data = self.ingestor.ingest_workspace_metadata(include=[])
+ self.assertEqual(data.workspaces, [])
+ self.assertEqual(data.datasets, [])
+ self.assertEqual(data.reports, [])
+ self.assertEqual(data.dataflows, [])
+ self.assertEqual(self.guard.call_count, 0) # not even a token fetch
+
+ def test_unscoped_ingest_walks_each_workspace(self):
+ self.guard.side_effect = [
+ token_response(),
+ FakeResponse({"value": [{"id": "ws-1"}, {"id": "ws-2"}]}),
+ FakeResponse({"value": [{"id": "ds-1"}]}),
+ FakeResponse({"value": [{"id": "rp-1"}]}),
+ FakeResponse({"value": [{"id": "df-1"}]}),
+ FakeResponse({"value": [{"id": "ds-2"}]}),
+ FakeResponse({"value": [{"id": "rp-2"}]}),
+ FakeResponse({"value": [{"id": "df-2"}]}),
+ ]
+ data = self.ingestor.ingest_workspace_metadata()
+ self.assertEqual([d["id"] for d in data.datasets], ["ds-1", "ds-2"])
+ self.assertEqual(data.datasets[0]["workspace_id"], "ws-1")
+ self.assertEqual(data.dataflows[1]["workspace_id"], "ws-2")
+ urls = [call.args[1] for call in self.guard.call_args_list[1:]]
+ self.assertIn("https://api.powerbi.com/v1.0/myorg/groups/ws-1/dataflows", urls)
+ self.assertIn("https://api.powerbi.com/v1.0/myorg/groups/ws-2/dataflows", urls)
+
+ def test_scoped_ingest_uses_group_paths(self):
+ self.guard.side_effect = [
+ token_response(),
+ FakeResponse({"id": "ws-9", "name": "Only"}),
+ FakeResponse({"value": [{"id": "ds-9"}]}),
+ FakeResponse({"value": []}),
+ FakeResponse({"value": []}),
+ ]
+ data = self.ingestor.ingest_workspace_metadata(workspace_id="ws-9")
+ self.assertEqual(len(data.workspaces), 1)
+ self.assertEqual([d["id"] for d in data.datasets], ["ds-9"])
+ urls = [call.args[1] for call in self.guard.call_args_list[1:]]
+ self.assertIn("https://api.powerbi.com/v1.0/myorg/groups/ws-9/datasets", urls)
+ self.assertIn("https://api.powerbi.com/v1.0/myorg/groups/ws-9/dataflows", urls)
+
+ def test_scoped_ingest_tags_workspace_id(self):
+ self.guard.side_effect = [
+ token_response(),
+ FakeResponse({"id": "ws-9", "name": "Only"}),
+ FakeResponse({"value": [{"id": "ds-9"}]}),
+ FakeResponse({"value": []}),
+ FakeResponse({"value": []}),
+ ]
+ data = self.ingestor.ingest_workspace_metadata(workspace_id="ws-9")
+ self.assertEqual(data.datasets[0]["workspace_id"], "ws-9")
+
+ def test_unknown_include_raises(self):
+ with self.assertRaises(ValidationError):
+ self.ingestor.ingest_workspace_metadata(include=["nope"])
+
+ def test_export_documents_shape(self):
+ data = self.ingestor.ingest_workspace_metadata()
+ documents = self.ingestor.export_as_documents(data)
+ self.assertEqual(len(documents), 3)
+ for doc in documents:
+ self.assertIn("id", doc)
+ self.assertIn("text", doc)
+ self.assertIn("metadata", doc)
+ self.assertEqual(doc["metadata"]["source"], "powerbi")
+
+ def test_export_documents_keeps_source_over_upstream_key(self):
+ data = PowerBIData(
+ workspaces=[],
+ datasets=[{"id": "ds-1", "source": "upstream"}],
+ reports=[],
+ dataflows=[],
+ )
+ documents = self.ingestor.export_as_documents(data)
+ self.assertEqual(documents[0]["metadata"]["source"], "powerbi")
+
+ def test_config_string_allow_private_ips_is_parsed(self):
+ ingestor = PowerBIIngestor(**CREDS, config={"allow_private_ips": "false"})
+ self.assertFalse(ingestor.connector.allow_private_ips)
+ ingestor.close()
+
+ def test_export_documents_resource_types(self):
+ data = self.ingestor.ingest_workspace_metadata()
+ documents = self.ingestor.export_as_documents(data)
+ types = {doc["metadata"]["resource_type"] for doc in documents}
+ self.assertEqual(types, {"workspace", "dataset", "report"})
+
+ def test_export_document_text_mentions_name(self):
+ data = self.ingestor.ingest_workspace_metadata()
+ documents = self.ingestor.export_as_documents(data)
+ dataset_doc = [
+ d for d in documents if d["metadata"]["resource_type"] == "dataset"
+ ][0]
+ self.assertIn("Orders", dataset_doc["text"])
+
+ def test_missing_id_falls_back_to_index(self):
+ data = PowerBIData(
+ workspaces=[],
+ datasets=[{"name": "Nameless"}],
+ reports=[],
+ dataflows=[],
+ )
+ documents = self.ingestor.export_as_documents(data)
+ self.assertEqual(documents[0]["id"], "dataset-0")
+
+ def test_context_manager_closes(self):
+ with PowerBIIngestor(**CREDS) as ingestor:
+ self.assertIsNotNone(ingestor.connector)
+ self.assertIsNone(ingestor.connector._session)
+
+
+if __name__ == "__main__":
+ unittest.main()