Skip to content

Commit

Permalink
feat: make pg usage cache timeout configurable (#4485)
Browse files Browse the repository at this point in the history
  • Loading branch information
gagantrivedi authored Aug 13, 2024
1 parent 16881a6 commit cd4fbe7
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 10 deletions.
1 change: 1 addition & 0 deletions api/app/settings/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@

USE_POSTGRES_FOR_ANALYTICS = env.bool("USE_POSTGRES_FOR_ANALYTICS", default=False)
USE_CACHE_FOR_USAGE_DATA = env.bool("USE_CACHE_FOR_USAGE_DATA", default=False)
PG_API_USAGE_CACHE_SECONDS = env.int("PG_API_USAGE_CACHE_SECONDS", default=60)

FEATURE_EVALUATION_CACHE_SECONDS = env.int(
"FEATURE_EVALUATION_CACHE_SECONDS", default=60
Expand Down
6 changes: 3 additions & 3 deletions api/app_analytics/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
from django.conf import settings
from django.utils import timezone

CACHE_FLUSH_INTERVAL = 60 # seconds


class APIUsageCache:
def __init__(self):
Expand All @@ -33,7 +31,9 @@ def track_request(self, resource: int, host: str, environment_key: str):
self._cache[key] = 1
else:
self._cache[key] += 1
if (timezone.now() - self._last_flushed_at).seconds > CACHE_FLUSH_INTERVAL:
if (
timezone.now() - self._last_flushed_at
).seconds > settings.PG_API_USAGE_CACHE_SECONDS:
self._flush()


Expand Down
15 changes: 8 additions & 7 deletions api/tests/unit/app_analytics/test_unit_app_analytics_cache.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
from app_analytics.cache import (
CACHE_FLUSH_INTERVAL,
APIUsageCache,
FeatureEvaluationCache,
)
from app_analytics.cache import APIUsageCache, FeatureEvaluationCache
from app_analytics.models import Resource
from django.utils import timezone
from freezegun import freeze_time
from pytest_django.fixtures import SettingsWrapper
from pytest_mock import MockerFixture


def test_api_usage_cache(mocker: MockerFixture) -> None:
def test_api_usage_cache(
mocker: MockerFixture,
settings: SettingsWrapper,
) -> None:
# Given
settings.PG_API_USAGE_CACHE_SECONDS = 60

cache = APIUsageCache()
now = timezone.now()
mocked_track_request_task = mocker.patch("app_analytics.cache.track_request")
Expand All @@ -30,7 +31,7 @@ def test_api_usage_cache(mocker: MockerFixture) -> None:
assert not mocked_track_request_task.called

# Now, let's move the time forward
frozen_time.tick(CACHE_FLUSH_INTERVAL + 1)
frozen_time.tick(settings.PG_API_USAGE_CACHE_SECONDS + 1)

# let's track another request(to trigger flush)
cache.track_request(
Expand Down

0 comments on commit cd4fbe7

Please sign in to comment.