Skip to content

Commit

Permalink
fix: corrected static assets resolution
Browse files Browse the repository at this point in the history
  • Loading branch information
alexpop-zengenti committed Jan 24, 2024
1 parent 3726d7e commit 29a1650
Show file tree
Hide file tree
Showing 17 changed files with 94 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ internal void SetCallContextData(HttpRequest request)
SetCallContextValueFromRequest(Constants.Headers.ServerType, ServerType.Live.ToString());
SetCallContextValueFromRequest(Constants.Headers.TraceEnabled, null);
SetCallContextValueFromRequest(Constants.Headers.NodeVersionStatus, "published");
SetCallContextValueFromRequest(Constants.Headers.IisHostname, "");
SetCallContextValueFromRequest(Constants.Headers.LoadBalancerVip, "");

// TODO: remove when we deprecate old nodes delivery api
SetCallContextValueFromRequest(Constants.Headers.UseNewNodeService, "false");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,15 @@ public class RequestHandlerMiddleware
"/livez"
};

private readonly IRequestContext _requestContext;

public IEndpointRequestService RequestService { get; }

internal IRouteService RouteService { get; }

public RequestHandlerMiddleware(
RequestDelegate nextMiddleware,
IRequestContext requestContext,
IRouteService routeService,
IRouteInfoFactory routeInfoFactory,
ICacheKeyService cacheKeyService,
Expand All @@ -45,15 +48,15 @@ public RequestHandlerMiddleware(
CallContextService callContextService,
ILogger<RequestHandlerMiddleware> logger)
{
_globalApi = globalApi;
_nextMiddleware = nextMiddleware;
_requestContext = requestContext;
RouteService = routeService;
_routeInfoFactory = routeInfoFactory;
_cacheKeyService = cacheKeyService;
RequestService = endpointRequestService;
_globalApi = globalApi;
_callContextService = callContextService;
_logger = logger;

RouteService = routeService;
RequestService = endpointRequestService;
}

public async Task Invoke(HttpContext context)
Expand Down Expand Up @@ -145,7 +148,7 @@ private void SetContextValues(HttpRequest request, Activity? activity)

private RouteInfo TryToCreateIisFallbackRouteInfo(HttpContext context, Headers headers)
{
if (headers.IisFallbackHeadersAreSet)
if (!string.IsNullOrWhiteSpace(_requestContext.IisHostname) && ! string.IsNullOrWhiteSpace(_requestContext.LoadBalancerVip))
{
return _routeInfoFactory.CreateForIisFallback(
context.Request.GetOriginUri(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ private async Task<HttpRequestMessage> CreateRequestMessage(
return requestMessage;
}

private static void AddHeaders(
private void AddHeaders(
RouteInfo routeInfo,
HttpRequestMessage requestMessage,
Dictionary<string, IEnumerable<string>>? headers)
Expand Down Expand Up @@ -312,10 +312,10 @@ private static void AddHeaders(
}
}

if (routeInfo.IsIisFallback && headers.TryGetValue(Constants.Headers.IisHostName, out var header))
if (routeInfo.IsIisFallback && !string.IsNullOrWhiteSpace(_requestContext.IisHostname))
{
// Override host header with IIS fallback host
requestMessage.Headers.Host = header.FirstOrDefault();
requestMessage.Headers.Host = _requestContext.IisHostname;
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ public RouteInfo Create(

public RouteInfo CreateForIisFallback(Uri originUri, Headers headers)
{
var baseUri = new Uri($"https://{headers.LoadBalancerVip}");
var baseUri = new Uri($"https://{_requestContext.LoadBalancerVip}");
var uri = BuildUri(baseUri, originUri.AbsolutePath, new QueryString(originUri.Query));
headers["Host"] = headers.GetFirstValueIfExists("x-iis-hostname");
headers["Host"] = _requestContext.IisHostname;

return new RouteInfo(uri, headers, "", true, isIisFallback: true);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public static class Headers
public const string IsLocalRequestHandler = "x-is-local-request-handler";
public const string ServerType = "x-site-type";
public const string LoadBalancerVip = "x-loadbalancer-vip";
public const string IisHostName = "x-iis-hostname";
public const string IisHostname = "x-iis-hostname";

public static readonly string[] ConfigHeaders =
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ public interface IRequestContext

public Guid ProjectUuid { get; }

//public Uri ApiUri { get; }

public VersionStatus NodeVersionStatus { get; }

public string BlockConfig { get; }

public string RendererConfig { get; }

public string ProxyConfig { get; }

public string IisHostname { get; }

public string LoadBalancerVip { get; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,6 @@ public Headers(HttpResponseHeaders? headers)
: headers.ToDictionary(h => h.Key, h => h.Value);
}

public bool IisFallbackHeadersAreSet =>
_values.ContainsKey(Constants.Headers.LoadBalancerVip) &&
_values.ContainsKey(Constants.Headers.IisHostName);

public string? LoadBalancerVip => GetFirstValueIfExists(Constants.Headers.LoadBalancerVip);

public string? SiteType => GetFirstValueIfExists(Constants.Headers.ServerType);

public string? EntryVersionStatus => GetFirstValueIfExists(Constants.Headers.EntryVersionStatus);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ public class Block
public string? Id { get; set; }

public Uri? BaseUri { get; set; }

public bool? EnableFullUriRouting { get; set; }

public List<string> StaticPaths { get; set; } = new();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ public class SiteConfig
public string Alias { get; set; } = null!;

public string ProjectApiId { get; set; } = null!;

public string? IisHostname { get; set; }

public string? PodIngressIp { get; set; }

public string? AccessToken { get; set; }
public string? ClientId { get; set; }
Expand Down Expand Up @@ -107,7 +111,9 @@ public static SiteConfig LoadFromJson(
string? clientId = null,
string? sharedSecret = null,
string? username = null,
string? password = null)
string? password = null,
string? iisHostname = null,
string? podIngressIp = null)
{
var siteConfig = new SiteConfig
{
Expand All @@ -117,7 +123,9 @@ public static SiteConfig LoadFromJson(
ClientId = clientId,
SharedSecret = sharedSecret,
Username = username,
Password = password
Password = password,
IisHostname = iisHostname,
PodIngressIp = podIngressIp
};

var jsonSerializerOptions = new JsonSerializerOptions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public ProgramOptions()

[Option("project-api-id", HelpText = "The API id of the project for the site config.")]
public string? ProjectApiId { get; init; }

[Option("access-token", HelpText = "The access token for the site config.")]
public string? AccessToken { get; init; }

Expand All @@ -46,6 +46,12 @@ public ProgramOptions()
[Option("renderers-json", HelpText = "The renderers as JSON for the site config.")]
public string? RenderersAsJson { get; init; }

[Option("iis-hostname", HelpText = "The IIS hostname for the site config.")]
public string? IisHostname { get; init; }

[Option("pod-cluster-id", HelpText = "The pod cluster id", Default = null)]
public string? PodClusterId { get; set; } = null!;

[Option("block-cluster-ingress-ip", HelpText = "The ingress IP for the block cluster", Default = null)]
public string? BlockClusterIngressIp { get; set; } = null!;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ public class HttpPublishingApi : IPublishingApi
private readonly ISiteConfigLoader _siteConfigLoader;
private readonly RestClient _internalRestClient;
private SiteConfig _siteConfig;
private readonly string _projectApiId;
private readonly IRequestContext _requestContext;
private ILogger<HttpPublishingApi> _logger;

private SiteConfig SiteConfig
{
Expand All @@ -31,9 +32,13 @@ private SiteConfig SiteConfig
}

public HttpPublishingApi(
IRequestContext requestContext,
ISiteConfigLoader siteConfigLoader,
ISecurityTokenProviderFactory securityTokenProviderFactory)
ISecurityTokenProviderFactory securityTokenProviderFactory,
ILogger<HttpPublishingApi> logger)
{
_logger = logger;
_requestContext = requestContext;
_siteConfigLoader = siteConfigLoader;
_siteConfig = _siteConfigLoader.SiteConfig;

Expand All @@ -55,44 +60,46 @@ public HttpPublishingApi(
// new RestClientFactory($"http://localhost:5000/")
// .SecuredRestClient(new InternalSecurityTokenProvider(securityTokenParams));
// _internalRestClient.AddHeader("x-alias", securityTokenParams.Alias);
_projectApiId = _siteConfigLoader.SiteConfig.ProjectApiId;

}

public async Task<BlockVersionInfo?> GetBlockVersionInfo(Guid versionId)
{
var blockVersion = (await _internalRestClient.GetAsync<dynamic>(
$"api/management/projects/{_projectApiId}/blocks/versions/{versionId}"))
$"api/management/projects/{_requestContext.ProjectApiId}/blocks/versions/{versionId}"))
.ResponseObject;

if (blockVersion == null)
{
_logger.LogWarning("Could not find block version with uuid {Uuid} using the http api", versionId);
return null;
}

var projectUuid = Guid.Empty; // NOT required for local development ATM.

// TODO: check if we need to populate enableFullUriRouting
var enableFullUriRouting = false;
var blockId = (string)blockVersion.id;
var block = _siteConfig.GetBlockById(blockId);
if (block == null)
{
_logger.LogWarning("Could not find block version with id {Id} in site config", blockId);
return null;
}

var blockVersionInfo = new BlockVersionInfo(
projectUuid,
"",
_requestContext.ProjectUuid,
blockId,
versionId,
new Uri(""),
"",
enableFullUriRouting,
new[]
{
""
},
1);
block.BaseUri,

Check warning on line 90 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/HttpPublishingApi.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'baseUri' in 'BlockVersionInfo.BlockVersionInfo(Guid projectUuid, string blockId, Guid blockVersionId, Uri baseUri, string branch, bool enableFullUriRouting, IEnumerable<string>? staticPaths = null, int? versionNo = null)'.

Check warning on line 90 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/HttpPublishingApi.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'baseUri' in 'BlockVersionInfo.BlockVersionInfo(Guid projectUuid, string blockId, Guid blockVersionId, Uri baseUri, string branch, bool enableFullUriRouting, IEnumerable<string>? staticPaths = null, int? versionNo = null)'.

Check warning on line 90 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/HttpPublishingApi.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'baseUri' in 'BlockVersionInfo.BlockVersionInfo(Guid projectUuid, string blockId, Guid blockVersionId, Uri baseUri, string branch, bool enableFullUriRouting, IEnumerable<string>? staticPaths = null, int? versionNo = null)'.

Check warning on line 90 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/HttpPublishingApi.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'baseUri' in 'BlockVersionInfo.BlockVersionInfo(Guid projectUuid, string blockId, Guid blockVersionId, Uri baseUri, string branch, bool enableFullUriRouting, IEnumerable<string>? staticPaths = null, int? versionNo = null)'.
block.Branch,
block.EnableFullUriRouting??false,
block.StaticPaths,
block.VersionNo);
return blockVersionInfo;
}

public async Task<EndpointRequestInfo?> GetEndpointForRequest(RequestContext requestContext)
{
var httpEndpointRequestContext = new HttpEndpointRequestContext(requestContext);
var endpointRequestInfo = (await _internalRestClient.PostAsJsonAsync<dynamic>(
$"api/management/projects/{_projectApiId}/renderers/endpointrequestinfo",
$"api/management/projects/{_requestContext.ProjectApiId}/renderers/endpointrequestinfo",
httpEndpointRequestContext))
.ResponseObject;
var layoutRendererIdValue = endpointRequestInfo["layoutRendererId"]?.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public LocalNodeService(
}
catch (Exception e)
{
_logger.LogError(e, "Error getting a management node or renderer");
_logger.LogError(e, "Error getting a management node or renderer for path {Path}", path);
return null;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

namespace Zengenti.Contensis.RequestHandler.LocalDevelopment.Services;

public class LocalDevelopmentRequestContext : IRequestContext
public class LocalRequestContext : IRequestContext
{
private readonly ISiteConfigLoader _siteConfigLoader;

public LocalDevelopmentRequestContext(ISiteConfigLoader siteConfigLoader, bool traceEnabled = true)
public LocalRequestContext(ISiteConfigLoader siteConfigLoader, bool traceEnabled = true)
{
_siteConfigLoader = siteConfigLoader;
TraceEnabled = traceEnabled;
Expand All @@ -23,8 +23,6 @@ public LocalDevelopmentRequestContext(ISiteConfigLoader siteConfigLoader, bool t

public Guid ProjectUuid => Guid.Empty; // NOT required for local development ATM.

public Uri ApiUri => new Uri($"https://cms-{_siteConfigLoader.SiteConfig.Alias}.cloud.contensis.com");

public VersionStatus NodeVersionStatus =>
CallContext.Current[Constants.Headers.NodeVersionStatus].EqualsCaseInsensitive("published")
? VersionStatus.Published
Expand All @@ -33,4 +31,6 @@ public LocalDevelopmentRequestContext(ISiteConfigLoader siteConfigLoader, bool t
public string BlockConfig => CallContext.Current[Constants.Headers.BlockConfig];
public string RendererConfig => CallContext.Current[Constants.Headers.RendererConfig];
public string ProxyConfig => CallContext.Current[Constants.Headers.ProxyConfig];
public string IisHostname => _siteConfigLoader.SiteConfig.IisHostname;

Check warning on line 34 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/LocalRequestContext.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference return.

Check warning on line 34 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/LocalRequestContext.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference return.

Check warning on line 34 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/LocalRequestContext.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference return.

Check warning on line 34 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/LocalRequestContext.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference return.
public string LoadBalancerVip => _siteConfigLoader.SiteConfig.PodIngressIp;

Check warning on line 35 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/LocalRequestContext.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference return.

Check warning on line 35 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/LocalRequestContext.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference return.

Check warning on line 35 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/LocalRequestContext.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference return.

Check warning on line 35 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Services/LocalRequestContext.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference return.
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ public SiteConfigLoader(
string? clientId = null,
string? sharedSecret = null,
string? username = null,
string? password = null)
string? password = null,
string? iisHostname = null,
string? podIngressIp = null)
{
SiteConfig = SiteConfig.LoadFromJson(
alias,
Expand All @@ -46,7 +48,9 @@ public SiteConfigLoader(
clientId,
sharedSecret,
username,
password);
password,
iisHostname,
podIngressIp);
}

private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
Expand Down
15 changes: 13 additions & 2 deletions src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ public void ConfigureServices(IServiceCollection services)
}
else
{
var podIngressIpDictionary = new Dictionary<string, string>()
{
{"local", "127.0.0.1" },
{"hq", "185.18.139.20" },
{"hq2", "185.18.139.242" },
{"lon", "185.18.139.108" },
{"man", "185.18.139.88" },
};

siteConfigLoader = new SiteConfigLoader(
ProgramOptions.Current.Alias!,
ProgramOptions.Current.ProjectApiId!,
Expand All @@ -64,11 +73,13 @@ public void ConfigureServices(IServiceCollection services)
ProgramOptions.Current.ClientId,
ProgramOptions.Current.ClientSecret,
ProgramOptions.Current.Username,
ProgramOptions.Current.Password);
ProgramOptions.Current.Password,
ProgramOptions.Current.IisHostname,
podIngressIpDictionary[ProgramOptions.Current.PodClusterId]);

Check warning on line 78 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Startup.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'key' in 'string Dictionary<string, string>.this[string key]'.

Check warning on line 78 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Startup.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'key' in 'string Dictionary<string, string>.this[string key]'.

Check warning on line 78 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Startup.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'key' in 'string Dictionary<string, string>.this[string key]'.

Check warning on line 78 in src/Zengenti.Contensis.RequestHandler.LocalDevelopment/Startup.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'key' in 'string Dictionary<string, string>.this[string key]'.
}

services.AddSingleton<ISiteConfigLoader>(_ => siteConfigLoader);
services.AddTransient<IRequestContext, LocalDevelopmentRequestContext>();
services.AddTransient<IRequestContext, LocalRequestContext>();
services.AddSingleton<IPublishingServiceCache, NullPublishingServiceCache>();
services.AddSingleton<ISecurityTokenProviderFactory, SecurityTokenProviderFactory>();
services.AddSingleton<IPublishingApi, HttpPublishingApi>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,6 @@ public void WhenCreateIsInvoked()
{
{
Constants.Headers.Alias, "zenhub"
},
{
Constants.Headers.LoadBalancerVip, "10.0.0.1"
},
{
Constants.Headers.IisHostName, "www.mysite.com"
}
}));
}
Expand All @@ -52,7 +46,7 @@ public void ThenTheUriIsRewrittenCorrectly()
[AndThen]
public void AndThenTheHeadersAreMapped()
{
Assert.That(_result.Headers.Values.Count, Is.EqualTo(4));
Assert.That(_result.Headers.Values.Count, Is.EqualTo(2));
Assert.That(_result.Headers.GetFirstValueIfExists(Constants.Headers.Alias) == "zenhub");
}

Expand Down
Loading

0 comments on commit 29a1650

Please sign in to comment.