Skip to content
Merged
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
2 changes: 1 addition & 1 deletion architecture.html

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions architecture.json
Original file line number Diff line number Diff line change
Expand Up @@ -2675,7 +2675,7 @@
"Challenges": 15,
"Chat": 79,
"ChecklistTemplates": 5,
"Common": 33,
"Common": 34,
"Gamification": 26,
"Goals": 33,
"Habits": 74,
Expand Down Expand Up @@ -2884,10 +2884,10 @@
"Challenges": 14,
"Chat": 59,
"ChecklistTemplates": 9,
"Common": 160,
"Common": 161,
"Gamification": 33,
"Goals": 38,
"Habits": 80,
"Habits": 81,
"Marketing": 6,
"Notifications": 16,
"Profile": 38,
Expand Down Expand Up @@ -4111,6 +4111,8 @@
"testClass": "LogHabitCommandHandlerTests",
"file": "tests/Orbit.Application.Tests/Commands/Habits/LogHabitCommandHandlerTests.cs",
"references": [
"GetRetrospectiveQuery",
"GetRetrospectiveQueryHandler",
"Goal",
"Habit",
"HabitLog",
Expand Down
14 changes: 8 additions & 6 deletions src/Orbit.Application/Common/CacheInvalidationHelper.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using Microsoft.Extensions.Caching.Memory;
using Orbit.Application.Habits.Queries;

namespace Orbit.Application.Common;

public static class CacheInvalidationHelper
{
private static readonly string[] RetrospectivePeriods = ["week", "month", "quarter", "semester", "year"];
private static readonly int[] RetrospectiveWeekStartDays = [0, 1];
private static readonly string[] SummaryTimeBuckets = ["morning", "afternoon", "evening", "night", "timeless"];

public static void InvalidateSummaryCache(IMemoryCache cache, Guid userId, DateOnly today)
Expand All @@ -28,13 +30,13 @@ public static void InvalidateSummaryCache(IMemoryCache cache, Guid userId, DateO
/// </summary>
public static void InvalidateRetrospectiveCache(IMemoryCache cache, Guid userId, DateOnly today)
{
for (int i = -2; i <= 2; i++)
{
var date = today.AddDays(i);
foreach (var period in RetrospectivePeriods)
foreach (var period in RetrospectivePeriods)
foreach (var weekStartDay in RetrospectiveWeekStartDays)
{
var (dateFrom, _) = RetrospectivePeriodRange.Resolve(period, today, weekStartDay);
foreach (var lang in AppConstants.SupportedLanguages)
cache.Remove($"retro:{userId}:{period}:{date}:{lang}");
}
cache.Remove(RetrospectiveCacheKey.Build(userId, period, dateFrom, lang));
}
}

/// <summary>
Expand Down
12 changes: 12 additions & 0 deletions src/Orbit.Application/Common/RetrospectiveCacheKey.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Orbit.Application.Common;

public static class RetrospectiveCacheKey
{
public static string Build(Guid userId, string period, DateOnly dateFrom, string language)
{
var normalizedPeriod = period.ToLowerInvariant();
var normalizedLanguage = string.IsNullOrEmpty(language) ? "en" : language;

return $"retro:v2:{userId}:{normalizedPeriod}:{dateFrom}:{normalizedLanguage}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ public async Task<Result<RetrospectiveResponse>> Handle(
if (gateCheck.IsFailure)
return gateCheck.PropagateError<RetrospectiveResponse>();

var cacheKey = $"retro:v2:{request.UserId}:{request.Period}:{request.DateFrom}:{request.Language}";
var cacheKey = RetrospectiveCacheKey.Build(
request.UserId,
request.Period,
request.DateFrom,
request.Language);

if (cache.TryGetValue(cacheKey, out RetrospectiveResponse? cached) && cached is not null)
return Result.Success(cached with { FromCache = true });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Orbit.Application.Challenges.Services;
using Orbit.Application.Common;
using Orbit.Application.Habits.Commands;
using Orbit.Application.Habits.Queries;
using Orbit.Domain.Common;
using Orbit.Domain.Entities;
using Orbit.Domain.Enums;
using Orbit.Domain.Interfaces;
Expand Down Expand Up @@ -210,6 +213,56 @@ public async Task Handle_InvalidatesSummaryCache()
_cache.TryGetValue(cacheKey, out _).Should().BeFalse();
}

[Fact]
public async Task Handle_LogInvalidatesCachedRetrospective_SoNextReadIsFresh()
{
var habit = CreateTestHabit();
_habitRepo.FindOneTrackedAsync(
Arg.Any<Expression<Func<Habit, bool>>>(),
Arg.Any<Func<IQueryable<Habit>, IQueryable<Habit>>?>(),
Arg.Any<CancellationToken>())
.Returns(habit);
_habitRepo.FindAsync(
Arg.Any<Expression<Func<Habit, bool>>>(),
Arg.Any<Func<IQueryable<Habit>, IQueryable<Habit>>?>(),
Arg.Any<CancellationToken>())
.Returns(_ => new[] { habit });

var (dateFrom, dateTo) = RetrospectivePeriodRange.Resolve("week", Today, weekStartDay: 1);
var cacheKey = RetrospectiveCacheKey.Build(UserId, "week", dateFrom, "en");
var staleNarrative = new RetrospectiveNarrative("Stale", "", "", "");
var emptyMetrics = new RetrospectiveMetrics(0, 0, 0, 0, 0, 0, 0, 0, new int[7], [], []);
_cache.Set(cacheKey, new RetrospectiveResponse("week", emptyMetrics, staleNarrative, FromCache: false));

var payGate = Substitute.For<IPayGateService>();
var retrospectiveService = Substitute.For<IRetrospectiveService>();
var freshNarrative = new RetrospectiveNarrative("Fresh", "", "", "");
payGate.CanUseRetrospective(UserId, Arg.Any<CancellationToken>()).Returns(Result.Success());
retrospectiveService.GenerateRetrospectiveAsync(
Arg.Any<List<Habit>>(),
dateFrom,
dateTo,
"week",
"en",
Arg.Any<CancellationToken>())
.Returns(Result.Success(freshNarrative));
var queryHandler = new GetRetrospectiveQueryHandler(
_habitRepo,
payGate,
retrospectiveService,
_userStreakService,
_cache);

await _handler.Handle(new LogHabitCommand(UserId, habit.Id), CancellationToken.None);
var result = await queryHandler.Handle(
new GetRetrospectiveQuery(UserId, dateFrom, dateTo, "week", "en"),
CancellationToken.None);

result.IsSuccess.Should().BeTrue();
result.Value.FromCache.Should().BeFalse();
result.Value.Narrative.Should().Be(freshNarrative);
}

[Fact]
public async Task Handle_FutureDateOnRecurring_ReturnsFailure()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
using FluentAssertions;
using Microsoft.Extensions.Caching.Memory;
using Orbit.Application.Common;
using Orbit.Application.Habits.Queries;

namespace Orbit.Application.Tests.Common;

public class CacheInvalidationHelperTests
{
public static TheoryData<string, string, int> RetrospectiveKeyCases
{
get
{
var cases = new TheoryData<string, string, int>();
foreach (var period in new[] { "week", "month", "quarter", "semester", "year" })
foreach (var language in AppConstants.SupportedLanguages)
foreach (var weekStartDay in new[] { 0, 1 })
cases.Add(period, language, weekStartDay);

return cases;
}
}

[Fact]
public void InvalidateSummaryCache_RemovesSummaryKeys()
{
Expand Down Expand Up @@ -62,14 +77,44 @@ public void InvalidateSummaryCache_UsesSuppliedTodayNotUtc()
cache.TryGetValue(utcKey, out _).Should().BeTrue("an unrelated UTC-dated key stays untouched");
}

[Fact]
public void InvalidateRetrospectiveCache_RemovesKeysAroundSuppliedToday()
[Theory]
[MemberData(nameof(RetrospectiveKeyCases))]
public void InvalidateRetrospectiveCache_RemovesSharedKey_AndPreservesUnrelatedKeys(
string period,
string language,
int weekStartDay)
{
var cache = new MemoryCache(new MemoryCacheOptions());
var userId = Guid.NewGuid();
var today = new DateOnly(2020, 1, 15);
var (dateFrom, _) = RetrospectivePeriodRange.Resolve(period, today, weekStartDay);
var targetKey = RetrospectiveCacheKey.Build(userId, period, dateFrom, language);
var otherUserKey = RetrospectiveCacheKey.Build(Guid.NewGuid(), period, dateFrom, language);
var otherWindowKey = RetrospectiveCacheKey.Build(userId, period, dateFrom.AddYears(-1), language);
cache.Set(targetKey, "target");
cache.Set(otherUserKey, "other-user");
cache.Set(otherWindowKey, "other-window");

CacheInvalidationHelper.InvalidateRetrospectiveCache(cache, userId, today);

cache.TryGetValue(targetKey, out _).Should().BeFalse();
cache.TryGetValue(otherUserKey, out _).Should().BeTrue();
cache.TryGetValue(otherWindowKey, out _).Should().BeTrue();
}

[Theory]
[InlineData("Week", "en")]
[InlineData("week", "")]
public void InvalidateRetrospectiveCache_RemovesAcceptedNoncanonicalKeys(
string period,
string language)
{
var cache = new MemoryCache(new MemoryCacheOptions());
var userId = Guid.NewGuid();
var today = new DateOnly(2020, 1, 15);
var key = $"retro:{userId}:week:{today}:en";
cache.Set(key, "cached");
var (dateFrom, _) = RetrospectivePeriodRange.Resolve(period, today, weekStartDay: 1);
var key = RetrospectiveCacheKey.Build(userId, period, dateFrom, language);
cache.Set(key, "target");

CacheInvalidationHelper.InvalidateRetrospectiveCache(cache, userId, today);

Expand Down
Loading