From 6ed614b4f440691005124df1432f550220eec32c Mon Sep 17 00:00:00 2001 From: Sebastian Stehle Date: Wed, 30 Sep 2026 23:17:20 +0200 Subject: [PATCH] Query cache (#1343) * Query cache * Simplified * Final fixes --- .../Assets/AssetQueryCacheOptions.cs | 13 + .../Assets/Queries/AssetEnricher.cs | 74 +-- .../Queries/CachingAssetQueryService.cs | 212 ++++++++ .../Assets/Queries/IAssetEnricher.cs | 3 + .../Assets/Queries/IAssetEnricherStep.cs | 2 + .../Assets/Queries/Steps/EnrichForCaching.cs | 2 + .../Contents/ContentQueryCacheOptions.cs | 13 + .../Queries/CachingContentQueryService.cs | 235 +++++++++ .../Contents/Queries/ContentEnricher.cs | 93 ++-- .../Contents/Queries/IContentEnricher.cs | 3 + .../Contents/Queries/IContentEnricherStep.cs | 3 + .../Queries/Steps/EnrichForCaching.cs | 2 + .../Squidex.Domain.Apps.Entities/Context.cs | 19 +- .../ContextHeaders.cs | 11 + .../Caching/CacheGenerations.cs | 103 ++++ .../Caching/CacheGenerationsOptions.cs | 13 + .../Caching/ICacheGenerations.cs | 16 + .../Caching/JsonHybridCacheSerializer.cs | 27 + .../JsonHybridCacheSerializerFactory.cs | 21 + .../Queries/CompareOperatorTypeConverter.cs | 2 +- .../Queries/Json/JsonFilterSurrogate.cs | 20 +- .../src/Squidex.Web/Pipeline/ContextFilter.cs | 14 + .../Schemas/SchemaContentsController.cs | 20 +- .../Squidex/Config/Domain/AssetServices.cs | 19 +- .../Squidex/Config/Domain/ContentsServices.cs | 19 +- .../Config/Domain/InfrastructureServices.cs | 10 + backend/src/Squidex/Squidex.csproj | 1 + backend/src/Squidex/appsettings.json | 19 + .../Assets/Queries/AssetEnricherTests.cs | 33 ++ .../Queries/CachingAssetQueryServiceTests.cs | 360 +++++++++++++ .../CachingContentQueryServiceTests.cs | 479 ++++++++++++++++++ .../Contents/Queries/ContentEnricherTests.cs | 33 ++ .../ContextHeadersTests.cs | 35 ++ .../Squidex.Domain.Apps.Entities.Tests.csproj | 1 + .../Caching/CacheGenerationsTests.cs | 141 ++++++ .../Caching/JsonHybridCacheSerializerTests.cs | 50 ++ .../Queries/QueryJsonTests.cs | 30 ++ .../Pipeline/ContextFilterTests.cs | 78 +++ 38 files changed, 2136 insertions(+), 93 deletions(-) create mode 100644 backend/src/Squidex.Domain.Apps.Entities/Assets/AssetQueryCacheOptions.cs create mode 100644 backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/CachingAssetQueryService.cs create mode 100644 backend/src/Squidex.Domain.Apps.Entities/Contents/ContentQueryCacheOptions.cs create mode 100644 backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/CachingContentQueryService.cs create mode 100644 backend/src/Squidex.Infrastructure/Caching/CacheGenerations.cs create mode 100644 backend/src/Squidex.Infrastructure/Caching/CacheGenerationsOptions.cs create mode 100644 backend/src/Squidex.Infrastructure/Caching/ICacheGenerations.cs create mode 100644 backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializer.cs create mode 100644 backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializerFactory.cs create mode 100644 backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/CachingAssetQueryServiceTests.cs create mode 100644 backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/CachingContentQueryServiceTests.cs create mode 100644 backend/tests/Squidex.Infrastructure.Tests/Caching/CacheGenerationsTests.cs create mode 100644 backend/tests/Squidex.Infrastructure.Tests/Caching/JsonHybridCacheSerializerTests.cs create mode 100644 backend/tests/Squidex.Web.Tests/Pipeline/ContextFilterTests.cs diff --git a/backend/src/Squidex.Domain.Apps.Entities/Assets/AssetQueryCacheOptions.cs b/backend/src/Squidex.Domain.Apps.Entities/Assets/AssetQueryCacheOptions.cs new file mode 100644 index 000000000..1ee6ec944 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Assets/AssetQueryCacheOptions.cs @@ -0,0 +1,13 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +namespace Squidex.Domain.Apps.Entities.Assets; + +public sealed class AssetQueryCacheOptions +{ + public TimeSpan CacheDuration { get; set; } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/AssetEnricher.cs b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/AssetEnricher.cs index 62fbda5b2..4ef2f6537 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/AssetEnricher.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/AssetEnricher.cs @@ -1,4 +1,4 @@ -// ========================================================================== +// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) @@ -32,44 +32,54 @@ public sealed class AssetEnricher(IEnumerable steps) : IAsse using (var activity = Telemetry.Activities.StartActivity("AssetEnricher/EnrichAsync")) { - var results = new List(); + var results = assets.Select(x => SimpleMapper.Map(x, new EnrichedAsset())).ToList(); - if (context.App != null) - { - foreach (var step in steps) - { - await step.EnrichAsync(context, ct); - } - } + await RunStepsAsync(steps, results, context, ct); - if (!assets.Any()) - { - return results; - } + activity?.SetTag("numItems", results.Count); - foreach (var asset in assets) - { - var result = SimpleMapper.Map(asset, new EnrichedAsset()); + return results; + } + } - results.Add(result); - } + public async Task EnrichCachedAsync(IReadOnlyList assets, Context context, + CancellationToken ct) + { + Guard.NotNull(assets); + Guard.NotNull(context); - if (context.App != null) - { - foreach (var step in steps) - { - ct.ThrowIfCancellationRequested(); - - using (Telemetry.Activities.StartActivity(step.ToString()!)) - { - await step.EnrichAsync(context, results, ct); - } - } - } + using (Telemetry.Activities.StartActivity("AssetEnricher/EnrichCachedAsync")) + { + await RunStepsAsync(steps.Where(x => x.RunOnCachedResults), assets, context, ct); + } + } - activity?.SetTag("numItems", results.Count); + private static async Task RunStepsAsync(IEnumerable stepsToRun, IReadOnlyList assets, Context context, + CancellationToken ct) + { + if (context.App == null) + { + return; + } - return results; + foreach (var step in stepsToRun) + { + await step.EnrichAsync(context, ct); + } + + if (assets.Count == 0) + { + return; + } + + foreach (var step in stepsToRun) + { + ct.ThrowIfCancellationRequested(); + + using (Telemetry.Activities.StartActivity(step.ToString()!)) + { + await step.EnrichAsync(context, assets, ct); + } } } } diff --git a/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/CachingAssetQueryService.cs b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/CachingAssetQueryService.cs new file mode 100644 index 000000000..254487531 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/CachingAssetQueryService.cs @@ -0,0 +1,212 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Security.Cryptography; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Squidex.Domain.Apps.Core.Assets; +using Squidex.Domain.Apps.Entities.Assets.Commands; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Caching; +using Squidex.Infrastructure.Commands; +using Squidex.Infrastructure.Json; + +#pragma warning disable RECS0082 // Parameter has the same name as a member and hides it +#pragma warning disable SA1313 // Parameter names should begin with lower-case letter + +namespace Squidex.Domain.Apps.Entities.Assets.Queries; + +public sealed class CachingAssetQueryService( + IAssetQueryService inner, + HybridCache cache, + ICacheGenerations generations, + IAssetEnricher assetEnricher, + IJsonSerializer serializer, + IOptions options, + ILogger log) + : IAssetQueryService, ICommandMiddleware +{ + private sealed record CachedAssets(long Total, EnrichedAsset[] Items); + + private sealed record CacheKey(string Generation, long AppVersion, DomainId? ParentId, IReadOnlyDictionary Headers, Q Query); + + private readonly HybridCacheEntryOptions entryOptions = new HybridCacheEntryOptions + { + Expiration = options.Value.CacheDuration, + // Only the distributed cache is used, because the local caches of the other nodes cannot be invalidated. + Flags = HybridCacheEntryFlags.DisableLocalCache, + }; + + public async Task HandleAsync(CommandContext context, NextDelegate next, + CancellationToken ct) + { + await next(context, ct); + + if (context.Command is not IAppCommand appCommand || !ChangesAssets(appCommand)) + { + return; + } + + static bool ChangesAssets(ICommand command) + { + // Queries remove references to deleted assets. + return command is AssetCommand; + } + + // A new generation changes all cache keys of the app on all nodes. + generations.Reset(GenerationKey(appCommand.AppId.Id)); + } + + public async Task> QueryAsync(Context context, DomainId? parentId, Q q, + CancellationToken ct = default) + { + Guard.NotNull(context); + + if (q == null || !CanCache(context) || !CanCache(q)) + { + return await inner.QueryAsync(context, parentId, q!, ct); + } + + var key = await CreateKeyAsync(context, parentId, q, ct); + if (key == null) + { + return await inner.QueryAsync(context, parentId, q, ct); + } + + var isQueried = false; + + var cached = await cache.GetOrCreateAsync(key, async ct => + { + isQueried = true; + + var assets = await inner.QueryAsync(context, parentId, q, ct); + + return new CachedAssets(assets.Total, assets.ToArray()); + }, entryOptions, cancellationToken: ct); + + // Results from the cache have skipped the enrichment steps, which only affect the current request. + if (!isQueried) + { + await assetEnricher.EnrichCachedAsync(cached.Items, context, ct); + } + + return ResultList.Create(cached.Total, cached.Items); + } + + public Task FindAsync(Context context, DomainId id, bool allowDeleted = false, long version = EtagVersion.Any, + CancellationToken ct = default) + { + return inner.FindAsync(context, id, allowDeleted, version, ct); + } + + public Task FindBySlugAsync(Context context, string slug, bool allowDeleted = false, + CancellationToken ct = default) + { + return inner.FindBySlugAsync(context, slug, allowDeleted, ct); + } + + public Task> QueryAssetFoldersAsync(Context context, DomainId? parentId, + CancellationToken ct = default) + { + return inner.QueryAssetFoldersAsync(context, parentId, ct); + } + + public Task> FindAssetFolderAsync(DomainId appId, DomainId id, + CancellationToken ct = default) + { + return inner.FindAssetFolderAsync(appId, id, ct); + } + + public Task FindByHashAsync(Context context, string hash, string fileName, long fileSize, + CancellationToken ct = default) + { + return inner.FindByHashAsync(context, hash, fileName, fileSize, ct); + } + + public Task FindGlobalAsync(Context context, DomainId id, + CancellationToken ct = default) + { + return inner.FindGlobalAsync(context, id, ct); + } + + private static string GenerationKey(DomainId appId) + { + return $"assets/{appId}"; + } + + private async Task CreateKeyAsync(Context context, DomainId? parentId, Q q, + CancellationToken ct) + { + string generation; + try + { + generation = await generations.GetAsync(GenerationKey(context.App.Id), ct); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Without the generation the cache cannot be used, but the query must not fail because of it. + log.LogWarning(ex, "Failed to read asset query cache generation for app {appId}.", context.App.Id); + return null; + } + + var keyObj = new CacheKey(generation, context.App.Version, parentId, context.Headers, q); + var keyHash = SHA256.HashData(serializer.SerializeToBytes(keyObj)); + + return $"assets/{context.App.Id}/{Convert.ToHexString(keyHash)}"; + } + + private static bool CanCache(Context context) + { + // Clients can bypass the cache, for example with the Cache-Control header. + if (context.NoQueryCache()) + { + return false; + } + + // The UI always needs the latest state. + if (context.IsFrontendClient) + { + return false; + } + + // Scripts can depend on the user or on the current time. + if (!context.NoScripting() && HasQueryScripts(context)) + { + return false; + } + + return true; + } + + private static bool CanCache(Q q) + { + // The parsed query is usually only set by the query parser and cannot be serialized for the cache key. + if (!string.IsNullOrEmpty(q.Query?.ToString())) + { + return false; + } + + // Random queries should return a different result for each call. + if (q.JsonQuery?.Random > 0) + { + return false; + } + + return !ContainsRandom(q.QueryAsJson) && !ContainsRandom(q.QueryAsOdata); + } + + private static bool ContainsRandom(string? query) + { + return query?.Contains("random", StringComparison.OrdinalIgnoreCase) == true; + } + + private static bool HasQueryScripts(Context context) + { + return !string.IsNullOrWhiteSpace(context.App.AssetScripts.Query) || !string.IsNullOrWhiteSpace(context.App.AssetScripts.QueryPre); + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricher.cs b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricher.cs index 81415938a..3eb91c9f7 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricher.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricher.cs @@ -16,4 +16,7 @@ public interface IAssetEnricher Task> EnrichAsync(IEnumerable assets, Context context, CancellationToken ct); + + Task EnrichCachedAsync(IReadOnlyList assets, Context context, + CancellationToken ct); } diff --git a/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricherStep.cs b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricherStep.cs index f7f251394..5f0259f34 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricherStep.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricherStep.cs @@ -9,6 +9,8 @@ namespace Squidex.Domain.Apps.Entities.Assets.Queries; public interface IAssetEnricherStep { + bool RunOnCachedResults => false; + Task EnrichAsync(Context context, IEnumerable assets, CancellationToken ct); diff --git a/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/Steps/EnrichForCaching.cs b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/Steps/EnrichForCaching.cs index 7c2650098..b5fb7a631 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/Steps/EnrichForCaching.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/Steps/EnrichForCaching.cs @@ -12,6 +12,8 @@ namespace Squidex.Domain.Apps.Entities.Assets.Queries.Steps; public sealed class EnrichForCaching(IRequestCache requestCache) : IAssetEnricherStep { + public bool RunOnCachedResults => true; + public Task EnrichAsync(Context context, CancellationToken ct) { diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/ContentQueryCacheOptions.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/ContentQueryCacheOptions.cs new file mode 100644 index 000000000..0e17791f2 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/ContentQueryCacheOptions.cs @@ -0,0 +1,13 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +namespace Squidex.Domain.Apps.Entities.Contents; + +public sealed class ContentQueryCacheOptions +{ + public TimeSpan CacheDuration { get; set; } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/CachingContentQueryService.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/CachingContentQueryService.cs new file mode 100644 index 000000000..f96822403 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/CachingContentQueryService.cs @@ -0,0 +1,235 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Security.Cryptography; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Domain.Apps.Entities.Assets.Commands; +using Squidex.Domain.Apps.Entities.Contents.Commands; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Caching; +using Squidex.Infrastructure.Commands; +using Squidex.Infrastructure.Json; +using Squidex.Shared; + +#pragma warning disable RECS0082 // Parameter has the same name as a member and hides it +#pragma warning disable SA1313 // Parameter names should begin with lower-case letter + +namespace Squidex.Domain.Apps.Entities.Contents.Queries; + +public sealed class CachingContentQueryService( + IContentQueryService inner, + HybridCache cache, + ICacheGenerations generations, + IContentEnricher contentEnricher, + IJsonSerializer serializer, + IOptions options, + ILogger log) + : IContentQueryService, ICommandMiddleware +{ + private sealed record CachedContents(long Total, EnrichedContent[] Items); + + private sealed record CacheKey(string Generation, long AppVersion, DomainId SchemaId, long SchemaVersion, IReadOnlyDictionary Headers, Q Query); + + // Only the distributed cache is used, because the local caches of the other nodes cannot be invalidated. + private readonly HybridCacheEntryOptions entryOptions = new HybridCacheEntryOptions + { + Expiration = options.Value.CacheDuration, + Flags = HybridCacheEntryFlags.DisableLocalCache, + }; + + public async Task HandleAsync(CommandContext context, NextDelegate next, + CancellationToken ct) + { + await next(context, ct); + + if (context.Command is not IAppCommand appCommand || !ChangesContents(appCommand)) + { + return; + } + + static bool ChangesContents(ICommand command) + { + // Queries remove references to deleted assets. + return command is ContentCommand and not ValidateContent and not EnrichContentDefaults or DeleteAsset; + } + + // A new generation changes all cache keys of the app on all nodes. + generations.Reset(GenerationKey(appCommand.AppId.Id)); + } + + public IAsyncEnumerable StreamAsync(Context context, string schemaIdOrName, int skip, + CancellationToken ct = default) + { + return inner.StreamAsync(context, schemaIdOrName, skip, ct); + } + + public Task> QueryAsync(Context context, Q q, + CancellationToken ct = default) + { + // Queries over all schemas depend on the schema permissions of the user, therefore they are not cached. + return inner.QueryAsync(context, q, ct); + } + + public async Task> QueryAsync(Context context, string schemaIdOrName, Q q, + CancellationToken ct = default) + { + Guard.NotNull(context); + + if (q == null) + { + return await inner.QueryAsync(context, schemaIdOrName, q!, ct); + } + + // Also validates the permissions, which must never be skipped by a cache hit. + var schema = await inner.GetSchemaOrThrowAsync(context, schemaIdOrName, ct); + if (!CanCache(context, schema) || !CanCache(q)) + { + return await inner.QueryAsync(context, schemaIdOrName, q, ct); + } + + var key = await CreateKeyAsync(context, schema, q, ct); + if (key == null) + { + return await inner.QueryAsync(context, schemaIdOrName, q, ct); + } + + var isQueried = false; + + var cached = await cache.GetOrCreateAsync(key, async ct => + { + isQueried = true; + + var contents = await inner.QueryAsync(context, schemaIdOrName, q, ct); + + return new CachedContents(contents.Total, contents.ToArray()); + }, entryOptions, cancellationToken: ct); + + // Results from the cache have skipped the enrichment steps, which only affect the current request. + if (!isQueried) + { + await contentEnricher.EnrichCachedAsync(cached.Items, context, ct); + } + + return ResultList.Create(cached.Total, cached.Items); + } + + public Task FindAsync(Context context, string schemaIdOrName, DomainId id, long version = EtagVersion.Any, + CancellationToken ct = default) + { + // Single contents are loaded by ID, which is not faster with the distributed cache. + return inner.FindAsync(context, schemaIdOrName, id, version, ct); + } + + public Task GetSchemaOrThrowAsync(Context context, string schemaIdOrName, + CancellationToken ct = default) + { + return inner.GetSchemaOrThrowAsync(context, schemaIdOrName, ct); + } + + public Task GetSchemaAsync(Context context, string schemaIdOrName, + CancellationToken ct = default) + { + return inner.GetSchemaAsync(context, schemaIdOrName, ct); + } + + private async Task CreateKeyAsync(Context context, Schema schema, Q q, + CancellationToken ct) + { + string generation; + try + { + generation = await generations.GetAsync(GenerationKey(context.App.Id), ct); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Without the generation the cache cannot be used, but the query must not fail because of it. + log.LogWarning(ex, "Failed to read content query cache generation for app {appId}.", context.App.Id); + return null; + } + + var keyObj = new CacheKey(generation, context.App.Version, schema.Id, schema.Version, context.Headers, q); + var keyHash = SHA256.HashData(serializer.SerializeToBytes(keyObj)); + + return $"contents/{context.App.Id}/{Convert.ToHexString(keyHash)}"; + } + + private static bool CanCache(Context context, Schema schema) + { + // Clients can bypass the cache, for example with the Cache-Control header. + if (context.NoQueryCache()) + { + return false; + } + + // Only published content is invalidated reliably and the UI always needs the latest state. + if (context.IsFrontendClient || context.Scope() != SearchScope.Published) + { + return false; + } + + // The workflow information depends on the current user. + if (context.ResolveFlow()) + { + return false; + } + + // With the read.own permission the result depends on the current user. + if (!context.Allows(PermissionIds.AppContentsRead, schema.Name)) + { + return false; + } + + // Scripts can depend on the user or on the current time. + if (!context.NoScripting() && HasQueryScripts(schema)) + { + return false; + } + + return true; + } + + private static bool CanCache(Q q) + { + // The schedule queries are made for background processes. + if (q.ScheduledFrom != null || q.ScheduledTo != null) + { + return false; + } + + // The parsed query is usually only set by the query parser and cannot be serialized for the cache key. + if (!string.IsNullOrEmpty(q.Query?.ToString())) + { + return false; + } + + // Random queries should return a different result for each call. + if (q.JsonQuery?.Random > 0) + { + return false; + } + + return !ContainsRandom(q.QueryAsJson) && !ContainsRandom(q.QueryAsOdata); + } + + private static string GenerationKey(DomainId appId) + { + return $"contents/{appId}"; + } + + private static bool ContainsRandom(string? query) + { + return query?.Contains("random", StringComparison.OrdinalIgnoreCase) == true; + } + + private static bool HasQueryScripts(Schema schema) + { + return !string.IsNullOrWhiteSpace(schema.Scripts.Query) || !string.IsNullOrWhiteSpace(schema.Scripts.QueryPre); + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs index 0eebb7c48..03636e3f7 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs @@ -1,4 +1,4 @@ -// ========================================================================== +// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) @@ -33,6 +33,18 @@ public sealed class ContentEnricher(IEnumerable steps, IAp return EnrichInternalAsync(contents, false, context, ct); } + public async Task EnrichCachedAsync(IReadOnlyList contents, Context context, + CancellationToken ct) + { + Guard.NotNull(contents); + Guard.NotNull(context); + + using (Telemetry.Activities.StartActivity("ContentEnricher/EnrichCachedAsync")) + { + await RunStepsAsync(steps.Where(x => x.RunOnCachedResults), contents, context, ct); + } + } + private async Task> EnrichInternalAsync(IEnumerable contents, bool cloneData, Context context, CancellationToken ct) { @@ -40,19 +52,6 @@ public sealed class ContentEnricher(IEnumerable steps, IAp { var results = new List(); - if (context.App != null) - { - foreach (var step in steps) - { - await step.EnrichAsync(context, ct); - } - } - - if (!contents.Any()) - { - return results; - } - foreach (var content in contents) { var result = SimpleMapper.Map(content, new EnrichedContent()); @@ -69,37 +68,55 @@ public sealed class ContentEnricher(IEnumerable steps, IAp results.Add(result); } - if (context.App != null) - { - var schemaCache = new Dictionary>(); + await RunStepsAsync(steps, results, context, ct); - Task<(Schema, ResolvedComponents)> GetSchema(DomainId id) - { - return schemaCache.GetOrAdd(id, async x => - { - var schema = await appProvider.GetSchemaAsync(context.App.Id, x, false, ct) - ?? throw new DomainObjectNotFoundException(x.ToString()); + activity?.SetTag("numItems", results.Count); - var components = await appProvider.GetComponentsAsync(schema, ct); + return results; + } + } - return (schema, components); - }); - } + private async Task RunStepsAsync(IEnumerable stepsToRun, IReadOnlyList contents, Context context, + CancellationToken ct) + { + if (context.App == null) + { + return; + } - foreach (var step in steps) - { - ct.ThrowIfCancellationRequested(); + foreach (var step in stepsToRun) + { + await step.EnrichAsync(context, ct); + } - using (Telemetry.Activities.StartActivity(step.ToString()!)) - { - await step.EnrichAsync(context, results, GetSchema, ct); - } - } - } + if (contents.Count == 0) + { + return; + } - activity?.SetTag("numItems", results.Count); + var schemaCache = new Dictionary>(); - return results; + Task<(Schema, ResolvedComponents)> GetSchema(DomainId id) + { + return schemaCache.GetOrAdd(id, async x => + { + var schema = await appProvider.GetSchemaAsync(context.App.Id, x, false, ct) + ?? throw new DomainObjectNotFoundException(x.ToString()); + + var components = await appProvider.GetComponentsAsync(schema, ct); + + return (schema, components); + }); + } + + foreach (var step in stepsToRun) + { + ct.ThrowIfCancellationRequested(); + + using (Telemetry.Activities.StartActivity(step.ToString()!)) + { + await step.EnrichAsync(context, contents, GetSchema, ct); + } } } } diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricher.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricher.cs index 71d664d70..31996f62f 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricher.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricher.cs @@ -16,4 +16,7 @@ public interface IContentEnricher Task> EnrichAsync(IEnumerable contents, Context context, CancellationToken ct); + + Task EnrichCachedAsync(IReadOnlyList contents, Context context, + CancellationToken ct); } diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricherStep.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricherStep.cs index 19be75461..1dbe0cadb 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricherStep.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricherStep.cs @@ -16,6 +16,9 @@ public delegate Task<(Schema Schema, ResolvedComponents Components)> ProvideSche public interface IContentEnricherStep { + // Steps that do not change the contents, but only the current request, must also run for cached results. + bool RunOnCachedResults => false; + Task EnrichAsync(Context context, IEnumerable contents, ProvideSchema schemas, CancellationToken ct); diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/Steps/EnrichForCaching.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/Steps/EnrichForCaching.cs index 753185b61..f7ed20a97 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/Steps/EnrichForCaching.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/Steps/EnrichForCaching.cs @@ -11,6 +11,8 @@ namespace Squidex.Domain.Apps.Entities.Contents.Queries.Steps; public sealed class EnrichForCaching(IRequestCache requestCache) : IContentEnricherStep { + public bool RunOnCachedResults => true; + public Task EnrichAsync(Context context, CancellationToken ct) { diff --git a/backend/src/Squidex.Domain.Apps.Entities/Context.cs b/backend/src/Squidex.Domain.Apps.Entities/Context.cs index 7d31b40cc..d80da35f5 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Context.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Context.cs @@ -20,7 +20,7 @@ namespace Squidex.Domain.Apps.Entities; public sealed class Context { - private static readonly IReadOnlyDictionary EmptyHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly SortedDictionary EmptyHeaders = new SortedDictionary(StringComparer.OrdinalIgnoreCase); private static readonly char[] Separators = [',', ';']; // Splitting a header is not free and the same headers are read several times per request, for @@ -29,7 +29,10 @@ public sealed class Context // parsed values never have to be invalidated. private readonly ConcurrentDictionary headerValues = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - public IReadOnlyDictionary Headers { get; } + // The headers are sorted, so that they can be serialized to stable cache keys. + private readonly SortedDictionary headers; + + public IReadOnlyDictionary Headers => headers; public ClaimsPermissions UserPermissions { get; } @@ -49,7 +52,7 @@ public sealed class Context App app, ClaimsPrincipal userPrincipal, ClaimsPermissions userPermissions, - IReadOnlyDictionary headers) + SortedDictionary headers) { App = app; @@ -58,7 +61,7 @@ public sealed class Context IsFrontendClient = userPrincipal.IsInClient(DefaultClients.Frontend); - Headers = headers; + this.headers = headers; } public static Context Anonymous(App app) @@ -105,7 +108,7 @@ public sealed class Context private sealed class HeaderBuilder(Context context) : ICloneBuilder { - private Dictionary? headers; + private SortedDictionary? headers; public Context Build() { @@ -119,20 +122,20 @@ public sealed class Context public void Remove(string key) { - headers ??= new Dictionary(context.Headers, StringComparer.OrdinalIgnoreCase); + headers ??= new SortedDictionary(context.headers, StringComparer.OrdinalIgnoreCase); headers.Remove(key); } public void SetHeader(string key, string value) { - headers ??= new Dictionary(context.Headers, StringComparer.OrdinalIgnoreCase); + headers ??= new SortedDictionary(context.headers, StringComparer.OrdinalIgnoreCase); headers[key] = value; } } public Context WithApp(App app) { - return new Context(app, UserPrincipal, UserPermissions, Headers); + return new Context(app, UserPrincipal, UserPermissions, headers); } public Context Clone(Action action) diff --git a/backend/src/Squidex.Domain.Apps.Entities/ContextHeaders.cs b/backend/src/Squidex.Domain.Apps.Entities/ContextHeaders.cs index 5c2e4f9b6..3fa84204e 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/ContextHeaders.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/ContextHeaders.cs @@ -13,6 +13,7 @@ public static class ContextHeaders { public const string KeyBatchSize = "X-BatchSize"; public const string KeyNoCacheKeys = "X-NoCacheKeys"; + public const string KeyNoQueryCache = "X-NoQueryCache"; public const string KeyNoScripting = "X-NoScripting"; public const string KeyNoSlowTotal = "X-NoSlowTotal"; public const string KeyNoTotal = "X-NoTotal"; @@ -37,6 +38,16 @@ public static class ContextHeaders return builder.WithBoolean(KeyNoCacheKeys, value); } + public static bool NoQueryCache(this Context context) + { + return context.AsBoolean(KeyNoQueryCache); + } + + public static ICloneBuilder WithNoQueryCache(this ICloneBuilder builder, bool value = true) + { + return builder.WithBoolean(KeyNoQueryCache, value); + } + public static bool NoScripting(this Context context) { return context.AsBoolean(KeyNoScripting); diff --git a/backend/src/Squidex.Infrastructure/Caching/CacheGenerations.cs b/backend/src/Squidex.Infrastructure/Caching/CacheGenerations.cs new file mode 100644 index 000000000..0deff47dc --- /dev/null +++ b/backend/src/Squidex.Infrastructure/Caching/CacheGenerations.cs @@ -0,0 +1,103 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Collections.Concurrent; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Squidex.Hosting; +using Squidex.Infrastructure.Timers; + +namespace Squidex.Infrastructure.Caching; + +public sealed class CacheGenerations( + IDistributedCache cache, + IOptions options, + ILogger log) + : ICacheGenerations, IBackgroundProcess +{ + // Without an expiration the generation lives forever. A lost generation is replaced by a new + // random value, so that entries of an old generation can never be read again. + private static readonly DistributedCacheEntryOptions EntryOptions = new DistributedCacheEntryOptions(); + private readonly ConcurrentDictionary pendingKeys = new ConcurrentDictionary(); + private CompletionTimer? timer; + + public Task StartAsync( + CancellationToken ct) + { + timer = new CompletionTimer(options.Value.ResetInterval, FlushAsync); + + return Task.CompletedTask; + } + + public async Task StopAsync( + CancellationToken ct) + { + if (timer != null) + { + await timer.StopAsync(); + } + + // Do not lose the resets of the last interval. + await FlushAsync(ct); + } + + public async Task GetAsync(string key, + CancellationToken ct = default) + { + var generation = await cache.GetStringAsync(CacheKey(key), ct); + if (generation != null) + { + return generation; + } + + return await WriteAsync(key, ct); + } + + public void Reset(string key) + { + // Many resets in a short time, for example from bulk updates, are written once per interval. + pendingKeys[key] = true; + } + + public async Task FlushAsync( + CancellationToken ct) + { + foreach (var key in pendingKeys.Keys) + { + if (!pendingKeys.TryRemove(key, out _)) + { + continue; + } + + try + { + await WriteAsync(key, ct); + } + catch (Exception ex) + { + // The callers have changed data already and must not fail because of the cache. + log.LogWarning(ex, "Failed to reset cache generation {key}.", key); + } + } + } + + private async Task WriteAsync(string key, + CancellationToken ct) + { + var generation = Guid.NewGuid().ToString(); + + await cache.SetStringAsync(CacheKey(key), generation, EntryOptions, ct); + + return generation; + } + + private static string CacheKey(string key) + { + return $"generation/{key}"; + } +} diff --git a/backend/src/Squidex.Infrastructure/Caching/CacheGenerationsOptions.cs b/backend/src/Squidex.Infrastructure/Caching/CacheGenerationsOptions.cs new file mode 100644 index 000000000..d602e0ab5 --- /dev/null +++ b/backend/src/Squidex.Infrastructure/Caching/CacheGenerationsOptions.cs @@ -0,0 +1,13 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +namespace Squidex.Infrastructure.Caching; + +public sealed class CacheGenerationsOptions +{ + public TimeSpan ResetInterval { get; set; } = TimeSpan.FromSeconds(1); +} diff --git a/backend/src/Squidex.Infrastructure/Caching/ICacheGenerations.cs b/backend/src/Squidex.Infrastructure/Caching/ICacheGenerations.cs new file mode 100644 index 000000000..429223d05 --- /dev/null +++ b/backend/src/Squidex.Infrastructure/Caching/ICacheGenerations.cs @@ -0,0 +1,16 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +namespace Squidex.Infrastructure.Caching; + +public interface ICacheGenerations +{ + Task GetAsync(string key, + CancellationToken ct = default); + + void Reset(string key); +} diff --git a/backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializer.cs b/backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializer.cs new file mode 100644 index 000000000..bbbbe49cb --- /dev/null +++ b/backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializer.cs @@ -0,0 +1,27 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Buffers; +using Microsoft.Extensions.Caching.Hybrid; +using Squidex.Infrastructure.Json; + +namespace Squidex.Infrastructure.Caching; + +public sealed class JsonHybridCacheSerializer(IJsonSerializer serializer) : IHybridCacheSerializer +{ + public T Deserialize(ReadOnlySequence source) + { + using var stream = new MemoryStream(source.ToArray(), false); + + return serializer.Deserialize(stream); + } + + public void Serialize(T value, IBufferWriter target) + { + target.Write(serializer.SerializeToBytes(value)); + } +} diff --git a/backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializerFactory.cs b/backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializerFactory.cs new file mode 100644 index 000000000..f0a7bf80a --- /dev/null +++ b/backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializerFactory.cs @@ -0,0 +1,21 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Diagnostics.CodeAnalysis; +using Microsoft.Extensions.Caching.Hybrid; +using Squidex.Infrastructure.Json; + +namespace Squidex.Infrastructure.Caching; + +public sealed class JsonHybridCacheSerializerFactory(IJsonSerializer serializer) : IHybridCacheSerializerFactory +{ + public bool TryCreateSerializer([NotNullWhen(true)] out IHybridCacheSerializer? result) + { + result = new JsonHybridCacheSerializer(serializer); + return true; + } +} diff --git a/backend/src/Squidex.Infrastructure/Queries/CompareOperatorTypeConverter.cs b/backend/src/Squidex.Infrastructure/Queries/CompareOperatorTypeConverter.cs index b12a60cd2..ecc2c306e 100644 --- a/backend/src/Squidex.Infrastructure/Queries/CompareOperatorTypeConverter.cs +++ b/backend/src/Squidex.Infrastructure/Queries/CompareOperatorTypeConverter.cs @@ -76,7 +76,7 @@ public sealed class CompareOperatorTypeConverter : TypeConverter case CompareOperator.GreaterThan: return "gt"; case CompareOperator.GreaterThanOrEqual: - return "gt"; + return "ge"; case CompareOperator.Empty: return "empty"; case CompareOperator.Exists: diff --git a/backend/src/Squidex.Infrastructure/Queries/Json/JsonFilterSurrogate.cs b/backend/src/Squidex.Infrastructure/Queries/Json/JsonFilterSurrogate.cs index fb495c5b2..2cbf9cc6b 100644 --- a/backend/src/Squidex.Infrastructure/Queries/Json/JsonFilterSurrogate.cs +++ b/backend/src/Squidex.Infrastructure/Queries/Json/JsonFilterSurrogate.cs @@ -25,7 +25,25 @@ public sealed class JsonFilterSurrogate : ISurrogate> public void FromSource(FilterNode source) { - throw new NotSupportedException(); + switch (source) + { + case NegateFilter negate: + Not = negate.Filter; + break; + case LogicalFilter { Type: LogicalFilterType.And } and: + And = [.. and.Filters]; + break; + case LogicalFilter or: + Or = [.. or.Filters]; + break; + case CompareFilter compare: + Path = compare.Path.ToString(); + Op = compare.Operator; + Value = compare.Value; + break; + default: + throw new NotSupportedException(); + } } public FilterNode ToSource() diff --git a/backend/src/Squidex.Web/Pipeline/ContextFilter.cs b/backend/src/Squidex.Web/Pipeline/ContextFilter.cs index 449eeb0ac..7b5442c92 100644 --- a/backend/src/Squidex.Web/Pipeline/ContextFilter.cs +++ b/backend/src/Squidex.Web/Pipeline/ContextFilter.cs @@ -5,6 +5,7 @@ // All rights reserved. Licensed under the MIT license. // ========================================================================== +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Filters; using Squidex.Domain.Apps.Entities; @@ -26,10 +27,23 @@ public sealed class ContextFilter : IAsyncActionFilter builder.SetHeader(key, value.ToString()); } } + + // Clients can also bypass the query cache with the standard HTTP header. + if (IsNoCache(httpContext.Request)) + { + builder.WithNoQueryCache(); + } }); httpContext.Features.Set(requestContext); return next(); } + + private static bool IsNoCache(HttpRequest request) + { + var cacheControl = request.GetTypedHeaders().CacheControl; + + return cacheControl?.NoCache == true || cacheControl?.NoStore == true; + } } diff --git a/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs b/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs index 7f757cdc0..612d18852 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs @@ -46,12 +46,13 @@ public class SchemaContentsController(ICommandBus commandBus, IJobService jobSer public async Task PostContentMigration(string app, string schema, [FromBody] MigrateContentsDto request, [FromQuery] string? reference = null) { var job = MigrateContentsJob.BuildRequest( - User.Token()!, - App, - Schema, - request.MigrateDraft ?? true, + User.Token()!, + App, + Schema, + request.MigrateDraft ?? true, request.MigratePublished ?? true) - with { Reference = reference }; + with + { Reference = reference, }; await jobService.StartAsync(App.Id, job, HttpContext.RequestAborted); @@ -80,12 +81,13 @@ public class SchemaContentsController(ICommandBus commandBus, IJobService jobSer { var job = ExportContentsJob.BuildRequest( User.Token()!, - App, + App, Schema, - request.Format ?? ExportFormat.Csv, + request.Format ?? ExportFormat.Csv, request.Fields, - request.Unpublished ?? false) - with { Reference = reference }; + request.Unpublished ?? false) + with + { Reference = reference, }; await jobService.StartAsync(App.Id, job, HttpContext.RequestAborted); diff --git a/backend/src/Squidex/Config/Domain/AssetServices.cs b/backend/src/Squidex/Config/Domain/AssetServices.cs index d6b3faf58..639c3bb68 100644 --- a/backend/src/Squidex/Config/Domain/AssetServices.cs +++ b/backend/src/Squidex/Config/Domain/AssetServices.cs @@ -12,6 +12,7 @@ using Squidex.Domain.Apps.Entities.Assets.Queries.Steps; using Squidex.Domain.Apps.Entities.History; using Squidex.Domain.Apps.Entities.Search; using Squidex.Hosting.Ssrf; +using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.EventSourcing; namespace Squidex.Config.Domain; @@ -80,8 +81,22 @@ public static class AssetServices services.AddSingletonAs() .As(); - services.AddSingletonAs() - .As(); + if (config.GetValue("caching:assets:cacheDuration") > TimeSpan.Zero) + { + services.Configure(config, + "caching:assets"); + + services.AddSingletonAs() + .AsSelf(); + + services.AddSingletonAs(c => ActivatorUtilities.CreateInstance(c, c.GetRequiredService())) + .As().As(); + } + else + { + services.AddSingletonAs() + .As(); + } services.AddSingletonAs() .As(); diff --git a/backend/src/Squidex/Config/Domain/ContentsServices.cs b/backend/src/Squidex/Config/Domain/ContentsServices.cs index ef4257c7c..8012baabc 100644 --- a/backend/src/Squidex/Config/Domain/ContentsServices.cs +++ b/backend/src/Squidex/Config/Domain/ContentsServices.cs @@ -17,6 +17,7 @@ using Squidex.Domain.Apps.Entities.Contents.Text; using Squidex.Domain.Apps.Entities.Contents.Validation; using Squidex.Domain.Apps.Entities.History; using Squidex.Domain.Apps.Entities.Search; +using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.EventSourcing; namespace Squidex.Config.Domain; @@ -54,8 +55,22 @@ public static class ContentsServices services.AddSingletonAs() .As(); - services.AddSingletonAs() - .As(); + if (config.GetValue("caching:contents:cacheDuration") > TimeSpan.Zero) + { + services.Configure(config, + "caching:contents"); + + services.AddSingletonAs() + .AsSelf(); + + services.AddSingletonAs(c => ActivatorUtilities.CreateInstance(c, c.GetRequiredService())) + .As().As(); + } + else + { + services.AddSingletonAs() + .As(); + } services.AddSingletonAs() .As(); diff --git a/backend/src/Squidex/Config/Domain/InfrastructureServices.cs b/backend/src/Squidex/Config/Domain/InfrastructureServices.cs index 90e4ac525..e3774ad31 100644 --- a/backend/src/Squidex/Config/Domain/InfrastructureServices.cs +++ b/backend/src/Squidex/Config/Domain/InfrastructureServices.cs @@ -23,6 +23,7 @@ using Squidex.Domain.Apps.Entities.Scripting; using Squidex.Domain.Apps.Entities.Tags; using Squidex.Hosting.Ssrf; using Squidex.Infrastructure; +using Squidex.Infrastructure.Caching; using Squidex.Infrastructure.Diagnostics; using Squidex.Infrastructure.Log; using Squidex.Infrastructure.Translations; @@ -58,6 +59,15 @@ public static class InfrastructureServices services.AddAsyncLocalCache(); services.AddBackgroundCache(); + services.AddHybridCache() + .AddSerializerFactory(); + + services.Configure(config, + "caching:generations"); + + services.AddSingletonAs() + .As(); + services.AddSingletonAs(_ => SystemClock.Instance) .As(); diff --git a/backend/src/Squidex/Squidex.csproj b/backend/src/Squidex/Squidex.csproj index 2d9c56784..7c5319d60 100644 --- a/backend/src/Squidex/Squidex.csproj +++ b/backend/src/Squidex/Squidex.csproj @@ -45,6 +45,7 @@ + diff --git a/backend/src/Squidex/appsettings.json b/backend/src/Squidex/appsettings.json index 5994644db..1d185fc58 100644 --- a/backend/src/Squidex/appsettings.json +++ b/backend/src/Squidex/appsettings.json @@ -137,6 +137,25 @@ "domainObjects": { // The cache duration for domain objects. "cacheDuration": "00:10:00" + }, + + "contents": { + // The cache duration for published content queries of API clients. Zero to disable the cache. + // + // The results are stored in the distributed cache (the database by default) and changes invalidate the cache of the app. + "cacheDuration": "00:00:00" + }, + + "assets": { + // The cache duration for asset queries of API clients. Zero to disable the cache. + // + // The results are stored in the distributed cache (the database by default) and changes invalidate the cache of the app. + "cacheDuration": "00:00:00" + }, + + "generations": { + // Changes are collected and invalidate the caches once per interval. + "resetInterval": "00:00:01" } }, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/AssetEnricherTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/AssetEnricherTests.cs index 112e86260..6b0c95211 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/AssetEnricherTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/AssetEnricherTests.cs @@ -36,6 +36,39 @@ public class AssetEnricherTests : GivenContext .MustNotHaveHappened(); } + [Fact] + public async Task Should_only_invoke_steps_for_cached_results_if_flagged() + { + var assets = new[] { CreateAsset() }; + + var step1 = A.Fake(); + var step2 = A.Fake(); + + A.CallTo(() => step1.RunOnCachedResults) + .Returns(true); + + var sut = new AssetEnricher([step1, step2]); + + await sut.EnrichCachedAsync(assets, ApiContext, CancellationToken); + + A.CallTo(() => step1.EnrichAsync(ApiContext, CancellationToken)) + .MustHaveHappened(); + A.CallTo(() => step1.EnrichAsync(ApiContext, assets, CancellationToken)) + .MustHaveHappened(); + A.CallTo(() => step2.EnrichAsync(A._, A._)) + .MustNotHaveHappened(); + A.CallTo(() => step2.EnrichAsync(A._, A>._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public void Should_run_caching_step_for_cached_results() + { + IAssetEnricherStep step = new Steps.EnrichForCaching(A.Fake()); + + Assert.True(step.RunOnCachedResults); + } + [Fact] public async Task Should_invoke_steps() { diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/CachingAssetQueryServiceTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/CachingAssetQueryServiceTests.cs new file mode 100644 index 000000000..cd845f534 --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/CachingAssetQueryServiceTests.cs @@ -0,0 +1,360 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Squidex.Domain.Apps.Core.Assets; +using Squidex.Domain.Apps.Core.TestHelpers; +using Squidex.Domain.Apps.Entities.Assets.Commands; +using Squidex.Domain.Apps.Entities.TestHelpers; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Caching; +using Squidex.Infrastructure.Commands; +using Squidex.Infrastructure.Json; +using Squidex.Infrastructure.Json.Objects; +using Squidex.Infrastructure.Queries; + +namespace Squidex.Domain.Apps.Entities.Assets.Queries; + +public class CachingAssetQueryServiceTests : GivenContext +{ + private const string QueryPrefix = "assets/"; + + private readonly IAssetQueryService inner = A.Fake(); + private readonly IAssetEnricher assetEnricher = A.Fake(); + private readonly IDistributedCache distributedCache = A.Fake(x => x.Wrapping(new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())))); + private readonly IOptions options = Options.Create(new AssetQueryCacheOptions { CacheDuration = TimeSpan.FromMinutes(1) }); + private readonly ICacheGenerations generations = A.Fake(); + private readonly CachingAssetQueryService sut; + private readonly EnrichedAsset asset; + private readonly Dictionary generationValues = []; + + public CachingAssetQueryServiceTests() + { + asset = CreateAsset(); + + A.CallTo(() => inner.QueryAsync(A._, A._, A._, A._)) + .ReturnsLazily(() => ResultList.CreateFrom(10, asset)); + + A.CallTo(() => inner.FindAsync(A._, asset.Id, A._, A._, A._)) + .ReturnsLazily(() => asset); + + A.CallTo(() => inner.FindBySlugAsync(A._, "my-slug", A._, A._)) + .ReturnsLazily(() => asset); + + A.CallTo(() => generations.GetAsync(A._, A._)) + .ReturnsLazily((string key, CancellationToken _) => generationValues.GetValueOrDefault(key, "1")); + + A.CallTo(() => generations.Reset(A._)) + .Invokes(x => generationValues[x.GetArgument(0)!] = Guid.NewGuid().ToString()); + + sut = CreateSut(distributedCache); + } + + [Fact] + public async Task Should_query_inner_service_once_if_query_is_cached() + { + var actual = await QueryTwiceAsync(ApiContext, null, Q.Empty); + + Assert.Equal(10, actual.Total); + actual.Single().Should().BeEquivalentTo(asset); + + A.CallTo(() => inner.QueryAsync(A._, A._, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_enrich_result_for_request_if_read_from_cache() + { + await QueryTwiceAsync(ApiContext, null, Q.Empty); + + A.CallTo(() => assetEnricher.EnrichCachedAsync(A>.That.Matches(x => x.Single().Id == asset.Id), ApiContext, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_not_enrich_result_again_if_queried() + { + await sut.QueryAsync(ApiContext, null, Q.Empty, CancellationToken); + + A.CallTo(() => assetEnricher.EnrichCachedAsync(A>._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task Should_read_query_from_distributed_cache_of_other_node() + { + await sut.QueryAsync(ApiContext, null, Q.Empty, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + var actual = await CreateSut(distributedCache).QueryAsync(ApiContext, null, Q.Empty, CancellationToken); + + actual.Single().Should().BeEquivalentTo(asset); + + A.CallTo(() => inner.QueryAsync(A._, A._, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_query_again_after_change() + { + await sut.QueryAsync(ApiContext, null, Q.Empty, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + await HandleAsync(new AnnotateAsset { AppId = AppId }); + + await sut.QueryAsync(ApiContext, null, Q.Empty, CancellationToken); + + A.CallTo(() => inner.QueryAsync(A._, A._, A._, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_cache_queries_with_different_parents_separately() + { + await sut.QueryAsync(ApiContext, null, Q.Empty, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + await sut.QueryAsync(ApiContext, DomainId.NewGuid(), Q.Empty, CancellationToken); + + A.CallTo(() => inner.QueryAsync(A._, A._, A._, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_query_inner_service_if_generation_cannot_be_read() + { + var failingGenerations = A.Fake(); + + A.CallTo(() => failingGenerations.GetAsync(A._, A._)) + .Throws(new InvalidOperationException()); + + var actual = await CreateSut(distributedCache, failingGenerations).QueryAsync(ApiContext, null, Q.Empty, CancellationToken); + + actual.Single().Should().BeEquivalentTo(asset); + AssertCacheNotUsed(); + } + + [Fact] + public async Task Should_not_cache_query_if_disabled_by_header() + { + await QueryWithoutCacheAsync(ApiContext.Clone(b => b.WithNoQueryCache()), Q.Empty); + } + + [Fact] + public async Task Should_not_cache_find() + { + await sut.FindAsync(ApiContext, asset.Id, ct: CancellationToken); + await sut.FindAsync(ApiContext, asset.Id, ct: CancellationToken); + + AssertCacheNotUsed(); + + A.CallTo(() => inner.FindAsync(A._, asset.Id, false, EtagVersion.Any, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_not_cache_find_by_slug() + { + await sut.FindBySlugAsync(ApiContext, "my-slug", ct: CancellationToken); + await sut.FindBySlugAsync(ApiContext, "my-slug", ct: CancellationToken); + + AssertCacheNotUsed(); + + A.CallTo(() => inner.FindBySlugAsync(A._, "my-slug", false, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_not_cache_query_for_frontend() + { + await QueryWithoutCacheAsync(FrontendContext, Q.Empty); + } + + [Fact] + public async Task Should_not_cache_query_if_app_has_asset_query_script() + { + App = App with { AssetScripts = new AssetScripts { Query = "" } }; + + await QueryWithoutCacheAsync(ApiContext, Q.Empty); + } + + [Fact] + public async Task Should_cache_query_if_app_has_asset_query_script_but_scripting_is_disabled() + { + App = App with { AssetScripts = new AssetScripts { Query = "" } }; + + await QueryTwiceAsync(ApiContext.Clone(b => b.WithNoScripting()), null, Q.Empty); + + A.CallTo(() => inner.QueryAsync(A._, A._, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_cache_different_queries_separately() + { + await sut.QueryAsync(ApiContext, null, Q.Empty.WithODataQuery("$top=1"), CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + await sut.QueryAsync(ApiContext, null, Q.Empty.WithODataQuery("$top=2"), CancellationToken); + + A.CallTo(() => inner.QueryAsync(A._, A._, A._, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_not_cache_already_parsed_query() + { + await QueryWithoutCacheAsync(ApiContext, Q.Empty.WithQuery(new ClrQuery { Take = 5 })); + } + + [Fact] + public async Task Should_not_cache_random_query() + { + await QueryWithoutCacheAsync(ApiContext, Q.Empty.WithJsonQuery(new Query { Random = 5 })); + } + + [Fact] + public async Task Should_not_cache_find_by_hash() + { + await sut.FindByHashAsync(ApiContext, "hash", "file", 100, CancellationToken); + await sut.FindByHashAsync(ApiContext, "hash", "file", 100, CancellationToken); + + AssertCacheNotUsed(); + + A.CallTo(() => inner.FindByHashAsync(A._, "hash", "file", 100, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_not_cache_find_global() + { + await sut.FindGlobalAsync(ApiContext, asset.Id, CancellationToken); + await sut.FindGlobalAsync(ApiContext, asset.Id, CancellationToken); + + AssertCacheNotUsed(); + + A.CallTo(() => inner.FindGlobalAsync(A._, asset.Id, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_reset_generation_if_asset_changed() + { + await HandleAsync(new AnnotateAsset { AppId = AppId }); + + A.CallTo(() => generations.Reset(A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_reset_generation_if_asset_deleted() + { + await HandleAsync(new DeleteAsset { AppId = AppId }); + + A.CallTo(() => generations.Reset(A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_not_reset_generation_if_folder_changed() + { + await HandleAsync(new RenameAssetFolder { AppId = AppId }); + + A.CallTo(() => generations.Reset(A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task Should_not_reset_generation_if_command_failed() + { + var commandContext = new CommandContext(new AnnotateAsset { AppId = AppId }, A.Fake()); + + await Assert.ThrowsAsync(() => + sut.HandleAsync(commandContext, (_, _) => throw new InvalidOperationException(), CancellationToken)); + + A.CallTo(() => generations.Reset(A._)) + .MustNotHaveHappened(); + } + + private Task HandleAsync(ICommand command) + { + return sut.HandleAsync(new CommandContext(command, A.Fake()), (_, _) => Task.CompletedTask, CancellationToken); + } + + private async Task> QueryTwiceAsync(Context requestContext, DomainId? parentId, Q q) + { + await sut.QueryAsync(requestContext, parentId, q, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + return await sut.QueryAsync(requestContext, parentId, q, CancellationToken); + } + + private async Task QueryWithoutCacheAsync(Context requestContext, Q q) + { + await sut.QueryAsync(requestContext, null, q, CancellationToken); + await sut.QueryAsync(requestContext, null, q, CancellationToken); + + AssertCacheNotUsed(); + + A.CallTo(() => inner.QueryAsync(A._, A._, A._, A._)) + .MustHaveHappenedTwiceExactly(); + } + + private CachingAssetQueryService CreateSut(IDistributedCache cache, ICacheGenerations? customGenerations = null) + { + return new CachingAssetQueryService(inner, + CreateHybridCache(cache, TestUtils.DefaultSerializer), + customGenerations ?? generations, + assetEnricher, + TestUtils.DefaultSerializer, + options, + A.Fake>()); + } + + private static HybridCache CreateHybridCache(IDistributedCache cache, IJsonSerializer serializer) + { + var services = new ServiceCollection(); + + services.AddSingleton(cache); + services.AddSingleton(serializer); + services.AddHybridCache() + .AddSerializerFactory(); + + return services.BuildServiceProvider().GetRequiredService(); + } + + private async Task WaitForEntriesAsync(string prefix, int count) + { + // The hybrid cache writes to the distributed cache in the background. + for (var i = 0; i < 500; i++) + { + var numWrites = Fake.GetCalls(distributedCache).Count(x => x.Method.Name.StartsWith("Set", StringComparison.Ordinal) && x.Arguments.Get(0)!.StartsWith(prefix, StringComparison.Ordinal)); + if (numWrites >= count) + { + return; + } + + await Task.Delay(10, CancellationToken); + } + + throw new TimeoutException($"Expected {count} entries with prefix '{prefix}'."); + } + + private void AssertCacheNotUsed() + { + // The hybrid cache reads its own invalidation state when it is created. + A.CallTo(() => distributedCache.GetAsync(A.That.Not.StartsWith("__MSFT_HCT__"), A._)) + .MustNotHaveHappened(); + A.CallTo(() => distributedCache.SetAsync(A._, A._, A._, A._)) + .MustNotHaveHappened(); + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/CachingContentQueryServiceTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/CachingContentQueryServiceTests.cs new file mode 100644 index 000000000..e256276a1 --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/CachingContentQueryServiceTests.cs @@ -0,0 +1,479 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Domain.Apps.Core.TestHelpers; +using Squidex.Domain.Apps.Entities.Assets.Commands; +using Squidex.Domain.Apps.Entities.Contents.Commands; +using Squidex.Domain.Apps.Entities.TestHelpers; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Caching; +using Squidex.Infrastructure.Commands; +using Squidex.Infrastructure.Json; +using Squidex.Infrastructure.Json.Objects; +using Squidex.Infrastructure.Json.System; +using Squidex.Infrastructure.Queries; +using Squidex.Infrastructure.Queries.Json; +using Squidex.Shared; + +namespace Squidex.Domain.Apps.Entities.Contents.Queries; + +public class CachingContentQueryServiceTests : GivenContext +{ + private const string QueryPrefix = "contents/"; + + private static readonly IJsonSerializer Serializer = TestUtils.CreateSerializer(options => + { + options.Converters.Add(new SurrogateJsonConverter, JsonFilterSurrogate>()); + }); + + private readonly IContentQueryService inner = A.Fake(); + private readonly IContentEnricher contentEnricher = A.Fake(); + private readonly IDistributedCache distributedCache = A.Fake(x => x.Wrapping(new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())))); + private readonly IOptions options = Options.Create(new ContentQueryCacheOptions { CacheDuration = TimeSpan.FromMinutes(1) }); + private readonly ICacheGenerations generations = A.Fake(); + private readonly CachingContentQueryService sut; + private readonly EnrichedContent content; + private readonly Dictionary generationValues = []; + + public CachingContentQueryServiceTests() + { + content = CreateContent(); + + A.CallTo(() => inner.GetSchemaOrThrowAsync(A._, SchemaId.Name, A._)) + .ReturnsLazily(() => Schema); + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .ReturnsLazily(() => ResultList.CreateFrom(10, content)); + + A.CallTo(() => inner.FindAsync(A._, SchemaId.Name, content.Id, A._, A._)) + .ReturnsLazily(() => content); + + A.CallTo(() => generations.GetAsync(A._, A._)) + .ReturnsLazily((string key, CancellationToken _) => generationValues.GetValueOrDefault(key, "1")); + + A.CallTo(() => generations.Reset(A._)) + .Invokes(x => generationValues[x.GetArgument(0)!] = Guid.NewGuid().ToString()); + + sut = CreateSut(distributedCache); + } + + [Fact] + public async Task Should_query_inner_service_once_if_query_is_cached() + { + var actual = await QueryTwiceAsync(CreateApiContext(), Q.Empty); + + Assert.Equal(10, actual.Total); + actual.Single().Should().BeEquivalentTo(content); + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_enrich_result_for_request_if_read_from_cache() + { + var requestContext = CreateApiContext(); + + await QueryTwiceAsync(requestContext, Q.Empty); + + A.CallTo(() => contentEnricher.EnrichCachedAsync(A>.That.Matches(x => x.Single().Id == content.Id), requestContext, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_not_enrich_result_again_if_queried() + { + await sut.QueryAsync(CreateApiContext(), SchemaId.Name, Q.Empty, CancellationToken); + + A.CallTo(() => contentEnricher.EnrichCachedAsync(A>._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task Should_read_query_from_distributed_cache_of_other_node() + { + await sut.QueryAsync(CreateApiContext(), SchemaId.Name, Q.Empty, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + var actual = await CreateSut(distributedCache).QueryAsync(CreateApiContext(), SchemaId.Name, Q.Empty, CancellationToken); + + actual.Single().Should().BeEquivalentTo(content); + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_query_again_after_change() + { + await sut.QueryAsync(CreateApiContext(), SchemaId.Name, Q.Empty, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + await HandleAsync(new UpdateContent { AppId = AppId }); + + await sut.QueryAsync(CreateApiContext(), SchemaId.Name, Q.Empty, CancellationToken); + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_query_again_if_schema_has_changed() + { + await sut.QueryAsync(CreateApiContext(), SchemaId.Name, Q.Empty, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + Schema = Schema with { Version = Schema.Version + 1 }; + + await sut.QueryAsync(CreateApiContext(), SchemaId.Name, Q.Empty, CancellationToken); + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_query_inner_service_if_generation_cannot_be_read() + { + var failingGenerations = A.Fake(); + + A.CallTo(() => failingGenerations.GetAsync(A._, A._)) + .Throws(new InvalidOperationException()); + + var actual = await CreateSut(distributedCache, failingGenerations).QueryAsync(CreateApiContext(), SchemaId.Name, Q.Empty, CancellationToken); + + actual.Single().Should().BeEquivalentTo(content); + AssertCacheNotUsed(); + } + + [Fact] + public async Task Should_not_cache_query_if_disabled_by_header() + { + await QueryWithoutCacheAsync(CreateApiContext().Clone(b => b.WithNoQueryCache()), Q.Empty); + } + + [Fact] + public async Task Should_not_cache_find() + { + await sut.FindAsync(CreateApiContext(), SchemaId.Name, content.Id, ct: CancellationToken); + await sut.FindAsync(CreateApiContext(), SchemaId.Name, content.Id, ct: CancellationToken); + + AssertCacheNotUsed(); + + A.CallTo(() => inner.FindAsync(A._, SchemaId.Name, content.Id, EtagVersion.Any, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_not_cache_query_for_frontend() + { + await QueryWithoutCacheAsync(CreateApiContext(isFrontend: true), Q.Empty); + } + + [Fact] + public async Task Should_not_cache_query_for_unpublished_content() + { + await QueryWithoutCacheAsync(CreateApiContext().Clone(b => b.WithUnpublished()), Q.Empty); + } + + [Fact] + public async Task Should_not_cache_query_if_workflow_is_resolved() + { + await QueryWithoutCacheAsync(CreateApiContext().Clone(b => b.WithResolveFlow()), Q.Empty); + } + + [Fact] + public async Task Should_not_cache_query_if_user_can_only_read_own_content() + { + await QueryWithoutCacheAsync(CreateApiContext(permissionId: PermissionIds.AppContentsReadOwn), Q.Empty); + } + + [Fact] + public async Task Should_not_cache_query_if_schema_has_query_pre_script() + { + Schema = Schema with { Scripts = new SchemaScripts { QueryPre = "" } }; + + await QueryWithoutCacheAsync(CreateApiContext(), Q.Empty); + } + + [Fact] + public async Task Should_not_cache_scheduled_query() + { + await QueryWithoutCacheAsync(CreateApiContext(), Q.Empty.WithSchedule(default, default)); + } + + [Fact] + public async Task Should_not_cache_query_if_schema_has_query_script() + { + Schema = Schema with { Scripts = new SchemaScripts { Query = "" } }; + + await QueryWithoutCacheAsync(CreateApiContext(), Q.Empty); + } + + [Fact] + public async Task Should_cache_query_if_schema_has_query_script_but_scripting_is_disabled() + { + Schema = Schema with { Scripts = new SchemaScripts { Query = "" } }; + + await QueryTwiceAsync(CreateApiContext().Clone(b => b.WithNoScripting()), Q.Empty); + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_not_cache_already_parsed_query() + { + await QueryWithoutCacheAsync(CreateApiContext(), Q.Empty.WithQuery(new ClrQuery { Take = 5 })); + } + + [Fact] + public async Task Should_not_cache_random_query() + { + await QueryWithoutCacheAsync(CreateApiContext(), Q.Empty.WithJsonQuery(new Query { Random = 5 })); + } + + [Fact] + public async Task Should_not_cache_random_json_query() + { + await QueryWithoutCacheAsync(CreateApiContext(), Q.Empty.WithJsonQuery("{ \"random\": 5 }")); + } + + [Fact] + public async Task Should_cache_different_queries_separately() + { + await QuerySeparatelyAsync( + (CreateApiContext(), Q.Empty.WithODataQuery("$top=1")), + (CreateApiContext(), Q.Empty.WithODataQuery("$top=2"))); + } + + [Fact] + public async Task Should_cache_json_queries_with_different_filters_separately() + { + await QuerySeparatelyAsync( + (CreateApiContext(), Q.Empty.WithJsonQuery(CreateJsonQuery("a", 1))), + (CreateApiContext(), Q.Empty.WithJsonQuery(CreateJsonQuery("a", 2))), + (CreateApiContext(), Q.Empty.WithJsonQuery(CreateJsonQuery("b", 1)))); + } + + [Fact] + public async Task Should_cache_json_queries_with_different_sorting_separately() + { + var query2 = CreateJsonQuery("a", 1); + + query2.Sort = [new SortNode("data.field", SortOrder.Descending)]; + + await QuerySeparatelyAsync( + (CreateApiContext(), Q.Empty.WithJsonQuery(CreateJsonQuery("a", 1))), + (CreateApiContext(), Q.Empty.WithJsonQuery(query2))); + } + + [Fact] + public async Task Should_cache_queries_with_different_headers_separately() + { + await QuerySeparatelyAsync( + (CreateApiContext().Clone(b => b.WithLanguages(["en"])), Q.Empty), + (CreateApiContext().Clone(b => b.WithLanguages(["de"])), Q.Empty)); + } + + [Fact] + public async Task Should_cache_same_json_query_once() + { + await QueryTwiceAsync(CreateApiContext(), Q.Empty.WithJsonQuery(CreateJsonQuery("a", 1))); + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_ignore_header_order_for_cache_key() + { + await sut.QueryAsync(CreateApiContext().Clone(b => b.WithFlatten().WithNoTotal()), SchemaId.Name, Q.Empty, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + await sut.QueryAsync(CreateApiContext().Clone(b => b.WithNoTotal().WithFlatten()), SchemaId.Name, Q.Empty, CancellationToken); + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_not_cache_query_over_all_schemas() + { + await sut.QueryAsync(CreateApiContext(), Q.Empty, CancellationToken); + await sut.QueryAsync(CreateApiContext(), Q.Empty, CancellationToken); + + AssertCacheNotUsed(); + + A.CallTo(() => inner.QueryAsync(A._, A._, A._)) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task Should_reset_generation_if_content_changed() + { + await HandleAsync(new UpdateContent { AppId = AppId }); + + A.CallTo(() => generations.Reset(A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_reset_generation_if_asset_deleted() + { + await HandleAsync(new DeleteAsset { AppId = AppId }); + + A.CallTo(() => generations.Reset(A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_not_reset_generation_if_content_is_only_validated() + { + await HandleAsync(new ValidateContent { AppId = AppId }); + + A.CallTo(() => generations.Reset(A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task Should_not_reset_generation_if_content_defaults_are_only_enriched() + { + await HandleAsync(new EnrichContentDefaults { AppId = AppId }); + + A.CallTo(() => generations.Reset(A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task Should_not_reset_generation_if_asset_changed() + { + await HandleAsync(new AnnotateAsset { AppId = AppId }); + + A.CallTo(() => generations.Reset(A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task Should_not_reset_generation_if_command_failed() + { + var commandContext = new CommandContext(new UpdateContent { AppId = AppId }, A.Fake()); + + await Assert.ThrowsAsync(() => + sut.HandleAsync(commandContext, (_, _) => throw new InvalidOperationException(), CancellationToken)); + + A.CallTo(() => generations.Reset(A._)) + .MustNotHaveHappened(); + } + + private Task HandleAsync(ICommand command) + { + return sut.HandleAsync(new CommandContext(command, A.Fake()), (_, _) => Task.CompletedTask, CancellationToken); + } + + private async Task> QueryTwiceAsync(Context requestContext, Q q) + { + await sut.QueryAsync(requestContext, SchemaId.Name, q, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, 1); + + return await sut.QueryAsync(requestContext, SchemaId.Name, q, CancellationToken); + } + + private async Task QueryWithoutCacheAsync(Context requestContext, Q q) + { + await sut.QueryAsync(requestContext, SchemaId.Name, q, CancellationToken); + await sut.QueryAsync(requestContext, SchemaId.Name, q, CancellationToken); + + AssertCacheNotUsed(); + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .MustHaveHappenedTwiceExactly(); + } + + private async Task QuerySeparatelyAsync(params (Context Context, Q Query)[] queries) + { + // Wait for each entry, so that the next query would get a hit, if the keys were equal. + for (var i = 0; i < queries.Length; i++) + { + await sut.QueryAsync(queries[i].Context, SchemaId.Name, queries[i].Query, CancellationToken); + await WaitForEntriesAsync(QueryPrefix, i + 1); + } + + A.CallTo(() => inner.QueryAsync(A._, SchemaId.Name, A._, A._)) + .MustHaveHappened(queries.Length, Times.Exactly); + } + + private CachingContentQueryService CreateSut(IDistributedCache cache, ICacheGenerations? customGenerations = null) + { + return new CachingContentQueryService(inner, + CreateHybridCache(cache, Serializer), + customGenerations ?? generations, + contentEnricher, + Serializer, + options, + A.Fake>()); + } + + private static HybridCache CreateHybridCache(IDistributedCache cache, IJsonSerializer serializer) + { + var services = new ServiceCollection(); + + services.AddSingleton(cache); + services.AddSingleton(serializer); + services.AddHybridCache() + .AddSerializerFactory(); + + return services.BuildServiceProvider().GetRequiredService(); + } + + private async Task WaitForEntriesAsync(string prefix, int count) + { + // The hybrid cache writes to the distributed cache in the background. + for (var i = 0; i < 500; i++) + { + var numWrites = Fake.GetCalls(distributedCache).Count(x => x.Method.Name.StartsWith("Set", StringComparison.Ordinal) && x.Arguments.Get(0)!.StartsWith(prefix, StringComparison.Ordinal)); + if (numWrites >= count) + { + return; + } + + await Task.Delay(10, CancellationToken); + } + + throw new TimeoutException($"Expected {count} entries with prefix '{prefix}'."); + } + + private void AssertCacheNotUsed() + { + // The hybrid cache reads its own invalidation state when it is created. + A.CallTo(() => distributedCache.GetAsync(A.That.Not.StartsWith("__MSFT_HCT__"), A._)) + .MustNotHaveHappened(); + A.CallTo(() => distributedCache.SetAsync(A._, A._, A._, A._)) + .MustNotHaveHappened(); + } + + private Context CreateApiContext(bool isFrontend = false, string permissionId = PermissionIds.AppContentsRead) + { + var permission = PermissionIds.ForApp(permissionId, AppId.Name, SchemaId.Name).Id; + + return CreateContext(isFrontend, permission); + } + + private static Query CreateJsonQuery(string field, int value) + { + return new Query + { + Filter = new CompareFilter($"data.{field}", CompareOperator.Equals, value), + }; + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentEnricherTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentEnricherTests.cs index f461de80b..a30f4943c 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentEnricherTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentEnricherTests.cs @@ -52,6 +52,39 @@ public class ContentEnricherTests : GivenContext .MustNotHaveHappened(); } + [Fact] + public async Task Should_only_invoke_steps_for_cached_results_if_flagged() + { + var contents = new[] { CreateContent() }; + + var step1 = A.Fake(); + var step2 = A.Fake(); + + A.CallTo(() => step1.RunOnCachedResults) + .Returns(true); + + var sut = new ContentEnricher([step1, step2], AppProvider); + + await sut.EnrichCachedAsync(contents, ApiContext, CancellationToken); + + A.CallTo(() => step1.EnrichAsync(ApiContext, CancellationToken)) + .MustHaveHappened(); + A.CallTo(() => step1.EnrichAsync(ApiContext, contents, A._, CancellationToken)) + .MustHaveHappened(); + A.CallTo(() => step2.EnrichAsync(A._, A._)) + .MustNotHaveHappened(); + A.CallTo(() => step2.EnrichAsync(A._, A>._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public void Should_run_caching_step_for_cached_results() + { + IContentEnricherStep step = new Steps.EnrichForCaching(A.Fake()); + + Assert.True(step.RunOnCachedResults); + } + [Fact] public async Task Should_invoke_steps() { diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/ContextHeadersTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/ContextHeadersTests.cs index 638f873ae..536529329 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/ContextHeadersTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/ContextHeadersTests.cs @@ -110,4 +110,39 @@ public class ContextHeadersTests // The original must not be affected. Assert.Equal("my-app", context1.App.Name); } + + [Fact] + public void Should_sort_headers_independent_from_insertion_order() + { + var context1 = sut.Clone(b => + { + b.SetHeader("X-B", "2"); + b.SetHeader("X-A", "1"); + }); + + var context2 = sut.Clone(b => + { + b.SetHeader("X-A", "1"); + b.SetHeader("X-B", "2"); + }); + + Assert.Equal(["X-A", "X-B"], context1.Headers.Keys); + Assert.Equal(context1.Headers, context2.Headers); + } + + [Fact] + public void Should_find_headers_case_insensitive() + { + var context = sut.Clone(b => b.SetHeader("X-Fields", "a")); + + Assert.Equal("a", context.Headers["x-fields"]); + } + + [Fact] + public void Should_keep_headers_when_app_changes() + { + var context = sut.Clone(b => b.SetHeader("X-Fields", "a")).WithApp(new App { Name = "other-app" }); + + Assert.Equal("a", context.Headers["X-Fields"]); + } } diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Squidex.Domain.Apps.Entities.Tests.csproj b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Squidex.Domain.Apps.Entities.Tests.csproj index d27e77d3b..fe27bfcc1 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Squidex.Domain.Apps.Entities.Tests.csproj +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Squidex.Domain.Apps.Entities.Tests.csproj @@ -33,6 +33,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/backend/tests/Squidex.Infrastructure.Tests/Caching/CacheGenerationsTests.cs b/backend/tests/Squidex.Infrastructure.Tests/Caching/CacheGenerationsTests.cs new file mode 100644 index 000000000..03c3f47b5 --- /dev/null +++ b/backend/tests/Squidex.Infrastructure.Tests/Caching/CacheGenerationsTests.cs @@ -0,0 +1,141 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Squidex.Infrastructure.Caching; + +public class CacheGenerationsTests +{ + private readonly CancellationTokenSource cts = new CancellationTokenSource(); + private readonly CancellationToken ct; + private readonly IDistributedCache cache = A.Fake(x => x.Wrapping(new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())))); + private readonly CacheGenerations sut; + + public CacheGenerationsTests() + { + ct = cts.Token; + + var options = Options.Create(new CacheGenerationsOptions { ResetInterval = TimeSpan.FromMilliseconds(100) }); + + sut = new CacheGenerations(cache, options, A.Fake>()); + } + + [Fact] + public async Task Should_create_generation_if_not_found() + { + var generation1 = await sut.GetAsync("key", ct); + var generation2 = await sut.GetAsync("key", ct); + + Assert.NotEmpty(generation1); + Assert.Equal(generation1, generation2); + } + + [Fact] + public async Task Should_use_separate_generations_for_different_keys() + { + var generation1 = await sut.GetAsync("key1", ct); + var generation2 = await sut.GetAsync("key2", ct); + + Assert.NotEqual(generation1, generation2); + } + + [Fact] + public async Task Should_store_generation_without_expiration() + { + await sut.GetAsync("key", ct); + + A.CallTo(() => cache.SetAsync("generation/key", A._, + A.That.Matches(x => + x.AbsoluteExpiration == null && + x.AbsoluteExpirationRelativeToNow == null && + x.SlidingExpiration == null), + A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_not_change_generation_on_reset_before_flush() + { + var generation = await sut.GetAsync("key", ct); + + sut.Reset("key"); + + Assert.Equal(generation, await sut.GetAsync("key", ct)); + } + + [Fact] + public async Task Should_change_generation_after_reset_and_flush() + { + var generation = await sut.GetAsync("key", ct); + + sut.Reset("key"); + await sut.FlushAsync(ct); + + Assert.NotEqual(generation, await sut.GetAsync("key", ct)); + } + + [Fact] + public async Task Should_write_each_reset_key_once_on_flush() + { + sut.Reset("key1"); + sut.Reset("key1"); + sut.Reset("key2"); + + await sut.FlushAsync(ct); + await sut.FlushAsync(ct); + + A.CallTo(() => cache.SetAsync("generation/key1", A._, A._, A._)) + .MustHaveHappenedOnceExactly(); + A.CallTo(() => cache.SetAsync("generation/key2", A._, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_not_throw_if_flush_fails() + { + A.CallTo(() => cache.SetAsync(A._, A._, A._, A._)) + .Throws(new InvalidOperationException()); + + sut.Reset("key"); + await sut.FlushAsync(ct); + } + + [Fact] + public async Task Should_flush_resets_with_timer() + { + await sut.StartAsync(ct); + try + { + sut.Reset("key"); + + await Task.Delay(500, ct); + + A.CallTo(() => cache.SetAsync("generation/key", A._, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + finally + { + await sut.StopAsync(ct); + } + } + + [Fact] + public async Task Should_flush_pending_resets_when_stopped() + { + await sut.StartAsync(ct); + + sut.Reset("key"); + await sut.StopAsync(ct); + + A.CallTo(() => cache.SetAsync("generation/key", A._, A._, A._)) + .MustHaveHappenedOnceExactly(); + } +} diff --git a/backend/tests/Squidex.Infrastructure.Tests/Caching/JsonHybridCacheSerializerTests.cs b/backend/tests/Squidex.Infrastructure.Tests/Caching/JsonHybridCacheSerializerTests.cs new file mode 100644 index 000000000..e15980df0 --- /dev/null +++ b/backend/tests/Squidex.Infrastructure.Tests/Caching/JsonHybridCacheSerializerTests.cs @@ -0,0 +1,50 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Buffers; +using Microsoft.Extensions.Caching.Hybrid; +using Squidex.Infrastructure.TestHelpers; + +#pragma warning disable SA1313 // Parameter names should begin with lower-case letter + +namespace Squidex.Infrastructure.Caching; + +public class JsonHybridCacheSerializerTests +{ + public sealed record Value(string Text, int Number, DomainId Id); + + [Fact] + public void Should_serialize_and_deserialize_value() + { + var source = new Value("text", 42, DomainId.NewGuid()); + + var actual = SerializeAndDeserialize(new JsonHybridCacheSerializer(TestUtils.DefaultSerializer), source); + + Assert.Equal(source, actual); + } + + [Fact] + public void Should_create_serializer_for_any_type() + { + var factory = new JsonHybridCacheSerializerFactory(TestUtils.DefaultSerializer); + + Assert.True(factory.TryCreateSerializer(out var serializer)); + + var source = new Value("text", 42, DomainId.NewGuid()); + + Assert.Equal(source, SerializeAndDeserialize(serializer, source)); + } + + private static T SerializeAndDeserialize(IHybridCacheSerializer serializer, T value) + { + var buffer = new ArrayBufferWriter(); + + serializer.Serialize(value, buffer); + + return serializer.Deserialize(new ReadOnlySequence(buffer.WrittenMemory)); + } +} diff --git a/backend/tests/Squidex.Infrastructure.Tests/Queries/QueryJsonTests.cs b/backend/tests/Squidex.Infrastructure.Tests/Queries/QueryJsonTests.cs index cb90c562e..58d437437 100644 --- a/backend/tests/Squidex.Infrastructure.Tests/Queries/QueryJsonTests.cs +++ b/backend/tests/Squidex.Infrastructure.Tests/Queries/QueryJsonTests.cs @@ -174,6 +174,36 @@ public class QueryJsonTests SerializeAndDeserialize(json); } + [Fact] + public void Should_serialize_and_deserialize_all_operators() + { + foreach (var op in Enum.GetValues()) + { + var serialized = TestUtils.DefaultSerializer.Serialize(op); + + Assert.Equal(op, TestUtils.DefaultSerializer.Deserialize(serialized)); + } + } + + [Fact] + public void Should_serialize_and_deserialize_filter() + { + var source = + new LogicalFilter(LogicalFilterType.Or, + [ + new LogicalFilter(LogicalFilterType.And, + [ + new CompareFilter("property1", CompareOperator.GreaterThanOrEqual, 10), + new CompareFilter("property2", CompareOperator.In, JsonValue.Array(1, 2)), + ]), + new NegateFilter(new CompareFilter("property3", CompareOperator.Empty, default)), + ]); + + var filter = SerializeAndDeserialize>(source); + + Assert.Equal(source.ToString(), filter.ToString()); + } + private static FilterNode SerializeAndDeserialize(T value) { var json = TestUtils.DefaultSerializer.Serialize(value, true); diff --git a/backend/tests/Squidex.Web.Tests/Pipeline/ContextFilterTests.cs b/backend/tests/Squidex.Web.Tests/Pipeline/ContextFilterTests.cs new file mode 100644 index 000000000..ee42eb7c7 --- /dev/null +++ b/backend/tests/Squidex.Web.Tests/Pipeline/ContextFilterTests.cs @@ -0,0 +1,78 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Routing; +using Microsoft.Net.Http.Headers; +using Squidex.Domain.Apps.Entities; + +namespace Squidex.Web.Pipeline; + +public class ContextFilterTests +{ + private readonly HttpContext httpContext = new DefaultHttpContext(); + private readonly ActionExecutingContext executingContext; + private readonly ContextFilter sut = new ContextFilter(); + + public ContextFilterTests() + { + var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); + + executingContext = new ActionExecutingContext(actionContext, [], new Dictionary(), this); + } + + [Fact] + public async Task Should_copy_custom_headers() + { + httpContext.Request.Headers["X-Fields"] = "a,b"; + httpContext.Request.Headers["Accept"] = "application/json"; + + var context = await ExecuteAsync(); + + Assert.Equal("a,b", context.Headers["X-Fields"]); + Assert.False(context.Headers.ContainsKey("Accept")); + } + + [Theory] + [InlineData("no-cache")] + [InlineData("no-store")] + [InlineData("max-age=0, no-cache")] + public async Task Should_disable_query_cache_if_client_does_not_want_cached_responses(string cacheControl) + { + httpContext.Request.Headers[HeaderNames.CacheControl] = cacheControl; + + var context = await ExecuteAsync(); + + Assert.True(context.NoQueryCache()); + } + + [Theory] + [InlineData(null)] + [InlineData("max-age=60")] + [InlineData("public")] + public async Task Should_not_disable_query_cache_for_other_cache_control_values(string? cacheControl) + { + if (cacheControl != null) + { + httpContext.Request.Headers[HeaderNames.CacheControl] = cacheControl; + } + + var context = await ExecuteAsync(); + + Assert.False(context.NoQueryCache()); + } + + private async Task ExecuteAsync() + { + await sut.OnActionExecutionAsync(executingContext, () => Task.FromResult(null!)); + + return httpContext.Features.Get()!; + } +}