Skip to content
Open
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
21 changes: 5 additions & 16 deletions FastGithub.DomainResolve/DnsClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using DNS.Client;
using AsyncKeyedLock;
using DNS.Client;
using DNS.Client.RequestResolver;
using DNS.Protocol;
using DNS.Protocol.ResourceRecords;
Expand All @@ -7,7 +8,6 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
Expand All @@ -30,7 +30,7 @@ sealed class DnsClient
private readonly FastGithubConfig fastGithubConfig;
private readonly ILogger<DnsClient> logger;

private readonly ConcurrentDictionary<string, SemaphoreSlim> semaphoreSlims = new();
private readonly AsyncKeyedLocker<string> locks = new();
private readonly IMemoryCache dnsStateCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
private readonly IMemoryCache dnsLookupCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));

Expand Down Expand Up @@ -123,9 +123,8 @@ private async ValueTask<bool> IsDnsAvailableAsync(IPEndPoint dns, CancellationTo
}

var key = dns.ToString();
var semaphore = this.semaphoreSlims.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync(CancellationToken.None);

using var _ = await locks.LockAsync(key);
try
{
using var timeoutTokenSource = new CancellationTokenSource(tcpConnectTimeout);
Expand All @@ -139,10 +138,6 @@ private async ValueTask<bool> IsDnsAvailableAsync(IPEndPoint dns, CancellationTo
cancellationToken.ThrowIfCancellationRequested();
return this.dnsStateCache.Set(dns, false, this.stateExpiration);
}
finally
{
semaphore.Release();
}
}

/// <summary>
Expand All @@ -156,9 +151,7 @@ private async ValueTask<bool> IsDnsAvailableAsync(IPEndPoint dns, CancellationTo
private async Task<IList<IPAddress>> LookupAsync(IPEndPoint dns, DnsEndPoint endPoint, bool fastSort, CancellationToken cancellationToken = default)
{
var key = $"{dns}/{endPoint}";
var semaphore = this.semaphoreSlims.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync(CancellationToken.None);

using var _ = await locks.LockAsync(key);
try
{
if (this.dnsLookupCache.TryGetValue<IList<IPAddress>>(key, out var value))
Expand All @@ -178,10 +171,6 @@ private async Task<IList<IPAddress>> LookupAsync(IPEndPoint dns, DnsEndPoint end
var expiration = IsSocketException(ex) ? this.maxTimeToLive : this.minTimeToLive;
return this.dnsLookupCache.Set(key, Array.Empty<IPAddress>(), expiration);
}
finally
{
semaphore.Release();
}
}

/// <summary>
Expand Down
1 change: 1 addition & 0 deletions FastGithub.DomainResolve/FastGithub.DomainResolve.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<ItemGroup>
<PackageReference Include="AsyncKeyedLock" Version="8.0.0" />
<PackageReference Include="PInvoke.AdvApi32" Version="0.7.124" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
Expand Down
19 changes: 5 additions & 14 deletions FastGithub.DomainResolve/PersistenceService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using FastGithub.Configuration;
using AsyncKeyedLock;
using FastGithub.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
Expand All @@ -18,7 +19,7 @@ namespace FastGithub.DomainResolve
sealed partial class PersistenceService
{
private static readonly string dataFile = "dnsendpoints.json";
private static readonly SemaphoreSlim dataLocker = new(1, 1);
private static readonly AsyncNonKeyedLocker dataLocker = new(1);

private readonly FastGithubConfig fastGithubConfig;
private readonly ILogger<PersistenceService> logger;
Expand Down Expand Up @@ -60,10 +61,9 @@ public IList<DnsEndPoint> ReadDnsEndPoints()
return Array.Empty<DnsEndPoint>();
}

using var _ = dataLocker.Lock();
try
{
dataLocker.Wait();

var utf8Json = File.ReadAllBytes(dataFile);
var endPointItems = JsonSerializer.Deserialize(utf8Json, EndPointItemsContext.Default.EndPointItemArray);
if (endPointItems == null)
Expand All @@ -86,10 +86,6 @@ public IList<DnsEndPoint> ReadDnsEndPoints()
this.logger.LogWarning(ex.Message, "读取dns记录异常");
return Array.Empty<DnsEndPoint>();
}
finally
{
dataLocker.Release();
}
}

/// <summary>
Expand All @@ -100,10 +96,9 @@ public IList<DnsEndPoint> ReadDnsEndPoints()
/// <returns></returns>
public async Task WriteDnsEndPointsAsync(IEnumerable<DnsEndPoint> dnsEndPoints, CancellationToken cancellationToken)
{
using var _ = await dataLocker.LockAsync();
try
{
await dataLocker.WaitAsync(CancellationToken.None);

var endPointItems = dnsEndPoints.Select(item => new EndPointItem(item.Host, item.Port)).ToArray();
var utf8Json = JsonSerializer.SerializeToUtf8Bytes(endPointItems, EndPointItemsContext.Default.EndPointItemArray);
await File.WriteAllBytesAsync(dataFile, utf8Json, cancellationToken);
Expand All @@ -112,10 +107,6 @@ public async Task WriteDnsEndPointsAsync(IEnumerable<DnsEndPoint> dnsEndPoints,
{
this.logger.LogWarning(ex.Message, "保存dns记录异常");
}
finally
{
dataLocker.Release();
}
}
}
}