-
Notifications
You must be signed in to change notification settings - Fork 3
/
faucet.go
160 lines (128 loc) · 3.65 KB
/
faucet.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
package faucet
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"time"
"github.com/gnolang/faucet/client"
"github.com/gnolang/faucet/config"
"github.com/gnolang/faucet/estimate"
"github.com/gnolang/faucet/keyring"
"github.com/gnolang/faucet/keyring/memory"
"github.com/gnolang/gno/tm2/pkg/std"
"github.com/go-chi/chi/v5"
"github.com/rs/cors"
"golang.org/x/sync/errgroup"
)
// Faucet is a standard Gno faucet
type Faucet struct {
estimator estimate.Estimator // gas pricing estimations
logger *slog.Logger // log feedback
client client.Client // TM2 client
keyring keyring.Keyring // the faucet keyring
mux *chi.Mux // HTTP routing
config *config.Config // faucet configuration
middlewares []Middleware // request middlewares
handlers []Handler // request handlers
prepareTxMsgFn PrepareTxMessageFn // transaction message creator
maxSendAmount std.Coins // the max send amount per drip
}
var noopLogger = slog.New(slog.NewTextHandler(io.Discard, nil))
// NewFaucet creates a new instance of the Gno faucet server
func NewFaucet(
estimator estimate.Estimator,
client client.Client,
opts ...Option,
) (*Faucet, error) {
f := &Faucet{
estimator: estimator,
client: client,
logger: noopLogger,
config: config.DefaultConfig(),
prepareTxMsgFn: defaultPrepareTxMessage,
middlewares: nil, // no middlewares by default
mux: chi.NewMux(),
}
// Set the single default HTTP handler
f.handlers = []Handler{
{
f.defaultHTTPHandler,
"/",
},
}
// Apply the options
for _, opt := range opts {
opt(f)
}
// Validate the configuration
if err := config.ValidateConfig(f.config); err != nil {
return nil, fmt.Errorf("invalid configuration, %w", err)
}
// Set the send amount
//nolint:errcheck // MaxSendAmount is validated beforehand
f.maxSendAmount, _ = std.ParseCoins(f.config.MaxSendAmount)
// Generate the in-memory keyring
f.keyring = memory.New(f.config.Mnemonic, f.config.NumAccounts)
// Set up the CORS middleware
if f.config.CORSConfig != nil {
corsMiddleware := cors.New(cors.Options{
AllowedOrigins: f.config.CORSConfig.AllowedOrigins,
AllowedMethods: f.config.CORSConfig.AllowedMethods,
AllowedHeaders: f.config.CORSConfig.AllowedHeaders,
})
f.mux.Use(corsMiddleware.Handler)
}
// Register the health check handler
f.mux.Get("/health", f.healthcheckHandler)
// Branch off another route group, so they don't influence
// "standard" routes like health
f.mux.Group(func(r chi.Router) {
// Apply user middlewares
for _, middleware := range f.middlewares {
r.Use(middleware)
}
// Apply standard and custom route handlers
for _, handler := range f.handlers {
r.Post(handler.Pattern, handler.HandlerFunc)
}
})
return f, nil
}
// Serve serves the Gno faucet [BLOCKING]
func (f *Faucet) Serve(ctx context.Context) error {
faucet := &http.Server{
Addr: f.config.ListenAddress,
Handler: f.mux,
ReadHeaderTimeout: 60 * time.Second,
}
group, gCtx := errgroup.WithContext(ctx)
group.Go(func() error {
defer f.logger.Info("faucet shut down")
ln, err := net.Listen("tcp", faucet.Addr)
if err != nil {
return err
}
f.logger.Info(
fmt.Sprintf(
"faucet started at %s",
ln.Addr().String(),
),
)
if err := faucet.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
})
group.Go(func() error {
<-gCtx.Done()
f.logger.Info("faucet to be shutdown")
wsCtx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
return faucet.Shutdown(wsCtx)
})
return group.Wait()
}