Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drop TimeProvider.Delay #1355

Merged
merged 4 commits into from
Jun 26, 2023
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
1 change: 1 addition & 0 deletions src/Polly.Core/Retry/RetryResilienceStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ protected override async ValueTask<Outcome<T>> ExecuteCallbackAsync<TState>(Func
await DisposeHelper.TryDisposeSafeAsync(resultValue, context.IsSynchronous).ConfigureAwait(context.ContinueOnCapturedContext);
}

// stryker disable once equality : no means to test this
if (delay > TimeSpan.Zero)
{
try
Expand Down
3 changes: 0 additions & 3 deletions src/Polly.Core/ToBeRemoved/TimeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,6 @@ public DateTimeOffset GetLocalNow()

public virtual long GetTimestamp() => Stopwatch.GetTimestamp();

// This one is not on TimeProvider, temporarly we need to use it
public virtual Task Delay(TimeSpan delay, CancellationToken cancellationToken = default) => Task.Delay(delay, cancellationToken);

public TimeSpan GetElapsedTime(long startingTimestamp, long endingTimestamp)
{
long timestampFrequency = TimestampFrequency;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,11 @@ public async Task TryWaitForCompletedExecutionAsync_HedgedExecution_Ok()
}

var hedgingDelay = TimeSpan.FromSeconds(5);
var count = _timeProvider.DelayEntries.Count;
var count = _timeProvider.TimerEntries.Count;
var task = context.TryWaitForCompletedExecutionAsync(hedgingDelay).AsTask();
task.Wait(20).Should().BeFalse();
_timeProvider.DelayEntries.Should().HaveCount(count + 1);
_timeProvider.DelayEntries.Last().Delay.Should().Be(hedgingDelay);
_timeProvider.TimerEntries.Should().HaveCount(count + 1);
_timeProvider.TimerEntries.Last().Delay.Should().Be(hedgingDelay);
_timeProvider.Advance(TimeSpan.FromDays(1));
await task;
await context.Tasks[0].ExecutionTaskSafe!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,11 @@ public void ExecutePrimaryAndSecondary_EnsureAttemptReported()
var attempts = _events.Select(v => v.Arguments).OfType<ExecutionAttemptArguments>().ToArray();

attempts[0].Handled.Should().BeTrue();
attempts[0].ExecutionTime.Should().Be(_timeProvider.GetElapsedTime(0, 1000));
attempts[0].ExecutionTime.Should().BeGreaterThan(TimeSpan.Zero);
attempts[0].Attempt.Should().Be(0);

attempts[1].Handled.Should().BeTrue();
attempts[1].ExecutionTime.Should().Be(_timeProvider.GetElapsedTime(0, 1000));
attempts[1].ExecutionTime.Should().BeGreaterThan(TimeSpan.Zero);
attempts[1].Attempt.Should().Be(1);
}

Expand Down Expand Up @@ -164,7 +164,7 @@ public async Task ExecuteAsync_ShouldReturnAnyPossibleResult()
var result = await strategy.ExecuteAsync(_primaryTasks.SlowTask);

result.Should().NotBeNull();
_timeProvider.DelayEntries.Should().HaveCount(5);
_timeProvider.TimerEntries.Should().HaveCount(5);
result.Should().Be("Oranges");
}

Expand Down Expand Up @@ -865,7 +865,7 @@ public async Task ExecuteAsync_EnsureHedgingDelayGeneratorRespected()

_timeProvider.Advance(TimeSpan.FromHours(5));
(await task).Should().Be(Success);
_timeProvider.DelayEntries.Should().Contain(e => e.Delay == delay);
_timeProvider.TimerEntries.Should().Contain(e => e.Delay == delay);
}

[Fact]
Expand Down
33 changes: 22 additions & 11 deletions test/Polly.Core.Tests/Hedging/HedgingTimeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,44 @@ public void Advance(TimeSpan diff)
{
_utcNow = _utcNow.Add(diff);

foreach (var entry in DelayEntries.Where(e => e.TimeStamp <= _utcNow))
foreach (var entry in TimerEntries.Where(e => e.TimeStamp <= _utcNow))
{
entry.Complete();
}
}

public Func<int> TimeStampProvider { get; set; } = () => 0;

public List<DelayEntry> DelayEntries { get; } = new List<DelayEntry>();
public List<TimerEntry> TimerEntries { get; } = new List<TimerEntry>();

public override DateTimeOffset GetUtcNow() => _utcNow;

public override long GetTimestamp() => TimeStampProvider();

public override Task Delay(TimeSpan delayValue, CancellationToken cancellationToken = default)
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
var entry = new DelayEntry(delayValue, new TaskCompletionSource<bool>(), _utcNow.Add(delayValue));
cancellationToken.Register(() => entry.Source.TrySetCanceled(cancellationToken));
DelayEntries.Add(entry);
var entry = new TimerEntry(dueTime, new TaskCompletionSource<bool>(), _utcNow.Add(dueTime), () => callback(state));
TimerEntries.Add(entry);

Advance(AutoAdvance);

return entry.Source.Task;
return entry;
}

public record DelayEntry(TimeSpan Delay, TaskCompletionSource<bool> Source, DateTimeOffset TimeStamp)
public record TimerEntry(TimeSpan Delay, TaskCompletionSource<bool> Source, DateTimeOffset TimeStamp, Action Callback) : ITimer
{
public void Complete() => Source.TrySetResult(true);
public bool Change(TimeSpan dueTime, TimeSpan period) => throw new NotSupportedException();

public void Complete()
{
Callback();
Source.TrySetResult(true);
}

public void Dispose() => Source.TrySetResult(true);

public ValueTask DisposeAsync()
{
Source.TrySetResult(true);
return default;
}
}
}
35 changes: 29 additions & 6 deletions test/Polly.Core.Tests/Helpers/MockTimeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,44 @@ public MockTimeProvider()
{
}

public MockTimeProvider SetupAnyDelay(CancellationToken cancellationToken = default)
public MockTimeProvider SetupAnyCreateTimer()
{
Setup(x => x.Delay(It.IsAny<TimeSpan>(), cancellationToken)).Returns(Task.CompletedTask);
Setup(t => t.CreateTimer(It.IsAny<TimerCallback>(), It.IsAny<object?>(), It.IsAny<TimeSpan>(), It.IsAny<TimeSpan>()))
.Callback((TimerCallback callback, object? state, TimeSpan _, TimeSpan _) => callback(state))
.Returns(Of<ITimer>());

return this;
}

public MockTimeProvider SetupDelay(TimeSpan delay, CancellationToken cancellationToken = default)
public Mock<ITimer> SetupCreateTimer(TimeSpan delay)
{
var timer = new Mock<ITimer>(MockBehavior.Loose);

Setup(t => t.CreateTimer(It.IsAny<TimerCallback>(), It.IsAny<object?>(), delay, It.IsAny<TimeSpan>()))
.Callback((TimerCallback callback, object? state, TimeSpan _, TimeSpan _) => callback(state))
.Returns(timer.Object);

return timer;
}

public MockTimeProvider VerifyCreateTimer(Times times)
{
Setup(x => x.Delay(delay, cancellationToken)).Returns(Task.CompletedTask);
Verify(t => t.CreateTimer(It.IsAny<TimerCallback>(), It.IsAny<object?>(), It.IsAny<TimeSpan>(), It.IsAny<TimeSpan>()), times);
return this;
}

public MockTimeProvider SetupDelayCancelled(TimeSpan delay, CancellationToken cancellationToken = default)
public MockTimeProvider VerifyCreateTimer(TimeSpan delay, Times times)
{
Setup(x => x.Delay(delay, cancellationToken)).ThrowsAsync(new OperationCanceledException());
Verify(t => t.CreateTimer(It.IsAny<TimerCallback>(), It.IsAny<object?>(), delay, It.IsAny<TimeSpan>()), times);
return this;
}

public MockTimeProvider SetupCreateTimerException(TimeSpan delay, Exception exception)
{
Setup(t => t.CreateTimer(It.IsAny<TimerCallback>(), It.IsAny<object?>(), delay, It.IsAny<TimeSpan>()))
.Callback((TimerCallback _, object? _, TimeSpan _, TimeSpan _) => throw exception)
.Returns(Of<ITimer>());

return this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public void HandleMultipleResults_898()
};

// create the strategy
var strategy = new ResilienceStrategyBuilder { TimeProvider = TimeProvider }.AddRetry(options).Build();
var strategy = new ResilienceStrategyBuilder().AddRetry(options).Build();

// check that int-based results is retried
bool isRetry = false;
Expand Down
Loading