Browse Source

Query cache (#1343)

* Query cache

* Simplified

* Final fixes
pull/1345/head
Sebastian Stehle 2 months ago
committed by GitHub
parent
commit
6ed614b4f4
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 13
      backend/src/Squidex.Domain.Apps.Entities/Assets/AssetQueryCacheOptions.cs
  2. 74
      backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/AssetEnricher.cs
  3. 212
      backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/CachingAssetQueryService.cs
  4. 3
      backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricher.cs
  5. 2
      backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricherStep.cs
  6. 2
      backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/Steps/EnrichForCaching.cs
  7. 13
      backend/src/Squidex.Domain.Apps.Entities/Contents/ContentQueryCacheOptions.cs
  8. 235
      backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/CachingContentQueryService.cs
  9. 93
      backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs
  10. 3
      backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricher.cs
  11. 3
      backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricherStep.cs
  12. 2
      backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/Steps/EnrichForCaching.cs
  13. 19
      backend/src/Squidex.Domain.Apps.Entities/Context.cs
  14. 11
      backend/src/Squidex.Domain.Apps.Entities/ContextHeaders.cs
  15. 103
      backend/src/Squidex.Infrastructure/Caching/CacheGenerations.cs
  16. 13
      backend/src/Squidex.Infrastructure/Caching/CacheGenerationsOptions.cs
  17. 16
      backend/src/Squidex.Infrastructure/Caching/ICacheGenerations.cs
  18. 27
      backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializer.cs
  19. 21
      backend/src/Squidex.Infrastructure/Caching/JsonHybridCacheSerializerFactory.cs
  20. 2
      backend/src/Squidex.Infrastructure/Queries/CompareOperatorTypeConverter.cs
  21. 20
      backend/src/Squidex.Infrastructure/Queries/Json/JsonFilterSurrogate.cs
  22. 14
      backend/src/Squidex.Web/Pipeline/ContextFilter.cs
  23. 20
      backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs
  24. 19
      backend/src/Squidex/Config/Domain/AssetServices.cs
  25. 19
      backend/src/Squidex/Config/Domain/ContentsServices.cs
  26. 10
      backend/src/Squidex/Config/Domain/InfrastructureServices.cs
  27. 1
      backend/src/Squidex/Squidex.csproj
  28. 19
      backend/src/Squidex/appsettings.json
  29. 33
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/AssetEnricherTests.cs
  30. 360
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/Queries/CachingAssetQueryServiceTests.cs
  31. 479
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/CachingContentQueryServiceTests.cs
  32. 33
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentEnricherTests.cs
  33. 35
      backend/tests/Squidex.Domain.Apps.Entities.Tests/ContextHeadersTests.cs
  34. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Squidex.Domain.Apps.Entities.Tests.csproj
  35. 141
      backend/tests/Squidex.Infrastructure.Tests/Caching/CacheGenerationsTests.cs
  36. 50
      backend/tests/Squidex.Infrastructure.Tests/Caching/JsonHybridCacheSerializerTests.cs
  37. 30
      backend/tests/Squidex.Infrastructure.Tests/Queries/QueryJsonTests.cs
  38. 78
      backend/tests/Squidex.Web.Tests/Pipeline/ContextFilterTests.cs

13
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; }
}

74
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<IAssetEnricherStep> steps) : IAsse
using (var activity = Telemetry.Activities.StartActivity("AssetEnricher/EnrichAsync"))
{
var results = new List<EnrichedAsset>();
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<EnrichedAsset> 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<IAssetEnricherStep> stepsToRun, IReadOnlyList<EnrichedAsset> 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);
}
}
}
}

212
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<AssetQueryCacheOptions> options,
ILogger<CachingAssetQueryService> log)
: IAssetQueryService, ICommandMiddleware
{
private sealed record CachedAssets(long Total, EnrichedAsset[] Items);
private sealed record CacheKey(string Generation, long AppVersion, DomainId? ParentId, IReadOnlyDictionary<string, string> 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<IResultList<EnrichedAsset>> 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<EnrichedAsset?> 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<EnrichedAsset?> FindBySlugAsync(Context context, string slug, bool allowDeleted = false,
CancellationToken ct = default)
{
return inner.FindBySlugAsync(context, slug, allowDeleted, ct);
}
public Task<IResultList<AssetFolder>> QueryAssetFoldersAsync(Context context, DomainId? parentId,
CancellationToken ct = default)
{
return inner.QueryAssetFoldersAsync(context, parentId, ct);
}
public Task<IReadOnlyList<AssetFolder>> FindAssetFolderAsync(DomainId appId, DomainId id,
CancellationToken ct = default)
{
return inner.FindAssetFolderAsync(appId, id, ct);
}
public Task<EnrichedAsset?> FindByHashAsync(Context context, string hash, string fileName, long fileSize,
CancellationToken ct = default)
{
return inner.FindByHashAsync(context, hash, fileName, fileSize, ct);
}
public Task<EnrichedAsset?> 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<string?> 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);
}
}

3
backend/src/Squidex.Domain.Apps.Entities/Assets/Queries/IAssetEnricher.cs

@ -16,4 +16,7 @@ public interface IAssetEnricher
Task<IReadOnlyList<EnrichedAsset>> EnrichAsync(IEnumerable<Asset> assets, Context context,
CancellationToken ct);
Task EnrichCachedAsync(IReadOnlyList<EnrichedAsset> assets, Context context,
CancellationToken ct);
}

2
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<EnrichedAsset> assets,
CancellationToken ct);

2
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)
{

13
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; }
}

235
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<ContentQueryCacheOptions> options,
ILogger<CachingContentQueryService> log)
: IContentQueryService, ICommandMiddleware
{
private sealed record CachedContents(long Total, EnrichedContent[] Items);
private sealed record CacheKey(string Generation, long AppVersion, DomainId SchemaId, long SchemaVersion, IReadOnlyDictionary<string, string> 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<EnrichedContent> StreamAsync(Context context, string schemaIdOrName, int skip,
CancellationToken ct = default)
{
return inner.StreamAsync(context, schemaIdOrName, skip, ct);
}
public Task<IResultList<EnrichedContent>> 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<IResultList<EnrichedContent>> 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<EnrichedContent?> 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<Schema> GetSchemaOrThrowAsync(Context context, string schemaIdOrName,
CancellationToken ct = default)
{
return inner.GetSchemaOrThrowAsync(context, schemaIdOrName, ct);
}
public Task<Schema?> GetSchemaAsync(Context context, string schemaIdOrName,
CancellationToken ct = default)
{
return inner.GetSchemaAsync(context, schemaIdOrName, ct);
}
private async Task<string?> 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);
}
}

93
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<IContentEnricherStep> steps, IAp
return EnrichInternalAsync(contents, false, context, ct);
}
public async Task EnrichCachedAsync(IReadOnlyList<EnrichedContent> 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<IReadOnlyList<EnrichedContent>> EnrichInternalAsync(IEnumerable<Content> contents, bool cloneData, Context context,
CancellationToken ct)
{
@ -40,19 +52,6 @@ public sealed class ContentEnricher(IEnumerable<IContentEnricherStep> steps, IAp
{
var results = new List<EnrichedContent>();
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<IContentEnricherStep> steps, IAp
results.Add(result);
}
if (context.App != null)
{
var schemaCache = new Dictionary<DomainId, Task<(Schema, ResolvedComponents)>>();
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<IContentEnricherStep> stepsToRun, IReadOnlyList<EnrichedContent> 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<DomainId, Task<(Schema, ResolvedComponents)>>();
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);
}
}
}
}

3
backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/IContentEnricher.cs

@ -16,4 +16,7 @@ public interface IContentEnricher
Task<IReadOnlyList<EnrichedContent>> EnrichAsync(IEnumerable<Content> contents, Context context,
CancellationToken ct);
Task EnrichCachedAsync(IReadOnlyList<EnrichedContent> contents, Context context,
CancellationToken ct);
}

3
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<EnrichedContent> contents, ProvideSchema schemas,
CancellationToken ct);

2
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)
{

19
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<string, string> EmptyHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private static readonly SortedDictionary<string, string> EmptyHeaders = new SortedDictionary<string, string>(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<string, string[]> headerValues = new ConcurrentDictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
public IReadOnlyDictionary<string, string> Headers { get; }
// The headers are sorted, so that they can be serialized to stable cache keys.
private readonly SortedDictionary<string, string> headers;
public IReadOnlyDictionary<string, string> Headers => headers;
public ClaimsPermissions UserPermissions { get; }
@ -49,7 +52,7 @@ public sealed class Context
App app,
ClaimsPrincipal userPrincipal,
ClaimsPermissions userPermissions,
IReadOnlyDictionary<string, string> headers)
SortedDictionary<string, string> 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<string, string>? headers;
private SortedDictionary<string, string>? headers;
public Context Build()
{
@ -119,20 +122,20 @@ public sealed class Context
public void Remove(string key)
{
headers ??= new Dictionary<string, string>(context.Headers, StringComparer.OrdinalIgnoreCase);
headers ??= new SortedDictionary<string, string>(context.headers, StringComparer.OrdinalIgnoreCase);
headers.Remove(key);
}
public void SetHeader(string key, string value)
{
headers ??= new Dictionary<string, string>(context.Headers, StringComparer.OrdinalIgnoreCase);
headers ??= new SortedDictionary<string, string>(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<ICloneBuilder> action)

11
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);

103
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<CacheGenerationsOptions> options,
ILogger<CacheGenerations> 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<string, bool> pendingKeys = new ConcurrentDictionary<string, bool>();
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<string> 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<string> 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}";
}
}

13
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);
}

16
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<string> GetAsync(string key,
CancellationToken ct = default);
void Reset(string key);
}

27
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<T>(IJsonSerializer serializer) : IHybridCacheSerializer<T>
{
public T Deserialize(ReadOnlySequence<byte> source)
{
using var stream = new MemoryStream(source.ToArray(), false);
return serializer.Deserialize<T>(stream);
}
public void Serialize(T value, IBufferWriter<byte> target)
{
target.Write(serializer.SerializeToBytes(value));
}
}

21
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<T>([NotNullWhen(true)] out IHybridCacheSerializer<T>? result)
{
result = new JsonHybridCacheSerializer<T>(serializer);
return true;
}
}

2
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:

20
backend/src/Squidex.Infrastructure/Queries/Json/JsonFilterSurrogate.cs

@ -25,7 +25,25 @@ public sealed class JsonFilterSurrogate : ISurrogate<FilterNode<JsonValue>>
public void FromSource(FilterNode<JsonValue> source)
{
throw new NotSupportedException();
switch (source)
{
case NegateFilter<JsonValue> negate:
Not = negate.Filter;
break;
case LogicalFilter<JsonValue> { Type: LogicalFilterType.And } and:
And = [.. and.Filters];
break;
case LogicalFilter<JsonValue> or:
Or = [.. or.Filters];
break;
case CompareFilter<JsonValue> compare:
Path = compare.Path.ToString();
Op = compare.Operator;
Value = compare.Value;
break;
default:
throw new NotSupportedException();
}
}
public FilterNode<JsonValue> ToSource()

14
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;
}
}

20
backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs

@ -46,12 +46,13 @@ public class SchemaContentsController(ICommandBus commandBus, IJobService jobSer
public async Task<IActionResult> 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);

19
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<ScriptAsset>()
.As<IAssetEnricherStep>();
services.AddSingletonAs<AssetQueryService>()
.As<IAssetQueryService>();
if (config.GetValue<TimeSpan>("caching:assets:cacheDuration") > TimeSpan.Zero)
{
services.Configure<AssetQueryCacheOptions>(config,
"caching:assets");
services.AddSingletonAs<AssetQueryService>()
.AsSelf();
services.AddSingletonAs(c => ActivatorUtilities.CreateInstance<CachingAssetQueryService>(c, c.GetRequiredService<AssetQueryService>()))
.As<IAssetQueryService>().As<ICommandMiddleware>();
}
else
{
services.AddSingletonAs<AssetQueryService>()
.As<IAssetQueryService>();
}
services.AddSingletonAs<AssetLoader>()
.As<IAssetLoader>();

19
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<ContentHistoryEventsCreator>()
.As<IHistoryEventsCreator>();
services.AddSingletonAs<ContentQueryService>()
.As<IContentQueryService>();
if (config.GetValue<TimeSpan>("caching:contents:cacheDuration") > TimeSpan.Zero)
{
services.Configure<ContentQueryCacheOptions>(config,
"caching:contents");
services.AddSingletonAs<ContentQueryService>()
.AsSelf();
services.AddSingletonAs(c => ActivatorUtilities.CreateInstance<CachingContentQueryService>(c, c.GetRequiredService<ContentQueryService>()))
.As<IContentQueryService>().As<ICommandMiddleware>();
}
else
{
services.AddSingletonAs<ContentQueryService>()
.As<IContentQueryService>();
}
services.AddSingletonAs<ConvertData>()
.As<IContentEnricherStep>();

10
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<JsonHybridCacheSerializerFactory>();
services.Configure<CacheGenerationsOptions>(config,
"caching:generations");
services.AddSingletonAs<CacheGenerations>()
.As<ICacheGenerations>();
services.AddSingletonAs(_ => SystemClock.Instance)
.As<IClock>();

1
backend/src/Squidex/Squidex.csproj

@ -45,6 +45,7 @@
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="10.0.6" />
<PackageReference Include="Microsoft.CodeAnalysis.RulesetToEditorconfigConverter" Version="4.14.0" />
<PackageReference Include="Microsoft.Data.Edm" Version="5.8.5" />
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.5.0" />
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.17.0" />
<PackageReference Include="Microsoft.OData.Core" Version="8.4.3" />
<PackageReference Include="NetTopologySuite.IO.GeoJSON4STJ" Version="4.0.0" />

19
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"
}
},

33
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<IAssetEnricherStep>();
var step2 = A.Fake<IAssetEnricherStep>();
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<Context>._, A<CancellationToken>._))
.MustNotHaveHappened();
A.CallTo(() => step2.EnrichAsync(A<Context>._, A<IEnumerable<EnrichedAsset>>._, A<CancellationToken>._))
.MustNotHaveHappened();
}
[Fact]
public void Should_run_caching_step_for_cached_results()
{
IAssetEnricherStep step = new Steps.EnrichForCaching(A.Fake<Infrastructure.Caching.IRequestCache>());
Assert.True(step.RunOnCachedResults);
}
[Fact]
public async Task Should_invoke_steps()
{

360
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<IAssetQueryService>();
private readonly IAssetEnricher assetEnricher = A.Fake<IAssetEnricher>();
private readonly IDistributedCache distributedCache = A.Fake<IDistributedCache>(x => x.Wrapping(new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()))));
private readonly IOptions<AssetQueryCacheOptions> options = Options.Create(new AssetQueryCacheOptions { CacheDuration = TimeSpan.FromMinutes(1) });
private readonly ICacheGenerations generations = A.Fake<ICacheGenerations>();
private readonly CachingAssetQueryService sut;
private readonly EnrichedAsset asset;
private readonly Dictionary<string, string> generationValues = [];
public CachingAssetQueryServiceTests()
{
asset = CreateAsset();
A.CallTo(() => inner.QueryAsync(A<Context>._, A<DomainId?>._, A<Q>._, A<CancellationToken>._))
.ReturnsLazily(() => ResultList.CreateFrom(10, asset));
A.CallTo(() => inner.FindAsync(A<Context>._, asset.Id, A<bool>._, A<long>._, A<CancellationToken>._))
.ReturnsLazily(() => asset);
A.CallTo(() => inner.FindBySlugAsync(A<Context>._, "my-slug", A<bool>._, A<CancellationToken>._))
.ReturnsLazily(() => asset);
A.CallTo(() => generations.GetAsync(A<string>._, A<CancellationToken>._))
.ReturnsLazily((string key, CancellationToken _) => generationValues.GetValueOrDefault(key, "1"));
A.CallTo(() => generations.Reset(A<string>._))
.Invokes(x => generationValues[x.GetArgument<string>(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<Context>._, A<DomainId?>._, A<Q>._, A<CancellationToken>._))
.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<IReadOnlyList<EnrichedAsset>>.That.Matches(x => x.Single().Id == asset.Id), ApiContext, A<CancellationToken>._))
.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<IReadOnlyList<EnrichedAsset>>._, A<Context>._, A<CancellationToken>._))
.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<Context>._, A<DomainId?>._, A<Q>._, A<CancellationToken>._))
.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<Context>._, A<DomainId?>._, A<Q>._, A<CancellationToken>._))
.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<Context>._, A<DomainId?>._, A<Q>._, A<CancellationToken>._))
.MustHaveHappenedTwiceExactly();
}
[Fact]
public async Task Should_query_inner_service_if_generation_cannot_be_read()
{
var failingGenerations = A.Fake<ICacheGenerations>();
A.CallTo(() => failingGenerations.GetAsync(A<string>._, A<CancellationToken>._))
.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<Context>._, asset.Id, false, EtagVersion.Any, A<CancellationToken>._))
.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<Context>._, "my-slug", false, A<CancellationToken>._))
.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 = "<query-script>" } };
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 = "<query-script>" } };
await QueryTwiceAsync(ApiContext.Clone(b => b.WithNoScripting()), null, Q.Empty);
A.CallTo(() => inner.QueryAsync(A<Context>._, A<DomainId?>._, A<Q>._, A<CancellationToken>._))
.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<Context>._, A<DomainId?>._, A<Q>._, A<CancellationToken>._))
.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<JsonValue> { 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<Context>._, "hash", "file", 100, A<CancellationToken>._))
.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<Context>._, asset.Id, A<CancellationToken>._))
.MustHaveHappenedTwiceExactly();
}
[Fact]
public async Task Should_reset_generation_if_asset_changed()
{
await HandleAsync(new AnnotateAsset { AppId = AppId });
A.CallTo(() => generations.Reset(A<string>._))
.MustHaveHappenedOnceExactly();
}
[Fact]
public async Task Should_reset_generation_if_asset_deleted()
{
await HandleAsync(new DeleteAsset { AppId = AppId });
A.CallTo(() => generations.Reset(A<string>._))
.MustHaveHappenedOnceExactly();
}
[Fact]
public async Task Should_not_reset_generation_if_folder_changed()
{
await HandleAsync(new RenameAssetFolder { AppId = AppId });
A.CallTo(() => generations.Reset(A<string>._))
.MustNotHaveHappened();
}
[Fact]
public async Task Should_not_reset_generation_if_command_failed()
{
var commandContext = new CommandContext(new AnnotateAsset { AppId = AppId }, A.Fake<ICommandBus>());
await Assert.ThrowsAsync<InvalidOperationException>(() =>
sut.HandleAsync(commandContext, (_, _) => throw new InvalidOperationException(), CancellationToken));
A.CallTo(() => generations.Reset(A<string>._))
.MustNotHaveHappened();
}
private Task HandleAsync(ICommand command)
{
return sut.HandleAsync(new CommandContext(command, A.Fake<ICommandBus>()), (_, _) => Task.CompletedTask, CancellationToken);
}
private async Task<IResultList<EnrichedAsset>> 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<Context>._, A<DomainId?>._, A<Q>._, A<CancellationToken>._))
.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<ILogger<CachingAssetQueryService>>());
}
private static HybridCache CreateHybridCache(IDistributedCache cache, IJsonSerializer serializer)
{
var services = new ServiceCollection();
services.AddSingleton(cache);
services.AddSingleton(serializer);
services.AddHybridCache()
.AddSerializerFactory<JsonHybridCacheSerializerFactory>();
return services.BuildServiceProvider().GetRequiredService<HybridCache>();
}
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<string>(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<string>.That.Not.StartsWith("__MSFT_HCT__"), A<CancellationToken>._))
.MustNotHaveHappened();
A.CallTo(() => distributedCache.SetAsync(A<string>._, A<byte[]>._, A<DistributedCacheEntryOptions>._, A<CancellationToken>._))
.MustNotHaveHappened();
}
}

479
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<FilterNode<JsonValue>, JsonFilterSurrogate>());
});
private readonly IContentQueryService inner = A.Fake<IContentQueryService>();
private readonly IContentEnricher contentEnricher = A.Fake<IContentEnricher>();
private readonly IDistributedCache distributedCache = A.Fake<IDistributedCache>(x => x.Wrapping(new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()))));
private readonly IOptions<ContentQueryCacheOptions> options = Options.Create(new ContentQueryCacheOptions { CacheDuration = TimeSpan.FromMinutes(1) });
private readonly ICacheGenerations generations = A.Fake<ICacheGenerations>();
private readonly CachingContentQueryService sut;
private readonly EnrichedContent content;
private readonly Dictionary<string, string> generationValues = [];
public CachingContentQueryServiceTests()
{
content = CreateContent();
A.CallTo(() => inner.GetSchemaOrThrowAsync(A<Context>._, SchemaId.Name, A<CancellationToken>._))
.ReturnsLazily(() => Schema);
A.CallTo(() => inner.QueryAsync(A<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.ReturnsLazily(() => ResultList.CreateFrom(10, content));
A.CallTo(() => inner.FindAsync(A<Context>._, SchemaId.Name, content.Id, A<long>._, A<CancellationToken>._))
.ReturnsLazily(() => content);
A.CallTo(() => generations.GetAsync(A<string>._, A<CancellationToken>._))
.ReturnsLazily((string key, CancellationToken _) => generationValues.GetValueOrDefault(key, "1"));
A.CallTo(() => generations.Reset(A<string>._))
.Invokes(x => generationValues[x.GetArgument<string>(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<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.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<IReadOnlyList<EnrichedContent>>.That.Matches(x => x.Single().Id == content.Id), requestContext, A<CancellationToken>._))
.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<IReadOnlyList<EnrichedContent>>._, A<Context>._, A<CancellationToken>._))
.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<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.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<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.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<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.MustHaveHappenedTwiceExactly();
}
[Fact]
public async Task Should_query_inner_service_if_generation_cannot_be_read()
{
var failingGenerations = A.Fake<ICacheGenerations>();
A.CallTo(() => failingGenerations.GetAsync(A<string>._, A<CancellationToken>._))
.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<Context>._, SchemaId.Name, content.Id, EtagVersion.Any, A<CancellationToken>._))
.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 = "<query-script>" } };
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 = "<query-script>" } };
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 = "<query-script>" } };
await QueryTwiceAsync(CreateApiContext().Clone(b => b.WithNoScripting()), Q.Empty);
A.CallTo(() => inner.QueryAsync(A<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.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<JsonValue> { 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<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.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<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.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<Context>._, A<Q>._, A<CancellationToken>._))
.MustHaveHappenedTwiceExactly();
}
[Fact]
public async Task Should_reset_generation_if_content_changed()
{
await HandleAsync(new UpdateContent { AppId = AppId });
A.CallTo(() => generations.Reset(A<string>._))
.MustHaveHappenedOnceExactly();
}
[Fact]
public async Task Should_reset_generation_if_asset_deleted()
{
await HandleAsync(new DeleteAsset { AppId = AppId });
A.CallTo(() => generations.Reset(A<string>._))
.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<string>._))
.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<string>._))
.MustNotHaveHappened();
}
[Fact]
public async Task Should_not_reset_generation_if_asset_changed()
{
await HandleAsync(new AnnotateAsset { AppId = AppId });
A.CallTo(() => generations.Reset(A<string>._))
.MustNotHaveHappened();
}
[Fact]
public async Task Should_not_reset_generation_if_command_failed()
{
var commandContext = new CommandContext(new UpdateContent { AppId = AppId }, A.Fake<ICommandBus>());
await Assert.ThrowsAsync<InvalidOperationException>(() =>
sut.HandleAsync(commandContext, (_, _) => throw new InvalidOperationException(), CancellationToken));
A.CallTo(() => generations.Reset(A<string>._))
.MustNotHaveHappened();
}
private Task HandleAsync(ICommand command)
{
return sut.HandleAsync(new CommandContext(command, A.Fake<ICommandBus>()), (_, _) => Task.CompletedTask, CancellationToken);
}
private async Task<IResultList<EnrichedContent>> 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<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.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<Context>._, SchemaId.Name, A<Q>._, A<CancellationToken>._))
.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<ILogger<CachingContentQueryService>>());
}
private static HybridCache CreateHybridCache(IDistributedCache cache, IJsonSerializer serializer)
{
var services = new ServiceCollection();
services.AddSingleton(cache);
services.AddSingleton(serializer);
services.AddHybridCache()
.AddSerializerFactory<JsonHybridCacheSerializerFactory>();
return services.BuildServiceProvider().GetRequiredService<HybridCache>();
}
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<string>(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<string>.That.Not.StartsWith("__MSFT_HCT__"), A<CancellationToken>._))
.MustNotHaveHappened();
A.CallTo(() => distributedCache.SetAsync(A<string>._, A<byte[]>._, A<DistributedCacheEntryOptions>._, A<CancellationToken>._))
.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<JsonValue> CreateJsonQuery(string field, int value)
{
return new Query<JsonValue>
{
Filter = new CompareFilter<JsonValue>($"data.{field}", CompareOperator.Equals, value),
};
}
}

33
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<IContentEnricherStep>();
var step2 = A.Fake<IContentEnricherStep>();
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<ProvideSchema>._, CancellationToken))
.MustHaveHappened();
A.CallTo(() => step2.EnrichAsync(A<Context>._, A<CancellationToken>._))
.MustNotHaveHappened();
A.CallTo(() => step2.EnrichAsync(A<Context>._, A<IEnumerable<EnrichedContent>>._, A<ProvideSchema>._, A<CancellationToken>._))
.MustNotHaveHappened();
}
[Fact]
public void Should_run_caching_step_for_cached_results()
{
IContentEnricherStep step = new Steps.EnrichForCaching(A.Fake<Infrastructure.Caching.IRequestCache>());
Assert.True(step.RunOnCachedResults);
}
[Fact]
public async Task Should_invoke_steps()
{

35
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"]);
}
}

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Squidex.Domain.Apps.Entities.Tests.csproj

@ -33,6 +33,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.5.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="10.0.6" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.6" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.4.0" />

141
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<IDistributedCache>(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<ILogger<CacheGenerations>>());
}
[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<byte[]>._,
A<DistributedCacheEntryOptions>.That.Matches(x =>
x.AbsoluteExpiration == null &&
x.AbsoluteExpirationRelativeToNow == null &&
x.SlidingExpiration == null),
A<CancellationToken>._))
.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<byte[]>._, A<DistributedCacheEntryOptions>._, A<CancellationToken>._))
.MustHaveHappenedOnceExactly();
A.CallTo(() => cache.SetAsync("generation/key2", A<byte[]>._, A<DistributedCacheEntryOptions>._, A<CancellationToken>._))
.MustHaveHappenedOnceExactly();
}
[Fact]
public async Task Should_not_throw_if_flush_fails()
{
A.CallTo(() => cache.SetAsync(A<string>._, A<byte[]>._, A<DistributedCacheEntryOptions>._, A<CancellationToken>._))
.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<byte[]>._, A<DistributedCacheEntryOptions>._, A<CancellationToken>._))
.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<byte[]>._, A<DistributedCacheEntryOptions>._, A<CancellationToken>._))
.MustHaveHappenedOnceExactly();
}
}

50
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<Value>(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<Value>(out var serializer));
var source = new Value("text", 42, DomainId.NewGuid());
Assert.Equal(source, SerializeAndDeserialize(serializer, source));
}
private static T SerializeAndDeserialize<T>(IHybridCacheSerializer<T> serializer, T value)
{
var buffer = new ArrayBufferWriter<byte>();
serializer.Serialize(value, buffer);
return serializer.Deserialize(new ReadOnlySequence<byte>(buffer.WrittenMemory));
}
}

30
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<CompareOperator>())
{
var serialized = TestUtils.DefaultSerializer.Serialize(op);
Assert.Equal(op, TestUtils.DefaultSerializer.Deserialize<CompareOperator>(serialized));
}
}
[Fact]
public void Should_serialize_and_deserialize_filter()
{
var source =
new LogicalFilter<JsonValue>(LogicalFilterType.Or,
[
new LogicalFilter<JsonValue>(LogicalFilterType.And,
[
new CompareFilter<JsonValue>("property1", CompareOperator.GreaterThanOrEqual, 10),
new CompareFilter<JsonValue>("property2", CompareOperator.In, JsonValue.Array(1, 2)),
]),
new NegateFilter<JsonValue>(new CompareFilter<JsonValue>("property3", CompareOperator.Empty, default)),
]);
var filter = SerializeAndDeserialize<FilterNode<JsonValue>>(source);
Assert.Equal(source.ToString(), filter.ToString());
}
private static FilterNode<JsonValue> SerializeAndDeserialize<T>(T value)
{
var json = TestUtils.DefaultSerializer.Serialize(value, true);

78
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<string, object?>(), 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<Context> ExecuteAsync()
{
await sut.OnActionExecutionAsync(executingContext, () => Task.FromResult<ActionExecutedContext>(null!));
return httpContext.Features.Get<Context>()!;
}
}
Loading…
Cancel
Save