Documentation ¶
Index ¶
- Constants
- Variables
- func AccessLogsFieldHandler(attributes []config.CustomAttribute, err any, request *http.Request, ...) []zapcore.Field
- func AddCacheControlPolicyToRules(rules *config.HeaderRules, cacheControl config.CacheControlPolicy) *config.HeaderRules
- func CorsDefaultOptions() *cors.Config
- 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) string
- func HeaderPropagationWriter(w http.ResponseWriter, ctx context.Context) io.Writer
- func InitializeConfigPoller(r *Router, cdnProviders map[string]config.BaseStorageProvider, ...) (*configpoller.ConfigPoller, error)
- 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 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 PropagatedHeaders(rules []*config.RequestHeaderRule) (headerNames []string, headerNameRegexps []*regexp.Regexp, err error)
- func RegisterModule(instance Module)
- func SpanNameFormatter(_ string, r *http.Request) string
- 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 WriteResponseError(ctx RequestContext, err error)
- type AccessController
- type AccessLogsConfig
- type ApiTransportFactory
- type AuthorizationExtension
- type CacheWarmupConfig
- type CacheWarmupItem
- 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
- type CosmoRateLimiterOptions
- type CustomTransport
- type DefaultFactoryResolver
- func (d *DefaultFactoryResolver) ResolveGraphqlFactory() (plan.PlannerFactory[graphql_datasource.Configuration], error)
- func (d *DefaultFactoryResolver) ResolvePubsubFactory() (factory plan.PlannerFactory[pubsub_datasource.Configuration], err error)
- func (d *DefaultFactoryResolver) ResolveStaticFactory() (factory plan.PlannerFactory[staticdatasource.Configuration], err error)
- type EnginePostOriginHandler
- type EnginePreOriginHandler
- type EnginePubSubProviders
- type ExecutionConfig
- type ExecutionPlanCache
- type Executor
- type ExecutorBuildOptions
- type ExecutorConfigurationBuilder
- type Extensions
- type FactoryResolver
- type FileSystemSource
- type FileSystemSourceConfig
- type GraphQLErrorResponse
- type GraphQLHandler
- type GraphQLMetricsConfig
- type GraphQLRequest
- type GraphQLRequestExtensions
- type GraphQLRequestExtensionsPersistedQuery
- type HandlerOptions
- type HeaderPropagation
- func (h *HeaderPropagation) HasRequestRules() bool
- func (h *HeaderPropagation) HasResponseRules() bool
- func (h *HeaderPropagation) OnOriginRequest(request *http.Request, ctx RequestContext) (*http.Request, *http.Response)
- func (h *HeaderPropagation) OnOriginResponse(resp *http.Response, ctx RequestContext) *http.Response
- type HttpError
- type HttpFlushWriter
- type IPAnonymizationConfig
- type IPAnonymizationMethod
- type Loader
- type MissingScopesError
- type Module
- type ModuleContext
- type ModuleID
- type ModuleInfo
- type ModuleRequestContext
- type MultipartParser
- type NoopWebSocketStats
- func (s *NoopWebSocketStats) ConnectionsDec()
- func (s *NoopWebSocketStats) ConnectionsInc()
- func (s *NoopWebSocketStats) GetReport() *UsageReport
- func (s *NoopWebSocketStats) Subscribe(_ context.Context) chan *UsageReport
- func (s *NoopWebSocketStats) SubscriptionCountDec(_ int)
- func (s *NoopWebSocketStats) SubscriptionCountInc(_ int)
- func (s *NoopWebSocketStats) SubscriptionUpdateSent()
- func (s *NoopWebSocketStats) SynchronousSubscriptionsDec()
- func (s *NoopWebSocketStats) SynchronousSubscriptionsInc()
- func (s *NoopWebSocketStats) TriggerCountDec(count int)
- func (s *NoopWebSocketStats) TriggerCountInc(count int)
- 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) (bool, bool, error)
- func (o *OperationKit) Free()
- func (o *OperationKit) NormalizeOperation(clientName string, isApq bool) (bool, error)
- func (o *OperationKit) NormalizeVariables() error
- func (o *OperationKit) Parse() error
- func (o *OperationKit) UnmarshalOperationFromBody(data []byte) error
- func (o *OperationKit) UnmarshalOperationFromURL(url *url.URL) error
- func (o *OperationKit) Validate(skipLoader bool) (cacheHit bool, err error)
- func (o *OperationKit) ValidateQueryComplexity(complexityLimitConfig *config.ComplexityLimits, ...) (bool, ComplexityCacheEntry, error)
- type OperationMetrics
- type OperationMetricsOptions
- type OperationPlanner
- type OperationProcessor
- type OperationProcessorOptions
- type OperationProtocol
- 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 WithAuthorizationConfig(cfg *config.AuthorizationConfiguration) Option
- func WithAutomatedPersistedQueriesConfig(cfg config.AutomaticPersistedQueriesConfig) Option
- func WithAwsLambdaRuntime() 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 WithCors(corsOpts *cors.Config) Option
- func WithCustomModules(modules ...Module) Option
- func WithDevelopmentMode(enabled bool) 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 WithHostName(hostName string) Option
- func WithInstanceID(id string) Option
- func WithIntrospection(enable bool) Option
- func WithListenerAddr(addr string) Option
- func WithLivenessCheckPath(path string) Option
- func WithLocalhostFallbackInsideDocker(fallback bool) Option
- func WithLogger(logger *zap.Logger) Option
- func WithMetrics(cfg *rmetric.Config) Option
- func WithModulesConfig(config map[string]interface{}) Option
- func WithMultipartHeartbeatInterval(interval time.Duration) 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 WithPlaygroundPath(p string) Option
- func WithProxy(proxy ProxyFunc) Option
- func WithQueryPlans(enabled bool) Option
- func WithRateLimitConfig(cfg *config.RateLimitConfiguration) Option
- func WithReadinessCheckPath(path string) 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 WithSubgraphErrorPropagation(cfg config.SubgraphErrorPropagationConfiguration) Option
- func WithSubgraphRetryOptions(enabled bool, maxRetryCount int, retryMaxDuration, retryInterval time.Duration) Option
- func WithSubgraphTransportOptions(opts *SubgraphTransportOptions) Option
- func WithTLSConfig(cfg *TlsConfig) Option
- func WithTelemetryAttributes(attributes []config.CustomAttribute) Option
- func WithTracing(cfg *rtrace.Config) Option
- func WithWebSocketConfiguration(cfg *config.WebSocketConfiguration) Option
- type ParsedOperation
- type PlanOptions
- type PreHandler
- type PreHandlerOptions
- type Provisioner
- type ProxyFunc
- type RateLimitStats
- type ReportError
- type RequestContext
- type RequiredAndScopes
- type Router
- type RouterConfigPollerConfig
- type RouterEngineConfiguration
- type RouterMetrics
- type RouterMiddlewareHandler
- type Server
- type Subgraph
- type SubgraphResolver
- type SubgraphTransportOptions
- type SubscriptionParams
- type SubscriptionRegistration
- type TimeoutTransport
- type TlsClientAuthConfig
- type TlsConfig
- type TransportFactory
- type TransportOptions
- type TransportPostHandler
- type TransportPreHandler
- type TransportTimeoutOptions
- type UsageReport
- type WebSocketConnectionHandler
- type WebSocketConnectionHandlerOptions
- type WebSocketStats
- func (s *WebSocketStats) ConnectionsDec()
- func (s *WebSocketStats) ConnectionsInc()
- func (s *WebSocketStats) GetReport() *UsageReport
- func (s *WebSocketStats) Subscribe(ctx context.Context) chan *UsageReport
- func (s *WebSocketStats) SubscriptionCountDec(count int)
- func (s *WebSocketStats) SubscriptionCountInc(count int)
- func (s *WebSocketStats) SubscriptionUpdateSent()
- func (s *WebSocketStats) TriggerCountDec(count int)
- func (s *WebSocketStats) TriggerCountInc(count int)
- type WebSocketsStatistics
- type WebsocketHandler
- type WebsocketMiddlewareOptions
Constants ¶
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" )
const ( OperationProtocolHTTP = OperationProtocol("http") 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" )
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") )
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 ( // and authorization requires authentication // or when authentication information is available but invalid ErrUnauthorized = errors.New("unauthorized") )
Functions ¶
func AccessLogsFieldHandler ¶
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 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 GetWriterPrefix ¶
func HeaderPropagationWriter ¶
func InitializeConfigPoller ¶
func InitializeConfigPoller(r *Router, cdnProviders map[string]config.BaseStorageProvider, 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) resolve.LoaderHooks
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 PropagatedHeaders ¶
func PropagatedHeaders(rules []*config.RequestHeaderRule) (headerNames []string, headerNameRegexps []*regexp.Regexp, 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 SpanNameFormatter ¶
SpanNameFormatter formats the span name based on the http request
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 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(authenticators []authentication.Authenticator, authenticationRequired bool) *AccessController
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.
type AccessLogsConfig ¶
type AccessLogsConfig struct { Attributes []config.CustomAttribute Logger *zap.Logger SubgraphEnabled bool SubgraphAttributes []config.CustomAttribute }
type ApiTransportFactory ¶
type ApiTransportFactory interface { RoundTripper(enableSingleFlight bool, transport http.RoundTripper) http.RoundTripper DefaultTransportTimeout() time.Duration DefaultHTTPProxyURL() *url.URL }
type AuthorizationExtension ¶
type AuthorizationExtension struct { MissingScopes []MissingScopesError `json:"missingScopes,omitempty"` ActualScopes []string `json:"actualScopes"` }
type CacheWarmupConfig ¶
type CacheWarmupConfig struct { Log *zap.Logger Source CacheWarmupSource Workers int ItemsPerSecond int Timeout time.Duration Processor CacheWarmupProcessor }
type CacheWarmupItem ¶
type CacheWarmupItem struct { Request GraphQLRequest `json:"request"` Client *ClientInfo `json:"client"` }
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, item *CacheWarmupItem) error
type CacheWarmupPlanningProcessorOptions ¶
type CacheWarmupPlanningProcessorOptions struct { OperationProcessor *OperationProcessor OperationPlanner *OperationPlanner ComplexityLimits *config.ComplexityLimits RouterSchema *ast.Document TrackSchemaUsage bool }
type CacheWarmupProcessor ¶
type CacheWarmupProcessor interface {
ProcessOperation(ctx context.Context, item *CacheWarmupItem) error
}
type CacheWarmupSource ¶
type CacheWarmupSource interface {
LoadItems(ctx context.Context, log *zap.Logger) ([]*CacheWarmupItem, 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
}
Config defines the configuration options for the Router.
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) *CosmoRateLimiter
func (*CosmoRateLimiter) RateLimitPreFetch ¶
func (c *CosmoRateLimiter) RateLimitPreFetch(ctx *resolve.Context, info *resolve.FetchInfo, input json.RawMessage) (result *resolve.RateLimitDeny, err error)
func (*CosmoRateLimiter) RenderResponseExtension ¶
type CosmoRateLimiterOptions ¶
type CosmoRateLimiterOptions struct { RedisClient *redis.Client Debug bool }
type CustomTransport ¶
type CustomTransport struct {
// contains filtered or unexported fields
}
func NewCustomTransport ¶
func NewCustomTransport( logger *zap.Logger, roundTripper http.RoundTripper, retryOptions retrytransport.RetryOptions, metricStore metric.Store, enableSingleFlight bool, ) *CustomTransport
type DefaultFactoryResolver ¶
type DefaultFactoryResolver struct {
// contains filtered or unexported fields
}
func NewDefaultFactoryResolver ¶
func NewDefaultFactoryResolver( ctx context.Context, transportFactory ApiTransportFactory, baseTransport http.RoundTripper, log *zap.Logger, enableSingleFlight bool, enableNetPoll bool, natsPubSubBySourceID map[string]pubsub_datasource.NatsPubSub, kafkaPubSubBySourceID map[string]pubsub_datasource.KafkaPubSub, ) *DefaultFactoryResolver
func (*DefaultFactoryResolver) ResolveGraphqlFactory ¶
func (d *DefaultFactoryResolver) ResolveGraphqlFactory() (plan.PlannerFactory[graphql_datasource.Configuration], error)
func (*DefaultFactoryResolver) ResolvePubsubFactory ¶
func (d *DefaultFactoryResolver) ResolvePubsubFactory() (factory plan.PlannerFactory[pubsub_datasource.Configuration], err error)
func (*DefaultFactoryResolver) ResolveStaticFactory ¶
func (d *DefaultFactoryResolver) ResolveStaticFactory() (factory plan.PlannerFactory[staticdatasource.Configuration], err error)
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 EnginePubSubProviders ¶
type EnginePubSubProviders struct {
// contains filtered or unexported fields
}
type ExecutionConfig ¶
type ExecutionPlanCache ¶
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 PubSubProviders *EnginePubSubProviders Reporter resolve.Reporter ApolloCompatibilityFlags config.ApolloCompatibilityFlags HeartbeatInterval time.Duration }
type ExecutorConfigurationBuilder ¶
type ExecutorConfigurationBuilder struct {
// contains filtered or unexported fields
}
func (*ExecutorConfigurationBuilder) Build ¶
func (b *ExecutorConfigurationBuilder) Build(ctx context.Context, opts *ExecutorBuildOptions) (*Executor, error)
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"` }
type FactoryResolver ¶
type FactoryResolver interface { ResolveGraphqlFactory() (plan.PlannerFactory[graphql_datasource.Configuration], error) ResolveStaticFactory() (plan.PlannerFactory[staticdatasource.Configuration], error) ResolvePubsubFactory() (plan.PlannerFactory[pubsub_datasource.Configuration], error) }
type FileSystemSource ¶
type FileSystemSource struct {
RootPath string
}
func (*FileSystemSource) LoadItems ¶
func (f *FileSystemSource) LoadItems(_ context.Context, log *zap.Logger) ([]*CacheWarmupItem, error)
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 HandlerOptions ¶
type HandlerOptions struct { Executor *Executor Log *zap.Logger EnableExecutionPlanCacheResponseHeader bool EnablePersistedOperationCacheResponseHeader bool EnableNormalizationCacheResponseHeader bool EnableResponseHeaderPropagation bool WebSocketStats WebSocketsStatistics TracerProvider trace.TracerProvider Authorizer *CosmoAuthorizer RateLimiter *CosmoRateLimiter RateLimitConfig *config.RateLimitConfiguration SubgraphErrorPropagation config.SubgraphErrorPropagationConfiguration EngineLoaderHooks resolve.LoaderHooks }
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) HasRequestRules ¶
func (h *HeaderPropagation) HasRequestRules() bool
func (*HeaderPropagation) HasResponseRules ¶
func (h *HeaderPropagation) HasResponseRules() bool
func (*HeaderPropagation) OnOriginRequest ¶
func (h *HeaderPropagation) OnOriginRequest(request *http.Request, ctx RequestContext) (*http.Request, *http.Response)
func (*HeaderPropagation) OnOriginResponse ¶
func (h *HeaderPropagation) OnOriginResponse(resp *http.Response, ctx RequestContext) *http.Response
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()
func (*HttpFlushWriter) Complete ¶
func (f *HttpFlushWriter) Complete()
func (*HttpFlushWriter) Flush ¶
func (f *HttpFlushWriter) Flush() (err error)
type IPAnonymizationConfig ¶
type IPAnonymizationConfig struct { Enabled bool Method IPAnonymizationMethod }
type IPAnonymizationMethod ¶
type IPAnonymizationMethod string
const ( Hash IPAnonymizationMethod = "hash" Redact IPAnonymizationMethod = "redact" )
type Loader ¶
type Loader struct {
// contains filtered or unexported fields
}
func NewLoader ¶
func NewLoader(includeInfo bool, resolver FactoryResolver) *Loader
func (*Loader) Load ¶
func (l *Loader) Load(engineConfig *nodev1.EngineConfiguration, subgraphs []*nodev1.Subgraph, routerEngineConfig *RouterEngineConfiguration) (*plan.Configuration, 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.File, error)
func (*MultipartParser) RemoveAll ¶
func (p *MultipartParser) RemoveAll() (err error)
type NoopWebSocketStats ¶
type NoopWebSocketStats struct{}
func NewNoopWebSocketStats ¶
func NewNoopWebSocketStats() *NoopWebSocketStats
func (*NoopWebSocketStats) ConnectionsDec ¶
func (s *NoopWebSocketStats) ConnectionsDec()
func (*NoopWebSocketStats) ConnectionsInc ¶
func (s *NoopWebSocketStats) ConnectionsInc()
func (*NoopWebSocketStats) GetReport ¶
func (s *NoopWebSocketStats) GetReport() *UsageReport
func (*NoopWebSocketStats) Subscribe ¶
func (s *NoopWebSocketStats) Subscribe(_ context.Context) chan *UsageReport
func (*NoopWebSocketStats) SubscriptionCountDec ¶
func (s *NoopWebSocketStats) SubscriptionCountDec(_ int)
func (*NoopWebSocketStats) SubscriptionCountInc ¶
func (s *NoopWebSocketStats) SubscriptionCountInc(_ int)
func (*NoopWebSocketStats) SubscriptionUpdateSent ¶
func (s *NoopWebSocketStats) SubscriptionUpdateSent()
func (*NoopWebSocketStats) SynchronousSubscriptionsDec ¶
func (s *NoopWebSocketStats) SynchronousSubscriptionsDec()
func (*NoopWebSocketStats) SynchronousSubscriptionsInc ¶
func (s *NoopWebSocketStats) SynchronousSubscriptionsInc()
func (*NoopWebSocketStats) TriggerCountDec ¶
func (s *NoopWebSocketStats) TriggerCountDec(count int)
func (*NoopWebSocketStats) TriggerCountInc ¶
func (s *NoopWebSocketStats) TriggerCountInc(count int)
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
func (*OperationBlocker) OperationIsBlocked ¶
func (o *OperationBlocker) OperationIsBlocked(operation *ParsedOperation) error
type OperationBlockerOptions ¶
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 // ClientInfo returns information about the client that initiated this operation ClientInfo() ClientInfo }
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) (bool, bool, 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() error
func (*OperationKit) Parse ¶
func (o *OperationKit) Parse() error
Parse parses the operation, populate the document and set the operation type. UnmarshalOperationFromBody must be called before calling this method.
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) (cacheHit bool, err error)
Validate validates the operation variables.
func (*OperationKit) ValidateQueryComplexity ¶
func (o *OperationKit) ValidateQueryComplexity(complexityLimitConfig *config.ComplexityLimits, operation, definition *ast.Document, isPersisted bool) (bool, ComplexityCacheEntry, 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 OperationMetricsOptions struct { InFlightAddOption otelmetric.AddOption SliceAttributes []attribute.KeyValue RouterConfigVersion string RequestContentLength int64 RouterMetrics RouterMetrics Logger *zap.Logger TrackUsageInfo bool }
type OperationPlanner ¶
type OperationPlanner struct {
// contains filtered or unexported fields
}
func NewOperationPlanner ¶
func NewOperationPlanner(executor *Executor, planCache ExecutionPlanCache[uint64, *planWithMetaData]) *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.SaveClient AutomaticPersistedOperationCacheTtl int EnablePersistedOperationsCache bool PersistedOpsNormalizationCache *ristretto.Cache[uint64, NormalizationCacheEntry] NormalizationCache *ristretto.Cache[uint64, NormalizationCacheEntry] QueryDepthCache *ristretto.Cache[uint64, ComplexityCacheEntry] ValidationCache *ristretto.Cache[uint64, bool] OperationHashCache *ristretto.Cache[uint64, string] ParseKitPoolSize int IntrospectionEnabled bool ApolloCompatibilityFlags config.ApolloCompatibilityFlags }
type OperationProtocol ¶
type OperationProtocol string
func (OperationProtocol) String ¶
func (p OperationProtocol) String() string
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 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 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 WithCustomModules ¶
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 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 WithHostName ¶
func WithInstanceID ¶
func WithIntrospection ¶
func WithListenerAddr ¶
func WithLivenessCheckPath ¶
func WithLogger ¶
func WithMetrics ¶
WithMetrics sets the metrics configuration for the router.
func WithModulesConfig ¶
func WithMultipartHeartbeatInterval ¶
WithMultipartHeartbeatInterval sets the interval for the engine to send heartbeats for multipart subscriptions.
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 WithPlaygroundPath ¶
WithPlaygroundPath sets the path where the GraphQL Playground is served.
func WithQueryPlans ¶
func WithRateLimitConfig ¶
func WithRateLimitConfig(cfg *config.RateLimitConfiguration) Option
func WithReadinessCheckPath ¶
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 WithSubgraphErrorPropagation ¶
func WithSubgraphErrorPropagation(cfg config.SubgraphErrorPropagationConfiguration) Option
func WithSubgraphTransportOptions ¶
func WithSubgraphTransportOptions(opts *SubgraphTransportOptions) Option
func WithTLSConfig ¶
func WithTelemetryAttributes ¶
func WithTelemetryAttributes(attributes []config.CustomAttribute) Option
func WithTracing ¶
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 // Files is a list of files, an interface representing the file data needed to be passed forward. Files []httpclient.File // 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 }
type PlanOptions ¶
type PlanOptions struct { ClientInfo *ClientInfo TraceOptions resolve.TraceOptions ExecutionOptions resolve.ExecutionOptions TrackSchemaUsageInfo bool }
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 }
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 RateLimitStats ¶
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 }
type RequiredAndScopes ¶
type RequiredAndScopes struct {
RequiredAndScopes []string `json:"and"`
}
type Router ¶
type Router struct { Config WebsocketStats WebSocketsStatistics // contains filtered or unexported fields }
Router is the main application instance.
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().
type RouterConfigPollerConfig ¶
type RouterConfigPollerConfig struct { config.ExecutionConfig PollInterval time.Duration GraphSignKey string }
type RouterEngineConfiguration ¶
type RouterEngineConfiguration struct { Execution config.EngineExecutionConfiguration Headers *config.HeaderRules Events config.EventsConfiguration SubgraphErrorPropagation config.SubgraphErrorPropagationConfiguration }
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) GqlMetricsExporter() *graphqlmetrics.Exporter 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 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 SubgraphTransportOptions ¶
type SubgraphTransportOptions struct { TransportTimeoutOptions SubgraphMap map[string]*TransportTimeoutOptions }
func DefaultSubgraphTransportOptions ¶
func DefaultSubgraphTransportOptions() *SubgraphTransportOptions
func NewSubgraphTransportOptions ¶
func NewSubgraphTransportOptions(cfg config.TrafficShapingRules) *SubgraphTransportOptions
type SubscriptionParams ¶
func NegotiateSubscriptionParams ¶
func NegotiateSubscriptionParams(r *http.Request) SubscriptionParams
type SubscriptionRegistration ¶
type SubscriptionRegistration struct {
// contains filtered or unexported fields
}
type TimeoutTransport ¶
type TimeoutTransport struct {
// contains filtered or unexported fields
}
func NewTimeoutTransport ¶
func NewTimeoutTransport(transportOpts *SubgraphTransportOptions, roundTripper http.RoundTripper, logger *zap.Logger, proxy ProxyFunc) *TimeoutTransport
type TlsClientAuthConfig ¶
type TlsConfig ¶
type TlsConfig struct { Enabled bool CertFile string KeyFile string ClientAuth *TlsClientAuthConfig }
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) DefaultTransportTimeout ¶
func (t TransportFactory) DefaultTransportTimeout() time.Duration
func (TransportFactory) RoundTripper ¶
func (t TransportFactory) RoundTripper(enableSingleFlight bool, baseTransport http.RoundTripper) http.RoundTripper
type TransportOptions ¶
type TransportOptions struct { PreHandlers []TransportPreHandler PostHandlers []TransportPostHandler SubgraphTransportOptions *SubgraphTransportOptions Proxy ProxyFunc RetryOptions retrytransport.RetryOptions LocalhostFallbackInsideDocker bool MetricStore metric.Store Logger *zap.Logger TracerProvider *sdktrace.TracerProvider TracePropagators propagation.TextMapPropagator }
type TransportPostHandler ¶
type TransportPostHandler func(resp *http.Response, ctx RequestContext) *http.Response
type TransportPreHandler ¶
type TransportTimeoutOptions ¶
type TransportTimeoutOptions struct { RequestTimeout time.Duration ResponseHeaderTimeout time.Duration ExpectContinueTimeout time.Duration KeepAliveIdleTimeout time.Duration DialTimeout time.Duration TLSHandshakeTimeout time.Duration KeepAliveProbeInterval time.Duration }
func NewTransportTimeoutOptions ¶
func NewTransportTimeoutOptions(cfg config.GlobalSubgraphRequestRule) TransportTimeoutOptions
type UsageReport ¶
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()
func (*WebSocketConnectionHandler) Complete ¶
func (h *WebSocketConnectionHandler) Complete(rw *websocketResponseWriter)
func (*WebSocketConnectionHandler) Initialize ¶
func (h *WebSocketConnectionHandler) Initialize() (err error)
type WebSocketConnectionHandlerOptions ¶
type WebSocketConnectionHandlerOptions struct { Config *config.WebSocketConfiguration 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 WebSocketsStatistics PlanOptions PlanOptions ConnectionID int64 ClientInfo *ClientInfo InitRequestID string ForwardUpgradeHeaders forwardConfig ForwardQueryParams forwardConfig Attributes []attribute.KeyValue }
type WebSocketStats ¶
type WebSocketStats struct {
// contains filtered or unexported fields
}
func NewWebSocketStats ¶
func NewWebSocketStats(ctx context.Context, logger *zap.Logger) *WebSocketStats
func (*WebSocketStats) ConnectionsDec ¶
func (s *WebSocketStats) ConnectionsDec()
func (*WebSocketStats) ConnectionsInc ¶
func (s *WebSocketStats) ConnectionsInc()
func (*WebSocketStats) GetReport ¶
func (s *WebSocketStats) GetReport() *UsageReport
func (*WebSocketStats) Subscribe ¶
func (s *WebSocketStats) Subscribe(ctx context.Context) chan *UsageReport
func (*WebSocketStats) SubscriptionCountDec ¶
func (s *WebSocketStats) SubscriptionCountDec(count int)
func (*WebSocketStats) SubscriptionCountInc ¶
func (s *WebSocketStats) SubscriptionCountInc(count int)
func (*WebSocketStats) SubscriptionUpdateSent ¶
func (s *WebSocketStats) SubscriptionUpdateSent()
func (*WebSocketStats) TriggerCountDec ¶
func (s *WebSocketStats) TriggerCountDec(count int)
func (*WebSocketStats) TriggerCountInc ¶
func (s *WebSocketStats) TriggerCountInc(count int)
type WebSocketsStatistics ¶
type WebSocketsStatistics interface { Subscribe(ctx context.Context) chan *UsageReport GetReport() *UsageReport SubscriptionUpdateSent() ConnectionsInc() ConnectionsDec() SubscriptionCountInc(count int) SubscriptionCountDec(count int) TriggerCountInc(count int) TriggerCountDec(count int) }
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 WebSocketsStatistics ReadTimeout time.Duration EnableNetPoll bool NetPollTimeout time.Duration NetPollConnBufferSize int WebSocketConfiguration *config.WebSocketConfiguration ClientHeader config.ClientHeader Attributes []attribute.KeyValue }
Source Files ¶
- access_controller.go
- authorizer.go
- cache_warmup.go
- cache_warmup_filesystem.go
- context.go
- engine_loader_hooks.go
- errors.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
- ratelimiter.go
- request_context_fields.go
- request_tracing.go
- router.go
- router_metrics.go
- timout_transport.go
- transport.go
- version.go
- websocket.go
- websocket_stats.go