Merge pull request #255 from binarymash/feature/AddStyleCopAnalyzers

Feature/add style cop analyzers
This commit is contained in:
Philip Wood 2018-03-03 17:10:44 +00:00 committed by GitHub
commit a53338312b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
137 changed files with 493 additions and 440 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-and-run-tests.ps1 = build-and-run-tests.ps1
build.cake = build.cake build.cake = build.cake
build.ps1 = build.ps1 build.ps1 = build.ps1
codeanalysis.ruleset = codeanalysis.ruleset
GitVersion.yml = GitVersion.yml GitVersion.yml = GitVersion.yml
global.json = global.json global.json = global.json
LICENSE.md = LICENSE.md LICENSE.md = LICENSE.md
@ -39,14 +40,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Benchmarks", "test\O
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.IntegrationTests", "test\Ocelot.IntegrationTests\Ocelot.IntegrationTests.csproj", "{D4575572-99CA-4530-8737-C296EDA326F8}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.IntegrationTests", "test\Ocelot.IntegrationTests\Ocelot.IntegrationTests.csproj", "{D4575572-99CA-4530-8737-C296EDA326F8}"
EndProject 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 Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU 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}.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.ActiveCfg = Release|Any CPU
{D4575572-99CA-4530-8737-C296EDA326F8}.Release|Any CPU.Build.0 = 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 EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@ -96,9 +81,6 @@ Global
{02BBF4C5-517E-4157-8D21-4B8B9E118B7A} = {5B401523-36DA-4491-B73A-7590A26E420B} {02BBF4C5-517E-4157-8D21-4B8B9E118B7A} = {5B401523-36DA-4491-B73A-7590A26E420B}
{106B49E6-95F6-4A7B-B81C-96BFA74AF035} = {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} {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 EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {21476EFF-778A-4F97-8A56-D1AF1CEC0C48} SolutionGuid = {21476EFF-778A-4F97-8A56-D1AF1CEC0C48}

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

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

View File

@ -47,6 +47,7 @@ namespace Ocelot.Authorisation
}); });
} }
} }
return new OkResponse<bool>(true); 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 contentHeaders = response?.Content?.Headers.ToDictionary(v => v.Key, v => v.Value);
var cached = new CachedResponse(statusCode, headers, body, contentHeaders); var cached = new CachedResponse(statusCode, headers, body, contentHeaders);
return cached; return cached;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -7,6 +7,7 @@
Host = host; Host = host;
Port = port; Port = port;
} }
public string Host { get; private set; } public string Host { get; private set; }
public int Port { 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; } public List<FileReRoute> ReRoutes { get; set; }
// Seperate field for aggregates because this let's you re-use ReRoutes in multiple Aggregates // Seperate field for aggregates because this let's you re-use ReRoutes in multiple Aggregates
public List<FileAggregateReRoute> Aggregates { get;set; } public List<FileAggregateReRoute> Aggregates { get;set; }
public FileGlobalConfiguration GlobalConfiguration { get; set; } public FileGlobalConfiguration GlobalConfiguration { get; set; }

View File

@ -1,5 +1,4 @@
 namespace Ocelot.Configuration.File
namespace Ocelot.Configuration.File
{ {
public class FileGlobalConfiguration public class FileGlobalConfiguration
{ {

View File

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

View File

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

View File

@ -16,7 +16,6 @@ namespace Ocelot.Configuration
TimeoutStrategy = timeoutStrategy; TimeoutStrategy = timeoutStrategy;
} }
public int ExceptionsAllowedBeforeBreaking { get; private set; } public int ExceptionsAllowedBeforeBreaking { get; private set; }
public int DurationOfBreak { get; private set; } public int DurationOfBreak { get; private set; }
@ -24,6 +23,5 @@ namespace Ocelot.Configuration
public int TimeoutValue { get; private set; } public int TimeoutValue { get; private set; }
public TimeoutStrategy TimeoutStrategy { 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 string Period { get; private set; }
public double PeriodTimespan { get; private set; } public double PeriodTimespan { get; private set; }
/// <summary> /// <summary>
/// Maximum number of requests that a client can make in a defined period /// Maximum number of requests that a client can make in a defined period
/// </summary> /// </summary>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -67,6 +67,7 @@ namespace Ocelot.Configuration.Validator
{ {
return true; return true;
} }
var schemes = await _authenticationSchemeProvider.GetAllSchemesAsync(); var schemes = await _authenticationSchemeProvider.GetAllSchemesAsync();
var supportedSchemes = schemes.Select(scheme => scheme.Name).ToList(); 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.. // We add this here so that we can always inject something into the factory for IoC..
_services.AddSingleton<IServiceTracer, FakeServiceTracer>(); _services.AddSingleton<IServiceTracer, FakeServiceTracer>();
} }
public IOcelotAdministrationBuilder AddAdministration(string path, string secret) public IOcelotAdministrationBuilder AddAdministration(string path, string secret)
@ -266,7 +265,6 @@ namespace Ocelot.DependencyInjection
var baseSchemeUrlAndPort = urlFinder.Find(); var baseSchemeUrlAndPort = urlFinder.Find();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
_services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) _services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(o => .AddIdentityServerAuthentication(o =>
{ {

View File

@ -11,6 +11,7 @@ namespace Ocelot.DownstreamRouteFinder
TemplatePlaceholderNameAndValues = templatePlaceholderNameAndValues; TemplatePlaceholderNameAndValues = templatePlaceholderNameAndValues;
ReRoute = reRoute; ReRoute = reRoute;
} }
public List<PlaceholderNameAndValue> TemplatePlaceholderNameAndValues { get; private set; } public List<PlaceholderNameAndValue> TemplatePlaceholderNameAndValues { get; private set; }
public ReRoute ReRoute { 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 IOcelotConfigurationProvider _configProvider;
private readonly IMultiplexer _multiplexer; private readonly IMultiplexer _multiplexer;
public DownstreamRouteFinderMiddleware(OcelotRequestDelegate next, public DownstreamRouteFinderMiddleware(OcelotRequestDelegate next,
IOcelotLoggerFactory loggerFactory, IOcelotLoggerFactory loggerFactory,
IDownstreamRouteFinder downstreamRouteFinder, IDownstreamRouteFinder downstreamRouteFinder,
@ -60,8 +59,8 @@ namespace Ocelot.DownstreamRouteFinder.Middleware
return; return;
} }
//todo - put this back in // todo - put this back in
// _logger.LogDebug("downstream template is {downstreamRoute.Data.ReRoute.DownstreamPath}", downstreamRoute.Data.ReRoute.DownstreamReRoute.DownstreamPathTemplate); //// _logger.LogDebug("downstream template is {downstreamRoute.Data.ReRoute.DownstreamPath}", downstreamRoute.Data.ReRoute.DownstreamReRoute.DownstreamPathTemplate);
context.TemplatePlaceholderNameAndValues = downstreamRoute.Data.TemplatePlaceholderNameAndValues; context.TemplatePlaceholderNameAndValues = downstreamRoute.Data.TemplatePlaceholderNameAndValues;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -17,6 +17,7 @@
<GeneratePackageOnBuild>True</GeneratePackageOnBuild> <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<Authors>Tom Pallister</Authors> <Authors>Tom Pallister</Authors>
<CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>full</DebugType> <DebugType>full</DebugType>
@ -35,6 +36,9 @@
<PackageReference Include="Microsoft.Extensions.Logging.Console" 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.Logging.Debug" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" 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="System.Text.RegularExpressions" Version="4.3.0" />
<PackageReference Include="CacheManager.Core" Version="1.1.1" /> <PackageReference Include="CacheManager.Core" Version="1.1.1" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" 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) public FakeCommand(string value)
{ {
this.Value = value; this.Value = value;
} }
public string Value { get; private set; } public string Value { get; private set; }
} }
} }

View File

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

View File

@ -28,7 +28,7 @@ namespace Ocelot.Raft
{ {
_identityServerConfiguration = identityServerConfiguration; _identityServerConfiguration = identityServerConfiguration;
_config = config; _config = config;
Id = hostAndPort; Id = hostAndPort;
_hostAndPort = hostAndPort; _hostAndPort = hostAndPort;
_httpClient = httpClient; _httpClient = httpClient;
_jsonSerializerSettings = new JsonSerializerSettings() { _jsonSerializerSettings = new JsonSerializerSettings() {
@ -68,6 +68,7 @@ namespace Ocelot.Raft
{ {
SetToken(); SetToken();
} }
var json = JsonConvert.SerializeObject(appendEntries, _jsonSerializerSettings); var json = JsonConvert.SerializeObject(appendEntries, _jsonSerializerSettings);
var content = new StringContent(json); var content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/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) if(_token == null)
{ {
SetToken(); SetToken();
} }
var json = JsonConvert.SerializeObject(command, _jsonSerializerSettings); var json = JsonConvert.SerializeObject(command, _jsonSerializerSettings);
var content = new StringContent(json); var content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/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 //todo - handle an error
//hack it to just cast as at the moment we know this is the only command :P //hack it to just cast as at the moment we know this is the only command :P
var hack = (UpdateFileConfiguration)log.CommandData; 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); FileStream fs = File.Create(_path);
fs.Dispose(); fs.Dispose();
} }
using(var connection = new SqliteConnection($"Data Source={_path};")) using(var connection = new SqliteConnection($"Data Source={_path};"))
{ {
connection.Open(); connection.Open();
@ -59,6 +60,7 @@ namespace Ocelot.Raft
} }
} }
} }
return result; return result;
} }
} }
@ -88,6 +90,7 @@ namespace Ocelot.Raft
} }
} }
} }
return result; return result;
} }
} }
@ -113,6 +116,7 @@ namespace Ocelot.Raft
} }
} }
} }
return result; return result;
} }
} }
@ -129,6 +133,7 @@ namespace Ocelot.Raft
TypeNameHandling = TypeNameHandling.All TypeNameHandling = TypeNameHandling.All
}; };
var data = JsonConvert.SerializeObject(log, jsonSerializerSettings); var data = JsonConvert.SerializeObject(log, jsonSerializerSettings);
//todo - sql injection dont copy this.. //todo - sql injection dont copy this..
var sql = $"insert into logs (data) values ('{data}')"; var sql = $"insert into logs (data) values ('{data}')";
using(var command = new SqliteCommand(sql, connection)) using(var command = new SqliteCommand(sql, connection))
@ -153,6 +158,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};")) using(var connection = new SqliteConnection($"Data Source={_path};"))
{ {
connection.Open(); connection.Open();
//todo - sql injection dont copy this.. //todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index};"; var sql = $"select data from logs where id = {index};";
using(var command = new SqliteCommand(sql, connection)) using(var command = new SqliteCommand(sql, connection))
@ -183,6 +189,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};")) using(var connection = new SqliteConnection($"Data Source={_path};"))
{ {
connection.Open(); connection.Open();
//todo - sql injection dont copy this.. //todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index}"; var sql = $"select data from logs where id = {index}";
using(var command = new SqliteCommand(sql, connection)) using(var command = new SqliteCommand(sql, connection))
@ -207,6 +214,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};")) using(var connection = new SqliteConnection($"Data Source={_path};"))
{ {
connection.Open(); connection.Open();
//todo - sql injection dont copy this.. //todo - sql injection dont copy this..
var sql = $"select id, data from logs where id >= {index}"; var sql = $"select id, data from logs where id >= {index}";
using(var command = new SqliteCommand(sql, connection)) using(var command = new SqliteCommand(sql, connection))
@ -222,7 +230,6 @@ namespace Ocelot.Raft
}; };
var log = JsonConvert.DeserializeObject<LogEntry>(data, jsonSerializerSettings); var log = JsonConvert.DeserializeObject<LogEntry>(data, jsonSerializerSettings);
logsToReturn.Add((id, log)); logsToReturn.Add((id, log));
} }
} }
} }
@ -230,7 +237,6 @@ namespace Ocelot.Raft
return logsToReturn; return logsToReturn;
} }
} }
public long GetTermAtIndex(int index) public long GetTermAtIndex(int index)
@ -241,6 +247,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};")) using(var connection = new SqliteConnection($"Data Source={_path};"))
{ {
connection.Open(); connection.Open();
//todo - sql injection dont copy this.. //todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index}"; var sql = $"select data from logs where id = {index}";
using(var command = new SqliteCommand(sql, connection)) using(var command = new SqliteCommand(sql, connection))
@ -256,9 +263,11 @@ namespace Ocelot.Raft
} }
} }
} }
return result; return result;
} }
} }
public void Remove(int indexOfCommand) public void Remove(int indexOfCommand)
{ {
lock(_lock) lock(_lock)
@ -266,6 +275,7 @@ namespace Ocelot.Raft
using(var connection = new SqliteConnection($"Data Source={_path};")) using(var connection = new SqliteConnection($"Data Source={_path};"))
{ {
connection.Open(); connection.Open();
//todo - sql injection dont copy this.. //todo - sql injection dont copy this..
var deleteSql = $"delete from logs where id >= {indexOfCommand};"; var deleteSql = $"delete from logs where id >= {indexOfCommand};";
using(var deleteCommand = new SqliteCommand(deleteSql, connection)) using(var deleteCommand = new SqliteCommand(deleteSql, connection))

View File

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

View File

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

View File

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

View File

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

View File

@ -55,7 +55,6 @@ namespace Ocelot.Requester
{ {
_cacheHandlers.Set(cacheKey, httpClient, TimeSpan.FromHours(24)); _cacheHandlers.Set(cacheKey, httpClient, TimeSpan.FromHours(24));
} }
} }
private IHttpClient GetHttpClient(string cacheKey, IHttpClientBuilder builder, DownstreamContext request) 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); connectionQueue.TryDequeue(out client);
} }
return client; return client;
} }

View File

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

View File

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

View File

@ -29,7 +29,6 @@ namespace Ocelot.Responder.Middleware
_responder = responder; _responder = responder;
_codeMapper = codeMapper; _codeMapper = codeMapper;
_logger = loggerFactory.CreateLogger<ResponderMiddleware>(); _logger = loggerFactory.CreateLogger<ResponderMiddleware>();
} }
public async Task Invoke(DownstreamContext context) 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(Error error) : base(new List<Error>{error})
{ {
} }
public ErrorResponse(List<Error> errors) : base(errors) public ErrorResponse(List<Error> errors) : base(errors)
{ {
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -177,7 +177,7 @@ namespace Ocelot.AcceptanceTests
AuthenticationOptions = new FileAuthenticationOptions AuthenticationOptions = new FileAuthenticationOptions
{ {
AuthenticationProviderKey = "Test", 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 AuthenticationOptions = new FileAuthenticationOptions
{ {
AuthenticationProviderKey = "Test", 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" "CustomerId", "LocationId", "UserType", "UserId"
} }
}, },
}) })
.AddInMemoryClients(new List<Client> .AddInMemoryClients(new List<Client>
{ {
@ -437,7 +436,6 @@ namespace Ocelot.AcceptanceTests
"CustomerId", "LocationId", "UserType", "UserId", "Role" "CustomerId", "LocationId", "UserType", "UserId", "Role"
} }
}, },
}) })
.AddInMemoryClients(new List<Client> .AddInMemoryClients(new List<Client>
{ {
@ -450,7 +448,6 @@ namespace Ocelot.AcceptanceTests
AccessTokenType = tokenType, AccessTokenType = tokenType,
Enabled = true, Enabled = true,
RequireClientSecret = false, RequireClientSecret = false,
} }
}) })
.AddTestUsers(users); .AddTestUsers(users);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -25,7 +25,7 @@ namespace Ocelot.AcceptanceTests
public CustomMiddlewareTests() public CustomMiddlewareTests()
{ {
_counter = 0; _counter = 0;
_steps = new Steps();; _steps = new Steps();
_configurationPath = "configuration.json"; _configurationPath = "configuration.json";
} }
@ -287,7 +287,6 @@ namespace Ocelot.AcceptanceTests
.BDDfy(); .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!")] [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() public void should_fix_issue_237()
{ {
@ -352,14 +351,13 @@ namespace Ocelot.AcceptanceTests
app.UsePathBase(basePath); app.UsePathBase(basePath);
app.Run(context => app.Run(context =>
{ {
if(string.IsNullOrEmpty(basePath)) if(string.IsNullOrEmpty(basePath))
{ {
context.Response.StatusCode = statusCode; context.Response.StatusCode = statusCode;
} }
else if(context.Request.Path.Value != basePath) else if(context.Request.Path.Value != basePath)
{ {
context.Response.StatusCode = 404;; context.Response.StatusCode = 404;
} }
return Task.CompletedTask; return Task.CompletedTask;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -110,7 +110,6 @@ namespace Ocelot.UnitTests.Cache
private void GivenThereAreNoErrors() private void GivenThereAreNoErrors()
{ {
_downstreamContext.Errors = new List<Error>(); _downstreamContext.Errors = new List<Error>();
} }
private void ThenTheCacheGetIsCalledCorrectly() private void ThenTheCacheGetIsCalledCorrectly()

View File

@ -93,7 +93,6 @@ namespace Ocelot.UnitTests.Claims
.BDDfy(); .BDDfy();
} }
private void GivenClaimsToThings(List<ClaimToThing> configuration) private void GivenClaimsToThings(List<ClaimToThing> configuration)
{ {
_claimsToThings = configuration; _claimsToThings = configuration;
@ -129,7 +128,6 @@ namespace Ocelot.UnitTests.Claims
private void ThenTheResultIsError() private void ThenTheResultIsError()
{ {
_result.IsError.ShouldBe(true); _result.IsError.ShouldBe(true);
} }

View File

@ -15,12 +15,10 @@ namespace Ocelot.UnitTests.Claims
using Ocelot.Responses; using Ocelot.Responses;
using TestStack.BDDfy; using TestStack.BDDfy;
using Xunit; using Xunit;
using Ocelot.DownstreamRouteFinder.Middleware;
public class ClaimsBuilderMiddlewareTests public class ClaimsBuilderMiddlewareTests
{ {
private readonly Mock<IAddClaimsToRequest> _addHeaders; private readonly Mock<IAddClaimsToRequest> _addHeaders;
private Response<DownstreamRoute> _downstreamRoute;
private Mock<IOcelotLoggerFactory> _loggerFactory; private Mock<IOcelotLoggerFactory> _loggerFactory;
private Mock<IOcelotLogger> _logger; private Mock<IOcelotLogger> _logger;
private readonly ClaimsBuilderMiddleware _middleware; private readonly ClaimsBuilderMiddleware _middleware;
@ -68,7 +66,6 @@ namespace Ocelot.UnitTests.Claims
_middleware.Invoke(_downstreamContext).GetAwaiter().GetResult(); _middleware.Invoke(_downstreamContext).GetAwaiter().GetResult();
} }
private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute)
{ {
_downstreamContext.TemplatePlaceholderNameAndValues = downstreamRoute.TemplatePlaceholderNameAndValues; _downstreamContext.TemplatePlaceholderNameAndValues = downstreamRoute.TemplatePlaceholderNameAndValues;

View File

@ -79,6 +79,7 @@ namespace Ocelot.UnitTests.Configuration
{ {
_result.Count.ShouldBeGreaterThan(0); _result.Count.ShouldBeGreaterThan(0);
} }
private void GivenTheFollowingDictionary(Dictionary<string,string> claimsToThings) private void GivenTheFollowingDictionary(Dictionary<string,string> claimsToThings)
{ {
_claimsToThings = claimsToThings; _claimsToThings = claimsToThings;

View File

@ -588,7 +588,8 @@ namespace Ocelot.UnitTests.Configuration
AuthenticationOptions = new FileAuthenticationOptions() AuthenticationOptions = new FileAuthenticationOptions()
{ {
AuthenticationProviderKey = "Test" AuthenticationProviderKey = "Test"
} } }
}
} }
})) }))
.When(x => x.WhenIValidateTheConfiguration()) .When(x => x.WhenIValidateTheConfiguration())
@ -869,7 +870,6 @@ namespace Ocelot.UnitTests.Configuration
.BDDfy(); .BDDfy();
} }
[Theory] [Theory]
[InlineData(null)] [InlineData(null)]
[InlineData("")] [InlineData("")]
@ -981,7 +981,8 @@ namespace Ocelot.UnitTests.Configuration
.And(x => x.ThenTheErrorMessageAtPositionIs(0, "When not using service discovery DownstreamHostAndPorts must be set and not empty or Ocelot cannot find your service!")) .And(x => x.ThenTheErrorMessageAtPositionIs(0, "When not using service discovery DownstreamHostAndPorts must be set and not empty or Ocelot cannot find your service!"))
.BDDfy(); .BDDfy();
} }
[Fact]
[Fact]
public void configuration_is_not_valid_when_host_and_port_is_empty() public void configuration_is_not_valid_when_host_and_port_is_empty()
{ {
this.Given(x => x.GivenAConfiguration(new FileConfiguration this.Given(x => x.GivenAConfiguration(new FileConfiguration
@ -1007,7 +1008,6 @@ namespace Ocelot.UnitTests.Configuration
.BDDfy(); .BDDfy();
} }
private void GivenAConfiguration(FileConfiguration fileConfiguration) private void GivenAConfiguration(FileConfiguration fileConfiguration)
{ {
_fileConfiguration = fileConfiguration; _fileConfiguration = fileConfiguration;

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