Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
# Needed for the example-test to run.
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
go test -cover -v ./...
go test -race -cover -v ./...
lint:
name: Lint
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ lint:
internal/lint/golangci-lint run ./... --fix

check: lint
go test -cover ./...
go test -race -cover ./...
go mod tidy

.PHONY: example
2 changes: 1 addition & 1 deletion generate/operation.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func {{.Name}}ForwardData(interfaceChan interface{}, jsonRawMsg json.RawMessage)
if !ok {
return errors.New("failed to cast interface into 'chan {{.Name}}WsResponse'")
}
dataChan_ <- wsResp
graphql.SafeSend(dataChan_, wsResp)
return nil
}
{{end}}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions graphql/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -363,3 +363,10 @@ func (c *client) createGetRequest(req *Request) (*http.Request, error) {

return httpReq, nil
}

func SafeSend[T any](dataChan_ chan T, wsResp T) {
defer func() {
_ = recover()
}()
dataChan_ <- wsResp
}
25 changes: 20 additions & 5 deletions graphql/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,8 @@ func (s *subscriptionMap) Unsubscribe(subscriptionID string) error {
if !success {
return fmt.Errorf("tried to unsubscribe from unknown subscription with ID '%s'", subscriptionID)
}
hasBeenUnsubscribed := unsub.hasBeenUnsubscribed
unsub.hasBeenUnsubscribed = true
s.map_[subscriptionID] = unsub

if !hasBeenUnsubscribed {
reflect.ValueOf(s.map_[subscriptionID].interfaceChan).Close()
}
return nil
}

Expand All @@ -61,3 +56,23 @@ func (s *subscriptionMap) Delete(subscriptionID string) {
defer s.Unlock()
delete(s.map_, subscriptionID)
}

func (s *subscriptionMap) GetOrClose(subscriptionID string, subscriptionType string) (*subscription, error) {
s.Lock()
defer s.Unlock()
sub, success := s.map_[subscriptionID]
if !success {
return nil, fmt.Errorf("received message for unknown subscription ID '%s'", subscriptionID)
}
if sub.hasBeenUnsubscribed {
return nil, nil
}
if subscriptionType == webSocketTypeComplete {
sub.hasBeenUnsubscribed = true
s.map_[subscriptionID] = sub
reflect.ValueOf(sub.interfaceChan).Close()
return nil, nil
}

return &sub, nil
}
27 changes: 9 additions & 18 deletions graphql/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
"sync"
"sync/atomic"
"time"

"github.com/google/uuid"
Expand Down Expand Up @@ -51,7 +51,7 @@ type webSocketClient struct {
connParams map[string]interface{}
errChan chan error
subscriptions subscriptionMap
isClosing bool
isClosing atomic.Bool
sync.Mutex
}

Expand Down Expand Up @@ -107,14 +107,14 @@ func (w *webSocketClient) waitForConnAck() error {
func (w *webSocketClient) handleErr(err error) {
w.Lock()
defer w.Unlock()
if !w.isClosing {
if !w.isClosing.Load() {
w.errChan <- err
}
}

func (w *webSocketClient) listenWebSocket() {
for {
if w.isClosing {
if w.isClosing.Load() {
return
}
_, message, err := w.conn.ReadMessage()
Expand All @@ -139,22 +139,13 @@ func (w *webSocketClient) forwardWebSocketData(message []byte) error {
if wsMsg.ID == "" { // e.g. keep-alive messages
return nil
}
w.subscriptions.Lock()
defer w.subscriptions.Unlock()
sub, success := w.subscriptions.map_[wsMsg.ID]
if !success {
return fmt.Errorf("received message for unknown subscription ID '%s'", wsMsg.ID)
}
if sub.hasBeenUnsubscribed {
return nil
sub, err := w.subscriptions.GetOrClose(wsMsg.ID, wsMsg.Type)
if err != nil {
return err
}
if wsMsg.Type == webSocketTypeComplete {
sub.hasBeenUnsubscribed = true
w.subscriptions.map_[wsMsg.ID] = sub
reflect.ValueOf(sub.interfaceChan).Close()
if sub == nil {
return nil
}

return sub.forwardDataFunc(sub.interfaceChan, wsMsg.Payload)
}

Expand Down Expand Up @@ -208,7 +199,7 @@ func (w *webSocketClient) Close() error {
}
w.Lock()
defer w.Unlock()
w.isClosing = true
w.isClosing.Store(true)
close(w.errChan)
return w.conn.Close()
}
Expand Down
6 changes: 3 additions & 3 deletions internal/integration/generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions internal/integration/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,10 +252,6 @@ func TestSubscriptionClose(t *testing.T) {
_ = `# @genqlient
subscription countClose { countClose }`

ctx := context.Background()
server := server.RunServer()
defer server.Close()

cases := []struct {
name string
unsub bool
Expand All @@ -272,6 +268,12 @@ func TestSubscriptionClose(t *testing.T) {

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

server := server.RunServer()
defer server.Close()

wsClient := newRoundtripWebSocketClient(t, server.URL)

_, err := wsClient.Start(ctx)
Expand Down
22 changes: 13 additions & 9 deletions internal/integration/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,33 +157,37 @@ func (m mutationResolver) CreateUser(ctx context.Context, input NewUser) (*User,
return &newUser, nil
}

func (s *subscriptionResolver) Count(ctx context.Context) (<-chan int, error) {
func countTo(ctx context.Context, stopCount int) (<-chan int, error) {
respChan := make(chan int, 1)
go func(respChan chan int) {
defer close(respChan)
counter := 0
for {
if counter == 10 {
for counter := range stopCount {
select {
case <-ctx.Done():
return
default:
respChan <- counter
time.Sleep(100 * time.Millisecond)
}
respChan <- counter
counter++
time.Sleep(100 * time.Millisecond)
}
}(respChan)
return respChan, nil
}

func (s *subscriptionResolver) Count(ctx context.Context) (<-chan int, error) {
return countTo(ctx, 10)
}

func (s *subscriptionResolver) CountAuthorized(ctx context.Context) (<-chan int, error) {
if getAuthToken(ctx) != "authorized-user-token" {
return nil, fmt.Errorf("unauthorized")
}

return s.Count(ctx)
return countTo(ctx, 10)
}

func (s *subscriptionResolver) CountClose(ctx context.Context) (<-chan int, error) {
return s.Count(ctx)
return countTo(ctx, 1000)
}

const AuthKey = "authToken"
Expand Down
Loading