Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ public sealed class ScheduledMessageTableInfo
public string CreatedAt { get; set; } = "created_at";

/// <summary>
/// Gets or sets the column name for the maximum number of dispatch attempts. Defaults to <c>"max_attempts"</c>.
/// Gets or sets the column name for the attempt limit, which the dispatcher does not apply.
/// Defaults to <c>"max_attempts"</c>.
/// </summary>
public string MaxAttempts { get; set; } = "max_attempts";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ public void Configure(EntityTypeBuilder<ScheduledMessage> 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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public sealed class ScheduledMessage(Guid id, JsonDocument envelope)
public int TimesSent { get; private set; }

/// <summary>
/// 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.
/// </summary>
public int MaxAttempts { get; private set; } = 10;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,22 @@ namespace Mocha.Scheduling;
/// </summary>
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<ScheduledMessageDispatcher> _logger;
private readonly IServiceProvider _services;
private readonly IMessagingRuntime _runtime;
private readonly ISchedulerSignal _signal;
private readonly ObjectPool<DispatchContext> _contextPool;
private readonly PostgresScheduledMessageOptions _options;
private readonly TimeProvider _timeProvider;

/// <summary>
/// Initializes a new instance of the <see cref="ScheduledMessageDispatcher"/> class.
Expand Down Expand Up @@ -58,6 +68,7 @@ internal ScheduledMessageDispatcher(
_signal = signal;
_contextPool = pools.DispatchContext;
_options = options;
_timeProvider = services.GetService<TimeProvider>() ?? TimeProvider.System;
}

/// <summary>
Expand All @@ -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
{
Expand All @@ -91,36 +108,56 @@ public async Task ProcessAsync(CancellationToken cancellationToken)
}
}

private async ValueTask<DateTimeOffset?> ProcessPendingAsync(CancellationToken cancellationToken)
private async ValueTask<MessageResult> 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<DateTimeOffset?> 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<bool> ProcessMessageAsync(NpgsqlConnection connection, CancellationToken cancellationToken)
private async Task<MessageResult> ProcessMessageAsync(
NpgsqlConnection connection,
CancellationToken cancellationToken)
{
using var activity = OpenTelemetry.Source.StartActivity(
"Process Scheduled Message Event",
Expand All @@ -146,36 +183,35 @@ private async Task<bool> 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);

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);

if (endpoint is null)
{
_logger.CouldNotDetermineScheduledMessageDestination(id, envelope.DestinationAddress);
LogIfExhausted(id, timesSent, maxAttempts);
LogIfRepeatedlyFailed(id, envelope, timesSent);

return true;
return MessageResult.Processed;
}

try
Expand All @@ -186,22 +222,29 @@ private async Task<bool> 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);

await reader.CloseAsync();

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
Expand Down Expand Up @@ -234,14 +277,38 @@ private async Task<bool> 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
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,21 @@ namespace Mocha.Scheduling;
/// </summary>
internal sealed class ScheduledMessageQueries
{
/// <summary>
/// The number of seconds after a failed dispatch before the message is dispatched again.
/// </summary>
public const int RetryDelaySeconds = 10;

/// <summary>
/// Gets or sets the SQL statement to insert a new scheduled message into the table.
/// </summary>
public string InsertMessage { get; set; } = null!;

/// <summary>
/// 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.
/// </summary>
public string NextWakeTime { get; set; } = null!;
public string NextWakeInterval { get; set; } = null!;

/// <summary>
/// Gets or sets the SQL statement that locks a single scheduled message row for processing,
Expand All @@ -35,8 +41,7 @@ internal sealed class ScheduledMessageQueries
public string UpdateLastError { get; set; } = null!;

/// <summary>
/// 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.
/// </summary>
public string CancelMessage { get; set; } = null!;

Expand All @@ -54,29 +59,27 @@ 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
)
RETURNING
"{t.Id}",
"{t.Envelope}",
"{t.TimesSent}",
"{t.MaxAttempts}";
"{t.TimesSent}";
""",

DeleteMessage = $"""
Expand All @@ -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}";
"""
};
Expand Down
Loading
Loading