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 78df7cd4304..f577b686fc9 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs @@ -16,12 +16,22 @@ namespace Mocha.Scheduling; /// public sealed class ScheduledMessageDispatcher { + // 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; 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 +68,7 @@ internal ScheduledMessageDispatcher( _signal = signal; _contextPool = pools.DispatchContext; _options = options; + _timeProvider = services.GetService() ?? TimeProvider.System; } /// @@ -71,12 +82,18 @@ public async Task ProcessAsync(CancellationToken cancellationToken) { try { - var nextWakeTime = await ProcessPendingAsync(cancellationToken); + var result = await ProcessPendingAsync(cancellationToken); - if (nextWakeTime is not null) + if (result.Status is MessageStatus.DispatchFailed) + { + // 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 (result.NextWakeTime is { } nextWakeTime) { - _logger.SchedulerSleepingUntil(nextWakeTime.Value); - await _signal.WaitUntilAsync(nextWakeTime.Value, cancellationToken); + _logger.SchedulerSleepingUntil(nextWakeTime); + await _signal.WaitUntilAsync(nextWakeTime, cancellationToken); } else { @@ -91,36 +108,56 @@ public async Task ProcessAsync(CancellationToken cancellationToken) } } - private async ValueTask ProcessPendingAsync(CancellationToken cancellationToken) + private async ValueTask ProcessPendingAsync(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) { + var result = await ProcessMessageAsync(connection, cancellationToken); + + if (result.Status is not MessageStatus.Processed) + { + return result; + } + cancellationToken.ThrowIfCancellationRequested(); } - - return await GetNextWakeTimeAsync(connection, cancellationToken); } private async Task GetNextWakeTimeAsync( 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); + 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 result is not null and not DBNull - ? new DateTimeOffset((DateTime)result, TimeSpan.Zero) - : null; + return secondsUntilDue < (DateTimeOffset.MaxValue - now).TotalSeconds + ? now.AddSeconds(secondsUntilDue) + : DateTimeOffset.MaxValue; } - private async Task ProcessMessageAsync(NpgsqlConnection connection, CancellationToken cancellationToken) + private async Task ProcessMessageAsync( + NpgsqlConnection connection, + CancellationToken cancellationToken) { using var activity = OpenTelemetry.Source.StartActivity( "Process Scheduled Message Event", @@ -146,16 +183,15 @@ private async Task ProcessMessageAsync(NpgsqlConnection connection, Cancel 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. + // retried after the retry delay. if (envelope is null) { _logger.CouldNotDeserializeScheduledMessageBody(id); - LogIfExhausted(id, timesSent, maxAttempts); + LogIfRepeatedlyFailed(id, null, timesSent); - return true; + return MessageResult.Processed; } var messageType = GetMessageType(envelope.MessageType); @@ -163,9 +199,9 @@ private async Task ProcessMessageAsync(NpgsqlConnection connection, Cancel if (messageType is null) { _logger.CouldNotResolveScheduledMessageType(id, envelope.MessageType); - LogIfExhausted(id, timesSent, maxAttempts); + LogIfRepeatedlyFailed(id, envelope, timesSent); - return true; + return MessageResult.Processed; } var endpoint = ResolveDispatchEndpoint(envelope); @@ -173,9 +209,9 @@ private async Task ProcessMessageAsync(NpgsqlConnection connection, Cancel if (endpoint is null) { _logger.CouldNotDetermineScheduledMessageDestination(id, envelope.DestinationAddress); - LogIfExhausted(id, timesSent, maxAttempts); + LogIfRepeatedlyFailed(id, envelope, timesSent); - return true; + return MessageResult.Processed; } try @@ -186,7 +222,7 @@ private async Task ProcessMessageAsync(NpgsqlConnection connection, Cancel await DeleteMessageAsync(connection, id, transaction, cancellationToken); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { _logger.ScheduledMessageDispatchFailed(id, ex); @@ -194,14 +230,21 @@ private async Task ProcessMessageAsync(NpgsqlConnection connection, Cancel await UpdateLastErrorAsync(connection, id, ex, transaction, cancellationToken); - LogIfExhausted(id, timesSent, maxAttempts); + LogIfRepeatedlyFailed(id, envelope, timesSent); + + return MessageResult.DispatchFailed; } - return true; + return MessageResult.Processed; } else { - return false; + // The wake time is read in the transaction of the claim, so that both see the same time. + await reader.CloseAsync(); + + return new MessageResult( + MessageStatus.NoneDue, + await GetNextWakeTimeAsync(connection, transaction, cancellationToken)); } } finally @@ -234,14 +277,38 @@ private async Task ProcessMessageAsync(NpgsqlConnection connection, Cancel } } - private void LogIfExhausted(Guid id, int timesSent, int maxAttempts) + private void LogIfRepeatedlyFailed(Guid id, MessageEnvelope? envelope, int timesSent) { - if (timesSent >= maxAttempts) + if (timesSent % CriticalAttemptInterval == 0) { - _logger.ScheduledMessageExhausted(id, maxAttempts); + _logger.ScheduledMessageFailedRepeatedly( + id, + envelope?.MessageId, + envelope?.MessageType, + envelope?.DestinationAddress, + timesSent); } } + private readonly record struct MessageResult(MessageStatus Status, DateTimeOffset? NextWakeTime) + { + public static MessageResult Processed { get; } = new(MessageStatus.Processed, null); + + public static MessageResult DispatchFailed { get; } = new(MessageStatus.DispatchFailed, null); + } + + private enum MessageStatus + { + // 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) { try @@ -410,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, diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs index 2e707bd70bd..8d3f6af9647 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageQueries.cs @@ -8,15 +8,21 @@ 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. /// 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, @@ -35,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!; @@ -54,20 +59,19 @@ 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" - FROM {t.QualifiedTableName} - WHERE "{t.TimesSent}" < "{t.MaxAttempts}"; + NextWakeInterval = $""" + SELECT (EXTRACT(EPOCH FROM MIN("{t.ScheduledTime}")) - EXTRACT(EPOCH FROM NOW()))::double precision + AS "SecondsUntilDue" + 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 @@ -75,8 +79,7 @@ LIMIT 1 RETURNING "{t.Id}", "{t.Envelope}", - "{t.TimesSent}", - "{t.MaxAttempts}"; + "{t.TimesSent}"; """, DeleteMessage = $""" @@ -93,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/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs new file mode 100644 index 00000000000..25144aa6a70 --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs @@ -0,0 +1,252 @@ +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 const string EmptyEnvelope = "{}"; + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task ProcessAsync_Should_DispatchMessage_When_AttemptCountExceedsFormerLimit() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var dispatch = new ScriptedDispatch(static attempt => attempt.SendAsync()); + await using var provider = await CreateProviderAsync(connectionString, dispatch); + await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); + await ExecuteAsync(connectionString, """UPDATE "scheduled_messages" SET "times_sent" = 10;"""); + object? remaining; + + // act + await using (StartDispatcher(provider)) + { + remaining = await WaitForAsync( + connectionString, + """SELECT COUNT(*) FROM "scheduled_messages";""", + static count => count is 0L); + } + + // assert + Assert.Equal(0L, remaining); + Assert.Equal(["A"], dispatch.Accepted); + } + + [Fact] + public async Task ProcessAsync_Should_ScheduleRetryTenSecondsAhead_When_DispatchFails() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + 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); + object? timesSent; + + // act + 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.Equal(1, timesSent); + Assert.InRange(Assert.IsType(secondsUntilDue), 5, 10); + } + + [Fact] + public async Task ProcessAsync_Should_NotDispatchNextMessage_When_DispatchFailed() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + 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); + await MessageRows.InsertScheduledAsync(connectionString, CreateEnvelope(provider, "B"), TestToken); + object? remaining; + + // act + 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 + Assert.Equal(2L, remaining); + Assert.Equal(1, dispatch.AttemptsOf("A")); + Assert.Equal(0, dispatch.AttemptsOf("B")); + } + + [Fact] + public async Task NextWakeInterval_Should_ReturnNull_When_NoMessageIsScheduled() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + await using var provider = await CreateProviderAsync( + connectionString, + new ScriptedDispatch(static attempt => attempt.SendAsync())); + + // act + var result = await ExecuteScalarAsync(connectionString, NextWakeInterval); + + // 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 + var result = await ExecuteScalarAsync(connectionString, NextWakeInterval); + + // assert + Assert.InRange(Assert.IsType(result), 25, 30); + } + + [Fact] + public async Task NextWakeInterval_Should_ReturnNegativeSeconds_When_MessagePastFormerLimitIsDue() + { + // 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: 10); + + // act + var result = await ExecuteScalarAsync(connectionString, NextWakeInterval); + + // assert + 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) + { + 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; + } + + 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 314622f7d0e..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,6 +26,29 @@ 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. +## 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). + +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. + +- 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 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..d3cd1580d90 100644 --- a/website/content/docs/mocha/scheduling.md +++ b/website/content/docs/mocha/scheduling.md @@ -245,7 +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. +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. @@ -312,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.