hyperlane_core/server/impl.rs
1use super::*;
2
3/// Provides a default implementation for Server.
4impl Default for Server {
5 /// Creates a new Server instance with default values.
6 ///
7 /// # Returns
8 ///
9 /// - `Self` - A new instance with default configuration.
10 #[inline(always)]
11 fn default() -> Self {
12 Self {
13 server_config: ServerConfig::default(),
14 request_config: RequestConfig::default(),
15 task_panic: Vec::new(),
16 request_error: Vec::new(),
17 route_matcher: RouteMatcher::new(),
18 request_middleware: Vec::new(),
19 response_middleware: Vec::new(),
20 }
21 }
22}
23
24/// Implements the `PartialEq` trait for `Server`.
25///
26/// This allows for comparing two `Server` instances for equality.
27impl PartialEq for Server {
28 /// Checks if two `Server` instances are equal.
29 ///
30 /// # Arguments
31 ///
32 /// - `&Self` - The other `Server` instance to compare against.
33 ///
34 /// # Returns
35 ///
36 /// - `bool` - `true` if the instances are equal, `false` otherwise.
37 #[inline]
38 fn eq(&self, other: &Self) -> bool {
39 self.get_server_config() == other.get_server_config()
40 && self.get_request_config() == other.get_request_config()
41 && self.get_route_matcher() == other.get_route_matcher()
42 && self.get_task_panic().len() == other.get_task_panic().len()
43 && self.get_request_error().len() == other.get_request_error().len()
44 && self.get_request_middleware().len() == other.get_request_middleware().len()
45 && self.get_response_middleware().len() == other.get_response_middleware().len()
46 && self
47 .get_task_panic()
48 .iter()
49 .zip(other.get_task_panic().iter())
50 .all(|pair: (&ServerHookHandler, &ServerHookHandler)| Arc::ptr_eq(pair.0, pair.1))
51 && self
52 .get_request_error()
53 .iter()
54 .zip(other.get_request_error().iter())
55 .all(|pair: (&ServerHookHandler, &ServerHookHandler)| Arc::ptr_eq(pair.0, pair.1))
56 && self
57 .get_request_middleware()
58 .iter()
59 .zip(other.get_request_middleware().iter())
60 .all(|pair: (&ServerHookHandler, &ServerHookHandler)| Arc::ptr_eq(pair.0, pair.1))
61 && self
62 .get_response_middleware()
63 .iter()
64 .zip(other.get_response_middleware().iter())
65 .all(|pair: (&ServerHookHandler, &ServerHookHandler)| Arc::ptr_eq(pair.0, pair.1))
66 }
67}
68
69/// Implements the `Eq` trait for `Server`.
70///
71/// This indicates that `Server` has a total equality relation.
72impl Eq for Server {}
73
74/// Implementation of `From` trait for converting `usize` address into `Server`.
75impl From<usize> for Server {
76 /// Converts a memory address into an owned `Server` by cloning from the reference.
77 ///
78 /// # Arguments
79 ///
80 /// - `usize` - The memory address of the `Server` instance.
81 ///
82 /// # Returns
83 ///
84 /// - `Server` - A cloned `Server` instance from the given address.
85 #[inline(always)]
86 fn from(address: usize) -> Self {
87 let server: &Server = address.into();
88 server.clone()
89 }
90}
91
92/// Implementation of `From` trait for converting `usize` address into `&Server`.
93impl From<usize> for &'static Server {
94 /// Converts a memory address into a reference to `Server`.
95 ///
96 /// # Arguments
97 ///
98 /// - `usize` - The memory address of the `Server` instance.
99 ///
100 /// # Returns
101 ///
102 /// - `&'static Server` - A reference to the `Server` at the given address.
103 ///
104 /// # Safety
105 ///
106 /// - The address is guaranteed to be a valid `Server` instance
107 /// that was previously converted from a reference and is managed by the runtime.
108 #[inline(always)]
109 fn from(address: usize) -> &'static Server {
110 unsafe { &*(address as *const Server) }
111 }
112}
113
114/// Implementation of `From` trait for converting `usize` address into `&mut Server`.
115impl From<usize> for &'static mut Server {
116 /// Converts a memory address into a mutable reference to `Server`.
117 ///
118 /// # Arguments
119 ///
120 /// - `usize` - The memory address of the `Server` instance.
121 ///
122 /// # Returns
123 ///
124 /// - `&'static mut Server` - A mutable reference to the `Server` at the given address.
125 ///
126 /// # Safety
127 ///
128 /// - The address is guaranteed to be a valid `Server` instance
129 /// that was previously converted from a reference and is managed by the runtime.
130 #[inline(always)]
131 fn from(address: usize) -> &'static mut Server {
132 unsafe { &mut *(address as *mut Server) }
133 }
134}
135
136/// Implementation of `From` trait for converting `&Server` into `usize` address.
137impl From<&Server> for usize {
138 /// Converts a reference to `Server` into its memory address.
139 ///
140 /// # Arguments
141 ///
142 /// - `&Server` - The reference to the `Server` instance.
143 ///
144 /// # Returns
145 ///
146 /// - `usize` - The memory address of the `Server` instance.
147 #[inline(always)]
148 fn from(server: &Server) -> Self {
149 server as *const Server as usize
150 }
151}
152
153/// Implementation of `From` trait for converting `&mut Server` into `usize` address.
154impl From<&mut Server> for usize {
155 /// Converts a mutable reference to `Server` into its memory address.
156 ///
157 /// # Arguments
158 ///
159 /// - `&mut Server` - The mutable reference to the `Server` instance.
160 ///
161 /// # Returns
162 ///
163 /// - `usize` - The memory address of the `Server` instance.
164 #[inline(always)]
165 fn from(server: &mut Server) -> Self {
166 server as *mut Server as usize
167 }
168}
169
170/// Implementation of `AsRef` trait for `Server`.
171impl AsRef<Server> for Server {
172 /// Converts `&Server` to `&Server` via memory address conversion.
173 ///
174 /// # Returns
175 ///
176 /// - `&Self` - A reference to the `Server` instance.
177 #[inline(always)]
178 fn as_ref(&self) -> &Self {
179 let address: usize = self.into();
180 address.into()
181 }
182}
183
184/// Implementation of `AsMut` trait for `Server`.
185impl AsMut<Server> for Server {
186 /// Converts `&mut Server` to `&mut Server` via memory address conversion.
187 ///
188 /// # Returns
189 ///
190 /// - `&mut Self` - A mutable reference to the `Server` instance.
191 #[inline(always)]
192 fn as_mut(&mut self) -> &mut Self {
193 let address: usize = self.into();
194 address.into()
195 }
196}
197
198/// Converts a `ServerConfig` into a `Server` instance.
199///
200/// This allows creating a `Server` directly from its configuration,
201/// using default values for other fields.
202impl From<ServerConfig> for Server {
203 /// Creates a new `Server` instance from the given `ServerConfig`.
204 ///
205 /// # Arguments
206 ///
207 /// - `ServerConfig` - The server configuration to use.
208 ///
209 /// # Returns
210 ///
211 /// - `Self` - A new `Server` instance with the provided configuration.
212 #[inline(always)]
213 fn from(server_config: ServerConfig) -> Self {
214 Self {
215 server_config,
216 ..Default::default()
217 }
218 }
219}
220
221/// Converts a `RequestConfig` into a `Server` instance.
222///
223/// This allows creating a `Server` directly from its request configuration,
224/// using default values for other fields.
225impl From<RequestConfig> for Server {
226 /// Creates a new `Server` instance from the given `RequestConfig`.
227 ///
228 /// # Arguments
229 ///
230 /// - `RequestConfig` - The request configuration to use.
231 ///
232 /// # Returns
233 ///
234 /// - `Self` - A new `Server` instance with the provided request configuration.
235 #[inline(always)]
236 fn from(request_config: RequestConfig) -> Self {
237 Self {
238 request_config,
239 ..Default::default()
240 }
241 }
242}
243
244/// Implementation of `Lifetime` trait for `Server`.
245impl Lifetime for Server {
246 /// Converts a reference to the server into a `'static` reference.
247 ///
248 /// # Returns
249 ///
250 /// - `&'static Self` - A reference to the server with a `'static` lifetime.
251 ///
252 /// # Safety
253 ///
254 /// - The address is guaranteed to be a valid `Server` instance
255 /// that was previously converted from a reference and is managed by the runtime.
256 #[inline(always)]
257 unsafe fn leak(&self) -> &'static Self {
258 let address: usize = self.into();
259 address.into()
260 }
261
262 /// Converts a reference to the server into a `'static` mutable reference.
263 ///
264 /// # Returns
265 ///
266 /// - `&'static mut Self` - A mutable reference to the server with a `'static` lifetime.
267 ///
268 /// # Safety
269 ///
270 /// - The address is guaranteed to be a valid `Server` instance
271 /// that was previously converted from a reference and is managed by the runtime.
272 #[inline(always)]
273 unsafe fn leak_mut(&self) -> &'static mut Self {
274 let address: usize = self.into();
275 address.into()
276 }
277}
278
279/// Represents the server, providing methods to configure and run it.
280///
281/// This struct wraps the `Server` configuration and routing logic,
282/// offering a high-level API for setting up the HTTP and WebSocket server.
283impl Server {
284 /// Registers a hook into the server's processing pipeline.
285 ///
286 /// This function dispatches the provided `HookType` to the appropriate
287 /// internal hook collection based on its variant. The hook will be executed
288 /// at the corresponding stage of request processing according to its type:
289 /// - `Panic` - Added to panic handlers for error recovery
290 /// - `RequestError` - Added to request error handlers
291 /// - `RequestMiddleware` - Added to pre-route middleware chain
292 /// - `Route` - Registered as a route handler for the specified path
293 /// - `ResponseMiddleware` - Added to post-route middleware chain
294 ///
295 /// # Arguments
296 ///
297 /// - `HookType` - The `HookType` instance containing the hook configuration and factory.
298 #[inline]
299 pub fn handle_hook(&mut self, hook: HookType) {
300 match hook {
301 HookType::TaskPanic(_, hook) => {
302 self.get_mut_task_panic().push(hook());
303 }
304 HookType::RequestError(_, hook) => {
305 self.get_mut_request_error().push(hook());
306 }
307 HookType::RequestMiddleware(_, hook) => {
308 self.get_mut_request_middleware().push(hook());
309 }
310 HookType::Route(path, hook) => {
311 self.get_mut_route_matcher().add(path, hook()).unwrap();
312 }
313 HookType::ResponseMiddleware(_, hook) => {
314 self.get_mut_response_middleware().push(hook());
315 }
316 };
317 }
318
319 /// Sets the server configuration from a JSON string.
320 ///
321 /// # Arguments
322 ///
323 /// - `C` - The configuration.
324 ///
325 /// # Returns
326 ///
327 /// - `&mut Self` - Reference to self for method chaining.
328 #[inline]
329 pub fn config_from_json<C>(&mut self, json: C) -> &mut Self
330 where
331 C: AsRef<str>,
332 {
333 let config: ServerConfig = serde_json::from_str(json.as_ref()).unwrap();
334 self.set_server_config(config);
335 self
336 }
337
338 /// Sets the server configuration.
339 ///
340 /// # Arguments
341 ///
342 /// - `ServerConfig` - The server configuration.
343 ///
344 /// # Returns
345 ///
346 /// - `&mut Self` - Reference to self for method chaining.
347 #[inline(always)]
348 pub fn server_config(&mut self, config: ServerConfig) -> &mut Self {
349 self.set_server_config(config);
350 self
351 }
352
353 /// Sets the HTTP request config.
354 ///
355 /// # Arguments
356 ///
357 /// - `RequestConfig` - The HTTP request config to set.
358 ///
359 /// # Returns
360 ///
361 /// - `&mut Self` - Reference to self for method chaining.
362 #[inline(always)]
363 pub fn request_config(&mut self, config: RequestConfig) -> &mut Self {
364 self.set_request_config(config);
365 self
366 }
367
368 /// Registers a task panic handler to the processing pipeline.
369 ///
370 /// This method allows registering task panic handlers that implement the `ServerHook` trait,
371 /// which will be executed when a panic occurs during request processing.
372 ///
373 /// # Returns
374 ///
375 /// - `&mut Self` - Reference to self for method chaining.
376 #[inline(always)]
377 pub fn task_panic<S>(&mut self) -> &mut Self
378 where
379 S: ServerHook,
380 {
381 self.get_mut_task_panic().push(Hook::factory::<S>());
382 self
383 }
384
385 /// Registers a request error handler to the processing pipeline.
386 ///
387 /// This method allows registering request error handlers that implement the `ServerHook` trait,
388 /// which will be executed when a request error occurs during HTTP request processing.
389 ///
390 /// # Returns
391 ///
392 /// - `&mut Self` - Reference to self for method chaining.
393 #[inline(always)]
394 pub fn request_error<S>(&mut self) -> &mut Self
395 where
396 S: ServerHook,
397 {
398 self.get_mut_request_error().push(Hook::factory::<S>());
399 self
400 }
401
402 /// Registers a route hook for a specific path.
403 ///
404 /// This method allows registering route handlers that implement the `ServerHook` trait,
405 /// providing type safety and better code organization.
406 ///
407 /// # Arguments
408 ///
409 /// - `P` - The route path pattern.
410 ///
411 /// # Returns
412 ///
413 /// - `&mut Self` - Reference to self for method chaining.
414 #[inline(always)]
415 pub fn route<S, P>(&mut self, path: P) -> &mut Self
416 where
417 S: ServerHook,
418 P: AsRef<str>,
419 {
420 self.get_mut_route_matcher()
421 .add(path.as_ref(), Hook::factory::<S>())
422 .unwrap();
423 self
424 }
425
426 /// Registers request middleware to the processing pipeline.
427 ///
428 /// This method allows registering middleware that implements the `ServerHook` trait,
429 /// which will be executed before route handlers for every incoming request.
430 ///
431 /// # Returns
432 ///
433 /// - `&mut Self` - Reference to self for method chaining.
434 #[inline(always)]
435 pub fn request_middleware<S>(&mut self) -> &mut Self
436 where
437 S: ServerHook,
438 {
439 self.get_mut_request_middleware().push(Hook::factory::<S>());
440 self
441 }
442
443 /// Registers response middleware to the processing pipeline.
444 ///
445 /// This method allows registering middleware that implements the `ServerHook` trait,
446 /// which will be executed after route handlers for every outgoing response.
447 ///
448 /// # Returns
449 ///
450 /// - `&mut Self` - Reference to self for method chaining.
451 #[inline(always)]
452 pub fn response_middleware<S>(&mut self) -> &mut Self
453 where
454 S: ServerHook,
455 {
456 self.get_mut_response_middleware()
457 .push(Hook::factory::<S>());
458 self
459 }
460
461 /// Format the host and port into a bindable address string.
462 ///
463 /// # Arguments
464 ///
465 /// - `H` - The host address.
466 /// - `u16` - The port number.
467 ///
468 /// # Returns
469 ///
470 /// - `String` - The formatted address string in the form "host:port".
471 #[inline(always)]
472 pub fn format_bind_address<H>(host: H, port: u16) -> String
473 where
474 H: AsRef<str>,
475 {
476 format!("{}{COLON}{port}", host.as_ref())
477 }
478
479 /// Flushes the standard output stream.
480 ///
481 /// # Returns
482 ///
483 /// - `io::Result<()>` - The result of the flush operation.
484 #[inline(always)]
485 pub fn try_flush_stdout() -> io::Result<()> {
486 stdout().flush()
487 }
488
489 /// Flushes the standard output stream.
490 ///
491 /// # Panics
492 ///
493 /// This function will panic if the flush operation fails.
494 #[inline(always)]
495 pub fn flush_stdout() {
496 stdout().flush().unwrap();
497 }
498
499 /// Flushes the standard error stream.
500 ///
501 /// # Returns
502 ///
503 /// - `io::Result<()>` - The result of the flush operation.
504 #[inline(always)]
505 pub fn try_flush_stderr() -> io::Result<()> {
506 stderr().flush()
507 }
508
509 /// Flushes the standard error stream.
510 ///
511 /// # Panics
512 ///
513 /// This function will panic if the flush operation fails.
514 #[inline(always)]
515 pub fn flush_stderr() {
516 stderr().flush().unwrap();
517 }
518
519 /// Flushes both the standard output and error streams.
520 ///
521 /// # Returns
522 ///
523 /// - `io::Result<()>` - The result of the flush operation.
524 #[inline(always)]
525 pub fn try_flush_stdout_and_stderr() -> io::Result<()> {
526 Self::try_flush_stdout()?;
527 Self::try_flush_stderr()
528 }
529
530 /// Flushes both the standard output and error streams.
531 ///
532 /// # Panics
533 ///
534 /// This function will panic if either flush operation fails.
535 #[inline(always)]
536 pub fn flush_stdout_and_stderr() {
537 Self::flush_stdout();
538 Self::flush_stderr();
539 }
540
541 /// Spawns a task handler for a given stream and hook.
542 ///
543 /// # Arguments
544 ///
545 /// - `&'static self` - The server instance whose task-panic hooks are used.
546 /// - `usize` - The addresses of the stream and of the context.
547 /// - `F` - The hook to execute.
548 ///
549 /// # Safety
550 ///
551 /// - The address is guaranteed to be a valid `Context` instance
552 /// that was previously converted from a reference and is managed by the runtime.
553 async fn task_handler<F>(&'static self, stream_address: usize, ctx_address: usize, hook: F)
554 where
555 F: Future<Output = ()> + Send + 'static,
556 {
557 if let Err(error) = spawn(hook).await
558 && error.is_panic()
559 {
560 let ctx: &mut Context = ctx_address.into();
561 let stream: &mut Stream = stream_address.into();
562 let panic: PanicData = PanicData::from_join_error(error);
563 ctx.set_task_panic(panic)
564 .get_mut_response()
565 .set_status_code(HttpStatus::InternalServerError.code());
566 stream.set_closed(false);
567 for hook in self.get_task_panic().iter() {
568 if hook(stream, ctx).await.is_reject() {
569 break;
570 }
571 }
572 unsafe {
573 let _: Box<Context> = Box::from_raw(ctx);
574 let _: Box<Stream> = Box::from_raw(stream);
575 }
576 };
577 }
578
579 /// Configures socket options for a newly accepted `TcpStream`.
580 ///
581 /// This applies settings like `TCP_NODELAY`, and `IP_TTL` from the server's configuration.
582 ///
583 /// # Arguments
584 ///
585 /// - `&TcpStream` - A reference to the `TcpStream` to configure.
586 fn configure_stream(&self, stream: &TcpStream) {
587 let config: &ServerConfig = self.get_server_config();
588 if let Some(nodelay) = config.try_get_nodelay() {
589 let _: Result<(), io::Error> = stream.set_nodelay(nodelay);
590 }
591 if let Some(ttl) = config.try_get_ttl() {
592 let _: Result<(), io::Error> = stream.set_ttl(ttl);
593 }
594 }
595
596 /// Executes trait-based request middleware in sequence.
597 ///
598 /// # Arguments
599 ///
600 /// - `&mut Stream` - The `Stream` for the current request.
601 /// - `&mut Context` - The `Context` for the current request.
602 ///
603 /// # Returns
604 ///
605 /// - `bool` - `true` if the lifecycle was aborted, `false` otherwise.
606 pub(super) async fn handle_request_middleware(
607 &self,
608 stream: &mut Stream,
609 ctx: &mut Context,
610 ) -> bool {
611 for hook in self.get_request_middleware().iter() {
612 if hook(stream, ctx).await.is_reject() {
613 return true;
614 }
615 }
616 false
617 }
618
619 /// Executes a trait-based route hook if one matches.
620 ///
621 /// # Arguments
622 ///
623 /// - `&mut Stream` - The `Stream` for the current request.
624 /// - `&mut Context` - The `Context` for the current request.
625 /// - `&str` - The request path to match.
626 ///
627 /// # Returns
628 ///
629 /// - `bool` - `true` if the lifecycle was aborted, `false` otherwise.
630 pub(super) async fn handle_route_matcher(
631 &self,
632 stream: &mut Stream,
633 ctx: &mut Context,
634 path: &str,
635 ) -> bool {
636 if let Some(hook) = self.get_route_matcher().try_resolve_route(ctx, path)
637 && hook(stream, ctx).await.is_reject()
638 {
639 return true;
640 }
641 false
642 }
643
644 /// Executes trait-based response middleware in sequence.
645 ///
646 /// # Arguments
647 ///
648 /// - `&mut Stream` - The `Stream` for the current request.
649 /// - `&mut Context` - The `Context` for the current request.
650 ///
651 /// # Returns
652 ///
653 /// - `bool` - `true` if the lifecycle was aborted, `false` otherwise.
654 pub(super) async fn handle_response_middleware(
655 &self,
656 stream: &mut Stream,
657 ctx: &mut Context,
658 ) -> bool {
659 for hook in self.get_response_middleware().iter() {
660 if hook(stream, ctx).await.is_reject() {
661 return true;
662 }
663 }
664 false
665 }
666
667 /// Handles errors that occur while processing HTTP requests.
668 ///
669 /// # Arguments
670 ///
671 /// - `&mut Stream` - The `Stream` for the current request.
672 /// - `&mut Context` - The `Context` for the current request.
673 /// - `&RequestError` - The error that occurred.
674 pub async fn handle_request_error(
675 &self,
676 stream: &mut Stream,
677 ctx: &mut Context,
678 error: &RequestError,
679 ) {
680 ctx.set_request_error_data(error.clone());
681 stream.set_closed(false);
682 for hook in self.get_request_error().iter() {
683 if hook(stream, ctx).await.is_reject() {
684 return;
685 }
686 }
687 }
688
689 /// The core request handling pipeline.
690 ///
691 /// This function orchestrates the execution of request middleware, the route hook,
692 /// and response middleware. It supports both function-based and trait-based handlers.
693 ///
694 /// # Arguments
695 ///
696 /// - `&mut Stream` - The `Stream` for the current request.
697 /// - `&mut Context` - The `Context` for the current request.
698 /// - `Request` - The incoming request to be processed.
699 ///
700 /// # Returns
701 ///
702 /// - `bool` - A boolean indicating whether the connection should be kept alive.
703 async fn request_hook(&self, stream: &mut Stream, ctx: &mut Context, request: Request) -> bool {
704 let keep_alive: bool = request.is_enable_keep_alive();
705 let version: RequestVersion = request.get_version().clone();
706 let route: RequestPath = request.get_path().clone();
707 ctx.set_request(request);
708 ctx.get_mut_response().reset().set_version(version);
709 ctx.clear_route_params();
710 ctx.clear_attribute();
711 stream.set_closed(false);
712 if self.handle_request_middleware(stream, ctx).await {
713 return stream.is_keep_alive(keep_alive);
714 }
715 if self.handle_route_matcher(stream, ctx, &route).await {
716 return stream.is_keep_alive(keep_alive);
717 }
718 if self.handle_response_middleware(stream, ctx).await {
719 return stream.is_keep_alive(keep_alive);
720 }
721 stream.is_keep_alive(keep_alive)
722 }
723
724 /// Handles subsequent HTTP requests on a persistent (keep-alive) connection.
725 ///
726 /// # Arguments
727 ///
728 /// - `&mut Stream` - The `Stream` for the current request.
729 /// - `&mut Context` - The `Context` for the current request.
730 /// - `Request` - The initial request that established the keep-alive connection.
731 async fn handle_http_requests(&self, stream: &mut Stream, ctx: &mut Context, request: Request) {
732 if !self.request_hook(stream, ctx, request).await {
733 return;
734 }
735 loop {
736 let mut reused_request: Request = mem::take(ctx.get_mut_request());
737 match stream.try_fill_http_request(&mut reused_request).await {
738 Ok(()) => {
739 if !self.request_hook(stream, ctx, reused_request).await {
740 return;
741 }
742 }
743 Err(error) => {
744 ctx.set_request(reused_request);
745 self.handle_request_error(stream, ctx, &error).await;
746 return;
747 }
748 }
749 }
750 }
751
752 /// Handles a single client connection, determining whether it's an HTTP or WebSocket request.
753 ///
754 /// It reads the initial request from the stream and dispatches it to the appropriate hook.
755 ///
756 /// # Arguments
757 ///
758 /// - `&mut Stream` - The `Stream` for the current request.
759 /// - `&mut Context` - The `Context` for the current request.
760 ///
761 /// # Safety
762 ///
763 /// - The `ctx` is a valid pointer to a `Context` that was
764 /// originally created via `Box::into_raw` and is now being reclaimed.
765 async fn handle_connection(&self, stream: &mut Stream, ctx: &mut Context) {
766 match stream.try_get_http_request().await {
767 Ok(request) => {
768 self.handle_http_requests(stream, ctx, request).await;
769 }
770 Err(error) => {
771 self.handle_request_error(stream, ctx, &error).await;
772 }
773 }
774 unsafe {
775 let _: Box<Context> = Box::from_raw(ctx);
776 let _: Box<Stream> = Box::from_raw(stream);
777 }
778 }
779
780 /// Enters a loop to accept incoming TCP connections and spawn handlers for them.
781 ///
782 /// # Arguments
783 ///
784 /// - `&'static self` - The server instance that owns the accept loop.
785 /// - `&TcpListener` - A reference to the `TcpListener` to accept connections from.
786 async fn tcp_accept(&'static self, tcp_listener: &TcpListener) {
787 loop {
788 if let Ok((stream, _)) = tcp_listener.accept().await {
789 self.configure_stream(&stream);
790 let request_config: RequestConfig = *self.get_request_config();
791 let stream: &'static mut Stream =
792 Box::leak(Box::new(Stream::new(stream, request_config, false)));
793 let ctx: &'static mut Context = Box::leak(Box::new(Context::default()));
794 spawn(self.task_handler(
795 stream.into(),
796 ctx.into(),
797 self.handle_connection(stream, ctx),
798 ));
799 }
800 }
801 }
802
803 /// Starts the server, binds to the configured address, and begins listening for connections.
804 ///
805 /// This is the main entry point to launch the server. It will initialize the panic hook,
806 /// create a TCP listener, and then enter the connection acceptance loop in a background task.
807 ///
808 /// # Returns
809 ///
810 /// Returns a `Result` containing a shutdown function on success.
811 /// Calling this function will shut down the server by aborting its main task.
812 /// Returns an error if the server fails to start.
813 pub async fn run(&self) -> Result<ServerControlHook, Box<ServerError>> {
814 let bind_address: &String = self.get_server_config().get_address();
815 let tcp_listener: TcpListener = TcpListener::bind(&bind_address)
816 .await
817 .map_err(|error: io::Error| Box::new(ServerError::from(error)))?;
818 let server: &'static Self = unsafe { self.leak() };
819 let (wait_sender, wait_receiver) = channel(());
820 let (shutdown_sender, mut shutdown_receiver) = channel(());
821 let accept_connections: JoinHandle<()> = spawn(async move {
822 server.tcp_accept(&tcp_listener).await;
823 let _: Result<(), tokio::sync::watch::error::SendError<()>> = wait_sender.send(());
824 });
825 let wait_hook: ServerControlHookHandler<()> = Arc::new(move || {
826 let mut wait_receiver_clone: Receiver<()> = wait_receiver.clone();
827 Box::pin(async move {
828 let _: Result<(), tokio::sync::watch::error::RecvError> =
829 wait_receiver_clone.changed().await;
830 })
831 });
832 let shutdown_hook: ServerControlHookHandler<()> = Arc::new(move || {
833 let shutdown_sender_clone: Sender<()> = shutdown_sender.clone();
834 Box::pin(async move {
835 let _: Result<(), tokio::sync::watch::error::SendError<()>> =
836 shutdown_sender_clone.send(());
837 })
838 });
839 spawn(async move {
840 let _: Result<(), tokio::sync::watch::error::RecvError> =
841 shutdown_receiver.changed().await;
842 accept_connections.abort();
843 });
844 let mut server_control_hook: ServerControlHook = ServerControlHook::default();
845 server_control_hook.set_shutdown_hook(shutdown_hook);
846 server_control_hook.set_wait_hook(wait_hook);
847 Ok(server_control_hook)
848 }
849}