/
graphql_relay.go
180 lines (151 loc) · 4.26 KB
/
graphql_relay.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
package msg
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/graph-gophers/graphql-go"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// NOTE(jrubin) this file combines github.com/neelance/graphql-go/relay with the
// AnnotateContext func of github.com/grpc-ecosystem/grpc-gateway/runtime in
// order to proxy headers received via graphql to the APIClient grpc service
//
// github.com/grpc-ecosystem/grpc-gateway is licensed under BSD-3-Clause
// github.com/neelance/graphql-go/relay is licensed under BSD-2-Clause
type relay struct {
Schema *graphql.Schema
}
const (
metadataGrpcTimeout = "Grpc-Timeout"
xForwardedFor = "X-Forwarded-For"
xForwardedHost = "X-Forwarded-Host"
defaultContextTimeout = 0 * time.Second
)
func timeoutUnitToDuration(u uint8) (d time.Duration, ok bool) {
switch u {
case 'H':
return time.Hour, true
case 'M':
return time.Minute, true
case 'S':
return time.Second, true
case 'm':
return time.Millisecond, true
case 'u':
return time.Microsecond, true
case 'n':
return time.Nanosecond, true
default:
}
return
}
func timeoutDecode(s string) (time.Duration, error) {
size := len(s)
if size < 2 {
return 0, fmt.Errorf("timeout string is too short: %q", s)
}
d, ok := timeoutUnitToDuration(s[size-1])
if !ok {
return 0, fmt.Errorf("timeout unit is not recognized: %q", s)
}
t, err := strconv.ParseInt(s[:size-1], 10, 64)
if err != nil {
return 0, err
}
return d * time.Duration(t), nil
}
func annotateContext(req *http.Request) (context.Context, context.CancelFunc, error) {
var pairs []string
ctx := req.Context()
cancel := func() {}
timeout := defaultContextTimeout
if tm := req.Header.Get(metadataGrpcTimeout); tm != "" {
var err error
timeout, err = timeoutDecode(tm)
if err != nil {
return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm)
}
}
for key, vals := range req.Header {
for _, val := range vals {
pairs = append(pairs, key, val)
}
}
if host := req.Header.Get(xForwardedHost); host != "" {
pairs = append(pairs, strings.ToLower(xForwardedHost), host)
} else if req.Host != "" {
pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host)
}
if addr := req.RemoteAddr; addr != "" {
if remoteIP, _, err := net.SplitHostPort(addr); err == nil {
if fwd := req.Header.Get(xForwardedFor); fwd == "" {
pairs = append(pairs, strings.ToLower(xForwardedFor), remoteIP)
} else {
pairs = append(pairs, strings.ToLower(xForwardedFor), fmt.Sprintf("%s, %s", fwd, remoteIP))
}
}
}
if timeout != 0 {
ctx, cancel = context.WithTimeout(ctx, timeout)
}
if len(pairs) == 0 {
return ctx, cancel, nil
}
return metadata.NewOutgoingContext(ctx, metadata.Pairs(pairs...)), cancel, nil
}
type serverMetadataKey struct{}
type serverMetadata struct {
sync.Mutex
Header metadata.MD
}
func serverMetadataFromContext(ctx context.Context) *serverMetadata {
if md, ok := ctx.Value(serverMetadataKey{}).(*serverMetadata); ok {
return md
}
return &serverMetadata{}
}
func newServerMetadataContext(ctx context.Context, md *serverMetadata) context.Context {
return context.WithValue(ctx, serverMetadataKey{}, md)
}
func (h relay) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var params struct {
Query string `json:"query"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}
if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ctx, cancel, err := annotateContext(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer cancel()
var md serverMetadata
ctx = newServerMetadataContext(ctx, &md)
response := h.Schema.Exec(ctx, params.Query, params.OperationName, params.Variables)
responseJSON, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
md.Lock()
defer md.Unlock()
for k, vs := range md.Header {
for _, v := range vs {
w.Header().Add(k, v)
}
}
_, _ = w.Write(responseJSON) // #nosec
}