-
Notifications
You must be signed in to change notification settings - Fork 19
/
server.go
164 lines (135 loc) · 4.39 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
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package nullchain
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strconv"
"time"
"code.vegaprotocol.io/vega/logging"
)
var ErrInvalidRequest = errors.New("invalid request")
const (
NullChainStatusReady = "chain-ready"
NullChainStatusReplaying = "chain-replaying"
)
func (n *NullBlockchain) Stop() error {
if n.replayer != nil {
if err := n.replayer.Stop(); err != nil {
n.log.Error("failed to stop nullchain replayer")
}
}
if n.srv == nil {
return nil
}
n.log.Info("Stopping nullchain server")
if err := n.srv.Shutdown(context.Background()); err != nil {
n.log.Error("failed to shutdown")
}
return nil
}
func (n *NullBlockchain) Start() error {
// the nullblockchain needs to start after the grpc API have started, so we pretend to start here
return nil
}
func (n *NullBlockchain) StartServer() error {
n.srv = &http.Server{Addr: net.JoinHostPort(n.cfg.IP, strconv.Itoa(n.cfg.Port))}
http.HandleFunc("/api/v1/forwardtime", n.handleForwardTime)
http.HandleFunc("/api/v1/status", n.status)
n.log.Info("starting time-forwarding server", logging.String("addr", n.srv.Addr))
go n.srv.ListenAndServe()
n.log.Info("starting blockchain")
if err := n.StartChain(); err != nil {
return err
}
return nil
}
// RequestToDuration should receive either be a parsable duration or a RFC3339 datetime.
func RequestToDuration(req string, now time.Time) (time.Duration, error) {
d, err := time.ParseDuration(req)
if err != nil {
newTime, err := time.Parse(time.RFC3339, req)
if err != nil {
return 0, fmt.Errorf("%w: time is not a duration or RFC3339 datetime", ErrInvalidRequest)
}
// Convert to a duration by subtracting the current frozen time of the nullchain
d = newTime.Sub(now)
}
if d < 0 {
return 0, fmt.Errorf("%w: cannot step backwards in time", ErrInvalidRequest)
}
return d, nil
}
// handleForwardTime processes the incoming request to shuffle forward in time converting it into a valid
// duration from `now` and pushing it into the nullchain to do its thing.
func (n *NullBlockchain) handleForwardTime(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "unexpected request body", http.StatusBadRequest)
return
}
req := struct {
Forward string `json:"forward"`
}{}
if err := json.Unmarshal(body, &req); err != nil {
http.Error(w, "unexpected request body", http.StatusBadRequest)
return
}
d, err := RequestToDuration(req.Forward, n.now)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
if n.replaying.Load() {
http.Error(w, ErrChainReplaying.Error(), http.StatusServiceUnavailable)
}
// we need to call ForwardTime in a different routine so that if it panics it stops the node instead of just being
// caught in the http-handler recover. But awkwardly it seems like the vega-sim relies on the http-request not
// returning until the time-forward has finished, so we need to preserve that for now.
done := make(chan struct{})
go func() {
n.ForwardTime(d)
done <- struct{}{}
}()
<-done
}
// status returns the status of the nullchain, whether it is replaying or whether its ready to go.
func (n *NullBlockchain) status(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
resp := struct {
Status string `json:"status"`
}{
Status: NullChainStatusReady,
}
if n.replaying.Load() {
resp.Status = NullChainStatusReplaying
}
buf, err := json.Marshal(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write(buf)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}