mirror of https://github.com/Squidex/squidex.git
Browse Source
* Custom indexes * Add missing files * Improve tests * Fix tests * Update resize service. * Cleanup settings.pull/1372/head
committed by
GitHub
41 changed files with 1519 additions and 218 deletions
@ -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<string> 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<T>(this ContentDbContext dbContext, IndexDefinition index, |
|||
CancellationToken ct) where T : EFContentEntity |
|||
{ |
|||
var table = GetTableName<T>(dbContext); |
|||
|
|||
var queryBuilder = dbContext.ContentQuery<T>(); |
|||
|
|||
var indexKeys = new List<SqlIndexKey>(); |
|||
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<List<IndexDefinition>> GetCustomIndexesAsync<T>(this ContentDbContext dbContext, |
|||
CancellationToken ct) where T : EFContentEntity |
|||
{ |
|||
var table = GetTableName<T>(dbContext); |
|||
|
|||
var result = new List<IndexDefinition>(); |
|||
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<T>(this ContentDbContext dbContext, string name, |
|||
CancellationToken ct) where T : EFContentEntity |
|||
{ |
|||
var table = GetTableName<T>(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<T>(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; |
|||
} |
|||
} |
|||
@ -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<TContext, TContentContext> |
|||
{ |
|||
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<EFContentCompleteEntity>(index, ct); |
|||
await dbContext.CreateCustomIndexAsync<EFContentPublishedEntity>(index, ct); |
|||
} |
|||
|
|||
public async Task<List<IndexDefinition>> 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<EFContentCompleteEntity>(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<EFContentCompleteEntity>(name, ct); |
|||
await dbContext.DropCustomIndexAsync<EFContentPublishedEntity>(name, ct); |
|||
} |
|||
} |
|||
@ -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<IDbContextOptions>().FindExtension<PrefixExtension>()?.Prefix; |
|||
|
|||
return (context.GetType(), prefix, designTime); |
|||
} |
|||
} |
|||
@ -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; } |
|||
} |
|||
@ -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<TContext, TContentContext>( |
|||
IDbContextFactory<TContext> dbContextFactory, |
|||
IDbContextNamedFactory<TContentContext> dbContentContextFactory, |
|||
IOptions<ContentsOptions> options, |
|||
ILogger<RebuildDedicatedContentTables<TContext, TContentContext>> 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<TContext, TContentContext>(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<EFContentCompleteEntity>() |
|||
.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<EFContentCompleteEntity>(dbContext, contentContext, name, ct); |
|||
await RebuildAsync<EFContentPublishedEntity>(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<T>(DbContext dbContext, DbContext contentContext, DynamicContextName name, |
|||
CancellationToken ct) where T : EFContentEntity |
|||
{ |
|||
await contentContext.Set<T>().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<ISqlGenerationHelper>(); |
|||
|
|||
// 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); |
|||
} |
|||
} |
|||
@ -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<ISchemasIndex>(); |
|||
|
|||
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<IAppsIndex>(), |
|||
A.Fake<IRulesIndex>(), |
|||
schemasIndex, |
|||
A.Fake<ITeamsIndex>(), |
|||
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<OperationCanceledException>(() => 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<IAppProvider>(); |
|||
|
|||
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<DomainId, long>()); |
|||
|
|||
var schemasHash = A.Fake<ISchemasHash>(); |
|||
|
|||
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<IAppProvider>(); |
|||
|
|||
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<ILoggerFactory>(); |
|||
|
|||
A.CallTo(() => loggerFactory.CreateLogger("GraphQL")) |
|||
.MustHaveHappened(); |
|||
} |
|||
} |
|||
@ -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
|
|||
Loading…
Reference in new issue