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

Add Azure Functions support #966

Merged
merged 18 commits into from
Dec 9, 2022
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
14 changes: 14 additions & 0 deletions GraphQL.Server.sln
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{7F5D
samples\Directory.Build.props = samples\Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Samples.AzureFunctions", "samples\Samples.AzureFunctions\Samples.AzureFunctions.csproj", "{FD93A9D8-4663-4FF0-8082-DE9E006956FD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Samples.AzureFunctions.Tests", "tests\Samples.AzureFunctions.Tests\Samples.AzureFunctions.Tests.csproj", "{A204E359-05E8-4CEE-891C-4CCA6570FA52}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -250,6 +254,14 @@ Global
{2B5A39E8-098F-458E-981C-BC9470CB94B0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2B5A39E8-098F-458E-981C-BC9470CB94B0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2B5A39E8-098F-458E-981C-BC9470CB94B0}.Release|Any CPU.Build.0 = Release|Any CPU
{FD93A9D8-4663-4FF0-8082-DE9E006956FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FD93A9D8-4663-4FF0-8082-DE9E006956FD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FD93A9D8-4663-4FF0-8082-DE9E006956FD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FD93A9D8-4663-4FF0-8082-DE9E006956FD}.Release|Any CPU.Build.0 = Release|Any CPU
{A204E359-05E8-4CEE-891C-4CCA6570FA52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A204E359-05E8-4CEE-891C-4CCA6570FA52}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A204E359-05E8-4CEE-891C-4CCA6570FA52}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A204E359-05E8-4CEE-891C-4CCA6570FA52}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -287,6 +299,8 @@ Global
{5A16B117-0FAD-4F91-A97C-E72B733B4E57} = {5C07AFA3-12F2-40EA-807D-7A1EEF29012B}
{2B5A39E8-098F-458E-981C-BC9470CB94B0} = {BBD07745-C962-4D2D-B302-6DA1BCC2FF43}
{7F5D8EE4-CD03-482E-A478-E3334F1D0439} = {382C5C04-A34D-4C81-83D7-584C85FB9356}
{FD93A9D8-4663-4FF0-8082-DE9E006956FD} = {5C07AFA3-12F2-40EA-807D-7A1EEF29012B}
{A204E359-05E8-4CEE-891C-4CCA6570FA52} = {BBD07745-C962-4D2D-B302-6DA1BCC2FF43}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3FC7FA59-E938-453C-8C4A-9D5635A9489A}
Expand Down
51 changes: 51 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,57 @@ public class HomeController : Controller
}
```

### Configuration with Azure Functions

This project also supports hosting GraphQL endpoints within Azure Functions.
You will need to complete the following steps:

1. Configure the Azure Function to use Dependency Injection:
See https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection
for details.

2. Configure GraphQL via `builder.Services.AddGraphQL()` the same as you would in a typical
ASP.NET Core application.

3. Add a call to `.AddAzureFunctionsMiddleware()` within the `AddGraphQL` call.

4. Add an HTTP function that returns an appropriate `ActionResult`:

```csharp
[FunctionName("GraphQL")]
public static IActionResult RunGraphQL(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post"] HttpRequest req)
{
return new AzureGraphQLActionResult(req);
}
```

5. Optionally, add a UI package to the project and configure it:

```csharp
[FunctionName("Playground")]
public static IActionResult RunGraphQL(
[HttpTrigger(AuthorizationLevel.Anonymous, "get"] HttpRequest req)
{
return new PlaygroundActionResult(opts => opts.GraphQLEndPoint = "/api/graphql");
}
```

Middleware can be configured by passing a configuration delegate to `.AddAzureFunctionsMiddleware()`.
Multiple schemas are supported by the use of `AddAzureFunctionsMiddleware<TSchema>()`
and `AzureGraphQLActionResult<TSchema>`. However, there is no way to configure multiple
endpoints for the same schema to have different configurations. It is also not possible to
configure subscription support, as Azure Functions do not support WebSockets since it is
a serverless environment.

See the `Samples.AzureFunctions` project for a complete sample based on the
.NET template for Azure Functions.

Please note that the GraphQL schema needs to be initialized for every call through
Azure Functions, since it is a serverless environment. This is done automatically
but will come at a performance cost. If you are using a schema that is expensive
to initialize, you may want to consider using a different hosting environment.
Comment on lines +245 to +248
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspected that the schema should be created every time so your note about overhead here

We could eliminate the need to register the middleware in DI, similar to how the UI action results work, but then there is a bit of startup overhead for each request. Not sure if this occurs anyway for azure functions or not, or which would be a better approach.

will not affect the overall costs.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking the same thing. I think we will find that the alternative approach for Azure Functions is better overall.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's possible that if multiple calls are made in succession maybe then the schema would not need to be reinitialized.

But regardless, I looked at GraphQLHttpMiddleware and it seems that we can make some private readonly fields static anyway. At which point, initializing one class should have little effect on speed/memory.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will have any effect only if Azure Function environment does not unload entirely the whole app (dll/domain/process/whatever) from memory.


### User context configuration

To set the user context to be used during the execution of GraphQL requests,
Expand Down
32 changes: 32 additions & 0 deletions samples/Samples.AzureFunctions/GraphQL.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using GraphQL.Server.Transports.AspNetCore.AzureFunctions;
using GraphQL.Server.Ui.Playground;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;

namespace Samples.AzureFunctions;

public class GraphQL
{
[FunctionName("GraphQL")]
public static IActionResult RunGraphQL(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest request,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a GraphQL request.");

return new AzureGraphQLActionResult(request);
}

[FunctionName("Playground")]
public static IActionResult RunPlayground(
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest request,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request for the GraphQL Playground UI.");

return new PlaygroundActionResult(opts => opts.GraphQLEndPoint = "/api/graphql"); // /api/graphql route will call RunGraphQL method
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"dependencies": {
"appInsights1": {
"type": "appInsights"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"dependencies": {
"appInsights1": {
"type": "appInsights.sdk"
}
}
}
23 changes: 23 additions & 0 deletions samples/Samples.AzureFunctions/Samples.AzureFunctions.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<NoWarn>$(NoWarn);IDE0060</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Transports.AspNetCore\Transports.AspNetCore.csproj" />
<ProjectReference Include="..\..\src\Ui.GraphiQL\Ui.GraphiQL.csproj" />
<ProjectReference Include="..\..\src\Ui.Playground\Ui.Playground.csproj" />
<ProjectReference Include="..\Samples.Schemas.Chat\Samples.Schemas.Chat.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
22 changes: 22 additions & 0 deletions samples/Samples.AzureFunctions/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using GraphQL;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Chat = GraphQL.Samples.Schemas.Chat;

[assembly: FunctionsStartup(typeof(Samples.AzureFunctions.Startup))]
namespace Samples.AzureFunctions;

public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSingleton<Chat.IChat, Chat.Chat>();

builder.Services.AddGraphQL(b => b
.AddAutoSchema<Chat.Query>(s => s
.WithMutation<Chat.Mutation>()
.WithSubscription<Chat.Subscription>())
.AddSystemTextJson()
.AddAzureFunctionsMiddleware());
}
}
11 changes: 11 additions & 0 deletions samples/Samples.AzureFunctions/host.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
}
}
3 changes: 2 additions & 1 deletion samples/Samples.Controller/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using GraphQL;
using GraphQL.Server.Transports.AspNetCore;
using GraphQL.Server.Ui.GraphiQL;
using GraphQL.Transport;
using GraphQL.Types;
using GraphQL.Validation;
Expand All @@ -21,7 +22,7 @@ public HomeController(IDocumentExecuter<ISchema> executer, IGraphQLTextSerialize
}

public IActionResult Index()
=> View();
=> new GraphiQLActionResult(opts => opts.GraphQLEndPoint = "/Home/graphql");

[HttpGet]
[ActionName("graphql")]
Expand Down
1 change: 1 addition & 0 deletions samples/Samples.Controller/Samples.Controller.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

<ItemGroup>
<ProjectReference Include="..\..\src\Transports.AspNetCore\Transports.AspNetCore.csproj" />
<ProjectReference Include="..\..\src\Ui.GraphiQL\Ui.GraphiQL.csproj" />
<ProjectReference Include="..\Samples.Schemas.Chat\Samples.Schemas.Chat.csproj" />
</ItemGroup>

Expand Down
Loading