From 0037b075f07a760d1285954c0107444b42754e13 Mon Sep 17 00:00:00 2001 From: Kamil Kisiela Date: Thu, 19 Nov 2026 10:08:46 +0100 Subject: [PATCH 1/5] feat: add skipSatisfiability option to composeSchemaContract A contract only adds @inaccessible to an already composed graph. Satisfiability ignores inaccessible fields in the paths it requires while still using them to resolve those paths, so a contract of a satisfiable graph is satisfiable too. When the base graph composed successfully, callers can now skip the check, which is the most expensive part of composing each contract. Also adds tests for the errors only a contract can introduce (REFERENCED_INACCESSIBLE, REQUIRED_INACCESSIBLE, ONLY_INACCESSIBLE_CHILDREN), run with and without the skip. --- .changeset/quick-hounds-skip.md | 17 +++ .../contracts/compose-schema-contract.spec.ts | 135 ++++++++++++++++++ src/contracts/schema-contract.ts | 18 ++- 3 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 .changeset/quick-hounds-skip.md diff --git a/.changeset/quick-hounds-skip.md b/.changeset/quick-hounds-skip.md new file mode 100644 index 00000000..ee321221 --- /dev/null +++ b/.changeset/quick-hounds-skip.md @@ -0,0 +1,17 @@ +--- +"@theguild/federation-composition": minor +--- + +Add a `skipSatisfiability` option to `composeSchemaContract`. A contract only adds `@inaccessible` to an already composed graph, so when the same services composed successfully without the contract, the satisfiability check cannot find anything new. Skipping it cuts roughly 45% of the time spent composing each contract. + +```ts +const base = composeServices(services); + +if (!base.errors) { + const contract = composeSchemaContract(services, filter, true, { + skipSatisfiability: true, + }); +} +``` + +The `@inaccessible` rules that contracts can trigger (for example `REFERENCED_INACCESSIBLE`, `REQUIRED_INACCESSIBLE` and `ONLY_INACCESSIBLE_CHILDREN`) keep running. diff --git a/__tests__/contracts/compose-schema-contract.spec.ts b/__tests__/contracts/compose-schema-contract.spec.ts index 6c88d2fc..79f6cbbd 100644 --- a/__tests__/contracts/compose-schema-contract.spec.ts +++ b/__tests__/contracts/compose-schema-contract.spec.ts @@ -994,3 +994,138 @@ describe("composeSchemaContract", () => { `); }); }); + +describe("composeSchemaContract: errors introduced by the contract", () => { + const link = /* GraphQL */ ` + extend schema + @link( + url: "https://specs.apollo.dev/federation/v2.3" + import: ["@key", "@tag"] + ) + `; + const excludeInternal = { + include: new Set(), + exclude: new Set(["internal"]), + }; + + // These compose as a base graph but fail as a contract. They come from the + // @inaccessible rules, which must keep running when satisfiability is skipped. + const cases = [ + { + title: "excluded type is still referenced by an included field", + code: "REFERENCED_INACCESSIBLE", + sdl: /* GraphQL */ ` + type Query { + a: A @tag(name: "public") + } + type A @tag(name: "internal") { + id: ID! + } + `, + }, + { + title: "required argument is excluded", + code: "REQUIRED_INACCESSIBLE", + sdl: /* GraphQL */ ` + type Query { + a(id: ID! @tag(name: "internal")): String @tag(name: "public") + } + `, + }, + { + title: "every Query field is excluded", + code: "ONLY_INACCESSIBLE_CHILDREN", + sdl: /* GraphQL */ ` + type Query { + a: String @tag(name: "internal") + } + `, + }, + ]; + + for (const { title, code, sdl } of cases) { + for (const skipSatisfiability of [false, true]) { + test(`${title} (skipSatisfiability: ${skipSatisfiability})`, () => { + const result = composeSchemaContract( + [{ name: "a", typeDefs: parse(link + sdl) }], + excludeInternal, + true, + { skipSatisfiability }, + ); + + expect(result.errors).toContainEqual( + expect.objectContaining({ + extensions: expect.objectContaining({ code }), + }), + ); + }); + } + } +}); + +describe("composeSchemaContract: skipSatisfiability", () => { + // An unsatisfiable graph: "feed" requires User.name, but cannot reach "users" + // because the key includes a field "feed" only has as @external. + const services = [ + { + name: "users", + typeDefs: parse(/* GraphQL */ ` + extend schema + @link( + url: "https://specs.apollo.dev/federation/v2.3" + import: ["@key"] + ) + + type Query { + users: [User] + } + + type User @key(fields: "id name") { + id: ID! + name: String! + } + `), + }, + { + name: "feed", + typeDefs: parse(/* GraphQL */ ` + extend schema + @link( + url: "https://specs.apollo.dev/federation/v2.3" + import: ["@key", "@external", "@requires"] + ) + + type Query { + usersByIds(ids: [ID!]!): [User!]! + } + + extend type User @key(fields: "id") { + id: ID @external + name: String! @external + comments: [String] @requires(fields: "name") + } + `), + }, + ]; + const filter = { include: new Set(), exclude: new Set() }; + + test("runs satisfiability by default", () => { + const result = composeSchemaContract(services, filter); + + expect(result.errors).toContainEqual( + expect.objectContaining({ + extensions: expect.objectContaining({ code: "SATISFIABILITY_ERROR" }), + }), + ); + }); + + test("skips satisfiability when asked", () => { + // Only safe when the base graph already passed composition. + // This graph does not, which is how the test can see the check was skipped. + const result = composeSchemaContract(services, filter, true, { + skipSatisfiability: true, + }); + + expect(result.errors).toBeUndefined(); + }); +}); diff --git a/src/contracts/schema-contract.ts b/src/contracts/schema-contract.ts index 4a3e688f..cf64a874 100644 --- a/src/contracts/schema-contract.ts +++ b/src/contracts/schema-contract.ts @@ -15,9 +15,25 @@ export function composeSchemaContract( tagFilter: SchemaContractFilter, /** Whether types that are not referenced by the schema contracts public schema should be annotated with `@inaccessible`. */ removeUnreachableTypes = true, + options?: { + /** + * Skip the satisfiability check, the most expensive part of composition. + * + * Only set it when the same services already composed successfully without a contract. + * A contract only adds `@inaccessible`, and satisfiability ignores inaccessible fields + * in the paths it requires while still using them to resolve those paths, + * so a contract of a satisfiable graph is satisfiable too. + */ + skipSatisfiability?: boolean; + }, ) { const filteredSubgraphs = applyTagFilterOnSubgraphs(services, tagFilter); - const compositionResult = composeServices(filteredSubgraphs); + const compositionResult = composeServices( + filteredSubgraphs, + options?.skipSatisfiability + ? { disableValidationRules: ["SatisfiabilityRule"] } + : undefined, + ); if ( !compositionResult.errors && From 40c288c4bc2a3c24e77b45705b5e7a2c95a767df Mon Sep 17 00:00:00 2001 From: Kamil Kisiela Date: Thu, 19 Nov 2026 10:38:13 +0100 Subject: [PATCH 2/5] feat: derive schema contracts from the composed supergraph Add composeServicesWithContracts, which composes the supergraph once and derives each contract from its state instead of composing all the subgraphs again. The tag filter is applied to the supergraph state with an undo log, only the rules about @inaccessible run, and the state is restored for the next contract. Errors and output are the same as composeServices followed by composeSchemaContract for each contract. The filter mirrors the decisions the subgraph filter makes, including the ones the merged state cannot tell on its own: tags matched by the type names used in each subgraph (renamed root types), type-level @external in Federation v1, @tag the filter leaves in place, federation types declared in subgraphs, and QUERY_ROOT_TYPE_INACCESSIBLE reported by subgraph validation. When the subgraphs fail to compose, each contract is composed from the subgraphs as before. --- .changeset/wise-crabs-derive.md | 19 + .../compose-services-with-contracts.spec.ts | 467 +++++++++++++ src/compose.ts | 31 +- src/contracts/schema-contract.ts | 105 ++- src/contracts/supergraph-state-contract.ts | 644 ++++++++++++++++++ src/contracts/tag-extraction.ts | 2 +- src/index.ts | 6 +- .../query-root-type-inaccessible-rule.ts | 29 +- src/subgraph/validation/validate-subgraph.ts | 2 +- .../validation/validate-supergraph.ts | 35 +- src/validate.ts | 44 +- 11 files changed, 1356 insertions(+), 28 deletions(-) create mode 100644 .changeset/wise-crabs-derive.md create mode 100644 __tests__/contracts/compose-services-with-contracts.spec.ts create mode 100644 src/contracts/supergraph-state-contract.ts diff --git a/.changeset/wise-crabs-derive.md b/.changeset/wise-crabs-derive.md new file mode 100644 index 00000000..cbc3b1f4 --- /dev/null +++ b/.changeset/wise-crabs-derive.md @@ -0,0 +1,19 @@ +--- +"@theguild/federation-composition": minor +--- + +Add `composeServicesWithContracts` to compose a supergraph together with its schema contracts. + +Instead of composing all the subgraphs again for every contract, each contract is derived from the composed supergraph: the tag filter is applied to it, and only the rules about `@inaccessible` run, since those are the only ones a contract can fail. The results are the same as `composeServices` followed by `composeSchemaContract` for each contract, at a fraction of the time and memory. + +```ts +const { supergraph, contracts } = composeServicesWithContracts(services, [ + { filter: { include: new Set(["public"]), exclude: new Set() } }, + { + filter: { include: new Set(), exclude: new Set(["internal"]) }, + removeUnreachableTypes: false, + }, +]); +``` + +When the subgraphs fail to compose, each contract is composed from the subgraphs, as before. diff --git a/__tests__/contracts/compose-services-with-contracts.spec.ts b/__tests__/contracts/compose-services-with-contracts.spec.ts new file mode 100644 index 00000000..f7783a41 --- /dev/null +++ b/__tests__/contracts/compose-services-with-contracts.spec.ts @@ -0,0 +1,467 @@ +import { + type ConstDirectiveNode, + type DocumentNode, + Kind, + parse, + visit, +} from "graphql"; +import { describe, expect, test } from "vitest"; +import { composeServices, type CompositionResult } from "../../src/compose.js"; +import { + composeSchemaContract, + composeServicesWithContracts, + type SchemaContract, +} from "../../src/contracts/schema-contract.js"; +import { extractLinkImplementations } from "../../src/utils/link/index.js"; +import { getSubgraphs as getDGS } from "../fixtures/dgs/index.js"; + +type Service = { name: string; typeDefs: DocumentNode }; + +function describeResult(result: CompositionResult) { + return result.errors + ? { errors: result.errors.map((error) => error.message) } + : { supergraphSdl: result.supergraphSdl }; +} + +/** + * Deriving contracts from the composed supergraph must give exactly the result + * of composing each contract from the subgraphs. + */ +function expectSameAsComposingEachContract( + services: Service[], + contracts: SchemaContract[], +) { + const result = composeServicesWithContracts(services, contracts); + + expect(describeResult(result.supergraph)).toEqual( + describeResult(composeServices(services)), + ); + expect(result.contracts).toHaveLength(contracts.length); + + contracts.forEach((contract, i) => { + expect(describeResult(result.contracts[i])).toEqual( + describeResult( + composeSchemaContract( + services, + contract.filter, + contract.removeUnreachableTypes ?? true, + ), + ), + ); + }); + + return result; +} + +function include(...tags: string[]): SchemaContract { + return { filter: { include: new Set(tags), exclude: new Set() } }; +} + +function exclude(...tags: string[]): SchemaContract { + return { filter: { include: new Set(), exclude: new Set(tags) } }; +} + +const fed2 = (imports: string[]) => /* GraphQL */ ` + extend schema + @link( + url: "https://specs.apollo.dev/federation/v2.3" + import: [${imports.map((i) => `"${i}"`).join(", ")}] + ) +`; + +describe("composeServicesWithContracts", () => { + test("composes the supergraph and the contracts, in order", () => { + const services = [ + { + name: "a", + typeDefs: parse(/* GraphQL */ ` + ${fed2(["@key", "@tag"])} + type Query { + public: String @tag(name: "public") + internal: String @tag(name: "internal") + } + `), + }, + ]; + + const result = expectSameAsComposingEachContract(services, [ + exclude("internal"), + include("internal"), + ]); + + expect(result.supergraph.publicSdl).toContain("internal: String"); + expect(result.contracts[0].publicSdl).not.toContain("internal: String"); + expect(result.contracts[0].publicSdl).toContain("public: String"); + expect(result.contracts[1].publicSdl).toContain("internal: String"); + expect(result.contracts[1].publicSdl).not.toContain("public: String"); + }); + + test("a contract does not leak into the next one", () => { + const services = [ + { + name: "a", + typeDefs: parse(/* GraphQL */ ` + ${fed2(["@key", "@tag"])} + type Query { + a: A @tag(name: "a") + b: String @tag(name: "b") + } + type A @key(fields: "id") { + id: ID! + secret: String @tag(name: "secret") + } + enum Color { + RED @tag(name: "a") + BLUE @tag(name: "b") + } + `), + }, + ]; + + expectSameAsComposingEachContract(services, [ + exclude("a"), // fails: Query.a references the excluded type A + exclude("secret"), + include("b"), + exclude("b"), + include(), + ]); + }); + + test("subgraphs fail to compose", () => { + const services = [ + { + name: "a", + typeDefs: parse(/* GraphQL */ ` + ${fed2(["@key", "@tag"])} + type Query { + a: String @tag(name: "a") + } + `), + }, + { + name: "b", + typeDefs: parse(/* GraphQL */ ` + ${fed2(["@key", "@tag"])} + type Query { + a: Int + } + `), + }, + ]; + + const result = expectSameAsComposingEachContract(services, [exclude("a")]); + + expect(result.supergraph.errors).toBeDefined(); + expect(result.contracts[0].errors).toBeDefined(); + }); + + describe("errors introduced by a contract", () => { + test.each([ + { + code: "REFERENCED_INACCESSIBLE", + sdl: /* GraphQL */ ` + type Query { + a: A @tag(name: "public") + } + type A @tag(name: "internal") { + id: ID! + } + `, + }, + { + code: "REQUIRED_INACCESSIBLE", + sdl: /* GraphQL */ ` + type Query { + a(id: ID! @tag(name: "internal")): String @tag(name: "public") + } + `, + }, + { + code: "ONLY_INACCESSIBLE_CHILDREN", + sdl: /* GraphQL */ ` + type Query { + a: String @tag(name: "internal") + } + `, + }, + { + // reported by subgraph validation, before the supergraph is validated + code: "QUERY_ROOT_TYPE_INACCESSIBLE", + sdl: /* GraphQL */ ` + type Query @tag(name: "internal") { + a: String + } + `, + }, + ])("$code", ({ code, sdl }) => { + const result = expectSameAsComposingEachContract( + [{ name: "a", typeDefs: parse(fed2(["@key", "@tag"]) + sdl) }], + [exclude("internal")], + ); + + expect(result.contracts[0].errors).toContainEqual( + expect.objectContaining({ + extensions: expect.objectContaining({ code }), + }), + ); + }); + }); + + // Cases where the tag filter works on the subgraphs in ways the composed supergraph alone does not tell. + describe("same result as filtering the subgraphs", () => { + test("renamed root types are filtered by the names used in each subgraph", () => { + expectSameAsComposingEachContract( + [ + { + name: "a", + typeDefs: parse(/* GraphQL */ ` + schema { + query: CustomQueryName + } + type CustomQueryName { + helloFromA: String @tag(name: "c") + } + `), + }, + { + name: "b", + typeDefs: parse(/* GraphQL */ ` + type Query @tag(name: "a") { + helloFromB: String @tag(name: "c") + } + `), + }, + ], + [include("a"), exclude("a"), include("c")], + ); + }); + + test("fields of a type annotated with @external (Federation v1)", () => { + expectSameAsComposingEachContract( + [ + { + name: "users", + typeDefs: parse(/* GraphQL */ ` + type Query { + users: [User] + } + type User @key(fields: "id") @external { + id: ID! + name: String! + } + `), + }, + ], + [exclude("b"), include("a")], + ); + }); + + test("@tag on an @external field stays (Federation v1)", () => { + expectSameAsComposingEachContract( + [ + { + name: "inventory", + typeDefs: parse(/* GraphQL */ ` + directive @tag(name: String!) repeatable on FIELD_DEFINITION + + extend type Product @key(fields: "id") { + id: ID! @external @tag(name: "public") + delivery: String @tag(name: "public") + } + `), + }, + { + name: "products", + typeDefs: parse(/* GraphQL */ ` + directive @tag(name: String!) repeatable on FIELD_DEFINITION + + type Product @key(fields: "id") { + id: ID! + name: String @tag(name: "internal") + } + type Query { + product: Product @tag(name: "public") + } + `), + }, + ], + [exclude("internal"), include("public")], + ); + }); + + test("@tag on an argument of a directive definition", () => { + expectSameAsComposingEachContract( + [ + { + name: "a", + typeDefs: parse(/* GraphQL */ ` + extend schema + @link( + url: "https://specs.apollo.dev/federation/v2.2" + import: ["@tag", "@composeDirective"] + ) + @link( + url: "https://myspecs.dev/access/v1.0" + import: ["@access"] + ) + @composeDirective(name: "@access") + + directive @access( + scope: String @tag(name: "admin") + ) on FIELD_DEFINITION + + type Query { + employee: String @tag(name: "admin") @access(scope: "admin") + name: String + } + `), + }, + ], + [exclude("admin"), include("admin")], + ); + }); + + test("federation types declared in a subgraph", () => { + expectSameAsComposingEachContract( + [ + { + name: "users", + typeDefs: parse(/* GraphQL */ ` + extend schema + @link( + url: "https://specs.apollo.dev/federation/v2.3" + import: ["@key", "FieldSet"] + ) + + scalar FieldSet @federation__tag(name: "internal") + + type Query { + user: User + } + type User @key(fields: "id") { + id: ID! + } + `), + }, + ], + [exclude("internal")], + ); + }); + + test("excluded argument of an interface field", () => { + expectSameAsComposingEachContract( + [ + { + name: "a", + typeDefs: parse(/* GraphQL */ ` + ${fed2(["@key", "@tag"])} + interface User { + id: ID! + tags(limit: Int @tag(name: "internal")): [String!]! + } + type Admin implements User @key(fields: "id") { + id: ID! + tags(limit: Int): [String!]! + } + type Query { + users: [User] + } + `), + }, + ], + [exclude("internal")], + ); + }); + }); + + test("random tags on a real-world schema", async () => { + const services = await getDGS(); + + for (const seed of [1, 2, 3]) { + const random = createRandom(seed); + const tagged = services.map((service) => ({ + ...service, + typeDefs: addRandomTags(service.typeDefs, random), + })); + + expectSameAsComposingEachContract(tagged, [ + include("a"), + exclude("b"), + { + filter: { include: new Set(["a", "c"]), exclude: new Set(["b"]) }, + removeUnreachableTypes: false, + }, + ]); + } + }, 60_000); +}); + +function createRandom(seed: number) { + return () => { + seed = (seed * 1664525 + 1013904223) >>> 0; + return seed / 2 ** 32; + }; +} + +/** Adds `@tag(name: "a" | "b" | "c")` to a third of types, fields, arguments and enum values. */ +function addRandomTags( + typeDefs: DocumentNode, + random: () => number, +): DocumentNode { + const tagDirectiveName = extractLinkImplementations( + typeDefs, + ).resolveImportName("https://specs.apollo.dev/federation", "@tag"); + const taggable = new Set([ + Kind.OBJECT_TYPE_DEFINITION, + Kind.OBJECT_TYPE_EXTENSION, + Kind.INTERFACE_TYPE_DEFINITION, + Kind.INPUT_OBJECT_TYPE_DEFINITION, + Kind.ENUM_TYPE_DEFINITION, + Kind.SCALAR_TYPE_DEFINITION, + Kind.UNION_TYPE_DEFINITION, + Kind.FIELD_DEFINITION, + Kind.INPUT_VALUE_DEFINITION, + Kind.ENUM_VALUE_DEFINITION, + ]); + + return visit(typeDefs, { + enter(node) { + if (!taggable.has(node.kind) || random() > 0.33) { + return; + } + + const withDirectives = node as { + directives?: readonly ConstDirectiveNode[]; + }; + + // `@tag` can't be applied to external fields + if ( + withDirectives.directives?.some((d) => + d.name.value.endsWith("external"), + ) + ) { + return; + } + + const tag: ConstDirectiveNode = { + kind: Kind.DIRECTIVE, + name: { kind: Kind.NAME, value: tagDirectiveName }, + arguments: [ + { + kind: Kind.ARGUMENT, + name: { kind: Kind.NAME, value: "name" }, + value: { + kind: Kind.STRING, + value: ["a", "b", "c"][Math.floor(random() * 3)], + }, + }, + ], + }; + + return { + ...node, + directives: [...(withDirectives.directives ?? []), tag], + }; + }, + }); +} diff --git a/src/compose.ts b/src/compose.ts index 7c8b92b3..4a187745 100644 --- a/src/compose.ts +++ b/src/compose.ts @@ -1,4 +1,11 @@ -import { DocumentNode, GraphQLError, Kind, parse } from "graphql"; +import { + DirectiveDefinitionNode, + DocumentNode, + GraphQLError, + Kind, + parse, + TypeDefinitionNode, +} from "graphql"; import { print } from "./graphql/printer.js"; import { transformSupergraphToPublicSchema } from "./graphql/transform-supergraph-to-public-schema.js"; import { sdl as authenticatedSDL } from "./specifications/authenticated.js"; @@ -7,10 +14,11 @@ import { sdl as costSDL } from "./specifications/cost.js"; import { FederationVersion } from "./specifications/federation.js"; import { sdl as inaccessibleSDL } from "./specifications/inaccessible.js"; import { sdl as joinSDL } from "./specifications/join.js"; -import { sdl as linkSDL, printLink } from "./specifications/link.js"; +import { Link, sdl as linkSDL, printLink } from "./specifications/link.js"; import { sdl as policySDL } from "./specifications/policy.js"; import { sdl as requiresScopesSDL } from "./specifications/requires-scopes.js"; import { sdl as tagSDL } from "./specifications/tag.js"; +import type { SupergraphState } from "./supergraph/state.js"; import { ServiceDefinition } from "./types.js"; import { validate } from "./validate.js"; @@ -33,6 +41,21 @@ export function composeServices( }; } + return createCompositionSuccessReadCacheContainer( + createSupergraphDocumentNode(validationResult), + ); +} + +/** + * Wraps the composed types and directives with the schema definition, + * and the definitions of the specs (link, join, tag...) the supergraph uses. + */ +export function createSupergraphDocumentNode(validationResult: { + supergraph: ReadonlyArray; + links: ReadonlyArray; + specs: SupergraphState["specs"]; + federationVersion: FederationVersion; +}): DocumentNode { const rootTypes = { query: false, mutation: false, @@ -153,12 +176,10 @@ export function composeServices( ${usedAuthenticatedSpec ? authenticatedSDL : ""} `); - const supergraphDocument: DocumentNode = { + return { kind: Kind.DOCUMENT, definitions: [...core.definitions, ...validationResult.supergraph], }; - - return createCompositionSuccessReadCacheContainer(supergraphDocument); } function createLinkImportValue(name: string, alias: string | null) { diff --git a/src/contracts/schema-contract.ts b/src/contracts/schema-contract.ts index cf64a874..e7331e74 100644 --- a/src/contracts/schema-contract.ts +++ b/src/contracts/schema-contract.ts @@ -3,7 +3,15 @@ import { type SchemaContractFilter, } from "./tag-extraction.js"; import { type ServiceDefinition } from "../types.js"; -import { composeServices } from "../compose.js"; +import { + type CompositionResult, + composeServices, + createCompositionSuccessReadCacheContainer, + createSupergraphDocumentNode, +} from "../compose.js"; +import { validateAndKeepState } from "../validate.js"; +import { validateInaccessibleUsage } from "../supergraph/validation/validate-supergraph.js"; +import { createSupergraphStateContractFilter } from "./supergraph-state-contract.js"; import { extractLinkImplementations } from "../utils/link/index.js"; import { addInaccessibleToUnreachableTypes } from "./add-inaccessible-to-unreachable-types.js"; @@ -51,3 +59,98 @@ export function composeSchemaContract( return compositionResult; } + +export type SchemaContract = { + /** The filter of tag names to include and/or exclude. */ + filter: SchemaContractFilter; + /** Whether types that are not referenced by the schema contracts public schema should be annotated with `@inaccessible`. Defaults to `true`. */ + removeUnreachableTypes?: boolean; +}; + +/** + * Compose a federation schema and its schema contracts. + * + * The result is the same as `composeServices` followed by `composeSchemaContract` for each contract, + * but a contract is derived from the composed supergraph instead of composing all the subgraphs again. + * A contract only adds `@inaccessible`, so the only checks it needs are the ones about `@inaccessible`. + */ +export function composeServicesWithContracts( + /** The services that are composed */ + services: ServiceDefinition[], + /** The schema contracts to compose, the results are in the same order */ + contracts: SchemaContract[], +): { + supergraph: CompositionResult; + contracts: CompositionResult[]; +} { + const result = validateAndKeepState(services); + + if (!result.success) { + // There is no composed supergraph to derive the contracts from, so compose each of them in full. + return { + supergraph: { errors: result.errors }, + contracts: contracts.map((contract) => + composeSchemaContract( + services, + contract.filter, + contract.removeUnreachableTypes ?? true, + ), + ), + }; + } + + const supergraph = createCompositionSuccessReadCacheContainer( + createSupergraphDocumentNode(result), + ); + const supergraphState = result.supergraphStateBuilder.getSupergraphState(); + const applyTagFilter = createSupergraphStateContractFilter( + services, + supergraphState, + ); + + return { + supergraph, + contracts: contracts.map((contract): CompositionResult => { + const filtered = applyTagFilter(contract.filter); + + try { + // A subgraph that fails validation stops the composition before the supergraph is validated. + if (filtered.errors.length > 0) { + return { errors: filtered.errors }; + } + + const errors = validateInaccessibleUsage( + result.subgraphStates, + supergraphState, + ); + + if (errors.length > 0) { + return { errors }; + } + + const compositionResult = createCompositionSuccessReadCacheContainer( + createSupergraphDocumentNode({ + ...result, + supergraph: result.supergraphStateBuilder.build(), + specs: supergraphState.specs, + }), + ); + + if (contract.removeUnreachableTypes === false) { + return compositionResult; + } + + const { resolveImportName } = extractLinkImplementations( + compositionResult.supergraphDocumentNode, + ); + + return addInaccessibleToUnreachableTypes( + resolveImportName, + compositionResult, + ); + } finally { + filtered.restore(); + } + }), + }; +} diff --git a/src/contracts/supergraph-state-contract.ts b/src/contracts/supergraph-state-contract.ts new file mode 100644 index 00000000..62a1975a --- /dev/null +++ b/src/contracts/supergraph-state-contract.ts @@ -0,0 +1,644 @@ +import { + type ConstDirectiveNode, + type DocumentNode, + type FieldDefinitionNode, + GraphQLError, + type InputValueDefinitionNode, + Kind, + type ObjectTypeDefinitionNode, + OperationTypeNode, +} from "graphql"; +import type { SupergraphState } from "../supergraph/state.js"; +import { createQueryRootTypeInaccessibleError } from "../subgraph/validation/rules/query-root-type-inaccessible-rule.js"; +import { enrichErrorWithSubgraphName } from "../subgraph/validation/validate-subgraph.js"; +import { extractLinkImplementations } from "../utils/link/index.js"; +import { + buildSchemaCoordinateTagRegister, + createTagDirectiveNameExtractionStrategy, + type SchemaContractFilter, +} from "./tag-extraction.js"; + +type GraphInfo = { + name: string; + /** Normalized root type name (Query, Mutation, Subscription) to the name used in the subgraph */ + localRootTypeNames: Map; + /** The node that gets `@inaccessible` when the root query type is excluded, if it is a type definition */ + rootQueryDefinition: ObjectTypeDefinitionNode | null; + /** Fields of types annotated with `@external` (Federation v1), by the type names used in the subgraph */ + fieldsOfExternalTypes: Set; + /** + * Types declared in the subgraph that are not part of the supergraph (for example federation's own types). + * They are not in the supergraph state, but the filter applying `@inaccessible` to them still makes the supergraph use the spec. + */ + typesMissingInSupergraph: TypeMissingInSupergraph[]; +}; + +type TypeMissingInSupergraph = { + name: string; + /** Scalars and unions are excluded by `include` too */ + isLeaf: boolean; + /** Schema coordinates of fields, arguments and enum values */ + children: Array<{ coordinate: string; external: boolean }>; +}; + +/** Where `@tag` is left as it is by the filter */ +type TagsLeftByFilter = { + /** Whether any subgraph has `@tag` the filter does not remove */ + any: boolean; + /** `@tag` on scalar and union type extensions */ + byTypeName: Map>; +}; + +/** + * Prepares an already composed supergraph state for deriving schema contracts from it. + * + * The returned function applies a contract's tag filter to the state, + * making the same decisions `applyTagFilterOnSubgraphs` makes for each subgraph: + * elements excluded by the filter get `@inaccessible`, and `@tag` is removed. + * + * It mutates the state, and returns a function that puts it back the way it was, + * so several contracts can be derived from one composition, one after another. + */ +export function createSupergraphStateContractFilter( + services: ReadonlyArray<{ name: string; typeDefs: DocumentNode }>, + state: SupergraphState, +) { + // The decisions are made with the same tag register as the subgraph filter, + // which is keyed by the type names used in each subgraph (root types can be renamed). + const register = buildSchemaCoordinateTagRegister( + services.map((service) => service.typeDefs), + ); + const typeDefsByName = new Map( + services.map((service) => [service.name, service.typeDefs]), + ); + const graphs = new Map(); + const supergraphTypeNames = new Set([ + ...state.objectTypes.keys(), + ...state.interfaceTypes.keys(), + ...state.inputObjectTypes.keys(), + ...state.enumTypes.keys(), + ...state.scalarTypes.keys(), + ...state.unionTypes.keys(), + ]); + const tagsLeftByFilter: TagsLeftByFilter = { + any: false, + byTypeName: new Map(), + }; + + for (const [graphId, subgraphState] of state.subgraphs) { + const typeDefs = typeDefsByName.get(subgraphState.graph.name); + + if (!typeDefs) { + throw new Error(`Could not find subgraph ${subgraphState.graph.name}`); + } + + graphs.set( + graphId, + describeGraph( + subgraphState.graph.name, + typeDefs, + supergraphTypeNames, + tagsLeftByFilter, + ), + ); + } + + return function applyTagFilter(filter: SchemaContractFilter): { + errors: GraphQLError[]; + restore(): void; + } { + const undo: Array<() => void> = []; + + function set( + obj: T, + key: K, + value: T[K], + ) { + const previous = obj[key]; + if (previous === value) { + return; + } + obj[key] = value; + undo.push(() => { + obj[key] = previous; + }); + } + + const errors: GraphQLError[] = []; + let appliedInaccessible = false; + let hasRemainingTags = tagsLeftByFilter.any; + + function markInaccessible(element: object) { + appliedInaccessible = true; + + // Arguments of interface fields have no `@inaccessible` in the supergraph, + // but applying it in a subgraph still makes the supergraph use the spec. + if (hasInaccessibleFlag(element)) { + set(element, "inaccessible", true); + } + } + + function setTags(element: { tags: Set }, tags: Set) { + if (tags.size > 0) { + hasRemainingTags = true; + } + + if (element.tags.size > 0 || tags.size > 0) { + set(element, "tags", tags); + } + } + + function localTypeName(graphId: string, typeName: string) { + return graphs.get(graphId)!.localRootTypeNames.get(typeName) ?? typeName; + } + + function tagsOf(coordinate: string) { + return register.get(coordinate) ?? emptyTags; + } + + function isExcluded(tags: Set) { + if (filter.include.size && !hasIntersection(filter.include, tags)) { + return true; + } + + return filter.exclude.size > 0 && hasIntersection(filter.exclude, tags); + } + + /** Object, interface, input object and enum types are excluded only by `exclude`, never by a missing `include` */ + function isExcludedByExclude(tags: Set) { + return filter.exclude.size > 0 && hasIntersection(filter.exclude, tags); + } + + /** + * Whether all fields (or enum values) of a type are excluded, by the type name used in subgraphs. + * A type gets `@inaccessible` when that is true in every subgraph that has it. + */ + const allChildrenExcluded = new Map(); + /** Supergraph types by the type names used in subgraphs */ + const typesByLocalName = new Map>(); + + function trackChildren( + graphId: string, + typeName: string, + type: object, + someAccessible: boolean, + ) { + const local = localTypeName(graphId, typeName); + const rootQueryName = + graphs.get(graphId)!.localRootTypeNames.get("Query") ?? "Query"; + + // The root query type can't be made inaccessible, even when none of its fields are part of the contract. + if (local === rootQueryName) { + return; + } + + allChildrenExcluded.set( + local, + (allChildrenExcluded.get(local) ?? true) && !someAccessible, + ); + + let types = typesByLocalName.get(local); + if (!types) { + types = new Set(); + typesByLocalName.set(local, types); + } + types.add(type); + } + + for (const objectType of [ + ...state.objectTypes.values(), + ...state.interfaceTypes.values(), + ]) { + const someAccessibleInGraph = new Set(); + + for (const field of objectType.fields.values()) { + for (const arg of field.args.values()) { + for (const graphId of arg.byGraph.keys()) { + if ( + isExcluded( + tagsOf( + `${localTypeName(graphId, objectType.name)}.${field.name}(${arg.name}:)`, + ), + ) + ) { + markInaccessible(arg); + } + } + + setTags(arg, emptyTags); + } + + let remainingTags = emptyTags; + + for (const [graphId, fieldInGraph] of field.byGraph) { + const typeInGraph = objectType.byGraph.get(graphId); + + // `@inaccessible` can't be applied to an external field, + // so a subgraph where the field is external leaves it, and its `@tag`, as it is. + if ( + fieldInGraph.external || + (!!typeInGraph && + "external" in typeInGraph && + typeInGraph.external) || + graphs + .get(graphId)! + .fieldsOfExternalTypes.has( + `${localTypeName(graphId, objectType.name)}.${field.name}`, + ) + ) { + const fieldTags = getFieldTagsInGraph( + state, + graphId, + objectType.name, + field.name, + ); + + if (fieldTags?.size) { + remainingTags = new Set([...remainingTags, ...fieldTags]); + } + + continue; + } + + if ( + isExcluded( + tagsOf( + `${localTypeName(graphId, objectType.name)}.${field.name}`, + ), + ) + ) { + markInaccessible(field); + } else { + someAccessibleInGraph.add(graphId); + } + } + + setTags(field, remainingTags); + } + + for (const graphId of objectType.byGraph.keys()) { + if ( + isExcludedByExclude(tagsOf(localTypeName(graphId, objectType.name))) + ) { + markInaccessible(objectType); + + const graph = graphs.get(graphId)!; + if (objectType.name === "Query" && graph.rootQueryDefinition) { + errors.push( + enrichErrorWithSubgraphName( + createQueryRootTypeInaccessibleError(graph.rootQueryDefinition), + graph.name, + ), + ); + } + } + + trackChildren( + graphId, + objectType.name, + objectType, + someAccessibleInGraph.has(graphId), + ); + } + + setTags(objectType, emptyTags); + } + + for (const inputObjectType of state.inputObjectTypes.values()) { + const someAccessibleInGraph = new Set(); + + for (const field of inputObjectType.fields.values()) { + for (const graphId of field.byGraph.keys()) { + if (isExcluded(tagsOf(`${inputObjectType.name}.${field.name}`))) { + markInaccessible(field); + } else { + someAccessibleInGraph.add(graphId); + } + } + + setTags(field, emptyTags); + } + + if (isExcludedByExclude(tagsOf(inputObjectType.name))) { + markInaccessible(inputObjectType); + } + + for (const graphId of inputObjectType.byGraph.keys()) { + trackChildren( + graphId, + inputObjectType.name, + inputObjectType, + someAccessibleInGraph.has(graphId), + ); + } + + setTags(inputObjectType, emptyTags); + } + + for (const enumType of state.enumTypes.values()) { + const someAccessibleInGraph = new Set(); + + for (const value of enumType.values.values()) { + for (const graphId of value.byGraph.keys()) { + if (isExcluded(tagsOf(`${enumType.name}.${value.name}`))) { + markInaccessible(value); + } else { + someAccessibleInGraph.add(graphId); + } + } + + setTags(value, emptyTags); + } + + if (isExcludedByExclude(tagsOf(enumType.name))) { + // An excluded enum is not tracked, it is inaccessible already. + markInaccessible(enumType); + } else { + for (const graphId of enumType.byGraph.keys()) { + trackChildren( + graphId, + enumType.name, + enumType, + someAccessibleInGraph.has(graphId), + ); + } + } + + setTags(enumType, emptyTags); + } + + for (const type of [ + ...state.scalarTypes.values(), + ...state.unionTypes.values(), + ]) { + if (isExcluded(tagsOf(type.name))) { + markInaccessible(type); + } + + // `@tag` on a type extension of a scalar or union is not removed by the filter. + const tagsLeft = tagsLeftByFilter.byTypeName.get(type.name); + setTags( + type, + tagsLeft + ? new Set(Array.from(type.tags).filter((tag) => tagsLeft.has(tag))) + : emptyTags, + ); + } + + if (!appliedInaccessible) { + for (const graph of graphs.values()) { + for (const type of graph.typesMissingInSupergraph) { + if ( + (type.isLeaf + ? isExcluded(tagsOf(type.name)) + : isExcludedByExclude(tagsOf(type.name))) || + type.children.some( + (child) => + !child.external && isExcluded(tagsOf(child.coordinate)), + ) + ) { + appliedInaccessible = true; + } + } + } + } + + for (const [localName, excluded] of allChildrenExcluded) { + if (excluded) { + for (const type of typesByLocalName.get(localName)!) { + markInaccessible(type); + } + } + } + + if (!hasRemainingTags) { + set(state.specs, "tag", false); + } + + if (appliedInaccessible) { + set(state.specs, "inaccessible", true); + } + + return { + errors, + restore() { + for (let i = undo.length - 1; i >= 0; i--) { + undo[i](); + } + }, + }; + }; +} + +const emptyTags: Set = new Set(); + +function getFieldTagsInGraph( + state: SupergraphState, + graphId: string, + typeName: string, + fieldName: string, +): Set | undefined { + const type = state.subgraphs.get(graphId)?.types.get(typeName); + + if (!type || !("fields" in type)) { + return undefined; + } + + const field = type.fields.get(fieldName); + + return field && "tags" in field ? field.tags : undefined; +} + +function describeGraph( + name: string, + typeDefs: DocumentNode, + supergraphTypeNames: Set, + tagsLeftByFilter: TagsLeftByFilter, +): GraphInfo { + const { resolveImportName } = extractLinkImplementations(typeDefs); + const extractTag = createTagDirectiveNameExtractionStrategy( + resolveImportName("https://specs.apollo.dev/federation", "@tag"), + ); + const externalDirectiveName = resolveImportName( + "https://specs.apollo.dev/federation", + "@external", + ); + + function tagsOn(node: { directives?: readonly ConstDirectiveNode[] }) { + const tags = new Set(); + for (const directive of node.directives ?? []) { + const tag = extractTag(directive); + if (tag !== null) { + tags.add(tag); + } + } + return tags; + } + + function isExternal(node: { directives?: readonly ConstDirectiveNode[] }) { + return ( + node.directives?.some( + (directive) => directive.name.value === externalDirectiveName, + ) ?? false + ); + } + + const localRootTypeNames = new Map(); + const normalizedNames = { + [OperationTypeNode.QUERY]: "Query", + [OperationTypeNode.MUTATION]: "Mutation", + [OperationTypeNode.SUBSCRIPTION]: "Subscription", + }; + + for (const definition of typeDefs.definitions) { + if ( + definition.kind === Kind.SCHEMA_DEFINITION || + definition.kind === Kind.SCHEMA_EXTENSION + ) { + for (const operationType of definition.operationTypes ?? []) { + localRootTypeNames.set( + normalizedNames[operationType.operation], + operationType.type.name.value, + ); + } + } + } + + // `@inaccessible` goes on the first node of the type, and it is reported only when that is a type definition. + const rootQueryName = localRootTypeNames.get("Query") ?? "Query"; + const firstRootQueryNode = typeDefs.definitions.find( + (definition) => + (definition.kind === Kind.OBJECT_TYPE_DEFINITION || + definition.kind === Kind.OBJECT_TYPE_EXTENSION) && + definition.name.value === rootQueryName, + ); + + const fieldsOfExternalTypes = new Set(); + const typesMissingInSupergraph: TypeMissingInSupergraph[] = []; + const localRootNames = new Set(localRootTypeNames.values()); + + for (const definition of typeDefs.definitions) { + switch (definition.kind) { + case Kind.SCHEMA_DEFINITION: + case Kind.SCHEMA_EXTENSION: { + if (tagsOn(definition).size > 0) { + tagsLeftByFilter.any = true; + } + break; + } + case Kind.DIRECTIVE_DEFINITION: { + if (definition.arguments?.some((arg) => tagsOn(arg).size > 0)) { + tagsLeftByFilter.any = true; + } + break; + } + case Kind.SCALAR_TYPE_EXTENSION: + case Kind.UNION_TYPE_EXTENSION: { + const tags = tagsOn(definition); + if (tags.size > 0) { + tagsLeftByFilter.any = true; + let tagsOfType = tagsLeftByFilter.byTypeName.get( + definition.name.value, + ); + if (!tagsOfType) { + tagsOfType = new Set(); + tagsLeftByFilter.byTypeName.set(definition.name.value, tagsOfType); + } + for (const tag of tags) { + tagsOfType.add(tag); + } + } + break; + } + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.OBJECT_TYPE_EXTENSION: + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_EXTENSION: + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + case Kind.ENUM_TYPE_DEFINITION: + case Kind.ENUM_TYPE_EXTENSION: + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.UNION_TYPE_DEFINITION: { + const typeName = definition.name.value; + const isExternalType = isExternal(definition); + const fields: ReadonlyArray< + FieldDefinitionNode | InputValueDefinitionNode + > = "fields" in definition ? (definition.fields ?? []) : []; + + if (isExternalType) { + for (const field of fields) { + fieldsOfExternalTypes.add(`${typeName}.${field.name.value}`); + } + } + + if (supergraphTypeNames.has(typeName) || localRootNames.has(typeName)) { + break; + } + + const children: TypeMissingInSupergraph["children"] = []; + + for (const field of fields) { + children.push({ + coordinate: `${typeName}.${field.name.value}`, + external: isExternalType || isExternal(field), + }); + + if ("arguments" in field) { + for (const arg of field.arguments ?? []) { + children.push({ + coordinate: `${typeName}.${field.name.value}(${arg.name.value}:)`, + external: isExternal(arg), + }); + } + } + } + + if ("values" in definition) { + for (const value of definition.values ?? []) { + children.push({ + coordinate: `${typeName}.${value.name.value}`, + external: false, + }); + } + } + + typesMissingInSupergraph.push({ + name: typeName, + isLeaf: + definition.kind === Kind.SCALAR_TYPE_DEFINITION || + definition.kind === Kind.UNION_TYPE_DEFINITION, + children, + }); + break; + } + } + } + + return { + name, + localRootTypeNames, + rootQueryDefinition: + firstRootQueryNode?.kind === Kind.OBJECT_TYPE_DEFINITION + ? firstRootQueryNode + : null, + fieldsOfExternalTypes, + typesMissingInSupergraph, + }; +} + +function hasIntersection(filterTags: Set, tags: Set) { + for (const tag of filterTags) { + if (tags.has(tag)) { + return true; + } + } + + return false; +} + +function hasInaccessibleFlag( + element: object, +): element is { inaccessible: boolean } { + return "inaccessible" in element; +} diff --git a/src/contracts/tag-extraction.ts b/src/contracts/tag-extraction.ts index 7c9c3a53..d3bcd178 100644 --- a/src/contracts/tag-extraction.ts +++ b/src/contracts/tag-extraction.ts @@ -217,7 +217,7 @@ function collectTagsBySchemaCoordinateFromSubgraph( }); } -type SchemaCoordinateToTagsRegistry = Map< +export type SchemaCoordinateToTagsRegistry = Map< /* schema coordinate */ string, /* tag list */ Set >; diff --git a/src/index.ts b/src/index.ts index 838d4e5a..45f85c23 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,10 @@ export * from "./utils/link/index.js"; export { transformSupergraphToPublicSchema } from "./graphql/transform-supergraph-to-public-schema.js"; export { containsSupergraphSpec } from "./graphql/contains-supergraph-spec.js"; export { sortSDL } from "./graphql/sort-sdl.js"; -export { composeSchemaContract } from "./contracts/schema-contract.js"; +export { + composeSchemaContract, + composeServicesWithContracts, + type SchemaContract, +} from "./contracts/schema-contract.js"; export { addInaccessibleToUnreachableTypes } from "./contracts/add-inaccessible-to-unreachable-types.js"; export { applyTagFilterOnSubgraphs } from "./contracts/tag-extraction.js"; diff --git a/src/subgraph/validation/rules/query-root-type-inaccessible-rule.ts b/src/subgraph/validation/rules/query-root-type-inaccessible-rule.ts index 86154e3a..05c93a6c 100644 --- a/src/subgraph/validation/rules/query-root-type-inaccessible-rule.ts +++ b/src/subgraph/validation/rules/query-root-type-inaccessible-rule.ts @@ -1,4 +1,9 @@ -import { ASTVisitor, GraphQLError, OperationTypeNode } from "graphql"; +import { + ASTVisitor, + GraphQLError, + ObjectTypeDefinitionNode, + OperationTypeNode, +} from "graphql"; import type { SubgraphValidationContext } from "../validation-context.js"; export function QueryRootTypeInaccessibleRule( @@ -41,16 +46,20 @@ export function QueryRootTypeInaccessibleRule( context.isAvailableFederationDirective("inaccessible", directive), ) ) { - context.reportError( - new GraphQLError( - `Type "Query" is @inaccessible but is the root query type, which must be in the API schema.`, - { - nodes: node, - extensions: { code: "QUERY_ROOT_TYPE_INACCESSIBLE" }, - }, - ), - ); + context.reportError(createQueryRootTypeInaccessibleError(node)); } }, }; } + +export function createQueryRootTypeInaccessibleError( + node: ObjectTypeDefinitionNode, +) { + return new GraphQLError( + `Type "Query" is @inaccessible but is the root query type, which must be in the API schema.`, + { + nodes: node, + extensions: { code: "QUERY_ROOT_TYPE_INACCESSIBLE" }, + }, + ); +} diff --git a/src/subgraph/validation/validate-subgraph.ts b/src/subgraph/validation/validate-subgraph.ts index 18d238ed..25b7f83e 100644 --- a/src/subgraph/validation/validate-subgraph.ts +++ b/src/subgraph/validation/validate-subgraph.ts @@ -315,7 +315,7 @@ export function validateSubgraph( .map((error) => enrichErrorWithSubgraphName(error, subgraph.name)); } -function enrichErrorWithSubgraphName( +export function enrichErrorWithSubgraphName( error: GraphQLError, subgraphName: string, ) { diff --git a/src/supergraph/validation/validate-supergraph.ts b/src/supergraph/validation/validate-supergraph.ts index 5dfb7476..62f79fc1 100644 --- a/src/supergraph/validation/validate-supergraph.ts +++ b/src/supergraph/validation/validate-supergraph.ts @@ -1,6 +1,6 @@ import type { SubgraphState } from "../../subgraph/state.js"; import { visitSupergraphState } from "../composition/visitor.js"; -import type { SupergraphStateBuilder } from "../state.js"; +import type { SupergraphState, SupergraphStateBuilder } from "../state.js"; import { AuthOnRequiresRule } from "./rules/auth-on-requires-rule.js"; import { AuthOnContextRule } from "./rules/auth-on-context-rule.js"; import { ContextualArgumentRule } from "./rules/contextual-argument-rule.js"; @@ -138,3 +138,36 @@ export function validateSupergraph( return context.collectReportedErrors(); } + +/** + * The rules whose outcome depends on `@inaccessible`. + * + * Every other rule reads nothing a schema contract changes, + * so it passes for a contract whenever it passed for the graph the contract is made of. + */ +const inaccessibleRules = [ + EnumValuesRule, + DefaultValueUsesInaccessibleRule, + OnlyInaccessibleChildrenRule, + ReferencedInaccessibleRule, + RequiredArgumentOrFieldIsNotInaccessibleRule, + NoInaccessibleOnImplementedInterfaceFieldsRule, +]; + +/** + * Runs only the rules whose outcome depends on `@inaccessible`, + * on a supergraph state that already passed the full validation and then got more `@inaccessible` applied. + */ +export function validateInaccessibleUsage( + subgraphStates: Map, + supergraph: SupergraphState, +) { + const context = createSupergraphValidationContext(subgraphStates); + + visitSupergraphState( + supergraph, + inaccessibleRules.map((rule) => rule(context, supergraph)), + ); + + return context.collectReportedErrors(); +} diff --git a/src/validate.ts b/src/validate.ts index 4d1e1400..1f5bc5f8 100644 --- a/src/validate.ts +++ b/src/validate.ts @@ -182,6 +182,31 @@ export function validate( __internal?: { disableValidationRules?: string[]; }, +) { + const result = validateAndKeepState(subgraphs, __internal); + + if (!result.success) { + return result; + } + + const { supergraphStateBuilder, subgraphStates, ...rest } = result; + + return rest; +} + +/** + * Same as `validate`, but also returns the internal state of the supergraph, + * so it can be reused (for example to derive schema contracts without composing again). + */ +export function validateAndKeepState( + subgraphs: ReadonlyArray<{ + name: string; + url?: string; + typeDefs: DocumentNode; + }>, + __internal?: { + disableValidationRules?: string[]; + }, ) { const graphList = buildGraphList(subgraphs); @@ -249,15 +274,16 @@ export function validate( // We build the state of the supergraph as we validate the supergraph. // We do it for better performance (less iterations and shit like that). const state = createSupergraphStateBuilder(); + const subgraphStates = new Map( + Array.from(subgraphStateBuilders.entries()).map(([id, builder]) => [ + id, + cleanSubgraphStateFromFederationSpec( + cleanSubgraphStateFromLinkSpec(builder.state), + ), + ]), + ); const supergraphErrors = validateSupergraph( - new Map( - Array.from(subgraphStateBuilders.entries()).map(([id, builder]) => [ - id, - cleanSubgraphStateFromFederationSpec( - cleanSubgraphStateFromLinkSpec(builder.state), - ), - ]), - ), + subgraphStates, state, __internal, ); @@ -287,6 +313,8 @@ export function validate( links: state.links(), specs: state.getSupergraphState().specs, federationVersion: maxFederationVersion, + supergraphStateBuilder: state, + subgraphStates, } as const; } From 886f010abc12ea6d9685ae6590b2ce7fa3c052bb Mon Sep 17 00:00:00 2001 From: Kamil Kisiela Date: Thu, 19 Nov 2026 10:57:04 +0100 Subject: [PATCH 3/5] perf: share unchanged definitions between a contract and its supergraph A contract's supergraph document is almost entirely the same as the supergraph it is derived from, yet every contract kept its own copy of each definition. A contract document now reuses the definitions of the supergraph document that print the same, so each additional contract adds little memory: base + 8 contracts on the huge-schema fixture needs 145 MB of heap instead of 279 MB. Add benchmarks of a medium and a huge schema with 3 contracts, comparing composeServices followed by composeSchemaContract per contract with composeServicesWithContracts. --- .changeset/wise-crabs-derive.md | 1 + .../compose-services-with-contracts.spec.ts | 37 ++++++++ benchmark.ts | 92 +++++++++++++++++++ src/contracts/schema-contract.ts | 59 +++++++++++- 4 files changed, 184 insertions(+), 5 deletions(-) diff --git a/.changeset/wise-crabs-derive.md b/.changeset/wise-crabs-derive.md index cbc3b1f4..17025409 100644 --- a/.changeset/wise-crabs-derive.md +++ b/.changeset/wise-crabs-derive.md @@ -5,6 +5,7 @@ Add `composeServicesWithContracts` to compose a supergraph together with its schema contracts. Instead of composing all the subgraphs again for every contract, each contract is derived from the composed supergraph: the tag filter is applied to it, and only the rules about `@inaccessible` run, since those are the only ones a contract can fail. The results are the same as `composeServices` followed by `composeSchemaContract` for each contract, at a fraction of the time and memory. +The document of a contract reuses the definitions it has in common with the supergraph's document, so each contract adds little memory, however many there are. ```ts const { supergraph, contracts } = composeServicesWithContracts(services, [ diff --git a/__tests__/contracts/compose-services-with-contracts.spec.ts b/__tests__/contracts/compose-services-with-contracts.spec.ts index f7783a41..a5ce8087 100644 --- a/__tests__/contracts/compose-services-with-contracts.spec.ts +++ b/__tests__/contracts/compose-services-with-contracts.spec.ts @@ -127,6 +127,43 @@ describe("composeServicesWithContracts", () => { ]); }); + test("a contract reuses the definitions it does not change", () => { + const services = [ + { + name: "a", + typeDefs: parse(/* GraphQL */ ` + ${fed2(["@key", "@tag"])} + type Query { + user: User + internal: String @tag(name: "internal") + } + type User @key(fields: "id") { + id: ID! + name: String + } + `), + }, + ]; + + const result = expectSameAsComposingEachContract(services, [ + exclude("internal"), + ]); + + function definition(result: CompositionResult, name: string) { + return result.supergraphDocumentNode!.definitions.find( + (node) => "name" in node && node.name?.value === name, + ); + } + + expect(definition(result.contracts[0], "User")).toBeDefined(); + expect(definition(result.contracts[0], "User")).toBe( + definition(result.supergraph, "User"), + ); + expect(definition(result.contracts[0], "Query")).not.toBe( + definition(result.supergraph, "Query"), + ); + }); + test("subgraphs fail to compose", () => { const services = [ { diff --git a/benchmark.ts b/benchmark.ts index d684061b..5f3f9247 100644 --- a/benchmark.ts +++ b/benchmark.ts @@ -1,3 +1,4 @@ +import { Kind, visit, type DocumentNode } from "graphql"; import { bench, group, run } from "mitata"; import { composeServices as apolloComposeServices } from "@apollo/composition"; import { getSubgraphs as huge } from "./__tests__/fixtures/huge-schema/index.js"; @@ -7,7 +8,14 @@ import { graphql } from "./__tests__/shared/utils.js"; import { assertCompositionSuccess, composeServices as guildComposeServices, + type CompositionResult, } from "./src/compose.js"; +import { + composeSchemaContract, + composeServicesWithContracts, + type SchemaContract, +} from "./src/contracts/schema-contract.js"; +import { extractLinkImplementations } from "./src/utils/link/index.js"; const starsStuff = Object.values(createStarsStuff()); @@ -54,6 +62,87 @@ const basicServices = [ const hugeSchema = await huge(); const mediumSchema = await dgs(); +/** + * Tags root query fields, one in three as "internal" and one in three as "partner", + * so the contracts have something to filter. + */ +function withTags(services: T[]): T[] { + return services.map((service) => { + const tagDirectiveName = extractLinkImplementations( + service.typeDefs, + ).resolveImportName("https://specs.apollo.dev/federation", "@tag"); + let i = 0; + const onlyQuery = (node: { name: { value: string } }) => + node.name.value === "Query" ? undefined : false; + const skip = () => false; + + return { + ...service, + typeDefs: visit(service.typeDefs, { + ObjectTypeDefinition: onlyQuery, + ObjectTypeExtension: onlyQuery, + InterfaceTypeDefinition: skip, + InterfaceTypeExtension: skip, + InputObjectTypeDefinition: skip, + InputObjectTypeExtension: skip, + FieldDefinition(node) { + const tag = ["internal", "partner", null][i++ % 3]; + if (!tag) { + return false; + } + return { + ...node, + directives: [ + ...(node.directives ?? []), + { + kind: Kind.DIRECTIVE, + name: { kind: Kind.NAME, value: tagDirectiveName }, + arguments: [ + { + kind: Kind.ARGUMENT, + name: { kind: Kind.NAME, value: "name" }, + value: { kind: Kind.STRING, value: tag }, + }, + ], + }, + ], + }; + }, + }), + }; + }); +} + +const contracts: SchemaContract[] = [ + { filter: { include: new Set(), exclude: new Set(["internal"]) } }, + { filter: { include: new Set(), exclude: new Set(["partner"]) } }, + { filter: { include: new Set(), exclude: new Set(["internal", "partner"]) } }, +]; + +function assertAllSuccess(results: CompositionResult[]) { + for (const result of results) { + assertCompositionSuccess(result); + } +} + +function contractsGroup(name: string, services: ReturnType) { + group(`${name} + ${contracts.length} contracts`, () => { + bench("guild: composeServices + composeSchemaContract", () => { + assertAllSuccess([ + guildComposeServices(services), + ...contracts.map((contract) => + composeSchemaContract(services, contract.filter), + ), + ]); + }).gc("inner"); + + bench("guild: composeServicesWithContracts", () => { + const result = composeServicesWithContracts(services, contracts); + assertAllSuccess([result.supergraph, ...result.contracts]); + }).gc("inner"); + }); +} + group("basic schema", () => { bench("apollo", () => { assertCompositionSuccess(apolloComposeServices(basicServices)); @@ -94,4 +183,7 @@ group("huge schema", () => { }).gc("inner"); }); +contractsGroup("medium schema", withTags(mediumSchema)); +contractsGroup("huge schema", withTags(hugeSchema)); + await run(); diff --git a/src/contracts/schema-contract.ts b/src/contracts/schema-contract.ts index e7331e74..d3763eb8 100644 --- a/src/contracts/schema-contract.ts +++ b/src/contracts/schema-contract.ts @@ -2,6 +2,8 @@ import { applyTagFilterOnSubgraphs, type SchemaContractFilter, } from "./tag-extraction.js"; +import { type DefinitionNode, type DocumentNode } from "graphql"; +import { print } from "../graphql/printer.js"; import { type ServiceDefinition } from "../types.js"; import { type CompositionResult, @@ -107,6 +109,9 @@ export function composeServicesWithContracts( services, supergraphState, ); + const shareDefinitions = createDefinitionSharing( + supergraph.supergraphDocumentNode, + ); return { supergraph, @@ -129,11 +134,13 @@ export function composeServicesWithContracts( } const compositionResult = createCompositionSuccessReadCacheContainer( - createSupergraphDocumentNode({ - ...result, - supergraph: result.supergraphStateBuilder.build(), - specs: supergraphState.specs, - }), + shareDefinitions( + createSupergraphDocumentNode({ + ...result, + supergraph: result.supergraphStateBuilder.build(), + specs: supergraphState.specs, + }), + ), ); if (contract.removeUnreachableTypes === false) { @@ -154,3 +161,45 @@ export function composeServicesWithContracts( }), }; } + +/** + * A contract changes only a few definitions of the supergraph, + * so its document reuses the definitions of the supergraph's document that print the same, + * instead of keeping a copy of each of them for every contract. + */ +function createDefinitionSharing(supergraphDocument: DocumentNode) { + let printedDefinitions: Map< + string, + { node: DefinitionNode; printed: string } + > | null = null; + + return function shareDefinitions(document: DocumentNode): DocumentNode { + if (!printedDefinitions) { + printedDefinitions = new Map(); + for (const node of supergraphDocument.definitions) { + printedDefinitions.set(definitionKey(node), { + node, + printed: print(node), + }); + } + } + + const definitions = printedDefinitions; + + return { + ...document, + definitions: document.definitions.map((node) => { + const existing = definitions.get(definitionKey(node)); + return existing && existing.printed === print(node) + ? existing.node + : node; + }), + }; + }; +} + +function definitionKey(node: DefinitionNode) { + return "name" in node && node.name + ? `${node.kind}:${node.name.value}` + : node.kind; +} From 1dae6bcf6e3c26ec7bf4e78c7ac9c6e6215c3113 Mon Sep 17 00:00:00 2001 From: Kamil Kisiela Date: Thu, 19 Nov 2026 17:06:46 +0100 Subject: [PATCH 4/5] fix: inherit field tags for untagged arguments in derived contracts Mirrors the include-filter argument behavior from #345 in the state-based contract filter. --- .../compose-services-with-contracts.spec.ts | 22 +++++++++++++++++++ src/contracts/supergraph-state-contract.ts | 14 +++++++----- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/__tests__/contracts/compose-services-with-contracts.spec.ts b/__tests__/contracts/compose-services-with-contracts.spec.ts index a5ce8087..7dfde99d 100644 --- a/__tests__/contracts/compose-services-with-contracts.spec.ts +++ b/__tests__/contracts/compose-services-with-contracts.spec.ts @@ -409,6 +409,28 @@ describe("composeServicesWithContracts", () => { [exclude("internal")], ); }); + + test("untagged arguments of an included field inherit its tags", () => { + expectSameAsComposingEachContract( + [ + { + name: "a", + typeDefs: parse(/* GraphQL */ ` + ${fed2(["@key", "@tag"])} + type Query { + user(id: ID!): User @tag(name: "public") + users(first: Int, debug: Boolean @tag(name: "internal")): [User] + @tag(name: "public") + } + type User @key(fields: "id") @tag(name: "public") { + id: ID! + } + `), + }, + ], + [include("public"), include("public", "internal")], + ); + }); }); test("random tags on a real-world schema", async () => { diff --git a/src/contracts/supergraph-state-contract.ts b/src/contracts/supergraph-state-contract.ts index 62a1975a..a09df04e 100644 --- a/src/contracts/supergraph-state-contract.ts +++ b/src/contracts/supergraph-state-contract.ts @@ -214,12 +214,16 @@ export function createSupergraphStateContractFilter( for (const field of objectType.fields.values()) { for (const arg of field.args.values()) { for (const graphId of arg.byGraph.keys()) { + const fieldCoordinate = `${localTypeName(graphId, objectType.name)}.${field.name}`; + const argTags = tagsOf(`${fieldCoordinate}(${arg.name}:)`); + // For `include`, an argument without its own `@tag` inherits the tags of its field. + const argTagsForInclude = + argTags.size > 0 ? argTags : tagsOf(fieldCoordinate); + if ( - isExcluded( - tagsOf( - `${localTypeName(graphId, objectType.name)}.${field.name}(${arg.name}:)`, - ), - ) + (filter.include.size && + !hasIntersection(filter.include, argTagsForInclude)) || + isExcludedByExclude(argTags) ) { markInaccessible(arg); } From 21d86525b09fca0ba1fa74aed0e82fc6eb9ca46b Mon Sep 17 00:00:00 2001 From: Kamil Kisiela Date: Thu, 19 Nov 2026 17:46:00 +0100 Subject: [PATCH 5/5] refactor: share tag filter rules between both contract implementations The subgraph transform and the supergraph state filter now make every include/exclude decision through the same functions, so a rule change (like argument tag inheritance) lands in both. The random-tags test now covers several tag densities and a second fixture to catch any remaining drift. --- .../compose-services-with-contracts.spec.ts | 116 ++++++++++++++---- src/contracts/supergraph-state-contract.ts | 63 +++++----- src/contracts/tag-extraction.ts | 88 ++++++++----- 3 files changed, 183 insertions(+), 84 deletions(-) diff --git a/__tests__/contracts/compose-services-with-contracts.spec.ts b/__tests__/contracts/compose-services-with-contracts.spec.ts index 7dfde99d..10545aa7 100644 --- a/__tests__/contracts/compose-services-with-contracts.spec.ts +++ b/__tests__/contracts/compose-services-with-contracts.spec.ts @@ -14,6 +14,7 @@ import { } from "../../src/contracts/schema-contract.js"; import { extractLinkImplementations } from "../../src/utils/link/index.js"; import { getSubgraphs as getDGS } from "../fixtures/dgs/index.js"; +import { createStarsStuff } from "../fixtures/stars-stuff.js"; type Service = { name: string; typeDefs: DocumentNode }; @@ -53,6 +54,60 @@ function expectSameAsComposingEachContract( return result; } +/** + * Like `expectSameAsComposingEachContract`, but a contract may also throw + * (`addInaccessibleToUnreachableTypes` does on some schemas), and it must throw the same way in both. + */ +function expectSameAsComposingEachContractOrThrow( + services: Service[], + contracts: SchemaContract[], +) { + try { + expectSameAsComposingEachContract(services, contracts); + return; + } catch (error) { + if (!contracts.some((contract) => throwsOnItsOwn(services, contract))) { + throw error; + } + } + + // One of the contracts throws, which stops the others, so compare them one by one. + for (const contract of contracts) { + expect( + settle( + () => composeServicesWithContracts(services, [contract]).contracts[0], + ), + ).toEqual( + settle(() => + composeSchemaContract( + services, + contract.filter, + contract.removeUnreachableTypes ?? true, + ), + ), + ); + } +} + +function throwsOnItsOwn(services: Service[], contract: SchemaContract) { + return "thrown" in + settle(() => + composeSchemaContract( + services, + contract.filter, + contract.removeUnreachableTypes ?? true, + ), + ); +} + +function settle(compose: () => CompositionResult) { + try { + return describeResult(compose()); + } catch (error) { + return { thrown: String(error) }; + } +} + function include(...tags: string[]): SchemaContract { return { filter: { include: new Set(tags), exclude: new Set() } }; } @@ -433,26 +488,42 @@ describe("composeServicesWithContracts", () => { }); }); - test("random tags on a real-world schema", async () => { - const services = await getDGS(); - - for (const seed of [1, 2, 3]) { - const random = createRandom(seed); - const tagged = services.map((service) => ({ - ...service, - typeDefs: addRandomTags(service.typeDefs, random), - })); - - expectSameAsComposingEachContract(tagged, [ - include("a"), - exclude("b"), - { - filter: { include: new Set(["a", "c"]), exclude: new Set(["b"]) }, - removeUnreachableTypes: false, - }, - ]); - } - }, 60_000); + // A guard against the two implementations of the tag filter drifting apart: + // the subgraph transform (composeSchemaContract) and the supergraph state filter. + // Sparse tags exercise `include` (most elements untagged, arguments inheriting field tags), + // dense tags exercise types with all children excluded and the spec links. + test.each([ + ["dgs", () => getDGS()], + ["stars-stuff", async () => Object.values(createStarsStuff())], + ])( + "random tags on a real-world schema (%s)", + async (_, getServices) => { + const services: Service[] = await getServices(); + + for (const density of [0.1, 0.33, 0.8]) { + for (const seed of [1, 2, 3]) { + const random = createRandom(seed); + const tagged = services.map((service) => ({ + ...service, + typeDefs: addRandomTags(service.typeDefs, random, density), + })); + + expectSameAsComposingEachContractOrThrow(tagged, [ + include("a"), + exclude("b"), + { + filter: { + include: new Set(["a", "c"]), + exclude: new Set(["b"]), + }, + removeUnreachableTypes: false, + }, + ]); + } + } + }, + 120_000, + ); }); function createRandom(seed: number) { @@ -462,10 +533,11 @@ function createRandom(seed: number) { }; } -/** Adds `@tag(name: "a" | "b" | "c")` to a third of types, fields, arguments and enum values. */ +/** Adds `@tag(name: "a" | "b" | "c")` to a share (`density`) of types, fields, arguments and enum values. */ function addRandomTags( typeDefs: DocumentNode, random: () => number, + density: number, ): DocumentNode { const tagDirectiveName = extractLinkImplementations( typeDefs, @@ -485,7 +557,7 @@ function addRandomTags( return visit(typeDefs, { enter(node) { - if (!taggable.has(node.kind) || random() > 0.33) { + if (!taggable.has(node.kind) || random() > density) { return; } diff --git a/src/contracts/supergraph-state-contract.ts b/src/contracts/supergraph-state-contract.ts index a09df04e..8ffff75f 100644 --- a/src/contracts/supergraph-state-contract.ts +++ b/src/contracts/supergraph-state-contract.ts @@ -15,6 +15,9 @@ import { extractLinkImplementations } from "../utils/link/index.js"; import { buildSchemaCoordinateTagRegister, createTagDirectiveNameExtractionStrategy, + isArgumentExcludedByFilter, + isExcludedByExcludeFilter, + isExcludedByFilter, type SchemaContractFilter, } from "./tag-extraction.js"; @@ -37,8 +40,13 @@ type TypeMissingInSupergraph = { name: string; /** Scalars and unions are excluded by `include` too */ isLeaf: boolean; - /** Schema coordinates of fields, arguments and enum values */ - children: Array<{ coordinate: string; external: boolean }>; + /** Fields, arguments and enum values */ + children: Array<{ + name: string; + /** For an argument, the schema coordinate of its field */ + argumentOf?: string; + external: boolean; + }>; }; /** Where `@tag` is left as it is by the filter */ @@ -157,16 +165,19 @@ export function createSupergraphStateContractFilter( } function isExcluded(tags: Set) { - if (filter.include.size && !hasIntersection(filter.include, tags)) { - return true; - } - - return filter.exclude.size > 0 && hasIntersection(filter.exclude, tags); + return isExcludedByFilter(tags, filter); } - /** Object, interface, input object and enum types are excluded only by `exclude`, never by a missing `include` */ function isExcludedByExclude(tags: Set) { - return filter.exclude.size > 0 && hasIntersection(filter.exclude, tags); + return isExcludedByExcludeFilter(tags, filter); + } + + function isArgumentExcluded(fieldCoordinate: string, argName: string) { + return isArgumentExcludedByFilter( + tagsOf(`${fieldCoordinate}(${argName}:)`), + () => tagsOf(fieldCoordinate), + filter, + ); } /** @@ -214,16 +225,11 @@ export function createSupergraphStateContractFilter( for (const field of objectType.fields.values()) { for (const arg of field.args.values()) { for (const graphId of arg.byGraph.keys()) { - const fieldCoordinate = `${localTypeName(graphId, objectType.name)}.${field.name}`; - const argTags = tagsOf(`${fieldCoordinate}(${arg.name}:)`); - // For `include`, an argument without its own `@tag` inherits the tags of its field. - const argTagsForInclude = - argTags.size > 0 ? argTags : tagsOf(fieldCoordinate); - if ( - (filter.include.size && - !hasIntersection(filter.include, argTagsForInclude)) || - isExcludedByExclude(argTags) + isArgumentExcluded( + `${localTypeName(graphId, objectType.name)}.${field.name}`, + arg.name, + ) ) { markInaccessible(arg); } @@ -398,7 +404,10 @@ export function createSupergraphStateContractFilter( : isExcludedByExclude(tagsOf(type.name))) || type.children.some( (child) => - !child.external && isExcluded(tagsOf(child.coordinate)), + !child.external && + (child.argumentOf + ? isArgumentExcluded(child.argumentOf, child.name) + : isExcluded(tagsOf(`${type.name}.${child.name}`))), ) ) { appliedInaccessible = true; @@ -584,14 +593,15 @@ function describeGraph( for (const field of fields) { children.push({ - coordinate: `${typeName}.${field.name.value}`, + name: field.name.value, external: isExternalType || isExternal(field), }); if ("arguments" in field) { for (const arg of field.arguments ?? []) { children.push({ - coordinate: `${typeName}.${field.name.value}(${arg.name.value}:)`, + name: arg.name.value, + argumentOf: `${typeName}.${field.name.value}`, external: isExternal(arg), }); } @@ -601,7 +611,7 @@ function describeGraph( if ("values" in definition) { for (const value of definition.values ?? []) { children.push({ - coordinate: `${typeName}.${value.name.value}`, + name: value.name.value, external: false, }); } @@ -631,15 +641,6 @@ function describeGraph( }; } -function hasIntersection(filterTags: Set, tags: Set) { - for (const tag of filterTags) { - if (tags.has(tag)) { - return true; - } - } - - return false; -} function hasInaccessibleFlag( element: object, diff --git a/src/contracts/tag-extraction.ts b/src/contracts/tag-extraction.ts index d3bcd178..5421b482 100644 --- a/src/contracts/tag-extraction.ts +++ b/src/contracts/tag-extraction.ts @@ -298,6 +298,50 @@ function hasIntersection(a: Set, b: Set): boolean { return false; } +// The decisions of a contract filter, shared by every implementation of it +// (the subgraph transform below and the supergraph state filter), so they cannot drift apart. + +/** Fields, enum values, scalars and unions: excluded by `exclude`, or by a missing `include`. */ +export function isExcludedByFilter( + tags: Set, + filter: SchemaContractFilter, +): boolean { + return ( + (filter.include.size > 0 && !hasIntersection(tags, filter.include)) || + isExcludedByExcludeFilter(tags, filter) + ); +} + +/** Object, interface, input object and enum types: excluded only by `exclude`, never by a missing `include`. */ +export function isExcludedByExcludeFilter( + tags: Set, + filter: SchemaContractFilter, +): boolean { + return filter.exclude.size > 0 && hasIntersection(tags, filter.exclude); +} + +/** + * Field arguments: for `include`, an argument without its own `@tag` (in any subgraph) + * inherits the tags of its field. Otherwise, including a field would hide all of its + * untagged arguments (failing composition with REQUIRED_INACCESSIBLE for required ones). + * This matches the behavior of Apollo contracts. + * For `exclude` no inheritance is needed, as an excluded field is already hidden. + */ +export function isArgumentExcludedByFilter( + argumentTags: Set, + getFieldTags: () => Set, + filter: SchemaContractFilter, +): boolean { + return ( + (filter.include.size > 0 && + !hasIntersection( + argumentTags.size > 0 ? argumentTags : getFieldTags(), + filter.include, + )) || + isExcludedByExcludeFilter(argumentTags, filter) + ); +} + function difference<$Type>(set1: Set<$Type>, set2: Set<$Type>): Set<$Type> { const result = new Set<$Type>(); set1.forEach((item) => { @@ -383,22 +427,15 @@ export function applyTagFilterToInaccessibleTransformOnSubgraphSchema( `${objectLikeNode.name.value}.${fieldLikeNode.name.value}(${node.name.value}:)`, ); - // For the include filter, an argument without its own `@tag` (in any subgraph) - // inherits the tags of its field. Otherwise, including a field would hide all of its - // untagged arguments (failing composition with REQUIRED_INACCESSIBLE for required ones). - // This matches the behavior of Apollo contracts. - // For the exclude filter no inheritance is needed, as an excluded field is already hidden. - const tagsForInclude = - tagsOnNode.size > 0 - ? tagsOnNode - : getTagsForSchemaCoordinate( - `${objectLikeNode.name.value}.${fieldLikeNode.name.value}`, - ); - if ( - (filter.include.size && - !hasIntersection(tagsForInclude, filter.include)) || - (filter.exclude.size && hasIntersection(tagsOnNode, filter.exclude)) + isArgumentExcludedByFilter( + tagsOnNode, + () => + getTagsForSchemaCoordinate( + `${objectLikeNode.name.value}.${fieldLikeNode.name.value}`, + ), + filter, + ) ) { return { ...node, @@ -477,11 +514,7 @@ export function applyTagFilterToInaccessibleTransformOnSubgraphSchema( return fieldNode; } - if ( - (filter.include.size && - !hasIntersection(tagsOnNode, filter.include)) || - (filter.exclude.size && hasIntersection(tagsOnNode, filter.exclude)) - ) { + if (isExcludedByFilter(tagsOnNode, filter)) { return { ...fieldNode, directives: transformTagDirectives(fieldNode, true), @@ -497,7 +530,7 @@ export function applyTagFilterToInaccessibleTransformOnSubgraphSchema( }), } as ObjectLikeNode; - if (filter.exclude.size && hasIntersection(tagsOnNode, filter.exclude)) { + if (isExcludedByExcludeFilter(tagsOnNode, filter)) { newNode = { ...newNode, directives: transformTagDirectives( @@ -547,11 +580,7 @@ export function applyTagFilterToInaccessibleTransformOnSubgraphSchema( `${node.name.value}.${valueNode.name.value}`, ); - if ( - (filter.include.size && - !hasIntersection(tagsOnNode, filter.include)) || - (filter.exclude.size && hasIntersection(tagsOnNode, filter.exclude)) - ) { + if (isExcludedByFilter(tagsOnNode, filter)) { return { ...valueNode, directives: transformTagDirectives(valueNode, true), @@ -567,7 +596,7 @@ export function applyTagFilterToInaccessibleTransformOnSubgraphSchema( }), }; - if (filter.exclude.size && hasIntersection(tagsOnNode, filter.exclude)) { + if (isExcludedByExcludeFilter(tagsOnNode, filter)) { return { ...newNode, directives: transformTagDirectives(node, true), @@ -591,10 +620,7 @@ export function applyTagFilterToInaccessibleTransformOnSubgraphSchema( ) { const tagsOnNode = getTagsForSchemaCoordinate(node.name.value); - if ( - (filter.include.size && !hasIntersection(tagsOnNode, filter.include)) || - (filter.exclude.size && hasIntersection(tagsOnNode, filter.exclude)) - ) { + if (isExcludedByFilter(tagsOnNode, filter)) { return { ...node, directives: transformTagDirectives(node, true),