forked from StellarRouter/StellarRouter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.rs
More file actions
219 lines (205 loc) · 6.86 KB
/
Copy pathhandlers.rs
File metadata and controls
219 lines (205 loc) · 6.86 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
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
Json,
};
use router_off_chain_common::logging::sanitize_for_log;
use router_off_chain_common::validation::{validate_contract_id, validate_function_name, validate_route_name};
use serde_json::json;
use tracing::{error, info};
use crate::{
state::AppState,
types::{ErrorResponse, FeeEstimate, SimulateRequest, SimulateResponse, SimulationDetail, StatsResponse},
};
#[utoipa::path(
get,
path = "/health",
responses(
(status = 200, description = "Health check response")
)
)]
/// GET /health
pub async fn health() -> impl IntoResponse {
(StatusCode::OK, Json(json!({"status": "ok"})))
}
#[utoipa::path(
get,
path = "/stats",
responses(
(status = 200, description = "Server statistics", body = StatsResponse)
)
)]
/// GET /stats
///
/// Returns live WebSocket connection and subscription statistics:
/// - `active_subscriptions`: total subscription count across all tx IDs
/// - `unique_tx_ids`: number of distinct tx IDs being tracked
/// - `broadcast_channel_capacity`: fixed capacity of the broadcast channel
pub async fn stats(State(state): State<AppState>) -> impl IntoResponse {
Json(StatsResponse {
active_subscriptions: state.active_subscriptions(),
unique_tx_ids: state.unique_tx_ids(),
broadcast_channel_capacity: state.broadcast_channel_capacity(),
})
}
#[utoipa::path(
post,
path = "/simulate",
request_body = SimulateRequest,
responses(
(status = 200, description = "Simulation result", body = SimulateResponse),
(status = 400, description = "Bad request", body = ErrorResponse),
(status = 503, description = "Service unavailable", body = ErrorResponse),
(status = 500, description = "Internal server error", body = ErrorResponse)
)
)]
/// POST /simulate
///
/// Calls the Soroban RPC `simulateTransaction` endpoint to get real fee
/// estimates. Falls back to heuristic estimates if the RPC is unavailable.
pub async fn simulate(
State(state): State<AppState>,
Json(req): Json<SimulateRequest>,
) -> Result<Json<SimulateResponse>, (StatusCode, Json<ErrorResponse>)> {
// Use shared validation from router-off-chain-common
if let Err(e) = validate_contract_id(&req.target) {
return Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
error: format!(
"target must be a 56-character Stellar contract ID starting with C: {}",
e.message
),
}),
));
}
if let Err(e) = validate_function_name(&req.function) {
return Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
error: e.message,
}),
));
}
info!(
target = %req.target,
function = %sanitize_for_log(&req.function),
"simulating transaction"
);
let breakdown = state
.rpc
.simulate(&req.target, &req.function, req.amount, req.network_load_bps)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
error: e.to_string(),
}),
)
})?;
Ok(Json(SimulateResponse {
success: breakdown.would_succeed,
estimated_fees: FeeEstimate {
base_fee: breakdown.base_fee,
resource_fee: breakdown.resource_fee,
total_fee: breakdown.total_fee,
surge_multiplier: breakdown.surge_multiplier,
high_load: breakdown.high_load,
},
simulation: SimulationDetail {
target: req.target,
function: req.function,
would_succeed: breakdown.would_succeed,
},
message: if breakdown.would_succeed {
"Simulation successful".to_string()
} else {
"Simulation indicates transaction would fail".to_string()
},
}))
}
#[utoipa::path(
get,
path = "/routes/{name}",
params(
("name" = String, Path, description = "Route name")
),
responses(
(status = 200, description = "Route entry", body = RouteEntryResponse),
(status = 400, description = "Bad request", body = ErrorResponse),
(status = 404, description = "Route not found", body = ErrorResponse),
(status = 500, description = "Internal server error", body = ErrorResponse)
)
)]
/// GET /routes/:name
///
/// Calls router-core::get_route(name) via the Soroban RPC and returns the
/// full RouteEntry as JSON. Returns 404 if the route does not exist.
pub async fn get_route(
State(state): State<AppState>,
Path(name): Path<String>,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
// Validate before logging to prevent log injection via a malicious route
// name containing newlines or other control characters.
if let Err(e) = validate_route_name(&name) {
return Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
error: format!("invalid route name: {}", e.message),
}),
));
}
// `name` is now guaranteed to be alphanumeric/underscore/hyphen only —
// safe to log directly.
info!(route = %name, "fetching route");
match state.rpc.get_route(&name).await {
Ok(Some(entry)) => Ok((StatusCode::OK, Json(entry))),
Ok(None) => Err((
StatusCode::NOT_FOUND,
Json(ErrorResponse {
error: format!("route '{}' not found", name),
}),
)),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
error: e.to_string(),
}),
)),
}
}
#[utoipa::path(
get,
path = "/routes",
responses(
(status = 200, description = "Routes list", body = serde_json::Value),
(status = 503, description = "Service unavailable", body = ErrorResponse),
(status = 500, description = "Internal server error", body = ErrorResponse)
)
)]
/// GET /routes
///
/// Calls `get_all_routes` on the router-core contract via Soroban RPC and
/// returns the list of registered route names as JSON.
pub async fn list_routes(
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
if state.router_core_contract_id.is_empty() {
return Err((
StatusCode::SERVICE_UNAVAILABLE,
"ROUTER_CORE_CONTRACT_ID not configured".to_string(),
));
}
let routes = state
.rpc
.get_all_routes(&state.router_core_contract_id)
.await
.map_err(|e| {
error!("Failed to fetch routes: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
})?;
info!("Returning {} routes", routes.len());
Ok(Json(json!({ "routes": routes })))
}