@t8n/ui 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,433 @@
1
+ use anyhow::Result;
2
+ use axum::{
3
+ Router,
4
+ body::{Body, to_bytes},
5
+ extract::State,
6
+ http::{Request, StatusCode},
7
+ response::{IntoResponse, Json},
8
+ routing::any,
9
+ };
10
+ use serde_json::Value;
11
+ use std::time::Instant;
12
+ use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};
13
+ use tokio::net::TcpListener;
14
+ use smallvec::SmallVec;
15
+
16
+ mod utils;
17
+
18
+ mod action_management;
19
+ mod extensions;
20
+ mod runtime;
21
+
22
+ use action_management::{
23
+ DynamicRoute, RouteVal, match_dynamic_route,
24
+ };
25
+ use runtime::RuntimeManager;
26
+ use utils::{blue, gray, green, red, white, yellow};
27
+
28
+ #[derive(Clone)]
29
+ struct AppState {
30
+ routes: Arc<HashMap<String, RouteVal>>,
31
+ dynamic_routes: Arc<Vec<DynamicRoute>>,
32
+ runtime: Arc<RuntimeManager>,
33
+ }
34
+
35
+ // Root/dynamic handlers -----------------------------------------------------
36
+
37
+ async fn root_route(state: State<AppState>, req: Request<Body>) -> impl IntoResponse {
38
+ dynamic_handler_inner(state, req).await
39
+ }
40
+
41
+ async fn dynamic_route(state: State<AppState>, req: Request<Body>) -> impl IntoResponse {
42
+ dynamic_handler_inner(state, req).await
43
+ }
44
+
45
+ async fn dynamic_handler_inner(
46
+ State(state): State<AppState>,
47
+ req: Request<Body>,
48
+ ) -> impl IntoResponse {
49
+ // ---------------------------
50
+ // BASIC REQUEST INFO
51
+ // ---------------------------
52
+ let method = req.method().as_str().to_uppercase();
53
+ let path = req.uri().path().to_string();
54
+ let strict_key = format!("{}:{}", method, path);
55
+ // Also try simple path for generic routes
56
+ // Check strict first, then simple path
57
+
58
+ // ---------------------------
59
+ // TIMER + LOG META
60
+ // ---------------------------
61
+ let start = Instant::now();
62
+ let mut route_label = String::from("not_found");
63
+ let mut route_kind = "none"; // exact | dynamic | reply
64
+
65
+ // ---------------------------
66
+ // QUERY PARSING
67
+ // ---------------------------
68
+ let query_pairs: Vec<(String, String)> = req
69
+ .uri()
70
+ .query()
71
+ .map(|q| {
72
+ q.split('&')
73
+ .filter_map(|pair| {
74
+ let mut it = pair.splitn(2, '=');
75
+ Some((it.next()?.to_string(), it.next().unwrap_or("").to_string()))
76
+ })
77
+ .collect()
78
+ })
79
+ .unwrap_or_default();
80
+
81
+ let query_map: HashMap<String, String> = query_pairs.into_iter().collect();
82
+
83
+ // ---------------------------
84
+ // HEADERS & BODY
85
+ // ---------------------------
86
+ let (parts, body) = req.into_parts();
87
+
88
+ let headers_map: HashMap<String, String> = parts
89
+ .headers
90
+ .iter()
91
+ .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
92
+ .collect();
93
+
94
+ let body_bytes = match to_bytes(body, usize::MAX).await {
95
+ Ok(b) => b,
96
+ Err(_) => return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response(),
97
+ };
98
+
99
+ // ---------------------------
100
+ // ROUTE RESOLUTION
101
+ // ---------------------------
102
+ let mut params: HashMap<String, String> = HashMap::new();
103
+ let mut action_name: Option<String> = None;
104
+
105
+ // Exact route
106
+ let route = state.routes.get(&strict_key).or_else(|| state.routes.get(&path));
107
+ if let Some(route) = route {
108
+ route_kind = "exact";
109
+ if route.r#type == "action" {
110
+ let name = route.value.as_str().unwrap_or("unknown").to_string();
111
+ route_label = name.clone();
112
+ action_name = Some(name);
113
+ } else if route.r#type == "json" {
114
+ let elapsed = start.elapsed();
115
+ println!(
116
+ "{} {} {} {}",
117
+ blue("[Titan]"),
118
+ white(&format!("{} {}", method, path)),
119
+ white("→ json"),
120
+ gray(&format!("in {:.2?}", elapsed))
121
+ );
122
+ return Json(route.value.clone()).into_response();
123
+ } else if let Some(s) = route.value.as_str() {
124
+ let elapsed = start.elapsed();
125
+ println!(
126
+ "{} {} {} {}",
127
+ blue("[Titan]"),
128
+ white(&format!("{} {}", method, path)),
129
+ white("→ reply"),
130
+ gray(&format!("in {:.2?}", elapsed))
131
+ );
132
+ return s.to_string().into_response();
133
+ }
134
+ }
135
+
136
+ // Dynamic route
137
+ if action_name.is_none() {
138
+ if let Some((action, p)) =
139
+ match_dynamic_route(&method, &path, state.dynamic_routes.as_slice())
140
+ {
141
+ route_kind = "dynamic";
142
+ route_label = action.clone();
143
+ action_name = Some(action);
144
+ params = p;
145
+ }
146
+ }
147
+
148
+ let action_name = match action_name {
149
+ Some(a) => a,
150
+ None => {
151
+ let elapsed = start.elapsed();
152
+ println!(
153
+ "{} {} {} {}",
154
+ blue("[Titan]"),
155
+ white(&format!("{} {}", method, path)),
156
+ white("→ 404"),
157
+ gray(&format!("in {:.2?}", elapsed))
158
+ );
159
+ return (StatusCode::NOT_FOUND, "Not Found").into_response();
160
+ }
161
+ };
162
+
163
+
164
+ // ---------------------------
165
+ // EXECUTE IN V8 (WORKER POOL)
166
+ // ---------------------------
167
+
168
+ // OPTIMIZATION: Zero-Copy & Stack Allocation
169
+ // 1. Headers/Params are collected into `SmallVec` (stack allocated if small).
170
+ // 2. Body is passed as `Bytes` (ref-counted pointer), not copied.
171
+ // 3. No JSON serialization happens here anymore. This saves ~60% CPU vs previous version.
172
+
173
+ let headers_vec: SmallVec<[(String, String); 8]> = headers_map.into_iter().collect();
174
+ let params_vec: SmallVec<[(String, String); 4]> = params.into_iter().collect();
175
+ let query_vec: SmallVec<[(String, String); 4]> = query_map.into_iter().collect();
176
+
177
+ // Pass raw bytes to worker if not empty
178
+ let body_arg = if !body_bytes.is_empty() {
179
+ Some(body_bytes)
180
+ } else {
181
+ None
182
+ };
183
+
184
+ // Dispatch to the optimized RuntimeManager
185
+ // This sends a pointer-sized message through the ring buffer, triggering
186
+ // the V8 thread to wake up and process the request immediately.
187
+
188
+ // Dispatch to the optimized RuntimeManager
189
+ let (mut result_json, timings) = state
190
+ .runtime
191
+ .execute(
192
+ action_name,
193
+ method.clone(),
194
+ path.clone(),
195
+ body_arg,
196
+ headers_vec,
197
+ params_vec,
198
+ query_vec
199
+ )
200
+ .await
201
+ .unwrap_or_else(|e| (serde_json::json!({"error": e}), vec![]));
202
+
203
+ // Construct Server-Timing header
204
+ let server_timing = timings.iter().enumerate().map(|(i, (name, duration))| {
205
+ format!("{}_{};dur={:.2}", name, i, duration)
206
+ }).collect::<Vec<_>>().join(", ");
207
+
208
+ // Inject timings into JSON if it's an object
209
+ if let Some(obj) = result_json.as_object_mut() {
210
+ obj.insert("_titanTimings".to_string(), serde_json::json!(timings));
211
+ }
212
+
213
+ // Prepare response
214
+ let mut response = if let Some(err) = result_json.get("error") {
215
+ let prefix = if !timings.is_empty() {
216
+ format!("{} {}", blue("[Titan"), blue("Drift]"))
217
+ } else {
218
+ blue("[Titan]").to_string()
219
+ };
220
+
221
+ println!(
222
+ "{} {} {} {}",
223
+ prefix,
224
+ red(&format!("{} {}", method, path)),
225
+ red("→ error"),
226
+ gray(&format!("in {:.2?}", start.elapsed()))
227
+ );
228
+ println!(
229
+ "{} {} {} {}",
230
+ prefix,
231
+ red("Action Error:"),
232
+ red(err.as_str().unwrap_or("Unknown")),
233
+ gray(&format!("in {:.2?}", start.elapsed()))
234
+ );
235
+ (StatusCode::INTERNAL_SERVER_ERROR, Json(result_json.clone())).into_response()
236
+ } else if let Some(is_resp) = result_json.get("_isResponse") {
237
+ if is_resp.as_bool().unwrap_or(false) {
238
+ let status_u16 = match result_json.get("status") {
239
+ Some(Value::Number(n)) => {
240
+ if let Some(u) = n.as_u64() {
241
+ u as u16
242
+ } else if let Some(f) = n.as_f64() {
243
+ f as u16
244
+ } else {
245
+ 200
246
+ }
247
+ }
248
+ _ => 200,
249
+ };
250
+
251
+ let status = StatusCode::from_u16(status_u16).unwrap_or(StatusCode::OK);
252
+ let mut builder = axum::http::Response::builder().status(status);
253
+
254
+ if let Some(hmap) = result_json.get("headers").and_then(|v| v.as_object()) {
255
+ for (k, v) in hmap {
256
+ if let Some(vs) = v.as_str() {
257
+ builder = builder.header(k, vs);
258
+ }
259
+ }
260
+ }
261
+
262
+ let mut is_redirect = false;
263
+
264
+ if let Some(location) = result_json.get("redirect") {
265
+ if let Some(url) = location.as_str() {
266
+ let mut final_status_u16 = status.as_u16();
267
+ // If it's a redirect call, ensure we use a 3xx status
268
+ if final_status_u16 < 300 || final_status_u16 > 399 {
269
+ final_status_u16 = 302; // Default to 302 Found
270
+ }
271
+
272
+ builder = builder.status(StatusCode::from_u16(final_status_u16).unwrap_or(StatusCode::FOUND))
273
+ .header("Location", url);
274
+ is_redirect = true;
275
+ }
276
+ }
277
+
278
+ let body_text = if is_redirect {
279
+ "".to_string()
280
+ } else {
281
+ match result_json.get("body") {
282
+ Some(Value::String(s)) => s.clone(),
283
+ Some(v) => v.to_string(),
284
+ None => "".to_string(),
285
+ }
286
+ };
287
+
288
+ builder.body(Body::from(body_text)).unwrap()
289
+ } else {
290
+ Json(result_json.clone()).into_response()
291
+ }
292
+ } else {
293
+ Json(result_json.clone()).into_response()
294
+ };
295
+
296
+ // Add Server-Timing Header
297
+ if !server_timing.is_empty() {
298
+ response.headers_mut().insert("Server-Timing", server_timing.parse().unwrap());
299
+ }
300
+
301
+ // ---------------------------
302
+ // FINAL LOG (SUCCESS)
303
+ // ---------------------------
304
+ let total_elapsed = start.elapsed();
305
+ let total_elapsed_ms = total_elapsed.as_secs_f64() * 1000.0;
306
+
307
+ let total_drift_ms: f64 = timings.iter()
308
+ .filter(|(n, _)| n == "drift" || n == "drift_error")
309
+ .map(|(_, d)| d)
310
+ .sum();
311
+
312
+ let compute_ms = (total_elapsed_ms - total_drift_ms).max(0.0);
313
+
314
+ let prefix = if !timings.is_empty() {
315
+ format!("{} {}", blue("[Titan"), blue("Drift]"))
316
+ } else {
317
+ blue("[Titan]").to_string()
318
+ };
319
+
320
+ let timing_info = if !timings.is_empty() {
321
+ gray(&format!("(active: {:.2}ms, drift: {:.2}ms) in {:.2?}", compute_ms, total_drift_ms, total_elapsed))
322
+ } else {
323
+ gray(&format!("in {:.2?}", total_elapsed))
324
+ };
325
+
326
+ match route_kind {
327
+ "dynamic" => println!(
328
+ "{} {} {} {} {} {}",
329
+ prefix,
330
+ green(&format!("{} {}", method, path)),
331
+ white("→"),
332
+ green(&route_label),
333
+ white("(dynamic)"),
334
+ timing_info
335
+ ),
336
+ "exact" => println!(
337
+ "{} {} {} {} {}",
338
+ prefix,
339
+ white(&format!("{} {}", method, path)),
340
+ white("→"),
341
+ yellow(&route_label),
342
+ timing_info
343
+ ),
344
+ _ => {}
345
+ }
346
+
347
+ response
348
+ }
349
+
350
+
351
+ // Entrypoint ---------------------------------------------------------------
352
+
353
+ #[tokio::main]
354
+ async fn main() -> Result<()> {
355
+ dotenvy::dotenv().ok();
356
+
357
+ // Load routes.json
358
+ let raw = fs::read_to_string("./routes.json").unwrap_or_else(|_| "{}".to_string());
359
+ let json: Value = serde_json::from_str(&raw).unwrap_or_default();
360
+
361
+ let port = json["__config"]["port"].as_u64().unwrap_or(3000);
362
+ let thread_count = json["__config"]["threads"].as_u64();
363
+ let routes_json = json["routes"].clone();
364
+ let map: HashMap<String, RouteVal> = serde_json::from_value(routes_json).unwrap_or_default();
365
+ let dynamic_routes: Vec<DynamicRoute> =
366
+ serde_json::from_value(json["__dynamic_routes"].clone()).unwrap_or_default();
367
+
368
+ // Identify project root (where .ext or node_modules lives)
369
+ let project_root = resolve_project_root();
370
+
371
+ // Load extensions (Load definitions globally)
372
+ extensions::load_project_extensions(project_root.clone());
373
+
374
+ // Initialize Runtime Manager (Worker Pool)
375
+ let threads = match thread_count {
376
+ Some(t) if t > 0 => t as usize,
377
+ _ => num_cpus::get() * 4, // default
378
+ };
379
+
380
+
381
+ let runtime_manager = Arc::new(RuntimeManager::new(project_root.clone(), threads));
382
+
383
+ let state = AppState {
384
+ routes: Arc::new(map),
385
+ dynamic_routes: Arc::new(dynamic_routes),
386
+ runtime: runtime_manager,
387
+ };
388
+
389
+ let app = Router::new()
390
+ .route("/", any(root_route))
391
+ .fallback(any(dynamic_route))
392
+ .with_state(state);
393
+
394
+ let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).await?;
395
+
396
+
397
+ println!(
398
+ "\x1b[38;5;39mTitan server running at:\x1b[0m http://localhost:{} \x1b[90m(Threads: {})\x1b[0m",
399
+ port,
400
+ threads
401
+ );
402
+
403
+
404
+ axum::serve(listener, app).await?;
405
+ Ok(())
406
+ }
407
+
408
+ fn resolve_project_root() -> PathBuf {
409
+ // 1. Check CWD (preferred for local dev/tooling)
410
+ if let Ok(cwd) = std::env::current_dir() {
411
+ if cwd.join("node_modules").exists()
412
+ || cwd.join("package.json").exists()
413
+ || cwd.join(".ext").exists()
414
+ {
415
+ return cwd;
416
+ }
417
+ }
418
+
419
+ // 2. Check executable persistence (Docker / Production)
420
+ // Walk up from the executable to find .ext or node_modules
421
+ if let Ok(exe) = std::env::current_exe() {
422
+ let mut current = exe.parent();
423
+ while let Some(dir) = current {
424
+ if dir.join(".ext").exists() || dir.join("node_modules").exists() {
425
+ return dir.to_path_buf();
426
+ }
427
+ current = dir.parent();
428
+ }
429
+ }
430
+
431
+ // 3. Fallback to CWD
432
+ std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
433
+ }