Skip to content
Subscriptions

Subscriptions

A subscription is an operation that returns a stream of results instead of one: the client subscribes once and receives a result each time an event happens, such as a new book being added. This page shows how to define a subscription field, how to run it with graphql.Subscribe, and how to end it cleanly; the complete program is at the end.

Subscription fields

The fields of the schema’s Subscription type have two functions:

  • Subscribe returns the stream of events, as a chan interface{}. It is called once per subscription, with the arguments and the context of the request, and the root value as p.Source.
  • Resolve maps each event to the field’s value. It is called once per event, with the event as p.Source.
"bookAdded": &graphql.Field{
	Type: bookType,
	Args: graphql.FieldConfigArgument{
		"genre": &graphql.ArgumentConfig{Type: graphql.String},
	},
	// Subscribe returns the stream of events.
	Subscribe: func(p graphql.ResolveParams) (interface{}, error) {
		genre, _ := p.Args["genre"].(string)
		return broker.Subscribe(p.Context, genre), nil
	},
	// Resolve maps each event to the field's value.
	Resolve: func(p graphql.ResolveParams) (interface{}, error) {
		return p.Source, nil
	},
},
schema, err := graphql.NewSchema(graphql.SchemaConfig{
	Query:        queryType,
	Mutation:     mutationType,
	Subscription: subscriptionType,
})

Each event is executed as a query whose root value is the event: the subscription field and everything selected below it are resolved again for every event. Without a Resolve function, the default resolver reads the field’s name from the event, so either publish events shaped like the response, such as map[string]interface{}{"bookAdded": book}, or return p.Source from Resolve as above. This is the same contract as graphql-js.

Only a value of type chan interface{} is a stream. Any other value, including a typed channel such as chan *Book, is treated as a single event: the client gets one result and the stream ends (#151).

Running a subscription

graphql.Subscribe takes the same graphql.Params as graphql.Do and returns a channel of results:

ctx, cancel := context.WithCancel(context.Background())
results := graphql.Subscribe(graphql.Params{
	Schema:        schema,
	RequestString: `subscription { bookAdded(genre: "fantasy") { id title } }`,
	Context:       ctx,
})
for result := range results {
	// send result to the client
}

The channel is closed when the event channel is closed, when the context is done, or after a result that ends the subscription, such as an error. Each result has the shape of a graphql.Do result, so it encodes to JSON the same way.

graphql.ExecuteSubscription does the same for a document that is already parsed, like graphql.Execute, and likewise does not validate it.

graphql.Do and graphql.Execute do not run subscriptions: given a subscription operation, they call Resolve once with the root value and never call Subscribe.

Producing events

Events usually come from somewhere else in the program, such as a mutation, a message queue or a database listener. The complete program uses a small broker: Subscribe registers a buffered channel for the subscriber and unregisters it when the subscription’s context is done,

// Subscribe returns a channel that receives the published books of genre,
// or of every genre if genre is empty, until ctx is done.
func (b *Broker) Subscribe(ctx context.Context, genre string) chan interface{} {
	s := &subscriber{ch: make(chan interface{}, subscriberBuffer), genre: genre}
	b.mu.Lock()
	b.subs[s] = struct{}{}
	b.mu.Unlock()
	go func() {
		<-ctx.Done()
		b.mu.Lock()
		delete(b.subs, s)
		b.mu.Unlock()
	}()
	return s.ch
}

and the addBook mutation publishes the book it created:

// Publish sends book to the matching subscribers without blocking: a
// subscriber whose buffer is full misses the book.
func (b *Broker) Publish(book *Book) {
	b.mu.Lock()
	defer b.mu.Unlock()
	for s := range b.subs {
		if s.genre != "" && s.genre != book.Genre {
			continue
		}
		select {
		case s.ch <- book:
		default:
		}
	}
}

Events are executed one at a time, and the result channel is unbuffered: until the consumer reads a result, the next event is not read from the event channel. Cancellation is one more case in the executor’s select on the event channel, competing with incoming events: events that are waiting, or that arrive around the cancellation, can still be executed, and once the executor picks the cancellation it stops reading the event channel for good. A producer that sends with a plain ch <- event can therefore block on one slow or finished subscriber, and with it every other subscriber it serves. Publish never blocks: each subscriber has a buffer of 16 events, and a subscriber that falls further behind misses events. Other policies, such as ending the subscription of a client that falls behind, fit the same place.

Ending a subscription

Cancel the context to end a subscription. Once the context is done, the executor no longer waits for a reader to take a result: it stops sending, closes the result channel and returns, whether or not anything still reads it (v0.14.0). Two things qualify this:

  • Cancellation competes with incoming events in the executor’s select. While a reader is still reading, events that were already waiting can still be executed and delivered after the cancellation; once nothing reads, a result computed around the cancellation is dropped instead.
  • The executor waits for your Subscribe function to return before it can close the channel. A Subscribe function that blocks should watch p.Context and return when it is done.

Before v0.14.0, the executor sent each result without watching the context: if nothing read the channel after the context was done, the goroutine that executes the subscription could block forever on a result it had already computed. Code that has to support those versions keeps reading until the channel is closed:

cancel()
for range results {
}

Errors

ErrorResult
Syntax, validation or variable errorOne result with the error; the stream ends.
Subscribe returns an error, or nil, nilOne result with the error, without location or path (#149); the stream ends.
Subscribe panicsOne result with the error; the stream ends.
The field has no Subscribe functionthe subscription function "name" is not defined.
A field fails while executing an eventThat event’s result has the error, as in a query; the stream goes on.

The specification requires a subscription to select a single root field. Validation does not check it yet, so a document that selects two subscribes through one of them, chosen arbitrarily, and resolves both for every event (#150). Select one.

Extensions

The parse, validation and Init hooks of extensions do not run for subscriptions, and no hook wraps the Subscribe call. Every event is executed like a query, so ExecutionDidStart runs once per event and ResolveFieldDidStart once per resolved field of each event, and each result carries the value of every extension whose HasResult returns true.

Serving subscriptions

graphql.Subscribe produces the results; sending them to clients is up to the server. A WebSocket server speaking the graphql-transport-ws protocol, or an endpoint with server-sent events, reads the subscription from the client, calls graphql.Subscribe with a context that is cancelled when the client leaves, and writes each result. gql-go/handler serves queries and mutations over HTTP; support for these transports is planned in gql-go/handler#4.

Complete program

main.go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"runtime"
	"sync"
	"sync/atomic"

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

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

// subscriberBuffer is how many events a subscriber can fall behind before
// the broker drops events for it.
const subscriberBuffer = 16

type subscriber struct {
	ch    chan interface{}
	genre string
}

// Broker fans published books out to subscribers.
type Broker struct {
	mu   sync.Mutex
	subs map[*subscriber]struct{}
}

// NewBroker returns a broker without subscribers.
func NewBroker() *Broker {
	return &Broker{subs: map[*subscriber]struct{}{}}
}

// Subscribe returns a channel that receives the published books of genre,
// or of every genre if genre is empty, until ctx is done.
func (b *Broker) Subscribe(ctx context.Context, genre string) chan interface{} {
	s := &subscriber{ch: make(chan interface{}, subscriberBuffer), genre: genre}
	b.mu.Lock()
	b.subs[s] = struct{}{}
	b.mu.Unlock()
	go func() {
		<-ctx.Done()
		b.mu.Lock()
		delete(b.subs, s)
		b.mu.Unlock()
	}()
	return s.ch
}

// Publish sends book to the matching subscribers without blocking: a
// subscriber whose buffer is full misses the book.
func (b *Broker) Publish(book *Book) {
	b.mu.Lock()
	defer b.mu.Unlock()
	for s := range b.subs {
		if s.genre != "" && s.genre != book.Genre {
			continue
		}
		select {
		case s.ch <- book:
		default:
		}
	}
}

// Len returns the number of subscribers.
func (b *Broker) Len() int {
	b.mu.Lock()
	defer b.mu.Unlock()
	return len(b.subs)
}

func main() {
	broker := NewBroker()
	var lastID atomic.Int64

	bookType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Book",
		Fields: graphql.Fields{
			"id":    &graphql.Field{Type: graphql.ID},
			"title": &graphql.Field{Type: graphql.String},
			"genre": &graphql.Field{Type: graphql.String},
		},
	})
	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"ping": &graphql.Field{Type: graphql.String},
		},
	})
	mutationType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Mutation",
		Fields: graphql.Fields{
			"addBook": &graphql.Field{
				Type: bookType,
				Args: graphql.FieldConfigArgument{
					"title": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.String)},
					"genre": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.String)},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					book := &Book{
						ID:    fmt.Sprint(lastID.Add(1)),
						Title: p.Args["title"].(string),
						Genre: p.Args["genre"].(string),
					}
					broker.Publish(book)
					return book, nil
				},
			},
		},
	})
	subscriptionType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Subscription",
		Fields: graphql.Fields{
			"bookAdded": &graphql.Field{
				Type: bookType,
				Args: graphql.FieldConfigArgument{
					"genre": &graphql.ArgumentConfig{Type: graphql.String},
				},
				// Subscribe returns the stream of events.
				Subscribe: func(p graphql.ResolveParams) (interface{}, error) {
					genre, _ := p.Args["genre"].(string)
					return broker.Subscribe(p.Context, genre), nil
				},
				// Resolve maps each event to the field's value.
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return p.Source, nil
				},
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query:        queryType,
		Mutation:     mutationType,
		Subscription: subscriptionType,
	})
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithCancel(context.Background())
	results := graphql.Subscribe(graphql.Params{
		Schema:        schema,
		RequestString: `subscription { bookAdded(genre: "fantasy") { id title } }`,
		Context:       ctx,
	})

	// Wait until the subscription is registered, so that the output does
	// not depend on timing.
	for broker.Len() == 0 {
		runtime.Gosched()
	}

	go func() {
		for _, b := range [][2]string{
			{"A Wizard of Earthsea", "fantasy"},
			{"The Dispossessed", "science fiction"},
			{"The Tombs of Atuan", "fantasy"},
		} {
			graphql.Do(graphql.Params{
				Schema:         schema,
				RequestString:  `mutation ($t: String!, $g: String!) { addBook(title: $t, genre: $g) { id } }`,
				VariableValues: map[string]interface{}{"t": b[0], "g": b[1]},
				Context:        context.Background(),
			})
		}
	}()

	for i := 0; i < 2; i++ {
		out, _ := json.Marshal(<-results)
		fmt.Println(string(out))
	}

	// End the subscription, then read until the stream is closed.
	cancel()
	for range results {
	}
	for broker.Len() != 0 {
		runtime.Gosched()
	}
	fmt.Println("subscribers:", broker.Len())
}

The program subscribes to fantasy books, adds three books through the mutation, and prints the two results the subscription receives (the science fiction book is filtered out), then ends the subscription:

{"data":{"bookAdded":{"id":"1","title":"A Wizard of Earthsea"}}}
{"data":{"bookAdded":{"id":"3","title":"The Tombs of Atuan"}}}
subscribers: 0
Last updated on