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
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ Copyright: (c) 2023, Mike 'PhiSyX' S. (https://github.com/PhiSyX)         ┃
// ┃ SPDX-License-Identifier: MPL-2.0                                          ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃                                                                           ┃
// ┃  This Source Code Form is subject to the terms of the Mozilla Public      ┃
// ┃  License, v. 2.0. If a copy of the MPL was not distributed with this      ┃
// ┃  file, You can obtain one at https://mozilla.org/MPL/2.0/.                ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

mod error;
pub mod settings;
mod components {
	#[cfg(feature = "cookies")]
	pub(super) mod cookies;
	#[cfg(feature = "cors")]
	pub(super) mod cors;
	#[cfg(feature = "database-postgres")]
	pub(super) mod database_postgres;
	#[cfg(feature = "encryption-argon2")]
	pub(super) mod encryption_argon2;
}

use std::net;

use console::style;

pub use self::error::Error;
use crate::{routing, state};

// -------- //
// Constant //
// -------- //

pub const PORT_PLAINTEXT: u16 = 80;
pub const PORT_ENCRYPT: u16 = 443;

// --------- //
// Structure //
// --------- //

pub struct Server<UserState> {
	pub state: crate::state::State<UserState>,

	pub application_settings: crate::application::Settings,
	pub(crate) settings: settings::Settings,
	#[cfg(feature = "cors")]
	pub(crate) cors_settings: Option<crate::http::cors::Settings>,

	global_router: axum::Router<()>,
	pub(crate) router: axum::Router<crate::state::State<UserState>>,
	pub(crate) routes: crate::routing::RouteCollection<UserState>,
	static_resources: Vec<settings::SettingsStaticResource>,
}

// -------------- //
// Implémentation //
// -------------- //

impl<UserState> Server<UserState>
where
	UserState: 'static,
	UserState: crate::state::StateInterface,
{
	/// Instancie un serveur.
	pub async fn new(
		application_settings: crate::application::Settings,
	) -> Result<Self, Error> {
		let state = crate::state::State {
			#[cfg(feature = "cookies")]
			cookie_key: None,
			#[cfg(feature = "database-postgres")]
			database_postgres: None,
			user_state: None,
		};

		let settings = settings::Settings::fetch_or_default(
			&application_settings.config_dir,
			&application_settings.loader_extension,
		);

		let static_resources = settings
			.static_resources
			.iter()
			.cloned()
			.map(|mut sr| {
				sr.dir_path = if sr.dir_path.is_relative() {
					application_settings.root_dir.join(&sr.dir_path)
				} else {
					sr.dir_path.to_owned()
				};
				sr
			})
			.collect();

		Ok(Self {
			state,
			#[cfg(feature = "cors")]
			cors_settings: {
				lexa_fs::load(
					&application_settings.config_dir,
					"cors",
					application_settings.loader_extension,
				)
				.ok()
			},
			application_settings,
			settings,
			global_router: axum::Router::new(),
			router: axum::Router::new(),
			routes: routing::RouteCollection::new(),
			static_resources,
		})
	}

	pub fn layer<Layer>(mut self, layer: Layer) -> Self
	where
		Layer: Clone + Send + Sync + 'static,
		Layer: tower_layer::Layer<axum::routing::Route>,
		Layer::Service: tower_service::Service<
			hyper::Request<hyper::Body>,
			Error = std::convert::Infallible,
		>,
		Layer::Service: Clone + Send + 'static,
		<Layer::Service as tower_service::Service<
			hyper::Request<hyper::Body>,
		>>::Response: axum::response::IntoResponse + 'static,
		<Layer::Service as tower_service::Service<
			hyper::Request<hyper::Body>,
		>>::Future: Send + 'static,
	{
		self.router = self.router.layer(layer);
		self
	}

	/// Crée une application qui est scopée pour le serveur.
	pub fn make_application<A>(mut self) -> Self
	where
		A: crate::Application<State = UserState>,
	{
		let routes = <A::Router as routing::RouterExt>::routes();
		let routes_state =
			<A::Router as routing::RouterExt>::routes_with_state(&self.state);

		let mut scoped_router = axum::Router::<state::State<UserState>>::new();

		for route in routes.all().chain(routes_state.all()) {
			scoped_router =
				scoped_router.route(&route.fullpath, route.action.to_owned());
		}

		scoped_router = A::register_extension(&self.state, scoped_router);
		scoped_router = A::register_layer(&self.state, scoped_router);
		scoped_router = A::register_middleware(&self.state, scoped_router);

		self.router = self.router.merge(scoped_router);
		self.routes.extend(routes);
		self.routes.extend(routes_state);

		A::register_service(self)
	}

	/// Démarre un serveur WEB avec ses composants. En se basant sur les
	/// configurations de l'utilisateur.
	///
	/// À terme:
	/// Pendant la phase de développement, une interface textuelle interactive y
	/// est également lancée, afin de:
	///  1) Apporter un peu d'aide visuelle à l'utilisateur.
	///  2) Afin d'accéder à la base de données pour y faire des modifications.
	///  3) Afin de pouvoir tester les requêtes HTTP.
	pub async fn run(mut self) -> Result<(), Error> {
		self.display_all_routes();

		self = self.define_static_resources();

		#[cfg(feature = "cors")]
		{
			self = self.using_cors_layer();
		}

		#[cfg(feature = "cookies")]
		{
			self = self.using_cookie_layer().await?;
		}

		self.launch_server().await?;

		Ok(())
	}

	/// Définit les paramètres utilisateur de l'état.
	pub fn with_user_state(mut self, data: UserState::UserData) -> Self {
		self.state.user_state.replace(UserState::new(data));
		self
	}
}

impl<UserState> Server<UserState>
where
	UserState: 'static,
	UserState: crate::state::StateInterface,
{
	fn define_static_resources(mut self) -> Self {
		for static_resource in self.static_resources.iter() {
			self.global_router = self.global_router.nest_service(
				&static_resource.url_path,
				tower_http::services::ServeDir::new(&static_resource.dir_path),
			);
		}

		self
	}

	fn display_all_routes(&self) {
		println!();
		println!("Liste des routes du serveur web:");
		for route in self.routes.all() {
			let methods = route
				.methods
				.iter()
				.map(|m| style(&m).yellow().to_string())
				.collect::<Vec<String>>()
				.join(" | ");

			println!(
				"\t[{}]: {} {}",
				methods,
				style(&route.fullpath).bright().green(),
				if let Some(name) = route.name.as_deref() {
					format!("as {}", style(name).bright().black())
				} else {
					String::new()
				}
			);
		}
		println!();

		for static_resource in self.static_resources.iter() {
			println!(
				"\t[{}]: {} -> {}",
				style("STATIC RESOURCE").magenta(),
				style(&static_resource.url_path).bright().green(),
				style(static_resource.dir_path.display()).bright().black(),
			);
		}
	}

	async fn launch_server(mut self) -> Result<(), Error> {
		log::info!("Tentative de lancement du serveur web...");

		self.global_router =
			self.global_router.merge(self.router.with_state(self.state));

		let protocol = if self.settings.tls.is_some() {
			"https"
		} else {
			"http"
		};
		let host = self.settings.host;
		let port = self.settings.port;

		let server_socket_addr =
			<_ as Into<net::SocketAddr>>::into((host, port));

		let port_with_prefix = if port == PORT_PLAINTEXT || port == PORT_ENCRYPT
		{
			String::new()
		} else {
			format!(":{}", port)
		};

		let url = format!("{protocol}://{host}{port_with_prefix}");
		type S = net::SocketAddr;
		println!("URL: {url}");

		if let Some(settings_tls) = self.settings.tls {
			let tls_config =
				axum_server::tls_rustls::RustlsConfig::from_pem_file(
					&settings_tls.cert,
					&settings_tls.key,
				)
				.await?;

			let http_config =
				axum_server::HttpConfig::new().http2_only(true).build();

			axum_server::bind_rustls(server_socket_addr, tls_config)
				.http_config(http_config)
				.serve(
					self.global_router
						.into_make_service_with_connect_info::<S>(),
				)
				.await?;
		} else {
			axum::Server::bind(&server_socket_addr)
				.serve(
					self.global_router
						.into_make_service_with_connect_info::<S>(),
				)
				.await?;
		}

		Ok(())
	}
}