Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
667 changes: 667 additions & 0 deletions debugger/test_magics_jupyterlab.ipynb

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ strict = true
warn_return_any = false

[[tool.mypy.overrides]]
module = ["respx.*", "pyarrow.*", "shapely.*", "lxml.*"] # none ships type stubs
module = ["respx.*", "pyarrow.*", "shapely.*", "lxml.*", "pandas.*"] # none ships type stubs
ignore_missing_imports = true

[tool.pytest.ini_options]
Expand Down
6 changes: 6 additions & 0 deletions src/eea_datalakehouse/catalog/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ def root(self) -> str:

def close(self) -> None: ...

def search(self, query: str, *, kind: str | None, limit: int) -> list[dict[str, Any]]:
"""Ranked hits for `query` across the catalog's names, tags, descriptions, columns
and wiki pages, as far as the caller may read them: ``{"path": full path, "kind",
"display_name", "description", "tags", "matched", "snippet", "restricted"}``."""
...

# -- what is where --------------------------------------------------------

def exists(self, path: str) -> bool:
Expand Down
10 changes: 10 additions & 0 deletions src/eea_datalakehouse/catalog/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@

from . import dremio_publish, foldertree, operations, retry_state
from .backend import Partitions, PublishOutcome
from .errors import CatalogOperationError
from .foldertree import FolderTransferReport, FolderTree, ProgressCallback
from .operations import CatalogEntry, TableInfo, VersionResult, ViewDefinition
from .rest import CatalogRestClient
Expand Down Expand Up @@ -260,6 +261,15 @@ def __enter__(self) -> Catalog:
def __exit__(self, *exc_info: object) -> None:
self.close()

def search(
self, query: str, *, kind: str | None = None, limit: int = 50
) -> list[dict[str, Any]]:
"""Not on Dremio: catalog search is the Polaris stack's (the Document Service's index)."""
raise CatalogOperationError(
"search is available on the Polaris catalog only (the Document Service's index); "
"on Dremio, use the Dremio catalog panel's search"
)

def close(self) -> None:
"""Dispose the underlying Flight/REST session(s). Idempotent."""
if self._closed:
Expand Down
90 changes: 90 additions & 0 deletions src/eea_datalakehouse/catalog/dds_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""`CatalogSearchClient` — the Document Service's catalog search, for `search` on Polaris.

DDS (``/api/v1/catalog-search``, EEA Lakehouse ``Components/DremioDocumentService``) keeps
one index of the Polaris catalog's metadata: names, tags, display names, descriptions,
columns and wiki pages. It answers with the signed-in user's Keycloak token
(``X-Keycloak-Token``) and only with what their grants let them read::

GET /api/v1/catalog-search?q=…&kind=…&limit=… — ranked hits

A hit's ``path`` is the list of its parts below the catalog (``["water", "bathing",
"sites"]``); ``match`` says where it matched when not by its name (``tag``, ``column``, or
a ``wiki`` sentence); ``restricted`` marks a namespace the user may see exists but not open.
"""

from __future__ import annotations

from collections.abc import Callable
from typing import Any

import httpx

from .dds_public import _message
from .errors import CatalogAuthError, CatalogOperationError
from .settings import user_token

DEFAULT_TIMEOUT = 60.0


class CatalogSearchClient:
"""`search` against DDS at `base_url`, as the signed-in user."""

def __init__(
self,
base_url: str,
*,
token_provider: Callable[[], str | None] = user_token,
http: httpx.Client | None = None,
timeout: float = DEFAULT_TIMEOUT,
verify: str | bool = True,
) -> None:
if not base_url:
raise CatalogOperationError(
"search needs the Document Service: set DDS_BASE_URL in the kernel environment"
)
self._base_url = base_url.rstrip("/")
self._token_provider = token_provider
self._owns_http = http is None
self._http = http or httpx.Client(timeout=timeout, verify=verify)

def __repr__(self) -> str:
return f"CatalogSearchClient(base_url={self._base_url!r})"

def close(self) -> None:
if self._owns_http:
self._http.close()

def search(
self, query: str, *, kind: str | None = None, limit: int = 50
) -> list[dict[str, Any]]:
"""The hits for `query`, best first (see the module docstring for their shape)."""
token = self._token_provider()
if not token:
raise CatalogAuthError(
"search needs your own sign-in (KEYCLOAK_ACCESS_TOKEN is not set)"
)
params: dict[str, str | int] = {"q": query, "limit": limit}
if kind:
params["kind"] = kind
try:
response = self._http.get(
f"{self._base_url}/api/v1/catalog-search",
params=params,
headers={"X-Keycloak-Token": token},
)
except httpx.HTTPError as exc:
raise CatalogOperationError(
f"the Document Service can't be reached ({self._base_url}): {exc}"
) from exc
if response.status_code == 401:
raise CatalogAuthError(f"the Document Service refused the search: {_message(response)}")
if response.status_code == 503:
raise CatalogOperationError(
f"catalog search is not available on the Document Service: {_message(response)}"
)
if response.status_code >= 400:
raise CatalogOperationError(
f"the search failed (HTTP {response.status_code}): {_message(response)}"
)
hits = response.json().get("hits")
return hits if isinstance(hits, list) else []
114 changes: 103 additions & 11 deletions src/eea_datalakehouse/catalog/polaris.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@
from . import operations
from .backend import Partitions, PublishOutcome
from .dds_public import PublicDataClient
from .dds_search import CatalogSearchClient
from .duckdb_engine import DuckDbEngine, quote_identifier, quote_literal
from .errors import CatalogAuthError, CatalogOperationError
from .layout import NOT_PUBLISHED, PUBLIC_TAG
from .object_store import ObjectStore, s3_credentials
from .operations import TableInfo, VersionResult
from .polaris_rest import PARQUET_FORMAT, PolarisHttpError, PolarisRestClient
from .settings import PolarisSettings, tls_verify
Expand Down Expand Up @@ -211,11 +213,15 @@ def __init__(
rest: PolarisRestClient | None = None,
engine: DuckDbEngine | None = None,
public: PublicDataClient | None = None,
searcher: CatalogSearchClient | None = None,
store: ObjectStore | None = None,
) -> None:
self._settings = settings
self.rest = rest or PolarisRestClient(settings)
self.engine = engine or DuckDbEngine(settings)
self._public = public
self._searcher = searcher
self._store = store # made on first use: only dropping a table needs it

def __repr__(self) -> str:
return f"PolarisCatalog(uri={self._settings.uri!r}, catalog={self.root!r})"
Expand All @@ -233,6 +239,34 @@ def close(self) -> None:
self.rest.close()
if self._public is not None:
self._public.close()
if self._searcher is not None:
self._searcher.close()

# -- search -----------------------------------------------------------------
# Through the Document Service's catalog index, which holds every namespace's and
# table's names, tags, descriptions, columns and wiki pages, and answers as the user.

def search(
self, query: str, *, kind: str | None = None, limit: int = 50
) -> list[dict[str, Any]]:
if self._searcher is None:
self._searcher = CatalogSearchClient(
self._settings.dds_base_url, verify=tls_verify(self._settings.ca_file)
)
out = []
for hit in self._searcher.search(query, kind=kind, limit=limit):
match = hit.get("match") or {}
out.append({
"path": ".".join([self.root, *hit.get("path", [])]),
"kind": hit.get("kind"),
"display_name": hit.get("display_name") or "",
"description": hit.get("comment") or "",
"tags": list(hit.get("tags") or []),
"matched": match.get("field") or "",
"snippet": match.get("snippet") or "",
"restricted": bool(hit.get("restricted")),
})
return out

# -- paths ----------------------------------------------------------------

Expand Down Expand Up @@ -461,9 +495,12 @@ def createfolder(

def deletefolder(self, path: str, *, cascade: bool = False, idempotency_key: str) -> None:
"""Delete the namespace `path`; one that is already gone is not an error.
Without `cascade` it must be empty. With it, every table (its data files
too), view, read-only Parquet table (the catalog entry — its files stay in
the bucket) and sub-namespace inside goes first, deepest first."""
Without `cascade` it must be empty. With it, everything inside is purged,
deepest first: every view, table and read-only Parquet table (each with its
folder of files), registered database and sub-namespace, and then each
namespace's own folder in the object store with whatever else is in it (plain
files, leftovers). A folder is only deleted when it lies inside its parent
namespace's folder — a top-level namespace's never is, nor anything outside."""
parts = self.parts(path)
if not parts:
raise CatalogOperationError(f"{path!r} is the catalog itself and can't be deleted")
Expand All @@ -479,20 +516,34 @@ def deletefolder(self, path: str, *, cascade: bool = False, idempotency_key: str
) from exc
raise
return
# Every namespace's folder, read before anything goes (a child's guard is its
# parent's folder, and the parent is dropped after it).
locations: dict[tuple[str, ...], str] = {}
if len(parts) > 1:
locations[tuple(parts[:-1])] = self._namespace_location(parts[:-1])
order: list[list[str]] = []
pending = [parts]
while pending:
namespace = pending.pop()
order.append(namespace)
locations[tuple(namespace)] = self._namespace_location(namespace)
pending.extend(self.rest.list_namespaces(namespace))
for namespace in sorted(order, key=len, reverse=True):
for name in self.rest.list_views(namespace):
self.rest.drop_view(namespace, name)
for name in self.rest.list_tables(namespace):
self._drop_table(namespace, name)
for name in self.rest.list_generic(namespace):
self.rest.drop_generic(namespace, name)
self._drop_generic(namespace, name)
self.rest.drop_namespace(namespace)
self._remove_folder(
locations[tuple(namespace)],
locations.get(tuple(namespace[:-1]), ""),
what=self.path_of(namespace),
)

def _namespace_location(self, namespace: Sequence[str]) -> str:
return str(self.rest.namespace_properties(list(namespace)).get("location") or "")

# -- wiki ------------------------------------------------------------------------

Expand Down Expand Up @@ -658,26 +709,67 @@ def iceberg_select_from(self, source: str) -> str:
return f"SELECT {', '.join(select)} FROM {source}"

def _drop(self, namespace: list[str], name: str, kind: EntryType) -> None:
"""Drop `name` in `namespace`, which is a `kind`: a table with its data
files, a view, or a read-only Parquet table's registration (its files stay)."""
"""Drop `name` in `namespace`, which is a `kind`, purged: a table or a read-only
Parquet table with its folder of files, or a view."""
if kind == "table":
self._drop_table(namespace, name)
elif kind == "view":
self.rest.drop_view(namespace, name)
else:
self.rest.drop_generic(namespace, name)
self._drop_generic(namespace, name)

def _drop_generic(self, namespace: list[str], name: str) -> None:
"""Drop a generic table: a read-only Parquet table goes with its folder of
files (see `_purge`); a registered database has none."""
entry = self.rest.load_generic(namespace, name)
self.rest.drop_generic(namespace, name)
if entry.get("format") == PARQUET_FORMAT:
self._purge(namespace, name, str(entry.get("base-location") or ""))

def _drop_table(self, namespace: list[str], name: str) -> None:
"""Drop an Iceberg table with its data files (purge). A caller Polaris doesn't
allow to purge (``DROP_TABLE_WITH_PURGE`` — e.g. a principal with
catalog_admin only) gets the table dropped from the catalog instead; its data
files then stay in the bucket."""
"""Drop an Iceberg table from the catalog, then delete its folder (data and
metadata files) from the object store.

Polaris is asked to purge the files too, but that is only a cleanup task it runs
later, and a caller it doesn't let purge (``DROP_TABLE_WITH_PURGE`` — e.g. a
principal with catalog_admin only) gets a plain drop that leaves them all. So
the folder is removed here either way, with the caller's own object-store keys —
only when it lies inside the namespace's own folder, so a table registered on
some shared location never takes other files with it."""
location = str(self.rest.load_table(namespace, name).get("location") or "")
try:
self.rest.drop_table(namespace, name)
except CatalogAuthError as exc:
if "PURGE" not in str(exc).upper():
raise
self.rest.drop_table(namespace, name, purge=False)
self._purge(namespace, name, location)

def _purge(self, namespace: list[str], name: str, location: str) -> None:
"""Delete the folder `location` of the dropped `name` from the object store,
when it lies strictly inside `namespace`'s own folder."""
base = str(self.rest.namespace_properties(namespace).get("location") or "")
self._remove_folder(location, base, what=self.path_of([*namespace, name]))

def _remove_folder(self, folder: str, parent: str, *, what: str) -> None:
"""Delete `folder` with everything in it, but only when it is strictly inside
`parent` (so never a bucket, the catalog's root or someone else's location);
`what` (just dropped from the catalog) names it in the error."""
folder, parent = folder.rstrip("/"), parent.rstrip("/")
if not folder or not parent or not folder.startswith(f"{parent}/"):
return
try:
self._object_store().remove_folder(f"{folder}/")
except (CatalogAuthError, CatalogOperationError) as exc:
raise CatalogOperationError(
f"{what!r} was dropped from the catalog, but its files in {folder}/ could "
f"not be deleted: {exc}"
) from exc

def _object_store(self) -> ObjectStore:
if self._store is None:
self._store = ObjectStore(self._settings, s3_credentials(self._settings))
return self._store

def _prepare_target(
self,
Expand Down
20 changes: 20 additions & 0 deletions src/eea_datalakehouse/catalog/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
from dataclasses import dataclass, field
from typing import Any

import pandas as pd

from . import operations
from .backend import CatalogBackend
from .dremio_publish import PUBLIC_ROOT
Expand Down Expand Up @@ -1355,6 +1357,24 @@ def list(self, path: str = "") -> CatalogListing:
self._catalog.list_dataset_kinds(path)
)

def search(self, query: str, *, kind: str | None = None, limit: int = 50) -> pd.DataFrame:
"""Find tables, views, folders, databases and Parquet tables by their names, tags,
display names, descriptions, columns and wiki pages: one row per hit, best first,
as far as you may read them. Answered immediately — not queued.

`query`: words (each matching by prefix, all of them somewhere), ``"exact phrase"``,
``#tag`` (exactly that tag), ``in:path`` (under that path), ``kind:table`` (view,
namespace, database, parquet) and ``col:name`` (a column). `kind` and `limit`
narrow it further. Columns: ``path`` (full, to pass on to other calls), ``kind``,
``display_name``, ``description``, ``tags``, ``matched`` (``tag``, ``column`` or
``wiki`` when not by its name) with its ``snippet``, and ``restricted`` (a folder
you may see exists but not open). Polaris only."""
hits = self._catalog.search(query, kind=kind, limit=limit)
return pd.DataFrame(hits, columns=[
"path", "kind", "display_name", "description", "tags", "matched", "snippet",
"restricted",
])

def schema(self, path: str) -> TableInfo:
"""The column schema and row count of `path` (see
`gettableitemsfrom`) — never fetches the actual rows. Answered
Expand Down
8 changes: 8 additions & 0 deletions src/eea_datalakehouse/notebook/magics.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,14 @@
"CatalogSessionError if none is set. Raises CatalogOperationError if path "
"doesn't exist.",
),
(
"search",
"Find tables, views, folders, databases and Parquet tables by name, tags, display "
"name, description, columns and wiki: a DataFrame, best first, with what matched. "
'query: words (by prefix, all must match), "exact phrase", #tag, in:path, '
"kind:table|view|namespace|database|parquet, col:name; kind= and limit= (50) too. "
"Only what you may read. Polaris only (the Document Service's index, DDS_BASE_URL).",
),
(
"schema",
"Show path's column schema and row count (never fetches the actual rows). path "
Expand Down
Loading