From d01a06465264c7e83c2a7b3a4926b3cc9013681e Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:08:45 +0000 Subject: [PATCH 1/2] [Mocha] Fix scheduled messages using up their attempts while the transport is unavailable --- .../Scheduling/ScheduledMessageDispatcher.cs | 339 +++++++++++++----- .../Scheduling/ScheduledMessageQueries.cs | 10 +- .../Scheduling/ScheduledMessageWorker.cs | 19 +- ...PostgresScheduledMessageDispatcherTests.cs | 227 ++++++++++++ .../migration/migrate-from-16-7-to-16-8.md | 8 + website/content/docs/mocha/scheduling.md | 2 + 6 files changed, 504 insertions(+), 101 deletions(-) create mode 100644 src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs index 78df7cd4304..932ff18a7e9 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs @@ -1,10 +1,12 @@ using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; using Mocha.Middlewares; using Mocha.Outbox; +using Mocha.Threading; using Npgsql; using NpgsqlTypes; @@ -16,12 +18,19 @@ namespace Mocha.Scheduling; /// public sealed class ScheduledMessageDispatcher { + private static readonly TimeSpan s_pauseDelay = TimeSpan.FromMilliseconds(100); + private static readonly TimeSpan s_maxPauseDelay = TimeSpan.FromSeconds(10); + + // The pause before the dispatcher looks again for a due message that another dispatcher holds. + private static readonly TimeSpan s_heldMessagePollingInterval = TimeSpan.FromSeconds(1); + private readonly ILogger _logger; private readonly IServiceProvider _services; private readonly IMessagingRuntime _runtime; private readonly ISchedulerSignal _signal; private readonly ObjectPool _contextPool; private readonly PostgresScheduledMessageOptions _options; + private readonly TimeProvider _timeProvider; /// /// Initializes a new instance of the class. @@ -58,6 +67,7 @@ internal ScheduledMessageDispatcher( _signal = signal; _contextPool = pools.DispatchContext; _options = options; + _timeProvider = services.GetService() ?? TimeProvider.System; } /// @@ -67,22 +77,38 @@ internal ScheduledMessageDispatcher( /// A token that signals when the dispatcher should stop. public async Task ProcessAsync(CancellationToken cancellationToken) { + // The pause before a released message is claimed again, which grows until a message is sent. + var pause = new ExponentialBackoff(int.MaxValue, s_pauseDelay, s_maxPauseDelay); + while (!cancellationToken.IsCancellationRequested) { try { - var nextWakeTime = await ProcessPendingAsync(cancellationToken); + var pass = await ProcessPendingAsync(pause, cancellationToken); - if (nextWakeTime is not null) + if (pass.IsPaused) { - _logger.SchedulerSleepingUntil(nextWakeTime.Value); - await _signal.WaitUntilAsync(nextWakeTime.Value, cancellationToken); + // The released message is claimed again after the pause, with or without a signal. + await pause.WaitAsync(cancellationToken); } - else + else if (pass.SecondsUntilDue is not { } secondsUntilDue) { // No scheduled messages - sleep until notified. await _signal.WaitUntilAsync(DateTimeOffset.MaxValue, cancellationToken); } + else if (secondsUntilDue > 0) + { + var wakeTime = GetWakeTime(secondsUntilDue); + _logger.SchedulerSleepingUntil(wakeTime); + await _signal.WaitUntilAsync(wakeTime, cancellationToken); + } + else + { + // The claim did not return the message that is due, so another dispatcher holds it. + await _signal.WaitUntilAsync( + _timeProvider.GetUtcNow() + s_heldMessagePollingInterval, + cancellationToken); + } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -91,149 +117,221 @@ public async Task ProcessAsync(CancellationToken cancellationToken) } } - private async ValueTask ProcessPendingAsync(CancellationToken cancellationToken) + private DateTimeOffset GetWakeTime(double secondsUntilDue) + { + var now = _timeProvider.GetUtcNow(); + + return secondsUntilDue < (DateTimeOffset.MaxValue - now).TotalSeconds + ? now.AddSeconds(secondsUntilDue) + : DateTimeOffset.MaxValue; + } + + private async ValueTask ProcessPendingAsync( + ExponentialBackoff pause, + CancellationToken cancellationToken) { await using var scope = _services.CreateAsyncScope(); await using var connection = _options.CreateConnection(scope.ServiceProvider); await connection.OpenAsync(cancellationToken); - while (await ProcessMessageAsync(connection, cancellationToken)) + while (true) { cancellationToken.ThrowIfCancellationRequested(); - } - return await GetNextWakeTimeAsync(connection, cancellationToken); + // An exception before the commit rolls the claim back when the transaction is disposed. + await using var transaction = await connection.BeginTransactionAsync(cancellationToken); + + switch (await ProcessMessageAsync(connection, transaction, pause, cancellationToken)) + { + case ClaimResult.Empty: + // The time is read in the transaction of the claim, so that both see the same time. + return new PassResult( + IsPaused: false, + await GetSecondsUntilDueAsync(connection, transaction, cancellationToken)); + + case ClaimResult.Released: + return new PassResult(IsPaused: true, SecondsUntilDue: null); + } + } } - private async Task GetNextWakeTimeAsync( + private async Task GetSecondsUntilDueAsync( NpgsqlConnection connection, + NpgsqlTransaction transaction, CancellationToken cancellationToken) { await using var command = connection.CreateCommand(); - command.CommandText = _options.Queries.NextWakeTime; + command.Transaction = transaction; + command.CommandText = _options.Queries.NextWakeInterval; await command.PrepareAsync(cancellationToken); - var result = await command.ExecuteScalarAsync(cancellationToken); - - return result is not null and not DBNull - ? new DateTimeOffset((DateTime)result, TimeSpan.Zero) - : null; + return await command.ExecuteScalarAsync(cancellationToken) as double?; } - private async Task ProcessMessageAsync(NpgsqlConnection connection, CancellationToken cancellationToken) + private async Task ProcessMessageAsync( + NpgsqlConnection connection, + NpgsqlTransaction transaction, + ExponentialBackoff pause, + CancellationToken cancellationToken) { using var activity = OpenTelemetry.Source.StartActivity( "Process Scheduled Message Event", ActivityKind.Producer, new ActivityContext()); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - try { - await using var command = connection.CreateCommand(); - command.Transaction = transaction; - command.CommandText = _options.Queries.ProcessMessage; + Guid id; + int timesSent; + int maxAttempts; + var outcome = DispatchOutcome.Failed; + Exception? dispatchError = null; - await command.PrepareAsync(cancellationToken); - - try + await using (var command = connection.CreateCommand()) { - await using var reader = await command.ExecuteReaderAsync(cancellationToken); + command.Transaction = transaction; + command.CommandText = _options.Queries.ProcessMessage; - if (await reader.ReadAsync(cancellationToken)) - { - var id = reader.GetGuid(0); - var envelope = Serializer.ReadMessageEnvelopeSafe(reader, 1, _logger); - var timesSent = reader.GetInt32(2); - var maxAttempts = reader.GetInt32(3); - - // A message this instance cannot read or route stays in the table and is - // retried after its backoff. - if (envelope is null) - { - _logger.CouldNotDeserializeScheduledMessageBody(id); - LogIfExhausted(id, timesSent, maxAttempts); + await command.PrepareAsync(cancellationToken); - return true; - } - - var messageType = GetMessageType(envelope.MessageType); - - if (messageType is null) - { - _logger.CouldNotResolveScheduledMessageType(id, envelope.MessageType); - LogIfExhausted(id, timesSent, maxAttempts); - - return true; - } - - var endpoint = ResolveDispatchEndpoint(envelope); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); - if (endpoint is null) - { - _logger.CouldNotDetermineScheduledMessageDestination(id, envelope.DestinationAddress); - LogIfExhausted(id, timesSent, maxAttempts); + if (!await reader.ReadAsync(cancellationToken)) + { + return ClaimResult.Empty; + } - return true; - } + id = reader.GetGuid(0); + var envelope = Serializer.ReadMessageEnvelopeSafe(reader, 1, _logger); + timesSent = reader.GetInt32(2); + maxAttempts = reader.GetInt32(3); + if (TryResolve(id, envelope, out var messageType, out var endpoint)) + { try { await SendAsync(envelope, endpoint, messageType, cancellationToken); - await reader.CloseAsync(); - - await DeleteMessageAsync(connection, id, transaction, cancellationToken); + outcome = DispatchOutcome.Sent; } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) { - _logger.ScheduledMessageDispatchFailed(id, ex); - - await reader.CloseAsync(); - - await UpdateLastErrorAsync(connection, id, ex, transaction, cancellationToken); - - LogIfExhausted(id, timesSent, maxAttempts); + outcome = OnDispatchFailed(ex, id, envelope, cancellationToken); + dispatchError = ex; } - - return true; - } - else - { - return false; } } - finally + + switch (outcome) { - try - { - await transaction.CommitAsync(cancellationToken); - } - catch - { - // Commit failed (e.g., connection lost). Attempt rollback. - // If commit actually succeeded server-side, the message stays - // with times_sent incremented - safe, just causes a retry. - try + case DispatchOutcome.Sent: + // The transport has the message, so its row is removed whatever the token says. + await DeleteMessageAsync(connection, id, transaction, CancellationToken.None); + await transaction.CommitAsync(CancellationToken.None); + pause.Reset(); + return ClaimResult.Processed; + + case DispatchOutcome.Released: + // The rollback restores the attempt count and the due time of the row. + await transaction.RollbackAsync(CancellationToken.None); + return ClaimResult.Released; + + default: + if (dispatchError is not null) { - await transaction.RollbackAsync(CancellationToken.None); + await UpdateLastErrorAsync(connection, id, dispatchError, transaction, cancellationToken); } - catch - { - /* swallow */ - } - } + + // The commit stores the incremented attempt count and the backoff of the row. + await transaction.CommitAsync(cancellationToken); + LogIfExhausted(id, timesSent, maxAttempts); + return ClaimResult.Processed; } } - catch (Exception ex) + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { - // Log only - no RollbackAsync here (commit already handled in finally) _logger.UnexpectedErrorWhileProcessingScheduledMessage(ex); throw; } } + /// + /// Resolves what a dispatch of the message needs, and logs why when the message cannot be dispatched. + /// + private bool TryResolve( + Guid id, + [NotNullWhen(true)] MessageEnvelope? envelope, + [NotNullWhen(true)] out MessageType? messageType, + [NotNullWhen(true)] out DispatchEndpoint? endpoint) + { + messageType = null; + endpoint = null; + + // A message this instance cannot read or route stays in the table and is + // retried after its backoff. + if (envelope is null) + { + _logger.CouldNotDeserializeScheduledMessageBody(id); + return false; + } + + messageType = GetMessageType(envelope.MessageType); + + if (messageType is null) + { + _logger.CouldNotResolveScheduledMessageType(id, envelope.MessageType); + return false; + } + + endpoint = ResolveDispatchEndpoint(envelope); + + if (endpoint is null) + { + _logger.CouldNotDetermineScheduledMessageDestination(id, envelope.DestinationAddress); + return false; + } + + return true; + } + + /// + /// Logs why the dispatch did not complete and returns whether the attempt counts. + /// + private DispatchOutcome OnDispatchFailed( + Exception exception, + Guid id, + MessageEnvelope envelope, + CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + _logger.ScheduledMessageDispatchCancelled( + exception, + id, + envelope.MessageId, + envelope.MessageType, + envelope.DestinationAddress); + + return DispatchOutcome.Released; + } + + if (exception is TransportUnavailableException) + { + _logger.ScheduledMessageTransportUnavailable( + exception, + id, + envelope.MessageId, + envelope.MessageType, + envelope.DestinationAddress); + + return DispatchOutcome.Released; + } + + _logger.ScheduledMessageDispatchFailed(id, exception); + + return DispatchOutcome.Failed; + } + private void LogIfExhausted(Guid id, int timesSent, int maxAttempts) { if (timesSent >= maxAttempts) @@ -388,6 +486,33 @@ private async Task UpdateLastErrorAsync( await command.ExecuteNonQueryAsync(cancellationToken); } + + private enum ClaimResult + { + // No message was due. + Empty, + + // A message was claimed and its outcome was stored. + Processed, + + // A message was claimed and handed back unchanged. + Released + } + + private enum DispatchOutcome + { + // The transport accepted the message. + Sent, + + // The attempt failed and counts. + Failed, + + // The attempt was cut short and does not count. + Released + } + + // What the dispatcher does after a pass: it pauses after a released claim and waits for a signal otherwise. + private readonly record struct PassResult(bool IsPaused, double? SecondsUntilDue); } internal static partial class SchedulerLogs @@ -427,6 +552,30 @@ public static partial void CouldNotDetermineScheduledMessageDestination( this ILogger logger, Guid id, string? destinationAddress); + + [LoggerMessage( + 8, + LogLevel.Warning, + "The dispatch of scheduled message {Id} (message ID {MessageId}, type {MessageType}) to {DestinationAddress} failed because the transport is unavailable. The attempt is not counted and the message is dispatched again.")] + public static partial void ScheduledMessageTransportUnavailable( + this ILogger logger, + Exception exception, + Guid id, + string? messageId, + string? messageType, + string? destinationAddress); + + [LoggerMessage( + 9, + LogLevel.Debug, + "The dispatch of scheduled message {Id} (message ID {MessageId}, type {MessageType}) to {DestinationAddress} was cancelled because the host is stopping. The attempt is not counted.")] + public static partial void ScheduledMessageDispatchCancelled( + this ILogger logger, + Exception exception, + Guid id, + string? messageId, + string? messageType, + string? destinationAddress); } file static class Serializer diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs index 2e707bd70bd..7de4384b636 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs @@ -14,9 +14,10 @@ internal sealed class ScheduledMessageQueries public string InsertMessage { get; set; } = null!; /// - /// Gets or sets the SQL query to retrieve the earliest scheduled time that is due for dispatch. + /// Gets or sets the SQL query that returns the seconds until the earliest pending message is due. The + /// result is not positive when a message is due, and null when no message is pending. /// - public string NextWakeTime { get; set; } = null!; + public string NextWakeInterval { get; set; } = null!; /// /// Gets or sets the SQL statement that locks a single scheduled message row for processing, @@ -54,8 +55,9 @@ public static ScheduledMessageQueries From(ScheduledMessageTableInfo t) VALUES (@id, @envelope, @scheduled_time, 0, 10, NOW()); """, - NextWakeTime = $""" - SELECT MIN("{t.ScheduledTime}" + INTERVAL '1 second' * POWER(2, "{t.TimesSent}")) AS "NextWakeTime" + NextWakeInterval = $""" + SELECT (EXTRACT(EPOCH FROM MIN("{t.ScheduledTime}")) - EXTRACT(EPOCH FROM NOW()))::double precision + AS "SecondsUntilDue" FROM {t.QualifiedTableName} WHERE "{t.TimesSent}" < "{t.MaxAttempts}"; """, diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageWorker.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageWorker.cs index e21327bbb32..aeeaecd080a 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageWorker.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageWorker.cs @@ -12,6 +12,7 @@ internal sealed class ScheduledMessageWorker(ScheduledMessageDispatcher dispatch { private readonly object _lock = new(); private ContinuousTask? _task; + private Task _processing = Task.CompletedTask; /// /// Starts the scheduled message processing background task. This call is idempotent: invoking it @@ -28,14 +29,15 @@ public Task StartAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - _task = new ContinuousTask(dispatcher.ProcessAsync); + _task = new ContinuousTask(ProcessAsync); } return Task.CompletedTask; } /// - /// Stops the scheduled message processing background task and waits for it to complete gracefully. + /// Stops the scheduled message processing background task and waits until the message that was being + /// dispatched is either removed from the schedule or kept for a later dispatch. /// /// A token that signals when shutdown should be forced. public async Task StopAsync(CancellationToken cancellationToken) @@ -54,5 +56,18 @@ public async Task StopAsync(CancellationToken cancellationToken) } await task.DisposeAsync(); + + // The continuous task stops waiting once it is cancelled, while the dispatcher still removes the + // message a transport has already accepted. The wait ends early when the shutdown is forced. + await Volatile.Read(ref _processing) + .WaitAsync(cancellationToken) + .ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing); + } + + private Task ProcessAsync(CancellationToken cancellationToken) + { + var processing = dispatcher.ProcessAsync(cancellationToken); + Volatile.Write(ref _processing, processing); + return processing; } } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs new file mode 100644 index 00000000000..5ee5fc47b99 --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs @@ -0,0 +1,227 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Middlewares; +using Mocha.Scheduling; +using Mocha.Transport.InMemory; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresScheduledMessageDispatcherTests(PostgresFixture fixture) : IClassFixture +{ + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_stopGracePeriod = TimeSpan.FromMilliseconds(500); + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task ProcessAsync_Should_DeleteMessage_When_TransportAcceptedItBeforeTheStop() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var accepted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var dispatch = new ScriptedDispatch(async attempt => + { + await attempt.SendAsync(); + accepted.TrySetResult(); + await attempt.WaitForCancellationAsync(Task.Delay(s_timeout)); + }); + await using var provider = await CreateProviderAsync(connectionString, dispatch); + await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); + await accepted.Task.WaitAsync(s_timeout, TestToken); + + // act + await cancellation.CancelAsync(); + await processing.WaitAsync(s_timeout, TestToken); + var remaining = await MessageRows.CountScheduledAsync(connectionString, TestToken); + + // assert + Assert.Equal(0, remaining); + Assert.Equal(["A"], dispatch.Accepted); + } + + [Fact] + public async Task StopAsync_Should_WaitUntilMessageIsDeleted_When_TransportAcceptedItBeforeTheStop() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var accepted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var cancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var dispatch = new ScriptedDispatch(async attempt => + { + await attempt.SendAsync(); + accepted.TrySetResult(); + await attempt.WaitForCancellationAsync(Task.Delay(s_timeout)); + cancelled.TrySetResult(); + await release.Task; + }); + await using var provider = await CreateProviderAsync(connectionString, dispatch); + await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); + var host = await MessagingTestHost.StartAsync(provider, TestToken); + await accepted.Task.WaitAsync(s_timeout, TestToken); + + // act + // the dispatch returns only after the stop had the time to return without it + var stopping = host.DisposeAsync().AsTask(); + await cancelled.Task.WaitAsync(s_timeout, TestToken); + var stoppedBeforeDispatchReturned = + await Task.WhenAny(stopping, Task.Delay(s_stopGracePeriod, TestToken)) == stopping; + release.TrySetResult(); + await stopping.WaitAsync(s_timeout, TestToken); + var remaining = await MessageRows.CountScheduledAsync(connectionString, TestToken); + + // assert + Assert.False(stoppedBeforeDispatchReturned); + Assert.Equal(0, remaining); + Assert.Equal(["A"], dispatch.Accepted); + } + + [Fact] + public async Task ProcessAsync_Should_DispatchAgainAfterOneAndTwoSeconds_When_AttemptsKeepFailing() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var watch = new Stopwatch(); + var attempts = new ConcurrentQueue(); + var dispatch = new ScriptedDispatch(attempt => + { + attempts.Enqueue(watch.Elapsed); + + return attempt.Number <= 2 + ? throw new InvalidOperationException("The broker refused the message.") + : attempt.SendAsync(); + }); + await using var provider = await CreateProviderAsync(connectionString, dispatch); + await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + + // act + watch.Start(); + var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); + var remaining = await MessageRows.WaitForScheduledCountAsync(connectionString, 0, s_timeout, TestToken); + await cancellation.CancelAsync(); + await processing.WaitAsync(s_timeout, TestToken); + + // assert + // A message is due one second after its first counted attempt and two seconds after its second one. + TimeSpan[] times = [.. attempts]; + Assert.Equal(0, remaining); + Assert.Equal(3, times.Length); + Assert.InRange(times[1] - times[0], TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(2.5)); + Assert.InRange(times[2] - times[1], TimeSpan.FromSeconds(1.5), TimeSpan.FromSeconds(5)); + } + + [Fact] + public async Task ProcessAsync_Should_NotCountAttempts_When_TransportIsUnavailable() + { + // arrange + const int unavailableAttempts = 3; + var connectionString = await fixture.CreateDatabaseAsync(); + var watch = new Stopwatch(); + var attempts = new ConcurrentQueue(); + var available = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var resume = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var dispatch = new ScriptedDispatch(async attempt => + { + attempts.Enqueue(watch.Elapsed); + + if (attempt.Number <= unavailableAttempts) + { + throw new TransportUnavailableException("The broker is unreachable.", null); + } + + available.TrySetResult(); + await resume.Task.WaitAsync(attempt.CancellationToken); + await attempt.SendAsync(); + }); + await using var provider = await CreateProviderAsync(connectionString, dispatch); + var id = await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + + // act + watch.Start(); + var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); + await available.Task.WaitAsync(s_timeout, TestToken); + var timesSentAfterOutage = await MessageRows.GetScheduledTimesSentAsync(connectionString, id, TestToken); + resume.TrySetResult(); + var remaining = await MessageRows.WaitForScheduledCountAsync(connectionString, 0, s_timeout, TestToken); + await cancellation.CancelAsync(); + await processing.WaitAsync(s_timeout, TestToken); + + // assert + // The three pauses double from at least 100 milliseconds, which adds up to at least 0.7 seconds. + TimeSpan[] times = [.. attempts]; + Assert.Equal(0, timesSentAfterOutage); + Assert.Equal(0, remaining); + Assert.Equal(["A"], dispatch.Accepted); + Assert.InRange(times[unavailableAttempts] - times[0], TimeSpan.FromSeconds(0.5), s_timeout); + } + + [Fact] + public async Task ProcessAsync_Should_NotCountAttempt_When_HostStopsDuringDispatch() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var dispatching = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var dispatch = new ScriptedDispatch(async attempt => + { + dispatching.TrySetResult(); + await Task.Delay(Timeout.InfiniteTimeSpan, attempt.CancellationToken); + }); + await using var provider = await CreateProviderAsync(connectionString, dispatch); + var id = await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); + await dispatching.Task.WaitAsync(s_timeout, TestToken); + + // act + await cancellation.CancelAsync(); + await processing.WaitAsync(s_timeout, TestToken); + var timesSent = await MessageRows.GetScheduledTimesSentAsync(connectionString, id, TestToken); + + // assert + Assert.Equal(0, timesSent); + Assert.Equal(1, dispatch.AttemptsOf("A")); + } + + private static MessageEnvelope CreateEnvelope(IServiceProvider provider, string messageId) + { + var runtime = provider.GetRequiredService(); + var type = runtime.GetMessageType(typeof(ScheduledEvent)); + return new MessageEnvelope + { + MessageId = messageId, + MessageType = type.Identity, + ContentType = MessageContentType.Json.Value, + DestinationAddress = runtime.GetPublishEndpoint(type).Address.ToString(), + Body = JsonSerializer.SerializeToUtf8Bytes(new ScheduledEvent(messageId)) + }; + } + + private static async Task CreateProviderAsync(string connectionString, ScriptedDispatch dispatch) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(o => o.UseTestNpgsql(connectionString)); + var builder = services.AddMessageBus(); + builder.AddEntityFramework(ef => ef.UsePostgresScheduling()); + builder.AddInMemory(t => + { + t.DeclareQueue("scheduled"); + t.DispatchEndpoint("scheduled").ToQueue("scheduled").Publish(); + }); + builder.ConfigureMessageBus(b => b.UseDispatch(dispatch.Middleware, after: "Serialization")); + + var provider = services.BuildServiceProvider(); + await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + await using var scope = provider.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); + return provider; + } + + public sealed record ScheduledEvent(string Name); +} diff --git a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md index 314622f7d0e..e7e4ca89dc6 100644 --- a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md +++ b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md @@ -26,6 +26,14 @@ Outbox message (message ID , type ) to fail - A message that cannot be read, has an unknown message type, or matches no endpoint is retried in the same way. Its Critical entry shows `(null)` for the message ID, the type, and the destination when the stored envelope cannot be read. - A failed dispatch no longer ends the processing run. The processor logs the exception at Error with the text `The dispatch of outbox message (message ID , type ) to failed on attempt . The message is retried.` and continues with the next message. In 16.7 the failure was logged as `An unexpected error occurred while processing outbox event`. Change alert rules that match that text for a failed dispatch. +## Scheduled messages and redeliveries keep their attempts during a RabbitMQ outage + +This entry applies to the Postgres-backed scheduled message store that `UsePostgresScheduling()` registers. With RabbitMQ it stores scheduled messages and [redeliveries](../reliability.md#redeliver-failed-messages). + +A dispatch that fails with `TransportUnavailableException`, or that a host stop interrupts, no longer counts towards the 10 attempts of a scheduled message. In 16.7 every dispatch that failed with an exception counted, so a broker outage could use up all attempts of the scheduled messages and redeliveries that came due. Every other failure still counts and is recorded in the `last_error` column. + +Only the RabbitMQ transport throws `TransportUnavailableException`. See [Retry behavior](../scheduling.md#retry-behavior). + ## RequestAsync cancels a dispatch that outlasts the response timeout The response timeout of `RequestAsync`, two minutes, now also ends the dispatch of the request. When it elapses while the request is still being dispatched, the dispatch is cancelled and `RequestAsync` throws `ResponseTimeoutException`. In 16.7 `RequestAsync` waited for the dispatch to return first. See [How to handle timeouts](../messaging-patterns.md#how-to-handle-timeouts). diff --git a/website/content/docs/mocha/scheduling.md b/website/content/docs/mocha/scheduling.md index ad44f0b300c..06d9e87a058 100644 --- a/website/content/docs/mocha/scheduling.md +++ b/website/content/docs/mocha/scheduling.md @@ -247,6 +247,8 @@ The PostgreSQL, InMemory, and Azure Service Bus transports each have a schedulin This section applies to the Postgres-backed scheduled message store, used natively by the PostgreSQL transport or through the `UsePostgresScheduling()` fallback for RabbitMQ. If a scheduled message fails to dispatch, the scheduler retries with exponential backoff. Each failed attempt increases the wait time before the next retry. After 10 attempts (the default `max_attempts`), the message is no longer eligible for dispatch. You can inspect failed messages by querying the `scheduled_messages` table and checking the `last_error` column. +A dispatch that fails with `TransportUnavailableException`, which the RabbitMQ transport throws when the broker cannot be reached or does not confirm in time, does not count as an attempt. Neither does a dispatch that a host stop interrupts. The message keeps its scheduled time and is dispatched again after a pause of about 100 milliseconds to 10 seconds. + The InMemory transport's store does not retry failed dispatches. If a scheduled message fails to dispatch, it is dropped and the failure is logged. ## Multiple service instances From 444d971f6e8250c6383ed26e6c9a6919f96deee3 Mon Sep 17 00:00:00 2001 From: Pascal Senn Date: Mon, 16 Nov 2026 20:39:59 +0100 Subject: [PATCH 2/2] [Mocha] Retry Postgres scheduled messages without an attempt limit A scheduled message is dispatched again every 10 seconds until the transport accepts it. The dispatcher pauses for 10 seconds after a failed dispatch, logs a Critical entry on every 10th failed attempt, and wakes at the time the next message is due. The handling of TransportUnavailableException is removed. --- .../ScheduledMessageTableInfo.cs | 3 +- ...gresScheduledMessageEntityConfiguration.cs | 5 +- .../Scheduling/ScheduledMessage.cs | 2 +- .../Scheduling/ScheduledMessageDispatcher.cs | 378 +++++++----------- .../Scheduling/ScheduledMessageQueries.cs | 20 +- .../Scheduling/ScheduledMessageWorker.cs | 19 +- ...PostgresScheduledMessageDispatcherTests.cs | 259 ++++++------ .../migration/migrate-from-16-7-to-16-8.md | 21 +- website/content/docs/mocha/scheduling.md | 10 +- 9 files changed, 331 insertions(+), 386 deletions(-) diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/ScheduledMessageTableInfo.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/ScheduledMessageTableInfo.cs index 068fe43b649..43e3b0ce48d 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/ScheduledMessageTableInfo.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/ScheduledMessageTableInfo.cs @@ -42,7 +42,8 @@ public sealed class ScheduledMessageTableInfo public string CreatedAt { get; set; } = "created_at"; /// - /// Gets or sets the column name for the maximum number of dispatch attempts. Defaults to "max_attempts". + /// Gets or sets the column name for the attempt limit, which the dispatcher does not apply. + /// Defaults to "max_attempts". /// public string MaxAttempts { get; set; } = "max_attempts"; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/PostgresScheduledMessageEntityConfiguration.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/PostgresScheduledMessageEntityConfiguration.cs index 97205f71ab9..2ba2b453d98 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/PostgresScheduledMessageEntityConfiguration.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/PostgresScheduledMessageEntityConfiguration.cs @@ -28,10 +28,7 @@ public void Configure(EntityTypeBuilder builder) builder.HasKey(e => e.Id).HasName(s_defaults.IxPrimaryKey); - builder.HasIndex(x => x.ScheduledTime) - .HasDatabaseName(s_defaults.IxScheduledTime) - // Only consider messages that are not yet due or have remaining retry attempts. - .HasFilter($"\"{s_defaults.TimesSent}\" < \"{s_defaults.MaxAttempts}\""); + builder.HasIndex(x => x.ScheduledTime).HasDatabaseName(s_defaults.IxScheduledTime); builder.HasIndex(x => x.TimesSent).HasDatabaseName(s_defaults.IxTimesSent); diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessage.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessage.cs index bb62e650158..fc40144b12c 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessage.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessage.cs @@ -30,7 +30,7 @@ public sealed class ScheduledMessage(Guid id, JsonDocument envelope) public int TimesSent { get; private set; } /// - /// Gets the maximum number of times dispatch will be attempted before the message is considered dead. + /// Gets the value of the attempt limit column. The dispatcher does not apply it. /// public int MaxAttempts { get; private set; } = 10; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs index 932ff18a7e9..f577b686fc9 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs @@ -1,12 +1,10 @@ using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; using Mocha.Middlewares; using Mocha.Outbox; -using Mocha.Threading; using Npgsql; using NpgsqlTypes; @@ -18,12 +16,15 @@ namespace Mocha.Scheduling; /// public sealed class ScheduledMessageDispatcher { - private static readonly TimeSpan s_pauseDelay = TimeSpan.FromMilliseconds(100); - private static readonly TimeSpan s_maxPauseDelay = TimeSpan.FromSeconds(10); + // A Critical entry is logged every time the attempt count of a message reaches a multiple of this value. + private const int CriticalAttemptInterval = 10; // The pause before the dispatcher looks again for a due message that another dispatcher holds. private static readonly TimeSpan s_heldMessagePollingInterval = TimeSpan.FromSeconds(1); + // The pause of the dispatcher after a failed dispatch, which is as long as the retry delay of the message. + private static readonly TimeSpan s_failurePause = TimeSpan.FromSeconds(ScheduledMessageQueries.RetryDelaySeconds); + private readonly ILogger _logger; private readonly IServiceProvider _services; private readonly IMessagingRuntime _runtime; @@ -77,37 +78,27 @@ internal ScheduledMessageDispatcher( /// A token that signals when the dispatcher should stop. public async Task ProcessAsync(CancellationToken cancellationToken) { - // The pause before a released message is claimed again, which grows until a message is sent. - var pause = new ExponentialBackoff(int.MaxValue, s_pauseDelay, s_maxPauseDelay); - while (!cancellationToken.IsCancellationRequested) { try { - var pass = await ProcessPendingAsync(pause, cancellationToken); + var result = await ProcessPendingAsync(cancellationToken); - if (pass.IsPaused) + if (result.Status is MessageStatus.DispatchFailed) { - // The released message is claimed again after the pause, with or without a signal. - await pause.WaitAsync(cancellationToken); - } - else if (pass.SecondsUntilDue is not { } secondsUntilDue) - { - // No scheduled messages - sleep until notified. - await _signal.WaitUntilAsync(DateTimeOffset.MaxValue, cancellationToken); + // A signal does not end the pause, so that a transport that is down is not called + // for every message that is scheduled meanwhile. + await Task.Delay(s_failurePause, _timeProvider, cancellationToken); } - else if (secondsUntilDue > 0) + else if (result.NextWakeTime is { } nextWakeTime) { - var wakeTime = GetWakeTime(secondsUntilDue); - _logger.SchedulerSleepingUntil(wakeTime); - await _signal.WaitUntilAsync(wakeTime, cancellationToken); + _logger.SchedulerSleepingUntil(nextWakeTime); + await _signal.WaitUntilAsync(nextWakeTime, cancellationToken); } else { - // The claim did not return the message that is due, so another dispatcher holds it. - await _signal.WaitUntilAsync( - _timeProvider.GetUtcNow() + s_heldMessagePollingInterval, - cancellationToken); + // No scheduled messages - sleep until notified. + await _signal.WaitUntilAsync(DateTimeOffset.MaxValue, cancellationToken); } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) @@ -117,18 +108,7 @@ await _signal.WaitUntilAsync( } } - private DateTimeOffset GetWakeTime(double secondsUntilDue) - { - var now = _timeProvider.GetUtcNow(); - - return secondsUntilDue < (DateTimeOffset.MaxValue - now).TotalSeconds - ? now.AddSeconds(secondsUntilDue) - : DateTimeOffset.MaxValue; - } - - private async ValueTask ProcessPendingAsync( - ExponentialBackoff pause, - CancellationToken cancellationToken) + private async ValueTask ProcessPendingAsync(CancellationToken cancellationToken) { await using var scope = _services.CreateAsyncScope(); await using var connection = _options.CreateConnection(scope.ServiceProvider); @@ -136,26 +116,18 @@ private async ValueTask ProcessPendingAsync( while (true) { - cancellationToken.ThrowIfCancellationRequested(); - - // An exception before the commit rolls the claim back when the transaction is disposed. - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); + var result = await ProcessMessageAsync(connection, cancellationToken); - switch (await ProcessMessageAsync(connection, transaction, pause, cancellationToken)) + if (result.Status is not MessageStatus.Processed) { - case ClaimResult.Empty: - // The time is read in the transaction of the claim, so that both see the same time. - return new PassResult( - IsPaused: false, - await GetSecondsUntilDueAsync(connection, transaction, cancellationToken)); - - case ClaimResult.Released: - return new PassResult(IsPaused: true, SecondsUntilDue: null); + return result; } + + cancellationToken.ThrowIfCancellationRequested(); } } - private async Task GetSecondsUntilDueAsync( + private async Task GetNextWakeTimeAsync( NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken) @@ -165,13 +137,26 @@ private async ValueTask ProcessPendingAsync( command.CommandText = _options.Queries.NextWakeInterval; await command.PrepareAsync(cancellationToken); - return await command.ExecuteScalarAsync(cancellationToken) as double?; + if (await command.ExecuteScalarAsync(cancellationToken) is not double secondsUntilDue) + { + return null; + } + + var now = _timeProvider.GetUtcNow(); + + if (secondsUntilDue <= 0) + { + // The claim did not return the message that is due, so another dispatcher holds it. + return now + s_heldMessagePollingInterval; + } + + return secondsUntilDue < (DateTimeOffset.MaxValue - now).TotalSeconds + ? now.AddSeconds(secondsUntilDue) + : DateTimeOffset.MaxValue; } - private async Task ProcessMessageAsync( + private async Task ProcessMessageAsync( NpgsqlConnection connection, - NpgsqlTransaction transaction, - ExponentialBackoff pause, CancellationToken cancellationToken) { using var activity = OpenTelemetry.Source.StartActivity( @@ -179,165 +164,149 @@ private async Task ProcessMessageAsync( ActivityKind.Producer, new ActivityContext()); + await using var transaction = await connection.BeginTransactionAsync(cancellationToken); + try { - Guid id; - int timesSent; - int maxAttempts; - var outcome = DispatchOutcome.Failed; - Exception? dispatchError = null; - - await using (var command = connection.CreateCommand()) - { - command.Transaction = transaction; - command.CommandText = _options.Queries.ProcessMessage; + await using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = _options.Queries.ProcessMessage; - await command.PrepareAsync(cancellationToken); + await command.PrepareAsync(cancellationToken); + try + { await using var reader = await command.ExecuteReaderAsync(cancellationToken); - if (!await reader.ReadAsync(cancellationToken)) + if (await reader.ReadAsync(cancellationToken)) { - return ClaimResult.Empty; - } + var id = reader.GetGuid(0); + var envelope = Serializer.ReadMessageEnvelopeSafe(reader, 1, _logger); + var timesSent = reader.GetInt32(2); - id = reader.GetGuid(0); - var envelope = Serializer.ReadMessageEnvelopeSafe(reader, 1, _logger); - timesSent = reader.GetInt32(2); - maxAttempts = reader.GetInt32(3); + // A message this instance cannot read or route stays in the table and is + // retried after the retry delay. + if (envelope is null) + { + _logger.CouldNotDeserializeScheduledMessageBody(id); + LogIfRepeatedlyFailed(id, null, timesSent); + + return MessageResult.Processed; + } + + var messageType = GetMessageType(envelope.MessageType); + + if (messageType is null) + { + _logger.CouldNotResolveScheduledMessageType(id, envelope.MessageType); + LogIfRepeatedlyFailed(id, envelope, timesSent); + + return MessageResult.Processed; + } + + var endpoint = ResolveDispatchEndpoint(envelope); + + if (endpoint is null) + { + _logger.CouldNotDetermineScheduledMessageDestination(id, envelope.DestinationAddress); + LogIfRepeatedlyFailed(id, envelope, timesSent); + + return MessageResult.Processed; + } - if (TryResolve(id, envelope, out var messageType, out var endpoint)) - { try { await SendAsync(envelope, endpoint, messageType, cancellationToken); - outcome = DispatchOutcome.Sent; + await reader.CloseAsync(); + + await DeleteMessageAsync(connection, id, transaction, cancellationToken); } - catch (Exception ex) + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { - outcome = OnDispatchFailed(ex, id, envelope, cancellationToken); - dispatchError = ex; + _logger.ScheduledMessageDispatchFailed(id, ex); + + await reader.CloseAsync(); + + await UpdateLastErrorAsync(connection, id, ex, transaction, cancellationToken); + + LogIfRepeatedlyFailed(id, envelope, timesSent); + + return MessageResult.DispatchFailed; } + + return MessageResult.Processed; } - } + else + { + // The wake time is read in the transaction of the claim, so that both see the same time. + await reader.CloseAsync(); - switch (outcome) + return new MessageResult( + MessageStatus.NoneDue, + await GetNextWakeTimeAsync(connection, transaction, cancellationToken)); + } + } + finally { - case DispatchOutcome.Sent: - // The transport has the message, so its row is removed whatever the token says. - await DeleteMessageAsync(connection, id, transaction, CancellationToken.None); - await transaction.CommitAsync(CancellationToken.None); - pause.Reset(); - return ClaimResult.Processed; - - case DispatchOutcome.Released: - // The rollback restores the attempt count and the due time of the row. - await transaction.RollbackAsync(CancellationToken.None); - return ClaimResult.Released; - - default: - if (dispatchError is not null) + try + { + await transaction.CommitAsync(cancellationToken); + } + catch + { + // Commit failed (e.g., connection lost). Attempt rollback. + // If commit actually succeeded server-side, the message stays + // with times_sent incremented - safe, just causes a retry. + try { - await UpdateLastErrorAsync(connection, id, dispatchError, transaction, cancellationToken); + await transaction.RollbackAsync(CancellationToken.None); } - - // The commit stores the incremented attempt count and the backoff of the row. - await transaction.CommitAsync(cancellationToken); - LogIfExhausted(id, timesSent, maxAttempts); - return ClaimResult.Processed; + catch + { + /* swallow */ + } + } } } - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + catch (Exception ex) { + // Log only - no RollbackAsync here (commit already handled in finally) _logger.UnexpectedErrorWhileProcessingScheduledMessage(ex); throw; } } - /// - /// Resolves what a dispatch of the message needs, and logs why when the message cannot be dispatched. - /// - private bool TryResolve( - Guid id, - [NotNullWhen(true)] MessageEnvelope? envelope, - [NotNullWhen(true)] out MessageType? messageType, - [NotNullWhen(true)] out DispatchEndpoint? endpoint) + private void LogIfRepeatedlyFailed(Guid id, MessageEnvelope? envelope, int timesSent) { - messageType = null; - endpoint = null; - - // A message this instance cannot read or route stays in the table and is - // retried after its backoff. - if (envelope is null) + if (timesSent % CriticalAttemptInterval == 0) { - _logger.CouldNotDeserializeScheduledMessageBody(id); - return false; - } - - messageType = GetMessageType(envelope.MessageType); - - if (messageType is null) - { - _logger.CouldNotResolveScheduledMessageType(id, envelope.MessageType); - return false; - } - - endpoint = ResolveDispatchEndpoint(envelope); - - if (endpoint is null) - { - _logger.CouldNotDetermineScheduledMessageDestination(id, envelope.DestinationAddress); - return false; + _logger.ScheduledMessageFailedRepeatedly( + id, + envelope?.MessageId, + envelope?.MessageType, + envelope?.DestinationAddress, + timesSent); } - - return true; } - /// - /// Logs why the dispatch did not complete and returns whether the attempt counts. - /// - private DispatchOutcome OnDispatchFailed( - Exception exception, - Guid id, - MessageEnvelope envelope, - CancellationToken cancellationToken) + private readonly record struct MessageResult(MessageStatus Status, DateTimeOffset? NextWakeTime) { - if (cancellationToken.IsCancellationRequested) - { - _logger.ScheduledMessageDispatchCancelled( - exception, - id, - envelope.MessageId, - envelope.MessageType, - envelope.DestinationAddress); - - return DispatchOutcome.Released; - } - - if (exception is TransportUnavailableException) - { - _logger.ScheduledMessageTransportUnavailable( - exception, - id, - envelope.MessageId, - envelope.MessageType, - envelope.DestinationAddress); - - return DispatchOutcome.Released; - } - - _logger.ScheduledMessageDispatchFailed(id, exception); + public static MessageResult Processed { get; } = new(MessageStatus.Processed, null); - return DispatchOutcome.Failed; + public static MessageResult DispatchFailed { get; } = new(MessageStatus.DispatchFailed, null); } - private void LogIfExhausted(Guid id, int timesSent, int maxAttempts) + private enum MessageStatus { - if (timesSent >= maxAttempts) - { - _logger.ScheduledMessageExhausted(id, maxAttempts); - } + // A message was claimed and the dispatcher continues with the next one. + Processed, + + // The transport did not accept a claimed message and the dispatcher pauses. + DispatchFailed, + + // No message was due. + NoneDue } private MessageType? GetMessageType(string? messageType) @@ -486,33 +455,6 @@ private async Task UpdateLastErrorAsync( await command.ExecuteNonQueryAsync(cancellationToken); } - - private enum ClaimResult - { - // No message was due. - Empty, - - // A message was claimed and its outcome was stored. - Processed, - - // A message was claimed and handed back unchanged. - Released - } - - private enum DispatchOutcome - { - // The transport accepted the message. - Sent, - - // The attempt failed and counts. - Failed, - - // The attempt was cut short and does not count. - Released - } - - // What the dispatcher does after a pass: it pauses after a released claim and waits for a signal otherwise. - private readonly record struct PassResult(bool IsPaused, double? SecondsUntilDue); } internal static partial class SchedulerLogs @@ -535,8 +477,14 @@ internal static partial class SchedulerLogs [LoggerMessage( 5, LogLevel.Critical, - "Scheduled message {Id} exhausted all {MaxAttempts} retry attempts and will not be retried.")] - public static partial void ScheduledMessageExhausted(this ILogger logger, Guid id, int maxAttempts); + "Scheduled message {Id} (message ID {MessageId}, type {MessageType}) to {DestinationAddress} failed on attempt {Attempt}. The message is retried.")] + public static partial void ScheduledMessageFailedRepeatedly( + this ILogger logger, + Guid id, + string? messageId, + string? messageType, + string? destinationAddress, + int attempt); [LoggerMessage( 6, @@ -552,30 +500,6 @@ public static partial void CouldNotDetermineScheduledMessageDestination( this ILogger logger, Guid id, string? destinationAddress); - - [LoggerMessage( - 8, - LogLevel.Warning, - "The dispatch of scheduled message {Id} (message ID {MessageId}, type {MessageType}) to {DestinationAddress} failed because the transport is unavailable. The attempt is not counted and the message is dispatched again.")] - public static partial void ScheduledMessageTransportUnavailable( - this ILogger logger, - Exception exception, - Guid id, - string? messageId, - string? messageType, - string? destinationAddress); - - [LoggerMessage( - 9, - LogLevel.Debug, - "The dispatch of scheduled message {Id} (message ID {MessageId}, type {MessageType}) to {DestinationAddress} was cancelled because the host is stopping. The attempt is not counted.")] - public static partial void ScheduledMessageDispatchCancelled( - this ILogger logger, - Exception exception, - Guid id, - string? messageId, - string? messageType, - string? destinationAddress); } file static class Serializer diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs index 7de4384b636..8d3f6af9647 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs @@ -8,6 +8,11 @@ namespace Mocha.Scheduling; /// internal sealed class ScheduledMessageQueries { + /// + /// The number of seconds after a failed dispatch before the message is dispatched again. + /// + public const int RetryDelaySeconds = 10; + /// /// Gets or sets the SQL statement to insert a new scheduled message into the table. /// @@ -36,8 +41,7 @@ internal sealed class ScheduledMessageQueries public string UpdateLastError { get; set; } = null!; /// - /// Gets or sets the SQL statement to cancel a scheduled message by deleting it if it has not - /// exceeded its maximum delivery attempts. + /// Gets or sets the SQL statement to cancel a scheduled message by deleting it. /// public string CancelMessage { get; set; } = null!; @@ -58,18 +62,16 @@ public static ScheduledMessageQueries From(ScheduledMessageTableInfo t) NextWakeInterval = $""" SELECT (EXTRACT(EPOCH FROM MIN("{t.ScheduledTime}")) - EXTRACT(EPOCH FROM NOW()))::double precision AS "SecondsUntilDue" - FROM {t.QualifiedTableName} - WHERE "{t.TimesSent}" < "{t.MaxAttempts}"; + FROM {t.QualifiedTableName}; """, ProcessMessage = $""" UPDATE {t.QualifiedTableName} SET "{t.TimesSent}" = "{t.TimesSent}" + 1, - "{t.ScheduledTime}" = NOW() + INTERVAL '1 second' * POWER(2, "{t.TimesSent}") + "{t.ScheduledTime}" = NOW() + INTERVAL '{RetryDelaySeconds} seconds' WHERE "{t.Id}" = ( SELECT "{t.Id}" FROM {t.QualifiedTableName} - WHERE "{t.TimesSent}" < "{t.MaxAttempts}" - AND "{t.ScheduledTime}" <= NOW() + WHERE "{t.ScheduledTime}" <= NOW() ORDER BY "{t.ScheduledTime}" FOR UPDATE SKIP LOCKED LIMIT 1 @@ -77,8 +79,7 @@ LIMIT 1 RETURNING "{t.Id}", "{t.Envelope}", - "{t.TimesSent}", - "{t.MaxAttempts}"; + "{t.TimesSent}"; """, DeleteMessage = $""" @@ -95,7 +96,6 @@ DELETE FROM {t.QualifiedTableName} CancelMessage = $""" DELETE FROM {t.QualifiedTableName} WHERE "{t.Id}" = @id - AND "{t.TimesSent}" < "{t.MaxAttempts}" RETURNING "{t.Id}"; """ }; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageWorker.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageWorker.cs index aeeaecd080a..e21327bbb32 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageWorker.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageWorker.cs @@ -12,7 +12,6 @@ internal sealed class ScheduledMessageWorker(ScheduledMessageDispatcher dispatch { private readonly object _lock = new(); private ContinuousTask? _task; - private Task _processing = Task.CompletedTask; /// /// Starts the scheduled message processing background task. This call is idempotent: invoking it @@ -29,15 +28,14 @@ public Task StartAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - _task = new ContinuousTask(ProcessAsync); + _task = new ContinuousTask(dispatcher.ProcessAsync); } return Task.CompletedTask; } /// - /// Stops the scheduled message processing background task and waits until the message that was being - /// dispatched is either removed from the schedule or kept for a later dispatch. + /// Stops the scheduled message processing background task and waits for it to complete gracefully. /// /// A token that signals when shutdown should be forced. public async Task StopAsync(CancellationToken cancellationToken) @@ -56,18 +54,5 @@ public async Task StopAsync(CancellationToken cancellationToken) } await task.DisposeAsync(); - - // The continuous task stops waiting once it is cancelled, while the dispatcher still removes the - // message a transport has already accepted. The wait ends early when the shutdown is forced. - await Volatile.Read(ref _processing) - .WaitAsync(cancellationToken) - .ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing); - } - - private Task ProcessAsync(CancellationToken cancellationToken) - { - var processing = dispatcher.ProcessAsync(cancellationToken); - Volatile.Write(ref _processing, processing); - return processing; } } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs index 5ee5fc47b99..25144aa6a70 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs @@ -1,191 +1,198 @@ -using System.Collections.Concurrent; -using System.Diagnostics; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Middlewares; using Mocha.Scheduling; using Mocha.Transport.InMemory; +using Npgsql; namespace Mocha.EntityFrameworkCore.Postgres.Tests; public sealed class PostgresScheduledMessageDispatcherTests(PostgresFixture fixture) : IClassFixture { private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); - private static readonly TimeSpan s_stopGracePeriod = TimeSpan.FromMilliseconds(500); + private const string EmptyEnvelope = "{}"; private static CancellationToken TestToken => TestContext.Current.CancellationToken; [Fact] - public async Task ProcessAsync_Should_DeleteMessage_When_TransportAcceptedItBeforeTheStop() + public async Task ProcessAsync_Should_DispatchMessage_When_AttemptCountExceedsFormerLimit() { // arrange var connectionString = await fixture.CreateDatabaseAsync(); - var accepted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var dispatch = new ScriptedDispatch(async attempt => - { - await attempt.SendAsync(); - accepted.TrySetResult(); - await attempt.WaitForCancellationAsync(Task.Delay(s_timeout)); - }); + var dispatch = new ScriptedDispatch(static attempt => attempt.SendAsync()); await using var provider = await CreateProviderAsync(connectionString, dispatch); await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); - using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); - var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); - await accepted.Task.WaitAsync(s_timeout, TestToken); + await ExecuteAsync(connectionString, """UPDATE "scheduled_messages" SET "times_sent" = 10;"""); + object? remaining; // act - await cancellation.CancelAsync(); - await processing.WaitAsync(s_timeout, TestToken); - var remaining = await MessageRows.CountScheduledAsync(connectionString, TestToken); + await using (StartDispatcher(provider)) + { + remaining = await WaitForAsync( + connectionString, + """SELECT COUNT(*) FROM "scheduled_messages";""", + static count => count is 0L); + } // assert - Assert.Equal(0, remaining); + Assert.Equal(0L, remaining); Assert.Equal(["A"], dispatch.Accepted); } [Fact] - public async Task StopAsync_Should_WaitUntilMessageIsDeleted_When_TransportAcceptedItBeforeTheStop() + public async Task ProcessAsync_Should_ScheduleRetryTenSecondsAhead_When_DispatchFails() { // arrange var connectionString = await fixture.CreateDatabaseAsync(); - var accepted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var cancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var dispatch = new ScriptedDispatch(async attempt => - { - await attempt.SendAsync(); - accepted.TrySetResult(); - await attempt.WaitForCancellationAsync(Task.Delay(s_timeout)); - cancelled.TrySetResult(); - await release.Task; - }); + var dispatch = new ScriptedDispatch( + static _ => throw new InvalidOperationException("The broker is unreachable.")); await using var provider = await CreateProviderAsync(connectionString, dispatch); await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); - var host = await MessagingTestHost.StartAsync(provider, TestToken); - await accepted.Task.WaitAsync(s_timeout, TestToken); + object? timesSent; // act - // the dispatch returns only after the stop had the time to return without it - var stopping = host.DisposeAsync().AsTask(); - await cancelled.Task.WaitAsync(s_timeout, TestToken); - var stoppedBeforeDispatchReturned = - await Task.WhenAny(stopping, Task.Delay(s_stopGracePeriod, TestToken)) == stopping; - release.TrySetResult(); - await stopping.WaitAsync(s_timeout, TestToken); - var remaining = await MessageRows.CountScheduledAsync(connectionString, TestToken); + await using (StartDispatcher(provider)) + { + timesSent = await WaitForAsync( + connectionString, + """SELECT "times_sent" FROM "scheduled_messages";""", + static count => count is 1); + } + + var secondsUntilDue = await ExecuteScalarAsync( + connectionString, + """ + SELECT (EXTRACT(EPOCH FROM "scheduled_time") - EXTRACT(EPOCH FROM NOW()))::double precision + FROM "scheduled_messages"; + """); // assert - Assert.False(stoppedBeforeDispatchReturned); - Assert.Equal(0, remaining); - Assert.Equal(["A"], dispatch.Accepted); + Assert.Equal(1, timesSent); + Assert.InRange(Assert.IsType(secondsUntilDue), 5, 10); } [Fact] - public async Task ProcessAsync_Should_DispatchAgainAfterOneAndTwoSeconds_When_AttemptsKeepFailing() + public async Task ProcessAsync_Should_NotDispatchNextMessage_When_DispatchFailed() { // arrange var connectionString = await fixture.CreateDatabaseAsync(); - var watch = new Stopwatch(); - var attempts = new ConcurrentQueue(); - var dispatch = new ScriptedDispatch(attempt => - { - attempts.Enqueue(watch.Elapsed); - - return attempt.Number <= 2 - ? throw new InvalidOperationException("The broker refused the message.") - : attempt.SendAsync(); - }); + var dispatch = new ScriptedDispatch(static attempt => attempt.MessageId == "A" + ? throw new InvalidOperationException("The broker is unreachable.") + : attempt.SendAsync()); await using var provider = await CreateProviderAsync(connectionString, dispatch); await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); - using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "B"), TestToken); + object? remaining; // act - watch.Start(); - var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); - var remaining = await MessageRows.WaitForScheduledCountAsync(connectionString, 0, s_timeout, TestToken); - await cancellation.CancelAsync(); - await processing.WaitAsync(s_timeout, TestToken); + await using (StartDispatcher(provider)) + { + await WaitForAsync( + connectionString, + """SELECT MAX("times_sent") FROM "scheduled_messages";""", + static count => count is 1); + await Task.Delay(TimeSpan.FromMilliseconds(500), TestToken); + remaining = await ExecuteScalarAsync(connectionString, """SELECT COUNT(*) FROM "scheduled_messages";"""); + } // assert - // A message is due one second after its first counted attempt and two seconds after its second one. - TimeSpan[] times = [.. attempts]; - Assert.Equal(0, remaining); - Assert.Equal(3, times.Length); - Assert.InRange(times[1] - times[0], TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(2.5)); - Assert.InRange(times[2] - times[1], TimeSpan.FromSeconds(1.5), TimeSpan.FromSeconds(5)); + Assert.Equal(2L, remaining); + Assert.Equal(1, dispatch.AttemptsOf("A")); + Assert.Equal(0, dispatch.AttemptsOf("B")); } [Fact] - public async Task ProcessAsync_Should_NotCountAttempts_When_TransportIsUnavailable() + public async Task NextWakeInterval_Should_ReturnNull_When_NoMessageIsScheduled() { // arrange - const int unavailableAttempts = 3; var connectionString = await fixture.CreateDatabaseAsync(); - var watch = new Stopwatch(); - var attempts = new ConcurrentQueue(); - var available = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var resume = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var dispatch = new ScriptedDispatch(async attempt => - { - attempts.Enqueue(watch.Elapsed); + await using var provider = await CreateProviderAsync( + connectionString, + new ScriptedDispatch(static attempt => attempt.SendAsync())); - if (attempt.Number <= unavailableAttempts) - { - throw new TransportUnavailableException("The broker is unreachable.", null); - } + // act + var result = await ExecuteScalarAsync(connectionString, NextWakeInterval); - available.TrySetResult(); - await resume.Task.WaitAsync(attempt.CancellationToken); - await attempt.SendAsync(); - }); - await using var provider = await CreateProviderAsync(connectionString, dispatch); - var id = await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); - using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + // assert + Assert.Null(result); + } + + [Fact] + public async Task NextWakeInterval_Should_ReturnSecondsUntilEarliestMessage_When_MessagesAreNotDue() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + await using var provider = await CreateProviderAsync( + connectionString, + new ScriptedDispatch(static attempt => attempt.SendAsync())); + await InsertRowAsync(connectionString, "NOW() + INTERVAL '60 seconds'", timesSent: 0); + await InsertRowAsync(connectionString, "NOW() + INTERVAL '30 seconds'", timesSent: 3); // act - watch.Start(); - var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); - await available.Task.WaitAsync(s_timeout, TestToken); - var timesSentAfterOutage = await MessageRows.GetScheduledTimesSentAsync(connectionString, id, TestToken); - resume.TrySetResult(); - var remaining = await MessageRows.WaitForScheduledCountAsync(connectionString, 0, s_timeout, TestToken); - await cancellation.CancelAsync(); - await processing.WaitAsync(s_timeout, TestToken); + var result = await ExecuteScalarAsync(connectionString, NextWakeInterval); // assert - // The three pauses double from at least 100 milliseconds, which adds up to at least 0.7 seconds. - TimeSpan[] times = [.. attempts]; - Assert.Equal(0, timesSentAfterOutage); - Assert.Equal(0, remaining); - Assert.Equal(["A"], dispatch.Accepted); - Assert.InRange(times[unavailableAttempts] - times[0], TimeSpan.FromSeconds(0.5), s_timeout); + Assert.InRange(Assert.IsType(result), 25, 30); } [Fact] - public async Task ProcessAsync_Should_NotCountAttempt_When_HostStopsDuringDispatch() + public async Task NextWakeInterval_Should_ReturnNegativeSeconds_When_MessagePastFormerLimitIsDue() { // arrange var connectionString = await fixture.CreateDatabaseAsync(); - var dispatching = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var dispatch = new ScriptedDispatch(async attempt => - { - dispatching.TrySetResult(); - await Task.Delay(Timeout.InfiniteTimeSpan, attempt.CancellationToken); - }); - await using var provider = await CreateProviderAsync(connectionString, dispatch); - var id = await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); - using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); - var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); - await dispatching.Task.WaitAsync(s_timeout, TestToken); + await using var provider = await CreateProviderAsync( + connectionString, + new ScriptedDispatch(static attempt => attempt.SendAsync())); + await InsertRowAsync(connectionString, "NOW() + INTERVAL '60 seconds'", timesSent: 0); + await InsertRowAsync(connectionString, "NOW() - INTERVAL '30 seconds'", timesSent: 10); // act - await cancellation.CancelAsync(); - await processing.WaitAsync(s_timeout, TestToken); - var timesSent = await MessageRows.GetScheduledTimesSentAsync(connectionString, id, TestToken); + var result = await ExecuteScalarAsync(connectionString, NextWakeInterval); // assert - Assert.Equal(0, timesSent); - Assert.Equal(1, dispatch.AttemptsOf("A")); + Assert.InRange(Assert.IsType(result), -35, -25); + } + + private static string NextWakeInterval + => ScheduledMessageQueries.From(new ScheduledMessageTableInfo()).NextWakeInterval; + + private static Task InsertRowAsync(string connectionString, string scheduledTime, int timesSent) + => ExecuteAsync( + connectionString, + $""" + INSERT INTO "scheduled_messages" + ("id", "envelope", "scheduled_time", "times_sent", "max_attempts", "created_at") + VALUES (gen_random_uuid(), '{EmptyEnvelope}', {scheduledTime}, {timesSent}, 10, NOW()); + """); + + private static Task ExecuteAsync(string connectionString, string sql) + => ExecuteScalarAsync(connectionString, sql); + + private static async Task ExecuteScalarAsync(string connectionString, string sql) + { + await using var connection = new NpgsqlConnection(connectionString); + await connection.OpenAsync(TestToken); + await using var command = connection.CreateCommand(); + command.CommandText = sql; + + var result = await command.ExecuteScalarAsync(TestToken); + + return result is DBNull ? null : result; + } + + // Polls the query until its value is the expected one or the timeout elapsed, and returns the last value. + private static async Task WaitForAsync(string connectionString, string sql, Func isExpected) + { + var deadline = DateTime.UtcNow + s_timeout; + var value = await ExecuteScalarAsync(connectionString, sql); + + while (!isExpected(value) && DateTime.UtcNow < deadline) + { + await Task.Delay(20, TestToken); + value = await ExecuteScalarAsync(connectionString, sql); + } + + return value; } private static MessageEnvelope CreateEnvelope(IServiceProvider provider, string messageId) @@ -223,5 +230,23 @@ private static async Task CreateProviderAsync(string connection return provider; } + private static RunningDispatcher StartDispatcher(IServiceProvider provider) + { + var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); + return new RunningDispatcher(processing, cancellation); + } + public sealed record ScheduledEvent(string Name); + + // Stops the dispatcher like a host does and waits until it has returned. + private sealed class RunningDispatcher(Task processing, CancellationTokenSource cancellation) : IAsyncDisposable + { + public async ValueTask DisposeAsync() + { + await cancellation.CancelAsync(); + await processing.WaitAsync(s_timeout, TestToken); + cancellation.Dispose(); + } + } } diff --git a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md index e7e4ca89dc6..52f711e2cfd 100644 --- a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md +++ b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md @@ -26,13 +26,28 @@ Outbox message (message ID , type ) to fail - A message that cannot be read, has an unknown message type, or matches no endpoint is retried in the same way. Its Critical entry shows `(null)` for the message ID, the type, and the destination when the stored envelope cannot be read. - A failed dispatch no longer ends the processing run. The processor logs the exception at Error with the text `The dispatch of outbox message (message ID , type ) to failed on attempt . The message is retried.` and continues with the next message. In 16.7 the failure was logged as `An unexpected error occurred while processing outbox event`. Change alert rules that match that text for a failed dispatch. -## Scheduled messages and redeliveries keep their attempts during a RabbitMQ outage +## The Postgres scheduler no longer stops retrying a scheduled message This entry applies to the Postgres-backed scheduled message store that `UsePostgresScheduling()` registers. With RabbitMQ it stores scheduled messages and [redeliveries](../reliability.md#redeliver-failed-messages). -A dispatch that fails with `TransportUnavailableException`, or that a host stop interrupts, no longer counts towards the 10 attempts of a scheduled message. In 16.7 every dispatch that failed with an exception counted, so a broker outage could use up all attempts of the scheduled messages and redeliveries that came due. Every other failure still counts and is recorded in the `last_error` column. +In 16.7 the scheduler stopped dispatching a scheduled message after 10 attempts and delayed each attempt twice as long as the one before. In 16.8 the scheduler dispatches a message until the transport accepts it. -Only the RabbitMQ transport throws `TransportUnavailableException`. See [Retry behavior](../scheduling.md#retry-behavior). +- A message that fails is dispatched again after 10 seconds. The delay does not grow with the number of attempts. +- After a failed dispatch the scheduler pauses for 10 seconds before it dispatches the next message. Other due messages can be up to 10 seconds late while a message fails. +- The `times_sent` column still counts the attempts. The `max_attempts` column is no longer applied. +- A message that failed 10 times in 16.7 stays in the table and is dispatched after the update. Delete the rows that must not be sent before you update: + + ```sql + DELETE FROM scheduled_messages + WHERE times_sent >= max_attempts; + ``` + +- A scheduled message can be cancelled at any attempt count. In 16.7 a message that had used all attempts could not be cancelled. +- When the attempt count of a message is a multiple of 10, the dispatcher writes the Critical entry `Scheduled message (message ID , type ) to failed on attempt . The message is retried.` The 16.7 entry `Scheduled message exhausted all 10 retry attempts and will not be retried.` is no longer written. Change alert rules that match it. +- The index on `scheduled_time` no longer has the filter `"times_sent" < "max_attempts"`. Add an EF Core migration to apply the change. Without it the scheduler works, but its queries do not use the index. +- The scheduler wakes at the time the next message is due. In 16.7 it woke 1 second late for a new message and later for a retry. + +See [Retry behavior](../scheduling.md#retry-behavior). ## RequestAsync cancels a dispatch that outlasts the response timeout diff --git a/website/content/docs/mocha/scheduling.md b/website/content/docs/mocha/scheduling.md index 06d9e87a058..d3cd1580d90 100644 --- a/website/content/docs/mocha/scheduling.md +++ b/website/content/docs/mocha/scheduling.md @@ -245,9 +245,7 @@ The PostgreSQL, InMemory, and Azure Service Bus transports each have a schedulin ## Retry behavior -This section applies to the Postgres-backed scheduled message store, used natively by the PostgreSQL transport or through the `UsePostgresScheduling()` fallback for RabbitMQ. If a scheduled message fails to dispatch, the scheduler retries with exponential backoff. Each failed attempt increases the wait time before the next retry. After 10 attempts (the default `max_attempts`), the message is no longer eligible for dispatch. You can inspect failed messages by querying the `scheduled_messages` table and checking the `last_error` column. - -A dispatch that fails with `TransportUnavailableException`, which the RabbitMQ transport throws when the broker cannot be reached or does not confirm in time, does not count as an attempt. Neither does a dispatch that a host stop interrupts. The message keeps its scheduled time and is dispatched again after a pause of about 100 milliseconds to 10 seconds. +This section applies to the Postgres-backed scheduled message store, used natively by the PostgreSQL transport or through the `UsePostgresScheduling()` fallback for RabbitMQ. If a scheduled message fails to dispatch, the scheduler dispatches it again after 10 seconds, until the transport accepts it. The `times_sent` column counts the attempts and the `last_error` column holds the last failure. After a failed dispatch the scheduler also pauses for 10 seconds, so other due messages can be up to 10 seconds late while a message fails. When the attempt count of a message is a multiple of 10, the dispatcher logs a `Critical` entry. The `max_attempts` column is not applied. The InMemory transport's store does not retry failed dispatches. If a scheduled message fails to dispatch, it is dropped and the failure is logged. @@ -314,15 +312,15 @@ Check that the background worker is running. Look for `Scheduler sleeping until Messages scheduled for a time in the past are dispatched immediately. Verify that your `ScheduledTime` is in the future. **"The message will be retried" warnings in logs.** -The Postgres-backed dispatcher logs at `Warning` level when it cannot read or route a scheduled message, and leaves the row in place for a later attempt by this or another instance. The log message names the cause: `Could not deserialize message body` means the stored envelope could not be parsed, `Could not resolve the message type` means the message type is not registered in the dispatching instance (for example after it was renamed or removed, or before a rolling deployment has reached every instance), and `Could not resolve a dispatch endpoint for the destination` means no transport in the dispatching instance can deliver to the stored destination address. Each attempt counts toward `max_attempts`. After the last attempt, the dispatcher logs `exhausted all ... retry attempts` at `Critical` level and the message is no longer eligible for dispatch. +The Postgres-backed dispatcher logs at `Warning` level when it cannot read or route a scheduled message, and leaves the row in place for a later attempt by this or another instance. The log message names the cause: `Could not deserialize message body` means the stored envelope could not be parsed, `Could not resolve the message type` means the message type is not registered in the dispatching instance (for example after it was renamed or removed, or before a rolling deployment has reached every instance), and `Could not resolve a dispatch endpoint for the destination` means no transport in the dispatching instance can deliver to the stored destination address. The message is retried every 10 seconds. On every 10th attempt the dispatcher logs `failed on attempt ... The message is retried.` at `Critical` level. **Scheduled messages fail repeatedly (Postgres-backed scheduling).** -The Postgres-backed dispatcher records each failure in the `last_error` column and retries with exponential backoff. After 10 attempts, the message is no longer eligible for dispatch. Query the `scheduled_messages` table and inspect the `last_error` column for diagnostics: +The Postgres-backed dispatcher records each failure in the `last_error` column and retries every 10 seconds until the transport accepts the message. Query the `scheduled_messages` table and inspect the `last_error` column for diagnostics: ```sql SELECT id, scheduled_time, times_sent, last_error FROM scheduled_messages -WHERE times_sent >= max_attempts; +WHERE times_sent > 0; ``` The in-memory transport does not retry or record errors: a scheduled message whose dispatch fails is dropped, and the failure is logged.