federation

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 19, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package federation implements Apollo Federation v2 query planning and execution.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyProjection

func ApplyProjection(data map[string]any, proj []*FieldProjection) map[string]any

ApplyProjection trims data to only the fields in proj, discarding planner-added fields.

func Handler

func Handler(sg *Supergraph, client *http.Client) http.Handler

Handler returns an http.Handler that executes GraphQL federation queries against the given supergraph routing table using client for subgraph HTTP calls.

func SubgraphURLs

func SubgraphURLs(sdl string) (map[string]string, error)

SubgraphURLs parses sdl and returns a map of join__Graph enum name → service URL. It is the minimal SDL parse a federation client needs at startup: just the routing table. Use the returned map as the subgraphURLs argument to generated NewClient constructors.

Types

type EntityFetchSpec

type EntityFetchSpec struct {
	Subgraph       *Subgraph
	TypeName       string   // entity type, e.g. "User"
	KeyFields      []string // key field names, e.g. ["id"]
	RequiresFields []string // @requires fields to embed in representations beyond key fields
	Selection      string   // the selection body: "reviews {\n  title\n}\n" (kept for backward compat)
	Query          string   // full entity query with variable declarations; supersedes Selection when non-empty
	Variables      []string // operation variable names to forward beyond "representations"
	ParentPath     []string // JSON path to the parent in the merged data, e.g. ["user"]
	IsParentList   bool     // true when ParentPath resolves to a list
}

EntityFetchSpec describes a cross-subgraph entity resolution step.

type EntityFetchSpecData

type EntityFetchSpecData struct {
	SubgraphEnum   string   `json:"subgraphEnum"`
	TypeName       string   `json:"typeName"`
	KeyFields      []string `json:"keyFields"`
	RequiresFields []string `json:"requiresFields,omitempty"`
	Selection      string   `json:"selection"`
	Query          string   `json:"query,omitempty"`
	Variables      []string `json:"variables,omitempty"`
	ParentPath     []string `json:"parentPath"`
	IsParentList   bool     `json:"isParentList,omitempty"`
}

EntityFetchSpecData is the serializable form of an EntityFetchSpec.

type FetchSpec

type FetchSpec struct {
	Subgraph  *Subgraph
	Query     string
	Variables []string // variable names from the original operation used here
}

FetchSpec is a query to send to one subgraph.

type FetchSpecData

type FetchSpecData struct {
	SubgraphEnum string   `json:"subgraphEnum"`
	Query        string   `json:"query"`
	Variables    []string `json:"variables,omitempty"`
}

FetchSpecData is the serializable form of a FetchSpec.

type FieldProjection

type FieldProjection struct {
	Key      string             `json:"key"`                // response key (alias or field name)
	Children []*FieldProjection `json:"children,omitempty"` // nil for scalar fields
}

FieldProjection is a node in the user-requested selection tree. It is used to strip planner-added fields from the final merged response.

type GraphQLError

type GraphQLError struct {
	Message    string           `json:"message"`
	Locations  []map[string]int `json:"locations,omitempty"`
	Path       []any            `json:"path,omitempty"`
	Extensions map[string]any   `json:"extensions,omitempty"`
}

GraphQLError is a single error object in a GraphQL response.

func Execute

func Execute(
	ctx context.Context,
	plan *Plan,
	variables map[string]any,
	client *http.Client,
) (map[string]any, []GraphQLError, error)

Execute runs a Plan against real HTTP subgraph endpoints. It executes initial fetches in parallel, then resolves entity fetches sequentially, and returns the merged data and any accumulated errors.

type GraphQLRequest

type GraphQLRequest struct {
	Query         string         `json:"query"`
	OperationName string         `json:"operationName,omitempty"`
	Variables     map[string]any `json:"variables,omitempty"`
}

GraphQLRequest is the JSON body sent to a subgraph.

type GraphQLResponse

type GraphQLResponse struct {
	Data   json.RawMessage `json:"data"`
	Errors []GraphQLError  `json:"errors,omitempty"`
}

GraphQLResponse is the JSON body received from a subgraph.

type Plan

type Plan struct {
	// Fetches are the initial per-subgraph queries, safe to run in parallel.
	Fetches []*FetchSpec
	// EntityFetches run after Fetches in order; later steps may depend on earlier ones.
	EntityFetches []*EntityFetchSpec
	// Projection holds the user-requested field tree, used to strip planner-added
	// fields (key fields, __typename, @requires pre-fetch fields) from the final response.
	Projection []*FieldProjection
}

Plan is the execution plan for a GraphQL operation.

func BuildPlan

func BuildPlan(sg *Supergraph, queryStr, operationName string) (*Plan, error)

BuildPlan analyzes a GraphQL query against the supergraph routing table and returns a Plan describing how to execute it.

type PlanSpec

type PlanSpec struct {
	Fetches       []*FetchSpecData       `json:"fetches"`
	EntityFetches []*EntityFetchSpecData `json:"entityFetches,omitempty"`
	Projection    []*FieldProjection     `json:"projection,omitempty"`
}

PlanSpec is the serializable form of a Plan. Subgraphs are identified by enum name rather than by *Subgraph pointer so the spec can be embedded in generated code and resolved against any *Supergraph at runtime.

The URL of each subgraph is not stored here — it is supplied by the *Supergraph passed to Resolve, after any WithURLOverrides have been applied.

func BuildPlanSpec

func BuildPlanSpec(sg *Supergraph, queryStr, operationName string) (*PlanSpec, error)

BuildPlanSpec builds a Plan for the given query and converts it to a PlanSpec.

func PlanToSpec

func PlanToSpec(plan *Plan) *PlanSpec

PlanToSpec converts a resolved Plan to its serializable form. The Projection slice is shared with plan; BuildPlan never mutates it after returning.

func (*PlanSpec) Resolve

func (s *PlanSpec) Resolve(sg *Supergraph) (*Plan, error)

Resolve returns a Plan with *Subgraph pointers filled from sg. Returns an error if any referenced subgraph enum is not present in sg — the supergraph changed incompatibly since the spec was built.

type Subgraph

type Subgraph struct {
	EnumName string // join__Graph enum value, e.g. "ACCOUNTS"
	Name     string // human name from @join__graph, e.g. "accounts"
	URL      string // service URL
}

Subgraph is a downstream federated GraphQL service.

type Supergraph

type Supergraph struct {
	// contains filtered or unexported fields
}

Supergraph holds parsed routing information extracted from a supergraph SDL.

func ParseSchema

func ParseSchema(sdl string) (*Supergraph, error)

ParseSchema parses a Federation v2 supergraph SDL and returns a Supergraph routing table populated with subgraph URLs, type ownership, and field metadata extracted from @join__type / @join__field directives.

func (*Supergraph) FieldIsList

func (sg *Supergraph) FieldIsList(typeName, fieldName string) bool

FieldIsList reports whether a field on a type returns a list.

func (*Supergraph) FieldProvides

func (sg *Supergraph) FieldProvides(typeName, fieldName string) string

FieldProvides returns the raw @provides field set for a field (e.g. "totalProductsCreated"), or "" if the field has no @provides.

func (*Supergraph) FieldRequires

func (sg *Supergraph) FieldRequires(typeName, fieldName string) string

FieldRequires returns the raw @requires field set for a field (e.g. "id email"), or "" if the field has no @requires.

func (*Supergraph) FieldTypeName

func (sg *Supergraph) FieldTypeName(typeName, fieldName string) string

FieldTypeName returns the base return type name of a field (no !, no []).

func (*Supergraph) KeysFor

func (sg *Supergraph) KeysFor(typeName, subgraphEnum string) []string

KeysFor returns the key field names for a type in a given subgraph, parsed from the @join__type key argument (e.g. "id email" → ["id","email"]). Falls back to ["id"] when not specified.

func (*Supergraph) OwnerOf

func (sg *Supergraph) OwnerOf(typeName, fieldName string) string

OwnerOf returns the subgraph enum name owning a field on a type, or "" if unknown.

func (*Supergraph) SubgraphByEnum

func (sg *Supergraph) SubgraphByEnum(name string) *Subgraph

SubgraphByEnum returns the subgraph for an enum value name (e.g. "ACCOUNTS").

func (*Supergraph) WithURLOverrides

func (sg *Supergraph) WithURLOverrides(overrides map[string]string) *Supergraph

WithURLOverrides returns a shallow copy of sg with the specified subgraph URLs replaced. Keys are join__Graph enum names (e.g. "PRODUCTS").

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL