-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathserver.rs
More file actions
344 lines (300 loc) · 11.9 KB
/
server.rs
File metadata and controls
344 lines (300 loc) · 11.9 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use crate::{
constant::{X_API_KEY, X_HMAC_SIGNATURE, X_TIMESTAMP},
metrics::run_metrics_server_if_required,
rpc_server::{
auth::{ApiKeyAuthLayer, HmacAuthLayer},
rpc::KoraRpc,
},
usage_limit::UsageTracker,
};
#[cfg(not(test))]
use crate::state::get_config;
#[cfg(test)]
use crate::tests::config_mock::mock_state::get_config;
use http::{header, Method};
use jsonrpsee::{
server::{middleware::proxy_get_request::ProxyGetRequestLayer, ServerBuilder, ServerHandle},
RpcModule,
};
use std::{net::SocketAddr, time::Duration};
use tokio::task::JoinHandle;
use tower::limit::RateLimitLayer;
use tower_http::cors::CorsLayer;
pub struct ServerHandles {
pub rpc_handle: ServerHandle,
pub metrics_handle: Option<ServerHandle>,
pub balance_tracker_handle: Option<JoinHandle<()>>,
}
// We'll always prioritize the environment variable over the config value
fn get_value_by_priority(env_var: &str, config_value: Option<String>) -> Option<String> {
std::env::var(env_var).ok().or(config_value)
}
pub async fn run_rpc_server(rpc: KoraRpc, port: u16) -> Result<ServerHandles, anyhow::Error> {
let addr = SocketAddr::from(([0, 0, 0, 0], port));
log::info!("RPC server started on {addr}, port {port}");
// Initialize usage limiter
if let Err(e) = UsageTracker::init_usage_limiter().await {
log::error!("Failed to initialize usage limiter: {e}");
return Err(anyhow::anyhow!("Usage limiter initialization failed: {e}"));
}
// Build middleware stack with tracing and CORS
let cors = CorsLayer::new()
.allow_origin(tower_http::cors::Any)
.allow_methods([Method::POST, Method::GET])
.allow_headers([
header::CONTENT_TYPE,
header::HeaderName::from_static(X_API_KEY),
header::HeaderName::from_static(X_HMAC_SIGNATURE),
header::HeaderName::from_static(X_TIMESTAMP),
])
.max_age(Duration::from_secs(3600));
let config = get_config()?;
// Get the RPC client from KoraRpc to pass to metrics initialization
let rpc_client = rpc.get_rpc_client().clone();
let (metrics_handle, metrics_layers, balance_tracker_handle) =
run_metrics_server_if_required(port, rpc_client).await?;
let middleware = tower::ServiceBuilder::new()
// Add metrics handler first (before other layers) so it can intercept /metrics
.layer(ProxyGetRequestLayer::new("/liveness", "liveness")?)
.layer(RateLimitLayer::new(config.kora.rate_limit, Duration::from_secs(1)))
// Add metrics handler layer for Prometheus metrics
.option_layer(
metrics_layers.as_ref().and_then(|layers| layers.metrics_handler_layer.clone()),
)
.layer(cors)
// Add metrics collection layer
.option_layer(metrics_layers.as_ref().and_then(|layers| layers.http_metrics_layer.clone()))
// Add authentication layer for API key if configured
.option_layer(
(get_value_by_priority("KORA_API_KEY", config.kora.auth.api_key.clone()))
.map(|key| ApiKeyAuthLayer::new(key.clone())),
)
// Add authentication layer for HMAC if configured
.option_layer(
(get_value_by_priority("KORA_HMAC_SECRET", config.kora.auth.hmac_secret.clone())).map(
|secret| HmacAuthLayer::new(secret.clone(), config.kora.auth.max_timestamp_age),
),
);
// Configure and build the server with HTTP support
let server = ServerBuilder::default()
.set_middleware(middleware)
.http_only() // Explicitly enable HTTP
.build(addr)
.await?;
let rpc_module = build_rpc_module(rpc)?;
// Start the RPC server
let rpc_handle = server
.start(rpc_module)
.map_err(|e| anyhow::anyhow!("Failed to start RPC server: {}", e))?;
Ok(ServerHandles { rpc_handle, metrics_handle, balance_tracker_handle })
}
macro_rules! register_method_if_enabled {
// For methods without parameters
($module:expr, $enabled_methods:expr, $field:ident, $method_name:expr, $rpc_method:ident) => {
if $enabled_methods.$field {
let _ = $module.register_async_method(
$method_name,
|_rpc_params, rpc_context| async move {
let rpc = rpc_context.as_ref();
rpc.$rpc_method().await.map_err(Into::into)
},
);
}
};
// For methods with parameters
($module:expr, $enabled_methods:expr, $field:ident, $method_name:expr, $rpc_method:ident, with_params) => {
if $enabled_methods.$field {
let _ =
$module.register_async_method($method_name, |rpc_params, rpc_context| async move {
let rpc = rpc_context.as_ref();
let params = rpc_params.parse()?;
rpc.$rpc_method(params).await.map_err(Into::into)
});
}
};
}
fn build_rpc_module(rpc: KoraRpc) -> Result<RpcModule<KoraRpc>, anyhow::Error> {
let mut module = RpcModule::new(rpc.clone());
let enabled_methods = &get_config()?.kora.enabled_methods;
register_method_if_enabled!(module, enabled_methods, liveness, "liveness", liveness);
register_method_if_enabled!(
module,
enabled_methods,
estimate_transaction_fee,
"estimateTransactionFee",
estimate_transaction_fee,
with_params
);
register_method_if_enabled!(
module,
enabled_methods,
get_supported_tokens,
"getSupportedTokens",
get_supported_tokens
);
register_method_if_enabled!(
module,
enabled_methods,
get_payer_signer,
"getPayerSigner",
get_payer_signer
);
register_method_if_enabled!(
module,
enabled_methods,
sign_transaction,
"signTransaction",
sign_transaction,
with_params
);
register_method_if_enabled!(
module,
enabled_methods,
sign_and_send_transaction,
"signAndSendTransaction",
sign_and_send_transaction,
with_params
);
register_method_if_enabled!(
module,
enabled_methods,
transfer_transaction,
"transferTransaction",
transfer_transaction,
with_params
);
register_method_if_enabled!(
module,
enabled_methods,
get_blockhash,
"getBlockhash",
get_blockhash
);
register_method_if_enabled!(module, enabled_methods, get_config, "getConfig", get_config);
register_method_if_enabled!(
module,
enabled_methods,
sign_transaction_if_paid,
"signTransactionIfPaid",
sign_transaction_if_paid,
with_params
);
Ok(module)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
config::EnabledMethods,
tests::{
common::setup_or_get_test_signer,
config_mock::{ConfigMockBuilder, KoraConfigBuilder},
rpc_mock::RpcMockBuilder,
},
};
use std::env;
#[test]
fn test_get_value_by_priority_env_var_takes_precedence() {
let env_var_name = "TEST_ENV_VAR_PRECEDENCE_UNIQUE";
env::set_var(env_var_name, "env_value");
let result = get_value_by_priority(env_var_name, Some("config_value".to_string()));
assert_eq!(result, Some("env_value".to_string()));
env::remove_var(env_var_name);
}
#[test]
fn test_get_value_by_priority_config_fallback() {
let env_var_name = "TEST_ENV_VAR_FALLBACK_UNIQUE_XYZ123";
let result = get_value_by_priority(env_var_name, Some("config_value".to_string()));
assert_eq!(result, Some("config_value".to_string()));
}
#[test]
fn test_get_value_by_priority_none_when_both_missing() {
let env_var_name = "TEST_ENV_VAR_MISSING_UNIQUE_ABC789";
let result = get_value_by_priority(env_var_name, None);
assert_eq!(result, None);
}
#[test]
fn test_build_rpc_module_all_methods_enabled() {
// Default is all methods enabled
let enabled_methods = EnabledMethods::default();
let kora_config = KoraConfigBuilder::new().with_enabled_methods(enabled_methods).build();
let _m = ConfigMockBuilder::new().with_kora(kora_config).build_and_setup();
let _ = setup_or_get_test_signer();
let rpc_client = RpcMockBuilder::new().build();
let kora_rpc = KoraRpc::new(rpc_client);
let result = build_rpc_module(kora_rpc);
assert!(result.is_ok(), "Failed to build RPC module with all methods enabled");
// Verify that the module has the expected methods
let module = result.unwrap();
let method_names: Vec<&str> = module.method_names().collect();
assert_eq!(method_names.len(), 10);
assert!(method_names.contains(&"liveness"));
assert!(method_names.contains(&"estimateTransactionFee"));
assert!(method_names.contains(&"getSupportedTokens"));
assert!(method_names.contains(&"getPayerSigner"));
assert!(method_names.contains(&"signTransaction"));
assert!(method_names.contains(&"signAndSendTransaction"));
assert!(method_names.contains(&"transferTransaction"));
assert!(method_names.contains(&"getBlockhash"));
assert!(method_names.contains(&"getConfig"));
assert!(method_names.contains(&"signTransactionIfPaid"));
}
#[test]
fn test_build_rpc_module_all_methods_disabled() {
// Setup config with all methods disabled
let enabled_methods = EnabledMethods {
estimate_transaction_fee: false,
get_supported_tokens: false,
get_payer_signer: false,
sign_transaction: false,
sign_and_send_transaction: false,
transfer_transaction: false,
get_blockhash: false,
get_config: false,
sign_transaction_if_paid: false,
liveness: false,
};
let kora_config = KoraConfigBuilder::new().with_enabled_methods(enabled_methods).build();
let _m = ConfigMockBuilder::new().with_kora(kora_config).build_and_setup();
let _ = setup_or_get_test_signer();
// Create RPC module
let rpc_client = RpcMockBuilder::new().build();
let kora_rpc = KoraRpc::new(rpc_client);
// Build the module - should succeed even with no methods
let result = build_rpc_module(kora_rpc);
assert!(result.is_ok(), "Failed to build RPC module with all methods disabled");
assert_eq!(result.unwrap().method_names().count(), 0);
}
#[test]
fn test_build_rpc_module_selective_methods() {
// Setup config with only some methods enabled
let enabled_methods = EnabledMethods {
liveness: true,
get_config: true,
get_supported_tokens: true,
estimate_transaction_fee: false,
get_payer_signer: false,
sign_transaction: false,
sign_and_send_transaction: false,
transfer_transaction: false,
get_blockhash: false,
sign_transaction_if_paid: false,
};
let kora_config = KoraConfigBuilder::new().with_enabled_methods(enabled_methods).build();
let _m = ConfigMockBuilder::new().with_kora(kora_config).build_and_setup();
let _ = setup_or_get_test_signer();
// Create RPC module
let rpc_client = RpcMockBuilder::new().build();
let kora_rpc = KoraRpc::new(rpc_client);
// Build the module
let result = build_rpc_module(kora_rpc);
assert!(result.is_ok(), "Failed to build RPC module with selective methods");
// Verify that only the expected methods are registered
let module = result.unwrap();
let method_names: Vec<&str> = module.method_names().collect();
assert_eq!(method_names.len(), 3);
assert!(method_names.contains(&"liveness"));
assert!(method_names.contains(&"getConfig"));
assert!(method_names.contains(&"getSupportedTokens"));
}
}