|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Cleipnir.ResilientFunctions.CoreRuntime; |
| 7 | +using Cleipnir.ResilientFunctions.CoreRuntime.Watchdogs; |
| 8 | +using Cleipnir.ResilientFunctions.Domain; |
| 9 | +using Cleipnir.ResilientFunctions.Domain.Exceptions; |
| 10 | +using Cleipnir.ResilientFunctions.Messaging; |
| 11 | +using Cleipnir.ResilientFunctions.Storage; |
| 12 | +using Cleipnir.ResilientFunctions.Tests.Utils; |
| 13 | +using Microsoft.VisualStudio.TestTools.UnitTesting; |
| 14 | +using Shouldly; |
| 15 | + |
| 16 | +namespace Cleipnir.ResilientFunctions.Tests.Messaging.InMemoryTests; |
| 17 | + |
| 18 | +[TestClass] |
| 19 | +public class MessageClearerTests |
| 20 | +{ |
| 21 | + private static readonly TimeSpan MaxWait = TimeSpan.FromSeconds(10); |
| 22 | + |
| 23 | + [TestMethod] |
| 24 | + public async Task ClearCoalescesCallsArrivingWhileADeleteIsInFlight() |
| 25 | + { |
| 26 | + var firstDeleteReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
| 27 | + var releaseFirstDelete = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
| 28 | + var callCount = 0; |
| 29 | + |
| 30 | + var store = new ControllableMessageStore(async _ => |
| 31 | + { |
| 32 | + if (Interlocked.Increment(ref callCount) == 1) |
| 33 | + { |
| 34 | + firstDeleteReached.SetResult(); |
| 35 | + await releaseFirstDelete.Task; |
| 36 | + } |
| 37 | + }); |
| 38 | + var clearer = CreateClearer(store); |
| 39 | + |
| 40 | + // First call starts the drain and blocks inside DeleteMessages. |
| 41 | + var first = clearer.Clear([1]); |
| 42 | + await firstDeleteReached.Task.WaitAsync(MaxWait); |
| 43 | + |
| 44 | + // These arrive mid-flight, so they should be batched into a single follow-up delete. |
| 45 | + var second = clearer.Clear([2]); |
| 46 | + var third = clearer.Clear([3]); |
| 47 | + |
| 48 | + releaseFirstDelete.SetResult(); |
| 49 | + await Task.WhenAll(first, second, third).WaitAsync(MaxWait); |
| 50 | + |
| 51 | + store.DeletedBatches.Count.ShouldBe(2); |
| 52 | + store.DeletedBatches[0].ShouldBe(new long[] { 1 }); |
| 53 | + store.DeletedBatches[1].OrderBy(p => p).ShouldBe(new long[] { 2, 3 }); |
| 54 | + } |
| 55 | + |
| 56 | + [TestMethod] |
| 57 | + public async Task ClearRetriesUntilDeleteSucceedsAndNotifiesEachFailure() |
| 58 | + { |
| 59 | + var unhandledLock = new Lock(); |
| 60 | + var unhandled = new List<FrameworkException>(); |
| 61 | + var failuresRemaining = 3; |
| 62 | + |
| 63 | + var store = new ControllableMessageStore(_ => |
| 64 | + Interlocked.Decrement(ref failuresRemaining) >= 0 |
| 65 | + ? throw new InvalidOperationException("boom") |
| 66 | + : Task.CompletedTask |
| 67 | + ); |
| 68 | + var clearer = CreateClearer( |
| 69 | + store, |
| 70 | + onUnhandledException: e => { lock (unhandledLock) unhandled.Add(e); }, |
| 71 | + retryDelay: TimeSpan.FromMilliseconds(10) |
| 72 | + ); |
| 73 | + |
| 74 | + // Despite the first three deletes throwing, the caller's task completes (it is never faulted). |
| 75 | + await clearer.Clear([1]).WaitAsync(MaxWait); |
| 76 | + |
| 77 | + store.DeletedPositions.ShouldContain(1L); |
| 78 | + lock (unhandledLock) |
| 79 | + { |
| 80 | + unhandled.Count.ShouldBe(3); |
| 81 | + unhandled.ShouldAllBe(e => e.InnerException is InvalidOperationException); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + [TestMethod] |
| 86 | + public async Task ClearCompletesEveryCallerUnderConcurrentLoad() |
| 87 | + { |
| 88 | + var store = new ControllableMessageStore(_ => Task.CompletedTask); |
| 89 | + var clearer = CreateClearer(store); |
| 90 | + |
| 91 | + var tasks = Enumerable |
| 92 | + .Range(0, 200) |
| 93 | + .Select(i => clearer.Clear([i])) |
| 94 | + .ToArray(); |
| 95 | + |
| 96 | + await Task.WhenAll(tasks).WaitAsync(MaxWait); |
| 97 | + |
| 98 | + store.DeletedPositions.OrderBy(p => p).ShouldBe(Enumerable.Range(0, 200).Select(i => (long)i)); |
| 99 | + } |
| 100 | + |
| 101 | + [TestMethod] |
| 102 | + public async Task ClearRemovesPositionsFromIgnoreSetOnceDeleted() |
| 103 | + { |
| 104 | + var store = new ControllableMessageStore(_ => Task.CompletedTask); |
| 105 | + var clearer = CreateClearer(store); |
| 106 | + |
| 107 | + clearer.MarkPushed([1, 2, 3]); |
| 108 | + clearer.NonClearedPositions().OrderBy(p => p).ShouldBe(new long[] { 1, 2, 3 }); |
| 109 | + |
| 110 | + await clearer.Clear([2]).WaitAsync(MaxWait); |
| 111 | + |
| 112 | + clearer.NonClearedPositions().OrderBy(p => p).ShouldBe(new long[] { 1, 3 }); |
| 113 | + } |
| 114 | + |
| 115 | + [TestMethod] |
| 116 | + public async Task ClearedPositionsAreGoneFromTheStoreWhenTheReturnedTaskCompletes() |
| 117 | + { |
| 118 | + var functionStore = new InMemoryFunctionStore(); |
| 119 | + var messageStore = functionStore.MessageStore; |
| 120 | + var storedId = TestStoredId.Create(); |
| 121 | + |
| 122 | + await messageStore.AppendMessages([ |
| 123 | + new StoredIdAndMessage(storedId, Message()), |
| 124 | + new StoredIdAndMessage(storedId, Message()), |
| 125 | + new StoredIdAndMessage(storedId, Message()) |
| 126 | + ]); |
| 127 | + var positions = (await messageStore.GetMessages(storedId)).Select(m => m.Position).ToList(); |
| 128 | + positions.Count.ShouldBe(3); |
| 129 | + |
| 130 | + var clearer = CreateClearer(messageStore); |
| 131 | + await clearer.Clear(positions.Take(2).ToList()).WaitAsync(MaxWait); |
| 132 | + |
| 133 | + // The instant Clear's task completes, the cleared messages must already be gone from the store. |
| 134 | + var remaining = (await messageStore.GetMessages(storedId)).Select(m => m.Position).ToList(); |
| 135 | + remaining.ShouldBe(new[] { positions[2] }); |
| 136 | + } |
| 137 | + |
| 138 | + private static StoredMessage Message() |
| 139 | + => new(MessageContent: new byte[] { 1 }, MessageType: new byte[] { 2 }, Position: 0, Replica: ReplicaId.Empty); |
| 140 | + |
| 141 | + private static MessageClearer CreateClearer( |
| 142 | + IMessageStore messageStore, |
| 143 | + Action<FrameworkException>? onUnhandledException = null, |
| 144 | + TimeSpan? retryDelay = null) |
| 145 | + => new( |
| 146 | + messageStore, |
| 147 | + new UnhandledExceptionHandler(onUnhandledException ?? (_ => { })), |
| 148 | + retryDelay ?? TimeSpan.FromSeconds(1) |
| 149 | + ); |
| 150 | + |
| 151 | + // Minimal IMessageStore that only implements the positions-only DeleteMessages (the sole method |
| 152 | + // MessageClearer touches); every other member is irrelevant to these tests. |
| 153 | + private sealed class ControllableMessageStore(Func<IReadOnlyList<long>, Task> onDelete) : IMessageStore |
| 154 | + { |
| 155 | + private readonly Lock _lock = new(); |
| 156 | + public List<long[]> DeletedBatches { get; } = new(); |
| 157 | + public IEnumerable<long> DeletedPositions => DeletedBatches.SelectMany(b => b); |
| 158 | + |
| 159 | + public async Task DeleteMessages(IReadOnlyList<long> positions) |
| 160 | + { |
| 161 | + var batch = positions.ToArray(); |
| 162 | + lock (_lock) |
| 163 | + DeletedBatches.Add(batch); |
| 164 | + await onDelete(batch); |
| 165 | + } |
| 166 | + |
| 167 | + public Task Initialize() => throw new NotSupportedException(); |
| 168 | + public Task AppendMessages(IReadOnlyList<StoredIdAndMessage> messages) => throw new NotSupportedException(); |
| 169 | + public Task<bool> ReplaceMessage(StoredId storedId, long position, StoredMessage storedMessage) => throw new NotSupportedException(); |
| 170 | + public Task DeleteMessages(StoredId storedId, IEnumerable<long> positions) => throw new NotSupportedException(); |
| 171 | + public Task Truncate(StoredId storedId) => throw new NotSupportedException(); |
| 172 | + public Task<IReadOnlyList<StoredMessage>> GetMessages(StoredId storedId) => throw new NotSupportedException(); |
| 173 | + public Task<IReadOnlyList<StoredMessage>> GetMessages(StoredId storedId, IReadOnlyList<long> skipPositions) => throw new NotSupportedException(); |
| 174 | + public Task<Dictionary<StoredId, List<StoredMessage>>> GetMessages(IEnumerable<StoredId> storedIds) => throw new NotSupportedException(); |
| 175 | + public Task<List<StoredMessages>> GetMessagesForReplica(ReplicaId replicaId, IReadOnlyList<long> ignorePositions) => throw new NotSupportedException(); |
| 176 | + public Task<List<StoredIdAndPosition>> GetCrashedReplicaMessages(IReadOnlySet<ReplicaId> liveReplicas) => throw new NotSupportedException(); |
| 177 | + public Task SetReplica(IEnumerable<long> positions, ReplicaId newReplica, ReplicaId expectedReplica) => throw new NotSupportedException(); |
| 178 | + } |
| 179 | +} |
0 commit comments