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

Adds GraphQL SSE support to StrawberryShake #6401

Merged
merged 5 commits into from
Oct 25, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -206,14 +206,7 @@ private static void WriteList(

for (var i = 0; i < list.Count; i++)
{
var element = list[i];

if (element is null)
{
continue;
}

WriteFieldValue(writer, element);
WriteFieldValue(writer, list[i]);
Copy link
Member Author

Choose a reason for hiding this comment

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

We need the null values also in arrays

Copy link
Member

Choose a reason for hiding this comment

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

Ah ... i know why i did that ... if null i wanted to short-circur

writer.WriteNullValue()

in the null check

Copy link
Member

Choose a reason for hiding this comment

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

uhh ... there are a couple of bugs in there .... I will need to do a separate PR

Copy link
Member

Choose a reason for hiding this comment

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

damn it michael ;)

Copy link
Member Author

Choose a reason for hiding this comment

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

in the Utf8JsonWriter?

}

writer.WriteEndArray();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ public GraphQLHttpResponse(HttpResponseMessage message)
/// </summary>
public bool IsSuccessStatusCode => _message.IsSuccessStatusCode;

/// <summary>
/// Gets the reason phrase which typically is sent by servers together with the status code.
/// </summary>
public string? ReasonPhrase => _message.ReasonPhrase;

/// <summary>
/// Throws an exception if the HTTP response was unsuccessful.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<InternalsVisibleTo Include="HotChocolate.OpenApi" />
<InternalsVisibleTo Include="HotChocolate.Transport.Http" />
<InternalsVisibleTo Include="HotChocolate.Transport.Sockets.Client" />
<InternalsVisibleTo Include="StrawberryShake.Transport.Http" />
</ItemGroup>

<ItemGroup>
Expand Down
30 changes: 30 additions & 0 deletions src/StrawberryShake/Client/StrawberryShake.Client.sln
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StrawberryShake.Persistence
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StrawberryShake.Razor", "src\Razor\StrawberryShake.Razor.csproj", "{2A834588-BA60-4906-B111-20AF9FD5B1E6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HotChocolate.Transport.Http", "..\..\HotChocolate\AspNetCore\src\Transport.Http\HotChocolate.Transport.Http.csproj", "{1A765D49-CF64-4C34-AE37-E6171362A858}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HotChocolate.Utilities", "..\..\HotChocolate\Utilities\src\Utilities\HotChocolate.Utilities.csproj", "{62478E17-8EAE-4473-9C8E-5933042B25A0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -218,6 +222,30 @@ Global
{2A834588-BA60-4906-B111-20AF9FD5B1E6}.Release|x64.Build.0 = Release|Any CPU
{2A834588-BA60-4906-B111-20AF9FD5B1E6}.Release|x86.ActiveCfg = Release|Any CPU
{2A834588-BA60-4906-B111-20AF9FD5B1E6}.Release|x86.Build.0 = Release|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Debug|x64.ActiveCfg = Debug|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Debug|x64.Build.0 = Debug|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Debug|x86.ActiveCfg = Debug|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Debug|x86.Build.0 = Debug|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Release|Any CPU.Build.0 = Release|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Release|x64.ActiveCfg = Release|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Release|x64.Build.0 = Release|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Release|x86.ActiveCfg = Release|Any CPU
{1A765D49-CF64-4C34-AE37-E6171362A858}.Release|x86.Build.0 = Release|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Debug|x64.ActiveCfg = Debug|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Debug|x64.Build.0 = Debug|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Debug|x86.ActiveCfg = Debug|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Debug|x86.Build.0 = Debug|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Release|Any CPU.Build.0 = Release|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Release|x64.ActiveCfg = Release|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Release|x64.Build.0 = Release|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Release|x86.ActiveCfg = Release|Any CPU
{62478E17-8EAE-4473-9C8E-5933042B25A0}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{61894B9B-EC9A-4FC0-AAAF-9922978A5AB8} = {5F283FE4-BB0A-4806-B079-42DBFE0B2EDF}
Expand All @@ -234,5 +262,7 @@ Global
{DFFA574E-439F-4FCE-BF6D-CE5BEACA360A} = {5F283FE4-BB0A-4806-B079-42DBFE0B2EDF}
{9A5345E8-A2EB-410F-BD72-6F268794D2DC} = {4E0B9145-BE75-4F46-906B-092DFF4AD5CC}
{2A834588-BA60-4906-B111-20AF9FD5B1E6} = {5F283FE4-BB0A-4806-B079-42DBFE0B2EDF}
{1A765D49-CF64-4C34-AE37-E6171362A858} = {264FDF20-A58F-476E-9E02-9F082FB65612}
{62478E17-8EAE-4473-9C8E-5933042B25A0} = {264FDF20-A58F-476E-9E02-9F082FB65612}
EndGlobalSection
EndGlobal

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,7 @@
<data name="ResponseEnumerator_HttpNoSuccessStatusCode" xml:space="preserve">
<value>Response status code does not indicate success: {0} ({1}).</value>
</data>
<data name="HttpConnection_FileMapDoesNotMatch" xml:space="preserve">
<value>Could not map the file uploads to the variables. The data structures did not match. Could not find path {0} in the variables.</value>
</data>
</root>
212 changes: 179 additions & 33 deletions src/StrawberryShake/Client/src/Transport.Http/HttpConnection.cs
Original file line number Diff line number Diff line change
@@ -1,74 +1,220 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using StrawberryShake.Internal;
using HotChocolate.Transport.Http;
using HotChocolate.Utilities;
using StrawberryShake.Json;
using static StrawberryShake.Properties.Resources;
using static StrawberryShake.Transport.Http.ResponseEnumerable;

namespace StrawberryShake.Transport.Http;

public sealed class HttpConnection : IHttpConnection
{
private readonly Func<HttpClient> _createClient;
private readonly JsonOperationRequestSerializer _serializer = new();

public HttpConnection(Func<HttpClient> createClient)
{
_createClient = createClient ?? throw new ArgumentNullException(nameof(createClient));
}

public IAsyncEnumerable<Response<JsonDocument>> ExecuteAsync(OperationRequest request)
=> Create(_createClient, () => CreateRequestMessage(request));
=> Create(_createClient, () => MapRequest(request));

private HttpRequestMessage CreateRequestMessage(OperationRequest request)
private static GraphQLHttpRequest MapRequest(OperationRequest request)
{
var operation = CreateRequestMessageBody(request);
var (id, name, document, variables, extensions, _, files, _) = request;

var content = request.Files.Count == 0
? CreateRequestContent(operation)
: CreateMultipartContent(request, operation);
#if NETSTANDARD2_0
var body = Encoding.UTF8.GetString(document.Body.ToArray());
#else
var body = Encoding.UTF8.GetString(document.Body);
#endif

return new HttpRequestMessage { Method = HttpMethod.Post, Content = content };
var hasFiles = files is { Count: > 0 };

variables = MapVariables(variables);
if (hasFiles && variables is not null)
{
variables = MapFilesToVariables(variables, files!);
}

var operation =
new HotChocolate.Transport.OperationRequest(body, id, name, variables, extensions);

return new GraphQLHttpRequest(operation) { EnableFileUploads = hasFiles };
}

private byte[] CreateRequestMessageBody(OperationRequest request)
/// <summary>
/// Converts the variables into a dictionary that can be serialized. This is necessary
/// because the variables can contain lists of key value pairs which are not supported
/// by HotChocolate.Transport.Http
/// </summary>
/// <remarks>
/// We only convert the variables if necessary to avoid unnecessary allocations.
/// </remarks>
private static IReadOnlyDictionary<string, object?>? MapVariables(
IReadOnlyDictionary<string, object?> variables)
{
using var arrayWriter = new ArrayWriter();
_serializer.Serialize(request, arrayWriter);
var buffer = new byte[arrayWriter.Length];
arrayWriter.Body.Span.CopyTo(buffer);
return buffer;
if (variables.Count == 0)
{
return null;
}

Dictionary<string, object?>? copy = null;
foreach (var variable in variables)
{
var value = variable.Value;
// the value can be a List<T> of key value pairs and not only a dictionary. We do expect
// to just have lists here, but in case we have a dictionary this should also just work.
if (value is IEnumerable<KeyValuePair<string, object?>> items)
{
copy ??= CreateDictionary(variables);

value = MapVariables(CreateDictionary(items));
}
else if (value is List<object?> list)
{
// the lists are mutable so we can just update the value in the list
MapVariables(list);
}

if (copy is not null)
{
copy[variable.Key] = value;
}
}

return copy ?? variables;
}

private static HttpContent CreateRequestContent(byte[] operation)
private static void MapVariables(List<object?> variables)
{
var content = new ByteArrayContent(operation);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return content;
if (variables.Count == 0)
{
return;
}

for (var index = 0; index < variables.Count; index++)
{
switch (variables[index])
{
case IEnumerable<KeyValuePair<string, object?>> items:
variables[index] = MapVariables(CreateDictionary(items));
break;

case List<object?> list:
MapVariables(list);
break;
}
}
}

private static HttpContent CreateMultipartContent(OperationRequest request, byte[] operation)
private static Dictionary<string, object?> CreateDictionary(
IEnumerable<KeyValuePair<string, object?>> values)
{
var fileMap = new Dictionary<string, string[]>();
var form = new MultipartFormDataContent
#if NETSTANDARD2_0
var dictionary = new Dictionary<string, object?>();

foreach (var value in values)
{
{ new ByteArrayContent(operation), "operations" },
{ JsonContent.Create(fileMap), "map" }
};
dictionary[value.Key] = value.Value;
}

foreach (var file in request.Files)
return dictionary;
#else
return new Dictionary<string, object?>(values);
#endif
}

private static IReadOnlyDictionary<string, object?> MapFilesToVariables(
IReadOnlyDictionary<string, object?> variables,
IReadOnlyDictionary<string, Upload?> files)
{
foreach (var file in files)
{
if (file.Value is { } fileContent)
var path = file.Key;
var upload = file.Value;

if (!upload.HasValue)
{
continue;
}

var currentPath = path.Substring("variables.".Length);
object? currentObject = variables;
int index;
while ((index = currentPath.IndexOf('.')) >= 0)
{
var identifier = (fileMap.Count + 1).ToString();
fileMap.Add(identifier, new[] { file.Key });
form.Add(new StreamContent(fileContent.Content), identifier, fileContent.FileName);
var segment = currentPath.Substring(0, index);
switch (currentObject)
{
case Dictionary<string, object> dictionary:
if (!dictionary.TryGetValue(segment, out currentObject))
{
throw new InvalidOperationException(
string.Format(HttpConnection_FileMapDoesNotMatch, path));
}

break;

case List<object> array:
if (!int.TryParse(segment, out var arrayIndex))
{
throw new InvalidOperationException(
string.Format(HttpConnection_FileMapDoesNotMatch, path));
}

if (arrayIndex >= array.Count)
{
throw new InvalidOperationException(
string.Format(HttpConnection_FileMapDoesNotMatch, path));
}

currentObject = array[arrayIndex];
break;

default:
throw new InvalidOperationException(
string.Format(HttpConnection_FileMapDoesNotMatch, path));
}

currentPath = currentPath.Substring(index + 1);
}

switch (currentObject)
{
case Dictionary<string, object> result:
result[currentPath] =
new FileReference(upload.Value.Content, upload.Value.FileName);
break;

case List<object> array:
if (!int.TryParse(currentPath, out var arrayIndex))
{
throw new InvalidOperationException(
string.Format(HttpConnection_FileMapDoesNotMatch, path));
}

if (arrayIndex >= array.Count)
{
throw new InvalidOperationException(
string.Format(HttpConnection_FileMapDoesNotMatch, path));
}

array[arrayIndex] =
new FileReference(upload.Value.Content, upload.Value.FileName);

break;

default:
throw new InvalidOperationException(
string.Format(HttpConnection_FileMapDoesNotMatch, path));
}
}

return form;
return variables;
}
}
Loading
Loading