-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
168 lines (154 loc) · 5.15 KB
/
mod.rs
File metadata and controls
168 lines (154 loc) · 5.15 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
pub mod admin;
pub mod groups;
pub mod tasks;
pub mod users;
pub mod workers;
#[cfg(feature = "debugging")]
use std::net::SocketAddr;
#[cfg(feature = "debugging")]
use axum::{
body::{Body, Bytes},
extract::{ConnectInfo, Request},
middleware::Next,
response::{IntoResponse, Response},
};
use axum::{
http::StatusCode,
middleware,
routing::{get, post},
Extension, Json, Router,
};
#[cfg(feature = "debugging")]
use http_body_util::BodyExt;
use serde_json::json;
use tokio_util::sync::CancellationToken;
use tower_http::catch_panic::CatchPanicLayer;
use tower_http::cors::CorsLayer;
use crate::{
config::{InfraPool, REDIS_CONNECTION_INFO},
error::ApiError,
schema::RedisConnectionInfo,
service::auth::{user_auth_middleware, user_auth_with_name_middleware, AuthUser},
};
pub fn router(st: InfraPool, cancel_token: CancellationToken) -> Router {
#[cfg(not(feature = "debugging"))]
{
Router::new()
.route(
"/auth",
get(users::user_auth).layer(middleware::from_fn_with_state(
st.clone(),
user_auth_with_name_middleware,
)),
)
.route(
"/health",
get(|| async { (StatusCode::OK, Json(json!({"status": "ok"}))) }),
)
.route("/login", post(users::user_login))
.route(
"/redis",
get(query_redis_connection_info).layer(middleware::from_fn_with_state(
st.clone(),
user_auth_middleware,
)),
)
.nest("/users", users::users_router(st.clone()))
.nest("/admin", admin::admin_router(st.clone(), cancel_token))
.nest("/groups", groups::groups_router(st.clone()))
.nest("/workers", workers::workers_router(st.clone()))
.nest("/tasks", tasks::tasks_router(st.clone()))
.with_state(st)
.layer(CorsLayer::permissive())
.layer(CatchPanicLayer::new())
}
#[cfg(feature = "debugging")]
{
Router::new()
.route(
"/auth",
get(users::user_auth).layer(middleware::from_fn_with_state(
st.clone(),
user_auth_with_name_middleware,
)),
)
.route(
"/health",
get(|| async { (StatusCode::OK, Json(json!({"status": "ok"}))) }),
)
.route("/login", post(users::user_login))
.route(
"/redis",
get(query_redis_connection_info).layer(middleware::from_fn_with_state(
st.clone(),
user_auth_middleware,
)),
)
.nest("/users", users::users_router(st.clone()))
.nest("/admin", admin::admin_router(st.clone(), cancel_token))
.nest("/groups", groups::groups_router(st.clone()))
.nest("/workers", workers::workers_router(st.clone()))
.nest("/tasks", tasks::tasks_router(st.clone()))
.with_state(st)
.layer(CorsLayer::permissive())
.layer(CatchPanicLayer::new())
.layer(middleware::from_fn(print_request_addr))
.layer(middleware::from_fn(print_request_response))
}
}
pub async fn query_redis_connection_info(
Extension(_): Extension<AuthUser>,
) -> Result<Json<RedisConnectionInfo>, ApiError> {
let url = REDIS_CONNECTION_INFO.get().map(|info| info.client_url());
Ok(Json(RedisConnectionInfo { url }))
}
#[cfg(feature = "debugging")]
// For debugging purpose
async fn print_request_addr(
req: Request,
next: Next,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let remote_addr = req
.extensions()
.get::<ConnectInfo<SocketAddr>>()
.map(|ci| ci.0);
tracing::debug!("receive request from {:?} to {}", remote_addr, req.uri());
let res = next.run(req).await;
Ok(res)
}
#[cfg(feature = "debugging")]
// For debugging purpose
async fn print_request_response(
req: Request,
next: Next,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let (parts, body) = req.into_parts();
let bytes = buffer_and_print("request", body).await?;
let req = Request::from_parts(parts, Body::from(bytes));
let res = next.run(req).await;
let (parts, body) = res.into_parts();
let bytes = buffer_and_print("response", body).await?;
let res = Response::from_parts(parts, Body::from(bytes));
Ok(res)
}
#[cfg(feature = "debugging")]
// For debugging purpose
async fn buffer_and_print<B>(direction: &str, body: B) -> Result<Bytes, (StatusCode, String)>
where
B: axum::body::HttpBody<Data = Bytes>,
B::Error: std::fmt::Display,
{
let bytes = match body.collect().await {
Ok(collected) => collected.to_bytes(),
Err(err) => {
return Err((
StatusCode::BAD_REQUEST,
format!("failed to read {direction} body: {err}"),
));
}
};
if let Ok(body) = std::str::from_utf8(&bytes) {
tracing::debug!("{direction} body = {body:?}");
}
Ok(bytes)
}