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
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ server = [
"uvicorn[standard]==0.38.0"
]
catalogs = [
"stac-fastapi-catalogs-extension>=1.0.0,<2.0",
"stac-fastapi-catalogs-extension>=1.1.0,<2.0",
]
metrics = [
"stac-fastapi-api[metrics]",
Expand All @@ -76,7 +76,7 @@ dev = [
# tests only: ships the migrations to install every pgstac in the test matrix
"pypgstac>=0.10,<0.11",
"requests",
"stac-fastapi-catalogs-extension>=1.0.0,<2.0",
"stac-fastapi-catalogs-extension>=1.1.0,<2.0",
"stac-fastapi-api[metrics]",
"httpx",
"psycopg[pool,binary]==3.2.*",
Expand Down
16 changes: 16 additions & 0 deletions stac_fastapi/pgstac/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ async def all_collections( # type: ignore [override] # noqa: C901
# When CollectionSearchExtension is disabled, use a high limit to return all collections
clean_args = {"limit": limit or 10000, "offset": offset or 0}

reject_collection_parent_ids_sort(clean_args)

# Add filter to ensure only Collections are returned (not Catalogs)
# This is needed because catalogs are also stored in the collections table
# pgstac rejects a `query` + `filter` payload, so the type constraint is
Expand Down Expand Up @@ -726,13 +728,27 @@ def join_free_text_query(args: dict[str, Any]) -> None:
args["q"] = " OR ".join(q) if isinstance(q, list) else q


def reject_collection_parent_ids_sort(clean_args: dict[str, Any]) -> None:
"""Reject `parent_ids` as a collection sort field.

`parent_ids` is pgstac-internal catalog metadata, not a collection
sortable, but pgstac accepts it silently.
"""
for sort in clean_args.get("sortby") or []:
if sort.get("field") == "parent_ids":
raise InvalidQueryParameter(
"Sorting collections by 'parent_ids' is not supported."
)


def clean_collection_search_args(
base_args: dict[str, Any],
**kwargs: Any,
) -> dict[str, Any]:
"""Clean up collection search arguments to match `collection_search()`"""
clean = clean_search_args(base_args, **kwargs)
join_free_text_query(clean)
reject_collection_parent_ids_sort(clean)
return clean


Expand Down
51 changes: 31 additions & 20 deletions stac_fastapi/pgstac/extensions/catalogs/catalogs_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from stac_fastapi.types.stac import ItemCollection
from stac_fastapi_catalogs_extension import (
CATALOGS_CORE_CONFORMANCE,
CATALOGS_TRANSACTION_CONFORMANCE,
)
from stac_fastapi_catalogs_extension.client import AsyncBaseCatalogsClient
from stac_fastapi_catalogs_extension.types import Children
Expand Down Expand Up @@ -64,6 +63,7 @@ class CatalogsClient(AsyncBaseCatalogsClient):
"""

database: CatalogsDatabaseLogic = attr.ib()
scoped_conformance_classes: list[str] = attr.ib(factory=list, kw_only=True)

@staticmethod
async def _add_catalog_links(
Expand Down Expand Up @@ -441,12 +441,6 @@ def _generate_base_collection_links(
"title": "Queryables",
"href": base_url + f"/collections/{collection_id}/queryables",
},
{
"rel": "http://www.opengis.net/def/rel/ogc/1.0/sortables",
"type": "application/schema+json",
"title": "Sortables",
"href": base_url + f"/collections/{collection_id}/sortables",
},
]

@staticmethod
Expand Down Expand Up @@ -518,6 +512,8 @@ async def get_catalog_collections(
limit: int | None = None,
token: str | None = None,
request: Request | None = None,
bbox: list[float] | None = None,
datetime: str | None = None,
fields: list[str] | None = None,
sortby: list[str] | None = None,
q: list[str] | None = None,
Expand All @@ -535,6 +531,8 @@ async def get_catalog_collections(
limit: The maximum number of collections to return.
token: The pagination token.
request: The FastAPI request object.
bbox: Bounding box matching the collection spatial extents.
datetime: Datetime matching the collection temporal extents.
fields: Fields extension include/exclude list.
sortby: Sort extension fields, prefixed with `+` or `-`.
q: Free text search terms.
Expand All @@ -548,7 +546,8 @@ async def get_catalog_collections(
limit, token = CatalogsClient._extract_limit_and_token(limit, token, request)

search = clean_collection_search_args(
base_args={},
base_args={"bbox": bbox},
datetime=datetime,
fields=fields,
sortby=sortby,
q=q,
Expand Down Expand Up @@ -902,6 +901,8 @@ async def get_catalog_collection_items(
limit: int | None = None,
token: str | None = None,
request: Request | None = None,
bbox: list[float] | None = None,
datetime: str | None = None,
**kwargs,
) -> ItemCollection:
"""Get items from a collection in a catalog.
Expand All @@ -914,6 +915,8 @@ async def get_catalog_collection_items(
limit: The maximum number of items to return.
token: The pagination token.
request: The FastAPI request object.
bbox: Bounding box to filter items.
datetime: Datetime to filter items.
**kwargs: Additional keyword arguments.

Returns:
Expand Down Expand Up @@ -945,8 +948,13 @@ async def get_catalog_collection_items(
"limit": limit,
}

if token:
search_query["token"] = token
for key, value in (
("token", token),
("bbox", bbox),
("datetime", datetime),
):
if value:
search_query[key] = value

# Execute search and get full item collection with links
async with request.app.state.get_connection(request, "r") as conn:
Expand Down Expand Up @@ -1099,16 +1107,21 @@ async def get_catalog_children(

async def get_catalog_conformance(
self, catalog_id: str, request: Request | None = None, **kwargs
) -> JSONResponse:
) -> dict[str, Any]:
"""Get conformance classes for a catalog.

Returns a dict rather than a Response so the extension merges in the
conformance classes registered on `app.state.catalogs_conformance_classes`
(core, marker, and transaction classes when the transaction extension is
registered).

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

Returns:
JSONResponse containing conformance classes.
Dictionary containing conformance classes.

Raises:
NotFoundError: If the catalog does not exist.
Expand All @@ -1117,14 +1130,12 @@ async def get_catalog_conformance(
if request:
await self.database.find_catalog(catalog_id, request=request)

return JSONResponse(
content={
"conformsTo": [
*CATALOGS_CORE_CONFORMANCE,
*CATALOGS_TRANSACTION_CONFORMANCE,
]
}
)
return {
"conformsTo": [
*CATALOGS_CORE_CONFORMANCE,
*self.scoped_conformance_classes,
]
}

async def get_catalog_queryables(
self, catalog_id: str, request: Request | None = None, **kwargs
Expand Down
12 changes: 10 additions & 2 deletions stac_fastapi/pgstac/extensions/catalogs/catalogs_database_logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,8 @@ async def get_catalog_collections(
request: The FastAPI request object.
sort: Sort order. Takes precedence over `search["sortby"]`.
search: Collection search parameters in `collection_search()` form.
Only `filter` (CQL2-JSON), `fields`, `sortby`, `q` and `filter_lang` are used.
Only `filter` (CQL2-JSON), `bbox`, `datetime`, `fields`, `sortby`, `q`
and `filter_lang` are used.
`filter` is ANDed onto the catalog scoping clauses, so it can only narrow the result.

Returns:
Expand Down Expand Up @@ -448,7 +449,14 @@ async def get_catalog_collections(
# ANDed onto the scoping so it can't return Catalogs or another catalog's collections
if search.get("filter") is not None:
filter_args.append(search["filter"])
for key in ("fields", "sortby", "q", "filter_lang"):
for key in (
"bbox",
"datetime",
"fields",
"sortby",
"q",
"filter_lang",
):
if key in search:
search_query[key] = search[key]

Expand Down
48 changes: 48 additions & 0 deletions stac_fastapi/pgstac/extensions/catalogs/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Request types for the catalogs extension."""

from typing import Annotated

import attr
from fastapi import Query
from stac_fastapi.types.search import (
DateTimeQueryType,
_bbox_converter,
_validate_datetime,
)
from stac_fastapi_catalogs_extension.types import (
CatalogCollectionItemsRequest,
CatalogCollectionsRequest,
)
from stac_pydantic.shared import BBox


@attr.s
class PgstacCatalogCollectionsRequest(CatalogCollectionsRequest):
"""Request model for `GET /catalogs/{catalog_id}/collections`.

Adds the Collection Search `bbox` and `datetime` parameters on top of the
library's pagination primitives so the scoped listing can claim the
`multi-tenant-catalogs#collection-search` marker, which requires the
Collection Search Basics.
"""

bbox: Annotated[
BBox | None,
Query(description="Bounding box to filter collections [minx, miny, maxx, maxy]"),
] = attr.ib(
default=None,
converter=lambda x: _bbox_converter(x) if x is not None else None,
)
datetime: DateTimeQueryType = attr.ib(default=None, validator=_validate_datetime)


@attr.s
class PgstacCatalogCollectionItemsRequest(CatalogCollectionItemsRequest):
"""Request model for `GET /catalogs/{catalog_id}/collections/{collection_id}/items`.

Re-declares the library's `datetime` parameter with the same RFC 3339
validator `GET /collections/{collection_id}/items` uses, so invalid values
are rejected with a 400 instead of reaching pgstac and erroring with a 500.
"""

datetime: DateTimeQueryType = attr.ib(default=None, validator=_validate_datetime)
52 changes: 49 additions & 3 deletions stac_fastapi/pgstac/models/extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
TokenPaginationExtension,
TransactionExtension,
)
from stac_fastapi.extensions.collection_search import CollectionSearchConformanceClasses
from stac_fastapi.extensions.fields import FieldsConformanceClasses
from stac_fastapi.extensions.filter import FilterConformanceClasses
from stac_fastapi.extensions.free_text import FreeTextConformanceClasses
Expand Down Expand Up @@ -86,6 +87,10 @@ def get_default_extensions_map(key: str) -> dict[str, ApiExtension]:
return extensions


CATALOGS_COLLECTION_SEARCH_MARKER = (
"https://api.stacspec.org/v1.0.0/multi-tenant-catalogs#collection-search"
)

logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -169,7 +174,7 @@ def catalog(self) -> list[ApiExtension]:
if self.settings.enable_catalogs_extension:
try:
from stac_fastapi_catalogs_extension import (
CatalogCollectionsRequest,
CATALOGS_CORE_CONFORMANCE,
CatalogsExtension,
CatalogsTransactionExtension,
)
Expand All @@ -188,6 +193,10 @@ def catalog(self) -> list[ApiExtension]:
from stac_fastapi.pgstac.extensions.catalogs.catalogs_database_logic import (
CatalogsDatabaseLogic,
)
from stac_fastapi.pgstac.extensions.catalogs.types import (
PgstacCatalogCollectionItemsRequest,
PgstacCatalogCollectionsRequest,
)

# No Query or pagination, the route pages with token/offset and has no `query`
enabled_keys = self.settings.enabled_extensions
Expand All @@ -199,22 +208,59 @@ def catalog(self) -> list[ApiExtension]:
]
catalog_collections_get_request_model = create_request_model(
model_name="CatalogCollectionsRequest",
base_model=CatalogCollectionsRequest,
base_model=PgstacCatalogCollectionsRequest,
extensions=catalog_collections_extensions,
request_type="GET",
)

# The marker binds the scoped listing to the root's Collection Search
# class. Only declare it when collection search is on: the
# v1.0.0/collection-search base in the library's
# CATALOGS_COLLECTION_SEARCH_CONFORMANCE is not used here because the
# CollectionSearchExtension already registers the v1.0.0-rc.1 base.
collection_search_enabled = (
enabled_keys is None or "collection_search" in enabled_keys
)
scoped_collection_search_classes = (
[
CATALOGS_COLLECTION_SEARCH_MARKER,
CollectionSearchConformanceClasses.COLLECTIONSEARCH.value,
CollectionSearchConformanceClasses.BASIS.value,
*(
uri
for ext in catalog_collections_extensions
for uri in ext.conformance_classes
),
]
if collection_search_enabled
else []
)

try:
catalogs_client = CatalogsClient(database=CatalogsDatabaseLogic())
catalogs_client = CatalogsClient(
database=CatalogsDatabaseLogic(),
scoped_conformance_classes=list(
dict.fromkeys(scoped_collection_search_classes)
),
)

# Register the read-only catalogs extension
catalogs_extension = CatalogsExtension(
client=catalogs_client,
settings={
"enable_response_models": self.settings.enable_response_models
},
conformance_classes=[
*CATALOGS_CORE_CONFORMANCE,
*(
[CATALOGS_COLLECTION_SEARCH_MARKER]
if collection_search_enabled
else []
),
],
hide_alternate_parents=self.settings.hide_alternate_parents,
catalog_collections_get_request_model=catalog_collections_get_request_model,
catalog_collection_items_get_request_model=PgstacCatalogCollectionItemsRequest,
)
logger.info("CatalogsExtension (read-only) enabled successfully.")

Expand Down
Loading
Loading