1414from pccommon .config .core import PCAPIsConfig
1515from pccommon .constants import (
1616 BACKPRESSURE_KEY_PREFIX ,
17+ CACHE_KEY_ITEM ,
1718 HTTP_429_TOO_MANY_REQUESTS ,
1819 RATE_LIMIT_KEY_PREFIX ,
1920)
@@ -104,9 +105,15 @@ async def register_scripts(state: State) -> None:
104105
105106
106107async def cached_result (
107- fn : Callable [[], Coroutine [Any , Any , T ]], cache_key : str , request : Request
108+ fn : Callable [[], Coroutine [Any , Any , T ]],
109+ cache_key : str ,
110+ request : Request ,
111+ read_only : bool = False ,
108112) -> T :
109- """Either get the result from redis or run the function and cache the result."""
113+ """Either get the result from redis or run the function and cache the result.
114+
115+ If `read_only` is True, only attempt to read from the cache, do not write to it.
116+ """
110117 host = request .url .hostname
111118 host_cache_key = f"{ cache_key } :{ host } "
112119 settings = PCAPIsConfig .from_environment ()
@@ -124,7 +131,7 @@ async def cached_result(
124131 except Exception as e :
125132 # Don't fail on redis failure
126133 logger .error (
127- f"Error in cache: { e } " ,
134+ f"Error in cache read : { e } " ,
128135 extra = get_custom_dimensions ({"cache_key" : host_cache_key }, request ),
129136 )
130137 if settings .debug :
@@ -139,14 +146,19 @@ async def cached_result(
139146 {"cache_key" : host_cache_key , "duration" : f"{ te - ts :0.4f} " }, request
140147 ),
141148 )
149+ if read_only :
150+ return result
151+
142152 try :
143153 if r :
144154 await r .set (host_cache_key , orjson .dumps (result ), settings .redis_ttl )
145155 except Exception as e :
146156 # Don't fail on redis failure
147157 logger .error (
148- f"Error in cache: { e } " ,
149- extra = get_custom_dimensions ({"cache_key" : host_cache_key }, request ),
158+ f"Error in cache write: { e } " ,
159+ extra = get_custom_dimensions (
160+ {"cache_key" : host_cache_key , "cache_value_type" : type (result )}, request
161+ ),
150162 )
151163 if settings .debug :
152164 raise
@@ -321,3 +333,8 @@ async def _wrapper(*args: Any, **kwargs: Any) -> T:
321333 return _wrapper
322334
323335 return _decorator
336+
337+
338+ def stac_item_cache_key (collection : str , item : str ) -> str :
339+ """Generate a cache key for a STAC item."""
340+ return f"{ CACHE_KEY_ITEM } :{ collection } :{ item } "
0 commit comments