-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoint_handle_request.go
168 lines (143 loc) · 5.14 KB
/
endpoint_handle_request.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
package v2
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
vfmt "github.com/elysiumstation/fury/libs/fmt"
"github.com/elysiumstation/fury/libs/jsonrpc"
vgrand "github.com/elysiumstation/fury/libs/rand"
"github.com/elysiumstation/fury/logging"
"github.com/elysiumstation/fury/wallet/api"
"github.com/julienschmidt/httprouter"
"go.uber.org/zap"
)
func (a *API) HandleRequest(w http.ResponseWriter, httpRequest *http.Request, _ httprouter.Params) {
traceID := vgrand.RandomStr(64)
ctx := context.WithValue(httpRequest.Context(), jsonrpc.TraceIDKey, traceID)
a.log.Info("New request",
logging.String("url", vfmt.Escape(httpRequest.URL.String())),
logging.String("trace-id", traceID),
)
lw := newResponseWriter(w, traceID)
defer logResponse(a.log, lw)
rpcRequest, errDetails := a.unmarshallRequest(traceID, httpRequest)
if errDetails != nil {
lw.SetStatusCode(http.StatusBadRequest)
// Failing to unmarshall the request prevent us from retrieving the
// request ID. So, it's left empty.
lw.WriteJSONRPCResponse(jsonrpc.NewErrorResponse("", errDetails))
return
}
response := a.processJSONRPCRequest(ctx, traceID, lw, httpRequest, rpcRequest)
// If the request doesn't have an ID, it's a notification. Notifications do
// not send content back, even if an error occurred.
if rpcRequest.IsNotification() {
lw.SetStatusCode(http.StatusNoContent)
return
}
if response.Error == nil {
lw.SetStatusCode(http.StatusOK)
} else {
if response.Error.Code == api.ErrorCodeAuthenticationFailure {
lw.SetStatusCode(401)
} else if response.Error.IsInternalError() {
lw.SetStatusCode(http.StatusInternalServerError)
} else {
lw.SetStatusCode(http.StatusBadRequest)
}
}
lw.WriteJSONRPCResponse(response)
}
func (a *API) unmarshallRequest(traceID string, r *http.Request) (jsonrpc.Request, *jsonrpc.ErrorDetails) {
defer func() {
_ = r.Body.Close()
}()
body, err := io.ReadAll(r.Body)
if err != nil {
return jsonrpc.Request{}, jsonrpc.NewParseError(ErrCouldNotReadRequestBody)
}
if len(body) == 0 {
return jsonrpc.Request{}, jsonrpc.NewParseError(ErrRequestCannotBeBlank)
}
request := jsonrpc.Request{}
if err := json.Unmarshal(body, &request); err != nil {
a.log.Error("Request could not be parsed",
logging.String("trace-id", traceID),
logging.Error(err),
)
var syntaxError *json.SyntaxError
var unmarshallTypeError *json.UnmarshalTypeError
if errors.As(err, &syntaxError) || errors.As(err, &unmarshallTypeError) || errors.As(err, &unmarshallTypeError) {
return jsonrpc.Request{}, jsonrpc.NewParseError(err)
}
return jsonrpc.Request{}, jsonrpc.NewInvalidRequest(err)
}
strReq, _ := json.Marshal(&request)
a.log.Info("Request successfully parsed",
logging.String("request", vfmt.Escape(string(strReq))),
logging.String("trace-id", traceID),
)
return request, nil
}
func (a *API) processJSONRPCRequest(ctx context.Context, traceID string, lw *responseWriter, httpRequest *http.Request, rpcRequest jsonrpc.Request) *jsonrpc.Response {
if err := rpcRequest.Check(); err != nil {
a.log.Info("invalid RPC request",
zap.String("trace-id", traceID),
zap.Error(err))
return jsonrpc.NewErrorResponse(rpcRequest.ID, jsonrpc.NewInvalidRequest(err))
}
// We add this pre-check so users stop asking why they can't access the
// administrative endpoints.
if strings.HasPrefix(rpcRequest.Method, "admin.") {
a.log.Debug("attempt to call administrative endpoint rejected",
zap.String("trace-id", traceID),
zap.String("method", vfmt.Escape(rpcRequest.Method)))
return jsonrpc.NewErrorResponse(rpcRequest.ID, jsonrpc.NewUnsupportedMethod(ErrAdminEndpointsNotExposed))
}
command, ok := a.commands[rpcRequest.Method]
if !ok {
a.log.Debug("unknown RPC method",
zap.String("trace-id", traceID),
zap.String("method", vfmt.Escape(rpcRequest.Method)))
return jsonrpc.NewErrorResponse(rpcRequest.ID, jsonrpc.NewMethodNotFound(rpcRequest.Method))
}
result, errDetails := command(ctx, lw, httpRequest, rpcRequest)
if errDetails != nil {
a.log.Info("RPC request failed",
zap.String("trace-id", traceID),
zap.Error(errDetails))
return jsonrpc.NewErrorResponse(rpcRequest.ID, errDetails)
}
a.log.Info("RPC request succeeded",
zap.String("trace-id", traceID))
return jsonrpc.NewSuccessfulResponse(rpcRequest.ID, result)
}
func logResponse(logger *zap.Logger, lw *responseWriter) {
if lw.statusCode >= 400 && lw.statusCode <= 499 {
logger.Error("Client error",
logging.Int("http-status", lw.statusCode),
logging.String("response", string(lw.response)),
logging.String("request-id", vfmt.Escape(lw.requestID)),
logging.String("trace-id", lw.traceID),
)
return
}
if lw.statusCode >= 500 && lw.statusCode <= 599 {
logger.Error("Internal error",
logging.Int("http-status", lw.statusCode),
logging.Error(lw.internalError),
logging.String("request-id", vfmt.Escape(lw.requestID)),
logging.String("trace-id", lw.traceID),
)
return
}
logger.Info("Successful response",
logging.Int("http-status", lw.statusCode),
logging.String("response", string(lw.response)),
logging.String("request-id", vfmt.Escape(lw.requestID)),
logging.String("trace-id", lw.traceID),
)
}