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
use crate::configuration::ApplicationBuilder;
use crate::container::Container;
use crate::http::Request;
use crate::routing::Router;
use crate::support::ServiceProvider;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
const MAX_REQUEST_BYTES: usize = 64 * 1024;
#[derive(Default)]
pub struct Scheduler {}
#[derive(Default)]
pub struct Application {
base_path: String,
pub container: Container,
pub router: Router,
pub scheduler: Scheduler,
pub providers: Vec<Box<dyn ServiceProvider>>,
booted: bool,
}
impl Application {
pub fn new(base_path: &str) -> Self {
Self {
base_path: base_path.to_string(),
container: Container::new(),
router: Router::new(),
providers: Vec::new(),
scheduler: Scheduler::default(),
booted: false,
}
}
pub fn configure(base_path: &str) -> ApplicationBuilder {
ApplicationBuilder::new(Self::new(base_path))
// .with_kernels()
// .with_events()
}
/// Register a service provider with the application.
/// This immediately calls the provider's `register` method.
pub async fn register_provider<P: ServiceProvider + 'static>(mut self, provider: P) -> Self {
let provider = Box::new(provider);
// 1. Run the register method immediately upon binding
provider.register(&mut self.container).await;
// 2. If the application is already booted, boot this provider immediately
if self.booted {
provider.boot(&self.container, &mut self.router).await;
}
self.providers.push(provider);
self
}
/// Boot the application's service providers.
/// This loops through all registered providers and calls their `boot` methods.
pub async fn boot(&mut self) {
if self.booted {
return;
}
for provider in &self.providers {
provider.boot(&self.container, &mut self.router).await;
}
self.booted = true;
}
/// Start the TCP Listener (analogous to public/index.php `$kernel->handle()`)
pub async fn listen(
mut self,
host: String,
port: u16,
) -> Result<(), Box<dyn std::error::Error>> {
// 1. Ensure all providers are booted before accepting traffic
self.boot().await;
let addr = format!("{}:{}", host, port);
let listener = TcpListener::bind(&addr).await?;
println!("🚀 Ruvel native server running on http://{}", addr);
let router = Arc::new(self.router);
loop {
let (mut socket, _) = listener.accept().await?;
let _ = socket.set_nodelay(true);
let router_clone = Arc::clone(&router);
tokio::spawn(async move {
// 1. Fixed-size chunk for reading from the OS network stack
let mut chunk = [0u8; 2048];
// 2. Buffer for assembling fragmented packets and handling pipelining
let mut read_buffer = Vec::with_capacity(2048);
// 3. Pre-allocated response buffer (used repeatedly for keep-alive)
let mut response_buffer = Vec::with_capacity(1024);
'connection: loop {
// Read directly from the raw TCP socket
match socket.read(&mut chunk).await {
Ok(0) => break, // Client gracefully closed connection
Ok(n) => {
// Security: Prevent buffer overflow / memory exhaustion
if read_buffer.len().saturating_add(n) > MAX_REQUEST_BYTES {
break;
}
read_buffer.extend_from_slice(&chunk[..n]);
let mut offset = 0;
loop {
if offset >= read_buffer.len() {
// Fully consumed. `clear` keeps the allocation for the next read.
read_buffer.clear();
break;
}
// Attempt to parse a complete request from the unconsumed tail.
let (req, consumed) = match Request::parse(&read_buffer[offset..]) {
Ok(Some(parsed)) => parsed,
Ok(None) => {
// One shift per read, and only when a previous request
// in this read left a partial one behind.
if offset > 0 {
read_buffer.drain(..offset);
}
break;
}
Err(()) => break 'connection, // Malformed payload, drop connection
};
let Some(end) = offset.checked_add(consumed) else {
break 'connection;
};
if consumed == 0 || end > read_buffer.len() {
break 'connection;
}
// Dispatch to the Router
let response = router_clone.dispatch(req).await;
// Reset the response buffer (keeps capacity)
response_buffer.clear();
// Format your response into the contiguous Vec<u8>
response.write_to(&mut response_buffer);
// Performance: A single write_all syscall directly to the kernel,
// completely bypassing the overhead of BufWriter.
if socket.write_all(&response_buffer).await.is_err() {
break 'connection;
}
offset = end;
}
}
Err(_) => break, // Network error
}
}
});
}
}
}