github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/internal/metrics/request_interceptor.go (about)

     1  package metrics
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/99designs/gqlgen/graphql"
     7  	"github.com/vektah/gqlparser/v2/ast"
     8  )
     9  
    10  // GraphqlRequestInstrumenter collects metrics for GraphQL requests usage per enpoint.
    11  type GraphqlRequestInstrumenter interface {
    12  	InstrumentGraphqlRequest(queryType, queryOperation string)
    13  }
    14  
    15  // NewInstrumentGraphqlRequestInterceptor creates a new InstrumentGraphqlRequestInterceptor instance
    16  func NewInstrumentGraphqlRequestInterceptor(graphqlRequestInstrumenter GraphqlRequestInstrumenter) *instrumentGraphqlRequestInterceptor {
    17  	return &instrumentGraphqlRequestInterceptor{graphqlRequestInstrumenter: graphqlRequestInstrumenter}
    18  }
    19  
    20  type instrumentGraphqlRequestInterceptor struct {
    21  	graphqlRequestInstrumenter GraphqlRequestInstrumenter
    22  }
    23  
    24  func (m *instrumentGraphqlRequestInterceptor) ExtensionName() string {
    25  	return "GraphQL Metrics Request Interceptor Interceptor"
    26  }
    27  
    28  func (m *instrumentGraphqlRequestInterceptor) Validate(_ graphql.ExecutableSchema) error {
    29  	return nil
    30  }
    31  
    32  func (m *instrumentGraphqlRequestInterceptor) InterceptOperation(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler {
    33  	opsCtx := graphql.GetOperationContext(ctx)
    34  
    35  	for _, selection := range opsCtx.Operation.SelectionSet {
    36  		if field, ok := selection.(*ast.Field); ok {
    37  			m.graphqlRequestInstrumenter.InstrumentGraphqlRequest(string(opsCtx.Operation.Operation), field.Name)
    38  		}
    39  	}
    40  
    41  	return next(ctx)
    42  }