titanpl 4.0.2 → 7.0.0-beta
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 +11 -5
- package/packages/cli/index.js +25 -11
- package/packages/cli/package.json +5 -5
- package/packages/cli/src/commands/build-ext.js +157 -0
- package/packages/cli/src/commands/build.js +12 -0
- package/packages/cli/src/commands/create.js +160 -0
- package/packages/cli/src/commands/init.js +5 -11
- package/packages/cli/src/commands/run-ext.js +104 -0
- package/packages/engine-darwin-arm64/README.md +0 -2
- package/packages/engine-darwin-arm64/package.json +1 -1
- package/packages/engine-linux-x64/README.md +0 -2
- package/packages/engine-linux-x64/package.json +1 -1
- package/packages/engine-win32-x64/README.md +0 -1
- package/packages/engine-win32-x64/bin/titan-server.exe +0 -0
- package/packages/engine-win32-x64/package.json +1 -1
- package/packages/native/README.md +0 -1
- package/packages/native/index.d.ts +10 -0
- package/packages/native/index.js +4 -0
- package/packages/native/package.json +1 -1
- package/packages/native/t.native.d.ts +175 -44
- package/packages/packet/README.md +0 -1
- package/packages/packet/index.js +19 -2
- package/packages/packet/package.json +1 -1
- package/packages/route/README.md +21 -0
- package/packages/route/index.d.ts +1 -0
- package/packages/route/index.js +22 -0
- package/packages/route/package.json +1 -1
- package/packages/sdk/index.js +2 -0
- package/packages/sdk/package.json +18 -0
- package/packages/sdk/test/index.js +120 -0
- package/templates/common/Dockerfile +9 -45
- package/templates/common/_tanfig.json +17 -13
- package/templates/extension/index.d.ts +26 -22
- package/templates/extension/index.js +15 -15
- package/templates/extension/native/Cargo.toml +5 -3
- package/templates/extension/native/src/lib.rs +2 -3
- package/templates/extension/package.json +10 -20
- package/templates/extension/titan.json +5 -16
- package/templates/extension/utils/registerExtension.js +44 -0
- package/templates/js/package.json +8 -8
- package/templates/rust-js/package.json +4 -4
- package/templates/rust-ts/package.json +4 -4
- package/templates/ts/package.json +8 -8
- package/templates/common/app/t.native.d.ts +0 -2043
- package/templates/common/app/t.native.js +0 -39
- package/titanpl-sdk/LICENSE +0 -15
- package/titanpl-sdk/README.md +0 -111
- package/titanpl-sdk/assets/titanpl-sdk.png +0 -0
- package/titanpl-sdk/bin/run.js +0 -274
- package/titanpl-sdk/index.js +0 -5
- package/titanpl-sdk/package-lock.json +0 -28
- package/titanpl-sdk/package.json +0 -40
- package/titanpl-sdk/templates/app/actions/hello.js +0 -5
- package/titanpl-sdk/templates/app/app.js +0 -7
- package/titanpl-sdk/templates/jsconfig.json +0 -19
- package/titanpl-sdk/templates/server/Cargo.toml +0 -52
- package/titanpl-sdk/templates/server/src/action_management.rs +0 -175
- package/titanpl-sdk/templates/server/src/errors.rs +0 -12
- package/titanpl-sdk/templates/server/src/extensions/builtin.rs +0 -1055
- package/titanpl-sdk/templates/server/src/extensions/external.rs +0 -338
- package/titanpl-sdk/templates/server/src/extensions/mod.rs +0 -580
- package/titanpl-sdk/templates/server/src/extensions/titan_core.js +0 -249
- package/titanpl-sdk/templates/server/src/fast_path.rs +0 -719
- package/titanpl-sdk/templates/server/src/main.rs +0 -607
- package/titanpl-sdk/templates/server/src/runtime.rs +0 -284
- package/titanpl-sdk/templates/server/src/utils.rs +0 -33
- package/titanpl-sdk/templates/titan/bundle.js +0 -259
- package/titanpl-sdk/templates/titan/dev.js +0 -390
- package/titanpl-sdk/templates/titan/error-box.js +0 -277
- package/titanpl-sdk/templates/titan/titan.js +0 -129
|
@@ -1,1055 +0,0 @@
|
|
|
1
|
-
//! Built-in V8 extensions and native bindings.
|
|
2
|
-
//!
|
|
3
|
-
//! Includes:
|
|
4
|
-
//! - Native API bindings (t.read, t.log, etc.)
|
|
5
|
-
//! - JWT utilities
|
|
6
|
-
//! - Password hashing
|
|
7
|
-
//! - Database connection pool
|
|
8
|
-
//! - Shared context
|
|
9
|
-
|
|
10
|
-
use v8;
|
|
11
|
-
use reqwest::{
|
|
12
|
-
blocking::Client,
|
|
13
|
-
header::{HeaderMap, HeaderName, HeaderValue},
|
|
14
|
-
};
|
|
15
|
-
use std::path::PathBuf;
|
|
16
|
-
use std::time::{SystemTime, UNIX_EPOCH};
|
|
17
|
-
use serde_json::Value;
|
|
18
|
-
use jsonwebtoken::{encode, decode, Header, EncodingKey, DecodingKey, Validation};
|
|
19
|
-
use bcrypt::{hash, verify, DEFAULT_COST};
|
|
20
|
-
use std::sync::OnceLock;
|
|
21
|
-
use deadpool_postgres::{Manager, Pool};
|
|
22
|
-
use tokio_postgres::{NoTls, Config};
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
use crate::utils::{blue, gray, red, parse_expires_in};
|
|
26
|
-
use super::{TitanRuntime, v8_str, v8_to_string, throw, ShareContextStore};
|
|
27
|
-
|
|
28
|
-
const TITAN_CORE_JS: &str = include_str!("titan_core.js");
|
|
29
|
-
|
|
30
|
-
// Database connection pool
|
|
31
|
-
static DB_POOL: OnceLock<Pool> = OnceLock::new();
|
|
32
|
-
static HTTP_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
|
|
33
|
-
|
|
34
|
-
fn get_http_client() -> &'static reqwest::Client {
|
|
35
|
-
HTTP_CLIENT.get_or_init(|| {
|
|
36
|
-
reqwest::Client::builder()
|
|
37
|
-
.use_rustls_tls()
|
|
38
|
-
.tcp_nodelay(true)
|
|
39
|
-
.user_agent("TitanPL/1.0")
|
|
40
|
-
.build()
|
|
41
|
-
.unwrap_or_else(|_| reqwest::Client::new())
|
|
42
|
-
})
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
pub fn inject_builtin_extensions(scope: &mut v8::HandleScope, global: v8::Local<v8::Object>, t_obj: v8::Local<v8::Object>) {
|
|
47
|
-
// 1. Native API Bindings
|
|
48
|
-
|
|
49
|
-
// defineAction (Native side)
|
|
50
|
-
let def_fn = v8::Function::new(scope, native_define_action).unwrap();
|
|
51
|
-
let def_key = v8_str(scope, "defineAction");
|
|
52
|
-
global.set(scope, def_key.into(), def_fn.into());
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
// t.read
|
|
56
|
-
let read_fn = v8::Function::new(scope, native_read).unwrap();
|
|
57
|
-
let read_key = v8_str(scope, "read");
|
|
58
|
-
t_obj.set(scope, read_key.into(), read_fn.into());
|
|
59
|
-
|
|
60
|
-
// t.decodeUtf8
|
|
61
|
-
let dec_fn = v8::Function::new(scope, native_decode_utf8).unwrap();
|
|
62
|
-
let dec_key = v8_str(scope, "decodeUtf8");
|
|
63
|
-
t_obj.set(scope, dec_key.into(), dec_fn.into());
|
|
64
|
-
|
|
65
|
-
// t.log
|
|
66
|
-
let log_fn = v8::Function::new(scope, native_log).unwrap();
|
|
67
|
-
let log_key = v8_str(scope, "log");
|
|
68
|
-
t_obj.set(scope, log_key.into(), log_fn.into());
|
|
69
|
-
|
|
70
|
-
// t.fetch (Metadata version for drift)
|
|
71
|
-
let fetch_fn = v8::Function::new(scope, native_fetch_meta).unwrap();
|
|
72
|
-
let fetch_key = v8_str(scope, "fetch");
|
|
73
|
-
t_obj.set(scope, fetch_key.into(), fetch_fn.into());
|
|
74
|
-
|
|
75
|
-
// t._drift_call
|
|
76
|
-
let drift_fn = v8::Function::new(scope, native_drift_call).unwrap();
|
|
77
|
-
let drift_key = v8_str(scope, "_drift_call");
|
|
78
|
-
t_obj.set(scope, drift_key.into(), drift_fn.into());
|
|
79
|
-
|
|
80
|
-
// t._finish_request
|
|
81
|
-
let finish_fn = v8::Function::new(scope, native_finish_request).unwrap();
|
|
82
|
-
let finish_key = v8_str(scope, "_finish_request");
|
|
83
|
-
t_obj.set(scope, finish_key.into(), finish_fn.into());
|
|
84
|
-
|
|
85
|
-
// t.loadEnv
|
|
86
|
-
let env_fn = v8::Function::new(scope, native_load_env).unwrap();
|
|
87
|
-
let env_key = v8_str(scope, "loadEnv");
|
|
88
|
-
t_obj.set(scope, env_key.into(), env_fn.into());
|
|
89
|
-
|
|
90
|
-
// auth, jwt, password, db, core ... (setup native objects BEFORE JS injection)
|
|
91
|
-
setup_native_utils(scope, t_obj);
|
|
92
|
-
|
|
93
|
-
// 2. JS Side Injection (Embedded)
|
|
94
|
-
let tc = &mut v8::TryCatch::new(scope);
|
|
95
|
-
let source = v8_str(tc, TITAN_CORE_JS);
|
|
96
|
-
if let Some(script) = v8::Script::compile(tc, source, None) {
|
|
97
|
-
if script.run(tc).is_none() {
|
|
98
|
-
let msg = tc.message().map(|m| m.get(tc).to_rust_string_lossy(tc)).unwrap_or("Unknown".to_string());
|
|
99
|
-
println!("{} {} {}", blue("[Titan]"), red("Core JS Init Failed:"), msg);
|
|
100
|
-
}
|
|
101
|
-
} else {
|
|
102
|
-
println!("{} {}", blue("[Titan]"), red("Core JS Compilation Failed"));
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
fn setup_native_utils(scope: &mut v8::HandleScope, t_obj: v8::Local<v8::Object>) {
|
|
107
|
-
// t.jwt
|
|
108
|
-
let jwt_obj = v8::Object::new(scope);
|
|
109
|
-
let sign_fn = v8::Function::new(scope, native_jwt_sign).unwrap();
|
|
110
|
-
let verify_fn = v8::Function::new(scope, native_jwt_verify).unwrap();
|
|
111
|
-
|
|
112
|
-
let sign_key = v8_str(scope, "sign");
|
|
113
|
-
jwt_obj.set(scope, sign_key.into(), sign_fn.into());
|
|
114
|
-
let verify_key = v8_str(scope, "verify");
|
|
115
|
-
jwt_obj.set(scope, verify_key.into(), verify_fn.into());
|
|
116
|
-
|
|
117
|
-
let jwt_key = v8_str(scope, "jwt");
|
|
118
|
-
t_obj.set(scope, jwt_key.into(), jwt_obj.into());
|
|
119
|
-
|
|
120
|
-
// t.password
|
|
121
|
-
let pw_obj = v8::Object::new(scope);
|
|
122
|
-
let hash_fn = v8::Function::new(scope, native_password_hash).unwrap();
|
|
123
|
-
let pw_verify_fn = v8::Function::new(scope, native_password_verify).unwrap();
|
|
124
|
-
|
|
125
|
-
let hash_key = v8_str(scope, "hash");
|
|
126
|
-
pw_obj.set(scope, hash_key.into(), hash_fn.into());
|
|
127
|
-
let pw_v_key = v8_str(scope, "verify");
|
|
128
|
-
pw_obj.set(scope, pw_v_key.into(), pw_verify_fn.into());
|
|
129
|
-
|
|
130
|
-
let pw_key = v8_str(scope, "password");
|
|
131
|
-
t_obj.set(scope, pw_key.into(), pw_obj.into());
|
|
132
|
-
|
|
133
|
-
// t.shareContext (Native primitives)
|
|
134
|
-
let sc_obj = v8::Object::new(scope);
|
|
135
|
-
let n_get = v8::Function::new(scope, share_context_get).unwrap();
|
|
136
|
-
let n_set = v8::Function::new(scope, share_context_set).unwrap();
|
|
137
|
-
let n_del = v8::Function::new(scope, share_context_delete).unwrap();
|
|
138
|
-
let n_keys = v8::Function::new(scope, share_context_keys).unwrap();
|
|
139
|
-
let n_pub = v8::Function::new(scope, share_context_broadcast).unwrap();
|
|
140
|
-
|
|
141
|
-
let get_key = v8_str(scope, "get");
|
|
142
|
-
sc_obj.set(scope, get_key.into(), n_get.into());
|
|
143
|
-
let set_key = v8_str(scope, "set");
|
|
144
|
-
sc_obj.set(scope, set_key.into(), n_set.into());
|
|
145
|
-
let del_key = v8_str(scope, "delete");
|
|
146
|
-
sc_obj.set(scope, del_key.into(), n_del.into());
|
|
147
|
-
let keys_key = v8_str(scope, "keys");
|
|
148
|
-
sc_obj.set(scope, keys_key.into(), n_keys.into());
|
|
149
|
-
let pub_key = v8_str(scope, "broadcast");
|
|
150
|
-
sc_obj.set(scope, pub_key.into(), n_pub.into());
|
|
151
|
-
|
|
152
|
-
let sc_key = v8_str(scope, "shareContext");
|
|
153
|
-
let sc_val = sc_obj.into();
|
|
154
|
-
t_obj.set(scope, sc_key.into(), sc_val);
|
|
155
|
-
|
|
156
|
-
// t.db (Database operations)
|
|
157
|
-
let db_obj = v8::Object::new(scope);
|
|
158
|
-
let db_connect_fn = v8::Function::new(scope, native_db_connect).unwrap();
|
|
159
|
-
let connect_key = v8_str(scope, "connect");
|
|
160
|
-
db_obj.set(scope, connect_key.into(), db_connect_fn.into());
|
|
161
|
-
|
|
162
|
-
let db_key = v8_str(scope, "db");
|
|
163
|
-
t_obj.set(scope, db_key.into(), db_obj.into());
|
|
164
|
-
|
|
165
|
-
// t.core (System operations)
|
|
166
|
-
let core_obj = v8::Object::new(scope);
|
|
167
|
-
let fs_obj = v8::Object::new(scope);
|
|
168
|
-
let fs_read_fn = v8::Function::new(scope, native_read).unwrap();
|
|
169
|
-
let read_key = v8_str(scope, "read");
|
|
170
|
-
fs_obj.set(scope, read_key.into(), fs_read_fn.into());
|
|
171
|
-
|
|
172
|
-
let fs_read_sync_fn = v8::Function::new(scope, native_read_sync).unwrap();
|
|
173
|
-
let read_sync_key = v8_str(scope, "readFile");
|
|
174
|
-
fs_obj.set(scope, read_sync_key.into(), fs_read_sync_fn.into());
|
|
175
|
-
|
|
176
|
-
// Also Expose as t.readSync
|
|
177
|
-
let t_read_sync_fn = v8::Function::new(scope, native_read_sync).unwrap();
|
|
178
|
-
let t_read_sync_key = v8_str(scope, "readSync");
|
|
179
|
-
t_obj.set(scope, t_read_sync_key.into(), t_read_sync_fn.into());
|
|
180
|
-
|
|
181
|
-
let fs_key = v8_str(scope, "fs");
|
|
182
|
-
core_obj.set(scope, fs_key.into(), fs_obj.into());
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
fn native_read_sync(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
188
|
-
let path_val = args.get(0);
|
|
189
|
-
if !path_val.is_string() {
|
|
190
|
-
throw(scope, "readSync/readFile: path is required");
|
|
191
|
-
return;
|
|
192
|
-
}
|
|
193
|
-
let path_str = v8_to_string(scope, path_val);
|
|
194
|
-
|
|
195
|
-
let root = super::PROJECT_ROOT.get().cloned().unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
|
|
196
|
-
let joined = root.join(&path_str);
|
|
197
|
-
|
|
198
|
-
if let Ok(target) = joined.canonicalize() {
|
|
199
|
-
if target.starts_with(&root.canonicalize().unwrap_or(root.clone())) {
|
|
200
|
-
match std::fs::read_to_string(&target) {
|
|
201
|
-
Ok(content) => {
|
|
202
|
-
let v8_content = v8_str(scope, &content);
|
|
203
|
-
retval.set(v8_content.into());
|
|
204
|
-
},
|
|
205
|
-
Err(e) => {
|
|
206
|
-
retval.set(v8::null(scope).into());
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
} else {
|
|
210
|
-
retval.set(v8::null(scope).into());
|
|
211
|
-
}
|
|
212
|
-
} else {
|
|
213
|
-
retval.set(v8::null(scope).into());
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
fn native_read(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
218
|
-
let path_val = args.get(0);
|
|
219
|
-
if !path_val.is_string() {
|
|
220
|
-
throw(scope, "t.read(path): path is required");
|
|
221
|
-
return;
|
|
222
|
-
}
|
|
223
|
-
let path_str = v8_to_string(scope, path_val);
|
|
224
|
-
|
|
225
|
-
let obj = v8::Object::new(scope);
|
|
226
|
-
let op_key = v8_str(scope, "__titanAsync");
|
|
227
|
-
let op_val = v8::Boolean::new(scope, true);
|
|
228
|
-
obj.set(scope, op_key.into(), op_val.into());
|
|
229
|
-
|
|
230
|
-
let type_key = v8_str(scope, "type");
|
|
231
|
-
let type_val = v8_str(scope, "fs_read");
|
|
232
|
-
obj.set(scope, type_key.into(), type_val.into());
|
|
233
|
-
|
|
234
|
-
let data_obj = v8::Object::new(scope);
|
|
235
|
-
let path_k = v8_str(scope, "path");
|
|
236
|
-
let path_v = v8_str(scope, &path_str);
|
|
237
|
-
data_obj.set(scope, path_k.into(), path_v.into());
|
|
238
|
-
|
|
239
|
-
let data_key = v8_str(scope, "data");
|
|
240
|
-
obj.set(scope, data_key.into(), data_obj.into());
|
|
241
|
-
|
|
242
|
-
retval.set(obj.into());
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
fn native_decode_utf8(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
246
|
-
let val = args.get(0);
|
|
247
|
-
if let Ok(u8arr) = v8::Local::<v8::Uint8Array>::try_from(val) {
|
|
248
|
-
let buf = u8arr.buffer(scope).unwrap();
|
|
249
|
-
let store = v8::ArrayBuffer::get_backing_store(&buf);
|
|
250
|
-
let offset = usize::from(u8arr.byte_offset());
|
|
251
|
-
let length = usize::from(u8arr.byte_length());
|
|
252
|
-
let slice = &store[offset..offset+length];
|
|
253
|
-
|
|
254
|
-
let bytes: Vec<u8> = slice.iter().map(|b| b.get()).collect();
|
|
255
|
-
let s = String::from_utf8_lossy(&bytes);
|
|
256
|
-
retval.set(v8_str(scope, &s).into());
|
|
257
|
-
} else if let Ok(ab) = v8::Local::<v8::ArrayBuffer>::try_from(val) {
|
|
258
|
-
let store = v8::ArrayBuffer::get_backing_store(&ab);
|
|
259
|
-
let bytes: Vec<u8> = store.iter().map(|b| b.get()).collect();
|
|
260
|
-
let s = String::from_utf8_lossy(&bytes);
|
|
261
|
-
retval.set(v8_str(scope, &s).into());
|
|
262
|
-
} else {
|
|
263
|
-
retval.set(v8::null(scope).into());
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
fn share_context_get(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
268
|
-
let key = v8_to_string(scope, args.get(0));
|
|
269
|
-
let store = ShareContextStore::get();
|
|
270
|
-
if let Some(val) = store.kv.get(&key) {
|
|
271
|
-
let json_str = val.to_string();
|
|
272
|
-
let v8_str = v8::String::new(scope, &json_str).unwrap();
|
|
273
|
-
if let Some(v8_val) = v8::json::parse(scope, v8_str) {
|
|
274
|
-
retval.set(v8_val);
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
retval.set(v8::null(scope).into());
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
fn share_context_set(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut _retval: v8::ReturnValue) {
|
|
282
|
-
let key = v8_to_string(scope, args.get(0));
|
|
283
|
-
let val_v8 = args.get(1);
|
|
284
|
-
|
|
285
|
-
if let Some(json_v8) = v8::json::stringify(scope, val_v8) {
|
|
286
|
-
let json_str = json_v8.to_rust_string_lossy(scope);
|
|
287
|
-
if let Ok(val) = serde_json::from_str(&json_str) {
|
|
288
|
-
ShareContextStore::get().kv.insert(key, val);
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
fn share_context_delete(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut _retval: v8::ReturnValue) {
|
|
294
|
-
let key = v8_to_string(scope, args.get(0));
|
|
295
|
-
ShareContextStore::get().kv.remove(&key);
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
fn share_context_keys(scope: &mut v8::HandleScope, _args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
299
|
-
let store = ShareContextStore::get();
|
|
300
|
-
let keys: Vec<v8::Local<v8::Value>> = store.kv.iter().map(|kv| v8_str(scope, kv.key()).into()).collect();
|
|
301
|
-
let arr = v8::Array::new_with_elements(scope, &keys);
|
|
302
|
-
retval.set(arr.into());
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
fn share_context_broadcast(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut _retval: v8::ReturnValue) {
|
|
306
|
-
let event = v8_to_string(scope, args.get(0));
|
|
307
|
-
let payload_v8 = args.get(1);
|
|
308
|
-
|
|
309
|
-
if let Some(json_v8) = v8::json::stringify(scope, payload_v8) {
|
|
310
|
-
let json_str = json_v8.to_rust_string_lossy(scope);
|
|
311
|
-
if let Ok(payload) = serde_json::from_str(&json_str) {
|
|
312
|
-
let _ = ShareContextStore::get().broadcast_tx.send((event, payload));
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
fn native_log(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut _retval: v8::ReturnValue) {
|
|
320
|
-
let context = scope.get_current_context();
|
|
321
|
-
let global = context.global(scope);
|
|
322
|
-
let action_key = v8_str(scope, "__titan_action");
|
|
323
|
-
let action_name = if let Some(action_val) = global.get(scope, action_key.into()) {
|
|
324
|
-
if action_val.is_string() {
|
|
325
|
-
v8_to_string(scope, action_val)
|
|
326
|
-
} else {
|
|
327
|
-
"init".to_string()
|
|
328
|
-
}
|
|
329
|
-
} else {
|
|
330
|
-
"init".to_string()
|
|
331
|
-
};
|
|
332
|
-
|
|
333
|
-
let mut parts = Vec::new();
|
|
334
|
-
for i in 0..args.length() {
|
|
335
|
-
let val = args.get(i);
|
|
336
|
-
let mut appended = false;
|
|
337
|
-
|
|
338
|
-
if val.is_object() && !val.is_function() {
|
|
339
|
-
if let Some(json) = v8::json::stringify(scope, val) {
|
|
340
|
-
parts.push(json.to_rust_string_lossy(scope));
|
|
341
|
-
appended = true;
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
if !appended {
|
|
346
|
-
parts.push(v8_to_string(scope, val));
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
let titan_str = blue("[Titan]");
|
|
351
|
-
let log_msg = gray(&format!("\x1b[90mlog({})\x1b[0m\x1b[97m: {}\x1b[0m", action_name, parts.join(" ")));
|
|
352
|
-
println!(
|
|
353
|
-
"{} {}",
|
|
354
|
-
titan_str,
|
|
355
|
-
log_msg
|
|
356
|
-
);
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
fn native_jwt_sign(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
362
|
-
let payload_val = args.get(0);
|
|
363
|
-
let json_str = v8::json::stringify(scope, payload_val).unwrap().to_rust_string_lossy(scope);
|
|
364
|
-
let mut payload: serde_json::Map<String, Value> = serde_json::from_str(&json_str).unwrap_or_default();
|
|
365
|
-
let secret = v8_to_string(scope, args.get(1));
|
|
366
|
-
|
|
367
|
-
let opts_val = args.get(2);
|
|
368
|
-
if opts_val.is_object() {
|
|
369
|
-
let opts_obj = opts_val.to_object(scope).unwrap();
|
|
370
|
-
let exp_key = v8_str(scope, "expiresIn");
|
|
371
|
-
if let Some(val) = opts_obj.get(scope, exp_key.into()) {
|
|
372
|
-
let seconds = if val.is_number() {
|
|
373
|
-
Some(val.to_number(scope).unwrap().value() as u64)
|
|
374
|
-
} else if val.is_string() {
|
|
375
|
-
parse_expires_in(&v8_to_string(scope, val))
|
|
376
|
-
} else { None };
|
|
377
|
-
if let Some(sec) = seconds {
|
|
378
|
-
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
|
|
379
|
-
payload.insert("exp".to_string(), Value::Number(serde_json::Number::from(now + sec)));
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
let token = encode(&Header::default(), &Value::Object(payload), &EncodingKey::from_secret(secret.as_bytes()));
|
|
385
|
-
match token {
|
|
386
|
-
Ok(t) => {
|
|
387
|
-
let res = v8_str(scope, &t);
|
|
388
|
-
retval.set(res.into());
|
|
389
|
-
},
|
|
390
|
-
Err(e) => throw(scope, &e.to_string()),
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
fn native_jwt_verify(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
395
|
-
let token = v8_to_string(scope, args.get(0));
|
|
396
|
-
let secret = v8_to_string(scope, args.get(1));
|
|
397
|
-
let mut validation = Validation::default();
|
|
398
|
-
validation.validate_exp = true;
|
|
399
|
-
let data = decode::<Value>(&token, &DecodingKey::from_secret(secret.as_bytes()), &validation);
|
|
400
|
-
match data {
|
|
401
|
-
Ok(d) => {
|
|
402
|
-
let json_str = serde_json::to_string(&d.claims).unwrap();
|
|
403
|
-
let v8_json_str = v8_str(scope, &json_str);
|
|
404
|
-
if let Some(val) = v8::json::parse(scope, v8_json_str) {
|
|
405
|
-
retval.set(val);
|
|
406
|
-
}
|
|
407
|
-
},
|
|
408
|
-
Err(e) => throw(scope, &format!("Invalid or expired JWT: {}", e)),
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
fn native_password_hash(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
413
|
-
let pw = v8_to_string(scope, args.get(0));
|
|
414
|
-
match hash(pw, DEFAULT_COST) {
|
|
415
|
-
Ok(h) => {
|
|
416
|
-
let res = v8_str(scope, &h);
|
|
417
|
-
retval.set(res.into());
|
|
418
|
-
},
|
|
419
|
-
Err(e) => throw(scope, &e.to_string()),
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
fn native_password_verify(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
424
|
-
let pw = v8_to_string(scope, args.get(0));
|
|
425
|
-
let hash_str = v8_to_string(scope, args.get(1));
|
|
426
|
-
let ok = verify(pw, &hash_str).unwrap_or(false);
|
|
427
|
-
retval.set(v8::Boolean::new(scope, ok).into());
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
fn native_load_env(scope: &mut v8::HandleScope, _args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
431
|
-
use serde_json::json;
|
|
432
|
-
|
|
433
|
-
let mut map = serde_json::Map::new();
|
|
434
|
-
|
|
435
|
-
for (key, value) in std::env::vars() {
|
|
436
|
-
map.insert(key, json!(value));
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
let json_str = serde_json::to_string(&map).unwrap();
|
|
440
|
-
let v8_str = v8::String::new(scope, &json_str).unwrap();
|
|
441
|
-
|
|
442
|
-
if let Some(obj) = v8::json::parse(scope, v8_str) {
|
|
443
|
-
retval.set(obj);
|
|
444
|
-
} else {
|
|
445
|
-
retval.set(v8::null(scope).into());
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
fn native_define_action(_scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
450
|
-
retval.set(args.get(0));
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
fn native_db_connect(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
454
|
-
|
|
455
|
-
let conn_string = v8_to_string(scope, args.get(0));
|
|
456
|
-
|
|
457
|
-
if conn_string.is_empty() {
|
|
458
|
-
throw(scope, "t.db.connect(): connection string required");
|
|
459
|
-
return;
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
let mut max_size = 16;
|
|
463
|
-
|
|
464
|
-
if args.length() > 1 && args.get(1).is_object() {
|
|
465
|
-
let opts = args.get(1).to_object(scope).unwrap();
|
|
466
|
-
let max_key = v8_str(scope, "max");
|
|
467
|
-
if let Some(v) = opts.get(scope, max_key.into()) {
|
|
468
|
-
if let Some(n) = v.number_value(scope) {
|
|
469
|
-
max_size = n as usize;
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
if DB_POOL.get().is_none() {
|
|
475
|
-
let cfg: Config = match conn_string.parse() {
|
|
476
|
-
Ok(c) => c,
|
|
477
|
-
Err(e) => {
|
|
478
|
-
throw(scope, &format!("t.db.connect(): Invalid connection string: {}", e));
|
|
479
|
-
return;
|
|
480
|
-
}
|
|
481
|
-
};
|
|
482
|
-
let mgr = Manager::new(cfg, NoTls);
|
|
483
|
-
|
|
484
|
-
let pool = match Pool::builder(mgr)
|
|
485
|
-
.max_size(max_size)
|
|
486
|
-
.build() {
|
|
487
|
-
Ok(p) => p,
|
|
488
|
-
Err(e) => {
|
|
489
|
-
throw(scope, &format!("t.db.connect(): Failed to build connection pool: {}", e));
|
|
490
|
-
return;
|
|
491
|
-
}
|
|
492
|
-
};
|
|
493
|
-
|
|
494
|
-
DB_POOL.set(pool).ok();
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
let db_conn_obj = v8::Object::new(scope);
|
|
498
|
-
|
|
499
|
-
let query_fn = match v8::Function::new(scope, native_db_query) {
|
|
500
|
-
Some(f) => f,
|
|
501
|
-
None => {
|
|
502
|
-
throw(scope, "t.db.connect(): Failed to create query function");
|
|
503
|
-
return;
|
|
504
|
-
}
|
|
505
|
-
};
|
|
506
|
-
let query_key = v8_str(scope, "query");
|
|
507
|
-
db_conn_obj.set(scope, query_key.into(), query_fn.into());
|
|
508
|
-
|
|
509
|
-
retval.set(db_conn_obj.into());
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
fn native_db_query(
|
|
513
|
-
scope: &mut v8::HandleScope,
|
|
514
|
-
args: v8::FunctionCallbackArguments,
|
|
515
|
-
mut retval: v8::ReturnValue,
|
|
516
|
-
) {
|
|
517
|
-
let sql = v8_to_string(scope, args.get(0));
|
|
518
|
-
|
|
519
|
-
// Collect params
|
|
520
|
-
let mut params = Vec::new();
|
|
521
|
-
if args.length() > 1 && args.get(1).is_array() {
|
|
522
|
-
let arr = v8::Local::<v8::Array>::try_from(args.get(1)).unwrap();
|
|
523
|
-
for i in 0..arr.length() {
|
|
524
|
-
if let Some(v) = arr.get_index(scope, i) {
|
|
525
|
-
params.push(v8_to_string(scope, v));
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
// Main async wrapper object
|
|
531
|
-
let obj = v8::Object::new(scope);
|
|
532
|
-
|
|
533
|
-
let async_key = v8_str(scope, "__titanAsync");
|
|
534
|
-
let async_val = v8::Boolean::new(scope, true);
|
|
535
|
-
obj.set(scope, async_key.into(), async_val.into());
|
|
536
|
-
|
|
537
|
-
let type_key = v8_str(scope, "type");
|
|
538
|
-
let type_val = v8_str(scope, "db_query");
|
|
539
|
-
obj.set(scope, type_key.into(), type_val.into());
|
|
540
|
-
|
|
541
|
-
// Data object
|
|
542
|
-
let data_obj = v8::Object::new(scope);
|
|
543
|
-
|
|
544
|
-
let conn_key = v8_str(scope, "conn");
|
|
545
|
-
let conn_val = v8_str(scope, "default");
|
|
546
|
-
data_obj.set(scope, conn_key.into(), conn_val.into());
|
|
547
|
-
|
|
548
|
-
let query_key = v8_str(scope, "query");
|
|
549
|
-
let query_val = v8_str(scope, &sql);
|
|
550
|
-
data_obj.set(scope, query_key.into(), query_val.into());
|
|
551
|
-
|
|
552
|
-
// Params array
|
|
553
|
-
let params_arr = v8::Array::new(scope, params.len() as i32);
|
|
554
|
-
|
|
555
|
-
for (i, p) in params.iter().enumerate() {
|
|
556
|
-
let param_val = v8_str(scope, p);
|
|
557
|
-
params_arr.set_index(scope, i as u32, param_val.into());
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
let params_key = v8_str(scope, "params");
|
|
561
|
-
data_obj.set(scope, params_key.into(), params_arr.into());
|
|
562
|
-
|
|
563
|
-
let data_key = v8_str(scope, "data");
|
|
564
|
-
obj.set(scope, data_key.into(), data_obj.into());
|
|
565
|
-
|
|
566
|
-
retval.set(obj.into());
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
fn native_fetch_meta(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
570
|
-
let url = v8_to_string(scope, args.get(0));
|
|
571
|
-
let opts = args.get(1);
|
|
572
|
-
|
|
573
|
-
let obj = v8::Object::new(scope);
|
|
574
|
-
let op_key = v8_str(scope, "__titanAsync");
|
|
575
|
-
let op_val = v8::Boolean::new(scope, true);
|
|
576
|
-
obj.set(scope, op_key.into(), op_val.into());
|
|
577
|
-
|
|
578
|
-
let type_key = v8_str(scope, "type");
|
|
579
|
-
let type_val = v8_str(scope, "fetch");
|
|
580
|
-
obj.set(scope, type_key.into(), type_val.into());
|
|
581
|
-
|
|
582
|
-
let data_obj = v8::Object::new(scope);
|
|
583
|
-
let url_key = v8_str(scope, "url");
|
|
584
|
-
let url_val = v8_str(scope, &url);
|
|
585
|
-
data_obj.set(scope, url_key.into(), url_val.into());
|
|
586
|
-
|
|
587
|
-
let opts_key = v8_str(scope, "opts");
|
|
588
|
-
data_obj.set(scope, opts_key.into(), opts);
|
|
589
|
-
|
|
590
|
-
let data_key = v8_str(scope, "data");
|
|
591
|
-
obj.set(scope, data_key.into(), data_obj.into());
|
|
592
|
-
|
|
593
|
-
retval.set(obj.into());
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
fn parse_async_op(scope: &mut v8::HandleScope, op_val: v8::Local<v8::Value>) -> Option<super::TitanAsyncOp> {
|
|
597
|
-
if !op_val.is_object() { return None; }
|
|
598
|
-
let op_obj = op_val.to_object(scope).unwrap();
|
|
599
|
-
|
|
600
|
-
let type_key = v8_str(scope, "type");
|
|
601
|
-
let type_obj = op_obj.get(scope, type_key.into())?;
|
|
602
|
-
let op_type = v8_to_string(scope, type_obj);
|
|
603
|
-
|
|
604
|
-
let data_key = v8_str(scope, "data");
|
|
605
|
-
let data_val = op_obj.get(scope, data_key.into())?;
|
|
606
|
-
if !data_val.is_object() { return None; }
|
|
607
|
-
let data_obj = data_val.to_object(scope).unwrap();
|
|
608
|
-
|
|
609
|
-
match op_type.as_str() {
|
|
610
|
-
"fetch" => {
|
|
611
|
-
let url_key = v8_str(scope, "url");
|
|
612
|
-
let url_obj = data_obj.get(scope, url_key.into())?;
|
|
613
|
-
let url = v8_to_string(scope, url_obj);
|
|
614
|
-
|
|
615
|
-
let mut method = "GET".to_string();
|
|
616
|
-
let mut body = None;
|
|
617
|
-
let mut headers = Vec::new();
|
|
618
|
-
|
|
619
|
-
let opts_key = v8_str(scope, "opts");
|
|
620
|
-
if let Some(opts_val) = data_obj.get(scope, opts_key.into()) {
|
|
621
|
-
if opts_val.is_object() {
|
|
622
|
-
let opts_obj = opts_val.to_object(scope).unwrap();
|
|
623
|
-
let m_key = v8_str(scope, "method");
|
|
624
|
-
if let Some(m_val) = opts_obj.get(scope, m_key.into()) {
|
|
625
|
-
if m_val.is_string() { method = v8_to_string(scope, m_val); }
|
|
626
|
-
}
|
|
627
|
-
let b_key = v8_str(scope, "body");
|
|
628
|
-
if let Some(b_val) = opts_obj.get(scope, b_key.into()) {
|
|
629
|
-
if b_val.is_string() {
|
|
630
|
-
body = Some(v8_to_string(scope, b_val));
|
|
631
|
-
} else if b_val.is_object() {
|
|
632
|
-
body = Some(v8::json::stringify(scope, b_val).unwrap().to_rust_string_lossy(scope));
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
let h_key = v8_str(scope, "headers");
|
|
636
|
-
if let Some(h_val) = opts_obj.get(scope, h_key.into()) {
|
|
637
|
-
if h_val.is_object() {
|
|
638
|
-
let h_obj = h_val.to_object(scope).unwrap();
|
|
639
|
-
if let Some(keys) = h_obj.get_own_property_names(scope, Default::default()) {
|
|
640
|
-
for i in 0..keys.length() {
|
|
641
|
-
let key = keys.get_index(scope, i).unwrap();
|
|
642
|
-
let val = h_obj.get(scope, key).unwrap();
|
|
643
|
-
headers.push((v8_to_string(scope, key), v8_to_string(scope, val)));
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
Some(super::TitanAsyncOp::Fetch { url, method, body, headers })
|
|
651
|
-
},
|
|
652
|
-
|
|
653
|
-
"db_query" => {
|
|
654
|
-
|
|
655
|
-
let conn_key = v8_str(scope, "conn");
|
|
656
|
-
let conn_val = data_obj.get(scope, conn_key.into())?;
|
|
657
|
-
let conn = v8_to_string(scope, conn_val);
|
|
658
|
-
|
|
659
|
-
let query_key = v8_str(scope, "query");
|
|
660
|
-
let query_val = data_obj.get(scope, query_key.into())?;
|
|
661
|
-
let query = v8_to_string(scope, query_val);
|
|
662
|
-
|
|
663
|
-
let params_key = v8_str(scope, "params");
|
|
664
|
-
let mut params = Vec::new();
|
|
665
|
-
|
|
666
|
-
if let Some(p_val) = data_obj.get(scope, params_key.into()) {
|
|
667
|
-
if p_val.is_array() {
|
|
668
|
-
let arr = v8::Local::<v8::Array>::try_from(p_val).unwrap();
|
|
669
|
-
for i in 0..arr.length() {
|
|
670
|
-
if let Some(v) = arr.get_index(scope, i) {
|
|
671
|
-
params.push(v8_to_string(scope, v));
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
Some(super::TitanAsyncOp::DbQuery { conn, query, params })
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
"fs_read" => {
|
|
682
|
-
let path_key = v8_str(scope, "path");
|
|
683
|
-
let path_obj = data_obj.get(scope, path_key.into())?;
|
|
684
|
-
let path = v8_to_string(scope, path_obj);
|
|
685
|
-
Some(super::TitanAsyncOp::FsRead { path })
|
|
686
|
-
},
|
|
687
|
-
_ => None
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
fn native_drift_call(scope: &mut v8::HandleScope, mut args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
692
|
-
let runtime_ptr = unsafe { args.get_isolate() }.get_data(0) as *mut super::TitanRuntime;
|
|
693
|
-
let runtime = unsafe { &mut *runtime_ptr };
|
|
694
|
-
|
|
695
|
-
let arg0 = args.get(0);
|
|
696
|
-
|
|
697
|
-
let (async_op, op_type) = if arg0.is_array() {
|
|
698
|
-
let arr = v8::Local::<v8::Array>::try_from(arg0).unwrap();
|
|
699
|
-
let mut ops = Vec::new();
|
|
700
|
-
for i in 0..arr.length() {
|
|
701
|
-
let op_val = arr.get_index(scope, i).unwrap();
|
|
702
|
-
if let Some(op) = parse_async_op(scope, op_val) {
|
|
703
|
-
ops.push(op);
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
(super::TitanAsyncOp::Batch(ops), "batch".to_string())
|
|
707
|
-
} else {
|
|
708
|
-
match parse_async_op(scope, arg0) {
|
|
709
|
-
Some(op) => {
|
|
710
|
-
let t = match &op {
|
|
711
|
-
super::TitanAsyncOp::Fetch { .. } => "fetch",
|
|
712
|
-
super::TitanAsyncOp::DbQuery { .. } => "db_query",
|
|
713
|
-
super::TitanAsyncOp::FsRead { .. } => "fs_read",
|
|
714
|
-
_ => "unknown"
|
|
715
|
-
};
|
|
716
|
-
(op, t.to_string())
|
|
717
|
-
},
|
|
718
|
-
None => {
|
|
719
|
-
throw(scope, "drift() requires an async operation or array of operations");
|
|
720
|
-
return;
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
};
|
|
724
|
-
|
|
725
|
-
let runtime_ptr = unsafe { args.get_isolate() }.get_data(0) as *mut super::TitanRuntime;
|
|
726
|
-
let runtime = unsafe { &mut *runtime_ptr };
|
|
727
|
-
|
|
728
|
-
let req_id = {
|
|
729
|
-
let context = scope.get_current_context();
|
|
730
|
-
let global = context.global(scope);
|
|
731
|
-
let req_key = v8_str(scope, "__titan_req");
|
|
732
|
-
if let Some(req_obj_val) = global.get(scope, req_key.into()) {
|
|
733
|
-
if req_obj_val.is_object() {
|
|
734
|
-
let req_obj = req_obj_val.to_object(scope).unwrap();
|
|
735
|
-
let id_key = v8_str(scope, "__titan_request_id");
|
|
736
|
-
req_obj.get(scope, id_key.into()).unwrap().uint32_value(scope).unwrap_or(0)
|
|
737
|
-
} else { 0 }
|
|
738
|
-
} else { 0 }
|
|
739
|
-
};
|
|
740
|
-
|
|
741
|
-
runtime.drift_counter += 1;
|
|
742
|
-
let drift_id = runtime.drift_counter;
|
|
743
|
-
|
|
744
|
-
if req_id != 0 {
|
|
745
|
-
runtime.drift_to_request.insert(drift_id, req_id);
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
// --- REPLAY CHECK ---
|
|
749
|
-
if let Some(res) = runtime.completed_drifts.get(&drift_id) {
|
|
750
|
-
let json_str = serde_json::to_string(res).unwrap_or_else(|_| "null".to_string());
|
|
751
|
-
let v8_str = v8::String::new(scope, &json_str).unwrap();
|
|
752
|
-
let mut try_catch = v8::TryCatch::new(scope);
|
|
753
|
-
if let Some(val) = v8::json::parse(&mut try_catch, v8_str) {
|
|
754
|
-
retval.set(val);
|
|
755
|
-
} else {
|
|
756
|
-
retval.set(v8::null(&mut try_catch).into());
|
|
757
|
-
}
|
|
758
|
-
return;
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
let (tx, rx) = tokio::sync::oneshot::channel::<super::WorkerAsyncResult>();
|
|
762
|
-
|
|
763
|
-
let req = super::AsyncOpRequest {
|
|
764
|
-
op: async_op,
|
|
765
|
-
drift_id,
|
|
766
|
-
request_id: req_id,
|
|
767
|
-
op_type,
|
|
768
|
-
respond_tx: tx,
|
|
769
|
-
};
|
|
770
|
-
|
|
771
|
-
if let Err(e) = runtime.global_async_tx.try_send(req) {
|
|
772
|
-
println!("[Titan] Drift Call Failed to queue: {}", e);
|
|
773
|
-
retval.set(v8::null(scope).into());
|
|
774
|
-
return;
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
let tokio_handle = runtime.tokio_handle.clone();
|
|
778
|
-
let worker_tx = runtime.worker_tx.clone();
|
|
779
|
-
|
|
780
|
-
tokio_handle.spawn(async move {
|
|
781
|
-
if let Ok(res) = rx.await {
|
|
782
|
-
let _ = worker_tx.send(crate::runtime::WorkerCommand::Resume {
|
|
783
|
-
drift_id,
|
|
784
|
-
result: res,
|
|
785
|
-
});
|
|
786
|
-
}
|
|
787
|
-
});
|
|
788
|
-
|
|
789
|
-
throw(scope, "__SUSPEND__");
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
fn native_finish_request(scope: &mut v8::HandleScope, mut args: v8::FunctionCallbackArguments, _retval: v8::ReturnValue) {
|
|
793
|
-
let request_id = args.get(0).uint32_value(scope).unwrap_or(0);
|
|
794
|
-
let result_val = args.get(1);
|
|
795
|
-
|
|
796
|
-
// --- OPTIMIZATION: Direct field extraction for _isResponse objects ---
|
|
797
|
-
let json = if result_val.is_object() {
|
|
798
|
-
let obj = result_val.to_object(scope).unwrap();
|
|
799
|
-
let is_resp_key = v8_str(scope, "_isResponse");
|
|
800
|
-
let is_response = obj
|
|
801
|
-
.get(scope, is_resp_key.into())
|
|
802
|
-
.map(|v| v.boolean_value(scope))
|
|
803
|
-
.unwrap_or(false);
|
|
804
|
-
|
|
805
|
-
if is_response {
|
|
806
|
-
// Hot path: extract fields directly without full stringify+parse.
|
|
807
|
-
let mut map = serde_json::Map::with_capacity(5);
|
|
808
|
-
map.insert("_isResponse".into(), Value::Bool(true));
|
|
809
|
-
|
|
810
|
-
// status (number → u64)
|
|
811
|
-
let status_key = v8_str(scope, "status");
|
|
812
|
-
if let Some(s) = obj.get(scope, status_key.into()) {
|
|
813
|
-
if let Some(n) = s.number_value(scope) {
|
|
814
|
-
map.insert(
|
|
815
|
-
"status".into(),
|
|
816
|
-
Value::Number(serde_json::Number::from(n as u64)),
|
|
817
|
-
);
|
|
818
|
-
}
|
|
819
|
-
}
|
|
820
|
-
|
|
821
|
-
// body (already a JSON string from JS — extract as-is, no re-serialization)
|
|
822
|
-
let body_key = v8_str(scope, "body");
|
|
823
|
-
if let Some(b) = obj.get(scope, body_key.into()) {
|
|
824
|
-
if b.is_string() {
|
|
825
|
-
let body_str = b.to_string(scope).unwrap().to_rust_string_lossy(scope);
|
|
826
|
-
map.insert("body".into(), Value::String(body_str));
|
|
827
|
-
} else if !b.is_null_or_undefined() {
|
|
828
|
-
// Non-string body (rare) — stringify it
|
|
829
|
-
let body_str = v8_to_string(scope, b);
|
|
830
|
-
map.insert("body".into(), Value::String(body_str));
|
|
831
|
-
}
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
// headers (flat object with ~2-3 keys typically)
|
|
835
|
-
let headers_key = v8_str(scope, "headers");
|
|
836
|
-
if let Some(h) = obj.get(scope, headers_key.into()) {
|
|
837
|
-
if h.is_object() {
|
|
838
|
-
let h_obj = h.to_object(scope).unwrap();
|
|
839
|
-
if let Some(keys) =
|
|
840
|
-
h_obj.get_own_property_names(scope, Default::default())
|
|
841
|
-
{
|
|
842
|
-
let mut h_map = serde_json::Map::with_capacity(keys.length() as usize);
|
|
843
|
-
for i in 0..keys.length() {
|
|
844
|
-
if let Some(key) = keys.get_index(scope, i) {
|
|
845
|
-
if let Some(val) = h_obj.get(scope, key) {
|
|
846
|
-
let k_str =
|
|
847
|
-
key.to_string(scope).unwrap().to_rust_string_lossy(scope);
|
|
848
|
-
let v_str =
|
|
849
|
-
val.to_string(scope).unwrap().to_rust_string_lossy(scope);
|
|
850
|
-
h_map.insert(k_str, Value::String(v_str));
|
|
851
|
-
}
|
|
852
|
-
}
|
|
853
|
-
}
|
|
854
|
-
map.insert("headers".into(), Value::Object(h_map));
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
}
|
|
858
|
-
serde_json::Value::Object(map)
|
|
859
|
-
} else {
|
|
860
|
-
super::v8_to_json(scope, result_val)
|
|
861
|
-
}
|
|
862
|
-
} else {
|
|
863
|
-
super::v8_to_json(scope, result_val)
|
|
864
|
-
};
|
|
865
|
-
|
|
866
|
-
let runtime_ptr = unsafe { args.get_isolate() }.get_data(0) as *mut super::TitanRuntime;
|
|
867
|
-
let runtime = unsafe { &mut *runtime_ptr };
|
|
868
|
-
|
|
869
|
-
if let Some(tx) = runtime.pending_requests.remove(&request_id) {
|
|
870
|
-
let timings = runtime.request_timings.remove(&request_id).unwrap_or_default();
|
|
871
|
-
let _ = tx.send(crate::runtime::WorkerResult {
|
|
872
|
-
json,
|
|
873
|
-
timings
|
|
874
|
-
});
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
pub fn run_async_operation(
|
|
879
|
-
op: super::TitanAsyncOp,
|
|
880
|
-
) -> std::pin::Pin<Box<dyn std::future::Future<Output = serde_json::Value> + Send>> {
|
|
881
|
-
Box::pin(async move {
|
|
882
|
-
match op {
|
|
883
|
-
|
|
884
|
-
// =========================
|
|
885
|
-
// FETCH
|
|
886
|
-
// =========================
|
|
887
|
-
super::TitanAsyncOp::Fetch {
|
|
888
|
-
url,
|
|
889
|
-
method,
|
|
890
|
-
body,
|
|
891
|
-
headers,
|
|
892
|
-
} => {
|
|
893
|
-
let client = get_http_client();
|
|
894
|
-
|
|
895
|
-
let method = reqwest::Method::from_bytes(method.as_bytes())
|
|
896
|
-
.unwrap_or(reqwest::Method::GET);
|
|
897
|
-
|
|
898
|
-
let mut req = client.request(method, &url);
|
|
899
|
-
|
|
900
|
-
for (k, v) in headers {
|
|
901
|
-
req = req.header(k, v);
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
if let Some(b) = body {
|
|
905
|
-
req = req.body(b);
|
|
906
|
-
}
|
|
907
|
-
|
|
908
|
-
match req.send().await {
|
|
909
|
-
Ok(resp) => {
|
|
910
|
-
let status = resp.status().as_u16();
|
|
911
|
-
let api_headers = resp.headers().clone();
|
|
912
|
-
let text = resp.text().await.unwrap_or_default();
|
|
913
|
-
|
|
914
|
-
let mut h_map = serde_json::Map::new();
|
|
915
|
-
for (k, v) in api_headers.iter() {
|
|
916
|
-
if let Ok(s) = v.to_str() {
|
|
917
|
-
h_map.insert(
|
|
918
|
-
k.as_str().to_string(),
|
|
919
|
-
serde_json::Value::String(s.to_string()),
|
|
920
|
-
);
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
serde_json::json!({
|
|
925
|
-
"_isResponse": true,
|
|
926
|
-
"status": status,
|
|
927
|
-
"body": text,
|
|
928
|
-
"headers": h_map
|
|
929
|
-
})
|
|
930
|
-
}
|
|
931
|
-
Err(e) => serde_json::json!({ "error": e.to_string() }),
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
// =========================
|
|
936
|
-
// DB QUERY
|
|
937
|
-
// =========================
|
|
938
|
-
super::TitanAsyncOp::DbQuery { conn: _, query, params } => {
|
|
939
|
-
|
|
940
|
-
let pool = match DB_POOL.get() {
|
|
941
|
-
Some(p) => p,
|
|
942
|
-
None => {
|
|
943
|
-
return serde_json::json!({
|
|
944
|
-
"error": "DB pool not initialized"
|
|
945
|
-
});
|
|
946
|
-
}
|
|
947
|
-
};
|
|
948
|
-
|
|
949
|
-
match pool.get().await {
|
|
950
|
-
Ok(client) => {
|
|
951
|
-
|
|
952
|
-
let stmt = match client.prepare(&query).await {
|
|
953
|
-
Ok(s) => s,
|
|
954
|
-
Err(e) => {
|
|
955
|
-
return serde_json::json!({
|
|
956
|
-
"error": e.to_string()
|
|
957
|
-
});
|
|
958
|
-
}
|
|
959
|
-
};
|
|
960
|
-
|
|
961
|
-
let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
|
|
962
|
-
params.iter()
|
|
963
|
-
.map(|p| p as &(dyn tokio_postgres::types::ToSql + Sync))
|
|
964
|
-
.collect();
|
|
965
|
-
|
|
966
|
-
match client.query(&stmt, ¶m_refs).await {
|
|
967
|
-
Ok(rows) => {
|
|
968
|
-
|
|
969
|
-
let mut result = Vec::new();
|
|
970
|
-
|
|
971
|
-
for row in rows {
|
|
972
|
-
let mut obj = serde_json::Map::new();
|
|
973
|
-
|
|
974
|
-
for (i, col) in row.columns().iter().enumerate() {
|
|
975
|
-
|
|
976
|
-
let val =
|
|
977
|
-
if let Ok(v) = row.try_get::<_, String>(i) {
|
|
978
|
-
serde_json::Value::String(v)
|
|
979
|
-
} else if let Ok(v) = row.try_get::<_, i64>(i) {
|
|
980
|
-
serde_json::Value::Number(v.into())
|
|
981
|
-
} else if let Ok(v) = row.try_get::<_, i32>(i) {
|
|
982
|
-
serde_json::Value::Number(v.into())
|
|
983
|
-
} else if let Ok(v) = row.try_get::<_, bool>(i) {
|
|
984
|
-
serde_json::Value::Bool(v)
|
|
985
|
-
} else {
|
|
986
|
-
serde_json::Value::Null
|
|
987
|
-
};
|
|
988
|
-
|
|
989
|
-
obj.insert(col.name().to_string(), val);
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
result.push(serde_json::Value::Object(obj));
|
|
993
|
-
}
|
|
994
|
-
|
|
995
|
-
serde_json::Value::Array(result)
|
|
996
|
-
}
|
|
997
|
-
Err(e) => serde_json::json!({
|
|
998
|
-
"error": e.to_string()
|
|
999
|
-
}),
|
|
1000
|
-
}
|
|
1001
|
-
}
|
|
1002
|
-
Err(e) => serde_json::json!({
|
|
1003
|
-
"error": e.to_string()
|
|
1004
|
-
}),
|
|
1005
|
-
}
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1008
|
-
// =========================
|
|
1009
|
-
// FS READ
|
|
1010
|
-
// =========================
|
|
1011
|
-
super::TitanAsyncOp::FsRead { path } => {
|
|
1012
|
-
|
|
1013
|
-
let root = super::PROJECT_ROOT
|
|
1014
|
-
.get()
|
|
1015
|
-
.cloned()
|
|
1016
|
-
.unwrap_or(std::path::PathBuf::from("."));
|
|
1017
|
-
|
|
1018
|
-
let target = root.join(&path);
|
|
1019
|
-
|
|
1020
|
-
let safe = target
|
|
1021
|
-
.canonicalize()
|
|
1022
|
-
.map(|p| {
|
|
1023
|
-
p.starts_with(
|
|
1024
|
-
root.canonicalize()
|
|
1025
|
-
.unwrap_or(root.clone())
|
|
1026
|
-
)
|
|
1027
|
-
})
|
|
1028
|
-
.unwrap_or(false);
|
|
1029
|
-
|
|
1030
|
-
if safe {
|
|
1031
|
-
match tokio::fs::read_to_string(target).await {
|
|
1032
|
-
Ok(c) => serde_json::json!({ "data": c }),
|
|
1033
|
-
Err(e) => serde_json::json!({ "error": e.to_string() }),
|
|
1034
|
-
}
|
|
1035
|
-
} else {
|
|
1036
|
-
serde_json::json!({ "error": "Access denied" })
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
|
|
1040
|
-
// =========================
|
|
1041
|
-
// BATCH
|
|
1042
|
-
// =========================
|
|
1043
|
-
super::TitanAsyncOp::Batch(ops) => {
|
|
1044
|
-
|
|
1045
|
-
let mut res = Vec::new();
|
|
1046
|
-
|
|
1047
|
-
for op in ops {
|
|
1048
|
-
res.push(run_async_operation(op).await);
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
serde_json::Value::Array(res)
|
|
1052
|
-
}
|
|
1053
|
-
}
|
|
1054
|
-
})
|
|
1055
|
-
}
|