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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/// axumserver mod
/// ```ignore
/// #[allow(warnings)]
/// fn main() {
/// let rt = doe::asyncrs::runtime::Builder::new_multi_thread()
/// .enable_all()
/// .build()
/// .unwrap();
/// rt.block_on(run());
/// rt.block_on(async {
/// run().await;
/// });
/// }
///
/// async fn run() {
/// use doe::logger::*;
/// doe::logger::init_info();
/// debug!("开始服务");
/// use doe::axumserver::response::Html;
/// use doe::axumserver::routing::get;
/// pub async fn home() -> Html<String> {
/// include_str!("../index.html").to_string().into()
/// }
/// let router = doe::axumserver::router_allow_cors().route("/", get(home));
/// doe::axumserver::server_app_default_ip(router, 60001)
/// .await
/// .unwrap();
/// // doe::axumserver::server_app( vec![IpAddr::from([127, 0, 0, 1])],router, 60001).await;
/// }
/// ```
///
#[allow(warnings)]
#[cfg(feature = "axumserver")]
pub mod axumserver {
use crate::ip_addr;
use crate::ip_addr::print_listening_with_protocol;
use crate::logger::info;
use axum::extract::Request;
use axum::middleware::Next;
use axum::response::Response;
pub use axum::*;
use hyper::HeaderMap;
use hyper::StatusCode;
pub async fn log_ip_middleware(
headers: HeaderMap,
request: Request<axum::body::Body>,
next: Next,
) -> Result<Response, StatusCode> {
let ip_port = request
.extensions()
.get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
.map(|ci| (ci.0.ip(), ci.0.port()));
if let Some(ip_port) = ip_port {
info!("Ok get request ip_port: {}:{}", ip_port.0, ip_port.1);
return Ok(next.run(request).await);
} else {
return Ok(next.run(request).await);
}
}
use axum::response::IntoResponse;
use std::borrow::Cow;
use std::path::Path;
use std::path::PathBuf;
use tower::BoxError;
pub 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}")),
)
}
use axum::routing::{get, post};
use axum::{error_handling::HandleErrorLayer, extract::DefaultBodyLimit, Router};
use hyper::Method;
use std::sync::Arc;
use std::time::Duration;
use tower::ServiceBuilder;
use tower_http::cors::Any;
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer;
pub fn router() -> Router {
Router::new()
.layer(axum::middleware::from_fn(log_ip_middleware))
.layer(DefaultBodyLimit::disable())
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(handle_error))
.load_shed()
.concurrency_limit(2048)
.timeout(Duration::from_secs(10))
.layer(TraceLayer::new_for_http()),
)
}
pub fn router_allow_cors() -> Router {
let cors_layer = CorsLayer::new()
.allow_origin(Any)
.allow_headers(Any)
.allow_private_network(true)
.allow_methods(Any);
Router::new()
.layer(cors_layer)
.layer(axum::middleware::from_fn(log_ip_middleware))
.layer(DefaultBodyLimit::disable())
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(handle_error))
.load_shed()
.concurrency_limit(2048)
.timeout(Duration::from_secs(10))
.layer(TraceLayer::new_for_http()),
)
}
use crate::ip_addr::create_listener;
use crate::ip_addr::get_addrs;
use crate::ip_addr::print_listening;
use crate::ip_addr::shutdown_signal;
use crate::ip_addr::BindAddr;
use crate::logger::error;
use futures_util::future::join_all;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, Ordering};
pub async fn server_app_default_ip(router: Router, port: u16) -> anyhow::Result<()> {
let mut handles = vec![];
let (mut ipv4_addrs, ipv6_addrs) = get_addrs()?;
ipv4_addrs.extend(ipv6_addrs);
let addrs = ipv4_addrs.clone();
let listening = print_listening(&ipv4_addrs, port)?;
info!("{}", listening);
let running = Arc::new(AtomicBool::new(true));
// Iterate through IPv4 addresses, create a listener for each and start async tasks
for bind_addr in addrs.iter() {
// Ensure the current address is an IP address type
match bind_addr {
BindAddr::IpAddr(ip) => {
// Create listener, bind IP address and server port
let listener = create_listener(SocketAddr::new(*ip, port))?;
let router = router.clone();
// Start async task to listen and handle client requests
let handle = tokio::spawn(async move {
// Create application instance with database connection pool and Minio client
let app = router;
// Start listening and handling requests
axum::serve(listener, app).await.unwrap();
});
// Add current task handle to the list
handles.push(handle);
}
#[cfg(unix)]
BindAddr::SocketPath(ip) => {}
}
}
// Start an async task that will terminate all tasks and gracefully shutdown the program when receiving shutdown signal
handles.push(tokio::spawn(async move {
// Wait for shutdown signal
shutdown_signal().await;
// Define exit code as success
let code = std::process::ExitCode::SUCCESS;
// Exit program
std::process::exit(0);
}));
// Use tokio's select! macro to concurrently handle task completion and shutdown signals
tokio::select! {
// When all tasks complete
ret = join_all(handles) => {
// Iterate through each task's result
for r in ret {
// If task fails, log error message
if let Err(e) = r {
error!("Task failed: {}", e);
}
}
},
// When shutdown signal is received
_ = shutdown_signal() => {
// Set running flag to false, indicating program will stop
running.store(false, Ordering::SeqCst);
},
};
Ok(())
}
#[cfg_attr(docsrs, doc(cfg(feature = "tls-rustls")))]
pub async fn server_app_default_ip_with_tls(
router: Router,
port: u16,
cert: PathBuf,
key: PathBuf,
) -> anyhow::Result<()> {
use rustls::crypto::ring::default_provider;
use rustls::crypto::CryptoProvider;
CryptoProvider::install_default(default_provider());
let mut handles = vec![];
let (mut ipv4_addrs, ipv6_addrs) = get_addrs()?;
ipv4_addrs.extend(ipv6_addrs);
let addrs = ipv4_addrs.clone();
let listening = print_listening_with_protocol(&ipv4_addrs, port,"https")?;
info!("{}", listening);
let running = Arc::new(AtomicBool::new(true));
// Iterate through IPv4 addresses, create a listener for each and start async tasks
for bind_addr in addrs.iter() {
// Ensure the current address is an IP address type
match bind_addr {
BindAddr::IpAddr(ip) => {
// Create listener, bind IP address and server port
// let listener = create_listener(SocketAddr::new(*ip, port))?;
let addr = SocketAddr::new(*ip, port);
let router = router.clone();
let cert = cert.clone();
let key = key.clone();
// Start async task to listen and handle client requests
let handle = tokio::spawn(async move {
// Create application instance with database connection pool and Minio client
let app = router;
// Start listening and handling requests
use axum_server::tls_rustls::RustlsConfig;
let config = RustlsConfig::from_pem_file(cert, key).await.unwrap();
axum_server::bind_rustls(addr, config)
.serve(app.into_make_service())
.await
.unwrap();
// axum::serve(listener, app).await.unwrap();
});
// Add current task handle to the list
handles.push(handle);
}
#[cfg(unix)]
BindAddr::SocketPath(ip) => {}
}
}
// Start an async task that will terminate all tasks and gracefully shutdown the program when receiving shutdown signal
handles.push(tokio::spawn(async move {
// Wait for shutdown signal
shutdown_signal().await;
// Define exit code as success
let code = std::process::ExitCode::SUCCESS;
// Exit program
std::process::exit(0);
}));
// Use tokio's select! macro to concurrently handle task completion and shutdown signals
tokio::select! {
// When all tasks complete
ret = join_all(handles) => {
// Iterate through each task's result
for r in ret {
// If task fails, log error message
if let Err(e) = r {
error!("Task failed: {}", e);
}
}
},
// When shutdown signal is received
_ = shutdown_signal() => {
// Set running flag to false, indicating program will stop
running.store(false, Ordering::SeqCst);
},
};
Ok(())
}
use std::net::IpAddr;
pub async fn server_app(
ip_addrs: Vec<IpAddr>,
router: Router,
port: u16,
) -> anyhow::Result<()> {
let mut handles = vec![];
let bind_ddr: Vec<BindAddr> = ip_addrs.iter().map(|ip| BindAddr::IpAddr(*ip)).collect();
let listening = print_listening(&bind_ddr, port)?;
info!("{}", listening);
let running = Arc::new(AtomicBool::new(true));
// Iterate through IPv4 addresses, create a listener for each and start async tasks
for bind_addr in ip_addrs.iter() {
// Create listener, bind IP address and server port
let listener = create_listener(SocketAddr::new(*bind_addr, port))?;
let router = router.clone();
// Start async task to listen and handle client requests
let handle = tokio::spawn(async move {
// Create application instance with database connection pool and Minio client
let app = router;
// Start listening and handling requests
axum::serve(listener, app).await.unwrap();
});
// Add current task handle to the list
handles.push(handle);
}
// Start an async task that will terminate all tasks and gracefully shutdown the program when receiving shutdown signal
handles.push(tokio::spawn(async move {
// Wait for shutdown signal
shutdown_signal().await;
// Define exit code as success
let code = std::process::ExitCode::SUCCESS;
// Exit program
std::process::exit(0);
}));
// Use tokio's select! macro to concurrently handle task completion and shutdown signals
tokio::select! {
// When all tasks complete
ret = join_all(handles) => {
// Iterate through each task's result
for r in ret {
// If task fails, log error message
if let Err(e) = r {
error!("Task failed: {}", e);
}
}
},
// When shutdown signal is received
_ = shutdown_signal() => {
// Set running flag to false, indicating program will stop
running.store(false, Ordering::SeqCst);
},
};
Ok(())
}
#[cfg_attr(docsrs, doc(cfg(feature = "tls-rustls")))]
pub async fn server_app_with_tls(
ip_addrs: Vec<IpAddr>,
router: Router,
port: u16,
cert: PathBuf,
key: PathBuf,
) -> anyhow::Result<()> {
use rustls::crypto::ring::default_provider;
use rustls::crypto::CryptoProvider;
CryptoProvider::install_default(default_provider());
let mut handles = vec![];
let bind_ddr: Vec<BindAddr> = ip_addrs.iter().map(|ip| BindAddr::IpAddr(*ip)).collect();
let listening = print_listening_with_protocol(&bind_ddr, port,"https")?;
info!("{}", listening);
let running = Arc::new(AtomicBool::new(true));
// Iterate through IPv4 addresses, create a listener for each and start async tasks
for bind_addr in ip_addrs.iter() {
// Create listener, bind IP address and server port
let listener = create_listener(SocketAddr::new(*bind_addr, port))?;
let router = router.clone();
let addr = SocketAddr::new(*bind_addr, port);
let cert = cert.clone();
let key = key.clone();
// Start async task to listen and handle client requests
let handle = tokio::spawn(async move {
// Create application instance with database connection pool and Minio client
let app = router;
use axum_server::tls_rustls::RustlsConfig;
let config = RustlsConfig::from_pem_file(cert, key).await.unwrap();
axum_server::bind_rustls(addr, config)
.serve(app.into_make_service())
.await
.unwrap();
});
// Add current task handle to the list
handles.push(handle);
}
// Start an async task that will terminate all tasks and gracefully shutdown the program when receiving shutdown signal
handles.push(tokio::spawn(async move {
// Wait for shutdown signal
shutdown_signal().await;
// Define exit code as success
let code = std::process::ExitCode::SUCCESS;
// Exit program
std::process::exit(0);
}));
// Use tokio's select! macro to concurrently handle task completion and shutdown signals
tokio::select! {
// When all tasks complete
ret = join_all(handles) => {
// Iterate through each task's result
for r in ret {
// If task fails, log error message
if let Err(e) = r {
error!("Task failed: {}", e);
}
}
},
// When shutdown signal is received
_ = shutdown_signal() => {
// Set running flag to false, indicating program will stop
running.store(false, Ordering::SeqCst);
},
};
Ok(())
}
}
#[cfg(feature = "axumserver")]
pub use axumserver::*;