Path: redb-route/redb.Route.IbmMq/IbmMqBackoutPause.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.IbmMq/IbmMqBackoutPause.cs
----
namespace redb.Route.IbmMq;
///
/// The consumer's pause after a backout (backoutDelay): once a worker backs a failed message (or batch) out, no
/// worker of the consumer starts another MQGET until the delay has passed, so the backed-out message is not taken again
/// at once. A later backout extends the pause; it never shortens it. A delay of zero keeps no pause.
///
internal sealed class IbmMqBackoutPause
{
private readonly TimeSpan _delay;
private readonly TimeProvider _time;
private long _resumeAt = long.MinValue;
public IbmMqBackoutPause(int delayMs, TimeProvider? time = null)
{
_delay = TimeSpan.FromMilliseconds(delayMs);
_time = time ?? TimeProvider.System;
}
/// Starts (or extends) the pause after a backout.
public void Begin()
{
if (_delay <= TimeSpan.Zero)
return;
var resumeAt = _time.GetTimestamp() + (long)(_delay.TotalSeconds * _time.TimestampFrequency);
long current;
do
{
current = Interlocked.Read(ref _resumeAt);
if (current >= resumeAt)
return;
}
while (Interlocked.CompareExchange(ref _resumeAt, resumeAt, current) != current);
}
/// What is left of the pause; zero when there is none.
public TimeSpan Remaining
{
get
{
var resumeAt = Interlocked.Read(ref _resumeAt);
if (resumeAt == long.MinValue)
return TimeSpan.Zero;
var left = resumeAt - _time.GetTimestamp();
return left <= 0 ? TimeSpan.Zero : TimeSpan.FromSeconds((double)left / _time.TimestampFrequency);
}
}
/// Waits out the pause, or at most when given.
public async Task WaitAsync(CancellationToken ct, TimeSpan? max = null)
{
var left = Remaining;
while (left > TimeSpan.Zero)
{
if (max is { } limit && left > limit)
left = limit;
await Task.Delay(left, _time, ct).ConfigureAwait(false);
if (max is not null)
return;
left = Remaining;
}
}
}