mirror of https://github.com/Squidex/squidex.git
Browse Source
* temp * Test * Test * Test * Temp * Finalized * Test * Text improvements. * Simplifications * Fix testpull/1345/head
committed by
GitHub
103 changed files with 8432 additions and 185 deletions
File diff suppressed because it is too large
@ -0,0 +1,28 @@ |
|||
using Microsoft.EntityFrameworkCore.Migrations; |
|||
|
|||
#nullable disable |
|||
|
|||
namespace Squidex.Providers.MySql.App.Migrations |
|||
{ |
|||
/// <inheritdoc />
|
|||
public partial class AddTextStateVersion : Migration |
|||
{ |
|||
/// <inheritdoc />
|
|||
protected override void Up(MigrationBuilder migrationBuilder) |
|||
{ |
|||
migrationBuilder.AddColumn<long>( |
|||
name: "Version", |
|||
table: "TextState", |
|||
type: "bigint", |
|||
nullable: true); |
|||
} |
|||
|
|||
/// <inheritdoc />
|
|||
protected override void Down(MigrationBuilder migrationBuilder) |
|||
{ |
|||
migrationBuilder.DropColumn( |
|||
name: "Version", |
|||
table: "TextState"); |
|||
} |
|||
} |
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,28 @@ |
|||
using Microsoft.EntityFrameworkCore.Migrations; |
|||
|
|||
#nullable disable |
|||
|
|||
namespace Squidex.Providers.Postgres.App.Migrations |
|||
{ |
|||
/// <inheritdoc />
|
|||
public partial class AddTextStateVersion : Migration |
|||
{ |
|||
/// <inheritdoc />
|
|||
protected override void Up(MigrationBuilder migrationBuilder) |
|||
{ |
|||
migrationBuilder.AddColumn<long>( |
|||
name: "Version", |
|||
table: "TextState", |
|||
type: "bigint", |
|||
nullable: true); |
|||
} |
|||
|
|||
/// <inheritdoc />
|
|||
protected override void Down(MigrationBuilder migrationBuilder) |
|||
{ |
|||
migrationBuilder.DropColumn( |
|||
name: "Version", |
|||
table: "TextState"); |
|||
} |
|||
} |
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,28 @@ |
|||
using Microsoft.EntityFrameworkCore.Migrations; |
|||
|
|||
#nullable disable |
|||
|
|||
namespace Squidex.Providers.SqlServer.App.Migrations |
|||
{ |
|||
/// <inheritdoc />
|
|||
public partial class AddTextStateVersion : Migration |
|||
{ |
|||
/// <inheritdoc />
|
|||
protected override void Up(MigrationBuilder migrationBuilder) |
|||
{ |
|||
migrationBuilder.AddColumn<long>( |
|||
name: "Version", |
|||
table: "TextState", |
|||
type: "bigint", |
|||
nullable: true); |
|||
} |
|||
|
|||
/// <inheritdoc />
|
|||
protected override void Down(MigrationBuilder migrationBuilder) |
|||
{ |
|||
migrationBuilder.DropColumn( |
|||
name: "Version", |
|||
table: "TextState"); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
namespace Squidex.Domain.Apps.Core.Schemas; |
|||
|
|||
public enum FieldSearchMode |
|||
{ |
|||
Default, |
|||
Title, |
|||
Exclude, |
|||
} |
|||
@ -0,0 +1,34 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Infrastructure.Json.Objects; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class ArrayFieldTextStrategy : ITextFieldStrategy |
|||
{ |
|||
public int Order => 0; |
|||
|
|||
public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) |
|||
{ |
|||
if (field is not IArrayField arrayField || value.Value is not JsonArray items) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
foreach (var item in items) |
|||
{ |
|||
if (item.Value is JsonObject obj) |
|||
{ |
|||
walker.AppendObject(obj, arrayField.FieldsByName); |
|||
} |
|||
} |
|||
|
|||
return true; |
|||
} |
|||
} |
|||
@ -0,0 +1,30 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Infrastructure; |
|||
using Squidex.Infrastructure.Json.Objects; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class ComponentTextStrategy : ITextFieldStrategy |
|||
{ |
|||
// Components are detected by value, because they can also be nested in other values.
|
|||
public int Order => 100; |
|||
|
|||
public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) |
|||
{ |
|||
if (!Component.IsValid(value, out var discriminator) || !walker.Context.Components.TryGetValue(DomainId.Create(discriminator), out var schema)) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
walker.AppendObject(value.AsObject, schema.FieldsByName); |
|||
return true; |
|||
} |
|||
} |
|||
@ -0,0 +1,147 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Infrastructure.Json.Objects; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
// Walks through a single content and passes the texts to the collector.
|
|||
public sealed class ContentTextWalker( |
|||
IReadOnlyList<ITextFieldStrategy> strategies, |
|||
IReadOnlyList<ITextNormalizer> normalizers, |
|||
TextExtractionContext context, |
|||
TextCollector collector) |
|||
{ |
|||
private static readonly object TitleFieldsKey = new object(); |
|||
private string language = string.Empty; |
|||
private bool isTitle; |
|||
|
|||
public TextExtractionContext Context => context; |
|||
|
|||
public void Walk(ContentData data) |
|||
{ |
|||
var schema = context.Schema; |
|||
|
|||
var titleFields = context.GetOrAdd(TitleFieldsKey, schema, static x => GetTitleFields(x)); |
|||
foreach (var (fieldName, fieldData) in data) |
|||
{ |
|||
if (fieldData == null) |
|||
{ |
|||
continue; |
|||
} |
|||
|
|||
RootField? field = null; |
|||
schema?.FieldsByName.TryGetValue(fieldName, out field); |
|||
|
|||
isTitle = titleFields.Contains(fieldName); |
|||
|
|||
foreach (var (fieldLanguage, value) in fieldData) |
|||
{ |
|||
// When the text is later appended we need the current language.
|
|||
language = fieldLanguage; |
|||
|
|||
AppendField(field, value); |
|||
} |
|||
} |
|||
} |
|||
|
|||
public void AppendField(IField? field, JsonValue value) |
|||
{ |
|||
var searchMode = field?.RawProperties.SearchMode ?? FieldSearchMode.Default; |
|||
if (searchMode == FieldSearchMode.Exclude) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
var wasTitle = isTitle; |
|||
try |
|||
{ |
|||
isTitle |= searchMode == FieldSearchMode.Title; |
|||
foreach (var strategy in strategies) |
|||
{ |
|||
if (strategy.TryExtract(field, value, this)) |
|||
{ |
|||
return; |
|||
} |
|||
} |
|||
} |
|||
finally |
|||
{ |
|||
// The title mode only applies to the field and its nested values.
|
|||
isTitle = wasTitle; |
|||
} |
|||
} |
|||
|
|||
public void AppendValue(JsonValue value) |
|||
{ |
|||
AppendField(null, value); |
|||
} |
|||
|
|||
public void AppendObject<T>(JsonObject obj, IReadOnlyDictionary<string, T> fields) where T : IField |
|||
{ |
|||
foreach (var (key, value) in obj) |
|||
{ |
|||
if (key is Component.Discriminator or Component.Descriptor) |
|||
{ |
|||
continue; |
|||
} |
|||
|
|||
AppendField(fields.GetValueOrDefault(key), value); |
|||
} |
|||
} |
|||
|
|||
public void AppendText(string text, IField? field = null) |
|||
{ |
|||
foreach (var normalizer in normalizers) |
|||
{ |
|||
var normalized = normalizer.Normalize(text, field); |
|||
if (string.IsNullOrWhiteSpace(normalized)) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
text = normalized; |
|||
} |
|||
|
|||
collector.Append(text, language, isTitle); |
|||
} |
|||
|
|||
private static HashSet<string> GetTitleFields(Schema? schema) |
|||
{ |
|||
var result = new HashSet<string>(); |
|||
|
|||
if (schema == null) |
|||
{ |
|||
return result; |
|||
} |
|||
|
|||
// The fields in the references are used to identify a content, so they are the best candidates for titles.
|
|||
var names = schema.FieldsInReferences.Count > 0 ? schema.FieldsInReferences : schema.FieldsInLists; |
|||
|
|||
foreach (var name in names) |
|||
{ |
|||
if (FieldNames.IsDataField(name, out var dataField)) |
|||
{ |
|||
result.Add(dataField); |
|||
} |
|||
else if (!FieldNames.IsMetaField(name)) |
|||
{ |
|||
result.Add(name); |
|||
} |
|||
} |
|||
|
|||
// Use the same fallback as the UI, which shows the first field if nothing is configured.
|
|||
if (result.Count == 0 && schema.Fields.Count > 0) |
|||
{ |
|||
result.Add(schema.Fields[0].Name); |
|||
} |
|||
|
|||
return result; |
|||
} |
|||
} |
|||
@ -0,0 +1,12 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
|
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed record ExtractedTexts(Dictionary<string, string>? Texts, Dictionary<string, string>? Titles); |
|||
@ -0,0 +1,54 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Text; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class HtmlTextNormalizer : ITextNormalizer |
|||
{ |
|||
public int Order => 0; |
|||
|
|||
public string? Normalize(string text, IField? field) |
|||
{ |
|||
if (!IsHtmlField(field) && !LooksLikeHtml(text)) |
|||
{ |
|||
return text; |
|||
} |
|||
|
|||
try |
|||
{ |
|||
return text.Html2Text(); |
|||
} |
|||
catch |
|||
{ |
|||
// The parser fails for some invalid documents.
|
|||
return text; |
|||
} |
|||
} |
|||
|
|||
private static bool IsHtmlField(IField? field) |
|||
{ |
|||
if (field?.RawProperties is not StringFieldProperties properties) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
return properties.Editor is StringFieldEditor.Html or StringFieldEditor.RichText || properties.ContentType == StringContentType.Html; |
|||
} |
|||
|
|||
private static bool LooksLikeHtml(string text) |
|||
{ |
|||
if (!text.Contains('<', StringComparison.Ordinal)) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
return text.Contains("</", StringComparison.Ordinal) || text.Contains("/>", StringComparison.Ordinal); |
|||
} |
|||
} |
|||
@ -0,0 +1,18 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public interface ITextExtractionStrategy |
|||
{ |
|||
int Order { get; } |
|||
|
|||
ExtractedTexts? Extract(TextExtractionContext context, DomainId contentId, ContentData data); |
|||
} |
|||
@ -0,0 +1,18 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Infrastructure.Json.Objects; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public interface ITextFieldStrategy |
|||
{ |
|||
int Order { get; } |
|||
|
|||
bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker); |
|||
} |
|||
@ -0,0 +1,17 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public interface ITextNormalizer |
|||
{ |
|||
int Order { get; } |
|||
|
|||
string? Normalize(string text, IField? field); |
|||
} |
|||
@ -0,0 +1,43 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Infrastructure.Json.Objects; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class JsonTextStrategy : ITextFieldStrategy |
|||
{ |
|||
// Fallback for all values, e.g. JSON fields or unknown fields, that indexes all strings.
|
|||
public int Order => int.MaxValue; |
|||
|
|||
public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) |
|||
{ |
|||
switch (value.Value) |
|||
{ |
|||
case string text: |
|||
walker.AppendText(text, field); |
|||
break; |
|||
case JsonArray array: |
|||
foreach (var item in array) |
|||
{ |
|||
walker.AppendValue(item); |
|||
} |
|||
|
|||
break; |
|||
case JsonObject obj: |
|||
foreach (var (_, item) in obj) |
|||
{ |
|||
walker.AppendValue(item); |
|||
} |
|||
|
|||
break; |
|||
} |
|||
|
|||
return true; |
|||
} |
|||
} |
|||
@ -0,0 +1,39 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Text; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class MarkdownTextNormalizer : ITextNormalizer |
|||
{ |
|||
// Markdown can contain HTML, therefore it must be converted before the HTML.
|
|||
public int Order => -100; |
|||
|
|||
public string? Normalize(string text, IField? field) |
|||
{ |
|||
if (field?.RawProperties is not StringFieldProperties properties) |
|||
{ |
|||
return text; |
|||
} |
|||
|
|||
if (properties.Editor != StringFieldEditor.Markdown && properties.ContentType != StringContentType.Markdown) |
|||
{ |
|||
return text; |
|||
} |
|||
|
|||
try |
|||
{ |
|||
return text.Markdown2Text(); |
|||
} |
|||
catch |
|||
{ |
|||
return text; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,104 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using System.Buffers; |
|||
using System.Globalization; |
|||
using System.Text.RegularExpressions; |
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed partial class NoiseTextNormalizer : ITextNormalizer |
|||
{ |
|||
// Strings without whitespaces above this length are usually tokens, hashes or base64 data.
|
|||
private const int MaxWordLength = 64; |
|||
|
|||
// Same as char.IsWhiteSpace, but vectorized.
|
|||
private static readonly SearchValues<char> WhiteSpaces = |
|||
SearchValues.Create(Enumerable.Range(char.MinValue, char.MaxValue + 1).Select(x => (char)x).Where(char.IsWhiteSpace).ToArray()); |
|||
|
|||
// Runs last, because the other normalizers can change the text.
|
|||
public int Order => 1000; |
|||
|
|||
public string? Normalize(string text, IField? field) |
|||
{ |
|||
return IsNoise(text) ? null : text; |
|||
} |
|||
|
|||
public static bool IsNoise(string text) |
|||
{ |
|||
// The checks are ordered by costs, most texts are sentences or words and should be handled by the cheap checks.
|
|||
var span = text.AsSpan().Trim(); |
|||
if (span.Length == 0) |
|||
{ |
|||
return true; |
|||
} |
|||
|
|||
// Anything with whitespaces is considered as normal text.
|
|||
if (span.ContainsAny(WhiteSpaces)) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
if (span.Length > MaxWordLength) |
|||
{ |
|||
return true; |
|||
} |
|||
|
|||
if (IsUrl(span)) |
|||
{ |
|||
return true; |
|||
} |
|||
|
|||
// Colors can consist of letters only, e.g. #fff, therefore they are checked before the digits.
|
|||
if (span[0] == '#') |
|||
{ |
|||
return HexColorRegex().IsMatch(span); |
|||
} |
|||
|
|||
// Numbers, dates and IDs contain digits.
|
|||
if (!span.ContainsAnyInRange('0', '9')) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
if (span.Length >= 10 && span[4] == '-' && IsoDateRegex().IsMatch(span)) |
|||
{ |
|||
return true; |
|||
} |
|||
|
|||
// Reference IDs, asset IDs and component schema IDs.
|
|||
if (Guid.TryParse(span, out _)) |
|||
{ |
|||
return true; |
|||
} |
|||
|
|||
return double.TryParse(span, NumberStyles.Float, CultureInfo.InvariantCulture, out _); |
|||
} |
|||
|
|||
private static bool IsUrl(ReadOnlySpan<char> span) |
|||
{ |
|||
// Only the prefix is checked, because a full validation would be expensive and the URL is not indexed anyway.
|
|||
if (span.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) |
|||
{ |
|||
return true; |
|||
} |
|||
|
|||
if (span.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) |
|||
{ |
|||
return true; |
|||
} |
|||
|
|||
return span.StartsWith("data:", StringComparison.OrdinalIgnoreCase); |
|||
} |
|||
|
|||
[GeneratedRegex("^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$")]
|
|||
private static partial Regex HexColorRegex(); |
|||
|
|||
[GeneratedRegex("^\\d{4}-\\d{2}-\\d{2}(T[0-9:.]+(Z|[+-]\\d{2}:?\\d{2})?)?$")]
|
|||
private static partial Regex IsoDateRegex(); |
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Infrastructure.Json.Objects; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class RichTextFieldTextStrategy : ITextFieldStrategy |
|||
{ |
|||
public int Order => 0; |
|||
|
|||
public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) |
|||
{ |
|||
if (field?.RawProperties is not RichTextFieldProperties || !RichTextNode.TryCreate(value, SquidexRichText.Options, out var node)) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
walker.AppendText(node.ToText(), field); |
|||
return true; |
|||
} |
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class SchemaTextExtractionStrategy(IEnumerable<ITextFieldStrategy> fieldStrategies, IEnumerable<ITextNormalizer> normalizers) : ITextExtractionStrategy |
|||
{ |
|||
private readonly ITextFieldStrategy[] fieldStrategies = fieldStrategies.OrderBy(x => x.Order).ToArray(); |
|||
private readonly ITextNormalizer[] normalizers = normalizers.OrderBy(x => x.Order).ToArray(); |
|||
|
|||
public int Order => 0; |
|||
|
|||
public ExtractedTexts? Extract(TextExtractionContext context, DomainId contentId, ContentData data) |
|||
{ |
|||
using var collector = new TextCollector(); |
|||
|
|||
new ContentTextWalker(fieldStrategies, normalizers, context, collector).Walk(data); |
|||
|
|||
return collector.Build(); |
|||
} |
|||
} |
|||
@ -0,0 +1,130 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core; |
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Domain.Apps.Core.Scripting; |
|||
using Squidex.Infrastructure; |
|||
using Squidex.Infrastructure.Json.Objects; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class ScriptTextExtractionStrategy(IScriptEngine scriptEngine) : ITextExtractionStrategy |
|||
{ |
|||
private static readonly object ScriptKey = new object(); |
|||
private static readonly ScriptOptions ScriptOptions = new ScriptOptions |
|||
{ |
|||
AsContext = true, |
|||
CanDisallow = false, |
|||
CanReject = false, |
|||
Readonly = true, |
|||
}; |
|||
|
|||
// The script can override the schema, therefore it must run first.
|
|||
public int Order => -1000; |
|||
|
|||
public ExtractedTexts? Extract(TextExtractionContext context, DomainId contentId, ContentData data) |
|||
{ |
|||
var script = context.Schema?.Scripts.Index; |
|||
if (string.IsNullOrWhiteSpace(script)) |
|||
{ |
|||
return null; |
|||
} |
|||
|
|||
// The context is only used by one thread, therefore the script can be reused for all contents of the schema.
|
|||
var compiled = context.GetOrAdd(ScriptKey, (ScriptEngine: scriptEngine, Script: script), static x => Compile(x.ScriptEngine, x.Script)); |
|||
if (compiled == null) |
|||
{ |
|||
return null; |
|||
} |
|||
|
|||
try |
|||
{ |
|||
// Script vars are just wrappers over dictionaries for better performance.
|
|||
var vars = new ContentScriptVars |
|||
{ |
|||
AppId = context.AppId.Id, |
|||
AppName = context.AppId.Name, |
|||
ContentId = contentId, |
|||
Data = data, |
|||
SchemaId = context.SchemaId.Id, |
|||
SchemaName = context.SchemaId.Name, |
|||
}; |
|||
|
|||
return ToTexts(compiled.Execute(vars)); |
|||
} |
|||
catch |
|||
{ |
|||
// The state of the script is unknown after an error, e.g. a timeout, therefore it is not reused.
|
|||
context.Remove(ScriptKey); |
|||
|
|||
// Fallback to the next strategy.
|
|||
return null; |
|||
} |
|||
} |
|||
|
|||
private static IScript? Compile(IScriptEngine scriptEngine, string script) |
|||
{ |
|||
try |
|||
{ |
|||
return scriptEngine.CreateScript(script, ScriptOptions); |
|||
} |
|||
catch |
|||
{ |
|||
// The contents are indexed without the script.
|
|||
return null; |
|||
} |
|||
} |
|||
|
|||
public static ExtractedTexts? ToTexts(JsonValue result) |
|||
{ |
|||
// The script output is used as it is, therefore the normalizers are not applied.
|
|||
using var collector = new TextCollector(); |
|||
|
|||
// Undefined or null means that the script wants to fallback to the next strategy.
|
|||
switch (result.Value) |
|||
{ |
|||
case string text: |
|||
collector.Append(text, InvariantPartitioning.Key, false); |
|||
break; |
|||
case JsonObject obj: |
|||
Append(collector, obj, "title", true); |
|||
Append(collector, obj, "body", false); |
|||
break; |
|||
default: |
|||
return null; |
|||
} |
|||
|
|||
// An empty result means that the script has handled the content, therefore the next strategy must not run.
|
|||
return collector.Build() ?? new ExtractedTexts(null, null); |
|||
} |
|||
|
|||
private static void Append(TextCollector collector, JsonObject obj, string key, bool isTitle) |
|||
{ |
|||
if (!obj.TryGetValue(key, out var value)) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
switch (value.Value) |
|||
{ |
|||
case string text: |
|||
collector.Append(text, InvariantPartitioning.Key, isTitle); |
|||
break; |
|||
case JsonObject languages: |
|||
foreach (var (language, languageValue) in languages) |
|||
{ |
|||
if (languageValue.Value is string languageText) |
|||
{ |
|||
collector.Append(languageText, language, isTitle); |
|||
} |
|||
} |
|||
|
|||
break; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,73 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Infrastructure.Collections; |
|||
using Squidex.Infrastructure.Json.Objects; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class SearchPathsFieldTextStrategy : ITextFieldStrategy |
|||
{ |
|||
// Search paths are configured explicitly and therefore override all other strategies.
|
|||
public int Order => -1000; |
|||
|
|||
public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) |
|||
{ |
|||
if (field?.RawProperties.SearchPaths is not { Count: > 0 } paths) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
// Parse the paths only once for all contents of the schema. The list is the key, so that no key has to be allocated.
|
|||
var parsedPaths = walker.Context.GetOrAdd(paths, paths, static x => ParsePaths(x)); |
|||
|
|||
foreach (var path in parsedPaths) |
|||
{ |
|||
AppendPath(value, path, 0, walker); |
|||
} |
|||
|
|||
return true; |
|||
} |
|||
|
|||
private static void AppendPath(JsonValue value, string[] path, int index, ContentTextWalker walker) |
|||
{ |
|||
if (index == path.Length) |
|||
{ |
|||
walker.AppendValue(value); |
|||
return; |
|||
} |
|||
|
|||
switch (value.Value) |
|||
{ |
|||
case JsonArray array: |
|||
// Arrays are traversed implicitly, so that users do not have to specify the index.
|
|||
foreach (var item in array) |
|||
{ |
|||
AppendPath(item, path, index, walker); |
|||
} |
|||
|
|||
break; |
|||
case JsonObject obj when obj.TryGetValue(path[index], out var child): |
|||
AppendPath(child, path, index + 1, walker); |
|||
break; |
|||
} |
|||
} |
|||
|
|||
private static string[][] ParsePaths(ReadonlyList<string> paths) |
|||
{ |
|||
return paths.Select(ParsePath).ToArray(); |
|||
} |
|||
|
|||
private static string[] ParsePath(string path) |
|||
{ |
|||
// Also support the JSON path syntax, e.g. '$.items[*].label'.
|
|||
path = path.Trim().TrimStart('$').Replace("[*]", string.Empty, StringComparison.Ordinal).Replace("[]", string.Empty, StringComparison.Ordinal); |
|||
|
|||
return path.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); |
|||
} |
|||
} |
|||
@ -0,0 +1,68 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using System.Text; |
|||
using Squidex.Infrastructure; |
|||
using Squidex.Infrastructure.ObjectPool; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class TextCollector : IDisposable |
|||
{ |
|||
private readonly Dictionary<string, StringBuilder> bodies = []; |
|||
private readonly Dictionary<string, StringBuilder> titles = []; |
|||
|
|||
public void Dispose() |
|||
{ |
|||
foreach (var sb in bodies.Values.Concat(titles.Values)) |
|||
{ |
|||
DefaultPools.StringBuilder.Return(sb); |
|||
} |
|||
} |
|||
|
|||
public void Append(string text, string language, bool isTitle) |
|||
{ |
|||
if (string.IsNullOrWhiteSpace(text)) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
var target = isTitle ? titles : bodies; |
|||
if (!target.TryGetValue(language, out var sb)) |
|||
{ |
|||
sb = DefaultPools.StringBuilder.Get(); |
|||
|
|||
target[language] = sb; |
|||
} |
|||
|
|||
sb.AppendIfNotEmpty(' '); |
|||
sb.Append(text.Trim()); |
|||
} |
|||
|
|||
public ExtractedTexts? Build() |
|||
{ |
|||
var extractedTexts = Build(bodies); |
|||
var extractedTitles = Build(titles); |
|||
|
|||
if (extractedTexts == null && extractedTitles == null) |
|||
{ |
|||
return null; |
|||
} |
|||
|
|||
return new ExtractedTexts(extractedTexts, extractedTitles); |
|||
} |
|||
|
|||
private static Dictionary<string, string>? Build(Dictionary<string, StringBuilder> source) |
|||
{ |
|||
if (source.Count == 0) |
|||
{ |
|||
return null; |
|||
} |
|||
|
|||
return source.ToDictionary(x => x.Key, x => x.Value.ToString()); |
|||
} |
|||
} |
|||
@ -0,0 +1,58 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
// The context is created for all contents of a schema in a batch and only used by a single thread.
|
|||
public sealed class TextExtractionContext : IDisposable |
|||
{ |
|||
private readonly Dictionary<object, object?> items = []; |
|||
|
|||
required public NamedId<DomainId> AppId { get; init; } |
|||
|
|||
required public NamedId<DomainId> SchemaId { get; init; } |
|||
|
|||
public Schema? Schema { get; init; } |
|||
|
|||
public ResolvedComponents Components { get; init; } = ResolvedComponents.Empty; |
|||
|
|||
public void Dispose() |
|||
{ |
|||
foreach (var item in items.Values.OfType<IDisposable>()) |
|||
{ |
|||
item.Dispose(); |
|||
} |
|||
|
|||
items.Clear(); |
|||
} |
|||
|
|||
public T GetOrAdd<T, TArg>(object key, TArg arg, Func<TArg, T> factory) |
|||
{ |
|||
// The strategies can store expensive values for the schema, e.g. compiled scripts.
|
|||
if (items.TryGetValue(key, out var existing)) |
|||
{ |
|||
return (T)existing!; |
|||
} |
|||
|
|||
// The argument allows static factories without closures, because this method is called for every content.
|
|||
var value = factory(arg); |
|||
|
|||
items[key] = value; |
|||
return value; |
|||
} |
|||
|
|||
public void Remove(object key) |
|||
{ |
|||
if (items.Remove(key, out var existing) && existing is IDisposable disposable) |
|||
{ |
|||
disposable.Dispose(); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,31 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
|
|||
public sealed class TextExtractor(IEnumerable<ITextExtractionStrategy> strategies) |
|||
{ |
|||
private readonly ITextExtractionStrategy[] strategies = strategies.OrderBy(x => x.Order).ToArray(); |
|||
|
|||
public ExtractedTexts? Extract(TextExtractionContext context, DomainId contentId, ContentData data) |
|||
{ |
|||
// The first strategy that returns a result wins, e.g. the index script before the schema.
|
|||
foreach (var strategy in strategies) |
|||
{ |
|||
var result = strategy.Extract(context, contentId, data); |
|||
if (result != null) |
|||
{ |
|||
return result; |
|||
} |
|||
} |
|||
|
|||
return null; |
|||
} |
|||
} |
|||
@ -0,0 +1,131 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Apps; |
|||
using Squidex.Domain.Apps.Entities.Jobs; |
|||
using Squidex.Events; |
|||
using Squidex.Infrastructure; |
|||
using Squidex.Infrastructure.EventSourcing; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; |
|||
|
|||
public sealed class RebuildTextIndexJob( |
|||
IAppProvider appProvider, |
|||
IEventStore eventStore, |
|||
IEventFormatter eventFormatter, |
|||
TextIndexingProcess textIndexer, |
|||
TextIndexRebuildCoordinator coordinator) |
|||
: IJobRunner |
|||
{ |
|||
public const string TaskName = "rebuildTextIndex"; |
|||
public const string ArgAppId = "appId"; |
|||
public const string ArgAppName = "appName"; |
|||
|
|||
// Same as the text indexer, the commands only keep the latest version of each content in the batch.
|
|||
private const int BatchSize = 1000; |
|||
|
|||
private sealed class Progress |
|||
{ |
|||
// The position of the last event that has been written to the index.
|
|||
public string? Position { get; set; } |
|||
|
|||
public long ProcessedEvents { get; set; } |
|||
} |
|||
|
|||
public string Name => TaskName; |
|||
|
|||
public static JobRequest BuildRequest(RefToken actor, App app) |
|||
{ |
|||
Guard.NotNull(actor); |
|||
Guard.NotNull(app); |
|||
|
|||
var arguments = new Dictionary<string, string> |
|||
{ |
|||
[ArgAppId] = app.Id.ToString(), |
|||
[ArgAppName] = app.Name, |
|||
}; |
|||
|
|||
return JobRequest.Create(actor, TaskName, arguments) with |
|||
{ |
|||
AppId = app.NamedId(), |
|||
}; |
|||
} |
|||
|
|||
public async Task RunAsync(JobRunContext context, |
|||
CancellationToken ct) |
|||
{ |
|||
var app = await appProvider.GetAppAsync(context.OwnerId, true, ct) |
|||
?? throw new DomainObjectNotFoundException(context.OwnerId.ToString()); |
|||
|
|||
// Use a readable name to describe the job.
|
|||
context.Job.Description = "Rebuild full text index"; |
|||
|
|||
// From now on the text indexer skips the events of the app and only counts them.
|
|||
await coordinator.TakeOverAsync(app.Id, ct); |
|||
|
|||
await context.LogAsync("Started rebuild"); |
|||
|
|||
var progress = new Progress(); |
|||
|
|||
try |
|||
{ |
|||
await ReplayAsync(context, app.Id, progress, ct); |
|||
} |
|||
finally |
|||
{ |
|||
// Hand the app back to the text indexer, also when the job has been cancelled or has failed.
|
|||
await HandBackAsync(context, app.Id, progress); |
|||
} |
|||
|
|||
await context.LogAsync($"Completed rebuild of {progress.ProcessedEvents} events"); |
|||
} |
|||
|
|||
private async Task HandBackAsync(JobRunContext context, DomainId appId, Progress progress) |
|||
{ |
|||
try |
|||
{ |
|||
// The events are replayed in order, therefore the contents could be at an older version when the job has been cancelled.
|
|||
// So we cannot cancel the handback, but have to replay all remaining events.
|
|||
while (true) |
|||
{ |
|||
var skippedEvents = await coordinator.GetSkippedEventsAsync(appId); |
|||
|
|||
await ReplayAsync(context, appId, progress, default); |
|||
|
|||
// Only hand back if the text indexer has not skipped any event while we were reading the event store.
|
|||
if (await coordinator.TryHandBackAsync(appId, skippedEvents)) |
|||
{ |
|||
break; |
|||
} |
|||
} |
|||
} |
|||
catch |
|||
{ |
|||
// The text indexer must not skip the app forever. The job fails and has to be started again.
|
|||
await coordinator.ReleaseAsync(appId); |
|||
throw; |
|||
} |
|||
} |
|||
|
|||
private async Task ReplayAsync(JobRunContext context, DomainId appId, Progress progress, |
|||
CancellationToken ct) |
|||
{ |
|||
var streamFilter = StreamFilter.Prefix($"content-{appId}{DomainId.IdSeparator}"); |
|||
|
|||
// Continue from the last position, e.g. to catch up with the events that have been skipped by the text indexer.
|
|||
await foreach (var batch in eventStore.QueryAllAsync(streamFilter, progress.Position, ct: ct).Batch(BatchSize, ct)) |
|||
{ |
|||
// The text indexer skips the events of the app, therefore we can replay the events without the version check.
|
|||
await textIndexer.ApplyAsync(batch.Select(eventFormatter.ParseIfKnown).NotNull().ToList(), true, ct); |
|||
|
|||
progress.Position = batch[^1].EventPosition; |
|||
progress.ProcessedEvents += batch.Count; |
|||
|
|||
await context.LogAsync($"Rebuilt events: {progress.ProcessedEvents}", true); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,31 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; |
|||
|
|||
public sealed class TextIndexBatch(IDisposable handle, Dictionary<DomainId, long> skippedEvents) : IDisposable |
|||
{ |
|||
public bool TrySkip(DomainId appId) |
|||
{ |
|||
if (!skippedEvents.TryGetValue(appId, out var count)) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
// The rebuild reads the event from the event store, but it must know that it has to catch up.
|
|||
skippedEvents[appId] = count + 1; |
|||
return true; |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
// The rebuild cannot hand back the app while the batch is processed.
|
|||
handle.Dispose(); |
|||
} |
|||
} |
|||
@ -0,0 +1,74 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Infrastructure; |
|||
using Squidex.Infrastructure.Tasks; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; |
|||
|
|||
// The text indexer and the rebuild jobs both run on the worker node, therefore the coordination can happen in memory.
|
|||
public sealed class TextIndexRebuildCoordinator |
|||
{ |
|||
private readonly AsyncLock syncLock = new AsyncLock(); |
|||
|
|||
// The number of events per app that the text indexer has skipped, because the app is rebuilt.
|
|||
private readonly Dictionary<DomainId, long> skippedEvents = []; |
|||
|
|||
public async Task<TextIndexBatch> BeginBatchAsync( |
|||
CancellationToken ct = default) |
|||
{ |
|||
// The rebuild only holds the lock for short operations in memory, never for the rebuild itself.
|
|||
var handle = await syncLock.EnterAsync(ct); |
|||
|
|||
return new TextIndexBatch(handle, skippedEvents); |
|||
} |
|||
|
|||
public async Task TakeOverAsync(DomainId appId, |
|||
CancellationToken ct = default) |
|||
{ |
|||
using (await syncLock.EnterAsync(ct)) |
|||
{ |
|||
if (!skippedEvents.TryAdd(appId, 0)) |
|||
{ |
|||
throw new DomainException("The full text index of the app is already rebuilt."); |
|||
} |
|||
} |
|||
} |
|||
|
|||
public async Task<long> GetSkippedEventsAsync(DomainId appId, |
|||
CancellationToken ct = default) |
|||
{ |
|||
using (await syncLock.EnterAsync(ct)) |
|||
{ |
|||
return skippedEvents.GetValueOrDefault(appId); |
|||
} |
|||
} |
|||
|
|||
public async Task<bool> TryHandBackAsync(DomainId appId, long expectedSkippedEvents, |
|||
CancellationToken ct = default) |
|||
{ |
|||
using (await syncLock.EnterAsync(ct)) |
|||
{ |
|||
// The text indexer has skipped events after the rebuild has read the event store, therefore it has to catch up again.
|
|||
if (skippedEvents.TryGetValue(appId, out var count) && count != expectedSkippedEvents) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
skippedEvents.Remove(appId); |
|||
return true; |
|||
} |
|||
} |
|||
|
|||
public async Task ReleaseAsync(DomainId appId) |
|||
{ |
|||
using (await syncLock.EnterAsync()) |
|||
{ |
|||
skippedEvents.Remove(appId); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,67 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
using Squidex.Domain.Apps.Events.Contents; |
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text; |
|||
|
|||
public sealed class TextIndexExtraction(IAppProvider appProvider, TextExtractor textExtractor) |
|||
{ |
|||
public async Task<Dictionary<ContentData, ExtractedTexts?>> ExtractAsync(IEnumerable<(ContentEvent Event, ContentData Data)> sources, |
|||
CancellationToken ct) |
|||
{ |
|||
// Compare by reference, because the events hold the instances and value equality is expensive.
|
|||
var result = new Dictionary<ContentData, ExtractedTexts?>(ReferenceEqualityComparer.Instance); |
|||
|
|||
// Group by schema, so that the strategies can reuse expensive values for all contents, e.g. compiled scripts.
|
|||
var groups = sources.GroupBy(x => (AppId: x.Event.AppId.Id, SchemaId: x.Event.SchemaId.Id)); |
|||
|
|||
foreach (var group in groups) |
|||
{ |
|||
var (schema, components) = await GetSchemaAsync(group.Key.AppId, group.Key.SchemaId, ct); |
|||
|
|||
var first = group.First().Event; |
|||
|
|||
using var context = new TextExtractionContext |
|||
{ |
|||
AppId = first.AppId, |
|||
Components = components, |
|||
Schema = schema, |
|||
SchemaId = first.SchemaId, |
|||
}; |
|||
|
|||
foreach (var (@event, data) in group) |
|||
{ |
|||
if (!result.ContainsKey(data)) |
|||
{ |
|||
result[data] = textExtractor.Extract(context, @event.ContentId, data); |
|||
} |
|||
} |
|||
} |
|||
|
|||
return result; |
|||
} |
|||
|
|||
private async Task<(Schema?, ResolvedComponents)> GetSchemaAsync(DomainId appId, DomainId schemaId, |
|||
CancellationToken ct) |
|||
{ |
|||
var schema = await appProvider.GetSchemaAsync(appId, schemaId, true, ct); |
|||
if (schema == null) |
|||
{ |
|||
return (null, ResolvedComponents.Empty); |
|||
} |
|||
|
|||
// Slightly outdated components are fine for the index, but loading them for each batch is expensive.
|
|||
var components = await appProvider.GetComponentsAsync(schema, true, ct); |
|||
|
|||
return (schema, components); |
|||
} |
|||
} |
|||
@ -0,0 +1,141 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core.Apps; |
|||
using Squidex.Events; |
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; |
|||
|
|||
public class RebuildTextIndexJobTests : TextIndexTestBase |
|||
{ |
|||
private readonly TextIndexingProcess process; |
|||
private readonly RebuildTextIndexJob sut; |
|||
|
|||
public RebuildTextIndexJobTests() |
|||
{ |
|||
process = CreateProcess(); |
|||
|
|||
sut = CreateJob(process); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_create_request() |
|||
{ |
|||
var job = RebuildTextIndexJob.BuildRequest(User, App); |
|||
|
|||
job.Arguments.Should().BeEquivalentTo( |
|||
new Dictionary<string, string> |
|||
{ |
|||
["appId"] = App.Id.ToString(), |
|||
["appName"] = App.Name, |
|||
}); |
|||
|
|||
Assert.Equal(App.NamedId(), job.AppId); |
|||
Assert.Equal(RebuildTextIndexJob.TaskName, job.TaskName); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_throw_exception_if_app_not_found() |
|||
{ |
|||
A.CallTo(() => AppProvider.GetAppAsync(AppId.Id, true, A<CancellationToken>._)) |
|||
.Returns(Task.FromResult<App?>(null)); |
|||
|
|||
await Assert.ThrowsAsync<DomainObjectNotFoundException>(() => sut.RunAsync(CreateRunContext(), CancellationToken)); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_throw_exception_if_app_is_already_rebuilt() |
|||
{ |
|||
await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); |
|||
|
|||
await Assert.ThrowsAsync<DomainException>(() => sut.RunAsync(CreateRunContext(), CancellationToken)); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_replay_events_of_app() |
|||
{ |
|||
StoreEvents(Created(TextData("field", "Version1"), 0), Updated(TextData("field", "Version2"), 1)); |
|||
|
|||
await sut.RunAsync(CreateRunContext(), CancellationToken); |
|||
|
|||
Assert.Equal("Version2", GetText()); |
|||
|
|||
A.CallTo(() => EventStore.QueryAllAsync(StreamFilter.Prefix($"content-{AppId.Id}{DomainId.IdSeparator}"), A<StreamPosition>.That.Matches(x => x.Token == null), A<int>._, A<CancellationToken>._)) |
|||
.MustHaveHappened(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_replay_events_that_have_been_skipped_during_rebuild() |
|||
{ |
|||
var updated = Updated(TextData("field", "Version2"), 1); |
|||
|
|||
StoreEvents(Created(TextData("field", "Version1"), 0)); |
|||
|
|||
var isFirst = true; |
|||
|
|||
A.CallTo(() => TextIndex.ExecuteAsync(A<IndexCommand[]>._, A<CancellationToken>._)) |
|||
.ReturnsLazily(async x => |
|||
{ |
|||
Commands.AddRange(x.GetArgument<IndexCommand[]>(0)!); |
|||
|
|||
// The content is changed while the app is rebuilt, therefore the indexer skips the event.
|
|||
if (isFirst) |
|||
{ |
|||
isFirst = false; |
|||
|
|||
StoreEvents(updated); |
|||
await process.On([updated]); |
|||
} |
|||
}); |
|||
|
|||
await sut.RunAsync(CreateRunContext(), CancellationToken); |
|||
|
|||
Assert.Equal("Version2", GetText()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_index_app_again_after_rebuild() |
|||
{ |
|||
StoreEvents(Created(TextData("field", "Version1"), 0)); |
|||
|
|||
await sut.RunAsync(CreateRunContext(), CancellationToken); |
|||
|
|||
await process.On([Updated(TextData("field", "Version2"), 1)]); |
|||
|
|||
Assert.Equal("Version2", GetText()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_replay_events_and_hand_back_if_rebuild_failed() |
|||
{ |
|||
StoreEvents(Created(TextData("field", "Version1"), 0)); |
|||
|
|||
A.CallTo(() => EventStore.QueryAllAsync(A<StreamFilter>._, A<StreamPosition>._, A<int>._, A<CancellationToken>._)) |
|||
.Throws(new OperationCanceledException()).Once(); |
|||
|
|||
await Assert.ThrowsAsync<OperationCanceledException>(() => sut.RunAsync(CreateRunContext(), CancellationToken)); |
|||
|
|||
await process.On([Updated(TextData("field", "Version2"), 1)]); |
|||
|
|||
Assert.Equal("Version2", GetText()); |
|||
Assert.Equal(2, Commands.OfType<UpsertIndexEntry>().Count()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_release_app_if_hand_back_failed() |
|||
{ |
|||
A.CallTo(() => EventStore.QueryAllAsync(A<StreamFilter>._, A<StreamPosition>._, A<int>._, A<CancellationToken>._)) |
|||
.Throws(new InvalidOperationException()); |
|||
|
|||
await Assert.ThrowsAsync<InvalidOperationException>(() => sut.RunAsync(CreateRunContext(), CancellationToken)); |
|||
|
|||
await process.On([Created(TextData("field", "Hello"), 0)]); |
|||
|
|||
Assert.Equal("Hello", GetText()); |
|||
} |
|||
} |
|||
@ -0,0 +1,114 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; |
|||
|
|||
public class TextIndexRebuildCoordinatorTests |
|||
{ |
|||
private readonly DomainId appId = DomainId.NewGuid(); |
|||
private readonly TextIndexRebuildCoordinator sut = new TextIndexRebuildCoordinator(); |
|||
|
|||
[Fact] |
|||
public async Task Should_throw_exception_if_app_is_already_taken_over() |
|||
{ |
|||
await sut.TakeOverAsync(appId); |
|||
|
|||
await Assert.ThrowsAsync<DomainException>(() => sut.TakeOverAsync(appId)); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_not_skip_events_if_app_is_not_taken_over() |
|||
{ |
|||
using var batch = await sut.BeginBatchAsync(); |
|||
|
|||
Assert.False(batch.TrySkip(appId)); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_skip_and_count_events_if_app_is_taken_over() |
|||
{ |
|||
await sut.TakeOverAsync(appId); |
|||
|
|||
using (var batch = await sut.BeginBatchAsync()) |
|||
{ |
|||
Assert.True(batch.TrySkip(appId)); |
|||
Assert.True(batch.TrySkip(appId)); |
|||
Assert.False(batch.TrySkip(DomainId.NewGuid())); |
|||
} |
|||
|
|||
var skipped = await sut.GetSkippedEventsAsync(appId); |
|||
|
|||
Assert.Equal(2, skipped); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_not_hand_back_if_events_have_been_skipped_in_the_meantime() |
|||
{ |
|||
await sut.TakeOverAsync(appId); |
|||
|
|||
using (var batch = await sut.BeginBatchAsync()) |
|||
{ |
|||
batch.TrySkip(appId); |
|||
} |
|||
|
|||
var handedBack = await sut.TryHandBackAsync(appId, 0); |
|||
|
|||
Assert.False(handedBack); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_hand_back_if_no_events_have_been_skipped_in_the_meantime() |
|||
{ |
|||
await sut.TakeOverAsync(appId); |
|||
|
|||
using (var batch = await sut.BeginBatchAsync()) |
|||
{ |
|||
batch.TrySkip(appId); |
|||
} |
|||
|
|||
var handedBack = await sut.TryHandBackAsync(appId, 1); |
|||
|
|||
using (var batch = await sut.BeginBatchAsync()) |
|||
{ |
|||
Assert.False(batch.TrySkip(appId)); |
|||
} |
|||
|
|||
Assert.True(handedBack); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_not_skip_events_after_release() |
|||
{ |
|||
await sut.TakeOverAsync(appId); |
|||
await sut.ReleaseAsync(appId); |
|||
|
|||
using (var batch = await sut.BeginBatchAsync()) |
|||
{ |
|||
Assert.False(batch.TrySkip(appId)); |
|||
} |
|||
|
|||
await sut.TakeOverAsync(appId); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_not_hand_back_while_batch_is_processed() |
|||
{ |
|||
await sut.TakeOverAsync(appId); |
|||
|
|||
var batch = await sut.BeginBatchAsync(); |
|||
|
|||
var handBack = sut.TryHandBackAsync(appId, 0); |
|||
|
|||
Assert.False(handBack.IsCompleted); |
|||
|
|||
batch.Dispose(); |
|||
|
|||
Assert.True(await handBack); |
|||
} |
|||
} |
|||
@ -0,0 +1,94 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using System.Globalization; |
|||
using Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text; |
|||
|
|||
public class TextExtractionContextTests |
|||
{ |
|||
private readonly object key = new object(); |
|||
private readonly TextExtractionContext sut = new TextExtractionContext |
|||
{ |
|||
AppId = NamedId.Of(DomainId.NewGuid(), "my-app"), |
|||
SchemaId = NamedId.Of(DomainId.NewGuid(), "my-schema"), |
|||
}; |
|||
|
|||
[Fact] |
|||
public void Should_create_value_only_once() |
|||
{ |
|||
var calls = new List<int>(); |
|||
|
|||
var value1 = sut.GetOrAdd(key, 42, x => Create(calls, x)); |
|||
var value2 = sut.GetOrAdd(key, 13, x => Create(calls, x)); |
|||
|
|||
Assert.Equal("42", value1); |
|||
Assert.Equal("42", value2); |
|||
Assert.Equal([42], calls); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_cache_null_value() |
|||
{ |
|||
var calls = new List<int>(); |
|||
|
|||
var value1 = sut.GetOrAdd(key, 42, x => CreateNull(calls, x)); |
|||
var value2 = sut.GetOrAdd(key, 13, x => CreateNull(calls, x)); |
|||
|
|||
Assert.Null(value1); |
|||
Assert.Null(value2); |
|||
|
|||
Assert.Equal([42], calls); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_dispose_value_if_removed() |
|||
{ |
|||
var disposable = A.Fake<IDisposable>(); |
|||
|
|||
sut.GetOrAdd(key, disposable, x => x); |
|||
sut.Remove(key); |
|||
|
|||
var value = sut.GetOrAdd(key, 0, x => "new"); |
|||
|
|||
Assert.Equal("new", value); |
|||
A.CallTo(() => disposable.Dispose()) |
|||
.MustHaveHappenedOnceExactly(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_dispose_values_if_disposed() |
|||
{ |
|||
var disposable1 = A.Fake<IDisposable>(); |
|||
var disposable2 = A.Fake<IDisposable>(); |
|||
|
|||
sut.GetOrAdd(new object(), disposable1, x => x); |
|||
sut.GetOrAdd(new object(), disposable2, x => x); |
|||
sut.Dispose(); |
|||
|
|||
A.CallTo(() => disposable1.Dispose()) |
|||
.MustHaveHappenedOnceExactly(); |
|||
A.CallTo(() => disposable2.Dispose()) |
|||
.MustHaveHappenedOnceExactly(); |
|||
} |
|||
|
|||
private static string Create(List<int> calls, int value) |
|||
{ |
|||
calls.Add(value); |
|||
|
|||
return value.ToString(CultureInfo.InvariantCulture); |
|||
} |
|||
|
|||
private static string? CreateNull(List<int> calls, int value) |
|||
{ |
|||
calls.Add(value); |
|||
|
|||
return null; |
|||
} |
|||
} |
|||
@ -0,0 +1,682 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core; |
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Domain.Apps.Core.Scripting; |
|||
using Squidex.Domain.Apps.Entities.Contents.Text.Extraction; |
|||
using Squidex.Infrastructure; |
|||
using Squidex.Infrastructure.Collections; |
|||
using Squidex.Infrastructure.Json.Objects; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text; |
|||
|
|||
public class TextExtractorTests |
|||
{ |
|||
private readonly DomainId componentId = DomainId.NewGuid(); |
|||
private readonly IScriptEngine scriptEngine = A.Fake<IScriptEngine>(); |
|||
private readonly TextExtractor sut; |
|||
|
|||
public TextExtractorTests() |
|||
{ |
|||
sut = CreateExtractor(scriptEngine); |
|||
} |
|||
|
|||
public static TextExtractor CreateExtractor(IScriptEngine scriptEngine) |
|||
{ |
|||
ITextFieldStrategy[] fieldStrategies = |
|||
[ |
|||
new ArrayFieldTextStrategy(), |
|||
new ComponentTextStrategy(), |
|||
new JsonTextStrategy(), |
|||
new RichTextFieldTextStrategy(), |
|||
new SearchPathsFieldTextStrategy(), |
|||
]; |
|||
|
|||
ITextNormalizer[] normalizers = |
|||
[ |
|||
new HtmlTextNormalizer(), |
|||
new MarkdownTextNormalizer(), |
|||
new NoiseTextNormalizer(), |
|||
]; |
|||
|
|||
return new TextExtractor( |
|||
[ |
|||
new SchemaTextExtractionStrategy(fieldStrategies, normalizers), |
|||
new ScriptTextExtractionStrategy(scriptEngine), |
|||
]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_extract_texts_by_language_without_schema() |
|||
{ |
|||
var data = |
|||
new ContentData() |
|||
.AddField("field1", |
|||
new ContentFieldData() |
|||
.AddLocalized("en", "Hello") |
|||
.AddLocalized("de", "Hallo")) |
|||
.AddField("field2", |
|||
new ContentFieldData() |
|||
.AddLocalized("en", "World")); |
|||
|
|||
var actual = Extract(data); |
|||
|
|||
Assert.Equal("Hello World", actual!.Texts!["en"]); |
|||
Assert.Equal("Hallo", actual!.Texts!["de"]); |
|||
Assert.Null(actual!.Titles); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_return_null_if_no_text_found() |
|||
{ |
|||
var data = |
|||
new ContentData() |
|||
.AddField("field1", |
|||
new ContentFieldData() |
|||
.AddInvariant(42)); |
|||
|
|||
var actual = Extract(data); |
|||
|
|||
Assert.Null(actual); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_extract_all_strings_from_json_values() |
|||
{ |
|||
var data = |
|||
new ContentData() |
|||
.AddField("json", |
|||
new ContentFieldData() |
|||
.AddInvariant( |
|||
JsonValue.Object() |
|||
.Add("label", "Hello") |
|||
.Add("nested", JsonValue.Array(JsonValue.Object().Add("text", "World"))))); |
|||
|
|||
var actual = Extract(data); |
|||
|
|||
Assert.Equal("Hello World", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData("a3d0e3c8-4c7b-4b54-8c9e-3a7c0d1f2e5b")] |
|||
[InlineData("42")] |
|||
[InlineData("3.14")] |
|||
[InlineData("#ff0000")] |
|||
[InlineData("#fff")] |
|||
[InlineData("2024-01-15")] |
|||
[InlineData("2024-01-15T10:30:00Z")] |
|||
[InlineData("https://squidex.io/path?query=1")] |
|||
[InlineData("data:image/png;base64,iVBORw0KGgo")] |
|||
[InlineData("dGhpc2lzYXZlcnlsb25nYmFzZTY0c3RyaW5ndGhhdHNob3VsZGJlZmlsdGVyZWRvdXRieXRoZWZpbHRlcg==")] |
|||
[InlineData(" ")] |
|||
public void Should_detect_noise(string text) |
|||
{ |
|||
Assert.True(NoiseTextNormalizer.IsNoise(text)); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData("Hello")] |
|||
[InlineData("my-great-article")] |
|||
[InlineData("Visit https://squidex.io for more")] |
|||
[InlineData("42 is the answer")] |
|||
[InlineData("mail@squidex.io")] |
|||
public void Should_not_detect_text_as_noise(string text) |
|||
{ |
|||
Assert.False(NoiseTextNormalizer.IsNoise(text)); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_skip_reference_ids() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddReferences(2, "references", Partitioning.Invariant); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("title", |
|||
new ContentFieldData() |
|||
.AddInvariant("Hello")) |
|||
.AddField("references", |
|||
new ContentFieldData() |
|||
.AddInvariant(JsonValue.Array(DomainId.NewGuid().ToString(), DomainId.NewGuid().ToString()))); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); |
|||
Assert.Null(actual!.Texts); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_use_first_field_as_title_if_nothing_configured() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddString(2, "description", Partitioning.Invariant); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("description", |
|||
new ContentFieldData() |
|||
.AddInvariant("World")) |
|||
.AddField("title", |
|||
new ContentFieldData() |
|||
.AddInvariant("Hello")); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); |
|||
Assert.Equal("World", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_use_fields_in_references_as_title() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "description", Partitioning.Invariant) |
|||
.AddString(2, "title", Partitioning.Invariant) |
|||
.SetFieldsInReferences(FieldNames.Create("data.title")) |
|||
.SetFieldsInLists(FieldNames.Create("data.description")); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("description", |
|||
new ContentFieldData() |
|||
.AddInvariant("World")) |
|||
.AddField("title", |
|||
new ContentFieldData() |
|||
.AddInvariant("Hello")); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); |
|||
Assert.Equal("World", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_use_fields_with_title_mode_as_title() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "description", Partitioning.Invariant) |
|||
.AddJson(2, "json", Partitioning.Invariant, |
|||
new JsonFieldProperties { SearchMode = FieldSearchMode.Title }) |
|||
.SetFieldsInReferences(FieldNames.Create("data.other")); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("description", |
|||
new ContentFieldData() |
|||
.AddInvariant("World")) |
|||
.AddField("json", |
|||
new ContentFieldData() |
|||
.AddInvariant(JsonValue.Object().Add("name", "Hello"))); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); |
|||
Assert.Equal("World", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_skip_excluded_fields() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddString(2, "internal", Partitioning.Invariant, |
|||
new StringFieldProperties { SearchMode = FieldSearchMode.Exclude }); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("title", |
|||
new ContentFieldData() |
|||
.AddInvariant("Hello")) |
|||
.AddField("internal", |
|||
new ContentFieldData() |
|||
.AddInvariant("Secret")); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); |
|||
Assert.Null(actual!.Texts); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_only_index_search_paths() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddJson(2, "json", Partitioning.Invariant, |
|||
new JsonFieldProperties { SearchPaths = ReadonlyList.Create("$.items[*].label", "author.name") }); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("json", |
|||
new ContentFieldData() |
|||
.AddInvariant( |
|||
JsonValue.Object() |
|||
.Add("items", |
|||
JsonValue.Array( |
|||
JsonValue.Object().Add("label", "Label1").Add("config", "Hidden1"), |
|||
JsonValue.Object().Add("label", "Label2").Add("config", "Hidden2"))) |
|||
.Add("author", JsonValue.Object().Add("name", "Sebastian")) |
|||
.Add("other", "Hidden3"))); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("Label1 Label2 Sebastian", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_apply_settings_of_nested_fields() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddArray(2, "array", Partitioning.Invariant, a => a |
|||
.AddString(21, "nested1") |
|||
.AddString(22, "nested2", |
|||
new StringFieldProperties { SearchMode = FieldSearchMode.Exclude })); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("array", |
|||
new ContentFieldData() |
|||
.AddInvariant( |
|||
JsonValue.Array( |
|||
JsonValue.Object().Add("nested1", "Hello").Add("nested2", "Hidden")))); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("Hello", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_apply_settings_of_component_fields() |
|||
{ |
|||
var componentSchema = |
|||
new Schema { Name = "my-component" } |
|||
.AddString(1, "visible", Partitioning.Invariant) |
|||
.AddString(2, "hidden", Partitioning.Invariant, |
|||
new StringFieldProperties { SearchMode = FieldSearchMode.Exclude }); |
|||
|
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddComponent(2, "component", Partitioning.Invariant); |
|||
|
|||
var components = new ResolvedComponents(new Dictionary<DomainId, Schema> |
|||
{ |
|||
[componentId] = componentSchema, |
|||
}); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("component", |
|||
new ContentFieldData() |
|||
.AddInvariant( |
|||
JsonValue.Object() |
|||
.Add(Component.Discriminator, componentId.ToString()) |
|||
.Add("visible", "Hello") |
|||
.Add("hidden", "Hidden"))); |
|||
|
|||
var actual = Extract(data, schema, components); |
|||
|
|||
Assert.Equal("Hello", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_convert_markdown_to_text() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddString(2, "markdown", Partitioning.Invariant, |
|||
new StringFieldProperties { Editor = StringFieldEditor.Markdown }); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("markdown", |
|||
new ContentFieldData() |
|||
.AddInvariant("# Hello **World**")); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("Hello World", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_use_custom_field_strategy_before_default_strategies() |
|||
{ |
|||
var customStrategy = A.Fake<ITextFieldStrategy>(); |
|||
|
|||
A.CallTo(() => customStrategy.Order) |
|||
.Returns(-1); |
|||
|
|||
A.CallTo(() => customStrategy.TryExtract(A<IField?>.That.Matches(x => x != null && x.Name == "custom"), A<JsonValue>._, A<ContentTextWalker>._)) |
|||
.Invokes(x => x.GetArgument<ContentTextWalker>(2)!.AppendText("Custom")) |
|||
.Returns(true); |
|||
|
|||
var customExtractor = new TextExtractor([new SchemaTextExtractionStrategy([customStrategy, new JsonTextStrategy()], [])]); |
|||
|
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddJson(2, "custom", Partitioning.Invariant, |
|||
new JsonFieldProperties { EditorUrl = "https://editor.io" }); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("custom", |
|||
new ContentFieldData() |
|||
.AddInvariant(JsonValue.Object().Add("raw", "Hidden"))); |
|||
|
|||
var actual = Extract(customExtractor, data, schema); |
|||
|
|||
Assert.Equal("Custom", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_apply_normalizers_in_order_and_exclude_dropped_texts() |
|||
{ |
|||
var normalizer1 = A.Fake<ITextNormalizer>(); |
|||
var normalizer2 = A.Fake<ITextNormalizer>(); |
|||
|
|||
A.CallTo(() => normalizer1.Order) |
|||
.Returns(2); |
|||
|
|||
A.CallTo(() => normalizer1.Normalize(A<string>._, A<IField?>._)) |
|||
.ReturnsLazily(x => x.GetArgument<string>(0) == "Drop!" ? null : x.GetArgument<string>(0)); |
|||
|
|||
A.CallTo(() => normalizer2.Order) |
|||
.Returns(1); |
|||
|
|||
A.CallTo(() => normalizer2.Normalize(A<string>._, A<IField?>._)) |
|||
.ReturnsLazily(x => $"{x.GetArgument<string>(0)}!"); |
|||
|
|||
var customExtractor = new TextExtractor([new SchemaTextExtractionStrategy([new JsonTextStrategy()], [normalizer1, normalizer2])]); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("field", |
|||
new ContentFieldData() |
|||
.AddInvariant(JsonValue.Array("Drop", "Keep"))); |
|||
|
|||
var actual = Extract(customExtractor, data); |
|||
|
|||
Assert.Equal("Keep!", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_not_convert_markdown_if_field_is_not_markdown() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddString(2, "input", Partitioning.Invariant); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("input", |
|||
new ContentFieldData() |
|||
.AddInvariant("C# **is** great")); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("C# **is** great", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_convert_html_to_text() |
|||
{ |
|||
var data = |
|||
new ContentData() |
|||
.AddField("html", |
|||
new ContentFieldData() |
|||
.AddInvariant("<p>Hello <strong>World</strong> & <script>alert(1)</script>more</p>")); |
|||
|
|||
var actual = Extract(data); |
|||
|
|||
Assert.Equal("Hello World & more", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_convert_rich_text_to_text() |
|||
{ |
|||
var schema = |
|||
new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddRichText(2, "richText", Partitioning.Invariant); |
|||
|
|||
var data = |
|||
new ContentData() |
|||
.AddField("richText", |
|||
new ContentFieldData() |
|||
.AddInvariant( |
|||
JsonValue.Object() |
|||
.Add("type", "doc") |
|||
.Add("content", |
|||
JsonValue.Array( |
|||
JsonValue.Object() |
|||
.Add("type", "paragraph") |
|||
.Add("content", |
|||
JsonValue.Array( |
|||
JsonValue.Object() |
|||
.Add("type", "text") |
|||
.Add("text", "Hello World"))))))); |
|||
|
|||
var actual = Extract(data, schema); |
|||
|
|||
Assert.Equal("Hello World", actual!.Texts![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_return_null_for_undefined_script_result() |
|||
{ |
|||
var actual = ScriptTextExtractionStrategy.ToTexts(JsonValue.Null); |
|||
|
|||
Assert.Null(actual); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_convert_string_script_result() |
|||
{ |
|||
var actual = ScriptTextExtractionStrategy.ToTexts(JsonValue.Create("Hello World")); |
|||
|
|||
Assert.Equal("Hello World", actual!.Texts![InvariantPartitioning.Key]); |
|||
Assert.Null(actual!.Titles); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_convert_object_script_result() |
|||
{ |
|||
var result = |
|||
JsonValue.Object() |
|||
.Add("title", "Hello") |
|||
.Add("body", |
|||
JsonValue.Object() |
|||
.Add("en", "World") |
|||
.Add("de", "Welt")); |
|||
|
|||
var actual = ScriptTextExtractionStrategy.ToTexts(result); |
|||
|
|||
Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); |
|||
Assert.Equal("World", actual!.Texts!["en"]); |
|||
Assert.Equal("Welt", actual!.Texts!["de"]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_use_script_before_schema() |
|||
{ |
|||
var script = A.Fake<IScript>(); |
|||
|
|||
A.CallTo(() => scriptEngine.CreateScript("script", A<ScriptOptions>._)) |
|||
.Returns(script); |
|||
|
|||
A.CallTo(() => script.Execute(A<ScriptVars>._)) |
|||
.Returns(JsonValue.Create("Scripted")); |
|||
|
|||
var actual = Extract(CreateData("Hello"), CreateScriptSchema()); |
|||
|
|||
Assert.Equal("Scripted", actual!.Texts![InvariantPartitioning.Key]); |
|||
Assert.Null(actual!.Titles); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_fallback_to_schema_if_script_returns_null() |
|||
{ |
|||
var script = A.Fake<IScript>(); |
|||
|
|||
A.CallTo(() => scriptEngine.CreateScript("script", A<ScriptOptions>._)) |
|||
.Returns(script); |
|||
|
|||
A.CallTo(() => script.Execute(A<ScriptVars>._)) |
|||
.Returns(JsonValue.Null); |
|||
|
|||
var actual = Extract(CreateData("Hello"), CreateScriptSchema()); |
|||
|
|||
Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_not_fallback_to_schema_if_script_returns_empty_object() |
|||
{ |
|||
var script = A.Fake<IScript>(); |
|||
|
|||
A.CallTo(() => scriptEngine.CreateScript("script", A<ScriptOptions>._)) |
|||
.Returns(script); |
|||
|
|||
A.CallTo(() => script.Execute(A<ScriptVars>._)) |
|||
.Returns(JsonValue.Object()); |
|||
|
|||
var actual = Extract(CreateData("Hello"), CreateScriptSchema()); |
|||
|
|||
Assert.Null(actual!.Texts); |
|||
Assert.Null(actual!.Titles); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_compile_script_only_once_per_context() |
|||
{ |
|||
var script = A.Fake<IScript>(); |
|||
|
|||
A.CallTo(() => scriptEngine.CreateScript("script", A<ScriptOptions>._)) |
|||
.Returns(script); |
|||
|
|||
A.CallTo(() => script.Execute(A<ScriptVars>._)) |
|||
.Returns(JsonValue.Create("Scripted")); |
|||
|
|||
using (var context = CreateContext(CreateScriptSchema())) |
|||
{ |
|||
sut.Extract(context, DomainId.NewGuid(), CreateData("Hello")); |
|||
sut.Extract(context, DomainId.NewGuid(), CreateData("World")); |
|||
} |
|||
|
|||
A.CallTo(() => scriptEngine.CreateScript("script", A<ScriptOptions>._)) |
|||
.MustHaveHappenedOnceExactly(); |
|||
A.CallTo(() => script.Execute(A<ScriptVars>._)) |
|||
.MustHaveHappenedTwiceExactly(); |
|||
A.CallTo(() => script.Dispose()) |
|||
.MustHaveHappenedOnceExactly(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_recompile_script_after_error() |
|||
{ |
|||
var script = A.Fake<IScript>(); |
|||
|
|||
A.CallTo(() => scriptEngine.CreateScript("script", A<ScriptOptions>._)) |
|||
.Returns(script); |
|||
|
|||
A.CallTo(() => script.Execute(A<ScriptVars>._)) |
|||
.Throws(new InvalidOperationException()); |
|||
|
|||
using var context = CreateContext(CreateScriptSchema()); |
|||
|
|||
var actual1 = sut.Extract(context, DomainId.NewGuid(), CreateData("Hello")); |
|||
var actual2 = sut.Extract(context, DomainId.NewGuid(), CreateData("World")); |
|||
|
|||
Assert.Equal("Hello", actual1!.Titles![InvariantPartitioning.Key]); |
|||
Assert.Equal("World", actual2!.Titles![InvariantPartitioning.Key]); |
|||
|
|||
A.CallTo(() => scriptEngine.CreateScript("script", A<ScriptOptions>._)) |
|||
.MustHaveHappenedTwiceExactly(); |
|||
A.CallTo(() => script.Dispose()) |
|||
.MustHaveHappenedTwiceExactly(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_fallback_to_schema_if_script_cannot_be_compiled() |
|||
{ |
|||
A.CallTo(() => scriptEngine.CreateScript("script", A<ScriptOptions>._)) |
|||
.Throws(new InvalidOperationException()); |
|||
|
|||
using var context = CreateContext(CreateScriptSchema()); |
|||
|
|||
var actual1 = sut.Extract(context, DomainId.NewGuid(), CreateData("Hello")); |
|||
var actual2 = sut.Extract(context, DomainId.NewGuid(), CreateData("World")); |
|||
|
|||
Assert.Equal("Hello", actual1!.Titles![InvariantPartitioning.Key]); |
|||
Assert.Equal("World", actual2!.Titles![InvariantPartitioning.Key]); |
|||
|
|||
A.CallTo(() => scriptEngine.CreateScript("script", A<ScriptOptions>._)) |
|||
.MustHaveHappenedOnceExactly(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_return_text_if_html_cannot_be_parsed() |
|||
{ |
|||
var actual = new HtmlTextNormalizer().Normalize("<!-]</p>", null); |
|||
|
|||
Assert.NotNull(actual); |
|||
} |
|||
|
|||
private static Schema CreateScriptSchema() |
|||
{ |
|||
return new Schema { Name = "my-schema" } |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.SetScripts(new SchemaScripts { Index = "script" }); |
|||
} |
|||
|
|||
private static ContentData CreateData(string title) |
|||
{ |
|||
return new ContentData() |
|||
.AddField("title", |
|||
new ContentFieldData() |
|||
.AddInvariant(title)); |
|||
} |
|||
|
|||
private ExtractedTexts? Extract(ContentData data, Schema? schema = null, ResolvedComponents? components = null) |
|||
{ |
|||
return Extract(sut, data, schema, components); |
|||
} |
|||
|
|||
private static ExtractedTexts? Extract(TextExtractor extractor, ContentData data, Schema? schema = null, ResolvedComponents? components = null) |
|||
{ |
|||
using var context = CreateContext(schema, components); |
|||
|
|||
return extractor.Extract(context, DomainId.NewGuid(), data); |
|||
} |
|||
|
|||
private static TextExtractionContext CreateContext(Schema? schema, ResolvedComponents? components = null) |
|||
{ |
|||
return new TextExtractionContext |
|||
{ |
|||
AppId = NamedId.Of(DomainId.NewGuid(), "my-app"), |
|||
Components = components ?? ResolvedComponents.Empty, |
|||
Schema = schema, |
|||
SchemaId = NamedId.Of(DomainId.NewGuid(), "my-schema"), |
|||
}; |
|||
} |
|||
} |
|||
@ -0,0 +1,171 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using System.Globalization; |
|||
using Microsoft.Extensions.Caching.Memory; |
|||
using Microsoft.Extensions.Options; |
|||
using Squidex.Domain.Apps.Core; |
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Domain.Apps.Core.Scripting; |
|||
using Squidex.Domain.Apps.Core.TestHelpers; |
|||
using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; |
|||
using Squidex.Domain.Apps.Entities.Contents.Text.State; |
|||
using Squidex.Domain.Apps.Entities.Jobs; |
|||
using Squidex.Domain.Apps.Entities.TestHelpers; |
|||
using Squidex.Domain.Apps.Events.Contents; |
|||
using Squidex.Events; |
|||
using Squidex.Infrastructure; |
|||
using Squidex.Infrastructure.EventSourcing; |
|||
using Squidex.Infrastructure.States; |
|||
using IClock = NodaTime.IClock; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text; |
|||
|
|||
public abstract class TextIndexTestBase : GivenContext |
|||
{ |
|||
private readonly List<(StoredEvent Stored, Envelope<IEvent> Parsed)> storedEvents = []; |
|||
private long lastVersion = -1; |
|||
|
|||
protected ITextIndex TextIndex { get; } = A.Fake<ITextIndex>(); |
|||
|
|||
protected IEventStore EventStore { get; } = A.Fake<IEventStore>(); |
|||
|
|||
protected IEventFormatter EventFormatter { get; } = A.Fake<IEventFormatter>(); |
|||
|
|||
protected InMemoryTextIndexerState TextIndexerState { get; } = new InMemoryTextIndexerState(); |
|||
|
|||
protected TextIndexRebuildCoordinator Coordinator { get; } = new TextIndexRebuildCoordinator(); |
|||
|
|||
protected List<IndexCommand> Commands { get; } = []; |
|||
|
|||
protected DomainId ContentId { get; } = DomainId.NewGuid(); |
|||
|
|||
protected TextIndexExtraction Extraction { get; } |
|||
|
|||
protected TextIndexTestBase() |
|||
{ |
|||
A.CallTo(() => TextIndex.ExecuteAsync(A<IndexCommand[]>._, A<CancellationToken>._)) |
|||
.Invokes(x => Commands.AddRange(x.GetArgument<IndexCommand[]>(0)!)); |
|||
|
|||
A.CallTo(() => EventStore.QueryAllAsync(A<StreamFilter>._, A<StreamPosition>._, A<int>._, A<CancellationToken>._)) |
|||
.ReturnsLazily(x => QueryEvents(x.GetArgument<StreamPosition>(1).Token)); |
|||
|
|||
A.CallTo(() => EventFormatter.ParseIfKnown(A<StoredEvent>._)) |
|||
.ReturnsLazily(x => storedEvents.Find(e => e.Stored == x.GetArgument<StoredEvent>(0)).Parsed); |
|||
|
|||
var scriptEngine = |
|||
new JintScriptEngine(new MemoryCache(Options.Create(new MemoryCacheOptions())), |
|||
Options.Create(new JintScriptOptions |
|||
{ |
|||
TimeoutScript = TimeSpan.FromSeconds(2), |
|||
TimeoutExecution = TimeSpan.FromSeconds(10), |
|||
})); |
|||
|
|||
Extraction = new TextIndexExtraction(AppProvider, TextExtractorTests.CreateExtractor(scriptEngine)); |
|||
} |
|||
|
|||
protected TextIndexingProcess CreateProcess() |
|||
{ |
|||
return new TextIndexingProcess(TestUtils.DefaultSerializer, TextIndex, TextIndexerState, Extraction, Coordinator); |
|||
} |
|||
|
|||
protected RebuildTextIndexJob CreateJob(TextIndexingProcess process) |
|||
{ |
|||
return new RebuildTextIndexJob(AppProvider, EventStore, EventFormatter, process, Coordinator); |
|||
} |
|||
|
|||
protected JobRunContext CreateRunContext() |
|||
{ |
|||
var state = new SimpleState<JobsState>(A.Fake<IPersistenceFactory<JobsState>>(), GetType(), App.Id); |
|||
|
|||
var jobRequest = RebuildTextIndexJob.BuildRequest(User, App); |
|||
|
|||
return new JobRunContext(state, A.Fake<IClock>(), default) |
|||
{ |
|||
Actor = User, |
|||
Job = new Job { Id = DomainId.NewGuid(), Arguments = jobRequest.Arguments }, |
|||
OwnerId = App.Id, |
|||
}; |
|||
} |
|||
|
|||
protected void StoreEvents(params Envelope<IEvent>[] events) |
|||
{ |
|||
foreach (var @event in events) |
|||
{ |
|||
var position = storedEvents.Count.ToString(CultureInfo.InvariantCulture); |
|||
|
|||
var stored = new StoredEvent("content", position, 0, new EventData("Type", [], "Payload")); |
|||
|
|||
storedEvents.Add((stored, @event)); |
|||
} |
|||
} |
|||
|
|||
protected async Task<TextContentState?> GetStateAsync() |
|||
{ |
|||
var states = await TextIndexerState.GetAsync([UniqueId()]); |
|||
|
|||
return states.GetValueOrDefault(UniqueId()); |
|||
} |
|||
|
|||
protected string? GetText() |
|||
{ |
|||
return Commands.OfType<UpsertIndexEntry>().Last().Texts?[InvariantPartitioning.Key]; |
|||
} |
|||
|
|||
protected string? GetTitle() |
|||
{ |
|||
return Commands.OfType<UpsertIndexEntry>().Last().Titles?[InvariantPartitioning.Key]; |
|||
} |
|||
|
|||
protected UniqueContentId UniqueId() |
|||
{ |
|||
return new UniqueContentId(AppId.Id, ContentId); |
|||
} |
|||
|
|||
protected static ContentData TextData(string field, string text) |
|||
{ |
|||
return new ContentData() |
|||
.AddField(field, |
|||
new ContentFieldData() |
|||
.AddInvariant(text)); |
|||
} |
|||
|
|||
protected Envelope<IEvent> Created(ContentData data, long? version = null, NamedId<DomainId>? appId = null) |
|||
{ |
|||
return CreateEnvelope(new ContentCreated { Data = data }, version, appId); |
|||
} |
|||
|
|||
protected Envelope<IEvent> Updated(ContentData data, long? version = null) |
|||
{ |
|||
return CreateEnvelope(new ContentUpdated { Data = data }, version); |
|||
} |
|||
|
|||
protected Envelope<IEvent> Published(long? version = null) |
|||
{ |
|||
return CreateEnvelope(new ContentStatusChanged { Status = Status.Published }, version); |
|||
} |
|||
|
|||
private IAsyncEnumerable<StoredEvent> QueryEvents(string? position) |
|||
{ |
|||
// The position is the index of the last event that has been read.
|
|||
var skip = position != null ? int.Parse(position, CultureInfo.InvariantCulture) + 1 : 0; |
|||
|
|||
return storedEvents.Skip(skip).Select(x => x.Stored).ToList().ToAsyncEnumerable(); |
|||
} |
|||
|
|||
private Envelope<IEvent> CreateEnvelope(ContentEvent @event, long? version, NamedId<DomainId>? appId = null) |
|||
{ |
|||
@event.AppId = appId ?? AppId; |
|||
@event.ContentId = ContentId; |
|||
@event.SchemaId = SchemaId; |
|||
|
|||
// The indexer ignores events with versions that have already been indexed, therefore we need increasing versions.
|
|||
lastVersion = Math.Max(lastVersion, version ?? lastVersion + 1); |
|||
|
|||
return Envelope.Create<IEvent>(@event).SetEventStreamNumber(version ?? lastVersion); |
|||
} |
|||
} |
|||
@ -0,0 +1,168 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
using Squidex.Domain.Apps.Core; |
|||
using Squidex.Domain.Apps.Core.Contents; |
|||
using Squidex.Domain.Apps.Core.Schemas; |
|||
using Squidex.Domain.Apps.Entities.Contents.Text.State; |
|||
using Squidex.Infrastructure; |
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text; |
|||
|
|||
public class TextIndexingProcessTests : TextIndexTestBase |
|||
{ |
|||
private readonly TextIndexingProcess sut; |
|||
|
|||
public TextIndexingProcessTests() |
|||
{ |
|||
sut = CreateProcess(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_use_schema_to_extract_texts() |
|||
{ |
|||
Schema = Schema |
|||
.AddString(1, "title", Partitioning.Invariant) |
|||
.AddString(2, "internal", Partitioning.Invariant, |
|||
new StringFieldProperties { SearchMode = FieldSearchMode.Exclude }); |
|||
|
|||
await sut.On([Created(TextData("title", "Hello").AddField("internal", new ContentFieldData().AddInvariant("Secret")))]); |
|||
|
|||
Assert.Equal("Hello", GetTitle()); |
|||
Assert.Null(GetText()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_use_index_script_to_extract_texts() |
|||
{ |
|||
Schema = Schema.SetScripts(new SchemaScripts |
|||
{ |
|||
Index = "complete({ title: ctx.data.title.iv, body: 'World' });", |
|||
}); |
|||
|
|||
await sut.On([Created(TextData("title", "Hello"))]); |
|||
|
|||
Assert.Equal("Hello", GetTitle()); |
|||
Assert.Equal("World", GetText()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_fallback_to_default_if_index_script_fails() |
|||
{ |
|||
Schema = Schema.SetScripts(new SchemaScripts |
|||
{ |
|||
Index = "throw 'Error';", |
|||
}); |
|||
|
|||
await sut.On([Created(TextData("field", "Hello"))]); |
|||
|
|||
Assert.Equal("Hello", GetText()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_store_version_of_last_event() |
|||
{ |
|||
await sut.On([Created(TextData("field", "Hello"), 0), Updated(TextData("field", "World"), 1)]); |
|||
|
|||
var state = await GetStateAsync(); |
|||
|
|||
Assert.Equal(1, state?.Version); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_skip_events_that_have_already_been_indexed_by_rebuild() |
|||
{ |
|||
await TextIndexerState.SetAsync([new TextContentState { UniqueContentId = UniqueId(), State = TextState.Stage0_Draft__Stage1_None, Version = 5 }]); |
|||
|
|||
await sut.On([Updated(TextData("field", "Old"), 4), Updated(TextData("field", "Current"), 5)]); |
|||
|
|||
Assert.Empty(Commands); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_handle_events_after_version_of_rebuild() |
|||
{ |
|||
await TextIndexerState.SetAsync([new TextContentState { UniqueContentId = UniqueId(), State = TextState.Stage0_Draft__Stage1_None, Version = 5 }]); |
|||
|
|||
await sut.On([Updated(TextData("field", "Old"), 5), Updated(TextData("field", "New"), 6)]); |
|||
|
|||
Assert.Equal("New", GetText()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_ignore_version_of_state_during_rebuild() |
|||
{ |
|||
await TextIndexerState.SetAsync([new TextContentState { UniqueContentId = UniqueId(), State = TextState.Stage0_Draft__Stage1_None, Version = 5 }]); |
|||
|
|||
await sut.ApplyAsync([Created(TextData("field", "Hello"), 0)], true, CancellationToken); |
|||
|
|||
var state = await GetStateAsync(); |
|||
|
|||
Assert.Equal("Hello", GetText()); |
|||
Assert.Equal(0, state?.Version); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_only_index_final_version_of_content_in_batch() |
|||
{ |
|||
await sut.On([Created(TextData("field", "Version1"), 0), Updated(TextData("field", "Version2"), 1)]); |
|||
|
|||
Assert.Equal("Version2", GetText()); |
|||
Assert.Single(Commands.OfType<UpsertIndexEntry>()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_skip_and_count_events_of_app_that_is_rebuilt() |
|||
{ |
|||
await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); |
|||
|
|||
await sut.On([Created(TextData("field", "Hello"), 0), Updated(TextData("field", "World"), 1)]); |
|||
|
|||
var skipped = await Coordinator.GetSkippedEventsAsync(AppId.Id, CancellationToken); |
|||
|
|||
Assert.Empty(Commands); |
|||
Assert.Equal(2, skipped); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_index_other_apps_while_app_is_rebuilt() |
|||
{ |
|||
await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); |
|||
|
|||
var otherApp = NamedId.Of(DomainId.NewGuid(), "other-app"); |
|||
|
|||
A.CallTo(() => AppProvider.GetSchemaAsync(otherApp.Id, A<DomainId>._, A<bool>._, A<CancellationToken>._)) |
|||
.Returns(Task.FromResult<Schema?>(null)); |
|||
|
|||
await sut.On([Created(TextData("field", "Skipped"), 0), Created(TextData("field", "Other"), 0, otherApp)]); |
|||
|
|||
Assert.Equal("Other", GetText()); |
|||
Assert.Single(Commands); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_index_app_again_after_hand_back() |
|||
{ |
|||
await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); |
|||
await Coordinator.TryHandBackAsync(AppId.Id, 0, CancellationToken); |
|||
|
|||
await sut.On([Created(TextData("field", "Hello"), 0)]); |
|||
|
|||
Assert.Equal("Hello", GetText()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_index_app_again_after_release() |
|||
{ |
|||
await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); |
|||
await Coordinator.ReleaseAsync(AppId.Id); |
|||
|
|||
await sut.On([Created(TextData("field", "Hello"), 0)]); |
|||
|
|||
Assert.Equal("Hello", GetText()); |
|||
} |
|||
} |
|||
@ -0,0 +1,71 @@ |
|||
// ==========================================================================
|
|||
// Squidex Headless CMS
|
|||
// ==========================================================================
|
|||
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|||
// All rights reserved. Licensed under the MIT license.
|
|||
// ==========================================================================
|
|||
|
|||
namespace Squidex.Domain.Apps.Entities.Contents.Text; |
|||
|
|||
public class WeightedTextsTests |
|||
{ |
|||
[Fact] |
|||
public void Should_return_texts_if_no_titles_defined() |
|||
{ |
|||
var texts = new Dictionary<string, string> { ["en"] = "World" }; |
|||
|
|||
var actual = new UpsertIndexEntry { Texts = texts }.GetWeightedTexts(); |
|||
|
|||
Assert.Same(texts, actual); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_return_null_if_nothing_defined() |
|||
{ |
|||
var actual = new UpsertIndexEntry().GetWeightedTexts(); |
|||
|
|||
Assert.Null(actual); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_repeat_titles_before_texts() |
|||
{ |
|||
var upsert = new UpsertIndexEntry |
|||
{ |
|||
Texts = new Dictionary<string, string> |
|||
{ |
|||
["en"] = "World", |
|||
["de"] = "Welt", |
|||
}, |
|||
Titles = new Dictionary<string, string> |
|||
{ |
|||
["en"] = "Hello", |
|||
["iv"] = "Title", |
|||
}, |
|||
}; |
|||
|
|||
var actual = upsert.GetWeightedTexts(); |
|||
|
|||
actual.Should().BeEquivalentTo( |
|||
new Dictionary<string, string> |
|||
{ |
|||
["en"] = "Hello Hello Hello World", |
|||
["de"] = "Welt", |
|||
["iv"] = "Title Title Title", |
|||
}); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_not_modify_texts_of_upsert() |
|||
{ |
|||
var upsert = new UpsertIndexEntry |
|||
{ |
|||
Texts = new Dictionary<string, string> { ["en"] = "World" }, |
|||
Titles = new Dictionary<string, string> { ["en"] = "Hello" }, |
|||
}; |
|||
|
|||
upsert.GetWeightedTexts(); |
|||
|
|||
Assert.Equal("World", upsert.Texts["en"]); |
|||
} |
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue