Skip to content

V1: Update ElasticSearch to v1 #1088

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: develop-v1
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions EventFlow.sln
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventFlow.SourceGenerators"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventFlow.SourceGenerators.Tests", "Source\EventFlow.SourceGenerators.Tests\EventFlow.SourceGenerators.Tests.csproj", "{D8317769-F140-4E5D-9041-19342A3A33BD}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ElasticSearch", "ElasticSearch", "{B684211A-CF37-4A6A-BF1B-460D0369DD61}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventFlow.Elasticsearch", "Source\EventFlow.Elasticsearch\EventFlow.Elasticsearch.csproj", "{199E59E3-C674-4D8E-B31D-699C7331F4CA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventFlow.Elasticsearch.Tests", "Source\EventFlow.Elasticsearch.Tests\EventFlow.Elasticsearch.Tests.csproj", "{20775513-2FA6-4148-8068-B7C0AA08EB76}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -172,6 +178,14 @@ Global
{D8317769-F140-4E5D-9041-19342A3A33BD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D8317769-F140-4E5D-9041-19342A3A33BD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D8317769-F140-4E5D-9041-19342A3A33BD}.Release|Any CPU.Build.0 = Release|Any CPU
{199E59E3-C674-4D8E-B31D-699C7331F4CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{199E59E3-C674-4D8E-B31D-699C7331F4CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{199E59E3-C674-4D8E-B31D-699C7331F4CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{199E59E3-C674-4D8E-B31D-699C7331F4CA}.Release|Any CPU.Build.0 = Release|Any CPU
{20775513-2FA6-4148-8068-B7C0AA08EB76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{20775513-2FA6-4148-8068-B7C0AA08EB76}.Debug|Any CPU.Build.0 = Debug|Any CPU
{20775513-2FA6-4148-8068-B7C0AA08EB76}.Release|Any CPU.ActiveCfg = Release|Any CPU
{20775513-2FA6-4148-8068-B7C0AA08EB76}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -208,6 +222,9 @@ Global
{91929C7C-D9AE-B5BA-2467-C9FCAEC69696} = {5EE323DE-E69B-451A-8AC3-22DD6A004FBA}
{35098BEA-A0B8-4E63-8D71-35CE5297B459} = {91929C7C-D9AE-B5BA-2467-C9FCAEC69696}
{D8317769-F140-4E5D-9041-19342A3A33BD} = {91929C7C-D9AE-B5BA-2467-C9FCAEC69696}
{B684211A-CF37-4A6A-BF1B-460D0369DD61} = {5EE323DE-E69B-451A-8AC3-22DD6A004FBA}
{199E59E3-C674-4D8E-B31D-699C7331F4CA} = {B684211A-CF37-4A6A-BF1B-460D0369DD61}
{20775513-2FA6-4148-8068-B7C0AA08EB76} = {B684211A-CF37-4A6A-BF1B-460D0369DD61}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {17607E2C-4E8E-45A2-85BD-0A5808E1C0F3}
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ The following list key characteristics of each version as well as its related br
- 🟠 `EventFlow.AspNetCore`
- 💀 `EventFlow.Autofac`
- 💀 `EventFlow.DependencyInjection`
- 🟠 `EventFlow.Elasticsearch`
- 🟢 `EventFlow.Elasticsearch`
- 🟢 `EventFlow.EntityFramework`
- 🟠 `EventFlow.EventStores.EventStore`
- 🟢 `EventFlow.Hangfire`
Expand Down
3 changes: 1 addition & 2 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
### New in 1.2.1 (working version, not released yet)

* *Nothing yet...*
* New: NuGet `EventFlow.Elasticsearch` now ported to v1 (thanks @MMonrad)

### New in 1.2.0 (released 2025-03-09)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../Common.props" />
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
<GenerateAssemblyInfo>False</GenerateAssemblyInfo>
<IsPackable>False</IsPackable>
Expand All @@ -11,13 +10,16 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" />
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\EventFlow.Elasticsearch\EventFlow.Elasticsearch.csproj" />
<ProjectReference Include="..\EventFlow.TestHelpers\EventFlow.TestHelpers.csproj" />
<ProjectReference Include="..\EventFlow\EventFlow.csproj" />
</ItemGroup>

<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
using EventFlow.TestHelpers.Aggregates;
using EventFlow.TestHelpers.Aggregates.Entities;
using EventFlow.TestHelpers.Suites;
using Microsoft.Extensions.DependencyInjection;
using Nest;
using NUnit.Framework;
using IndexName = EventFlow.Elasticsearch.ValueObjects.IndexName;
Expand All @@ -52,7 +53,7 @@ public class ElasticsearchReadModelStoreTests : TestSuiteForReadModelStore

private readonly List<string> _indexes = new List<string>();

protected override IRootResolver CreateRootResolver(IEventFlowOptions eventFlowOptions)
protected override IServiceProvider Configure(IEventFlowOptions eventFlowOptions)
{
var elasticsearchUrl = Environment.GetEnvironmentVariable("ELASTICSEARCH_URL") ?? "http://localhost:9200";

Expand All @@ -63,25 +64,25 @@ protected override IRootResolver CreateRootResolver(IEventFlowOptions eventFlowO
.SniffLifeSpan(TimeSpan.FromMinutes(5))
.DisablePing();

var resolver = eventFlowOptions
.RegisterServices(sr => { sr.RegisterType(typeof(ThingyMessageLocator)); })
var options = eventFlowOptions
.RegisterServices(sr => { sr.AddTransient<ThingyMessageLocator>(); })
.ConfigureElasticsearch(connectionSettings)
.UseElasticsearchReadModel<ElasticsearchThingyReadModel>()
.UseElasticsearchReadModel<ElasticsearchThingyMessageReadModel, ThingyMessageLocator>()
.AddQueryHandlers(
typeof(ElasticsearchThingyGetQueryHandler),
typeof(ElasticsearchThingyGetVersionQueryHandler),
typeof(ElasticsearchThingyGetMessagesQueryHandler))
.CreateResolver();
typeof(ElasticsearchThingyGetMessagesQueryHandler));

PrepareIndexes(resolver);
PrepareIndexes(options);

return resolver;
return base.Configure(eventFlowOptions);
Copy link
Preview

Copilot AI Mar 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It appears that you are configuring services using the modified 'options', but then returning base.Configure(eventFlowOptions) which may not incorporate your new registrations. Consider returning the configured 'options' to preserve the changes made during dependency registration.

Suggested change
return base.Configure(eventFlowOptions);
return options;

Copilot uses AI. Check for mistakes.

}

private void PrepareIndexes(IRootResolver resolver)
private void PrepareIndexes(IEventFlowOptions options)
{
_elasticClient = resolver.Resolve<IElasticClient>();
using var provider = options.ServiceCollection.BuildServiceProvider();
_elasticClient = provider.GetRequiredService<IElasticClient>();

var readModelTypes =
GetLoadableTypes<ElasticsearchTypeAttribute>(typeof(ElasticsearchThingyReadModel).Assembly);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,56 +21,63 @@
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EventFlow.Aggregates;
using EventFlow.ReadStores;
using EventFlow.TestHelpers.Aggregates;
using EventFlow.TestHelpers.Aggregates.Entities;
using EventFlow.TestHelpers.Aggregates.Events;
using Nest;

namespace EventFlow.Elasticsearch.Tests.IntegrationTests.ReadModels
namespace EventFlow.Elasticsearch.Tests.IntegrationTests.ReadModels;

[ElasticsearchType(IdProperty = "Id", RelationName = "message")]
public class ElasticsearchThingyMessageReadModel : IReadModel,
IAmReadModelFor<ThingyAggregate, ThingyId, ThingyMessageAddedEvent>,
IAmReadModelFor<ThingyAggregate, ThingyId, ThingyMessageHistoryAddedEvent>
{
[ElasticsearchType(IdProperty = "Id", RelationName = "message")]
public class ElasticsearchThingyMessageReadModel : IReadModel,
IAmReadModelFor<ThingyAggregate, ThingyId, ThingyMessageAddedEvent>,
IAmReadModelFor<ThingyAggregate, ThingyId, ThingyMessageHistoryAddedEvent>
{
public string Id { get; set; }
public string Id { get; set; }

[Keyword(
Name = "ThingyId",
Index = true)]
public string ThingyId { get; set; }
[Keyword(
Name = "ThingyId",
Index = true)]
public string ThingyId { get; set; }

[Text(
Name = "Message",
Index = false)]
public string Message { get; set; }
[Text(
Name = "Message",
Index = false)]
public string Message { get; set; }

public void Apply(IReadModelContext context, IDomainEvent<ThingyAggregate, ThingyId, ThingyMessageAddedEvent> domainEvent)
{
ThingyId = domainEvent.AggregateIdentity.Value;
public Task ApplyAsync(IReadModelContext context,
IDomainEvent<ThingyAggregate, ThingyId, ThingyMessageAddedEvent> domainEvent,
CancellationToken cancellationToken)
{
ThingyId = domainEvent.AggregateIdentity.Value;

var thingyMessage = domainEvent.AggregateEvent.ThingyMessage;
Id = thingyMessage.Id.Value;
Message = thingyMessage.Message;
}
var thingyMessage = domainEvent.AggregateEvent.ThingyMessage;
Id = thingyMessage.Id.Value;
Message = thingyMessage.Message;
return Task.CompletedTask;
}

public void Apply(IReadModelContext context, IDomainEvent<ThingyAggregate, ThingyId, ThingyMessageHistoryAddedEvent> domainEvent)
{
ThingyId = domainEvent.AggregateIdentity.Value;
public Task ApplyAsync(IReadModelContext context,
IDomainEvent<ThingyAggregate, ThingyId, ThingyMessageHistoryAddedEvent> domainEvent,
CancellationToken cancellationToken)
{
ThingyId = domainEvent.AggregateIdentity.Value;

var messageId = new ThingyMessageId(context.ReadModelId);
var thingyMessage = domainEvent.AggregateEvent.ThingyMessages.Single(m => m.Id == messageId);
Id = messageId.Value;
Message = thingyMessage.Message;
}
var messageId = new ThingyMessageId(context.ReadModelId);
var thingyMessage = domainEvent.AggregateEvent.ThingyMessages.Single(m => m.Id == messageId);
Id = messageId.Value;
Message = thingyMessage.Message;
return Task.CompletedTask;
}

public ThingyMessage ToThingyMessage()
{
return new ThingyMessage(
ThingyMessageId.With(Id),
Message);
}
public ThingyMessage ToThingyMessage()
{
return new ThingyMessage(
ThingyMessageId.With(Id),
Message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System.Threading;
using System.Threading.Tasks;
using EventFlow.Aggregates;
using EventFlow.ReadStores;
using EventFlow.TestHelpers.Aggregates;
Expand Down Expand Up @@ -49,21 +51,24 @@ public class ElasticsearchThingyReadModel : IReadModel,
Index = false)]
public int PingsReceived { get; set; }

public void Apply(IReadModelContext context, IDomainEvent<ThingyAggregate, ThingyId, ThingyDomainErrorAfterFirstEvent> domainEvent)
public Task ApplyAsync(IReadModelContext context, IDomainEvent<ThingyAggregate, ThingyId, ThingyDomainErrorAfterFirstEvent> domainEvent, CancellationToken cancellationToken)
{
Id = domainEvent.AggregateIdentity.Value;
DomainErrorAfterFirstReceived = true;
return Task.CompletedTask;
}

public void Apply(IReadModelContext context, IDomainEvent<ThingyAggregate, ThingyId, ThingyPingEvent> domainEvent)
public Task ApplyAsync(IReadModelContext context, IDomainEvent<ThingyAggregate, ThingyId, ThingyPingEvent> domainEvent, CancellationToken cancellationToken)
{
Id = domainEvent.AggregateIdentity.Value;
PingsReceived++;
return Task.CompletedTask;
}

public void Apply(IReadModelContext context, IDomainEvent<ThingyAggregate, ThingyId, ThingyDeletedEvent> domainEvent)
public Task ApplyAsync(IReadModelContext context, IDomainEvent<ThingyAggregate, ThingyId, ThingyDeletedEvent> domainEvent, CancellationToken cancellationToken)
{
context.MarkForDeletion();
return Task.CompletedTask;
}

public Thingy ToThingy()
Expand Down
5 changes: 2 additions & 3 deletions Source/EventFlow.Elasticsearch/EventFlow.Elasticsearch.csproj
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../Common.props" />
<PropertyGroup>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<TargetFrameworks>netstandard2.1;netcoreapp3.1;net6.0;net8.0</TargetFrameworks>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
<GenerateAssemblyInfo>True</GenerateAssemblyInfo>
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<Title>EventFlow.Elasticsearch</Title>
<Authors>Rasmus Mikkelsen</Authors>
<Company>Rasmus Mikkelsen</Company>
<Copyright>Copyright (c) Rasmus Mikkelsen 2015 - 2021</Copyright>
<Copyright>Copyright (c) Rasmus Mikkelsen 2015 - 2025</Copyright>
<Description>Elasticsearch support for EventFlow</Description>
<PackageTags>CQRS ES event sourcing Elasticsearch</PackageTags>
<RepositoryType>git</RepositoryType>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,10 @@
using System;
using System.Linq;
using Elasticsearch.Net;
using EventFlow.Aggregates;
using EventFlow.Configuration;
using EventFlow.Core;
using EventFlow.Elasticsearch.ReadStores;
using EventFlow.Extensions;
using EventFlow.ReadStores;
using Microsoft.Extensions.DependencyInjection;
using Nest;

namespace EventFlow.Elasticsearch.Extensions
Expand Down Expand Up @@ -70,8 +68,8 @@ public static IEventFlowOptions ConfigureElasticsearch(
{
return eventFlowOptions.RegisterServices(sr =>
{
sr.Register(f => elasticClientFactory(), Lifetime.Singleton);
sr.Register<IReadModelDescriptionProvider, ReadModelDescriptionProvider>(Lifetime.Singleton, true);
sr.AddSingleton(_ => elasticClientFactory());
sr.AddSingleton<IReadModelDescriptionProvider, ReadModelDescriptionProvider>();
});
}

Expand All @@ -94,24 +92,11 @@ public static IEventFlowOptions UseElasticsearchReadModel<TReadModel, TReadModel
.UseReadStoreFor<IElasticsearchReadModelStore<TReadModel>, TReadModel, TReadModelLocator>();
}

[Obsolete("Use the simpler method UseElasticsearchReadModel<TReadModel> instead.")]
public static IEventFlowOptions UseElasticsearchReadModelFor<TAggregate, TIdentity, TReadModel>(
this IEventFlowOptions eventFlowOptions)
where TAggregate : IAggregateRoot<TIdentity>
where TIdentity : IIdentity
where TReadModel : class, IReadModel
{
return eventFlowOptions
.RegisterServices(RegisterElasticsearchReadStore<TReadModel>)
.UseReadStoreFor<TAggregate, TIdentity, IElasticsearchReadModelStore<TReadModel>, TReadModel>();
}

private static void RegisterElasticsearchReadStore<TReadModel>(
IServiceRegistration serviceRegistration)
private static void RegisterElasticsearchReadStore<TReadModel>(IServiceCollection collection)
where TReadModel : class, IReadModel
{
serviceRegistration.Register<IElasticsearchReadModelStore<TReadModel>, ElasticsearchReadModelStore<TReadModel>>();
serviceRegistration.Register<IReadModelStore<TReadModel>>(r => r.Resolver.Resolve<IElasticsearchReadModelStore<TReadModel>>());
collection.AddTransient<IElasticsearchReadModelStore<TReadModel>, ElasticsearchReadModelStore<TReadModel>>();
collection.AddTransient<IReadModelStore<TReadModel>>(r => r.GetRequiredService<IElasticsearchReadModelStore<TReadModel>>());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
using EventFlow.Elasticsearch.ValueObjects;
using EventFlow.Exceptions;
using EventFlow.Extensions;
using EventFlow.Logs;
using EventFlow.ReadStores;
using Microsoft.Extensions.Logging;
using Nest;

namespace EventFlow.Elasticsearch.ReadStores
Expand All @@ -42,13 +42,13 @@ public class ElasticsearchReadModelStore<TReadModel> :
IElasticsearchReadModelStore<TReadModel>
where TReadModel : class, IReadModel
{
private readonly ILog _log;
private readonly ILogger<ElasticsearchReadModelStore<TReadModel>> _log;
private readonly IElasticClient _elasticClient;
private readonly IReadModelDescriptionProvider _readModelDescriptionProvider;
private readonly ITransientFaultHandler<IOptimisticConcurrencyRetryStrategy> _transientFaultHandler;

public ElasticsearchReadModelStore(
ILog log,
ILogger<ElasticsearchReadModelStore<TReadModel>> log,
IElasticClient elasticClient,
IReadModelDescriptionProvider readModelDescriptionProvider,
ITransientFaultHandler<IOptimisticConcurrencyRetryStrategy> transientFaultHandler)
Expand All @@ -65,7 +65,7 @@ public async Task<ReadModelEnvelope<TReadModel>> GetAsync(
{
var readModelDescription = _readModelDescriptionProvider.GetReadModelDescription<TReadModel>();

_log.Verbose(() => $"Fetching read model '{typeof(TReadModel).PrettyPrint()}' with ID '{id}' from index '{readModelDescription.IndexName}'");
_log.LogTrace("Fetching read model '{TReadModel}' with ID '{Id}' from index '{IndexName}'", typeof(TReadModel).PrettyPrint(), id, readModelDescription.IndexName);

var getResponse = await _elasticClient.GetAsync<TReadModel>(
id,
Expand Down Expand Up @@ -108,9 +108,10 @@ public async Task DeleteAllAsync(
{
var readModelDescription = _readModelDescriptionProvider.GetReadModelDescription<TReadModel>();

_log.Information($"Deleting ALL '{typeof(TReadModel).PrettyPrint()}' by DELETING INDEX '{readModelDescription.IndexName}'!");
_log.LogInformation("Deleting ALL '{TReadModel}' by DELETING INDEX '{IndexName}'!", typeof(TReadModel).PrettyPrint(), readModelDescription.IndexName);

var indices = _elasticClient.GetIndicesPointingToAlias(readModelDescription.IndexName.Value);
var indices = await _elasticClient.GetIndicesPointingToAliasAsync(readModelDescription.IndexName.Value)
.ConfigureAwait(false);

foreach (var indexKey in indices)
{
Expand Down