Help us shape the future of Go! Take the 2026 Go Developer Survey

grpcdatasource

package
v2.30.5 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 41 Imported by: 6

Documentation

Overview

Package grpcdatasource provides a GraphQL datasource implementation for gRPC services. It allows GraphQL servers to connect to gRPC backends and execute RPC calls as part of GraphQL query resolution.

The package includes tools for parsing Protobuf definitions, building execution plans, and converting GraphQL queries into gRPC requests.

Index

Constants

View Source
const (
	// InvalidRef is a constant used to indicate that a reference is invalid.
	InvalidRef = -1
)

Variables

This section is empty.

Functions

This section is empty.

Types

type CallKind

type CallKind uint8

CallKind is the type of call operation to perform.

const (
	// CallKindStandard is a basic fetch operation.
	CallKindStandard CallKind = iota
	// CallKindEntity is a fetch operation for entities.
	CallKindEntity
	// CallKindResolve is a fetch operation for resolving field values.
	CallKindResolve
	// CallKindRequired is a fetch operation which is similar to Resolve, but it can be executed in parallel.
	// Required fields are indicated by the @requires federation directive.
	CallKindRequired
)

type ConnectEncoding added in v2.11.0

type ConnectEncoding string

ConnectEncoding selects the wire format for Connect protocol requests. It is declared as a string so that router/config layers can pass values through unchanged from YAML/JSON without intermediate translation. The zero value ("") is treated as ConnectEncodingProtobuf for safety.

const (
	// ConnectEncodingProtobuf uses binary protobuf encoding.
	ConnectEncodingProtobuf ConnectEncoding = "proto"
	// ConnectEncodingJSON uses JSON encoding via protojson.
	ConnectEncodingJSON ConnectEncoding = "json"
)

type ConnectTransportConfig added in v2.11.0

type ConnectTransportConfig struct {
	// BaseURL is the base URL of the Connect service (e.g., "http://localhost:8080").
	BaseURL string
	// HTTPClient is the HTTP client to use. If nil, http.DefaultClient is used.
	HTTPClient connect.HTTPClient
	// Encoding specifies the serialization format (Protobuf or JSON).
	Encoding ConnectEncoding
	// Interceptors are applied, in order, to every Connect client this
	// transport constructs. Use them for cross-cutting concerns such as
	// tracing, logging, retries, or auth header injection. The slice is
	// captured at construction time; mutating it after NewConnectTransport
	// returns has no effect.
	Interceptors []connect.Interceptor
}

ConnectTransportConfig holds the configuration for creating a Connect transport.

type DataSource

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

DataSource implements the resolve.DataSource interface for gRPC services. It handles the conversion of GraphQL queries to gRPC requests and transforms the responses back to GraphQL format.

func NewDataSource

func NewDataSource(transport RPCTransport, config DataSourceConfig) (*DataSource, error)

NewDataSource creates a new datasource with the given RPCTransport.

func (*DataSource) Load

func (d *DataSource) Load(ctx context.Context, headers http.Header, input []byte) (data []byte, err error)

Load implements resolve.DataSource interface. It processes the input JSON data to make gRPC calls and returns the response data.

Headers are converted to gRPC metadata and are part of gRPC calls.

The input is expected to contain the necessary information to make a gRPC call, including service name, method name, and request data.

func (*DataSource) LoadWithFiles

func (d *DataSource) LoadWithFiles(ctx context.Context, headers http.Header, input []byte, files []*httpclient.FileUpload) (data []byte, err error)

LoadWithFiles implements resolve.DataSource interface. Similar to Load, but handles file uploads if needed.

Note: File uploads are typically not part of gRPC, so this method might not be applicable for most gRPC use cases.

Currently unimplemented.

type DataSourceConfig

type DataSourceConfig struct {
	// Operation is the GraphQL operation to plan.
	Operation *ast.Document
	// Definition is the GraphQL schema of the subgraph.
	Definition *ast.Document
	// Compiler holds the compiled protobuf schema.
	Compiler *RPCCompiler
	// SubgraphName is the name of the subgraph.
	SubgraphName string
	// Mapping maps GraphQL types and fields to gRPC messages and RPCs.
	Mapping *GRPCMapping
	// FederationConfigs holds the federation field configurations.
	FederationConfigs plan.FederationFieldConfigurations
	// Disabled returns an error instead of executing the operation.
	Disabled bool
	// UseProtoReflect builds gRPC requests with protoreflect instead of wire encoding.
	UseProtoReflect bool
}

type DataType

type DataType int8

DataType represents the different types of data that can be stored in a protobuf field.

const (
	DataTypeUnknown DataType = -1 // Represents an unknown or unsupported type
	DataTypeDouble  DataType = 1  // 64-bit floating point type (protoref.DoubleKind)
	DataTypeFloat   DataType = 2  // 32-bit floating point type (protoref.FloatKind)
	DataTypeInt64   DataType = 3  // 64-bit integer type (protoref.Int64Kind)
	DataTypeUint64  DataType = 4  // 64-bit unsigned integer type (protoref.Uint64Kind)
	DataTypeInt32   DataType = 5  // 32-bit integer type (protoref.Int32Kind)
	DataTypeBool    DataType = 8  // Boolean type (protoref.BoolKind)
	DataTypeString  DataType = 9  // String type (protoref.StringKind)
	DataTypeMessage DataType = 11 // Nested message type (protoref.MessageKind)
	DataTypeBytes   DataType = 12 // Bytes type (protoref.BytesKind)
	DataTypeUint32  DataType = 13 // 32-bit unsigned integer type (protoref.Uint32Kind)
	DataTypeEnum    DataType = 14 // Enumeration type (protoref.EnumKind)
)

Protobuf data types supported by the compiler. These values intentionally match the google.protobuf.FieldDescriptorProto.Type enum (exposed via protoref.Kind) for efficient conversion. The protobuf spec has been stable since 2008, so these values are unlikely to change.

func (DataType) String

func (i DataType) String() string

type Document

type Document struct {
	Package  string    // The package name of the protobuf document
	Imports  []string  // The imports of the protobuf document
	Services []Service // All services defined in the document
	Enums    []Enum    // All enums defined in the document
	Messages []Message // All messages defined in the document
	Methods  []Method  // All methods from all services in the document
	// contains filtered or unexported fields
}

Document represents a compiled protobuf document with all its services, messages, and methods.

func (*Document) MessageByName

func (d *Document) MessageByName(name string) (Message, bool)

MessageByName returns a Message by its name. Returns false if no message with the given name exists. We only expect this function to return false if either the message name was provided incorrectly, or the schema and mapping was not properly configured.

func (*Document) MessageRefByName

func (d *Document) MessageRefByName(name string) int

MessageRefByName returns the index of a Message in the Messages slice by its name. Returns -1 if no message with the given name exists.

type EntityRPCConfig

type EntityRPCConfig struct {
	// RPCConfig is the embedded configuration for the RPC operation
	RPCConfig

	// Key is a list of field names that uniquely identify the entity
	Key string

	// RequiredFields is the configuration for the required fields method
	RequiredFields RequiredFieldsRPCMapping
}

EntityRPCConfig defines the configuration for entity lookups

type Enum

type Enum struct {
	Name   string      // The name of the enum
	Values []EnumValue // The values in the enum
}

Enum represents a protobuf enum type with its values.

type EnumValue

type EnumValue struct {
	Name         string // The name of the enum value
	GraphqlValue string // The target value of the enum value
	Number       int32  // The numeric value of the enum value
}

EnumValue represents a single value in a protobuf enum.

type EnumValueMapping

type EnumValueMapping struct {
	Value       string // The GraphQL enum value
	TargetValue string // The gRPC enum value
}

EnumValueMapping defines the mapping between a GraphQL enum value and a gRPC enum value

type FieldArgumentMap

type FieldArgumentMap map[string]string

FieldArgumentMap defines the mapping between a GraphQL field argument and a gRPC field

type FieldMap

type FieldMap map[string]FieldMapData

FieldMap defines the mapping between a GraphQL field and a gRPC field The key is the field name in the GraphQL type. The value is the FieldMapData for that field which contains the target name and the argument mappings.

type FieldMapData

type FieldMapData struct {
	TargetName       string           // The name of the gRPC field
	ArgumentMappings FieldArgumentMap // The mapping between GraphQL field arguments and gRPC request arguments
}

FieldMapData defines the mapping between a GraphQL field and a gRPC field

type GRPCConfiguration

type GRPCConfiguration struct {
	Disabled        bool         // Whether the RPC is disabled
	Mapping         *GRPCMapping // The mapping between GraphQL types and gRPC messages
	Compiler        *RPCCompiler // The compiler for the RPC
	UseProtoReflect bool         // Whether to use protoreflect instead of wire encoding for gRPC requests
}

GRPCConfiguration defines the configuration for a gRPC datasource

type GRPCMapping

type GRPCMapping struct {
	// Service is the name of the gRPC service to use
	Service string
	// QueryRPCs maps GraphQL query fields to the corresponding gRPC RPC configurations
	QueryRPCs RPCConfigMap[RPCConfig]
	// MutationRPCs maps GraphQL mutation fields to the corresponding gRPC RPC configurations
	MutationRPCs RPCConfigMap[RPCConfig]
	// SubscriptionRPCs maps GraphQL subscription fields to the corresponding gRPC RPC configurations
	SubscriptionRPCs RPCConfigMap[RPCConfig]
	// ResolveRPCs maps GraphQL resolve fields to the corresponding gRPC RPC configurations
	ResolveRPCs RPCConfigMap[ResolveRPCMapping]
	// EntityRPCs defines how GraphQL types are resolved as entities using specific RPCs
	// The key is the type name and the value is a list of EntityRPCConfig for that type
	EntityRPCs map[string][]EntityRPCConfig
	// Fields defines the field mappings between GraphQL types and gRPC messages
	// The key is the type name and the value is a map of field name to FieldMapData for that type
	Fields map[string]FieldMap
	// EnumValues defines the enum values for each enum type
	// The key is the enum type name and the value is a list of EnumValueMapping for that enum type
	EnumValues map[string][]EnumValueMapping
}

func (*GRPCMapping) FindEntityRPCConfig

func (g *GRPCMapping) FindEntityRPCConfig(typeName, key string) (RPCConfig, bool)

FindEntityRPCConfig finds the gRPC RPC config for a given GraphQL type and key

func (*GRPCMapping) FindEnumValueMapping

func (g *GRPCMapping) FindEnumValueMapping(enumName, enumValue string) (string, bool)

FindEnumValueMapping finds the gRPC enum value for a given GraphQL enum value

func (*GRPCMapping) FindFieldArgumentMapping

func (g *GRPCMapping) FindFieldArgumentMapping(typeName, fieldName, argumentName string) (string, bool)

FindFieldArgumentMapping finds the gRPC field name for a given GraphQL field name and argument name

func (*GRPCMapping) FindFieldMapping

func (g *GRPCMapping) FindFieldMapping(typeName string, fieldName string) (string, bool)

FindFieldMapping finds the gRPC field name for a given GraphQL field name and type

func (*GRPCMapping) FindRequiredFieldsRPCConfig

func (g *GRPCMapping) FindRequiredFieldsRPCConfig(typeName, key, field string) (RequiredFieldsRPCTypeField, bool)

func (*GRPCMapping) FindResolveTypeFieldMapping

func (g *GRPCMapping) FindResolveTypeFieldMapping(typeName, fieldName string) *ResolveRPCTypeField

FindResolveTypeFieldMapping finds the gRPC field name for a given GraphQL field name and type

type LevelInfo

type LevelInfo struct {
	// Optional indicates if the field is optional
	Optional bool
}

LevelInfo contains the metadata for the list type

type ListMetadata

type ListMetadata struct {
	// NestingLevel is the nesting level of the list type
	NestingLevel int
	// LevelInfo contains the metadata for each nesting level of the list
	LevelInfo []LevelInfo
}

ListMetadata contains the metadata for the list type

type Message

type Message struct {
	Name string                     // The name of the message
	Desc protoref.MessageDescriptor // The protobuf descriptor for the message
}

Message represents a protobuf message type.

type Method

type Method struct {
	Name      string // The name of the method
	InputRef  int    // Reference to the input message in the Document.Messages slice
	OutputRef int    // Reference to the output message in the Document.Messages slice
}

Method represents a gRPC method with input and output message types.

type NodeKind

type NodeKind int
const (
	NodeKindMessage NodeKind = iota + 1
	NodeKindEnum
	NodeKindService
	NodeKindUnknown
)

type OneOfType

type OneOfType uint8

OneOfType represents the type of a oneof field in a protobuf message. It can be either an interface or a union type.

const (
	// OneOfTypeNone represents no oneof type (default/zero value)
	OneOfTypeNone OneOfType = iota
	// OneOfTypeInterface represents an interface type oneof field
	OneOfTypeInterface
	// OneOfTypeUnion represents a union type oneof field
	OneOfTypeUnion
)

OneOfType constants define the different types of oneof fields.

func (OneOfType) FieldName

func (o OneOfType) FieldName() string

FieldName returns the corresponding field name for the OneOfType. For interfaces, it returns "instance", for unions it returns "value". Returns an empty string for invalid or unknown types.

type PlanVisitor

type PlanVisitor interface {
	PlanOperation(operation, definition *ast.Document) (*RPCExecutionPlan, error)
}

func NewPlanner

func NewPlanner(subgraphName string, mapping *GRPCMapping, federationConfigs plan.FederationFieldConfigurations) (PlanVisitor, error)

NewPlanner returns a new PlanVisitor instance.

The planner is responsible for creating an RPCExecutionPlan from a given GraphQL operation. It is used by the engine to execute operations against gRPC services.

type PreWiredInputMessage added in v2.27.0

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

func NewPreWiredInputMessage added in v2.27.0

func NewPreWiredInputMessage(buffer []byte) *PreWiredInputMessage

type RPCCall

type RPCCall struct {
	// ID indicates the expected index of the call in the execution plan
	ID int
	// Kind of call, used to decide how to execute the call
	// This is used to identify the call type and execution behaviour.
	Kind CallKind
	// DependentCalls is a list of calls that must be executed before this call
	DependentCalls []int
	// ServiceName is the name of the gRPC service to call
	ServiceName string
	// MethodName is the name of the method on the service to call
	MethodName string
	// Request contains the message structure for the gRPC request
	Request RPCMessage
	// Response contains the message structure for the gRPC response
	Response RPCMessage
	// ResponsePath is the path to the response in the JSON response
	ResponsePath ast.Path
	// RequestedEntityType is the type of the entity that is being requested
	// Empty if the call is not an entity lookup.
	RequestedEntityType string
}

RPCCall represents a single call to a gRPC service method. It contains all the information needed to make the call and process the response.

type RPCCompiler

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

RPCCompiler compiles protobuf schema strings into a Document and runtime schema.

func NewProtoCompiler

func NewProtoCompiler(schema string, mapping *GRPCMapping) (*RPCCompiler, error)

NewProtoCompiler compiles the protobuf schema into a Document structure. It extracts information about services, methods, messages, and enums from the protobuf schema.

type RPCConfig

type RPCConfig struct {
	// RPC is the name of the RPC method to call
	RPC string
	// Request is the name of the request message type
	Request string
	// Response is the name of the response message type
	Response string
}

RPCConfig defines the configuration for a specific RPC operation

type RPCConfigMap

type RPCConfigMap[T RPCMapping] map[string]T

RPCConfigMap is a map of RPC names to RPC configurations The key is the field name in the GraphQL operation type (query, mutation, subscription). The value is the RPC configuration for that field.

type RPCExecutionPlan

type RPCExecutionPlan struct {
	// Calls is a list of gRPC calls that are executed in the same group
	Calls []RPCCall
}

RPCExecutionPlan represents a plan for executing one or more RPC calls to gRPC services. It defines the sequence of calls and their dependencies.

func (*RPCExecutionPlan) String

func (r *RPCExecutionPlan) String() string

type RPCField

type RPCField struct {
	// Alias can be used to rename the field in the request message
	// This is needed to make sure that during the json composition,
	// the field names match the GraphQL request naming.
	Alias string
	// Repeated indicates if the field is a repeated field (array/list)
	Repeated bool
	// Name is the name of the field as defined in the protobuf message
	Name string
	// ProtoTypeName is the name of the type of the field in the protobuf definition
	ProtoTypeName DataType
	// JSONPath either holds the path to the variable definition for the request message,
	// or defines the name of the response field in the message.
	JSONPath string
	// ResolvePath is used to resolve values from another message.
	ResolvePath ast.Path
	// EnumName is the name of the enum if the field is an enum type
	EnumName string
	// StaticValue is the static value of the field
	StaticValue string
	// Optional indicates if the field is optional
	Optional bool
	// IsListType indicates if the field is a list wrapper type
	IsListType bool
	// ListMetadata contains the metadata for the list type
	ListMetadata *ListMetadata
	// Message represents the nested message type definition for complex fields.
	// This enables recursive construction of nested protobuf message structures.
	Message *RPCMessage
}

RPCField represents a single field in a gRPC message. It contains all information required to extract data from GraphQL variables and construct the appropriate protobuf field.

func (*RPCField) AliasOrPath

func (r *RPCField) AliasOrPath() string

AliasOrPath returns the alias of the field if it exists, otherwise it returns the JSONPath.

func (*RPCField) IsOptionalScalar

func (r *RPCField) IsOptionalScalar() bool

IsOptionalScalar checks if the field is an optional scalar value that is wrapped in a google.protobuf.*Value message. Nullable enums are plain proto enum fields: protobuf has no wrapper type for them.

func (*RPCField) ToOptionalTypeMessage

func (r *RPCField) ToOptionalTypeMessage(protoName string) *RPCMessage

ToOptionalTypeMessage returns a message that wraps the scalar value in a message as protobuf scalar types are not nullable.

type RPCFieldSelectionSet

type RPCFieldSelectionSet map[string]RPCFields

RPCFieldSelectionSet is a map of field selections based on inline fragments

func (RPCFieldSelectionSet) Add

func (r RPCFieldSelectionSet) Add(fragmentName string, field ...RPCField)

Add adds a field selection set to the map

func (RPCFieldSelectionSet) SelectFieldsForTypes

func (r RPCFieldSelectionSet) SelectFieldsForTypes(validTypes []string) RPCFields

SelectFieldsForTypes returns the fields for the given valid types. It also makes sure to deduplicate the fields.

type RPCFields

type RPCFields []RPCField

RPCFields is a list of RPCFields that provides helper methods for working with collections of fields.

func (RPCFields) ByName

func (r RPCFields) ByName(name string) *RPCField

ByName returns a field by its name from the collection of fields. Returns nil if no field with the given name exists.

func (RPCFields) Exists

func (r RPCFields) Exists(name, alias string) bool

Exists checks if a field with the given name and alias exists in the collection of fields.

func (RPCFields) Last

func (r RPCFields) Last() *RPCField

Last returns the last element of r or nil if r has no elements.

type RPCMapping

type RPCMapping interface {
	RPCConfig | ResolveRPCMapping
}

LookupFieldMapDefinition defines the mapping between a GraphQL field and a gRPC field

type RPCMessage

type RPCMessage struct {
	// Name is the name of the message type in the protobuf definition
	Name string
	// Fields is a list of fields in the message
	Fields RPCFields
	// FragmentFields are field selections based on inline fragments
	FragmentFields RPCFieldSelectionSet
	// OneOfType indicates the type of the oneof field
	OneOfType OneOfType
	// MemberTypes provides the names of the types that are implemented by the Interface or Union
	MemberTypes []string
}

RPCMessage represents a gRPC message structure for requests and responses. It defines the structure of the message including all its fields.

func (*RPCMessage) IsOneOf

func (r *RPCMessage) IsOneOf() bool

IsOneOf checks if the message is a oneof field.

func (*RPCMessage) SelectValidTypes

func (r *RPCMessage) SelectValidTypes(typeName string) []string

SelectValidTypes returns the valid types for a given type name.

type RPCTransport added in v2.4.0

type RPCTransport interface {
	// Invoke dispatches a unary call against the remote service.
	//   - methodFullName is the gRPC-style procedure path "/package.Service/Method"
	//     (leading slash required). The gRPC transport passes it directly to
	//     grpc.ClientConnInterface.Invoke; the Connect transport appends it to
	//     the configured base URL.
	//   - input is a *PreWiredInputMessage (pre-encoded wire bytes) for the gRPC
	//     transport, or a *dynamicpb.Message populated by the caller for the
	//     Connect transport.
	//   - output must be a *dynamicpb.Message bound to the expected response
	//     descriptor; Invoke populates it on success.
	Invoke(ctx context.Context, methodFullName string, input, output any) error
}

RPCTransport abstracts the transport protocol for RPC calls. Both gRPC and Connect implement this interface.

func NewConnectTransport added in v2.11.0

func NewConnectTransport(config ConnectTransportConfig) RPCTransport

NewConnectTransport creates an RPCTransport that uses the Connect protocol.

func NewGRPCTransport added in v2.4.0

func NewGRPCTransport(cc grpc.ClientConnInterface) RPCTransport

NewGRPCTransport creates an RPCTransport that delegates to a gRPC ClientConnInterface.

type RequiredFieldsRPCMapping

type RequiredFieldsRPCMapping map[string]RequiredFieldsRPCTypeField

RequiredFieldsRPCMapping defines the mapping between a federation @requires fields and the gRPC RPC configurations

type RequiredFieldsRPCTypeField

type RequiredFieldsRPCTypeField struct {
	RPCConfig

	// TargetName is the name of the gRPC field that is used to store the required fields arguments
	TargetName string
}

RequiredFieldsRPCTypeField defines the mapping between a federation @requires field and a gRPC RPC configuration

type ResolveRPCMapping

type ResolveRPCMapping map[string]ResolveRPCTypeField

ResolveRPCMapping defines the mapping between a GraphQL field resolver and a gRPC RPC configuration

type ResolveRPCTypeField

type ResolveRPCTypeField struct {
	FieldMappingData FieldMapData // The mapping between GraphQL field arguments and gRPC request arguments
	RPC              string       // The name of the RPC method to call
	Request          string       // The name of the request message type
	Response         string       // The name of the response message type
}

ResolveRPCTypeField defines the mapping between a GraphQL resolve field and a gRPC RPC configuration

type Service

type Service struct {
	Name        string // The name of the service
	FullName    string // The full name of the service
	MethodsRefs []int  // References to methods in the Document.Methods slice
}

Service represents a gRPC service with methods.

Jump to

Keyboard shortcuts

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