Skip to content

Add NetCord.Hosting.AzureFunctions to support serverless bots via azu… #101

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

Open
wants to merge 1 commit into
base: alpha
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -364,4 +364,6 @@ FodyWeavers.xsd

# Settings file
appsettings.json
!Documentation/**/appsettings.json
!Documentation/**/appsettings.json
host.json
local.settings.json
149 changes: 149 additions & 0 deletions Hosting/NetCord.Hosting.AzureFunctions/DiscordInteractionsHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
using System.Buffers;
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Options;
using NetCord.Rest;
using Microsoft.Extensions.DependencyInjection;
namespace NetCord.Hosting.AzureFunctions;

public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the <see cref="DiscordInteractionsHandler"/> to the service collection.
/// </summary>
public static IServiceCollection AddDiscordInteractions(this IServiceCollection services)
{
services.AddSingleton<DiscordInteractionsHandler>();
return services;
}
}

public class DiscordInteractionsHandler
{
private readonly IHttpInteractionHandler[] _handlers;
private readonly ValueTask[] _tasks;
private readonly HttpInteractionValidator _validator;
private readonly RestClient _client;

public DiscordInteractionsHandler(
IOptions<IDiscordOptions> options,
IEnumerable<IHttpInteractionHandler> handlers,
RestClient client)
{
var publicKey = options.Value.PublicKey ?? throw new InvalidOperationException("PublicKey must be set in IDiscordOptions.");
_validator = new HttpInteractionValidator(publicKey);
_handlers = handlers.ToArray();
_tasks = new ValueTask[_handlers.Length];
_client = client;
}

/// <summary>
/// Handles the Discord interaction request.
/// </summary>
/// <param name="req">The HTTP request data.</param>
/// <param name="context">The function context.</param>
/// <returns>The result of the interaction.</returns>
public async Task<HttpResponseData> HandleRequestAsync(HttpRequestData req, FunctionContext context)
{
var httpContext = context.GetHttpContext();
if (httpContext == null)
{
var res = req.CreateResponse(HttpStatusCode.InternalServerError);
await res.WriteStringAsync("HttpContext not available.").ConfigureAwait(false);
return res;
}

var interaction = await ParseInteractionAsync(httpContext, _validator, _client).ConfigureAwait(false);
if (interaction == null)
{
var res = req.CreateResponse(HttpStatusCode.Unauthorized);
return res;
}

HttpResponseData response = req.CreateResponse(HttpStatusCode.OK);

switch (interaction)
{
case Interaction realInteraction:
await HandleInteractionAsync(realInteraction, _handlers, _tasks).ConfigureAwait(false);
break;

case PingInteraction ping:
await ping.SendResponseAsync(InteractionCallback.Pong).ConfigureAwait(false);
break;

default:
response.StatusCode = HttpStatusCode.Unauthorized;
break;
}

return response;
}

private static async ValueTask<IInteraction?> ParseInteractionAsync(HttpContext context, HttpInteractionValidator validator, RestClient client)
{
var request = context.Request;

var headers = request.Headers;
if (!headers.TryGetValue("X-Signature-Ed25519", out var signatures) || !headers.TryGetValue("X-Signature-Timestamp", out var timestamps))
{
return null;
}

var timestamp = timestamps[0]!;
int timestampByteCount = Encoding.UTF8.GetByteCount(timestamp);

int timestampAndBodyLength = timestampByteCount + (int)request.ContentLength.GetValueOrDefault();

var timestampAndBodyArray = ArrayPool<byte>.Shared.Rent(timestampAndBodyLength);
var timestampAndBody = timestampAndBodyArray.AsMemory(0, timestampAndBodyLength);

Encoding.UTF8.GetBytes(timestamp, timestampAndBody.Span);

int position = timestampByteCount;
var body = request.Body;
while (position < timestampAndBodyLength)
{
position += await body.ReadAsync(timestampAndBody[position..]).ConfigureAwait(false);
}

if (!validator.Validate(signatures[0], timestampAndBody.Span))
{
return null;
}

var response = context.Response;
var interaction = HttpInteractionFactory.Create(timestampAndBody.Span[timestampByteCount..], async (interaction, interactionCallback, properties, cancellationToken) =>
{
using var content = interactionCallback.Serialize();
response.ContentType = content.Headers.ContentType!.ToString();
await content.CopyToAsync(response.Body, cancellationToken).ConfigureAwait(false);
await response.CompleteAsync().ConfigureAwait(false);
}, client);

ArrayPool<byte>.Shared.Return(timestampAndBodyArray);

return interaction;
}

private static async ValueTask HandleInteractionAsync(Interaction interaction, IHttpInteractionHandler[] handlers, ValueTask[] tasks)
{
int length = handlers.Length;

for (int i = 0; i < length; i++)
#pragma warning disable CA2012
{
tasks[i] = handlers[i].HandleAsync(interaction);
}
#pragma warning restore CA2012

for (int i = 0; i < length; i++)
{
await tasks[i].ConfigureAwait(false);
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<IsAotCompatible>true</IsAotCompatible>

<RepositoryUrl>https://github.com/NetCordDev/NetCord</RepositoryUrl>
<PackageProjectUrl>https://netcord.dev</PackageProjectUrl>
<PackageTags>bot;discord;discord-api</PackageTags>
<PackageIcon>SmallSquare.png</PackageIcon>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Version>$(VersionPrefix)</Version>
<VersionSuffix>alpha.363</VersionSuffix>
<Description>The modern and fully customizable C# Discord library.</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<ItemGroup>
<None Include="..\..\Resources\NuGet\README.md" Pack="true" PackagePath="" />
<None Include="..\..\Resources\Logo\png\SmallSquare.png" Pack="true" PackagePath="" />
</ItemGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore"
Version="2.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\NetCord.Hosting\NetCord.Hosting.csproj" />
</ItemGroup>
</Project>
2 changes: 2 additions & 0 deletions NetCord.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
</Folder>
<Folder Name="/Hosting/">
<Project Path="Hosting/NetCord.Hosting.AspNetCore/NetCord.Hosting.AspNetCore.csproj" />
<Project Path="Hosting/NetCord.Hosting.AzureFunctions/NetCord.Hosting.AzureFunctions.csproj" />
<Project Path="Hosting/NetCord.Hosting.Services/NetCord.Hosting.Services.csproj" />
<Project Path="Hosting/NetCord.Hosting/NetCord.Hosting.csproj" />
</Folder>
Expand All @@ -71,6 +72,7 @@
<Project Path="Tests/ColorTest/ColorTest.csproj" />
<Project Path="Tests/MentionTest/MentionTest.csproj" />
<Project Path="Tests/NetCord.Test.Hosting.AspNetCore/NetCord.Test.Hosting.AspNetCore.csproj" />
<Project Path="Tests/NetCord.Test.Hosting.AzureFunctions/NetCord.Test.Hosting.AzureFunctions.csproj" />
<Project Path="Tests/NetCord.Test.Hosting/NetCord.Test.Hosting.csproj" />
<Project Path="Tests/NetCord.Test.Sharded.Hosting/NetCord.Test.Sharded.Hosting.csproj" />
<Project Path="Tests/NetCord.Test.Sharded/NetCord.Test.Sharded.csproj" />
Expand Down
16 changes: 16 additions & 0 deletions Tests/NetCord.Test.Hosting.AzureFunctions/Interactions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;

using NetCord.Hosting.AzureFunctions;

namespace NetCord.Test.Hosting.AzureFunctions;

public class Interactions(DiscordInteractionsHandler handler)
{
[Function("interactions")]
public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, FunctionContext context)
{
var res = await handler.HandleRequestAsync(req, context).ConfigureAwait(false);
return res;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference
Include="..\..\Hosting\NetCord.Hosting.AzureFunctions\NetCord.Hosting.AzureFunctions.csproj" />
<ProjectReference
Include="..\..\Hosting\NetCord.Hosting.Services\NetCord.Hosting.Services.csproj" />
<ProjectReference Include="..\..\Hosting\NetCord.Hosting\NetCord.Hosting.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="libsodium" Version="1.0.20" />

<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.2.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.0.0" />
</ItemGroup>

<ItemGroup>
<None Update="host.json" Condition="Exists('host.json')">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

<None Update="local.settings.json" Condition="Exists('local.settings.json')">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

<ItemGroup>
<Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" />
</ItemGroup>
</Project>
23 changes: 23 additions & 0 deletions Tests/NetCord.Test.Hosting.AzureFunctions/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

using NetCord;
using NetCord.Hosting;
using NetCord.Hosting.AzureFunctions;
using NetCord.Hosting.Rest;
using NetCord.Hosting.Services.ApplicationCommands;

var host = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureServices((context, services) =>
{
services.AddDiscordRest();
services.AddHttpApplicationCommands();
services.AddDiscordInteractions();
})
.Build();

host.AddSlashCommand("ping", "Ping!", () => "Pong!");

host.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"profiles": {
"NetCord.Test.Hosting.AzureFunctions": {
"commandName": "Project",
"commandLineArgs": "--port 7048",
"launchBrowser": false
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"dependencies": {
"storage1": {
"type": "storage",
"connectionId": "AzureWebJobsStorage"
}
}
}