Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storing request query information on HttpContext #72

Merged
merged 1 commit into from
Jan 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions src/Microsoft.AspNetCore.OData/Microsoft.AspNetCore.OData.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7271,18 +7271,6 @@
Gets or sets the maximum number of expressions that can be present in the $orderby.
</summary>
</member>
<member name="F:Microsoft.AspNetCore.OData.Query.EnableQueryAttribute._queryValidationRunBeforeActionExecution">
<summary>
Marks if the query validation was run before the action execution. This is not always possible.
For cases where the run failed before action execution. We will run validation on result.
</summary>
</member>
<member name="F:Microsoft.AspNetCore.OData.Query.EnableQueryAttribute._processedQueryOptions">
<summary>
Stores the processed query options to be used later if OnActionExecuting was able to verify the query.
This is because ValidateQuery internally modifies query options (expands are prime example of this).
</summary>
</member>
<member name="M:Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext)">
<summary>
Performs the query composition before action is executing.
Expand Down Expand Up @@ -7449,6 +7437,29 @@
<param name="actionDescriptor">The action descriptor for the action being queried on.</param>
<returns>The EDM model for the given type and request.</returns>
</member>
<member name="T:Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.RequestQueryData">
<summary>
Holds request level query information.
</summary>
</member>
<member name="P:Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.RequestQueryData.QueryValidationRunBeforeActionExecution">
<summary>
Gets or sets a value indicating whether query validation was run before action (controller method) is executed.
</summary>
<remarks>
Marks if the query validation was run before the action execution. This is not always possible.
For cases where the run failed before action execution. We will run validation on result.
</remarks>
</member>
<member name="P:Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.RequestQueryData.ProcessedQueryOptions">
<summary>
Gets or sets the processed query options.
</summary>
<remarks>
Stores the processed query options to be used later if OnActionExecuting was able to verify the query.
This is because ValidateQuery internally modifies query options (expands are prime example of this).
</remarks>
</member>
<member name="T:Microsoft.AspNetCore.OData.Query.ETag">
<summary>
The ETag parsed from request.
Expand Down
61 changes: 38 additions & 23 deletions src/Microsoft.AspNetCore.OData/Query/EnableQueryAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,6 @@ namespace Microsoft.AspNetCore.OData.Query
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public partial class EnableQueryAttribute : ActionFilterAttribute
{
/// <summary>
/// Marks if the query validation was run before the action execution. This is not always possible.
/// For cases where the run failed before action execution. We will run validation on result.
/// </summary>
private bool _queryValidationRunBeforeActionExecution;

/// <summary>
/// Stores the processed query options to be used later if OnActionExecuting was able to verify the query.
/// This is because ValidateQuery internally modifies query options (expands are prime example of this).
/// </summary>
private ODataQueryOptions _processedQueryOptions;

/// <summary>
/// Performs the query composition before action is executing.
/// </summary>
Expand All @@ -62,6 +50,13 @@ public override void OnActionExecuting(ActionExecutingContext actionExecutingCon

base.OnActionExecuting(actionExecutingContext);

RequestQueryData requestQueryData = new RequestQueryData()
{
QueryValidationRunBeforeActionExecution = false,
};

actionExecutingContext.HttpContext.Items.Add(nameof(RequestQueryData), requestQueryData);

HttpRequest request = actionExecutingContext.HttpContext.Request;
ODataPath path = request.ODataFeature().Path;

Expand All @@ -86,7 +81,6 @@ public override void OnActionExecuting(ActionExecutingContext actionExecutingCon
// For Swagger metadata request. elementType is null.
if (elementType == null || edmModel == null)
{
_queryValidationRunBeforeActionExecution = false;
return;
}

Expand All @@ -104,11 +98,8 @@ public override void OnActionExecuting(ActionExecutingContext actionExecutingCon
// In case where CLRType is missing, $count, $expand verifications cannot be done.
// More importantly $expand required ODataQueryContext with clrType which cannot be done
// If the model is untyped. Hence for such cases, letting the validation run post action.
_queryValidationRunBeforeActionExecution = false;
return;
}

_queryValidationRunBeforeActionExecution = true;
}
else
{
Expand All @@ -121,7 +112,6 @@ public override void OnActionExecuting(ActionExecutingContext actionExecutingCon

if (controllerActionDescriptor == null)
{
_queryValidationRunBeforeActionExecution = false;
return;
}

Expand Down Expand Up @@ -150,7 +140,6 @@ public override void OnActionExecuting(ActionExecutingContext actionExecutingCon
}
else
{
_queryValidationRunBeforeActionExecution = false;
return;
}

Expand All @@ -162,15 +151,15 @@ public override void OnActionExecuting(ActionExecutingContext actionExecutingCon
queryContext = new ODataQueryContext(
edmModel,
elementType);
_queryValidationRunBeforeActionExecution = true;
}

// Create and validate the query options.
_processedQueryOptions = new ODataQueryOptions(queryContext, request);
requestQueryData.QueryValidationRunBeforeActionExecution = true;
requestQueryData.ProcessedQueryOptions = new ODataQueryOptions(queryContext, request);

try
{
ValidateQuery(request, _processedQueryOptions);
ValidateQuery(request, requestQueryData.ProcessedQueryOptions);
}
catch (ArgumentOutOfRangeException e)
{
Expand Down Expand Up @@ -547,9 +536,11 @@ public virtual object ApplyQuery(object entity, ODataQueryOptions queryOptions)
/// <returns></returns>
private ODataQueryOptions CreateAndValidateQueryOptions(HttpRequest request, ODataQueryContext queryContext)
{
if (_queryValidationRunBeforeActionExecution)
RequestQueryData requestQueryData = request.HttpContext.Items[nameof(RequestQueryData)] as RequestQueryData;

if (requestQueryData.QueryValidationRunBeforeActionExecution)
{
return _processedQueryOptions;
return requestQueryData.ProcessedQueryOptions;
}

ODataQueryOptions queryOptions = new ODataQueryOptions(queryContext, request);
Expand Down Expand Up @@ -824,5 +815,29 @@ public virtual void ValidateQuery(HttpRequest request, ODataQueryOptions queryOp
Contract.Assert(model != null);
return model;
}

/// <summary>
/// Holds request level query information.
/// </summary>
private class RequestQueryData
{
/// <summary>
/// Gets or sets a value indicating whether query validation was run before action (controller method) is executed.
/// </summary>
/// <remarks>
/// Marks if the query validation was run before the action execution. This is not always possible.
/// For cases where the run failed before action execution. We will run validation on result.
/// </remarks>
public bool QueryValidationRunBeforeActionExecution { get; set; }

/// <summary>
/// Gets or sets the processed query options.
/// </summary>
/// <remarks>
/// Stores the processed query options to be used later if OnActionExecuting was able to verify the query.
/// This is because ValidateQuery internally modifies query options (expands are prime example of this).
/// </remarks>
public ODataQueryOptions ProcessedQueryOptions { get; set; }
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,5 @@
<ProjectReference Include="..\..\src\Microsoft.AspNetCore.OData\Microsoft.AspNetCore.OData.csproj" />
<ProjectReference Include="..\Microsoft.AspNetCore.OData.TestCommon\Microsoft.AspNetCore.OData.TestCommon.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="Query\" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;

namespace Microsoft.AspNetCore.OData.E2E.Tests.Query.ConcurrentQuery
{
public class CustomersController : ControllerBase
{
[HttpGet]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Count | AllowedQueryOptions.Filter)]
public IQueryable<Customer> GetCustomers()
{
return Enumerable.Range(1, 100)
.Select(i => new Customer
{
Id = i,
}).AsQueryable();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;

namespace Microsoft.AspNetCore.OData.E2E.Tests.Query.ConcurrentQuery
{
public class ConcurrentQueryEdmModel
{
public static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
return builder.GetEdmModel();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace Microsoft.AspNetCore.OData.E2E.Tests.Query.ConcurrentQuery
{
public class Customer
{
public int Id { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.OData.TestCommon;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OData.Edm;
using Newtonsoft.Json.Linq;
using Xunit;

namespace Microsoft.AspNetCore.OData.E2E.Tests.Query.ConcurrentQuery
{
/// <summary>
/// EnableQuery attribute works correctly when controller returns ActionResult.
/// </summary>
public class ConcurrentQueryTests : WebODataTestBase<ConcurrentQueryTests.Startup>
{
/// <summary>
/// Startup class.
/// </summary>
public class Startup : TestStartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.ConfigureControllers(typeof(CustomersController));

IEdmModel model = ConcurrentQueryEdmModel.GetEdmModel();
services.AddOData(options => options.AddModel("odata", model).SetMaxTop(2).Expand().Select().OrderBy().Filter());
}
}

public ConcurrentQueryTests(WebODataTestFixture<Startup> fixture)
: base(fixture)
{
}

/// <summary>
/// For OData paths enable query should work with expansion.
/// </summary>
/// <returns>Task tracking operation.</returns>
////[Fact] - Commented out as running this test right now throws 'Concurrent reads or writes are not supported' exception
public async Task ConcurrentQueryExecutionIsThreadSafe()
{
// Arrange
// Bumping thread count to allow higher parallelization.
ThreadPool.SetMinThreads(100, 100);

// Act
var results = await Task.WhenAll(
Enumerable.Range(1, 100)
.Select(async i =>
{
string queryUrl = string.Format("odata/Customers?$filter=Id gt {0}", i);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata.metadata=none"));

HttpResponseMessage response = await this.Client.SendAsync(request);

Assert.Equal(HttpStatusCode.OK, response.StatusCode);

List<Customer> customers = JToken.Parse(await response.Content.ReadAsStringAsync())["value"].ToObject<List<Customer>>();

return (i: i, length: customers.Count);
}));

// Assert
foreach (var result in results)
{
Assert.Equal(100 - result.i, result.length);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;

namespace Microsoft.AspNetCore.OData.E2E.Tests.Query.QueryValidationBeforeAction
{
public class CustomersController : ControllerBase
{
[HttpGet]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Top, MaxTop = 10)]
public IEnumerable<Customer> GetCustomers()
{
throw new Exception("Controller should never be invoked as query validation should fail");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;

namespace Microsoft.AspNetCore.OData.E2E.Tests.Query.QueryValidationBeforeAction
{
public class QueryValidationBeforeActionEdmModel
{
public static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
return builder.GetEdmModel();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Collections.Generic;

namespace Microsoft.AspNetCore.OData.E2E.Tests.Query.QueryValidationBeforeAction
{
public class Customer
{
public string Id { get; set; }

public IEnumerable<Book> Books { get; set; }
}

public class Book
{
public string Id { get; set; }
}
}
Loading