-
Notifications
You must be signed in to change notification settings - Fork 0
#1 Create Nacos service discovery provider #2
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
Changes from 18 commits
470bee5
643c478
732fec4
7899622
589cf4d
2100626
ffbf1b5
f39757d
30a0f34
0a3f426
306196c
31308ca
1eed642
de2b498
ece0185
71d81bc
c7c0460
d7c7c33
d962f9e
b82594c
6767b6e
4547c55
bea32f4
7912f62
7ac2cae
1a16f83
eec6bad
950c5ae
dd05752
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| # This workflow will build a .NET project | ||
| # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net | ||
|
|
||
| name: Main | ||
|
|
||
| on: | ||
| push: | ||
| branches: [ "main" ] | ||
|
|
||
| jobs: | ||
| build: | ||
| runs-on: ubuntu-latest | ||
| strategy: | ||
| matrix: | ||
| dotnet-version: [ '8.0', '9.0' ] | ||
|
|
||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - name: Setup .NET ${{ matrix.dotnet-version }} | ||
| uses: actions/setup-dotnet@v3 | ||
| with: | ||
| dotnet-version: ${{ matrix.dotnet-version }}.x | ||
| - name: Restore | ||
| run: dotnet restore ./Ocelot.Discovery.Nacos.sln -p:TargetFramework=net${{ matrix.dotnet-version }} | ||
| - name: Build | ||
| run: dotnet build --no-restore ./Ocelot.Discovery.Nacos.sln --framework net${{ matrix.dotnet-version }} | ||
| - name: Unit Tests | ||
| run: dotnet test --no-restore --no-build --verbosity minimal --framework net${{ matrix.dotnet-version }} ./unit/Ocelot.Discovery.Nacos.UnitTests.csproj |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| # This workflow will build a .NET project | ||
| # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net | ||
|
|
||
| name: PR | ||
|
|
||
| on: pull_request | ||
|
|
||
| jobs: | ||
| build: | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - name: Setup .NET 8.0 | ||
| uses: actions/setup-dotnet@v3 | ||
| with: | ||
| dotnet-version: 8.0.x | ||
| - name: Restore | ||
| run: dotnet restore ./Ocelot.Discovery.Nacos.sln -p:TargetFramework=net8.0 | ||
| - name: Build | ||
| run: dotnet build --no-restore ./Ocelot.Discovery.Nacos.sln --framework net8.0 | ||
| - name: Unit Tests | ||
| run: dotnet test --no-restore --no-build --verbosity normal --framework net8.0 ./unit/Ocelot.Discovery.Nacos.UnitTests.csproj |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -398,3 +398,5 @@ FodyWeavers.xsd | |
|
|
||
| # JetBrains Rider | ||
| *.sln.iml | ||
| .idea/* | ||
| /Ocelot.Discovery.Nacos/.idea | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| | ||
| Microsoft Visual Studio Solution File, Format Version 12.00 | ||
| # Visual Studio Version 17 | ||
| VisualStudioVersion = 17.12.35527.113 | ||
| MinimumVisualStudioVersion = 10.0.40219.1 | ||
| Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ocelot.Discovery.Nacos", "src\Ocelot.Discovery.Nacos.csproj", "{CEF24699-3E41-D971-ACCA-FEF5CCB2011C}" | ||
| EndProject | ||
| Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ocelot.Discovery.Nacos.UnitTests", "unit\Ocelot.Discovery.Nacos.UnitTests.csproj", "{FAD17C0B-4F8F-99A6-1419-9665E4210346}" | ||
| EndProject | ||
| Global | ||
| GlobalSection(SolutionConfigurationPlatforms) = preSolution | ||
| Debug|Any CPU = Debug|Any CPU | ||
| Release|Any CPU = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(ProjectConfigurationPlatforms) = postSolution | ||
| {CEF24699-3E41-D971-ACCA-FEF5CCB2011C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
| {CEF24699-3E41-D971-ACCA-FEF5CCB2011C}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
| {CEF24699-3E41-D971-ACCA-FEF5CCB2011C}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
| {CEF24699-3E41-D971-ACCA-FEF5CCB2011C}.Release|Any CPU.Build.0 = Release|Any CPU | ||
| {FAD17C0B-4F8F-99A6-1419-9665E4210346}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
| {FAD17C0B-4F8F-99A6-1419-9665E4210346}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
| {FAD17C0B-4F8F-99A6-1419-9665E4210346}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
| {FAD17C0B-4F8F-99A6-1419-9665E4210346}.Release|Any CPU.Build.0 = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(SolutionProperties) = preSolution | ||
| HideSolutionNode = FALSE | ||
| EndGlobalSection | ||
| GlobalSection(ExtensibilityGlobals) = postSolution | ||
| SolutionGuid = {0E583663-7152-4575-9AE5-FF3D78AEAA1C} | ||
| EndGlobalSection | ||
| EndGlobal |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| using Service = Ocelot.Values.Service; | ||
|
|
||
| namespace Ocelot.Discovery.Nacos; | ||
|
|
||
| public class Nacos : IServiceDiscoveryProvider | ||
| { | ||
| private readonly INacosNamingService _client; | ||
| private readonly string _serviceName; | ||
| private readonly ILogger<Nacos> _logger; | ||
|
|
||
| public Nacos(string serviceName, INacosNamingService client, ILogger<Nacos> logger) | ||
| { | ||
| _client = client; | ||
| _serviceName = serviceName; | ||
| _logger = logger; | ||
| } | ||
MiaoShuYo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| public async Task<List<Service>> GetAsync() | ||
| { | ||
| try | ||
| { | ||
| var instances = await _client.GetAllInstances(_serviceName) | ||
| .ConfigureAwait(false); | ||
|
|
||
| return instances? | ||
| .Where(i => i.Healthy && i.Enabled && i.Weight > 0) // Filter out unhealthy instances | ||
| .Select(TransformInstance) | ||
| .ToList() ?? new(); | ||
| } | ||
| catch (NacosException ex) | ||
| { | ||
| _logger.LogError(ex, $"An exception occurred while fetching instances for service {_serviceName} from Nacos."); | ||
| return new(); | ||
| } | ||
| } | ||
|
|
||
| private Service TransformInstance(Instance instance) | ||
| { | ||
| var metadata = instance.Metadata ?? new(); | ||
|
|
||
| return new Service( | ||
| id: instance.InstanceId, | ||
| hostAndPort: new(instance.Ip, instance.Port), | ||
| name: instance.ServiceName, | ||
| version: metadata.GetValueOrDefault("version", "default"), | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I cannot get this default value. Could you show me in Nacos docs please that default version is marked as "default"?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The version value is not explicitly defined as "default" in the Nacos documentation. The "default" value in the code is a custom fallback in case there is no "version" key in the metadata dictionary.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You confirmed that this is the issue. I am not certain but these values may be applicable:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The version can be customized through the configuration file. |
||
| tags: Nacos.ProcessMetadataTags(metadata) | ||
| ); | ||
| } | ||
|
|
||
| private static List<string> ProcessMetadataTags(IDictionary<string, string> metadata) => metadata | ||
| .Where(kv => !_reservedKeys.Contains(kv.Key)) | ||
| .Select(FormatTag) | ||
| .ToList(); | ||
|
|
||
| private static string FormatTag(KeyValuePair<string, string> kv) | ||
| => $"{WebUtility.UrlEncode(kv.Key)}={WebUtility.UrlEncode(kv.Value)}"; | ||
|
|
||
| private static readonly string[] _reservedKeys = { "version", "group", "cluster", "namespace", "weight" }; | ||
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| using Ocelot.Configuration.Repository; | ||
| using Ocelot.Middleware; | ||
|
|
||
| namespace Ocelot.Discovery.Nacos; | ||
|
|
||
| public class NacosMiddlewareConfigurationProvider | ||
| { | ||
| public static OcelotMiddlewareConfigurationDelegate Get { get; } = builder => | ||
| { | ||
| var internalConfigRepo = builder.ApplicationServices.GetService<IInternalConfigurationRepository>(); | ||
| var log = builder.ApplicationServices.GetService<ILogger<NacosMiddlewareConfigurationProvider>>(); | ||
raman-m marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| var config = internalConfigRepo?.Get(); | ||
|
|
||
| if (config != null && UsingNacosServiceDiscoveryProvider(config.Data)) | ||
| { | ||
| log?.LogInformation("Using Nacos service discovery provider."); | ||
| } | ||
raman-m marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| return Task.CompletedTask; | ||
| }; | ||
|
|
||
| private static bool UsingNacosServiceDiscoveryProvider(IInternalConfiguration configuration) | ||
| { | ||
| return configuration?.ServiceProviderConfiguration != null | ||
| && configuration.ServiceProviderConfiguration.Type?.ToLower() == "nacos"; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| using Ocelot.ServiceDiscovery; | ||
|
|
||
| namespace Ocelot.Discovery.Nacos; | ||
|
|
||
| public static class NacosProviderFactory | ||
| { | ||
| /// <summary> | ||
| /// String constant used for provider type definition. | ||
| /// </summary> | ||
| public const string Nacos = nameof(Discovery.Nacos.Nacos); | ||
|
|
||
| public static ServiceDiscoveryFinderDelegate Get { get; } = CreateProvider; | ||
|
|
||
| private static IServiceDiscoveryProvider? CreateProvider(IServiceProvider provider, ServiceProviderConfiguration config, DownstreamRoute route) | ||
| { | ||
| var client = provider.GetService<INacosNamingService>(); | ||
| var logger = provider.GetService<ILogger<Nacos>>(); | ||
| if (client == null) | ||
| { | ||
| throw new NullReferenceException($"Cannot get an {nameof(INacosNamingService)} service during {nameof(CreateProvider)} operation to instantiate the {nameof(Nacos)} provider!"); | ||
| } | ||
| if (logger != null) | ||
| { | ||
| return Nacos.Equals(config.Type, StringComparison.OrdinalIgnoreCase) | ||
| ? new Nacos(route.ServiceName, client, logger) | ||
| : null; | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFrameworks>net6.0;net8.0</TargetFrameworks> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <PackageReference Include="nacos-sdk-csharp" Version="1.3.10" /> | ||
| <PackageReference Include="nacos-sdk-csharp.AspNetCore" Version="1.3.10" /> | ||
| <PackageReference Include="Ocelot" Version="23.4.3" /> | ||
| </ItemGroup> | ||
| </Project> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| using Ocelot.DependencyInjection; | ||
| using Nacos.AspNetCore.V2; | ||
|
|
||
| namespace Ocelot.Discovery.Nacos; | ||
|
|
||
| public static class OcelotBuilderExtensions | ||
| { | ||
| public static IOcelotBuilder AddNacos(this IOcelotBuilder builder, string section = "nacos") | ||
| { | ||
| builder.Services | ||
| .AddNacosAspNet(builder.Configuration,section) | ||
| .AddSingleton(NacosProviderFactory.Get) | ||
| .AddSingleton(NacosMiddlewareConfigurationProvider.Get); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just a word of caution! |
||
| return builder; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| global using Microsoft.Extensions.DependencyInjection; | ||
| global using Microsoft.Extensions.Logging; | ||
| global using Ocelot.Configuration; | ||
| global using Ocelot.ServiceDiscovery.Providers; | ||
| global using Nacos.V2; | ||
| global using Nacos.V2.Exceptions; | ||
| global using Nacos.V2.Naming.Dtos; | ||
| global using System.Net; | ||
| global using System.Collections.Generic; | ||
| global using System.Linq; | ||
| global using System.Threading.Tasks; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Ocelot.Discovery.Nacos.UnitTests; | ||
|
|
||
| public class LogEntry | ||
MiaoShuYo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| public LogEntry(LogLevel logLevel, EventId eventId, string message, Exception exception) | ||
| { | ||
| LogLevel = logLevel; | ||
| EventId = eventId; | ||
| Message = message; | ||
| Exception = exception; | ||
| } | ||
|
|
||
| public LogLevel LogLevel { get; set; } | ||
| public EventId EventId { get; set; } | ||
| public string Message { get; set; } | ||
| public Exception Exception { get; set; } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| [assembly: Parallelize(Scope = ExecutionScope.MethodLevel)] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| using Microsoft.AspNetCore.Builder; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Moq; | ||
| using Ocelot.Configuration; | ||
| using Ocelot.Configuration.Builder; | ||
| using Ocelot.Configuration.Repository; | ||
| using Ocelot.Responses; | ||
|
|
||
| namespace Ocelot.Discovery.Nacos.UnitTests; | ||
|
|
||
| [TestClass] | ||
| public class NacosMiddlewareConfigurationProviderTests | ||
| { | ||
| [TestMethod] | ||
| public void ShouldNotBuild() | ||
| { | ||
| var configRepo = new Mock<IInternalConfigurationRepository>(); | ||
| configRepo.Setup(x => x.Get()) | ||
| .Returns(new OkResponse<IInternalConfiguration>( | ||
| new InternalConfiguration(null, null, null, null, null, null, null, null,null,null))); | ||
| var services = new ServiceCollection(); | ||
| services.AddSingleton<IInternalConfigurationRepository>(configRepo.Object); | ||
| var sp = services.BuildServiceProvider(); | ||
| var provider = NacosMiddlewareConfigurationProvider.Get(new ApplicationBuilder(sp)); | ||
| Assert.IsInstanceOfType(provider, typeof(Task)); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public void ShouldBuild() | ||
| { | ||
| var serviceProviderConfig = new ServiceProviderConfigurationBuilder().WithType("nacos").Build(); | ||
| var configRepo = new Mock<IInternalConfigurationRepository>(); | ||
| configRepo.Setup(x => x.Get()) | ||
| .Returns(new OkResponse<IInternalConfiguration>( | ||
| new InternalConfiguration(null, null, serviceProviderConfig, null, null, null, null, null, null, null))); | ||
| var services = new ServiceCollection(); | ||
| services.AddSingleton<IInternalConfigurationRepository>(configRepo.Object); | ||
| var sp = services.BuildServiceProvider(); | ||
| var provider = NacosMiddlewareConfigurationProvider.Get(new ApplicationBuilder(sp)); | ||
| Assert.IsInstanceOfType(provider, typeof(Task)); | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.