-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
281 lines (234 loc) · 5.97 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
)
type Feed struct {
ID string `graphql:"id"`
}
var FeedType = graphql.NewObject(graphql.ObjectConfig{
Name: "FeedType",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.ID,
},
},
})
var RootSubscription = graphql.NewObject(graphql.ObjectConfig{
Name: "RootSubscription",
Fields: graphql.Fields{
"feed": &graphql.Field{
Type: FeedType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Source, nil
},
Subscribe: func(p graphql.ResolveParams) (interface{}, error) {
c := make(chan interface{})
go func() {
var i int
for {
i++
feed := Feed{ID: fmt.Sprintf("%d", i)}
select {
case <-p.Context.Done():
log.Println("[RootSubscription] [Subscribe] subscription canceled")
close(c)
return
default:
c <- feed
}
time.Sleep(250 * time.Millisecond)
if i == 21 {
close(c)
return
}
}
}()
return c, nil
},
},
},
})
var RootQuery = graphql.NewObject(graphql.ObjectConfig{
Name: "RootQuery",
Fields: graphql.Fields{
"ping": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "ok", nil
},
},
},
})
var schema graphql.Schema
func main() {
schemaConfig := graphql.SchemaConfig{
Query: RootQuery,
Subscription: RootSubscription,
}
s, err := graphql.NewSchema(schemaConfig)
if err != nil {
log.Fatal(err)
}
schema = s
h := handler.New(&handler.Config{
Schema: &s,
Pretty: true,
GraphiQL: false,
Playground: true,
})
http.Handle("/graphql", h)
http.HandleFunc("/subscriptions", SubscriptionsHandler)
log.Println("GraphQL Server running on [POST]: localhost:8081/graphql")
log.Println("GraphQL Playground running on [GET]: localhost:8081/graphql")
log.Fatal(http.ListenAndServe(":8081", nil))
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
Subprotocols: []string{"graphql-ws"},
}
type ConnectionACKMessage struct {
OperationID string `json:"id,omitempty"`
Type string `json:"type"`
Payload struct {
Query string `json:"query"`
} `json:"payload,omitempty"`
}
func SubscriptionsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("failed to do websocket upgrade: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
connectionACK, err := json.Marshal(map[string]string{
"type": "connection_ack",
})
if err != nil {
log.Printf("failed to marshal ws connection ack: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if err := conn.WriteMessage(websocket.TextMessage, connectionACK); err != nil {
log.Printf("failed to write to ws connection: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
go handleSubscription(conn)
}
func handleSubscription(conn *websocket.Conn) {
var subscriber *Subscriber
subscriptionCtx, subscriptionCancelFn := context.WithCancel(context.Background())
handleClosedConnection := func() {
log.Println("[SubscriptionsHandler] subscriber closed connection")
unsubscribe(subscriptionCancelFn, subscriber)
return
}
for {
_, p, err := conn.ReadMessage()
if err != nil {
log.Printf("failed to read websocket message: %v", err)
return
}
var msg ConnectionACKMessage
if err := json.Unmarshal(p, &msg); err != nil {
log.Printf("failed to unmarshal websocket message: %v", err)
continue
}
if msg.Type == "stop" {
handleClosedConnection()
return
}
if msg.Type == "start" {
subscriber = subscribe(subscriptionCtx, subscriptionCancelFn, conn, msg)
}
}
}
type Subscriber struct {
UUID string
Conn *websocket.Conn
RequestString string
OperationID string
}
var subscribers sync.Map
func subscribersSize() uint64 {
var size uint64
subscribers.Range(func(_, _ interface{}) bool {
size++
return true
})
return size
}
func unsubscribe(subscriptionCancelFn context.CancelFunc, subscriber *Subscriber) {
subscriptionCancelFn()
if subscriber != nil {
subscriber.Conn.Close()
subscribers.Delete(subscriber.UUID)
}
log.Printf("[SubscriptionsHandler] subscribers size: %+v", subscribersSize())
}
func subscribe(ctx context.Context, subscriptionCancelFn context.CancelFunc, conn *websocket.Conn, msg ConnectionACKMessage) *Subscriber {
subscriber := &Subscriber{
UUID: uuid.New().String(),
Conn: conn,
RequestString: msg.Payload.Query,
OperationID: msg.OperationID,
}
subscribers.Store(subscriber.UUID, &subscriber)
log.Printf("[SubscriptionsHandler] subscribers size: %+v", subscribersSize())
sendMessage := func(r *graphql.Result) error {
message, err := json.Marshal(map[string]interface{}{
"type": "data",
"id": subscriber.OperationID,
"payload": r.Data,
})
if err != nil {
return err
}
if err := subscriber.Conn.WriteMessage(websocket.TextMessage, message); err != nil {
return err
}
return nil
}
go func() {
subscribeParams := graphql.Params{
Context: ctx,
RequestString: msg.Payload.Query,
Schema: schema,
}
subscribeChannel := graphql.Subscribe(subscribeParams)
for {
select {
case <-ctx.Done():
log.Printf("[SubscriptionsHandler] subscription ctx done")
return
case r, isOpen := <-subscribeChannel:
if !isOpen {
log.Printf("[SubscriptionsHandler] subscription channel closed")
unsubscribe(subscriptionCancelFn, subscriber)
return
}
if err := sendMessage(r); err != nil {
if err == websocket.ErrCloseSent {
unsubscribe(subscriptionCancelFn, subscriber)
}
log.Printf("failed to send message: %v", err)
}
}
}
}()
return subscriber
}