From 96eacbf367639d7b68b804e20dab7b945226f931 Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Tue, 28 Apr 2026 09:15:50 +0000 Subject: [PATCH 1/6] Refactor ISourceSchemaClientFactory --- ...olloFederationSourceSchemaClientFactory.cs | 2 ++ .../LookupFieldInfo.cs | 2 +- .../InMemorySourceSchemaClientFactory.cs | 2 ++ .../Clients/DefaultSourceSchemaClientScope.cs | 13 ++++++----- .../Clients/HttpSourceSchemaClientFactory.cs | 2 ++ .../Clients/ISourceSchemaClientFactory.cs | 7 +++++- .../Clients/SourceSchemaClientFactory.cs | 13 ++++++++--- .../Infrastructure/FusionGatewayBuilder.cs | 20 ++++++++--------- .../SchemaTransformationIntegrationTests.cs | 22 +++++++++---------- ...h_Should_ProduceValidSourceSchema.graphql} | 0 10 files changed, 52 insertions(+), 31 deletions(-) rename src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/__snapshots__/{SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidCompositeSchema.graphql => SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidSourceSchema.graphql} (100%) diff --git a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientFactory.cs b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientFactory.cs index ecc47a80935..80f0d8e6410 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientFactory.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientFactory.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using HotChocolate.Fusion.Transport.Http; +using HotChocolate.Fusion.Types; namespace HotChocolate.Fusion.Execution.Clients; @@ -26,6 +27,7 @@ public ApolloFederationSourceSchemaClientFactory(IHttpClientFactory httpClientFa /// protected override ISourceSchemaClient CreateClient( + FusionSchemaDefinition schema, ApolloFederationSourceSchemaClientConfiguration configuration) { var httpClient = _httpClientFactory.CreateClient(configuration.HttpClientName); diff --git a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/LookupFieldInfo.cs b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/LookupFieldInfo.cs index 63e3fc15335..16228ee2f90 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/LookupFieldInfo.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/LookupFieldInfo.cs @@ -1,7 +1,7 @@ namespace HotChocolate.Fusion.Execution.Clients; /// -/// Describes a single lookup field on the composite schema that maps +/// Describes a single lookup field on the source schema that maps /// to an Apollo Federation entity type. Used by /// to detect entity lookups and rewrite them into _entities queries. /// diff --git a/src/HotChocolate/Fusion/src/Fusion.Connectors.InMemory/InMemorySourceSchemaClientFactory.cs b/src/HotChocolate/Fusion/src/Fusion.Connectors.InMemory/InMemorySourceSchemaClientFactory.cs index 0bb094e015f..dbe2304b5df 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Connectors.InMemory/InMemorySourceSchemaClientFactory.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Connectors.InMemory/InMemorySourceSchemaClientFactory.cs @@ -1,4 +1,5 @@ using HotChocolate.Execution; +using HotChocolate.Fusion.Types; using HotChocolate.Transport.Formatters; namespace HotChocolate.Fusion.Execution.Clients; @@ -36,6 +37,7 @@ public InMemorySourceSchemaClientFactory( /// protected override ISourceSchemaClient CreateClient( + FusionSchemaDefinition schema, InMemorySourceSchemaClientConfiguration configuration) { var proxy = new RequestExecutorProxy(_executorProvider, _executorEvents, configuration.Name); diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/DefaultSourceSchemaClientScope.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/DefaultSourceSchemaClientScope.cs index c8f1824636c..5020ab0cc4d 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/DefaultSourceSchemaClientScope.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/DefaultSourceSchemaClientScope.cs @@ -14,6 +14,7 @@ public sealed class DefaultSourceSchemaClientScope : ISourceSchemaClientScope #endif private readonly ConcurrentDictionary<(string Name, OperationType Type), ISourceSchemaClient> _clients = []; private readonly ISourceSchemaClientFactory[] _clientFactories; + private readonly FusionSchemaDefinition _schemaDefinition; private readonly SourceSchemaClientConfigurations _configurations; private bool _disposed; @@ -25,6 +26,7 @@ public DefaultSourceSchemaClientScope( ArgumentNullException.ThrowIfNull(clientFactories); _clientFactories = clientFactories; + _schemaDefinition = schemaDefinition; _configurations = schemaDefinition.Features.GetRequired(); } @@ -58,25 +60,26 @@ public ISourceSchemaClient GetClient(string name, OperationType operationType) private ISourceSchemaClient CreateClient(ISourceSchemaClientConfiguration configuration) { var factories = _clientFactories; + var schema = _schemaDefinition; if (factories.Length > 0 && factories[0].CanHandle(configuration)) { - return factories[0].CreateClient(configuration); + return factories[0].CreateClient(schema, configuration); } if (factories.Length > 1 && factories[1].CanHandle(configuration)) { - return factories[1].CreateClient(configuration); + return factories[1].CreateClient(schema, configuration); } if (factories.Length > 2 && factories[2].CanHandle(configuration)) { - return factories[2].CreateClient(configuration); + return factories[2].CreateClient(schema, configuration); } if (factories.Length > 3 && factories[3].CanHandle(configuration)) { - return factories[3].CreateClient(configuration); + return factories[3].CreateClient(schema, configuration); } if (factories.Length > 4) @@ -85,7 +88,7 @@ private ISourceSchemaClient CreateClient(ISourceSchemaClientConfiguration config { if (factories[i].CanHandle(configuration)) { - return factories[i].CreateClient(configuration); + return factories[i].CreateClient(schema, configuration); } } } diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/HttpSourceSchemaClientFactory.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/HttpSourceSchemaClientFactory.cs index 44e3bc3ed9e..69937b681c7 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/HttpSourceSchemaClientFactory.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/HttpSourceSchemaClientFactory.cs @@ -1,4 +1,5 @@ using HotChocolate.Fusion.Transport.Http; +using HotChocolate.Fusion.Types; namespace HotChocolate.Fusion.Execution.Clients; @@ -14,6 +15,7 @@ public HttpSourceSchemaClientFactory(IHttpClientFactory httpClientFactory) } protected override ISourceSchemaClient CreateClient( + FusionSchemaDefinition schema, SourceSchemaHttpClientConfiguration configuration) { var httpClient = _httpClientFactory.CreateClient(configuration.HttpClientName); diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/ISourceSchemaClientFactory.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/ISourceSchemaClientFactory.cs index aefd8080cbd..640d4b54ca1 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/ISourceSchemaClientFactory.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/ISourceSchemaClientFactory.cs @@ -1,3 +1,5 @@ +using HotChocolate.Fusion.Types; + namespace HotChocolate.Fusion.Execution.Clients; /// @@ -17,7 +19,10 @@ public interface ISourceSchemaClientFactory /// /// Creates a new for the given configuration. /// + /// The composed Fusion gateway schema. /// The client configuration. /// A new source schema client instance. - ISourceSchemaClient CreateClient(ISourceSchemaClientConfiguration configuration); + ISourceSchemaClient CreateClient( + FusionSchemaDefinition schema, + ISourceSchemaClientConfiguration configuration); } diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/SourceSchemaClientFactory.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/SourceSchemaClientFactory.cs index 7e21029d381..4deb30e4528 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/SourceSchemaClientFactory.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Clients/SourceSchemaClientFactory.cs @@ -1,3 +1,5 @@ +using HotChocolate.Fusion.Types; + namespace HotChocolate.Fusion.Execution.Clients; /// @@ -17,20 +19,25 @@ public bool CanHandle(ISourceSchemaClientConfiguration configuration) => configuration is TConfiguration; /// - public ISourceSchemaClient CreateClient(ISourceSchemaClientConfiguration configuration) + public ISourceSchemaClient CreateClient( + FusionSchemaDefinition schema, + ISourceSchemaClientConfiguration configuration) { if (configuration is not TConfiguration casted) { throw ThrowHelper.InvalidClientConfiguration(typeof(TConfiguration), configuration.GetType()); } - return CreateClient(casted); + return CreateClient(schema, casted); } /// /// Creates a new for the given typed configuration. /// + /// The composed Fusion gateway schema. /// The typed client configuration. /// A new source schema client instance. - protected abstract ISourceSchemaClient CreateClient(TConfiguration configuration); + protected abstract ISourceSchemaClient CreateClient( + FusionSchemaDefinition schema, + TConfiguration configuration); } diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/Infrastructure/FusionGatewayBuilder.cs b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/Infrastructure/FusionGatewayBuilder.cs index 4afa81e0d95..d6a509989a7 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/Infrastructure/FusionGatewayBuilder.cs +++ b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/Infrastructure/FusionGatewayBuilder.cs @@ -68,7 +68,7 @@ public static async Task ComposeAsync( var info = await BuildSubgraphInfoAsync(host).ConfigureAwait(false); - sourceSchemaTexts.Add(new SourceSchemaText(name, info.CompositeSdl)); + sourceSchemaTexts.Add(new SourceSchemaText(name, info.SourceSchemaSdl)); subgraphInfos.Add(info); } @@ -119,13 +119,13 @@ private static async Task BuildSubgraphInfoAsync(SubgraphHost host $"Apollo Federation transform failed for subgraph '{host.Name}': {messages}"); } - var compositeSdl = transformResult.Value; - var lookups = ExtractLookups(compositeSdl); - var entityRequires = ExtractEntityRequires(compositeSdl, lookups); + var sourceSchemaSdl = transformResult.Value; + var lookups = ExtractLookups(sourceSchemaSdl); + var entityRequires = ExtractEntityRequires(sourceSchemaSdl, lookups); return new SubgraphInfo( host.Name, - compositeSdl, + sourceSchemaSdl, lookups, entityRequires, new Uri(DefaultBaseAddress)); @@ -325,9 +325,9 @@ private static JsonDocumentOwner BuildGatewaySettings(IReadOnlyList ExtractLookups(string compositeSdl) + private static IReadOnlyDictionary ExtractLookups(string sourceSchemaSdl) { - var document = Utf8GraphQLParser.Parse(compositeSdl); + var document = Utf8GraphQLParser.Parse(sourceSchemaSdl); var queryName = FindRootQueryName(document) ?? "Query"; var lookups = new Dictionary(StringComparer.Ordinal); @@ -386,7 +386,7 @@ private static IReadOnlyDictionary ExtractLookups(s /// private static IReadOnlyDictionary>> ExtractEntityRequires( - string compositeSdl, + string sourceSchemaSdl, IReadOnlyDictionary lookups) { var entityTypeNames = new HashSet(StringComparer.Ordinal); @@ -402,7 +402,7 @@ private static IReadOnlyDictionary>>( @@ -592,7 +592,7 @@ private sealed record LookupFieldSettings( private sealed record SubgraphInfo( string Name, - string CompositeSdl, + string SourceSchemaSdl, IReadOnlyDictionary Lookups, IReadOnlyDictionary>> EntityRequires, Uri BaseAddress); diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/SchemaTransformationIntegrationTests.cs b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/SchemaTransformationIntegrationTests.cs index ac89c171ca2..3f3d3995601 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/SchemaTransformationIntegrationTests.cs +++ b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/SchemaTransformationIntegrationTests.cs @@ -13,7 +13,7 @@ private static readonly IReadOnlyDictionary s_noRequ = new Dictionary(StringComparer.Ordinal); [Fact] - public async Task Transform_FederationSubgraph_Should_ProduceValidCompositeSchema() + public async Task Transform_FederationSubgraph_Should_ProduceValidSourceSchema() { // arrange: build an Apollo Federation subgraph and get its SDL var schema = await new ServiceCollection() @@ -34,23 +34,23 @@ public async Task Transform_FederationSubgraph_Should_ProduceValidCompositeSchem result.IsSuccess, $"Transform failed: {string.Join(", ", result.Errors.Select(e => e.Message))}"); - var compositeSdl = result.Value; + var sourceSchemaSdl = result.Value; // Should have @key directives - Assert.Contains("@key", compositeSdl); + Assert.Contains("@key", sourceSchemaSdl); // Should have @lookup fields - Assert.Contains("@lookup", compositeSdl); + Assert.Contains("@lookup", sourceSchemaSdl); // Should NOT have federation infrastructure - Assert.DoesNotContain("_entities", compositeSdl); - Assert.DoesNotContain("_service", compositeSdl); - Assert.DoesNotContain("_Service", compositeSdl); - Assert.DoesNotContain("_Entity", compositeSdl); - Assert.DoesNotContain("_Any", compositeSdl); + Assert.DoesNotContain("_entities", sourceSchemaSdl); + Assert.DoesNotContain("_service", sourceSchemaSdl); + Assert.DoesNotContain("_Service", sourceSchemaSdl); + Assert.DoesNotContain("_Entity", sourceSchemaSdl); + Assert.DoesNotContain("_Any", sourceSchemaSdl); // Snapshot the output - compositeSdl.MatchSnapshot(extension: ".graphql"); + sourceSchemaSdl.MatchSnapshot(extension: ".graphql"); } [Fact] @@ -71,7 +71,7 @@ public async Task Rewriter_Should_RewriteLookupToEntities_FromTransformedSchema( result.IsSuccess, $"Transform failed: {string.Join(", ", result.Errors.Select(e => e.Message))}"); - // Parse the composite SDL to find @lookup fields + // Parse the source schema SDL to find @lookup fields // (In a real scenario, the connector would do this from the MutableSchemaDefinition) var lookupFields = new Dictionary { diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/__snapshots__/SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidCompositeSchema.graphql b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/__snapshots__/SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidSourceSchema.graphql similarity index 100% rename from src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/__snapshots__/SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidCompositeSchema.graphql rename to src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/__snapshots__/SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidSourceSchema.graphql From a4c221e1a6af9e0939d48a42a91fa004f1dc25f8 Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Fri, 1 May 2026 12:42:12 +0000 Subject: [PATCH 2/6] wip --- .gitignore | 1 + src/All.slnx | 1 - .../Fusion/HotChocolate.Fusion.slnx | 1 - ...Fusion.Composition.ApolloFederation.csproj | 33 -- .../ApolloFederation}/EntityKeyInfo.cs | 0 .../FederationDirectiveNames.cs | 0 .../ApolloFederation}/FederationFieldNames.cs | 0 .../FederationSchemaAnalyzer.cs | 49 ++- .../FederationSchemaTransformer.cs | 51 ++- .../ApolloFederation}/FederationTypeNames.cs | 0 .../ApolloFederation}/GenerateLookupFields.cs | 0 .../FederationResources.Designer.cs | 0 .../Properties/FederationResources.resx | 0 .../ApolloFederation}/RemoveExternalFields.cs | 0 .../RemoveFederationInfrastructure.cs | 0 .../ApolloFederation}/RewriteKeyDirectives.cs | 0 .../ApolloFederation/StampConnectorKind.cs | 50 +++ .../TransformRequiresToRequire.cs | 0 .../ConnectorMutableDirectiveDefinition.cs | 28 ++ ...sionConnectorMutableDirectiveDefinition.cs | 28 ++ .../src/Fusion.Composition/FusionBuiltIns.cs | 1 + .../HotChocolate.Fusion.Composition.csproj | 10 + .../Logging/LogEntryCodes.cs | 2 + .../CompositionResources.Designer.cs | 38 +- .../Properties/CompositionResources.resx | 12 + .../Fusion.Composition/SourceSchemaMerger.cs | 36 ++ .../SourceSchemaPreprocessor.cs | 12 + .../WellKnownArgumentNames.cs | 1 + .../WellKnownDirectiveNames.cs | 1 + ...olloFederationClientConfigurationParser.cs | 208 +--------- ...derationSourceSchemaClientConfiguration.cs | 144 ++++++- ...olloFederationSourceSchemaClientFactory.cs | 9 +- ...ederationFusionGatewayBuilderExtensions.cs | 4 +- ....Fusion.Connectors.ApolloFederation.csproj | 1 - .../LookupArgumentPathMapper.cs | 26 ++ .../Completion/CompositeSchemaBuilder.cs | 30 +- .../Fusion.Execution.Types/FusionBuiltIns.cs | 1 + .../FusionSchemaDefinition.cs | 31 +- ...HotChocolate.Fusion.Execution.Types.csproj | 1 + .../Metadata/SourceSchemaInfo.cs | 2 +- .../ISourceSchemaClientConfigurationParser.cs | 31 +- ...efaultGraphQLClientConfigurationParser.cs} | 25 +- .../Execution/FusionOptions.cs | 2 +- .../Execution/FusionRequestExecutorManager.cs | 204 ++++++---- ....Composition.ApolloFederation.Tests.csproj | 2 +- ...TransformerTests.Transform_CompositeKey.md | 8 +- ...rmerTests.Transform_DeeplyNestedListKey.md | 8 +- ...formerTests.Transform_ExternalDirective.md | 8 +- ...nsformerTests.Transform_FullIntegration.md | 8 +- ...erTests.Transform_KeyResolvableArgument.md | 8 +- ...TransformerTests.Transform_MultipleKeys.md | 8 +- ...ransformerTests.Transform_NestedListKey.md | 8 +- ...nsformerTests.Transform_NestedObjectKey.md | 8 +- ...ransform_NonResolvableAndResolvableKeys.md | 8 +- ...sformerTests.Transform_NonResolvableKey.md | 8 +- ...formerTests.Transform_ProvidesDirective.md | 8 +- ...formerTests.Transform_RequiresDirective.md | 8 +- ...TransformerTests.Transform_SimpleEntity.md | 8 +- ...ceSchemaMerger.ConnectorDirective.Tests.cs | 136 +++++++ ...NamedSchemas_AddsFusionDefinitions.graphql | 6 + ...s.ApolloFederation.Compliance.Tests.csproj | 1 - .../Infrastructure/FusionGatewayBuilder.cs | 334 +--------------- .../ApolloFederationConnectorTests.cs | 8 +- .../ApolloFederationCompletionTests.cs | 181 +++++++++ .../LookupArgumentPathMapperTests.cs | 81 ++++ .../Configuration/ParsersTests.cs | 376 +++++++----------- ...ph_Should_ProduceValidSourceSchema.graphql | 8 +- .../Configuration/ParsersTests.cs | 147 ++----- ...usionSchemaDefinitionConnectorKindTests.cs | 120 ++++++ 69 files changed, 1507 insertions(+), 1071 deletions(-) delete mode 100644 src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/HotChocolate.Fusion.Composition.ApolloFederation.csproj rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/EntityKeyInfo.cs (100%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/FederationDirectiveNames.cs (100%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/FederationFieldNames.cs (100%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/FederationSchemaAnalyzer.cs (57%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/FederationSchemaTransformer.cs (51%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/FederationTypeNames.cs (100%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/GenerateLookupFields.cs (100%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/Properties/FederationResources.Designer.cs (100%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/Properties/FederationResources.resx (100%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/RemoveExternalFields.cs (100%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/RemoveFederationInfrastructure.cs (100%) rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/RewriteKeyDirectives.cs (100%) create mode 100644 src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/StampConnectorKind.cs rename src/HotChocolate/Fusion/src/{Fusion.Composition.ApolloFederation => Fusion.Composition/ApolloFederation}/TransformRequiresToRequire.cs (100%) create mode 100644 src/HotChocolate/Fusion/src/Fusion.Composition/Definitions/ConnectorMutableDirectiveDefinition.cs create mode 100644 src/HotChocolate/Fusion/src/Fusion.Composition/Definitions/FusionConnectorMutableDirectiveDefinition.cs create mode 100644 src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/LookupArgumentPathMapper.cs rename src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/Parsers/{HttpSourceSchemaClientConfigurationParser.cs => DefaultGraphQLClientConfigurationParser.cs} (85%) create mode 100644 src/HotChocolate/Fusion/test/Fusion.Composition.Tests/SourceSchemaMerger.ConnectorDirective.Tests.cs create mode 100644 src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/ApolloFederationCompletionTests.cs create mode 100644 src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/LookupArgumentPathMapperTests.cs create mode 100644 src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Types/FusionSchemaDefinitionConnectorKindTests.cs diff --git a/.gitignore b/.gitignore index b5ee7a08d72..d719535568e 100644 --- a/.gitignore +++ b/.gitignore @@ -330,3 +330,4 @@ Directory.Build.user.props .claude/ src/Mocha/benchmarks/Mocha.Mediator.Benchmarks/Generated/ +.work/ diff --git a/src/All.slnx b/src/All.slnx index 39c317bdc08..cf15671aa61 100644 --- a/src/All.slnx +++ b/src/All.slnx @@ -214,7 +214,6 @@ - diff --git a/src/HotChocolate/Fusion/HotChocolate.Fusion.slnx b/src/HotChocolate/Fusion/HotChocolate.Fusion.slnx index 560ef71f902..89e79ece137 100644 --- a/src/HotChocolate/Fusion/HotChocolate.Fusion.slnx +++ b/src/HotChocolate/Fusion/HotChocolate.Fusion.slnx @@ -6,7 +6,6 @@ - diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/HotChocolate.Fusion.Composition.ApolloFederation.csproj b/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/HotChocolate.Fusion.Composition.ApolloFederation.csproj deleted file mode 100644 index 01abf1e6865..00000000000 --- a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/HotChocolate.Fusion.Composition.ApolloFederation.csproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - HotChocolate.Fusion.Composition.ApolloFederation - HotChocolate.Fusion.ApolloFederation - - - - - - - - - - - - - - - ResXFileCodeGenerator - FederationResources.Designer.cs - - - - - - True - True - FederationResources.resx - - - - diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/EntityKeyInfo.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/EntityKeyInfo.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/EntityKeyInfo.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/EntityKeyInfo.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationDirectiveNames.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationDirectiveNames.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationDirectiveNames.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationDirectiveNames.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationFieldNames.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationFieldNames.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationFieldNames.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationFieldNames.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationSchemaAnalyzer.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationSchemaAnalyzer.cs similarity index 57% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationSchemaAnalyzer.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationSchemaAnalyzer.cs index b34dda1ef61..b8d3262b688 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationSchemaAnalyzer.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationSchemaAnalyzer.cs @@ -1,4 +1,5 @@ -using HotChocolate.Fusion.Errors; +using HotChocolate.Fusion.Logging; +using HotChocolate.Fusion.Logging.Contracts; using HotChocolate.Language; using HotChocolate.Types.Mutable; using static HotChocolate.Fusion.ApolloFederation.Properties.FederationResources; @@ -11,7 +12,7 @@ namespace HotChocolate.Fusion.ApolloFederation; /// internal static class FederationSchemaAnalyzer { - private const string FederationUrlPrefix = "specs.apollo.dev/federation"; + internal const string FederationUrlPrefix = "specs.apollo.dev/federation"; private static readonly HashSet s_unsupportedDirectives = [ @@ -23,33 +24,45 @@ internal static class FederationSchemaAnalyzer ]; /// - /// Validates the given federation schema and returns any composition errors. + /// Validates the given federation schema and writes any composition errors to the + /// provided . /// /// /// The mutable schema definition to validate. /// + /// + /// The composition log that receives validation errors. + /// /// - /// A list of instances. An empty list indicates success. + /// true when validation passed (no errors were written); otherwise, false. /// - public static List Validate(MutableSchemaDefinition schema) + public static bool Validate(MutableSchemaDefinition schema, ICompositionLog log) { - var errors = new List(); + var entryCountBefore = log.Count(); - ValidateFederationVersion(schema, errors); - ValidateUnsupportedDirectives(schema, errors); + ValidateFederationVersion(schema, log); + ValidateUnsupportedDirectives(schema, log); - return errors; + // Pre-existing entries on the log are not ours to report on; this run reports + // failure only when it wrote new entries (all of which are errors) of its own. + return log.Count() == entryCountBefore; } private static void ValidateFederationVersion( MutableSchemaDefinition schema, - List errors) + ICompositionLog log) { var federationVersion = FindFederationVersion(schema); if (federationVersion is null) { - errors.Add(new CompositionError(FederationSchemaAnalyzer_FederationV1NotSupported)); + log.Write( + LogEntryBuilder.New() + .SetMessage(FederationSchemaAnalyzer_FederationV1NotSupported) + .SetCode(LogEntryCodes.FederationV1NotSupported) + .SetSeverity(LogSeverity.Error) + .SetSchema(schema) + .Build()); } } @@ -90,15 +103,21 @@ private static void ValidateFederationVersion( private static void ValidateUnsupportedDirectives( MutableSchemaDefinition schema, - List errors) + ICompositionLog log) { foreach (var name in s_unsupportedDirectives) { if (schema.DirectiveDefinitions.ContainsName(name)) { - errors.Add(new CompositionError(string.Format( - FederationSchemaAnalyzer_DirectiveNotSupported, - name))); + log.Write( + LogEntryBuilder.New() + .SetMessage( + FederationSchemaAnalyzer_DirectiveNotSupported, + name) + .SetCode(LogEntryCodes.FederationDirectiveNotSupported) + .SetSeverity(LogSeverity.Error) + .SetSchema(schema) + .Build()); } } } diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationSchemaTransformer.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationSchemaTransformer.cs similarity index 51% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationSchemaTransformer.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationSchemaTransformer.cs index 7d62015057d..28a6ba14eac 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationSchemaTransformer.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationSchemaTransformer.cs @@ -1,5 +1,6 @@ using System.Collections.Immutable; using HotChocolate.Fusion.Errors; +using HotChocolate.Fusion.Logging; using HotChocolate.Fusion.Results; using HotChocolate.Language; using HotChocolate.Types.Mutable; @@ -14,6 +15,47 @@ namespace HotChocolate.Fusion.ApolloFederation; /// public static class FederationSchemaTransformer { + /// + /// Determines whether the given schema is an Apollo Federation v2 subgraph + /// based on the presence of an @link directive that imports the + /// Apollo Federation specification. + /// + /// + /// The mutable schema definition to inspect. + /// + /// + /// true when the schema declares an @link directive whose + /// url argument references the Apollo Federation specification; + /// otherwise, false. + /// + public static bool IsFederationSchema(MutableSchemaDefinition schema) + { + ArgumentNullException.ThrowIfNull(schema); + + foreach (var directive in schema.Directives) + { + if (!directive.Name.Equals(FederationDirectiveNames.Link, StringComparison.Ordinal)) + { + continue; + } + + if (!directive.Arguments.TryGetValue("url", out var urlValue) + || urlValue is not StringValueNode urlString) + { + continue; + } + + if (urlString.Value.Contains( + FederationSchemaAnalyzer.FederationUrlPrefix, + StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } + /// /// Transforms the given Apollo Federation v2 subgraph SDL. /// @@ -40,11 +82,13 @@ public static CompositionResult Transform(string federationSdl) string.Format(FederationSchemaTransformer_ParseFailed, ex.Message)); } - var errors = FederationSchemaAnalyzer.Validate(schema); + var log = new CompositionLog(); - if (errors.Count > 0) + if (!FederationSchemaAnalyzer.Validate(schema, log)) { - return errors.ToImmutableArray(); + return log + .Select(entry => new CompositionError(entry.Message)) + .ToImmutableArray(); } RemoveFederationInfrastructure.Apply(schema); @@ -52,6 +96,7 @@ public static CompositionResult Transform(string federationSdl) RewriteKeyDirectives.Apply(schema); TransformRequiresToRequire.Apply(schema); RemoveExternalFields.Apply(schema); + StampConnectorKind.Apply(schema); return SchemaFormatter.FormatAsString(schema); } diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationTypeNames.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationTypeNames.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/FederationTypeNames.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/FederationTypeNames.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/GenerateLookupFields.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/GenerateLookupFields.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/GenerateLookupFields.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/GenerateLookupFields.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/Properties/FederationResources.Designer.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/Properties/FederationResources.Designer.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/Properties/FederationResources.Designer.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/Properties/FederationResources.Designer.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/Properties/FederationResources.resx b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/Properties/FederationResources.resx similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/Properties/FederationResources.resx rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/Properties/FederationResources.resx diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/RemoveExternalFields.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/RemoveExternalFields.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/RemoveExternalFields.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/RemoveExternalFields.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/RemoveFederationInfrastructure.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/RemoveFederationInfrastructure.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/RemoveFederationInfrastructure.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/RemoveFederationInfrastructure.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/RewriteKeyDirectives.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/RewriteKeyDirectives.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/RewriteKeyDirectives.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/RewriteKeyDirectives.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/StampConnectorKind.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/StampConnectorKind.cs new file mode 100644 index 00000000000..a133103f40e --- /dev/null +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/StampConnectorKind.cs @@ -0,0 +1,50 @@ +using HotChocolate.Fusion.Definitions; +using HotChocolate.Language; +using HotChocolate.Types; +using HotChocolate.Types.Mutable; + +namespace HotChocolate.Fusion.ApolloFederation; + +/// +/// Stamps the @fusion__connector(kind: "Apollo") directive onto the source schema +/// so the composer can lift the kind onto the corresponding fusion__Schema enum value +/// in the merged execution schema. +/// +internal static class StampConnectorKind +{ + private const string ApolloKind = "Apollo"; + + /// + /// Applies the connector kind stamp to the schema. Idempotent: the directive + /// definition is registered only when missing, and a duplicate + /// @fusion__connector(kind: "Apollo") instance is not added when one + /// is already present. + /// + /// + /// The mutable schema definition to stamp in place. + /// + public static void Apply(MutableSchemaDefinition schema) + { + if (!schema.DirectiveDefinitions.TryGetDirective( + WellKnownDirectiveNames.FusionConnector, + out var connectorDefinition)) + { + connectorDefinition = new ConnectorMutableDirectiveDefinition(BuiltIns.String.Create()); + schema.DirectiveDefinitions.Add(connectorDefinition); + } + + foreach (var existing in schema.Directives[WellKnownDirectiveNames.FusionConnector]) + { + if (existing.Arguments.TryGetValue(WellKnownArgumentNames.Kind, out var kindValue) + && kindValue is StringValueNode { Value: ApolloKind }) + { + return; + } + } + + schema.Directives.Add( + new Directive( + connectorDefinition, + new ArgumentAssignment(WellKnownArgumentNames.Kind, ApolloKind))); + } +} diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/TransformRequiresToRequire.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/TransformRequiresToRequire.cs similarity index 100% rename from src/HotChocolate/Fusion/src/Fusion.Composition.ApolloFederation/TransformRequiresToRequire.cs rename to src/HotChocolate/Fusion/src/Fusion.Composition/ApolloFederation/TransformRequiresToRequire.cs diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/Definitions/ConnectorMutableDirectiveDefinition.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/Definitions/ConnectorMutableDirectiveDefinition.cs new file mode 100644 index 00000000000..eefda87be9f --- /dev/null +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/Definitions/ConnectorMutableDirectiveDefinition.cs @@ -0,0 +1,28 @@ +using HotChocolate.Types; +using HotChocolate.Types.Mutable; +using static HotChocolate.Fusion.Properties.CompositionResources; +using static HotChocolate.Fusion.WellKnownDirectiveNames; +using argNames = HotChocolate.Fusion.WellKnownArgumentNames; + +namespace HotChocolate.Fusion.Definitions; + +/// +/// The @fusion__connector directive is applied to a source schema definition to declare +/// which connector kind handles that source schema. The composer lifts the directive onto the +/// corresponding fusion__Schema enum value in the merged execution schema. +/// +internal sealed class ConnectorMutableDirectiveDefinition : MutableDirectiveDefinition +{ + public ConnectorMutableDirectiveDefinition(MutableScalarTypeDefinition stringType) + : base(FusionConnector) + { + Description = ConnectorMutableDirectiveDefinition_Description; + + Arguments.Add(new MutableInputFieldDefinition(argNames.Kind, new NonNullType(stringType)) + { + Description = ConnectorMutableDirectiveDefinition_Argument_Kind_Description + }); + + Locations = DirectiveLocation.Schema; + } +} diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/Definitions/FusionConnectorMutableDirectiveDefinition.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/Definitions/FusionConnectorMutableDirectiveDefinition.cs new file mode 100644 index 00000000000..67aec224125 --- /dev/null +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/Definitions/FusionConnectorMutableDirectiveDefinition.cs @@ -0,0 +1,28 @@ +using HotChocolate.Types; +using HotChocolate.Types.Mutable; +using static HotChocolate.Fusion.Properties.CompositionResources; +using static HotChocolate.Fusion.WellKnownDirectiveNames; +using argNames = HotChocolate.Fusion.WellKnownArgumentNames; + +namespace HotChocolate.Fusion.Definitions; + +/// +/// The @fusion__connector directive is applied to a fusion__Schema enum value to +/// declare which connector kind handles the corresponding source schema. The default GraphQL +/// connector treats absent kinds as "GraphQL". +/// +internal sealed class FusionConnectorMutableDirectiveDefinition : MutableDirectiveDefinition +{ + public FusionConnectorMutableDirectiveDefinition(MutableScalarTypeDefinition stringType) + : base(FusionConnector) + { + Description = FusionConnectorMutableDirectiveDefinition_Description; + + Arguments.Add(new MutableInputFieldDefinition(argNames.Kind, new NonNullType(stringType)) + { + Description = FusionConnectorMutableDirectiveDefinition_Argument_Kind_Description + }); + + Locations = DirectiveLocation.EnumValue; + } +} diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/FusionBuiltIns.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/FusionBuiltIns.cs index 8ec9b672e47..168dc2715ed 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition/FusionBuiltIns.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/FusionBuiltIns.cs @@ -18,6 +18,7 @@ internal static class FusionBuiltIns public static FrozenDictionary SourceSchemaDirectives { get; } = new HashSet( [ + new ConnectorMutableDirectiveDefinition(s_stringType), new ExternalMutableDirectiveDefinition(), new InaccessibleMutableDirectiveDefinition(), new InternalMutableDirectiveDefinition(), diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/HotChocolate.Fusion.Composition.csproj b/src/HotChocolate/Fusion/src/Fusion.Composition/HotChocolate.Fusion.Composition.csproj index 0257f090664..cf6b9aae6a8 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition/HotChocolate.Fusion.Composition.csproj +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/HotChocolate.Fusion.Composition.csproj @@ -11,6 +11,7 @@ + @@ -28,6 +29,10 @@ ResXFileCodeGenerator CompositionResources.Designer.cs + + ResXFileCodeGenerator + FederationResources.Designer.cs + @@ -36,6 +41,11 @@ True CompositionResources.resx + + True + True + FederationResources.resx + diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/Logging/LogEntryCodes.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/Logging/LogEntryCodes.cs index 24d8e0aec71..c4786d8b1cf 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition/Logging/LogEntryCodes.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/Logging/LogEntryCodes.cs @@ -21,6 +21,8 @@ public static class LogEntryCodes public const string ExternalRequireCollision = "EXTERNAL_REQUIRE_COLLISION"; public const string ExternalTypeMismatch = "EXTERNAL_TYPE_MISMATCH"; public const string ExternalUnused = "EXTERNAL_UNUSED"; + public const string FederationDirectiveNotSupported = "FEDERATION_DIRECTIVE_NOT_SUPPORTED"; + public const string FederationV1NotSupported = "FEDERATION_V1_NOT_SUPPORTED"; public const string FieldArgumentTypesNotMergeable = "FIELD_ARGUMENT_TYPES_NOT_MERGEABLE"; public const string FieldWithMissingRequiredArgument = "FIELD_WITH_MISSING_REQUIRED_ARGUMENT"; public const string ImplementedByInaccessible = "IMPLEMENTED_BY_INACCESSIBLE"; diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/Properties/CompositionResources.Designer.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/Properties/CompositionResources.Designer.cs index d34e4766422..e5a66425ac2 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition/Properties/CompositionResources.Designer.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/Properties/CompositionResources.Designer.cs @@ -103,7 +103,25 @@ internal static string CompositionLogExtensions_EntryMessageWithSchemaName { return ResourceManager.GetString("CompositionLogExtensions_EntryMessageWithSchemaName", resourceCulture); } } - + + /// + /// Looks up a localized string similar to The kind of connector that backs this source schema.. + /// + internal static string ConnectorMutableDirectiveDefinition_Argument_Kind_Description { + get { + return ResourceManager.GetString("ConnectorMutableDirectiveDefinition_Argument_Kind_Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The @fusion__connector directive declares which connector kind handles this source schema.. + /// + internal static string ConnectorMutableDirectiveDefinition_Description { + get { + return ResourceManager.GetString("ConnectorMutableDirectiveDefinition_Description", resourceCulture); + } + } + /// /// Looks up a localized string similar to The @cost directive must have a 'weight' argument of type String.. /// @@ -176,6 +194,24 @@ internal static string ExternalMutableDirectiveDefinition_Description { } } + /// + /// Looks up a localized string similar to The kind of connector that handles the source schema represented by this enum value.. + /// + internal static string FusionConnectorMutableDirectiveDefinition_Argument_Kind_Description { + get { + return ResourceManager.GetString("FusionConnectorMutableDirectiveDefinition_Argument_Kind_Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The @fusion__connector directive declares which connector kind handles a source schema.. + /// + internal static string FusionConnectorMutableDirectiveDefinition_Description { + get { + return ResourceManager.GetString("FusionConnectorMutableDirectiveDefinition_Description", resourceCulture); + } + } + /// /// Looks up a localized string similar to The name of the source schema that defined the cost metadata.. /// diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/Properties/CompositionResources.resx b/src/HotChocolate/Fusion/src/Fusion.Composition/Properties/CompositionResources.resx index 206ffcea0d6..4f4f86489a0 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition/Properties/CompositionResources.resx +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/Properties/CompositionResources.resx @@ -33,6 +33,12 @@ {0} (Schema: '{1}') + + The kind of connector that backs this source schema. + + + The @fusion__connector directive declares which connector kind handles this source schema. + The @cost directive must have a 'weight' argument of type String. @@ -57,6 +63,12 @@ The @external directive indicates that a field is recognized by the current source schema but is not directly contributed (resolved) by it. + + The kind of connector that handles the source schema represented by this enum value. + + + The @fusion__connector directive declares which connector kind handles a source schema. + The name of the source schema that defined the cost metadata. diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/SourceSchemaMerger.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/SourceSchemaMerger.cs index 8d729996342..0d89e1e78d0 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition/SourceSchemaMerger.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/SourceSchemaMerger.cs @@ -114,6 +114,7 @@ public CompositionResult Merge() if (_options.AddFusionDefinitions) { AddFusionDefinitions(mergedSchema); + LiftConnectorKindOntoEnumValues(mergedSchema); } return mergedSchema; @@ -1529,6 +1530,10 @@ private FrozenDictionary CreateFusionDirecti return new Dictionary { + { + DirectiveNames.FusionConnector, + new FusionConnectorMutableDirectiveDefinition(stringType) + }, { DirectiveNames.FusionCost, new FusionCostMutableDirectiveDefinition(schemaEnumType, stringType) @@ -1611,6 +1616,37 @@ private void AddFusionDefinitions(MutableSchemaDefinition mergedSchema) } } + private void LiftConnectorKindOntoEnumValues(MutableSchemaDefinition mergedSchema) + { + if (!mergedSchema.Types.TryGetType( + TypeNames.FusionSchema, + out var schemaEnum)) + { + return; + } + + var connectorDirective = _fusionDirectiveDefinitions[DirectiveNames.FusionConnector]; + + foreach (var schema in _schemas) + { + if (schema.Directives.FirstOrDefault(DirectiveNames.FusionConnector) is not { } connector + || !connector.Arguments.TryGetValue(ArgumentNames.Kind, out var kindValue) + || kindValue is not StringValueNode kindString + || kindString.Value == "GraphQL") + { + continue; + } + + if (schemaEnum.Values.TryGetValue(_schemaConstantNames[schema.Name], out var enumValue)) + { + enumValue.Directives.Add( + new Directive( + connectorDirective, + new ArgumentAssignment(ArgumentNames.Kind, kindString.Value))); + } + } + } + private ValueSelectionToSelectionSetRewriter GetSelectedValueToSelectionSetRewriter( MutableSchemaDefinition schema) { diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/SourceSchemaPreprocessor.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/SourceSchemaPreprocessor.cs index e46ae94cc46..d7e37f08a20 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition/SourceSchemaPreprocessor.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/SourceSchemaPreprocessor.cs @@ -1,5 +1,6 @@ using System.Collections.Immutable; using System.Text.RegularExpressions; +using HotChocolate.Fusion.ApolloFederation; using HotChocolate.Fusion.Errors; using HotChocolate.Fusion.Extensions; using HotChocolate.Fusion.Language; @@ -31,6 +32,17 @@ public CompositionResult Preprocess() { var fusionV1CompatibilityMode = sourceSchemaVersion?.Major == 1; + if (FederationSchemaTransformer.IsFederationSchema(schema) + && FederationSchemaAnalyzer.Validate(schema, log)) + { + RemoveFederationInfrastructure.Apply(schema); + GenerateLookupFields.Apply(schema); + RewriteKeyDirectives.Apply(schema); + TransformRequiresToRequire.Apply(schema); + RemoveExternalFields.Apply(schema); + StampConnectorKind.Apply(schema); + } + if (_options.ExcludeByTag is { } excludeByTag) { RemoveTaggedMembers(excludeByTag); diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/WellKnownArgumentNames.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/WellKnownArgumentNames.cs index 1365fe71d0f..332bb2e7ac8 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition/WellKnownArgumentNames.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/WellKnownArgumentNames.cs @@ -14,6 +14,7 @@ internal static class WellKnownArgumentNames public const string Interface = "interface"; public const string Internal = "internal"; public const string Key = "key"; + public const string Kind = "kind"; public const string Map = "map"; public const string MaxAge = "maxAge"; public const string Member = "member"; diff --git a/src/HotChocolate/Fusion/src/Fusion.Composition/WellKnownDirectiveNames.cs b/src/HotChocolate/Fusion/src/Fusion.Composition/WellKnownDirectiveNames.cs index cf746ac7cea..05d6e92d1e6 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Composition/WellKnownDirectiveNames.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Composition/WellKnownDirectiveNames.cs @@ -8,6 +8,7 @@ internal static class WellKnownDirectiveNames public const string CacheControl = DirectiveNames.CacheControl.Name; public const string Cost = DirectiveNames.Cost.Name; public const string External = DirectiveNames.External.Name; + public const string FusionConnector = "fusion__connector"; public const string FusionCost = "fusion__cost"; public const string FusionEnumValue = "fusion__enumValue"; public const string FusionField = "fusion__field"; diff --git a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationClientConfigurationParser.cs b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationClientConfigurationParser.cs index 8b8c77ee521..4572a09d839 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationClientConfigurationParser.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationClientConfigurationParser.cs @@ -2,44 +2,48 @@ using System.Text.Json; using HotChocolate.Fusion.Configuration; using HotChocolate.Fusion.Execution.Clients; +using HotChocolate.Fusion.Types; namespace HotChocolate.Fusion.Connectors.ApolloFederation; /// -/// Parser that claims the http transport for source schemas that carry an -/// extensions.apolloFederation block and produces an -/// . +/// Parses source schema settings for Apollo Federation connectors and produces +/// an . /// internal sealed class ApolloFederationClientConfigurationParser : ISourceSchemaClientConfigurationParser { + private const string ApolloKind = "Apollo"; + public bool TryParse( + FusionSchemaDefinition schema, JsonProperty sourceSchema, - JsonProperty transport, - [NotNullWhen(true)] out ISourceSchemaClientConfiguration? configuration) + [NotNullWhen(true)] out ISourceSchemaClientConfiguration[]? configurations) { - if (!sourceSchema.Value.TryGetProperty("extensions", out var extensions) - || extensions.ValueKind != JsonValueKind.Object - || !extensions.TryGetProperty("apolloFederation", out var federation) - || federation.ValueKind != JsonValueKind.Object) + ArgumentNullException.ThrowIfNull(schema); + + var connectorKind = schema.GetSourceSchemaConnectorKind(sourceSchema.Name); + if (!string.Equals(connectorKind, ApolloKind, StringComparison.Ordinal)) { - configuration = null; + configurations = null; return false; } - if (!transport.Name.Equals("http", StringComparison.OrdinalIgnoreCase)) + if (!sourceSchema.Value.TryGetProperty("transports", out var transports) + || transports.ValueKind != JsonValueKind.Object + || !transports.TryGetProperty("http", out var http) + || http.ValueKind != JsonValueKind.Object) { - configuration = null; + configurations = null; return false; } - configuration = CreateConfiguration(sourceSchema.Name, transport.Value, federation); + configurations = [CreateConfiguration(sourceSchema.Name, http)]; return true; } private static ApolloFederationSourceSchemaClientConfiguration CreateConfiguration( string schemaName, - JsonElement http, - JsonElement federation) + JsonElement http) { if (!http.TryGetProperty("url", out var urlProperty) || urlProperty.ValueKind != JsonValueKind.String @@ -58,181 +62,9 @@ private static ApolloFederationSourceSchemaClientConfiguration CreateConfigurati clientName = customClientName; } - var lookups = ParseLookups(schemaName, federation); - var entityRequires = ParseEntityRequires(schemaName, federation); - return new ApolloFederationSourceSchemaClientConfiguration( schemaName, clientName, - new Uri(url), - lookups, - entityRequires); - } - - private static Dictionary ParseLookups( - string schemaName, - JsonElement federation) - { - if (!federation.TryGetProperty("lookups", out var lookupsElement) - || lookupsElement.ValueKind != JsonValueKind.Object) - { - return []; - } - - var lookups = new Dictionary(StringComparer.Ordinal); - - foreach (var lookup in lookupsElement.EnumerateObject()) - { - if (lookup.Value.ValueKind != JsonValueKind.Object) - { - throw new InvalidOperationException( - $"Source schema '{schemaName}' lookup '{lookup.Name}' must be a JSON object."); - } - - if (!lookup.Value.TryGetProperty("entityType", out var entityTypeProperty) - || entityTypeProperty.ValueKind != JsonValueKind.String - || entityTypeProperty.GetString() is not { Length: > 0 } entityType) - { - throw new InvalidOperationException( - $"Source schema '{schemaName}' lookup '{lookup.Name}' is missing an 'entityType' string."); - } - - var argumentToKeyFieldMap = ParseArguments(schemaName, lookup.Name, lookup.Value); - - lookups[lookup.Name] = new LookupFieldInfo - { - EntityTypeName = entityType, - ArgumentToKeyFieldMap = argumentToKeyFieldMap - }; - } - - return lookups; - } - - private static Dictionary ParseEntityRequires( - string schemaName, - JsonElement federation) - { - if (!federation.TryGetProperty("entityTypes", out var entityTypesElement) - || entityTypesElement.ValueKind != JsonValueKind.Object) - { - return []; - } - - var entityRequires = new Dictionary(StringComparer.Ordinal); - - foreach (var entityType in entityTypesElement.EnumerateObject()) - { - if (entityType.Value.ValueKind != JsonValueKind.Object) - { - throw new InvalidOperationException( - $"Source schema '{schemaName}' entity type '{entityType.Name}' must be a JSON object."); - } - - if (!entityType.Value.TryGetProperty("fields", out var fieldsElement) - || fieldsElement.ValueKind != JsonValueKind.Object) - { - continue; - } - - var fields = new Dictionary>(StringComparer.Ordinal); - - foreach (var field in fieldsElement.EnumerateObject()) - { - if (field.Value.ValueKind != JsonValueKind.Object) - { - throw new InvalidOperationException( - $"Source schema '{schemaName}' entity type '{entityType.Name}' " - + $"field '{field.Name}' must be a JSON object."); - } - - if (!field.Value.TryGetProperty("requires", out var requiresElement) - || requiresElement.ValueKind != JsonValueKind.Object) - { - continue; - } - - var requires = new Dictionary(StringComparer.Ordinal); - - foreach (var argument in requiresElement.EnumerateObject()) - { - if (argument.Value.ValueKind != JsonValueKind.String - || argument.Value.GetString() is not { Length: > 0 } path) - { - throw new InvalidOperationException( - $"Source schema '{schemaName}' entity type '{entityType.Name}' " - + $"field '{field.Name}' require argument '{argument.Name}' " - + "must map to a non-empty string representing the field path."); - } - - requires[argument.Name] = path; - } - - if (requires.Count > 0) - { - fields[field.Name] = requires; - } - } - - if (fields.Count > 0) - { - entityRequires[entityType.Name] = new EntityRequiresInfo - { - Fields = fields - }; - } - } - - return entityRequires; - } - - private static Dictionary ParseArguments( - string schemaName, - string lookupName, - JsonElement lookup) - { - if (!lookup.TryGetProperty("arguments", out var argumentsElement) - || argumentsElement.ValueKind != JsonValueKind.Object) - { - return []; - } - - var arguments = new Dictionary(StringComparer.Ordinal); - - foreach (var argument in argumentsElement.EnumerateObject()) - { - arguments[argument.Name] = ReadArgumentPath(schemaName, lookupName, argument); - } - - return arguments; - } - - private static string ReadArgumentPath( - string schemaName, - string lookupName, - JsonProperty argument) - { - switch (argument.Value.ValueKind) - { - case JsonValueKind.String: - // An empty-string path is the "splat" marker that tells the - // connector to spread the variable value's object fields into - // the representation root (used for wrapper-shape arguments on - // nested '@key' lookups). Any other string is a path segment. - return argument.Value.GetString() ?? string.Empty; - - case JsonValueKind.Object: - if (argument.Value.TryGetProperty("path", out var pathProperty) - && pathProperty.ValueKind == JsonValueKind.String) - { - return pathProperty.GetString() ?? string.Empty; - } - - break; - } - - throw new InvalidOperationException( - $"Source schema '{schemaName}' lookup '{lookupName}' argument '{argument.Name}' " - + "must map to a string key field path or an object with a 'path' string property."); + new Uri(url)); } } diff --git a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientConfiguration.cs b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientConfiguration.cs index 0eed66f4900..44039e7eb5f 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientConfiguration.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientConfiguration.cs @@ -1,11 +1,21 @@ +using HotChocolate.Fusion.Types; +using HotChocolate.Fusion.Types.Completion; +using HotChocolate.Fusion.Types.Metadata; + namespace HotChocolate.Fusion.Execution.Clients; /// /// Configuration for an Apollo Federation subgraph source schema client /// that sends queries over HTTP using the _entities protocol. /// -public sealed class ApolloFederationSourceSchemaClientConfiguration : ISourceSchemaClientConfiguration +public sealed class ApolloFederationSourceSchemaClientConfiguration + : ISourceSchemaClientConfiguration + , INeedsCompletion { + private Dictionary _lookups = new(StringComparer.Ordinal); + private Dictionary _entityRequires = new(StringComparer.Ordinal); + private FederationQueryRewriter? _queryRewriter; + /// /// Initializes a new instance of . /// @@ -17,36 +27,20 @@ public sealed class ApolloFederationSourceSchemaClientConfiguration : ISourceSch /// /// The base address of the Apollo Federation subgraph endpoint. /// - /// - /// The lookup field metadata used to rewrite Fusion planner queries into - /// Apollo Federation _entities queries. - /// - /// - /// Per-entity-type metadata describing the @require arguments on - /// each entity field. Enables the rewriter to strip synthetic require - /// arguments from outgoing queries and to inject the bound variable - /// values into the _entities representation body. - /// /// The supported operation types. internal ApolloFederationSourceSchemaClientConfiguration( string name, string httpClientName, Uri baseAddress, - IReadOnlyDictionary lookups, - IReadOnlyDictionary entityRequires, SupportedOperationType supportedOperations = SupportedOperationType.Query | SupportedOperationType.Mutation) { ArgumentException.ThrowIfNullOrEmpty(name); ArgumentException.ThrowIfNullOrEmpty(httpClientName); ArgumentNullException.ThrowIfNull(baseAddress); - ArgumentNullException.ThrowIfNull(lookups); - ArgumentNullException.ThrowIfNull(entityRequires); Name = name; HttpClientName = httpClientName; BaseAddress = baseAddress; - Lookups = lookups; - EntityRequires = entityRequires; SupportedOperations = supportedOperations; } @@ -65,16 +59,124 @@ internal ApolloFederationSourceSchemaClientConfiguration( /// /// Gets the lookup field metadata used to rewrite Fusion planner queries - /// into Apollo Federation _entities queries. + /// into Apollo Federation _entities queries. Populated during schema + /// completion from the runtime metadata on + /// . /// - internal IReadOnlyDictionary Lookups { get; } + internal IReadOnlyDictionary Lookups => _lookups; /// /// Gets the per-entity-type @require argument metadata keyed by - /// entity type name (e.g. "Product"). + /// entity type name (e.g. "Product"). Populated during schema + /// completion from the runtime metadata on + /// . /// - internal IReadOnlyDictionary EntityRequires { get; } + internal IReadOnlyDictionary EntityRequires => _entityRequires; + + /// + /// Gets the per-source-schema that + /// rewrites planner-emitted lookup queries into Apollo Federation + /// _entities queries. Available after schema completion. + /// + internal FederationQueryRewriter QueryRewriter + => _queryRewriter + ?? throw new InvalidOperationException( + $"The query rewriter for source schema '{Name}' is not available before schema completion."); /// public SupportedOperationType SupportedOperations { get; } + + void INeedsCompletion.Complete(FusionSchemaDefinition schema, CompositeSchemaBuilderContext context) + { + var lookups = new Dictionary(StringComparer.Ordinal); + var entityRequires = new Dictionary(StringComparer.Ordinal); + + foreach (var type in schema.Types.AsEnumerable(allowInaccessibleFields: true)) + { + if (type is not FusionObjectTypeDefinition objectType) + { + continue; + } + + if (objectType.Sources.TryGetMember(Name, out var sourceObjectType)) + { + ProjectLookups(sourceObjectType, lookups); + } + + ProjectEntityRequires(objectType, entityRequires); + } + + _lookups = lookups; + _entityRequires = entityRequires; + _queryRewriter = new FederationQueryRewriter(_lookups, _entityRequires); + } + + private static void ProjectLookups( + SourceObjectType sourceObjectType, + Dictionary lookups) + { + foreach (var lookup in sourceObjectType.Lookups) + { + var argumentToKeyFieldMap = new Dictionary(StringComparer.Ordinal); + + for (var i = 0; i < lookup.Arguments.Length; i++) + { + var argument = lookup.Arguments[i]; + var selection = lookup.Fields[i]; + argumentToKeyFieldMap[argument.Name] = LookupArgumentPathMapper.Map(selection); + } + + lookups[lookup.FieldName] = new LookupFieldInfo + { + EntityTypeName = lookup.FieldType.Name, + ArgumentToKeyFieldMap = argumentToKeyFieldMap + }; + } + } + + private void ProjectEntityRequires( + FusionObjectTypeDefinition objectType, + Dictionary entityRequires) + { + Dictionary>? fieldMap = null; + + foreach (var field in objectType.Fields.AsEnumerable(allowInaccessibleFields: true)) + { + if (!field.Sources.TryGetMember(Name, out var sourceField) + || sourceField.Requirements is null) + { + continue; + } + + var requirements = sourceField.Requirements; + var requires = new Dictionary(StringComparer.Ordinal); + + for (var i = 0; i < requirements.Arguments.Length; i++) + { + var argument = requirements.Arguments[i]; + var selection = requirements.Fields[i]; + + if (selection is null) + { + continue; + } + + requires[argument.Name] = LookupArgumentPathMapper.Map(selection); + } + + if (requires.Count > 0) + { + fieldMap ??= new Dictionary>(StringComparer.Ordinal); + fieldMap[field.Name] = requires; + } + } + + if (fieldMap is { Count: > 0 }) + { + entityRequires[objectType.Name] = new EntityRequiresInfo + { + Fields = fieldMap + }; + } + } } diff --git a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientFactory.cs b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientFactory.cs index 80f0d8e6410..c56b25e6875 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientFactory.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/ApolloFederationSourceSchemaClientFactory.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using HotChocolate.Fusion.Transport.Http; using HotChocolate.Fusion.Types; @@ -12,7 +11,6 @@ public sealed class ApolloFederationSourceSchemaClientFactory : SourceSchemaClientFactory { private readonly IHttpClientFactory _httpClientFactory; - private readonly ConcurrentDictionary _rewritersBySchema = new(); /// /// Initializes a new instance of . @@ -33,12 +31,7 @@ protected override ISourceSchemaClient CreateClient( var httpClient = _httpClientFactory.CreateClient(configuration.HttpClientName); httpClient.BaseAddress = configuration.BaseAddress; - var queryRewriter = _rewritersBySchema.GetOrAdd( - configuration.Name, - static (_, config) => new FederationQueryRewriter(config.Lookups, config.EntityRequires), - configuration); - var graphQLClient = GraphQLHttpClient.Create(httpClient, disposeHttpClient: true); - return new ApolloFederationSourceSchemaClient(graphQLClient, queryRewriter); + return new ApolloFederationSourceSchemaClient(graphQLClient, configuration.QueryRewriter); } } diff --git a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/DependencyInjection/ApolloFederationFusionGatewayBuilderExtensions.cs b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/DependencyInjection/ApolloFederationFusionGatewayBuilderExtensions.cs index 4eff3b95ca9..c4110fb20f0 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/DependencyInjection/ApolloFederationFusionGatewayBuilderExtensions.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/DependencyInjection/ApolloFederationFusionGatewayBuilderExtensions.cs @@ -12,9 +12,7 @@ namespace Microsoft.Extensions.DependencyInjection; public static class ApolloFederationFusionGatewayBuilderExtensions { /// - /// Adds Apollo Federation support to the Fusion gateway. Source schemas whose - /// settings carry an extensions.apolloFederation block will be served by - /// the Apollo Federation _entities connector. + /// Adds Apollo Federation support to the Fusion gateway. /// /// The Fusion gateway builder. /// The Fusion gateway builder for chaining. diff --git a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/HotChocolate.Fusion.Connectors.ApolloFederation.csproj b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/HotChocolate.Fusion.Connectors.ApolloFederation.csproj index b74701e94e7..6b081aa11a2 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/HotChocolate.Fusion.Connectors.ApolloFederation.csproj +++ b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/HotChocolate.Fusion.Connectors.ApolloFederation.csproj @@ -13,7 +13,6 @@ - diff --git a/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/LookupArgumentPathMapper.cs b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/LookupArgumentPathMapper.cs new file mode 100644 index 00000000000..4313dd45aad --- /dev/null +++ b/src/HotChocolate/Fusion/src/Fusion.Connectors.ApolloFederation/LookupArgumentPathMapper.cs @@ -0,0 +1,26 @@ +using HotChocolate.Fusion.Language; + +namespace HotChocolate.Fusion.Execution.Clients; + +/// +/// Maps a lookup argument's selection to the representation field it binds to. +/// An empty result indicates that the argument's value is itself shaped like +/// the representation and should be merged at its root. +/// +internal static class LookupArgumentPathMapper +{ + public static string Map(IValueSelectionNode selection) + { + ArgumentNullException.ThrowIfNull(selection); + + return selection switch + { + ObjectValueSelectionNode => string.Empty, + PathNode path => path.PathSegment.FieldName.Value, + PathObjectValueSelectionNode pathObject => pathObject.Path.PathSegment.FieldName.Value, + PathListValueSelectionNode pathList => pathList.Path.PathSegment.FieldName.Value, + _ => throw new InvalidOperationException( + $"Unsupported lookup-argument selection node '{selection.GetType().Name}'.") + }; + } +} diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/Completion/CompositeSchemaBuilder.cs b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/Completion/CompositeSchemaBuilder.cs index cdff19dd49f..4662e76d565 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/Completion/CompositeSchemaBuilder.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/Completion/CompositeSchemaBuilder.cs @@ -170,6 +170,8 @@ private static CompositeSchemaBuilderContext CreateTypes( features ??= new FeatureCollection(); + var sourceSchemaLookup = CreateSourceSchemaLookup(schemaDocument); + return new CompositeSchemaBuilderContext( schemaDocument, name, @@ -183,7 +185,7 @@ private static CompositeSchemaBuilderContext CreateTypes( typeDefinitions.ToImmutable(), directiveTypes.ToImmutable(), directiveDefinitions.ToImmutable(), - CreateSourceSchemaLookup(schemaDocument), + sourceSchemaLookup, features, typeInterceptor); } @@ -605,7 +607,8 @@ context.SubscriptionType is not null directives, new FusionTypeDefinitionCollection(AsArray(context.TypeDefinitions)!), new FusionDirectiveDefinitionCollection(AsArray(context.DirectiveDefinitions)!), - features); + features, + context.SourceSchemaLookup); context.Interceptor.OnAfterCompleteSchema(context, schema); schema.Seal(); @@ -1057,9 +1060,18 @@ private static ImmutableDictionary CreateSourceSchemaL $"An executable schema must specify the `{FusionBuiltIns.Schema}` type."); } - return sourceSchemaDefinition.Values - .Select(sourceSchema => new SourceSchemaInfo(sourceSchema.Name.Value, GetSchemaName(sourceSchema))) - .ToImmutableDictionary(sourceSchemaInfo => sourceSchemaInfo.Key); + var sourceSchemaBuilder = ImmutableDictionary.CreateBuilder(); + + foreach (var sourceSchema in sourceSchemaDefinition.Values) + { + var schemaName = GetSchemaName(sourceSchema); + var connectorKind = GetConnectorKind(sourceSchema); + sourceSchemaBuilder.Add( + sourceSchema.Name.Value, + new SourceSchemaInfo(sourceSchema.Name.Value, schemaName, connectorKind)); + } + + return sourceSchemaBuilder.ToImmutable(); static string GetSchemaName(EnumValueDefinitionNode sourceSchema) { @@ -1068,6 +1080,14 @@ static string GetSchemaName(EnumValueDefinitionNode sourceSchema) var nameArg = directive?.Arguments.FirstOrDefault(t => t.Name.Value.Equals("name")); return nameArg?.Value is StringValueNode nameValue ? nameValue.Value : sourceSchema.Name.Value; } + + static string? GetConnectorKind(EnumValueDefinitionNode sourceSchema) + { + var directive = sourceSchema.Directives.FirstOrDefault(t => + t.Name.Value.Equals(FusionBuiltIns.Connector, StringComparison.Ordinal)); + var kindArg = directive?.Arguments.FirstOrDefault(t => t.Name.Value.Equals("kind")); + return kindArg?.Value is StringValueNode kindValue ? kindValue.Value : null; + } } private sealed class EmptyServiceProvider : IServiceProvider diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/FusionBuiltIns.cs b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/FusionBuiltIns.cs index ad6c2b1e256..24e064a4066 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/FusionBuiltIns.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/FusionBuiltIns.cs @@ -11,6 +11,7 @@ internal static class FusionBuiltIns public const string Schema = "fusion__Schema"; public const string Type = "fusion__type"; + public const string Connector = "fusion__connector"; public const string Field = "fusion__field"; public const string InputField = "fusion__inputField"; public const string Requires = "fusion__requires"; diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/FusionSchemaDefinition.cs b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/FusionSchemaDefinition.cs index cff3fdf5f1d..0213b7a828a 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/FusionSchemaDefinition.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/FusionSchemaDefinition.cs @@ -22,6 +22,7 @@ public sealed class FusionSchemaDefinition : ISchemaDefinition, IAsyncDisposable private readonly ConcurrentDictionary> _possibleTypes = new(); private readonly ConcurrentDictionary<(string, string?), ImmutableArray> _possibleLookups = new(); private readonly IServiceProvider _services; + private readonly ImmutableDictionary _sourceSchemaLookup; private PlannerTopologyCache? _plannerTopologyCache; private ImmutableArray _unionTypes; private IFeatureCollection _features; @@ -38,7 +39,8 @@ internal FusionSchemaDefinition( FusionDirectiveCollection directives, FusionTypeDefinitionCollection types, FusionDirectiveDefinitionCollection directiveDefinitions, - IFeatureCollection features) + IFeatureCollection features, + ImmutableDictionary sourceSchemaLookup) { Name = name; Description = description; @@ -50,6 +52,7 @@ internal FusionSchemaDefinition( Types = types; DirectiveDefinitions = directiveDefinitions; _features = features; + _sourceSchemaLookup = sourceSchemaLookup; } public static FusionSchemaDefinition Create( @@ -136,6 +139,32 @@ IReadOnlyDirectiveDefinitionCollection ISchemaDefinition.DirectiveDefinitions public IFeatureCollection Features => _features; + /// + /// Gets the connector kind declared by the specified source schema. + /// + /// The source schema name. + /// + /// The connector kind (for example "Apollo") declared via + /// @fusion__connector(kind:) on the corresponding fusion__Schema + /// enum value, or if the source schema has no + /// connector kind associated with it. Callers that want to default + /// treat as "GraphQL". + /// + public string? GetSourceSchemaConnectorKind(string sourceSchemaName) + { + ArgumentException.ThrowIfNullOrEmpty(sourceSchemaName); + + foreach (var info in _sourceSchemaLookup.Values) + { + if (string.Equals(info.Name, sourceSchemaName, StringComparison.Ordinal)) + { + return info.ConnectorKind; + } + } + + return null; + } + public FusionObjectTypeDefinition GetOperationType(OperationType operation) { var type = operation switch diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/HotChocolate.Fusion.Execution.Types.csproj b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/HotChocolate.Fusion.Execution.Types.csproj index 7caddae3908..e251ea38f8e 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/HotChocolate.Fusion.Execution.Types.csproj +++ b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/HotChocolate.Fusion.Execution.Types.csproj @@ -8,6 +8,7 @@ + diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/Metadata/SourceSchemaInfo.cs b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/Metadata/SourceSchemaInfo.cs index 0dee9546cb2..5cb86f37798 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution.Types/Metadata/SourceSchemaInfo.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution.Types/Metadata/SourceSchemaInfo.cs @@ -1,3 +1,3 @@ namespace HotChocolate.Fusion.Types.Metadata; -public sealed record SourceSchemaInfo(string Key, string Name); +public sealed record SourceSchemaInfo(string Key, string Name, string? ConnectorKind); diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/ISourceSchemaClientConfigurationParser.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/ISourceSchemaClientConfigurationParser.cs index e57e1c0215a..503ef4efda8 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/ISourceSchemaClientConfigurationParser.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/ISourceSchemaClientConfigurationParser.cs @@ -1,37 +1,40 @@ using System.Diagnostics.CodeAnalysis; using System.Text.Json; using HotChocolate.Fusion.Execution.Clients; +using HotChocolate.Fusion.Types; namespace HotChocolate.Fusion.Configuration; /// -/// Parses a source-schema settings element into an . +/// Parses a source-schema settings element into one or more +/// instances. /// public interface ISourceSchemaClientConfigurationParser { /// - /// Attempts to build a configuration for the specified source schema and transport. + /// Attempts to claim a source schema and produce its client configurations. /// + /// + /// The completed . Parsers consult + /// to decide whether + /// to claim the source schema. + /// /// /// The source-schema JSON property. sourceSchema.Name is the schema name; - /// sourceSchema.Value is the per-schema settings object (including transports - /// and optional extensions). - /// - /// - /// The specific transport JSON property currently being offered. transport.Name is the - /// transport kind ("http", "websockets", ...) and transport.Value is the - /// transport element. + /// sourceSchema.Value is the per-schema settings object (including transports). /// - /// + /// /// When this method returns , contains the parsed - /// ; otherwise, . + /// instances; otherwise, . + /// A parser may return multiple configurations for one source schema (for example one for + /// HTTP and one for WebSocket). /// /// - /// if the parser claimed the transport and produced a configuration; + /// if the parser claimed the source schema and produced configurations; /// otherwise, . /// bool TryParse( + FusionSchemaDefinition schema, JsonProperty sourceSchema, - JsonProperty transport, - [NotNullWhen(true)] out ISourceSchemaClientConfiguration? configuration); + [NotNullWhen(true)] out ISourceSchemaClientConfiguration[]? configurations); } diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/Parsers/HttpSourceSchemaClientConfigurationParser.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/Parsers/DefaultGraphQLClientConfigurationParser.cs similarity index 85% rename from src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/Parsers/HttpSourceSchemaClientConfigurationParser.cs rename to src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/Parsers/DefaultGraphQLClientConfigurationParser.cs index 6834861d732..fa06e60c7dc 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/Parsers/HttpSourceSchemaClientConfigurationParser.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Configuration/Parsers/DefaultGraphQLClientConfigurationParser.cs @@ -3,28 +3,33 @@ using System.Net.Http.Headers; using System.Text.Json; using HotChocolate.Fusion.Execution.Clients; +using HotChocolate.Fusion.Types; namespace HotChocolate.Fusion.Configuration.Parsers; /// -/// Built-in parser that claims the http transport and produces a -/// . +/// Built-in fallback parser that produces a default +/// from a source schema's +/// transports.http block. /// -internal sealed class HttpSourceSchemaClientConfigurationParser : ISourceSchemaClientConfigurationParser +internal sealed class DefaultGraphQLClientConfigurationParser : ISourceSchemaClientConfigurationParser { public bool TryParse( + FusionSchemaDefinition schema, JsonProperty sourceSchema, - JsonProperty transport, - [NotNullWhen(true)] out ISourceSchemaClientConfiguration? configuration) + [NotNullWhen(true)] out ISourceSchemaClientConfiguration[]? configurations) { - if (transport.Name.Equals("http", StringComparison.OrdinalIgnoreCase)) + if (!sourceSchema.Value.TryGetProperty("transports", out var transports) + || transports.ValueKind != JsonValueKind.Object + || !transports.TryGetProperty("http", out var http) + || http.ValueKind != JsonValueKind.Object) { - configuration = CreateHttpClientConfiguration(sourceSchema.Name, transport.Value); - return true; + configurations = null; + return false; } - configuration = null; - return false; + configurations = [CreateHttpClientConfiguration(sourceSchema.Name, http)]; + return true; } private static SourceSchemaHttpClientConfiguration CreateHttpClientConfiguration( diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionOptions.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionOptions.cs index 89b065b36ac..403b49e9c28 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionOptions.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionOptions.cs @@ -197,7 +197,7 @@ public bool EnableSemanticIntrospection field = value; } - } + } = true; /// /// Clones the options into a new mutable instance. diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionRequestExecutorManager.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionRequestExecutorManager.cs index 1a6870ca865..c42ba9e5f10 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionRequestExecutorManager.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionRequestExecutorManager.cs @@ -41,8 +41,6 @@ internal sealed class FusionRequestExecutorManager private readonly IOptionsMonitor _optionsMonitor; private readonly EventObservable _events = new(); private readonly IServiceProvider _applicationServices; - private readonly ImmutableArray _builtInParsers = - [new HttpSourceSchemaClientConfigurationParser()]; private bool _disposed; private ulong _version; @@ -151,7 +149,10 @@ private async ValueTask CreateInitialRegistrationAs var setup = _optionsMonitor.Get(schemaName); var (configuration, documentProvider) = - await GetSchemaDocumentAsync(setup.DocumentProvider, cancellationToken).ConfigureAwait(false); + await GetSchemaDocumentAsync( + setup.DocumentProvider, + cancellationToken) + .ConfigureAwait(false); var executor = CreateRequestExecutor(schemaName, configuration); @@ -182,14 +183,12 @@ private FusionRequestExecutor CreateRequestExecutor( var requestOptions = CreateRequestOptions(setup); var plannerOptions = CreatePlannerOptions(setup, options); var parserOptions = CreateParserOptions(setup); - var clientConfigurations = CreateClientConfigurations(setup, configuration.Settings.Document); var features = CreateSchemaFeatures( setup, options, requestOptions, - parserOptions, - clientConfigurations); - var schemaServices = CreateSchemaServices(setup, options, requestOptions, plannerOptions); + parserOptions); + var schemaServices = CreateSchemaServices(configuration, setup, options, requestOptions, plannerOptions); var schema = CreateSchema(schemaName, configuration.Schema, schemaServices, features); var pipeline = CreatePipeline(setup, schema, schemaServices, requestOptions); @@ -202,7 +201,7 @@ private FusionRequestExecutor CreateRequestExecutor( return executor; } - private async Task WarmupExecutorAsync( + private static async Task WarmupExecutorAsync( IRequestExecutor executor, bool isInitialCreation, CancellationToken cancellationToken) @@ -303,80 +302,11 @@ private static ParserOptions CreateParserOptions(FusionGatewaySetup setup) maxAllowedRecursionDepth: options.MaxAllowedRecursionDepth); } - private SourceSchemaClientConfigurations CreateClientConfigurations( - FusionGatewaySetup setup, - JsonDocument settings) - { - var configurations = new List(); - - if (settings.RootElement.TryGetProperty("sourceSchemas", out var sourceSchemas)) - { - foreach (var sourceSchema in sourceSchemas.EnumerateObject()) - { - if (!sourceSchema.Value.TryGetProperty("transports", out var transports)) - { - throw new InvalidOperationException( - $"Source schema '{sourceSchema.Name}' has no 'transports' section."); - } - - var anyConfig = false; - foreach (var transport in transports.EnumerateObject()) - { - if (TryParseTransport(sourceSchema, transport, setup, out var config)) - { - configurations.Add(config); - anyConfig = true; - } - } - - if (!anyConfig) - { - throw new InvalidOperationException( - $"No parser claimed any transport for source schema '{sourceSchema.Name}'."); - } - } - } - - foreach (var configure in setup.ClientConfigurationModifiers) - { - configurations.Add(configure.Invoke(_applicationServices)); - } - - return new SourceSchemaClientConfigurations(configurations); - } - - private bool TryParseTransport( - JsonProperty sourceSchema, - JsonProperty transport, - FusionGatewaySetup setup, - [NotNullWhen(true)] out ISourceSchemaClientConfiguration? configuration) - { - foreach (var parser in setup.SourceSchemaClientConfigurationParsers) - { - if (parser.TryParse(sourceSchema, transport, out configuration)) - { - return true; - } - } - - foreach (var parser in _builtInParsers) - { - if (parser.TryParse(sourceSchema, transport, out configuration)) - { - return true; - } - } - - configuration = null; - return false; - } - private FeatureCollection CreateSchemaFeatures( FusionGatewaySetup setup, FusionOptions options, FusionRequestOptions requestOptions, - ParserOptions parserOptions, - SourceSchemaClientConfigurations clientConfigurations) + ParserOptions parserOptions) { var features = new FeatureCollection(); @@ -385,7 +315,6 @@ private FeatureCollection CreateSchemaFeatures( features.Set(requestOptions); features.Set(requestOptions.PersistedOperations); features.Set(parserOptions); - features.Set(clientConfigurations); features.Set(CreateTypeResolverInterceptors(options)); features.Set(new SchemaCancellationFeature()); @@ -420,6 +349,7 @@ private static Dictionary CreateTypeResolverIn } private ServiceProvider CreateSchemaServices( + FusionConfiguration configuration, FusionGatewaySetup setup, FusionOptions options, FusionRequestOptions requestOptions, @@ -427,7 +357,12 @@ private ServiceProvider CreateSchemaServices( { var schemaServices = new ServiceCollection(); - AddCoreServices(schemaServices, options, requestOptions); + AddCoreServices( + configuration.Settings.Document.RootElement.Clone(), + setup, + schemaServices, + options, + requestOptions); AddOperationPlanner(schemaServices, plannerOptions); AddParserServices(schemaServices); AddDocumentValidator(setup, schemaServices); @@ -442,6 +377,8 @@ private ServiceProvider CreateSchemaServices( } private void AddCoreServices( + JsonElement settings, + FusionGatewaySetup setup, IServiceCollection services, FusionOptions options, FusionRequestOptions requestOptions) @@ -488,6 +425,11 @@ private void AddCoreServices( static sp => sp.GetRequiredService().CreateStringBuilderPool()); services.AddTransient(static _ => new IntrospectionFieldInterceptor()); + services.AddTransient( + sp => new SchemaConfigurationInterceptor( + sp.GetRequiredService().ServiceProvider, + setup, + settings)); } private static void AddOperationPlanner( @@ -659,6 +601,7 @@ private sealed class RequestExecutorRegistration : IAsyncDisposable private readonly FusionRequestExecutorManager _manager; private readonly IDisposable _documentProviderSubscription; + private FusionConfiguration _currentConfiguration; private ulong _documentHash; private ulong _settingsHash; private bool _disposed; @@ -672,6 +615,7 @@ public RequestExecutorRegistration( { _manager = manager; _cancellationToken = _cancellationTokenSource.Token; + _currentConfiguration = configuration; _documentHash = XxHash64.HashToUInt64(Encoding.UTF8.GetBytes(configuration.Schema.ToString())); _settingsHash = XxHash64.HashToUInt64(GetRawUtf8Value(configuration.Settings.Document.RootElement)); @@ -699,6 +643,7 @@ private async Task WaitForUpdatesAsync() { if (_cancellationToken.IsCancellationRequested) { + configuration.Dispose(); break; } @@ -707,6 +652,7 @@ private async Task WaitForUpdatesAsync() if (documentHash == _documentHash && settingsHash == _settingsHash) { + configuration.Dispose(); continue; } @@ -714,11 +660,13 @@ private async Task WaitForUpdatesAsync() _settingsHash = settingsHash; var previousExecutor = Executor; + var previousConfiguration = _currentConfiguration; var nextExecutor = _manager.CreateRequestExecutor(Executor.Schema.Name, configuration); - await _manager.WarmupExecutorAsync(nextExecutor, false, _cancellationToken).ConfigureAwait(false); + await WarmupExecutorAsync(nextExecutor, false, _cancellationToken).ConfigureAwait(false); Executor = nextExecutor; + _currentConfiguration = configuration; DiagnosticEvents.ExecutorCreated(nextExecutor.Schema.Name, nextExecutor); @@ -726,7 +674,7 @@ private async Task WaitForUpdatesAsync() _manager.EvictExecutor(previousExecutor, DiagnosticEvents); - configuration.Dispose(); + previousConfiguration.Dispose(); } } @@ -754,6 +702,8 @@ public async ValueTask DisposeAsync() configuration.Dispose(); } + _currentConfiguration.Dispose(); + await Executor.DisposeAsync(); } } @@ -886,4 +836,94 @@ public IError OnError(IError error) } } } + + private sealed class SchemaConfigurationInterceptor( + IServiceProvider applicationServices, + FusionGatewaySetup setup, + JsonElement settings) + : CompositeTypeInterceptor + { + private readonly ImmutableArray _builtInParsers = + [new HttpSourceSchemaClientConfigurationParser()]; + + public override void OnAfterCompleteSchema( + ICompositeSchemaBuilderContext context, + FusionSchemaDefinition schema) + { + var clientConfigurations = CreateClientConfigurations( + (CompositeSchemaBuilderContext)context, + schema, + setup, + settings); + schema.Features.Set(clientConfigurations); + } + + private SourceSchemaClientConfigurations CreateClientConfigurations( + CompositeSchemaBuilderContext context, + FusionSchemaDefinition schema, + FusionGatewaySetup setup, + JsonElement settings) + { + var configurations = new List(); + + if (settings.TryGetProperty("sourceSchemas", out var sourceSchemas)) + { + foreach (var sourceSchema in sourceSchemas.EnumerateObject()) + { + if (!TryClaimSourceSchema(schema, sourceSchema, setup, out var sourceConfigurations)) + { + throw new InvalidOperationException( + $"No parser claimed source schema '{sourceSchema.Name}'."); + } + + configurations.AddRange(sourceConfigurations); + } + } + + foreach (var configure in setup.ClientConfigurationModifiers) + { + configurations.Add(configure.Invoke(applicationServices)); + } + + // Register configurations that need post-Seal projection. The + // per-type completions (Lookup.FieldType, FieldRequirements.Requirements) + // were registered earlier during type completion; appending here + // ensures connector-level projection runs after them. + foreach (var configuration in configurations) + { + if (configuration is INeedsCompletion needsCompletion) + { + context.RegisterForCompletion(needsCompletion); + } + } + + return new SourceSchemaClientConfigurations(configurations); + } + + private bool TryClaimSourceSchema( + FusionSchemaDefinition schema, + JsonProperty sourceSchema, + FusionGatewaySetup setup, + [NotNullWhen(true)] out ISourceSchemaClientConfiguration[]? configurations) + { + foreach (var parser in setup.SourceSchemaClientConfigurationParsers) + { + if (parser.TryParse(schema, sourceSchema, out configurations)) + { + return true; + } + } + + foreach (var parser in _builtInParsers) + { + if (parser.TryParse(schema, sourceSchema, out configurations)) + { + return true; + } + } + + configurations = null; + return false; + } + } } diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/HotChocolate.Fusion.Composition.ApolloFederation.Tests.csproj b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/HotChocolate.Fusion.Composition.ApolloFederation.Tests.csproj index 1d60935f928..bbe7fd11b6c 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/HotChocolate.Fusion.Composition.ApolloFederation.Tests.csproj +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/HotChocolate.Fusion.Composition.ApolloFederation.Tests.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_CompositeKey.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_CompositeKey.md index 6403323baa7..f423506f7fe 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_CompositeKey.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_CompositeKey.md @@ -33,7 +33,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -49,4 +49,10 @@ type Product @key(fields: "sku package") { package: String! sku: String! } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_DeeplyNestedListKey.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_DeeplyNestedListKey.md index 28a48704d0c..622e4616224 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_DeeplyNestedListKey.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_DeeplyNestedListKey.md @@ -46,7 +46,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -108,4 +108,10 @@ input ProductListByProductsAndIdAndPidAndCategoryAndIdAndTagAndSelectedAndIdInpu input ProductListByProductsAndIdAndPidAndCategoryAndIdAndTagAndSelectedAndIdInput_Selected { id: String! } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_ExternalDirective.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_ExternalDirective.md index d1f5508f680..f1697d1b4d8 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_ExternalDirective.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_ExternalDirective.md @@ -33,7 +33,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -45,4 +45,10 @@ type Query { type Product @key(fields: "id") { id: ID! } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_FullIntegration.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_FullIntegration.md index 7d5f9a47923..9dffd29e1f8 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_FullIntegration.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_FullIntegration.md @@ -53,7 +53,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -87,4 +87,10 @@ type User @key(fields: "id") { id: ID! totalProductsCreated: Int } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_KeyResolvableArgument.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_KeyResolvableArgument.md index 010ebd25b0f..c063bf5e766 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_KeyResolvableArgument.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_KeyResolvableArgument.md @@ -32,7 +32,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -45,4 +45,10 @@ type Product @key(fields: "id") { id: ID! name: String } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_MultipleKeys.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_MultipleKeys.md index 6c3cb64850a..0f9a0a13a58 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_MultipleKeys.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_MultipleKeys.md @@ -34,7 +34,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -52,4 +52,10 @@ type Product @key(fields: "id") @key(fields: "sku package") { package: String! sku: String! } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NestedListKey.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NestedListKey.md index 00ebde534e9..c136487dfff 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NestedListKey.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NestedListKey.md @@ -35,7 +35,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -62,4 +62,10 @@ input ProductListByProductsAndIdInput { input ProductListByProductsAndIdInput_Products { id: ID! } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NestedObjectKey.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NestedObjectKey.md index c0b3758d232..df864c4bef3 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NestedObjectKey.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NestedObjectKey.md @@ -37,7 +37,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -65,4 +65,10 @@ input ArticleByMetadataAndIdInput { input ArticleByMetadataAndIdInput_Metadata { id: ID! } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NonResolvableAndResolvableKeys.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NonResolvableAndResolvableKeys.md index da6b41838e1..b0cdf494d0a 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NonResolvableAndResolvableKeys.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NonResolvableAndResolvableKeys.md @@ -33,7 +33,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -47,4 +47,10 @@ type Product @key(fields: "id") @key(fields: "sku") { name: String sku: String! } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NonResolvableKey.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NonResolvableKey.md index f836ee812ba..f9719daec5a 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NonResolvableKey.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_NonResolvableKey.md @@ -32,7 +32,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -44,4 +44,10 @@ type Product @key(fields: "id") { id: ID! name: String } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_ProvidesDirective.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_ProvidesDirective.md index baa308ca522..35c9ffa0f6e 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_ProvidesDirective.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_ProvidesDirective.md @@ -39,7 +39,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -58,4 +58,10 @@ type User @key(fields: "id") { totalProductsCreated: Int username: String } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_RequiresDirective.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_RequiresDirective.md index 88eff946e4d..695fcf9d8fa 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_RequiresDirective.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_RequiresDirective.md @@ -36,7 +36,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -52,4 +52,10 @@ type Product @key(fields: "id") { weight: Float @require(field: "weight") ): Float } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_SimpleEntity.md b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_SimpleEntity.md index bf850ccd926..cc6b920ccb0 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_SimpleEntity.md +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.ApolloFederation.Tests/__snapshots__/FederationSchemaTransformerTests.Transform_SimpleEntity.md @@ -32,7 +32,7 @@ directive @link(url: String! import: [String!]) repeatable on SCHEMA ## Transformed SDL ```graphql -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -45,4 +45,10 @@ type Product @key(fields: "id") { id: ID! name: String } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA ``` diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.Tests/SourceSchemaMerger.ConnectorDirective.Tests.cs b/src/HotChocolate/Fusion/test/Fusion.Composition.Tests/SourceSchemaMerger.ConnectorDirective.Tests.cs new file mode 100644 index 00000000000..bd0fd952285 --- /dev/null +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.Tests/SourceSchemaMerger.ConnectorDirective.Tests.cs @@ -0,0 +1,136 @@ +using System.Collections.Immutable; +using HotChocolate.Fusion.Comparers; +using HotChocolate.Fusion.Logging; +using HotChocolate.Language; +using HotChocolate.Types.Mutable; + +namespace HotChocolate.Fusion; + +public sealed class SourceSchemaMergerConnectorDirectiveTests +{ + [Fact] + public void Merge_Should_LiftConnectorKind_OntoEnumValue_When_DirectivePresent() + { + // arrange + var sourceSchemaText = + new SourceSchemaText( + "Products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productById(id: ID!): Product @lookup + } + + type Product @key(fields: "id") { + id: ID! + } + """); + var compositionLog = new CompositionLog(); + var sourceSchemaParser = new SourceSchemaParser(sourceSchemaText, compositionLog); + var schema = sourceSchemaParser.Parse().Value; + var schemas = ImmutableSortedSet.Create( + new SchemaByNameComparer(), schema); + new SourceSchemaEnricher(schema, schemas).Enrich(); + var merger = new SourceSchemaMerger(schemas); + + // act + var result = merger.Merge(); + + // assert + Assert.True(result.IsSuccess); + Assert.Equal("Apollo", GetConnectorKind(result.Value, "PRODUCTS")); + } + + [Fact] + public void Merge_Should_OmitConnectorDirective_When_DirectiveAbsent() + { + // arrange + var sourceSchemaText = + new SourceSchemaText( + "Catalog", + """ + type Query { + ping: String + } + """); + var compositionLog = new CompositionLog(); + var sourceSchemaParser = new SourceSchemaParser(sourceSchemaText, compositionLog); + var schema = sourceSchemaParser.Parse().Value; + var schemas = ImmutableSortedSet.Create( + new SchemaByNameComparer(), schema); + new SourceSchemaEnricher(schema, schemas).Enrich(); + var merger = new SourceSchemaMerger(schemas); + + // act + var result = merger.Merge(); + + // assert + Assert.True(result.IsSuccess); + Assert.Null(GetConnectorDirective(result.Value, "CATALOG")); + } + + [Fact] + public void Merge_Should_LiftPerSchemaConnectorKind_When_MixedSources() + { + // arrange + var apolloSource = new SourceSchemaText( + "Reviews", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + reviewById(id: ID!): Review @lookup + } + + type Review @key(fields: "id") { + id: ID! + } + """); + var graphqlSource = new SourceSchemaText( + "Catalog", + """ + type Query { + ping: String + } + """); + var compositionLog = new CompositionLog(); + var schemaA = new SourceSchemaParser(apolloSource, compositionLog).Parse().Value; + var schemaB = new SourceSchemaParser(graphqlSource, compositionLog).Parse().Value; + var schemas = ImmutableSortedSet.Create( + new SchemaByNameComparer(), schemaA, schemaB); + new SourceSchemaEnricher(schemaA, schemas).Enrich(); + new SourceSchemaEnricher(schemaB, schemas).Enrich(); + var merger = new SourceSchemaMerger(schemas); + + // act + var result = merger.Merge(); + + // assert + Assert.True(result.IsSuccess); + Assert.Equal("Apollo", GetConnectorKind(result.Value, "REVIEWS")); + Assert.Null(GetConnectorDirective(result.Value, "CATALOG")); + } + + private static string GetConnectorKind(MutableSchemaDefinition mergedSchema, string valueName) + { + var directive = GetConnectorDirective(mergedSchema, valueName); + Assert.NotNull(directive); + Assert.True(directive.Arguments.TryGetValue("kind", out var kindValue)); + return Assert.IsType(kindValue).Value; + } + + private static Directive? GetConnectorDirective( + MutableSchemaDefinition mergedSchema, + string valueName) + { + var schemaEnum = Assert.IsAssignableFrom( + mergedSchema.Types["fusion__Schema"]); + Assert.True(schemaEnum.Values.TryGetValue(valueName, out var enumValue)); + return enumValue.Directives.FirstOrDefault("fusion__connector"); + } +} diff --git a/src/HotChocolate/Fusion/test/Fusion.Composition.Tests/__snapshots__/SourceSchemaMergerTests.Merge_FourNamedSchemas_AddsFusionDefinitions.graphql b/src/HotChocolate/Fusion/test/Fusion.Composition.Tests/__snapshots__/SourceSchemaMergerTests.Merge_FourNamedSchemas_AddsFusionDefinitions.graphql index 3995b47f310..126b715e726 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Composition.Tests/__snapshots__/SourceSchemaMergerTests.Merge_FourNamedSchemas_AddsFusionDefinitions.graphql +++ b/src/HotChocolate/Fusion/test/Fusion.Composition.Tests/__snapshots__/SourceSchemaMergerTests.Merge_FourNamedSchemas_AddsFusionDefinitions.graphql @@ -18,6 +18,12 @@ scalar fusion__FieldSelectionPath "The fusion__FieldSelectionSet scalar is used to represent a GraphQL selection set. To simplify the syntax, the outermost selection set is not wrapped in curly braces." scalar fusion__FieldSelectionSet +"The @fusion__connector directive declares which connector kind handles a source schema." +directive @fusion__connector( + "The kind of connector that handles the source schema represented by this enum value." + kind: String! +) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost( "The name of the source schema that defined the cost metadata." diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/HotChocolate.Fusion.Connectors.ApolloFederation.Compliance.Tests.csproj b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/HotChocolate.Fusion.Connectors.ApolloFederation.Compliance.Tests.csproj index 091f96bd0aa..3f20eb497e1 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/HotChocolate.Fusion.Connectors.ApolloFederation.Compliance.Tests.csproj +++ b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/HotChocolate.Fusion.Connectors.ApolloFederation.Compliance.Tests.csproj @@ -8,7 +8,6 @@ - diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/Infrastructure/FusionGatewayBuilder.cs b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/Infrastructure/FusionGatewayBuilder.cs index d6a509989a7..fe7a0dffdb8 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/Infrastructure/FusionGatewayBuilder.cs +++ b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Compliance.Tests/Infrastructure/FusionGatewayBuilder.cs @@ -119,15 +119,9 @@ private static async Task BuildSubgraphInfoAsync(SubgraphHost host $"Apollo Federation transform failed for subgraph '{host.Name}': {messages}"); } - var sourceSchemaSdl = transformResult.Value; - var lookups = ExtractLookups(sourceSchemaSdl); - var entityRequires = ExtractEntityRequires(sourceSchemaSdl, lookups); - return new SubgraphInfo( host.Name, - sourceSchemaSdl, - lookups, - entityRequires, + transformResult.Value, new Uri(DefaultBaseAddress)); } @@ -254,65 +248,6 @@ private static JsonDocumentOwner BuildGatewaySettings(IReadOnlyList 0) - { - writer.WriteStartObject("arguments"); - - foreach (var (argument, keyField) in info.ArgumentToKeyFieldMap) - { - writer.WriteString(argument, keyField); - } - - writer.WriteEndObject(); - } - - writer.WriteEndObject(); - } - - writer.WriteEndObject(); - - if (subgraph.EntityRequires.Count > 0) - { - writer.WriteStartObject("entityTypes"); - - foreach (var (entityTypeName, fields) in subgraph.EntityRequires) - { - writer.WriteStartObject(entityTypeName); - writer.WriteStartObject("fields"); - - foreach (var (fieldName, requires) in fields) - { - writer.WriteStartObject(fieldName); - writer.WriteStartObject("requires"); - - foreach (var (argumentName, requireField) in requires) - { - writer.WriteString(argumentName, requireField); - } - - writer.WriteEndObject(); - writer.WriteEndObject(); - } - - writer.WriteEndObject(); - writer.WriteEndObject(); - } - - writer.WriteEndObject(); - } - - writer.WriteEndObject(); - writer.WriteEndObject(); - writer.WriteEndObject(); } @@ -325,276 +260,9 @@ private static JsonDocumentOwner BuildGatewaySettings(IReadOnlyList ExtractLookups(string sourceSchemaSdl) - { - var document = Utf8GraphQLParser.Parse(sourceSchemaSdl); - var queryName = FindRootQueryName(document) ?? "Query"; - - var lookups = new Dictionary(StringComparer.Ordinal); - - foreach (var definition in document.Definitions) - { - if (definition is not ObjectTypeDefinitionNode objectType - || !string.Equals(objectType.Name.Value, queryName, StringComparison.Ordinal)) - { - continue; - } - - foreach (var field in objectType.Fields) - { - if (!HasDirective(field.Directives, "lookup")) - { - continue; - } - - var entityTypeName = GetNamedTypeName(field.Type); - - if (entityTypeName is null) - { - continue; - } - - var arguments = new Dictionary(StringComparer.Ordinal); - - foreach (var argument in field.Arguments) - { - var keyFieldName = GetIsFieldName(argument.Directives) ?? argument.Name.Value; - arguments[argument.Name.Value] = keyFieldName; - } - - lookups[field.Name.Value] = new LookupFieldSettings(entityTypeName, arguments); - } - } - - return lookups; - } - - /// - /// - /// Walks every entity type (any object type that is the declared target - /// of a @lookup field) and extracts its per-field @require - /// argument metadata. - /// - /// - /// For each field that carries one or more @require(field: ...) - /// arguments, returns a mapping of field name to a dictionary of - /// argument name to representation field path. The connector rewriter - /// uses this map to strip the synthetic require arguments from outgoing - /// queries and inject the bound variable values onto the - /// _entities representation body. - /// - /// - private static IReadOnlyDictionary>> - ExtractEntityRequires( - string sourceSchemaSdl, - IReadOnlyDictionary lookups) - { - var entityTypeNames = new HashSet(StringComparer.Ordinal); - - foreach (var (_, settings) in lookups) - { - entityTypeNames.Add(settings.EntityTypeName); - } - - if (entityTypeNames.Count == 0) - { - return new Dictionary>>( - StringComparer.Ordinal); - } - - var document = Utf8GraphQLParser.Parse(sourceSchemaSdl); - - var entityRequires = - new Dictionary>>( - StringComparer.Ordinal); - - foreach (var definition in document.Definitions) - { - if (definition is not ObjectTypeDefinitionNode objectType - || !entityTypeNames.Contains(objectType.Name.Value)) - { - continue; - } - - var fieldMap = new Dictionary>( - StringComparer.Ordinal); - - foreach (var field in objectType.Fields) - { - var requires = new Dictionary(StringComparer.Ordinal); - - foreach (var argument in field.Arguments) - { - var requireFieldPath = GetRequireFieldPath(argument.Directives); - - if (requireFieldPath is null) - { - continue; - } - - requires[argument.Name.Value] = requireFieldPath; - } - - if (requires.Count > 0) - { - fieldMap[field.Name.Value] = requires; - } - } - - if (fieldMap.Count > 0) - { - entityRequires[objectType.Name.Value] = fieldMap; - } - } - - return entityRequires; - } - - private static string? GetRequireFieldPath(IReadOnlyList directives) - { - foreach (var directive in directives) - { - if (!string.Equals(directive.Name.Value, "require", StringComparison.Ordinal)) - { - continue; - } - - foreach (var argument in directive.Arguments) - { - if (string.Equals(argument.Name.Value, "field", StringComparison.Ordinal) - && argument.Value is StringValueNode stringValue) - { - return stringValue.Value; - } - } - } - - return null; - } - - private static string? FindRootQueryName(DocumentNode document) - { - foreach (var definition in document.Definitions) - { - if (definition is SchemaDefinitionNode schema) - { - foreach (var operationType in schema.OperationTypes) - { - if (operationType.Operation is OperationType.Query) - { - return operationType.Type.Name.Value; - } - } - } - } - - return null; - } - - private static bool HasDirective( - IReadOnlyList directives, - string name) - { - foreach (var directive in directives) - { - if (string.Equals(directive.Name.Value, name, StringComparison.Ordinal)) - { - return true; - } - } - - return false; - } - - private static string? GetIsFieldName(IReadOnlyList directives) - { - foreach (var directive in directives) - { - if (!string.Equals(directive.Name.Value, "is", StringComparison.Ordinal)) - { - continue; - } - - foreach (var argument in directive.Arguments) - { - if (string.Equals(argument.Name.Value, "field", StringComparison.Ordinal) - && argument.Value is StringValueNode stringValue) - { - return MapLookupArgumentPath(stringValue.Value); - } - } - } - - return null; - } - - /// - /// - /// Turns the @is(field: "...") value on a lookup argument into the - /// marker the runtime connector uses when building the - /// _entities(representations: [...]) payload. - /// - /// - /// The @is value is a Field Selection Map (FSM). That is the - /// Composite Schema Spec syntax for a field path (e.g. id, - /// category.{id, tag}, products[{id, pid}]). - /// - /// Two cases: - /// - /// - /// - /// The FSM starts with {. The argument is a wrapper whose value is - /// already shaped like the representation. Return an empty string, which - /// tells the connector to spread the argument's fields into the - /// representation root instead of nesting under a field name. - /// - /// - /// - /// - /// Any other FSM. The argument maps to one top-level representation field. - /// Return the first path segment, that is, everything before the first - /// ., [, { or space. - /// - /// - /// - /// - private static string MapLookupArgumentPath(string fieldSelectionMap) - { - if (fieldSelectionMap.Length > 0 && fieldSelectionMap[0] == '{') - { - return string.Empty; - } - - for (var i = 0; i < fieldSelectionMap.Length; i++) - { - var c = fieldSelectionMap[i]; - - if (c is '.' or '[' or '{' or ' ') - { - return fieldSelectionMap[..i]; - } - } - - return fieldSelectionMap; - } - - private static string? GetNamedTypeName(ITypeNode type) => type switch - { - NonNullTypeNode nonNull => GetNamedTypeName(nonNull.Type), - ListTypeNode list => GetNamedTypeName(list.Type), - NamedTypeNode named => named.Name.Value, - _ => null - }; - - private sealed record LookupFieldSettings( - string EntityTypeName, - IReadOnlyDictionary ArgumentToKeyFieldMap); - private sealed record SubgraphInfo( string Name, string SourceSchemaSdl, - IReadOnlyDictionary Lookups, - IReadOnlyDictionary>> EntityRequires, Uri BaseAddress); private sealed class TestSubgraphHttpClientFactory : IHttpClientFactory diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/ApolloFederationConnectorTests.cs b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/ApolloFederationConnectorTests.cs index 42ccdc85283..936c90e9b41 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/ApolloFederationConnectorTests.cs +++ b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/ApolloFederationConnectorTests.cs @@ -17,22 +17,18 @@ public void Configuration_Should_StoreProperties() { // arrange var baseAddress = new Uri("http://localhost:5000/graphql"); - var lookups = new Dictionary(); // act var config = new ApolloFederationSourceSchemaClientConfiguration( "products", "products-http", baseAddress, - lookups, - new Dictionary(), supportedOperations: SupportedOperationType.Query); // assert Assert.Equal("products", config.Name); Assert.Equal("products-http", config.HttpClientName); Assert.Same(baseAddress, config.BaseAddress); - Assert.Same(lookups, config.Lookups); Assert.Equal(SupportedOperationType.Query, config.SupportedOperations); } @@ -43,9 +39,7 @@ public void Configuration_Should_DefaultToQueryAndMutation() var config = new ApolloFederationSourceSchemaClientConfiguration( "products", "products-http", - new Uri("http://localhost:5000/graphql"), - new Dictionary(), - new Dictionary()); + new Uri("http://localhost:5000/graphql")); // assert Assert.Equal( diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/ApolloFederationCompletionTests.cs b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/ApolloFederationCompletionTests.cs new file mode 100644 index 00000000000..990d83fdf42 --- /dev/null +++ b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/ApolloFederationCompletionTests.cs @@ -0,0 +1,181 @@ +using System.Reflection; +using HotChocolate.Fusion.Execution.Clients; +using HotChocolate.Fusion.Logging; +using HotChocolate.Fusion.Options; +using HotChocolate.Fusion.Types; + +namespace HotChocolate.Fusion.Configuration; + +public sealed class ApolloFederationCompletionTests +{ + [Fact] + public void Complete_Should_ProjectLookups_From_SchemaMetadata() + { + // arrange + var schema = ComposeSchema( + "products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productById(id: ID! @is(field: "id")): Product @lookup + } + + type Product @key(fields: "id") { + id: ID! + name: String + } + """); + + var configuration = new ApolloFederationSourceSchemaClientConfiguration( + "products", + "products", + new Uri("http://products/graphql")); + + // act + InvokeComplete(configuration, schema); + + // assert + Assert.True(configuration.Lookups.TryGetValue("productById", out var lookup)); + Assert.Equal("Product", lookup.EntityTypeName); + Assert.Equal("id", lookup.ArgumentToKeyFieldMap["id"]); + } + + [Fact] + public void Complete_Should_See_PopulatedLookupFieldType_When_OrderingHolds() + { + // arrange + // Lookup.FieldType is populated inside an INeedsCompletion.Complete callback + // that fires before the federation projection runs. If a future change to + // CompositeSchemaBuilderContext re-orders completions (e.g. switches Add to + // Insert(0, ...)), this projection would observe a null FieldType and crash, + // so this test guards the ordering invariant. + var schema = ComposeSchema( + "products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productById(id: ID! @is(field: "id")): Product @lookup + } + + type Product @key(fields: "id") { + id: ID! + } + """); + + var configuration = new ApolloFederationSourceSchemaClientConfiguration( + "products", + "products", + new Uri("http://products/graphql")); + + // act + InvokeComplete(configuration, schema); + + // assert + var lookup = configuration.Lookups["productById"]; + Assert.False(string.IsNullOrEmpty(lookup.EntityTypeName)); + } + + [Fact] + public void Complete_Should_BindRewriter_To_ProvidedSchema_For_HotReload() + { + // arrange + // Schema rebuild must produce a fresh rewriter bound to the new schema. + // The factory is stateless w.r.t. schema; the rewriter lives on the + // configuration. Building two configurations from two FusionSchemaDefinitions + // therefore produces two distinct rewriters. + var schemaA = ComposeSchema( + "products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productById(id: ID! @is(field: "id")): Product @lookup + } + + type Product @key(fields: "id") { + id: ID! + } + """); + + var schemaB = ComposeSchema( + "products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productByCode(code: String! @is(field: "code")): Product @lookup + } + + type Product @key(fields: "code") { + code: String! + } + """); + + var configurationA = new ApolloFederationSourceSchemaClientConfiguration( + "products", + "products", + new Uri("http://products/graphql")); + + var configurationB = new ApolloFederationSourceSchemaClientConfiguration( + "products", + "products", + new Uri("http://products/graphql")); + + // act + InvokeComplete(configurationA, schemaA); + InvokeComplete(configurationB, schemaB); + + // assert + Assert.NotSame(configurationA.QueryRewriter, configurationB.QueryRewriter); + Assert.True(configurationA.Lookups.ContainsKey("productById")); + Assert.False(configurationA.Lookups.ContainsKey("productByCode")); + Assert.True(configurationB.Lookups.ContainsKey("productByCode")); + Assert.False(configurationB.Lookups.ContainsKey("productById")); + } + + private static FusionSchemaDefinition ComposeSchema(string name, string sourceSdl) + { + var sources = new[] { new SourceSchemaText(name, sourceSdl) }; + var compositionLog = new CompositionLog(); + var composerOptions = new SchemaComposerOptions(); + var composer = new SchemaComposer(sources, composerOptions, compositionLog); + + var result = composer.Compose(); + if (!result.IsSuccess) + { + throw new InvalidOperationException(result.Errors[0].Message); + } + + return FusionSchemaDefinition.Create(result.Value.ToSyntaxNode()); + } + + private static void InvokeComplete( + ApolloFederationSourceSchemaClientConfiguration configuration, + FusionSchemaDefinition schema) + { + // INeedsCompletion is internal in HotChocolate.Fusion.Execution.Types. + // The connector test project does not have IVT into that assembly, so we + // invoke the explicit interface implementation through reflection. This + // is a unit-level guard for the projection logic; the same code path is + // exercised end-to-end by the compliance suite. + var method = configuration + .GetType() + .GetMethod( + "HotChocolate.Fusion.Types.Completion.INeedsCompletion.Complete", + BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) + ?? throw new InvalidOperationException( + "Could not locate INeedsCompletion.Complete on configuration."); + + method.Invoke(configuration, [schema, null]); + } +} diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/LookupArgumentPathMapperTests.cs b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/LookupArgumentPathMapperTests.cs new file mode 100644 index 00000000000..8b3b78aa977 --- /dev/null +++ b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/LookupArgumentPathMapperTests.cs @@ -0,0 +1,81 @@ +using HotChocolate.Fusion.Execution.Clients; +using HotChocolate.Fusion.Language; + +namespace HotChocolate.Fusion.Configuration; + +public sealed class LookupArgumentPathMapperTests +{ + [Fact] + public void Map_Should_ReturnEmptyString_When_ObjectValueSelectionNode() + { + // arrange + var selection = FieldSelectionMapParser.Parse("{ id name }"); + + // act + var result = LookupArgumentPathMapper.Map(selection); + + // assert + Assert.IsType(selection); + Assert.Equal(string.Empty, result); + } + + [Fact] + public void Map_Should_ReturnPathName_When_PathNode() + { + // arrange + var selection = FieldSelectionMapParser.Parse("id"); + + // act + var result = LookupArgumentPathMapper.Map(selection); + + // assert + Assert.IsType(selection); + Assert.Equal("id", result); + } + + [Fact] + public void Map_Should_ReturnPathName_When_PathObjectValueSelectionNode() + { + // arrange + var selection = FieldSelectionMapParser.Parse("category.{ id name }"); + + // act + var result = LookupArgumentPathMapper.Map(selection); + + // assert + Assert.IsType(selection); + Assert.Equal("category", result); + } + + [Fact] + public void Map_Should_ReturnPathName_When_PathListValueSelectionNode() + { + // arrange + var selection = FieldSelectionMapParser.Parse("products[{ id pid }]"); + + // act + var result = LookupArgumentPathMapper.Map(selection); + + // assert + Assert.IsType(selection); + Assert.Equal("products", result); + } + + [Fact] + public void Map_Should_Throw_When_UnsupportedNode() + { + // arrange + // ListValueSelectionNode is a valid IValueSelectionNode subtype that the + // Apollo Federation transformer never emits, so it falls through to the + // unsupported branch. + var inner = FieldSelectionMapParser.Parse("id"); + var selection = new ListValueSelectionNode(inner); + + // act + void Act() => LookupArgumentPathMapper.Map(selection); + + // assert + var exception = Assert.Throws(Act); + Assert.Contains("ListValueSelectionNode", exception.Message); + } +} diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/ParsersTests.cs b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/ParsersTests.cs index 0b2cdfa8968..a3e1a286901 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/ParsersTests.cs +++ b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/Configuration/ParsersTests.cs @@ -1,332 +1,264 @@ using System.Text.Json; using HotChocolate.Fusion.Connectors.ApolloFederation; using HotChocolate.Fusion.Execution.Clients; +using HotChocolate.Fusion.Logging; +using HotChocolate.Fusion.Options; +using HotChocolate.Fusion.Types; +using HotChocolate.Language; namespace HotChocolate.Fusion.Configuration; public sealed class ParsersTests { [Fact] - public void TryParse_Should_Produce_Configuration_For_FlatScalarLookup() + public void TryParse_Should_Claim_When_ConnectorKindIsApollo() { // arrange - const string settingsJson = + var schema = ComposeSchema( + "products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productById(id: ID! @is(field: "id")): Product @lookup + } + + type Product @key(fields: "id") { + id: ID! + } + """); + + var sourceSchema = ReadSourceSchema( """ { "products": { - "transports": { "http": { "url": "http://products/graphql" } }, - "extensions": { - "apolloFederation": { - "lookups": { - "productById": { - "entityType": "Product", - "arguments": { "id": "id" } - } - } - } - } + "transports": { "http": { "url": "http://products/graphql" } } } } - """; - - var (sourceSchema, transport) = ReadSettings(settingsJson); + """); var parser = new ApolloFederationClientConfigurationParser(); // act - var matched = parser.TryParse(sourceSchema, transport, out var configuration); + var matched = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(matched); - var federationConfig = Assert.IsType(configuration); + var federationConfig = Assert.IsType( + Assert.Single(configurations!)); Assert.Equal("products", federationConfig.Name); Assert.Equal("http://products/graphql", federationConfig.BaseAddress.ToString()); - Assert.True(federationConfig.Lookups.TryGetValue("productById", out var lookup)); - Assert.Equal("Product", lookup.EntityTypeName); - Assert.Equal("id", Assert.Single(lookup.ArgumentToKeyFieldMap).Value); } [Fact] - public void TryParse_Should_Accept_FlatCompositeKey_StringMap() + public void TryParse_Should_NotClaim_When_ConnectorKindIsAbsent() { // arrange - const string settingsJson = + var schema = ComposeSchema( + "catalog", """ - { - "products": { - "transports": { "http": { "url": "http://products/graphql" } }, - "extensions": { - "apolloFederation": { - "lookups": { - "productBySkuAndPackage": { - "entityType": "Product", - "arguments": { - "sku": "sku", - "package": "package" - } - } - } - } - } - } + schema { + query: Query } - """; - - var (sourceSchema, transport) = ReadSettings(settingsJson); - var parser = new ApolloFederationClientConfigurationParser(); - - // act - var matched = parser.TryParse(sourceSchema, transport, out var configuration); - // assert - Assert.True(matched); - var federationConfig = Assert.IsType(configuration); - var lookup = federationConfig.Lookups["productBySkuAndPackage"]; - Assert.Equal("sku", lookup.ArgumentToKeyFieldMap["sku"]); - Assert.Equal("package", lookup.ArgumentToKeyFieldMap["package"]); - } + type Query { + ping: String + } + """); - [Fact] - public void TryParse_Should_Accept_NestedKey_EmptyStringSplatMarker() - { - // arrange: an empty string for the argument's path signals the - // connector to splat the variable's object fields into the - // '_entities' representation root (used for wrapper-shape arguments - // on nested/list '@key' lookups). - const string settingsJson = + var sourceSchema = ReadSourceSchema( """ { - "list": { - "transports": { "http": { "url": "http://list/graphql" } }, - "extensions": { - "apolloFederation": { - "lookups": { - "productListByProductsAndIdAndPid": { - "entityType": "ProductList", - "arguments": { "key": "" } - } - } - } - } + "catalog": { + "transports": { "http": { "url": "http://catalog/graphql" } } } } - """; - - var (sourceSchema, transport) = ReadSettings(settingsJson); + """); var parser = new ApolloFederationClientConfigurationParser(); // act - var matched = parser.TryParse(sourceSchema, transport, out var configuration); + var matched = parser.TryParse(schema, sourceSchema, out var configurations); // assert - Assert.True(matched); - var federationConfig = Assert.IsType(configuration); - var lookup = federationConfig.Lookups["productListByProductsAndIdAndPid"]; - Assert.Equal("ProductList", lookup.EntityTypeName); - Assert.Equal(string.Empty, lookup.ArgumentToKeyFieldMap["key"]); + Assert.False(matched); + Assert.Null(configurations); } [Fact] - public void TryParse_Should_Accept_NestedKey_ObjectFormWithPathProperty() + public void TryParse_Should_NotClaim_When_ConnectorKindIsGraphQL() { - // arrange: an object argument entry with a 'path' string property is - // the richer shorthand for expressing the same mapping. Additional - // metadata properties may be layered on later without breaking the - // string form. - const string settingsJson = + // arrange + var schema = ComposeSchema( + "catalog", + """ + schema @fusion__connector(kind: "GraphQL") { + query: Query + } + + type Query { + ping: String + } + """); + + var sourceSchema = ReadSourceSchema( """ { - "price": { - "transports": { "http": { "url": "http://price/graphql" } }, - "extensions": { - "apolloFederation": { - "lookups": { - "productListByKey": { - "entityType": "ProductList", - "arguments": { - "key": { "path": "" } - } - } - } - } - } + "catalog": { + "transports": { "http": { "url": "http://catalog/graphql" } } } } - """; - - var (sourceSchema, transport) = ReadSettings(settingsJson); + """); var parser = new ApolloFederationClientConfigurationParser(); // act - var matched = parser.TryParse(sourceSchema, transport, out var configuration); + var matched = parser.TryParse(schema, sourceSchema, out var configurations); // assert - Assert.True(matched); - var federationConfig = Assert.IsType(configuration); - var lookup = federationConfig.Lookups["productListByKey"]; - Assert.Equal(string.Empty, lookup.ArgumentToKeyFieldMap["key"]); + Assert.False(matched); + Assert.Null(configurations); } [Fact] - public void TryParse_Should_Reject_InvalidArgumentShape() + public void TryParse_Should_Throw_When_HttpUrlIsMissing() { // arrange - const string settingsJson = + var schema = ComposeSchema( + "products", """ - { - "products": { - "transports": { "http": { "url": "http://products/graphql" } }, - "extensions": { - "apolloFederation": { - "lookups": { - "productById": { - "entityType": "Product", - "arguments": { "id": 42 } - } - } - } - } - } + schema @fusion__connector(kind: "Apollo") { + query: Query } - """; - var (sourceSchema, transport) = ReadSettings(settingsJson); - var parser = new ApolloFederationClientConfigurationParser(); + type Query { + productById(id: ID! @is(field: "id")): Product @lookup + } - // act & assert - Assert.Throws( - () => parser.TryParse(sourceSchema, transport, out _)); - } + type Product @key(fields: "id") { + id: ID! + } + """); - [Fact] - public void TryParse_Should_Accept_ObjectForm_WithPathSegment() - { - // arrange - const string settingsJson = + var sourceSchema = ReadSourceSchema( """ { - "email": { - "transports": { "http": { "url": "http://email/graphql" } }, - "extensions": { - "apolloFederation": { - "lookups": { - "userById": { - "entityType": "User", - "arguments": { - "id": { "path": "id" } - } - } - } - } - } + "products": { + "transports": { "http": { } } } } - """; - - var (sourceSchema, transport) = ReadSettings(settingsJson); + """); var parser = new ApolloFederationClientConfigurationParser(); // act - var matched = parser.TryParse(sourceSchema, transport, out var configuration); + void Act() => parser.TryParse(schema, sourceSchema, out _); // assert - Assert.True(matched); - var federationConfig = Assert.IsType(configuration); - var lookup = federationConfig.Lookups["userById"]; - Assert.Equal("id", lookup.ArgumentToKeyFieldMap["id"]); + var exception = Assert.Throws(Act); + Assert.Contains("transports.http.url", exception.Message); + Assert.Contains("products", exception.Message); } [Fact] - public void TryParse_Should_Accept_EntityRequires_Block() + public void TryParse_Should_NotClaim_When_HttpTransportBlockIsMissing() { - // arrange: the composer emits per-entity-type field require metadata - // under 'extensions.apolloFederation.entityTypes'. For each field - // with synthetic '@require' arguments, the block carries the - // argument name to representation field path mapping that the - // rewriter uses to strip the argument and project the variable - // value onto the '_entities' representation. - const string settingsJson = + // arrange + var schema = ComposeSchema( + "products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productById(id: ID! @is(field: "id")): Product @lookup + } + + type Product @key(fields: "id") { + id: ID! + } + """); + + var sourceSchema = ReadSourceSchema( """ { - "inventory": { - "transports": { "http": { "url": "http://inventory/graphql" } }, - "extensions": { - "apolloFederation": { - "lookups": { - "productById": { - "entityType": "Product", - "arguments": { "id": "id" } - } - }, - "entityTypes": { - "Product": { - "fields": { - "shippingEstimate": { - "requires": { "price": "price", "weight": "weight" } - } - } - } - } - } - } + "products": { + "transports": { } } } - """; - - var (sourceSchema, transport) = ReadSettings(settingsJson); + """); var parser = new ApolloFederationClientConfigurationParser(); // act - var matched = parser.TryParse(sourceSchema, transport, out var configuration); + var matched = parser.TryParse(schema, sourceSchema, out var configurations); // assert - Assert.True(matched); - var federationConfig = Assert.IsType(configuration); - Assert.True(federationConfig.EntityRequires.TryGetValue("Product", out var productRequires)); - Assert.True(productRequires.Fields.TryGetValue("shippingEstimate", out var shippingArgs)); - Assert.Equal("price", shippingArgs["price"]); - Assert.Equal("weight", shippingArgs["weight"]); + Assert.False(matched); + Assert.Null(configurations); } [Fact] - public void TryParse_Should_Treat_Missing_EntityRequires_As_Empty() + public void TryParse_Should_HonorCustomClientName() { // arrange - const string settingsJson = + var schema = ComposeSchema( + "products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productById(id: ID! @is(field: "id")): Product @lookup + } + + type Product @key(fields: "id") { + id: ID! + } + """); + + var sourceSchema = ReadSourceSchema( """ { "products": { - "transports": { "http": { "url": "http://products/graphql" } }, - "extensions": { - "apolloFederation": { - "lookups": { - "productById": { - "entityType": "Product", - "arguments": { "id": "id" } - } - } + "transports": { + "http": { + "url": "http://products/graphql", + "clientName": "products-client" } } } } - """; - - var (sourceSchema, transport) = ReadSettings(settingsJson); + """); var parser = new ApolloFederationClientConfigurationParser(); // act - var matched = parser.TryParse(sourceSchema, transport, out var configuration); + parser.TryParse(schema, sourceSchema, out var configurations); // assert - Assert.True(matched); - var federationConfig = Assert.IsType(configuration); - Assert.Empty(federationConfig.EntityRequires); + var federationConfig = Assert.IsType( + Assert.Single(configurations!)); + Assert.Equal("products-client", federationConfig.HttpClientName); + } + + private static FusionSchemaDefinition ComposeSchema(string name, string sourceSdl) + { + var sources = new[] { new SourceSchemaText(name, sourceSdl) }; + var compositionLog = new CompositionLog(); + var composerOptions = new SchemaComposerOptions(); + var composer = new SchemaComposer(sources, composerOptions, compositionLog); + + var result = composer.Compose(); + if (!result.IsSuccess) + { + throw new InvalidOperationException(result.Errors[0].Message); + } + + return FusionSchemaDefinition.Create(result.Value.ToSyntaxNode()); } - private static (JsonProperty SourceSchema, JsonProperty Transport) ReadSettings(string settingsJson) + private static JsonProperty ReadSourceSchema(string settingsJson) { var document = JsonDocument.Parse(settingsJson); - var sourceSchema = document.RootElement.EnumerateObject().First(); - var transport = sourceSchema.Value.GetProperty("transports").EnumerateObject().First(); - return (sourceSchema, transport); + return document.RootElement.EnumerateObject().First(); } } diff --git a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/__snapshots__/SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidSourceSchema.graphql b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/__snapshots__/SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidSourceSchema.graphql index 1e171550a4b..e083573ce6e 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/__snapshots__/SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidSourceSchema.graphql +++ b/src/HotChocolate/Fusion/test/Fusion.Connectors.ApolloFederation.Tests/__snapshots__/SchemaTransformationIntegrationTests.Transform_FederationSubgraph_Should_ProduceValidSourceSchema.graphql @@ -1,4 +1,4 @@ -schema { +schema @fusion__connector(kind: "Apollo") { query: Query } @@ -19,3 +19,9 @@ type User @key(fields: "email") { email: String! name: String! } + +"The @fusion__connector directive declares which connector kind handles this source schema." +directive @fusion__connector( + "The kind of connector that backs this source schema." + kind: String! +) on SCHEMA diff --git a/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Configuration/ParsersTests.cs b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Configuration/ParsersTests.cs index 212c974c0c9..10895fc804a 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Configuration/ParsersTests.cs +++ b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Configuration/ParsersTests.cs @@ -2,9 +2,9 @@ using System.Text.Json; using HotChocolate.Buffers; using HotChocolate.Features; -using HotChocolate.Fusion.Configuration.Parsers; using HotChocolate.Fusion.Execution; using HotChocolate.Fusion.Execution.Clients; +using HotChocolate.Fusion.Types; using HotChocolate.Language; using Microsoft.Extensions.DependencyInjection; @@ -12,73 +12,6 @@ namespace HotChocolate.Fusion.Configuration; public class ParsersTests : FusionTestBase { - [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Return_False_When_Http_Transport_Missing() - { - // arrange - var sourceSchema = GetSourceSchemaProperty( - """ - { - "sourceSchemas": { - "a": { - "transports": { - "websockets": { "url": "ws://localhost:5000/graphql" } - } - } - } - } - """, - "a"); - var transport = GetTransportProperty(sourceSchema, "websockets"); - var parser = new HttpSourceSchemaClientConfigurationParser(); - - // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); - - // assert - Assert.False(claimed); - Assert.Null(configuration); - } - - [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Produce_Configuration_When_Http_Transport_Present() - { - // arrange - var sourceSchema = GetSourceSchemaProperty( - """ - { - "sourceSchemas": { - "products": { - "transports": { - "http": { - "url": "http://localhost:5000/graphql", - "clientName": "products-client" - } - } - } - } - } - """, - "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); - - // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); - - // assert - Assert.True(claimed); - var http = Assert.IsType(configuration); - Summarize(http).MatchInlineSnapshot( - """ - Name: products - HttpClientName: products-client - BaseAddress: http://localhost:5000/graphql - SupportedOperations: All - Capabilities: All - """); - } - [Fact] public async Task CreateClientConfigurations_Should_Throw_When_No_Parser_Claims_Schema() { @@ -112,7 +45,7 @@ public async Task CreateClientConfigurations_Should_Throw_When_No_Parser_Claims_ // assert var exception = await Assert.ThrowsAsync(Act); - Assert.Equal("No parser claimed any transport for source schema 'a'.", exception.Message); + Assert.Equal("No parser claimed source schema 'a'.", exception.Message); } [Fact] @@ -159,46 +92,52 @@ public async Task CreateClientConfigurations_Should_Prefer_User_Parser_Over_Buil Assert.IsType(queryConfig); } - private static JsonProperty GetSourceSchemaProperty(string settingsJson, string schemaName) + [Fact] + public async Task DefaultParser_Should_Throw_When_LegacyApolloFederationBlockIsPresent() { - var document = JsonDocument.Parse(settingsJson); - var sourceSchemas = document.RootElement.GetProperty("sourceSchemas"); - - foreach (var candidate in sourceSchemas.EnumerateObject()) - { - if (candidate.Name == schemaName) + // arrange + // The settings JSON carries the legacy v15 'extensions.apolloFederation' + // block, but the schema does not declare '@fusion__connector(kind: "Apollo")'. + // The default parser must fail loudly at executor build time so users + // discover the v16 migration mismatch instead of silently dropping + // federation metadata. + var config = CreateConfigurationWithSettings( + """ { - return candidate; + "sourceSchemas": { + "a": { + "transports": { + "http": { "url": "http://localhost:5000/graphql" } + }, + "extensions": { + "apolloFederation": { + "lookups": { "ping": { "entityType": "Foo" } } + } + } + } + } } - } + """); - throw new InvalidOperationException($"Source schema '{schemaName}' not found."); - } + var configProvider = new TestFusionConfigurationProvider(config); - private static JsonProperty GetTransportProperty(JsonProperty sourceSchema, string transportName) - { - var transports = sourceSchema.Value.GetProperty("transports"); + var services = + new ServiceCollection() + .AddGraphQLGateway() + .AddConfigurationProvider(_ => configProvider) + .Services + .BuildServiceProvider(); - foreach (var candidate in transports.EnumerateObject()) - { - if (candidate.Name == transportName) - { - return candidate; - } - } + var manager = services.GetRequiredService(); - throw new InvalidOperationException($"Transport '{transportName}' not found."); - } + // act + async Task Act() => await manager.GetExecutorAsync(); - private static string Summarize(SourceSchemaHttpClientConfiguration configuration) - { - return $""" - Name: {configuration.Name} - HttpClientName: {configuration.HttpClientName} - BaseAddress: {configuration.BaseAddress} - SupportedOperations: {configuration.SupportedOperations} - Capabilities: {configuration.Capabilities} - """; + // assert + var exception = await Assert.ThrowsAsync(Act); + Assert.Contains("legacy 'extensions.apolloFederation'", exception.Message); + Assert.Contains("'a'", exception.Message); + Assert.Contains("FederationSchemaTransformer", exception.Message); } private static FusionConfiguration CreateConfigurationWithSettings(string settingsJson) @@ -214,11 +153,11 @@ private static FusionConfiguration CreateConfigurationWithSettings(string settin private sealed class AlwaysClaimParser : ISourceSchemaClientConfigurationParser { public bool TryParse( + FusionSchemaDefinition schema, JsonProperty sourceSchema, - JsonProperty transport, - [NotNullWhen(true)] out ISourceSchemaClientConfiguration? configuration) + [NotNullWhen(true)] out ISourceSchemaClientConfiguration[]? configurations) { - configuration = new StubClientConfiguration(sourceSchema.Name); + configurations = [new StubClientConfiguration(sourceSchema.Name)]; return true; } } diff --git a/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Types/FusionSchemaDefinitionConnectorKindTests.cs b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Types/FusionSchemaDefinitionConnectorKindTests.cs new file mode 100644 index 00000000000..65908f8f2dd --- /dev/null +++ b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Types/FusionSchemaDefinitionConnectorKindTests.cs @@ -0,0 +1,120 @@ +using HotChocolate.Fusion.Logging; +using HotChocolate.Fusion.Options; +using HotChocolate.Fusion.Types; + +namespace HotChocolate.Fusion.Execution.Types; + +public sealed class FusionSchemaDefinitionConnectorKindTests +{ + [Fact] + public void GetSourceSchemaConnectorKind_Should_ReturnApollo_When_DirectiveStampedAsApollo() + { + // arrange + var schema = ComposeSchema( + ("Products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productById(id: ID!): Product @lookup + } + + type Product @key(fields: "id") { + id: ID! + } + """)); + + // act + var kind = schema.GetSourceSchemaConnectorKind("Products"); + + // assert + Assert.Equal("Apollo", kind); + } + + [Fact] + public void GetSourceSchemaConnectorKind_Should_ReturnNull_When_DirectiveAbsent() + { + // arrange + var schema = ComposeSchema( + ("Catalog", + """ + type Query { + ping: String + } + """)); + + // act + var kind = schema.GetSourceSchemaConnectorKind("Catalog"); + + // assert + Assert.Null(kind); + } + + [Fact] + public void GetSourceSchemaConnectorKind_Should_ReturnNull_When_DirectiveStampedAsGraphQL() + { + // arrange + var schema = ComposeSchema( + ("Catalog", + """ + schema @fusion__connector(kind: "GraphQL") { + query: Query + } + + type Query { + ping: String + } + """)); + + // act + var kind = schema.GetSourceSchemaConnectorKind("Catalog"); + + // assert + Assert.Null(kind); + } + + [Fact] + public void GetSourceSchemaConnectorKind_Should_ReturnNull_When_NameIsNotASourceSchema() + { + // arrange + var schema = ComposeSchema( + ("Products", + """ + schema @fusion__connector(kind: "Apollo") { + query: Query + } + + type Query { + productById(id: ID!): Product @lookup + } + + type Product @key(fields: "id") { + id: ID! + } + """)); + + // act + var kind = schema.GetSourceSchemaConnectorKind("Unknown"); + + // assert + Assert.Null(kind); + } + + private static FusionSchemaDefinition ComposeSchema(params (string Name, string Sdl)[] sources) + { + var sourceTexts = sources.Select(s => new SourceSchemaText(s.Name, s.Sdl)).ToArray(); + var compositionLog = new CompositionLog(); + var composerOptions = new SchemaComposerOptions(); + var composer = new SchemaComposer(sourceTexts, composerOptions, compositionLog); + + var result = composer.Compose(); + if (!result.IsSuccess) + { + throw new InvalidOperationException(result.Errors[0].Message); + } + + return FusionSchemaDefinition.Create(result.Value.ToSyntaxNode()); + } +} From f08a6e8573c8b14b064592b2a4ad1f7afb57965e Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Fri, 1 May 2026 13:15:31 +0000 Subject: [PATCH 3/6] Fix post-merge build and disposal regression --- .../Execution/FusionRequestExecutorManager.cs | 6 +- ...ltGraphQLClientConfigurationParserTests.cs | 126 ++++++++---------- 2 files changed, 58 insertions(+), 74 deletions(-) diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionRequestExecutorManager.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionRequestExecutorManager.cs index c42ba9e5f10..669438bdd16 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionRequestExecutorManager.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/FusionRequestExecutorManager.cs @@ -427,7 +427,7 @@ private void AddCoreServices( services.AddTransient(static _ => new IntrospectionFieldInterceptor()); services.AddTransient( sp => new SchemaConfigurationInterceptor( - sp.GetRequiredService().ServiceProvider, + sp.GetRequiredService().ServiceProvider, setup, settings)); } @@ -643,7 +643,6 @@ private async Task WaitForUpdatesAsync() { if (_cancellationToken.IsCancellationRequested) { - configuration.Dispose(); break; } @@ -652,7 +651,6 @@ private async Task WaitForUpdatesAsync() if (documentHash == _documentHash && settingsHash == _settingsHash) { - configuration.Dispose(); continue; } @@ -844,7 +842,7 @@ private sealed class SchemaConfigurationInterceptor( : CompositeTypeInterceptor { private readonly ImmutableArray _builtInParsers = - [new HttpSourceSchemaClientConfigurationParser()]; + [new DefaultGraphQLClientConfigurationParser()]; public override void OnAfterCompleteSchema( ICompositeSchemaBuilderContext context, diff --git a/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Configuration/DefaultGraphQLClientConfigurationParserTests.cs b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Configuration/DefaultGraphQLClientConfigurationParserTests.cs index effa0f3599e..61d40e02f74 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Configuration/DefaultGraphQLClientConfigurationParserTests.cs +++ b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Configuration/DefaultGraphQLClientConfigurationParserTests.cs @@ -5,17 +5,19 @@ using HotChocolate.Fusion.Configuration.Parsers; using HotChocolate.Fusion.Execution; using HotChocolate.Fusion.Execution.Clients; +using HotChocolate.Fusion.Types; using HotChocolate.Language; using Microsoft.Extensions.DependencyInjection; namespace HotChocolate.Fusion.Configuration; -public class HttpSourceSchemaClientConfigurationParserTests : FusionTestBase +public class DefaultGraphQLClientConfigurationParserTests : FusionTestBase { [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Return_False_When_Http_Transport_Missing() + public void DefaultGraphQLClientConfigurationParser_Should_Return_False_When_Http_Transport_Missing() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -29,21 +31,21 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Return_False_When_H } """, "a"); - var transport = GetTransportProperty(sourceSchema, "websockets"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.False(claimed); - Assert.Null(configuration); + Assert.Null(configurations); } [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Produce_Configuration_When_Http_Transport_Present() + public void DefaultGraphQLClientConfigurationParser_Should_Produce_Configuration_When_Http_Transport_Present() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -60,15 +62,14 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Produce_Configurati } """, "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(claimed); - var http = Assert.IsType(configuration); + var http = Assert.IsType(Assert.Single(configurations!)); Summarize(http).MatchInlineSnapshot( """ Name: products @@ -81,9 +82,10 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Produce_Configurati } [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Disable_VariableBatching_Capability_When_Configured() + public void DefaultGraphQLClientConfigurationParser_Should_Disable_VariableBatching_Capability_When_Configured() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -104,22 +106,22 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Disable_VariableBat } """, "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(claimed); - var http = Assert.IsType(configuration); + var http = Assert.IsType(Assert.Single(configurations!)); Assert.Equal(SourceSchemaClientCapabilities.RequestBatching, http.Capabilities); } [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Disable_Subscription_Operations_When_Configured() + public void DefaultGraphQLClientConfigurationParser_Should_Disable_Subscription_Operations_When_Configured() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -140,24 +142,24 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Disable_Subscriptio } """, "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(claimed); - var http = Assert.IsType(configuration); + var http = Assert.IsType(Assert.Single(configurations!)); Assert.Equal( SupportedOperationType.Query | SupportedOperationType.Mutation, http.SupportedOperations); } [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Set_OnError_To_Null_Mode_When_Configured_As_NULL() + public void DefaultGraphQLClientConfigurationParser_Should_Set_OnError_To_Null_Mode_When_Configured_As_NULL() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -176,22 +178,22 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Set_OnError_To_Null } """, "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(claimed); - var http = Assert.IsType(configuration); + var http = Assert.IsType(Assert.Single(configurations!)); Assert.Equal(ErrorHandlingMode.Null, http.OnError); } [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Set_OnError_To_Propagate_When_Configured_As_PROPAGATE() + public void DefaultGraphQLClientConfigurationParser_Should_Set_OnError_To_Propagate_When_Configured_As_PROPAGATE() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -210,22 +212,22 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Set_OnError_To_Prop } """, "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(claimed); - var http = Assert.IsType(configuration); + var http = Assert.IsType(Assert.Single(configurations!)); Assert.Equal(ErrorHandlingMode.Propagate, http.OnError); } [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Leave_OnError_Null_When_Property_Missing() + public void DefaultGraphQLClientConfigurationParser_Should_Leave_OnError_Null_When_Property_Missing() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -242,22 +244,22 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Leave_OnError_Null_ } """, "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(claimed); - var http = Assert.IsType(configuration); + var http = Assert.IsType(Assert.Single(configurations!)); Assert.Null(http.OnError); } [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Leave_OnError_Null_When_Value_Is_Json_Null() + public void DefaultGraphQLClientConfigurationParser_Should_Leave_OnError_Null_When_Value_Is_Json_Null() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -276,22 +278,22 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Leave_OnError_Null_ } """, "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(claimed); - var http = Assert.IsType(configuration); + var http = Assert.IsType(Assert.Single(configurations!)); Assert.Null(http.OnError); } [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Leave_OnError_Null_When_Value_Is_Unknown_String() + public void DefaultGraphQLClientConfigurationParser_Should_Leave_OnError_Null_When_Value_Is_Unknown_String() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -310,22 +312,22 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Leave_OnError_Null_ } """, "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(claimed); - var http = Assert.IsType(configuration); + var http = Assert.IsType(Assert.Single(configurations!)); Assert.Null(http.OnError); } [Fact] - public void HttpSourceSchemaClientConfigurationParser_Should_Default_ClientName_When_Not_Provided() + public void DefaultGraphQLClientConfigurationParser_Should_Default_ClientName_When_Not_Provided() { // arrange + var schema = CreateCompositeSchema(); var sourceSchema = GetSourceSchemaProperty( """ { @@ -341,15 +343,14 @@ public void HttpSourceSchemaClientConfigurationParser_Should_Default_ClientName_ } """, "products"); - var transport = GetTransportProperty(sourceSchema, "http"); - var parser = new HttpSourceSchemaClientConfigurationParser(); + var parser = new DefaultGraphQLClientConfigurationParser(); // act - var claimed = parser.TryParse(sourceSchema, transport, out var configuration); + var claimed = parser.TryParse(schema, sourceSchema, out var configurations); // assert Assert.True(claimed); - var http = Assert.IsType(configuration); + var http = Assert.IsType(Assert.Single(configurations!)); Assert.Equal(HttpSourceSchemaClientConfiguration.DefaultClientName, http.HttpClientName); } @@ -386,7 +387,7 @@ public async Task CreateClientConfigurations_Should_Throw_When_No_Parser_Claims_ // assert var exception = await Assert.ThrowsAsync(Act); - Assert.Equal("No parser claimed any transport for source schema 'a'.", exception.Message); + Assert.Equal("No parser claimed source schema 'a'.", exception.Message); } [Fact] @@ -449,21 +450,6 @@ private static JsonProperty GetSourceSchemaProperty(string settingsJson, string throw new InvalidOperationException($"Source schema '{schemaName}' not found."); } - private static JsonProperty GetTransportProperty(JsonProperty sourceSchema, string transportName) - { - var transports = sourceSchema.Value.GetProperty("transports"); - - foreach (var candidate in transports.EnumerateObject()) - { - if (candidate.Name == transportName) - { - return candidate; - } - } - - throw new InvalidOperationException($"Transport '{transportName}' not found."); - } - private static string Summarize(HttpSourceSchemaClientConfiguration configuration) { return $""" @@ -489,11 +475,11 @@ private static FusionConfiguration CreateConfigurationWithSettings(string settin private sealed class AlwaysClaimParser : ISourceSchemaClientConfigurationParser { public bool TryParse( + FusionSchemaDefinition schema, JsonProperty sourceSchema, - JsonProperty transport, - [NotNullWhen(true)] out ISourceSchemaClientConfiguration? configuration) + [NotNullWhen(true)] out ISourceSchemaClientConfiguration[]? configurations) { - configuration = new StubClientConfiguration(sourceSchema.Name); + configurations = [new StubClientConfiguration(sourceSchema.Name)]; return true; } } From 3ecbd0f0ff8c99c37556b511daff7204fe1356df Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Fri, 1 May 2026 14:11:18 +0000 Subject: [PATCH 4/6] snapshots --- ...usionConfigurationPublishCommitCommandTests.cs | 3 +++ .../Commands/Fusion/FusionPublishCommandTests.cs | 15 +++++++++++++++ .../Commands/Fusion/FusionValidateCommandTests.cs | 15 +++++++++++++++ .../composite-schema.graphqls | 3 +++ .../composite-schema.graphqls | 6 ++++++ .../composite-schema.graphqls | 6 ++++++ 6 files changed, 48 insertions(+) diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionConfigurationPublishCommitCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionConfigurationPublishCommitCommandTests.cs index fe8dc4a1306..9e688eaeaee 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionConfigurationPublishCommitCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionConfigurationPublishCommitCommandTests.cs @@ -408,6 +408,9 @@ scalar fusion__FieldSelectionSet directive @cacheControl(inheritMaxAge: Boolean maxAge: Int scope: CacheControlScope sharedMaxAge: Int vary: [String]) on OBJECT | FIELD_DEFINITION | INTERFACE | UNION + "The @fusion__connector directive declares which connector kind handles a source schema." + directive @fusion__connector("The kind of connector that handles the source schema represented by this enum value." kind: String!) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost("The name of the source schema that defined the cost metadata." schema: fusion__Schema! "The weight defined in the source schema." weight: String!) repeatable on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | ENUM | INPUT_FIELD_DEFINITION diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionPublishCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionPublishCommandTests.cs index aee14f8e203..8d09251c97f 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionPublishCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionPublishCommandTests.cs @@ -4487,6 +4487,9 @@ scalar fusion__FieldSelectionSet directive @cacheControl(inheritMaxAge: Boolean maxAge: Int scope: CacheControlScope sharedMaxAge: Int vary: [String]) on OBJECT | FIELD_DEFINITION | INTERFACE | UNION + "The @fusion__connector directive declares which connector kind handles a source schema." + directive @fusion__connector("The kind of connector that handles the source schema represented by this enum value." kind: String!) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost("The name of the source schema that defined the cost metadata." schema: fusion__Schema! "The weight defined in the source schema." weight: String!) repeatable on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | ENUM | INPUT_FIELD_DEFINITION @@ -4558,6 +4561,12 @@ scalar fusion__FieldSelectionPath "The fusion__FieldSelectionSet scalar is used to represent a GraphQL selection set. To simplify the syntax, the outermost selection set is not wrapped in curly braces." scalar fusion__FieldSelectionSet + "The @fusion__connector directive declares which connector kind handles a source schema." + directive @fusion__connector( + "The kind of connector that handles the source schema represented by this enum value." + kind: String! + ) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost( "The name of the source schema that defined the cost metadata." @@ -4806,6 +4815,12 @@ directive @cacheControl( vary: [String] ) on OBJECT | FIELD_DEFINITION | INTERFACE | UNION + "The @fusion__connector directive declares which connector kind handles a source schema." + directive @fusion__connector( + "The kind of connector that handles the source schema represented by this enum value." + kind: String! + ) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost( "The name of the source schema that defined the cost metadata." diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionValidateCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionValidateCommandTests.cs index 72420c4253a..da111a4b0e0 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionValidateCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionValidateCommandTests.cs @@ -1011,6 +1011,9 @@ scalar fusion__FieldSelectionSet directive @cacheControl(inheritMaxAge: Boolean maxAge: Int scope: CacheControlScope sharedMaxAge: Int vary: [String]) on OBJECT | FIELD_DEFINITION | INTERFACE | UNION + "The @fusion__connector directive declares which connector kind handles a source schema." + directive @fusion__connector("The kind of connector that handles the source schema represented by this enum value." kind: String!) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost("The name of the source schema that defined the cost metadata." schema: fusion__Schema! "The weight defined in the source schema." weight: String!) repeatable on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | ENUM | INPUT_FIELD_DEFINITION @@ -1080,6 +1083,12 @@ scalar fusion__FieldSelectionPath "The fusion__FieldSelectionSet scalar is used to represent a GraphQL selection set. To simplify the syntax, the outermost selection set is not wrapped in curly braces." scalar fusion__FieldSelectionSet + "The @fusion__connector directive declares which connector kind handles a source schema." + directive @fusion__connector( + "The kind of connector that handles the source schema represented by this enum value." + kind: String! + ) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost( "The name of the source schema that defined the cost metadata." @@ -1259,6 +1268,12 @@ directive @cacheControl( vary: [String] ) on OBJECT | FIELD_DEFINITION | INTERFACE | UNION + "The @fusion__connector directive declares which connector kind handles a source schema." + directive @fusion__connector( + "The kind of connector that handles the source schema represented by this enum value." + kind: String! + ) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost( "The name of the source schema that defined the cost metadata." diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/invalid-example-1-result/composite-schema.graphqls b/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/invalid-example-1-result/composite-schema.graphqls index 37b19248441..eb107dfabcd 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/invalid-example-1-result/composite-schema.graphqls +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/invalid-example-1-result/composite-schema.graphqls @@ -47,6 +47,9 @@ scalar fusion__FieldSelectionPath "The fusion__FieldSelectionSet scalar is used to represent a GraphQL selection set. To simplify the syntax, the outermost selection set is not wrapped in curly braces." scalar fusion__FieldSelectionSet +"The @fusion__connector directive declares which connector kind handles a source schema." +directive @fusion__connector("The kind of connector that handles the source schema represented by this enum value." kind: String!) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost("The name of the source schema that defined the cost metadata." schema: fusion__Schema! "The weight defined in the source schema." weight: String!) repeatable on | SCALAR diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/valid-example-1-result/composite-schema.graphqls b/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/valid-example-1-result/composite-schema.graphqls index 4ed507dbe9c..51e788c8933 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/valid-example-1-result/composite-schema.graphqls +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/valid-example-1-result/composite-schema.graphqls @@ -25,6 +25,12 @@ scalar fusion__FieldSelectionPath "The fusion__FieldSelectionSet scalar is used to represent a GraphQL selection set. To simplify the syntax, the outermost selection set is not wrapped in curly braces." scalar fusion__FieldSelectionSet +"The @fusion__connector directive declares which connector kind handles a source schema." +directive @fusion__connector( + "The kind of connector that handles the source schema represented by this enum value." + kind: String! +) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost( "The name of the source schema that defined the cost metadata." diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/valid-exclude-by-tag-result/composite-schema.graphqls b/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/valid-exclude-by-tag-result/composite-schema.graphqls index 4ed507dbe9c..51e788c8933 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/valid-exclude-by-tag-result/composite-schema.graphqls +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/__resources__/valid-exclude-by-tag-result/composite-schema.graphqls @@ -25,6 +25,12 @@ scalar fusion__FieldSelectionPath "The fusion__FieldSelectionSet scalar is used to represent a GraphQL selection set. To simplify the syntax, the outermost selection set is not wrapped in curly braces." scalar fusion__FieldSelectionSet +"The @fusion__connector directive declares which connector kind handles a source schema." +directive @fusion__connector( + "The kind of connector that handles the source schema represented by this enum value." + kind: String! +) on ENUM_VALUE + "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost( "The name of the source schema that defined the cost metadata." From eae2d03f0ee1684bbe81022ff8a54baf152269d4 Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Fri, 1 May 2026 14:17:35 +0000 Subject: [PATCH 5/6] Drop @fusion__connector from archived schema snapshots --- .../Fusion/FusionConfigurationPublishCommitCommandTests.cs | 3 --- .../Commands/Fusion/FusionPublishCommandTests.cs | 3 --- .../Commands/Fusion/FusionValidateCommandTests.cs | 3 --- 3 files changed, 9 deletions(-) diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionConfigurationPublishCommitCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionConfigurationPublishCommitCommandTests.cs index 9e688eaeaee..fe8dc4a1306 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionConfigurationPublishCommitCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionConfigurationPublishCommitCommandTests.cs @@ -408,9 +408,6 @@ scalar fusion__FieldSelectionSet directive @cacheControl(inheritMaxAge: Boolean maxAge: Int scope: CacheControlScope sharedMaxAge: Int vary: [String]) on OBJECT | FIELD_DEFINITION | INTERFACE | UNION - "The @fusion__connector directive declares which connector kind handles a source schema." - directive @fusion__connector("The kind of connector that handles the source schema represented by this enum value." kind: String!) on ENUM_VALUE - "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost("The name of the source schema that defined the cost metadata." schema: fusion__Schema! "The weight defined in the source schema." weight: String!) repeatable on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | ENUM | INPUT_FIELD_DEFINITION diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionPublishCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionPublishCommandTests.cs index 8d09251c97f..84beb1faa62 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionPublishCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionPublishCommandTests.cs @@ -4487,9 +4487,6 @@ scalar fusion__FieldSelectionSet directive @cacheControl(inheritMaxAge: Boolean maxAge: Int scope: CacheControlScope sharedMaxAge: Int vary: [String]) on OBJECT | FIELD_DEFINITION | INTERFACE | UNION - "The @fusion__connector directive declares which connector kind handles a source schema." - directive @fusion__connector("The kind of connector that handles the source schema represented by this enum value." kind: String!) on ENUM_VALUE - "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost("The name of the source schema that defined the cost metadata." schema: fusion__Schema! "The weight defined in the source schema." weight: String!) repeatable on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | ENUM | INPUT_FIELD_DEFINITION diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionValidateCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionValidateCommandTests.cs index da111a4b0e0..9d6202d536b 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionValidateCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Fusion/FusionValidateCommandTests.cs @@ -1011,9 +1011,6 @@ scalar fusion__FieldSelectionSet directive @cacheControl(inheritMaxAge: Boolean maxAge: Int scope: CacheControlScope sharedMaxAge: Int vary: [String]) on OBJECT | FIELD_DEFINITION | INTERFACE | UNION - "The @fusion__connector directive declares which connector kind handles a source schema." - directive @fusion__connector("The kind of connector that handles the source schema represented by this enum value." kind: String!) on ENUM_VALUE - "The @fusion__cost directive specifies cost metadata for each source schema." directive @fusion__cost("The name of the source schema that defined the cost metadata." schema: fusion__Schema! "The weight defined in the source schema." weight: String!) repeatable on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | ENUM | INPUT_FIELD_DEFINITION From 5d197a64fe79dade788a189060b49340ef0c183c Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Fri, 1 May 2026 14:46:15 +0000 Subject: [PATCH 6/6] Update introspection snapshots for semantic introspection default --- ...spectionTests.Fetch_Schema_Types_Name.yaml | 9 + ...trospectionQueries_IntrospectionQuery.yaml | 154 ++++++++++++++++++ ...Tests.Typename_On_Introspection_Types.yaml | 34 ++++ ...nd_Reviews_And_Products_Introspection.yaml | 51 ++++++ 4 files changed, 248 insertions(+) diff --git a/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.Fetch_Schema_Types_Name.yaml b/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.Fetch_Schema_Types_Name.yaml index aa7e6ae4525..3ebf3b0c988 100644 --- a/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.Fetch_Schema_Types_Name.yaml +++ b/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.Fetch_Schema_Types_Name.yaml @@ -38,6 +38,12 @@ response: { "name": "__DirectiveLocation" }, + { + "name": "__SearchResult" + }, + { + "name": "__SchemaDefinition" + }, { "name": "Query" }, @@ -68,6 +74,9 @@ response: { "name": "Boolean" }, + { + "name": "Float" + }, { "name": "Int" } diff --git a/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.IntrospectionQueries_IntrospectionQuery.yaml b/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.IntrospectionQueries_IntrospectionQuery.yaml index d7fc3d53b6e..efdab7d885e 100644 --- a/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.IntrospectionQueries_IntrospectionQuery.yaml +++ b/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.IntrospectionQueries_IntrospectionQuery.yaml @@ -1069,6 +1069,148 @@ response: ], "possibleTypes": null }, + { + "kind": "OBJECT", + "name": "__SearchResult", + "description": null, + "specifiedByURL": null, + "isOneOf": null, + "fields": [ + { + "name": "cursor", + "description": null, + "args": [], + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "String", + "ofType": null + } + }, + "isDeprecated": false, + "deprecationReason": null + }, + { + "name": "coordinate", + "description": null, + "args": [], + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "String", + "ofType": null + } + }, + "isDeprecated": false, + "deprecationReason": null + }, + { + "name": "definition", + "description": null, + "args": [], + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "UNION", + "name": "__SchemaDefinition", + "ofType": null + } + }, + "isDeprecated": false, + "deprecationReason": null + }, + { + "name": "pathsToRoot", + "description": null, + "args": [], + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "String" + } + } + } + } + } + }, + "isDeprecated": false, + "deprecationReason": null + }, + { + "name": "score", + "description": null, + "args": [], + "type": { + "kind": "SCALAR", + "name": "Float", + "ofType": null + }, + "isDeprecated": false, + "deprecationReason": null + } + ], + "inputFields": null, + "interfaces": [], + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "UNION", + "name": "__SchemaDefinition", + "description": null, + "specifiedByURL": null, + "isOneOf": null, + "fields": null, + "inputFields": null, + "interfaces": null, + "enumValues": null, + "possibleTypes": [ + { + "kind": "OBJECT", + "name": "__Directive", + "ofType": null + }, + { + "kind": "OBJECT", + "name": "__EnumValue", + "ofType": null + }, + { + "kind": "OBJECT", + "name": "__Field", + "ofType": null + }, + { + "kind": "OBJECT", + "name": "__InputValue", + "ofType": null + }, + { + "kind": "OBJECT", + "name": "__Type", + "ofType": null + } + ] + }, { "kind": "OBJECT", "name": "Query", @@ -1637,6 +1779,18 @@ response: "enumValues": null, "possibleTypes": null }, + { + "kind": "SCALAR", + "name": "Float", + "description": "The \u0060Float\u0060 scalar type represents signed double-precision finite values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).", + "specifiedByURL": null, + "isOneOf": null, + "fields": null, + "inputFields": null, + "interfaces": null, + "enumValues": null, + "possibleTypes": null + }, { "kind": "SCALAR", "name": "ID", diff --git a/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.Typename_On_Introspection_Types.yaml b/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.Typename_On_Introspection_Types.yaml index 332ec27a063..0464ecf6cb6 100644 --- a/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.Typename_On_Introspection_Types.yaml +++ b/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/__snapshots__/IntrospectionTests.Typename_On_Introspection_Types.yaml @@ -296,6 +296,34 @@ response: ], "inputFields": null }, + { + "__typename": "__Type", + "fields": [ + { + "__typename": "__Field" + }, + { + "__typename": "__Field" + }, + { + "__typename": "__Field" + }, + { + "__typename": "__Field" + }, + { + "__typename": "__Field" + } + ], + "enumValues": null, + "inputFields": null + }, + { + "__typename": "__Type", + "fields": null, + "enumValues": null, + "inputFields": null + }, { "__typename": "__Type", "fields": [ @@ -442,6 +470,12 @@ response: "enumValues": null, "inputFields": null }, + { + "__typename": "__Type", + "fields": null, + "enumValues": null, + "inputFields": null + }, { "__typename": "__Type", "fields": null, diff --git a/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/v15/__snapshots__/DemoIntegrationTests.Authors_And_Reviews_And_Products_Introspection.yaml b/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/v15/__snapshots__/DemoIntegrationTests.Authors_And_Reviews_And_Products_Introspection.yaml index 0f4750fd94e..57132d73cd5 100644 --- a/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/v15/__snapshots__/DemoIntegrationTests.Authors_And_Reviews_And_Products_Introspection.yaml +++ b/src/HotChocolate/Fusion/test/Fusion.AspNetCore.Tests/v15/__snapshots__/DemoIntegrationTests.Authors_And_Reviews_And_Products_Introspection.yaml @@ -334,6 +334,52 @@ response: "kind": "ENUM", "fields": null }, + { + "name": "__SearchResult", + "kind": "OBJECT", + "fields": [ + { + "name": "cursor", + "type": { + "name": null, + "kind": "NON_NULL" + } + }, + { + "name": "coordinate", + "type": { + "name": null, + "kind": "NON_NULL" + } + }, + { + "name": "definition", + "type": { + "name": null, + "kind": "NON_NULL" + } + }, + { + "name": "pathsToRoot", + "type": { + "name": null, + "kind": "NON_NULL" + } + }, + { + "name": "score", + "type": { + "name": "Float", + "kind": "SCALAR" + } + } + ] + }, + { + "name": "__SchemaDefinition", + "kind": "UNION", + "fields": null + }, { "name": "Query", "kind": "OBJECT", @@ -592,6 +638,11 @@ response: "kind": "SCALAR", "fields": null }, + { + "name": "Float", + "kind": "SCALAR", + "fields": null + }, { "name": "ID", "kind": "SCALAR",