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