Skip to content

Context

The context.Context of a request reaches every resolver as p.Context. It carries request-scoped values, such as the signed-in user or a cache that lives for one request, and the request’s deadline or cancellation. This page adds both to the catalogue; the complete program is at the end.

Passing a context

graphql.Params.Context is the context of the request:

result := graphql.Do(graphql.Params{
	Schema:        schema,
	RequestString: query,
	Context:       ctx,
})

Resolvers read it as p.Context; ResolveType and IsTypeOf functions get it as p.Context too. Without one, the request runs with context.Background().

gql-go/handler passes the HTTP request’s context, r.Context(), from ServeHTTP; call ContextHandler(ctx, w, r) instead to pass a context of your own, for example one that carries the user that your authentication middleware found.

Request values

Store values under a key of an unexported type, so that no other package can read or overwrite them, and give them typed accessors:

type contextKey int

const userKey contextKey = 0

// WithUser returns a context that carries the signed-in user.
func WithUser(ctx context.Context, u *User) context.Context {
	return context.WithValue(ctx, userKey, u)
}

// UserFrom returns the signed-in user, or nil.
func UserFrom(ctx context.Context) *User {
	u, _ := ctx.Value(userKey).(*User)
	return u
}

A resolver can then check who is asking:

Resolve: func(p graphql.ResolveParams) (interface{}, error) {
	user := UserFrom(p.Context)
	if user == nil {
		return nil, errors.New("not signed in")
	}
	return user.Name, nil
},

Put in the context what belongs to the request, such as the user, a request ID or a per-request cache. Long-lived dependencies, such as a database handle, belong in the struct or closure your resolvers are built from.

Per-request caches

When several fields load the same data, a cache stored in the context lets the request load it once, without sharing results between requests:

// authorName returns the author's name, loading it at most once per request.
func authorName(ctx context.Context, id string) string {
	cache := ctx.Value(authorCacheKey).(*authorCache)
	cache.mu.Lock()
	defer cache.mu.Unlock()
	if name, ok := cache.authors[id]; ok {
		return name
	}
	cache.lookups++ // stands for a database query
	name := map[string]string{"le-guin": "Ursula K. Le Guin"}[id]
	cache.authors[id] = name
	return name
}

Create the cache for each request, where the context is built, and guard it with a mutex: resolvers of one request can run concurrently. In the example, three books by the same author cause one lookup. Batching the loads of a whole level of the response (the DataLoader pattern) in the executor is on the roadmap (#34).

Deadlines and cancellation

When the context is done, because its deadline passed or it was cancelled, execution stops waiting for the result and returns, after running the execution-finished hooks of any extensions, normally with data set to null and the context’s error:

{"data":null,"errors":[{"message":"context deadline exceeded","locations":[]}]}

Fields that had already resolved are discarded. A few details:

  • Parsing and validation run before the context is checked, so they still take their time, and an invalid document returns its syntax or validation error instead of the context’s.
  • If execution completes at the moment the context is done, the result can be returned instead of the error.
  • Execution itself is not stopped: resolvers that are running continue, and fields not yet resolved can still be resolved after graphql.Do has returned, even when the context was done before the call (#135). For a mutation, its side effects can happen while the client receives an error.

So a resolver that does slow work should watch the context itself, and pass it on to the calls it makes, such as database queries and HTTP requests:

Resolve: func(p graphql.ResolveParams) (interface{}, error) {
	select {
	case <-time.After(time.Second): // stands for slow work
		return "ready", nil
	case <-p.Context.Done():
		return nil, p.Context.Err()
	}
},

Complete program

main.go
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"sync"
	"time"

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

// contextKey is unexported, so no other package can read or overwrite the
// values stored under it.
type contextKey int

const (
	userKey contextKey = iota
	authorCacheKey
)

type User struct {
	Name string
}

// WithUser returns a context that carries the signed-in user.
func WithUser(ctx context.Context, u *User) context.Context {
	return context.WithValue(ctx, userKey, u)
}

// UserFrom returns the signed-in user, or nil.
func UserFrom(ctx context.Context) *User {
	u, _ := ctx.Value(userKey).(*User)
	return u
}

// authorCache remembers the authors looked up during one request.
type authorCache struct {
	mu      sync.Mutex
	authors map[string]string
	lookups int
}

func withAuthorCache(ctx context.Context) context.Context {
	return context.WithValue(ctx, authorCacheKey, &authorCache{authors: map[string]string{}})
}

// authorName returns the author's name, loading it at most once per request.
func authorName(ctx context.Context, id string) string {
	cache := ctx.Value(authorCacheKey).(*authorCache)
	cache.mu.Lock()
	defer cache.mu.Unlock()
	if name, ok := cache.authors[id]; ok {
		return name
	}
	cache.lookups++ // stands for a database query
	name := map[string]string{"le-guin": "Ursula K. Le Guin"}[id]
	cache.authors[id] = name
	return name
}

type Book struct {
	Title    string `json:"title"`
	AuthorID string `json:"-"`
}

var books = []*Book{
	{Title: "A Wizard of Earthsea", AuthorID: "le-guin"},
	{Title: "The Tombs of Atuan", AuthorID: "le-guin"},
	{Title: "The Farthest Shore", AuthorID: "le-guin"},
}

func newSchema() (graphql.Schema, error) {
	bookType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Book",
		Fields: graphql.Fields{
			"title": &graphql.Field{Type: graphql.String},
			"author": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return authorName(p.Context, p.Source.(*Book).AuthorID), nil
				},
			},
		},
	})
	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 books, nil
				},
			},
			"me": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					user := UserFrom(p.Context)
					if user == nil {
						return nil, errors.New("not signed in")
					}
					return user.Name, nil
				},
			},
			"report": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					select {
					case <-time.After(time.Second): // stands for slow work
						return "ready", nil
					case <-p.Context.Done():
						return nil, p.Context.Err()
					}
				},
			},
		},
	})
	return graphql.NewSchema(graphql.SchemaConfig{Query: queryType})
}

func run(ctx context.Context, schema graphql.Schema, query string) {
	result := graphql.Do(graphql.Params{Schema: schema, RequestString: query, Context: ctx})
	out, _ := json.MarshalIndent(result, "", "  ")
	fmt.Println(string(out))
}

func main() {
	schema, err := newSchema()
	if err != nil {
		log.Fatal(err)
	}

	// A signed-in request with its own cache.
	ctx := withAuthorCache(WithUser(context.Background(), &User{Name: "Ged"}))
	run(ctx, schema, `{ me books { title author } }`)
	fmt.Println("author lookups:", ctx.Value(authorCacheKey).(*authorCache).lookups)

	// An anonymous request.
	run(withAuthorCache(context.Background()), schema, `{ me }`)

	// A request with a deadline shorter than the work.
	ctx, cancel := context.WithTimeout(withAuthorCache(context.Background()), 50*time.Millisecond)
	defer cancel()
	run(ctx, schema, `{ report }`)
}

Running it prints the signed-in request, the number of author lookups, the anonymous request and the request whose deadline passed:

{
  "data": {
    "books": [
      {
        "author": "Ursula K. Le Guin",
        "title": "A Wizard of Earthsea"
      },
      {
        "author": "Ursula K. Le Guin",
        "title": "The Tombs of Atuan"
      },
      {
        "author": "Ursula K. Le Guin",
        "title": "The Farthest Shore"
      }
    ],
    "me": "Ged"
  }
}
author lookups: 1
{
  "data": {
    "me": null
  },
  "errors": [
    {
      "message": "not signed in",
      "locations": [
        {
          "line": 1,
          "column": 3
        }
      ],
      "path": [
        "me"
      ]
    }
  ]
}
{
  "data": null,
  "errors": [
    {
      "message": "context deadline exceeded",
      "locations": []
    }
  ]
}
Last updated on