Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 15 additions & 19 deletions wger/manager/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
WorkoutLogSerializer,
WorkoutSessionSerializer,
)
from wger.manager.date_sequence_cache import DateSequenceCache
from wger.manager.models import (
Day,
MaxRepetitionsConfig,
Expand Down Expand Up @@ -124,10 +125,19 @@ def perform_create(self, serializer):
"""
serializer.save(user=self.request.user)

def _date_sequence(self):
"""The date sequence, following the owner's sessions and logs only for the owner"""
def _date_sequence_response(self, cache_key, serializer):
cached = DateSequenceCache.get(cache_key)
if cached is not None:
return Response(cached.value)

routine = self.get_object()
return routine.get_date_sequence(with_history=routine.user == self.request.user)
snapshot = routine.get_date_sequence_snapshot(
with_history=routine.user == self.request.user,
)
data = serializer(snapshot.value, many=True).data
response = DateSequenceCache(data, snapshot.expires_at)
response.store(cache_key)
return Response(response.value)

@extend_schema(responses={200: WorkoutDayDataDisplayModeSerializer(many=True)})
@action(detail=True, url_path='date-sequence-display', pagination_class=None)
Expand All @@ -136,14 +146,7 @@ def date_sequence_display_mode(self, request, pk):
Return the day sequence of the routine
"""
cache_key = CacheKeyMapper.routine_api_date_sequence_display_key(pk, request.user.id)
cached_data = cache.get(cache_key)
if cached_data is not None:
return Response(cached_data)

out = WorkoutDayDataDisplayModeSerializer(self._date_sequence(), many=True).data
cache.set(cache_key, out, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])

return Response(out)
return self._date_sequence_response(cache_key, WorkoutDayDataDisplayModeSerializer)

@extend_schema(responses={200: WorkoutDayDataGymModeSerializer(many=True)})
@action(detail=True, url_path='date-sequence-gym', pagination_class=None)
Expand All @@ -152,14 +155,7 @@ def date_sequence_gym_mode(self, request, pk):
Return the day sequence of the routine
"""
cache_key = CacheKeyMapper.routine_api_date_sequence_gym_key(pk, request.user.id)
cached_data = cache.get(cache_key)
if cached_data is not None:
return Response(cached_data)

out = WorkoutDayDataGymModeSerializer(self._date_sequence(), many=True).data
cache.set(cache_key, out, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])

return Response(out)
return self._date_sequence_response(cache_key, WorkoutDayDataGymModeSerializer)

@extend_schema(responses={200: RoutineStructureSerializer})
@action(detail=True)
Expand Down
51 changes: 51 additions & 0 deletions wger/manager/date_sequence_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# This file is part of wger Workout Manager <https://github.com/wger-project>.
# Copyright (C) 2013 - 2021 wger Team
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

# Standard Library
import datetime
from dataclasses import dataclass
from typing import Self

# Django
from django.conf import settings
from django.core.cache import cache
from django.utils import timezone


@dataclass(frozen=True)
class DateSequenceCache[T]:
"""The projection and, for log-gated days, its absolute local-midnight deadline."""

value: T
expires_at: datetime.datetime | None = None

@classmethod
def get(cls, key: str) -> Self | None:
snapshot = cache.get(key)
if isinstance(snapshot, cls) and (
snapshot.expires_at is None or timezone.now() < snapshot.expires_at
):
return snapshot
return None

def store(self, key: str):
timeout = settings.WGER_SETTINGS['ROUTINE_CACHE_TTL']
if self.expires_at is not None:
timeout = min(timeout, int((self.expires_at - timezone.now()).total_seconds()))

# A cache write late in the final fractional second must not outlive midnight.
if timeout > 0:
cache.set(key, self, timeout)
40 changes: 20 additions & 20 deletions wger/manager/models/routine.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@
from typing import List

# Django
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.db import models
from django.db.models import Prefetch
from django.urls import reverse
Expand All @@ -41,6 +39,7 @@
RoutineLogData,
WorkoutDayData,
)
from wger.manager.date_sequence_cache import DateSequenceCache
from wger.manager.managers import (
PublicRoutineTemplateManager,
RoutineManager,
Expand Down Expand Up @@ -190,11 +189,17 @@ def get_date_sequence(self, with_history: bool = True) -> List[WorkoutDayData]:
Without history the owner's sessions and logs are ignored, as for a fresh copy.
This variant is not cached here, only per user in the API.
"""
return self.get_date_sequence_snapshot(with_history=with_history).value

def get_date_sequence_snapshot(
self, *, with_history: bool
) -> DateSequenceCache[list[WorkoutDayData]]:
"""Return the projection and the deadline tied to its calculation."""
cache_key = CacheKeyMapper.routine_date_sequence_key(self.id)
if with_history:
cached_data = cache.get(cache_key)
if cached_data is not None:
return cached_data
cached = DateSequenceCache.get(cache_key)
if cached is not None:
return cached

# wger
from wger.manager.models import (
Expand Down Expand Up @@ -242,11 +247,12 @@ def get_date_sequence(self, with_history: bool = True) -> List[WorkoutDayData]:
)

if not days:
return []
return DateSequenceCache([])

# Precompute session dates from prefetched logs. The zone is the same
# for every session of this routine's user, fetch it once
tz = self.user.userprofile.zone_info
today = timezone.localdate(timezone=tz)
workout_session_map = defaultdict(set)
if with_history:
for day in days:
Expand Down Expand Up @@ -282,7 +288,7 @@ def get_date_sequence(self, with_history: bool = True) -> List[WorkoutDayData]:
can_proceed = (
not current_day.need_logs_to_advance
or (current_day.need_logs_to_advance and has_session)
or current_date > timezone.localdate(timezone=tz)
or current_date > today
)

wrapped = False
Expand Down Expand Up @@ -328,22 +334,16 @@ def get_date_sequence(self, with_history: bool = True) -> List[WorkoutDayData]:
current_date += datetime.timedelta(days=1)
is_first = False

# 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']
expires_at = None
if any(day.need_logs_to_advance for day in days_list):
now = timezone.localtime(timezone=tz)
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())))
expires_at = datetime.datetime.combine(
today + datetime.timedelta(days=1), datetime.time.min, tzinfo=tz
).astimezone(datetime.timezone.utc)

snapshot = DateSequenceCache(sequence, expires_at)
if with_history:
cache.set(cache_key, sequence, ttl)
return sequence
snapshot.store(cache_key)
return snapshot

def data_for_day(self, date=None) -> WorkoutDayData | None:
"""
Expand Down
135 changes: 133 additions & 2 deletions wger/manager/tests/test_routine.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
# Django
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.urls import reverse
from django.utils import timezone

Expand All @@ -40,6 +41,7 @@
WorkoutSession,
)
from wger.manager.models.routine import Routine
from wger.utils.cache import CacheKeyMapper


class RoutineTestCase(WgerTestCase):
Expand Down Expand Up @@ -576,11 +578,132 @@ def test_data_for_day_defaults_to_the_owners_today(self):
):
self.assertEqual(routine.data_for_day(), expected)

def setup_log_gated_sequence(self, zone_name):
profile = self.routine.user.userprofile
profile.time_zone = zone_name
profile.save()
self.routine.start = datetime.date(2024, 1, 3)
self.routine.end = datetime.date(2024, 1, 5)
self.routine.save()
self.day1.name = 'Waiting for logs'
self.day1.need_logs_to_advance = True
self.day1.save()
self.day2.name = 'Next day'
self.day2.save()
self.client.force_login(self.routine.user)

def name_on_january_fourth(self, url_name):
response = self.client.get(reverse(url_name, kwargs={'pk': self.routine.pk}))
self.assertEqual(response.status_code, 200)
return next(row['day']['name'] for row in response.data if str(row['date']) == '2024-01-04')

@timezone.override('UTC')
def test_date_sequence_api_caches_expire_at_the_owners_midnight(self):
self.setup_log_gated_sequence('Pacific/Kiritimati')
before = datetime.datetime(2024, 1, 3, 9, 59, tzinfo=datetime.timezone.utc)
after = before + datetime.timedelta(minutes=2)
url_names = ('routine-date-sequence-display-mode', 'routine-date-sequence-gym-mode')
with (
mock.patch.object(timezone, 'now', return_value=before),
mock.patch('time.time', return_value=before.timestamp()),
):
for url_name in url_names:
with self.subTest(url_name=url_name):
self.assertEqual(self.name_on_january_fourth(url_name), 'Next day')

with (
mock.patch.object(timezone, 'now', return_value=after),
mock.patch('time.time', return_value=after.timestamp()),
):
for url_name in url_names:
with self.subTest(url_name=url_name):
self.assertEqual(self.name_on_january_fourth(url_name), 'Waiting for logs')

@timezone.override('UTC')
def test_date_sequence_response_crossing_midnight_is_not_cached(self):
self.setup_log_gated_sequence('Pacific/Kiritimati')
midnight = datetime.datetime(2024, 1, 3, 10, tzinfo=datetime.timezone.utc)
before = midnight - datetime.timedelta(milliseconds=100)
after = midnight + datetime.timedelta(milliseconds=100)
now = midnight - datetime.timedelta(seconds=2)
snapshot_for = Routine.get_date_sequence_snapshot
model_key = CacheKeyMapper.routine_date_sequence_key(self.routine.pk)
owner_id = self.routine.user_id

def read_snapshot_then_cross_midnight(routine, *, with_history):
nonlocal now
snapshot = snapshot_for(routine, with_history=with_history)
self.assertEqual(snapshot.expires_at, midnight)
now = after
return snapshot

with (
mock.patch.object(timezone, 'now', side_effect=lambda: now),
mock.patch('time.time', side_effect=lambda: now.timestamp()),
):
for url_name, key_for in (
(
'routine-date-sequence-display-mode',
CacheKeyMapper.routine_api_date_sequence_display_key,
),
(
'routine-date-sequence-gym-mode',
CacheKeyMapper.routine_api_date_sequence_gym_key,
),
):
with self.subTest(url_name=url_name):
key = key_for(self.routine.pk, owner_id)
cache.delete_many((key, model_key))
now = midnight - datetime.timedelta(seconds=2)
self.routine.get_date_sequence()
now = before
self.assertIsNotNone(cache.get(model_key))
with mock.patch.object(
Routine,
'get_date_sequence_snapshot',
autospec=True,
side_effect=read_snapshot_then_cross_midnight,
):
self.assertEqual(self.name_on_january_fourth(url_name), 'Next day')

self.assertIsNone(cache.get(key))
self.assertEqual(self.name_on_january_fourth(url_name), 'Waiting for logs')

@timezone.override('UTC')
def test_log_gated_sequence_is_not_cached_in_final_fractional_second(self):
self.setup_log_gated_sequence('Pacific/Kiritimati')
midnight = datetime.datetime(2024, 1, 3, 10, tzinfo=datetime.timezone.utc)
before = midnight - datetime.timedelta(milliseconds=100)
with mock.patch.object(timezone, 'now', return_value=before):
for url_name in (
'routine-date-sequence-display-mode',
'routine-date-sequence-gym-mode',
):
with self.subTest(url_name=url_name):
self.assertEqual(self.name_on_january_fourth(url_name), 'Next day')

pk = self.routine.pk
owner_id = self.routine.user_id
for key in (
CacheKeyMapper.routine_date_sequence_key(pk),
CacheKeyMapper.routine_api_date_sequence_display_key(pk, owner_id),
CacheKeyMapper.routine_api_date_sequence_gym_key(pk, owner_id),
):
self.assertIsNone(cache.get(key))

@timezone.override('UTC')
def test_date_sequence_deadline_accounts_for_daylight_saving(self):
self.setup_log_gated_sequence('America/New_York')
now = datetime.datetime(2026, 3, 8, 5, tzinfo=datetime.timezone.utc)
with mock.patch.object(timezone, 'now', return_value=now):
snapshot = self.routine.get_date_sequence_snapshot(with_history=True)
self.assertEqual(snapshot.expires_at - now, datetime.timedelta(hours=23))

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,
mock.patch('wger.manager.date_sequence_cache.cache.get', return_value=None),
mock.patch('wger.manager.date_sequence_cache.cache.set') as mock_set,
):
_ = self.routine.date_sequence
return mock_set.call_args.args[2]
Expand Down Expand Up @@ -821,6 +944,14 @@ def test_days_follow_sessions_only_for_owner(self):
['A', 'A', 'A', 'B', 'A', 'A'],
)
self.assertEqual(self.day_names(url_name, 'test'), ['A'] * 6)
with mock.patch.object(
Routine, 'get_date_sequence_snapshot', side_effect=AssertionError('cache miss')
):
self.assertEqual(self.day_names(url_name, 'test'), ['A'] * 6)
self.assertEqual(
self.day_names(url_name, 'trainer2'),
['A', 'A', 'A', 'B', 'A', 'A'],
)

def test_progression_follows_logs_only_for_owner(self):
"""The owner's log unlocks the progression, for other users it does not"""
Expand Down
6 changes: 3 additions & 3 deletions wger/utils/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,15 @@ def get_exercise_api_key(cls, base_uuid: str):

@classmethod
def routine_date_sequence_key(cls, pk: int):
return f'routine-date-sequence-{pk}'
return f'routine-date-sequence-v2-{pk}'

@classmethod
def routine_api_date_sequence_display_key(cls, pk: int, user_id: int):
return f'routine-api-date-sequence-display-{user_id}-{pk}'
return f'routine-api-date-sequence-display-v2-{user_id}-{pk}'

@classmethod
def routine_api_date_sequence_gym_key(cls, pk: int, user_id: int):
return f'routine-api-date-sequence-gym-{user_id}-{pk}'
return f'routine-api-date-sequence-gym-v2-{user_id}-{pk}'

@classmethod
def routine_api_stats(cls, pk: int, user_id: int):
Expand Down
Loading