Concurrent resolvers
Resolvers run one after another. When fields wait on slow work, such as calls to other services, a resolver can start that work in a goroutine and return a function that waits for it; the executor calls the function later, after the other fields of the same level have started their work. This page shows how it works and the helper the complete program uses.
How it works
A resolver that returns a value of type func() (interface{}, error) defers its
field: the executor stores the function, resolves the remaining fields, and then
calls the stored functions one at a time, level by level. The function’s result
is the field’s value.
The executor calls those functions in its own goroutine, so the work only runs in parallel if the resolver has already started it before returning:
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
ch := make(chan interface{}, 1)
go func() { ch <- slowWork() }() // starts now
return func() (interface{}, error) {
return <-ch, nil // waits later
}, nil
},Three fields doing 100 ms of work each, measured on master:
| Where the work runs | Time |
|---|---|
| In a goroutine started by the resolver | 100 ms |
| Inside the returned function | 300 ms |
The same applies to every item of a list: three books with a field each take
100 ms, not 300 ms. Fields of the next level start only when the value of their
parent is known, so books { author { name } } with 100 ms on author and
on name takes 200 ms.
A helper
A helper keeps the pattern in one place, and handles two things a plain goroutine does not:
// async starts fetch in a goroutine and returns a function that waits for its
// result, which is what a concurrent resolver returns.
func async(ctx context.Context, fetch func(context.Context) (interface{}, error)) (interface{}, error) {
type result struct {
value interface{}
err error
}
ch := make(chan result, 1)
go func() {
// A panic in this goroutine would stop the program; turn it into
// an error for the field instead.
defer func() {
if r := recover(); r != nil {
ch <- result{err: fmt.Errorf("panic: %v", r)}
}
}()
value, err := fetch(ctx)
ch <- result{value, err}
}()
// The function can be called more than once, for example when a map
// value is selected under two aliases, so it keeps the first result.
var once sync.Once
var r result
return func() (interface{}, error) {
once.Do(func() {
select {
case r = <-ch:
case <-ctx.Done():
r = result{err: ctx.Err()}
}
})
return r.value, r.err
}, nil
}- Panics. The executor recovers panics in resolvers and in the returned function, and reports them as field errors. It cannot recover a panic in a goroutine you started: that stops the whole program, so the helper recovers it and returns it as an error.
- The request context. The work receives
p.Contextand the waiting stops when the context is done, so an abandoned request does not keep a resolver waiting; see Context. - Repeated calls. The executor can call the same function more than once, when a map value is selected under two aliases, so the function keeps its first result instead of waiting on the channel again.
A resolver then reads:
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
id := p.Source.(*Book).ID
return async(p.Context, func(ctx context.Context) (interface{}, error) {
return slowCall(ctx, id != "2")
})
},Read what the work needs from p before starting the goroutine, as id is
here, and guard any state that several goroutines share.
Errors
An error returned by the function, or a panic inside it, is a field error with the field’s path, like one returned by the resolver itself.
Two shapes are not supported:
- A function of any other type is an error:
Error resolving func. Expected `func() (interface{}, error)` signature. - A function that returns another function leaves that function in
Result.Data, which then fails to encode as JSON (#137). Return the value.
Mutations
The top-level fields of a mutation must run one after another. Functions returned by mutation resolvers are called only after every mutation resolver has run, and in an order that can change between executions (#102). Return values directly from mutation resolvers whose order matters; fields below them can still be concurrent.
Without a resolver
A map[string]interface{} source whose value is a
func() (interface{}, error) is treated the same way by the
default resolver.
Complete program
main.go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"sync"
"time"
"github.com/gql-go/graphql"
)
// async starts fetch in a goroutine and returns a function that waits for its
// result, which is what a concurrent resolver returns.
func async(ctx context.Context, fetch func(context.Context) (interface{}, error)) (interface{}, error) {
type result struct {
value interface{}
err error
}
ch := make(chan result, 1)
go func() {
// A panic in this goroutine would stop the program; turn it into
// an error for the field instead.
defer func() {
if r := recover(); r != nil {
ch <- result{err: fmt.Errorf("panic: %v", r)}
}
}()
value, err := fetch(ctx)
ch <- result{value, err}
}()
// The function can be called more than once, for example when a map
// value is selected under two aliases, so it keeps the first result.
var once sync.Once
var r result
return func() (interface{}, error) {
once.Do(func() {
select {
case r = <-ch:
case <-ctx.Done():
r = result{err: ctx.Err()}
}
})
return r.value, r.err
}, nil
}
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
}
// slowCall stands for a call to another service that takes 100 ms.
func slowCall(ctx context.Context, value interface{}) (interface{}, error) {
select {
case <-time.After(100 * time.Millisecond):
return value, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func newSchema() (graphql.Schema, error) {
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) {
id := p.Source.(*Book).ID
return async(p.Context, func(ctx context.Context) (interface{}, error) {
return slowCall(ctx, map[string]float64{"1": 4.5, "2": 4.2, "3": 4.4}[id])
})
},
},
"inStock": &graphql.Field{
Type: graphql.Boolean,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
id := p.Source.(*Book).ID
return async(p.Context, func(ctx context.Context) (interface{}, error) {
return slowCall(ctx, id != "2")
})
},
},
},
})
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 []*Book{
{ID: "1", Title: "A Wizard of Earthsea"},
{ID: "2", Title: "The Tombs of Atuan"},
{ID: "3", Title: "The Farthest Shore"},
}, nil
},
},
},
})
return graphql.NewSchema(graphql.SchemaConfig{Query: queryType})
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
start := time.Now()
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: `{ books { title rating inStock } }`,
Context: context.Background(),
})
// Six calls of 100 ms each, run at the same time.
fmt.Println("took about", time.Since(start).Round(100*time.Millisecond))
out, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(out))
}Three books with two fields of 100 ms each make six calls, which run at the same time. Running the program prints:
took about 100ms
{
"data": {
"books": [
{
"inStock": true,
"rating": 4.5,
"title": "A Wizard of Earthsea"
},
{
"inStock": false,
"rating": 4.2,
"title": "The Tombs of Atuan"
},
{
"inStock": true,
"rating": 4.4,
"title": "The Farthest Shore"
}
]
}
}