Self hosted FLOSS fitness/workout, nutrition and weight tracker
Don't cache routines that have a need_logs_to_advance set
Roland Geider74f4493ae8d0
diff --git a/wger/manager/models/routine.py b/wger/manager/models/routine.pyindex ba0776fe8..26fb88cfe 100644--- a/wger/manager/models/routine.py+++ b/wger/manager/models/routine.py@@ -306,7 +306,20 @@ class Routine(models.Model):current_date += datetime.timedelta(days=1)is_first = False- cache.set(cache_key, sequence, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])+ # For need_logs_to_advance days the sequence bakes in today's date (future+ # dates are optimistically advanced), so that projection is only valid for the+ # current local day. Cap the TTL to the next local midnight in that case+ # otherwise the cached calendar keeps showing a stale "today" until the next+ # mutation+ ttl = settings.WGER_SETTINGS['ROUTINE_CACHE_TTL']+ if any(day.need_logs_to_advance for day in days_list):+ now = timezone.localtime()+ next_midnight = (now + datetime.timedelta(days=1)).replace(+ hour=0, minute=0, second=0, microsecond=0+ )+ ttl = min(ttl, max(1, int((next_midnight - now).total_seconds())))++ cache.set(cache_key, sequence, ttl)return sequencedef data_for_day(self, date=None) -> WorkoutDayData | None:diff --git a/wger/manager/tests/test_routine.py b/wger/manager/tests/test_routine.pyindex 6e4acb99b..b9db0b702 100644--- a/wger/manager/tests/test_routine.py+++ b/wger/manager/tests/test_routine.py@@ -14,8 +14,10 @@# Standard Libraryimport datetime+from unittest import mock# Django+from django.conf import settingsfrom django.urls import reverse# wger@@ -486,6 +488,35 @@ class RoutineTestCase(WgerTestCase):WorkoutDayData(day=self.day1, iteration=3, date=datetime.date(2024, 1, 7)),)+ def _date_sequence_cache_ttl(self):+ """Capture the timeout date_sequence passes to cache.set, forcing a cache miss."""+ with (+ mock.patch('wger.manager.models.routine.cache.get', return_value=None),+ mock.patch('wger.manager.models.routine.cache.set') as mock_set,+ ):+ _ = self.routine.date_sequence+ return mock_set.call_args.args[2]++ def test_date_sequence_cache_keeps_full_ttl_without_need_logs(self):+ """+ A sequence that does not depend on the current date keeps the full cache TTL+ """+ self.assertEqual(+ self._date_sequence_cache_ttl(),+ settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'],+ )++ def test_date_sequence_cache_capped_to_day_with_need_logs(self):+ """+ A sequence that bakes in today's date must expire by the next local midnight+ """+ self.day1.need_logs_to_advance = True+ self.day1.save()++ ttl = self._date_sequence_cache_ttl()+ self.assertLessEqual(ttl, 24 * 60 * 60)+ self.assertLess(ttl, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])+class RoutineApiTestCase(ApiBaseResourceTestCase):"""