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
use std::env;
use std::error::Error;
use std::sync::Arc;
use crate::configuration::ApplicationBuilder;
use crate::container::Container;
use crate::database::{DatabaseManager, DatabaseServiceProvider};
use crate::events::EventServiceProvider;
use crate::http::{Kernel, Request};
use crate::routing::{Router, RoutingServiceProvider};
use crate::support::{LogServiceProvider, ServiceProvider};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
const MAX_REQUEST_BYTES: usize = 64 * 1024;
const READ_CHUNK_SIZE: usize = 8 * 1024; // 8 KiB read buffer to match standard MTU/TCP windows
#[derive(Default)]
pub struct Scheduler {}
pub struct Application {
pub container: Container,
pub scheduler: Scheduler,
pub providers: Vec<Box<dyn ServiceProvider>>,
booted: bool,
}
impl Default for Application {
fn default() -> Self {
Self::new("")
}
}
impl Application {
pub fn new(_base_path: &str) -> Self {
let mut app = Self {
container: Container::new(),
providers: Vec::new(),
scheduler: Scheduler::default(),
booted: false,
};
app.register_base_bindings();
app.register_base_service_providers();
app.register_core_container_aliases();
app
}
/// Register the basic bindings into the container.
pub fn register_base_bindings(&mut self) {
// Register static container instance
self.container.instance(Container::new());
}
/// Register the base service providers for the application.
pub fn register_base_service_providers(&mut self) {
self.register_provider(EventServiceProvider);
self.register_provider(LogServiceProvider);
self.register_provider(RoutingServiceProvider);
let db_provider = Box::new(DatabaseServiceProvider);
// Synchronously initialize the database service provider bindings into container
let db_manager = Arc::new(DatabaseManager::new());
DatabaseManager::register_global(Arc::clone(&db_manager));
self.container.instance((*db_manager).clone());
self.providers.push(db_provider);
}
/// Register the core class aliases in the container.
pub fn register_core_container_aliases(&mut self) {
self.container.alias::<Container>("app");
self.container.alias::<DatabaseManager>("db");
self.container.alias::<Router>("router");
self.container.alias::<Kernel>("kernel");
self.container.alias::<EventServiceProvider>("events");
self.container.alias::<LogServiceProvider>("log");
}
/// Configure the application and register default kernels.
pub fn configure(base_path: &str) -> ApplicationBuilder {
ApplicationBuilder::new(Self::new(base_path)).with_kernels()
}
/// Register a service provider with the application.
/// This immediately calls the provider's `register` method.
pub fn register_provider<P: ServiceProvider + 'static>(&mut self, provider: P) -> &mut Self {
let provider = Box::new(provider);
// 1. Run the register method immediately upon binding
provider.register(&mut self.container);
// 2. If the application is already booted, boot this provider immediately
if self.booted {
let kernel = self
.make::<Kernel>()
.expect("Kernel not found in container");
let mut router_clone = (*kernel.get_router()).clone();
provider.boot(&self.container, &mut router_clone);
kernel.set_router(Arc::new(router_clone));
}
self.providers.push(provider);
self
}
/// Boot the application's service providers.
/// This loops through all registered providers and calls their `boot` methods.
pub fn boot(&mut self) {
if self.booted {
return;
}
let kernel = self
.make::<Kernel>()
.expect("Kernel not found in container");
let mut router_clone = (*kernel.get_router()).clone();
for provider in &self.providers {
provider.boot(&self.container, &mut router_clone);
}
let final_router = Arc::new(router_clone);
kernel.set_router(Arc::clone(&final_router));
self.container.instance((*final_router).clone());
self.booted = true;
}
/// Resolve an instance of type `T` from the application container.
/// Equivalent to Laravel's `$app->make()`.
pub fn make<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, String> {
self.container.make()
}
pub async fn handle_requests(self) -> Result<(), Box<dyn Error>> {
self.listen(
env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_string()),
env::var("PORT")
.unwrap_or_else(|_| "7883".to_string())
.parse::<u16>()
.unwrap(),
)
.await
}
/// Start the TCP listener (analogous to `public/index.php` `$kernel->handle()`).
///
/// Each accepted connection maintains a streaming read buffer (`read_buffer`) and cursor
/// (`read_pos`) to handle keep-alive, HTTP/1.1 pipelining, and arbitrary TCP fragmentation:
/// - When [`Request::parse`] returns `Ok(None)`, unread bytes at `&read_buffer[read_pos..]`
/// remain buffered so the next `read_buf` call can append trailing TCP fragments.
/// - When [`Request::parse`] returns `Ok(Some((req, consumed)))`, `read_pos` advances by
/// `consumed` and any remaining bytes in `read_buffer` are immediately parsed as pipelined
/// requests before flushing `response_buffer` in a single `write_all` call.
/// - When [`Request::parse`] returns `Err(())`, any already-queued pipelined responses plus an
/// `HTTP/1.1 400 Bad Request` (`Connection: close`) response are flushed and the socket closes.
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();
let addr = format!("{}:{}", host, port);
let listener = TcpListener::bind(&addr).await?;
println!("🚀 Ruvel native server running on http://{}", addr);
// Resolve the HTTP Kernel directly from the container
let kernel: Arc<Kernel> = match self.make::<Kernel>() {
Ok(k) => k,
Err(e) => panic!("Failed to resolve Kernel from container: {}", e),
};
loop {
let (mut socket, _) = listener.accept().await?;
let _ = socket.set_nodelay(true);
let kernel_clone = Arc::clone(&kernel);
tokio::spawn(async move {
let mut read_buffer = Vec::with_capacity(READ_CHUNK_SIZE);
let mut read_pos = 0usize;
// Pre-allocated response buffer reused across pipelined requests
let mut response_buffer = Vec::with_capacity(4096);
'connection: loop {
// Compact consumed prefix bytes so unread partial fragments stay contiguous
// without letting `read_buffer` grow unbounded across keep-alive requests.
if read_pos >= read_buffer.len() {
read_buffer.clear();
read_pos = 0;
} else if read_pos > 0
&& (read_pos * 2 >= read_buffer.len()
|| read_buffer.len() >= MAX_REQUEST_BYTES)
{
let remaining = read_buffer.len() - read_pos;
read_buffer.copy_within(read_pos.., 0);
read_buffer.truncate(remaining);
read_pos = 0;
}
let remaining_budget = MAX_REQUEST_BYTES.saturating_sub(read_buffer.len());
if remaining_budget == 0 {
break;
}
let want = READ_CHUNK_SIZE.min(remaining_budget);
if read_buffer.capacity() - read_buffer.len() < want {
read_buffer.reserve(want);
}
match socket.read_buf(&mut read_buffer).await {
Ok(0) => break, // Client gracefully closed connection
Ok(_) => {
if read_buffer.len() > MAX_REQUEST_BYTES {
break;
}
let mut responses_queued = 0;
while read_pos < read_buffer.len() {
let (req, consumed) = match Request::parse(&read_buffer[read_pos..])
{
Ok(Some(parsed)) => parsed,
// Partial frame (split headers, Content-Length body, or chunked
// payload): preserve `&read_buffer[read_pos..]` for the next read.
Ok(None) => break,
Err(()) => {
response_buffer.extend_from_slice(
b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
);
let _ = socket.write_all(&response_buffer).await;
break 'connection;
}
};
let Some(end) = read_pos.checked_add(consumed) else {
break 'connection;
};
if consumed == 0 || end > read_buffer.len() {
break 'connection;
};
// Dispatch request through HTTP Kernel
let response = kernel_clone.handle(req).await;
// Serialize response into the write buffer
response.write_to(&mut response_buffer);
responses_queued += 1;
read_pos = end;
}
if read_pos >= read_buffer.len() {
read_buffer.clear();
read_pos = 0;
}
// Batched flush: If any responses were queued from this read chunk (pipelining),
// flush them all in one single write_all syscall to the OS socket.
if responses_queued > 0 {
if socket.write_all(&response_buffer).await.is_err() {
break 'connection;
}
response_buffer.clear();
if response_buffer.capacity() > 64 * 1024 {
response_buffer.shrink_to(4096);
}
}
}
Err(_) => break, // Network error
}
}
});
}
}
}