Skip to content

Extensions

An extension is notified as a request goes through parsing, validation, execution and each field’s resolver, and can add values to the extensions of the response. Extensions suit cross-cutting work such as tracing, metrics and logging. This page builds an extension that times every resolver; the complete program is at the end.

Registering an extension

An extension implements the graphql.Extension interface and is registered on the schema:

schema, err := graphql.NewSchema(graphql.SchemaConfig{
	Query:      queryType,
	Extensions: []graphql.Extension{Tracing{}},
})

schema.AddExtensions adds extensions to a schema that already exists.

One extension value serves every request of the schema, concurrently. Keep per-request state in the context, as the example does, not in the extension’s fields.

Hooks

A request through graphql.Do calls the hooks in this order:

HookWhenReturns
Init(ctx, *Params)Before parsing.The context for the next hooks.
ParseDidStart(ctx)Before parsing.A context, and a ParseFinishFunc called with the syntax error or nil.
ValidationDidStart(ctx)Before validation.A context, and a ValidationFinishFunc called with the validation errors.
ExecutionDidStart(ctx)Before execution.A context, and an ExecutionFinishFunc called with the result.
ResolveFieldDidStart(ctx, *ResolveInfo)Before each field’s resolver.A context, and a ResolveFieldFinishFunc called with the value and the error the resolver returned.
HasResult(), GetResult(ctx)After execution.Whether to add a value to the response, and the value.

Each hook receives the context returned by the hook before it, and the context returned by ExecutionDidStart reaches the resolvers as p.Context (since v0.12.2; v0.9.0 to v0.12.1 lost it, #142). graphql.Execute runs a parsed document, so it calls only ExecutionDidStart, ResolveFieldDidStart and GetResult; that makes ExecutionDidStart the place to set up per-request state that should work with both. GetResult receives the context returned by ExecutionDidStart, without what ResolveFieldDidStart added, so keep values that GetResult reads in a structure created at execution start, as the trace below is:

// ExecutionDidStart creates the request's trace, so the extension works with
// graphql.Execute as well as graphql.Do.
func (Tracing) ExecutionDidStart(ctx context.Context) (context.Context, graphql.ExecutionFinishFunc) {
	t := &trace{start: time.Now()}
	return context.WithValue(ctx, traceKey{}, t), func(*graphql.Result) {}
}

When a request stops early, the later hooks are not called: after a syntax error, ParseFinishFunc is the last one, and after validation errors, ValidationFinishFunc.

Return a finish function from every hook, even one that does nothing: a nil function panics when it is called, with the effects described in Hook failures.

GetResult puts its value in result.Extensions under the extension’s Name():

func (Tracing) GetResult(ctx context.Context) interface{} {
	t, _ := ctx.Value(traceKey{}).(*trace)
	if t == nil {
		return nil
	}
	t.mu.Lock()
	defer t.mu.Unlock()
	return map[string]interface{}{
		"duration": time.Since(t.start).Round(10 * time.Millisecond).String(),
		"fields":   append([]FieldTiming(nil), t.fields...),
	}
}

Give every extension a distinct name. The finish functions and results are kept by name, so of two extensions with the same name, only one has its finish functions called and its result returned. The finish functions of different extensions run in no particular order.

Timing fields

ResolveFieldDidStart runs right before the resolver, and the function it returns right after, which makes a resolver’s duration the time between the two:

func (Tracing) ResolveFieldDidStart(ctx context.Context, info *graphql.ResolveInfo) (context.Context, graphql.ResolveFieldFinishFunc) {
	t, _ := ctx.Value(traceKey{}).(*trace)
	if t == nil {
		return ctx, func(interface{}, error) {}
	}
	start := time.Now()
	return ctx, func(interface{}, error) {
		t.mu.Lock()
		defer t.mu.Unlock()
		t.fields = append(t.fields, FieldTiming{
			Path: pathString(info.Path),
			// Rounded so that the output of this example is the same on
			// every run; keep the full precision in real code.
			Duration: time.Since(start).Round(10 * time.Millisecond).String(),
		})
	}
}

The trace is guarded by a mutex: when a request is cancelled, graphql.Do returns, and GetResult runs, while resolvers that already started keep calling the field hooks (#135).

The finish function sees what the resolver returned, before the value is completed. For a concurrent resolver, that is the function the executor calls later, so the measured time covers starting the work, not waiting for it. Fields without a resolver are timed too, since the default resolver runs for them.

When a resolver panics, the executor recovers the panic outside the call, and the finish function is not called: the field is missing from the trace. Do not rely on the finish function to release what ResolveFieldDidStart acquired.

Per-field context

By default, the context returned by ResolveFieldDidStart is not scoped to its field: every field resolved after it starts from that context, siblings and other branches included, and the chain of contexts grows by one layer per field (#145). Set SchemaConfig.FieldContext to graphql.FieldContextScoped (v0.15.0) to apply it to that field only:

schema, err := graphql.NewSchema(graphql.SchemaConfig{
	Query:        queryType,
	Extensions:   []graphql.Extension{Tracing{}},
	FieldContext: graphql.FieldContextScoped,
})

In that mode the field’s resolver, the ResolveType or IsTypeOf of its value and its sub-fields, including those of a concurrent resolver, receive that context, and the next field starts from its parent’s. That makes it the place for a per-field span or deadline, with each field’s span the child of its parent field’s. Without the option, do not put per-field values in that context.

Hook failures

A panic in a hook is recovered and reported as an error named after the extension and the hook, such as tracing.ExecutionDidStart: .... These errors have no location or path.

Hook that panicsEffect
Init, ParseDidStart, ValidationDidStart, ExecutionDidStart, and the parse and validation finish functionsThe request stops and data is null. When a parse or validation finish function panics after a syntax or validation error, the response has both errors; otherwise the hook’s error is the only one.
ResolveFieldDidStartThe field resolves as usual, with the error added; that extension’s finish function is not called for the field.
ExecutionFinishFunc, ResolveFieldFinishFunc, HasResult, GetResultThe error is added to the response, and the data is kept. A panic in HasResult is reported as GetResult.

When Params.Context or ExecuteParams.Context is not set, the hooks receive context.Background(), as resolvers do.

Cost

Without extensions, the field hooks are skipped. With one extension, every resolved field allocates and calls the hooks. For a query of 1,001 fields measured on master, an extension whose hooks do nothing took:

ExtensionsTimeAllocations
none0.51 ms7,048
one, doing nothing0.73 ms10,054

That is about three allocations per field before the extension does any work, so keep the field hooks cheap, or leave them out of schemas that serve large responses.

Limits

Extensions observe a request; they do not change it. A hook cannot replace a field’s value, skip its resolver or retry it. Field middleware, which wraps resolvers and can do all three, is on the roadmap (#12).

Complete program

main.go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/gql-go/graphql"
	"github.com/gql-go/graphql/gqlerrors"
)

// FieldTiming is the time one field's resolver took.
type FieldTiming struct {
	Path     string `json:"path"`
	Duration string `json:"duration"`
}

// trace collects the timings of one request.
type trace struct {
	mu     sync.Mutex
	start  time.Time
	fields []FieldTiming
}

type traceKey struct{}

// Tracing is an extension that reports how long each resolver took, under
// "tracing" in the response's extensions.
type Tracing struct{}

func (Tracing) Name() string { return "tracing" }

func (Tracing) Init(ctx context.Context, p *graphql.Params) context.Context { return ctx }

func (Tracing) ParseDidStart(ctx context.Context) (context.Context, graphql.ParseFinishFunc) {
	return ctx, func(error) {}
}

func (Tracing) ValidationDidStart(ctx context.Context) (context.Context, graphql.ValidationFinishFunc) {
	return ctx, func([]gqlerrors.FormattedError) {}
}

// ExecutionDidStart creates the request's trace, so the extension works with
// graphql.Execute as well as graphql.Do.
func (Tracing) ExecutionDidStart(ctx context.Context) (context.Context, graphql.ExecutionFinishFunc) {
	t := &trace{start: time.Now()}
	return context.WithValue(ctx, traceKey{}, t), func(*graphql.Result) {}
}

func (Tracing) ResolveFieldDidStart(ctx context.Context, info *graphql.ResolveInfo) (context.Context, graphql.ResolveFieldFinishFunc) {
	t, _ := ctx.Value(traceKey{}).(*trace)
	if t == nil {
		return ctx, func(interface{}, error) {}
	}
	start := time.Now()
	return ctx, func(interface{}, error) {
		t.mu.Lock()
		defer t.mu.Unlock()
		t.fields = append(t.fields, FieldTiming{
			Path: pathString(info.Path),
			// Rounded so that the output of this example is the same on
			// every run; keep the full precision in real code.
			Duration: time.Since(start).Round(10 * time.Millisecond).String(),
		})
	}
}

func (Tracing) HasResult() bool { return true }

func (Tracing) GetResult(ctx context.Context) interface{} {
	t, _ := ctx.Value(traceKey{}).(*trace)
	if t == nil {
		return nil
	}
	t.mu.Lock()
	defer t.mu.Unlock()
	return map[string]interface{}{
		"duration": time.Since(t.start).Round(10 * time.Millisecond).String(),
		"fields":   append([]FieldTiming(nil), t.fields...),
	}
}

// pathString formats a response path as "books.0.title".
func pathString(p *graphql.ResponsePath) string {
	var parts []string
	for _, k := range p.AsArray() {
		parts = append(parts, fmt.Sprint(k))
	}
	return strings.Join(parts, ".")
}

// Book is a book in the catalogue.
type Book struct {
	ID    string `json:"id"`
	Title string `json:"title"`
}

var books = []*Book{
	{ID: "1", Title: "A Wizard of Earthsea"},
	{ID: "2", Title: "The Left Hand of Darkness"},
}

// slow stands for a call to another service.
func slow(d time.Duration, v interface{}) (interface{}, error) {
	time.Sleep(d)
	return v, nil
}

func main() {
	bookType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Book",
		Fields: graphql.Fields{
			"title": &graphql.Field{Type: graphql.String},
			"rating": &graphql.Field{
				Type: graphql.Float,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return slow(30*time.Millisecond, 4.5)
				},
			},
		},
	})
	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"books": &graphql.Field{
				Type: graphql.NewList(bookType),
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return slow(20*time.Millisecond, books)
				},
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query:      queryType,
		Extensions: []graphql.Extension{Tracing{}},
	})
	if err != nil {
		log.Fatal(err)
	}

	result := graphql.Do(graphql.Params{
		Schema:        schema,
		RequestString: `{ books { title rating } }`,
		Context:       context.Background(),
	})
	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	if err := enc.Encode(result); err != nil {
		log.Fatal(err)
	}
}

Running it prints the data and, under extensions, the time each resolver took. books and each rating sleep; each title uses the default resolver:

{
  "data": {
    "books": [
      {
        "rating": 4.5,
        "title": "A Wizard of Earthsea"
      },
      {
        "rating": 4.5,
        "title": "The Left Hand of Darkness"
      }
    ]
  },
  "extensions": {
    "tracing": {
      "duration": "80ms",
      "fields": [
        {
          "path": "books",
          "duration": "20ms"
        },
        {
          "path": "books.0.title",
          "duration": "0s"
        },
        {
          "path": "books.0.rating",
          "duration": "30ms"
        },
        {
          "path": "books.1.title",
          "duration": "0s"
        },
        {
          "path": "books.1.rating",
          "duration": "30ms"
        }
      ]
    }
  }
}
Last updated on