|
| 1 | +using Microsoft.Extensions.DependencyInjection; |
| 2 | +using Mocha.Events; |
| 3 | +using Mocha.Features; |
| 4 | +using Mocha.Middlewares; |
| 5 | +using Mocha.Transport.InMemory; |
| 6 | + |
| 7 | +namespace Mocha.Sagas.Tests; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Characterizes the publish leg of saga fault handling. A published event carries no reply address, |
| 11 | +/// so a failing subscriber is routed to the error endpoint rather than back to the saga. |
| 12 | +/// </summary> |
| 13 | +public class SagaPublishFaultTests |
| 14 | +{ |
| 15 | + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); |
| 16 | + |
| 17 | + private static readonly TaskCompletionSource<NotAcknowledgedEvent> s_faultObserved = new(); |
| 18 | + |
| 19 | + [Fact] |
| 20 | + public async Task Saga_Should_NotReceiveFault_When_PublishedEventSubscriberFaults() |
| 21 | + { |
| 22 | + // arrange |
| 23 | + var handlerRan = new TaskCompletionSource(); |
| 24 | + var services = new ServiceCollection(); |
| 25 | + services.AddInMemorySagas(); |
| 26 | + var builder = services.AddMessageBus(); |
| 27 | + builder.Services.AddSingleton(handlerRan); |
| 28 | + builder.AddEventHandler<FaultingSubscriber>(); |
| 29 | + builder.AddSaga<PublishingSaga>(); |
| 30 | + builder.AddInMemory(); |
| 31 | + |
| 32 | + await using var provider = services.BuildServiceProvider(); |
| 33 | + var runtime = (MessagingRuntime)provider.GetRequiredService<IMessagingRuntime>(); |
| 34 | + await runtime.StartAsync(CancellationToken.None); |
| 35 | + |
| 36 | + using var scope = provider.CreateScope(); |
| 37 | + var bus = scope.ServiceProvider.GetRequiredService<IMessageBus>(); |
| 38 | + var storage = provider.GetRequiredService<InMemorySagaStateStorage>(); |
| 39 | + |
| 40 | + // act |
| 41 | + await bus.PublishAsync(new StartPublishEvent(), CancellationToken.None); |
| 42 | + |
| 43 | + // assert - the subscriber ran and threw, proving the published event was delivered |
| 44 | + await handlerRan.Task.WaitAsync(s_timeout, TestContext.Current.CancellationToken); |
| 45 | + |
| 46 | + // assert - the saga is never told, so it stays in its waiting state holding its state |
| 47 | + var completed = await Task.WhenAny(s_faultObserved.Task, Task.Delay(2000, TestContext.Current.CancellationToken)); |
| 48 | + Assert.NotSame(s_faultObserved.Task, completed); |
| 49 | + Assert.Equal(1, storage.Count); |
| 50 | + } |
| 51 | + |
| 52 | + [Fact] |
| 53 | + public async Task ErrorEndpoint_Should_ReceiveSagaId_When_PublishedEventSubscriberFaults() |
| 54 | + { |
| 55 | + // The fault carries the original envelope, so the saga header survives onto the error |
| 56 | + // endpoint even though the saga itself is never notified. |
| 57 | + |
| 58 | + // arrange |
| 59 | + var handlerRan = new TaskCompletionSource(); |
| 60 | + var services = new ServiceCollection(); |
| 61 | + services.AddInMemorySagas(); |
| 62 | + var builder = services.AddMessageBus(); |
| 63 | + builder.Services.AddSingleton(handlerRan); |
| 64 | + builder.AddEventHandler<ErrorQueueSubscriber>(); |
| 65 | + builder.AddSaga<ErrorQueuePublishingSaga>(); |
| 66 | + builder.AddInMemory(d => d.AddConvention(new TestErrorEndpointConvention())); |
| 67 | + |
| 68 | + await using var provider = services.BuildServiceProvider(); |
| 69 | + var runtime = (MessagingRuntime)provider.GetRequiredService<IMessagingRuntime>(); |
| 70 | + await runtime.StartAsync(CancellationToken.None); |
| 71 | + |
| 72 | + using var scope = provider.CreateScope(); |
| 73 | + var bus = scope.ServiceProvider.GetRequiredService<IMessageBus>(); |
| 74 | + |
| 75 | + // act |
| 76 | + await bus.PublishAsync(new StartErrorQueueEvent(), CancellationToken.None); |
| 77 | + await handlerRan.Task.WaitAsync(s_timeout, TestContext.Current.CancellationToken); |
| 78 | + |
| 79 | + // assert |
| 80 | + var envelope = await ReadFirstErrorEnvelopeAsync(runtime); |
| 81 | + Assert.Equal(MessageKind.Fault, envelope.Headers!.Get(MessageHeaders.MessageKind)); |
| 82 | + Assert.True(Guid.TryParse(envelope.Headers!.Get(SagaContextData.SagaId), out _)); |
| 83 | + } |
| 84 | + |
| 85 | + /// <summary> |
| 86 | + /// Drains whichever error queue receives a message first, since every default endpoint gets one. |
| 87 | + /// </summary> |
| 88 | + private static async Task<MessageEnvelope> ReadFirstErrorEnvelopeAsync(MessagingRuntime runtime) |
| 89 | + { |
| 90 | + var transport = runtime.Transports.OfType<InMemoryMessagingTransport>().Single(); |
| 91 | + var topology = (InMemoryMessagingTopology)transport.Topology; |
| 92 | + var errorQueues = topology.Queues.Where(q => q.Name.EndsWith("_error")).ToArray(); |
| 93 | + |
| 94 | + using var cts = new CancellationTokenSource(s_timeout); |
| 95 | + |
| 96 | + var reads = errorQueues |
| 97 | + .Select(async queue => |
| 98 | + { |
| 99 | + await foreach (var item in queue.ConsumeAsync(cts.Token)) |
| 100 | + { |
| 101 | + var envelope = new MessageEnvelope(item.Envelope); |
| 102 | + item.Dispose(); |
| 103 | + return envelope; |
| 104 | + } |
| 105 | + |
| 106 | + return null; |
| 107 | + }) |
| 108 | + .ToArray(); |
| 109 | + |
| 110 | + var completed = await Task.WhenAny(reads); |
| 111 | + await cts.CancelAsync(); |
| 112 | + |
| 113 | + return await completed ?? throw new InvalidOperationException("no error envelope was received"); |
| 114 | + } |
| 115 | + |
| 116 | + private sealed class TestErrorEndpointConvention : IInMemoryReceiveEndpointConfigurationConvention |
| 117 | + { |
| 118 | + public void Configure( |
| 119 | + IMessagingConfigurationContext context, |
| 120 | + InMemoryMessagingTransport transport, |
| 121 | + InMemoryReceiveEndpointConfiguration configuration) |
| 122 | + { |
| 123 | + if (configuration is { Kind: ReceiveEndpointKind.Default, QueueName: { } queueName }) |
| 124 | + { |
| 125 | + var feature = configuration.Features.GetOrSet<ReceiveFaultEndpointFeature>(); |
| 126 | + feature.Address ??= new Uri($"{transport.Schema}:q/{queueName}_error"); |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + public sealed class StartErrorQueueEvent; |
| 132 | + |
| 133 | + public sealed record ErrorQueueEvent(Guid Id); |
| 134 | + |
| 135 | + public sealed class ErrorQueueSubscriber(TaskCompletionSource handlerRan) : IEventHandler<ErrorQueueEvent> |
| 136 | + { |
| 137 | + public ValueTask HandleAsync(ErrorQueueEvent message, CancellationToken cancellationToken) |
| 138 | + { |
| 139 | + handlerRan.TrySetResult(); |
| 140 | + throw new InvalidOperationException("terminal failure"); |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + public sealed class ErrorQueuePublishingSaga : Saga<PublishState> |
| 145 | + { |
| 146 | + protected override void Configure(ISagaDescriptor<PublishState> descriptor) |
| 147 | + { |
| 148 | + descriptor |
| 149 | + .Initially() |
| 150 | + .OnEvent<StartErrorQueueEvent>() |
| 151 | + .StateFactory(_ => new PublishState()) |
| 152 | + .Publish((_, state) => new ErrorQueueEvent(state.Id)) |
| 153 | + .TransitionTo("Awaiting"); |
| 154 | + |
| 155 | + descriptor.During("Awaiting").OnReplyFault().TransitionTo("Failed"); |
| 156 | + |
| 157 | + descriptor.Finally("Failed"); |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + public sealed class PublishState : SagaStateBase; |
| 162 | + |
| 163 | + public sealed class StartPublishEvent; |
| 164 | + |
| 165 | + public sealed record PublishedEvent(Guid Id); |
| 166 | + |
| 167 | + public sealed class FaultingSubscriber(TaskCompletionSource handlerRan) : IEventHandler<PublishedEvent> |
| 168 | + { |
| 169 | + public ValueTask HandleAsync(PublishedEvent message, CancellationToken cancellationToken) |
| 170 | + { |
| 171 | + handlerRan.TrySetResult(); |
| 172 | + throw new InvalidOperationException("terminal failure"); |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + public sealed class PublishingSaga : Saga<PublishState> |
| 177 | + { |
| 178 | + protected override void Configure(ISagaDescriptor<PublishState> descriptor) |
| 179 | + { |
| 180 | + descriptor |
| 181 | + .Initially() |
| 182 | + .OnEvent<StartPublishEvent>() |
| 183 | + .StateFactory(_ => new PublishState()) |
| 184 | + .Publish((_, state) => new PublishedEvent(state.Id)) |
| 185 | + .TransitionTo("Awaiting"); |
| 186 | + |
| 187 | + descriptor |
| 188 | + .During("Awaiting") |
| 189 | + .OnReplyFault() |
| 190 | + .Then((_, fault) => s_faultObserved.TrySetResult(fault)) |
| 191 | + .TransitionTo("Failed"); |
| 192 | + |
| 193 | + descriptor.Finally("Failed"); |
| 194 | + } |
| 195 | + } |
| 196 | +} |
0 commit comments