@ezetgalaxy/titan 26.12.3 → 26.12.4

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ezetgalaxy/titan",
3
- "version": "26.12.3",
3
+ "version": "26.12.4",
4
4
  "description": "Titan Planet is a JavaScript-first backend framework that embeds JS actions into a Rust + Axum server and ships as a single native binary. Routes are compiled to static metadata; only actions run in the embedded JS runtime. No Node.js. No event loop in production.",
5
5
  "license": "ISC",
6
6
  "author": "ezetgalaxy",
@@ -1,35 +1,34 @@
1
+ use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};
1
2
  use anyhow::Result;
2
3
  use axum::{
3
- Router,
4
- body::{Body, to_bytes},
4
+ body::{to_bytes, Body},
5
5
  extract::State,
6
6
  http::{Request, StatusCode},
7
7
  response::{IntoResponse, Json},
8
8
  routing::any,
9
+ Router,
9
10
  };
10
11
  use serde_json::Value;
11
- use std::time::Instant;
12
- use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};
13
12
  use tokio::net::TcpListener;
14
- use smallvec::SmallVec;
13
+ use std::time::Instant;
15
14
 
16
15
  mod utils;
17
16
 
18
- mod action_management;
19
17
  mod extensions;
20
- mod runtime;
18
+ mod action_management;
21
19
 
20
+ use utils::{blue, white, yellow, green, gray, red};
21
+ use extensions::{init_v8, inject_extensions};
22
22
  use action_management::{
23
- DynamicRoute, RouteVal, match_dynamic_route,
23
+ resolve_actions_dir, find_actions_dir, match_dynamic_route,
24
+ DynamicRoute, RouteVal
24
25
  };
25
- use runtime::RuntimeManager;
26
- use utils::{blue, gray, green, red, white, yellow};
27
26
 
28
27
  #[derive(Clone)]
29
28
  struct AppState {
30
29
  routes: Arc<HashMap<String, RouteVal>>,
31
30
  dynamic_routes: Arc<Vec<DynamicRoute>>,
32
- runtime: Arc<RuntimeManager>,
31
+ project_root: PathBuf,
33
32
  }
34
33
 
35
34
  // Root/dynamic handlers -----------------------------------------------------
@@ -46,6 +45,7 @@ async fn dynamic_handler_inner(
46
45
  State(state): State<AppState>,
47
46
  req: Request<Body>,
48
47
  ) -> impl IntoResponse {
48
+
49
49
  // ---------------------------
50
50
  // BASIC REQUEST INFO
51
51
  // ---------------------------
@@ -63,35 +63,45 @@ async fn dynamic_handler_inner(
63
63
  // ---------------------------
64
64
  // QUERY PARSING
65
65
  // ---------------------------
66
- let query_pairs: Vec<(String, String)> = req
66
+ let query: HashMap<String, String> = req
67
67
  .uri()
68
68
  .query()
69
69
  .map(|q| {
70
70
  q.split('&')
71
71
  .filter_map(|pair| {
72
72
  let mut it = pair.splitn(2, '=');
73
- Some((it.next()?.to_string(), it.next().unwrap_or("").to_string()))
73
+ Some((
74
+ it.next()?.to_string(),
75
+ it.next().unwrap_or("").to_string(),
76
+ ))
74
77
  })
75
78
  .collect()
76
79
  })
77
80
  .unwrap_or_default();
78
-
79
- let query_map: HashMap<String, String> = query_pairs.into_iter().collect();
80
81
 
81
82
  // ---------------------------
82
83
  // HEADERS & BODY
83
84
  // ---------------------------
84
85
  let (parts, body) = req.into_parts();
85
-
86
- let headers_map: HashMap<String, String> = parts
86
+
87
+ let headers = parts
87
88
  .headers
88
89
  .iter()
89
90
  .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
90
- .collect();
91
+ .collect::<HashMap<String, String>>();
91
92
 
92
93
  let body_bytes = match to_bytes(body, usize::MAX).await {
93
94
  Ok(b) => b,
94
- Err(_) => return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response(),
95
+ Err(_) => {
96
+ return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response()
97
+ }
98
+ };
99
+
100
+ let body_str = String::from_utf8_lossy(&body_bytes).to_string();
101
+ let body_json: Value = if body_str.is_empty() {
102
+ Value::Null
103
+ } else {
104
+ serde_json::from_str(&body_str).unwrap_or(Value::String(body_str))
95
105
  };
96
106
 
97
107
  // ---------------------------
@@ -109,32 +119,18 @@ async fn dynamic_handler_inner(
109
119
  action_name = Some(name);
110
120
  } else if route.r#type == "json" {
111
121
  let elapsed = start.elapsed();
112
- println!(
113
- "{} {} {} {}",
114
- blue("[Titan]"),
115
- white(&format!("{} {}", method, path)),
116
- white("→ json"),
117
- gray(&format!("in {:.2?}", elapsed))
118
- );
122
+ println!("{} {} {} {}", blue("[Titan]"), white(&format!("{} {}", method, path)), white("→ json"), gray(&format!("in {:.2?}", elapsed)));
119
123
  return Json(route.value.clone()).into_response();
120
124
  } else if let Some(s) = route.value.as_str() {
121
125
  let elapsed = start.elapsed();
122
- println!(
123
- "{} {} {} {}",
124
- blue("[Titan]"),
125
- white(&format!("{} {}", method, path)),
126
- white("→ reply"),
127
- gray(&format!("in {:.2?}", elapsed))
128
- );
126
+ println!("{} {} {} {}", blue("[Titan]"), white(&format!("{} {}", method, path)), white("→ reply"), gray(&format!("in {:.2?}", elapsed)));
129
127
  return s.to_string().into_response();
130
128
  }
131
129
  }
132
130
 
133
131
  // Dynamic route
134
132
  if action_name.is_none() {
135
- if let Some((action, p)) =
136
- match_dynamic_route(&method, &path, state.dynamic_routes.as_slice())
137
- {
133
+ if let Some((action, p)) = match_dynamic_route(&method, &path, state.dynamic_routes.as_slice()) {
138
134
  route_kind = "dynamic";
139
135
  route_label = action.clone();
140
136
  action_name = Some(action);
@@ -146,102 +142,179 @@ async fn dynamic_handler_inner(
146
142
  Some(a) => a,
147
143
  None => {
148
144
  let elapsed = start.elapsed();
149
- println!(
150
- "{} {} {} {}",
151
- blue("[Titan]"),
152
- white(&format!("{} {}", method, path)),
153
- white("→ 404"),
154
- gray(&format!("in {:.2?}", elapsed))
155
- );
145
+ println!("{} {} {} {}", blue("[Titan]"), white(&format!("{} {}", method, path)), white("→ 404"), gray(&format!("in {:.2?}", elapsed)));
156
146
  return (StatusCode::NOT_FOUND, "Not Found").into_response();
157
147
  }
158
148
  };
159
149
 
160
-
161
150
  // ---------------------------
162
- // EXECUTE IN V8 (WORKER POOL)
151
+ // LOAD ACTION
163
152
  // ---------------------------
164
-
165
- // OPTIMIZATION: Zero-Copy & Stack Allocation
166
- // 1. Headers/Params are collected into `SmallVec` (stack allocated if small).
167
- // 2. Body is passed as `Bytes` (ref-counted pointer), not copied.
168
- // 3. No JSON serialization happens here anymore. This saves ~60% CPU vs previous version.
169
-
170
- let headers_vec: SmallVec<[(String, String); 8]> = headers_map.into_iter().collect();
171
- let params_vec: SmallVec<[(String, String); 4]> = params.into_iter().collect();
172
- let query_vec: SmallVec<[(String, String); 4]> = query_map.into_iter().collect();
173
-
174
- // Pass raw bytes to worker if not empty
175
- let body_arg = if !body_bytes.is_empty() {
176
- Some(body_bytes)
177
- } else {
178
- None
153
+ let resolved = resolve_actions_dir();
154
+ let actions_dir = resolved.exists()
155
+ .then(|| resolved)
156
+ .or_else(|| find_actions_dir(&state.project_root))
157
+ .unwrap();
158
+
159
+ let mut action_path = actions_dir.join(format!("{}.jsbundle", action_name));
160
+ if !action_path.exists() {
161
+ let js_path = actions_dir.join(format!("{}.js", action_name));
162
+ if js_path.exists() {
163
+ action_path = js_path;
164
+ }
165
+ }
166
+
167
+ let js_code = match fs::read_to_string(&action_path) {
168
+ Ok(c) => c,
169
+ Err(_) => {
170
+ return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "Action bundle not found", "action": action_name}))).into_response()
171
+ }
179
172
  };
180
173
 
181
- // Dispatch to the optimized RuntimeManager
182
- // This sends a pointer-sized message through the ring buffer, triggering
183
- // the V8 thread to wake up and process the request immediately.
184
-
185
- let result_json = state
186
- .runtime
187
- .execute(
188
- action_name,
189
- method.clone(),
190
- path.clone(),
191
- body_arg,
192
- headers_vec,
193
- params_vec,
194
- query_vec
195
- )
196
- .await
197
- .unwrap_or_else(|e| serde_json::json!({"error": e}));
174
+ // ---------------------------
175
+ // EXECUTE IN V8
176
+ // ---------------------------
177
+ let env_json = std::env::vars().map(|(k, v)| (k, Value::String(v))).collect::<serde_json::Map<_, _>>();
178
+
179
+ let injected = format!(
180
+ r#"
181
+ globalThis.process = {{ env: {} }};
182
+ const __titan_req = {{
183
+ body: {},
184
+ method: "{}",
185
+ path: "{}",
186
+ headers: {},
187
+ params: {},
188
+ query: {}
189
+ }};
190
+ (function() {{
191
+ {}
192
+ }})(); // Run the bundle
193
+ // Call the action
194
+ if (typeof globalThis["{}"] === 'function') {{
195
+ globalThis["{}"](__titan_req);
196
+ }} else {{
197
+ throw new Error("Action function '{}' not found in bundle");
198
+ }}
199
+ "#,
200
+ Value::Object(env_json).to_string(),
201
+ body_json.to_string(),
202
+ method,
203
+ path,
204
+ serde_json::to_string(&headers).unwrap(),
205
+ serde_json::to_string(&params).unwrap(),
206
+ serde_json::to_string(&query).unwrap(),
207
+ js_code,
208
+ action_name,
209
+ action_name,
210
+ action_name
211
+ );
198
212
 
213
+ // Run V8 in a blocking task safely?
214
+ // Axum handlers are async. V8 operations should be blocking.
215
+ // We can use `task::spawn_blocking`.
216
+ let root = state.project_root.clone();
217
+ let action_name_for_v8 = action_name.clone();
218
+
219
+ let result_json: Value = tokio::task::spawn_blocking(move || {
220
+ let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
221
+ let handle_scope = &mut v8::HandleScope::new(isolate);
222
+ let context = v8::Context::new(handle_scope, v8::ContextOptions::default());
223
+ let scope = &mut v8::ContextScope::new(handle_scope, context);
224
+
225
+ let global = context.global(scope);
226
+
227
+ // Inject extensions (t.read, etc)
228
+ inject_extensions(scope, global);
229
+
230
+ // Set metadata globals
231
+ // Set metadata globals
232
+ let root_str = v8::String::new(scope, root.to_str().unwrap_or(".")).unwrap();
233
+ let root_key = v8::String::new(scope, "__titan_root").unwrap();
234
+ global.set(scope, root_key.into(), root_str.into());
235
+
236
+ let action_str = v8::String::new(scope, &action_name_for_v8).unwrap();
237
+ let action_key = v8::String::new(scope, "__titan_action").unwrap();
238
+ global.set(scope, action_key.into(), action_str.into());
239
+
240
+ let source = v8::String::new(scope, &injected).unwrap();
241
+
242
+ let try_catch = &mut v8::TryCatch::new(scope);
243
+
244
+ let script = match v8::Script::compile(try_catch, source, None) {
245
+ Some(s) => s,
246
+ None => {
247
+ let err = try_catch.message().unwrap();
248
+ let msg = err.get(try_catch).to_rust_string_lossy(try_catch);
249
+ return serde_json::json!({ "error": msg, "phase": "compile" });
250
+ }
251
+ };
252
+
253
+ let result = script.run(try_catch);
254
+
255
+ match result {
256
+ Some(val) => {
257
+ // Convert v8 Value to Serde JSON
258
+ // Minimal impl: stringify
259
+ let json_obj = v8::json::stringify(try_catch, val).unwrap();
260
+ let json_str = json_obj.to_rust_string_lossy(try_catch);
261
+ serde_json::from_str(&json_str).unwrap_or(Value::Null)
262
+ },
263
+ None => {
264
+ let err = try_catch.message().unwrap();
265
+ let msg = err.get(try_catch).to_rust_string_lossy(try_catch);
266
+ serde_json::json!({ "error": msg, "phase": "execution" })
267
+ }
268
+ }
269
+ }).await.unwrap_or(serde_json::json!({"error": "V8 task failed"}));
199
270
 
200
271
  // ---------------------------
201
272
  // FINAL LOG
202
273
  // ---------------------------
203
274
  let elapsed = start.elapsed();
204
-
275
+
205
276
  // Check for errors in result
206
277
  if let Some(err) = result_json.get("error") {
207
- println!(
208
- "{} {} {} {}",
209
- blue("[Titan]"),
210
- red(&format!("{} {}", method, path)),
211
- red("→ error"),
212
- gray(&format!("in {:.2?}", elapsed))
213
- );
214
- println!(
215
- "{} {} {} {}",
216
- blue("[Titan]"),
217
- red("Action Error:"),
218
- red(err.as_str().unwrap_or("Unknown")),
219
- gray(&format!("in {:.2?}", elapsed))
220
- );
278
+ println!("{} {} {} {}", blue("[Titan]"), red(&format!("{} {}", method, path)), red("→ error"), gray(&format!("in {:.2?}", elapsed)));
279
+ println!("{}", red(err.as_str().unwrap_or("Unknown")));
221
280
  return (StatusCode::INTERNAL_SERVER_ERROR, Json(result_json)).into_response();
222
281
  }
223
282
 
224
283
  match route_kind {
225
- "dynamic" => println!(
226
- "{} {} {} {} {} {}",
227
- blue("[Titan]"),
228
- green(&format!("{} {}", method, path)),
229
- white("→"),
230
- green(&route_label),
231
- white("(dynamic)"),
232
- gray(&format!("in {:.2?}", elapsed))
233
- ),
234
- "exact" => println!(
235
- "{} {} {} {} {}",
236
- blue("[Titan]"),
237
- white(&format!("{} {}", method, path)),
238
- white("→"),
239
- yellow(&route_label),
240
- gray(&format!("in {:.2?}", elapsed))
241
- ),
284
+ "dynamic" => println!("{} {} {} {} {} {}", blue("[Titan]"), green(&format!("{} {}", method, path)), white("→"), green(&route_label), white("(dynamic)"), gray(&format!("in {:.2?}", elapsed))),
285
+ "exact" => println!("{} {} {} {} {}", blue("[Titan]"), white(&format!("{} {}", method, path)), white("→"), yellow(&route_label), gray(&format!("in {:.2?}", elapsed))),
242
286
  _ => {}
243
287
  }
244
288
 
289
+ // Check for advanced response object from t.response defined in index.js
290
+ if result_json.get("_isResponse").and_then(|v| v.as_bool()).unwrap_or(false) {
291
+ let status_code = result_json.get("status")
292
+ .and_then(|v| v.as_u64())
293
+ .unwrap_or(200) as u16;
294
+
295
+ let status = StatusCode::from_u16(status_code).unwrap_or(StatusCode::OK);
296
+
297
+ let mut response_builder = axum::response::Response::builder()
298
+ .status(status);
299
+
300
+ // Add Headers
301
+ if let Some(headers) = result_json.get("headers").and_then(|v| v.as_object()) {
302
+ for (k, v) in headers {
303
+ if let Some(val_str) = v.as_str() {
304
+ response_builder = response_builder.header(k, val_str);
305
+ }
306
+ }
307
+ }
308
+
309
+ // Body
310
+ let body = result_json.get("body")
311
+ .and_then(|v| v.as_str())
312
+ .unwrap_or("")
313
+ .to_string();
314
+
315
+ return response_builder.body(Body::from(body)).unwrap().into_response();
316
+ }
317
+
245
318
  Json(result_json).into_response()
246
319
  }
247
320
 
@@ -251,6 +324,7 @@ async fn dynamic_handler_inner(
251
324
  #[tokio::main]
252
325
  async fn main() -> Result<()> {
253
326
  dotenvy::dotenv().ok();
327
+ init_v8(); // Init platform once
254
328
 
255
329
  // Load routes.json
256
330
  let raw = fs::read_to_string("./routes.json").unwrap_or_else(|_| "{}".to_string());
@@ -259,66 +333,42 @@ async fn main() -> Result<()> {
259
333
  let port = json["__config"]["port"].as_u64().unwrap_or(3000);
260
334
  let routes_json = json["routes"].clone();
261
335
  let map: HashMap<String, RouteVal> = serde_json::from_value(routes_json).unwrap_or_default();
262
- let dynamic_routes: Vec<DynamicRoute> =
263
- serde_json::from_value(json["__dynamic_routes"].clone()).unwrap_or_default();
264
-
265
- // Identify project root (where .ext or node_modules lives)
266
- let project_root = resolve_project_root();
336
+ let dynamic_routes: Vec<DynamicRoute> = serde_json::from_value(json["__dynamic_routes"].clone()).unwrap_or_default();
267
337
 
268
- // Load extensions (Load definitions globally)
269
- extensions::load_project_extensions(project_root.clone());
270
-
271
- // Initialize Runtime Manager (Worker Pool)
272
- let threads = num_cpus::get() * 4;
273
-
274
- let runtime_manager = Arc::new(RuntimeManager::new(project_root.clone(), threads));
338
+ // Project root heuristics
339
+ let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
340
+ // Ensure we find the 'app' directory as sibling if running from 'server'
341
+ let project_root = if cwd.join("../app").exists() {
342
+ cwd.join("../app")
343
+ } else {
344
+ cwd
345
+ };
275
346
 
276
347
  let state = AppState {
277
348
  routes: Arc::new(map),
278
349
  dynamic_routes: Arc::new(dynamic_routes),
279
- runtime: runtime_manager,
350
+ project_root: project_root.clone(),
280
351
  };
352
+
353
+ // Load extensions
354
+ extensions::load_project_extensions(project_root.clone());
281
355
 
282
356
  let app = Router::new()
357
+
283
358
  .route("/", any(root_route))
284
359
  .fallback(any(dynamic_route))
285
360
  .with_state(state);
286
361
 
287
362
  let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).await?;
288
363
 
289
-
290
- println!(
291
- "\x1b[38;5;39mTitan server running at:\x1b[0m http://localhost:{}",
292
- port
293
- );
364
+ println!("\n\x1b[38;5;208m████████╗██╗████████╗ █████╗ ███╗ ██╗");
365
+ println!("╚══██╔══╝██║╚══██╔══╝██╔══██╗████╗ ██║");
366
+ println!(" ██║ ██║ ██║ ███████║██╔██╗ ██║");
367
+ println!(" ██║ ██║ ██║ ██╔══██║██║╚██╗██║");
368
+ println!(" ██║ ██║ ██║ ██║ ██║██║ ╚████║");
369
+ println!(" ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝\x1b[0m\n");
370
+ println!("\x1b[38;5;39mTitan server running at:\x1b[0m http://localhost:{}", port);
294
371
 
295
372
  axum::serve(listener, app).await?;
296
373
  Ok(())
297
374
  }
298
-
299
- fn resolve_project_root() -> PathBuf {
300
- // 1. Check CWD (preferred for local dev/tooling)
301
- if let Ok(cwd) = std::env::current_dir() {
302
- if cwd.join("node_modules").exists()
303
- || cwd.join("package.json").exists()
304
- || cwd.join(".ext").exists()
305
- {
306
- return cwd;
307
- }
308
- }
309
-
310
- // 2. Check executable persistence (Docker / Production)
311
- // Walk up from the executable to find .ext or node_modules
312
- if let Ok(exe) = std::env::current_exe() {
313
- let mut current = exe.parent();
314
- while let Some(dir) = current {
315
- if dir.join(".ext").exists() || dir.join("node_modules").exists() {
316
- return dir.to_path_buf();
317
- }
318
- current = dir.parent();
319
- }
320
- }
321
-
322
- // 3. Fallback to CWD
323
- std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
324
- }