Browse Source

Feature/fulltext search (#1342)

* temp

* Test

* Test

* Test

* Temp

* Finalized

* Test

* Text improvements.

* Simplifications

* Fix test
pull/1345/head
Sebastian Stehle 2 months ago
committed by GitHub
parent
commit
7beda25d79
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 4
      CLAUDE.md
  2. 1
      backend/.editorconfig
  3. 2
      backend/extensions/Squidex.Extensions/Actions/CreateContent/CreateContentFlowStep.cs
  4. 5
      backend/extensions/Squidex.Extensions/Text/Azure/CommandFactory.cs
  5. 5
      backend/extensions/Squidex.Extensions/Text/ElasticSearch/CommandFactory.cs
  6. 12
      backend/i18n/frontend_de.json
  7. 12
      backend/i18n/frontend_en.json
  8. 12
      backend/i18n/frontend_fr.json
  9. 12
      backend/i18n/frontend_it.json
  10. 12
      backend/i18n/frontend_nl.json
  11. 12
      backend/i18n/frontend_pt.json
  12. 12
      backend/i18n/frontend_zh.json
  13. 12
      backend/i18n/source/frontend_en.json
  14. 2
      backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentEntity.cs
  15. 5
      backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs
  16. 1668
      backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.Designer.cs
  17. 28
      backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.cs
  18. 3
      backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/MySqlDbContextModelSnapshot.cs
  19. 1668
      backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.Designer.cs
  20. 28
      backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.cs
  21. 3
      backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/PostgresDbContextModelSnapshot.cs
  22. 1670
      backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.Designer.cs
  23. 28
      backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.cs
  24. 3
      backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/SqlServerDbContextModelSnapshot.cs
  25. 14
      backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj
  26. 4
      backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/CommandFactory.cs
  27. 4
      backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/MongoTextStateClassMap.cs
  28. 12
      backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj
  29. 4
      backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldProperties.cs
  30. 15
      backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldSearchMode.cs
  31. 2
      backend/src/Squidex.Domain.Apps.Core.Model/Schemas/SchemaScripts.cs
  32. 2
      backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj
  33. 4
      backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj
  34. 4
      backend/src/Squidex.Domain.Apps.Entities/AppProviderExtensions.cs
  35. 2
      backend/src/Squidex.Domain.Apps.Entities/Contents/Migration/MigrateContentsJob.cs
  36. 3
      backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs
  37. 4
      backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentQueryParser.cs
  38. 87
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extensions.cs
  39. 34
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ArrayFieldTextStrategy.cs
  40. 30
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ComponentTextStrategy.cs
  41. 147
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ContentTextWalker.cs
  42. 12
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ExtractedTexts.cs
  43. 54
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/HtmlTextNormalizer.cs
  44. 18
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextExtractionStrategy.cs
  45. 18
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextFieldStrategy.cs
  46. 17
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextNormalizer.cs
  47. 43
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/JsonTextStrategy.cs
  48. 39
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/MarkdownTextNormalizer.cs
  49. 104
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/NoiseTextNormalizer.cs
  50. 28
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/RichTextFieldTextStrategy.cs
  51. 28
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SchemaTextExtractionStrategy.cs
  52. 130
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ScriptTextExtractionStrategy.cs
  53. 73
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SearchPathsFieldTextStrategy.cs
  54. 68
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextCollector.cs
  55. 58
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractionContext.cs
  56. 31
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractor.cs
  57. 131
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/RebuildTextIndexJob.cs
  58. 31
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexBatch.cs
  59. 74
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexRebuildCoordinator.cs
  60. 2
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/State/TextContentState.cs
  61. 67
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexExtraction.cs
  62. 104
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexingProcess.cs
  63. 2
      backend/src/Squidex.Domain.Apps.Entities/Contents/Text/UpsertIndexEntry.cs
  64. 35
      backend/src/Squidex.Domain.Apps.Entities/Jobs/JobProcessor.cs
  65. 4
      backend/src/Squidex.Domain.Apps.Entities/LogMessages.cs
  66. 14
      backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj
  67. 3
      backend/src/Squidex.Shared/PermissionIds.cs
  68. 2
      backend/src/Squidex.Web/Resources.cs
  69. 2
      backend/src/Squidex/Areas/Api/Controllers/Contents/Generator/SchemasOpenApiGenerator.cs
  70. 24
      backend/src/Squidex/Areas/Api/Controllers/Jobs/JobsController.cs
  71. 6
      backend/src/Squidex/Areas/Api/Controllers/Jobs/Models/JobsDto.cs
  72. 10
      backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/FieldPropertiesDto.cs
  73. 5
      backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaScriptsDto.cs
  74. 3
      backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs
  75. 4
      backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemasController.cs
  76. 43
      backend/src/Squidex/Config/Domain/ContentsServices.cs
  77. 4
      backend/src/Squidex/Config/Messaging/MessagingServices.cs
  78. 24
      backend/src/Squidex/Squidex.csproj
  79. 4
      backend/tests/Squidex.Data.Tests/Shared/TextIndexerStateTests.cs
  80. 42
      backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Schemas/Schema.json
  81. 2
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentQueryParserTests.cs
  82. 141
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/RebuildTextIndexJobTests.cs
  83. 114
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/TextIndexRebuildCoordinatorTests.cs
  84. 94
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractionContextTests.cs
  85. 682
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractorTests.cs
  86. 171
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexTestBase.cs
  87. 18
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexerTests.cs
  88. 168
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexingProcessTests.cs
  89. 71
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/WeightedTextsTests.cs
  90. 39
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Jobs/JobProcessorTests.cs
  91. 12
      frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.html
  92. 3
      frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.ts
  93. 11
      frontend/src/app/features/settings/pages/jobs/jobs-page.component.html
  94. 7
      frontend/src/app/features/settings/pages/jobs/jobs-page.component.ts
  95. 4
      frontend/src/app/shared/model/custom.ts
  96. 38
      frontend/src/app/shared/model/generated.ts
  97. 9
      frontend/src/app/shared/services/jobs.service.ts
  98. 29
      frontend/src/app/shared/state/jobs.state.spec.ts
  99. 29
      frontend/src/app/shared/state/jobs.state.ts
  100. 13
      frontend/src/app/shared/state/schemas.forms.ts

4
CLAUDE.md

@ -60,6 +60,10 @@ dotnet test --filter "Category!=Dependencies & Category!=TestContainer"
- Do not comment a class or a method, only put comments inside functions or above variables.
- Do not comment properties in general (for example event properties). Only comment behavior inside classes.
- Exception: properties of API models (DTOs) keep their XML comments, because they are used for the OpenAPI documentation.
- Do not write conditions that span multiple lines. Split them into multiple `if` statements (e.g. early returns) instead.
- Try to keep files under 300 lines. Split larger classes by responsibility. This does not apply to tests.
- Do not put a blank line between a variable assignment and an `if` statement that checks this variable.
- Use primary constructors whenever possible.
## Maintaining this file

1
backend/.editorconfig

@ -10,6 +10,7 @@ indent_size = 4
[*.cs]
charset = utf-8-bom
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4

2
backend/extensions/Squidex.Extensions/Actions/CreateContent/CreateContentFlowStep.cs

@ -104,7 +104,7 @@ public sealed record CreateContentFlowStep : FlowStep, IConvertibleToAction
EnrichDefaults = true,
EnrichRequiredFields = false,
Patch = Patch,
Status = status
Status = status,
};
}
else

5
backend/extensions/Squidex.Extensions/Text/Azure/CommandFactory.cs

@ -92,7 +92,8 @@ public static class CommandFactory
}
}
if (upsert.Texts is { Count: > 0 })
var weightedTexts = upsert.GetWeightedTexts();
if (weightedTexts is { Count: > 0 })
{
var document = new SearchDocument
{
@ -106,7 +107,7 @@ public static class CommandFactory
["servePublished"] = upsert.ServePublished,
};
foreach (var (key, value) in upsert.Texts)
foreach (var (key, value) in weightedTexts)
{
var textMerged = value;
var textLanguage = AzureIndexDefinition.GetFieldName(key);

5
backend/extensions/Squidex.Extensions/Text/ElasticSearch/CommandFactory.cs

@ -103,11 +103,12 @@ public static class CommandFactory
}
}
if (upsert.Texts is { Count: > 0 })
var weightedTexts = upsert.GetWeightedTexts();
if (weightedTexts is { Count: > 0 })
{
var texts = new Dictionary<string, string>();
foreach (var (key, value) in upsert.Texts)
foreach (var (key, value) in weightedTexts)
{
var textMerged = value;
var textLanguage = ElasticSearchIndexDefinition.GetFieldName(key);

12
backend/i18n/frontend_de.json

@ -684,6 +684,11 @@
"jobs.restoreStoppedLabel": "Gestoppt",
"jobs.restoreTitle": "Backup wiederherstellen",
"jobs.started": "Job gestartet, es kann einige Minuten dauern.",
"jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.",
"jobs.textIndexConfirmTitle": "Rebuild Full Text Index",
"jobs.textIndexFailed": "Failed to start the rebuild of the full text index.",
"jobs.textIndexStart": "Rebuild Full Text Index",
"jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.",
"languages.add": "Sprache hinzufügen",
"languages.add.description": "Fügen Sie eine neue Sprache hinzu, die Sie für Ihre Inhalte unterstützen möchten.",
"languages.add.title": "Eine neue Sprache hinzufügen",
@ -949,6 +954,13 @@
"schemas.field.placeholderHint": "Definieren Sie den Platzhalter für das Eingabesteuerelement.",
"schemas.field.required": "Erforderlich",
"schemas.field.requiredOnPublish": "Beim Veröffentlichen erforderlich",
"schemas.field.searchMode": "Full Text Search",
"schemas.field.searchModeDefault": "Default",
"schemas.field.searchModeExclude": "Exclude",
"schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.",
"schemas.field.searchModeTitle": "Title",
"schemas.field.searchPaths": "Search Paths",
"schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.",
"schemas.field.show": "In API anzeigen",
"schemas.field.tabCommon": "Allgemein",
"schemas.field.tabEditing": "Bearbeitung",

12
backend/i18n/frontend_en.json

@ -684,6 +684,11 @@
"jobs.restoreStoppedLabel": "Stopped",
"jobs.restoreTitle": "Restore Backup",
"jobs.started": "Job started, it can take several minutes to complete.",
"jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.",
"jobs.textIndexConfirmTitle": "Rebuild Full Text Index",
"jobs.textIndexFailed": "Failed to start the rebuild of the full text index.",
"jobs.textIndexStart": "Rebuild Full Text Index",
"jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.",
"languages.add": "Add Language",
"languages.add.description": "Add a new language that you want to support for your content.",
"languages.add.title": "Add a new Language",
@ -949,6 +954,13 @@
"schemas.field.placeholderHint": "Define the placeholder for the input control.",
"schemas.field.required": "Required",
"schemas.field.requiredOnPublish": "Required when publishing",
"schemas.field.searchMode": "Full Text Search",
"schemas.field.searchModeDefault": "Default",
"schemas.field.searchModeExclude": "Exclude",
"schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.",
"schemas.field.searchModeTitle": "Title",
"schemas.field.searchPaths": "Search Paths",
"schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.",
"schemas.field.show": "Show in API",
"schemas.field.tabCommon": "Common",
"schemas.field.tabEditing": "Editing",

12
backend/i18n/frontend_fr.json

@ -684,6 +684,11 @@
"jobs.restoreStoppedLabel": "Stopped",
"jobs.restoreTitle": "Restore Backup",
"jobs.started": "Job started, it can take several minutes to complete.",
"jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.",
"jobs.textIndexConfirmTitle": "Rebuild Full Text Index",
"jobs.textIndexFailed": "Failed to start the rebuild of the full text index.",
"jobs.textIndexStart": "Rebuild Full Text Index",
"jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.",
"languages.add": "Ajouter une langue",
"languages.add.description": "Ajoutez une nouvelle langue que vous souhaitez prendre en charge pour votre contenu.",
"languages.add.title": "Ajouter une nouvelle langue",
@ -949,6 +954,13 @@
"schemas.field.placeholderHint": "Définissez l'espace réservé pour le contrôle d'entrée.",
"schemas.field.required": "Requis",
"schemas.field.requiredOnPublish": "Obligatoire lors de la publication",
"schemas.field.searchMode": "Full Text Search",
"schemas.field.searchModeDefault": "Default",
"schemas.field.searchModeExclude": "Exclude",
"schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.",
"schemas.field.searchModeTitle": "Title",
"schemas.field.searchPaths": "Search Paths",
"schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.",
"schemas.field.show": "Afficher dans l'API",
"schemas.field.tabCommon": "Commun",
"schemas.field.tabEditing": "Édition",

12
backend/i18n/frontend_it.json

@ -684,6 +684,11 @@
"jobs.restoreStoppedLabel": "Stopped",
"jobs.restoreTitle": "Restore Backup",
"jobs.started": "Job started, it can take several minutes to complete.",
"jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.",
"jobs.textIndexConfirmTitle": "Rebuild Full Text Index",
"jobs.textIndexFailed": "Failed to start the rebuild of the full text index.",
"jobs.textIndexStart": "Rebuild Full Text Index",
"jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.",
"languages.add": "Aggiungi lingua",
"languages.add.description": "Add a new language that you want to support for your content.",
"languages.add.title": "Add a new Language",
@ -949,6 +954,13 @@
"schemas.field.placeholderHint": "Definisci il segnaposto per la verifica dell'input.",
"schemas.field.required": "Obbligatorio",
"schemas.field.requiredOnPublish": "Obbligatorio quando pubblichi",
"schemas.field.searchMode": "Full Text Search",
"schemas.field.searchModeDefault": "Default",
"schemas.field.searchModeExclude": "Exclude",
"schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.",
"schemas.field.searchModeTitle": "Title",
"schemas.field.searchPaths": "Search Paths",
"schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.",
"schemas.field.show": "Mostra nelle API",
"schemas.field.tabCommon": "Comune",
"schemas.field.tabEditing": "Modifica",

12
backend/i18n/frontend_nl.json

@ -684,6 +684,11 @@
"jobs.restoreStoppedLabel": "Stopped",
"jobs.restoreTitle": "Restore Backup",
"jobs.started": "Job started, it can take several minutes to complete.",
"jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.",
"jobs.textIndexConfirmTitle": "Rebuild Full Text Index",
"jobs.textIndexFailed": "Failed to start the rebuild of the full text index.",
"jobs.textIndexStart": "Rebuild Full Text Index",
"jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.",
"languages.add": "Taal toevoegen",
"languages.add.description": "Voeg een nieuwe taal toe die u wilt ondersteunen voor uw inhoud.",
"languages.add.title": "Nieuwe taal toevoegen",
@ -949,6 +954,13 @@
"schemas.field.placeholderHint": "Definieer de tijdelijke aanduiding voor het invoerbesturingselement.",
"schemas.field.required": "Vereist",
"schemas.field.requiredOnPublish": "Verplicht bij het publiceren",
"schemas.field.searchMode": "Full Text Search",
"schemas.field.searchModeDefault": "Default",
"schemas.field.searchModeExclude": "Exclude",
"schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.",
"schemas.field.searchModeTitle": "Title",
"schemas.field.searchPaths": "Search Paths",
"schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.",
"schemas.field.show": "Weergeven in API",
"schemas.field.tabCommon": "Algemeen",
"schemas.field.tabEditing": "Bewerken",

12
backend/i18n/frontend_pt.json

@ -684,6 +684,11 @@
"jobs.restoreStoppedLabel": "Stopped",
"jobs.restoreTitle": "Restore Backup",
"jobs.started": "Job started, it can take several minutes to complete.",
"jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.",
"jobs.textIndexConfirmTitle": "Rebuild Full Text Index",
"jobs.textIndexFailed": "Failed to start the rebuild of the full text index.",
"jobs.textIndexStart": "Rebuild Full Text Index",
"jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.",
"languages.add": "Adicionar linguagem",
"languages.add.description": "Adicione um novo idioma que pretende apoiar para o seu conteúdo.",
"languages.add.title": "Adicione uma nova linguagem",
@ -949,6 +954,13 @@
"schemas.field.placeholderHint": "Defina o espaço reservado para o controlo de entrada.",
"schemas.field.required": "Necessário",
"schemas.field.requiredOnPublish": "Necessário na publicação",
"schemas.field.searchMode": "Full Text Search",
"schemas.field.searchModeDefault": "Default",
"schemas.field.searchModeExclude": "Exclude",
"schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.",
"schemas.field.searchModeTitle": "Title",
"schemas.field.searchPaths": "Search Paths",
"schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.",
"schemas.field.show": "Espetáculo em API",
"schemas.field.tabCommon": "Comum",
"schemas.field.tabEditing": "Edição",

12
backend/i18n/frontend_zh.json

@ -684,6 +684,11 @@
"jobs.restoreStoppedLabel": "Stopped",
"jobs.restoreTitle": "Restore Backup",
"jobs.started": "Job started, it can take several minutes to complete.",
"jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.",
"jobs.textIndexConfirmTitle": "Rebuild Full Text Index",
"jobs.textIndexFailed": "Failed to start the rebuild of the full text index.",
"jobs.textIndexStart": "Rebuild Full Text Index",
"jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.",
"languages.add": "添加语言",
"languages.add.description": "Add a new language that you want to support for your content.",
"languages.add.title": "Add a new Language",
@ -949,6 +954,13 @@
"schemas.field.placeholderHint": "定义输入控件的占位符。",
"schemas.field.required": "Required",
"schemas.field.requiredOnPublish": "发布时需要",
"schemas.field.searchMode": "Full Text Search",
"schemas.field.searchModeDefault": "Default",
"schemas.field.searchModeExclude": "Exclude",
"schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.",
"schemas.field.searchModeTitle": "Title",
"schemas.field.searchPaths": "Search Paths",
"schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.",
"schemas.field.show": "在 API 中显示",
"schemas.field.tabCommon": "通用",
"schemas.field.tabEditing": "Editing",

12
backend/i18n/source/frontend_en.json

@ -684,6 +684,11 @@
"jobs.restoreStoppedLabel": "Stopped",
"jobs.restoreTitle": "Restore Backup",
"jobs.started": "Job started, it can take several minutes to complete.",
"jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.",
"jobs.textIndexConfirmTitle": "Rebuild Full Text Index",
"jobs.textIndexFailed": "Failed to start the rebuild of the full text index.",
"jobs.textIndexStart": "Rebuild Full Text Index",
"jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.",
"languages.add": "Add Language",
"languages.add.description": "Add a new language that you want to support for your content.",
"languages.add.title": "Add a new Language",
@ -949,6 +954,13 @@
"schemas.field.placeholderHint": "Define the placeholder for the input control.",
"schemas.field.required": "Required",
"schemas.field.requiredOnPublish": "Required when publishing",
"schemas.field.searchMode": "Full Text Search",
"schemas.field.searchModeDefault": "Default",
"schemas.field.searchModeExclude": "Exclude",
"schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.",
"schemas.field.searchModeTitle": "Title",
"schemas.field.searchPaths": "Search Paths",
"schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.",
"schemas.field.show": "Show in API",
"schemas.field.tabCommon": "Common",
"schemas.field.tabEditing": "Editing",

2
backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentEntity.cs

@ -188,7 +188,7 @@ public record EFContentEntity : Content, IVersionedEntity<DomainId>
if (data.CanHaveReference())
{
var components = await appProvider.GetComponentsAsync(schema, ct);
var components = await appProvider.GetComponentsAsync(schema, ct: ct);
data.AddReferencedIds(schema, referencedIds, components);
}

5
backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs

@ -243,7 +243,8 @@ public sealed class EFTextIndex<TContext>(IDbContextFactory<TContext> dbContextF
switch (command)
{
case UpsertIndexEntry upsert:
if (upsert.Texts != null)
var weightedTexts = upsert.GetWeightedTexts();
if (weightedTexts != null)
{
insertsText.Add(new EFTextIndexTextEntity
{
@ -254,7 +255,7 @@ public sealed class EFTextIndex<TContext>(IDbContextFactory<TContext> dbContextF
ServeAll = upsert.ServeAll,
ServePublished = upsert.ServePublished,
Stage = upsert.Stage,
Texts = Tokenizer.Terms(upsert.Texts),
Texts = Tokenizer.Terms(weightedTexts),
});
}

1668
backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.Designer.cs

File diff suppressed because it is too large

28
backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.cs

@ -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");
}
}
}

3
backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/MySqlDbContextModelSnapshot.cs

@ -981,6 +981,9 @@ namespace Squidex.Providers.MySql.Migrations
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<long?>("Version")
.HasColumnType("bigint");
b.HasKey("UniqueContentId");
b.ToTable("TextState", (string)null);

1668
backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.Designer.cs

File diff suppressed because it is too large

28
backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.cs

@ -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");
}
}
}

3
backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/PostgresDbContextModelSnapshot.cs

@ -981,6 +981,9 @@ namespace Squidex.Providers.Postgres.Migrations
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<long?>("Version")
.HasColumnType("bigint");
b.HasKey("UniqueContentId");
b.ToTable("TextState", (string)null);

1670
backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.Designer.cs

File diff suppressed because it is too large

28
backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.cs

@ -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");
}
}
}

3
backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/SqlServerDbContextModelSnapshot.cs

@ -983,6 +983,9 @@ namespace Squidex.Providers.SqlServer.Migrations
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<long?>("Version")
.HasColumnType("bigint");
b.HasKey("UniqueContentId");
b.ToTable("TextState", (string)null);

14
backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj

@ -43,13 +43,13 @@
<PackageReference Include="Microting.EntityFrameworkCore.MySql.Json.Microsoft" Version="10.0.6" />
<PackageReference Include="Microting.EntityFrameworkCore.MySql.NetTopologySuite" Version="10.0.6" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.AI.EntityFramework" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.EntityFramework" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.4" />
<PackageReference Include="Squidex.Events.EntityFramework" Version="8.0.4" />
<PackageReference Include="Squidex.Flows.EntityFramework" Version="8.0.4" />
<PackageReference Include="Squidex.Hosting" Version="8.0.4" />
<PackageReference Include="Squidex.Messaging.EntityFramework" Version="8.0.4" />
<PackageReference Include="Squidex.AI.EntityFramework" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.EntityFramework" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.5" />
<PackageReference Include="Squidex.Events.EntityFramework" Version="8.0.5" />
<PackageReference Include="Squidex.Flows.EntityFramework" Version="8.0.5" />
<PackageReference Include="Squidex.Hosting" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.EntityFramework" Version="8.0.5" />
<PackageReference Include="Squidex.OpenIdDict.EntityFramework" Version="7.2.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.ValueTuple" Version="4.6.2" />

4
backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/CommandFactory.cs

@ -115,7 +115,9 @@ public sealed class CommandFactory<T>(Func<Dictionary<string, string>, T> textBu
private T? BuildTexts(UpsertIndexEntry upsert)
{
return upsert.Texts == null ? null : textBuilder(upsert.Texts);
var weightedTexts = upsert.GetWeightedTexts();
return weightedTexts == null ? null : textBuilder(weightedTexts);
}
private static void UpdateEntry(UpdateIndexEntry update, List<WriteModel<MongoTextIndexEntity<T>>> writes)

4
backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/MongoTextStateClassMap.cs

@ -20,6 +20,10 @@ internal static class MongoTextStateClassMap
cm.MapProperty(x => x.State)
.SetElementName("s");
cm.MapProperty(x => x.Version)
.SetElementName("v")
.SetIgnoreIfNull(true);
});
}
}

12
backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj

@ -25,12 +25,12 @@
<PackageReference Include="MongoDB.Driver.Core.Extensions.DiagnosticSources" Version="3.0.0" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.3.1" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.AI.Mongo" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.Mongo" Version="8.0.4" />
<PackageReference Include="Squidex.Events.Mongo" Version="8.0.4" />
<PackageReference Include="Squidex.Flows.Mongo" Version="8.0.4" />
<PackageReference Include="Squidex.Hosting" Version="8.0.4" />
<PackageReference Include="Squidex.Messaging.Mongo" Version="8.0.4" />
<PackageReference Include="Squidex.AI.Mongo" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.Mongo" Version="8.0.5" />
<PackageReference Include="Squidex.Events.Mongo" Version="8.0.5" />
<PackageReference Include="Squidex.Flows.Mongo" Version="8.0.5" />
<PackageReference Include="Squidex.Hosting" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.Mongo" Version="8.0.5" />
<PackageReference Include="Squidex.OpenIddict.MongoDb" Version="7.2.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.ValueTuple" Version="4.6.2" />

4
backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldProperties.cs

@ -25,6 +25,10 @@ public abstract record FieldProperties : NamedElementPropertiesBase
public ReadonlyList<string>? Tags { get; init; }
public FieldSearchMode SearchMode { get; init; }
public ReadonlyList<string>? SearchPaths { get; init; }
public abstract T Accept<T, TArgs>(IFieldPropertiesVisitor<T, TArgs> visitor, TArgs args);
public abstract T Accept<T, TArgs>(IFieldVisitor<T, TArgs> visitor, IField field, TArgs args);

15
backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldSearchMode.cs

@ -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,
}

2
backend/src/Squidex.Domain.Apps.Core.Model/Schemas/SchemaScripts.cs

@ -20,4 +20,6 @@ public sealed record SchemaScripts
public string? Query { get; init; }
public string? QueryPre { get; init; }
public string? Index { get; init; }
}

2
backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj

@ -20,7 +20,7 @@
<PackageReference Include="NetTopologySuite" Version="2.6.0" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.3.1" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.Flows" Version="8.0.4" />
<PackageReference Include="Squidex.Flows" Version="8.0.5" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup>

4
backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj

@ -29,8 +29,8 @@
<PackageReference Include="NJsonSchema" Version="11.6.1" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.3.1" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.AI" Version="8.0.4" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.4" />
<PackageReference Include="Squidex.AI" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.5" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.Linq.Async" Version="7.0.1" />
<PackageReference Include="ValueTaskSupplement" Version="1.1.0" />

4
backend/src/Squidex.Domain.Apps.Entities/AppProviderExtensions.cs

@ -13,7 +13,7 @@ namespace Squidex.Domain.Apps.Entities;
public static class AppProviderExtensions
{
public static async Task<ResolvedComponents> GetComponentsAsync(this IAppProvider appProvider, Schema schema,
public static async Task<ResolvedComponents> GetComponentsAsync(this IAppProvider appProvider, Schema schema, bool canCache = false,
CancellationToken ct = default)
{
Dictionary<DomainId, Schema>? result = null;
@ -36,7 +36,7 @@ public static class AppProviderExtensions
}
else if (result == null || !result.ContainsKey(schemaId))
{
var resolvedEntity = await appProvider.GetSchemaAsync(appId, schemaId, false, ct);
var resolvedEntity = await appProvider.GetSchemaAsync(appId, schemaId, canCache, ct);
if (resolvedEntity != null)
{

2
backend/src/Squidex.Domain.Apps.Entities/Contents/Migration/MigrateContentsJob.cs

@ -110,7 +110,7 @@ public sealed class MigrateContentsJob(
.WithNoCleanup()
.WithUnpublished(true));
var components = await appProvider.GetComponentsAsync(schema, ct);
var components = await appProvider.GetComponentsAsync(schema, ct: ct);
await MigrateAsync(
new MigrationContext

3
backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs

@ -69,7 +69,6 @@ public sealed class ContentEnricher(IEnumerable<IContentEnricherStep> steps, IAp
}
await RunStepsAsync(steps, results, context, ct);
activity?.SetTag("numItems", results.Count);
return results;
@ -103,7 +102,7 @@ public sealed class ContentEnricher(IEnumerable<IContentEnricherStep> steps, IAp
var schema = await appProvider.GetSchemaAsync(context.App.Id, x, false, ct)
?? throw new DomainObjectNotFoundException(x.ToString());
var components = await appProvider.GetComponentsAsync(schema, ct);
var components = await appProvider.GetComponentsAsync(schema, ct: ct);
return (schema, components);
});

4
backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentQueryParser.cs

@ -92,7 +92,7 @@ public class ContentQueryParser(
var textQuery = new TextQuery(query.FullText, options.MaxFullTextResults)
{
PreferredSchemaId = schema.Id,
RequiredSchemaIds = [schema.Id],
};
var fullTextIds = await textIndex.SearchAsync(context.App, textQuery, context.Scope(), ct);
@ -143,7 +143,7 @@ public class ContentQueryParser(
if (schema != null)
{
components = await appprovider.GetComponentsAsync(schema, ct);
components = await appprovider.GetComponentsAsync(schema, ct: ct);
}
var query = q.Query;

87
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extensions.cs

@ -10,8 +10,6 @@ using NetTopologySuite.Geometries;
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Json;
using Squidex.Infrastructure.Json.Objects;
using Squidex.Infrastructure.ObjectPool;
namespace Squidex.Domain.Apps.Entities.Contents.Text;
@ -65,84 +63,35 @@ public static class Extensions
return result;
}
public static Dictionary<string, string>? ToTexts(this ContentData data)
public static Dictionary<string, string>? GetWeightedTexts(this UpsertIndexEntry upsert, int titleWeight = 3)
{
Dictionary<string, string>? result = null;
if (data != null)
// Not all text indexes support field weights, therefore they can boost the titles by repeating them.
if (upsert.Titles is not { Count: > 0 } titles)
{
var languages = new Dictionary<string, StringBuilder>();
try
{
foreach (var (_, value) in data)
{
if (value != null)
{
foreach (var (key, jsonValue) in value)
{
AppendJsonText(languages, key, jsonValue);
}
}
}
foreach (var (key, sb) in languages)
{
if (sb.Length > 0)
{
result ??= [];
result[key] = sb.ToString();
}
}
}
finally
{
foreach (var (_, sb) in languages)
{
DefaultPools.StringBuilder.Return(sb);
}
}
return upsert.Texts;
}
return result;
}
var result = new Dictionary<string, string>(upsert.Texts ?? []);
private static void AppendJsonText(Dictionary<string, StringBuilder> languages, string language, JsonValue value)
{
switch (value.Value)
foreach (var (language, title) in titles)
{
case string s:
AppendText(languages, language, s);
break;
case JsonArray a:
foreach (var item in a)
{
AppendJsonText(languages, language, item);
}
var sb = new StringBuilder();
break;
case JsonObject o:
foreach (var (_, item) in o)
{
AppendJsonText(languages, language, item);
}
break;
}
}
private static void AppendText(Dictionary<string, StringBuilder> languages, string language, string text)
{
if (!string.IsNullOrWhiteSpace(text))
{
if (!languages.TryGetValue(language, out var sb))
for (var i = 0; i < titleWeight; i++)
{
sb = DefaultPools.StringBuilder.Get();
sb.AppendIfNotEmpty(' ');
sb.Append(title);
}
languages[language] = sb;
if (result.TryGetValue(language, out var text))
{
sb.Append(' ');
sb.Append(text);
}
sb.AppendIfNotEmpty(' ');
sb.Append(text);
result[language] = sb.ToString();
}
return result;
}
}

34
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ArrayFieldTextStrategy.cs

@ -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;
}
}

30
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ComponentTextStrategy.cs

@ -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;
}
}

147
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ContentTextWalker.cs

@ -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;
}
}

12
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ExtractedTexts.cs

@ -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);

54
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/HtmlTextNormalizer.cs

@ -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);
}
}

18
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextExtractionStrategy.cs

@ -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);
}

18
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextFieldStrategy.cs

@ -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);
}

17
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextNormalizer.cs

@ -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);
}

43
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/JsonTextStrategy.cs

@ -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;
}
}

39
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/MarkdownTextNormalizer.cs

@ -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;
}
}
}

104
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/NoiseTextNormalizer.cs

@ -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();
}

28
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/RichTextFieldTextStrategy.cs

@ -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;
}
}

28
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SchemaTextExtractionStrategy.cs

@ -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();
}
}

130
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ScriptTextExtractionStrategy.cs

@ -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;
}
}
}

73
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SearchPathsFieldTextStrategy.cs

@ -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);
}
}

68
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextCollector.cs

@ -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());
}
}

58
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractionContext.cs

@ -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();
}
}
}

31
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractor.cs

@ -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;
}
}

131
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/RebuildTextIndexJob.cs

@ -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);
}
}
}

31
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexBatch.cs

@ -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();
}
}

74
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexRebuildCoordinator.cs

@ -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);
}
}
}

2
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/State/TextContentState.cs

@ -12,4 +12,6 @@ public sealed class TextContentState
public UniqueContentId UniqueContentId { get; set; }
public TextState State { get; set; }
public long? Version { get; set; }
}

67
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexExtraction.cs

@ -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);
}
}

104
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexingProcess.cs

@ -6,6 +6,7 @@
// ==========================================================================
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild;
using Squidex.Domain.Apps.Entities.Contents.Text.State;
using Squidex.Domain.Apps.Events.Contents;
using Squidex.Events;
@ -17,7 +18,9 @@ namespace Squidex.Domain.Apps.Entities.Contents.Text;
public sealed class TextIndexingProcess(
IJsonSerializer serializer,
ITextIndex textIndex,
ITextIndexerState textIndexerState)
ITextIndexerState textIndexerState,
TextIndexExtraction extraction,
TextIndexRebuildCoordinator coordinator)
: IEventConsumer
{
public int BatchSize => 1000;
@ -33,13 +36,35 @@ public sealed class TextIndexingProcess(
get => textIndex;
}
private sealed class Updates(Dictionary<UniqueContentId, TextContentState> states, IJsonSerializer serializer)
private sealed class Updates(
Dictionary<UniqueContentId, TextContentState> states,
IJsonSerializer serializer,
bool isRebuild)
{
private readonly Dictionary<UniqueContentId, TextContentState> currentUpdates = [];
private readonly Dictionary<(UniqueContentId, byte), IndexCommand> commands = [];
private readonly Dictionary<UpsertIndexEntry, (ContentEvent Event, ContentData Data)> sources = [];
public async Task WriteAsync(ITextIndex textIndex, ITextIndexerState textIndexerState)
public async Task WriteAsync(ITextIndex textIndex, ITextIndexerState textIndexerState, TextIndexExtraction extraction,
CancellationToken ct)
{
// Only calculate the values for the final versions, the other versions have been replaced within the batch.
var upserts = commands.Values.OfType<UpsertIndexEntry>().ToList();
if (upserts.Count > 0)
{
var texts = await extraction.ExtractAsync(upserts.Select(x => sources[x]), ct);
foreach (var upsert in upserts)
{
var data = sources[upsert].Data;
var text = texts.GetValueOrDefault(data);
upsert.GeoObjects = data.ToGeo(serializer);
upsert.Texts = text?.Texts;
upsert.Titles = text?.Titles;
}
}
if (commands.Count > 0)
{
await textIndex.ExecuteAsync(commands.Values.ToArray());
@ -53,6 +78,21 @@ public sealed class TextIndexingProcess(
public void On(Envelope<IEvent> @event)
{
if (@event.Payload is not ContentEvent contentEvent)
{
return;
}
var uniqueId = new UniqueContentId(contentEvent.AppId.Id, contentEvent.ContentId);
var version = @event.Headers.EventStreamNumber();
// A rebuild has already indexed the content up to this version. The rebuild itself replays everything from the start.
if (!isRebuild && states.TryGetValue(uniqueId, out var existing) && existing.Version >= version)
{
return;
}
switch (@event.Payload)
{
case ContentCreated created:
@ -88,6 +128,13 @@ public sealed class TextIndexingProcess(
break;
}
if (states.TryGetValue(uniqueId, out var state))
{
state.Version = version;
currentUpdates[uniqueId] = state;
}
}
private void Create(ContentEvent @event, ContentData data)
@ -103,14 +150,19 @@ public sealed class TextIndexingProcess(
new UpsertIndexEntry
{
UniqueContentId = uniqueId,
GeoObjects = data.ToGeo(serializer),
IsNew = true,
IsNew = !isRebuild,
Stage = 0,
ServeAll = true,
ServePublished = false,
Texts = data.ToTexts(),
UserInfos = data.ToUserInfos(),
});
},
data);
// The entries of a rebuild already exist, therefore we also delete the old draft.
if (isRebuild)
{
CoreDelete(@event, uniqueId, 1);
}
states[state.UniqueContentId] = state;
currentUpdates[state.UniqueContentId] = state;
@ -328,12 +380,11 @@ public sealed class TextIndexingProcess(
new UpsertIndexEntry
{
UniqueContentId = uniqueId,
GeoObjects = data.ToGeo(serializer),
Stage = stage,
ServeAll = all,
ServePublished = published,
Texts = data.ToTexts(),
});
},
data);
}
private void CoreUpdate(ContentEvent @event, UniqueContentId uniqueId, byte stage, bool all, bool published)
@ -358,12 +409,17 @@ public sealed class TextIndexingProcess(
});
}
private void Index(ContentEvent @event, IndexCommand command)
private void Index(ContentEvent @event, IndexCommand command, ContentData? data = null)
{
command.SchemaId = @event.SchemaId;
var key = (command.UniqueContentId, command.Stage);
if (command is UpsertIndexEntry newUpsert && data != null)
{
sources[newUpsert] = (@event, data);
}
if (command is UpdateIndexEntry update &&
commands.TryGetValue(key, out var existing) &&
existing is UpsertIndexEntry upsert)
@ -385,16 +441,38 @@ public sealed class TextIndexingProcess(
}
public async Task On(IEnumerable<Envelope<IEvent>> events)
{
// The rebuild job cannot hand back the app while the batch is handled.
using var batch = await coordinator.BeginBatchAsync();
var indexEvents = new List<Envelope<IEvent>>();
foreach (var @event in events)
{
// The events of apps that are rebuilt are replayed by the rebuild job.
if (@event.Payload is ContentEvent contentEvent && batch.TrySkip(contentEvent.AppId.Id))
{
continue;
}
indexEvents.Add(@event);
}
await ApplyAsync(indexEvents, false);
}
public async Task ApplyAsync(List<Envelope<IEvent>> events, bool isRebuild,
CancellationToken ct = default)
{
var textStates = await QueryStatesAsync(events);
var textBatch = new Updates(textStates, serializer);
var textBatch = new Updates(textStates, serializer, isRebuild);
foreach (var @event in events)
{
textBatch.On(@event);
}
await textBatch.WriteAsync(textIndex, textIndexerState);
await textBatch.WriteAsync(textIndex, textIndexerState, extraction, ct);
}
private Task<Dictionary<UniqueContentId, TextContentState>> QueryStatesAsync(IEnumerable<Envelope<IEvent>> events)

2
backend/src/Squidex.Domain.Apps.Entities/Contents/Text/UpsertIndexEntry.cs

@ -16,6 +16,8 @@ public sealed class UpsertIndexEntry : IndexCommand
public Dictionary<string, string>? Texts { get; set; }
public Dictionary<string, string>? Titles { get; set; }
public List<UserInfoValue>? UserInfos { get; set; }
public bool ServeAll { get; set; }

35
backend/src/Squidex.Domain.Apps.Entities/Jobs/JobProcessor.cs

@ -54,27 +54,32 @@ public sealed class JobProcessor
{
await state.LoadAsync(ct);
var pending = state.Value.Jobs.Where(x => x.Stopped == null);
if (pending.Any())
var pending = state.Value.Jobs.Where(x => x.Stopped == null).ToList();
if (pending.Count == 0)
{
// This should actually never happen, so we log with warning.
LogMessages.LogRemovedUnfinishedJobs(log, ownerId);
return;
}
foreach (var job in pending.ToList())
{
var runner = runners.FirstOrDefault(x => x.Name == job.TaskName);
// This happens when the server has been stopped while the job was running, so we log with warning.
LogMessages.LogInterruptedJobs(log, ownerId);
if (runner != null)
{
await runner.CleanupAsync(job);
}
var now = Clock.GetCurrentInstant();
state.Value.Jobs.Remove(job);
}
foreach (var job in pending)
{
// Keep the job, so that the user can see that it has been interrupted and start it again.
job.Status = JobStatus.Failed;
job.Stopped = now;
job.Log.Add(new JobLogMessage(now, "The job has been interrupted, because the server has been stopped."));
await state.WriteAsync(ct);
var runner = runners.FirstOrDefault(x => x.Name == job.TaskName);
if (runner != null)
{
await runner.CleanupAsync(job);
}
}
await state.WriteAsync(ct);
}
public Task DeleteAsync(DomainId jobId)

4
backend/src/Squidex.Domain.Apps.Entities/LogMessages.cs

@ -69,8 +69,8 @@ internal static partial class LogMessages
[LoggerMessage(Level = LogLevel.Warning, Message = "Failed to invite user: Assignee {assigneeId} not found.")]
public static partial void LogInvitationAssigneeNotFound(ILogger logger, string assigneeId);
[LoggerMessage(Level = LogLevel.Warning, Message = "Removed unfinished jobs for owner {ownerId} after start.")]
public static partial void LogRemovedUnfinishedJobs(ILogger logger, DomainId ownerId);
[LoggerMessage(Level = LogLevel.Warning, Message = "Marked interrupted jobs for owner {ownerId} as failed after start.")]
public static partial void LogInterruptedJobs(ILogger logger, DomainId ownerId);
[LoggerMessage(Level = LogLevel.Information, Message = "Clearing jobs for owner {ownerId}.")]
public static partial void LogClearingJobs(ILogger logger, DomainId ownerId);

14
backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj

@ -24,13 +24,13 @@
<PackageReference Include="NodaTime" Version="3.3.1" />
<PackageReference Include="OpenTelemetry.Api" Version="1.15.3" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.Assets" Version="8.0.4" />
<PackageReference Include="Squidex.Caching" Version="8.0.4" />
<PackageReference Include="Squidex.Events" Version="8.0.4" />
<PackageReference Include="Squidex.Hosting.Abstractions" Version="8.0.4" />
<PackageReference Include="Squidex.Log" Version="8.0.4" />
<PackageReference Include="Squidex.Messaging" Version="8.0.4" />
<PackageReference Include="Squidex.Text" Version="8.0.4" />
<PackageReference Include="Squidex.Assets" Version="8.0.5" />
<PackageReference Include="Squidex.Caching" Version="8.0.5" />
<PackageReference Include="Squidex.Events" Version="8.0.5" />
<PackageReference Include="Squidex.Hosting.Abstractions" Version="8.0.5" />
<PackageReference Include="Squidex.Log" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging" Version="8.0.5" />
<PackageReference Include="Squidex.Text" Version="8.0.5" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageReference Include="System.Linq.Async" Version="7.0.1" />

3
backend/src/Squidex.Shared/PermissionIds.cs

@ -25,6 +25,9 @@ public static class PermissionIds
// Backup Admin
public const string AdminRestore = "squidex.admin.restore";
// Text Index Admin
public const string AdminTextIndex = "squidex.admin.text-index";
// Event Admin
public const string AdminEvents = "squidex.admin.events";
public const string AdminEventsRead = "squidex.admin.events.read";

2
backend/src/Squidex.Web/Resources.cs

@ -149,6 +149,8 @@ public sealed class Resources(ApiController controller)
// Backups
public bool CanRestoreBackup => Can(PermissionIds.AdminRestore);
public bool CanRebuildTextIndex => Can(PermissionIds.AdminTextIndex);
public bool CanCreateBackup => Can(PermissionIds.AppJobs);
// Jobs

2
backend/src/Squidex/Areas/Api/Controllers/Contents/Generator/SchemasOpenApiGenerator.cs

@ -49,7 +49,7 @@ public sealed class SchemasOpenApiGenerator(
{
if (schema.IsPublished && schema.Type != SchemaDefType.Component && schema.Fields.Count > 0)
{
var components = await appProvider.GetComponentsAsync(schema, httpContext.RequestAborted);
var components = await appProvider.GetComponentsAsync(schema, ct: httpContext.RequestAborted);
GenerateSchemaOperations(builder.Schema(schema, partitionResolver, components, flat));
}

24
backend/src/Squidex/Areas/Api/Controllers/Jobs/JobsController.cs

@ -7,9 +7,11 @@
using Microsoft.AspNetCore.Mvc;
using Squidex.Areas.Api.Controllers.Jobs.Models;
using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild;
using Squidex.Domain.Apps.Entities.Jobs;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.Security;
using Squidex.Shared;
using Squidex.Web;
@ -41,6 +43,28 @@ public class JobsController(ICommandBus commandBus, IJobService jobService) : Ap
return Ok(result);
}
/// <summary>
/// Rebuild the full text index.
/// </summary>
/// <param name="app">The name of the app.</param>
/// <param name="reference">An optional reference to find the job.</param>
/// <response code="204">Rebuild started.</response>
/// <response code="400">Another job is already running.</response>
/// <response code="404">App not found.</response>
[HttpPost]
[Route("apps/{app}/jobs/text-index/")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ApiPermission(PermissionIds.AdminTextIndex)]
[ApiCosts(0)]
public async Task<IActionResult> PostTextIndexRebuild(string app, [FromQuery] string? reference = null)
{
var job = RebuildTextIndexJob.BuildRequest(User.Token()!, App) with { Reference = reference };
await jobService.StartAsync(App.Id, job, HttpContext.RequestAborted);
return NoContent();
}
/// <summary>
/// Delete a job.
/// </summary>

6
backend/src/Squidex/Areas/Api/Controllers/Jobs/Models/JobsDto.cs

@ -40,6 +40,12 @@ public sealed class JobsDto : Resource
resources.Url<BackupsController>(x => nameof(x.PostBackup), values));
}
if (resources.CanRebuildTextIndex)
{
AddPostLink("create/text-index",
resources.Url<JobsController>(x => nameof(x.PostTextIndexRebuild), values));
}
return this;
}
}

10
backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/FieldPropertiesDto.cs

@ -63,5 +63,15 @@ public abstract class FieldPropertiesDto
/// </summary>
public ReadonlyList<string>? Tags { get; set; }
/// <summary>
/// Defines how the field is used for the full text search.
/// </summary>
public FieldSearchMode SearchMode { get; set; }
/// <summary>
/// Optional paths to the values that are indexed for the full text search, e.g. 'items.label'.
/// </summary>
public ReadonlyList<string>? SearchPaths { get; set; }
public abstract FieldProperties ToProperties();
}

5
backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaScriptsDto.cs

@ -43,6 +43,11 @@ public sealed class SchemaScriptsDto
/// </summary>
public string? Change { get; set; }
/// <summary>
/// The script that is executed when a content is indexed for the full text search.
/// </summary>
public string? Index { get; set; }
public ConfigureScripts ToCommand()
{
var scripts = SimpleMapper.Map(this, new SchemaScripts());

3
backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs

@ -86,8 +86,7 @@ public class SchemaContentsController(ICommandBus commandBus, IJobService jobSer
request.Format ?? ExportFormat.Csv,
request.Fields,
request.Unpublished ?? false)
with
{ Reference = reference, };
with { Reference = reference };
await jobService.StartAsync(App.Id, job, HttpContext.RequestAborted);

4
backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemasController.cs

@ -392,7 +392,7 @@ public sealed class SchemasController(
[ApiExplorerSettings(IgnoreApi = true)]
public async Task<IActionResult> GetFilters(string app, string schema)
{
var components = await appProvider.GetComponentsAsync(Schema, HttpContext.RequestAborted);
var components = await appProvider.GetComponentsAsync(Schema, ct: HttpContext.RequestAborted);
var result = ContentQueryModel.Build(Schema, App.PartitionResolver(), components).Flatten();
var response = await QueryModelDto.FromModelAsync(result, App, Schema, workflows);
@ -402,7 +402,7 @@ public sealed class SchemasController(
private async Task<FilterSchema> BuildModel()
{
var components = await appProvider.GetComponentsAsync(Schema, HttpContext.RequestAborted);
var components = await appProvider.GetComponentsAsync(Schema, ct: HttpContext.RequestAborted);
return Schema.BuildDataSchema(App.PartitionResolver(), components);
}

43
backend/src/Squidex/Config/Domain/ContentsServices.cs

@ -14,6 +14,8 @@ using Squidex.Domain.Apps.Entities.Contents.Counter;
using Squidex.Domain.Apps.Entities.Contents.Queries;
using Squidex.Domain.Apps.Entities.Contents.Queries.Steps;
using Squidex.Domain.Apps.Entities.Contents.Text;
using Squidex.Domain.Apps.Entities.Contents.Text.Extraction;
using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild;
using Squidex.Domain.Apps.Entities.Contents.Validation;
using Squidex.Domain.Apps.Entities.History;
using Squidex.Domain.Apps.Entities.Search;
@ -112,7 +114,46 @@ public static class ContentsServices
.AsOptional<IWorkflowsValidator>();
services.AddSingletonAs<TextIndexingProcess>()
.As<IEventConsumer>();
.AsSelf().As<IEventConsumer>();
services.AddSingletonAs<TextIndexExtraction>()
.AsSelf();
services.AddSingletonAs<TextIndexRebuildCoordinator>()
.AsSelf();
services.AddSingletonAs<TextExtractor>()
.AsSelf();
services.AddSingletonAs<ScriptTextExtractionStrategy>()
.As<ITextExtractionStrategy>();
services.AddSingletonAs<SchemaTextExtractionStrategy>()
.As<ITextExtractionStrategy>();
services.AddSingletonAs<SearchPathsFieldTextStrategy>()
.As<ITextFieldStrategy>();
services.AddSingletonAs<RichTextFieldTextStrategy>()
.As<ITextFieldStrategy>();
services.AddSingletonAs<ArrayFieldTextStrategy>()
.As<ITextFieldStrategy>();
services.AddSingletonAs<ComponentTextStrategy>()
.As<ITextFieldStrategy>();
services.AddSingletonAs<JsonTextStrategy>()
.As<ITextFieldStrategy>();
services.AddSingletonAs<MarkdownTextNormalizer>()
.As<ITextNormalizer>();
services.AddSingletonAs<HtmlTextNormalizer>()
.As<ITextNormalizer>();
services.AddSingletonAs<NoiseTextNormalizer>()
.As<ITextNormalizer>();
services.AddSingletonAs<ContentsSearchSource>()
.As<ISearchSource>();

4
backend/src/Squidex/Config/Messaging/MessagingServices.cs

@ -16,6 +16,7 @@ using Squidex.Domain.Apps.Entities.Contents;
using Squidex.Domain.Apps.Entities.Contents.Export;
using Squidex.Domain.Apps.Entities.Contents.Indexes;
using Squidex.Domain.Apps.Entities.Contents.Migration;
using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild;
using Squidex.Domain.Apps.Entities.Jobs;
using Squidex.Domain.Apps.Entities.Rules.Runner;
using Squidex.Domain.Apps.Entities.Rules.UsageTracking;
@ -104,6 +105,9 @@ public static class MessagingServices
services.AddSingletonAs<ExportContentsJob>()
.As<IJobRunner>();
services.AddSingletonAs<RebuildTextIndexJob>()
.As<IJobRunner>();
services.AddSingleton<IMessagingSerializer>(c =>
new SystemTextJsonMessagingSerializer(c.GetRequiredService<JsonSerializerOptions>()));

24
backend/src/Squidex/Squidex.csproj

@ -58,16 +58,16 @@
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.15.1" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="ReportGenerator" Version="5.5.6" PrivateAssets="all" />
<PackageReference Include="Squidex.Assets.Azure" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.GoogleCloud" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.FTP" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.ImageSharp" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.S3" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.4" />
<PackageReference Include="Squidex.ClientLibrary" Version="22.2.0" />
<PackageReference Include="Squidex.Hosting" Version="8.0.4" />
<PackageReference Include="Squidex.Messaging.All" Version="8.0.4" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.Azure" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.GoogleCloud" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.FTP" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.ImageSharp" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.S3" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.5" />
<PackageReference Include="Squidex.ClientLibrary" Version="22.6.0" />
<PackageReference Include="Squidex.Hosting" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.All" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.5" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="YDotNet" Version="0.6.0" />
<PackageReference Include="YDotNet.Native" Version="0.6.0" />
@ -81,12 +81,12 @@
</ItemGroup>
<ItemGroup Condition="'$(IncludeMagick)' == 'true'">
<PackageReference Include="Squidex.Assets.ImageMagick" Version="8.0.4" />
<PackageReference Include="Squidex.Assets.ImageMagick" Version="8.0.5" />
<PackageReference Include="Magick.NET-Q8-AnyCPU" Version="14.16.0" />
</ItemGroup>
<ItemGroup Condition="'$(IncludeKafka)' == 'true'">
<PackageReference Include="Squidex.Messaging.Kafka" Version="8.0.4" />
<PackageReference Include="Squidex.Messaging.Kafka" Version="8.0.5" />
</ItemGroup>
<PropertyGroup>

4
backend/tests/Squidex.Data.Tests/Shared/TextIndexerStateTests.cs

@ -36,7 +36,7 @@ public abstract class TextIndexerStateTests : GivenContext
await sut.SetAsync(
[
new TextContentState { UniqueContentId = id1, State = TextState.Stage0_Draft__Stage1_None },
new TextContentState { UniqueContentId = id1, State = TextState.Stage0_Draft__Stage1_None, Version = 3 },
new TextContentState { UniqueContentId = id2, State = TextState.Stage0_Published__Stage1_Draft },
new TextContentState { UniqueContentId = id3, State = TextState.Stage0_Published__Stage1_None },
]);
@ -45,7 +45,7 @@ public abstract class TextIndexerStateTests : GivenContext
actual.Should().BeEquivalentTo(new Dictionary<UniqueContentId, TextContentState>
{
[id1] = new TextContentState { UniqueContentId = id1, State = TextState.Stage0_Draft__Stage1_None },
[id1] = new TextContentState { UniqueContentId = id1, State = TextState.Stage0_Draft__Stage1_None, Version = 3 },
[id2] = new TextContentState { UniqueContentId = id2, State = TextState.Stage0_Published__Stage1_Draft },
});
}

42
backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Schemas/Schema.json

@ -29,7 +29,8 @@
"isRequired": true,
"isRequiredOnPublish": true,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -54,7 +55,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -75,7 +77,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -94,7 +97,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -114,7 +118,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -132,7 +137,8 @@
"isRequired": true,
"isRequiredOnPublish": true,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -148,7 +154,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": true,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -163,7 +170,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -186,7 +194,8 @@
"1",
"2",
"3"
]
],
"searchMode": "Default"
}
},
{
@ -209,7 +218,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -239,7 +249,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
},
{
@ -255,7 +266,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
},
"children": [
{
@ -275,7 +287,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": false
"isCreateOnly": false,
"searchMode": "Default"
}
}
]
@ -293,7 +306,8 @@
"isRequired": false,
"isRequiredOnPublish": false,
"isHalfWidth": false,
"isCreateOnly": true
"isCreateOnly": true,
"searchMode": "Default"
}
}
],

2
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentQueryParserTests.cs

@ -114,7 +114,7 @@ public class ContentQueryParserTests : GivenContext
[Fact]
public async Task Should_convert_full_text_query_to_filter_with_other_filter()
{
A.CallTo(() => textIndex.SearchAsync(ApiContext.App, A<TextQuery>.That.Matches(x => x.Text == "Hello"), ApiContext.Scope(), CancellationToken))
A.CallTo(() => textIndex.SearchAsync(ApiContext.App, A<TextQuery>.That.Matches(x => x.Text == "Hello" && x.RequiredSchemaIds!.SequenceEqual(new[] { SchemaId.Id })), ApiContext.Scope(), CancellationToken))
.Returns([DomainId.Create("1"), DomainId.Create("2")]);
var query = Q.Empty.WithODataQuery("$search=Hello&$filter=data/firstName/iv eq 'ABC'");

141
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/RebuildTextIndexJobTests.cs

@ -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());
}
}

114
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/TextIndexRebuildCoordinatorTests.cs

@ -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);
}
}

94
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractionContextTests.cs

@ -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;
}
}

682
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractorTests.cs

@ -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> &amp; <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"),
};
}
}

171
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexTestBase.cs

@ -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);
}
}

18
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexerTests.cs

@ -5,9 +5,13 @@
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Microsoft.Extensions.Logging;
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;
@ -21,6 +25,7 @@ namespace Squidex.Domain.Apps.Entities.Contents.Text;
public abstract class TextIndexerTests : GivenContext
{
private readonly Dictionary<DomainId, long> versions = [];
private TextIndexingProcess? process;
protected List<DomainId> Ids1 { get; } = [DomainId.NewGuid()];
@ -499,7 +504,12 @@ public abstract class TextIndexerTests : GivenContext
contentEvent.AppId = AppId;
contentEvent.SchemaId = SchemaId;
await sut.On(Enumerable.Repeat(Envelope.Create<IEvent>(contentEvent), 1));
// The indexer ignores events with versions that have already been indexed.
var version = versions.GetValueOrDefault(id, -1) + 1;
versions[id] = version;
await sut.On([Envelope.Create<IEvent>(contentEvent).SetEventStreamNumber(version)]);
}
private static ContentData TextData(string language, string text)
@ -627,7 +637,11 @@ public abstract class TextIndexerTests : GivenContext
{
var index = await CreateSutAsync();
process = new TextIndexingProcess(TestUtils.DefaultSerializer, index, new InMemoryTextIndexerState());
var coordinator = new TextIndexRebuildCoordinator();
var extraction = new TextIndexExtraction(AppProvider, TextExtractorTests.CreateExtractor(A.Fake<IScriptEngine>()));
process = new TextIndexingProcess(TestUtils.DefaultSerializer, index, new InMemoryTextIndexerState(), extraction, coordinator);
}
return process;

168
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexingProcessTests.cs

@ -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());
}
}

71
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/WeightedTextsTests.cs

@ -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"]);
}
}

39
backend/tests/Squidex.Domain.Apps.Entities.Tests/Jobs/JobProcessorTests.cs

@ -6,10 +6,12 @@
// ==========================================================================
using Microsoft.Extensions.Logging.Abstractions;
using NodaTime;
using Squidex.Caching;
using Squidex.Domain.Apps.Core;
using Squidex.Domain.Apps.Entities.Collaboration;
using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure;
using Squidex.Infrastructure.TestHelpers;
namespace Squidex.Domain.Apps.Entities.Jobs;
@ -53,4 +55,41 @@ public class JobProcessorTests : GivenContext
Assert.Equal("my-reference", job.Reference);
Assert.Equal(JobStatus.Completed, job.Status);
}
[Fact]
public async Task Should_mark_interrupted_jobs_as_failed()
{
var job = new Job { Id = DomainId.NewGuid(), TaskName = "job1", Status = JobStatus.Started };
state.Snapshot = new JobsState { Jobs = [job] };
await sut.LoadAsync(CancellationToken);
var actual = Assert.Single(state.Snapshot.Jobs);
Assert.Equal(JobStatus.Failed, actual.Status);
Assert.NotNull(actual.Stopped);
Assert.Single(actual.Log);
A.CallTo(() => runner.CleanupAsync(job))
.MustHaveHappenedOnceExactly();
}
[Fact]
public async Task Should_not_change_completed_jobs()
{
var job = new Job { Id = DomainId.NewGuid(), TaskName = "job1", Status = JobStatus.Completed, Stopped = default(Instant) };
state.Snapshot = new JobsState { Jobs = [job] };
await sut.LoadAsync(CancellationToken);
var actual = Assert.Single(state.Snapshot.Jobs);
Assert.Equal(JobStatus.Completed, actual.Status);
Assert.Empty(actual.Log);
A.CallTo(() => runner.CleanupAsync(A<Job>._))
.MustNotHaveHappened();
}
}

12
frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.html

@ -15,5 +15,17 @@
<sqx-form-row #tagsRow for="tags" hint="schemas.field.tagsHint" label="common.tags" [prefix]="field.fieldId">
<sqx-tag-editor [id]="tagsRow.fieldName" formControlName="tags" />
</sqx-form-row>
<sqx-form-row #searchModeRow for="searchMode" hint="schemas.field.searchModeHint" label="schemas.field.searchMode" [prefix]="field.fieldId">
<select class="form-select" [id]="searchModeRow.fieldName" formControlName="searchMode">
<option ngValue="Default">{{ "schemas.field.searchModeDefault" | sqxTranslate }}</option>
<option ngValue="Title">{{ "schemas.field.searchModeTitle" | sqxTranslate }}</option>
<option ngValue="Exclude">{{ "schemas.field.searchModeExclude" | sqxTranslate }}</option>
</select>
</sqx-form-row>
<sqx-form-row #searchPathsRow for="searchPaths" hint="schemas.field.searchPathsHint" label="schemas.field.searchPaths" [prefix]="field.fieldId">
<sqx-tag-editor [id]="searchPathsRow.fieldName" formControlName="searchPaths" />
</sqx-form-row>
}
</div>

3
frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.ts

@ -8,7 +8,7 @@
import { Component, Input } from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { FieldDto, FormRowComponent, SchemaDto, TagEditorComponent } from '@app/shared';
import { FieldDto, FormRowComponent, SchemaDto, TagEditorComponent, TranslatePipe } from '@app/shared';
@Component({
selector: 'sqx-field-form-common',
@ -19,6 +19,7 @@ import { FieldDto, FormRowComponent, SchemaDto, TagEditorComponent } from '@app/
FormsModule,
ReactiveFormsModule,
TagEditorComponent,
TranslatePipe,
],
})
export class FieldFormCommonComponent {

11
frontend/src/app/features/settings/pages/jobs/jobs-page.component.html

@ -4,6 +4,17 @@
<button class="btn btn-text-secondary me-2" (click)="reload()" shortcut="CTRL + B" title="i18n:jobs.refreshTooltip" type="button">
<i class="icon-reset"></i> {{ "common.refresh" | sqxTranslate }}
</button>
@if (jobsState.canRebuildTextIndex | async) {
<button
class="btn btn-outline-secondary me-2"
confirmText="i18n:jobs.textIndexConfirmText"
confirmTitle="i18n:jobs.textIndexConfirmTitle"
(sqxConfirmClick)="rebuildTextIndex()"
title="i18n:jobs.textIndexTooltip"
type="button">
{{ "jobs.textIndexStart" | sqxTranslate }}
</button>
}
@if (jobsState.canCreateBackup | async) {
<button class="btn btn-success" (click)="startBackup()" [disabled]="jobsState.maxBackupsReached | async" type="button">
{{ "jobs.backupStart" | sqxTranslate }}

7
frontend/src/app/features/settings/pages/jobs/jobs-page.component.ts

@ -10,7 +10,7 @@ import { Component, OnInit } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { ApiUrlConfig, JobsState, LayoutComponent, ListViewComponent, ShortcutDirective, SidebarMenuDirective, Subscriptions, TitleComponent, TooltipDirective, TourStepDirective, TranslatePipe } from '@app/shared';
import { ApiUrlConfig, ConfirmClickDirective, JobsState, LayoutComponent, ListViewComponent, ShortcutDirective, SidebarMenuDirective, Subscriptions, TitleComponent, TooltipDirective, TourStepDirective, TranslatePipe } from '@app/shared';
import { JobComponent } from './job.component';
@Component({
@ -19,6 +19,7 @@ import { JobComponent } from './job.component';
templateUrl: './jobs-page.component.html',
imports: [
AsyncPipe,
ConfirmClickDirective,
JobComponent,
LayoutComponent,
ListViewComponent,
@ -57,4 +58,8 @@ export class JobsPageComponent implements OnInit {
public startBackup() {
this.jobsState.startBackup();
}
public rebuildTextIndex() {
this.jobsState.rebuildTextIndex();
}
}

4
frontend/src/app/shared/model/custom.ts

@ -463,6 +463,10 @@ export class JobsDto extends generated.JobsDto {
public get canCreateBackup() {
return this.compute('canCreateBackup', () => hasAnyLink(this._links, 'create/backups'));
}
public get canRebuildTextIndex() {
return this.compute('canRebuildTextIndex', () => hasAnyLink(this._links, 'create/text-index'));
}
}
export class RoleDto extends generated.RoleDto {

38
frontend/src/app/shared/model/generated.ts

@ -3124,6 +3124,8 @@ export class SchemaScriptsDto implements ISchemaScriptsDto {
readonly delete?: string | undefined;
/** The script that is executed when change a content status. */
readonly change?: string | undefined;
/** The script that is executed when a content is indexed for the full text search. */
readonly index?: string | undefined;
constructor(data?: ISchemaScriptsDto) {
if (data) {
@ -3141,6 +3143,7 @@ export class SchemaScriptsDto implements ISchemaScriptsDto {
(<any>this).update = _data["update"];
(<any>this).delete = _data["delete"];
(<any>this).change = _data["change"];
(<any>this).index = _data["index"];
this.cleanup(this);
return this;
}
@ -3159,6 +3162,7 @@ export class SchemaScriptsDto implements ISchemaScriptsDto {
data["update"] = this.update;
data["delete"] = this.delete;
data["change"] = this.change;
data["index"] = this.index;
this.cleanup(data);
return data;
}
@ -3198,6 +3202,8 @@ export interface ISchemaScriptsDto {
readonly delete?: string | undefined;
/** The script that is executed when change a content status. */
readonly change?: string | undefined;
/** The script that is executed when a content is indexed for the full text search. */
readonly index?: string | undefined;
}
export class FieldRuleDto implements IFieldRuleDto {
@ -3449,6 +3455,10 @@ export abstract class FieldPropertiesDto implements IFieldPropertiesDto {
readonly editorUrl?: string | undefined;
/** Tags for automation processes. */
readonly tags?: string[] | undefined;
/** Defines how the field is used for the full text search. */
readonly searchMode?: FieldSearchMode;
/** Optional paths to the values that are indexed for the full text search, e.g. 'items.label'. */
readonly searchPaths?: string[] | undefined;
public get isComplexUI() {
return true;
@ -3494,6 +3504,12 @@ export abstract class FieldPropertiesDto implements IFieldPropertiesDto {
for (let item of _data["tags"])
(<any>this).tags!.push(item);
}
(<any>this).searchMode = _data["searchMode"];
if (Array.isArray(_data["searchPaths"])) {
(<any>this).searchPaths = [] as any;
for (let item of _data["searchPaths"])
(<any>this).searchPaths!.push(item);
}
this.cleanup(this);
return this;
}
@ -3563,6 +3579,12 @@ export abstract class FieldPropertiesDto implements IFieldPropertiesDto {
for (let item of this.tags)
data["tags"].push(item);
}
data["searchMode"] = this.searchMode;
if (Array.isArray(this.searchPaths)) {
data["searchPaths"] = [];
for (let item of this.searchPaths)
data["searchPaths"].push(item);
}
this.cleanup(data);
return data;
}
@ -3608,8 +3630,20 @@ export interface IFieldPropertiesDto {
readonly editorUrl?: string | undefined;
/** Tags for automation processes. */
readonly tags?: string[] | undefined;
/** Defines how the field is used for the full text search. */
readonly searchMode?: FieldSearchMode;
/** Optional paths to the values that are indexed for the full text search, e.g. 'items.label'. */
readonly searchPaths?: string[] | undefined;
}
export type FieldSearchMode = "Default" | "Title" | "Exclude";
export const FieldSearchModeValues: ReadonlyArray<FieldSearchMode> = [
"Default",
"Title",
"Exclude"
];
export class ArrayFieldPropertiesDto extends FieldPropertiesDto implements IArrayFieldPropertiesDto {
/** The minimum allowed items for the field value. */
readonly minItems?: number | undefined;
@ -11368,6 +11402,10 @@ export class JobsDto extends ResourceDto implements IJobsDto {
return this.compute('canCreateBackup', () => hasAnyLink(this._links, 'create/backups'));
}
public get canRebuildTextIndex() {
return this.compute('canRebuildTextIndex', () => hasAnyLink(this._links, 'create/text-index'));
}
constructor(data?: IJobsDto) {
super(data);
}

9
frontend/src/app/shared/services/jobs.service.ts

@ -57,6 +57,15 @@ export class JobsService {
pretifyError('i18n:jobs.backupFailed'));
}
public postTextIndexRebuild(appName: string, resource: Resource): Observable<any> {
const link = resource._links['create/text-index'];
const url = this.apiUrl.buildUrl(link.href);
return this.http.request(link.method, url).pipe(
pretifyError('i18n:jobs.textIndexFailed'));
}
public postRestore(dto: RestoreRequestDto): Observable<any> {
const url = this.apiUrl.buildUrl('api/apps/restore');

29
frontend/src/app/shared/state/jobs.state.spec.ts

@ -110,4 +110,33 @@ describe('JobsState', () => {
dialogs.verify(x => x.notifyInfo(It.isAnyString()), Times.once());
});
});
describe('Text Index', () => {
const payload = { items: [], canRebuildTextIndex: true, _links: { 'create/text-index': { method: 'POST', href: '/text-index' } } };
it('should not allow rebuild if link is missing', () => {
jobsService.setup(x => x.getJobs(app))
.returns(() => of({ items: [] } as any)).verifiable();
jobsState.load().subscribe();
let canRebuild: boolean | undefined;
jobsState.canRebuildTextIndex.subscribe(x => canRebuild = x);
expect(canRebuild).toBeFalsy();
});
it('should start rebuild with resource from payload', () => {
jobsService.setup(x => x.getJobs(app))
.returns(() => of(payload as any)).verifiable();
jobsService.setup(x => x.postTextIndexRebuild(app, It.isValue(payload as any)))
.returns(() => of({})).verifiable();
jobsState.load().subscribe();
jobsState.rebuildTextIndex().subscribe();
dialogs.verify(x => x.notifyInfo(It.isAnyString()), Times.once());
});
});
});

29
frontend/src/app/shared/state/jobs.state.ts

@ -6,9 +6,9 @@
*/
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { EMPTY, Observable } from 'rxjs';
import { finalize, tap } from 'rxjs/operators';
import { debug, DialogService, LoadingState, shareSubscribed, State } from '@app/framework';
import { debug, DialogService, LoadingState, Resource, shareSubscribed, State } from '@app/framework';
import { JobDto } from '../model';
import { JobsService } from '../services/jobs.service';
import { AppsState } from './apps.state';
@ -19,6 +19,9 @@ interface Snapshot extends LoadingState {
// Indicates if the user can create new backups.
canCreateBackup?: boolean;
// The resource to rebuild the full text index, if the user is allowed to do so.
textIndexResource?: Resource;
}
@Injectable({
@ -40,6 +43,9 @@ export class JobsState extends State<Snapshot> {
public canCreateBackup =
this.project(x => x.canCreateBackup === true);
public canRebuildTextIndex =
this.project(x => !!x.textIndexResource);
public get appId() {
return this.appsState.appId;
}
@ -72,7 +78,9 @@ export class JobsState extends State<Snapshot> {
}
return this.jobsService.getJobs(this.appName).pipe(
tap(({ items: jobs, canCreateBackup }) => {
tap(payload => {
const { items: jobs, canCreateBackup, canRebuildTextIndex } = payload;
if (isReload && !silent) {
this.dialogs.notifyInfo('i18n:jobs.reloaded');
}
@ -80,6 +88,7 @@ export class JobsState extends State<Snapshot> {
this.next({
jobs,
canCreateBackup,
textIndexResource: canRebuildTextIndex ? payload : undefined,
isLoaded: true,
isLoading: false,
}, 'Loading Success');
@ -98,6 +107,20 @@ export class JobsState extends State<Snapshot> {
shareSubscribed(this.dialogs));
}
public rebuildTextIndex(): Observable<any> {
const resource = this.snapshot.textIndexResource;
if (!resource) {
return EMPTY;
}
return this.jobsService.postTextIndexRebuild(this.appsState.appName, resource).pipe(
tap(() => {
this.dialogs.notifyInfo('i18n:jobs.started');
}),
shareSubscribed(this.dialogs));
}
public delete(job: JobDto): Observable<any> {
return this.jobsService.deleteJob(this.appsState.appName, job).pipe(
tap(() => {

13
frontend/src/app/shared/state/schemas.forms.ts

@ -203,6 +203,9 @@ export class EditSchemaScriptsForm extends Form<ExtendedFormGroup, {}, object> {
update: new UntypedFormControl('',
Validators.nullValidator,
),
index: new UntypedFormControl('',
Validators.nullValidator,
),
}));
}
}
@ -244,12 +247,22 @@ export class EditFieldForm extends Form<ExtendedFormGroup, {}, FieldPropertiesDt
tags: new UntypedFormControl([],
Validators.nullValidator,
),
searchMode: new UntypedFormControl('Default',
Validators.nullValidator,
),
searchPaths: new UntypedFormControl([],
Validators.nullValidator,
),
};
properties.accept(new EditFieldFormVisitor(config));
return new ExtendedFormGroup(config);
}
protected transformLoad(value: Partial<FieldPropertiesDto>) {
return { ...value, searchMode: value.searchMode || 'Default' };
}
}
export class EditFieldFormVisitor implements FieldPropertiesVisitor<any> {

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save