Skip to content

Commit

Permalink
Adopt System.TimeProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
martintmk committed May 17, 2023
1 parent f4d5347 commit d8ce39f
Show file tree
Hide file tree
Showing 12 changed files with 40 additions and 72 deletions.
3 changes: 2 additions & 1 deletion src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
<PackageVersion Include="BenchmarkDotNet" Version="0.13.5" />
<PackageVersion Include="FluentAssertions" Version="6.11.0" />
<PackageVersion Include="GitHubActionsTestLogger" Version="2.1.0" />
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="1.0.0" />
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="6.0.0" />
<PackageVersion Include="Microsoft.Bcl.TimeProvider" Version="8.0.0-preview.4.23259.5" />
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="7.0.1" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
Expand Down
8 changes: 4 additions & 4 deletions src/Polly.Core.Tests/Hedging/HedgingTimeProvider.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Threading.Tasks;
using Polly.Utils;

namespace Polly.Core.Tests.Hedging;

Expand All @@ -25,15 +24,16 @@ public void Advance(TimeSpan diff)

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

public override DateTimeOffset UtcNow => _utcNow;
public override DateTimeOffset GetUtcNow() => _utcNow;

public override void CancelAfter(CancellationTokenSource source, TimeSpan delay)
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
throw new NotSupportedException();
return base.CreateTimer(callback, state, dueTime, period);
}

public override Task Delay(TimeSpan delayValue, CancellationToken cancellationToken = default)
{

var entry = new DelayEntry(delayValue, new TaskCompletionSource<bool>(), _utcNow.Add(delayValue));
cancellationToken.Register(() => entry.Source.TrySetCanceled(cancellationToken));
DelayEntries.Add(entry);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ private void CloseCircuit_NeedsLock<TResult>(Outcome<TResult> outcome, bool manu

private bool PermitHalfOpenCircuitTest_NeedsLock()
{
var now = _timeProvider.UtcNow;
var now = _timeProvider.GetUtcNow();
if (now >= _blockedUntil)
{
_blockedUntil = now + _breakDuration;
Expand Down Expand Up @@ -307,7 +307,7 @@ private void OpenCircuit_NeedsLock<TResult>(Outcome<TResult> outcome, bool manua
private void OpenCircuitFor_NeedsLock<TResult>(Outcome<TResult> outcome, TimeSpan breakDuration, bool manual, ResilienceContext context, out Task? scheduledTask)
{
scheduledTask = null;
var utcNow = _timeProvider.UtcNow;
var utcNow = _timeProvider.GetUtcNow();

_blockedUntil = IsDateTimeOverflow(utcNow, breakDuration) ? DateTimeOffset.MaxValue : utcNow + breakDuration;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public override HealthInfo GetHealthInfo()

private HealthWindow UpdateCurrentWindow()
{
var now = TimeProvider.UtcNow;
var now = TimeProvider.GetUtcNow();
if (_currentWindow == null || now - _currentWindow.StartedAt >= _windowDuration)
{
_currentWindow = new()
Expand Down
6 changes: 3 additions & 3 deletions src/Polly.Core/CircuitBreaker/Health/SingleHealthMetrics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public SingleHealthMetrics(TimeSpan samplingDuration, TimeProvider timeProvider)
: base(timeProvider)
{
_samplingDuration = samplingDuration;
_startedAt = timeProvider.UtcNow;
_startedAt = timeProvider.GetUtcNow();
}

public override void IncrementSuccess()
Expand All @@ -32,7 +32,7 @@ public override void IncrementFailure()

public override void Reset()
{
_startedAt = TimeProvider.UtcNow;
_startedAt = TimeProvider.GetUtcNow();
_successes = 0;
_failures = 0;
}
Expand All @@ -46,7 +46,7 @@ public override HealthInfo GetHealthInfo()

private void TryReset()
{
if (TimeProvider.UtcNow - _startedAt >= _samplingDuration)
if (TimeProvider.GetUtcNow() - _startedAt >= _samplingDuration)
{
Reset();
}
Expand Down
2 changes: 1 addition & 1 deletion src/Polly.Core/Hedging/Controller/HedgingController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public HedgingController(TimeProvider provider, HedgingHandler.Handler handler,
_executionPool = new ObjectPool<TaskExecution>(() =>
{
Interlocked.Increment(ref _rentedExecutions);
return new TaskExecution(handler);
return new TaskExecution(handler, provider);
},
_ =>
{
Expand Down
9 changes: 7 additions & 2 deletions src/Polly.Core/Hedging/Controller/TaskExecution.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,16 @@ internal sealed class TaskExecution
{
private readonly ResilienceContext _cachedContext = ResilienceContext.Get();
private readonly HedgingHandler.Handler _handler;
private readonly TimeProvider _timeProvider;
private CancellationTokenSource? _cancellationSource;
private CancellationTokenRegistration? _cancellationRegistration;
private ResilienceContext? _activeContext;

public TaskExecution(HedgingHandler.Handler handler) => _handler = handler;
public TaskExecution(HedgingHandler.Handler handler, TimeProvider timeProvider)
{
_handler = handler;
_timeProvider = timeProvider;
}

/// <summary>
/// Gets the task that represents the execution of the hedged task.
Expand Down Expand Up @@ -81,7 +86,7 @@ public async ValueTask<bool> InitializeAsync<TResult, TState>(
int attempt)
{
Type = type;
_cancellationSource = CancellationTokenSourcePool.Get();
_cancellationSource = CancellationTokenSourcePool.Get(TimeSpan.Zero, _timeProvider);
Properties.Replace(snapshot.OriginalProperties);

if (snapshot.OriginalCancellationToken.CanBeCanceled)
Expand Down
1 change: 0 additions & 1 deletion src/Polly.Core/Hedging/HedgingResilienceStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using Polly.Hedging;
using Polly.Hedging.Utils;
using Polly.Strategy;
using Polly.Utils;

namespace Polly;

Expand Down
1 change: 1 addition & 0 deletions src/Polly.Core/Polly.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Condition="!$([MSBuild]::IsTargetFrameworkCompatible($(TargetFramework), 'netcoreapp3.1'))" />
<PackageReference Include="Microsoft.Bcl.TimeProvider" />
<PackageReference Include="System.Threading.Tasks.Extensions" Condition="!$([MSBuild]::IsTargetFrameworkCompatible($(TargetFramework), 'netcoreapp3.1'))" />
<PackageReference Include="System.ValueTuple" Condition="$([MSBuild]::GetTargetFrameworkIdentifier('$(TargetFramework)')) == '.NETFramework'" />
<PackageReference Include="System.ComponentModel.Annotations" Condition="!$([MSBuild]::IsTargetFrameworkCompatible($(TargetFramework), 'netcoreapp3.1'))" />
Expand Down
3 changes: 1 addition & 2 deletions src/Polly.Core/Timeout/TimeoutResilienceStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ protected internal override async ValueTask<TResult> ExecuteCoreAsync<TResult, T
}

var previousToken = context.CancellationToken;
var cancellationSource = CancellationTokenSourcePool.Get();
_timeProvider.CancelAfter(cancellationSource, timeout);
var cancellationSource = CancellationTokenSourcePool.Get(timeout, _timeProvider);

This comment has been minimized.

Copy link
@martincostello

martincostello May 17, 2023

Member

Thanks for doing this - I had a quick go yesterday for #1144 locally and then I wasn't sure what to do about this 😄

context.CancellationToken = cancellationSource.Token;

CancellationTokenRegistration? registration = null;
Expand Down
21 changes: 18 additions & 3 deletions src/Polly.Core/Utils/CancellationTokenSourcePool.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
using System.Threading;
using System.Threading.Tasks;

namespace Polly.Utils
{
internal static class CancellationTokenSourcePool
Expand All @@ -7,12 +10,24 @@ internal static class CancellationTokenSourcePool
static () => new CancellationTokenSource(),
static cts => true);
#endif
public static CancellationTokenSource Get()
public static CancellationTokenSource Get(TimeSpan delay, TimeProvider timeProvider)
{
#if NET6_0_OR_GREATER
return Pool.Get();
if (timeProvider != TimeProvider.System)
{
return timeProvider.CreateCancellationTokenSource(delay);
}

// we are only polling sources when system time provider is used
var pooledSource = Pool.Get();
if (delay != System.Threading.Timeout.InfiniteTimeSpan)
{
pooledSource.CancelAfter(delay);
}

return pooledSource;
#else
return new CancellationTokenSource();
return timeProvider.CreateCancellationTokenSource(delay);
#endif
}

Expand Down
52 changes: 0 additions & 52 deletions src/Polly.Core/Utils/TimeProvider.cs

This file was deleted.

0 comments on commit d8ce39f

Please sign in to comment.