-
Notifications
You must be signed in to change notification settings - Fork 230
/
server.go
209 lines (182 loc) · 4.82 KB
/
server.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
package dash
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httputil"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/hasura/go-graphql-client"
"github.com/rs/zerolog/log"
"encr.dev/cli/daemon/apps"
"encr.dev/cli/daemon/dash/ai"
"encr.dev/cli/daemon/dash/apiproxy"
"encr.dev/cli/daemon/dash/dashproxy"
"encr.dev/cli/daemon/engine/trace2"
"encr.dev/cli/daemon/run"
"encr.dev/cli/internal/jsonrpc2"
"encr.dev/internal/conf"
"encr.dev/pkg/fns"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(*http.Request) bool { return true },
}
// NewServer starts a new server and returns it.
func NewServer(appsMgr *apps.Manager, runMgr *run.Manager, tr trace2.Store, dashPort int) *Server {
proxy, err := dashproxy.New(conf.DevDashURL)
if err != nil {
log.Fatal().Err(err).Msg("could not create dash proxy")
}
apiProxy, err := apiproxy.New(conf.APIBaseURL + "/graphql")
if err != nil {
log.Fatal().Err(err).Msg("could not create graphql proxy")
}
aiClient := graphql.NewSubscriptionClient(conf.WSBaseURL + "/graphql").
WithRetryTimeout(5 * time.Second).
WithRetryDelay(2 * time.Second).
WithRetryStatusCodes("500-599").
WithWebSocketOptions(
graphql.WebsocketOptions{
HTTPClient: conf.AuthClient,
}).WithSyncMode(true)
aiMgr := ai.NewAIManager(aiClient)
s := &Server{
proxy: proxy,
apiProxy: apiProxy,
apps: appsMgr,
run: runMgr,
tr: tr,
dashPort: dashPort,
traceCh: make(chan trace2.NewSpanEvent, 10),
clients: make(map[chan<- *notification]struct{}),
ai: aiMgr,
}
runMgr.AddListener(s)
tr.Listen(s.traceCh)
go s.listenTraces()
return s
}
// Server is the http.Handler for serving the developer dashboard.
type Server struct {
proxy *httputil.ReverseProxy
apiProxy *httputil.ReverseProxy
apps *apps.Manager
run *run.Manager
tr trace2.Store
dashPort int
traceCh chan trace2.NewSpanEvent
ai *ai.Manager
mu sync.Mutex
clients map[chan<- *notification]struct{}
}
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
switch req.URL.Path {
case "/__encore":
s.WebSocket(w, req)
case "/__graphql":
s.apiProxy.ServeHTTP(w, req)
default:
s.proxy.ServeHTTP(w, req)
}
}
// WebSocket serves the jsonrpc2 API over WebSocket.
func (s *Server) WebSocket(w http.ResponseWriter, req *http.Request) {
c, err := upgrader.Upgrade(w, req, nil)
if err != nil {
log.Error().Err(err).Msg("dash: could not upgrade websocket")
return
}
defer fns.CloseIgnore(c)
log.Info().Msg("dash: websocket connection established")
stream := &wsStream{c: c}
conn := jsonrpc2.NewConn(stream)
handler := &handler{rpc: conn, apps: s.apps, run: s.run, tr: s.tr, ai: s.ai}
conn.Go(req.Context(), handler.Handle)
ch := make(chan *notification, 20)
s.addClient(ch)
defer s.removeClient(ch)
// nosemgrep: tools.semgrep-rules.semgrep-go.http-request-go-context
go handler.listenNotify(req.Context(), ch)
<-conn.Done()
if err := conn.Err(); err != nil {
if ce, ok := err.(*websocket.CloseError); ok && ce.Code == websocket.CloseNormalClosure {
log.Info().Msg("dash: websocket closed")
} else {
log.Info().Err(err).Msg("dash: websocket closed with error")
}
}
}
func (s *Server) addClient(ch chan *notification) {
s.mu.Lock()
defer s.mu.Unlock()
s.clients[ch] = struct{}{}
}
func (s *Server) removeClient(ch chan *notification) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.clients, ch)
}
// hasClients reports whether there are any active clients.
func (s *Server) hasClients() bool {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.clients) > 0
}
type notification struct {
Method string
Params interface{}
}
// notify notifies any active clients.
func (s *Server) notify(n *notification) {
var clients []chan<- *notification
s.mu.Lock()
for c := range s.clients {
clients = append(clients, c)
}
s.mu.Unlock()
for _, c := range clients {
select {
case c <- n:
default:
}
}
}
// wsStream implements jsonrpc2.Stream over a websocket.
type wsStream struct {
writeMu sync.Mutex
c *websocket.Conn
}
func (s *wsStream) Close() error {
s.writeMu.Lock()
defer s.writeMu.Unlock()
return s.c.Close()
}
func (s *wsStream) Read(context.Context) (jsonrpc2.Message, int64, error) {
typ, data, err := s.c.ReadMessage()
if err != nil {
return nil, 0, err
}
if typ != websocket.TextMessage {
return nil, 0, fmt.Errorf("webedit.wsStream: got non-text message type %v", typ)
}
msg, err := jsonrpc2.DecodeMessage(data)
if err != nil {
return nil, 0, err
}
return msg, int64(len(data)), nil
}
func (s *wsStream) Write(ctx context.Context, msg jsonrpc2.Message) (int64, error) {
s.writeMu.Lock()
defer s.writeMu.Unlock()
data, err := json.Marshal(msg)
if err != nil {
return 0, err
}
err = s.c.WriteMessage(websocket.TextMessage, data)
if err != nil {
return 0, err
}
return int64(len(data)), nil
}