diff --git a/backend/src/Migrations/MigrationPath.cs b/backend/src/Migrations/MigrationPath.cs index 3eb088fc4..c52deadcf 100644 --- a/backend/src/Migrations/MigrationPath.cs +++ b/backend/src/Migrations/MigrationPath.cs @@ -16,7 +16,7 @@ namespace Migrations; public sealed class MigrationPath(IServiceProvider serviceProvider) : IMigrationPath { - private const int CurrentVersion = 27; + private const int CurrentVersion = 28; public (int Version, IEnumerable? Migrations) GetNext(int version) { @@ -126,5 +126,11 @@ public sealed class MigrationPath(IServiceProvider serviceProvider) : IMigration { yield return serviceProvider.GetService(); } + + // Version 28: New asset indexes. + if (version < 28) + { + yield return serviceProvider.GetService(); + } } } diff --git a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Assets/MongoAssetRepository.cs b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Assets/MongoAssetRepository.cs index ed8e5afe8..b21142ba2 100644 --- a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Assets/MongoAssetRepository.cs +++ b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Assets/MongoAssetRepository.cs @@ -45,16 +45,23 @@ public sealed partial class MongoAssetRepository : MongoRepositoryBase collection, CancellationToken ct) { + // Equality fields first, then the default sort order, so that pages and counts are bounded by the app or folder. return collection.Indexes.CreateManyAsync( [ new CreateIndexModel( Index + .Ascending(x => x.IndexedAppId) .Descending(x => x.LastModified) .Ascending(x => x.Id) - .Ascending(x => x.IndexedAppId) .Ascending(x => x.IsDeleted) - .Ascending(x => x.ParentId) .Ascending(x => x.Tags)), + new CreateIndexModel( + Index + .Ascending(x => x.IndexedAppId) + .Ascending(x => x.ParentId) + .Descending(x => x.LastModified) + .Ascending(x => x.Id) + .Ascending(x => x.IsDeleted)), new CreateIndexModel( Index .Ascending(x => x.IndexedAppId) @@ -279,8 +286,6 @@ public sealed partial class MongoAssetRepository : MongoRepositoryBase BuildFilter(DomainId appId, DomainId parentId) { return Filter.And( - Filter.Gt(x => x.LastModified, default), - Filter.Gt(x => x.Id, DomainId.Create(string.Empty)), Filter.Eq(x => x.IndexedAppId, appId), Filter.Ne(x => x.IsDeleted, true), Filter.Eq(x => x.ParentId, parentId)); diff --git a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Assets/Visitors/FindExtensions.cs b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Assets/Visitors/FindExtensions.cs index 3905a3eb5..137b6d77e 100644 --- a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Assets/Visitors/FindExtensions.cs +++ b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Assets/Visitors/FindExtensions.cs @@ -39,8 +39,6 @@ public static class FindExtensions { var filters = new List> { - Filter.Ne(x => x.LastModified, default), - Filter.Ne(x => x.Id, default), Filter.Eq(x => x.IndexedAppId, appId), }; diff --git a/backend/src/Squidex.Data.MongoDb/Migrations/DropOldAssetIndex.cs b/backend/src/Squidex.Data.MongoDb/Migrations/DropOldAssetIndex.cs new file mode 100644 index 000000000..f1fcc16f0 --- /dev/null +++ b/backend/src/Squidex.Data.MongoDb/Migrations/DropOldAssetIndex.cs @@ -0,0 +1,38 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using MongoDB.Bson; +using MongoDB.Driver; +using Squidex.Infrastructure.Migrations; + +namespace Squidex.Migrations; + +public sealed class DropOldAssetIndex(IMongoDatabase database) : IMigration +{ + // The old index started with the sort fields and was therefore not bounded by the app. + public const string IndexName = "mt_-1_id_1__ai_1_dl_1_pi_1_td_1"; + + public async Task UpdateAsync( + CancellationToken ct) + { + // Each asset shard has its own collection. + var collectionNames = await (await database.ListCollectionNamesAsync(cancellationToken: ct)).ToListAsync(ct); + + foreach (var collectionName in collectionNames.Where(x => x.StartsWith("States_Assets2", StringComparison.Ordinal))) + { + var collection = database.GetCollection(collectionName); + try + { + await collection.Indexes.DropOneAsync(IndexName, ct); + } + catch (MongoCommandException ex) when (ex.Code == 27) + { + // The index does not exist, for example in the count collections. + } + } + } +} diff --git a/backend/src/Squidex.Data.MongoDb/ServiceExtensions.cs b/backend/src/Squidex.Data.MongoDb/ServiceExtensions.cs index 6b5da55e5..5427c2df5 100644 --- a/backend/src/Squidex.Data.MongoDb/ServiceExtensions.cs +++ b/backend/src/Squidex.Data.MongoDb/ServiceExtensions.cs @@ -292,6 +292,9 @@ public static class ServiceExtensions services.AddTransientAs() .As(); + + services.AddTransientAs() + .As(); } private static IMongoClient GetMongoClient(IConfiguration config, JsonSerializerOptions serializerOptions, string prefix) diff --git a/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Assets/MongoAssetRepositoryIndexTests.cs b/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Assets/MongoAssetRepositoryIndexTests.cs new file mode 100644 index 000000000..568304fa7 --- /dev/null +++ b/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Assets/MongoAssetRepositoryIndexTests.cs @@ -0,0 +1,301 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.Extensions.Logging; +using MongoDB.Driver; +using NodaTime; +using Squidex.Domain.Apps.Core.Assets; +using Squidex.Domain.Apps.Entities; +using Squidex.Domain.Apps.Entities.MongoDb.Assets; +using Squidex.Domain.Apps.Entities.TestHelpers; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Queries; +using Squidex.Infrastructure.States; +using Squidex.MongoDb.TestHelpers; + +namespace Squidex.MongoDb.Domain.Assets; + +[Trait("Category", "TestContainer")] +[Collection(MongoFixtureCollection.Name)] +public class MongoAssetRepositoryIndexTests : GivenContext, IAsyncLifetime +{ + private const string CollectionName = "States_Assets2"; + private const int PageSize = 20; + private const int NumNoise = 10_000; + private const int NumRoot = 200; + private const int NumFolder = 100; + private const int NumDeleted = 20; + private const int NumTarget = NumRoot + NumFolder + NumDeleted; + private const int MaxExaminedForPage = (PageSize * 2) + 10; + private const int MaxExaminedForApp = (NumTarget * 2) + 10; + private static readonly Instant NoiseTime = Instant.FromUtc(2025, 1, 1, 0, 0); + private static readonly Instant TargetTime = Instant.FromUtc(2024, 1, 1, 0, 0); + private static readonly NamedId NoiseAppId = NamedId.Of(DomainId.Create("2e4f5a3c-0a51-4c38-8a85-6a4b7c0f0001"), "noise"); + private static readonly NamedId TargetAppId = NamedId.Of(DomainId.Create("2e4f5a3c-0a51-4c38-8a85-6a4b7c0f0002"), "target"); + private static readonly DomainId NoiseFolderId = DomainId.Create("2e4f5a3c-0a51-4c38-8a85-6a4b7c0f0003"); + private static readonly DomainId TargetFolderId = DomainId.Create("2e4f5a3c-0a51-4c38-8a85-6a4b7c0f0004"); + private readonly MongoQueryProfiler profiler; + private readonly MongoAssetRepository sut; + + public MongoAssetRepositoryIndexTests(MongoFixture fixture) + { + // Use a dedicated database to control the data distribution. + var database = fixture.Client.GetDatabase("Test_AssetIndexes"); + + profiler = new MongoQueryProfiler(database, CollectionName); + + sut = new MongoAssetRepository(database, A.Fake>(), string.Empty); + } + + public async ValueTask InitializeAsync() + { + await sut.InitializeAsync(default); + await SeedAsync(); + } + + public ValueTask DisposeAsync() + { + return default; + } + + [Fact] + public async Task Should_use_index_to_query_assets_of_app() + { + await AssertPlansAsync(MaxExaminedForPage, () => + sut.QueryAsync(TargetAppId.Id, null, PageQuery(new ClrQuery()))); + } + + [Fact] + public async Task Should_use_index_to_query_assets_in_root_folder() + { + await AssertPlansAsync(MaxExaminedForPage, () => + sut.QueryAsync(TargetAppId.Id, DomainId.Empty, PageQuery(new ClrQuery()))); + } + + [Fact] + public async Task Should_use_index_to_query_assets_in_folder() + { + await AssertPlansAsync(MaxExaminedForPage, () => + sut.QueryAsync(TargetAppId.Id, TargetFolderId, PageQuery(new ClrQuery()))); + } + + [Fact] + public async Task Should_use_index_to_query_assets_by_tag() + { + var query = new ClrQuery + { + Filter = ClrFilter.Eq("tags", "tag-even"), + }; + + await AssertPlansAsync(MaxExaminedForApp, () => + sut.QueryAsync(TargetAppId.Id, null, PageQuery(query))); + } + + [Fact] + public async Task Should_use_index_to_count_assets_by_tag() + { + var query = new ClrQuery + { + Filter = ClrFilter.Eq("tags", "tag-even"), + }; + + var profiles = await AssertPlansAsync(MaxExaminedForApp, () => + sut.QueryAsync(TargetAppId.Id, null, PageQuery(query, withTotal: true))); + + // The query for the page and the query for the total. + Assert.Equal(2, profiles.Count); + } + + [Fact] + public async Task Should_use_index_to_count_assets_in_folder() + { + var query = new ClrQuery + { + Filter = ClrFilter.Eq("tags", "tag-even"), + }; + + var profiles = await AssertPlansAsync(MaxExaminedForApp, () => + sut.QueryAsync(TargetAppId.Id, TargetFolderId, PageQuery(query, withTotal: true))); + + // The query for the page and the query for the total. + Assert.Equal(2, profiles.Count); + } + + [Fact] + public async Task Should_use_index_to_query_assets_randomly() + { + var query = new ClrQuery + { + Random = 5, + }; + + await AssertPlansAsync(MaxExaminedForPage, () => + sut.QueryAsync(TargetAppId.Id, null, PageQuery(query))); + } + + [Fact] + public async Task Should_use_index_to_query_assets_by_ids() + { + var ids = await GetTargetIdsAsync(); + + await AssertPlansAsync(MaxExaminedForPage, () => + sut.QueryAsync(TargetAppId.Id, null, Q.Empty.WithIds(ids).WithQuery(SortedQuery(new ClrQuery()))), allowSort: true); + } + + [Fact] + public async Task Should_use_index_to_query_ids() + { + var ids = await GetTargetIdsAsync(); + + await AssertPlansAsync(MaxExaminedForPage, () => + sut.QueryIdsAsync(TargetAppId.Id, ids)); + } + + [Fact] + public async Task Should_use_index_to_query_child_ids() + { + await AssertPlansAsync(NumFolder + 10, () => + sut.QueryChildIdsAsync(TargetAppId.Id, TargetFolderId)); + } + + [Fact] + public async Task Should_use_index_to_stream_assets_of_app() + { + await AssertPlansAsync(MaxExaminedForApp, () => + sut.StreamAll(TargetAppId.Id).ToListAsync().AsTask()); + } + + [Fact] + public async Task Should_use_index_to_find_asset_by_id() + { + var id = (await GetTargetIdsAsync()).First(); + + await AssertPlansAsync(1, () => + sut.FindAssetAsync(TargetAppId.Id, id, false)); + } + + [Fact] + public async Task Should_use_index_to_find_asset_by_id_only() + { + var id = (await GetTargetIdsAsync()).First(); + + await AssertPlansAsync(1, () => + sut.FindAssetAsync(id)); + } + + [Fact] + public async Task Should_use_index_to_find_asset_by_slug() + { + await AssertPlansAsync(1, () => + sut.FindAssetBySlugAsync(TargetAppId.Id, "target-42", false)); + } + + [Fact] + public async Task Should_use_index_to_find_asset_by_hash() + { + await AssertPlansAsync(1, () => + sut.FindAssetByHashAsync(TargetAppId.Id, "hash-42", "file-42.png", 1024)); + } + + private async Task> AssertPlansAsync(int maxExamined, Func action, bool allowSort = false) + { + var profiles = await profiler.ProfileAsync(action); + + Assert.NotEmpty(profiles); + + foreach (var profile in profiles) + { + MongoQueryProfiler.AssertIndexed(profile, allowSort); + + var examined = Math.Max(profile.KeysExamined, profile.DocsExamined); + + Assert.True(examined <= maxExamined, $"Examined more than {maxExamined}: {profile}"); + } + + return profiles; + } + + private async Task> GetTargetIdsAsync() + { + return await sut.StreamAll(TargetAppId.Id).Take(PageSize).Select(x => x.Id).ToHashSetAsync(); + } + + private static Q PageQuery(ClrQuery query, bool withTotal = false) + { + var q = Q.Empty.WithQuery(SortedQuery(query)); + + return withTotal ? q : q.WithoutTotal(); + } + + private static ClrQuery SortedQuery(ClrQuery query) + { + // Same default sorting as the asset query parser. + query.Take = PageSize; + query.Sort = + [ + new SortNode("lastModified", SortOrder.Descending), + new SortNode("id", SortOrder.Ascending), + ]; + + return query; + } + + private async Task SeedAsync() + { + if (await sut.StreamAll(TargetAppId.Id).AnyAsync()) + { + return; + } + + var assets = new List(); + + // The noise app has newer assets, so that an index that is not bounded by the app has to skip all of them. + for (var i = 0; i < NumNoise; i++) + { + assets.Add(CreateAsset(NoiseAppId, i, NoiseTime) with + { + ParentId = i % 2 == 0 ? NoiseFolderId : default, + }); + } + + for (var i = 0; i < NumTarget; i++) + { + var asset = CreateAsset(TargetAppId, i, TargetTime); + + if (i >= NumRoot + NumFolder) + { + asset = asset with { IsDeleted = true }; + } + else if (i >= NumRoot) + { + asset = asset with { ParentId = TargetFolderId }; + } + + assets.Add(asset); + } + + var store = (ISnapshotStore)sut; + + foreach (var batch in assets.Chunk(1000)) + { + await store.WriteManyAsync(batch.Select(x => new SnapshotWriteJob(x.UniqueId, x, 0))); + } + } + + private Asset CreateAsset(NamedId appId, int index, Instant time) + { + return CreateAsset() with + { + AppId = appId, + FileHash = $"hash-{index}", + FileName = $"file-{index}.png", + LastModified = time.Plus(Duration.FromSeconds(index)), + Slug = $"{appId.Name}-{index}", + Tags = [index % 2 == 0 ? "tag-even" : "tag-odd"], + }; + } +} diff --git a/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Assets/MongoAssetRepositoryTests.cs b/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Assets/MongoAssetRepositoryTests.cs index 64b6b7d0b..97132d6b9 100644 --- a/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Assets/MongoAssetRepositoryTests.cs +++ b/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Assets/MongoAssetRepositoryTests.cs @@ -6,6 +6,7 @@ // ========================================================================== using Microsoft.Extensions.Logging; +using MongoDB.Driver; using Squidex.Domain.Apps.Entities.Assets.Repositories; using Squidex.Domain.Apps.Entities.MongoDb.Assets; using Squidex.MongoDb.TestHelpers; @@ -15,11 +16,33 @@ namespace Squidex.MongoDb.Domain.Assets; [Trait("Category", "TestContainer")] [Collection(MongoFixtureCollection.Name)] -public class MongoAssetRepositoryTests(MongoFixture fixture) : AssetRepositoryTests +public class MongoAssetRepositoryTests : AssetRepositoryTests, IAsyncLifetime { + private readonly IMongoDatabase database; + private readonly MongoQueryProfiler profiler; + + public MongoAssetRepositoryTests(MongoFixture fixture) + { + // The profiler works per database, therefore we use a dedicated one to not record queries from other tests. + database = fixture.Client.GetDatabase("Test_Assets"); + + profiler = new MongoQueryProfiler(database, "States_Assets2"); + } + + public async ValueTask InitializeAsync() + { + await profiler.StartAsync(); + } + + public async ValueTask DisposeAsync() + { + await profiler.StopAsync(); + await profiler.AssertIndexedAsync(); + } + protected override async Task CreateSutAsync() { - var sut = new MongoAssetRepository(fixture.Database, A.Fake>(), string.Empty); + var sut = new MongoAssetRepository(database, A.Fake>(), string.Empty); await sut.InitializeAsync(default); return sut; diff --git a/backend/tests/Squidex.Data.Tests/MongoDb/Migrations/DropOldAssetIndexTests.cs b/backend/tests/Squidex.Data.Tests/MongoDb/Migrations/DropOldAssetIndexTests.cs new file mode 100644 index 000000000..abd540e45 --- /dev/null +++ b/backend/tests/Squidex.Data.Tests/MongoDb/Migrations/DropOldAssetIndexTests.cs @@ -0,0 +1,75 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using MongoDB.Bson; +using MongoDB.Driver; +using Squidex.Migrations; +using Squidex.MongoDb.TestHelpers; + +namespace Squidex.MongoDb.Migrations; + +[Trait("Category", "TestContainer")] +[Collection(MongoFixtureCollection.Name)] +public class DropOldAssetIndexTests(MongoFixture fixture) +{ + private readonly IMongoDatabase database = fixture.Client.GetDatabase($"Test_{Guid.NewGuid()}"); + + [Fact] + public async Task Should_drop_old_index_from_all_shards() + { + var shard1 = await CreateCollectionAsync("States_Assets2", withOldIndex: true); + var shard2 = await CreateCollectionAsync("States_Assets2_1", withOldIndex: true); + var counts = await CreateCollectionAsync("States_Assets2_Count", withOldIndex: false); + + var sut = new DropOldAssetIndex(database); + + await sut.UpdateAsync(default); + + Assert.Equal(["_id_", "other_1"], await GetIndexNamesAsync(shard1)); + Assert.Equal(["_id_", "other_1"], await GetIndexNamesAsync(shard2)); + Assert.Equal(["_id_", "other_1"], await GetIndexNamesAsync(counts)); + } + + [Fact] + public async Task Should_not_fail_if_no_asset_collection_exists() + { + var sut = new DropOldAssetIndex(database); + + await sut.UpdateAsync(default); + } + + private async Task> CreateCollectionAsync(string name, bool withOldIndex) + { + var collection = database.GetCollection(name); + + await collection.Indexes.CreateOneAsync( + new CreateIndexModel( + Builders.IndexKeys.Ascending("other"))); + + if (withOldIndex) + { + await collection.Indexes.CreateOneAsync( + new CreateIndexModel( + Builders.IndexKeys + .Descending("mt") + .Ascending("id") + .Ascending("_ai") + .Ascending("dl") + .Ascending("pi") + .Ascending("td"))); + } + + return collection; + } + + private static async Task> GetIndexNamesAsync(IMongoCollection collection) + { + var indexes = await (await collection.Indexes.ListAsync()).ToListAsync(); + + return indexes.Select(x => x["name"].AsString).Order().ToList(); + } +} diff --git a/backend/tests/Squidex.Data.Tests/MongoDb/TestHelpers/MongoQueryProfiler.cs b/backend/tests/Squidex.Data.Tests/MongoDb/TestHelpers/MongoQueryProfiler.cs new file mode 100644 index 000000000..bfdef95e2 --- /dev/null +++ b/backend/tests/Squidex.Data.Tests/MongoDb/TestHelpers/MongoQueryProfiler.cs @@ -0,0 +1,128 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using MongoDB.Bson; +using MongoDB.Driver; + +#pragma warning disable MA0048 // File name must match type name + +namespace Squidex.MongoDb.TestHelpers; + +public sealed record QueryProfile +{ + public string Operation { get; init; } + + public string PlanSummary { get; init; } + + public bool HasSortStage { get; init; } + + public long KeysExamined { get; init; } + + public long DocsExamined { get; init; } + + public long Returned { get; init; } + + public static QueryProfile Parse(BsonDocument document) + { + long GetNumber(string name) + { + return document.TryGetValue(name, out var value) ? value.ToInt64() : 0; + } + + return new QueryProfile + { + Operation = document["op"].AsString, + PlanSummary = document["planSummary"].AsString, + HasSortStage = document.TryGetValue("hasSortStage", out var sort) && sort.ToBoolean(), + KeysExamined = GetNumber("keysExamined"), + DocsExamined = GetNumber("docsExamined"), + Returned = GetNumber("nreturned"), + }; + } +} + +public sealed class MongoQueryProfiler(IMongoDatabase database, string collectionName) +{ + private const string ProfileCollection = "system.profile"; + private const string PlanByDocumentId = "IXSCAN { _id: 1 }"; + private readonly List recorded = []; + + public IReadOnlyList Recorded => recorded; + + public async Task StartAsync() + { + await database.RunCommandAsync("{ profile: 0 }"); + await database.DropCollectionAsync(ProfileCollection); + + // The profile collection is capped, so make it large enough for all queries of a single test. + await database.CreateCollectionAsync(ProfileCollection, new CreateCollectionOptions { Capped = true, MaxSize = 64 * 1024 * 1024 }); + + // The profiler is enabled per database and only records the reads of the profiled collection. Level 2 would ignore the filter. + var command = new BsonDocument + { + ["profile"] = 1, + ["filter"] = new BsonDocument + { + ["ns"] = $"{database.DatabaseNamespace.DatabaseName}.{collectionName}", + ["op"] = new BsonDocument("$in", new BsonArray { "query", "getmore", "command" }), + }, + }; + + await database.RunCommandAsync(command); + } + + public async Task StopAsync() + { + await CollectAsync(); + await database.RunCommandAsync("{ profile: 0 }"); + } + + public ValueTask AssertIndexedAsync() + { + foreach (var profile in recorded) + { + // Queries by IDs are sorted in memory, but the number of results is bounded by the IDs. + AssertIndexed(profile, allowSort: profile.PlanSummary == PlanByDocumentId); + } + + return default; + } + + public static void AssertIndexed(QueryProfile profile, bool allowSort = false) + { + Assert.False(profile.PlanSummary.Contains("COLLSCAN", StringComparison.Ordinal), $"Collection scan: {profile}"); + + if (!allowSort) + { + Assert.False(profile.HasSortStage, $"Blocking sort: {profile}"); + } + } + + public async Task> ProfileAsync(Func action) + { + await CollectAsync(); + await action(); + + return await CollectAsync(); + } + + private async Task> CollectAsync() + { + var documents = + await database.GetCollection(ProfileCollection) + .Find(new BsonDocument()) + .ToListAsync(); + + var profiles = documents.Where(x => x.Contains("planSummary")).Select(QueryProfile.Parse).ToList(); + + recorded.AddRange(profiles); + + // Start from scratch, so that the next collection only returns new queries. + await StartAsync(); + return profiles; + } +}