JasperFx / marten

.NET Transactional Document DB and Event Store on PostgreSQL
https://martendb.io
MIT License
2.79k stars 441 forks source link

Strongly typed IDs not supported by Marten's event store? #3306

Open aradalvand opened 1 month ago

aradalvand commented 1 month ago

I thought support for this was added following https://github.com/JasperFx/marten/issues/2487 but I can't seem to get a pretty simple sample working.

Types.cs:

using System.Text.Json.Serialization;
using Vogen;

namespace Foo;

[ValueObject<Guid>(toPrimitiveCasting: CastOperator.Implicit)]
public readonly partial struct PaymentId;

public class Payment
{
    [JsonInclude]
    public PaymentId Id { get; private set; }
    [JsonInclude]
    public DateTimeOffset CreatedAt { get; private set; }
    [JsonInclude]
    public PaymentState State { get; private set; }

    public static Payment Create(PaymentCreated @event) => new()
    {
        Id = @event.Id,
        CreatedAt = @event.CreatedAt,
        State = PaymentState.Created,
    };

    public void Apply(PaymentCanceled @event)
    {
        State = PaymentState.Canceled;
    }

    public void Apply(PaymentVerified @event)
    {
        State = PaymentState.Verified;
    }
}

public enum PaymentState
{
    Created,
    Initialized,
    Canceled,
    Verified,
}

public record PaymentCreated(
    PaymentId Id,
    DateTimeOffset CreatedAt
);

public record PaymentCanceled(
    PaymentId Id,
    DateTimeOffset CanceledAt
);

public record PaymentVerified(
    PaymentId Id,
    DateTimeOffset VerifiedAt
);

Program.cs:

using Foo;
using Marten;
using Marten.Events.Daemon.Resiliency;
using Marten.Events.Projections;
using Weasel.Core;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMarten(options =>
{
    options.Connection(
        "Host=localhost;Database=marten_event_store_test;Username=arad;Password=1301381"
    );

    options.UseSystemTextJsonForSerialization(options: new()
    {
        IncludeFields = true,
    });

    if (builder.Environment.IsDevelopment())
        options.AutoCreateSchemaObjects = AutoCreate.All;

    options.Projections.Snapshot<Payment>(SnapshotLifecycle.Inline);

    options.Events.AddEventType<PaymentCreated>();
    options.Events.AddEventType<PaymentVerified>();
    options.Events.AddEventType<PaymentCanceled>();
})
.AddAsyncDaemon(DaemonMode.HotCold)
.UseLightweightSessions();

var app = builder.Build();

var paymentId = PaymentId.From(Guid.Parse("eb5b8626-973f-41f0-922d-4a4303eeb625"));
app.MapGet("/", async (IDocumentSession session) =>
{
    var r2 = await session.Events.FetchForWriting<Payment>(paymentId);
    return r2.Aggregate;
});
app.MapPost("/", async (IDocumentSession session) =>
{
    session.Events.Append(paymentId, new PaymentCreated(
        paymentId,
        DateTimeOffset.Now
    ));
    session.Events.Append(paymentId, new PaymentCanceled(
        paymentId,
        DateTimeOffset.Now
    ));
    await session.SaveChangesAsync();
    return "done";
});

app.Run();

Upon dotnet run, I get the following exception:

Unhandled exception. Marten.Exceptions.InvalidProjectionException: Id type mismatch. The stream identity type is System.Guid, but the aggregate document Foo.Payment id type is PaymentId
   at Marten.Events.Projections.ProjectionOptions.AssertValidity(DocumentStore store)
   at Marten.DocumentStore..ctor(StoreOptions options)
   at Marten.MartenServiceCollectionExtensions.<>c.<AddMarten>b__8_1(IServiceProvider s)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(ServiceIdentifier serviceIdentifier)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(ServiceIdentifier serviceIdentifier, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Marten.MartenServiceCollectionExtensions.MartenConfigurationExpression.<>c.<AddAsyncDaemon>b__8_1(IServiceProvider s)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(ServiceIdentifier serviceIdentifier)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(ServiceIdentifier serviceIdentifier, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at Program.<Main>$(String[] args) in /home/arad/scratchpad/marten-vogen-test/Program.cs:line 54
matthewtamm commented 1 month ago

Check docs @ https://martendb.io/documents/identity.html#strong-typed-identifiers

There is an Info callout re strong identifiers and the event store


From: Arad Alvand (AmirHossein Ahmadi) @.> Sent: Thursday, July 11, 2024 4:44:09 PM To: JasperFx/marten @.> Cc: Subscribed @.***> Subject: [JasperFx/marten] Id type mismatch exception when using strongly typed IDs (Issue #3306)

I thought support for this was added following #2487https://github.com/JasperFx/marten/issues/2487 but I can't seem to get a pretty simple sample working.

Types.cs:

using System.Text.Json.Serialization; using Vogen;

namespace Foo;

[ValueObject(toPrimitiveCasting: CastOperator.Implicit)] public readonly partial struct PaymentId;

public class Payment { [JsonInclude] public PaymentId Id { get; private set; } [JsonInclude] public DateTimeOffset CreatedAt { get; private set; } [JsonInclude] public PaymentState State { get; private set; }

public static Payment Create(PaymentCreated @event) => new()
{
    Id = @event.Id,
    CreatedAt = @event.CreatedAt,
    State = PaymentState.Created,
};

public void Apply(PaymentCanceled @event)
{
    State = PaymentState.Canceled;
}

public void Apply(PaymentVerified @event)
{
    State = PaymentState.Verified;
}

}

public enum PaymentState { Created, Initialized, Canceled, Verified, }

public record PaymentCreated( PaymentId Id, DateTimeOffset CreatedAt );

public record PaymentCanceled( PaymentId Id, DateTimeOffset CanceledAt );

public record PaymentVerified( PaymentId Id, DateTimeOffset VerifiedAt );

Program.cs:

using Foo; using Marten; using Marten.Events.Daemon.Resiliency; using Marten.Events.Projections; using Weasel.Core;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMarten(options => { options.Connection( "Host=localhost;Database=marten_event_store_test;Username=arad;Password=1301381" );

options.UseSystemTextJsonForSerialization(options: new()
{
    IncludeFields = true,
});

if (builder.Environment.IsDevelopment())
    options.AutoCreateSchemaObjects = AutoCreate.All;

options.Projections.Snapshot<Payment>(SnapshotLifecycle.Inline);

options.Events.AddEventType<PaymentCreated>();
options.Events.AddEventType<PaymentVerified>();
options.Events.AddEventType<PaymentCanceled>();

}) .AddAsyncDaemon(DaemonMode.HotCold) .UseLightweightSessions();

var app = builder.Build();

var paymentId = PaymentId.From(Guid.Parse("eb5b8626-973f-41f0-922d-4a4303eeb625")); app.MapGet("/", async (IDocumentSession session) => { var r2 = await session.Events.FetchForWriting(paymentId); return r2.Aggregate; }); app.MapPost("/", async (IDocumentSession session) => { session.Events.Append(paymentId, new PaymentCreated( paymentId, DateTimeOffset.Now )); session.Events.Append(paymentId, new PaymentCanceled( paymentId, DateTimeOffset.Now )); await session.SaveChangesAsync(); return "done"; });

app.Run();

Upon dotnet run, I get the following exception:

Unhandled exception. Marten.Exceptions.InvalidProjectionException: Id type mismatch. The stream identity type is System.Guid, but the aggregate document Foo.Payment id type is PaymentId at Marten.Events.Projections.ProjectionOptions.AssertValidity(DocumentStore store) at Marten.DocumentStore..ctor(StoreOptions options) at Marten.MartenServiceCollectionExtensions.<>c.b__8_1(IServiceProvider s) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(ServiceIdentifier serviceIdentifier) at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(ServiceIdentifier serviceIdentifier, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Marten.MartenServiceCollectionExtensions.MartenConfigurationExpression.<>c.b__8_1(IServiceProvider s) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(ServiceIdentifier serviceIdentifier) at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(ServiceIdentifier serviceIdentifier, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken) at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host) at Program.

$(String[] args) in /home/arad/scratchpad/marten-vogen-test/Program.cs:line 58

— Reply to this email directly, view it on GitHubhttps://github.com/JasperFx/marten/issues/3306, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AABRCTPEXOFS3C6YFI2TG73ZLYSTTAVCNFSM6AAAAABKWJ4THKVHI2DSMVQWIX3LMV43ASLTON2WKOZSGQYDEMZYHA4DOMA. You are receiving this because you are subscribed to this thread.Message ID: @.***>

mysticmind commented 1 month ago

There is not yet any direct support for strong typed identifiers for the event store

Screenshot 2024-07-11 at 12 48 36 PM
aradalvand commented 1 month ago

Ah, okay. Thanks for the pointers. I didn't see that callout. Huge bummer though; this is a deal breaker for a lot of us and it effectively means we couldn't use Marten at all.

Is there an issue tracking this limitation or could we leave this one open to do so?

mysticmind commented 1 month ago

Let us just leave this issue open.

jeremydmiller commented 1 month ago

@aradalvand C'mon, this was documented.

"Huge bummer though; this is a deal breaker for a lot of us and it effectively means we couldn't use Marten at all."

That's absolutely and completely bonkers IMO. Why does this even matter, really? Are you wanting that to maybe distinguish between different aggregates?

And just so everybody understands what an insane amount of work it was to add what's already there, check out the commit history for the document db side of this:

https://github.com/JasperFx/marten/pull/3268

I hate all of you. This is so much work for so very, very little value for just a handful of people who desperately love unnecessary complexity. But let's get this done so people stop complaining about it.