-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
232 lines (206 loc) · 6.11 KB
/
http.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
package server
import (
"context"
"fmt"
"github.com/bufbuild/connect-go"
"github.com/google/uuid"
"github.com/google/wire"
"github.com/pkg/errors"
phttp "github.com/protoflow-labs/protoflow/gen/http"
nhttp "github.com/protoflow-labs/protoflow/pkg/graph/node/http"
"github.com/protoflow-labs/protoflow/pkg/util/rx"
"github.com/protoflow-labs/protoflow/studio/dist/site"
"github.com/rs/zerolog/log"
"io"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"github.com/protoflow-labs/protoflow/gen/genconnect"
grpcreflect "github.com/bufbuild/connect-grpcreflect-go"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
)
type HTTPServer struct {
config Config
mux *http.ServeMux
}
var ProviderSet = wire.NewSet(
NewConfig,
NewHTTPServer,
)
func NewLogInterceptor() connect.UnaryInterceptorFunc {
interceptor := func(next connect.UnaryFunc) connect.UnaryFunc {
return func(
ctx context.Context,
req connect.AnyRequest,
) (connect.AnyResponse, error) {
resp, err := next(ctx, req)
if err != nil {
log.Error().Msgf("connect error: %+v\n", err)
}
return resp, err
}
}
return interceptor
}
func ParseHttpRequest(r *http.Request) (*phttp.Request, error) {
var req phttp.Request
h := make([]*phttp.Header, 0)
for name, headers := range r.Header {
for _, hValue := range headers {
h = append(h, &phttp.Header{Name: name, Value: hValue})
}
}
req.Id = uuid.NewString()
req.Method = r.Method
req.Url = r.URL.String()
req.Headers = h
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, errors.Wrapf(err, "error reading request body")
}
req.Body = body
return &req, nil
}
func NewHTTPServer(
config Config,
projectService genconnect.ProjectServiceHandler,
generateService genconnect.GenerateServiceHandler,
) (*HTTPServer, error) {
apiMux := http.NewServeMux()
interceptors := connect.WithInterceptors(NewLogInterceptor())
// The generated constructors return a path and a plain net/http
// handler.
apiMux.Handle(genconnect.NewProjectServiceHandler(projectService, interceptors))
apiMux.Handle(genconnect.NewGenerateServiceHandler(generateService, interceptors))
recoverCall := func(_ context.Context, spec connect.Spec, _ http.Header, p any) error {
log.Error().Msgf("%+v\n", p)
if err, ok := p.(error); ok {
return err
}
return fmt.Errorf("panic: %v", p)
}
reflector := grpcreflect.NewStaticReflector(
"project.ProjectService",
"generate.GenerateService",
// protoc-gen-connect-go generates package-level constants
// for these fully-qualified protobuf service names, so you'd more likely
// reference userv1.UserServiceName and groupv1.GroupServiceName.
)
apiMux.Handle(grpcreflect.NewHandlerV1(reflector, connect.WithRecover(recoverCall)))
// Many tools still expect the older version of the server reflection Server, so
// most servers should mount both handlers.
apiMux.Handle(grpcreflect.NewHandlerV1Alpha(reflector, connect.WithRecover(recoverCall)))
assets := site.Assets
fs := http.FS(site.Assets)
httpFileServer := http.FileServer(fs)
// TODO breadchris break this up into a separate function
u, err := url.Parse(config.StudioProxy)
if err != nil {
return nil, err
}
proxy := httputil.NewSingleHostReverseProxy(u)
httpStream := nhttp.NewHTTPEventStream()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Debug().Msgf("request: %s", r.URL.Path)
if r.URL.Path == "/" {
// redirect to /studio
http.Redirect(w, r, "/studio", http.StatusFound)
return
}
if r.URL.Path == "/ui" || strings.HasPrefix(r.URL.Path, "/ui/") {
req, err := ParseHttpRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Debug().Interface("request", req).Msg("ui request")
httpStream.Requests <- rx.NewItem(req)
i, err := httpStream.ResponseObs.Filter(func(item any) bool {
r, ok := item.(*phttp.Response)
if !ok {
return false
}
return r.Id == req.Id
}).First().Get()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
resp, ok := i.V.(*phttp.Response)
if !ok {
http.Error(w, "failed casting response", http.StatusInternalServerError)
return
}
for _, h := range resp.Headers {
w.Header().Set(h.Name, h.Value)
}
_, err = w.Write(resp.Body)
if err != nil {
http.Error(w, "failed writing body", http.StatusInternalServerError)
return
}
return
}
// If the path is '/studio', forward the request to the other mux handlers
if r.URL.Path == "/studio" || strings.HasPrefix(r.URL.Path, "/studio/") || r.URL.Path == "/esbuild" {
r.URL.Path = strings.Replace(r.URL.Path, "/studio", "", 1)
if config.StudioProxy != "" {
log.Debug().Msgf("proxying request: %s", r.URL.Path)
proxy.ServeHTTP(w, r)
} else {
filePath := r.URL.Path
if strings.Index(r.URL.Path, "/") == 0 {
filePath = r.URL.Path[1:]
}
f, err := assets.Open(filePath)
if os.IsNotExist(err) {
r.URL.Path = "/"
}
if err == nil {
f.Close()
}
log.Debug().Msgf("serving file: %s", filePath)
httpFileServer.ServeHTTP(w, r)
}
return
}
if strings.HasPrefix(r.URL.Path, "/api/") {
r.URL.Path = strings.Replace(r.URL.Path, "/api", "", 1)
}
apiMux.ServeHTTP(w, r)
return
})
return &HTTPServer{
config: config,
mux: mux,
}, nil
}
func (h *HTTPServer) Start(port int) error {
setPort := h.config.Port
if port != 0 {
setPort = port
}
log.Debug().
Int("port", setPort).
Msg("starting http server")
return http.ListenAndServe(
fmt.Sprintf(":%d", setPort),
h2c.NewHandler(corsMiddleware(h.mux), &http2.Server{}),
)
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Authorization, connect-protocol-version")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}