From 3ed1c598a752e792b55ce3d863c89059eed013ee Mon Sep 17 00:00:00 2001 From: Bobby Bonestell Date: Sat, 8 Feb 2025 13:28:59 -0700 Subject: [PATCH] WIP implementation of dynamic port configuration for YARP implementation --- FUNC/Node.cs | 4 ++++ FUNC/Program.cs | 42 +++++++++++++++++++++++++++++++++--------- FUNC/Shared.cs | 8 ++++++++ 3 files changed, 45 insertions(+), 9 deletions(-) create mode 100644 FUNC/Shared.cs diff --git a/FUNC/Node.cs b/FUNC/Node.cs index 6550417..b3540cd 100644 --- a/FUNC/Node.cs +++ b/FUNC/Node.cs @@ -27,6 +27,10 @@ public static async Task Get(string name) var endpointAddressToken = config.GetValue("EndpointAddress"); string endpointAddress = endpointAddressToken?.Value() ?? ":0"; port = int.Parse(endpointAddress[(endpointAddress.IndexOf(":") + 1)..]); + if (name == "algorand") + Shared.AlgoPort = port; + else if (name == "voi") + Shared.VoiPort = port; } string sc = string.Empty; diff --git a/FUNC/Program.cs b/FUNC/Program.cs index a4d14a2..6b3f3aa 100644 --- a/FUNC/Program.cs +++ b/FUNC/Program.cs @@ -1,6 +1,6 @@ using FUNC; using Microsoft.Net.Http.Headers; -//using Yarp.ReverseProxy.Transforms; +using Yarp.ReverseProxy.Transforms; var builder = WebApplication.CreateBuilder(args); @@ -18,14 +18,38 @@ }); }); builder.Services.AddReverseProxy() - .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); - //.AddTransforms(transformBuilderContext => - //{ - // transformBuilderContext.AddRequestTransform(transformContext => - // { - // // TODO: change port on destination address based on node configuration value - // }); - //}); + .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")) + .AddTransforms(transformBuilderContext => + { + transformBuilderContext.AddRequestTransform(transformContext => + { + // Get the original host + var ogPort = transformContext.HttpContext.Request.Host.Port; + var destPort = 8080; + + // Check if it's a request to the legacy site + if (ogPort == 1234) { + destPort = Shared.VoiPort; + + } else if (ogPort == 5678) { + // Algo Port + destPort = Shared.AlgoPort; + } + + var destinationPrefix = transformContext.DestinationPrefix; + if (destinationPrefix != null) + { + var originalUri = new Uri(destinationPrefix); + var newUri = new UriBuilder(originalUri) + { + Port = destPort + }.Uri; + transformContext.DestinationPrefix = newUri.ToString(); + } + + return ValueTask.CompletedTask; + }); + }); var app = builder.Build(); diff --git a/FUNC/Shared.cs b/FUNC/Shared.cs new file mode 100644 index 0000000..163f805 --- /dev/null +++ b/FUNC/Shared.cs @@ -0,0 +1,8 @@ +namespace FUNC +{ + public static class Shared + { + public static int AlgoPort { get; set; } = 8081; + public static int VoiPort { get; set; } = 8082; + } +}