Browse Source

Merge pull request #3 from EasyAbp/ut-outbox

UTs for outbox
pull/5/head
Super 5 years ago
committed by GitHub
parent
commit
92d2d21fe0
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 10
      src/EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore/EasyAbp/Abp/EventBus/Boxes/Dtm/Barriers/AbpEfCoreDtmMsgBarrierManager.cs
  2. 18
      src/EasyAbp.Abp.EventBus.Boxes.Dtm.Grpc/EasyAbp/Abp/EventBus/Boxes/Dtm/GrpcDtmMessageManager.cs
  3. 15
      src/EasyAbp.Abp.EventBus.Boxes.Dtm.Grpc/EasyAbp/Abp/EventBus/Boxes/Dtm/Models/GrpcDtmMessageInfoModel.cs
  4. 43
      src/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB/EasyAbp/Abp/EventBus/Boxes/Dtm/Barriers/AbpMongoDbDtmMsgBarrierManager.cs
  5. 6
      src/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB/EasyAbp/Abp/EventBus/Boxes/Dtm/Barriers/DtmMongoDbBarrierCollectionInitializer.cs
  6. 10
      src/EasyAbp.Abp.EventBus.Boxes.Dtm/EasyAbp/Abp/EventBus/Boxes/Dtm/DtmMsgBarrierManagerBase.cs
  7. 12
      src/EasyAbp.Abp.EventBus.Boxes.Dtm/EasyAbp/Abp/EventBus/Boxes/Dtm/IDtmMsgBarrierManager.cs
  8. 48
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore.Tests/EntityFrameworkCore/AbpEventBusBoxesDtmEntityFrameworkCoreTestModule.cs
  9. 153
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore.Tests/EntityFrameworkCore/DtmOutboxTests.cs
  10. 26
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore.Tests/EntityFrameworkCore/DtmTestDbContext2.cs
  11. 23
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB.Tests/MongoDB/AbpEventBusBoxesDtmMongoDbTestModule.cs
  12. 154
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB.Tests/MongoDB/DtmOutboxTests.cs
  13. 2
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB.Tests/MongoDB/DtmTestMongoDbContext.cs
  14. 19
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB.Tests/MongoDB/DtmTestMongoDbContext2.cs
  15. 6
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/AbpEventBusBoxesDtmTestBaseModule.cs
  16. 1
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/DtmDbProperties.cs
  17. 6
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/FakeDistributedEventBus.cs
  18. 27
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/FakeDtmMessageInfoModel.cs
  19. 57
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/FakeDtmMessageManager.cs
  20. 11
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/Test2Eto.cs
  21. 47
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/TestDtmUnitOfWork.cs
  22. 11
      test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/TestEto.cs

10
src/EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore/EasyAbp/Abp/EventBus/Boxes/Dtm/Barriers/AbpEfCoreDtmMsgBarrierManager.cs

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using DtmCommon;
@ -33,7 +34,8 @@ public class AbpEfCoreDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IEfCoreDbC
BarrierTableInitializer = barrierTableInitializer;
}
public override async Task EnsureInsertBarrierAsync(IEfCoreDbContext dbContext, string gid)
public override async Task EnsureInsertBarrierAsync(IEfCoreDbContext dbContext, string gid,
CancellationToken cancellationToken = default)
{
if (dbContext.Database.CurrentTransaction is null)
{
@ -50,7 +52,8 @@ public class AbpEfCoreDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IEfCoreDbC
}
}
public override async Task<bool> TryInsertBarrierAsRollbackAsync(IEfCoreDbContext dbContext, string gid)
public override async Task<bool> TryInsertBarrierAsRollbackAsync(IEfCoreDbContext dbContext, string gid,
CancellationToken cancellationToken = default)
{
try
{
@ -116,7 +119,8 @@ public class AbpEfCoreDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IEfCoreDbC
return affected;
}
public override async Task<bool> TryInvokeEnsureInsertBarrierAsync(IDatabaseApi databaseApi, string gid)
public override async Task<bool> TryInvokeEnsureInsertBarrierAsync(IDatabaseApi databaseApi, string gid,
CancellationToken cancellationToken)
{
if (!IsValidDatabaseApi<EfCoreDatabaseApi>(databaseApi))
{

18
src/EasyAbp.Abp.EventBus.Boxes.Dtm.Grpc/EasyAbp/Abp/EventBus/Boxes/Dtm/GrpcDtmMessageManager.cs

@ -83,7 +83,7 @@ public class GrpcDtmMessageManager : IDtmMessageManager, ITransientDependency
await PrepareTransMessagesAsync(eventBag, cancellationToken);
await InsertTransMessagesBarriersAsync(eventBag);
await InsertTransMessagesBarriersAsync(eventBag, cancellationToken);
}
public virtual async Task SubmitAsync(DtmOutboxEventBag eventBag, CancellationToken cancellationToken = default)
@ -141,22 +141,12 @@ public class GrpcDtmMessageManager : IDtmMessageManager, ITransientDependency
foreach (var model in eventBag.TransMessages.Values)
{
var message = (model.DtmMessage as MsgGrpc)!;
var dbContextType = $"{model.DbConnectionLookupInfo.DbContextType.FullName}, {model.DbConnectionLookupInfo.DbContextType.Assembly.GetName().Name}";
message.SetBranchHeaders(new Dictionary<string, string>
{
{DtmRequestHeaderNames.ActionApiToken, AbpDtmGrpcOptions.ActionApiToken},
{DtmRequestHeaderNames.DbContextType, dbContextType},
{DtmRequestHeaderNames.TenantId, model.DbConnectionLookupInfo.TenantId.ToString()},
{DtmRequestHeaderNames.HashedConnectionString, model.DbConnectionLookupInfo.HashedConnectionString},
});
await message.Prepare(AbpDtmGrpcOptions.GetQueryPreparedAddress(), cancellationToken);
}
}
protected virtual async Task InsertTransMessagesBarriersAsync(DtmOutboxEventBag eventBag)
protected virtual async Task InsertTransMessagesBarriersAsync(DtmOutboxEventBag eventBag,
CancellationToken cancellationToken = default)
{
foreach (var model in eventBag.TransMessages.Values)
{
@ -168,7 +158,7 @@ public class GrpcDtmMessageManager : IDtmMessageManager, ITransientDependency
foreach (var barrierManager in barrierManagers)
{
if (await barrierManager.TryInvokeEnsureInsertBarrierAsync(databaseApi, model.Gid))
if (await barrierManager.TryInvokeEnsureInsertBarrierAsync(databaseApi, model.Gid, cancellationToken))
{
inserted = true;
break;

15
src/EasyAbp.Abp.EventBus.Boxes.Dtm.Grpc/EasyAbp/Abp/EventBus/Boxes/Dtm/Models/GrpcDtmMessageInfoModel.cs

@ -35,11 +35,24 @@ public class GrpcDtmMessageInfoModel : IDtmMessageInfoModel
throw new AbpException("Duplicate events publishing action.");
}
((MsgGrpc)DtmMessage).Add(abpDtmEventBoxesOptions.GetPublishEventsAddress(), new DtmMsgPublishEventsRequest
var message = (DtmMessage as MsgGrpc)!;
message.Add(abpDtmEventBoxesOptions.GetPublishEventsAddress(), new DtmMsgPublishEventsRequest
{
OutgoingEventInfoListToByteString = serializer.Serialize(EventInfos)
});
var dbContextType =
$"{DbConnectionLookupInfo.DbContextType.FullName}, {DbConnectionLookupInfo.DbContextType.Assembly.GetName().Name}";
message.SetBranchHeaders(new Dictionary<string, string>
{
{DtmRequestHeaderNames.ActionApiToken, abpDtmEventBoxesOptions.ActionApiToken},
{DtmRequestHeaderNames.DbContextType, dbContextType},
{DtmRequestHeaderNames.TenantId, DbConnectionLookupInfo.TenantId.ToString()},
{DtmRequestHeaderNames.HashedConnectionString, DbConnectionLookupInfo.HashedConnectionString},
});
EventsPublishingActionAdded = true;
}
}

43
src/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB/EasyAbp/Abp/EventBus/Boxes/Dtm/Barriers/AbpMongoDbDtmMsgBarrierManager.cs

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DtmCommon;
using EasyAbp.Abp.EventBus.Boxes.Dtm.Options;
@ -31,7 +32,8 @@ public class AbpMongoDbDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IAbpMongo
BarrierCollectionInitializer = barrierCollectionInitializer;
}
public override async Task EnsureInsertBarrierAsync(IAbpMongoDbContext dbContext, string gid)
public override async Task EnsureInsertBarrierAsync(IAbpMongoDbContext dbContext, string gid,
CancellationToken cancellationToken = default)
{
if (dbContext.SessionHandle is null)
{
@ -40,7 +42,7 @@ public class AbpMongoDbDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IAbpMongo
try
{
await InsertBarrierAsync(dbContext, gid, Constant.TYPE_MSG);
await InsertBarrierAsync(dbContext, gid, Constant.TYPE_MSG, cancellationToken);
}
catch (Exception e)
{
@ -54,11 +56,12 @@ public class AbpMongoDbDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IAbpMongo
}
}
public override async Task<bool> TryInsertBarrierAsRollbackAsync(IAbpMongoDbContext dbContext, string gid)
public override async Task<bool> TryInsertBarrierAsRollbackAsync(IAbpMongoDbContext dbContext, string gid,
CancellationToken cancellationToken = default)
{
try
{
await InsertBarrierAsync(dbContext, gid, Constant.Barrier.MSG_BARRIER_REASON);
await InsertBarrierAsync(dbContext, gid, Constant.Barrier.MSG_BARRIER_REASON, cancellationToken);
}
catch (Exception e)
{
@ -76,10 +79,13 @@ public class AbpMongoDbDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IAbpMongo
var filter = BuildFindFilters(gid, Constant.Barrier.MSG_BRANCHID, Constant.TYPE_MSG,
Constant.Barrier.MSG_BARRIER_ID);
var cursor = dbContext.SessionHandle is null
? await mongoCollection.FindAsync<DtmBarrierDocument>(filter, cancellationToken: cancellationToken)
: await mongoCollection.FindAsync<DtmBarrierDocument>(dbContext.SessionHandle, filter,
cancellationToken: cancellationToken);
var cursor = await mongoCollection.FindAsync<DtmBarrierDocument>(filter);
var res = await cursor.ToListAsync();
var res = await cursor.ToListAsync(cancellationToken: cancellationToken);
if (res is { Count: > 0 } && res[0].Reason.Equals(Constant.Barrier.MSG_BARRIER_REASON))
{
@ -107,7 +113,7 @@ public class AbpMongoDbDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IAbpMongo
}
protected virtual async Task InsertBarrierAsync(IAbpMongoDbContext dbContext, string gid,
string reason)
string reason, CancellationToken cancellationToken = default)
{
var mongoCollection = GetMongoCollection(dbContext);
@ -115,7 +121,7 @@ public class AbpMongoDbDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IAbpMongo
try
{
await mongoCollection.InsertOneAsync(new DtmBarrierDocument
var document = new DtmBarrierDocument
{
TransType = Constant.TYPE_MSG,
GId = gid,
@ -123,7 +129,21 @@ public class AbpMongoDbDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IAbpMongo
Op = Constant.TYPE_MSG,
BarrierId = Constant.Barrier.MSG_BARRIER_ID,
Reason = reason
});
};
if (dbContext.SessionHandle is null)
{
await mongoCollection.InsertOneAsync(
document,
cancellationToken: cancellationToken);
}
else
{
await mongoCollection.InsertOneAsync(
dbContext.SessionHandle,
document,
cancellationToken: cancellationToken);
}
}
catch (Exception e)
{
@ -136,7 +156,8 @@ public class AbpMongoDbDtmMsgBarrierManager : DtmMsgBarrierManagerBase<IAbpMongo
}
}
public override async Task<bool> TryInvokeEnsureInsertBarrierAsync(IDatabaseApi databaseApi, string gid)
public override async Task<bool> TryInvokeEnsureInsertBarrierAsync(IDatabaseApi databaseApi, string gid,
CancellationToken cancellationToken)
{
if (!IsValidDatabaseApi<MongoDbDatabaseApi>(databaseApi))
{

6
src/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB/EasyAbp/Abp/EventBus/Boxes/Dtm/Barriers/DtmMongoDbBarrierCollectionInitializer.cs

@ -46,11 +46,7 @@ public class DtmMongoDbBarrierCollectionInitializer : IDtmMongoDbBarrierCollecti
foreach (var server in servers)
{
UnitOfWorkManager.Current.OnCompleted(() =>
{
CreatedServers[server] = true;
return Task.CompletedTask;
});
CreatedServers[server] = true;
}
}
}

10
src/EasyAbp.Abp.EventBus.Boxes.Dtm/EasyAbp/Abp/EventBus/Boxes/Dtm/DtmMsgBarrierManagerBase.cs

@ -1,4 +1,5 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Uow;
@ -7,14 +8,17 @@ namespace EasyAbp.Abp.EventBus.Boxes.Dtm;
public abstract class DtmMsgBarrierManagerBase<TDbContextInterface> : IDtmMsgBarrierManager<TDbContextInterface>, IDtmMsgBarrierManager
where TDbContextInterface : class
{
public abstract Task<bool> TryInvokeEnsureInsertBarrierAsync(IDatabaseApi databaseApi, string gid);
public abstract Task<bool> TryInvokeEnsureInsertBarrierAsync(IDatabaseApi databaseApi, string gid,
CancellationToken cancellationToken = default);
protected virtual bool IsValidDatabaseApi<TDatabaseApi>(IDatabaseApi databaseApi) where TDatabaseApi : IDatabaseApi
{
return databaseApi.GetType().IsAssignableTo(typeof(TDatabaseApi));
}
public abstract Task EnsureInsertBarrierAsync(TDbContextInterface dbContext, string gid);
public abstract Task EnsureInsertBarrierAsync(TDbContextInterface dbContext, string gid,
CancellationToken cancellationToken = default);
public abstract Task<bool> TryInsertBarrierAsRollbackAsync(TDbContextInterface dbContext, string gid);
public abstract Task<bool> TryInsertBarrierAsRollbackAsync(TDbContextInterface dbContext, string gid,
CancellationToken cancellationToken = default);
}

12
src/EasyAbp.Abp.EventBus.Boxes.Dtm/EasyAbp/Abp/EventBus/Boxes/Dtm/IDtmMsgBarrierManager.cs

@ -1,4 +1,5 @@
using System.Threading.Tasks;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Volo.Abp.Uow;
@ -6,9 +7,11 @@ namespace EasyAbp.Abp.EventBus.Boxes.Dtm;
public interface IDtmMsgBarrierManager<in TDbContextInterface> : IDtmMsgBarrierManager where TDbContextInterface : class
{
Task EnsureInsertBarrierAsync(TDbContextInterface dbContext, [NotNull] string gid);
Task EnsureInsertBarrierAsync(TDbContextInterface dbContext, [NotNull] string gid,
CancellationToken cancellationToken = default);
Task<bool> TryInsertBarrierAsRollbackAsync(TDbContextInterface dbContext, [NotNull] string gid);
Task<bool> TryInsertBarrierAsRollbackAsync(TDbContextInterface dbContext, [NotNull] string gid,
CancellationToken cancellationToken = default);
}
public interface IDtmMsgBarrierManager
@ -16,5 +19,6 @@ public interface IDtmMsgBarrierManager
/// <summary>
/// Invokes InsertBarrierAsync method if the <see cref="databaseApi"/> can be identified.
/// </summary>
Task<bool> TryInvokeEnsureInsertBarrierAsync(IDatabaseApi databaseApi, [NotNull] string gid);
Task<bool> TryInvokeEnsureInsertBarrierAsync(IDatabaseApi databaseApi, [NotNull] string gid,
CancellationToken cancellationToken = default);
}

48
test/EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore.Tests/EntityFrameworkCore/AbpEventBusBoxesDtmEntityFrameworkCoreTestModule.cs

@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Sqlite;
using Volo.Abp.EventBus.Distributed;
@ -23,22 +24,45 @@ public class AbpEventBusBoxesDtmEntityFrameworkCoreTestModule : AbpModule
Configure<AbpDbContextOptions>(options =>
{
options.Configure(abpDbContextConfigurationContext =>
options.Configure<DtmTestDbContext>(abpDbContextConfigurationContext =>
{
abpDbContextConfigurationContext.DbContextOptions.UseSqlite(sqliteConnection);
});
});
var sqliteConnection2 = CreateDatabaseAndGetConnection2();
Configure<AbpDbContextOptions>(options =>
{
options.Configure<DtmTestDbContext2>(abpDbContextConfigurationContext =>
{
abpDbContextConfigurationContext.DbContextOptions.UseSqlite(sqliteConnection2);
});
});
context.Services.AddAbpDbContext<DtmTestDbContext>(options =>
{
options.AddDefaultRepositories();
});
context.Services.AddAbpDbContext<DtmTestDbContext2>(options =>
{
options.AddDefaultRepositories();
});
Configure<AbpDistributedEventBusOptions>(options =>
{
options.Outboxes.Configure(config =>
options.Outboxes.Configure("FirstBox", config =>
{
config.UseDbContextWithDtmOutbox<DtmTestDbContext>();
config.Selector = type => type == typeof(TestEto);
});
options.Outboxes.Configure("SecondBox", config =>
{
config.UseDbContextWithDtmOutbox<DtmTestDbContext2>();
config.Selector = null;
// config.Selector = type => type == typeof(Test2Eto);
});
options.Inboxes.Configure(config =>
@ -46,11 +70,17 @@ public class AbpEventBusBoxesDtmEntityFrameworkCoreTestModule : AbpModule
config.UseDbContextWithDtmInbox<DtmTestDbContext>();
});
});
Configure<AbpDbConnectionOptions>(options =>
{
options.ConnectionStrings["Dtm"] = "Data Source=Context;Mode=Memory;Cache=Shared";
options.ConnectionStrings["Dtm2"] = "Data Source=Context2;Mode=Memory;Cache=Shared";
});
}
private static SqliteConnection CreateDatabaseAndGetConnection()
{
var connection = new SqliteConnection("Data Source=:memory:");
var connection = new SqliteConnection("Data Source=Context;Mode=Memory;Cache=Shared");
connection.Open();
new DtmTestDbContext(
@ -59,4 +89,16 @@ public class AbpEventBusBoxesDtmEntityFrameworkCoreTestModule : AbpModule
return connection;
}
private static SqliteConnection CreateDatabaseAndGetConnection2()
{
var connection = new SqliteConnection("Data Source=Context2;Mode=Memory;Cache=Shared");
connection.Open();
new DtmTestDbContext2(
new DbContextOptionsBuilder<DtmTestDbContext2>().UseSqlite(connection).Options
).GetService<IRelationalDatabaseCreator>().CreateTables();
return connection;
}
}

153
test/EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore.Tests/EntityFrameworkCore/DtmOutboxTests.cs

@ -0,0 +1,153 @@
using System.Linq;
using System.Threading.Tasks;
using EasyAbp.Abp.EventBus.Boxes.Dtm.Models;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.Uow;
using Xunit;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore;
public class DtmOutboxTests : DtmEntityFrameworkCoreTestBase
{
protected IUnitOfWorkManager UnitOfWorkManager { get; }
protected IDistributedEventBus DistributedEventBus { get; }
protected IDtmMsgBarrierManager<IEfCoreDbContext> DtmMsgBarrierManager { get; }
public DtmOutboxTests()
{
UnitOfWorkManager = ServiceProvider.GetRequiredService<IUnitOfWorkManager>();
DistributedEventBus = ServiceProvider.GetRequiredService<IDistributedEventBus>();
DtmMsgBarrierManager = ServiceProvider.GetRequiredService<IDtmMsgBarrierManager<IEfCoreDbContext>>();
}
[Fact]
public virtual async Task Should_Set_DefaultMessage_With_Non_Trans_Uow()
{
using var uow = UnitOfWorkManager.Begin(new AbpUnitOfWorkOptions(false));
await DistributedEventBus.PublishAsync(new TestEto());
var dtmUow = uow as TestDtmUnitOfWork;
dtmUow.ShouldNotBeNull();
await uow.CompleteAsync();
uow.IsCompleted.ShouldBeTrue();
var bag = dtmUow.GetDtmOutboxEventBag();
bag.HasAnyEvent().ShouldBeTrue();
bag.TransMessages.ShouldBeEmpty();
bag.DefaultMessage.ShouldNotBeNull();
bag.DefaultMessage.EventInfos.Count.ShouldBe(1);
bag.DefaultMessage.EventInfos[0].EventName.ShouldBe("test");
}
[Fact]
public virtual async Task Should_Not_Insert_Barrier_As_Rollback_If_Trans_Succeeded()
{
IDtmMessageInfoModel messageInfoModel;
using (var uow = UnitOfWorkManager.Begin(new AbpUnitOfWorkOptions(true)))
{
await DistributedEventBus.PublishAsync(new TestEto());
var dtmUow = uow as TestDtmUnitOfWork;
dtmUow.ShouldNotBeNull();
await uow.CompleteAsync();
uow.IsCompleted.ShouldBeTrue();
var bag = dtmUow.GetDtmOutboxEventBag();
bag.HasAnyEvent().ShouldBeTrue();
bag.TransMessages.Count.ShouldBe(1);
messageInfoModel = bag.TransMessages.First().Value;
}
await WithUnitOfWorkAsync(async () =>
{
var dbContextProvider = ServiceProvider.GetRequiredService<IDbContextProvider<DtmTestDbContext>>();
var dbContext = await dbContextProvider.GetDbContextAsync();
(await DtmMsgBarrierManager.TryInsertBarrierAsRollbackAsync(dbContext, messageInfoModel.Gid)).ShouldBe(false);
});
}
[Fact]
public virtual async Task Should_Insert_Barrier_As_Rollback_If_Trans_Rolled_Back()
{
IDtmMessageInfoModel messageInfoModel;
using (var uow = UnitOfWorkManager.Begin(new AbpUnitOfWorkOptions(true)))
{
await DistributedEventBus.PublishAsync(new TestEto());
var dtmUow = uow as TestDtmUnitOfWork;
dtmUow.ShouldNotBeNull();
dtmUow.ThrowIfCommit = true;
var exception = await Should.ThrowAsync<AbpException>(() => uow.CompleteAsync());
exception.Message.ShouldBe("bye");
uow.IsCompleted.ShouldBeFalse();
var bag = dtmUow.GetDtmOutboxEventBag();
bag.HasAnyEvent().ShouldBeTrue();
bag.TransMessages.Count.ShouldBe(1);
messageInfoModel = bag.TransMessages.First().Value;
}
await WithUnitOfWorkAsync(async () =>
{
var dbContextProvider = ServiceProvider.GetRequiredService<IDbContextProvider<DtmTestDbContext>>();
var dbContext = await dbContextProvider.GetDbContextAsync();
(await DtmMsgBarrierManager.TryInsertBarrierAsRollbackAsync(dbContext, messageInfoModel.Gid)).ShouldBe(true);
});
}
[Fact]
public virtual async Task Should_Support_Multi_Database()
{
IDtmMessageInfoModel messageInfoModel;
IDtmMessageInfoModel messageInfoModel2;
using (var uow = UnitOfWorkManager.Begin(new AbpUnitOfWorkOptions(true)))
{
await DistributedEventBus.PublishAsync(new TestEto());
await DistributedEventBus.PublishAsync(new Test2Eto());
var dtmUow = uow as TestDtmUnitOfWork;
dtmUow.ShouldNotBeNull();
await uow.CompleteAsync();
uow.IsCompleted.ShouldBeTrue();
var bag = dtmUow.GetDtmOutboxEventBag();
bag.HasAnyEvent().ShouldBeTrue();
bag.TransMessages.Count.ShouldBe(2);
messageInfoModel = bag.TransMessages
.First(x => x.Value.DbConnectionLookupInfo.DbContextType == typeof(DtmTestDbContext)).Value;
messageInfoModel2 = bag.TransMessages
.First(x => x.Value.DbConnectionLookupInfo.DbContextType == typeof(DtmTestDbContext2)).Value;
}
await WithUnitOfWorkAsync(async () =>
{
var dbContextProvider = ServiceProvider.GetRequiredService<IDbContextProvider<DtmTestDbContext>>();
var dbContext = await dbContextProvider.GetDbContextAsync();
var dbContextProvider2 = ServiceProvider.GetRequiredService<IDbContextProvider<DtmTestDbContext2>>();
var dbContext2 = await dbContextProvider2.GetDbContextAsync();
(await DtmMsgBarrierManager.TryInsertBarrierAsRollbackAsync(dbContext, messageInfoModel.Gid)).ShouldBe(false);
(await DtmMsgBarrierManager.TryInsertBarrierAsRollbackAsync(dbContext2, messageInfoModel2.Gid)).ShouldBe(false);
});
}
}

26
test/EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore.Tests/EntityFrameworkCore/DtmTestDbContext2.cs

@ -0,0 +1,26 @@
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm.EntityFrameworkCore;
[ConnectionStringName(DtmDbProperties.ConnectionString2Name)]
public class DtmTestDbContext2 : AbpDbContext<DtmTestDbContext2>, IDtmDbContext
{
/* Add DbSet for each Aggregate Root here. Example:
* public DbSet<Question> Questions { get; set; }
*/
public DtmTestDbContext2(DbContextOptions<DtmTestDbContext2> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ConfigureDtmTest();
}
}

23
test/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB.Tests/MongoDB/AbpEventBusBoxesDtmMongoDbTestModule.cs

@ -16,12 +16,16 @@ public class AbpEventBusBoxesDtmMongoDbTestModule : AbpModule
{
var stringArray = MongoDbFixture.ConnectionString.Split('?');
var connectionString = stringArray[0].EnsureEndsWith('/') +
"Db_" +
"Db_" +
Guid.NewGuid().ToString("N") + "/?" + stringArray[1];
var connectionString2 = stringArray[0].EnsureEndsWith('/') +
"Db_" +
Guid.NewGuid().ToString("N") + "/?" + stringArray[1];
Configure<AbpDbConnectionOptions>(options =>
{
options.ConnectionStrings.Default = connectionString;
options.ConnectionStrings["Dtm"] = connectionString;
options.ConnectionStrings["Dtm2"] = connectionString2;
});
context.Services.AddMongoDbContext<DtmTestMongoDbContext>(options =>
@ -29,11 +33,24 @@ public class AbpEventBusBoxesDtmMongoDbTestModule : AbpModule
options.AddDefaultRepositories();
});
context.Services.AddMongoDbContext<DtmTestMongoDbContext2>(options =>
{
options.AddDefaultRepositories();
});
Configure<AbpDistributedEventBusOptions>(options =>
{
options.Outboxes.Configure(config =>
options.Outboxes.Configure("FirstBox", config =>
{
config.UseMongoDbContextWithDtmOutbox<DtmTestMongoDbContext>();
config.Selector = type => type == typeof(TestEto);
});
options.Outboxes.Configure("SecondBox", config =>
{
config.UseMongoDbContextWithDtmOutbox<DtmTestMongoDbContext2>();
config.Selector = null;
// config.Selector = type => type == typeof(Test2Eto);
});
options.Inboxes.Configure(config =>

154
test/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB.Tests/MongoDB/DtmOutboxTests.cs

@ -0,0 +1,154 @@
using System.Linq;
using System.Threading.Tasks;
using EasyAbp.Abp.EventBus.Boxes.Dtm.Models;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MongoDB;
using Volo.Abp.Uow;
using Xunit;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB;
[Collection(MongoTestCollection.Name)]
public class DtmOutboxTests : DtmMongoDbTestBase
{
protected IUnitOfWorkManager UnitOfWorkManager { get; }
protected IDistributedEventBus DistributedEventBus { get; }
protected IDtmMsgBarrierManager<IAbpMongoDbContext> DtmMsgBarrierManager { get; }
public DtmOutboxTests()
{
UnitOfWorkManager = ServiceProvider.GetRequiredService<IUnitOfWorkManager>();
DistributedEventBus = ServiceProvider.GetRequiredService<IDistributedEventBus>();
DtmMsgBarrierManager = ServiceProvider.GetRequiredService<IDtmMsgBarrierManager<IAbpMongoDbContext>>();
}
[Fact]
public virtual async Task Should_Set_DefaultMessage_With_Non_Trans_Uow()
{
using var uow = UnitOfWorkManager.Begin(new AbpUnitOfWorkOptions(false));
await DistributedEventBus.PublishAsync(new TestEto());
var dtmUow = uow as TestDtmUnitOfWork;
dtmUow.ShouldNotBeNull();
await uow.CompleteAsync();
uow.IsCompleted.ShouldBeTrue();
var bag = dtmUow.GetDtmOutboxEventBag();
bag.HasAnyEvent().ShouldBeTrue();
bag.TransMessages.ShouldBeEmpty();
bag.DefaultMessage.ShouldNotBeNull();
bag.DefaultMessage.EventInfos.Count.ShouldBe(1);
bag.DefaultMessage.EventInfos[0].EventName.ShouldBe("test");
}
[Fact]
public virtual async Task Should_Not_Insert_Barrier_As_Rollback_If_Trans_Succeeded()
{
IDtmMessageInfoModel messageInfoModel;
using (var uow = UnitOfWorkManager.Begin(new AbpUnitOfWorkOptions(true)))
{
await DistributedEventBus.PublishAsync(new TestEto());
var dtmUow = uow as TestDtmUnitOfWork;
dtmUow.ShouldNotBeNull();
await uow.CompleteAsync();
uow.IsCompleted.ShouldBeTrue();
var bag = dtmUow.GetDtmOutboxEventBag();
bag.HasAnyEvent().ShouldBeTrue();
bag.TransMessages.Count.ShouldBe(1);
messageInfoModel = bag.TransMessages.First().Value;
}
await WithUnitOfWorkAsync(async () =>
{
var dbContextProvider = ServiceProvider.GetRequiredService<IMongoDbContextProvider<DtmTestMongoDbContext>>();
var dbContext = await dbContextProvider.GetDbContextAsync();
(await DtmMsgBarrierManager.TryInsertBarrierAsRollbackAsync(dbContext, messageInfoModel.Gid)).ShouldBe(false);
});
}
[Fact]
public virtual async Task Should_Insert_Barrier_As_Rollback_If_Trans_Rolled_Back()
{
IDtmMessageInfoModel messageInfoModel;
using (var uow = UnitOfWorkManager.Begin(new AbpUnitOfWorkOptions(true)))
{
await DistributedEventBus.PublishAsync(new TestEto());
var dtmUow = uow as TestDtmUnitOfWork;
dtmUow.ShouldNotBeNull();
dtmUow.ThrowIfCommit = true;
var exception = await Should.ThrowAsync<AbpException>(() => uow.CompleteAsync());
exception.Message.ShouldBe("bye");
uow.IsCompleted.ShouldBeFalse();
var bag = dtmUow.GetDtmOutboxEventBag();
bag.HasAnyEvent().ShouldBeTrue();
bag.TransMessages.Count.ShouldBe(1);
messageInfoModel = bag.TransMessages.First().Value;
}
await WithUnitOfWorkAsync(async () =>
{
var dbContextProvider = ServiceProvider.GetRequiredService<IMongoDbContextProvider<DtmTestMongoDbContext>>();
var dbContext = await dbContextProvider.GetDbContextAsync();
(await DtmMsgBarrierManager.TryInsertBarrierAsRollbackAsync(dbContext, messageInfoModel.Gid)).ShouldBe(true);
});
}
[Fact]
public virtual async Task Should_Support_Multi_Database()
{
IDtmMessageInfoModel messageInfoModel;
IDtmMessageInfoModel messageInfoModel2;
using (var uow = UnitOfWorkManager.Begin(new AbpUnitOfWorkOptions(true)))
{
await DistributedEventBus.PublishAsync(new TestEto());
await DistributedEventBus.PublishAsync(new Test2Eto());
var dtmUow = uow as TestDtmUnitOfWork;
dtmUow.ShouldNotBeNull();
await uow.CompleteAsync();
uow.IsCompleted.ShouldBeTrue();
var bag = dtmUow.GetDtmOutboxEventBag();
bag.HasAnyEvent().ShouldBeTrue();
bag.TransMessages.Count.ShouldBe(2);
messageInfoModel = bag.TransMessages
.First(x => x.Value.DbConnectionLookupInfo.DbContextType == typeof(DtmTestMongoDbContext)).Value;
messageInfoModel2 = bag.TransMessages
.First(x => x.Value.DbConnectionLookupInfo.DbContextType == typeof(DtmTestMongoDbContext2)).Value;
}
await WithUnitOfWorkAsync(async () =>
{
var dbContextProvider = ServiceProvider.GetRequiredService<IMongoDbContextProvider<DtmTestMongoDbContext>>();
var dbContext = await dbContextProvider.GetDbContextAsync();
var dbContextProvider2 = ServiceProvider.GetRequiredService<IMongoDbContextProvider<DtmTestMongoDbContext2>>();
var dbContext2 = await dbContextProvider2.GetDbContextAsync();
(await DtmMsgBarrierManager.TryInsertBarrierAsRollbackAsync(dbContext, messageInfoModel.Gid)).ShouldBe(false);
(await DtmMsgBarrierManager.TryInsertBarrierAsRollbackAsync(dbContext2, messageInfoModel2.Gid)).ShouldBe(false);
});
}
}

2
test/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB.Tests/MongoDB/DtmTestMongoDbContext.cs

@ -3,7 +3,7 @@ using Volo.Abp.MongoDB;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB;
[ConnectionStringName("Default")]
[ConnectionStringName("Dtm")]
public class DtmTestMongoDbContext : AbpMongoDbContext
{
/* Add mongo collections here. Example:

19
test/EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB.Tests/MongoDB/DtmTestMongoDbContext2.cs

@ -0,0 +1,19 @@
using Volo.Abp.Data;
using Volo.Abp.MongoDB;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm.MongoDB;
[ConnectionStringName("Dtm2")]
public class DtmTestMongoDbContext2 : AbpMongoDbContext
{
/* Add mongo collections here. Example:
* public IMongoCollection<Question> Questions => Collection<Question>();
*/
protected override void CreateModel(IMongoModelBuilder modelBuilder)
{
base.CreateModel(modelBuilder);
modelBuilder.ConfigureDtmTest();
}
}

6
test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/AbpEventBusBoxesDtmTestBaseModule.cs

@ -1,10 +1,12 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Volo.Abp;
using Volo.Abp.Authorization;
using Volo.Abp.Autofac;
using Volo.Abp.Data;
using Volo.Abp.Modularity;
using Volo.Abp.Threading;
using Volo.Abp.Uow;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm;
@ -21,6 +23,10 @@ public class AbpEventBusBoxesDtmTestBaseModule : AbpModule
context.Services.AddAlwaysAllowAuthorization();
context.Services.AddDtmBoxes();
context.Services.TryAddTransient<TestDtmUnitOfWork>();
context.Services.Replace(ServiceDescriptor.Transient<IUnitOfWork, TestDtmUnitOfWork>());
context.Services.Replace(ServiceDescriptor.Transient<DtmUnitOfWork, TestDtmUnitOfWork>());
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)

1
test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/DtmDbProperties.cs

@ -7,4 +7,5 @@ public static class DtmDbProperties
public static string DbSchema { get; set; } = null;
public const string ConnectionStringName = "Dtm";
public const string ConnectionString2Name = "Dtm2";
}

6
test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/FakeDistributedEventBus.cs

@ -65,12 +65,12 @@ public class FakeDistributedEventBus : DistributedEventBusBase, ITransientDepend
public override async Task PublishFromOutboxAsync(OutgoingEventInfo outgoingEvent, OutboxConfig outboxConfig)
{
throw new NotSupportedException();
await Task.CompletedTask;
}
public override async Task PublishManyFromOutboxAsync(IEnumerable<OutgoingEventInfo> outgoingEvents, OutboxConfig outboxConfig)
{
throw new NotSupportedException();
await Task.CompletedTask;
}
public override async Task ProcessFromInboxAsync(IncomingEventInfo incomingEvent, InboxConfig inboxConfig)
@ -80,6 +80,6 @@ public class FakeDistributedEventBus : DistributedEventBusBase, ITransientDepend
protected override byte[] Serialize(object eventData)
{
throw new NotSupportedException();
return null;
}
}

27
test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/FakeDtmMessageInfoModel.cs

@ -0,0 +1,27 @@
using System.Collections.Generic;
using EasyAbp.Abp.EventBus.Boxes.Dtm.Models;
using JetBrains.Annotations;
using Volo.Abp.EventBus.Distributed;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm;
public class FakeDtmMessageInfoModel : IDtmMessageInfoModel
{
public bool EventsPublishingActionAdded { get; }
public string Gid { get; set; }
public object DtmMessage { get; set; }
public DbConnectionLookupInfoModel DbConnectionLookupInfo { get; }
public List<OutgoingEventInfo> EventInfos { get; } = new();
public FakeDtmMessageInfoModel(string gid, object dtmMessage,
[NotNull] DbConnectionLookupInfoModel dbConnectionLookupInfo)
{
Gid = gid;
DtmMessage = dtmMessage;
DbConnectionLookupInfo = dbConnectionLookupInfo;
}
}

57
test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/FakeDtmMessageManager.cs

@ -1,45 +1,57 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using EasyAbp.Abp.EventBus.Boxes.Dtm.Models;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm;
public class FakeDtmMessageManager : IDtmMessageManager, ITransientDependency
{
protected ICurrentTenant CurrentTenant { get; }
protected IServiceProvider ServiceProvider { get; }
protected IDtmMsgGidProvider GidProvider { get; }
protected IUnitOfWorkManager UnitOfWorkManager { get; }
protected IConnectionStringHasher ConnectionStringHasher { get; }
protected IConnectionStringResolver ConnectionStringResolver { get; }
public FakeDtmMessageManager(
ICurrentTenant currentTenant,
IServiceProvider serviceProvider,
IDtmMsgGidProvider gidProvider,
IUnitOfWorkManager unitOfWorkManager,
IConnectionStringHasher connectionStringHasher,
IConnectionStringResolver connectionStringResolver)
{
CurrentTenant = currentTenant;
ServiceProvider = serviceProvider;
GidProvider = gidProvider;
UnitOfWorkManager = unitOfWorkManager;
ConnectionStringHasher = connectionStringHasher;
ConnectionStringResolver = connectionStringResolver;
}
public virtual async Task AddEventAsync(DtmOutboxEventBag eventBag, object dbContext, string connectionString,
object transObj, OutgoingEventInfo eventInfo)
{
await Task.CompletedTask;
var dbContextType = dbContext.GetType();
var hashedConnectionString = await ConnectionStringHasher.HashAsync(connectionString);
var model = GetOrCreateDtmMessageInfoModel(eventBag, transObj, dbContextType, hashedConnectionString);
model.EventInfos.Add(eventInfo);
}
public async Task InsertBarriersAndPrepareAsync(DtmOutboxEventBag eventBag,
CancellationToken cancellationToken = default)
{
await Task.CompletedTask;
}
public virtual async Task SubmitAsync(DtmOutboxEventBag eventBag, CancellationToken cancellationToken = default)
{
// await AddEventsPublishingActionAsync(eventBag);
@ -50,10 +62,16 @@ public class FakeDtmMessageManager : IDtmMessageManager, ITransientDependency
// await PrepareTransMessagesAsync(eventBag, cancellationToken);
await InsertTransMessagesBarriersAsync(eventBag);
await InsertTransMessagesBarriersAsync(eventBag, cancellationToken);
}
public virtual async Task SubmitAsync(DtmOutboxEventBag eventBag, CancellationToken cancellationToken = default)
{
await Task.CompletedTask;
}
protected virtual async Task InsertTransMessagesBarriersAsync(DtmOutboxEventBag eventBag)
protected virtual async Task InsertTransMessagesBarriersAsync(DtmOutboxEventBag eventBag,
CancellationToken cancellationToken = default)
{
foreach (var model in eventBag.TransMessages.Values)
{
@ -65,7 +83,7 @@ public class FakeDtmMessageManager : IDtmMessageManager, ITransientDependency
foreach (var barrierManager in barrierManagers)
{
if (await barrierManager.TryInvokeEnsureInsertBarrierAsync(databaseApi, model.Gid))
if (await barrierManager.TryInvokeEnsureInsertBarrierAsync(databaseApi, model.Gid, cancellationToken))
{
inserted = true;
break;
@ -92,4 +110,25 @@ public class FakeDtmMessageManager : IDtmMessageManager, ITransientDependency
return databaseApi;
}
protected virtual IDtmMessageInfoModel GetOrCreateDtmMessageInfoModel(DtmOutboxEventBag eventBag,
[CanBeNull] object transObj, Type dbContextType, string hashedConnectionString)
{
if (transObj is null)
{
return eventBag.DefaultMessage ?? (eventBag.DefaultMessage =
CreateDtmMessageInfoModel(dbContextType, hashedConnectionString));
}
return eventBag.TransMessages.GetOrAdd(transObj,
_ => CreateDtmMessageInfoModel(dbContextType, hashedConnectionString));
}
protected virtual IDtmMessageInfoModel CreateDtmMessageInfoModel(Type dbContextType, string hashedConnectionString)
{
var gid = GidProvider.Create();
return new FakeDtmMessageInfoModel(gid, null,
new DbConnectionLookupInfoModel(dbContextType, CurrentTenant.Id, hashedConnectionString));
}
}

11
test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/Test2Eto.cs

@ -0,0 +1,11 @@
using System;
using Volo.Abp.EventBus;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm;
[EventName("test2")]
[Serializable]
public class Test2Eto
{
public string Content { get; set; }
}

47
test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/TestDtmUnitOfWork.cs

@ -0,0 +1,47 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Volo.Abp;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Uow;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm;
[ExposeServices(typeof(TestDtmUnitOfWork), typeof(DtmUnitOfWork), typeof(IUnitOfWork))]
public class TestDtmUnitOfWork : DtmUnitOfWork
{
public bool ThrowIfCommit { get; set; }
public TestDtmUnitOfWork(IServiceProvider serviceProvider, IDtmMessageManager dtmMessageManager,
IUnitOfWorkEventPublisher unitOfWorkEventPublisher, IOptions<AbpUnitOfWorkDefaultOptions> options) : base(
serviceProvider, dtmMessageManager, unitOfWorkEventPublisher, options)
{
}
protected override async Task CommitTransactionsAsync()
{
if (!EventBag.HasAnyEvent())
{
foreach (var transaction in GetAllActiveTransactionApis())
{
await transaction.CommitAsync();
}
return;
}
OnCompleted(async () => await DtmMessageManager.SubmitAsync(EventBag));
await DtmMessageManager.InsertBarriersAndPrepareAsync(EventBag);
if (ThrowIfCommit)
{
throw new AbpException("bye");
}
foreach (var transaction in GetAllActiveTransactionApis())
{
await transaction.CommitAsync();
}
}
}

11
test/EasyAbp.Abp.EventBus.Boxes.Dtm.TestBase/TestEto.cs

@ -0,0 +1,11 @@
using System;
using Volo.Abp.EventBus;
namespace EasyAbp.Abp.EventBus.Boxes.Dtm;
[EventName("test")]
[Serializable]
public class TestEto
{
public string Content { get; set; }
}
Loading…
Cancel
Save