Merge branch 'release-3.1.9'

This commit is contained in:
TomPallister 2018-03-04 10:04:47 +00:00
commit 254910fea3
143 changed files with 641 additions and 460 deletions

View File

@ -12,6 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
build-and-run-tests.ps1 = build-and-run-tests.ps1
build.cake = build.cake
build.ps1 = build.ps1
codeanalysis.ruleset = codeanalysis.ruleset
GitVersion.yml = GitVersion.yml
global.json = global.json
LICENSE.md = LICENSE.md
@ -39,14 +40,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Benchmarks", "test\O
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.IntegrationTests", "test\Ocelot.IntegrationTests\Ocelot.IntegrationTests.csproj", "{D4575572-99CA-4530-8737-C296EDA326F8}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{E78EF991-3401-459A-94FE-EC4F4E5BD702}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotApplicationApiGateway", "samples\OcelotServiceFabric\src\OcelotApplicationApiGateway\OcelotApplicationApiGateway.csproj", "{1A3A3D97-33AB-48FB-8A9F-92905A15DF74}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotApplicationService", "samples\OcelotServiceFabric\src\OcelotApplicationService\OcelotApplicationService.csproj", "{272DD79B-7D04-4DFB-BB64-B1C098CE8050}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OcelotServiceFabric", "OcelotServiceFabric", "{98424512-BCF5-4F42-ACB2-6D7040D92487}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -77,14 +70,6 @@ Global
{D4575572-99CA-4530-8737-C296EDA326F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4575572-99CA-4530-8737-C296EDA326F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4575572-99CA-4530-8737-C296EDA326F8}.Release|Any CPU.Build.0 = Release|Any CPU
{1A3A3D97-33AB-48FB-8A9F-92905A15DF74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1A3A3D97-33AB-48FB-8A9F-92905A15DF74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1A3A3D97-33AB-48FB-8A9F-92905A15DF74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1A3A3D97-33AB-48FB-8A9F-92905A15DF74}.Release|Any CPU.Build.0 = Release|Any CPU
{272DD79B-7D04-4DFB-BB64-B1C098CE8050}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{272DD79B-7D04-4DFB-BB64-B1C098CE8050}.Debug|Any CPU.Build.0 = Debug|Any CPU
{272DD79B-7D04-4DFB-BB64-B1C098CE8050}.Release|Any CPU.ActiveCfg = Release|Any CPU
{272DD79B-7D04-4DFB-BB64-B1C098CE8050}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -96,9 +81,6 @@ Global
{02BBF4C5-517E-4157-8D21-4B8B9E118B7A} = {5B401523-36DA-4491-B73A-7590A26E420B}
{106B49E6-95F6-4A7B-B81C-96BFA74AF035} = {5B401523-36DA-4491-B73A-7590A26E420B}
{D4575572-99CA-4530-8737-C296EDA326F8} = {5B401523-36DA-4491-B73A-7590A26E420B}
{1A3A3D97-33AB-48FB-8A9F-92905A15DF74} = {98424512-BCF5-4F42-ACB2-6D7040D92487}
{272DD79B-7D04-4DFB-BB64-B1C098CE8050} = {98424512-BCF5-4F42-ACB2-6D7040D92487}
{98424512-BCF5-4F42-ACB2-6D7040D92487} = {E78EF991-3401-459A-94FE-EC4F4E5BD702}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {21476EFF-778A-4F97-8A56-D1AF1CEC0C48}

View File

@ -39,6 +39,7 @@ A quick list of Ocelot's capabilities for more information see the [documentatio
* Routing
* Request Aggregation
* Service Discovery with Consul
* Service Fabric
* Authentication
* Authorisation
* Rate Limiting

152
codeanalysis.ruleset Normal file
View File

@ -0,0 +1,152 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Rules for StyleCop.Analyzers" Description="Code analysis rules for StyleCop.Analyzers.csproj." ToolsVersion="14.0">
<Rules AnalyzerId="AsyncUsageAnalyzers" RuleNamespace="AsyncUsageAnalyzers">
<Rule Id="AvoidAsyncSuffix" Action="None" />
<Rule Id="AvoidAsyncVoid" Action="None" />
<Rule Id="UseAsyncSuffix" Action="None" />
<Rule Id="UseConfigureAwait" Action="None" />
</Rules>
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
<Rule Id="CA1001" Action="None" />
<Rule Id="CA1009" Action="None" />
<Rule Id="CA1016" Action="None" />
<Rule Id="CA1033" Action="None" />
<Rule Id="CA1049" Action="None" />
<Rule Id="CA1060" Action="None" />
<Rule Id="CA1061" Action="None" />
<Rule Id="CA1063" Action="None" />
<Rule Id="CA1065" Action="None" />
<Rule Id="CA1301" Action="None" />
<Rule Id="CA1400" Action="None" />
<Rule Id="CA1401" Action="None" />
<Rule Id="CA1403" Action="None" />
<Rule Id="CA1404" Action="None" />
<Rule Id="CA1405" Action="None" />
<Rule Id="CA1410" Action="None" />
<Rule Id="CA1415" Action="None" />
<Rule Id="CA1821" Action="None" />
<Rule Id="CA1900" Action="None" />
<Rule Id="CA1901" Action="None" />
<Rule Id="CA2002" Action="None" />
<Rule Id="CA2100" Action="None" />
<Rule Id="CA2101" Action="None" />
<Rule Id="CA2108" Action="None" />
<Rule Id="CA2111" Action="None" />
<Rule Id="CA2112" Action="None" />
<Rule Id="CA2114" Action="None" />
<Rule Id="CA2116" Action="None" />
<Rule Id="CA2117" Action="None" />
<Rule Id="CA2122" Action="None" />
<Rule Id="CA2123" Action="None" />
<Rule Id="CA2124" Action="None" />
<Rule Id="CA2126" Action="None" />
<Rule Id="CA2131" Action="None" />
<Rule Id="CA2132" Action="None" />
<Rule Id="CA2133" Action="None" />
<Rule Id="CA2134" Action="None" />
<Rule Id="CA2137" Action="None" />
<Rule Id="CA2138" Action="None" />
<Rule Id="CA2140" Action="None" />
<Rule Id="CA2141" Action="None" />
<Rule Id="CA2146" Action="None" />
<Rule Id="CA2147" Action="None" />
<Rule Id="CA2149" Action="None" />
<Rule Id="CA2200" Action="None" />
<Rule Id="CA2202" Action="None" />
<Rule Id="CA2207" Action="None" />
<Rule Id="CA2212" Action="None" />
<Rule Id="CA2213" Action="None" />
<Rule Id="CA2214" Action="None" />
<Rule Id="CA2216" Action="None" />
<Rule Id="CA2220" Action="None" />
<Rule Id="CA2229" Action="None" />
<Rule Id="CA2231" Action="None" />
<Rule Id="CA2232" Action="None" />
<Rule Id="CA2235" Action="None" />
<Rule Id="CA2236" Action="None" />
<Rule Id="CA2237" Action="None" />
<Rule Id="CA2238" Action="None" />
<Rule Id="CA2240" Action="None" />
<Rule Id="CA2241" Action="None" />
<Rule Id="CA2242" Action="None" />
</Rules>
<Rules AnalyzerId="Microsoft.CodeAnalysis.CSharp.Features" RuleNamespace="Microsoft.CodeAnalysis.CSharp.Features">
<Rule Id="IDE0003" Action="None" />
</Rules>
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
<Rule Id="SA0000" Action="Hidden" />
<Rule Id="SA1000" Action="None" />
<Rule Id="SA1001" Action="None" />
<Rule Id="SA1002" Action="None" />
<Rule Id="SA1003" Action="None" />
<Rule Id="SA1005" Action="None" />
<Rule Id="SA1008" Action="None" />
<Rule Id="SA1009" Action="None" />
<Rule Id="SA1011" Action="None" />
<Rule Id="SA1012" Action="None" />
<Rule Id="SA1013" Action="None" />
<Rule Id="SA1015" Action="None" />
<Rule Id="SA1016" Action="None" />
<Rule Id="SA1021" Action="None" />
<Rule Id="SA1022" Action="None" />
<Rule Id="SA1024" Action="None" />
<Rule Id="SA1026" Action="None" />
<Rule Id="SA1028" Action="None" />
<Rule Id="SA1100" Action="None" />
<Rule Id="SA1101" Action="None" />
<Rule Id="SA1106" Action="None" />
<Rule Id="SA1111" Action="None" />
<Rule Id="SA1112" Action="None" />
<Rule Id="SA1116" Action="None" />
<Rule Id="SA1117" Action="None" />
<Rule Id="SA1118" Action="None" />
<Rule Id="SA1119" Action="None" />
<Rule Id="SA1121" Action="None" />
<Rule Id="SA1122" Action="None" />
<Rule Id="SA1128" Action="None" />
<Rule Id="SA1133" Action="None" />
<Rule Id="SA1200" Action="None" />
<Rule Id="SA1201" Action="None" />
<Rule Id="SA1202" Action="None" />
<Rule Id="SA1203" Action="None" />
<Rule Id="SA1204" Action="None" />
<Rule Id="SA1208" Action="None" />
<Rule Id="SA1209" Action="None" />
<Rule Id="SA1210" Action="None" />
<Rule Id="SA1214" Action="None" />
<Rule Id="SA1216" Action="None" />
<Rule Id="SA1300" Action="None" />
<Rule Id="SA1302" Action="None" />
<Rule Id="SA1303" Action="None" />
<Rule Id="SA1304" Action="None" />
<Rule Id="SA1305" Action="None" />
<Rule Id="SA1309" Action="None" />
<Rule Id="SA1310" Action="None" />
<Rule Id="SA1311" Action="None" />
<Rule Id="SA1400" Action="None" />
<Rule Id="SA1401" Action="None" />
<Rule Id="SA1402" Action="None" />
<Rule Id="SA1403" Action="None" />
<Rule Id="SA1404" Action="None" />
<Rule Id="SA1405" Action="None" />
<Rule Id="SA1406" Action="None" />
<Rule Id="SA1407" Action="None" />
<Rule Id="SA1408" Action="None" />
<Rule Id="SA1410" Action="None" />
<Rule Id="SA1411" Action="None" />
<Rule Id="SA1412" Action="None" />
<Rule Id="SA1500" Action="None" />
<Rule Id="SA1502" Action="None" />
<Rule Id="SA1516" Action="None" />
<Rule Id="SA1600" Action="None" />
<Rule Id="SA1603" Action="None" />
<Rule Id="SA1609" Action="None" />
<Rule Id="SA1623" Action="None" />
<Rule Id="SA1633" Action="None" />
<Rule Id="SA1636" Action="None" />
<Rule Id="SA1642" Action="None" />
<Rule Id="SA1643" Action="None" />
<Rule Id="SA1652" Action="None" />
</Rules>
</RuleSet>

View File

@ -33,3 +33,11 @@ The example below is taken from the samples folder so please check it if this do
}
}
}
If you are using stateless / guest exe services ocelot will be able to proxy through the naming service without anything else. However
if you are using statefull / actor services you must send the PartitionKind and PartitionKey query string values with the client
request e.g.
GET http://ocelot.com/EquipmentInterfaces?PartitionKind=xxx&PartitionKey=xxx
There is no way for Ocelot to work these out for you.

View File

@ -9,7 +9,7 @@ author: raunakpandya edited by Tom Pallister for Ocelot
This shows a service fabric cluster with Ocelot exposed over HTTP accessing services in the cluster via the naming service. If you want to try and use Ocelot with
Service Fabric I reccomend using this as a starting point.
Ocelot does not support partitioned services (stateful & actors) at the moment.
If you want to use statefull / actors you must send the PartitionKind and PartitionKey to Ocelot as query string parameters.
I have not tested this sample on Service Fabric hosted on Linux just a Windows dev cluster. This sample assumes a good understanding of Service Fabric.

View File

@ -63,4 +63,3 @@ namespace Ocelot.Authentication.Middleware
}
}
}

View File

@ -47,6 +47,7 @@ namespace Ocelot.Authorisation
});
}
}
return new OkResponse<bool>(true);
}
}

View File

@ -123,7 +123,6 @@ namespace Ocelot.Cache.Middleware
var contentHeaders = response?.Content?.Headers.ToDictionary(v => v.Key, v => v.Value);
var cached = new CachedResponse(statusCode, headers, body, contentHeaders);
return cached;
}

View File

@ -4,7 +4,6 @@ using Ocelot.Configuration.File;
namespace Ocelot.Cache
{
public class RegionCreator : IRegionCreator
{
public string Create(FileReRoute reRoute)

View File

@ -8,6 +8,7 @@ namespace Ocelot.Cache
{
Value = value;
}
public List<string> Value {get;private set;}
}
}

View File

@ -39,6 +39,7 @@ namespace Ocelot.Claims.Middleware
return;
}
}
await _next.Invoke(context);
}
}

View File

@ -215,7 +215,6 @@ namespace Ocelot.Configuration.Builder
return this;
}
public DownstreamReRoute Build()
{
return new DownstreamReRoute(

View File

@ -35,7 +35,6 @@ namespace Ocelot.Configuration.Creator
private readonly IHeaderFindAndReplaceCreator _headerFAndRCreator;
private readonly IDownstreamAddressesCreator _downstreamAddressesCreator;
public FileOcelotConfigurationCreator(
IOptions<FileConfiguration> options,
IConfigurationValidator configurationValidator,

View File

@ -67,7 +67,6 @@ namespace Ocelot.Configuration.Creator
return false;
}
private bool IsPlaceHolder(string upstreamTemplate, int i)
{
return upstreamTemplate[i] == '{';

View File

@ -7,6 +7,7 @@
Host = host;
Port = port;
}
public string Host { get; private set; }
public int Port { get; private set; }
}

View File

@ -12,6 +12,7 @@ namespace Ocelot.Configuration.File
}
public List<FileReRoute> ReRoutes { get; set; }
// Seperate field for aggregates because this let's you re-use ReRoutes in multiple Aggregates
public List<FileAggregateReRoute> Aggregates { get;set; }
public FileGlobalConfiguration GlobalConfiguration { get; set; }

View File

@ -1,5 +1,4 @@

namespace Ocelot.Configuration.File
namespace Ocelot.Configuration.File
{
public class FileGlobalConfiguration
{

View File

@ -34,6 +34,4 @@ namespace Ocelot.Configuration.File
/// </summary>
public int HttpStatusCode { get; set; } = 429;
}
}

View File

@ -6,7 +6,6 @@ using System.Threading.Tasks;
namespace Ocelot.Configuration.File
{
public class FileRateLimitRule
{
public FileRateLimitRule()
@ -27,6 +26,7 @@ namespace Ocelot.Configuration.File
public string Period { get; set; }
public double PeriodTimespan { get; set; }
/// <summary>
/// Maximum number of requests that a client can make in a defined period
/// </summary>
@ -38,6 +38,7 @@ namespace Ocelot.Configuration.File
{
return string.Empty;
}
var sb = new StringBuilder();
sb.Append(
$"{nameof(Period)}:{Period},{nameof(PeriodTimespan)}:{PeriodTimespan:F},{nameof(Limit)}:{Limit},{nameof(ClientWhitelist)}:[");

View File

@ -16,7 +16,6 @@ namespace Ocelot.Configuration
TimeoutStrategy = timeoutStrategy;
}
public int ExceptionsAllowedBeforeBreaking { get; private set; }
public int DurationOfBreak { get; private set; }
@ -24,6 +23,5 @@ namespace Ocelot.Configuration
public int TimeoutValue { get; private set; }
public TimeoutStrategy TimeoutStrategy { get; private set; }
}
}

View File

@ -17,6 +17,7 @@ namespace Ocelot.Configuration
public string Period { get; private set; }
public double PeriodTimespan { get; private set; }
/// <summary>
/// Maximum number of requests that a client can make in a defined period
/// </summary>

View File

@ -9,8 +9,8 @@ namespace Ocelot.Configuration
IsCached = isCached;
IsQos = isQos;
EnableRateLimiting = isEnableRateLimiting;
}
public bool IsAuthenticated { get; private set; }
public bool IsAuthorised { get; private set; }
public bool IsCached { get; private set; }

View File

@ -34,7 +34,6 @@ namespace Ocelot.Configuration.Repository
_polling = true;
await Poll();
_polling = false;
}, null, 0, 1000);
}

View File

@ -9,7 +9,6 @@ using Ocelot.ServiceDiscovery;
namespace Ocelot.Configuration.Repository
{
public class ConsulFileConfigurationRepository : IFileConfigurationRepository
{
private readonly ConsulClient _consul;

View File

@ -12,7 +12,7 @@ namespace Ocelot.Configuration.Setter
private readonly IOcelotConfigurationCreator _configCreator;
private readonly IFileConfigurationRepository _repo;
public FileConfigurationSetter(IOcelotConfigurationRepository configRepo,
public FileConfigurationSetter(IOcelotConfigurationRepository configRepo,
IOcelotConfigurationCreator configCreator, IFileConfigurationRepository repo)
{
_configRepo = configRepo;

View File

@ -9,7 +9,6 @@ namespace Ocelot.Configuration.Validator
{
public FileValidationFailedError(string message) : base(message, OcelotErrorCode.FileValidationFailedError)
{
}
}
}

View File

@ -67,6 +67,7 @@ namespace Ocelot.Configuration.Validator
{
return true;
}
var schemes = await _authenticationSchemeProvider.GetAllSchemesAsync();
var supportedSchemes = schemes.Select(scheme => scheme.Name).ToList();

View File

@ -153,7 +153,6 @@ namespace Ocelot.DependencyInjection
// We add this here so that we can always inject something into the factory for IoC..
_services.AddSingleton<IServiceTracer, FakeServiceTracer>();
}
public IOcelotAdministrationBuilder AddAdministration(string path, string secret)
@ -266,7 +265,6 @@ namespace Ocelot.DependencyInjection
var baseSchemeUrlAndPort = urlFinder.Find();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
_services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(o =>
{

View File

@ -11,6 +11,7 @@ namespace Ocelot.DownstreamRouteFinder
TemplatePlaceholderNameAndValues = templatePlaceholderNameAndValues;
ReRoute = reRoute;
}
public List<PlaceholderNameAndValue> TemplatePlaceholderNameAndValues { get; private set; }
public ReRoute ReRoute { get; private set; }
}

View File

@ -17,7 +17,6 @@ namespace Ocelot.DownstreamRouteFinder.Middleware
private readonly IOcelotConfigurationProvider _configProvider;
private readonly IMultiplexer _multiplexer;
public DownstreamRouteFinderMiddleware(OcelotRequestDelegate next,
IOcelotLoggerFactory loggerFactory,
IDownstreamRouteFinder downstreamRouteFinder,
@ -60,8 +59,8 @@ namespace Ocelot.DownstreamRouteFinder.Middleware
return;
}
//todo - put this back in
// _logger.LogDebug("downstream template is {downstreamRoute.Data.ReRoute.DownstreamPath}", downstreamRoute.Data.ReRoute.DownstreamReRoute.DownstreamPathTemplate);
// todo - put this back in
//// _logger.LogDebug("downstream template is {downstreamRoute.Data.ReRoute.DownstreamPath}", downstreamRoute.Data.ReRoute.DownstreamReRoute.DownstreamPathTemplate);
context.TemplatePlaceholderNameAndValues = downstreamRoute.Data.TemplatePlaceholderNameAndValues;

View File

@ -7,6 +7,7 @@ namespace Ocelot.DownstreamRouteFinder.UrlMatcher
Name = name;
Value = value;
}
public string Name {get;private set;}
public string Value {get;private set;}
}

View File

@ -6,6 +6,7 @@ namespace Ocelot.DownstreamRouteFinder.UrlMatcher
{
Match = match;
}
public bool Match {get;private set;}
}
}

View File

@ -50,6 +50,7 @@ namespace Ocelot.DownstreamRouteFinder.UrlMatcher
counterForTemplate = endOfPlaceholder;
}
counterForPath++;
}
@ -90,6 +91,7 @@ namespace Ocelot.DownstreamRouteFinder.UrlMatcher
return variableName;
}
private int GetNextCounterPosition(string urlTemplate, int counterForTemplate, char delimiter)
{
var closingPlaceHolderPositionOnTemplate = urlTemplate.IndexOf(delimiter, counterForTemplate);

View File

@ -7,6 +7,8 @@ using Ocelot.Middleware;
using System;
using System.Linq;
using Ocelot.DownstreamRouteFinder.Middleware;
using Ocelot.Responses;
using Ocelot.Values;
namespace Ocelot.DownstreamUrlCreator.Middleware
{
@ -40,21 +42,9 @@ namespace Ocelot.DownstreamUrlCreator.Middleware
UriBuilder uriBuilder;
//todo - feel this is a bit crap the way we build the url dont see why we need this builder thing..maybe i blew my own brains out
// when i originally wrote it..
if (context.ServiceProviderConfiguration.Type == "ServiceFabric" && context.DownstreamReRoute.UseServiceDiscovery)
if (ServiceFabricRequest(context))
{
_logger.LogInformation("DownstreamUrlCreatorMiddleware - going to try set service fabric path");
var scheme = context.DownstreamReRoute.DownstreamScheme;
var host = context.DownstreamRequest.RequestUri.Host;
var port = context.DownstreamRequest.RequestUri.Port;
var serviceFabricPath = $"/{context.DownstreamReRoute.ServiceName + dsPath.Data.Value}";
_logger.LogInformation("DownstreamUrlCreatorMiddleware - service fabric path is {proxyUrl}", serviceFabricPath);
var uri = new Uri($"{scheme}://{host}:{port}{serviceFabricPath}?cmd=instance");
uriBuilder = new UriBuilder(uri);
uriBuilder = CreateServiceFabricUri(context, dsPath);
}
else
{
@ -71,5 +61,38 @@ namespace Ocelot.DownstreamUrlCreator.Middleware
await _next.Invoke(context);
}
private UriBuilder CreateServiceFabricUri(DownstreamContext context, Response<DownstreamPath> dsPath)
{
var query = context.DownstreamRequest.RequestUri.Query;
var scheme = context.DownstreamReRoute.DownstreamScheme;
var host = context.DownstreamRequest.RequestUri.Host;
var port = context.DownstreamRequest.RequestUri.Port;
var serviceFabricPath = $"/{context.DownstreamReRoute.ServiceName + dsPath.Data.Value}";
Uri uri;
if (RequestForStatefullService(query))
{
uri = new Uri($"{scheme}://{host}:{port}{serviceFabricPath}{query}");
}
else
{
var split = string.IsNullOrEmpty(query) ? "?" : "&";
uri = new Uri($"{scheme}://{host}:{port}{serviceFabricPath}{query}{split}cmd=instance");
}
return new UriBuilder(uri);
}
private static bool ServiceFabricRequest(DownstreamContext context)
{
return context.ServiceProviderConfiguration.Type == "ServiceFabric" && context.DownstreamReRoute.UseServiceDiscovery;
}
private static bool RequestForStatefullService(string query)
{
return query.Contains("PartitionKind") && query.Contains("PartitionKey");
}
}
}

View File

@ -100,6 +100,7 @@ namespace Ocelot.Errors.Middleware
message =
$"{message}, inner exception message {e.InnerException.Message}, inner exception stack {e.InnerException.StackTrace}";
}
return $"{message} RequestId: {context.HttpContext.TraceIdentifier}";
}
}

View File

@ -26,6 +26,7 @@ namespace Ocelot.Headers
return $"{downstreamUrl}/";
});
}
public Response Replace(HttpResponseMessage response, List<HeaderFindAndReplace> fAndRs, HttpRequestMessage httpRequestMessage)
{
foreach (var f in fAndRs)

View File

@ -37,7 +37,6 @@
return new OkResponse<string>(value);
}
public Response<List<string>> GetValuesByClaimType(IEnumerable<Claim> claims, string claimType)
{
List<string> values = new List<string>();
@ -47,7 +46,6 @@
return new OkResponse<List<string>>(values);
}
private Response<string> GetValue(IEnumerable<Claim> claims, string key)
{
var claim = claims.FirstOrDefault(c => c.Type == key);

View File

@ -9,6 +9,7 @@ namespace Ocelot.LoadBalancer.LoadBalancers
HostAndPort = hostAndPort;
Connections = connections;
}
public ServiceHostAndPort HostAndPort { get; private set; }
public int Connections { get; private set; }
}

View File

@ -17,7 +17,6 @@ namespace Ocelot.LoadBalancer.LoadBalancers
_services = services;
}
public async Task<Response<ServiceHostAndPort>> Lease()
{
var services = await _services.Invoke();

View File

@ -6,6 +6,7 @@ namespace Ocelot.Logging
{
IOcelotLogger CreateLogger<T>();
}
/// <summary>
/// Thin wrapper around the DotNet core logging framework, used to allow the scopedDataRepository to be injected giving access to the Ocelot RequestId
/// </summary>

View File

@ -22,8 +22,6 @@ namespace Ocelot.Middleware
public HttpRequestMessage DownstreamRequest { get; set; }
public HttpResponseMessage DownstreamResponse { get; set; }
public List<Error> Errors { get;set; }
//public string RequestId {get;set;}
//public string PreviousRequestId {get;set;}
public bool IsError => Errors.Count > 0;
}
}

View File

@ -59,9 +59,11 @@
var firstDelegate = pipelineBuilder.Build();
//inject first delegate into first piece of asp.net middleware..maybe not like this
//then because we are updating the http context in ocelot it comes out correct for
//rest of asp.net..
/*
inject first delegate into first piece of asp.net middleware..maybe not like this
then because we are updating the http context in ocelot it comes out correct for
rest of asp.net..
*/
builder.Use(async (context, task) =>
{

View File

@ -38,6 +38,5 @@
/// This allows the user to implement there own query string manipulation logic
/// </summary>
public Func<DownstreamContext, Func<Task>, Task> PreQueryStringBuilderMiddleware { get; set; }
}
}

View File

@ -17,6 +17,7 @@
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<Authors>Tom Pallister</Authors>
<CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>full</DebugType>
@ -35,6 +36,9 @@
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.0.2">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="System.Text.RegularExpressions" Version="4.3.0" />
<PackageReference Include="CacheManager.Core" Version="1.1.1" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="1.1.1" />

View File

@ -8,8 +8,8 @@ namespace Ocelot.Raft
public FakeCommand(string value)
{
this.Value = value;
}
public string Value { get; private set; }
}
}

View File

@ -27,16 +27,19 @@ namespace Ocelot.Raft
_finder = finder;
_options = options;
_peers = new List<IPeer>();
//todo - sort out async nonsense..
var config = _provider.Get().GetAwaiter().GetResult();
foreach (var item in _options.Value.Peers)
{
var httpClient = new HttpClient();
//todo what if this errors?
var httpPeer = new HttpPeer(item.HostAndPort, httpClient, _finder, config.Data, _identityServerConfig);
_peers.Add(httpPeer);
}
}
public List<IPeer> Get()
{
return _peers;

View File

@ -28,7 +28,7 @@ namespace Ocelot.Raft
{
_identityServerConfiguration = identityServerConfiguration;
_config = config;
Id = hostAndPort;
Id = hostAndPort;
_hostAndPort = hostAndPort;
_httpClient = httpClient;
_jsonSerializerSettings = new JsonSerializerSettings() {
@ -68,6 +68,7 @@ namespace Ocelot.Raft
{
SetToken();
}
var json = JsonConvert.SerializeObject(appendEntries, _jsonSerializerSettings);
var content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
@ -88,12 +89,14 @@ namespace Ocelot.Raft
}
}
public Response<T> Request<T>(T command) where T : ICommand
public Response<T> Request<T>(T command)
where T : ICommand
{
if(_token == null)
{
SetToken();
}
var json = JsonConvert.SerializeObject(command, _jsonSerializerSettings);
var content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

View File

@ -19,7 +19,7 @@ namespace Ocelot.Raft
//todo - handle an error
//hack it to just cast as at the moment we know this is the only command :P
var hack = (UpdateFileConfiguration)log.CommandData;
_setter.Set(hack.Configuration).GetAwaiter().GetResult();;
_setter.Set(hack.Configuration).GetAwaiter().GetResult();
}
}
}

View File

@ -24,6 +24,7 @@ namespace Ocelot.Raft
FileStream fs = File.Create(_path);
fs.Dispose();
}
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
@ -59,6 +60,7 @@ namespace Ocelot.Raft
}
}
}
return result;
}
}
@ -88,6 +90,7 @@ namespace Ocelot.Raft
}
}
}
return result;
}
}
@ -113,6 +116,7 @@ namespace Ocelot.Raft
}
}
}
return result;
}
}
@ -129,6 +133,7 @@ namespace Ocelot.Raft
TypeNameHandling = TypeNameHandling.All
};
var data = JsonConvert.SerializeObject(log, jsonSerializerSettings);
//todo - sql injection dont copy this..
var sql = $"insert into logs (data) values ('{data}')";
using(var command = new SqliteCommand(sql, connection))
@ -153,6 +158,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index};";
using(var command = new SqliteCommand(sql, connection))
@ -183,6 +189,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index}";
using(var command = new SqliteCommand(sql, connection))
@ -207,6 +214,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var sql = $"select id, data from logs where id >= {index}";
using(var command = new SqliteCommand(sql, connection))
@ -222,7 +230,6 @@ namespace Ocelot.Raft
};
var log = JsonConvert.DeserializeObject<LogEntry>(data, jsonSerializerSettings);
logsToReturn.Add((id, log));
}
}
}
@ -230,7 +237,6 @@ namespace Ocelot.Raft
return logsToReturn;
}
}
public long GetTermAtIndex(int index)
@ -241,6 +247,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index}";
using(var command = new SqliteCommand(sql, connection))
@ -256,9 +263,11 @@ namespace Ocelot.Raft
}
}
}
return result;
}
}
public void Remove(int indexOfCommand)
{
lock(_lock)
@ -266,6 +275,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var deleteSql = $"delete from logs where id >= {indexOfCommand};";
using(var deleteCommand = new SqliteCommand(deleteSql, connection))

View File

@ -7,7 +7,6 @@ using System.Threading.Tasks;
namespace Ocelot.RateLimit
{
public class ClientRateLimitProcessor
{
private readonly IRateLimitCounterHandler _counterHandler;
@ -24,7 +23,6 @@ namespace Ocelot.RateLimit
return _core.ProcessRequest(requestIdentity, option);
}
public int RetryAfterFrom(DateTime timestamp, RateLimitRule rule)
{
return _core.RetryAfterFrom(timestamp, rule);
@ -39,7 +37,5 @@ namespace Ocelot.RateLimit
{
return _core.ConvertToTimeSpan(timeSpan);
}
}
}

View File

@ -34,6 +34,7 @@ namespace Ocelot.RateLimit
{
return JsonConvert.DeserializeObject<RateLimitCounter>(stored);
}
return null;
}

View File

@ -31,6 +31,7 @@ namespace Ocelot.RateLimit.Middleware
public async Task Invoke(DownstreamContext context)
{
var options = context.DownstreamReRoute.RateLimitOptions;
// check if rate limiting is enabled
if (!context.DownstreamReRoute.EnableEndpointEndpointRateLimiting)
{
@ -38,6 +39,7 @@ namespace Ocelot.RateLimit.Middleware
await _next.Invoke(context);
return;
}
// compute identity from request
var identity = SetIdentity(context.HttpContext, options);
@ -65,13 +67,14 @@ namespace Ocelot.RateLimit.Middleware
LogBlockedRequest(context.HttpContext, identity, counter, rule, context.DownstreamReRoute);
var retrystring = retryAfter.ToString(System.Globalization.CultureInfo.InvariantCulture);
// break execution
await ReturnQuotaExceededResponse(context.HttpContext, options, retrystring);
return;
}
}
//set X-Rate-Limit headers for the longest period
if (!options.DisableRateLimitHeaders)
{
@ -103,6 +106,7 @@ namespace Ocelot.RateLimit.Middleware
{
return true;
}
return false;
}
@ -134,8 +138,5 @@ namespace Ocelot.RateLimit.Middleware
return Task.CompletedTask;
}
}
}

View File

@ -38,6 +38,7 @@ namespace Ocelot.RateLimit
{
// increment request count
var totalRequests = entry.Value.TotalRequests + 1;
// deep copy
counter = new RateLimitCounter(entry.Value.Timestamp, totalRequests);
}
@ -62,6 +63,7 @@ namespace Ocelot.RateLimit
var expirationTime = ConvertToTimeSpan(rule.Period);
_counterHandler.Set(counterId, counter, expirationTime);
}
return counter;
}
@ -69,6 +71,7 @@ namespace Ocelot.RateLimit
{
var counterId = ComputeCounterKey(requestIdentity, option);
var rule = option.RateLimitRule;
// stores: id (string) - timestamp (datetime) - total_requests (long)
_counterHandler.Set(counterId, counter, expirationTime);
}
@ -92,7 +95,6 @@ namespace Ocelot.RateLimit
rule.Period,
rule.Limit.ToString(),
(DateTime.UtcNow + ConvertToTimeSpan(rule.Period)).ToUniversalTime().ToString("o", DateTimeFormatInfo.InvariantInfo));
}
return headers;
@ -142,6 +144,5 @@ namespace Ocelot.RateLimit
throw new FormatException($"{timeSpan} can't be converted to TimeSpan, unknown type {type}");
}
}
}
}

View File

@ -92,4 +92,3 @@
}
}
}

View File

@ -18,7 +18,6 @@ namespace Ocelot.RequestId.Middleware
private readonly IOcelotLogger _logger;
private readonly IRequestScopedDataRepository _requestScopedDataRepository;
public ReRouteRequestIdMiddleware(OcelotRequestDelegate next,
IOcelotLoggerFactory loggerFactory,
IRequestScopedDataRepository requestScopedDataRepository)

View File

@ -55,7 +55,6 @@ namespace Ocelot.Requester
{
_cacheHandlers.Set(cacheKey, httpClient, TimeSpan.FromHours(24));
}
}
private IHttpClient GetHttpClient(string cacheKey, IHttpClientBuilder builder, DownstreamContext request)

View File

@ -0,0 +1,6 @@
namespace Ocelot.Requester
{
public interface ITracingHandler
{
}
}

View File

@ -41,6 +41,7 @@ namespace Ocelot.Requester
{
connectionQueue.TryDequeue(out client);
}
return client;
}

View File

@ -8,10 +8,6 @@ using Butterfly.OpenTracing;
namespace Ocelot.Requester
{
public interface ITracingHandler
{
}
public class OcelotHttpTracingHandler : DelegatingHandler, ITracingHandler
{
private readonly IServiceTracer _tracer;
@ -35,7 +31,7 @@ namespace Ocelot.Requester
{
request.Headers.Remove(prefix_spanId);
request.Headers.TryAddWithoutValidation(prefix_spanId, span.SpanContext.SpanId);
};
}
span.Tags.Client().Component("HttpClient")
.HttpMethod(request.Method.Method)
@ -51,7 +47,7 @@ namespace Ocelot.Requester
if (!c.Contains(k))
{
c.Add(k, v);
};
}
});
span.Log(LogField.CreateNew().ClientSend());

View File

@ -50,7 +50,6 @@ namespace Ocelot.Responder
httpContext.Response.StatusCode = (int)response.StatusCode;
return Task.CompletedTask;
}, context);
using (Stream stream = new MemoryStream(content))

View File

@ -29,7 +29,6 @@ namespace Ocelot.Responder.Middleware
_responder = responder;
_codeMapper = codeMapper;
_logger = loggerFactory.CreateLogger<ResponderMiddleware>();
}
public async Task Invoke(DownstreamContext context)

View File

@ -8,6 +8,7 @@ namespace Ocelot.Responses
public ErrorResponse(Error error) : base(new List<Error>{error})
{
}
public ErrorResponse(List<Error> errors) : base(errors)
{
}

View File

@ -3,13 +3,15 @@ using Ocelot.Errors;
namespace Ocelot.Responses
{
#pragma warning disable SA1649 // File name must match first type name
public class ErrorResponse<T> : Response<T>
#pragma warning restore SA1649 // File name must match first type name
{
public ErrorResponse(Error error)
: base(new List<Error> {error})
{
}
public ErrorResponse(List<Error> errors)
: base(errors)
{

View File

@ -1,6 +1,8 @@
namespace Ocelot.Responses
{
#pragma warning disable SA1649 // File name must match first type name
public class OkResponse<T> : Response<T>
#pragma warning restore SA1649 // File name must match first type name
{
public OkResponse(T data) : base(data)
{

View File

@ -3,7 +3,9 @@ using Ocelot.Errors;
namespace Ocelot.Responses
{
#pragma warning disable SA1649 // File name must match first type name
public abstract class Response<T> : Response
#pragma warning restore SA1649 // File name must match first type name
{
protected Response(T data)
{
@ -15,6 +17,5 @@ namespace Ocelot.Responses
}
public T Data { get; private set; }
}
}

View File

@ -14,7 +14,7 @@ namespace Ocelot.ServiceDiscovery
_factory = factory;
}
public IServiceDiscoveryProvider Get(ServiceProviderConfiguration serviceConfig, DownstreamReRoute reRoute)
public IServiceDiscoveryProvider Get(ServiceProviderConfiguration serviceConfig, DownstreamReRoute reRoute)
{
if (reRoute.UseServiceDiscovery)
{

View File

@ -16,6 +16,7 @@ namespace Ocelot.Values
Version = version;
Tags = tags;
}
public string Id { get; private set; }
public string Name { get; private set; }

View File

@ -15,7 +15,6 @@ namespace Ocelot.AcceptanceTests
public class AggregateTests : IDisposable
{
private IWebHost _serviceOneBuilder;
private IWebHost _serviceTwoBuilder;
private readonly Steps _steps;
private string _downstreamPathOne;
private string _downstreamPathTwo;
@ -229,7 +228,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
[Fact]
public void should_be_thread_safe()
{
@ -365,7 +363,6 @@ namespace Ocelot.AcceptanceTests
public void Dispose()
{
_serviceOneBuilder?.Dispose();
_serviceTwoBuilder?.Dispose();
_steps.Dispose();
}
}

View File

@ -177,7 +177,7 @@ namespace Ocelot.AcceptanceTests
AuthenticationOptions = new FileAuthenticationOptions
{
AuthenticationProviderKey = "Test",
AllowedScopes = new List<string>{ "api", "api.readOnly", "openid", "offline_access" },
AllowedScopes = new List<string>{ "api", "api.readOnly", "openid", "offline_access" },
},
}
}
@ -218,7 +218,7 @@ namespace Ocelot.AcceptanceTests
AuthenticationOptions = new FileAuthenticationOptions
{
AuthenticationProviderKey = "Test",
AllowedScopes = new List<string>{ "api", "openid", "offline_access" },
AllowedScopes = new List<string>{ "api", "openid", "offline_access" },
},
}
}
@ -356,7 +356,6 @@ namespace Ocelot.AcceptanceTests
"CustomerId", "LocationId", "UserType", "UserId"
}
},
})
.AddInMemoryClients(new List<Client>
{
@ -437,7 +436,6 @@ namespace Ocelot.AcceptanceTests
"CustomerId", "LocationId", "UserType", "UserId", "Role"
}
},
})
.AddInMemoryClients(new List<Client>
{
@ -450,7 +448,6 @@ namespace Ocelot.AcceptanceTests
AccessTokenType = tokenType,
Enabled = true,
RequireClientSecret = false,
}
})
.AddTestUsers(users);

View File

@ -52,7 +52,7 @@ namespace Ocelot.AcceptanceTests
UpstreamHttpMethod = new List<string> { "Get" },
HttpHandlerOptions = new FileHttpHandlerOptions
{
UseTracing = true
UseTracing = true
},
QoSOptions = new FileQoSOptions
{
@ -77,7 +77,7 @@ namespace Ocelot.AcceptanceTests
UpstreamHttpMethod = new List<string> { "Get" },
HttpHandlerOptions = new FileHttpHandlerOptions
{
UseTracing = true
UseTracing = true
},
QoSOptions = new FileQoSOptions
{
@ -104,7 +104,6 @@ namespace Ocelot.AcceptanceTests
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Tom"))
.BDDfy();
var commandOnAllStateMachines = WaitFor(5000).Until(() => _butterflyCalled == 4);
commandOnAllStateMachines.ShouldBeTrue();

View File

@ -1,19 +1,14 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.AcceptanceTests
{
public class CannotStartOcelotTests : IDisposable
{
private IWebHost _builder;
private readonly Steps _steps;
private string _downstreamPath;
public CannotStartOcelotTests()
{
@ -51,7 +46,6 @@ namespace Ocelot.AcceptanceTests
public void Dispose()
{
_builder?.Dispose();
_steps.Dispose();
}
}

View File

@ -156,7 +156,7 @@ namespace Ocelot.AcceptanceTests
{
new ApiResource
{
Name = apiName,
Name = apiName,
Description = "My API",
Enabled = true,
DisplayName = "test",

View File

@ -20,13 +20,11 @@ namespace Ocelot.AcceptanceTests
private readonly Steps _steps;
private int _counterOne;
public ClientRateLimitTests()
{
_steps = new Steps();
}
public void Dispose()
{
_builder?.Dispose();
@ -56,7 +54,7 @@ namespace Ocelot.AcceptanceTests
UpstreamHttpMethod = new List<string> { "Get" },
RequestIdKey = _steps.RequestIdKey,
RateLimitOptions = new FileRateLimitRule()
RateLimitOptions = new FileRateLimitRule()
{
EnableRateLimiting = true,
ClientWhitelist = new List<string>(),
@ -75,7 +73,6 @@ namespace Ocelot.AcceptanceTests
QuotaExceededMessage = "",
RateLimitCounterPrefix = "",
HttpStatusCode = 428
},
RequestIdKey ="oceclientrequest"
}
@ -93,7 +90,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
[Fact]
public void should_call_middleware_withWhitelistClient()
{
@ -117,7 +113,7 @@ namespace Ocelot.AcceptanceTests
UpstreamHttpMethod = new List<string> { "Get" },
RequestIdKey = _steps.RequestIdKey,
RateLimitOptions = new FileRateLimitRule()
RateLimitOptions = new FileRateLimitRule()
{
EnableRateLimiting = true,
ClientWhitelist = new List<string>() { "ocelotclient1"},
@ -148,7 +144,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath)
{
_builder = new WebHostBuilder()
@ -172,7 +167,5 @@ namespace Ocelot.AcceptanceTests
_builder.Start();
}
}
}

View File

@ -175,7 +175,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
[Fact]
public void should_load_configuration_out_of_consul_if_it_is_changed()
{
@ -308,7 +307,6 @@ namespace Ocelot.AcceptanceTests
await context.Response.WriteJsonAsync(new FakeConsulGetResponse[] { kvp });
}
else if (context.Request.Method.ToLower() == "put" && context.Request.Path.Value == "/v1/kv/OcelotConfiguration")
{
try

View File

@ -25,7 +25,7 @@ namespace Ocelot.AcceptanceTests
public CustomMiddlewareTests()
{
_counter = 0;
_steps = new Steps();;
_steps = new Steps();
_configurationPath = "configuration.json";
}
@ -287,7 +287,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
[Fact(Skip = "This is just an example to show how you could hook into Ocelot pipeline with your own middleware. At the moment you must use Response.OnCompleted callback and cannot change the response :( I will see if this can be changed one day!")]
public void should_fix_issue_237()
{
@ -352,14 +351,13 @@ namespace Ocelot.AcceptanceTests
app.UsePathBase(basePath);
app.Run(context =>
{
if(string.IsNullOrEmpty(basePath))
{
context.Response.StatusCode = statusCode;
}
else if(context.Request.Path.Value != basePath)
{
context.Response.StatusCode = 404;;
context.Response.StatusCode = 404;
}
return Task.CompletedTask;

View File

@ -186,7 +186,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string headerKey)
{
_builder = new WebHostBuilder()

View File

@ -71,7 +71,6 @@ namespace Ocelot.AcceptanceTests
class FakeHandler : DelegatingHandler
{
public DateTime TimeCalled { get; private set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
@ -111,6 +110,5 @@ namespace Ocelot.AcceptanceTests
_builder.Start();
}
}
}

View File

@ -160,7 +160,6 @@ namespace Ocelot.AcceptanceTests
{
await context.Response.WriteAsync(exception.StackTrace);
}
});
})
.Build();

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>0.0.0-dev</VersionPrefix>
<TargetFramework>netcoreapp2.0</TargetFramework>
@ -11,7 +11,9 @@
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<None Update="configuration.json;appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
@ -29,6 +31,9 @@
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0-preview-20171031-01" />
<PackageReference Include="StyleCop.Analyzers" Version="1.0.2">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.0.0" />

View File

@ -52,7 +52,6 @@ namespace Ocelot.AcceptanceTests
TimeoutValue = 500,
DurationOfBreak = 1000
},
}
}
};

View File

@ -543,7 +543,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
[Fact]
public void should_return_response_200_with_complex_url_that_starts_with_placeholder()
{
@ -578,7 +577,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
[Fact]
public void should_not_add_trailing_slash_to_downstream_url()
{
@ -834,7 +832,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
[Fact]
public void should_fix_145()
{

View File

@ -360,7 +360,6 @@ namespace Ocelot.AcceptanceTests
{
await context.Response.WriteAsync(exception.StackTrace);
}
});
})
.Build();

View File

@ -27,7 +27,7 @@ namespace Ocelot.AcceptanceTests
}
[Fact]
public void should_support_service_fabric_naming_and_dns_service()
public void should_support_service_fabric_naming_and_dns_service_stateless_and_guest()
{
var configuration = new FileConfiguration
{
@ -54,7 +54,7 @@ namespace Ocelot.AcceptanceTests
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:19081", "/OcelotServiceApplication/OcelotApplicationService/api/values", 200, "Hello from Laura"))
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:19081", "/OcelotServiceApplication/OcelotApplicationService/api/values", 200, "Hello from Laura", "cmd=instance"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway("/EquipmentInterfaces"))
@ -63,7 +63,44 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody)
[Fact]
public void should_support_service_fabric_naming_and_dns_service_statefull_and_actors()
{
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/values",
DownstreamScheme = "http",
UpstreamPathTemplate = "/EquipmentInterfaces",
UpstreamHttpMethod = new List<string> { "Get" },
UseServiceDiscovery = true,
ServiceName = "OcelotServiceApplication/OcelotApplicationService"
}
},
GlobalConfiguration = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider()
{
Host = "localhost",
Port = 19081,
Type = "ServiceFabric"
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:19081", "/OcelotServiceApplication/OcelotApplicationService/api/values", 200, "Hello from Laura", "PartitionKind=test&PartitionKey=1"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway("/EquipmentInterfaces?PartitionKind=test&PartitionKey=1"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.BDDfy();
}
private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody, string expectedQueryString)
{
_builder = new WebHostBuilder()
.UseUrls(baseUrl)
@ -84,9 +121,8 @@ namespace Ocelot.AcceptanceTests
}
else
{
if (context.Request.Query.TryGetValue("cmd", out var values))
if (context.Request.QueryString.Value.Contains(expectedQueryString))
{
values.First().ShouldBe("instance");
context.Response.StatusCode = statusCode;
await context.Response.WriteAsync(responseBody);
}

View File

@ -1,7 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
@ -19,15 +17,11 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Repository;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.ServiceDiscovery;
using Shouldly;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;
using Ocelot.AcceptanceTests.Caching;
using Butterfly.Client.AspNetCore;
using Butterfly.Client.Tracing;
namespace Ocelot.AcceptanceTests
{
@ -42,11 +36,9 @@ namespace Ocelot.AcceptanceTests
public string RequestIdKey = "OcRequestId";
private readonly Random _random;
private IWebHostBuilder _webHostBuilder;
private readonly string _baseUrl;
public Steps()
{
_baseUrl = "http://localhost:5000";
_random = new Random();
}
@ -144,6 +136,7 @@ namespace Ocelot.AcceptanceTests
_ocelotClient = _ocelotServer.CreateClient();
}
/*
public void GivenIHaveAddedXForwardedForHeader(string value)
{

View File

@ -58,7 +58,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy();
}
[Fact]
public void should_return_response_200_with_simple_url_and_hosts_match_multiple_re_routes()
{

View File

@ -11,6 +11,7 @@
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
@ -19,6 +20,9 @@
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.10.12" />
<PackageReference Include="StyleCop.Analyzers" Version="1.0.2">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
</Project>

View File

@ -8,7 +8,6 @@ namespace Ocelot.Benchmarks
{
var switcher = new BenchmarkSwitcher(new[] {
typeof(UrlPathToUrlPathTemplateMatcherBenchmarks),
});
switcher.Run(args);

View File

@ -124,7 +124,6 @@ namespace Ocelot.IntegrationTests
{
Host = "127.0.0.1",
}
},
ReRoutes = new List<FileReRoute>()
{
@ -485,7 +484,6 @@ namespace Ocelot.IntegrationTests
app.UseOcelot().Wait();
});
_builderTwo = _webHostBuilderTwo.Build();
_builderTwo.Start();

View File

@ -11,6 +11,7 @@
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<None Update="peers.json;configuration.json;appsettings.json;idsrv3test.pfx">
@ -18,29 +19,32 @@
</None>
</ItemGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}"/>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj"/>
<ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0-preview-20171031-01"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1"/>
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.0.0"/>
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.0.0"/>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0"/>
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0"/>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.0.0"/>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.0.0"/>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0"/>
<PackageReference Include="Microsoft.DotNet.InternalAbstractions" Version="1.0.500-preview2-1-003177"/>
<PackageReference Include="xunit" Version="2.3.1"/>
<PackageReference Include="IdentityServer4" Version="2.0.2"/>
<PackageReference Include="Shouldly" Version="3.0.0-beta0003"/>
<PackageReference Include="TestStack.BDDfy" Version="4.3.2"/>
<PackageReference Include="Consul" Version="0.7.2.3"/>
<PackageReference Include="Rafty" Version="0.4.2"/>
<PackageReference Include="Microsoft.Data.SQLite" Version="2.0.0"/>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0-preview-20171031-01" />
<PackageReference Include="StyleCop.Analyzers" Version="1.0.2">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0" />
<PackageReference Include="Microsoft.DotNet.InternalAbstractions" Version="1.0.500-preview2-1-003177" />
<PackageReference Include="xunit" Version="2.3.1" />
<PackageReference Include="IdentityServer4" Version="2.0.2" />
<PackageReference Include="Shouldly" Version="3.0.0-beta0003" />
<PackageReference Include="TestStack.BDDfy" Version="4.3.2" />
<PackageReference Include="Consul" Version="0.7.2.3" />
<PackageReference Include="Rafty" Version="0.4.2" />
<PackageReference Include="Microsoft.Data.SQLite" Version="2.0.0" />
</ItemGroup>
</Project>

View File

@ -45,6 +45,7 @@ namespace Ocelot.IntegrationTests
_builders = new List<IWebHost>();
_threads = new List<Thread>();
}
public void Dispose()
{
foreach (var builder in _builders)
@ -194,7 +195,6 @@ namespace Ocelot.IntegrationTests
var stopwatch = Stopwatch.StartNew();
while(stopwatch.ElapsedMilliseconds < 10000)
{
}
}
@ -204,10 +204,9 @@ namespace Ocelot.IntegrationTests
var stopwatch = Stopwatch.StartNew();
while(stopwatch.ElapsedMilliseconds < 2000)
{
}
bool CommandCalledOnAllStateMachines()
bool CommandCalledOnAllStateMachines()
{
try
{
@ -225,6 +224,7 @@ namespace Ocelot.IntegrationTests
index.ShouldBe(1);
}
}
_httpClientForAssertions.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.AccessToken);
var result = _httpClientForAssertions.GetAsync($"{peer.HostAndPort}/administration/configuration").Result;
var json = result.Content.ReadAsStringAsync().Result;
@ -248,6 +248,7 @@ namespace Ocelot.IntegrationTests
response.ReRoutes[i].UpstreamPathTemplate.ShouldBe(expecteds.Configuration.ReRoutes[i].UpstreamPathTemplate);
response.ReRoutes[i].UpstreamHttpMethod.ShouldBe(expecteds.Configuration.ReRoutes[i].UpstreamHttpMethod);
}
passed++;
}
@ -384,7 +385,6 @@ namespace Ocelot.IntegrationTests
var stopwatch = Stopwatch.StartNew();
while(stopwatch.ElapsedMilliseconds < 20000)
{
}
}
}

View File

@ -195,6 +195,7 @@ namespace Ocelot.IntegrationTests
result.Result.ShouldBe(result.Random);
}
}
public void Dispose()
{
_builder?.Dispose();
@ -208,7 +209,6 @@ namespace Ocelot.IntegrationTests
{
Result = result;
Random = random;
}
public int Result { get; private set; }

View File

@ -9,6 +9,7 @@
<OutputType>Exe</OutputType>
<PackageId>Ocelot.ManualTest</PackageId>
<RuntimeIdentifiers>osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64</RuntimeIdentifiers>
<CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
@ -38,6 +39,9 @@
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0" />
<PackageReference Include="Consul" Version="0.7.2.3" />
<PackageReference Include="Polly" Version="5.3.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.0.2">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
</Project>

View File

@ -6,24 +6,17 @@ namespace Ocelot.UnitTests.Authentication
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.Authentication.Middleware;
using Ocelot.Configuration.Builder;
using Ocelot.DownstreamRouteFinder;
using Ocelot.DownstreamRouteFinder.Middleware;
using Ocelot.DownstreamRouteFinder.UrlMatcher;
using Ocelot.Logging;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
public class AuthenticationMiddlewareTests
{
private OkResponse<DownstreamRoute> _downstreamRoute;
private AuthenticationMiddleware _middleware;
private Mock<IOcelotLoggerFactory> _factory;
private Mock<IOcelotLogger> _logger;
@ -49,7 +42,7 @@ namespace Ocelot.UnitTests.Authentication
.BDDfy();
}
private void WhenICallTheMiddleware()
private void WhenICallTheMiddleware()
{
_next = async (context) => {
byte[] byteArray = Encoding.ASCII.GetBytes("The user is authenticated");
@ -89,7 +82,7 @@ namespace Ocelot.UnitTests.Authentication
{
string text = reader.ReadToEnd();
return text;
};
}
}
}
}

View File

@ -28,7 +28,6 @@ namespace Ocelot.UnitTests.Authorization
this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim("UserType", "registered"),
}))))
.And(x => x.GivenARouteClaimsRequirement(new Dictionary<string, string>
{

View File

@ -1,5 +1,4 @@
using Ocelot.Errors;
using Ocelot.Infrastructure.RequestData;
using Ocelot.Middleware;
namespace Ocelot.UnitTests.Cache
@ -11,26 +10,19 @@ namespace Ocelot.UnitTests.Cache
using Shouldly;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.Cache;
using Ocelot.Cache.Middleware;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.DownstreamRouteFinder;
using Ocelot.DownstreamRouteFinder.UrlMatcher;
using Ocelot.Logging;
using Ocelot.Responses;
using TestStack.BDDfy;
using Xunit;
using Ocelot.DownstreamRouteFinder.Middleware;
using Microsoft.AspNetCore.Http;
public class OutputCacheMiddlewareRealCacheTests
{
private IOcelotCache<CachedResponse> _cacheManager;
private CachedResponse _response;
private OutputCacheMiddleware _middleware;
private DownstreamContext _downstreamContext;
private OcelotRequestDelegate _next;

Some files were not shown because too many files have changed in this diff Show More