|
| 1 | +"""A module for managing queryable attributes.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import os |
| 5 | +import time |
| 6 | +from typing import Any, Dict, List, Optional, Set |
| 7 | + |
| 8 | +from fastapi import HTTPException |
| 9 | + |
| 10 | +from stac_fastapi.core.base_database_logic import BaseDatabaseLogic |
| 11 | + |
| 12 | + |
| 13 | +class QueryablesCache: |
| 14 | + """A thread-safe, time-based cache for queryable properties.""" |
| 15 | + |
| 16 | + def __init__(self, database_logic: Any): |
| 17 | + """ |
| 18 | + Initialize the QueryablesCache. |
| 19 | +
|
| 20 | + Args: |
| 21 | + database_logic: An instance of a class with a `get_queryables_mapping` method. |
| 22 | + """ |
| 23 | + self._db_logic = database_logic |
| 24 | + self._cache: Dict[str, List[str]] = {} |
| 25 | + self._all_queryables: Set[str] = set() |
| 26 | + self._last_updated: float = 0 |
| 27 | + self._lock = asyncio.Lock() |
| 28 | + self.validation_enabled: bool = False |
| 29 | + self.cache_ttl: int = 3600 # How often to refresh cache (in seconds) |
| 30 | + self.reload_settings() |
| 31 | + |
| 32 | + def reload_settings(self): |
| 33 | + """Reload settings from environment variables.""" |
| 34 | + self.validation_enabled = ( |
| 35 | + os.getenv("VALIDATE_QUERYABLES", "false").lower() == "true" |
| 36 | + ) |
| 37 | + self.cache_ttl = int(os.getenv("QUERYABLES_CACHE_TTL", "3600")) |
| 38 | + |
| 39 | + async def _update_cache(self): |
| 40 | + """Update the cache with the latest queryables from the database.""" |
| 41 | + if not self.validation_enabled: |
| 42 | + return |
| 43 | + |
| 44 | + async with self._lock: |
| 45 | + if (time.time() - self._last_updated < self.cache_ttl) and self._cache: |
| 46 | + return |
| 47 | + |
| 48 | + queryables_mapping = await self._db_logic.get_queryables_mapping() |
| 49 | + all_queryables_set = set(queryables_mapping.keys()) |
| 50 | + |
| 51 | + self._all_queryables = all_queryables_set |
| 52 | + |
| 53 | + self._cache = {"*": list(all_queryables_set)} |
| 54 | + self._last_updated = time.time() |
| 55 | + |
| 56 | + async def get_all_queryables(self) -> Set[str]: |
| 57 | + """ |
| 58 | + Return a set of all queryable attributes across all collections. |
| 59 | +
|
| 60 | + This method will update the cache if it's stale or has been cleared. |
| 61 | + """ |
| 62 | + if not self.validation_enabled: |
| 63 | + return set() |
| 64 | + |
| 65 | + if (time.time() - self._last_updated >= self.cache_ttl) or not self._cache: |
| 66 | + await self._update_cache() |
| 67 | + return self._all_queryables |
| 68 | + |
| 69 | + async def validate(self, fields: Set[str]) -> None: |
| 70 | + """ |
| 71 | + Validate if the provided fields are queryable. |
| 72 | +
|
| 73 | + Raises HTTPException if invalid fields are found. |
| 74 | + """ |
| 75 | + if not self.validation_enabled: |
| 76 | + return |
| 77 | + |
| 78 | + allowed_fields = await self.get_all_queryables() |
| 79 | + invalid_fields = fields - allowed_fields |
| 80 | + if invalid_fields: |
| 81 | + raise HTTPException( |
| 82 | + status_code=400, |
| 83 | + detail=f"Invalid query fields: {', '.join(invalid_fields)}. Allowed fields are: {', '.join(allowed_fields)}", |
| 84 | + ) |
| 85 | + |
| 86 | + |
| 87 | +_queryables_cache_instance: Optional[QueryablesCache] = None |
| 88 | + |
| 89 | + |
| 90 | +def initialize_queryables_cache(database_logic: BaseDatabaseLogic): |
| 91 | + """ |
| 92 | + Initialize the global queryables cache. |
| 93 | +
|
| 94 | + :param database_logic: An instance of DatabaseLogic. |
| 95 | + """ |
| 96 | + global _queryables_cache_instance |
| 97 | + if _queryables_cache_instance is None: |
| 98 | + _queryables_cache_instance = QueryablesCache(database_logic) |
| 99 | + |
| 100 | + |
| 101 | +async def all_queryables() -> Set[str]: |
| 102 | + """Get all queryable properties from the cache.""" |
| 103 | + if _queryables_cache_instance is None: |
| 104 | + raise Exception("Queryables cache not initialized.") |
| 105 | + return await _queryables_cache_instance.get_all_queryables() |
| 106 | + |
| 107 | + |
| 108 | +async def validate_queryables(fields: Set[str]) -> None: |
| 109 | + """Validate if the provided fields are queryable.""" |
| 110 | + if _queryables_cache_instance is None: |
| 111 | + return |
| 112 | + await _queryables_cache_instance.validate(fields) |
| 113 | + |
| 114 | + |
| 115 | +def reload_queryables_settings(): |
| 116 | + """Reload queryables settings from environment variables.""" |
| 117 | + if _queryables_cache_instance: |
| 118 | + _queryables_cache_instance.reload_settings() |
| 119 | + |
| 120 | + |
| 121 | +def get_properties_from_cql2_filter(cql2_filter: Dict[str, Any]) -> Set[str]: |
| 122 | + """Recursively extract property names from a CQL2 filter.""" |
| 123 | + props: Set[str] = set() |
| 124 | + if "op" in cql2_filter and "args" in cql2_filter: |
| 125 | + for arg in cql2_filter["args"]: |
| 126 | + if isinstance(arg, dict): |
| 127 | + if "op" in arg: |
| 128 | + props.update(get_properties_from_cql2_filter(arg)) |
| 129 | + elif "property" in arg: |
| 130 | + props.add(arg["property"]) |
| 131 | + return props |
0 commit comments