Documentation
¶
Index ¶
- Constants
- Variables
- func AddCacheControlPolicyToRules(rules *config.HeaderRules, cacheControl config.CacheControlPolicy) *config.HeaderRules
- func CorsDefaultOptions() *cors.Config
- func CreateGRPCTraceGetter(telemetryAttributeExpressions *attributeExpressions, ...) func(context.Context) (string, otrace.SpanStartEventOption)
- func DefaultFileUploadConfig() *config.FileUpload
- func DefaultRouterTrafficConfig() *config.RouterTrafficConfiguration
- func FetchURLRules(rules *config.HeaderRules, subgraphs []*nodev1.Subgraph, routingURL string) []*config.RequestHeaderRule
- func GetLogFieldFromCustomAttribute(field config.CustomAttribute, req *requestContext, err any) zap.Field
- func GetSpanName(operationName string, operationType string) string
- func GetSubscriptionResponseWriter(ctx *resolve.Context, r *http.Request, w http.ResponseWriter, ...) (*resolve.Context, resolve.SubscriptionResponseWriter, bool)
- func GetWriterPrefix(sse bool, multipart bool, firstMessage bool) string
- func Handler(handlerOpts HandlerOpts) http.Handler
- func HeaderPropagationWriter(w http.ResponseWriter, resolveCtx *resolve.Context, setContentLength bool) io.Writer
- func InitializeConfigPoller(r *Router, cdnProviders map[string]config.CDNStorageProvider, ...) (*configpoller.ConfigPoller, error)
- func LogLevelHandler(r *http.Request) zapcore.Level
- func MetricConfigFromTelemetry(cfg *config.Telemetry) *rmetric.Config
- func NewBoolLogField(val bool, attribute config.CustomAttribute) zap.Field
- func NewDurationLogField(val time.Duration, attribute config.CustomAttribute) zap.Field
- func NewEngineRequestHooks(metricStore metric.Store, logger *requestlogger.SubgraphAccessLogger, ...) resolve.LoaderHooks
- func NewEngineSubscriptionOnStartHook(fn func(ctx SubscriptionOnStartHandlerContext) error) graphql_datasource.SubscriptionOnStartFn
- func NewExpressionLogField(val any, key string, defaultValue any) zap.Field
- func NewPubSubOnPublishEventsHook(...) datasource.OnPublishEventsFn
- func NewPubSubOnReceiveEventsHook(...) datasource.OnReceiveEventsFn
- func NewPubSubSubscriptionOnStartHook(fn func(ctx SubscriptionOnStartHandlerContext) error) datasource.SubscriptionOnStartFn
- func NewStringLogField(val string, attribute config.CustomAttribute) zap.Field
- func NewStringSliceLogField(val []string, attribute config.CustomAttribute) zap.Field
- func NewWebsocketMiddleware(ctx context.Context, opts WebsocketMiddlewareOptions) func(http.Handler) http.Handler
- func ProcessRetryOptions(retryOpts retrytransport.RetryOptions) (*retrytransport.RetryOptions, error)
- func PropagatedHeaders(rules []*config.RequestHeaderRule) (headerNames []string, headerNameRegexps []graphql_datasource.RegularExpression, ...)
- func RegisterModule(instance Module)
- func RouterAccessLogsFieldHandler(logger *zap.Logger, attributes []config.CustomAttribute, ...) []zapcore.Field
- func SpanNameFormatter(_ string, r *http.Request) string
- func SubgraphAccessLogsFieldHandler(logger *zap.Logger, attributes []config.CustomAttribute, ...) []zapcore.Field
- func SubgraphHeadersBuilder(ctx *requestContext, headerPropagation *HeaderPropagation, ...) resolve.SubgraphHeadersBuilder
- func SubgraphRules(rules *config.HeaderRules, subgraphName string) []*config.RequestHeaderRule
- func TraceConfigFromTelemetry(cfg *config.Telemetry) *rtrace.Config
- func WarmupCaches(ctx context.Context, cfg *CacheWarmupConfig) (err error)
- func WithAuthorizationExtension(ctx *resolve.Context) *resolve.Context
- func WithRateLimiterStats(ctx *resolve.Context) *resolve.Context
- func WithResponseHeaderPropagation(ctx *resolve.Context) *resolve.Context
- func WrapExprError(err error) error
- func WriteResponseError(ctx RequestContext, err error)
- type AccessController
- type AccessControllerOptions
- type AccessLogsConfig
- type AddExprOpts
- type ApiTransportFactory
- type AuthorizationExtension
- type BatchedOperationId
- type BatchingConfig
- type BlockMutationOptions
- type BlockNonPersistedOptions
- type BlockPersistedOptions
- type BlockSubscriptionOptions
- type BuildGraphMuxOptions
- type CDNSource
- type CacheWarmupConfig
- type CacheWarmupItem
- type CacheWarmupOperationPlanResult
- type CacheWarmupPlanningProcessor
- type CacheWarmupPlanningProcessorOptions
- type CacheWarmupProcessor
- type CacheWarmupSource
- type Cleaner
- type ClientInfo
- type ComplexityCacheEntry
- type Config
- type CosmoAuthorizer
- func (a *CosmoAuthorizer) AuthorizeObjectField(ctx *resolve.Context, dataSourceID string, object json.RawMessage, ...) (result *resolve.AuthorizationDeny, err error)
- func (a *CosmoAuthorizer) AuthorizePreFetch(ctx *resolve.Context, dataSourceID string, input json.RawMessage, ...) (result *resolve.AuthorizationDeny, err error)
- func (a *CosmoAuthorizer) HasResponseExtensionData(ctx *resolve.Context) bool
- func (a *CosmoAuthorizer) RenderResponseExtension(ctx *resolve.Context, out io.Writer) error
- type CosmoAuthorizerOptions
- type CosmoRateLimiter
- func (c *CosmoRateLimiter) RateLimitPreFetch(ctx *resolve.Context, info *resolve.FetchInfo, input json.RawMessage) (result *resolve.RateLimitDeny, err error)
- func (c *CosmoRateLimiter) RejectStatusCode() int
- func (c *CosmoRateLimiter) RenderResponseExtension(ctx *resolve.Context, out io.Writer) error
- type CosmoRateLimiterOptions
- type CustomTransport
- type DefaultFactoryResolver
- func (d *DefaultFactoryResolver) InstanceData() InstanceData
- func (d *DefaultFactoryResolver) ResolveGraphqlFactory(subgraphName string) (plan.PlannerFactory[graphql_datasource.Configuration], error)
- func (d *DefaultFactoryResolver) ResolveStaticFactory() (factory plan.PlannerFactory[staticdatasource.Configuration], err error)
- type DialerFunc
- type EngineEvent
- type EnginePostOriginHandler
- type EnginePreOriginHandler
- type ExecutionConfig
- type ExecutionPlanCache
- type Executor
- type ExecutorBuildOptions
- type ExecutorConfigurationBuilder
- type ExprWrapError
- type Extensions
- type FactoryResolver
- type FileSystemSource
- type FileSystemSourceConfig
- type GraphQLErrorResponse
- type GraphQLHandler
- type GraphQLMetricsConfig
- type GraphQLRequest
- type GraphQLRequestExtensions
- type GraphQLRequestExtensionsPersistedQuery
- type HandlerOptions
- type HandlerOpts
- type HeaderPropagation
- func (h *HeaderPropagation) ApplyResponseHeaderRules(ctx context.Context, headers http.Header, subgraphName string, statusCode int, ...)
- func (h *HeaderPropagation) ApplyRouterResponseHeaderRules(w http.ResponseWriter, reqCtx *requestContext) error
- func (h *HeaderPropagation) BuildRequestHeaderForSubgraph(subgraphName string, ctx *requestContext) (http.Header, uint64)
- func (h *HeaderPropagation) HasRequestRules() bool
- func (h *HeaderPropagation) HasResponseRules() bool
- func (h *HeaderPropagation) OnOriginResponse(resp *http.Response, ctx RequestContext) *http.Response
- type HeaderWithHash
- type HttpError
- type HttpFlushWriter
- type IPAnonymizationConfig
- type IPAnonymizationMethod
- type InMemoryPlanCacheFallback
- type InstanceData
- type Loader
- type MissingScopesError
- type Module
- type ModuleContext
- type ModuleID
- type ModuleInfo
- type ModuleRequestContext
- type MultipartParser
- type MutableEngineEvent
- type NormalizationCacheEntry
- type OperationBlocker
- type OperationBlockerOptions
- type OperationCache
- type OperationContext
- type OperationKit
- func (o *OperationKit) ComputeOperationSha256() error
- func (o *OperationKit) FetchPersistedOperation(ctx context.Context, clientInfo *ClientInfo) (skipParse bool, isAPQ bool, err error)
- func (o *OperationKit) Free()
- func (o *OperationKit) NormalizeOperation(clientName string, isApq bool) (bool, error)
- func (o *OperationKit) NormalizeVariables() (cached bool, mapping []uploads.UploadPathMapping, err error)
- func (o *OperationKit) Parse() error
- func (o *OperationKit) RemapVariables(disabled bool) (cached bool, err error)
- func (o *OperationKit) UnmarshalOperationFromBody(data []byte) error
- func (o *OperationKit) UnmarshalOperationFromURL(url *url.URL) error
- func (o *OperationKit) Validate(skipLoader bool, remapVariables map[string]string, ...) (cacheHit bool, err error)
- func (o *OperationKit) ValidateQueryComplexity() (ok bool, cacheEntry ComplexityCacheEntry, err error)
- type OperationMetrics
- type OperationMetricsOptions
- type OperationPlanner
- type OperationProcessor
- type OperationProcessorOptions
- type OperationProtocol
- type OperationTimes
- type OperationTimings
- type OperationType
- type Option
- func WithAccessController(controller *AccessController) Option
- func WithAccessLogs(cfg *AccessLogsConfig) Option
- func WithAnonymization(ipConfig *IPAnonymizationConfig) Option
- func WithApolloCompatibilityFlagsConfig(cfg config.ApolloCompatibilityFlags) Option
- func WithApolloRouterCompatibilityFlags(cfg config.ApolloRouterCompatibilityFlags) Option
- func WithAuthorizationConfig(cfg *config.AuthorizationConfiguration) Option
- func WithAutomatedPersistedQueriesConfig(cfg config.AutomaticPersistedQueriesConfig) Option
- func WithAwsLambdaRuntime() Option
- func WithBatching(cfg *BatchingConfig) Option
- func WithCDN(cfg config.CDNConfiguration) Option
- func WithCacheControlPolicy(cfg config.CacheControlPolicy) Option
- func WithCacheWarmupConfig(cfg *config.CacheWarmupConfiguration) Option
- func WithClientHeader(cfg config.ClientHeader) Option
- func WithClusterName(name string) Option
- func WithConfigPoller(cf configpoller.ConfigPoller) Option
- func WithConfigPollerConfig(cfg *RouterConfigPollerConfig) Option
- func WithConfigVersionHeader(include bool) Option
- func WithConnectRPC(cfg config.ConnectRPCConfiguration) Option
- func WithCors(corsOpts *cors.Config) Option
- func WithCustomModules(modules ...Module) Option
- func WithDemoMode(demoMode bool) Option
- func WithDevelopmentMode(enabled bool) Option
- func WithDisableUsageTracking() Option
- func WithEngineExecutionConfig(cfg config.EngineExecutionConfiguration) Option
- func WithEvents(cfg config.EventsConfiguration) Option
- func WithExecutionConfig(cfg *ExecutionConfig) Option
- func WithFileUploadConfig(cfg *config.FileUpload) Option
- func WithGracePeriod(timeout time.Duration) Option
- func WithGraphApiToken(token string) Option
- func WithGraphQLMetrics(cfg *GraphQLMetricsConfig) Option
- func WithGraphQLPath(p string) Option
- func WithGraphQLWebURL(p string) Option
- func WithHeaderRules(headers config.HeaderRules) Option
- func WithHealthCheckPath(path string) Option
- func WithHealthChecks(healthChecks health.Checker) Option
- func WithInstanceID(id string) Option
- func WithIntrospection(enable bool, config config.IntrospectionConfiguration) Option
- func WithListenerAddr(addr string) Option
- func WithLivenessCheckPath(path string) Option
- func WithLocalhostFallbackInsideDocker(fallback bool) Option
- func WithLogger(logger *zap.Logger) Option
- func WithMCP(cfg config.MCPConfiguration) Option
- func WithMetrics(cfg *rmetric.Config) Option
- func WithModulesConfig(config map[string]interface{}) Option
- func WithOverrideRoutingURL(overrideRoutingURL config.OverrideRoutingURLConfiguration) Option
- func WithOverrides(overrides config.OverridesConfiguration) Option
- func WithPersistedOperationsConfig(cfg config.PersistedOperationsConfig) Option
- func WithPlayground(enable bool) Option
- func WithPlaygroundConfig(c config.PlaygroundConfig) Option
- func WithPlaygroundPath(p string) Option
- func WithPlugins(cfg config.PluginsConfiguration) Option
- func WithProxy(proxy ProxyFunc) Option
- func WithQueryPlans(enabled bool) Option
- func WithRateLimitConfig(cfg *config.RateLimitConfiguration) Option
- func WithReadinessCheckPath(path string) Option
- func WithReloadPersistentState(cfg *ReloadPersistentState) Option
- func WithRouterTrafficConfig(cfg *config.RouterTrafficConfiguration) Option
- func WithSecurityConfig(cfg config.SecurityConfiguration) Option
- func WithSelfRegistration(sr selfregister.SelfRegister) Option
- func WithStaticExecutionConfig(cfg *nodev1.RouterConfig) Option
- func WithStorageProviders(cfg config.StorageProviders) Option
- func WithStreamsHandlerConfiguration(cfg config.StreamsHandlerConfiguration) Option
- func WithSubgraphCircuitBreakerOptions(opts *SubgraphCircuitBreakerOptions) Option
- func WithSubgraphErrorPropagation(cfg config.SubgraphErrorPropagationConfiguration) Option
- func WithSubgraphRetryOptions(enabled bool, algorithm string, maxRetryCount int, ...) Option
- func WithSubgraphTransportOptions(opts *SubgraphTransportOptions) Option
- func WithSubscriptionHeartbeatInterval(interval time.Duration) Option
- func WithTLSConfig(cfg *TlsConfig) Option
- func WithTelemetryAttributes(attributes []config.CustomAttribute) Option
- func WithTracing(cfg *rtrace.Config) Option
- func WithTracingAttributes(attributes []config.CustomAttribute) Option
- func WithWebSocketConfiguration(cfg *config.WebSocketConfiguration) Option
- type ParsedOperation
- type PlanGenerator
- type PlanOptions
- type PlanOutputFormat
- type PlanSource
- type Planner
- func (pl *Planner) ParseAndPrepareOperation(operationFilePath string) (*ast.Document, OperationTimes, error)
- func (pl *Planner) PlanOperation(operationFilePath string, outputFormat PlanOutputFormat) (string, OperationTimes, error)
- func (pl *Planner) PlanPreparedOperation(operation *ast.Document) (planNode *resolve.FetchTreeQueryPlanNode, opTimes OperationTimes, err error)
- func (pl *Planner) PrepareOperation(operation *ast.Document) (*ast.Document, OperationTimes, error)
- type PlannerOperationValidationError
- type PreHandler
- type PreHandlerOptions
- type ProgramWithKey
- type Provisioner
- type ProxyFunc
- type QueryPlanStats
- type RateLimitStats
- type ReloadPersistentState
- type RemapVariablesCacheEntry
- type ReportError
- type RequestContext
- type RequiredAndScopes
- type Router
- type RouterConfigPollerConfig
- type RouterEngineConfiguration
- type RouterMetrics
- type RouterMiddlewareHandler
- type RouterOnRequestHandler
- type RouterResources
- type RouterSupervisor
- type RouterSupervisorOpts
- type SafelistPersistedOptions
- type Server
- type StreamHandlerError
- type StreamPublishEventHandler
- type StreamPublishEventHandlerContext
- type StreamReceiveEventHandler
- type StreamReceiveEventHandlerContext
- type Subgraph
- type SubgraphCircuitBreakerOptions
- type SubgraphResolver
- type SubgraphRootField
- type SubgraphTransportOptions
- type SubscriptionClientOptions
- type SubscriptionOnStartHandler
- type SubscriptionOnStartHandlerContext
- type SubscriptionParams
- type SubscriptionRegistration
- type TlsClientAuthConfig
- type TlsConfig
- type TraceDialer
- type TracePropagationProvider
- type TransportFactory
- type TransportOptions
- type TransportPostHandler
- type TransportPreHandler
- type TransportRequestOptions
- type UsageTracker
- type UsageTrackerNoOp
- type VariablesNormalizationCacheEntry
- type WebSocketConnectionHandler
- type WebSocketConnectionHandlerOptions
- type WebsocketHandler
- type WebsocketMiddlewareOptions
Constants ¶
const ( ExtensionCodeBatchSizeExceeded = "BATCH_LIMIT_EXCEEDED" ExtensionCodeBatchSubscriptionsUnsupported = "BATCHING_SUBSCRIPTION_UNSUPPORTED" )
const ( WgPrefix = "wg_" WgSseParam = WgPrefix + "sse" WgSubscribeOnceParam = WgPrefix + "subscribe_once" )
const ( ExecutionPlanCacheHeader = "X-WG-Execution-Plan-Cache" PersistedOperationCacheHeader = "X-WG-Persisted-Operation-Cache" NormalizationCacheHeader = "X-WG-Normalization-Cache" VariablesNormalizationCacheHeader = "X-WG-Variables-Normalization-Cache" VariablesRemappingCacheHeader = "X-WG-Variables-Remapping-Cache" )
const ( OperationProtocolHTTP = OperationProtocol("http") OperationProtocolGRPC = OperationProtocol("grpc") OperationProtocolWS = OperationProtocol("ws") )
const ( ContextFieldOperationName = "operation_name" ContextFieldOperationHash = "operation_hash" ContextFieldOperationType = "operation_type" ContextFieldOperationServices = "operation_service_names" ContextFieldGraphQLErrorCodes = "graphql_error_codes" ContextFieldGraphQLErrorServices = "graphql_error_service_names" ContextFieldOperationParsingTime = "operation_parsing_time" ContextFieldOperationValidationTime = "operation_validation_time" ContextFieldOperationPlanningTime = "operation_planning_time" ContextFieldOperationNormalizationTime = "operation_normalization_time" ContextFieldPersistedOperationSha256 = "persisted_operation_sha256" ContextFieldOperationSha256 = "operation_sha256" ContextFieldResponseErrorMessage = "response_error_message" ContextFieldRequestError = "request_error" ContextFieldRouterConfigVersion = "router_config_version" )
Context field names used to expose information about the operation being executed.
const ( // RequestTraceHeader is the header used to enable request tracing RequestTraceHeader = "X-WG-Trace" // RequestTraceQueryParameter is the query parameter used to enable request tracing RequestTraceQueryParameter = "wg_trace" )
const EngineLoaderHooksScopeName = "wundergraph/cosmo/router/engine/loader"
const EngineLoaderHooksScopeVersion = "0.0.1"
Variables ¶
var ( ErrMutationOperationBlocked = errors.New("operation type 'mutation' is blocked") ErrSubscriptionOperationBlocked = errors.New("operation type 'subscription' is blocked") ErrNonPersistedOperationBlocked = errors.New("non-persisted operation is blocked") ErrPersistedOperationBlocked = errors.New("persisted operation is blocked") )
var ( // Version set by the build system. Version = "dev" // Commit set by the build system. Commit = "" // Date set by the build system. Date = "" )
var CompressibleContentTypes = []string{
"text/html",
"text/css",
"text/plain",
"text/javascript",
"application/javascript",
"application/x-javascript",
"application/json",
"application/atom+xml",
"application/rss+xml",
"image/svg+xml",
"application/graphql",
"application/graphql-response+json",
"application/graphql+json",
}
var (
ErrRateLimitExceeded = errors.New("rate limit exceeded")
)
var (
ErrStartupFailed = errors.New("router start error")
)
var ( // and authorization requires authentication // or when authentication information is available but invalid ErrUnauthorized = errors.New("unauthorized") )
Functions ¶
func AddCacheControlPolicyToRules ¶
func AddCacheControlPolicyToRules(rules *config.HeaderRules, cacheControl config.CacheControlPolicy) *config.HeaderRules
func CorsDefaultOptions ¶
CorsDefaultOptions returns the default CORS options for the rs/cors package.
func CreateGRPCTraceGetter ¶
func CreateGRPCTraceGetter( telemetryAttributeExpressions *attributeExpressions, tracingAttributeExpressions *attributeExpressions, ) func(context.Context) (string, otrace.SpanStartEventOption)
func DefaultFileUploadConfig ¶
func DefaultFileUploadConfig() *config.FileUpload
func DefaultRouterTrafficConfig ¶
func DefaultRouterTrafficConfig() *config.RouterTrafficConfiguration
func FetchURLRules ¶
func FetchURLRules(rules *config.HeaderRules, subgraphs []*nodev1.Subgraph, routingURL string) []*config.RequestHeaderRule
FetchURLRules returns the list of header rules for first subgraph that matches the given URL
func GetLogFieldFromCustomAttribute ¶
func GetLogFieldFromCustomAttribute(field config.CustomAttribute, req *requestContext, err any) zap.Field
func GetSpanName ¶
func Handler ¶
func Handler(handlerOpts HandlerOpts) http.Handler
func HeaderPropagationWriter ¶
func InitializeConfigPoller ¶
func InitializeConfigPoller(r *Router, cdnProviders map[string]config.CDNStorageProvider, s3Providers map[string]config.S3StorageProvider) (*configpoller.ConfigPoller, error)
InitializeConfigPoller creates a poller to fetch execution config. It is only initialized when a config poller is configured and the router is not started with a static config
func NewBoolLogField ¶
func NewBoolLogField(val bool, attribute config.CustomAttribute) zap.Field
func NewDurationLogField ¶
func NewEngineRequestHooks ¶
func NewEngineRequestHooks( metricStore metric.Store, logger *requestlogger.SubgraphAccessLogger, tracerProvider *sdktrace.TracerProvider, tracingAttributes *attributeExpressions, telemetryAttributes *attributeExpressions, metricAttributes *attributeExpressions, storeSubgraphResponseBody bool, headerPropagation *HeaderPropagation, ) resolve.LoaderHooks
func NewEngineSubscriptionOnStartHook ¶
func NewEngineSubscriptionOnStartHook(fn func(ctx SubscriptionOnStartHandlerContext) error) graphql_datasource.SubscriptionOnStartFn
NewEngineSubscriptionOnStartHook converts a SubscriptionOnStartHandler to a graphql_datasource.SubscriptionOnStartFn
func NewExpressionLogField ¶
func NewPubSubOnPublishEventsHook ¶
func NewPubSubOnPublishEventsHook(fn func(ctx StreamPublishEventHandlerContext, events datasource.StreamEvents) (datasource.StreamEvents, error)) datasource.OnPublishEventsFn
func NewPubSubOnReceiveEventsHook ¶
func NewPubSubOnReceiveEventsHook(fn func(ctx StreamReceiveEventHandlerContext, events datasource.StreamEvents) (datasource.StreamEvents, error)) datasource.OnReceiveEventsFn
func NewPubSubSubscriptionOnStartHook ¶
func NewPubSubSubscriptionOnStartHook(fn func(ctx SubscriptionOnStartHandlerContext) error) datasource.SubscriptionOnStartFn
NewPubSubSubscriptionOnStartHook converts a SubscriptionOnStartHandler to a pubsub.SubscriptionOnStartFn
func NewStringLogField ¶
func NewStringLogField(val string, attribute config.CustomAttribute) zap.Field
func NewStringSliceLogField ¶
func NewStringSliceLogField(val []string, attribute config.CustomAttribute) zap.Field
func NewWebsocketMiddleware ¶
func ProcessRetryOptions ¶
func ProcessRetryOptions(retryOpts retrytransport.RetryOptions) (*retrytransport.RetryOptions, error)
func PropagatedHeaders ¶
func PropagatedHeaders(rules []*config.RequestHeaderRule) (headerNames []string, headerNameRegexps []graphql_datasource.RegularExpression, err error)
PropagatedHeaders returns the list of header names and regular expressions that will be propagated when applying the given rules.
func RegisterModule ¶
func RegisterModule(instance Module)
func RouterAccessLogsFieldHandler ¶
func RouterAccessLogsFieldHandler( logger *zap.Logger, attributes []config.CustomAttribute, exprAttributes []requestlogger.ExpressionAttribute, passedErr any, request *http.Request, responseHeader *http.Header, _ *expr.Context, ) []zapcore.Field
func SpanNameFormatter ¶
SpanNameFormatter formats the span name based on the http request
func SubgraphAccessLogsFieldHandler ¶
func SubgraphAccessLogsFieldHandler( logger *zap.Logger, attributes []config.CustomAttribute, exprAttributes []requestlogger.ExpressionAttribute, passedErr any, request *http.Request, responseHeader *http.Header, overrideExprCtx *expr.Context, ) []zapcore.Field
func SubgraphHeadersBuilder ¶
func SubgraphHeadersBuilder(ctx *requestContext, headerPropagation *HeaderPropagation, executionPlan plan.Plan) resolve.SubgraphHeadersBuilder
func SubgraphRules ¶
func SubgraphRules(rules *config.HeaderRules, subgraphName string) []*config.RequestHeaderRule
SubgraphRules returns the list of header rules for the subgraph with the given name
func WarmupCaches ¶
func WarmupCaches(ctx context.Context, cfg *CacheWarmupConfig) (err error)
func WrapExprError ¶
func WriteResponseError ¶
func WriteResponseError(ctx RequestContext, err error)
WriteResponseError writes the given error as a GraphQL error response to the http.ResponseWriter associated with the given RequestContext. If err is nil, a generic "Internal Error" error is returned. Please never write errors directly to the http.ResponseWriter. The function takes care of logging and tracking the error in the underlying telemetry system.
Types ¶
type AccessController ¶
type AccessController struct {
// contains filtered or unexported fields
}
AccessController handles both authentication and authorization for the Router
func NewAccessController ¶
func NewAccessController(opts AccessControllerOptions) (*AccessController, error)
NewAccessController creates a new AccessController. It returns an error if the introspection auth mode is invalid.
func (*AccessController) Access ¶
func (a *AccessController) Access(w http.ResponseWriter, r *http.Request) (*http.Request, error)
Access performs authorization and authentication, returning an error if the request should not proceed. If it succeeds, a new http.Request with an updated context.Context is returned.
func (*AccessController) IntrospectionAccess ¶
func (a *AccessController) IntrospectionAccess(r *http.Request, body []byte) bool
IntrospectionAccess is a dedicated access method check specifically for introspection queries. It should only be used when introspection authentication skip is enabled.
func (*AccessController) IntrospectionSecretConfigured ¶
func (a *AccessController) IntrospectionSecretConfigured() bool
type AccessControllerOptions ¶
type AccessControllerOptions struct {
Authenticators []authentication.Authenticator
AuthenticationRequired bool
SkipIntrospectionQueries bool
IntrospectionSkipSecret string
}
AccessControllerOptions holds configuration options for creating a new AccessController
type AccessLogsConfig ¶
type AccessLogsConfig struct {
Attributes []config.CustomAttribute
Logger *zap.Logger
SubgraphEnabled bool
SubgraphAttributes []config.CustomAttribute
IgnoreQueryParamsList []string
}
type AddExprOpts ¶
type AddExprOpts struct {
// contains filtered or unexported fields
}
type ApiTransportFactory ¶
type ApiTransportFactory interface {
RoundTripper(transport http.RoundTripper) http.RoundTripper
DefaultHTTPProxyURL() *url.URL
}
type AuthorizationExtension ¶
type AuthorizationExtension struct {
MissingScopes []MissingScopesError `json:"missingScopes,omitempty"`
ActualScopes []string `json:"actualScopes"`
}
type BatchedOperationId ¶
type BatchedOperationId struct{}
type BatchingConfig ¶
type BlockMutationOptions ¶
type BlockPersistedOptions ¶
type BuildGraphMuxOptions ¶
type BuildGraphMuxOptions struct {
FeatureFlagName string
RouterConfigVersion string
EngineConfig *nodev1.EngineConfiguration
ConfigSubgraphs []*nodev1.Subgraph
RoutingUrlGroupings map[string]map[string]bool
ReloadPersistentState *ReloadPersistentState
}
BuildGraphMuxOptions contains the configuration options for building a graph mux.
func (BuildGraphMuxOptions) IsBaseGraph ¶
func (b BuildGraphMuxOptions) IsBaseGraph() bool
type CDNSource ¶
type CDNSource struct {
// contains filtered or unexported fields
}
func NewCDNSource ¶
type CacheWarmupConfig ¶
type CacheWarmupConfig struct {
Log *zap.Logger
Source CacheWarmupSource
FallbackSource CacheWarmupSource
Workers int
ItemsPerSecond int
Timeout time.Duration
Processor CacheWarmupProcessor
AfterOperation func(item *CacheWarmupOperationPlanResult)
}
type CacheWarmupItem ¶
type CacheWarmupItem struct {
Request GraphQLRequest
Client *ClientInfo
}
type CacheWarmupPlanningProcessor ¶
type CacheWarmupPlanningProcessor struct {
// contains filtered or unexported fields
}
func NewCacheWarmupPlanningProcessor ¶
func NewCacheWarmupPlanningProcessor(options *CacheWarmupPlanningProcessorOptions) *CacheWarmupPlanningProcessor
func (*CacheWarmupPlanningProcessor) ProcessOperation ¶
func (c *CacheWarmupPlanningProcessor) ProcessOperation(ctx context.Context, operation *nodev1.Operation) (*CacheWarmupOperationPlanResult, error)
type CacheWarmupPlanningProcessorOptions ¶
type CacheWarmupPlanningProcessorOptions struct {
OperationProcessor *OperationProcessor
OperationPlanner *OperationPlanner
ComplexityLimits *config.ComplexityLimits
RouterSchema *ast.Document
TrackSchemaUsage bool
DisableVariablesRemapping bool
}
type CacheWarmupProcessor ¶
type CacheWarmupSource ¶
type CacheWarmupSource interface {
LoadItems(ctx context.Context, log *zap.Logger) ([]*nodev1.Operation, error)
}
func NewFileSystemSource ¶
func NewFileSystemSource(cfg *FileSystemSourceConfig) CacheWarmupSource
type Cleaner ¶
type Cleaner interface {
// Cleanup is called after the server stops
Cleanup() error
}
type ClientInfo ¶
type ClientInfo struct {
// Name contains the client name, derived from the request headers
Name string
// Version contains the client version, derived from the request headers
Version string
// WGRequestToken contains the token to authenticate the request from the platform
WGRequestToken string
}
func NewClientInfoFromRequest ¶
func NewClientInfoFromRequest(r *http.Request, clientHeader config.ClientHeader) *ClientInfo
type ComplexityCacheEntry ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
func (*Config) Usage ¶
Usage returns an anonymized version of the config for usage tracking The anonymized usage map is not containing any sensitive information It's not a anonymized copy of the config, but a map of properties explaining how the Router is configured The purpose is to get a high level understanding of which features are used instead of how exactly the Router is configured
type CosmoAuthorizer ¶
type CosmoAuthorizer struct {
// contains filtered or unexported fields
}
func NewCosmoAuthorizer ¶
func NewCosmoAuthorizer(opts *CosmoAuthorizerOptions) *CosmoAuthorizer
func (*CosmoAuthorizer) AuthorizeObjectField ¶
func (a *CosmoAuthorizer) AuthorizeObjectField(ctx *resolve.Context, dataSourceID string, object json.RawMessage, coordinate resolve.GraphCoordinate) (result *resolve.AuthorizationDeny, err error)
func (*CosmoAuthorizer) AuthorizePreFetch ¶
func (a *CosmoAuthorizer) AuthorizePreFetch(ctx *resolve.Context, dataSourceID string, input json.RawMessage, coordinate resolve.GraphCoordinate) (result *resolve.AuthorizationDeny, err error)
func (*CosmoAuthorizer) HasResponseExtensionData ¶
func (a *CosmoAuthorizer) HasResponseExtensionData(ctx *resolve.Context) bool
func (*CosmoAuthorizer) RenderResponseExtension ¶
type CosmoAuthorizerOptions ¶
type CosmoAuthorizerOptions struct {
FieldConfigurations []*nodev1.FieldConfiguration
}
type CosmoRateLimiter ¶
type CosmoRateLimiter struct {
// contains filtered or unexported fields
}
func NewCosmoRateLimiter ¶
func NewCosmoRateLimiter(opts *CosmoRateLimiterOptions) (rl *CosmoRateLimiter, err error)
func (*CosmoRateLimiter) RateLimitPreFetch ¶
func (c *CosmoRateLimiter) RateLimitPreFetch(ctx *resolve.Context, info *resolve.FetchInfo, input json.RawMessage) (result *resolve.RateLimitDeny, err error)
func (*CosmoRateLimiter) RejectStatusCode ¶
func (c *CosmoRateLimiter) RejectStatusCode() int
func (*CosmoRateLimiter) RenderResponseExtension ¶
type CosmoRateLimiterOptions ¶
type CustomTransport ¶
type CustomTransport struct {
// contains filtered or unexported fields
}
func NewCustomTransport ¶
func NewCustomTransport( baseRoundTripper http.RoundTripper, retryOptions retrytransport.RetryOptions, metricStore metric.Store, connectionMetricStore metric.ConnectionMetricStore, breaker *circuit.Manager, enableTraceClient bool, ) *CustomTransport
type DefaultFactoryResolver ¶
type DefaultFactoryResolver struct {
// contains filtered or unexported fields
}
func NewDefaultFactoryResolver ¶
func NewDefaultFactoryResolver( ctx context.Context, transportOptions *TransportOptions, subscriptionClientOptions *SubscriptionClientOptions, baseTransport http.RoundTripper, subgraphTransports map[string]http.RoundTripper, connector *grpcconnector.Connector, log *zap.Logger, enableNetPoll bool, instanceData InstanceData, ) *DefaultFactoryResolver
func (*DefaultFactoryResolver) InstanceData ¶
func (d *DefaultFactoryResolver) InstanceData() InstanceData
func (*DefaultFactoryResolver) ResolveGraphqlFactory ¶
func (d *DefaultFactoryResolver) ResolveGraphqlFactory(subgraphName string) (plan.PlannerFactory[graphql_datasource.Configuration], error)
func (*DefaultFactoryResolver) ResolveStaticFactory ¶
func (d *DefaultFactoryResolver) ResolveStaticFactory() (factory plan.PlannerFactory[staticdatasource.Configuration], err error)
type DialerFunc ¶
type EngineEvent ¶
type EngineEvent struct {
// contains filtered or unexported fields
}
EngineEvent is the event used to write to the engine subscription
func (*EngineEvent) Clone ¶
func (e *EngineEvent) Clone() datasource.MutableStreamEvent
func (*EngineEvent) GetData ¶
func (e *EngineEvent) GetData() []byte
type EnginePostOriginHandler ¶
type EnginePostOriginHandler interface {
// OnOriginResponse is called after the request is sent to the origin.
// Might be called multiple times if there are multiple origins
OnOriginResponse(resp *http.Response, ctx RequestContext) *http.Response
}
EnginePostOriginHandler allows you to add a handler to the router engine origin requests. The handler is called after the response was received from the origin. All origin handlers are called sequentially. It allows you to return a custom response to the client. If your return nil as response, the next handler is called. The same semantics of http.RoundTripper apply here. In order to modify the response, you have to return a new response.
type EnginePreOriginHandler ¶
type EnginePreOriginHandler interface {
// OnOriginRequest is called before the request is sent to the origin
// Might be called multiple times if there are multiple origins
OnOriginRequest(req *http.Request, ctx RequestContext) (*http.Request, *http.Response)
}
EnginePreOriginHandler allows you to add a handler to the router engine origin requests. The handler is called before the request is sent to the origin. All origin handlers are called sequentially. It allows you to modify the request before it is sent or return a custom response. The same semantics of http.RoundTripper apply here. Don't manipulate / consume the body of the request unless you know what you are doing. If you consume the body of the request it will not be available for the next handler.
type ExecutionConfig ¶
type ExecutionPlanCache ¶
type ExecutionPlanCache[K any, V any] interface { // Get the value from the cache Get(key K) (V, bool) // Set the value in the cache with a cost. The cost depends on the cache implementation Set(key K, value V, cost int64) bool // Iterate over all items in the cache (non-deterministic) IterValues(cb func(v V) (stop bool)) // Close the cache and free resources Close() }
type Executor ¶
type Executor struct {
PlanConfig plan.Configuration
// ClientSchema is the GraphQL Schema that is exposed from our API
// it is used for the introspection and query normalization/validation.
ClientSchema *ast.Document
// RouterSchema the GraphQL Schema that we use for planning the queries
RouterSchema *ast.Document
Resolver *resolve.Resolver
RenameTypeNames []resolve.RenameTypeName
TrackUsageInfo bool
}
type ExecutorBuildOptions ¶
type ExecutorBuildOptions struct {
EngineConfig *nodev1.EngineConfiguration
Subgraphs []*nodev1.Subgraph
RouterEngineConfig *RouterEngineConfiguration
Reporter resolve.Reporter
ApolloCompatibilityFlags config.ApolloCompatibilityFlags
ApolloRouterCompatibilityFlags config.ApolloRouterCompatibilityFlags
HeartbeatInterval time.Duration
TraceClientRequired bool
PluginsEnabled bool
InstanceData InstanceData
}
type ExecutorConfigurationBuilder ¶
type ExecutorConfigurationBuilder struct {
// contains filtered or unexported fields
}
func (*ExecutorConfigurationBuilder) Build ¶
func (b *ExecutorConfigurationBuilder) Build(ctx context.Context, opts *ExecutorBuildOptions) (*Executor, []pubsub_datasource.Provider, error)
type ExprWrapError ¶
type ExprWrapError struct {
Err error
}
func (*ExprWrapError) Error ¶
func (e *ExprWrapError) Error() string
type Extensions ¶
type Extensions struct {
RateLimit json.RawMessage `json:"rateLimit,omitempty"`
Authorization json.RawMessage `json:"authorization,omitempty"`
Trace json.RawMessage `json:"trace,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
Code string `json:"code,omitempty"`
}
type FactoryResolver ¶
type FactoryResolver interface {
ResolveGraphqlFactory(subgraphName string) (plan.PlannerFactory[graphql_datasource.Configuration], error)
ResolveStaticFactory() (plan.PlannerFactory[staticdatasource.Configuration], error)
InstanceData() InstanceData
}
type FileSystemSource ¶
type FileSystemSource struct {
RootPath string
}
type FileSystemSourceConfig ¶
type FileSystemSourceConfig struct {
RootPath string
}
type GraphQLErrorResponse ¶
type GraphQLErrorResponse struct {
Errors []graphqlError `json:"errors"`
Data any `json:"data"`
Extensions *Extensions `json:"extensions,omitempty"`
}
type GraphQLHandler ¶
type GraphQLHandler struct {
// contains filtered or unexported fields
}
func NewGraphQLHandler ¶
func NewGraphQLHandler(opts HandlerOptions) *GraphQLHandler
func (*GraphQLHandler) ServeHTTP ¶
func (h *GraphQLHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*GraphQLHandler) WriteError ¶
func (h *GraphQLHandler) WriteError(ctx *resolve.Context, err error, res *resolve.GraphQLResponse, w io.Writer)
WriteError writes the error to the response writer. This function must be concurrency-safe. @TODO This function should be refactored to be a helper function for websocket and http error writing In the websocket case, we call this function concurrently as part of the polling loop. This is error-prone.
type GraphQLMetricsConfig ¶
func DefaultGraphQLMetricsConfig ¶
func DefaultGraphQLMetricsConfig() *GraphQLMetricsConfig
type GraphQLRequest ¶
type GraphQLRequest struct {
Query string `json:"query,omitempty"`
OperationName string `json:"operationName,omitempty"`
Variables json.RawMessage `json:"variables,omitempty"`
Extensions json.RawMessage `json:"extensions,omitempty"`
}
type GraphQLRequestExtensions ¶
type GraphQLRequestExtensions struct {
PersistedQuery *GraphQLRequestExtensionsPersistedQuery `json:"persistedQuery"`
}
type GraphQLRequestExtensionsPersistedQuery ¶
type GraphQLRequestExtensionsPersistedQuery struct {
Version int `json:"version"`
Sha256Hash string `json:"sha256Hash"`
}
func (*GraphQLRequestExtensionsPersistedQuery) HasHash ¶
func (pq *GraphQLRequestExtensionsPersistedQuery) HasHash() bool
type HandlerOptions ¶
type HandlerOptions struct {
Executor *Executor
Log *zap.Logger
EngineStats statistics.EngineStatistics
TracerProvider trace.TracerProvider
Authorizer *CosmoAuthorizer
RateLimiter *CosmoRateLimiter
RateLimitConfig *config.RateLimitConfiguration
SubgraphErrorPropagation config.SubgraphErrorPropagationConfiguration
EngineLoaderHooks resolve.LoaderHooks
EnableCacheResponseHeaders bool
EnableResponseHeaderPropagation bool
ApolloSubscriptionMultipartPrintBoundary bool
HeaderPropagation *HeaderPropagation
}
type HandlerOpts ¶
type HeaderPropagation ¶
type HeaderPropagation struct {
// contains filtered or unexported fields
}
HeaderPropagation is a pre-origin handler that can be used to propagate and manipulate headers from the client request to the upstream
func NewHeaderPropagation ¶
func NewHeaderPropagation(rules *config.HeaderRules) (*HeaderPropagation, error)
func (*HeaderPropagation) ApplyResponseHeaderRules ¶
func (h *HeaderPropagation) ApplyResponseHeaderRules(ctx context.Context, headers http.Header, subgraphName string, statusCode int, request *http.Request)
ApplyResponseHeaderRules applies response header rules for a subgraph fetch. Called from OnFinished for every fetch (both singleflight leaders and followers).
func (*HeaderPropagation) ApplyRouterResponseHeaderRules ¶
func (h *HeaderPropagation) ApplyRouterResponseHeaderRules(w http.ResponseWriter, reqCtx *requestContext) error
ApplyRouterResponseHeaderRules applies router response header rules to the response writer
func (*HeaderPropagation) BuildRequestHeaderForSubgraph ¶
func (h *HeaderPropagation) BuildRequestHeaderForSubgraph(subgraphName string, ctx *requestContext) (http.Header, uint64)
BuildRequestHeaderForSubgraph builds headers for an outbound subgraph request as if the propagation rules were applied during transport. It returns the resulting headers and a stable hash over all header names and values that is independent of map iteration order.
func (*HeaderPropagation) HasRequestRules ¶
func (h *HeaderPropagation) HasRequestRules() bool
func (*HeaderPropagation) HasResponseRules ¶
func (h *HeaderPropagation) HasResponseRules() bool
func (*HeaderPropagation) OnOriginResponse ¶
func (h *HeaderPropagation) OnOriginResponse(resp *http.Response, ctx RequestContext) *http.Response
type HeaderWithHash ¶
type HttpError ¶
type HttpError interface {
error
// ExtensionCode is the code that should be included in the error extensions
ExtensionCode() string
// Message represents a human-readable error message to be sent to the client/user
Message() string
// StatusCode is the status code to be sent to the client
StatusCode() int
}
func NewHttpGraphqlError ¶
type HttpFlushWriter ¶
type HttpFlushWriter struct {
// contains filtered or unexported fields
}
func (*HttpFlushWriter) Close ¶
func (f *HttpFlushWriter) Close(_ resolve.SubscriptionCloseKind)
func (*HttpFlushWriter) Complete ¶
func (f *HttpFlushWriter) Complete()
func (*HttpFlushWriter) Flush ¶
func (f *HttpFlushWriter) Flush() (err error)
func (*HttpFlushWriter) Heartbeat ¶
func (f *HttpFlushWriter) Heartbeat() error
type IPAnonymizationConfig ¶
type IPAnonymizationConfig struct {
Enabled bool
Method IPAnonymizationMethod
}
type IPAnonymizationMethod ¶
type IPAnonymizationMethod string
const ( Hash IPAnonymizationMethod = "hash" Redact IPAnonymizationMethod = "redact" )
type InMemoryPlanCacheFallback ¶
type InMemoryPlanCacheFallback struct {
// contains filtered or unexported fields
}
InMemoryPlanCacheFallback is a store that stores either queries or references to the planner cache for use with the cache warmer
func (*InMemoryPlanCacheFallback) IsEnabled ¶
func (c *InMemoryPlanCacheFallback) IsEnabled() bool
IsEnabled returns whether the in-memory fallback cache is enabled
type InstanceData ¶
type Loader ¶
type Loader struct {
// contains filtered or unexported fields
}
func (*Loader) Load ¶
func (l *Loader) Load(engineConfig *nodev1.EngineConfiguration, subgraphs []*nodev1.Subgraph, routerEngineConfig *RouterEngineConfiguration, pluginsEnabled bool) (*plan.Configuration, []pubsub_datasource.Provider, error)
func (*Loader) LoadInternedString ¶
func (l *Loader) LoadInternedString(engineConfig *nodev1.EngineConfiguration, str *nodev1.InternedString) (string, error)
type MissingScopesError ¶
type MissingScopesError struct {
Coordinate resolve.GraphCoordinate `json:"coordinate"`
RequiredOrScopes [][]string `json:"required"`
}
type Module ¶
type Module interface {
Module() ModuleInfo
}
type ModuleContext ¶
type ModuleContext struct {
stdContext.Context
Module Module
Logger *zap.Logger
}
ModuleContext is a type which defines the lifetime of modules that are registered with the router.
type ModuleInfo ¶
type ModuleRequestContext ¶
type ModuleRequestContext interface {
// RequestContext shared across all modules
RequestContext
// SendError returns the most recent error occurred while trying to make the origin request.
SendError() error
}
ModuleRequestContext is the interface that provides the context for a single origin request.
type MultipartParser ¶
type MultipartParser struct {
// contains filtered or unexported fields
}
func NewMultipartParser ¶
func NewMultipartParser(operationProcessor *OperationProcessor, maxUploadFiles int, maxUploadFileSize int) *MultipartParser
func (*MultipartParser) Parse ¶
func (p *MultipartParser) Parse(r *http.Request, buf *bytes.Buffer) ([]byte, []*httpclient.FileUpload, error)
func (*MultipartParser) RemoveAll ¶
func (p *MultipartParser) RemoveAll() (err error)
type MutableEngineEvent ¶
type MutableEngineEvent struct {
// contains filtered or unexported fields
}
MutableEngineEvent is comparable to EngineEvent, but is mutable.
func (*MutableEngineEvent) Clone ¶
func (e *MutableEngineEvent) Clone() datasource.MutableStreamEvent
func (*MutableEngineEvent) GetData ¶
func (e *MutableEngineEvent) GetData() []byte
func (*MutableEngineEvent) SetData ¶
func (e *MutableEngineEvent) SetData(data []byte)
type NormalizationCacheEntry ¶
type NormalizationCacheEntry struct {
// contains filtered or unexported fields
}
type OperationBlocker ¶
type OperationBlocker struct {
// contains filtered or unexported fields
}
func NewOperationBlocker ¶
func NewOperationBlocker(opts *OperationBlockerOptions) (*OperationBlocker, error)
func (*OperationBlocker) OperationIsBlocked ¶
func (o *OperationBlocker) OperationIsBlocked(requestLogger *zap.Logger, exprContext expr.Context, operation *ParsedOperation) error
type OperationBlockerOptions ¶
type OperationBlockerOptions struct {
BlockMutations BlockMutationOptions
BlockSubscriptions BlockSubscriptionOptions
BlockNonPersisted BlockNonPersistedOptions
BlockPersisted BlockPersistedOptions
SafelistEnabled bool
LogUnknownOperationsEnabled bool
// contains filtered or unexported fields
}
type OperationCache ¶
type OperationCache struct {
// contains filtered or unexported fields
}
type OperationContext ¶
type OperationContext interface {
// Name is the name of the operation
Name() string
// Type is the type of the operation (query, mutation, subscription)
Type() string
// Hash is the hash of the operation
Hash() uint64
// Content is the content of the operation
Content() string
// Variables is the variables of the operation
Variables() *astjson.Value
// ClientInfo returns information about the client that initiated this operation
ClientInfo() ClientInfo
// Sha256Hash returns the SHA256 hash of the original operation
// It is important to note that this hash is not calculated just because this method has been called
// and is only calculated based on other existing logic (such as if sha256Hash is used in expressions)
Sha256Hash() string
// QueryPlanStats returns some statistics about the query plan for the operation
// if called too early in request chain, it may be inaccurate for modules, using
// in Middleware is recommended
QueryPlanStats() (QueryPlanStats, error)
// Timings returns the timing information for various stages of operation processing
// if called too early in request chain, it may be inaccurate for modules, using
// in Middleware is recommended
Timings() OperationTimings
}
type OperationKit ¶
type OperationKit struct {
// contains filtered or unexported fields
}
OperationKit provides methods to parse, normalize and validate operations. After each step, the operation is available as a ParsedOperation. It must be created for each request and freed after the request is done.
func NewIndependentOperationKit ¶
func NewIndependentOperationKit(processor *OperationProcessor) *OperationKit
NewIndependentOperationKit creates a new OperationKit that does not share resources with other kits.
func NewOperationKit ¶
func NewOperationKit(processor *OperationProcessor) *OperationKit
NewOperationKit creates a new OperationKit. The kit is used to parse, normalize and validate operations. It allocates resources that need to be freed by calling OperationKit.Free()
func (*OperationKit) ComputeOperationSha256 ¶
func (o *OperationKit) ComputeOperationSha256() error
func (*OperationKit) FetchPersistedOperation ¶
func (o *OperationKit) FetchPersistedOperation(ctx context.Context, clientInfo *ClientInfo) (skipParse bool, isAPQ bool, err error)
FetchPersistedOperation fetches the persisted operation from the cache or the client. If the operation is fetched from the cache it returns true. UnmarshalOperationFromBody or UnmarshalOperationFromURL must be called before calling this method.
func (*OperationKit) Free ¶
func (o *OperationKit) Free()
Free releases the resources used by the OperationKit
func (*OperationKit) NormalizeOperation ¶
func (o *OperationKit) NormalizeOperation(clientName string, isApq bool) (bool, error)
NormalizeOperation normalizes the operation. After normalization the normalized representation of the operation and variables is available. Also, the final operation ID is generated.
func (*OperationKit) NormalizeVariables ¶
func (o *OperationKit) NormalizeVariables() (cached bool, mapping []uploads.UploadPathMapping, err error)
NormalizeVariables normalizes variables and returns a slice of upload mappings if any of them were present in a query. If normalized values were found in the cache, it skips normalization and returns the caching set to true. If an error is returned, then caching is set to false.
func (*OperationKit) Parse ¶
func (o *OperationKit) Parse() error
Parse parses the operation, populates the document and set the operation type. UnmarshalOperationFromBody must be called before calling this method.
func (*OperationKit) RemapVariables ¶
func (o *OperationKit) RemapVariables(disabled bool) (cached bool, err error)
RemapVariables updates and sorts variable names to have them in a predictable order.
func (*OperationKit) UnmarshalOperationFromBody ¶
func (o *OperationKit) UnmarshalOperationFromBody(data []byte) error
UnmarshalOperationFromBody loads the operation from the request body and unmarshal it into the ParsedOperation. This will load operationName, query, variables and extensions from the request body, but extension and variables will be unmarshalled as JSON.RawMessage. We always compact the variables and extensions to ensure that we produce easy to parse JSON for the engine
func (*OperationKit) UnmarshalOperationFromURL ¶
func (o *OperationKit) UnmarshalOperationFromURL(url *url.URL) error
UnmarshalOperationFromURL loads the operation from the URL and unmarshal it into the ParsedOperation It follows the GraphQL over HTTP specification for GET requests https://graphql.github.io/graphql-over-http/draft/#sec-GET We always compact the variables and extensions to ensure that we produce easy to parse JSON for the engine
func (*OperationKit) Validate ¶
func (o *OperationKit) Validate(skipLoader bool, remapVariables map[string]string, apolloCompatibilityFlags *config.ApolloCompatibilityFlags) (cacheHit bool, err error)
Validate validates the operation variables.
func (*OperationKit) ValidateQueryComplexity ¶
func (o *OperationKit) ValidateQueryComplexity() (ok bool, cacheEntry ComplexityCacheEntry, err error)
ValidateQueryComplexity validates that the query complexity is within the limits set in the configuration
type OperationMetrics ¶
type OperationMetrics struct {
// contains filtered or unexported fields
}
OperationMetrics is a struct that holds the metrics for an operation. It should be created on the parent router request subgraph metrics are created in the transport or engine loader hooks.
type OperationMetricsOptions ¶
type OperationPlanner ¶
type OperationPlanner struct {
// contains filtered or unexported fields
}
func NewOperationPlanner ¶
func NewOperationPlanner(executor *Executor, planCache ExecutionPlanCache[uint64, *planWithMetaData], storeContent bool) *OperationPlanner
type OperationProcessor ¶
type OperationProcessor struct {
// contains filtered or unexported fields
}
OperationProcessor provides shared resources to the parseKit and OperationKit. It should be only instantiated once and shared across requests
func NewOperationProcessor ¶
func NewOperationProcessor(opts OperationProcessorOptions) *OperationProcessor
func (*OperationProcessor) NewIndependentKit ¶
func (p *OperationProcessor) NewIndependentKit() (*OperationKit, error)
NewIndependentKit creates a new OperationKit which will not be pooled. This is useful, e.g. for warming up the caches
func (*OperationProcessor) NewKit ¶
func (p *OperationProcessor) NewKit() (*OperationKit, error)
NewKit creates a new OperationKit. The kit is used to parse, normalize and validate operations. It also validates if the operation size is within the limit.
type OperationProcessorOptions ¶
type OperationProcessorOptions struct {
Executor *Executor
MaxOperationSizeInBytes int64
PersistedOperationClient *persistedoperation.Client
AutomaticPersistedOperationCacheTtl int
EnablePersistedOperationsCache bool
PersistedOpsNormalizationCache *ristretto.Cache[uint64, NormalizationCacheEntry]
NormalizationCache *ristretto.Cache[uint64, NormalizationCacheEntry]
QueryDepthCache *ristretto.Cache[uint64, ComplexityCacheEntry]
VariablesNormalizationCache *ristretto.Cache[uint64, VariablesNormalizationCacheEntry]
RemapVariablesCache *ristretto.Cache[uint64, RemapVariablesCacheEntry]
ValidationCache *ristretto.Cache[uint64, bool]
OperationHashCache *ristretto.Cache[uint64, string]
ParseKitPoolSize int
IntrospectionEnabled bool
ApolloCompatibilityFlags config.ApolloCompatibilityFlags
ApolloRouterCompatibilityFlags config.ApolloRouterCompatibilityFlags
DisableExposingVariablesContentOnValidationError bool
RelaxSubgraphOperationFieldSelectionMergingNullability bool
ComplexityLimits *config.ComplexityLimits
ParserTokenizerLimits astparser.TokenizerLimits
OperationNameLengthLimit int
}
type OperationProtocol ¶
type OperationProtocol string
func (OperationProtocol) String ¶
func (p OperationProtocol) String() string
type OperationTimes ¶
type OperationTimes struct {
ParseTime time.Duration
NormalizeTime time.Duration
ValidateTime time.Duration
PlanTime time.Duration
}
func (OperationTimes) Merge ¶
func (ot OperationTimes) Merge(other OperationTimes) OperationTimes
func (*OperationTimes) TotalTime ¶
func (ot *OperationTimes) TotalTime() time.Duration
type OperationTimings ¶
type OperationTimings struct {
ParsingTime time.Duration
ValidationTime time.Duration
PlanningTime time.Duration
NormalizationTime time.Duration
}
OperationTimings contains timing information for various stages of operation processing
type OperationType ¶
type OperationType = string
const ( OperationTypeQuery OperationType = "query" OperationTypeMutation OperationType = "mutation" OperationTypeSubscription OperationType = "subscription" )
type Option ¶
type Option func(svr *Router)
Option defines the method to customize server.
func WithAccessController ¶
func WithAccessController(controller *AccessController) Option
func WithAccessLogs ¶
func WithAccessLogs(cfg *AccessLogsConfig) Option
func WithAnonymization ¶
func WithAnonymization(ipConfig *IPAnonymizationConfig) Option
func WithApolloCompatibilityFlagsConfig ¶
func WithApolloCompatibilityFlagsConfig(cfg config.ApolloCompatibilityFlags) Option
func WithApolloRouterCompatibilityFlags ¶
func WithApolloRouterCompatibilityFlags(cfg config.ApolloRouterCompatibilityFlags) Option
func WithAuthorizationConfig ¶
func WithAuthorizationConfig(cfg *config.AuthorizationConfiguration) Option
func WithAutomatedPersistedQueriesConfig ¶
func WithAutomatedPersistedQueriesConfig(cfg config.AutomaticPersistedQueriesConfig) Option
func WithAwsLambdaRuntime ¶
func WithAwsLambdaRuntime() Option
WithAwsLambdaRuntime enables the AWS Lambda behaviour. This flushes all telemetry data synchronously after the request is handled.
func WithBatching ¶
func WithBatching(cfg *BatchingConfig) Option
func WithCDN ¶
func WithCDN(cfg config.CDNConfiguration) Option
WithCDN sets the configuration for the CDN client
func WithCacheControlPolicy ¶
func WithCacheControlPolicy(cfg config.CacheControlPolicy) Option
func WithCacheWarmupConfig ¶
func WithCacheWarmupConfig(cfg *config.CacheWarmupConfiguration) Option
func WithClientHeader ¶
func WithClientHeader(cfg config.ClientHeader) Option
func WithClusterName ¶
func WithConfigPoller ¶
func WithConfigPoller(cf configpoller.ConfigPoller) Option
WithConfigPoller sets the poller client to fetch the router config. If not set, WithConfigPollerConfig should be set.
func WithConfigPollerConfig ¶
func WithConfigPollerConfig(cfg *RouterConfigPollerConfig) Option
func WithConfigVersionHeader ¶
func WithConnectRPC ¶
func WithConnectRPC(cfg config.ConnectRPCConfiguration) Option
func WithCustomModules ¶
func WithDemoMode ¶
func WithDevelopmentMode ¶
WithDevelopmentMode enables development mode. This should only be used for testing purposes. Development mode allows e.g. to use ART (Advanced Request Tracing) without request signing.
func WithDisableUsageTracking ¶
func WithDisableUsageTracking() Option
func WithEngineExecutionConfig ¶
func WithEngineExecutionConfig(cfg config.EngineExecutionConfiguration) Option
func WithEvents ¶
func WithEvents(cfg config.EventsConfiguration) Option
WithEvents sets the configuration for the events client
func WithExecutionConfig ¶
func WithExecutionConfig(cfg *ExecutionConfig) Option
func WithFileUploadConfig ¶
func WithFileUploadConfig(cfg *config.FileUpload) Option
func WithGracePeriod ¶
WithGracePeriod sets the grace period for the router to shutdown.
func WithGraphApiToken ¶
func WithGraphQLMetrics ¶
func WithGraphQLMetrics(cfg *GraphQLMetricsConfig) Option
func WithGraphQLPath ¶
WithGraphQLPath sets the path where the GraphQL endpoint is served.
func WithGraphQLWebURL ¶
WithGraphQLWebURL sets the URL to the GraphQL endpoint used by the GraphQL Playground. This is useful when the path differs from the actual GraphQL endpoint e.g. when the router is behind a reverse proxy. If not set, the GraphQL Playground uses the same URL as the GraphQL endpoint.
func WithHeaderRules ¶
func WithHeaderRules(headers config.HeaderRules) Option
func WithHealthCheckPath ¶
func WithHealthChecks ¶
func WithInstanceID ¶
func WithIntrospection ¶
func WithIntrospection(enable bool, config config.IntrospectionConfiguration) Option
func WithListenerAddr ¶
func WithLivenessCheckPath ¶
func WithLogger ¶
func WithMCP ¶
func WithMCP(cfg config.MCPConfiguration) Option
func WithMetrics ¶
WithMetrics sets the metrics configuration for the router.
func WithModulesConfig ¶
func WithOverrideRoutingURL ¶
func WithOverrideRoutingURL(overrideRoutingURL config.OverrideRoutingURLConfiguration) Option
func WithOverrides ¶
func WithOverrides(overrides config.OverridesConfiguration) Option
func WithPersistedOperationsConfig ¶
func WithPersistedOperationsConfig(cfg config.PersistedOperationsConfig) Option
func WithPlayground ¶
func WithPlaygroundConfig ¶
func WithPlaygroundConfig(c config.PlaygroundConfig) Option
WithPlaygroundConfig sets the path where the GraphQL Playground is served.
func WithPlaygroundPath ¶
WithPlaygroundPath sets the path where the GraphQL Playground is served.
func WithPlugins ¶
func WithPlugins(cfg config.PluginsConfiguration) Option
func WithQueryPlans ¶
func WithRateLimitConfig ¶
func WithRateLimitConfig(cfg *config.RateLimitConfiguration) Option
func WithReadinessCheckPath ¶
func WithReloadPersistentState ¶
func WithReloadPersistentState(cfg *ReloadPersistentState) Option
func WithRouterTrafficConfig ¶
func WithRouterTrafficConfig(cfg *config.RouterTrafficConfiguration) Option
func WithSecurityConfig ¶
func WithSecurityConfig(cfg config.SecurityConfiguration) Option
func WithSelfRegistration ¶
func WithSelfRegistration(sr selfregister.SelfRegister) Option
WithSelfRegistration sets the self registration client to register the router with the control plane.
func WithStaticExecutionConfig ¶
func WithStaticExecutionConfig(cfg *nodev1.RouterConfig) Option
WithStaticExecutionConfig sets the static execution config. This disables polling and file watching.
func WithStorageProviders ¶
func WithStorageProviders(cfg config.StorageProviders) Option
func WithStreamsHandlerConfiguration ¶
func WithStreamsHandlerConfiguration(cfg config.StreamsHandlerConfiguration) Option
func WithSubgraphCircuitBreakerOptions ¶
func WithSubgraphCircuitBreakerOptions(opts *SubgraphCircuitBreakerOptions) Option
func WithSubgraphErrorPropagation ¶
func WithSubgraphErrorPropagation(cfg config.SubgraphErrorPropagationConfiguration) Option
func WithSubgraphRetryOptions ¶
func WithSubgraphRetryOptions( enabled bool, algorithm string, maxRetryCount int, retryMaxDuration, retryInterval time.Duration, expression string, onRetryFunc retrytransport.OnRetryFunc, ) Option
func WithSubgraphTransportOptions ¶
func WithSubgraphTransportOptions(opts *SubgraphTransportOptions) Option
func WithSubscriptionHeartbeatInterval ¶
WithSubscriptionHeartbeatInterval sets the interval for the engine to send heartbeats for multipart subscriptions.
func WithTLSConfig ¶
func WithTelemetryAttributes ¶
func WithTelemetryAttributes(attributes []config.CustomAttribute) Option
func WithTracing ¶
func WithTracingAttributes ¶
func WithTracingAttributes(attributes []config.CustomAttribute) Option
func WithWebSocketConfiguration ¶
func WithWebSocketConfiguration(cfg *config.WebSocketConfiguration) Option
type ParsedOperation ¶
type ParsedOperation struct {
// ID represents a unique-ish ID for the operation calculated by hashing
// its normalized representation.
ID uint64
// InternalID is the internal ID of the operation calculated by hashing
// its normalized representation with the original operation name and normalized variables.
InternalID uint64
// Sha256Hash is the sha256 hash of the original operation query sent by the client.
Sha256Hash string
// Type is a string representing the operation type. One of "query", "mutation", "subscription".
Type string
Variables *fastjson.Object
VariablesHash uint64
RemapVariables map[string]string
// NormalizedRepresentation is the normalized representation of the operation as a string.
// This is provided for modules to be able to access the operation.
// Only available after the operation has been normalized.
NormalizedRepresentation string
Request GraphQLRequest
GraphQLRequestExtensions GraphQLRequestExtensions
IsPersistedOperation bool
PersistedOperationCacheHit bool
// NormalizationCacheHit is set to true if the request is a non-persisted operation,
// and the normalized operation was loaded from cache.
NormalizationCacheHit bool
}
func (*ParsedOperation) IDString ¶
func (o *ParsedOperation) IDString() string
type PlanGenerator ¶
type PlanGenerator struct {
// contains filtered or unexported fields
}
func NewPlanGenerator ¶
func NewPlanGeneratorFromConfig ¶
func NewPlanGeneratorFromConfig(config *nodev1.RouterConfig, logger *zap.Logger, maxDataSourceCollectorsConcurrency uint) (*PlanGenerator, error)
func (*PlanGenerator) GetPlanConfiguration ¶
func (pg *PlanGenerator) GetPlanConfiguration() *plan.Configuration
func (*PlanGenerator) GetPlanner ¶
func (pg *PlanGenerator) GetPlanner() (*Planner, error)
type PlanOptions ¶
type PlanOptions struct {
ClientInfo *ClientInfo
TraceOptions resolve.TraceOptions
ExecutionOptions resolve.ExecutionOptions
TrackSchemaUsageInfo bool
}
type PlanOutputFormat ¶
type PlanOutputFormat string
const ( PlanOutputFormatUnset PlanOutputFormat = "" PlanOutputFormatText PlanOutputFormat = "text" PlanOutputFormatJSON PlanOutputFormat = "json" )
type PlanSource ¶
type PlanSource struct {
// contains filtered or unexported fields
}
PlanSource is a very basic cache warmup source that relies on the caller of this type to pass in the queries to be used for cache warming directly
func NewPlanSource ¶
func NewPlanSource(inMemoryPlanCacheFallbackQueries []*nodev1.Operation) *PlanSource
NewPlanSource creates a new PlanSource with the given queries from the caller
type Planner ¶
type Planner struct {
// contains filtered or unexported fields
}
func NewPlanner ¶
func (*Planner) ParseAndPrepareOperation ¶
func (pl *Planner) ParseAndPrepareOperation(operationFilePath string) (*ast.Document, OperationTimes, error)
ParseAndPrepareOperation parses, normalizes and validates the operation
func (*Planner) PlanOperation ¶
func (pl *Planner) PlanOperation(operationFilePath string, outputFormat PlanOutputFormat) (string, OperationTimes, error)
PlanOperation creates a query plan from an operation file in a pretty-printed text or JSON format
func (*Planner) PlanPreparedOperation ¶
func (pl *Planner) PlanPreparedOperation(operation *ast.Document) (planNode *resolve.FetchTreeQueryPlanNode, opTimes OperationTimes, err error)
PlanPreparedOperation creates a query plan from a normalized and validated operation
func (*Planner) PrepareOperation ¶
PrepareOperation normalizes and validates the operation
type PlannerOperationValidationError ¶
type PlannerOperationValidationError struct {
// contains filtered or unexported fields
}
func (*PlannerOperationValidationError) Error ¶
func (e *PlannerOperationValidationError) Error() string
type PreHandler ¶
type PreHandler struct {
// contains filtered or unexported fields
}
func NewPreHandler ¶
func NewPreHandler(opts *PreHandlerOptions) *PreHandler
type PreHandlerOptions ¶
type PreHandlerOptions struct {
Logger *zap.Logger
Executor *Executor
Metrics RouterMetrics
OperationProcessor *OperationProcessor
Planner *OperationPlanner
AccessController *AccessController
OperationBlocker *OperationBlocker
RouterPublicKey *ecdsa.PublicKey
TracerProvider *sdktrace.TracerProvider
ComplexityLimits *config.ComplexityLimits
MaxUploadFiles int
MaxUploadFileSize int
FlushTelemetryAfterResponse bool
FileUploadEnabled bool
TraceExportVariables bool
DevelopmentMode bool
EnableRequestTracing bool
AlwaysIncludeQueryPlan bool
AlwaysSkipLoader bool
QueryPlansEnabled bool
QueryPlansLoggingEnabled bool
TrackSchemaUsageInfo bool
ClientHeader config.ClientHeader
ComputeOperationSha256 bool
ApolloCompatibilityFlags *config.ApolloCompatibilityFlags
DisableVariablesRemapping bool
ExprManager *expr.Manager
OmitBatchExtensions bool
OperationContentAttributes bool
EnableRequestDeduplication bool
ForceEnableRequestDeduplication bool
HasPreOriginHandlers bool
EnableInboundRequestDeduplication bool
ForceEnableInboundRequestDeduplication bool
HeaderPropagation *HeaderPropagation
}
type ProgramWithKey ¶
type Provisioner ¶
type Provisioner interface {
// Provision is called before the server starts
Provision(*ModuleContext) error
}
Provisioner is called before the server starts It allows you to initialize your module e.g. create a database connection or load a configuration file
type QueryPlanStats ¶
type QueryPlanStats struct {
TotalSubgraphFetches int
SubgraphFetches map[string]int
SubgraphRootFields []SubgraphRootField
}
type RateLimitStats ¶
type ReloadPersistentState ¶
type ReloadPersistentState struct {
// contains filtered or unexported fields
}
ReloadPersistentState This file describes any configuration which should persist or be shared across router restarts
func NewReloadPersistentState ¶
func NewReloadPersistentState(logger *zap.Logger) *ReloadPersistentState
func (*ReloadPersistentState) CleanupFeatureFlags ¶
func (s *ReloadPersistentState) CleanupFeatureFlags(routerCfg *nodev1.RouterConfig)
CleanupFeatureFlags cleans up anything related to unused feature flags due to being now excluded from the execution config
func (*ReloadPersistentState) OnRouterConfigReload ¶
func (s *ReloadPersistentState) OnRouterConfigReload()
func (*ReloadPersistentState) UpdateReloadPersistentState ¶
func (s *ReloadPersistentState) UpdateReloadPersistentState(config *Config)
UpdateReloadPersistentState updates the fallback config based on the provided config.
type RemapVariablesCacheEntry ¶
type RemapVariablesCacheEntry struct {
// contains filtered or unexported fields
}
type ReportError ¶
type ReportError interface {
error
Report() *operationreport.Report
}
type RequestContext ¶
type RequestContext interface {
// ResponseWriter is the original response writer received by the router.
ResponseWriter() http.ResponseWriter
// Request is the original request received by the router.
Request() *http.Request
// Logger is the logger for the request
Logger() *zap.Logger
// Operation is the GraphQL operation
Operation() OperationContext
// Set is used to store a new key/value pair exclusively for this context.
Set(string, any)
// Get returns the value for the given key, ie: (value, true).
Get(string) (value any, exists bool)
// GetString returns the value associated with the key as a string.
GetString(string) string
// MustGet returns the value for the given key if it exists, otherwise it panics.
MustGet(string) any
// GetBool returns the value associated with the key as a boolean.
GetBool(string) bool
// GetInt returns the value associated with the key as an integer.
GetInt(string) int
// GetInt64 returns the value associated with the key as an integer.
GetInt64(string) int64
// GetUint returns the value associated with the key as an unsigned integer.
GetUint(string) uint
// GetUint64 returns the value associated with the key as an unsigned integer.
GetUint64(string) uint64
// GetFloat64 returns the value associated with the key as a float64.
GetFloat64(string) float64
// GetTime returns the value associated with the key as time.
GetTime(string) time.Time
// GetDuration returns the value associated with the key as a duration.
GetDuration(string) time.Duration
// GetStringSlice returns the value associated with the key as a slice of strings.
GetStringSlice(string) []string
// GetStringMap returns the value associated with the key as a map of interfaces.
GetStringMap(string) map[string]any
// GetStringMapString returns the value associated with the key as a map of strings.
GetStringMapString(string) map[string]string
// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
GetStringMapStringSlice(string) map[string][]string
// ActiveSubgraph returns the current subgraph to which the request is made to
ActiveSubgraph(subgraphRequest *http.Request) *Subgraph
// SubgraphByID return the subgraph by its ID
SubgraphByID(subgraphID string) *Subgraph
// Authentication returns the authentication information for the request, if any
Authentication() authentication.Authentication
// SetAuthenticationScopes sets the scopes for the request on Authentication
// If Authentication is not set, it will be initialized with the scopes
SetAuthenticationScopes(scopes []string)
// SetCustomFieldValueRenderer overrides the default field value rendering behavior
// This can be used, e.g. to obfuscate sensitive data in the response
SetCustomFieldValueRenderer(renderer resolve.FieldValueRenderer)
// SetForceSha256Compute forces the computation of the Sha256Hash of the operation
// This is useful if the Sha256Hash is needed in custom modules but not used anywhere else
SetForceSha256Compute()
// Error returns the error associated with the request, if any
Error() error
}
type RequiredAndScopes ¶
type RequiredAndScopes struct {
RequiredAndScopes []string `json:"and"`
}
type Router ¶
type Router struct {
Config
EngineStats statistics.EngineStatistics
// contains filtered or unexported fields
}
Router is the main application instance.
func DefaultRouterFactory ¶
func DefaultRouterFactory(ctx context.Context, res *RouterResources) (*Router, error)
func NewRouter ¶
NewRouter creates a new Router instance. Router.Start() must be called to start the server. Alternatively, use Router.NewServer() to create a new server instance without starting it.
func (*Router) NewServer ¶
NewServer prepares a new server instance but does not start it. The method should only be used when you want to bootstrap the server manually otherwise you can use Router.Start(). You're responsible for setting health checks status to ready with Server.HealthChecks(). The server can be shutdown with Router.Shutdown(). Use core.WithExecutionConfig to pass the initial config otherwise the Router will try to fetch the config from the control plane. You can swap the router config by using Router.newGraphServer().
func (*Router) Shutdown ¶
Shutdown gracefully shuts down the router. It blocks until the server is shutdown. If the router is already shutdown, the method returns immediately without error.
func (*Router) Start ¶
Start starts the router. It does block until the router has been initialized. After that the server is listening on a separate goroutine. The server can be shutdown with Router.Shutdown(). Not safe for concurrent use. During initialization, the router will register itself with the control plane and poll the config from the CDN if the user opted in to connect to Cosmo Cloud.
type RouterEngineConfiguration ¶
type RouterEngineConfiguration struct {
Execution config.EngineExecutionConfiguration
Headers *config.HeaderRules
Events config.EventsConfiguration
SubgraphErrorPropagation config.SubgraphErrorPropagationConfiguration
StreamMetricStore rmetric.StreamMetricStore
}
type RouterMetrics ¶
type RouterMetrics interface {
StartOperation(logger *zap.Logger, requestContentLength int64, sliceAttr []attribute.KeyValue, inFlightAddOption otelmetric.AddOption) *OperationMetrics
ExportSchemaUsageInfo(operationContext *operationContext, statusCode int, hasError bool, exportSynchronous bool)
ExportSchemaUsageInfoPrometheus(operationContext *operationContext, statusCode int, hasError bool, exportSynchronous bool)
GQLMetricsExporter() *graphqlmetrics.GraphQLMetricsExporter
PrometheusMetricsExporter() *graphqlmetrics.PrometheusMetricsExporter
MetricStore() metric.Store
}
func NewRouterMetrics ¶
func NewRouterMetrics(cfg *routerMetricsConfig) RouterMetrics
type RouterMiddlewareHandler ¶
type RouterMiddlewareHandler interface {
// Middleware is the middleware handler
Middleware(ctx RequestContext, next http.Handler)
}
RouterMiddlewareHandler allows you to add a middleware to the router. The middleware is called for every request. It allows you to modify the request before it is processed by the router. The same semantics of http.Handler apply here. Don't manipulate / consume the body of the request unless you know what you are doing. If you consume the body of the request it will not be available for the next handler.
type RouterOnRequestHandler ¶
type RouterOnRequestHandler interface {
RouterOnRequest(ctx RequestContext, next http.Handler)
}
RouterOnRequestHandler allows you to add middleware that runs before most internal router logic. This runs after the creation of the request context and the creatio of the recovery handler. This hook is useful if you want to do some custom logic before tracing or authentication, for example if you want to manipulate the bearer auth headers or add a header on a condition that can be logged by tracing. The same semantics of http.Handler apply here. Don't manipulate / consume the body of the request unless you know what you are doing. If you consume the body of the request it will not be available for the next handler.
type RouterResources ¶
type RouterResources struct {
Config *config.Config
Logger *zap.Logger
ReloadPersistentState *ReloadPersistentState
}
RouterResources is a struct for holding resources used by the router.
type RouterSupervisor ¶
type RouterSupervisor struct {
// contains filtered or unexported fields
}
RouterSupervisor is a supervisor for the router.
func NewRouterSupervisor ¶
func NewRouterSupervisor(opts *RouterSupervisorOpts) (*RouterSupervisor, error)
NewRouterSupervisor creates a new RouterSupervisor instance.
func (*RouterSupervisor) Reload ¶
func (rs *RouterSupervisor) Reload()
Reload restarts the router supervisor.
func (*RouterSupervisor) Start ¶
func (rs *RouterSupervisor) Start() error
Start starts the router supervisor.
func (*RouterSupervisor) Stop ¶
func (rs *RouterSupervisor) Stop()
Stop stops the router supervisor.
type RouterSupervisorOpts ¶
type RouterSupervisorOpts struct {
BaseLogger *zap.Logger
ConfigFactory func() (*config.Config, error)
RouterFactory func(ctx context.Context, res *RouterResources) (*Router, error)
ReloadPersistentState *ReloadPersistentState
}
RouterSupervisorOpts is a struct for configuring the router supervisor.
type SafelistPersistedOptions ¶
type SafelistPersistedOptions struct {
Enabled bool
}
type StreamHandlerError ¶
type StreamHandlerError struct {
// The message for this error.
Message string
}
StreamHandlerError writes an error event with Reason to a subscription client and closes the websocket connection with code 1000 (Normal closure). It can returned from methods of the core.SubscriptionOnStartHandler interface.
func (*StreamHandlerError) Error ¶
func (e *StreamHandlerError) Error() string
Error returns the reason of this error.
type StreamPublishEventHandler ¶
type StreamPublishEventHandler interface {
// OnPublishEvents is called each time a batch of events is going to be sent to a provider.
// The events argument contains all events from a batch.
// Use events.All() to iterate through them and event.Clone() to create mutable copies, when needed.
// Returning an error will result in a GraphQL error being returned to the client, could be customized returning a
// StreamHookError.
OnPublishEvents(ctx StreamPublishEventHandlerContext, events datasource.StreamEvents) (datasource.StreamEvents, error)
}
type StreamPublishEventHandlerContext ¶
type StreamPublishEventHandlerContext interface {
// Request is the original request received by the router.
Request() *http.Request
// Logger is the logger for the request
Logger() *zap.Logger
// Operation is the GraphQL operation
Operation() OperationContext
// Authentication is the authentication for the request
Authentication() authentication.Authentication
// PublishEventConfiguration the publish event configuration
PublishEventConfiguration() datasource.PublishEventConfiguration
// NewEvent creates a new event that can be used in the subscription.
//
// The data parameter must contain valid JSON bytes representing the event payload
// that will be sent to your message broker (Kafka, NATS, etc.). The JSON must have
// properly quoted property names and must include the __typename field required by GraphQL.
// For example: []byte(`{"__typename": "Employee", "id": 1, "update": {"name": "John"}}`).
//
// This method is typically used in OnPublishEvents hooks to create new or modified events
// before they are sent to the message broker.
NewEvent(data []byte) datasource.MutableStreamEvent
}
type StreamReceiveEventHandler ¶
type StreamReceiveEventHandler interface {
// OnReceiveEvents is called whenever a batch of events is received from a provider,
// before delivering them to clients.
// The hook will be called once for each active subscription, therefore it is adviced to
// avoid resource heavy computation or blocking tasks whenever possible.
// The events argument contains all events from a batch and is shared between
// all active subscribers of these events.
// Use events.All() to iterate through them and event.Clone() to create mutable copies, when needed.
// Returning an error will result in the subscription being closed and the error being logged.
OnReceiveEvents(ctx StreamReceiveEventHandlerContext, events datasource.StreamEvents) (datasource.StreamEvents, error)
}
type StreamReceiveEventHandlerContext ¶
type StreamReceiveEventHandlerContext interface {
// Context is a context for handlers.
// If it is cancelled, the handler should stop processing.
Context() context.Context
// Request is the initial client request that started the subscription
Request() *http.Request
// Logger is the logger for the request
Logger() *zap.Logger
// Operation is the GraphQL operation
Operation() OperationContext
// Authentication is the authentication for the request
Authentication() authentication.Authentication
// SubscriptionEventConfiguration the subscription event configuration
SubscriptionEventConfiguration() datasource.SubscriptionEventConfiguration
// NewEvent creates a new event that can be used in the subscription.
//
// The data parameter must contain valid JSON bytes representing the raw event payload
// from your message broker (Kafka, NATS, etc.). The JSON must have properly quoted
// property names and must include the __typename field required by GraphQL.
// For example: []byte(`{"__typename": "Employee", "id": 1, "update": {"name": "John"}}`).
//
// This method is typically used in OnReceiveEvents hooks to create new or modified events.
NewEvent(data []byte) datasource.MutableStreamEvent
}
type SubgraphCircuitBreakerOptions ¶
type SubgraphCircuitBreakerOptions struct {
CircuitBreaker circuit.CircuitBreakerConfig
SubgraphMap map[string]circuit.CircuitBreakerConfig
}
func NewSubgraphCircuitBreakerOptions ¶
func NewSubgraphCircuitBreakerOptions(cfg config.TrafficShapingRules) *SubgraphCircuitBreakerOptions
func (*SubgraphCircuitBreakerOptions) IsEnabled ¶
func (r *SubgraphCircuitBreakerOptions) IsEnabled() bool
type SubgraphResolver ¶
type SubgraphResolver struct {
// contains filtered or unexported fields
}
func NewSubgraphResolver ¶
func NewSubgraphResolver(subgraphs []Subgraph) *SubgraphResolver
func (*SubgraphResolver) ByID ¶
func (s *SubgraphResolver) ByID(subgraphID string) *Subgraph
func (*SubgraphResolver) BySubgraphURL ¶
func (s *SubgraphResolver) BySubgraphURL(u string) *Subgraph
type SubgraphRootField ¶
type SubgraphTransportOptions ¶
type SubgraphTransportOptions struct {
*TransportRequestOptions
SubgraphMap map[string]*TransportRequestOptions
}
func DefaultSubgraphTransportOptions ¶
func DefaultSubgraphTransportOptions() *SubgraphTransportOptions
func NewSubgraphTransportOptions ¶
func NewSubgraphTransportOptions(cfg config.TrafficShapingRules) *SubgraphTransportOptions
type SubscriptionOnStartHandler ¶
type SubscriptionOnStartHandler interface {
// SubscriptionOnStart is called once at subscription start
// The error is propagated to the client.
SubscriptionOnStart(ctx SubscriptionOnStartHandlerContext) error
}
type SubscriptionOnStartHandlerContext ¶
type SubscriptionOnStartHandlerContext interface {
// Request is the original request received by the router.
Request() *http.Request
// Logger is the logger for the request
Logger() *zap.Logger
// Operation is the GraphQL operation
Operation() OperationContext
// Authentication is the authentication for the request
Authentication() authentication.Authentication
// SubscriptionEventConfiguration is the subscription event configuration (will return nil for engine subscription)
SubscriptionEventConfiguration() datasource.SubscriptionEventConfiguration
// EmitEvent sends an event directly to the subscription stream of the
// currently connected client.
//
// This method triggers the router to resolve the client's operation and emit
// the resulting data as a stream event. The event exists only within the
// router; it is not forwarded to any message broker.
//
// The event is delivered exclusively to the client associated with the current
// handler execution. No other subscriptions are affected.
//
// The method returns true if the event was successfully emitted, or false if
// it was dropped.
EmitEvent(event datasource.StreamEvent) bool
// NewEvent creates a new event that can be used in the subscription.
//
// The data parameter must contain valid JSON bytes. The format depends on the subscription type.
//
// For event-driven subscriptions (Cosmo Streams / EDFS), the data should contain:
// __typename : The name of the schema entity, which is expected to be returned to the client.
// {keyName} : The key of the entity as configured on the schema via @key directive.
// Example usage: ctx.NewEvent([]byte(`{"__typename": "Employee", "id": 1}`))
//
// For normal subscriptions, you need to provide the complete GraphQL response structure.
// Example usage: ctx.NewEvent([]byte(`{"data": {"fieldName": value}}`))
//
// You can use EmitEvent to emit this event to subscriptions.
NewEvent(data []byte) datasource.MutableStreamEvent
}
type SubscriptionParams ¶
func NegotiateSubscriptionParams ¶
func NegotiateSubscriptionParams(r *http.Request, preferJson bool) SubscriptionParams
type SubscriptionRegistration ¶
type SubscriptionRegistration struct {
// contains filtered or unexported fields
}
type TlsClientAuthConfig ¶
type TlsConfig ¶
type TlsConfig struct {
Enabled bool
CertFile string
KeyFile string
ClientAuth *TlsClientAuthConfig
}
type TraceDialer ¶
type TraceDialer struct {
// contains filtered or unexported fields
}
func NewTraceDialer ¶
func NewTraceDialer() *TraceDialer
func (*TraceDialer) WrapDial ¶
func (t *TraceDialer) WrapDial(base DialerFunc, subgraph string) DialerFunc
type TracePropagationProvider ¶
type TracePropagationProvider interface {
// TracePropagators returns the custom trace propagators which should be used by the router.
TracePropagators() []propagation.TextMapPropagator
}
TracePropagationProvider is an interface that allows you to provide custom trace propagators. The trace propagators are used to inject and extract trace information from the request. The provided propagators will be used in addition to the configured propagators.
type TransportFactory ¶
type TransportFactory struct {
// contains filtered or unexported fields
}
func NewTransport ¶
func NewTransport(opts *TransportOptions) *TransportFactory
func (TransportFactory) DefaultHTTPProxyURL ¶
func (t TransportFactory) DefaultHTTPProxyURL() *url.URL
func (TransportFactory) RoundTripper ¶
func (t TransportFactory) RoundTripper(baseTransport http.RoundTripper) http.RoundTripper
type TransportOptions ¶
type TransportOptions struct {
PreHandlers []TransportPreHandler
PostHandlers []TransportPostHandler
SubgraphTransportOptions *SubgraphTransportOptions
RetryOptions retrytransport.RetryOptions
LocalhostFallbackInsideDocker bool
MetricStore metric.Store
ConnectionMetricStore metric.ConnectionMetricStore
CircuitBreaker *circuit.Manager
Logger *zap.Logger
TracerProvider *sdktrace.TracerProvider
TracePropagators propagation.TextMapPropagator
EnableTraceClient bool
}
type TransportPostHandler ¶
type TransportPostHandler func(resp *http.Response, ctx RequestContext) *http.Response
type TransportPreHandler ¶
type TransportRequestOptions ¶
type TransportRequestOptions struct {
RequestTimeout time.Duration
ResponseHeaderTimeout time.Duration
ExpectContinueTimeout time.Duration
KeepAliveIdleTimeout time.Duration
DialTimeout time.Duration
TLSHandshakeTimeout time.Duration
KeepAliveProbeInterval time.Duration
MaxConnsPerHost int
MaxIdleConns int
MaxIdleConnsPerHost int
}
func DefaultTransportRequestOptions ¶
func DefaultTransportRequestOptions() *TransportRequestOptions
func NewTransportRequestOptions ¶
func NewTransportRequestOptions(cfg config.GlobalSubgraphRequestRule, defaults *TransportRequestOptions) *TransportRequestOptions
NewTransportRequestOptions creates a new TransportRequestOptions instance with the given configuration and defaults. If defaults is nil, it uses the global default values.
type UsageTracker ¶
type UsageTrackerNoOp ¶
type UsageTrackerNoOp struct{}
func (*UsageTrackerNoOp) Close ¶
func (u *UsageTrackerNoOp) Close()
func (*UsageTrackerNoOp) TrackExecutionConfigUsage ¶
func (u *UsageTrackerNoOp) TrackExecutionConfigUsage(_ map[string]any)
func (*UsageTrackerNoOp) TrackRouterConfigUsage ¶
func (u *UsageTrackerNoOp) TrackRouterConfigUsage(_ map[string]any)
func (*UsageTrackerNoOp) TrackUptime ¶
func (u *UsageTrackerNoOp) TrackUptime(_ context.Context)
type VariablesNormalizationCacheEntry ¶
type VariablesNormalizationCacheEntry struct {
// contains filtered or unexported fields
}
type WebSocketConnectionHandler ¶
type WebSocketConnectionHandler struct {
// contains filtered or unexported fields
}
func NewWebsocketConnectionHandler ¶
func NewWebsocketConnectionHandler(ctx context.Context, opts WebSocketConnectionHandlerOptions) *WebSocketConnectionHandler
func (*WebSocketConnectionHandler) Close ¶
func (h *WebSocketConnectionHandler) Close(unsubscribe bool)
func (*WebSocketConnectionHandler) Complete ¶
func (h *WebSocketConnectionHandler) Complete(rw *websocketResponseWriter)
func (*WebSocketConnectionHandler) Initialize ¶
func (h *WebSocketConnectionHandler) Initialize() (err error)
type WebSocketConnectionHandlerOptions ¶
type WebSocketConnectionHandlerOptions struct {
ClientInfoFromInitialPayload config.WebSocketClientInfoFromInitialPayloadConfiguration
ForwardInitialPayload bool
OperationProcessor *OperationProcessor
OperationBlocker *OperationBlocker
Planner *OperationPlanner
GraphQLHandler *GraphQLHandler
PreHandler *PreHandler
Metrics RouterMetrics
ResponseWriter http.ResponseWriter
Request *http.Request
Connection *wsConnectionWrapper
Protocol wsproto.Proto
Logger *zap.Logger
Stats statistics.EngineStatistics
PlanOptions PlanOptions
ConnectionID int64
ClientInfo *ClientInfo
InitRequestID string
ForwardUpgradeHeaders forwardConfig
ForwardQueryParams forwardConfig
DisableVariablesRemapping bool
ApolloCompatibilityFlags config.ApolloCompatibilityFlags
}
type WebsocketHandler ¶
type WebsocketHandler struct {
// contains filtered or unexported fields
}
func (*WebsocketHandler) HandleMessage ¶
func (h *WebsocketHandler) HandleMessage(handler *WebSocketConnectionHandler, msg *wsproto.Message) (err error)
type WebsocketMiddlewareOptions ¶
type WebsocketMiddlewareOptions struct {
OperationProcessor *OperationProcessor
OperationBlocker *OperationBlocker
Planner *OperationPlanner
GraphQLHandler *GraphQLHandler
PreHandler *PreHandler
Metrics RouterMetrics
AccessController *AccessController
Logger *zap.Logger
Stats statistics.EngineStatistics
ReadTimeout time.Duration
WriteTimeout time.Duration
EnableNetPoll bool
NetPollTimeout time.Duration
NetPollConnBufferSize int
WebSocketConfiguration *config.WebSocketConfiguration
ClientHeader config.ClientHeader
DisableVariablesRemapping bool
ApolloCompatibilityFlags config.ApolloCompatibilityFlags
}
Source Files
¶
- access_controller.go
- attribute_expressions.go
- attribute_mapper.go
- authorizer.go
- batch.go
- cache_warmup.go
- cache_warmup_cdn.go
- cache_warmup_filesystem.go
- cache_warmup_plans.go
- context.go
- engine_loader_hooks.go
- errors.go
- execution_config_usage.go
- executor.go
- factoryresolver.go
- flushwriter.go
- graph_server.go
- graphql_handler.go
- graphql_prehandler.go
- header_rule_engine.go
- http_graphql_error.go
- http_server.go
- init_config_poller.go
- modules.go
- operation_blocker.go
- operation_metrics.go
- operation_planner.go
- operation_processor.go
- parse_multipart.go
- plan_generator.go
- ratelimiter.go
- reload_persistent_state.go
- request_context_fields.go
- request_tracing.go
- retry_builder.go
- router.go
- router_config.go
- router_metrics.go
- subscriptions_modules.go
- supervisor.go
- supervisor_instance.go
- trace_dialer.go
- transport.go
- version.go
- websocket.go