-
Notifications
You must be signed in to change notification settings - Fork 491
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support subscriptions #203
Merged
pavelnikolov
merged 4 commits into
graph-gophers:master
from
matiasanaya:feature/subscriptions
Oct 22, 2018
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
package gqltesting | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"encoding/json" | ||
"strconv" | ||
"testing" | ||
|
||
graphql "github.com/graph-gophers/graphql-go" | ||
"github.com/graph-gophers/graphql-go/errors" | ||
) | ||
|
||
// TestResponse models the expected response | ||
type TestResponse struct { | ||
Data json.RawMessage | ||
Errors []*errors.QueryError | ||
} | ||
|
||
// TestSubscription is a GraphQL test case to be used with RunSubscribe. | ||
type TestSubscription struct { | ||
Name string | ||
Schema *graphql.Schema | ||
Query string | ||
OperationName string | ||
Variables map[string]interface{} | ||
ExpectedResults []TestResponse | ||
ExpectedErr error | ||
} | ||
|
||
// RunSubscribes runs the given GraphQL subscription test cases as subtests. | ||
func RunSubscribes(t *testing.T, tests []*TestSubscription) { | ||
for i, test := range tests { | ||
if test.Name == "" { | ||
test.Name = strconv.Itoa(i + 1) | ||
} | ||
|
||
t.Run(test.Name, func(t *testing.T) { | ||
RunSubscribe(t, test) | ||
}) | ||
} | ||
} | ||
|
||
// RunSubscribe runs a single GraphQL subscription test case. | ||
func RunSubscribe(t *testing.T, test *TestSubscription) { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
defer cancel() | ||
|
||
c, err := test.Schema.Subscribe(ctx, test.Query, test.OperationName, test.Variables) | ||
if err != nil { | ||
if err.Error() != test.ExpectedErr.Error() { | ||
t.Fatalf("unexpected error: got %+v, want %+v", err, test.ExpectedErr) | ||
} | ||
|
||
return | ||
} | ||
|
||
var results []*graphql.Response | ||
for res := range c { | ||
results = append(results, res) | ||
} | ||
|
||
for i, expected := range test.ExpectedResults { | ||
res := results[i] | ||
|
||
checkErrorStrings(t, expected.Errors, res.Errors) | ||
|
||
resData, err := res.Data.MarshalJSON() | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
got, err := formatJSON(resData) | ||
if err != nil { | ||
t.Fatalf("got: invalid JSON: %s", err) | ||
} | ||
|
||
expectedData, err := expected.Data.MarshalJSON() | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
want, err := formatJSON(expectedData) | ||
if err != nil { | ||
t.Fatalf("got: invalid JSON: %s", err) | ||
} | ||
|
||
if !bytes.Equal(got, want) { | ||
t.Logf("got: %s", got) | ||
t.Logf("want: %s", want) | ||
t.Fail() | ||
} | ||
} | ||
} | ||
|
||
func checkErrorStrings(t *testing.T, expected, actual []*errors.QueryError) { | ||
expectedCount, actualCount := len(expected), len(actual) | ||
|
||
if expectedCount != actualCount { | ||
t.Fatalf("unexpected number of errors: want %d, got %d", expectedCount, actualCount) | ||
} | ||
|
||
if expectedCount > 0 { | ||
for i, want := range expected { | ||
got := actual[i] | ||
|
||
if got.Error() != want.Error() { | ||
t.Fatalf("unexpected error: got %+v, want %+v", got, want) | ||
} | ||
} | ||
|
||
// Return because we're done checking. | ||
return | ||
} | ||
|
||
for _, err := range actual { | ||
t.Errorf("unexpected error: '%s'", err) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
package exec | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"reflect" | ||
"time" | ||
|
||
"github.com/graph-gophers/graphql-go/errors" | ||
"github.com/graph-gophers/graphql-go/internal/exec/resolvable" | ||
"github.com/graph-gophers/graphql-go/internal/exec/selected" | ||
"github.com/graph-gophers/graphql-go/internal/query" | ||
) | ||
|
||
type Response struct { | ||
Data json.RawMessage | ||
Errors []*errors.QueryError | ||
} | ||
|
||
func (r *Request) Subscribe(ctx context.Context, s *resolvable.Schema, op *query.Operation) <-chan *Response { | ||
var result reflect.Value | ||
var f *fieldToExec | ||
var err *errors.QueryError | ||
func() { | ||
defer r.handlePanic(ctx) | ||
|
||
sels := selected.ApplyOperation(&r.Request, s, op) | ||
var fields []*fieldToExec | ||
collectFieldsToResolve(sels, s.Resolver, &fields, make(map[string]*fieldToExec)) | ||
|
||
// TODO: move this check into validation.Validate | ||
if len(fields) != 1 { | ||
err = errors.Errorf("%s", "can subscribe to at most one subscription at a time") | ||
return | ||
} | ||
f = fields[0] | ||
|
||
var in []reflect.Value | ||
if f.field.HasContext { | ||
in = append(in, reflect.ValueOf(ctx)) | ||
} | ||
if f.field.ArgsPacker != nil { | ||
in = append(in, f.field.PackedArgs) | ||
} | ||
callOut := f.resolver.Method(f.field.MethodIndex).Call(in) | ||
result = callOut[0] | ||
|
||
if f.field.HasError && !callOut[1].IsNil() { | ||
resolverErr := callOut[1].Interface().(error) | ||
err = errors.Errorf("%s", resolverErr) | ||
err.ResolverError = resolverErr | ||
} | ||
}() | ||
|
||
if err != nil { | ||
return sendAndReturnClosed(&Response{Errors: []*errors.QueryError{err}}) | ||
} | ||
|
||
if ctxErr := ctx.Err(); ctxErr != nil { | ||
return sendAndReturnClosed(&Response{Errors: []*errors.QueryError{errors.Errorf("%s", ctxErr)}}) | ||
} | ||
|
||
c := make(chan *Response) | ||
// TODO: handle resolver nil channel better? | ||
if result == reflect.Zero(result.Type()) { | ||
close(c) | ||
return c | ||
} | ||
|
||
go func() { | ||
for { | ||
// Check subscription context | ||
chosen, resp, ok := reflect.Select([]reflect.SelectCase{ | ||
{ | ||
Dir: reflect.SelectRecv, | ||
Chan: reflect.ValueOf(ctx.Done()), | ||
}, | ||
{ | ||
Dir: reflect.SelectRecv, | ||
Chan: result, | ||
}, | ||
}) | ||
switch chosen { | ||
// subscription context done | ||
case 0: | ||
close(c) | ||
return | ||
// upstream received | ||
case 1: | ||
// upstream closed | ||
if !ok { | ||
close(c) | ||
return | ||
} | ||
|
||
subR := &Request{ | ||
Request: selected.Request{ | ||
Doc: r.Request.Doc, | ||
Vars: r.Request.Vars, | ||
Schema: r.Request.Schema, | ||
}, | ||
Limiter: r.Limiter, | ||
Tracer: r.Tracer, | ||
Logger: r.Logger, | ||
} | ||
var out bytes.Buffer | ||
func() { | ||
// TODO: configurable timeout | ||
subCtx, cancel := context.WithTimeout(ctx, time.Second) | ||
defer cancel() | ||
|
||
// resolve response | ||
func() { | ||
defer subR.handlePanic(subCtx) | ||
|
||
out.WriteString(fmt.Sprintf(`{"%s":`, f.field.Alias)) | ||
subR.execSelectionSet(subCtx, f.sels, f.field.Type, &pathSegment{nil, f.field.Alias}, resp, &out) | ||
out.WriteString(`}`) | ||
}() | ||
|
||
if err := subCtx.Err(); err != nil { | ||
c <- &Response{Errors: []*errors.QueryError{errors.Errorf("%s", err)}} | ||
return | ||
} | ||
|
||
// Send response within timeout | ||
// TODO: maybe block until sent? | ||
select { | ||
case <-subCtx.Done(): | ||
case c <- &Response{Data: out.Bytes(), Errors: subR.Errs}: | ||
} | ||
}() | ||
} | ||
} | ||
}() | ||
|
||
return c | ||
} | ||
|
||
func sendAndReturnClosed(resp *Response) chan *Response { | ||
c := make(chan *Response, 1) | ||
c <- resp | ||
close(c) | ||
return c | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should you send a timeout error here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don't believe it would make sense to try and send a timeout error since we've time'd out waiting to send an actual response. But I do think maybe this should be checking against
ctx.Done()
instead. Thoughts?