Files
Evection/apps/articles/queries.py
T
ksmithandClaude Sonnet 5 abf4cef55b Cache sidebar unread counts for a short TTL (C3)
apps.core.context_processors.sidebar runs on every authenticated page
render and called unread_counts_by_feed, a join/group-by over the
user's whole article corpus, every single time — cost grew with the
archive's size regardless of which page was being viewed.

unread_counts_by_feed now caches its {feed_id: count} result per user
for 30 seconds (apps.core.cache_utils). The reader views that change
the current user's own read state (toggle_read, mark_all_read, viewing
an article) invalidate it immediately so the sidebar never visibly lags
behind the action that just caused it; other paths (rule-driven state
changes during background ingestion) aren't explicitly invalidated and
simply self-heal within the TTL, which is an acceptable tradeoff
already made elsewhere in this app (the stream's own "new articles"
banner polls on the same 30s cadence).

Also adds a global cache.clear() autouse fixture (conftest.py) — the
test CACHES backend (LocMemCache) lives in process memory and survives
Django's per-test DB rollback, so a cached count keyed by a user's pk
could otherwise leak into an unrelated later test reusing that pk.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 16:09:28 -06:00

73 lines
2.8 KiB
Python

from django.core.cache import cache
from django.db.models import Count
from apps.core.cache_utils import SIDEBAR_UNREAD_CACHE_TTL_SECONDS, sidebar_unread_cache_key
from .models import SAVED_TAG_NAME, STARRED_TAG_NAME, Article, ArticleTag, UserArticleState
def with_user_state(articles, user):
"""Annotates an iterable of Article instances with is_read/is_starred/
is_saved_for_later booleans for the given user, in two queries total
regardless of how many articles there are (no N+1). Starred/saved come
from ArticleTag against the pre-configured system tags, not a field on
UserArticleState — see Tag.is_system.
Accepts either a queryset or a plain list (search backends return
plain lists already ordered by relevance), materializing it either
way.
"""
articles = list(articles)
if not articles:
return articles
article_ids = [a.pk for a in articles]
states = {
state.article_id: state
for state in UserArticleState.objects.filter(user=user, article_id__in=article_ids)
}
starred_ids = set()
saved_ids = set()
tag_rows = ArticleTag.objects.filter(
user=user,
article_id__in=article_ids,
tag__is_system=True,
tag__name__in=[STARRED_TAG_NAME, SAVED_TAG_NAME],
).values_list("article_id", "tag__name")
for article_id, tag_name in tag_rows:
(starred_ids if tag_name == STARRED_TAG_NAME else saved_ids).add(article_id)
for article in articles:
state = states.get(article.pk)
article.is_read = state.is_read if state else False
article.is_starred = article.pk in starred_ids
article.is_saved_for_later = article.pk in saved_ids
return articles
def unread_counts_by_feed(user):
"""{feed_id: unread_count} for every feed the user subscribes to — used
by the sidebar's context processor, which runs on every authenticated
page render, so the underlying join/group-by over the user's whole
article corpus is cached for a short TTL rather than recomputed on
every single page view (C3). apps.core.cache_utils.
invalidate_sidebar_unread_cache is called wherever a request changes
the current user's own read state, so this is rarely visibly stale.
"""
cache_key = sidebar_unread_cache_key(user.pk)
counts = cache.get(cache_key)
if counts is not None:
return counts
rows = (
Article.objects.filter(feed__subscriptions__user=user)
.exclude(user_states__user=user, user_states__is_read=True)
.exclude(user_states__user=user, user_states__is_hidden=True)
.values("feed_id")
.annotate(unread=Count("id"))
)
counts = {row["feed_id"]: row["unread"] for row in rows}
cache.set(cache_key, counts, SIDEBAR_UNREAD_CACHE_TTL_SECONDS)
return counts