/
server.go
83 lines (72 loc) · 1.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
package server
import (
"github.com/BlockPILabs/aggregator/config"
"github.com/BlockPILabs/aggregator/log"
"github.com/BlockPILabs/aggregator/middleware"
"github.com/BlockPILabs/aggregator/notify"
"github.com/BlockPILabs/aggregator/rpc"
"github.com/valyala/fasthttp"
)
var (
logger = log.Module("server")
)
var requestHandler = func(ctx *fasthttp.RequestCtx) {
defer func() {
if err := recover(); err != nil {
logger.Error("error", "msg", err)
}
}()
var err error
session := &rpc.Session{RequestCtx: ctx}
err = session.Init()
if err != nil {
ctx.Error(string(session.NewJsonRpcError(err).Marshal()), fasthttp.StatusOK)
return
}
for {
session.Tries++
err = middleware.OnRequest(session)
if err != nil {
if session.IsMaxRetriesExceeded() {
ctx.Error(string(session.NewJsonRpcError(err).Marshal()), fasthttp.StatusOK)
return
}
continue
}
err = middleware.OnProcess(session)
if err != nil {
if session.IsMaxRetriesExceeded() {
ctx.Error(string(session.NewJsonRpcError(err).Marshal()), fasthttp.StatusOK)
return
}
continue
}
err = middleware.OnResponse(session)
if err != nil {
if session.IsMaxRetriesExceeded() {
ctx.Error(string(session.NewJsonRpcError(err).Marshal()), fasthttp.StatusOK)
return
}
continue
}
return
}
}
func NewServer() error {
var err error
addr := ":8011"
logger.Info("Starting proxy server", "addr", addr)
for _, chain := range config.Chains() {
logger.Info("Registered RPC", "endpoint", "http://localhost:8011/"+chain)
}
s := &fasthttp.Server{
Handler: fasthttp.CompressHandlerLevel(requestHandler, 6),
MaxRequestBodySize: fasthttp.DefaultMaxRequestBodySize * 10,
}
err = s.ListenAndServe(addr)
if err != nil {
notify.SendError("Error start aggregator server.", err.Error())
return err
}
return nil
}