-
Notifications
You must be signed in to change notification settings - Fork 31
feat: Add Redis caching for navigation pagination #488
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
YuriZmytrakov
wants to merge
4
commits into
stac-utils:main
Choose a base branch
from
YuriZmytrakov:CAT-1382-2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
version: '3.8' | ||
|
||
services: | ||
redis: | ||
image: redis:7-alpine | ||
ports: | ||
- "6379:6379" | ||
volumes: | ||
- redis_test_data:/data | ||
command: redis-server --appendonly yes | ||
|
||
volumes: | ||
redis_test_data: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
[mypy] | ||
[mypy-redis.*] | ||
ignore_missing_imports = True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -24,9 +24,10 @@ | |
from stac_fastapi.core.base_settings import ApiBaseSettings | ||
from stac_fastapi.core.datetime_utils import format_datetime_range | ||
from stac_fastapi.core.models.links import PagingLinks | ||
from stac_fastapi.core.redis_utils import _handle_pagination_via_redis | ||
from stac_fastapi.core.serializers import CollectionSerializer, ItemSerializer | ||
from stac_fastapi.core.session import Session | ||
from stac_fastapi.core.utilities import filter_fields | ||
from stac_fastapi.core.utilities import filter_fields, get_bool_env | ||
from stac_fastapi.extensions.core.transaction import AsyncBaseTransactionsClient | ||
from stac_fastapi.extensions.core.transaction.request import ( | ||
PartialCollection, | ||
|
@@ -328,6 +329,8 @@ async def all_collections( | |
if parsed_sort: | ||
sort = parsed_sort | ||
|
||
redis_enable = get_bool_env("REDIS_ENABLE", default=False) | ||
|
||
# Convert q to a list if it's a string | ||
q_list = None | ||
if q is not None: | ||
|
@@ -426,6 +429,8 @@ async def all_collections( | |
}, | ||
] | ||
|
||
_handle_pagination_via_redis(redis_enable, next_token, token, request, links) | ||
|
||
if next_token: | ||
next_link = PagingLinks(next=next_token, request=request).link_next() | ||
links.append(next_link) | ||
|
@@ -744,6 +749,7 @@ async def post_search( | |
HTTPException: If there is an error with the cql2_json filter. | ||
""" | ||
base_url = str(request.base_url) | ||
redis_enable = get_bool_env("REDIS_ENABLE", default=False) | ||
|
||
search = self.database.make_search() | ||
|
||
|
@@ -850,6 +856,29 @@ async def post_search( | |
] | ||
links = await PagingLinks(request=request, next=next_token).get_links() | ||
|
||
collection_links = [] | ||
if search_request.collections: | ||
for collection_id in search_request.collections: | ||
collection_links.extend( | ||
[ | ||
{ | ||
"rel": "collection", | ||
"type": "application/json", | ||
"href": urljoin(base_url, f"collections/{collection_id}"), | ||
}, | ||
{ | ||
"rel": "parent", | ||
"type": "application/json", | ||
"href": urljoin(base_url, f"collections/{collection_id}"), | ||
}, | ||
] | ||
) | ||
links.extend(collection_links) | ||
|
||
_handle_pagination_via_redis( | ||
redis_enable, next_token, token_param, request, links | ||
) | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can this code - the redis_enabled block - be put into a function? It is used with all_collections too |
||
return stac_types.ItemCollection( | ||
type="FeatureCollection", | ||
features=items, | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
"""Utilities for connecting to and managing Redis connections.""" | ||
|
||
import logging | ||
from typing import Dict, List, Optional | ||
|
||
from fastapi import Request | ||
from pydantic_settings import BaseSettings | ||
from redis import asyncio as aioredis | ||
from redis.asyncio.sentinel import Sentinel | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
redis_pool: Optional[aioredis.Redis] = None | ||
|
||
|
||
class RedisSentinelSettings(BaseSettings): | ||
"""Configuration for connecting to Redis Sentinel.""" | ||
|
||
REDIS_SENTINEL_HOSTS: str = "" | ||
REDIS_SENTINEL_PORTS: str = "26379" | ||
REDIS_SENTINEL_MASTER_NAME: str = "master" | ||
REDIS_DB: int = 15 | ||
|
||
REDIS_MAX_CONNECTIONS: int = 10 | ||
REDIS_RETRY_TIMEOUT: bool = True | ||
REDIS_DECODE_RESPONSES: bool = True | ||
REDIS_CLIENT_NAME: str = "stac-fastapi-app" | ||
REDIS_HEALTH_CHECK_INTERVAL: int = 30 | ||
|
||
|
||
class RedisSettings(BaseSettings): | ||
"""Configuration for connecting Redis Sentinel.""" | ||
|
||
REDIS_HOST: str = "" | ||
REDIS_PORT: int = 6379 | ||
REDIS_DB: int = 0 | ||
|
||
REDIS_MAX_CONNECTIONS: int = 10 | ||
REDIS_RETRY_TIMEOUT: bool = True | ||
REDIS_DECODE_RESPONSES: bool = True | ||
REDIS_CLIENT_NAME: str = "stac-fastapi-app" | ||
REDIS_HEALTH_CHECK_INTERVAL: int = 30 | ||
|
||
|
||
# Select the Redis or Redis Sentinel configuration | ||
redis_settings: BaseSettings = RedisSettings() | ||
|
||
|
||
async def connect_redis(settings: Optional[RedisSettings] = None) -> aioredis.Redis: | ||
"""Return a Redis connection.""" | ||
global redis_pool | ||
settings = settings or redis_settings | ||
|
||
if not settings.REDIS_HOST or not settings.REDIS_PORT: | ||
return None | ||
|
||
if redis_pool is None: | ||
pool = aioredis.ConnectionPool( | ||
host=settings.REDIS_HOST, | ||
port=settings.REDIS_PORT, | ||
db=settings.REDIS_DB, | ||
max_connections=settings.REDIS_MAX_CONNECTIONS, | ||
decode_responses=settings.REDIS_DECODE_RESPONSES, | ||
retry_on_timeout=settings.REDIS_RETRY_TIMEOUT, | ||
health_check_interval=settings.REDIS_HEALTH_CHECK_INTERVAL, | ||
) | ||
redis_pool = aioredis.Redis( | ||
connection_pool=pool, client_name=settings.REDIS_CLIENT_NAME | ||
) | ||
return redis_pool | ||
|
||
|
||
async def connect_redis_sentinel( | ||
settings: Optional[RedisSentinelSettings] = None, | ||
) -> Optional[aioredis.Redis]: | ||
"""Return a Redis Sentinel connection.""" | ||
global redis_pool | ||
|
||
settings = settings or redis_settings | ||
|
||
if ( | ||
not settings.REDIS_SENTINEL_HOSTS | ||
or not settings.REDIS_SENTINEL_PORTS | ||
or not settings.REDIS_SENTINEL_MASTER_NAME | ||
): | ||
return None | ||
|
||
hosts = [h.strip() for h in settings.REDIS_SENTINEL_HOSTS.split(",") if h.strip()] | ||
ports = [ | ||
int(p.strip()) for p in settings.REDIS_SENTINEL_PORTS.split(",") if p.strip() | ||
] | ||
|
||
if redis_pool is None: | ||
try: | ||
sentinel = Sentinel( | ||
[(h, p) for h, p in zip(hosts, ports)], | ||
decode_responses=settings.REDIS_DECODE_RESPONSES, | ||
) | ||
master = sentinel.master_for( | ||
service_name=settings.REDIS_SENTINEL_MASTER_NAME, | ||
db=settings.REDIS_DB, | ||
decode_responses=settings.REDIS_DECODE_RESPONSES, | ||
retry_on_timeout=settings.REDIS_RETRY_TIMEOUT, | ||
client_name=settings.REDIS_CLIENT_NAME, | ||
max_connections=settings.REDIS_MAX_CONNECTIONS, | ||
health_check_interval=settings.REDIS_HEALTH_CHECK_INTERVAL, | ||
) | ||
redis_pool = master | ||
|
||
except Exception: | ||
return None | ||
|
||
return redis_pool | ||
|
||
|
||
async def save_self_link( | ||
redis: aioredis.Redis, token: Optional[str], self_href: str | ||
) -> None: | ||
"""Save the self link for the current token with 30 min TTL.""" | ||
if token: | ||
await redis.setex(f"nav:self:{token}", 1800, self_href) | ||
|
||
|
||
async def get_prev_link(redis: aioredis.Redis, token: Optional[str]) -> Optional[str]: | ||
"""Get the previous page link for the current token (if exists).""" | ||
if not token: | ||
return None | ||
return await redis.get(f"nav:self:{token}") | ||
|
||
|
||
async def _handle_pagination_via_redis( | ||
redis_enable: bool, | ||
next_token: Optional[str], | ||
token_param: Optional[str], | ||
request: Request, | ||
links: List[Dict], | ||
) -> None: | ||
"""Handle Redis connection and operations for pagination links.""" | ||
if not redis_enable: | ||
return | ||
|
||
redis = None | ||
try: | ||
redis = await connect_redis() | ||
logger.info("Redis connection established successfully") | ||
|
||
if redis and next_token: | ||
self_link = str(request.url) | ||
await save_self_link(redis, next_token, self_link) | ||
|
||
prev_link = await get_prev_link(redis, token_param) | ||
if prev_link: | ||
links.insert( | ||
0, | ||
{ | ||
"rel": "prev", | ||
"type": "application/json", | ||
"method": "GET", | ||
"href": prev_link, | ||
}, | ||
) | ||
except Exception as e: | ||
logger.warning(f"Redis connection failed, continuing without Redis: {e}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this code into a function