zino_axum/application/
cluster.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
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
use crate::{middleware, AxumResponse, Extractor};
use axum::{
    error_handling::HandleErrorLayer,
    extract::{rejection::LengthLimitError, DefaultBodyLimit},
    http::{HeaderName, HeaderValue, StatusCode},
    middleware::from_fn,
    BoxError, Router,
};
use std::{any::Any, borrow::Cow, convert::Infallible, fs, net::SocketAddr, time::Duration};
use tokio::{net::TcpListener, runtime::Builder, signal};
use tower::{
    timeout::{error::Elapsed, TimeoutLayer},
    ServiceBuilder,
};
use tower_http::{
    catch_panic::CatchPanicLayer,
    compression::{predicate::DefaultPredicate, CompressionLayer},
    decompression::DecompressionLayer,
    services::{ServeDir, ServeFile},
    set_header::SetResponseHeaderLayer,
};
use utoipa_rapidoc::RapiDoc;
use zino_core::{
    application::{Application, Plugin, ServerTag},
    extension::TomlTableExt,
    schedule::AsyncScheduler,
    LazyLock,
};
use zino_http::response::Response;

/// An HTTP server cluster.
#[derive(Default)]
pub struct Cluster {
    /// Custom plugins.
    custom_plugins: Vec<Plugin>,
    /// Default routes.
    default_routes: Vec<Router>,
    /// Tagged routes.
    tagged_routes: Vec<(ServerTag, Vec<Router>)>,
}

impl Application for Cluster {
    type Routes = Vec<Router>;

    #[inline]
    fn register(mut self, routes: Self::Routes) -> Self {
        self.default_routes = routes;
        self
    }

    #[inline]
    fn register_with(mut self, server_tag: ServerTag, routes: Self::Routes) -> Self {
        self.tagged_routes.push((server_tag, routes));
        self
    }

    #[inline]
    fn add_plugin(mut self, plugin: Plugin) -> Self {
        self.custom_plugins.push(plugin);
        self
    }

    fn run_with<T: AsyncScheduler + Send + 'static>(self, mut scheduler: T) {
        let runtime = Builder::new_multi_thread()
            .thread_keep_alive(Duration::from_secs(60))
            .thread_stack_size(2 * 1024 * 1024)
            .global_queue_interval(61)
            .enable_all()
            .build()
            .expect("fail to build Tokio runtime for `AxumCluster`");
        let app_env = Self::env();
        runtime.block_on(async {
            #[cfg(feature = "orm")]
            zino_orm::GlobalPool::connect_all().await;
            Self::load().await;
            app_env.load_plugins(self.custom_plugins).await;
        });
        if scheduler.is_ready() {
            if scheduler.is_blocking() {
                runtime.spawn(async move {
                    if let Err(err) = scheduler.run().await {
                        tracing::error!("fail to run the async scheduler: {err}");
                    }
                });
            } else {
                runtime.spawn(async move {
                    loop {
                        scheduler.tick().await;

                        // Cannot use `std::thread::sleep` because it blocks the Tokio runtime.
                        if let Some(duration) = scheduler.time_till_next_job() {
                            tokio::time::sleep(duration).await;
                        }
                    }
                });
            }
        }

        runtime.block_on(async {
            let default_routes = self.default_routes;
            let tagged_routes = self.tagged_routes;
            let app_state = Self::shared_state();
            let app_name = Self::name();
            let app_version = Self::version();
            let listeners = app_state.listeners();
            let has_debug_server = listeners.iter().any(|listener| listener.0.is_debug());
            let servers = listeners.into_iter().map(|listener| {
                let server_tag = listener.0;
                let addr = listener.1;
                tracing::warn!(
                    server_tag = server_tag.as_str(),
                    app_env = app_env.as_str(),
                    app_name,
                    app_version,
                    zino_version = env!("CARGO_PKG_VERSION"),
                    "listen on `{addr}`",
                );

                // Server config
                let mut public_dir = "public";
                let mut public_route_prefix = "/public";
                let mut body_limit = 128 * 1024 * 1024; // 128MB
                let mut request_timeout = Duration::from_secs(60); // 60 seconds
                let mut keep_alive_timeout = 75; // 75 seconds
                if let Some(config) = app_state.get_config("server") {
                    if let Some(dir) = config.get_str("page-dir") {
                        public_dir = dir;
                        public_route_prefix = "/page";
                    } else if let Some(dir) = config.get_str("public-dir") {
                        public_dir = dir;
                    }
                    if let Some(route_prefix) = config.get_str("public-route-prefix") {
                        public_route_prefix = route_prefix;
                    }
                    if let Some(limit) = config.get_usize("body-limit") {
                        body_limit = limit;
                    }
                    if let Some(timeout) = config.get_duration("request-timeout") {
                        request_timeout = timeout;
                    }
                    if let Some(timeout) = config.get_duration("keep-alive-timeout") {
                        keep_alive_timeout = timeout.as_secs();
                    }
                }

                let mut app = Router::new();
                let public_dir = Self::parse_path(public_dir);
                if public_dir.exists() {
                    let index_file = public_dir.join("index.html");
                    let favicon_file = public_dir.join("favicon.ico");
                    if index_file.exists() {
                        app = app.route_service("/", ServeFile::new(index_file));
                    }
                    if favicon_file.exists() {
                        app = app.route_service("/favicon.ico", ServeFile::new(favicon_file));
                    }

                    let not_found_file = public_dir.join("404.html");
                    let serve_dir = ServeDir::new(public_dir)
                        .precompressed_gzip()
                        .precompressed_br()
                        .append_index_html_on_directories(true)
                        .not_found_service(ServeFile::new(not_found_file));
                    let mut serve_dir_route =
                        Router::new().nest_service(public_route_prefix, serve_dir);
                    if public_route_prefix.ends_with("/page") {
                        serve_dir_route =
                            serve_dir_route.layer(from_fn(middleware::serve_static_pages));
                    }
                    app = app.merge(serve_dir_route);
                    tracing::info!(
                        "Static pages `{public_route_prefix}/**` are registered for `{addr}`"
                    );
                }
                for route in &default_routes {
                    app = app.merge(route.clone());
                }
                for (tag, routes) in &tagged_routes {
                    if tag == &server_tag || server_tag.is_debug() {
                        for route in routes {
                            app = app.merge(route.clone());
                        }
                    }
                }

                // OpenAPI docs
                let is_docs_server = if has_debug_server {
                    server_tag.is_debug()
                } else {
                    server_tag.is_main()
                };
                if is_docs_server {
                    let openapi = zino_openapi::openapi();
                    if let Some(config) = app_state.get_config("openapi") {
                        if config.get_bool("show-docs") != Some(false) {
                            // If the `spec-url` has been configured, the user should
                            // provide the generated OpenAPI object with a derivation.
                            let path = config.get_str("rapidoc-route").unwrap_or("/rapidoc");
                            let rapidoc = if let Some(url) = config.get_str("spec-url") {
                                RapiDoc::new(url)
                            } else {
                                RapiDoc::with_openapi("/api-docs/openapi.json", openapi)
                            };
                            if let Some(custom_html) = config.get_str("custom-html") {
                                let custom_html_file = Self::parse_path(custom_html);
                                if let Ok(html) = fs::read_to_string(custom_html_file) {
                                    app = app.merge(rapidoc.custom_html(html).path(path));
                                } else {
                                    app = app.merge(rapidoc.path(path));
                                }
                            } else {
                                app = app.merge(rapidoc.path(path));
                            }
                            tracing::info!("RapiDoc router `{path}` is registered for `{addr}`");
                        }
                    } else {
                        let rapidoc = RapiDoc::with_openapi("/api-docs/openapi.json", openapi)
                            .path("/rapidoc");
                        app = app.merge(rapidoc);
                        tracing::info!("RapiDoc router `/rapidoc` is registered for `{addr}`");
                    }
                }

                app = app
                    .fallback_service(tower::service_fn(|req| async {
                        let req = Extractor::from(req);
                        let res = Response::new(StatusCode::NOT_FOUND).context(&req);
                        Ok::<AxumResponse, Infallible>(res.into())
                    }))
                    .layer(
                        ServiceBuilder::new()
                            .layer(SetResponseHeaderLayer::if_not_present(
                                HeaderName::from_static("connection"),
                                HeaderValue::from_static("keep-alive"),
                            ))
                            .layer(SetResponseHeaderLayer::if_not_present(
                                HeaderName::from_static("keep-alive"),
                                HeaderValue::from_str(&format!("timeout={keep_alive_timeout}"))
                                    .expect("fail to set the `keep-alive` header value"),
                            ))
                            .layer(DefaultBodyLimit::max(body_limit))
                            .layer(
                                CompressionLayer::new()
                                    .gzip(true)
                                    .compress_when(DefaultPredicate::new()),
                            )
                            .layer(DecompressionLayer::new().gzip(true))
                            .layer(LazyLock::force(&middleware::TRACING_MIDDLEWARE))
                            .layer(LazyLock::force(&middleware::CORS_MIDDLEWARE))
                            .layer(from_fn(middleware::request_context))
                            .layer(from_fn(middleware::extract_etag))
                            .layer(HandleErrorLayer::new(|err: BoxError| async move {
                                let status_code = if err.is::<Elapsed>() {
                                    StatusCode::REQUEST_TIMEOUT
                                } else if err.is::<LengthLimitError>() {
                                    StatusCode::PAYLOAD_TOO_LARGE
                                } else {
                                    StatusCode::INTERNAL_SERVER_ERROR
                                };
                                let res = Response::new(status_code);
                                Ok::<AxumResponse, Infallible>(res.into())
                            }))
                            .layer(CatchPanicLayer::custom(
                                |err: Box<dyn Any + Send + 'static>| {
                                    let details = if let Some(s) = err.downcast_ref::<String>() {
                                        Cow::Owned(s.to_owned())
                                    } else if let Some(s) = err.downcast_ref::<&str>() {
                                        Cow::Borrowed(*s)
                                    } else {
                                        Cow::Borrowed("Unknown panic message")
                                    };
                                    let mut res = Response::internal_server_error();
                                    res.set_message(details);
                                    crate::response::build_http_response(res)
                                },
                            ))
                            .layer(TimeoutLayer::new(request_timeout)),
                    );
                Box::pin(async move {
                    let tcp_listener = TcpListener::bind(&addr)
                        .await
                        .unwrap_or_else(|err| panic!("fail to listen on {addr}: {err}"));
                    axum::serve(
                        tcp_listener,
                        app.into_make_service_with_connect_info::<SocketAddr>(),
                    )
                    .with_graceful_shutdown(Self::shutdown())
                    .await
                })
            });
            for result in futures::future::join_all(servers).await {
                if let Err(err) = result {
                    tracing::error!("axum server error: {err}");
                }
            }
        });
    }

    async fn shutdown() {
        let ctrl_c = async {
            if let Err(err) = signal::ctrl_c().await {
                tracing::error!("fail to install the `Ctrl+C` handler: {err}");
            }
            #[cfg(feature = "orm")]
            zino_orm::GlobalPool::close_all().await;
        };
        #[cfg(unix)]
        let terminate = async {
            signal::unix::signal(signal::unix::SignalKind::terminate())
                .expect("fail to install the terminate signal handler")
                .recv()
                .await;
            #[cfg(feature = "orm")]
            zino_orm::GlobalPool::close_all().await;
        };
        #[cfg(not(unix))]
        let terminate = std::future::pending::<()>();
        tokio::select! {
            _ = ctrl_c => {},
            _ = terminate => {},
        };
        tracing::warn!("signal received, starting graceful shutdown");
    }
}