Skip to content
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

Remove cached responses older than 4 mins #318

Merged
merged 10 commits into from
Jan 22, 2024
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ httpx
structlog
sentry-sdk
slowapi
pathy==0.10.3
29 changes: 29 additions & 0 deletions src/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,33 @@

CACHE_TIME_SECONDS = 120
cache_time_seconds = int(os.getenv("CACHE_TIME_SECONDS", CACHE_TIME_SECONDS))
DELETE_CACHE_TIME_SECONDS = 240
delete_cache_time_seconds = int(os.getenv("DELETE_CACHE_TIME_SECONDS", DELETE_CACHE_TIME_SECONDS))


def remove_old_cache(
last_updated: dict, response: dict, remove_cache_time_seconds: float = delete_cache_time_seconds
):
"""
Remove old cache entries from the cache

:param last_updated: dict of last updated times
:param response: dict of responses, same keys as last_updated
:param remove_cache_time_seconds: the amount of time, after which the cache should be removed
"""
now = datetime.now(tz=timezone.utc)
logger.info("Removing old cache entries")
keys_to_remove = []
for key, value in last_updated.items():
if now - timedelta(seconds=remove_cache_time_seconds) > value:
logger.debug(f"Removing {key} from cache, ({value})")
keys_to_remove.append(key)

for key in keys_to_remove:
last_updated.pop(key)
response.pop(key)

return last_updated, response


def cache_response(func):
Expand Down Expand Up @@ -52,6 +79,8 @@ def wrapper(*args, **kwargs): # noqa
if var in route_variables:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just checking as you mentioned this briefly @peterdudfield, is there anything else you can see in this dict that could be removed to make the keys more reusable/less long? Other than ["session", "user", "request"]

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, there might be, I'll put them in a different issue as we might be able to get rid of some

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

route_variables.pop(var)

last_updated, response = remove_old_cache(last_updated, response)

# make route_variables into a string
route_variables = json.dumps(route_variables)

Expand Down
Loading