-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
206 lines (173 loc) · 5.09 KB
/
main.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
// Copyright 2020 Coinbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/xyephy/rosetta-whive/configuration"
"github.com/xyephy/rosetta-whive/whive"
"github.com/xyephy/rosetta-whive/indexer"
"github.com/xyephy/rosetta-whive/services"
"github.com/xyephy/rosetta-whive/utils"
"github.com/coinbase/rosetta-sdk-go/asserter"
"github.com/coinbase/rosetta-sdk-go/server"
"github.com/coinbase/rosetta-sdk-go/types"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
const (
// readTimeout is the maximum duration for reading the entire
// request, including the body.
readTimeout = 5 * time.Second
// writeTimeout is the maximum duration before timing out
// writes of the response. It is reset whenever a new
// request's header is read.
writeTimeout = 15 * time.Second
// idleTimeout is the maximum amount of time to wait for the
// next request when keep-alives are enabled.
idleTimeout = 30 * time.Second
)
var (
signalReceived = false
)
// handleSignals handles OS signals so we can ensure we close database
// correctly. We call multiple sigListeners because we
// may need to cancel more than 1 context.
func handleSignals(ctx context.Context, listeners []context.CancelFunc) {
logger := utils.ExtractLogger(ctx, "signal handler")
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
logger.Warnw("received signal", "signal", sig)
signalReceived = true
for _, listener := range listeners {
listener()
}
}()
}
func startOnlineDependencies(
ctx context.Context,
cancel context.CancelFunc,
cfg *configuration.Configuration,
g *errgroup.Group,
) (*whive.Client, *indexer.Indexer, error) {
client := whive.NewClient(
whive.LocalhostURL(cfg.RPCPort),
cfg.GenesisBlockIdentifier,
cfg.Currency,
)
g.Go(func() error {
return whive.StartBitcoind(ctx, cfg.ConfigPath, g)
})
i, err := indexer.Initialize(
ctx,
cancel,
cfg,
client,
)
if err != nil {
return nil, nil, fmt.Errorf("%w: unable to initialize indexer", err)
}
g.Go(func() error {
return i.Sync(ctx)
})
g.Go(func() error {
return i.Prune(ctx)
})
return client, i, nil
}
func main() {
loggerRaw, err := zap.NewDevelopment()
if err != nil {
log.Fatalf("can't initialize zap logger: %v", err)
}
defer func() {
_ = loggerRaw.Sync()
}()
ctx := context.Background()
ctx = ctxzap.ToContext(ctx, loggerRaw)
ctx, cancel := context.WithCancel(ctx)
go handleSignals(ctx, []context.CancelFunc{cancel})
logger := loggerRaw.Sugar().Named("main")
cfg, err := configuration.LoadConfiguration(configuration.DataDirectory)
if err != nil {
logger.Fatalw("unable to load configuration", "error", err)
}
logger.Infow("loaded configuration", "configuration", types.PrintStruct(cfg))
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
return utils.MonitorMemoryUsage(ctx, -1)
})
var i *indexer.Indexer
var client *whive.Client
if cfg.Mode == configuration.Online {
client, i, err = startOnlineDependencies(ctx, cancel, cfg, g)
if err != nil {
logger.Fatalw("unable to start online dependencies", "error", err)
}
}
// The asserter automatically rejects incorrectly formatted
// requests.
asserter, err := asserter.NewServer(
whive.OperationTypes,
services.HistoricalBalanceLookup,
[]*types.NetworkIdentifier{cfg.Network},
nil,
services.MempoolCoins,
)
if err != nil {
logger.Fatalw("unable to create new server asserter", "error", err)
}
router := services.NewBlockchainRouter(cfg, client, i, asserter)
loggedRouter := services.LoggerMiddleware(loggerRaw, router)
corsRouter := server.CorsMiddleware(loggedRouter)
server := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
Handler: corsRouter,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
}
g.Go(func() error {
logger.Infow("server listening", "port", cfg.Port)
return server.ListenAndServe()
})
g.Go(func() error {
// If we don't shutdown server in errgroup, it will
// never stop because server.ListenAndServe doesn't
// take any context.
<-ctx.Done()
return server.Shutdown(ctx)
})
err = g.Wait()
// We always want to attempt to close the database, regardless of the error.
// We also want to do this after all indexer goroutines have stopped.
if i != nil {
i.CloseDatabase(ctx)
}
if signalReceived {
logger.Fatalw("rosetta-whive halted")
}
if err != nil {
logger.Fatalw("rosetta-whive sync failed", "error", err)
}
}