Self hosted FLOSS fitness/workout, nutrition and weight tracker
Use cursor-based api pagination for ingredients
Roland Geider80ac521dea10
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 59215ad7e..abd41a76a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,3 +3,7 @@* The ingredient API filter now supports range lookups on `nutriscore`(`gt`, `gte`, `lt`, `lte`) in addition to `exact` and `in`, enabling querieslike "better than C" (#2295).++* Add a new, more efficient ingredient API endpoint (`/api/v2/ingredient-sync`)+ for synchronizing the local database with an upstream wger server (note that+ this is a fallback, the regular sync is still via the db dump)diff --git a/wger/nutrition/api/endpoints.py b/wger/nutrition/api/endpoints.pyindex ab8e267b1..62cb80998 100644--- a/wger/nutrition/api/endpoints.py+++ b/wger/nutrition/api/endpoints.py@@ -1,3 +1,4 @@IMAGE_ENDPOINT = 'ingredient-image'INGREDIENTS_ENDPOINT = 'ingredient'+INGREDIENTS_SYNC_ENDPOINT = 'ingredient-sync'INGREDIENT_BULK_EXPORT_PATH = 'ingredients/ingredients.jsonl.gz'diff --git a/wger/nutrition/api/filtersets.py b/wger/nutrition/api/filtersets.pyindex 461909ac7..843765fd8 100644--- a/wger/nutrition/api/filtersets.py+++ b/wger/nutrition/api/filtersets.py@@ -105,7 +105,7 @@ class IngredientFilterSet(filters.FilterSet):class Meta:model = Ingredientfields = {- 'id': ['exact', 'in'],+ 'id': ['exact', 'in', 'gt', 'gte', 'lt', 'lte'],'uuid': ['exact'],'code': ['exact'],'source_name': ['exact'],diff --git a/wger/nutrition/api/views.py b/wger/nutrition/api/views.pyindex 07d8d6501..1c2304eeb 100644--- a/wger/nutrition/api/views.py+++ b/wger/nutrition/api/views.py@@ -55,6 +55,7 @@ from wger.nutrition.models import (MealItem,NutritionPlan,)+from wger.utils.pagination import IngredientCursorPaginationfrom wger.utils.viewsets import WgerOwnerObjectModelViewSet@@ -154,6 +155,33 @@ class IngredientInfoViewSet(IngredientViewSet):)+class IngredientSyncViewSet(viewsets.ReadOnlyModelViewSet):+ """+ Cursor-paginated read-only endpoint designed for syncing the ingredient+ catalogue.++ Unlike /api/v2/ingredient/, this endpoint uses cursor pagination so deep+ pagination stays fast and is intended for clients such as local wger instances.++ For incremental syncs, combine with the `last_update__gt` filter to only+ fetch ingredients that changed since that time.++ Note: the response does not contain a `count` key.+ """++ serializer_class = IngredientInfoSerializer+ pagination_class = IngredientCursorPagination+ filterset_class = IngredientFilterSet+ throttle_scope = 'ingredient_sync'++ def get_queryset(self):+ return Ingredient.objects.select_related(+ 'language',+ 'license',+ 'image',+ )++class ImageViewSet(viewsets.ReadOnlyModelViewSet):"""API endpoint for ingredient imagesdiff --git a/wger/nutrition/management/commands/sync-ingredients.py b/wger/nutrition/management/commands/sync-ingredients.pyindex 1d9d3f92c..d504665dc 100644--- a/wger/nutrition/management/commands/sync-ingredients.py+++ b/wger/nutrition/management/commands/sync-ingredients.py@@ -20,7 +20,10 @@ from django.core.management.base import CommandErrorfrom wger.core.api.min_server_version import check_min_server_versionfrom wger.core.management.wger_command import WgerCommandfrom wger.nutrition.sync import sync_ingredients-from wger.utils.validators import validate_language_code+from wger.utils.validators import (+ validate_iso_date,+ validate_language_code,+)class Command(WgerCommand):@@ -41,18 +44,31 @@ class Command(WgerCommand):default=None,help='Specify a comma-separated subset of languages to sync. Example: en,fr,es',)+ parser.add_argument(+ '--since',+ action='store',+ dest='since',+ default=None,+ help=(+ 'Only sync ingredients updated after this ISO-8601 timestamp '+ '(e.g. 2026-04-20T00:00:00Z). Useful for incremental syncs.'+ ),+ )def handle(self, **options):super().handle(**options)remote_url = options['remote_url']languages = options['languages']+ since = options['since']check_min_server_version(remote_url)try:if languages is not None:for language in languages.split(','):validate_language_code(language)+ if since is not None:+ validate_iso_date(since)except ValidationError as e:raise CommandError('\n'.join([str(arg) for arg in e.args if arg is not None]))@@ -62,4 +78,5 @@ class Command(WgerCommand):languages,self.style.SUCCESS,show_progress_bar=True,+ last_update_gt=since,)diff --git a/wger/nutrition/sync.py b/wger/nutrition/sync.pyindex 9acbc3c44..9ebf668ef 100644--- a/wger/nutrition/sync.py+++ b/wger/nutrition/sync.py@@ -49,6 +49,7 @@ from wger.nutrition.api.endpoints import (IMAGE_ENDPOINT,INGREDIENT_BULK_EXPORT_PATH,INGREDIENTS_ENDPOINT,+ INGREDIENTS_SYNC_ENDPOINT,)from wger.nutrition.api.serializers import IngredientSerializerfrom wger.nutrition.consts import SyncMode@@ -309,46 +310,29 @@ def download_ingredient_images(print_fn(style_fn(' successfully saved'))-def sync_ingredients_page(- page: int,- limit: int = API_MAX_ITEMS,- remote_url: str = settings.WGER_SETTINGS['WGER_INSTANCE'],- language_codes: Optional[str] = None,-) -> int:- """- Sync a single paginated page (0-based index). Returns number of processed ingredients.- Safe to rerun (idempotent).- """- try:- language_ids = _resolve_language_codes(language_codes)- except Language.DoesNotExist:- logger.warning(f'Language code not found, skipping page {page}.')- return 0-- offset = page * limit- query: dict[str, str | int] = {'limit': limit, 'offset': offset}- if language_ids:- query['language__in'] = ','.join(language_ids)-- url = make_uri(INGREDIENTS_ENDPOINT, server_url=remote_url, query=query)- response = requests.get(url, headers=wger_headers(), timeout=30).json()- results = response.get('results', [])- processed = 0- for data in results:- _sync_ingredient_from_api_data(data)- processed += 1- logger.debug(f'Page {page} synced ({processed} ingredients)')- return processed--def sync_ingredients(print_fn,remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],language_codes: Optional[str] = None,style_fn=lambda x: x,show_progress_bar: bool = False,+ last_update_gt: Optional[str] = None,+ id_gte: Optional[int] = None,+ id_lt: Optional[int] = None,):- """Synchronize the ingredients from the remote server"""+ """+ Synchronize ingredients from a remote wger instance++ Uses /api/v2/ingredient-sync which is backed by an indexed cursor instead+ of /api/v2/ingredientinfo which is OFFSET-based.++ For incremental syncs, pass an ISO-8601 timestamp via `last_update_gt` to+ only fetch ingredients that changed since the last sync.++ For parallel range-based syncs (used by the celery orchestrator), pass+ `id_gte` and/or `id_lt` to restrict the worker to one slice of the id+ space; combined with cursor pagination this is fast at any catalogue size.+ """print_fn('*** Synchronizing ingredients...')try:@@ -359,48 +343,61 @@ def sync_ingredients()return 0- query: dict[str, str | int] = {'limit': API_MAX_ITEMS}+ filter_query: dict[str, str] = {}if language_ids is not None:- query['language__in'] = ','.join(language_ids)+ filter_query['language__in'] = ','.join(language_ids)+ if last_update_gt:+ filter_query['last_update__gt'] = last_update_gt+ if id_gte is not None:+ filter_query['id__gte'] = str(id_gte)+ if id_lt is not None:+ filter_query['id__lt'] = str(id_lt)++ # Total count is only used for the progress bar's ETA / percentage. Skip+ # the probe when nobody is watching (e.g. inside the celery range-worker)+ # to avoid an unnecessary request against the throttled `ingredient_list`+ # scope.+ total = None+ if show_progress_bar:+ count_url = make_uri(+ INGREDIENTS_ENDPOINT,+ server_url=remote_url,+ query={**filter_query, 'limit': 1},+ )+ try:+ count_response = requests.get(count_url, headers=wger_headers(), timeout=30).json()+ total = count_response.get('count')+ except (requests.RequestException, ValueError) as e:+ logger.info(f'Could not fetch total ingredient count: {e}')url = make_uri(- INGREDIENTS_ENDPOINT,+ INGREDIENTS_SYNC_ENDPOINT,server_url=remote_url,- query=query,+ query={**filter_query, 'page_size': API_MAX_ITEMS},)- # Fetch once to retrieve the number of results- response = requests.get(url, headers=wger_headers()).json()- total_ingredients = response['count']- total_pages = total_ingredients // API_MAX_ITEMS-- ingredient_nr = 1- page_nr = 1pbar = tqdm(- total=total_ingredients,+ total=total,unit='ingredients',desc='Syncing progress',unit_scale=True,smoothing=0.1,mininterval=1.0,+ disable=not show_progress_bar,)++ count = 0for data in get_paginated(url, headers=wger_headers()):_sync_ingredient_from_api_data(data)-- if show_progress_bar:- pbar.update(1)- else:- # Note that get_paginated returns the individual result entries from the pages.- # To get the current page, we need to calculate this ourselves.- ingredient_nr += 1- if ingredient_nr % API_MAX_ITEMS == 0:- page_nr += 1- print_fn(f'Processing ingredients, page {page_nr: >4} of {total_pages}')+ count += 1+ pbar.update(1)+ if not show_progress_bar and count % API_MAX_ITEMS == 0:+ print_fn(f'Processed {count} ingredients...')pbar.close()- print_fn(style_fn('done!\n'))- return None+ print_fn(style_fn(f'done! Processed {count} ingredients.\n'))+ return countBULK_SIZE = 500diff --git a/wger/nutrition/tasks.py b/wger/nutrition/tasks.pyindex adc16e256..34251dc9a 100644--- a/wger/nutrition/tasks.py+++ b/wger/nutrition/tasks.py@@ -18,7 +18,6 @@ from random import randint# Djangofrom django.conf import settings-from django.core.cache import cachefrom django.core.management import call_commandfrom django.core.management.base import CommandError@@ -38,10 +37,7 @@ from wger.nutrition.sync import (fetch_ingredient_image,sync_ingredients,sync_ingredients_from_dump,- sync_ingredients_page,)-from wger.utils.cache import CacheKeyMapper-from wger.utils.constants import API_MAX_ITEMSfrom wger.utils.requests import wger_headersfrom wger.utils.url import make_uri@@ -49,12 +45,13 @@ from wger.utils.url import make_urilogger = logging.getLogger(__name__)-PAGE_RANGE_SIZE = 25-"""The number of pages (with API_MAX_ITEMS items each) the individual task processes"""+ID_RANGE_SIZE = 25_000+"""Approx. ingredients processed per parallel celery worker.--CACHE_TIMEOUT_SECONDS = 10 * 3600-"""Timeout for the cache keys marking completed pages/ranges"""+We split the id space [0, max_id] into chunks of this size and dispatch one+task per chunk via celery group. Within each chunk, sync_ingredients() walks+via cursor pagination — fast at any catalogue size.+"""@app.task@@ -81,35 +78,33 @@ def fetch_all_ingredient_images_task():retry_jitter=True,retry_kwargs={'max_retries': 5},)-def sync_ingredient_page_range_task(- total_pages: int,- start_page: int,- end_page: int,+def sync_ingredient_id_range_task(+ id_gte: int,+ id_lt: int,remote_url: str | None = None,language_codes: str | None = None,):"""- Sequentially processes pages in [start_page, end_page), skips pages already- completed by writing to the cache.+ Sync the ingredients in `[id_gte, id_lt)` via the cursor endpoint.++ One celery worker handles one slice of the id space. Cursor pagination+ inside the slice means each page is an indexed lookup (O(log n)), so the+ overall load on the remote scales linearly with the catalogue size — no+ deep-OFFSET penalty.++ Idempotent: `update_or_create` in `_sync_ingredient_from_api_data` makes+ re-running the same range safe. A failed worker simply retries (autoretry+ above) or is replayed by celery without leaving the local DB inconsistent."""remote = remote_url or settings.WGER_SETTINGS['WGER_INSTANCE']- processed = 0- for page in range(start_page, end_page):- # Atomic: only first caller succeeds; subsequent ones skip- key = CacheKeyMapper.ingredient_celery_sync(page)- if not cache.add(key, 'done', timeout=CACHE_TIMEOUT_SECONDS):- logger.info(f'Page {page} already done, skipping.')- continue-- page_processed = sync_ingredients_page(- page=page,- limit=API_MAX_ITEMS,- remote_url=remote,- language_codes=language_codes,- )- processed += page_processed- logger.info(f'Processed pages {start_page} - {end_page - 1} of {total_pages}')- return processed+ logger.info(f'Sync id range [{id_gte}, {id_lt})')+ sync_ingredients(+ logger.info,+ remote_url=remote,+ language_codes=language_codes,+ id_gte=id_gte,+ id_lt=id_lt,+ )@app.task@@ -118,8 +113,13 @@ def sync_all_ingredients_chunked_task(remote_url: str | None = None,):"""- Orchestrator: builds a group of page-range tasks that process a range of pages each.- Runs in parallel depending on the concurrency settings of the Celery worker.+ Orchestrator: splits the id space into ranges of `ID_RANGE_SIZE` rows each+ and dispatches a parallel task per range. Each worker uses cursor+ pagination internally (see sync_ingredient_id_range_task).++ Replaces the previous OFFSET-based chunking, which scaled quadratically+ with catalogue size and triggered minute-long queries on the remote at+ high page numbers."""remote = remote_url or settings.WGER_SETTINGS['WGER_INSTANCE']@@ -130,23 +130,29 @@ def sync_all_ingredients_chunked_task(logger.error(f'Ingredient sync aborted, server incompatible: {e}')return None- # Calculate number of pages- url = make_uri(INGREDIENTS_ENDPOINT, server_url=remote, query={'limit': 1})+ # Find the highest existing id on the remote so we know how far to chunk.+ url = make_uri(+ INGREDIENTS_ENDPOINT,+ server_url=remote,+ query={'ordering': '-id', 'limit': 1},+ )data = requests.get(url, headers=wger_headers(), timeout=30).json()+ if data.get('count', 0) == 0:+ logger.info('Remote has no ingredients, nothing to sync.')+ return None++ max_id = data['results'][0]['id']total = data['count']- total_pages = total // API_MAX_ITEMSlogger.info(- f'Start sync: {total} ingredients over {total_pages} pages (chunk={PAGE_RANGE_SIZE}).'+ f'Start sync: {total} ingredients up to id={max_id}, chunk size={ID_RANGE_SIZE} rows.')- # Create tasks for each page range and start them+ # Dispatch one task per id range. The last range covers max_id; ranges+ # past max_id never execute because no rows match.tasks = []- for start in range(0, total_pages, PAGE_RANGE_SIZE):- end = min(start + PAGE_RANGE_SIZE, total_pages)-- tasks.append(- sync_ingredient_page_range_task.s(total_pages, start, end, remote, language_codes)- )+ for start in range(0, max_id + 1, ID_RANGE_SIZE):+ end = start + ID_RANGE_SIZE+ tasks.append(sync_ingredient_id_range_task.s(start, end, remote, language_codes))group(*tasks).apply_async()return Nonediff --git a/wger/nutrition/templates/ingredient/overview.html b/wger/nutrition/templates/ingredient/overview.htmlindex a7db96f1d..d4431676a 100644--- a/wger/nutrition/templates/ingredient/overview.html+++ b/wger/nutrition/templates/ingredient/overview.html@@ -52,19 +52,30 @@{% if is_paginated %}<li class="page-item"><a href="{{ first_url }}" class="page-link">- « {% translate "Back to start" %}+ « {% translate "First page" %}</a></li>{% endif %}+ {% if has_prev %}+ <li class="page-item">+ <a href="{{ prev_url }}" class="page-link">+ ‹ {% translate "previous" %}+ </a>+ </li>+ {% else %}+ <li class="page-item disabled">+ <a href="#" class="page-link">‹ {% translate "previous" %}</a>+ </li>+ {% endif %}{% if has_next %}<li class="page-item"><a href="{{ next_url }}" class="page-link">- {% translate "next" %} »+ {% translate "next" %} ›</a></li>{% else %}<li class="page-item disabled">- <a href="#" class="page-link">{% translate "next" %} »</a>+ <a href="#" class="page-link">{% translate "next" %} ›</a></li>{% endif %}</ul>diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.pyindex 51ccc717a..2c855e25b 100644--- a/wger/nutrition/tests/test_ingredient.py+++ b/wger/nutrition/tests/test_ingredient.py@@ -794,3 +794,59 @@ class IngredientThrottleScopeTestCase(WgerTestCase):def test_ingredient_sync_uses_sync_scope(self):self.assertEqual(IngredientSyncViewSet.throttle_scope, 'ingredient_sync')+++class IngredientSyncViewSetTestCase(WgerTestCase):+ """+ Tests for the /api/v2/ingredient-sync endpoint.+ """++ url = reverse('api-ingredient-sync-list')++ def test_list_returns_cursor_pagination_shape(self):+ """The response has `next`/`previous`, but no `count`."""++ response = self.client.get(self.url)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertIn('results', response.data)+ self.assertIn('next', response.data)+ self.assertIn('previous', response.data)+ self.assertNotIn('count', response.data)++ def test_list_paginates_through_all_ingredients(self):+ """Following `next` returns disjoint pages that together cover all rows."""++ total = Ingredient.objects.count()+ self.assertGreater(total, 0, 'Fixture must contain ingredients')++ seen_ids = []+ url = self.url + '?page_size=5'+ while url:+ response = self.client.get(url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ seen_ids.extend(item['id'] for item in response.data['results'])+ url = response.data['next']++ # No duplicates and every ingredient seen exactly once.+ self.assertEqual(len(seen_ids), len(set(seen_ids)))+ self.assertEqual(set(seen_ids), set(Ingredient.objects.values_list('id', flat=True)))++ def test_page_size_query_param_is_capped(self):+ """`?page_size=` is honored but capped at `max_page_size`."""++ # Way above max_page_size=1000 — must be capped, not error+ response = self.client.get(self.url + '?page_size=999999')+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual(len(response.data['results']), 1000)++ def test_filterset_supports_incremental_sync(self):+ """`last_update__gt` filter narrows the result set for incremental syncs."""++ # Pick a timestamp newer than all fixture rows -> empty result+ future = '2999-01-01T00:00:00Z'+ response = self.client.get(f'{self.url}?last_update__gt={future}')++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.data['results'], [])+ self.assertIsNone(response.data['next'])diff --git a/wger/nutrition/tests/test_ingredient_overview.py b/wger/nutrition/tests/test_ingredient_overview.pyindex 25c6b0838..0cb6115d5 100644--- a/wger/nutrition/tests/test_ingredient_overview.py+++ b/wger/nutrition/tests/test_ingredient_overview.py@@ -52,13 +52,15 @@ class IngredientOverviewTestCase(WgerTestCase):self.user_logout()url = reverse('nutrition:ingredient:list')- # First page: full PAGE_SIZE, has_next, no is_paginated marker yet.+ # First page: full PAGE_SIZE, has_next, no previous, not paginated yet.response = self.client.get(url)self.assertEqual(response.status_code, 200)self.assertEqual(len(response.context['ingredients_list']), PAGINATION_OBJECTS_PER_PAGE)self.assertTrue(response.context['has_next'])+ self.assertFalse(response.context['has_prev'])self.assertFalse(response.context['is_paginated'])self.assertIsNotNone(response.context['next_url'])+ self.assertIsNone(response.context['prev_url'])self.assertIn('after=', response.context['next_url'])# Walk the catalogue forward until exhausted by following next_url.@@ -94,6 +96,68 @@ class IngredientOverviewTestCase(WgerTestCase):self.assertFalse(response.context['has_next'])self.assertIsNone(response.context['next_url'])+ def test_overview_backward_pagination(self):+ """`?before=<id>` walks backward through the catalogue."""++ self.user_login('admin')+ data = {+ 'name': 'Test ingredient',+ 'language': 2,+ 'sodium': 10.54,+ 'energy': 176,+ 'fat': 8.19,+ 'carbohydrates_sugar': 0.0,+ 'fat_saturated': 3.24,+ 'fiber': 0.0,+ 'protein': 25.63,+ 'carbohydrates': 0.0,+ 'license': 1,+ 'license_author': 'internet',+ }+ for i in range(0, 80):+ self.client.post(reverse('nutrition:ingredient:add'), data)++ self.user_logout()+ url = reverse('nutrition:ingredient:list')++ # Navigate forward two pages, then back via prev_url.+ page1 = self.client.get(url)+ page1_ids = [i.id for i in page1.context['ingredients_list']]++ page2 = self.client.get(url + page1.context['next_url'])+ page2_ids = [i.id for i in page2.context['ingredients_list']]++ # Page 2 must offer a "prev" link, since we've moved past page 1.+ self.assertTrue(page2.context['has_prev'])+ self.assertIsNotNone(page2.context['prev_url'])+ self.assertIn('before=', page2.context['prev_url'])++ # Going back from page 2 must yield exactly page 1.+ page1_again = self.client.get(url + page2.context['prev_url'])+ page1_again_ids = [i.id for i in page1_again.context['ingredients_list']]+ self.assertEqual(page1_again_ids, page1_ids)++ # On the (re)first page, prev disappears, next reappears.+ self.assertFalse(page1_again.context['has_prev'])+ self.assertTrue(page1_again.context['has_next'])++ # Going forward from there must take us back to page 2 again.+ page2_again = self.client.get(url + page1_again.context['next_url'])+ page2_again_ids = [i.id for i in page2_again.context['ingredients_list']]+ self.assertEqual(page2_again_ids, page2_ids)++ # An invalid `?before=` cursor falls back to the first page.+ response = self.client.get(url, {'before': 'foobar'})+ self.assertEqual(response.status_code, 200)+ self.assertFalse(response.context['has_prev'])++ # `?before=<very small id>` yields an empty page with no prev link.+ response = self.client.get(url, {'before': 0})+ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.context['ingredients_list'], [])+ self.assertFalse(response.context['has_prev'])+ self.assertIsNone(response.context['prev_url'])+def test_next_url_preserves_filter_params(self):"""The next_url must keep filter parameters like ?is_vegan=1 attached."""self.user_login('admin')diff --git a/wger/nutrition/tests/test_sync.py b/wger/nutrition/tests/test_sync.pyindex 8cf825268..c86efe128 100644--- a/wger/nutrition/tests/test_sync.py+++ b/wger/nutrition/tests/test_sync.py@@ -14,23 +14,29 @@# Standard Libraryfrom decimal import Decimal-from unittest.mock import patch+from unittest.mock import (+ MagicMock,+ patch,+)from uuid import UUID# Djangofrom django.core.management import CommandError+# Third Party+import requests+# wgerfrom wger.core.tests.base_testcase import WgerTestCasefrom wger.nutrition.models import (Ingredient,IngredientWeightUnit,)-from wger.nutrition.sync import (- sync_ingredients,- sync_ingredients_page,+from wger.nutrition.sync import sync_ingredients+from wger.nutrition.tasks import (+ sync_all_ingredients_chunked_task,+ sync_ingredient_id_range_task,)-from wger.nutrition.tasks import sync_all_ingredients_chunked_taskfrom wger.utils.requests import wger_headers@@ -131,8 +137,10 @@ class TestSyncMethods(WgerTestCase):# Actsync_ingredients(lambda x: x)+ # The last call is the cursor sync URL — the first call probes the+ # regular endpoint for `count` so the progress bar can show ETA.mock_request.assert_called_with(- 'https://wger.de/api/v2/ingredient/?limit=999',+ 'https://wger.de/api/v2/ingredient-sync/?page_size=999',headers=wger_headers(),)@@ -187,65 +195,86 @@ class TestSyncMethods(WgerTestCase):self.assertEqual(ingredient.ingredientweightunit_set.count(), 2)@patch('requests.get', return_value=MockIngredientResponse())- def test_sync_ingredients_page(self, mock_request):- """- Test syncing a single page of ingredients- """+ def test_ingredient_sync_languages(self, mock_request):+ # Call the function with the language_codes parameter+ sync_ingredients(lambda x: x, language_codes='en')- # Arrange- ingredient = Ingredient.objects.get(pk=1)+ # Assert that the correct URL is called with the expected parameters+ expected_url = 'https://wger.de/api/v2/ingredient-sync/?language__in=2&page_size=999'+ mock_request.assert_called_with(+ expected_url,+ headers=wger_headers(),+ )- self.assertEqual(Ingredient.objects.count(), 14)- self.assertEqual(ingredient.name, 'Test ingredient 1')- self.assertEqual(ingredient.energy, 176)- self.assertAlmostEqual(ingredient.protein, Decimal(25.63), 2)- self.assertEqual(ingredient.code, '1234567890987654321')+ @patch('requests.get', return_value=MockIngredientResponse())+ def test_ingredient_sync_incremental(self, mock_request):+ """Incremental sync passes `last_update__gt` to the cursor endpoint."""+ sync_ingredients(lambda x: x, last_update_gt='2026-04-20T00:00:00Z')- # Act- sync_ingredients_page(page=1)+ expected_url = (+ 'https://wger.de/api/v2/ingredient-sync/'+ '?last_update__gt=2026-04-20T00:00:00Z&page_size=999'+ )mock_request.assert_called_with(- 'https://wger.de/api/v2/ingredient/?limit=999&offset=999',+ expected_url,headers=wger_headers(),- timeout=30,)- # Assert- self.assertEqual(Ingredient.objects.count(), 15)+ @patch('requests.get', return_value=MockIngredientResponse())+ def test_ingredient_sync_fetches_count_when_progress_bar_enabled(self, mock_request):+ """With show_progress_bar=True, the first call probes for the total count.- ingredient = Ingredient.objects.get(pk=1)- self.assertEqual(ingredient.name, 'Gâteau double chocolat')- self.assertEqual(ingredient.energy, 360)- self.assertAlmostEqual(ingredient.protein, Decimal(5), 2)- self.assertEqual(ingredient.code, '0013087245950')- self.assertEqual(ingredient.license.pk, 5)- self.assertEqual(ingredient.uuid, UUID('7908c204-907f-4b1e-ad4e-f482e9769ade'))- self.assertTrue(ingredient.is_vegan)- self.assertTrue(ingredient.is_vegetarian)- self.assertEqual(ingredient.nutriscore, 'D')+ Cursor pagination has no `count` field, so we look up the total via+ the regular OFFSET endpoint (?limit=1) before starting the cursor+ walk so the progress bar can show percentage and ETA.+ """+ sync_ingredients(lambda x: x, show_progress_bar=True)- # Weight units synced- self.assertEqual(ingredient.ingredientweightunit_set.count(), 2)+ # First call probes the regular endpoint for count.+ first_call_args = mock_request.call_args_list[0].args+ self.assertIn('/api/v2/ingredient/', first_call_args[0])+ self.assertIn('limit=1', first_call_args[0])- new_ingredient = Ingredient.objects.get(uuid='582f1b7f-a8bd-4951-9edd-247bc68b28f4')- self.assertEqual(new_ingredient.name, 'Maxi Hot Dog New York Style')- self.assertEqual(new_ingredient.energy, 256)- self.assertAlmostEqual(new_ingredient.protein, Decimal(11), 2)- self.assertEqual(new_ingredient.code, '3181238941963')- self.assertIsNone(new_ingredient.is_vegan)- self.assertIsNone(new_ingredient.is_vegetarian)- self.assertIsNone(new_ingredient.nutriscore)+ # Last call is the cursor sync URL.+ last_call_args = mock_request.call_args_list[-1].args+ self.assertIn('/api/v2/ingredient-sync/', last_call_args[0])@patch('requests.get', return_value=MockIngredientResponse())- def test_ingredient_sync_languages(self, mock_request):- # Call the function with the language_codes parameter- sync_ingredients(lambda x: x, language_codes='en')+ def test_ingredient_sync_skips_count_probe_without_progress_bar(self, mock_request):+ """Without progress-bar, the count probe is skipped to save a request.- # Assert that the correct URL is called with the expected parameters- expected_url = 'https://wger.de/api/v2/ingredient/?limit=999&language__in=2'- mock_request.assert_called_with(- expected_url,- headers=wger_headers(),- )+ Celery range-workers run with show_progress_bar=False (the default), so+ skipping this probe avoids ~120 unnecessary `ingredient_list`-scoped+ requests per chunked sync run.+ """+ sync_ingredients(lambda x: x)++ # All calls go to the cursor endpoint; none to the regular one.+ for call in mock_request.call_args_list:+ self.assertIn('/api/v2/ingredient-sync/', call.args[0])+ self.assertNotIn('/api/v2/ingredient/?', call.args[0])++ @patch('requests.get')+ def test_ingredient_sync_continues_when_count_fetch_fails(self, mock_request):+ """A failing count fetch must not abort the sync — fallback to no-ETA bar."""+ # First call (count) raises, subsequent calls return a valid response+ # so the cursor sync can proceed.+ responses = [+ requests.exceptions.RequestException('count fetch failed'),+ MockIngredientResponse(),+ ]++ def side_effect(*args, **kwargs):+ r = responses.pop(0)+ if isinstance(r, Exception):+ raise r+ return r++ mock_request.side_effect = side_effect+ # show_progress_bar=True forces the count probe path+ sync_ingredients(lambda x: x, show_progress_bar=True)+ # Both calls were made+ self.assertGreaterEqual(mock_request.call_count, 2)@patch('wger.nutrition.tasks.requests.get')@patch('wger.nutrition.tasks.check_min_server_version')@@ -262,3 +291,128 @@ class TestSyncMethods(WgerTestCase):mock_check_version.assert_called_once_with('https://example.com')# No API requests must be made when the version check fails.mock_request.assert_not_called()++ @patch('wger.nutrition.tasks.group')+ @patch('wger.nutrition.tasks.sync_ingredient_id_range_task')+ @patch('wger.nutrition.tasks.requests.get')+ @patch('wger.nutrition.tasks.check_min_server_version')+ def test_chunked_sync_dispatches_id_range_tasks(+ self, mock_check_version, mock_request, mock_id_range_task, mock_group+ ):+ """Orchestrator splits the id space into ID_RANGE_SIZE-row chunks."""+ # wger+ from wger.nutrition.tasks import ID_RANGE_SIZE++ # Remote pretends to have ingredients up to id = 60_000 (so 3 chunks+ # at the default ID_RANGE_SIZE = 25_000).+ mock_response = MagicMock()+ mock_response.json.return_value = {+ 'count': 50_000,+ 'results': [{'id': 60_000}],+ }+ mock_request.return_value = mock_response++ sync_all_ingredients_chunked_task(remote_url='https://example.com')++ # The probe URL fetches the highest-id row.+ probe_url = mock_request.call_args.args[0]+ self.assertIn('ordering=-id', probe_url)+ self.assertIn('limit=1', probe_url)++ # Three id-range tasks dispatched: [0, 25k), [25k, 50k), [50k, 75k).+ self.assertEqual(mock_id_range_task.s.call_count, 3)+ for i, call in enumerate(mock_id_range_task.s.call_args_list):+ id_gte, id_lt, remote, language_codes = call.args+ self.assertEqual(id_gte, i * ID_RANGE_SIZE)+ self.assertEqual(id_lt, (i + 1) * ID_RANGE_SIZE)+ self.assertEqual(remote, 'https://example.com')+ self.assertIsNone(language_codes)++ # The group of tasks is dispatched to celery.+ mock_group.return_value.apply_async.assert_called_once()++ @patch('wger.nutrition.tasks.requests.get')+ @patch('wger.nutrition.tasks.check_min_server_version')+ def test_chunked_sync_handles_empty_remote(self, mock_check_version, mock_request):+ """If the remote has zero ingredients, the orchestrator returns cleanly."""+ mock_response = MagicMock()+ mock_response.json.return_value = {'count': 0, 'results': []}+ mock_request.return_value = mock_response++ # Should not raise, should not dispatch any tasks+ result = sync_all_ingredients_chunked_task(remote_url='https://example.com')+ self.assertIsNone(result)++ @patch('wger.nutrition.tasks.sync_ingredients')+ def test_id_range_task_passes_filter_params(self, mock_sync):+ """The worker task forwards id_gte/id_lt to sync_ingredients."""+ sync_ingredient_id_range_task(+ id_gte=25_000,+ id_lt=50_000,+ remote_url='https://example.com',+ language_codes='en',+ )++ mock_sync.assert_called_once()+ kwargs = mock_sync.call_args.kwargs+ self.assertEqual(kwargs['id_gte'], 25_000)+ self.assertEqual(kwargs['id_lt'], 50_000)+ self.assertEqual(kwargs['remote_url'], 'https://example.com')+ self.assertEqual(kwargs['language_codes'], 'en')+++class SyncIngredientsCommandTestCase(WgerTestCase):+ """+ Tests for the `sync-ingredients` management command.++ The `@patch('wger.core.api.min_server_version.check_min_server_version')`+ decorator is mandatory: it must be active when `_get_command_module()`+ triggers loading of `wger_command.py`, so the latter's+ `from ... import check_min_server_version` binds to a Mock instead of the+ real function. (Same pattern as `test_sync_bulk.py`.)+ """++ def _get_command_module(self):+ """The hyphenated module name needs importlib."""+ # Standard Library+ import importlib++ return importlib.import_module('wger.nutrition.management.commands.sync-ingredients')++ @patch('wger.core.api.min_server_version.check_min_server_version')+ def test_since_accepts_iso_date(self, mock_version_check):+ """Plain ISO date `YYYY-MM-DD` is accepted as `--since` value."""+ # Django+ from django.core.management import call_command++ mod = self._get_command_module()+ with patch.object(mod, 'sync_ingredients') as mock_sync:+ call_command('sync-ingredients', '--since', '2026-04-01')+ mock_sync.assert_called_once()+ self.assertEqual(mock_sync.call_args.kwargs['last_update_gt'], '2026-04-01')++ @patch('wger.core.api.min_server_version.check_min_server_version')+ def test_since_accepts_iso_datetime(self, mock_version_check):+ """Full ISO-8601 datetime is accepted as `--since` value."""+ # Django+ from django.core.management import call_command++ mod = self._get_command_module()+ with patch.object(mod, 'sync_ingredients') as mock_sync:+ call_command('sync-ingredients', '--since', '2026-04-01T12:34:56Z')+ mock_sync.assert_called_once()+ self.assertEqual(mock_sync.call_args.kwargs['last_update_gt'], '2026-04-01T12:34:56Z')++ @patch('wger.core.api.min_server_version.check_min_server_version')+ def test_since_rejects_garbage(self, mock_version_check):+ """A non-parseable `--since` value must abort the command before syncing."""+ # Django+ from django.core.management import call_command++ mod = self._get_command_module()+ with patch.object(mod, 'sync_ingredients') as mock_sync:+ with self.assertRaises(CommandError) as cm:+ call_command('sync-ingredients', '--since', 'yesterday')++ self.assertIn('ISO-8601', str(cm.exception))+ mock_sync.assert_not_called()diff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.pyindex 61b29ae45..4cc42253e 100644--- a/wger/nutrition/views/ingredient.py+++ b/wger/nutrition/views/ingredient.py@@ -88,51 +88,97 @@ class IngredientListView(ListView):def get_queryset(self):"""- Apply language + filterset, then cursor logic. We fetch one extra row- beyond PAGE_SIZE so we know whether a next page exists without an- extra COUNT query.+ Apply language + filterset, then the cursor logic.++ We fetch one extra row beyond PAGE_SIZE so we know whether a further+ page exists without an extra COUNT query.++ Three modes:+ - first page (no cursor): id ASC LIMIT N+1+ - forward (?after=X): id > X, id ASC LIMIT N+1+ - backward (?before=Y): id < Y, id DESC LIMIT N+1+ (rows are reversed in get_context_data)"""language = load_language()queryset = Ingredient.objects.filter(language=language)filterset = self.filterset_class(self.request.GET or None, queryset=queryset)- qs = filterset.qs.order_by('id')+ qs = filterset.qs++ self._cursor_mode = 'first'++ before = self.request.GET.get('before')+ if before:+ try:+ qs = qs.filter(id__lt=int(before))+ self._cursor_mode = 'before'+ return qs.order_by('-id')[: self.PAGE_SIZE + 1]+ except (TypeError, ValueError):+ # invalid cursor → fall through to first page+ passafter = self.request.GET.get('after')if after:try:qs = qs.filter(id__gt=int(after))+ self._cursor_mode = 'after'except (TypeError, ValueError):- # fall through to first pagepass- return qs[: self.PAGE_SIZE + 1]+ return qs.order_by('id')[: self.PAGE_SIZE + 1]def get_context_data(self, **kwargs):context = super().get_context_data(**kwargs)- ingredients = list(context['ingredients_list'])-- # We fetched PAGE_SIZE + 1 to peek at the next-page existence.- has_next = len(ingredients) > self.PAGE_SIZE- if has_next:- ingredients = ingredients[: self.PAGE_SIZE]-- # Pre-build the pagination URLs here+ rows = list(context['ingredients_list'])++ if self._cursor_mode == 'before':+ # Backward query returned descending; flip back to ascending for+ # display. The "+1 peek" is at the FRONT (smallest id) and tells+ # us whether further previous pages exist.+ rows.reverse()+ has_prev = len(rows) > self.PAGE_SIZE+ if has_prev:+ rows = rows[1:]+ # Going back, "next" always exists — it's the page we came from.+ has_next = True+ elif self._cursor_mode == 'after':+ has_next = len(rows) > self.PAGE_SIZE+ if has_next:+ rows = rows[: self.PAGE_SIZE]+ has_prev = True+ else: # first page+ has_next = len(rows) > self.PAGE_SIZE+ if has_next:+ rows = rows[: self.PAGE_SIZE]+ has_prev = False++ # Pre-build the pagination URLs (Python urlencode dodges template L10N).next_url = None- if has_next and ingredients:+ if has_next and rows:params = self.request.GET.copy()- params['after'] = str(ingredients[-1].id)+ params.pop('before', None)+ params['after'] = str(rows[-1].id)next_url = f'?{params.urlencode()}'- is_paginated = bool(self.request.GET.get('after'))+ prev_url = None+ if has_prev and rows:+ params = self.request.GET.copy()+ params.pop('after', None)+ params['before'] = str(rows[0].id)+ prev_url = f'?{params.urlencode()}'++ is_paginated = self._cursor_mode != 'first'first_url = Noneif is_paginated:params = self.request.GET.copy()params.pop('after', None)+ params.pop('before', None)first_url = f'?{params.urlencode()}' if params else '?'- context['ingredients_list'] = ingredients+ context['ingredients_list'] = rowscontext['has_next'] = has_next+ context['has_prev'] = has_prevcontext['next_url'] = next_url+ context['prev_url'] = prev_urlcontext['first_url'] = first_urlcontext['is_paginated'] = is_paginateddiff --git a/wger/urls.py b/wger/urls.pyindex 415962da2..315ba5297 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -209,6 +209,11 @@ router.register(r'ingredient', nutrition_api_views.IngredientViewSet, basename='router.register(r'ingredientinfo', nutrition_api_views.IngredientInfoViewSet, basename='api-ingredientinfo')+router.register(+ r'ingredient-sync',+ nutrition_api_views.IngredientSyncViewSet,+ basename='api-ingredient-sync',+)router.register(r'ingredientweightunit',nutrition_api_views.IngredientWeightUnitViewSet,diff --git a/wger/utils/cache.py b/wger/utils/cache.pyindex e214c602e..9d185a337 100644--- a/wger/utils/cache.py+++ b/wger/utils/cache.py@@ -109,9 +109,5 @@ class CacheKeyMapper:def slot_entry_configs_key(cls, pk: int):return f'slot-entry-configs-{pk}'- @classmethod- def ingredient_celery_sync(cls, page: int):- return f'ingredients-sync-page-{page}'-cache_mapper = CacheKeyMapper()diff --git a/wger/utils/validators.py b/wger/utils/validators.pyindex 15170959e..8e848f76f 100644--- a/wger/utils/validators.py+++ b/wger/utils/validators.py@@ -1,5 +1,9 @@# Djangofrom django.core.exceptions import ValidationError+from django.utils.dateparse import (+ parse_date,+ parse_datetime,+)from django.utils.translation import gettext_lazy as _# wger@@ -11,3 +15,18 @@ def validate_language_code(value):language = Language.objects.get(short_name=value)except Language.DoesNotExist:raise ValidationError(f'The language "{value}" does not exist in this wger database.')+++def validate_iso_date(value):+ """+ Accept a date or datetime in ISO-8601 form.++ Django's `parse_datetime` covers full ISO-8601 (with or without timezone),+ `parse_date` covers the common short form `YYYY-MM-DD`. Both return None+ on a non-matching string rather than raising, so we test them in order.+ """+ if parse_datetime(value) is None and parse_date(value) is None:+ raise ValidationError(+ f'"{value}" is not a valid ISO-8601 date or datetime '+ f'(e.g. "2026-04-01" or "2026-04-01T00:00:00Z").'+ )