mirror of https://github.com/Squidex/squidex.git
committed by
GitHub
38 changed files with 2136 additions and 93 deletions
@ -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; } |
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
@ -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; } |
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
@ -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}"; |
|||
} |
|||
} |
|||
@ -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); |
|||
} |
|||
@ -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); |
|||
} |
|||
@ -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)); |
|||
} |
|||
} |
|||
@ -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; |
|||
} |
|||
} |
|||
@ -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(); |
|||
} |
|||
} |
|||
@ -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), |
|||
}; |
|||
} |
|||
} |
|||
@ -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(); |
|||
} |
|||
} |
|||
@ -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)); |
|||
} |
|||
} |
|||
@ -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…
Reference in new issue