diff --git a/.github/workflows/claude-daily-review.yml b/.github/workflows/claude-daily-review.yml index 797e7759c..05eb772d7 100644 --- a/.github/workflows/claude-daily-review.yml +++ b/.github/workflows/claude-daily-review.yml @@ -67,6 +67,7 @@ jobs: with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }} + settings: .github/claude/settings-daily-review.json prompt: | You are doing a daily automated review of this repository (Squidex). Today's focus area is: ${{ steps.focus.outputs.area }} @@ -88,7 +89,7 @@ jobs: `--filter "Category!=Dependencies & Category!=TestContainer"`. - frontend: run `npm run lint` and `npm test` in `frontend/`. 5. Write the PR description to ${{ runner.temp }}/pr-body.md: first line is the - PR title (prefix it with "[${{ steps.focus.outputs.area }}]"), then category, + PR title, then category, severity, affected files, explanation of the problem, how it could be triggered, and what the fix does. @@ -96,7 +97,6 @@ jobs: claude_args: >- --model ${{ vars.CLAUDE_MODEL || 'claude-opus-5-5' }} --max-turns 80 - --allowedTools "Read,Grep,Glob,Edit,Write,Bash(gh pr list:*),Bash(git log:*),Bash(git diff:*),Bash(dotnet build:*),Bash(dotnet test:*),Bash(npm run lint:*),Bash(npm test:*),Bash(npx vitest:*)" - name: Enforce size limit and open PR env: diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 99dd5e6c0..471167b6f 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -46,8 +46,8 @@ jobs: with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }} + settings: .github/claude/settings.json claude_args: >- --model ${{ vars.CLAUDE_MODEL || 'claude-opus-5-5' }} --max-turns 40 - --append-system-prompt "Follow CLAUDE.md. Before committing, verify your changes: for backend changes run dotnet build on the affected project and the related tests with --filter \"Category!=Dependencies & Category!=TestContainer\"; for frontend changes run npm run lint and npm test in frontend/. Never commit frontend/package-lock.json." - --allowedTools "Read,Grep,Glob,Edit,Write,Bash(git status:*),Bash(git log:*),Bash(git diff:*),Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh pr list:*),Bash(gh issue view:*),Bash(dotnet build:*),Bash(dotnet test:*),Bash(npm run lint:*),Bash(npm test:*),Bash(npx vitest:*)" + --append-system-prompt-file .github/claude/prompt.md diff --git a/CLAUDE.md b/CLAUDE.md index c7c14d664..4dc4aad9b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,7 +65,9 @@ dotnet test --filter "Category!=Dependencies & Category!=TestContainer" - Do not write conditions that span multiple lines. Split them into multiple `if` statements (e.g. early returns) instead. - Try to keep files under 300 lines. Split larger classes by responsibility. This does not apply to tests. - Do not put a blank line between a variable assignment and an `if` statement that checks this variable. +- Use the same prefix for related variables, e.g. `postsAll` and `postsTaken` instead of `allPosts` and `taken`. - Use primary constructors whenever possible. +- In test classes, put helper methods after all tests. ## Maintaining this file diff --git a/backend/extensions/Squidex.Extensions/Actions/Kafka/KafkaProducer.cs b/backend/extensions/Squidex.Extensions/Actions/Kafka/KafkaProducer.cs index 5b5210c72..8a9169661 100644 --- a/backend/extensions/Squidex.Extensions/Actions/Kafka/KafkaProducer.cs +++ b/backend/extensions/Squidex.Extensions/Actions/Kafka/KafkaProducer.cs @@ -6,6 +6,8 @@ // ========================================================================== #if INCLUDE_KAFKA +using System.Buffers.Binary; +using System.Security.Cryptography; using System.Text; using Avro; using Avro.Generic; @@ -143,7 +145,7 @@ public sealed class KafkaProducer if (!string.IsNullOrWhiteSpace(job.PartitionKey) && job.PartitionCount > 0) { - var partition = Math.Abs(job.PartitionKey.GetHashCode(StringComparison.Ordinal)) % job.PartitionCount; + var partition = GetPartition(job.PartitionKey, job.PartitionCount); await producer.ProduceAsync(new TopicPartition(job.TopicName, partition), message, ct); } @@ -153,6 +155,15 @@ public sealed class KafkaProducer } } + public static int GetPartition(string partitionKey, int partitionCount) + { + // string.GetHashCode is randomized per process, so the same key would end up in different + // partitions after a restart or on another instance. + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(partitionKey)); + + return (int)(BinaryPrimitives.ReadUInt32LittleEndian(hash) % (uint)partitionCount); + } + private GenericRecord CreateAvroRecord(string json, string avroSchema) { try diff --git a/backend/src/Migrations/MigrationPath.cs b/backend/src/Migrations/MigrationPath.cs index c52deadcf..bf557b08d 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 = 28; + private const int CurrentVersion = 29; public (int Version, IEnumerable? Migrations) GetNext(int version) { @@ -132,5 +132,11 @@ public sealed class MigrationPath(IServiceProvider serviceProvider) : IMigration { yield return serviceProvider.GetService(); } + + // Version 29: Move contents into the correct dedicated tables (Entity Framework only). + if (version < 29) + { + yield return serviceProvider.GetKeyedService("RebuildDedicatedContentTables"); + } } } diff --git a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/ContentSqlQueryBuilder.cs b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/ContentSqlQueryBuilder.cs index 91825235d..a7743a72b 100644 --- a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/ContentSqlQueryBuilder.cs +++ b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/ContentSqlQueryBuilder.cs @@ -23,6 +23,17 @@ public class ContentSqlQueryBuilder(SqlDialect dialect, string table, SqlParams? public override bool IsJsonPath(PropertyPath path) { - return path.Count > 1 && string.Equals(path[0], "data", StringComparison.OrdinalIgnoreCase); + if (path.Count <= 1) + { + return false; + } + + // These properties are stored as JSON columns, therefore the nested fields are queried with JSON functions. + if (string.Equals(path[0], nameof(EFContentEntity.Data), StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + return string.Equals(path[0], nameof(EFContentEntity.TranslationStatus), StringComparison.OrdinalIgnoreCase); } } diff --git a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/CustomIndexes.cs b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/CustomIndexes.cs new file mode 100644 index 000000000..ddaf5f260 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/CustomIndexes.cs @@ -0,0 +1,172 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Queries; +using Squidex.Infrastructure.States; + +namespace Squidex.Domain.Apps.Entities.Contents; + +internal static partial class CustomIndexes +{ + // Fields inside JSON columns are indexed with JSON functions, the other columns must be scalar. + private static readonly HashSet IndexableColumns = + [ + nameof(EFContentEntity.Created), + nameof(EFContentEntity.CreatedBy), + nameof(EFContentEntity.Id), + nameof(EFContentEntity.IsDeleted), + nameof(EFContentEntity.LastModified), + nameof(EFContentEntity.LastModifiedBy), + nameof(EFContentEntity.NewStatus), + nameof(EFContentEntity.ScheduledAt), + nameof(EFContentEntity.Status), + nameof(EFContentEntity.Version), + ]; + + [GeneratedRegex("^[a-zA-Z0-9_\\-]+(\\.[a-zA-Z0-9_\\-]+)*$")] + private static partial Regex FieldNameRegex(); + + public static async Task CreateCustomIndexAsync(this ContentDbContext dbContext, IndexDefinition index, + CancellationToken ct) where T : EFContentEntity + { + var table = GetTableName(dbContext); + + var queryBuilder = dbContext.ContentQuery(); + + var indexKeys = new List(); + foreach (var field in index) + { + if (!FieldNameRegex().IsMatch(field.Name)) + { + throw new DomainException($"Invalid index field '{field.Name}'."); + } + + var fieldPath = queryBuilder.Visit(field.Name); + var fieldIsJson = queryBuilder.IsJsonPath(fieldPath); + + if (!fieldIsJson && (fieldPath.Count > 1 || !IndexableColumns.Contains(fieldPath[0]))) + { + throw new DomainException($"Field '{field.Name}' cannot be indexed."); + } + + indexKeys.AddRange(dbContext.Dialect.IndexKeys(fieldPath, field.Order, fieldIsJson)); + } + + if (indexKeys.Count == 0) + { + throw new DomainException("Index does not contain a field."); + } + + var indexName = GetIndexName(table, index.ToName()); + var indexesExisting = await dbContext.Dialect.QueryIndexesAsync(dbContext, table, ct); + + if (indexesExisting.Any(x => x.Name == indexName)) + { + return; + } + + foreach (var sql in dbContext.Dialect.CreateIndex(indexName, table, indexKeys, Describe(index))) + { + await dbContext.Database.ExecuteSqlRawAsync(sql, ct); + } + } + + public static async Task> GetCustomIndexesAsync(this ContentDbContext dbContext, + CancellationToken ct) where T : EFContentEntity + { + var table = GetTableName(dbContext); + + var result = new List(); + foreach (var index in await dbContext.Dialect.QueryIndexesAsync(dbContext, table, ct)) + { + if (!index.Name.StartsWith(GetIndexPrefix(table), StringComparison.Ordinal)) + { + continue; + } + + if (TryParse(index.Description, out var definition)) + { + result.Add(definition); + } + } + + return result; + } + + public static async Task DropCustomIndexAsync(this ContentDbContext dbContext, string name, + CancellationToken ct) where T : EFContentEntity + { + var table = GetTableName(dbContext); + + var indexName = GetIndexName(table, name); + var indexesExisting = await dbContext.Dialect.QueryIndexesAsync(dbContext, table, ct); + + if (!indexesExisting.Any(x => x.Name == indexName)) + { + return; + } + + foreach (var sql in dbContext.Dialect.DropIndex(indexName, table)) + { + await dbContext.Database.ExecuteSqlRawAsync(sql, ct); + } + } + + private static string GetTableName(DbContext dbContext) + { + return dbContext.Model.FindEntityType(typeof(T))?.GetTableName() + ?? throw new InvalidOperationException("Unknown model."); + } + + private static string GetIndexPrefix(string table) + { + return $"IX_{table}_cx_"; + } + + private static string GetIndexName(string table, string name) + { + // Index names are limited to 63 characters in Postgres, therefore the readable name is only stored as description. + var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(name)))[..16].ToLowerInvariant(); + + return $"{GetIndexPrefix(table)}{hash}"; + } + + private static string Describe(IndexDefinition index) + { + return string.Join(',', index.Select(x => $"{x.Name} {(x.Order == SortOrder.Ascending ? "asc" : "desc")}")); + } + + private static bool TryParse(string? description, out IndexDefinition index) + { + index = []; + + if (string.IsNullOrWhiteSpace(description)) + { + return false; + } + + foreach (var part in description.Split(',')) + { + var partTokens = part.Split(' '); + if (partTokens.Length != 2) + { + return false; + } + + var partOrder = partTokens[1] == "desc" ? SortOrder.Descending : SortOrder.Ascending; + + index.Add(new IndexField(partTokens[0], partOrder)); + } + + return index.Count > 0; + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository.cs b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository.cs index a07cc33bf..b595f3c2f 100644 --- a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository.cs +++ b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository.cs @@ -136,24 +136,6 @@ public sealed partial class EFContentRepository( ct); } - public Task CreateIndexAsync(DomainId appId, DomainId schemaId, IndexDefinition index, - CancellationToken ct = default) - { - return Task.CompletedTask; - } - - public Task> GetIndexesAsync(DomainId appId, DomainId schemaId, - CancellationToken ct = default) - { - return Task.FromResult>([]); - } - - public Task DropIndexAsync(DomainId appId, DomainId schemaId, string name, - CancellationToken ct = default) - { - return Task.CompletedTask; - } - private async Task CreateDbContextAsync( CancellationToken ct) { diff --git a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_Indexes.cs b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_Indexes.cs new file mode 100644 index 000000000..aae38e657 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_Indexes.cs @@ -0,0 +1,59 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.EntityFrameworkCore; +using Squidex.Infrastructure; +using Squidex.Infrastructure.States; + +#pragma warning disable MA0048 // File name must match type name + +namespace Squidex.Domain.Apps.Entities.Contents; + +public sealed partial class EFContentRepository +{ + public async Task CreateIndexAsync(DomainId appId, DomainId schemaId, IndexDefinition index, + CancellationToken ct = default) + { + // Custom indexes are only supported for dedicated tables, like the dedicated collections in MongoDB. + if (!dedicatedTables) + { + return; + } + + await using var dbContext = await dynamicTables.CreateDbContextAsync(appId, schemaId, ct); + + await dbContext.CreateCustomIndexAsync(index, ct); + await dbContext.CreateCustomIndexAsync(index, ct); + } + + public async Task> GetIndexesAsync(DomainId appId, DomainId schemaId, + CancellationToken ct = default) + { + if (!dedicatedTables) + { + return []; + } + + await using var dbContext = await dynamicTables.CreateDbContextAsync(appId, schemaId, ct); + + return await dbContext.GetCustomIndexesAsync(ct); + } + + public async Task DropIndexAsync(DomainId appId, DomainId schemaId, string name, + CancellationToken ct = default) + { + if (!dedicatedTables) + { + return; + } + + await using var dbContext = await dynamicTables.CreateDbContextAsync(appId, schemaId, ct); + + await dbContext.DropCustomIndexAsync(name, ct); + await dbContext.DropCustomIndexAsync(name, ct); + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_SnapshotStore.cs b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_SnapshotStore.cs index 9de939372..30b2c2beb 100644 --- a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_SnapshotStore.cs +++ b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_SnapshotStore.cs @@ -185,7 +185,7 @@ public sealed partial class EFContentRepository : ISn // The existing entity is only valid if we use dedicated tables. if (existing != null) { - var contentDbContext = await dynamicTables.CreateDbContextAsync(existing.AppId.Id, existing.AppId.Id, ct); + var contentDbContext = await dynamicTables.CreateDbContextAsync(existing.AppId.Id, existing.SchemaId.Id, ct); await RemoveCoreAsync(contentDbContext, key, ct); } @@ -351,8 +351,11 @@ public sealed partial class EFContentRepository : ISn .Where(x => x.AppId.Id == bySchema.Key.AppId && x.SchemaId.Id == bySchema.Key.SchemaId) .ToList(); - await contentDbContext.BulkInsertAsync(bySchema.ToList(), ct); - await contentDbContext.BulkInsertAsync(publishedContents, ct); + // The bulk inserter caches the table names per context type and would ignore the prefix. + contentDbContext.AddRange(bySchema); + contentDbContext.AddRange(publishedContents); + + await contentDbContext.SaveChangesAsync(ct); } } diff --git a/backend/src/Squidex.Data.EntityFramework/Infrastructure/PooledDbNamedContextFactory.cs b/backend/src/Squidex.Data.EntityFramework/Infrastructure/PooledDbNamedContextFactory.cs index b5bff4d65..ecf6fcfa6 100644 --- a/backend/src/Squidex.Data.EntityFramework/Infrastructure/PooledDbNamedContextFactory.cs +++ b/backend/src/Squidex.Data.EntityFramework/Infrastructure/PooledDbNamedContextFactory.cs @@ -7,6 +7,7 @@ using System.Collections.Concurrent; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; #pragma warning disable EF1001 // Internal EF Core API usage. @@ -48,6 +49,9 @@ public sealed class PooledDbNamedContextFactory( builder.UsePoolSize(128); builder.UsePrefix(name); + // All prefixes share the internal service provider, therefore the model must be cached per prefix. + builder.ReplaceService(); + var pool = new DbContextPool(builder.Options, serviceProvider); return pool; } diff --git a/backend/src/Squidex.Data.EntityFramework/Infrastructure/PrefixModelCacheKeyFactory.cs b/backend/src/Squidex.Data.EntityFramework/Infrastructure/PrefixModelCacheKeyFactory.cs new file mode 100644 index 000000000..3f38c68e2 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Infrastructure/PrefixModelCacheKeyFactory.cs @@ -0,0 +1,22 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Squidex.Infrastructure; + +public sealed class PrefixModelCacheKeyFactory : IModelCacheKeyFactory +{ + public object Create(DbContext context, bool designTime) + { + // The table names depend on the prefix, therefore each prefix needs its own model. + var prefix = context.GetService().FindExtension()?.Prefix; + + return (context.GetType(), prefix, designTime); + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs index 0e5795f5c..5a3deb718 100644 --- a/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs +++ b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs @@ -74,6 +74,27 @@ public class SqlDialect return string.Empty; } + public virtual IEnumerable IndexKeys(PropertyPath path, SortOrder order, bool isJson) + { + yield return new SqlIndexKey(FormatField(path, isJson), FormatOrder(order), isJson); + } + + public virtual IEnumerable CreateIndex(string name, string table, IReadOnlyList keys, string description) + { + throw new NotSupportedException(); + } + + public virtual IEnumerable DropIndex(string name, string table) + { + throw new NotSupportedException(); + } + + public virtual Task> QueryIndexesAsync(DbContext dbContext, string table, + CancellationToken ct) + { + throw new NotSupportedException(); + } + public virtual string FormatLimitOffset(long limit, long offset, bool hasOrder) { var hasLimit = limit > 0 && limit < long.MaxValue; @@ -258,6 +279,11 @@ public class SqlDialect return tableName; } + protected static string FormatLiteral(string value) + { + return $"'{value.Replace("'", "''", StringComparison.Ordinal)}'"; + } + protected virtual string FormatField(PropertyPath path, bool isJson) { if (isJson) diff --git a/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlIndexKey.cs b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlIndexKey.cs new file mode 100644 index 000000000..02d4cd3ae --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlIndexKey.cs @@ -0,0 +1,19 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +#pragma warning disable MA0048 // File name must match type name + +namespace Squidex.Infrastructure.Queries; + +public sealed record SqlIndexKey(string Expression, string Order, bool IsExpression); + +public sealed class SqlIndexInfo +{ + public string Name { get; set; } + + public string? Description { get; set; } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Migrations/RebuildDedicatedContentTables.cs b/backend/src/Squidex.Data.EntityFramework/Migrations/RebuildDedicatedContentTables.cs new file mode 100644 index 000000000..39ba8224f --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Migrations/RebuildDedicatedContentTables.cs @@ -0,0 +1,99 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Squidex.Domain.Apps.Entities.Contents; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Migrations; + +namespace Squidex.Migrations; + +public sealed class RebuildDedicatedContentTables( + IDbContextFactory dbContextFactory, + IDbContextNamedFactory dbContentContextFactory, + IOptions options, + ILogger> log) + : IMigration + where TContext : DbContext where TContentContext : ContentDbContext +{ + public const string Key = "RebuildDedicatedContentTables"; + + public async Task UpdateAsync( + CancellationToken ct) + { + if (!options.Value.OptimizeForSelfHosting) + { + return; + } + + var dynamicTables = new DynamicTables(dbContextFactory, dbContentContextFactory); + + // All dedicated tables shared the model of the first table, therefore the contents are in the wrong tables. + var names = await dynamicTables.GetContextNames(ct).ToHashSetAsync(cancellationToken: ct); + + await using (var dbContext = await dbContextFactory.CreateDbContextAsync(ct)) + { + var schemas = + await dbContext.Set() + .Select(x => new { x.IndexedAppId, x.IndexedSchemaId }).Distinct() + .ToListAsync(ct); + + foreach (var schema in schemas) + { + names.Add(new DynamicContextName(schema.IndexedAppId, schema.IndexedSchemaId)); + } + } + + foreach (var name in names) + { + await using var contentContext = await dynamicTables.CreateDbContextAsync(name, ct); + await using var dbContext = await dbContextFactory.CreateDbContextAsync(ct); + + await using var transaction = await contentContext.Database.BeginTransactionAsync(ct); + + await RebuildAsync(dbContext, contentContext, name, ct); + await RebuildAsync(dbContext, contentContext, name, ct); + + await transaction.CommitAsync(ct); + + log.LogInformation("Rebuilt dedicated content tables for app {appId} and schema {schemaId}.", name.AppId, name.SchemaId); + } + } + + private static async Task RebuildAsync(DbContext dbContext, DbContext contentContext, DynamicContextName name, + CancellationToken ct) where T : EFContentEntity + { + await contentContext.Set().ExecuteDeleteAsync(ct); + + var sourceType = dbContext.Model.FindEntityType(typeof(T))!; + var sourceTable = StoreObjectIdentifier.Table(sourceType.GetTableName()!, sourceType.GetSchema()); + + var targetType = contentContext.Model.FindEntityType(typeof(T))!; + var targetTable = StoreObjectIdentifier.Table(targetType.GetTableName()!, targetType.GetSchema()); + + var sqlHelper = contentContext.GetService(); + + // The column order can differ between the tables, therefore the columns are listed explicitly. + var sqlColumns = string.Join(", ", targetType.GetProperties().Select(x => sqlHelper.DelimitIdentifier(x.GetColumnName(targetTable)!))); + var sqlAppId = sqlHelper.DelimitIdentifier(sourceType.FindProperty(nameof(EFContentEntity.IndexedAppId))!.GetColumnName(sourceTable)!); + var sqlSchemaId = sqlHelper.DelimitIdentifier(sourceType.FindProperty(nameof(EFContentEntity.IndexedSchemaId))!.GetColumnName(sourceTable)!); + + var sqlInsert = $$""" + INSERT INTO {{sqlHelper.DelimitIdentifier(targetTable.Name, targetTable.Schema)}} ({{sqlColumns}}) + SELECT {{sqlColumns}} + FROM {{sqlHelper.DelimitIdentifier(sourceTable.Name, sourceTable.Schema)}} + WHERE {{sqlAppId}} = {0} AND {{sqlSchemaId}} = {1} + """; + + await contentContext.Database.ExecuteSqlRawAsync(sqlInsert, [name.AppId.ToString(), name.SchemaId.ToString()], ct); + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs index f63936899..1f1b825dd 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs @@ -85,25 +85,74 @@ public sealed class MySqlDialect : SqlDialect } } + public override IEnumerable CreateIndex(string name, string table, IReadOnlyList keys, string description) + { + var sqlColumns = string.Join(", ", keys.Select(x => x.IsExpression ? $"({x.Expression}) {x.Order}" : $"{x.Expression} {x.Order}")); + + yield return $"CREATE INDEX {FormatTable(name)} ON {FormatTable(table)} ({sqlColumns}) COMMENT {FormatLiteral(description)};"; + } + + public override IEnumerable DropIndex(string name, string table) + { + yield return $"DROP INDEX {FormatTable(name)} ON {FormatTable(table)};"; + } + + public override Task> QueryIndexesAsync(DbContext dbContext, string table, + CancellationToken ct) + { + var sqlQuery = $""" + SELECT INDEX_NAME AS {nameof(SqlIndexInfo.Name)}, MAX(INDEX_COMMENT) AS {nameof(SqlIndexInfo.Description)} + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = {FormatLiteral(table)} + GROUP BY INDEX_NAME + """; + + return dbContext.Database.SqlQueryRaw(sqlQuery).ToListAsync(ct); + } + + public override IEnumerable IndexKeys(PropertyPath path, SortOrder order, bool isJson) + { + if (isJson) + { + var sqlOrder = FormatOrder(order); + + // Must match the expressions of the ORDER BY clause, otherwise the index is not used. + yield return new SqlIndexKey(SortNumber(path), sqlOrder, true); + yield return new SqlIndexKey(SortText(path), sqlOrder, true); + yield break; + } + + foreach (var key in base.IndexKeys(path, order, isJson)) + { + yield return key; + } + } + public override string OrderBy(PropertyPath path, SortOrder order, bool isJson) { if (isJson) { var sqlOrder = FormatOrder(order); - var sqlPath = path.JsonPath(); - - return $""" - IF (JSON_TYPE(JSON_EXTRACT({sqlPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL'), - CAST(JSON_VALUE({sqlPath}) AS DOUBLE), - NULL - ) {sqlOrder}, - JSON_VALUE({sqlPath}) {sqlOrder} - """; + + return $"{SortNumber(path)} {sqlOrder}, {SortText(path)} {sqlOrder}"; } return base.OrderBy(path, order, isJson); } + private static string SortNumber(PropertyPath path) + { + var sqlPath = path.JsonPath(); + + return $"IF(JSON_TYPE(JSON_EXTRACT({sqlPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL'), CAST(JSON_VALUE({sqlPath}) AS DOUBLE), NULL)"; + } + + private static string SortText(PropertyPath path) + { + // Long texts would exceed the maximum size of index keys. + return $"LEFT(JSON_VALUE({path.JsonPath()}), 200)"; + } + public override string WhereMatch(PropertyPath path, string query, SqlParams queryParameters) { return $"MATCH({FormatField(path, false)}) AGAINST({queryParameters.AddPositional(query)})"; diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs index af4542a5f..24b72a9fb 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs @@ -51,19 +51,74 @@ public class PostgresDialect : SqlDialect return $"\"{tableName}\""; } + public override IEnumerable CreateIndex(string name, string table, IReadOnlyList keys, string description) + { + var sqlColumns = string.Join(", ", keys.Select(x => x.IsExpression ? $"({x.Expression}) {x.Order}" : $"{x.Expression} {x.Order}")); + + yield return $"CREATE INDEX {FormatTable(name)} ON {FormatTable(table)} ({sqlColumns});"; + yield return $"COMMENT ON INDEX {FormatTable(name)} IS {FormatLiteral(description)};"; + } + + public override IEnumerable DropIndex(string name, string table) + { + yield return $"DROP INDEX IF EXISTS {FormatTable(name)};"; + } + + public override Task> QueryIndexesAsync(DbContext dbContext, string table, + CancellationToken ct) + { + var sqlQuery = $""" + SELECT i.relname AS "{nameof(SqlIndexInfo.Name)}", obj_description(i.oid, 'pg_class') AS "{nameof(SqlIndexInfo.Description)}" + FROM pg_index x + JOIN pg_class i ON i.oid = x.indexrelid + JOIN pg_class t ON t.oid = x.indrelid + WHERE t.relname = {FormatLiteral(table)} AND t.relnamespace = current_schema()::regnamespace + """; + + return dbContext.Database.SqlQueryRaw(sqlQuery).ToListAsync(ct); + } + + public override IEnumerable IndexKeys(PropertyPath path, SortOrder order, bool isJson) + { + if (isJson) + { + var sqlOrder = FormatOrder(order); + + // Must match the expressions of the ORDER BY clause, otherwise the index is not used. + yield return new SqlIndexKey(SortNumber(path), $"{sqlOrder} NULLS LAST", true); + yield return new SqlIndexKey(SortText(path), sqlOrder, true); + yield break; + } + + foreach (var key in base.IndexKeys(path, order, isJson)) + { + yield return key; + } + } + public override string OrderBy(PropertyPath path, SortOrder order, bool isJson) { if (isJson) { var sqlOrder = FormatOrder(order); - var sqlPath = path.JsonPath(true); - return $"CASE WHEN jsonb_typeof({path.JsonPath(false)}) = 'number' THEN ({sqlPath})::numeric END {sqlOrder} NULLS LAST, {sqlPath} {sqlOrder}"; + return $"{SortNumber(path)} {sqlOrder} NULLS LAST, {SortText(path)} {sqlOrder}"; } return base.OrderBy(path, order, isJson); } + private static string SortNumber(PropertyPath path) + { + return $"CASE WHEN jsonb_typeof({path.JsonPath(false)}) = 'number' THEN ({path.JsonPath(true)})::numeric END"; + } + + private static string SortText(PropertyPath path) + { + // Long texts would exceed the maximum size of btree index entries and the writes would fail. + return $"left({path.JsonPath(true)}, 200)"; + } + public override string WhereMatch(PropertyPath path, string query, SqlParams queryParameters) { if (query.Contains(' ', StringComparison.OrdinalIgnoreCase)) diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs index 62899ea99..bd822d6b5 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs @@ -67,19 +67,98 @@ public sealed class SqlServerDialect : SqlDialect return $"[{tableName}]"; } + public override IEnumerable CreateIndex(string name, string table, IReadOnlyList keys, string description) + { + // SQL Server cannot index expressions, therefore we have to create computed columns first. + var sqlComputed = keys.Select((x, i) => (Key: x, Column: $"{name}_{i}")).Where(x => x.Key.IsExpression).ToList(); + + if (sqlComputed.Count > 0) + { + yield return $"ALTER TABLE {FormatTable(table)} ADD {string.Join(", ", sqlComputed.Select(x => $"{FormatTable(x.Column)} AS ({x.Key.Expression})"))};"; + } + + var sqlColumns = string.Join(", ", keys.Select((x, i) => x.IsExpression ? $"{FormatTable($"{name}_{i}")} {x.Order}" : $"{x.Expression} {x.Order}")); + + yield return $"CREATE INDEX {FormatTable(name)} ON {FormatTable(table)} ({sqlColumns});"; + yield return $""" + DECLARE @schema sysname = SCHEMA_NAME(); + EXEC sp_addextendedproperty + @name = N'squidex', @value = {FormatLiteral(description)}, + @level0type = N'SCHEMA', @level0name = @schema, + @level1type = N'TABLE', @level1name = {FormatLiteral(table)}, + @level2type = N'INDEX', @level2name = {FormatLiteral(name)}; + """; + } + + public override IEnumerable DropIndex(string name, string table) + { + yield return $"DROP INDEX IF EXISTS {FormatTable(name)} ON {FormatTable(table)};"; + yield return $""" + DECLARE @sql NVARCHAR(MAX) = N''; + SELECT @sql = @sql + N'ALTER TABLE {FormatTable(table)} DROP COLUMN ' + QUOTENAME(name) + N';' + FROM sys.computed_columns + WHERE object_id = OBJECT_ID({FormatLiteral(FormatTable(table))}) AND name LIKE {FormatLiteral($"{name}[_]%")}; + EXEC sp_executesql @sql; + """; + } + + public override Task> QueryIndexesAsync(DbContext dbContext, string table, + CancellationToken ct) + { + var sqlQuery = $""" + SELECT i.name AS {nameof(SqlIndexInfo.Name)}, CAST(p.value AS NVARCHAR(4000)) AS {nameof(SqlIndexInfo.Description)} + FROM sys.indexes i + LEFT JOIN sys.extended_properties p ON p.class = 7 AND p.major_id = i.object_id AND p.minor_id = i.index_id AND p.name = N'squidex' + WHERE i.object_id = OBJECT_ID({FormatLiteral(FormatTable(table))}) AND i.name IS NOT NULL + """; + + return dbContext.Database.SqlQueryRaw(sqlQuery).ToListAsync(ct); + } + + public override IEnumerable IndexKeys(PropertyPath path, SortOrder order, bool isJson) + { + if (isJson) + { + var sqlOrder = FormatOrder(order); + + // Must match the expressions of the ORDER BY clause, otherwise the index is not used. + yield return new SqlIndexKey(SortNumber(path), sqlOrder, true); + yield return new SqlIndexKey(SortText(path), sqlOrder, true); + yield break; + } + + foreach (var key in base.IndexKeys(path, order, isJson)) + { + yield return key; + } + } + public override string OrderBy(PropertyPath path, SortOrder order, bool isJson) { if (isJson) { var sqlOrder = FormatOrder(order); - var sqlPath = path.JsonPath(); - return $"IIF(ISNUMERIC(JSON_VALUE({sqlPath})) = 1, CAST(JSON_VALUE({sqlPath}) AS NUMERIC), NULL) {sqlOrder}, JSON_VALUE({sqlPath}) {sqlOrder}"; + return $"{SortNumber(path)} {sqlOrder}, {SortText(path)} {sqlOrder}"; } return base.OrderBy(path, order, isJson); } + private static string SortNumber(PropertyPath path) + { + var sqlPath = path.JsonPath(); + + // Use TRY_CAST, because ISNUMERIC also accepts values like '$' that cannot be converted. + return $"IIF(ISNUMERIC(JSON_VALUE({sqlPath})) = 1, TRY_CAST(JSON_VALUE({sqlPath}) AS NUMERIC), NULL)"; + } + + private static string SortText(PropertyPath path) + { + // Long texts would exceed the maximum size of index keys and the writes would fail. + return $"CAST(JSON_VALUE({path.JsonPath()}) AS NVARCHAR(200))"; + } + public override string WhereMatch(PropertyPath path, string query, SqlParams queryParameters) { if (query.Contains(' ', StringComparison.OrdinalIgnoreCase)) diff --git a/backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs b/backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs index a738c596f..9318acf04 100644 --- a/backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs +++ b/backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs @@ -48,6 +48,7 @@ using Squidex.Infrastructure; using Squidex.Infrastructure.Caching; using Squidex.Infrastructure.Log; using Squidex.Infrastructure.Migrations; +using Squidex.Migrations; using Squidex.Infrastructure.Queries; using Squidex.Infrastructure.States; using Squidex.Infrastructure.UsageTracking; @@ -218,6 +219,10 @@ public static class ServiceExtensions services.AddSingletonAs>() .As(); + // The migration path cannot reference the generic type, therefore it is resolved by key. + services.AddKeyedTransient>( + RebuildDedicatedContentTables.Key); + services.AddSingletonAs>() .As(); diff --git a/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj b/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj index e88032ba6..ff26122ac 100644 --- a/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj +++ b/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj @@ -43,13 +43,13 @@ - - - - - - - + + + + + + + diff --git a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Schemas/MongoSchemasHash.cs b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Schemas/MongoSchemasHash.cs index f3464a917..46dae7f1a 100644 --- a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Schemas/MongoSchemasHash.cs +++ b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Schemas/MongoSchemasHash.cs @@ -8,6 +8,7 @@ using MongoDB.Driver; using Squidex.Domain.Apps.Core.Apps; using Squidex.Domain.Apps.Events; +using Squidex.Domain.Apps.Events.Schemas; using Squidex.Events; using Squidex.Infrastructure; using Squidex.Infrastructure.EventSourcing; @@ -44,18 +45,29 @@ public sealed class MongoSchemasHash(IMongoDatabase database) : MongoRepositoryB continue; } - if (@event.Payload is SchemaEvent schemaEvent) + if (@event.Payload is not SchemaEvent schemaEvent) { - writes.Add( - new UpdateOneModel( - Filter.Eq(x => x.AppId, schemaEvent.AppId.Id), - Update - .Set($"s.{schemaEvent.SchemaId.Id}", @event.Headers.EventStreamNumber()) - .Set(x => x.Updated, @event.Headers.TimestampAsInstant())) - { - IsUpsert = true, - }); + continue; } + + var timestamp = @event.Headers.TimestampAsInstant(); + + var fieldName = $"s.{schemaEvent.SchemaId.Id}"; + + // Deleted schemas are not returned by the schema index, so they must not be part of the hash either. + var update = Update.Set(fieldName, @event.Headers.EventStreamNumber()); + if (schemaEvent is SchemaDeleted) + { + update = Update.Unset(fieldName); + } + + writes.Add( + new UpdateOneModel( + Filter.Eq(x => x.AppId, schemaEvent.AppId.Id), + update.Set(x => x.Updated, timestamp)) + { + IsUpsert = true, + }); } if (writes.Count == 0) @@ -63,7 +75,8 @@ public sealed class MongoSchemasHash(IMongoDatabase database) : MongoRepositoryB return Task.CompletedTask; } - return Collection.BulkWriteAsync(writes, BulkUnordered); + // The writes for the same app must be applied in order, for example a deletion after a creation. + return Collection.BulkWriteAsync(writes); } public async Task GetCurrentHashAsync(App app, @@ -74,7 +87,9 @@ public sealed class MongoSchemasHash(IMongoDatabase database) : MongoRepositoryB var entity = await Collection.Find(x => x.AppId == app.Id).FirstOrDefaultAsync(ct); if (entity == null) { - return SchemasHashKey.Empty; + // Apps without schema events since a restore have no document. The app version must still be part of + // the key, otherwise app changes would not be detected. + return SchemasHashKey.Create(app, new Dictionary()); } return SchemasHashKey.Create( diff --git a/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj b/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj index 241f3152b..b7686144d 100644 --- a/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj +++ b/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj @@ -25,12 +25,12 @@ - - - - - - + + + + + + diff --git a/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj b/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj index f151adf42..1f8315f64 100644 --- a/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj +++ b/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj @@ -20,7 +20,7 @@ - + diff --git a/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj b/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj index 21f8b8195..ff1a5730f 100644 --- a/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj +++ b/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj @@ -29,8 +29,8 @@ - - + + diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/CachingGraphQLResolver.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/CachingGraphQLResolver.cs index 99d3f2e92..cbcb7198c 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/CachingGraphQLResolver.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/CachingGraphQLResolver.cs @@ -23,6 +23,7 @@ namespace Squidex.Domain.Apps.Entities.Contents.GraphQL; public sealed class CachingGraphQLResolver( IBackgroundCache cache, + ILocalCache localCache, ISchemasHash schemasHash, IServiceProvider serviceProvider, IOptions options) @@ -43,8 +44,9 @@ public sealed class CachingGraphQLResolver( { var context = ((GraphQLExecutionContext)options.UserContext!).Context; - options.Schema = await GetSchemaAsync(context.App); + // Register the error handler first, so that errors when building the model are logged. options.HandleError(serviceProvider); + options.Schema = await GetSchemaAsync(context.App); return await next(options); } @@ -60,7 +62,7 @@ public sealed class CachingGraphQLResolver( { if (options.CacheDuration <= TimeSpan.Zero) { - return CreateModelAsync(app); + return CreateModelAsync(app, SchemasHashKey.Empty); } // The version is not part of the key. Building the schema is expensive and the version @@ -71,7 +73,17 @@ public sealed class CachingGraphQLResolver( return cache.GetOrCreateAsync(cacheKey, options.CacheDuration, async entry => { - return await CreateModelAsync(app); + // Compare the hash with the same source in the validator. A key computed from the schemas would never + // match if the hash store is incomplete, for example for restored apps. The hash is read before the + // schemas, so a change in between only causes another rebuild. + var hashKey = await schemasHash.GetCurrentHashAsync(app); + + // The model is shared between requests. Therefore it must not use schemas from the request-local + // cache, which might have been loaded with the cancellation token of another request. + using (localCache.StartContext()) + { + return await CreateModelAsync(app, hashKey); + } }, async entry => { @@ -81,11 +93,10 @@ public sealed class CachingGraphQLResolver( }); } - private async Task CreateModelAsync(App app) + private async Task CreateModelAsync(App app, SchemasHashKey hashKey) { var schemasList = await serviceProvider.GetRequiredService().GetSchemasAsync(app.Id); - var schemasKey = SchemasHashKey.Create(app, schemasList); - return new CacheEntry(new Builder(app, options).BuildSchema(schemasList), schemasKey); + return new CacheEntry(new Builder(app, options).BuildSchema(schemasList), hashKey); } } diff --git a/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj b/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj index 7a718ff20..3819d91e3 100644 --- a/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj +++ b/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj @@ -24,13 +24,13 @@ - - - - - - - + + + + + + + diff --git a/backend/src/Squidex/Squidex.csproj b/backend/src/Squidex/Squidex.csproj index a3399b7f7..8e5e19c74 100644 --- a/backend/src/Squidex/Squidex.csproj +++ b/backend/src/Squidex/Squidex.csproj @@ -59,16 +59,16 @@ - - - - - - + + + + + + - - - + + + @@ -82,12 +82,12 @@ - + - + diff --git a/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryDedicatedTests.cs b/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryDedicatedTests.cs index fee828d05..d6f72abd6 100644 --- a/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryDedicatedTests.cs +++ b/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryDedicatedTests.cs @@ -5,12 +5,23 @@ // All rights reserved. Licensed under the MIT license. // ========================================================================== +using System.Text; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; +using Squidex.Domain.Apps.Core.Contents; +using Squidex.Domain.Apps.Entities; using Squidex.Domain.Apps.Entities.Contents; using Squidex.Domain.Apps.Entities.Contents.Repositories; using Squidex.EntityFramework.TestHelpers; using Squidex.Infrastructure; +using Squidex.Infrastructure.Queries; +using Squidex.Infrastructure.States; +using Squidex.Migrations; +using Squidex.Providers.MySql; +using Squidex.Providers.Postgres; +using Squidex.Providers.SqlServer; using Squidex.Shared; namespace Squidex.EntityFramework.Domain.Contents; @@ -20,6 +31,13 @@ public abstract class EFContentRepositoryDedicatedTests options = Options.Create(new ContentsOptions { OptimizeForSelfHosting = true }); + private readonly NamedId appId = NamedId.Of(DomainId.NewGuid(), "my-app"); + private readonly NamedId schemaId1 = NamedId.Of(DomainId.NewGuid(), "my-schema1"); + private readonly NamedId schemaId2 = NamedId.Of(DomainId.NewGuid(), "my-schema2"); + + protected override bool SupportsCustomIndexes => true; + protected override Task CreateSutAsync() { var sut = @@ -27,8 +45,253 @@ public abstract class EFContentRepositoryDedicatedTests(sut); } + + [Fact] + public async Task Should_use_own_model_for_each_prefix() + { + await using var context1 = await fixture.DbContextNamedFactory.CreateDbContextAsync("__cTest1_"); + await using var context2 = await fixture.DbContextNamedFactory.CreateDbContextAsync("__cTest2_"); + + var table1 = context1.Model.FindEntityType(typeof(EFContentCompleteEntity))!.GetTableName(); + var table2 = context2.Model.FindEntityType(typeof(EFContentCompleteEntity))!.GetTableName(); + + Assert.Equal("__cTest1_ContentsAll", table1); + Assert.Equal("__cTest2_ContentsAll", table2); + } + + [Fact] + public async Task Should_move_contents_into_correct_dedicated_tables() + { + var content1 = CreateWriteContent() with { Id = DomainId.NewGuid(), AppId = appId, SchemaId = schemaId1 }; + var content2 = CreateWriteContent() with { Id = DomainId.NewGuid(), AppId = appId, SchemaId = schemaId2 }; + + var sut = await CreateSutAsync(); + + await ((ISnapshotStore)sut).WriteManyAsync( + [ + new SnapshotWriteJob(content1.UniqueId, content1, 0), + new SnapshotWriteJob(content2.UniqueId, content2, 0), + ]); + + // Simulate the old behavior, where all contents were written to the first dedicated table. + var dynamicTables = new DynamicTables(fixture.DbContextFactory, fixture.DbContextNamedFactory); + + await using (var context1 = await dynamicTables.CreateDbContextAsync(appId.Id, schemaId1.Id, default)) + { + await using var context2 = await dynamicTables.CreateDbContextAsync(appId.Id, schemaId2.Id, default); + + var misplaced = await context2.Set().ToListAsync(); + + await context2.Set().ExecuteDeleteAsync(); + await context2.Set().ExecuteDeleteAsync(); + + context1.AddRange(misplaced); + await context1.SaveChangesAsync(); + } + + var migration = + new RebuildDedicatedContentTables( + fixture.DbContextFactory, + fixture.DbContextNamedFactory, + options, + NullLogger>.Instance); + + await migration.UpdateAsync(default); + + var schema1 = Schema with { AppId = appId, Id = schemaId1.Id, Name = schemaId1.Name }; + var schema2 = Schema with { AppId = appId, Id = schemaId2.Id, Name = schemaId2.Name }; + + var app = App with { Id = appId.Id, Name = appId.Name }; + + var result1All = await sut.QueryAsync(app, schema1, Q.Empty, SearchScope.All); + var result2All = await sut.QueryAsync(app, schema2, Q.Empty, SearchScope.All); + var result2Published = await sut.QueryAsync(app, schema2, Q.Empty, SearchScope.Published); + + Assert.Equal([content1.Id], result1All.Select(x => x.Id).ToArray()); + Assert.Equal([content2.Id], result2All.Select(x => x.Id).ToArray()); + Assert.Equal([content2.Id], result2Published.Select(x => x.Id).ToArray()); + } + + [Theory] + [InlineData("data.field1.iv", SortOrder.Ascending)] + [InlineData("data.field1.iv", SortOrder.Descending)] + [InlineData("translationStatus.en", SortOrder.Ascending)] + [InlineData("lastModified", SortOrder.Descending)] + public async Task Should_sort_with_custom_index(string field, SortOrder order) + { + var index = new IndexDefinition + { + new IndexField(field, order), + }; + + var sut = await CreateSutAsync(); + + await sut.CreateIndexAsync(appId.Id, schemaId1.Id, index); + try + { + var dynamicTables = new DynamicTables(fixture.DbContextFactory, fixture.DbContextNamedFactory); + + await using var dbContext = await dynamicTables.CreateDbContextAsync(appId.Id, schemaId1.Id, default); + + var table = GetTableName(dbContext); + + var indexesCustom = await GetCustomIndexNamesAsync(dbContext, table); + var indexName = Assert.Single(indexesCustom); + + // Use the same query builder as the repository, otherwise the ORDER BY clause could be different. + var sqlQuery = + new ContentSqlQueryBuilder(dbContext.Dialect, table) + .Order(field, order) + .Limit(20) + .CompileQuery(); + + var (plan, sortMarker) = await ExplainAsync(dbContext, table, indexName, sqlQuery); + + Assert.Contains(indexName, plan, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(sortMarker, plan, StringComparison.OrdinalIgnoreCase); + } + finally + { + await sut.DropIndexAsync(appId.Id, schemaId1.Id, index.ToName()); + } + } + + [Fact] + public async Task Should_create_and_drop_custom_index_in_all_and_published_table() + { + var sut = await CreateSutAsync(); + + await sut.CreateIndexAsync(appId.Id, schemaId1.Id, [new IndexField("data.field1.iv", SortOrder.Ascending)]); + + var dynamicTables = new DynamicTables(fixture.DbContextFactory, fixture.DbContextNamedFactory); + + await using var dbContext = await dynamicTables.CreateDbContextAsync(appId.Id, schemaId1.Id, default); + + var tableAll = GetTableName(dbContext); + var tablePublished = GetTableName(dbContext); + + var createdAll = await GetCustomIndexNamesAsync(dbContext, tableAll); + var createdPublished = await GetCustomIndexNamesAsync(dbContext, tablePublished); + + Assert.Single(createdAll); + Assert.Single(createdPublished); + + await sut.DropIndexAsync(appId.Id, schemaId1.Id, "data.field1.iv_asc"); + + var droppedAll = await GetCustomIndexNamesAsync(dbContext, tableAll); + var droppedPublished = await GetCustomIndexNamesAsync(dbContext, tablePublished); + + Assert.Empty(droppedAll); + Assert.Empty(droppedPublished); + } + + private static string GetTableName(DbContext dbContext) + { + return dbContext.Model.FindEntityType(typeof(T))!.GetTableName()!; + } + + private static async Task> GetCustomIndexNamesAsync(TContentContext dbContext, string table) + { + var indexes = await dbContext.Dialect.QueryIndexesAsync(dbContext, table, default); + + return indexes.Select(x => x.Name).Where(x => x.StartsWith($"IX_{table}_cx_", StringComparison.Ordinal)).ToList(); + } + + private static async Task<(string Plan, string SortMarker)> ExplainAsync(TContentContext dbContext, string table, string indexName, string sqlQuery) + { + // The tables are almost empty, therefore the planners are pushed to the index. They can still sort, if the index does not match. + switch (dbContext.Dialect) + { + case PostgresDialect: + { + await using var transaction = await dbContext.Database.BeginTransactionAsync(); + try + { + await dbContext.Database.ExecuteSqlRawAsync("SET LOCAL enable_sort = off;"); + + var plan = await ReadAllAsync(dbContext, $"EXPLAIN {sqlQuery}"); + + return (plan, "Sort"); + } + finally + { + await transaction.RollbackAsync(); + } + } + + case MySqlDialect: + { + var sqlHinted = sqlQuery.Replace($"FROM `{table}`", $"FROM `{table}` FORCE INDEX (`{indexName}`)", StringComparison.Ordinal); + + var plan = await ReadAllAsync(dbContext, $"EXPLAIN {sqlHinted}"); + + return (plan, "filesort"); + } + + case SqlServerDialect: + { + var sqlHinted = sqlQuery.Replace($"FROM [{table}]", $"FROM [{table}] WITH (INDEX([{indexName}]))", StringComparison.Ordinal); + + await dbContext.Database.OpenConnectionAsync(); + try + { + await ReadAllAsync(dbContext, "SET SHOWPLAN_XML ON;"); + try + { + var plan = await ReadAllAsync(dbContext, sqlHinted); + + return (plan, "PhysicalOp=\"Sort\""); + } + finally + { + await ReadAllAsync(dbContext, "SET SHOWPLAN_XML OFF;"); + } + } + finally + { + await dbContext.Database.CloseConnectionAsync(); + } + } + + default: + throw new NotSupportedException(); + } + } + + private static async Task ReadAllAsync(DbContext dbContext, string sql) + { + await dbContext.Database.OpenConnectionAsync(); + try + { + await using var command = dbContext.Database.GetDbConnection().CreateCommand(); + + command.CommandText = sql; + command.Transaction = dbContext.Database.CurrentTransaction?.GetDbTransaction(); + + await using var reader = await command.ExecuteReaderAsync(); + + var result = new StringBuilder(); + do + { + while (await reader.ReadAsync()) + { + for (var i = 0; i < reader.FieldCount; i++) + { + result.AppendLine(reader.GetValue(i)?.ToString()); + } + } + } + while (await reader.NextResultAsync()); + + return result.ToString(); + } + finally + { + await dbContext.Database.CloseConnectionAsync(); + } + } } diff --git a/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryTests.cs b/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryTests.cs index 0aa79ee78..2fdd73f61 100644 --- a/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryTests.cs +++ b/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryTests.cs @@ -11,6 +11,8 @@ using Squidex.Domain.Apps.Entities.Contents; using Squidex.Domain.Apps.Entities.Contents.Repositories; using Squidex.EntityFramework.TestHelpers; using Squidex.Infrastructure; +using Squidex.Infrastructure.Queries; +using Squidex.Infrastructure.States; using Squidex.Shared; namespace Squidex.EntityFramework.Domain.Contents; @@ -19,6 +21,9 @@ public abstract class EFContentRepositoryTests(ISqlCo : ContentRepositoryTests where TContext : DbContext, IDbContextWithDialect where TContentContext : ContentDbContext { + private readonly NamedId appId = NamedId.Of(DomainId.NewGuid(), "my-app"); + private readonly NamedId schemaId = NamedId.Of(DomainId.NewGuid(), "my-schema1"); + protected override Task CreateSutAsync() { var sut = @@ -30,4 +35,28 @@ public abstract class EFContentRepositoryTests(ISqlCo return Task.FromResult(sut); } + + [Fact] + public async Task Should_ignore_custom_indexes_without_dedicated_tables() + { + var index = new IndexDefinition + { + new IndexField("data.field1.iv", SortOrder.Ascending), + }; + + var sut = await CreateSutAsync(); + + await sut.CreateIndexAsync(appId.Id, schemaId.Id, index); + try + { + var indexesCreated = await sut.GetIndexesAsync(appId.Id, schemaId.Id); + + // Custom indexes would apply to the contents of all schemas in the shared table. + Assert.Empty(indexesCreated); + } + finally + { + await sut.DropIndexAsync(appId.Id, schemaId.Id, index.ToName()); + } + } } diff --git a/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Schemas/MongoSchemasHashTests.cs b/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Schemas/MongoSchemasHashTests.cs index af6748d13..c07f0a0f5 100644 --- a/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Schemas/MongoSchemasHashTests.cs +++ b/backend/tests/Squidex.Data.Tests/MongoDb/Domain/Schemas/MongoSchemasHashTests.cs @@ -62,4 +62,46 @@ public class MongoSchemasHashTests(MongoFixture fixture) : GivenContext, IAsyncL Assert.NotEmpty(hashKey); Assert.Equal(hashKey.Timestamp, timestamp); } + + [Fact] + public async Task Should_remove_deleted_schemas_from_hash() + { + var schema1 = Schema.WithId(DomainId.NewGuid(), "my-schema1"); + var schema2 = Schema.WithId(DomainId.NewGuid(), "my-schema2"); + + var timestamp = SystemClock.Instance.GetCurrentInstant().WithoutMs(); + + await sut.On( + [ + Envelope.Create(new SchemaCreated + { + AppId = AppId, + SchemaId = schema1.NamedId(), + }).SetEventStreamNumber(schema1.Version).SetTimestamp(timestamp), + + Envelope.Create(new SchemaCreated + { + AppId = AppId, + SchemaId = schema2.NamedId(), + }).SetEventStreamNumber(schema2.Version).SetTimestamp(timestamp), + + Envelope.Create(new SchemaDeleted + { + AppId = AppId, + SchemaId = schema2.NamedId(), + }).SetEventStreamNumber(schema2.Version + 1).SetTimestamp(timestamp), + ]); + + var hashKey = await sut.GetCurrentHashAsync(App, CancellationToken); + + Assert.Equal(SchemasHashKey.Create(App, [schema1]), hashKey); + } + + [Fact] + public async Task Should_include_app_version_if_app_has_no_hash() + { + var hashKey = await sut.GetCurrentHashAsync(App, CancellationToken); + + Assert.Equal(SchemasHashKey.Create(App, Array.Empty()), hashKey); + } } diff --git a/backend/tests/Squidex.Data.Tests/Shared/ContentRepositoryTests.cs b/backend/tests/Squidex.Data.Tests/Shared/ContentRepositoryTests.cs index ae6a0a03e..5ec899a10 100644 --- a/backend/tests/Squidex.Data.Tests/Shared/ContentRepositoryTests.cs +++ b/backend/tests/Squidex.Data.Tests/Shared/ContentRepositoryTests.cs @@ -85,96 +85,7 @@ public abstract class ContentRepositoryTests : GivenContext protected abstract Task CreateSutAsync(); - private async Task CreateAndPrepareSutAsync(params WriteContent[] contents) - { - var sut = await CreateSutAsync(); - if (sut is not ISnapshotStore store) - { - return sut; - } - - // Write the contents of the test itself, because the shared contents are only written once. - await WriteAsync(store, contents); - - if (await sut.StreamAll(AppIds[0].Id, [schema.Id], SearchScope.All).AnyAsync()) - { - return sut; - } - - var batch = new List>(); - - async Task ExecuteBatchAsync(WriteContent? state) - { - if (state != null) - { - batch.Add(new SnapshotWriteJob(state.UniqueId, state, 0)); - } - - if ((state == null || batch.Count >= 1000) && batch.Count > 0) - { - await store.WriteManyAsync(batch, default); - batch.Clear(); - } - } - - foreach (var forAppId in AppIds) - { - foreach (var forSchemaId in SchemaIds) - { - var previousIds = new List(); - - for (var i = 0; i < NumValues; i++) - { - var contentId = DomainId.NewGuid(); - - if (i == 0) - { - previousIds = [contentId]; - } - - var content = CreateWriteContent() with - { - Id = contentId, - CurrentVersion = new ContentVersion( - Status.Published, - new ContentData() - .AddField("field1", - new ContentFieldData() - .AddInvariant(JsonValue.Create(i))) - .AddField("field2", - new ContentFieldData() - .AddInvariant(JsonValue.Create(Lorem.Paragraph(200, 20)))) - .AddField("references", - new ContentFieldData() - .AddInvariant( - JsonValue.Array(previousIds.ToArray())))), - SchemaId = forSchemaId, - ScheduleJob = - i > NumValues / 2 - ? new ScheduleJob(DomainId.NewGuid(), Status.Archived, User, now.Plus(Duration.FromDays(i))) - : null, - AppId = forAppId, - }; - - await ExecuteBatchAsync(content); - } - } - } - - await ExecuteBatchAsync(null); - - return sut; - } - - private static async Task WriteAsync(ISnapshotStore store, WriteContent[] contents) - { - if (contents.Length == 0) - { - return; - } - - await store.WriteManyAsync(contents.Select(x => new SnapshotWriteJob(x.UniqueId, x, 0)).ToList(), default); - } + protected virtual bool SupportsCustomIndexes => false; [Fact] public async Task Should_find_by_id() @@ -398,6 +309,21 @@ public abstract class ContentRepositoryTests : GivenContext Assert.Single(contents); } + [Fact] + public async Task Should_query_by_translation_status() + { + var query = new ClrQuery + { + Filter = ClrFilter.Eq("translationStatus.en", 100), + Sort = [new SortNode("translationStatus.en", SortOrder.Ascending)], + }; + + var contents = await QueryAsync(query, 1000, 0); + + // The schema has no localized fields, therefore all contents are fully translated. + Assert.Equal(NumValues, contents.Count); + } + [Fact] public async Task Should_query_scheduled() { @@ -722,6 +648,238 @@ public abstract class ContentRepositoryTests : GivenContext Assert.Empty(scheduled); } + [Fact] + public async Task Should_create_get_and_drop_custom_index() + { + if (!SupportsCustomIndexes) + { + return; + } + + var (otherApp, otherSchema) = CreateOtherApp(); + + var index = new IndexDefinition + { + new IndexField("data.field1.iv", SortOrder.Ascending), + new IndexField("translationStatus.en", SortOrder.Ascending), + new IndexField("lastModified", SortOrder.Descending), + }; + + var sut = await CreateAndPrepareSutAsync(); + + await sut.CreateIndexAsync(otherApp.Id, otherSchema.Id, index); + + // Creating the same index twice must not fail. + await sut.CreateIndexAsync(otherApp.Id, otherSchema.Id, index); + + var created = await sut.GetIndexesAsync(otherApp.Id, otherSchema.Id); + + created.Should().BeEquivalentTo([index]); + + await sut.DropIndexAsync(otherApp.Id, otherSchema.Id, index.ToName()); + + var dropped = await sut.GetIndexesAsync(otherApp.Id, otherSchema.Id); + + Assert.Empty(dropped); + } + + [Fact] + public async Task Should_not_fail_to_drop_unknown_custom_index() + { + if (!SupportsCustomIndexes) + { + return; + } + + var (otherApp, otherSchema) = CreateOtherApp(); + + var sut = await CreateAndPrepareSutAsync(); + + await sut.DropIndexAsync(otherApp.Id, otherSchema.Id, "data.unknown.iv_asc"); + + var indexes = await sut.GetIndexesAsync(otherApp.Id, otherSchema.Id); + + Assert.Empty(indexes); + } + + [Fact] + public async Task Should_write_and_sort_contents_with_custom_index() + { + if (!SupportsCustomIndexes) + { + return; + } + + var (otherApp, otherSchema) = CreateOtherApp(); + + var index = new IndexDefinition + { + new IndexField("data.field1.iv", SortOrder.Descending), + new IndexField("data.field2.iv", SortOrder.Ascending), + }; + + var sut = await CreateAndPrepareSutAsync(); + + await sut.CreateIndexAsync(otherApp.Id, otherSchema.Id, index); + try + { + // Long texts and values that look like numbers must not break the writes. + var contents = new[] + { + CreateContent(otherApp, Status.Published, 1, new string('a', 5000)), + CreateContent(otherApp, Status.Published, 3, "$"), + CreateContent(otherApp, Status.Published, 2, "1e400"), + }; + + await WriteAsync((ISnapshotStore)sut, contents); + + var query = new ClrQuery + { + Sort = [new SortNode("data.field1.iv", SortOrder.Descending)], + }; + + var result = await sut.QueryAsync(otherApp, otherSchema, Q.Empty.WithQuery(query), SearchScope.All); + + Assert.Equal([contents[1].Id, contents[2].Id, contents[0].Id], result.Select(x => x.Id).ToArray()); + } + finally + { + await sut.DropIndexAsync(otherApp.Id, otherSchema.Id, index.ToName()); + } + } + + [Fact] + public async Task Should_not_create_custom_index_for_invalid_field() + { + if (!SupportsCustomIndexes) + { + return; + } + + var (otherApp, otherSchema) = CreateOtherApp(); + + var sut = await CreateAndPrepareSutAsync(); + + foreach (var field in new[] { "data.field1'; DROP TABLE x; --", "newData", "lastModified.x" }) + { + var index = new IndexDefinition + { + new IndexField(field, SortOrder.Ascending), + }; + + await Assert.ThrowsAsync(() => sut.CreateIndexAsync(otherApp.Id, otherSchema.Id, index)); + } + } + + private async Task CreateAndPrepareSutAsync(params WriteContent[] contents) + { + var sut = await CreateSutAsync(); + if (sut is not ISnapshotStore store) + { + return sut; + } + + // Write the contents of the test itself, because the shared contents are only written once. + await WriteAsync(store, contents); + + if (await sut.StreamAll(AppIds[0].Id, [schema.Id], SearchScope.All).AnyAsync()) + { + return sut; + } + + var batch = new List>(); + + async Task ExecuteBatchAsync(WriteContent? state) + { + if (state != null) + { + batch.Add(new SnapshotWriteJob(state.UniqueId, state, 0)); + } + + if ((state == null || batch.Count >= 1000) && batch.Count > 0) + { + await store.WriteManyAsync(batch, default); + batch.Clear(); + } + } + + foreach (var forAppId in AppIds) + { + foreach (var forSchemaId in SchemaIds) + { + var previousIds = new List(); + + for (var i = 0; i < NumValues; i++) + { + var contentId = DomainId.NewGuid(); + + if (i == 0) + { + previousIds = [contentId]; + } + + var content = CreateWriteContent() with + { + Id = contentId, + CurrentVersion = new ContentVersion( + Status.Published, + new ContentData() + .AddField("field1", + new ContentFieldData() + .AddInvariant(JsonValue.Create(i))) + .AddField("field2", + new ContentFieldData() + .AddInvariant(JsonValue.Create(Lorem.Paragraph(200, 20)))) + .AddField("references", + new ContentFieldData() + .AddInvariant( + JsonValue.Array(previousIds.ToArray())))), + SchemaId = forSchemaId, + ScheduleJob = + i > NumValues / 2 + ? new ScheduleJob(DomainId.NewGuid(), Status.Archived, User, now.Plus(Duration.FromDays(i))) + : null, + AppId = forAppId, + }; + + await ExecuteBatchAsync(content); + } + } + } + + await ExecuteBatchAsync(null); + + return sut; + } + + private static async Task WriteAsync(ISnapshotStore store, WriteContent[] contents) + { + if (contents.Length == 0) + { + return; + } + + await store.WriteManyAsync(contents.Select(x => new SnapshotWriteJob(x.UniqueId, x, 0)).ToList(), default); + } + + private WriteContent CreateContent(App forApp, Status status, int number, string text) + { + var content = CreateContent(forApp, status); + + return content with + { + CurrentVersion = new ContentVersion( + status, + new ContentData() + .AddField("field1", + new ContentFieldData() + .AddInvariant(JsonValue.Create(number))) + .AddField("field2", + new ContentFieldData() + .AddInvariant(JsonValue.Create(text)))), + }; + } + private (App, Schema) CreateOtherApp() { // Use another app to not change the results of the other tests. diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/CachingGraphQLResolverTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/CachingGraphQLResolverTests.cs new file mode 100644 index 000000000..cd2ee44e3 --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/CachingGraphQLResolverTests.cs @@ -0,0 +1,120 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using GraphQL; +using GraphQL.Execution; +using GraphQL.Validation; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Squidex.Caching; +using Squidex.Domain.Apps.Core.TestHelpers; +using Squidex.Domain.Apps.Entities.Apps.Indexes; +using Squidex.Domain.Apps.Entities.Contents.TestData; +using Squidex.Domain.Apps.Entities.Rules.Indexes; +using Squidex.Domain.Apps.Entities.Schemas; +using Squidex.Domain.Apps.Entities.Schemas.Indexes; +using Squidex.Domain.Apps.Entities.Teams.Indexes; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.GraphQL; + +public class CachingGraphQLResolverTests : GraphQLTestBase +{ + [Fact] + public async Task Should_not_use_schemas_from_request_cache_to_build_model() + { + using var cts = new CancellationTokenSource(); + + await cts.CancelAsync(); + + var schemasIndex = A.Fake(); + + A.CallTo(() => schemasIndex.GetSchemasAsync(TestApp.Default.Id, cts.Token)) + .ThrowsAsync(new OperationCanceledException(cts.Token)); + + A.CallTo(() => schemasIndex.GetSchemasAsync(TestApp.Default.Id, default)) + .Returns([TestSchemas.Default]); + + var localCache = new AsyncLocalCache(); + var appProvider = new AppProvider( + A.Fake(), + A.Fake(), + schemasIndex, + A.Fake(), + localCache); + + var sut = CreateSut(appProvider); + + using (localCache.StartContext()) + { + // The request has loaded the schemas with its own token, but has been canceled. + await Assert.ThrowsAnyAsync(() => appProvider.GetSchemasAsync(TestApp.Default.Id, cts.Token)); + + var model = await sut.GetSchemaAsync(TestApp.Default); + + Assert.NotNull(model); + } + } + + [Fact] + public async Task Should_not_rebuild_model_if_hash_has_not_changed() + { + var appProvider = A.Fake(); + + A.CallTo(() => appProvider.GetSchemasAsync(TestApp.Default.Id, default)) + .Returns([TestSchemas.Default]); + + // The hash store does not know the schema, for example after a restore. + var hashKey = SchemasHashKey.Create(TestApp.Default, new Dictionary()); + + var schemasHash = A.Fake(); + + A.CallTo(() => schemasHash.GetCurrentHashAsync(TestApp.Default, default)) + .Returns(hashKey); + + var sut = CreateSut(appProvider, schemasHash); + + await sut.GetSchemaAsync(TestApp.Default); + await sut.GetSchemaAsync(TestApp.Default); + + // Wait for the validation in the background. + await Task.Delay(500); + + await sut.GetSchemaAsync(TestApp.Default); + + A.CallTo(() => appProvider.GetSchemasAsync(TestApp.Default.Id, default)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_log_error_if_model_cannot_be_created() + { + var appProvider = A.Fake(); + + A.CallTo(() => appProvider.GetSchemasAsync(TestApp.Default.Id, default)) + .ThrowsAsync(new InvalidOperationException()); + + var sut = CreateSut(appProvider); + + var options = new TestQuery { Query = "{ __typename }" }.ToOptions(sut.Services); + + var executer = new DocumentExecuter( + new GraphQLDocumentBuilder(), + new DocumentValidator(), + new DefaultExecutionStrategySelector(), + [sut]); + + var result = await executer.ExecuteAsync(options); + + Assert.NotEmpty(result.Errors!); + + var loggerFactory = sut.Services.GetRequiredService(); + + A.CallTo(() => loggerFactory.CreateLogger("GraphQL")) + .MustHaveHappened(); + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/GraphQLTestBase.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/GraphQLTestBase.cs index 85047695d..367d00fa1 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/GraphQLTestBase.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/GraphQLTestBase.cs @@ -116,6 +116,11 @@ public abstract class GraphQLTestBase : IClassFixture A.CallTo(() => appProvider.GetSchemasAsync(TestApp.Default.Id, default)) .Returns(schemas.ToList()); + return CreateSut(appProvider); + } + + protected CachingGraphQLResolver CreateSut(IAppProvider appProvider, ISchemasHash? schemasHash = null) + { var serviceProvider = new ServiceCollection() .AddSingleton(TimeProvider.System) @@ -145,9 +150,10 @@ public abstract class GraphQLTestBase : IClassFixture .AddSingleton( A.Fake()) .AddSingleton( - A.Fake()) + schemasHash ?? A.Fake()) .AddMemoryCache() .AddBackgroundCache() + .AddAsyncLocalCache() .AddSingleton(appProvider) .AddSingleton(assetQuery) .AddSingleton(commandBus) diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Extensions/Kafka/KafkaProducerTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Extensions/Kafka/KafkaProducerTests.cs new file mode 100644 index 000000000..79ec66ef9 --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Extensions/Kafka/KafkaProducerTests.cs @@ -0,0 +1,37 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +#if INCLUDE_KAFKA +using Squidex.Extensions.Actions.Kafka; + +namespace Squidex.Domain.Apps.Entities.Extensions.Kafka; + +public class KafkaProducerTests +{ + [Theory] + [InlineData("key1", 12, 5)] + [InlineData("key2", 12, 5)] + [InlineData("key3", 12, 1)] + public void Should_calculate_stable_partition(string partitionKey, int partitionCount, int expected) + { + var partition = KafkaProducer.GetPartition(partitionKey, partitionCount); + + Assert.Equal(expected, partition); + } + + [Fact] + public void Should_calculate_partition_in_range() + { + for (var i = 0; i < 1000; i++) + { + var partition = KafkaProducer.GetPartition($"key{i}", 7); + + Assert.InRange(partition, 0, 6); + } + } +} +#endif diff --git a/tools/TestSuite/TestSuite.ApiTests/AssetFormatTests.cs b/tools/TestSuite/TestSuite.ApiTests/AssetFormatTests.cs index 40e647374..09c46152d 100644 --- a/tools/TestSuite/TestSuite.ApiTests/AssetFormatTests.cs +++ b/tools/TestSuite/TestSuite.ApiTests/AssetFormatTests.cs @@ -59,7 +59,7 @@ public class AssetFormatTests(CreatedAppFixture fixture) : IClassFixture(x => x.FileHash) + .ScrubMember(x => x.FileSize) + .ScrubMember(x => x.MetadataText); + } + private async Task GetResizedLengthAsync(string imageId, int width, int height) { var url = $"{_.Client.GenerateImageUrl(imageId)}?width={width}&height={height}"; diff --git a/tools/TestSuite/TestSuite.ApiTests/TestSuite.ApiTests.csproj b/tools/TestSuite/TestSuite.ApiTests/TestSuite.ApiTests.csproj index 12ed3137c..ddf783b66 100644 --- a/tools/TestSuite/TestSuite.ApiTests/TestSuite.ApiTests.csproj +++ b/tools/TestSuite/TestSuite.ApiTests/TestSuite.ApiTests.csproj @@ -17,8 +17,8 @@ - - + + diff --git a/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_fix_orientation.verified.txt b/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_fix_orientation.verified.txt index 691683618..b4b154f6b 100644 --- a/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_fix_orientation.verified.txt +++ b/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_fix_orientation.verified.txt @@ -2,12 +2,12 @@ Id: Guid_1, ParentId: Guid_Empty, FileName: logo-wide-rotated.jpg, - FileHash: XFoH3mp4QW9EIWjF50vJkm8IwnrjjO+ZiqV2GnH1GGw=, + FileHash: {Scrubbed}, IsProtected: false, Slug: logo-wide-rotated.jpg, MimeType: image/jpeg, FileType: jpg, - MetadataText: 600x135px, 15.2 kB, + MetadataText: {Scrubbed}, EditToken: {Scrubbed}, Metadata: { description: JFIF File, @@ -20,7 +20,7 @@ image, image/medium ], - FileSize: 15598, + FileSize: {Scrubbed}, Type: Image, CreatedBy: {Scrubbed}, LastModifiedBy: {Scrubbed}, diff --git a/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_jpg_and_resize.verified.txt b/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_jpg_and_resize.verified.txt index 87fd1be05..146216532 100644 --- a/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_jpg_and_resize.verified.txt +++ b/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_jpg_and_resize.verified.txt @@ -2,12 +2,12 @@ Id: Guid_1, ParentId: Guid_Empty, FileName: SampleImage_62kb.jpg, - FileHash: ss/g3yq5dO3jYbWzJ9j2psJo1Nrk5TjSi78LJfCma38=, + FileHash: {Scrubbed}, IsProtected: false, Slug: sampleimage-62kb.jpg, MimeType: image/jpeg, FileType: jpg, - MetadataText: 600x400px, 59.2 kB, + MetadataText: {Scrubbed}, EditToken: {Scrubbed}, Metadata: { description: JFIF File, @@ -20,7 +20,7 @@ image, image/medium ], - FileSize: 60603, + FileSize: {Scrubbed}, Type: Image, CreatedBy: {Scrubbed}, LastModifiedBy: {Scrubbed}, diff --git a/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_tiff_and_resize.verified.txt b/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_tiff_and_resize.verified.txt index dad653eb6..6aa25deec 100644 --- a/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_tiff_and_resize.verified.txt +++ b/tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_tiff_and_resize.verified.txt @@ -2,12 +2,12 @@ Id: Guid_1, ParentId: Guid_Empty, FileName: SampleImage_400kb.tiff, - FileHash: f+ZdTDOoK23jmThbfPhWhXL8Q9+KIQajHeFfT/MtWFU=, + FileHash: {Scrubbed}, IsProtected: false, Slug: sampleimage-400kb.tiff, MimeType: image/jpeg, FileType: tiff, - MetadataText: 600x400px, 473.6 kB, + MetadataText: {Scrubbed}, EditToken: {Scrubbed}, Metadata: { description: TIFF File, @@ -19,7 +19,7 @@ image, image/medium ], - FileSize: 485012, + FileSize: {Scrubbed}, Type: Image, CreatedBy: {Scrubbed}, LastModifiedBy: {Scrubbed}, diff --git a/tools/TestSuite/TestSuite.Shared/TestSuite.Shared.csproj b/tools/TestSuite/TestSuite.Shared/TestSuite.Shared.csproj index 90e46ce6c..557472034 100644 --- a/tools/TestSuite/TestSuite.Shared/TestSuite.Shared.csproj +++ b/tools/TestSuite/TestSuite.Shared/TestSuite.Shared.csproj @@ -17,7 +17,7 @@ - + diff --git a/tools/TestSuite/docker-compose.yml b/tools/TestSuite/docker-compose.yml index 6dc441a32..a1e302b09 100644 --- a/tools/TestSuite/docker-compose.yml +++ b/tools/TestSuite/docker-compose.yml @@ -80,7 +80,7 @@ services: restart: unless-stopped resizer: - image: squidex/resizer:1.3.0 + image: squidex/resizer:1.7.0 webhookcatcher: image: tarampampam/webhook-tester:2