water_http 3.4.2-beta.4

fast web http framework that support http 1 and http 2 with very easy use
Documentation
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//
//
// pub (crate) mod connection;
// mod configurations;
// mod tls;
// mod sr_context;
// pub  use sr_context::*;
//
// #[doc(hidden)]
// pub mod errors;
// mod capsule;
// mod encoding;
// pub use encoding::*;
//
// pub use capsule::*;
//
// use std::io;
// use std::net::{SocketAddr, ToSocketAddrs};
// #[cfg(feature = "debugging")]
// use std::ops::Deref;
// #[cfg(feature = "support_tls")]
// use std::sync::{Arc};
// use tokio::runtime::Builder;
// use tokio::task::LocalSet;
// #[cfg(feature = "support_tls")]
// use tokio_rustls::TlsAcceptor;
// #[cfg(feature = "debugging")]
// use tracing::{debug};
// pub use configurations::*;
// use crate::server::connection::{ConnectionStream, WaterStream};
//
// pub (crate) static mut STATIC_SERVER_CONFIGURATION:Option<ServerConfigurations> = None;
// #[allow(static_mut_refs)]
// pub (crate)  fn get_server_config()->&'static ServerConfigurations{
//     unsafe  {
//         STATIC_SERVER_CONFIGURATION.as_ref().unwrap()
//     }
// }
//
//
// /// running given server configurations with Controller Root
// pub async fn run_server<Holder: Send + 'static + std::fmt::Debug, const HS: usize, const QS: usize>(
//     config: ServerConfigurations,
//     controller: &'static mut CapsuleWaterController<Holder, HS, QS>,
// ) {
//     // initialize global config (you may want to replace static mut with OnceCell in future)
//     unsafe { STATIC_SERVER_CONFIGURATION = Some(config); }
//     controller.set_up(String::new());
//     let pointer = controller as *const CapsuleWaterController<Holder, HS, QS>;
//     controller.____insure_binding();
//
//     // controller ref that is safe to read (we only pass as &'static)
//     let controller = unsafe { pointer.as_ref().unwrap() };
//
//     let conf = get_server_config();
//
//     // spawn one OS thread per address; each thread runs its own current-thread runtime + LocalSet
//     let mut handles = Vec::with_capacity(conf.addresses.len());
//     for address in conf.addresses.clone() {
//         // make static clones of controller pointer and address for the thread
//         let controller_arc = std::sync::Arc::new(StaticPtr(controller as *const CapsuleWaterController<Holder, HS, QS>));
//         let addr = address.clone();
//
//         let handle = std::thread::Builder::new()
//             .name(format!("listener-{}:{}", addr.0, addr.1))
//             .spawn({
//                 let controller_arc = controller_arc.clone();
//                 move || {
//                     let rt = Builder::new_current_thread().enable_all().build().unwrap();
//                     rt.block_on(async move {
//                         let controller_ref: &'static CapsuleWaterController<Holder, HS, QS> =
//                             unsafe { (*controller_arc).0.as_ref().unwrap() };
//                         let _ = run_server_with_address_in_thread(&addr, controller_ref).await;
//                     });
//                 }
//             })
//             .unwrap();
//
//         handles.push(handle);
//     }
//
//     // join all listener threads (this function is async but blocking join is acceptable here
//     // because we want to keep the server alive; alternatively you can detach threads as desired)
//     for h in handles {
//         let _ = h.join();
//     }
// }
// #[derive(Clone, Copy)]
// struct StaticPtr<T>(*const T);
//
// unsafe impl<T> Send for StaticPtr<T> {}
// unsafe impl<T> Sync for StaticPtr<T> {}
// /// This function is the async body that will be executed inside *the thread's runtime*
// /// and will create and run a LocalSet. It must be executed only from the thread that owns it.
// async fn run_server_with_address_in_thread<Holder: Send + 'static + std::fmt::Debug,
//     const HS: usize, const QS: usize>(
//     (address, port): &(String, u16),
//     controller: &'static CapsuleWaterController<Holder, HS, QS>,
// ) -> io::Result<()> {
//     // fetch server config
//     let server_config = get_server_config();
//
//     // bind inside this thread (we recreate socket here to ensure it is owned by this thread)
//     let address_string = format!("{}:{}", address, port);
//     let socket_address = (&address_string)
//         .to_socket_addrs()
//         .unwrap()
//         .next()
//         .expect("error while parsing address");
//
//     // create std listener with desired socket options (you can use socket2 if you need reuseport)
//     // We'll use tokio::net::TcpSocket here but create it inside the thread, it's fine.
//     let socket = match &socket_address {
//         SocketAddr::V4(_) => tokio::net::TcpSocket::new_v4(),
//         SocketAddr::V6(_) => tokio::net::TcpSocket::new_v6(),
//     }
//         .expect("can not create tcp socket from given address");
//
//     socket.set_reuseaddr(true).ok();
//     socket.set_nodelay(true).ok();
//     #[cfg(target_os = "linux")]
//     socket.set_reuseport(true).ok();
//     socket.bind(socket_address).expect("can not bind to given address");
//     let listener = socket
//         .listen(server_config.backlog)
//         .expect("tcp listen failed");
//
//     // build TLS acceptor if needed (clone inside thread)
//     #[cfg(feature = "support_tls")]
//         let mut tls_acceptor: Option<TlsAcceptor> = None;
//     #[cfg(feature = "support_tls")]
//     if let Some(tls_config) = server_config.tls_certificate.as_ref() {
//         if let Ok(server_tls_config) = tls::generate_tls_configurations(tls_config) {
//             tls_acceptor = Some(TlsAcceptor::from(Arc::new(server_tls_config)));
//         }
//     }
//     #[cfg(feature = "support_tls")]
//         let is_port_secure = server_config.tls_ports.contains(port) && tls_acceptor.is_some();
//
//     // Debugging counter - prefer AtomicUsize for light-weight counting (no await)
//     #[cfg(feature = "debugging")]
//     use std::sync::atomic::{AtomicUsize, Ordering};
//     #[cfg(feature = "debugging")]
//         let connections_count = Arc::new(AtomicUsize::new(0));
//
//     // create a LocalSet for this thread and run it
//     let local = LocalSet::new();
//     local
//         .run_until(async  {
//             loop {
//                 #[cfg(feature = "debugging")]
//                     let connections_count = connections_count.clone();
//
//                 // wait for a connection
//                 match listener.accept().await {
//                     Ok((stream, socket_addr)) => {
//                         #[cfg(feature = "debugging")]
//                         {
//                             // atomic increment
//                             connections_count.fetch_add(1, Ordering::Relaxed);
//                         }
//
//                         #[cfg(feature = "support_tls")]
//                             let tls = tls_acceptor.clone();
//
//                         // spawn the per-connection task as local (runs on same thread / LocalSet)
//                         local.spawn_local({
//                             // clone data for the async move block
//                             let controller = controller;
//                             let socket_address = socket_addr;
//                             async move {
//                                 // TLS path
//                                 #[cfg(feature = "support_tls")]
//                                 {
//                                     if is_port_secure {
//                                         if let Some(tls) = tls {
//                                             match tls.accept(stream).await {
//                                                 Ok(tls_stream) => {
//                                                     let connection = ConnectionStream::new(
//                                                         WaterStream::TLS(tls_stream),
//                                                         socket_address,
//                                                     );
//                                                     serve_connection(connection, controller).await;
//                                                 }
//                                                 Err(_e) => {
//                                                     // handle TLS accept error if needed
//                                                 }
//                                             }
//                                         }
//                                         #[cfg(feature = "debugging")]
//                                         {
//                                             // decrement counter
//                                             // (Atomic used, so no await)
//                                             // If you prefer logging, do it here.
//                                         }
//                                         return;
//                                     }
//                                 }
//
//                                 // Plain path
//                                 let connection =
//                                     ConnectionStream::new(WaterStream::TOStream(stream), socket_address);
//                                 serve_connection(connection, controller).await;
//
//                                 #[cfg(feature = "debugging")]
//                                 {
//                                     connections_count.fetch_sub(1, Ordering::Relaxed);
//                                 }
//                             }
//                         });
//                     }
//                     Err(e) => {
//                         // accept error; log or sleep a bit to avoid hot loop
//                         eprintln!("accept failed: {:?}", e);
//                         tokio::time::sleep(std::time::Duration::from_millis(10)).await;
//                     }
//                 }
//             }
//         })
//         .await;
//
//     Ok(())
// }
//
// #[inline(always)]
// async fn serve_connection<Holder: Send + 'static + std::fmt::Debug,
//     const HS: usize, const QS: usize,>(
//     connection: ConnectionStream,
//     controller: &'static CapsuleWaterController<Holder, HS, QS>,
// ) {
//     connection.serve(controller).await;
// }



pub (crate) mod connection;
mod configurations;
mod tls;
mod sr_context;

use std::collections::HashMap;
#[cfg(feature = "thread_shared_struct")]
use std::future::Future;
pub  use sr_context::*;

#[doc(hidden)]
pub mod errors;
mod capsule;
mod encoding;
#[cfg(not(feature = "use_io_uring"))]
mod io;
#[cfg(not(feature = "use_io_uring"))]
pub(crate) use io::*;
pub use encoding::*;

pub use capsule::*;

use std::io as stdio;
use std::net::{SocketAddr, ToSocketAddrs};
#[cfg(feature = "debugging")]
use std::ops::Deref;
#[cfg(feature = "cpu_affinity")]
use std::ops::DerefMut;
#[cfg(feature = "support_tls")]
use std::sync::{Arc};
#[cfg(not(feature = "use_tokio_send"))]
use tokio::task::LocalSet;
#[cfg(feature = "support_tls")]
use tokio_rustls::TlsAcceptor;
#[cfg(feature = "debugging")]
use tracing::{debug};
pub use configurations::*;
use crate::server::connection::{ConnectionStream, WaterStream};
use crate::server::matcher::{DynamicPathVec, Matcher, MatcherInitializer, PathHolder};

pub (crate) static mut STATIC_SERVER_CONFIGURATION:Option<ServerConfigurations> = None;
#[allow(static_mut_refs)]
pub (crate)  fn get_server_config()->&'static ServerConfigurations{
    unsafe  {
           STATIC_SERVER_CONFIGURATION.as_ref().unwrap()
    }
}


/// running given server configurations with Controller Root
pub  fn run_server<
    #[cfg(feature = "use_tokio_send")]
    Holder:Send + 'static + std::fmt::Debug,
    #[cfg(not(feature = "use_tokio_send"))]
    Holder,


    #[cfg(all(feature = "thread_shared_struct",not(feature = "use_tokio_send")))]
    SHARED:Clone,

    #[cfg(all(feature = "thread_shared_struct",feature = "use_tokio_send"))]
    SHARED:Clone + Send + 'static,
    const HS:usize,const QS:usize,

 >(
    config:ServerConfigurations,
    #[cfg(feature = "thread_shared_struct")]
    controller:&'static mut CapsuleWaterController<Holder,SHARED,HS,QS>,




    #[cfg(not(feature = "thread_shared_struct"))]
    controller:&'static mut CapsuleWaterController<Holder,HS,QS>,

    #[cfg(all(feature = "use_tokio_send",feature = "thread_shared_struct"))]
    shared_factory:fn()->std::pin::Pin<Box<dyn Future<Output=SHARED>+Send>>,
    #[cfg(all(feature = "thread_shared_struct",not(feature = "use_tokio_send")))]
    shared_factory:fn()->std::pin::Pin<Box<dyn Future<Output=SHARED>>>,

    #[cfg(feature = "thread_shared_struct")]
    static_path:&'static mut Option<HashMap<String,PathHolder<Holder,SHARED,HS,QS>>>,
    #[cfg(feature = "thread_shared_struct")]
    dynamic_path:&'static mut Option<HashMap<usize,DynamicPathVec<Holder,SHARED,HS,QS>>>,

    #[cfg(not(feature = "thread_shared_struct"))]
    static_path:&'static mut Option<HashMap<String,PathHolder<Holder,HS,QS>>>,
    #[cfg(not(feature = "thread_shared_struct"))]
    dynamic_path:&'static mut Option<HashMap<usize,DynamicPathVec<Holder,HS,QS>>>,
){
    unsafe  { STATIC_SERVER_CONFIGURATION = Some(config); }
    controller.set_up(String::new());
    #[cfg(not(feature = "thread_shared_struct"))]
    let pointer = controller as *const CapsuleWaterController<Holder,HS,QS>;


    *static_path = Some(HashMap::new());
    *dynamic_path = Some(HashMap::new());



    #[cfg(feature = "thread_shared_struct")]
    let pointer = controller as *const CapsuleWaterController<Holder,SHARED,HS,QS>;
    controller.____insure_binding();
    let sp = static_path.as_mut().unwrap();
    let dp = dynamic_path.as_mut().unwrap();

    _=MatcherInitializer::serialize(sp,dp,controller);



    let controller = unsafe {pointer.as_ref().unwrap()};
    let conf = get_server_config();

    #[cfg(feature = "use_tokio_send")]
    {
        #[cfg(feature = "debugging")]
            let mut workers_count = 0_usize;

        let rt = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .worker_threads(conf.worker_threads_count * 2)
            .build()
            .unwrap();
        let mut workers = vec![];
        for _ in 0..conf.worker_threads_count {

            for  address in conf.addresses.clone() {
                let matcher = Matcher::new(static_path.as_ref().unwrap(),dynamic_path.as_ref().unwrap());
                workers.push(
                    rt.spawn(async move {
                        #[cfg(feature = "debugging")]
                        {
                            debug!("listening on ip: {} port: {}",address.0,address.1);
                            workers_count +=1;
                            debug!("count of running workers {workers_count}");
                        }

                        #[cfg(feature = "thread_shared_struct")]
                        {
                            _=run_server_with_address(&address, controller,shared_factory,matcher).await;
                        }

                        #[cfg(not(feature = "thread_shared_struct"))]
                        {
                            _= crate::server::run_server_with_address(&address, controller, matcher).await;
                        }
                    })
                );
            }
        }

        rt.block_on(async move {
            for worker in workers {
                let _ = worker.await;
            }
        });
    }

    #[cfg(not(feature = "use_tokio_send"))]
    {
        let mut os_threads = vec![];

            #[cfg(feature = "cpu_affinity")]
            let cores = std::sync::Arc::new(
            if conf.core_affinity  {
                core_affinity::get_core_ids()
            } else {
                None
            }
        );
        #[cfg(feature = "cpu_affinity")]
        let  core_index = std::sync::Arc::new(std::sync::Mutex::new(0_usize));
        for _ in 0..conf.worker_threads_count {
            for address in &conf.addresses {
                let address = address.clone();
                let controller = controller;
                let matcher = Matcher::new(static_path.as_ref().unwrap(),dynamic_path.as_ref().unwrap());
                #[cfg(feature = "use_io_uring")]
                {

                    let thread = std::thread::spawn(move || {
                        tokio_uring::start(async move {
                            #[cfg(feature = "thread_shared_struct")]
                                let _ = crate::server::run_server_with_address(&address, controller,shared_factory,matcher).await;

                            #[cfg(not(feature = "thread_shared_struct"))]
                                let _ = crate::server::run_server_with_address(&address, controller,matcher).await;
                        });
                    });
                    os_threads.push(thread);

                }
                #[cfg(not(feature = "use_io_uring"))]
                {
                    #[cfg(feature = "cpu_affinity")]
                    let core_index = core_index.clone();
                    #[cfg(feature = "cpu_affinity")]
                        let  value = cores.clone();
                    let thread = std::thread::spawn(move || {
                        #[cfg(feature = "cpu_affinity")]
                        if let Some(core) = value.as_ref() {
                           let mut core_index_guard = core_index.lock();
                           let core_index = core_index_guard.as_mut().unwrap();
                           let m = core_index.deref_mut();
                           core_affinity::set_for_current((core[*m]).clone());
                           if *m + 1 >= core.len() {
                               *m = 0;
                           } else {
                               *m+=1;
                           }
                       }
                        let rt = tokio::runtime::Builder::new_current_thread()
                            .enable_all()
                            .max_blocking_threads(90)
                            .build()
                            .unwrap();

                        let local = LocalSet::new();

                        rt.block_on(async {
                            local.run_until(async {
                                #[cfg(feature = "thread_shared_struct")]
                                    let _ = run_server_with_address(&address, controller,shared_factory,matcher).await;

                                #[cfg(not(feature = "thread_shared_struct"))]
                                    let _ = run_server_with_address(&address, controller,matcher).await;
                            }).await;
                        });
                    });
                    os_threads.push(thread);
                }

            }
        }
        for thread in os_threads {
            let _ = thread.join();
        }
    }

}


#[cfg(feature = "use_io_uring")]
fn create_tokio_uring_listener(address: &str, port: &u16, backlog: u32) -> tokio_uring::net::TcpListener {
    let ad = format!("{address}:{port}");
    let listener = tokio_uring::net::TcpListener::bind(ad.parse().unwrap());
    listener.unwrap()
    // use tokio_uring::net::TcpListener;
    // use std::net::TcpListener as StdListener;
    // // Resolve address
    // let address_string = format!("{}:{}", address, port);
    // let socket_address: SocketAddr = address_string
    //     .to_socket_addrs()
    //     .unwrap()
    //     .next()
    //     .expect("error while parsing address");
    //
    // // Create std listener
    // let std_listener = match socket_address {
    //     SocketAddr::V4(_) => StdListener::bind(socket_address).expect("bind failed"),
    //     SocketAddr::V6(_) => StdListener::bind(socket_address).expect("bind failed"),
    // };
    //
    // // Configure options
    // std_listener
    //     .set_nonblocking(true)
    //     .expect("cannot set non-blocking");
    //
    // std_listener
    //     .set_reuse_address(true)
    //     .expect("cannot set reuse address");
    // #[cfg(target_os = "linux")]
    // std_listener
    //     .set_reuse_port(true)
    //     .expect("cannot set reuse port");
    //
    // // backlog is handled by bind+listen in std_listener
    // // On Rust 1.70+ TcpListener::bind already handles backlog internally
    //
    // // Convert to tokio-uring listener
    // TcpListener::from_std(std_listener).expect("cannot convert to tokio-uring listener")
}

#[inline(always)]
async fn run_server_with_address<
    #[cfg(feature = "use_tokio_send")]
    Holder:Send + 'static + std::fmt::Debug,

    #[cfg(not(feature = "use_tokio_send"))]
    Holder,



    #[cfg(all(feature = "thread_shared_struct",not(feature = "use_tokio_send")))]
    SHARED:Clone,

    #[cfg(all(feature = "thread_shared_struct",feature = "use_tokio_send"))]
    SHARED:Clone + Send + 'static,
    const HS:usize,const QS:usize,>(
    (address,port):&(String,u16),
    #[cfg(feature = "thread_shared_struct")]
    controller:&'static  CapsuleWaterController<Holder,SHARED,HS,QS>,
    #[cfg(not(feature = "thread_shared_struct"))]
    controller:&'static  CapsuleWaterController<Holder,HS,QS>,
    #[cfg(all(feature = "use_tokio_send",feature = "thread_shared_struct"))]
    shared_factory:fn()->std::pin::Pin<Box<dyn Future<Output=SHARED>+Send>>,
    #[cfg(all(feature = "thread_shared_struct",not(feature = "use_tokio_send")))]
    shared_factory:fn()->std::pin::Pin<Box<dyn Future<Output=SHARED>>>,

    #[cfg(feature = "thread_shared_struct")]
    matcher:Matcher<Holder,SHARED,HS,QS>,
    #[cfg(not(feature = "thread_shared_struct"))]
    matcher:Matcher<Holder,HS,QS>
)->stdio::Result<()>{
    // defining configuration object
    let server_config = get_server_config();


    #[cfg(feature = "use_io_uring")]
    let listener = create_tokio_uring_listener(address,port,server_config.backlog);

    let address_string = format!("{}:{}",address,port);
    let socket_address = (&address_string).to_socket_addrs()
        .unwrap().next()
        .expect("error while parsing address");

    #[cfg(not(feature = "use_io_uring"))]
    let listener = {
        // building tcp listener with defined backlog

        let socket = match &socket_address {
            SocketAddr::V4(_) => { tokio::net::TcpSocket::new_v4()}
            SocketAddr::V6(_) => {tokio::net::TcpSocket::new_v6()}
        }.expect("can not create tcp socket from given address");
        socket.set_reuseaddr(true).expect("can not set reuse address");
        socket.set_nodelay(true).expect("");
        #[cfg(target_os = "linux")]
        socket.set_reuseport(true).expect("could not reuse port on linux");
        socket.bind(socket_address).expect("can not bind to given address");
        socket.listen(
            server_config.backlog
        ).expect("")
    };

    #[cfg(feature = "thread_shared_struct")]
    // create shared factory
    let shared_struct:SHARED = shared_factory().await;

    // building tls acceptor
    #[cfg(feature = "support_tls")]
    let mut tls_acceptor:Option<TlsAcceptor> = None;
    #[cfg(feature = "support_tls")]
    if let Some(tls_config) = server_config.tls_certificate.as_ref() {
        let server_tls_config =
            tls::generate_tls_configurations(tls_config);
        if let Ok(server_tls_config ) = server_tls_config {
            tls_acceptor = Some(TlsAcceptor::from(Arc::new(server_tls_config)));
        }
    }

    #[cfg(feature = "support_tls")]
    let is_port_should_be_securely_handled=
        server_config.tls_ports.contains(port)
        && tls_acceptor.is_some();


    #[cfg(feature = "debugging")]
    use std::ops::DerefMut;
    #[cfg(feature = "debugging")]
    let  connections_count = std::sync::Arc::new(tokio::sync::Mutex::new(0_usize));



    loop {
        #[cfg(feature = "debugging")]
        let connections_count = connections_count.clone();
        if let Ok((stream,socket)) = listener.accept().await {
            #[cfg(feature = "debugging")]
            {
                let mut con = connections_count.lock().await;
                let m = con.deref_mut();
                *m +=1;
            }
            #[cfg(feature = "support_tls")]
            let tls = tls_acceptor.clone();

            #[cfg(feature = "use_tokio_send")]
            {
                #[cfg(feature = "thread_shared_struct")]
                    let shared_struct = shared_struct.clone();
                let matcher = matcher.clone();
                tokio::spawn(async move {
                    // checking if the current port should be handled
                    // with tls configurations if it`s exist
                    #[cfg(feature = "support_tls")]
                    {
                        if is_port_should_be_securely_handled {
                            let tls = tls.unwrap();
                            let tls_stream = tls.accept(stream).await;
                             if let Ok(tls_stream) = tls_stream {
                                let connection =  ConnectionStream::new(
                                    WaterStream::TLS(tls_stream),
                                    socket_address
                                );
                                #[cfg(feature = "thread_shared_struct")]
                                 serve_connection(connection,controller,shared_struct,matcher).await;
                                 #[cfg(not(feature = "thread_shared_struct"))]
                                serve_connection(connection, controller,matcher).await;
                            }
                            #[cfg(feature = "debugging")]
                            {
                                let mut con = connections_count.lock().await;
                                debug!("last connections count where port is not secure {:?}",con.deref());
                                let m = con.deref_mut();
                                if *m == 1 {
                                    *m = 0;
                                } else {
                                    *m -=1;
                                }

                            }
                            return ;
                        }
                    }

                    // handling connection normally
                    let connection
                        = ConnectionStream::new(WaterStream::TOStream(stream),socket);
                    #[cfg(feature = "thread_shared_struct")]
                    serve_connection(connection,controller,shared_struct,matcher).await;
                    #[cfg(not(feature = "thread_shared_struct"))]
                    serve_connection(connection, controller,matcher).await;
                    #[cfg(feature = "debugging")]
                    {
                        let mut con = connections_count.lock().await;
                        debug!("last connections count {:?}",con.deref());
                        let m = con.deref_mut();
                        if *m == 1 {
                            *m = 0;
                        } else {
                            *m -=1;
                        }

                    }
                });


            }

            #[cfg(not(feature = "use_tokio_send"))]
            {
                #[cfg(feature = "thread_shared_struct")]
                let shared_struct = shared_struct.clone();
                let matcher = matcher.clone();
                let future = async move {
                    // checking if the current port should be handled
                    // with tls configurations if it`s exist
                    #[cfg(feature = "support_tls")]
                    {
                        if is_port_should_be_securely_handled {
                            let tls = tls.unwrap();
                            let tls_stream = tls.accept(stream).await;
                            if let Ok(tls_stream) = tls_stream {
                                let connection =  ConnectionStream::new(
                                    WaterStream::TLS(tls_stream),
                                    socket_address
                                );
                                #[cfg(feature = "thread_shared_struct")]
                                crate::server::serve_connection(connection, controller, shared_struct,matcher).await;
                                #[cfg(not(feature = "thread_shared_struct"))]
                                serve_connection(connection, controller,matcher).await;
                            }
                            #[cfg(feature = "debugging")]
                            {
                                let mut con = connections_count.lock().await;
                                debug!("last connections count where port is not secure {:?}",con.deref());
                                let m = con.deref_mut();
                                if *m == 1 {
                                    *m = 0;
                                } else {
                                    *m -=1;
                                }

                            }
                            return ;
                        }
                    }

                    // handling connection normally
                    let connection
                        = ConnectionStream::new(WaterStream::TOStream(stream),socket);
                    #[cfg(feature = "thread_shared_struct")]
                    crate::server::serve_connection(connection, controller, shared_struct.clone(),matcher).await;
                    #[cfg(not(feature = "thread_shared_struct"))]
                    serve_connection(connection, controller,matcher).await;
                    #[cfg(feature = "debugging")]
                    {
                        let mut con = connections_count.lock().await;
                        debug!("last connections count {:?}",con.deref());
                        let m = con.deref_mut();
                        if *m == 1 {
                            *m = 0;
                        } else {
                            *m -=1;
                        }

                    }
                };

                #[cfg(feature = "use_io_uring")]
                tokio_uring::spawn(future);
                #[cfg(not(feature = "use_io_uring"))]
                tokio::task::spawn_local(future);
            }
        }
    }
}



#[inline(always)]
async fn serve_connection<
    #[cfg(feature = "use_tokio_send")]
    Holder:Send + 'static,

    #[cfg(all(feature = "thread_shared_struct",not(feature = "use_tokio_send")))]
    SHARED:Clone,


    #[cfg(all(feature = "thread_shared_struct",feature = "use_tokio_send"))]
    SHARED:Clone + Send + 'static,
    #[cfg(not(feature = "use_tokio_send"))]
    Holder,
    const HS:usize,const QS:usize,>
(connection:ConnectionStream,
 #[cfg(feature = "thread_shared_struct")]
 controller:&'static  CapsuleWaterController<Holder,SHARED,HS,QS>,
 #[cfg(not(feature = "thread_shared_struct"))]
 controller:&'static  CapsuleWaterController<Holder,HS,QS>,
 #[cfg(feature = "thread_shared_struct")]
 shared_factory:SHARED,
 #[cfg(feature = "thread_shared_struct")]
 matcher:Matcher<Holder,SHARED,HS,QS>,
 #[cfg(not(feature = "thread_shared_struct"))]
 matcher:Matcher<Holder,HS,QS>
){
    #[cfg(feature = "thread_shared_struct")]
    connection.serve(controller,shared_factory.clone(),matcher).await;
    #[cfg(not(feature = "thread_shared_struct"))]
    connection.serve(controller,matcher).await;
}