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

Adapt to SystemClock removal #84

Merged
merged 9 commits into from
Aug 31, 2024
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
7 changes: 3 additions & 4 deletions samples/Foundatio.SampleJob/PingQueueJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using Foundatio.Lock;
using Foundatio.Messaging;
using Foundatio.Queues;
using Foundatio.Utility;
using Microsoft.Extensions.Logging;

namespace Foundatio.SampleJob;
Expand All @@ -18,10 +17,10 @@ public class PingQueueJob : QueueJobBase<PingRequest>
private readonly ILockProvider _locker;
private int _runCount;

public PingQueueJob(IQueue<PingRequest> queue, ILoggerFactory loggerFactory, ICacheClient cacheClient, IMessageBus messageBus) : base(queue, loggerFactory)
public PingQueueJob(IQueue<PingRequest> queue, ILoggerFactory loggerFactory, ICacheClient cacheClient, IMessageBus messageBus) : base(queue, null, loggerFactory)
{
AutoComplete = true;
_locker = new CacheLockProvider(cacheClient, messageBus, loggerFactory);
_locker = new CacheLockProvider(cacheClient, messageBus, null, loggerFactory);
}

public int RunCount => _runCount;
Expand All @@ -39,7 +38,7 @@ protected override async Task<JobResult> ProcessQueueEntryAsync(QueueEntryContex

if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Got {RunCount} ping. Sending pong!", RunCount.ToOrdinal());
await SystemClock.SleepAsync(TimeSpan.FromMilliseconds(1)).AnyContext();
await Task.Delay(TimeSpan.FromMilliseconds(1)).AnyContext();

if (RandomData.GetBool(context.QueueEntry.Value.PercentChanceOfException))
throw new ApplicationException("Boom!");
Expand Down
4 changes: 2 additions & 2 deletions samples/Foundatio.SampleJob/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ public static int Main()
_logger = loggerFactory.CreateLogger("MessageBus");

var serviceProvider = SampleServiceProvider.Create(loggerFactory);
var jobOptions = JobOptions.GetDefaults<PingQueueJob>(() => serviceProvider.GetRequiredService<PingQueueJob>());
var jobOptions = JobOptions.GetDefaults<PingQueueJob>(_ => serviceProvider.GetRequiredService<PingQueueJob>());
var messageBus = serviceProvider.GetRequiredService<IMessageBus>();
messageBus.SubscribeAsync<EchoMessage>(m => HandleEchoMessage(m)).GetAwaiter().GetResult();
return new JobRunner(jobOptions).RunInConsoleAsync().GetAwaiter().GetResult();
return new JobRunner(jobOptions, serviceProvider).RunInConsoleAsync().GetAwaiter().GetResult();
}

private static void HandleEchoMessage(EchoMessage m)
Expand Down
2 changes: 1 addition & 1 deletion samples/Foundatio.SampleJob/SampleServiceProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static IServiceProvider Create(ILoggerFactory loggerFactory)
container.AddSingleton<IQueue<PingRequest>>(s => new RedisQueue<PingRequest>(o => o.ConnectionMultiplexer(muxer).RetryDelay(TimeSpan.FromSeconds(1)).WorkItemTimeout(TimeSpan.FromSeconds(5)).LoggerFactory(loggerFactory)));
container.AddSingleton<ICacheClient>(s => new RedisCacheClient(o => o.ConnectionMultiplexer(muxer).LoggerFactory(loggerFactory)));
container.AddSingleton<IMessageBus>(s => new RedisMessageBus(o => o.Subscriber(muxer.GetSubscriber()).LoggerFactory(loggerFactory).MapMessageTypeToClassName<EchoMessage>()));
container.AddSingleton<ILockProvider>(s => new CacheLockProvider(s.GetRequiredService<ICacheClient>(), s.GetRequiredService<IMessageBus>(), loggerFactory));
container.AddSingleton<ILockProvider>(s => new CacheLockProvider(s.GetRequiredService<ICacheClient>(), s.GetRequiredService<IMessageBus>(), null, loggerFactory));
container.AddTransient<PingQueueJob>();

return container.BuildServiceProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Foundatio.Xunit" Version="10.7.1" />
<PackageReference Include="Foundatio.Xunit" Version="11.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
5 changes: 2 additions & 3 deletions samples/Foundatio.SampleJobClient/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System.Threading.Tasks;
using Foundatio.Messaging;
using Foundatio.Queues;
using Foundatio.Utility;
using Foundatio.Xunit;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
Expand Down Expand Up @@ -97,7 +96,7 @@ private static void MonitorKeyPress()
{
while (!Console.KeyAvailable)
{
SystemClock.Sleep(250);
Thread.Sleep(250);
}
var key = Console.ReadKey(true).Key;

Expand All @@ -119,7 +118,7 @@ private static void DrawLoop()

Console.SetCursorPosition(0, OPTIONS_MENU_LINE_COUNT + 1);

SystemClock.Sleep(250);
Thread.Sleep(250);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/Foundatio.Redis/Foundatio.Redis.csproj
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" />
<ItemGroup>
<PackageReference Include="Foundatio" Version="10.7.1" Condition="'$(ReferenceFoundatioSource)' == '' OR '$(ReferenceFoundatioSource)' == 'false'" />
<PackageReference Include="Foundatio" Version="11.0.2" Condition="'$(ReferenceFoundatioSource)' == '' OR '$(ReferenceFoundatioSource)' == 'false'" />
<ProjectReference Include="..\..\..\Foundatio\src\Foundatio\Foundatio.csproj" Condition="'$(ReferenceFoundatioSource)' == 'true'" />

<PackageReference Include="StackExchange.Redis" Version="2.7.33" />
<PackageReference Include="StackExchange.Redis" Version="2.8.0" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Scripts\*.lua" />
Expand Down
17 changes: 0 additions & 17 deletions src/Foundatio.Redis/Metrics/RedisMetricsClient.cs

This file was deleted.

17 changes: 0 additions & 17 deletions src/Foundatio.Redis/Metrics/RedisMetricsClientOptions.cs

This file was deleted.

22 changes: 11 additions & 11 deletions src/Foundatio.Redis/Queues/RedisQueue.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
Expand Down Expand Up @@ -225,7 +225,7 @@ protected override async Task<string> EnqueueImplAsync(T data, QueueEntryOptions
return null;
}

var now = SystemClock.UtcNow;
var now = _timeProvider.GetUtcNow().UtcDateTime;
var envelope = new RedisPayloadEnvelope<T>
{
Properties = options.Properties,
Expand Down Expand Up @@ -386,7 +386,7 @@ protected override async Task<IQueueEntry<T>> DequeueImplAsync(CancellationToken
public override async Task RenewLockAsync(IQueueEntry<T> entry)
{
if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug("Queue {Name} renew lock item: {EntryId}", _options.Name, entry.Id);
await Run.WithRetriesAsync(() => _cache.SetAsync(GetRenewedTimeKey(entry.Id), SystemClock.UtcNow.Ticks, GetWorkItemTimeoutTimeTtl()), logger: _logger).AnyContext();
await Run.WithRetriesAsync(() => _cache.SetAsync(GetRenewedTimeKey(entry.Id), _timeProvider.GetUtcNow().Ticks, GetWorkItemTimeoutTimeTtl()), logger: _logger).AnyContext();
await OnLockRenewedAsync(entry).AnyContext();
if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace("Renew lock done: {EntryId}", entry.Id);
}
Expand Down Expand Up @@ -423,7 +423,7 @@ private async Task<RedisValue> DequeueIdAsync(CancellationToken linkedCancellati
return await Run.WithRetriesAsync(async () =>
{
var timeout = GetWorkItemTimeoutTimeTtl();
long now = SystemClock.UtcNow.Ticks;
long now = _timeProvider.GetUtcNow().Ticks;

await LoadScriptsAsync().AnyContext();
var result = await Database.ScriptEvaluateAsync(_dequeueId, new
Expand All @@ -435,7 +435,7 @@ private async Task<RedisValue> DequeueIdAsync(CancellationToken linkedCancellati
timeout = timeout.TotalMilliseconds
}).AnyContext();
return result.ToString();
}, 3, TimeSpan.FromMilliseconds(100), linkedCancellationToken, _logger).AnyContext();
}, 3, TimeSpan.FromMilliseconds(100), _timeProvider, linkedCancellationToken, _logger).AnyContext();
}
catch (Exception ex)
{
Expand Down Expand Up @@ -518,7 +518,7 @@ await Run.WithRetriesAsync(() => Task.WhenAll(
_logger.LogInformation("Adding item to wait list for future retry: {EntryId}", entry.Id);

await Run.WithRetriesAsync(() => Task.WhenAll(
_cache.SetAsync(GetWaitTimeKey(entry.Id), SystemClock.UtcNow.Add(retryDelay).Ticks, GetWaitTimeTtl()),
_cache.SetAsync(GetWaitTimeKey(entry.Id), _timeProvider.GetUtcNow().Add(retryDelay).Ticks, GetWaitTimeTtl()),
_cache.IncrementAsync(attemptsCacheKey, 1, GetAttemptsTtl())
), logger: _logger).AnyContext();

Expand Down Expand Up @@ -657,7 +657,7 @@ public async Task DoMaintenanceWorkAsync()
return;

_logger.LogTrace("Starting DoMaintenance: Name: {Name} Id: {Id}", _options.Name, QueueId);
var utcNow = SystemClock.UtcNow;
var utcNow = _timeProvider.GetUtcNow();

try
{
Expand All @@ -674,7 +674,7 @@ public async Task DoMaintenanceWorkAsync()
continue;
}

var renewedTime = new DateTime(renewedTimeTicks.Value);
var renewedTime = new DateTimeOffset(new DateTime(renewedTimeTicks.Value), TimeSpan.Zero);
_logger.LogTrace("{WorkId}: Renewed time {RenewedTime:o}", workId, renewedTime);

if (utcNow.Subtract(renewedTime) <= _options.WorkItemTimeout)
Expand Down Expand Up @@ -746,7 +746,7 @@ public async Task DoMaintenanceWorkAsync()
_logger.LogError(ex, "Error trimming deadletter items: {0}", ex.Message);
}

_logger.LogTrace("Finished DoMaintenance: Name: {Name} Id: {Id} Duration: {Duration:g}", _options.Name, QueueId, SystemClock.UtcNow.Subtract(utcNow));
_logger.LogTrace("Finished DoMaintenance: Name: {Name} Id: {Id} Duration: {Duration:g}", _options.Name, QueueId, _timeProvider.GetUtcNow().Subtract(utcNow));
}

private async Task DoMaintenanceWorkLoopAsync()
Expand All @@ -755,11 +755,11 @@ private async Task DoMaintenanceWorkLoopAsync()
{
_logger.LogTrace("Requesting Maintenance Lock. Name: {Name} Id: {Id}", _options.Name, QueueId);

var utcNow = SystemClock.UtcNow;
var utcNow = _timeProvider.GetUtcNow();
using var linkedCancellationToken = GetLinkedDisposableCancellationTokenSource(new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token);
bool gotLock = await _maintenanceLockProvider.TryUsingAsync($"{_options.Name}-maintenance", DoMaintenanceWorkAsync, cancellationToken: linkedCancellationToken.Token).AnyContext();

_logger.LogTrace("{Status} Maintenance Lock. Name: {Name} Id: {Id} Time To Acquire: {AcquireDuration:g}", gotLock ? "Acquired" : "Failed to acquire", _options.Name, QueueId, SystemClock.UtcNow.Subtract(utcNow));
_logger.LogTrace("{Status} Maintenance Lock. Name: {Name} Id: {Id} Time To Acquire: {AcquireDuration:g}", gotLock ? "Acquired" : "Failed to acquire", _options.Name, QueueId, _timeProvider.GetUtcNow().Subtract(utcNow));
}
}

Expand Down
10 changes: 5 additions & 5 deletions tests/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
<NoWarn>$(NoWarn);CS1591;NU1701</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="xunit" Version="2.7.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.7" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.3.3" PrivateAssets="All" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.4.1" PrivateAssets="All" />

<PackageReference Include="Foundatio.TestHarness" Version="10.7.1" Condition="'$(ReferenceFoundatioSource)' == '' OR '$(ReferenceFoundatioSource)' == 'false'" />
<PackageReference Include="Foundatio.TestHarness" Version="11.0.2" Condition="'$(ReferenceFoundatioSource)' == '' OR '$(ReferenceFoundatioSource)' == 'false'" />
<ProjectReference Include="..\..\..\Foundatio\src\Foundatio.TestHarness\Foundatio.TestHarness.csproj" Condition="'$(ReferenceFoundatioSource)' == 'true'" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion tests/Foundatio.Benchmarks/Foundatio.Benchmarks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
<ProjectReference Include="..\..\src\Foundatio.Redis\Foundatio.Redis.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.12" />
<PackageReference Include="BenchmarkDotNet" Version="0.14.0" />
</ItemGroup>
</Project>
4 changes: 2 additions & 2 deletions tests/Foundatio.Benchmarks/Queues/JobQueueBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ private Task RunJobUntilEmptyAsync(IQueue<QueueItem> queue)

public class BenchmarkJobQueue : QueueJobBase<QueueItem>
{
public BenchmarkJobQueue(Lazy<IQueue<QueueItem>> queue, ILoggerFactory loggerFactory = null) : base(queue, loggerFactory) { }
public BenchmarkJobQueue(Lazy<IQueue<QueueItem>> queue, ILoggerFactory loggerFactory = null) : base(queue, null, loggerFactory) { }

public BenchmarkJobQueue(IQueue<QueueItem> queue, ILoggerFactory loggerFactory = null) : base(queue, loggerFactory) { }
public BenchmarkJobQueue(IQueue<QueueItem> queue, ILoggerFactory loggerFactory = null) : base(queue, null, loggerFactory) { }

protected override Task<JobResult> ProcessQueueEntryAsync(QueueEntryContext<QueueItem> context)
{
Expand Down
5 changes: 5 additions & 0 deletions tests/Foundatio.Redis.Tests/Foundatio.Redis.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,9 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Content Include="..\..\docker-compose.yml">
<Link>docker-compose.yml</Link>
</Content>
</ItemGroup>
</Project>
6 changes: 3 additions & 3 deletions tests/Foundatio.Redis.Tests/Locks/RedisLockTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Foundatio.Caching;
Expand Down Expand Up @@ -28,12 +28,12 @@ public RedisLockTests(ITestOutputHelper output) : base(output)

protected override ILockProvider GetThrottlingLockProvider(int maxHits, TimeSpan period)
{
return new ThrottlingLockProvider(_cache, maxHits, period, Log);
return new ThrottlingLockProvider(_cache, maxHits, period, null, Log);
}

protected override ILockProvider GetLockProvider()
{
return new CacheLockProvider(_cache, _messageBus, Log);
return new CacheLockProvider(_cache, _messageBus, null, Log);
}

[Fact]
Expand Down
Loading