|
| 1 | +using Alba; |
| 2 | +using IntegrationTests; |
| 3 | +using JasperFx; |
| 4 | +using JasperFx.CodeGeneration; |
| 5 | +using JasperFx.Core.Reflection; |
| 6 | +using Marten; |
| 7 | +using Microsoft.AspNetCore.Builder; |
| 8 | +using Microsoft.EntityFrameworkCore; |
| 9 | +using Microsoft.Extensions.DependencyInjection; |
| 10 | +using Shouldly; |
| 11 | +using Wolverine.EntityFrameworkCore; |
| 12 | +using Wolverine.Marten; |
| 13 | +using Wolverine.Persistence; |
| 14 | +using WolverineWebApi; |
| 15 | +using Xunit; |
| 16 | + |
| 17 | +namespace Wolverine.Http.Tests; |
| 18 | + |
| 19 | +// Reproducer for GH-3291. A Wolverine.Http endpoint has no incoming envelope, so (unlike a message |
| 20 | +// handler, whose MessageContext is enlisted in the outbox by ReadEnvelope at runtime) its |
| 21 | +// MessageContext.Transaction stays null. In TransactionMiddlewareMode.Lightweight the EF Core |
| 22 | +// transaction middleware does NOT enroll the endpoint's DbContext/context in the outbox, so |
| 23 | +// MessageBus.PersistOrSendAsync takes the StoreAndForwardAsync() (send-now) branch and the cascaded |
| 24 | +// message is sent BEFORE the SaveChangesAsync postprocessor commits - silently dropping the |
| 25 | +// transactional-outbox guarantee the HTTP docs advertise. Message handlers are unaffected in both |
| 26 | +// modes; the bug is specific to HTTP endpoints in Lightweight mode. |
| 27 | +// |
| 28 | +// Like the sibling Eager-mode reproducer (Bug_efcore_outbox_flush_before_commit), we assert at the |
| 29 | +// codegen surface rather than at runtime: the runtime symptom (a stranded wolverine_outgoing row) is |
| 30 | +// cleaned up by the durability agent within ~250ms and races any post-request query. The generated |
| 31 | +// composition is the deterministic proof. |
| 32 | +// |
| 33 | +// Pre-fix state (the bug): the Lightweight HTTP chain carries a standalone FlushOutgoingMessages |
| 34 | +// postprocessor as its ONLY flush trigger, and its MessageContext is never enlisted, so the generated |
| 35 | +// code never calls EnlistInOutboxAsync. Fixed state: the chain enlists the DbContext in the outbox |
| 36 | +// WITHOUT an explicit BeginTransactionAsync (an IFlushesMessages middleware -> no standalone |
| 37 | +// FlushOutgoingMessages), and the buffered messages are flushed after the commit. |
| 38 | +public class Bug_3291_lightweight_http_cascade_flushes_before_commit |
| 39 | +{ |
| 40 | + private static async Task<IAlbaHost> buildLightweightHostAsync() |
| 41 | + { |
| 42 | + var schema = "ef_lw_" + Guid.NewGuid().ToString("N")[..8]; |
| 43 | + var builder = WebApplication.CreateBuilder(); |
| 44 | + |
| 45 | + // Wolverine-integrated DbContext supplies the outbox enrollment for EF Core (mirrors the |
| 46 | + // AddDbContextWithWolverineIntegration setup the issue reports). |
| 47 | + builder.Services.AddDbContextWithWolverineIntegration<ItemsDbContext>(x => |
| 48 | + x.UseNpgsql(Servers.PostgresConnectionString)); |
| 49 | + |
| 50 | + builder.Host.UseWolverine(opts => |
| 51 | + { |
| 52 | + opts.Durability.Mode = DurabilityMode.Solo; |
| 53 | + |
| 54 | + opts.Services.AddMarten(m => |
| 55 | + { |
| 56 | + m.Connection(Servers.PostgresConnectionString); |
| 57 | + m.DatabaseSchemaName = schema; |
| 58 | + }).IntegrateWithWolverine(); |
| 59 | + |
| 60 | + // The bug is specific to Lightweight mode. Eager already works (see the sibling reproducer). |
| 61 | + opts.UseEntityFrameworkCoreTransactions(TransactionMiddlewareMode.Lightweight); |
| 62 | + |
| 63 | + opts.Policies.AutoApplyTransactions(); |
| 64 | + opts.Policies.UseDurableLocalQueues(); |
| 65 | + |
| 66 | + opts.Discovery.DisableConventionalDiscovery(); |
| 67 | + // The cascaded ItemCreated needs a routed handler so it actually buffers into Outstanding. |
| 68 | + opts.Discovery.IncludeType<LightweightCascadeItemCreatedHandler>(); |
| 69 | + opts.Discovery.IncludeAssembly(typeof(Bug_3291_lightweight_http_cascade_flushes_before_commit).Assembly); |
| 70 | + }); |
| 71 | + |
| 72 | + builder.Services.AddWolverineHttp(); |
| 73 | + |
| 74 | + return await AlbaHost.For(builder, app => app.MapWolverineEndpoints()); |
| 75 | + } |
| 76 | + |
| 77 | + [Fact] |
| 78 | + public async Task lightweight_http_endpoint_enlists_outbox_and_does_not_flush_before_commit() |
| 79 | + { |
| 80 | + await using var host = await buildLightweightHostAsync(); |
| 81 | + |
| 82 | + var graph = host.Services.GetRequiredService<WolverineHttpOptions>().Endpoints!; |
| 83 | + var chain = graph.ChainFor("POST", "/ef/lightweight/publish"); |
| 84 | + chain.ShouldNotBeNull(); |
| 85 | + |
| 86 | + // (1) No standalone pre-commit flush. Pre-fix, applyEagerCommitOrLightweightFlush adds a |
| 87 | + // FlushOutgoingMessages postprocessor that (because the context is never enlisted) runs the |
| 88 | + // send BEFORE SaveChangesAsync commits. Fixed, the enlist middleware is IFlushesMessages, so |
| 89 | + // this standalone flush is gone and the commit path does the post-commit flush instead. |
| 90 | + chain.Postprocessors.OfType<FlushOutgoingMessages>().ShouldBeEmpty( |
| 91 | + "GH-3291: a Lightweight-mode HTTP endpoint that cascades messages still has a standalone " + |
| 92 | + "FlushOutgoingMessages postprocessor. Its MessageContext is never enlisted in the outbox, " + |
| 93 | + "so the cascade is sent before SaveChangesAsync commits."); |
| 94 | + |
| 95 | + // (2) The generated code must enlist the DbContext + IMessageContext in the outbox so the |
| 96 | + // cascade buffers and flushes after commit. Pre-fix this call is absent. |
| 97 | + // GH-3291: pre-fix the Lightweight HTTP endpoint never enrolls its DbContext/context in the |
| 98 | + // outbox, so cascaded messages are sent immediately instead of buffered until after the commit. |
| 99 | + chain.As<ICodeFile>().InitializeSynchronously(graph.Rules, graph, host.Services); |
| 100 | + var source = chain!.SourceCode; |
| 101 | + source.ShouldNotBeNull(); |
| 102 | + source.ShouldContain("EnlistInOutboxAsync"); |
| 103 | + |
| 104 | + // (3) Ordering: enroll in the outbox -> [endpoint body] -> SaveChangesAsync commits -> the |
| 105 | + // envelope transaction's CommitAsync flushes the buffered messages. The flush must come AFTER |
| 106 | + // the commit; that is the whole point of the fix. |
| 107 | + // Match the actual call sites (".Method(") rather than bare names, which also appear in comments. |
| 108 | + var enlistAt = source.IndexOf(".EnlistInOutboxAsync(", StringComparison.Ordinal); |
| 109 | + var saveAt = source.IndexOf(".SaveChangesAsync(", StringComparison.Ordinal); |
| 110 | + var commitAt = source.IndexOf(".CommitAsync(", StringComparison.Ordinal); |
| 111 | + |
| 112 | + saveAt.ShouldBeGreaterThan(enlistAt, "SaveChangesAsync must run after the outbox enrollment"); |
| 113 | + commitAt.ShouldBeGreaterThan(saveAt, |
| 114 | + "The outbox flush (EfCoreEnvelopeTransaction.CommitAsync) must run after SaveChangesAsync commits"); |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +public static class LightweightEfCascadeEndpoint |
| 119 | +{ |
| 120 | + // Writes an entity AND cascades a message: the exact shape from the GH-3291 report. In Lightweight |
| 121 | + // mode the cascade must not be sent until SaveChangesAsync commits the item. |
| 122 | + [WolverinePost("/ef/lightweight/publish")] |
| 123 | + public static async Task Publish(CreateItemCommand command, ItemsDbContext db, IMessageBus bus) |
| 124 | + { |
| 125 | + var item = new Item { Name = command.Name }; |
| 126 | + db.Items.Add(item); |
| 127 | + await bus.PublishAsync(new ItemCreated { Id = item.Id }); |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +// A routed handler so the cascaded ItemCreated has somewhere to go (durable local queue). Body is |
| 132 | +// irrelevant — the test asserts the outbox enrollment/flush composition, not the handling. |
| 133 | +public class LightweightCascadeItemCreatedHandler |
| 134 | +{ |
| 135 | + public void Handle(ItemCreated _) |
| 136 | + { |
| 137 | + } |
| 138 | +} |
0 commit comments