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

Fusion refactoring #6819

Closed
wants to merge 10 commits into from
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,9 @@ public static async Task<ClientQueryResult> GetAsync(
ClientQueryRequest request,
string path = "/graphql")
{
var query = request.ToString().Replace("+", "%2B");
var response =
await SendGetRequestAsync(testServer, request.ToString().Replace("+", "%2B"), path);
await SendGetRequestAsync(testServer, query, path);

if (response.StatusCode == HttpStatusCode.NotFound)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@

namespace HotChocolate.AspNetCore.Tests.Utilities;

public class TestServerFactory : IDisposable
public sealed class TestServerFactory : IDisposable
{
private readonly List<TestServer> _instances = new();

public TestServer Create(
Action<IServiceCollection> configureServices,
Action<IServiceCollection>? configureServices,
Action<IApplicationBuilder> configureApplication)
{
var builder = new WebHostBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ await server.GetAsync(
// assert
var time2 = await server.GetAsync(
new ClientQueryRequest { Query = "{ time }" });
Assert.False(((long)time1.Data!["time"]!).Equals((long)time2.Data!["time"]!));

Assert.False(Time(time1).Equals(Time(time2)));
}

[Fact]
Expand All @@ -47,6 +48,8 @@ await server.GetAsync(
var time2 = await server.GetAsync(
new ClientQueryRequest { Query = "{ time }" },
"/evict");
Assert.False(((long)time1.Data!["time"]!).Equals((long)time2.Data!["time"]!));
Assert.False(Time(time1).Equals(Time(time2)));
}

private static long Time(ClientQueryResult t) => (long)t.Data!["time"]!;
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public abstract class TypeModule : ITypeModule
/// </summary>
public event EventHandler<EventArgs>? TypesChanged;

internal virtual ValueTask ConfigureAsync(
protected internal virtual ValueTask ConfigureAsync(
ConfigurationContext context,
CancellationToken cancellationToken)
=> default;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ private static IRequestExecutorBuilder CreateBuilder(
(sp, e) =>
{
e.OnRequestExecutorEvictedHooks.Add(
// when ever we evict this schema we will clear the caches.
// Whenever we evict this schema, we will clear the caches.
new OnRequestExecutorEvictedAction(
_ => sp.GetRequiredService<IPreparedOperationCache>().Clear()));
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -716,18 +716,20 @@ private static ISchemaBuilder AddResolverTypeInternal(

private static void InitializeResolverTypeInterceptor(ISchemaBuilder builder)
{
if (!builder.ContextData.ContainsKey(WellKnownContextData.ResolverConfigs))
if (builder.ContextData.ContainsKey(WellKnownContextData.ResolverConfigs))
{
var resolverConfigs = new List<FieldResolverConfig>();
var resolverTypes = new List<(string, Type)>();
var runtimeTypes = new Dictionary<string, Type>();
return;
}

builder.ContextData.Add(WellKnownContextData.ResolverConfigs, resolverConfigs);
builder.ContextData.Add(WellKnownContextData.ResolverTypes, resolverTypes);
builder.ContextData.Add(WellKnownContextData.RuntimeTypes, runtimeTypes);
var resolverConfigs = new List<FieldResolverConfig>();
var resolverTypes = new List<(string, Type)>();
var runtimeTypes = new Dictionary<string, Type>();

builder.TryAddTypeInterceptor(
new ResolverTypeInterceptor(resolverConfigs, resolverTypes, runtimeTypes));
}
builder.ContextData.Add(WellKnownContextData.ResolverConfigs, resolverConfigs);
builder.ContextData.Add(WellKnownContextData.ResolverTypes, resolverTypes);
builder.ContextData.Add(WellKnownContextData.RuntimeTypes, runtimeTypes);

builder.TryAddTypeInterceptor(
new ResolverTypeInterceptor(resolverConfigs, resolverTypes, runtimeTypes));
}
}
8 changes: 6 additions & 2 deletions src/HotChocolate/Core/src/Types/SchemaBuilder.Setup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,12 @@ private static void RegisterOperationName(
OperationType operation,
string? typeName)
{
if (!builder._operations.ContainsKey(operation)
&& !string.IsNullOrEmpty(typeName))
if (string.IsNullOrEmpty(typeName))
{
return;
}

if (!builder._operations.ContainsKey(operation))
{
builder._operations.Add(
operation,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@
throw new ArgumentOutOfRangeException(nameof(access));
}

var package = Package.Open(stream, FileMode.OpenOrCreate, access);
// ReSharper disable once AccessToStaticMemberViaDerivedType
var package = ZipPackage.Open(stream, FileMode.OpenOrCreate, access);

Check warning on line 73 in src/HotChocolate/Fusion/src/Abstractions/FusionGraphPackage.cs

View check run for this annotation

Codecov / codecov/patch

src/HotChocolate/Fusion/src/Abstractions/FusionGraphPackage.cs#L72-L73

Added lines #L72 - L73 were not covered by tests
return new FusionGraphPackage(package);
}

Expand Down Expand Up @@ -107,7 +108,8 @@
var mode = access == FileAccess.Read
? FileMode.Open
: FileMode.OpenOrCreate;
var package = Package.Open(path, mode, access);
// ReSharper disable once AccessToStaticMemberViaDerivedType
var package = ZipPackage.Open(path, mode, access);
return new FusionGraphPackage(package);
}

Expand Down Expand Up @@ -560,7 +562,7 @@

return new SubgraphConfiguration(
config.Name,
schema.ToString(true),
schema.ToString(indented: true),
extensions.Select(t => t.ToString(_syntaxSerializerOptions)).ToArray(),
config.Clients,
config.Extensions);
Expand Down
15 changes: 10 additions & 5 deletions src/HotChocolate/Fusion/src/CommandLine/Commands/ComposeCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,11 @@ private static async Task ExecuteAsync(

if (settingsFile is null)
{
var settingsFileName = System.IO.Path.GetFileNameWithoutExtension(packageFile.FullName) + "-settings.json";
var settingsFileName = IOPath.GetFileNameWithoutExtension(packageFile.FullName) + "-settings.json";

if (packageFile.DirectoryName is not null)
{
settingsFileName = System.IO.Path.Combine(packageFile.DirectoryName, settingsFileName);
settingsFileName = IOPath.Combine(packageFile.DirectoryName, settingsFileName);
}

settingsFile = new FileInfo(settingsFileName);
Expand All @@ -109,12 +109,17 @@ private static async Task ExecuteAsync(
}
}

var configs = (await package.GetSubgraphConfigurationsAsync(cancellationToken)).ToDictionary(t => t.Name);
var configs = (await package.GetSubgraphConfigurationsAsync(cancellationToken))
.ToDictionary(t => t.Name);

// resolve subgraph packages will scan the directory for fsp's. In case of remove we don't want to do that.
if (removeSubgraphs is not { Count: > 0 } || subgraphPackageFiles is { Count: > 0 })
{
await ResolveSubgraphPackagesAsync(workingDirectory, subgraphPackageFiles, configs, cancellationToken);
await ResolveSubgraphPackagesAsync(
workingDirectory,
subgraphPackageFiles,
configs,
cancellationToken);
}

using var settingsJson = settingsFile.Exists
Expand Down Expand Up @@ -389,4 +394,4 @@ public sealed class Transport
[JsonPropertyOrder(10)]
public string? DefaultClientName { get; set; } = "Fusion";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,18 @@
new FileInfo(Combine(workingDirectory.FullName, ExtensionFile)),
};

bool hasErrors = false;

Check warning on line 57 in src/HotChocolate/Fusion/src/CommandLine/Commands/SubgraphPackCommand.cs

View check run for this annotation

Codecov / codecov/patch

src/HotChocolate/Fusion/src/CommandLine/Commands/SubgraphPackCommand.cs#L56-L57

Added lines #L56 - L57 were not covered by tests
if (!schemaFile.Exists)
{
console.WriteLine($"The schema file `{schemaFile.FullName}` does not exist.");
return;
hasErrors = true;
}

if (!configFile.Exists)
{
console.WriteLine($"The config file `{configFile.FullName}` does not exist.");
return;
hasErrors = true;
}

if (extensionFiles.Count == 0)
Expand All @@ -77,10 +79,18 @@
extensionFiles.Clear();
}

if (extensionFiles.Any(t => !t.Exists))
{
console.WriteLine(
$"The extension file `{extensionFiles.First(t => !t.Exists).FullName}` does not exist.");
var firstNonExistentFile = extensionFiles.FirstOrDefault(t => !t.Exists);
if (firstNonExistentFile is not null)

Check warning on line 84 in src/HotChocolate/Fusion/src/CommandLine/Commands/SubgraphPackCommand.cs

View check run for this annotation

Codecov / codecov/patch

src/HotChocolate/Fusion/src/CommandLine/Commands/SubgraphPackCommand.cs#L83-L84

Added lines #L83 - L84 were not covered by tests
{
console.WriteLine(
$"The extension file `{firstNonExistentFile.FullName}` does not exist.");
hasErrors = true;
}
}

if (hasErrors)
{

Check warning on line 93 in src/HotChocolate/Fusion/src/CommandLine/Commands/SubgraphPackCommand.cs

View check run for this annotation

Codecov / codecov/patch

src/HotChocolate/Fusion/src/CommandLine/Commands/SubgraphPackCommand.cs#L87-L93

Added lines #L87 - L93 were not covered by tests
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ public static async Task CreateSubgraphPackageAsync(
extensions.Add(await LoadSchemaDocumentAsync(extensionFile, ct));
}

using var package = Package.Open(packageFile, FileMode.Create);
// ReSharper disable once AccessToStaticMemberViaDerivedType
using var package = ZipPackage.Open(packageFile, FileMode.Create);
await AddSchemaToPackageAsync(package, schema);
await AddTransportConfigToPackage(package, transportConfig);
await AddSchemaExtensionsToPackage(package, extensions);
Expand Down
68 changes: 44 additions & 24 deletions src/HotChocolate/Fusion/src/Composition/FusionTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -322,19 +322,43 @@ private DirectiveType RegisterNodeDirectiveType(string name, ScalarType typeName
return directiveType;
}

private Directive CreateTransportDirective(
string subgraphName,
string? clientName,
Uri location,
string kind)
{
Argument[] arguments;
{
var argumentCount = 3;
if (clientName is not null)
{
argumentCount++;
}
arguments = new Argument[argumentCount];
}

var i = 0;
arguments[i++] = new Argument(SubgraphArg, subgraphName);
if (clientName is not null)
{
arguments[i++] = new Argument(ClientGroupArg, clientName);
}
arguments[i++] = new Argument(LocationArg, location.ToString());
arguments[i] = new Argument(KindArg, kind);

return new Directive(Transport, (IReadOnlyList<Argument>) arguments);
}

public Directive CreateHttpDirective(string subgraphName, string? clientName, Uri location)
=> clientName is null
? new Directive(
Transport,
new Argument(SubgraphArg, subgraphName),
new Argument(LocationArg, location.ToString()),
new Argument(KindArg, "HTTP"))
: new Directive(
Transport,
new Argument(SubgraphArg, subgraphName),
new Argument(ClientGroupArg, clientName),
new Argument(LocationArg, location.ToString()),
new Argument(KindArg, "HTTP"));
{
var result = CreateTransportDirective(
subgraphName: subgraphName,
clientName: clientName,
location: location,
kind: "HTTP");
return result;
}

private DirectiveType RegisterTransportDirectiveType(
string name,
Expand All @@ -354,18 +378,14 @@ private DirectiveType RegisterTransportDirectiveType(
}

public Directive CreateWebSocketDirective(string subgraphName, string? clientName, Uri location)
=> clientName is null
? new Directive(
Transport,
new Argument(SubgraphArg, subgraphName),
new Argument(LocationArg, location.ToString()),
new Argument(KindArg, "WebSocket"))
: new Directive(
Transport,
new Argument(SubgraphArg, subgraphName),
new Argument(ClientGroupArg, clientName),
new Argument(LocationArg, location.ToString()),
new Argument(KindArg, "WebSocket"));
{
var result = CreateTransportDirective(
subgraphName: subgraphName,
clientName: clientName,
location: location,
kind: "WebSocket");
return result;
}

private DirectiveType RegisterFusionDirectiveType(
string name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,20 @@ public async ValueTask InvokeAsync(CompositionContext context, MergeDelegate nex
{
if (schema.QueryType is not null)
{
var targetType = context.FusionGraph.QueryType!;

if (context.FusionGraph.QueryType is null)
if (context.FusionGraph.QueryType is not { } targetType)
{
targetType = context.FusionGraph.QueryType = new ObjectType(schema.QueryType.Name);
targetType = new ObjectType(schema.QueryType.Name);
context.FusionGraph.QueryType = targetType;
targetType.MergeDescriptionWith(schema.QueryType);
context.FusionGraph.Types.Add(targetType);
}

MergeRootFields(
context,
schema,
schema.QueryType,
targetType,
OperationType.Query,
context,
schema,
schema.QueryType,
targetType,
OperationType.Query,
skipOnQuery);
}

Expand Down Expand Up @@ -106,13 +105,13 @@ private static void MergeRootFields(
var arguments = new List<ArgumentNode>();

var selection = new FieldNode(
null,
new NameNode(field.GetOriginalName()),
null,
null,
location: null,
name: new NameNode(field.GetOriginalName()),
alias: null,
required: null,
Array.Empty<DirectiveNode>(),
arguments,
null);
selectionSet: null);

var selectionSet = new SelectionSetNode(new[] { selection });

Expand Down Expand Up @@ -182,4 +181,4 @@ private static Directive CreateVariableDirective(
subgraphName,
variableName,
variableName);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static class FusionRequestExecutorBuilderExtensions
/// Adds a Fusion GraphQL Gateway to the service collection.
/// </summary>
/// <param name="services">
/// The service collection.1
/// The service collection.
/// </param>
/// <param name="graphName">
/// The name of the fusion graph.
Expand Down Expand Up @@ -78,7 +78,7 @@ public static FusionGatewayBuilder AddFusionGatewayServer(

return new FusionGatewayBuilder(builder);
}

/// <summary>
/// Adds a custom ID parser to the gateway.
/// </summary>
Expand All @@ -95,7 +95,7 @@ public static FusionGatewayBuilder AddNodeIdParser<T>(
sc.RemoveAll<NodeIdParser>();
sc.AddSingleton<NodeIdParser, DefaultNodeIdParser>();
}));

return builder;
}

Expand Down
Loading
Loading