forked from MystenLabs/sui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
190 lines (164 loc) · 5.15 KB
/
main.rs
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
// Copyright (c) 2022, Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use axum::{
error_handling::HandleErrorLayer,
http::StatusCode,
response::IntoResponse,
routing::{get, post},
BoxError, Extension, Json, Router,
};
use clap::Parser;
use http::Method;
use std::env;
use std::{
borrow::Cow,
net::{IpAddr, Ipv4Addr, SocketAddr},
sync::Arc,
time::Duration,
};
use sui::client_commands::WalletContext;
use sui_config::{sui_config_dir, SUI_CLIENT_CONFIG};
use sui_faucet::{Faucet, FaucetRequest, FaucetResponse, SimpleFaucet};
use tower::ServiceBuilder;
use tower_http::cors::{Any, CorsLayer};
use tracing::{info, warn};
use uuid::Uuid;
const CONCURRENCY_LIMIT: usize = 30;
#[derive(Parser)]
#[clap(
name = "Sui Faucet",
about = "Faucet for requesting test tokens on Sui",
rename_all = "kebab-case"
)]
struct FaucetConfig {
#[clap(long, default_value_t = 5003)]
port: u16,
#[clap(long, default_value = "127.0.0.1")]
host_ip: Ipv4Addr,
#[clap(long, default_value_t = 50000)]
amount: u64,
#[clap(long, default_value_t = 5)]
num_coins: usize,
#[clap(long, default_value_t = 10)]
request_buffer_size: usize,
#[clap(long, default_value_t = 120)]
timeout_in_seconds: u64,
}
struct AppState<F = SimpleFaucet> {
faucet: F,
config: FaucetConfig,
// TODO: add counter
}
const PROM_PORT_ADDR: &str = "0.0.0.0:9184";
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
// initialize tracing
let _guard = telemetry_subscribers::TelemetryConfig::new(env!("CARGO_BIN_NAME"))
.with_env()
.init();
let max_concurrency = match env::var("MAX_CONCURRENCY") {
Ok(val) => val.parse::<usize>().unwrap(),
_ => CONCURRENCY_LIMIT,
};
info!("Max concurrency: {max_concurrency}.");
let context = create_wallet_context().await?;
let config: FaucetConfig = FaucetConfig::parse();
let FaucetConfig {
host_ip,
port,
request_buffer_size,
timeout_in_seconds,
..
} = config;
let prom_binding = PROM_PORT_ADDR.parse().unwrap();
info!("Starting Prometheus HTTP endpoint at {}", prom_binding);
let prometheus_registry = sui_node::metrics::start_prometheus_server(prom_binding);
let app_state = Arc::new(AppState {
faucet: SimpleFaucet::new(context, &prometheus_registry)
.await
.unwrap(),
config,
});
// TODO: restrict access if needed
let cors = CorsLayer::new()
.allow_methods(vec![Method::GET, Method::POST])
.allow_headers(Any)
.allow_origin(Any);
let app = Router::new()
.route("/", get(health))
.route("/gas", post(request_gas))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(handle_error))
.layer(cors)
.buffer(request_buffer_size)
.concurrency_limit(max_concurrency)
.timeout(Duration::from_secs(timeout_in_seconds))
.layer(Extension(app_state))
.into_inner(),
);
let addr = SocketAddr::new(IpAddr::V4(host_ip), port);
info!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await?;
Ok(())
}
/// basic handler that responds with a static string
async fn health() -> &'static str {
"OK"
}
/// handler for all the request_gas requests
async fn request_gas(
Json(payload): Json<FaucetRequest>,
Extension(state): Extension<Arc<AppState>>,
) -> impl IntoResponse {
// ID for traceability
let id = Uuid::new_v4();
info!(uuid = ?id, "Got new gas request.");
let result = match payload {
FaucetRequest::FixedAmountRequest(requests) => {
state
.faucet
.send(
id,
requests.recipient,
&vec![state.config.amount; state.config.num_coins],
)
.await
}
};
match result {
Ok(v) => {
info!(uuid =?id, "Request is successfully served");
(StatusCode::CREATED, Json(FaucetResponse::from(v)))
}
Err(v) => {
warn!(uuid =?id, "Failed to request gas: {:?}", v);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(FaucetResponse::from(v)),
)
}
}
}
async fn create_wallet_context() -> Result<WalletContext, anyhow::Error> {
let wallet_conf = sui_config_dir()?.join(SUI_CLIENT_CONFIG);
info!("Initialize wallet from config path: {:?}", wallet_conf);
WalletContext::new(&wallet_conf).await
}
async fn handle_error(error: BoxError) -> impl IntoResponse {
if error.is::<tower::timeout::error::Elapsed>() {
return (StatusCode::REQUEST_TIMEOUT, Cow::from("request timed out"));
}
if error.is::<tower::load_shed::error::Overloaded>() {
return (
StatusCode::SERVICE_UNAVAILABLE,
Cow::from("service is overloaded, try again later"),
);
}
(
StatusCode::INTERNAL_SERVER_ERROR,
Cow::from(format!("Unhandled internal error: {}", error)),
)
}