outbox pattern implemented

This commit is contained in:
2026-01-29 00:21:23 +01:00
Unverified
parent 09b7bb8bef
commit 236a7a0fe1
10 changed files with 274 additions and 93 deletions

View File

@@ -1,7 +1,9 @@
using MediatR; using MediatR;
using TimetableDesigner.Backend.Events.OutboxPattern;
using TimetableDesigner.Backend.Services.Authentication.Core.Helpers; using TimetableDesigner.Backend.Services.Authentication.Core.Helpers;
using TimetableDesigner.Backend.Services.Authentication.Database; using TimetableDesigner.Backend.Services.Authentication.Database;
using TimetableDesigner.Backend.Services.Authentication.Database.Model; using TimetableDesigner.Backend.Services.Authentication.Database.Model;
using TimetableDesigner.Backend.Services.Authentication.DTO.Events;
namespace TimetableDesigner.Backend.Services.Authentication.Core.Commands.Register; namespace TimetableDesigner.Backend.Services.Authentication.Core.Commands.Register;
@@ -27,13 +29,13 @@ public class RegisterHandler : IRequestHandler<RegisterCommand, RegisterResult>
PasswordSalt = hash.Salt, PasswordSalt = hash.Salt,
}; };
await _databaseContext.Accounts.AddAsync(account, cancellationToken); await _databaseContext.Accounts.AddAsync(account, cancellationToken);
// Change to outbox pattern
//RegisterEvent eventData = account.ToEvent();
//await _eventQueuePublisher.PublishAsync(eventData);
await _databaseContext.SaveChangesAsync(cancellationToken); await _databaseContext.SaveChangesAsync(cancellationToken);
Event eventData = Event.Create(new RegisterEvent(account.Id, account.Email));
await _databaseContext.Events.AddAsync(eventData, cancellationToken);
await _databaseContext.SaveChangesAsync(cancellationToken);
return new RegisterResult(account.Id, account.Email); return new RegisterResult(account.Id, account.Email);
} }
} }

View File

@@ -1,34 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using TimetableDesigner.Backend.Services.Authentication.Database.Model;
namespace TimetableDesigner.Backend.Services.Authentication.Database.Configuration;
public class EventConfiguration : IEntityTypeConfiguration<Event>
{
public void Configure(EntityTypeBuilder<Event> builder)
{
builder.HasKey(x => x.Id);
builder.HasIndex(x => x.Id)
.IsUnique();
builder.Property(x => x.Id)
.IsRequired();
builder.Property(x => x.Payload)
.IsRequired();
builder.Property(x => x.PayloadType)
.IsRequired();
builder.Property(x => x.OccuredOn)
.IsRequired();
builder.Property(x => x.ProcessedOn);
builder.Property(x => x.RetryCount)
.IsRequired();
builder.Property(b => b.Version)
.IsRowVersion();
}
}

View File

@@ -1,13 +1,15 @@
using System.Reflection; using System.Reflection;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using TimetableDesigner.Backend.Events.OutboxPattern;
using TimetableDesigner.Backend.Services.Authentication.Database.Model; using TimetableDesigner.Backend.Services.Authentication.Database.Model;
namespace TimetableDesigner.Backend.Services.Authentication.Database; namespace TimetableDesigner.Backend.Services.Authentication.Database;
public class DatabaseContext : DbContext public class DatabaseContext : DbContext, IEventOutboxDbContext
{ {
public virtual DbSet<Account> Accounts { get; set; } public virtual DbSet<Account> Accounts { get; set; }
public virtual DbSet<RefreshToken> RefreshTokens { get; set; } public virtual DbSet<RefreshToken> RefreshTokens { get; set; }
public virtual DbSet<Event> Events { get; set; }
public DatabaseContext() { } public DatabaseContext() { }
@@ -18,6 +20,10 @@ public class DatabaseContext : DbContext
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =>
optionsBuilder.UseNpgsql("name=Database"); optionsBuilder.UseNpgsql("name=Database");
protected override void OnModelCreating(ModelBuilder modelBuilder) => protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetAssembly(typeof(DatabaseContext))!); modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetAssembly(typeof(DatabaseContext))!);
modelBuilder.ApplyConfiguration(new EventConfiguration());
}
} }

View File

@@ -0,0 +1,145 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TimetableDesigner.Backend.Services.Authentication.Database;
#nullable disable
namespace TimetableDesigner.Backend.Services.Authentication.Database.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20260128230804_Outbox_Pattern_From_Nuget")]
partial class Outbox_Pattern_From_Nuget
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("TimetableDesigner.Backend.Events.OutboxPattern.Event", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("LastRetryOn")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("OccuredOn")
.HasColumnType("timestamp with time zone");
b.Property<string>("Payload")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PayloadType")
.IsRequired()
.HasColumnType("text");
b.Property<long>("RetryCount")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("Id")
.IsUnique();
b.ToTable("Events");
});
modelBuilder.Entity("TimetableDesigner.Backend.Services.Authentication.Database.Model.Account", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property<long>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(320)
.HasColumnType("character varying(320)");
b.Property<byte[]>("Password")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("bytea");
b.Property<string>("PasswordSalt")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)");
b.Property<uint>("Version")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("xid")
.HasColumnName("xmin");
b.HasKey("Id");
b.HasIndex("Id")
.IsUnique();
b.ToTable("Accounts");
});
modelBuilder.Entity("TimetableDesigner.Backend.Services.Authentication.Database.Model.RefreshToken", b =>
{
b.Property<Guid>("Token")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<long>("AccountId")
.HasColumnType("bigint");
b.Property<DateTimeOffset>("ExpirationDate")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsExtendable")
.HasColumnType("boolean");
b.Property<uint>("Version")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("xid")
.HasColumnName("xmin");
b.HasKey("Token");
b.HasIndex("AccountId");
b.HasIndex("Token")
.IsUnique();
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("TimetableDesigner.Backend.Services.Authentication.Database.Model.RefreshToken", b =>
{
b.HasOne("TimetableDesigner.Backend.Services.Authentication.Database.Model.Account", "Account")
.WithMany("RefreshTokens")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
});
modelBuilder.Entity("TimetableDesigner.Backend.Services.Authentication.Database.Model.Account", b =>
{
b.Navigation("RefreshTokens");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,70 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace TimetableDesigner.Backend.Services.Authentication.Database.Migrations
{
/// <inheritdoc />
public partial class Outbox_Pattern_From_Nuget : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Event");
migrationBuilder.CreateTable(
name: "Events",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Payload = table.Column<string>(type: "text", nullable: false),
PayloadType = table.Column<string>(type: "text", nullable: false),
OccuredOn = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
LastRetryOn = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
RetryCount = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Events", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Events_Id",
table: "Events",
column: "Id",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Events");
migrationBuilder.CreateTable(
name: "Event",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
OccuredOn = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
Payload = table.Column<string>(type: "text", nullable: false),
PayloadType = table.Column<string>(type: "text", nullable: false),
ProcessedOn = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
RetryCount = table.Column<long>(type: "bigint", nullable: false),
xmin = table.Column<uint>(type: "xid", rowVersion: true, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Event", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Event_Id",
table: "Event",
column: "Id",
unique: true);
}
}
}

View File

@@ -22,6 +22,37 @@ namespace TimetableDesigner.Backend.Services.Authentication.Database.Migrations
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("TimetableDesigner.Backend.Events.OutboxPattern.Event", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("LastRetryOn")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("OccuredOn")
.HasColumnType("timestamp with time zone");
b.Property<string>("Payload")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PayloadType")
.IsRequired()
.HasColumnType("text");
b.Property<long>("RetryCount")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("Id")
.IsUnique();
b.ToTable("Events");
});
modelBuilder.Entity("TimetableDesigner.Backend.Services.Authentication.Database.Model.Account", b => modelBuilder.Entity("TimetableDesigner.Backend.Services.Authentication.Database.Model.Account", b =>
{ {
b.Property<long>("Id") b.Property<long>("Id")
@@ -59,43 +90,6 @@ namespace TimetableDesigner.Backend.Services.Authentication.Database.Migrations
b.ToTable("Accounts"); b.ToTable("Accounts");
}); });
modelBuilder.Entity("TimetableDesigner.Backend.Services.Authentication.Database.Model.Event", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("OccuredOn")
.HasColumnType("timestamp with time zone");
b.Property<string>("Payload")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PayloadType")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("ProcessedOn")
.HasColumnType("timestamp with time zone");
b.Property<long>("RetryCount")
.HasColumnType("bigint");
b.Property<uint>("Version")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("xid")
.HasColumnName("xmin");
b.HasKey("Id");
b.HasIndex("Id")
.IsUnique();
b.ToTable("Event");
});
modelBuilder.Entity("TimetableDesigner.Backend.Services.Authentication.Database.Model.RefreshToken", b => modelBuilder.Entity("TimetableDesigner.Backend.Services.Authentication.Database.Model.RefreshToken", b =>
{ {
b.Property<Guid>("Token") b.Property<Guid>("Token")

View File

@@ -1,12 +0,0 @@
namespace TimetableDesigner.Backend.Services.Authentication.Database.Model;
public class Event
{
public Guid Id { get; set; }
public required string Payload { get; set; }
public required string PayloadType { get; set; }
public DateTimeOffset OccuredOn { get; set; } = DateTimeOffset.UtcNow;
public DateTimeOffset? ProcessedOn { get; set; }
public uint RetryCount { get; set; }
public uint Version { get; set; }
}

View File

@@ -8,6 +8,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
<PackageReference Include="TimetableDesigner.Backend.Events.OutboxPattern" Version="1.1.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -3,6 +3,7 @@ using FluentValidation;
using Microsoft.AspNetCore.Identity.Data; using Microsoft.AspNetCore.Identity.Data;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using TimetableDesigner.Backend.Events.Extensions.AspNetCore.OpenApi; using TimetableDesigner.Backend.Events.Extensions.AspNetCore.OpenApi;
using TimetableDesigner.Backend.Events.OutboxPattern;
using TimetableDesigner.Backend.Events.Providers.RabbitMQ; using TimetableDesigner.Backend.Events.Providers.RabbitMQ;
using TimetableDesigner.Backend.Services.Authentication.API; using TimetableDesigner.Backend.Services.Authentication.API;
using TimetableDesigner.Backend.Services.Authentication.API.Validators; using TimetableDesigner.Backend.Services.Authentication.API.Validators;
@@ -28,6 +29,7 @@ public static class Program
builder.Services.AddHelpers(); builder.Services.AddHelpers();
builder.Services.AddValidators(); builder.Services.AddValidators();
builder.Services.AddMediatR(x => x.RegisterServicesFromAssembly(typeof(Program).Assembly)); builder.Services.AddMediatR(x => x.RegisterServicesFromAssembly(typeof(Program).Assembly));
builder.Services.AddWorkers();
WebApplication app = builder.Build(); WebApplication app = builder.Build();
@@ -41,6 +43,12 @@ public static class Program
app.Run(); app.Run();
} }
private static IServiceCollection AddWorkers(this IServiceCollection services)
{
services.AddHostedService<EventOutboxSender<DatabaseContext>>();
return services;
}
private static IServiceCollection AddHelpers(this IServiceCollection services) private static IServiceCollection AddHelpers(this IServiceCollection services)
{ {
services.AddSingleton<IPasswordHasher, PasswordHasher>(); services.AddSingleton<IPasswordHasher, PasswordHasher>();

View File

@@ -18,8 +18,9 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
<PackageReference Include="timetabledesigner.backend.events.extensions.aspnetcore.openapi" Version="1.0.1" /> <PackageReference Include="timetabledesigner.backend.events.extensions.aspnetcore.openapi" Version="1.0.2" />
<PackageReference Include="TimetableDesigner.Backend.Events.Providers.RabbitMQ" Version="1.0.4" /> <PackageReference Include="timetabledesigner.backend.events.outboxpattern" Version="1.1.2" />
<PackageReference Include="TimetableDesigner.Backend.Events.Providers.RabbitMQ" Version="1.0.5" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>