Skip to content
Open
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ To prevent information leakage about other tenants in multi-tenant deployments,

**Note:** The link relation names for poly-hierarchy navigation are subject to change as the OGC and STAC communities continue to standardize on terminology. These names may be updated in future releases to align with emerging standards.

#### Catalog-Scoped Item Search

When the catalogs extension is enabled, `GET` and `POST /catalogs/{catalog_id}/search` perform a STAC item search bounded to the catalog's descendant tree (sub-catalogs included recursively, across poly-hierarchies). The endpoints accept the same parameters as `/search`, so enabled search extensions (filter, sort, fields, free text, pagination) apply to scoped searches as well. A `collections` filter is intersected with the catalog's scope: results never include items outside the catalog, and a request that resolves to no in-scope collections returns an empty `ItemCollection`.

### Migrations

There is a Python utility as part of PgSTAC ([pypgstac](https://stac-utils.github.io/pgstac/pypgstac/)) that includes a migration utility.
Expand Down
13 changes: 12 additions & 1 deletion stac_fastapi/pgstac/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,22 @@ def instantiate_api(

transaction_extensions = extensions.transaction

# Build the core client up front: the catalog-scoped search extension
# delegates item searches to it.
core_client = client(pgstac_search_model=post_request_model) # type: ignore [arg-type]

# Evaluated before `extensions.catalog` so the shared catalogs client is
# constructed with `core_client` injected.
catalog_search_extensions = extensions.catalog_search(
core_client, get_request_model, post_request_model
)

application_extensions = [
*extensions.search,
*extensions.item_collection,
*transaction_extensions,
*extensions.catalog,
*catalog_search_extensions,
*extensions.extra,
]
if collection_search_extension is not None:
Expand Down Expand Up @@ -113,7 +124,7 @@ async def default_lifespan(app: FastAPI):
router=APIRouter(prefix=settings.prefix_path),
settings=settings,
extensions=application_extensions,
client=client(pgstac_search_model=post_request_model), # type: ignore [arg-type]
client=core_client,
response_class=JSONResponse,
items_get_request_model=items_get_request_model,
search_get_request_model=get_request_model,
Expand Down
206 changes: 202 additions & 4 deletions stac_fastapi/pgstac/extensions/catalogs/catalogs_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,24 @@
from fastapi import HTTPException
from stac_fastapi.types.errors import NotFoundError
from stac_fastapi.types.requests import get_base_url
from stac_fastapi.types.search import BaseSearchPostRequest
from stac_fastapi.types.stac import ItemCollection
from stac_fastapi_catalogs_extension import (
CATALOGS_CORE_CONFORMANCE,
)
from stac_fastapi_catalogs_extension.client import AsyncBaseCatalogsClient
from stac_fastapi_catalogs_extension.client import (
AsyncBaseCatalogsClient,
AsyncCatalogsSearchClient,
)
from stac_fastapi_catalogs_extension.types import Children
from stac_pydantic.shared import BBox
from starlette.requests import Request
from starlette.responses import JSONResponse

from stac_fastapi.pgstac.core import clean_collection_search_args
from stac_fastapi.pgstac.core import (
CoreCrudClient,
clean_collection_search_args,
)
from stac_fastapi.pgstac.extensions.catalogs.catalogs_database_logic import (
CatalogsDatabaseLogic,
_parse_pagination_token,
Expand All @@ -33,8 +41,10 @@
CollectionSearchPagingLinks,
ItemCollectionLinks,
PagingLinks,
SearchLinks,
filter_links,
)
from stac_fastapi.pgstac.types.search import PgstacSearch


def _remove_null_titles(obj: Any) -> Any:
Expand All @@ -55,15 +65,18 @@ def _remove_null_titles(obj: Any) -> Any:


@attr.s
class CatalogsClient(AsyncBaseCatalogsClient):
class CatalogsClient(AsyncBaseCatalogsClient, AsyncCatalogsSearchClient):
"""Catalogs client implementation for pgstac.

This client implements the AsyncBaseCatalogsClient interface and delegates
to the database layer for all catalog operations.
to the database layer for all catalog operations. It also implements
AsyncCatalogsSearchClient when a `core_client` is supplied, enabling the
catalog-scoped item search routes.
"""

database: CatalogsDatabaseLogic = attr.ib()
scoped_conformance_classes: list[str] = attr.ib(factory=list, kw_only=True)
core_client: CoreCrudClient | None = attr.ib(default=None, kw_only=True)

@staticmethod
async def _add_catalog_links(
Expand Down Expand Up @@ -1182,3 +1195,188 @@ async def unlink_sub_catalog(
sub_catalog_id=sub_catalog_id,
request=request,
)

async def get_all_descendant_collections(
self, catalog_id: str, request: Request | None = None, **kwargs
) -> list[str]:
"""Return all collection ids in a catalog's descendant tree.

Args:
catalog_id: The ID of the catalog to traverse.
request: The FastAPI request object.
**kwargs: Additional keyword arguments.

Returns:
List of all descendant collection IDs.

Raises:
NotFoundError: If the catalog does not exist.
"""
return await self.database.get_all_descendant_collection_ids(
catalog_id, request=request
)

async def _bounded_collections(
self,
catalog_id: str,
requested: list[str] | None,
request: Request | None,
) -> list[str]:
"""Intersect requested collections with the catalog's descendants.

Args:
catalog_id: The ID of the catalog bounding the search.
requested: Collection IDs the caller asked for, or None/empty to
mean the catalog's full scope (matching /search semantics).
request: The FastAPI request object.

Returns:
The collection IDs to search within the catalog's scope. An empty
list means the request can match nothing inside this catalog.

Raises:
NotFoundError: If the catalog does not exist.
"""
allowed = await self.get_all_descendant_collections(catalog_id, request=request)
if not requested:
return allowed
return list(set(requested) & set(allowed))

async def _empty_scoped_result(self, request: Request | None) -> ItemCollection:
"""Return an empty ItemCollection for a search scoped to nothing."""
links: list[dict[str, Any]] = []
if request is not None:
search_links = SearchLinks(request=request)
links = await search_links.get_links()
for link in links:
if link.get("rel") == "self":
link["href"] = search_links.url
return ItemCollection(type="FeatureCollection", features=[], links=links)

@staticmethod
def _scoped_self_link(
result: ItemCollection | JSONResponse, request: Request | None
) -> ItemCollection | JSONResponse:
"""Rewrite the `self` link to the scoped search URL.

The delegated core search builds its self link against the global
`/search` route; scoped results should point at the route that
produced them.
"""
if request is None:
return result
self_url = SearchLinks(request=request).url
if isinstance(result, JSONResponse):
payload = json.loads(bytes(result.body))
for link in payload.get("links", []):
if link.get("rel") == "self":
link["href"] = self_url
return JSONResponse(payload)
for link in result.get("links", []):
if link.get("rel") == "self":
link["href"] = self_url
return result

async def catalog_search_get(
self,
catalog_id: str,
collections: list[str] | None = None,
ids: list[str] | None = None,
bbox: BBox | None = None,
intersects: str | None = None,
datetime: str | None = None,
limit: int | None = None,
token: str | None = None,
request: Request | None = None,
**kwargs,
) -> ItemCollection | JSONResponse:
"""Search items within a catalog and its descendants (GET).

Args:
catalog_id: The ID of the catalog to search within.
collections: List of collection IDs to search within.
ids: List of item IDs to search for.
bbox: Bounding box to search within.
intersects: GeoJSON geometry to search within.
datetime: Datetime range to search within.
limit: Maximum number of results to return.
token: Pagination token.
request: The FastAPI request object.
**kwargs: Search extension parameters (filter, sortby, fields, ...).

Returns:
ItemCollection with matching items. When the `collections` filter
resolves to nothing inside the catalog's scope, the result is an
empty ItemCollection rather than an error.

Raises:
NotFoundError: If the catalog does not exist.
HTTPException: 500 if the client has no core_client configured.
"""
if self.core_client is None:
raise HTTPException(
status_code=500,
detail="Catalog search is not configured (missing core_client).",
)
collections = await self._bounded_collections(catalog_id, collections, request)
if not collections:
# An empty scope must not reach the core client: get_search strips
# empty lists, which would turn this into an unbounded /search.
return await self._empty_scoped_result(request)
return self._scoped_self_link(
await self.core_client.get_search(
collections=collections,
ids=ids,
bbox=bbox,
intersects=intersects,
datetime=datetime,
limit=limit,
token=token,
request=cast(Request, request),
**kwargs,
),
request,
)

async def catalog_search_post(
self,
catalog_id: str,
search_request: BaseSearchPostRequest,
request: Request | None = None,
**kwargs,
) -> ItemCollection | JSONResponse:
"""Search items within a catalog and its descendants (POST).

Args:
catalog_id: The ID of the catalog to search within.
search_request: The search request parameters.
request: The FastAPI request object.
**kwargs: Additional keyword arguments.

Returns:
ItemCollection with matching items. When the `collections` filter
resolves to nothing inside the catalog's scope, the result is an
empty ItemCollection rather than an error.

Raises:
NotFoundError: If the catalog does not exist.
HTTPException: 500 if the client has no core_client configured.
"""
if self.core_client is None:
raise HTTPException(
status_code=500,
detail="Catalog search is not configured (missing core_client).",
)
search_request.collections = await self._bounded_collections(
catalog_id, search_request.collections, request
)
if not search_request.collections:
return await self._empty_scoped_result(request)
return self._scoped_self_link(
await self.core_client.post_search(
search_request=cast(PgstacSearch, search_request),
request=cast(Request, request),
**kwargs,
),
request,
)
48 changes: 48 additions & 0 deletions stac_fastapi/pgstac/extensions/catalogs/catalogs_database_logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,54 @@ async def get_sub_catalogs(

return catalogs, total_count, next_link

async def get_all_descendant_collection_ids(
self,
catalog_id: str,
request: Any = None,
) -> list[str]:
"""Return the ids of every collection in a catalog's descendant tree.

Walks the catalog DAG in a single recursive query: catalogs and
collections both live in the ``collections`` table and link to their
parents via ``content->'parent_ids'``. ``UNION`` deduplicates visited
nodes, which keeps poly-hierarchies out of the result and guarantees
termination even on cyclic graphs (writes already reject cycles).

Args:
catalog_id: The catalog ID to traverse.
request: The FastAPI request object.

Returns:
All descendant collection IDs.

Raises:
NotFoundError: If the catalog is not found.
"""
# find_catalog raises NotFoundError for a missing catalog (and for a
# missing request), so an unreachable catalog can never be mistaken
# for an empty scope.
await self.find_catalog(catalog_id, request=request)

async with request.app.state.get_connection(request, "r") as conn:
q, p = render(
"""
WITH RECURSIVE walk AS (
SELECT id, content->>'type' AS rtype
FROM collections
WHERE content->'parent_ids' ? :root
UNION
SELECT c.id, c.content->>'type' AS rtype
FROM collections c
JOIN walk w ON c.content->'parent_ids' ? w.id
)
SELECT id FROM walk WHERE rtype = 'Collection';
""",
root=catalog_id,
)
rows = await conn.fetch(q, *p)

return [row["id"] for row in rows]

async def find_collection(
self, collection_id: str, request: Any = None
) -> dict[str, Any]:
Expand Down
Loading
Loading