@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.
- package/README.md +276 -0
- package/index.d.ts +65 -0
- package/index.js +131 -0
- package/jsconfig.json +13 -0
- package/package.json +32 -0
- package/test-app/.dockerignore +3 -0
- package/test-app/Dockerfile +66 -0
- package/test-app/app/actions/hello.js +7 -0
- package/test-app/app/app.js +10 -0
- package/test-app/app/static/app.html +9 -0
- package/test-app/app/static/styles.css +9 -0
- package/test-app/app/titan.d.ts +249 -0
- package/test-app/eslint.config.js +8 -0
- package/test-app/jsconfig.json +20 -0
- package/test-app/package.json +25 -0
- package/test-app/server/Cargo.toml +32 -0
- package/test-app/server/src/action_management.rs +171 -0
- package/test-app/server/src/errors.rs +10 -0
- package/test-app/server/src/extensions/builtin.rs +828 -0
- package/test-app/server/src/extensions/external.rs +309 -0
- package/test-app/server/src/extensions/mod.rs +430 -0
- package/test-app/server/src/extensions/titan_core.js +178 -0
- package/test-app/server/src/main.rs +433 -0
- package/test-app/server/src/runtime.rs +314 -0
- package/test-app/server/src/utils.rs +33 -0
- package/test-app/server/titan_storage.json +5 -0
- package/test-app/titan/bundle.js +264 -0
- package/test-app/titan/dev.js +350 -0
- package/test-app/titan/error-box.js +268 -0
- package/test-app/titan/titan.js +129 -0
- package/titan.json +20 -0
|
@@ -0,0 +1,828 @@
|
|
|
1
|
+
use v8;
|
|
2
|
+
use reqwest::{
|
|
3
|
+
blocking::Client,
|
|
4
|
+
header::{HeaderMap, HeaderName, HeaderValue},
|
|
5
|
+
};
|
|
6
|
+
use std::path::PathBuf;
|
|
7
|
+
use std::time::{SystemTime, UNIX_EPOCH};
|
|
8
|
+
use serde_json::Value;
|
|
9
|
+
use jsonwebtoken::{encode, decode, Header, EncodingKey, DecodingKey, Validation};
|
|
10
|
+
use bcrypt::{hash, verify, DEFAULT_COST};
|
|
11
|
+
use postgres::{Client as PgClient, NoTls};
|
|
12
|
+
use std::sync::{Mutex, OnceLock};
|
|
13
|
+
use std::collections::{HashMap, BTreeMap};
|
|
14
|
+
|
|
15
|
+
use crate::utils::{blue, gray, red, parse_expires_in};
|
|
16
|
+
use super::{TitanRuntime, v8_str, v8_to_string, throw, ShareContextStore};
|
|
17
|
+
|
|
18
|
+
const TITAN_CORE_JS: &str = include_str!("titan_core.js");
|
|
19
|
+
|
|
20
|
+
// Database connection pool
|
|
21
|
+
static DB_POOL: Mutex<Option<HashMap<String, PgClient>>> = Mutex::new(None);
|
|
22
|
+
static HTTP_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
|
|
23
|
+
|
|
24
|
+
fn get_http_client() -> &'static reqwest::Client {
|
|
25
|
+
HTTP_CLIENT.get_or_init(|| {
|
|
26
|
+
reqwest::Client::builder()
|
|
27
|
+
.use_rustls_tls()
|
|
28
|
+
.tcp_nodelay(true)
|
|
29
|
+
.user_agent("TitanPL/1.0")
|
|
30
|
+
.build()
|
|
31
|
+
.unwrap_or_else(|_| reqwest::Client::new())
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
pub fn inject_builtin_extensions(scope: &mut v8::HandleScope, global: v8::Local<v8::Object>, t_obj: v8::Local<v8::Object>) {
|
|
37
|
+
// 1. Native API Bindings
|
|
38
|
+
|
|
39
|
+
// defineAction (Native side)
|
|
40
|
+
let def_fn = v8::Function::new(scope, native_define_action).unwrap();
|
|
41
|
+
let def_key = v8_str(scope, "defineAction");
|
|
42
|
+
global.set(scope, def_key.into(), def_fn.into());
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
// t.read
|
|
46
|
+
let read_fn = v8::Function::new(scope, native_read).unwrap();
|
|
47
|
+
let read_key = v8_str(scope, "read");
|
|
48
|
+
t_obj.set(scope, read_key.into(), read_fn.into());
|
|
49
|
+
|
|
50
|
+
// t.decodeUtf8
|
|
51
|
+
let dec_fn = v8::Function::new(scope, native_decode_utf8).unwrap();
|
|
52
|
+
let dec_key = v8_str(scope, "decodeUtf8");
|
|
53
|
+
t_obj.set(scope, dec_key.into(), dec_fn.into());
|
|
54
|
+
|
|
55
|
+
// t.log
|
|
56
|
+
let log_fn = v8::Function::new(scope, native_log).unwrap();
|
|
57
|
+
let log_key = v8_str(scope, "log");
|
|
58
|
+
t_obj.set(scope, log_key.into(), log_fn.into());
|
|
59
|
+
|
|
60
|
+
// t.fetch (Metadata version for drift)
|
|
61
|
+
let fetch_fn = v8::Function::new(scope, native_fetch_meta).unwrap();
|
|
62
|
+
let fetch_key = v8_str(scope, "fetch");
|
|
63
|
+
t_obj.set(scope, fetch_key.into(), fetch_fn.into());
|
|
64
|
+
|
|
65
|
+
// t._drift_call
|
|
66
|
+
let drift_fn = v8::Function::new(scope, native_drift_call).unwrap();
|
|
67
|
+
let drift_key = v8_str(scope, "_drift_call");
|
|
68
|
+
t_obj.set(scope, drift_key.into(), drift_fn.into());
|
|
69
|
+
|
|
70
|
+
// t._finish_request
|
|
71
|
+
let finish_fn = v8::Function::new(scope, native_finish_request).unwrap();
|
|
72
|
+
let finish_key = v8_str(scope, "_finish_request");
|
|
73
|
+
t_obj.set(scope, finish_key.into(), finish_fn.into());
|
|
74
|
+
|
|
75
|
+
// t.loadEnv
|
|
76
|
+
let env_fn = v8::Function::new(scope, native_load_env).unwrap();
|
|
77
|
+
let env_key = v8_str(scope, "loadEnv");
|
|
78
|
+
t_obj.set(scope, env_key.into(), env_fn.into());
|
|
79
|
+
|
|
80
|
+
// auth, jwt, password, db, core ... (setup native objects BEFORE JS injection)
|
|
81
|
+
setup_native_utils(scope, t_obj);
|
|
82
|
+
|
|
83
|
+
// 2. JS Side Injection (Embedded)
|
|
84
|
+
let tc = &mut v8::TryCatch::new(scope);
|
|
85
|
+
let source = v8_str(tc, TITAN_CORE_JS);
|
|
86
|
+
if let Some(script) = v8::Script::compile(tc, source, None) {
|
|
87
|
+
if script.run(tc).is_none() {
|
|
88
|
+
let msg = tc.message().map(|m| m.get(tc).to_rust_string_lossy(tc)).unwrap_or("Unknown".to_string());
|
|
89
|
+
println!("{} {} {}", blue("[Titan]"), red("Core JS Init Failed:"), msg);
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
println!("{} {}", blue("[Titan]"), red("Core JS Compilation Failed"));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
fn setup_native_utils(scope: &mut v8::HandleScope, t_obj: v8::Local<v8::Object>) {
|
|
97
|
+
// t.jwt
|
|
98
|
+
let jwt_obj = v8::Object::new(scope);
|
|
99
|
+
let sign_fn = v8::Function::new(scope, native_jwt_sign).unwrap();
|
|
100
|
+
let verify_fn = v8::Function::new(scope, native_jwt_verify).unwrap();
|
|
101
|
+
|
|
102
|
+
let sign_key = v8_str(scope, "sign");
|
|
103
|
+
jwt_obj.set(scope, sign_key.into(), sign_fn.into());
|
|
104
|
+
let verify_key = v8_str(scope, "verify");
|
|
105
|
+
jwt_obj.set(scope, verify_key.into(), verify_fn.into());
|
|
106
|
+
|
|
107
|
+
let jwt_key = v8_str(scope, "jwt");
|
|
108
|
+
t_obj.set(scope, jwt_key.into(), jwt_obj.into());
|
|
109
|
+
|
|
110
|
+
// t.password
|
|
111
|
+
let pw_obj = v8::Object::new(scope);
|
|
112
|
+
let hash_fn = v8::Function::new(scope, native_password_hash).unwrap();
|
|
113
|
+
let pw_verify_fn = v8::Function::new(scope, native_password_verify).unwrap();
|
|
114
|
+
|
|
115
|
+
let hash_key = v8_str(scope, "hash");
|
|
116
|
+
pw_obj.set(scope, hash_key.into(), hash_fn.into());
|
|
117
|
+
let pw_v_key = v8_str(scope, "verify");
|
|
118
|
+
pw_obj.set(scope, pw_v_key.into(), pw_verify_fn.into());
|
|
119
|
+
|
|
120
|
+
let pw_key = v8_str(scope, "password");
|
|
121
|
+
t_obj.set(scope, pw_key.into(), pw_obj.into());
|
|
122
|
+
|
|
123
|
+
// t.shareContext (Native primitives)
|
|
124
|
+
let sc_obj = v8::Object::new(scope);
|
|
125
|
+
let n_get = v8::Function::new(scope, share_context_get).unwrap();
|
|
126
|
+
let n_set = v8::Function::new(scope, share_context_set).unwrap();
|
|
127
|
+
let n_del = v8::Function::new(scope, share_context_delete).unwrap();
|
|
128
|
+
let n_keys = v8::Function::new(scope, share_context_keys).unwrap();
|
|
129
|
+
let n_pub = v8::Function::new(scope, share_context_broadcast).unwrap();
|
|
130
|
+
|
|
131
|
+
let get_key = v8_str(scope, "get");
|
|
132
|
+
sc_obj.set(scope, get_key.into(), n_get.into());
|
|
133
|
+
let set_key = v8_str(scope, "set");
|
|
134
|
+
sc_obj.set(scope, set_key.into(), n_set.into());
|
|
135
|
+
let del_key = v8_str(scope, "delete");
|
|
136
|
+
sc_obj.set(scope, del_key.into(), n_del.into());
|
|
137
|
+
let keys_key = v8_str(scope, "keys");
|
|
138
|
+
sc_obj.set(scope, keys_key.into(), n_keys.into());
|
|
139
|
+
let pub_key = v8_str(scope, "broadcast");
|
|
140
|
+
sc_obj.set(scope, pub_key.into(), n_pub.into());
|
|
141
|
+
|
|
142
|
+
let sc_key = v8_str(scope, "shareContext");
|
|
143
|
+
let sc_val = sc_obj.into();
|
|
144
|
+
t_obj.set(scope, sc_key.into(), sc_val);
|
|
145
|
+
|
|
146
|
+
// t.db (Database operations)
|
|
147
|
+
let db_obj = v8::Object::new(scope);
|
|
148
|
+
let db_connect_fn = v8::Function::new(scope, native_db_connect).unwrap();
|
|
149
|
+
let connect_key = v8_str(scope, "connect");
|
|
150
|
+
db_obj.set(scope, connect_key.into(), db_connect_fn.into());
|
|
151
|
+
|
|
152
|
+
let db_key = v8_str(scope, "db");
|
|
153
|
+
t_obj.set(scope, db_key.into(), db_obj.into());
|
|
154
|
+
|
|
155
|
+
// t.core (System operations)
|
|
156
|
+
let core_obj = v8::Object::new(scope);
|
|
157
|
+
let fs_obj = v8::Object::new(scope);
|
|
158
|
+
let fs_read_fn = v8::Function::new(scope, native_read).unwrap();
|
|
159
|
+
let read_key = v8_str(scope, "read");
|
|
160
|
+
fs_obj.set(scope, read_key.into(), fs_read_fn.into());
|
|
161
|
+
|
|
162
|
+
let fs_key = v8_str(scope, "fs");
|
|
163
|
+
core_obj.set(scope, fs_key.into(), fs_obj.into());
|
|
164
|
+
|
|
165
|
+
let core_key = v8_str(scope, "core");
|
|
166
|
+
t_obj.set(scope, core_key.into(), core_obj.into());
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
fn native_read(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
170
|
+
let path_val = args.get(0);
|
|
171
|
+
if !path_val.is_string() {
|
|
172
|
+
throw(scope, "t.read(path): path is required");
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
let path_str = v8_to_string(scope, path_val);
|
|
176
|
+
|
|
177
|
+
// Return Metadata (Non-blocking for drift)
|
|
178
|
+
let obj = v8::Object::new(scope);
|
|
179
|
+
let op_key = v8_str(scope, "__titanAsync");
|
|
180
|
+
let op_val = v8::Boolean::new(scope, true);
|
|
181
|
+
obj.set(scope, op_key.into(), op_val.into());
|
|
182
|
+
|
|
183
|
+
let type_key = v8_str(scope, "type");
|
|
184
|
+
let type_val = v8_str(scope, "fs_read");
|
|
185
|
+
obj.set(scope, type_key.into(), type_val.into());
|
|
186
|
+
|
|
187
|
+
let data_obj = v8::Object::new(scope);
|
|
188
|
+
let path_k = v8_str(scope, "path");
|
|
189
|
+
let path_v = v8_str(scope, &path_str);
|
|
190
|
+
data_obj.set(scope, path_k.into(), path_v.into());
|
|
191
|
+
|
|
192
|
+
let data_key = v8_str(scope, "data");
|
|
193
|
+
obj.set(scope, data_key.into(), data_obj.into());
|
|
194
|
+
|
|
195
|
+
retval.set(obj.into());
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
fn native_decode_utf8(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
199
|
+
let val = args.get(0);
|
|
200
|
+
if let Ok(u8arr) = v8::Local::<v8::Uint8Array>::try_from(val) {
|
|
201
|
+
let buf = u8arr.buffer(scope).unwrap();
|
|
202
|
+
let store = v8::ArrayBuffer::get_backing_store(&buf);
|
|
203
|
+
let offset = usize::from(u8arr.byte_offset());
|
|
204
|
+
let length = usize::from(u8arr.byte_length());
|
|
205
|
+
let slice = &store[offset..offset+length];
|
|
206
|
+
|
|
207
|
+
let bytes: Vec<u8> = slice.iter().map(|b| b.get()).collect();
|
|
208
|
+
let s = String::from_utf8_lossy(&bytes);
|
|
209
|
+
retval.set(v8_str(scope, &s).into());
|
|
210
|
+
} else if let Ok(ab) = v8::Local::<v8::ArrayBuffer>::try_from(val) {
|
|
211
|
+
let store = v8::ArrayBuffer::get_backing_store(&ab);
|
|
212
|
+
let bytes: Vec<u8> = store.iter().map(|b| b.get()).collect();
|
|
213
|
+
let s = String::from_utf8_lossy(&bytes);
|
|
214
|
+
retval.set(v8_str(scope, &s).into());
|
|
215
|
+
} else {
|
|
216
|
+
retval.set(v8::null(scope).into());
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
fn share_context_get(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
221
|
+
let key = v8_to_string(scope, args.get(0));
|
|
222
|
+
let store = ShareContextStore::get();
|
|
223
|
+
if let Some(val) = store.kv.get(&key) {
|
|
224
|
+
let json_str = val.to_string();
|
|
225
|
+
let v8_str = v8::String::new(scope, &json_str).unwrap();
|
|
226
|
+
if let Some(v8_val) = v8::json::parse(scope, v8_str) {
|
|
227
|
+
retval.set(v8_val);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
retval.set(v8::null(scope).into());
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
fn share_context_set(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut _retval: v8::ReturnValue) {
|
|
235
|
+
let key = v8_to_string(scope, args.get(0));
|
|
236
|
+
let val_v8 = args.get(1);
|
|
237
|
+
|
|
238
|
+
if let Some(json_v8) = v8::json::stringify(scope, val_v8) {
|
|
239
|
+
let json_str = json_v8.to_rust_string_lossy(scope);
|
|
240
|
+
if let Ok(val) = serde_json::from_str(&json_str) {
|
|
241
|
+
ShareContextStore::get().kv.insert(key, val);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
fn share_context_delete(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut _retval: v8::ReturnValue) {
|
|
247
|
+
let key = v8_to_string(scope, args.get(0));
|
|
248
|
+
ShareContextStore::get().kv.remove(&key);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
fn share_context_keys(scope: &mut v8::HandleScope, _args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
252
|
+
let store = ShareContextStore::get();
|
|
253
|
+
let keys: Vec<v8::Local<v8::Value>> = store.kv.iter().map(|kv| v8_str(scope, kv.key()).into()).collect();
|
|
254
|
+
let arr = v8::Array::new_with_elements(scope, &keys);
|
|
255
|
+
retval.set(arr.into());
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
fn share_context_broadcast(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut _retval: v8::ReturnValue) {
|
|
259
|
+
let event = v8_to_string(scope, args.get(0));
|
|
260
|
+
let payload_v8 = args.get(1);
|
|
261
|
+
|
|
262
|
+
if let Some(json_v8) = v8::json::stringify(scope, payload_v8) {
|
|
263
|
+
let json_str = json_v8.to_rust_string_lossy(scope);
|
|
264
|
+
if let Ok(payload) = serde_json::from_str(&json_str) {
|
|
265
|
+
let _ = ShareContextStore::get().broadcast_tx.send((event, payload));
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
fn native_log(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut _retval: v8::ReturnValue) {
|
|
273
|
+
let context = scope.get_current_context();
|
|
274
|
+
let global = context.global(scope);
|
|
275
|
+
let action_key = v8_str(scope, "__titan_action");
|
|
276
|
+
let action_name = if let Some(action_val) = global.get(scope, action_key.into()) {
|
|
277
|
+
if action_val.is_string() {
|
|
278
|
+
v8_to_string(scope, action_val)
|
|
279
|
+
} else {
|
|
280
|
+
"init".to_string()
|
|
281
|
+
}
|
|
282
|
+
} else {
|
|
283
|
+
"init".to_string()
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
let mut parts = Vec::new();
|
|
287
|
+
for i in 0..args.length() {
|
|
288
|
+
let val = args.get(i);
|
|
289
|
+
let mut appended = false;
|
|
290
|
+
|
|
291
|
+
if val.is_object() && !val.is_function() {
|
|
292
|
+
if let Some(json) = v8::json::stringify(scope, val) {
|
|
293
|
+
parts.push(json.to_rust_string_lossy(scope));
|
|
294
|
+
appended = true;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if !appended {
|
|
299
|
+
parts.push(v8_to_string(scope, val));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
let titan_str = blue("[Titan]");
|
|
304
|
+
let log_msg = gray(&format!("\x1b[90mlog({})\x1b[0m\x1b[97m: {}\x1b[0m", action_name, parts.join(" ")));
|
|
305
|
+
println!(
|
|
306
|
+
"{} {}",
|
|
307
|
+
titan_str,
|
|
308
|
+
log_msg
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
fn native_jwt_sign(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
315
|
+
let payload_val = args.get(0);
|
|
316
|
+
let json_str = v8::json::stringify(scope, payload_val).unwrap().to_rust_string_lossy(scope);
|
|
317
|
+
let mut payload: serde_json::Map<String, Value> = serde_json::from_str(&json_str).unwrap_or_default();
|
|
318
|
+
let secret = v8_to_string(scope, args.get(1));
|
|
319
|
+
|
|
320
|
+
let opts_val = args.get(2);
|
|
321
|
+
if opts_val.is_object() {
|
|
322
|
+
let opts_obj = opts_val.to_object(scope).unwrap();
|
|
323
|
+
let exp_key = v8_str(scope, "expiresIn");
|
|
324
|
+
if let Some(val) = opts_obj.get(scope, exp_key.into()) {
|
|
325
|
+
let seconds = if val.is_number() {
|
|
326
|
+
Some(val.to_number(scope).unwrap().value() as u64)
|
|
327
|
+
} else if val.is_string() {
|
|
328
|
+
parse_expires_in(&v8_to_string(scope, val))
|
|
329
|
+
} else { None };
|
|
330
|
+
if let Some(sec) = seconds {
|
|
331
|
+
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
|
|
332
|
+
payload.insert("exp".to_string(), Value::Number(serde_json::Number::from(now + sec)));
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
let token = encode(&Header::default(), &Value::Object(payload), &EncodingKey::from_secret(secret.as_bytes()));
|
|
338
|
+
match token {
|
|
339
|
+
Ok(t) => {
|
|
340
|
+
let res = v8_str(scope, &t);
|
|
341
|
+
retval.set(res.into());
|
|
342
|
+
},
|
|
343
|
+
Err(e) => throw(scope, &e.to_string()),
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
fn native_jwt_verify(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
348
|
+
let token = v8_to_string(scope, args.get(0));
|
|
349
|
+
let secret = v8_to_string(scope, args.get(1));
|
|
350
|
+
let mut validation = Validation::default();
|
|
351
|
+
validation.validate_exp = true;
|
|
352
|
+
let data = decode::<Value>(&token, &DecodingKey::from_secret(secret.as_bytes()), &validation);
|
|
353
|
+
match data {
|
|
354
|
+
Ok(d) => {
|
|
355
|
+
let json_str = serde_json::to_string(&d.claims).unwrap();
|
|
356
|
+
let v8_json_str = v8_str(scope, &json_str);
|
|
357
|
+
if let Some(val) = v8::json::parse(scope, v8_json_str) {
|
|
358
|
+
retval.set(val);
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
Err(e) => throw(scope, &format!("Invalid or expired JWT: {}", e)),
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
fn native_password_hash(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
366
|
+
let pw = v8_to_string(scope, args.get(0));
|
|
367
|
+
match hash(pw, DEFAULT_COST) {
|
|
368
|
+
Ok(h) => {
|
|
369
|
+
let res = v8_str(scope, &h);
|
|
370
|
+
retval.set(res.into());
|
|
371
|
+
},
|
|
372
|
+
Err(e) => throw(scope, &e.to_string()),
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
fn native_password_verify(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
377
|
+
let pw = v8_to_string(scope, args.get(0));
|
|
378
|
+
let hash_str = v8_to_string(scope, args.get(1));
|
|
379
|
+
let ok = verify(pw, &hash_str).unwrap_or(false);
|
|
380
|
+
retval.set(v8::Boolean::new(scope, ok).into());
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
fn native_load_env(scope: &mut v8::HandleScope, _args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
384
|
+
use serde_json::json;
|
|
385
|
+
|
|
386
|
+
let mut map = serde_json::Map::new();
|
|
387
|
+
|
|
388
|
+
for (key, value) in std::env::vars() {
|
|
389
|
+
map.insert(key, json!(value));
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
let json_str = serde_json::to_string(&map).unwrap();
|
|
393
|
+
let v8_str = v8::String::new(scope, &json_str).unwrap();
|
|
394
|
+
|
|
395
|
+
if let Some(obj) = v8::json::parse(scope, v8_str) {
|
|
396
|
+
retval.set(obj);
|
|
397
|
+
} else {
|
|
398
|
+
retval.set(v8::null(scope).into());
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
fn native_define_action(_scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
403
|
+
retval.set(args.get(0));
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
fn native_db_connect(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
407
|
+
let conn_string = v8_to_string(scope, args.get(0));
|
|
408
|
+
|
|
409
|
+
if conn_string.is_empty() {
|
|
410
|
+
throw(scope, "t.db.connect(): connection string is required");
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// Test connection immediately
|
|
415
|
+
match PgClient::connect(&conn_string, NoTls) {
|
|
416
|
+
Ok(mut client) => {
|
|
417
|
+
// Store in pool
|
|
418
|
+
let mut pool = DB_POOL.lock().unwrap();
|
|
419
|
+
let map = pool.get_or_insert_with(HashMap::new);
|
|
420
|
+
map.insert(conn_string.clone(), client);
|
|
421
|
+
},
|
|
422
|
+
Err(e) => {
|
|
423
|
+
throw(scope, &format!("Database connection failed: {}", e));
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// Return a DB connection object with methods
|
|
429
|
+
let db_conn_obj = v8::Object::new(scope);
|
|
430
|
+
|
|
431
|
+
// Store connection string in a hidden property
|
|
432
|
+
let conn_key = v8_str(scope, "__conn_string");
|
|
433
|
+
let conn_val = v8_str(scope, &conn_string);
|
|
434
|
+
db_conn_obj.set(scope, conn_key.into(), conn_val.into());
|
|
435
|
+
|
|
436
|
+
// Add query method
|
|
437
|
+
let query_fn = v8::Function::new(scope, native_db_query).unwrap();
|
|
438
|
+
let query_key = v8_str(scope, "query");
|
|
439
|
+
db_conn_obj.set(scope, query_key.into(), query_fn.into());
|
|
440
|
+
|
|
441
|
+
retval.set(db_conn_obj.into());
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
fn native_db_query(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
445
|
+
// Get 'this' context (the db connection object)
|
|
446
|
+
let this = args.this();
|
|
447
|
+
let this_obj = this.to_object(scope).unwrap();
|
|
448
|
+
|
|
449
|
+
// Retrieve connection string
|
|
450
|
+
let conn_key = v8_str(scope, "__conn_string");
|
|
451
|
+
let conn_val = this_obj.get(scope, conn_key.into()).unwrap();
|
|
452
|
+
let conn_string = v8_to_string(scope, conn_val);
|
|
453
|
+
|
|
454
|
+
// Get query string
|
|
455
|
+
let query = v8_to_string(scope, args.get(0));
|
|
456
|
+
|
|
457
|
+
if query.is_empty() {
|
|
458
|
+
throw(scope, "db.query(): SQL query is required");
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// Return Metadata (Non-blocking)
|
|
463
|
+
let obj = v8::Object::new(scope);
|
|
464
|
+
let op_key = v8_str(scope, "__titanAsync");
|
|
465
|
+
let op_val = v8::Boolean::new(scope, true);
|
|
466
|
+
obj.set(scope, op_key.into(), op_val.into());
|
|
467
|
+
|
|
468
|
+
let type_key = v8_str(scope, "type");
|
|
469
|
+
let type_val = v8_str(scope, "db_query");
|
|
470
|
+
obj.set(scope, type_key.into(), type_val.into());
|
|
471
|
+
|
|
472
|
+
let data_obj = v8::Object::new(scope);
|
|
473
|
+
let conn_k = v8_str(scope, "conn");
|
|
474
|
+
let conn_v = v8_str(scope, &conn_string);
|
|
475
|
+
data_obj.set(scope, conn_k.into(), conn_v.into());
|
|
476
|
+
|
|
477
|
+
let q_k = v8_str(scope, "query");
|
|
478
|
+
let q_v = v8_str(scope, &query);
|
|
479
|
+
data_obj.set(scope, q_k.into(), q_v.into());
|
|
480
|
+
|
|
481
|
+
let data_key = v8_str(scope, "data");
|
|
482
|
+
obj.set(scope, data_key.into(), data_obj.into());
|
|
483
|
+
|
|
484
|
+
retval.set(obj.into());
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
fn native_fetch_meta(scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
488
|
+
let url = v8_to_string(scope, args.get(0));
|
|
489
|
+
let opts = args.get(1);
|
|
490
|
+
|
|
491
|
+
let obj = v8::Object::new(scope);
|
|
492
|
+
let op_key = v8_str(scope, "__titanAsync");
|
|
493
|
+
let op_val = v8::Boolean::new(scope, true);
|
|
494
|
+
obj.set(scope, op_key.into(), op_val.into());
|
|
495
|
+
|
|
496
|
+
let type_key = v8_str(scope, "type");
|
|
497
|
+
let type_val = v8_str(scope, "fetch");
|
|
498
|
+
obj.set(scope, type_key.into(), type_val.into());
|
|
499
|
+
|
|
500
|
+
let data_obj = v8::Object::new(scope);
|
|
501
|
+
let url_key = v8_str(scope, "url");
|
|
502
|
+
let url_val = v8_str(scope, &url);
|
|
503
|
+
data_obj.set(scope, url_key.into(), url_val.into());
|
|
504
|
+
|
|
505
|
+
let opts_key = v8_str(scope, "opts");
|
|
506
|
+
data_obj.set(scope, opts_key.into(), opts);
|
|
507
|
+
|
|
508
|
+
let data_key = v8_str(scope, "data");
|
|
509
|
+
obj.set(scope, data_key.into(), data_obj.into());
|
|
510
|
+
|
|
511
|
+
retval.set(obj.into());
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
fn parse_async_op(scope: &mut v8::HandleScope, op_val: v8::Local<v8::Value>) -> Option<super::TitanAsyncOp> {
|
|
515
|
+
if !op_val.is_object() { return None; }
|
|
516
|
+
let op_obj = op_val.to_object(scope).unwrap();
|
|
517
|
+
|
|
518
|
+
let type_key = v8_str(scope, "type");
|
|
519
|
+
let type_obj = op_obj.get(scope, type_key.into())?;
|
|
520
|
+
let op_type = v8_to_string(scope, type_obj);
|
|
521
|
+
|
|
522
|
+
let data_key = v8_str(scope, "data");
|
|
523
|
+
let data_val = op_obj.get(scope, data_key.into())?;
|
|
524
|
+
if !data_val.is_object() { return None; }
|
|
525
|
+
let data_obj = data_val.to_object(scope).unwrap();
|
|
526
|
+
|
|
527
|
+
match op_type.as_str() {
|
|
528
|
+
"fetch" => {
|
|
529
|
+
let url_key = v8_str(scope, "url");
|
|
530
|
+
let url_obj = data_obj.get(scope, url_key.into())?;
|
|
531
|
+
let url = v8_to_string(scope, url_obj);
|
|
532
|
+
|
|
533
|
+
let mut method = "GET".to_string();
|
|
534
|
+
let mut body = None;
|
|
535
|
+
let mut headers = Vec::new();
|
|
536
|
+
|
|
537
|
+
let opts_key = v8_str(scope, "opts");
|
|
538
|
+
if let Some(opts_val) = data_obj.get(scope, opts_key.into()) {
|
|
539
|
+
if opts_val.is_object() {
|
|
540
|
+
let opts_obj = opts_val.to_object(scope).unwrap();
|
|
541
|
+
let m_key = v8_str(scope, "method");
|
|
542
|
+
if let Some(m_val) = opts_obj.get(scope, m_key.into()) {
|
|
543
|
+
if m_val.is_string() { method = v8_to_string(scope, m_val); }
|
|
544
|
+
}
|
|
545
|
+
let b_key = v8_str(scope, "body");
|
|
546
|
+
if let Some(b_val) = opts_obj.get(scope, b_key.into()) {
|
|
547
|
+
if b_val.is_string() {
|
|
548
|
+
body = Some(v8_to_string(scope, b_val));
|
|
549
|
+
} else if b_val.is_object() {
|
|
550
|
+
body = Some(v8::json::stringify(scope, b_val).unwrap().to_rust_string_lossy(scope));
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
let h_key = v8_str(scope, "headers");
|
|
554
|
+
if let Some(h_val) = opts_obj.get(scope, h_key.into()) {
|
|
555
|
+
if h_val.is_object() {
|
|
556
|
+
let h_obj = h_val.to_object(scope).unwrap();
|
|
557
|
+
if let Some(keys) = h_obj.get_own_property_names(scope, Default::default()) {
|
|
558
|
+
for i in 0..keys.length() {
|
|
559
|
+
let key = keys.get_index(scope, i).unwrap();
|
|
560
|
+
let val = h_obj.get(scope, key).unwrap();
|
|
561
|
+
headers.push((v8_to_string(scope, key), v8_to_string(scope, val)));
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
Some(super::TitanAsyncOp::Fetch { url, method, body, headers })
|
|
569
|
+
},
|
|
570
|
+
"db_query" => {
|
|
571
|
+
let conn_key = v8_str(scope, "conn");
|
|
572
|
+
let conn_obj = data_obj.get(scope, conn_key.into())?;
|
|
573
|
+
let conn = v8_to_string(scope, conn_obj);
|
|
574
|
+
let query_key = v8_str(scope, "query");
|
|
575
|
+
let query_obj = data_obj.get(scope, query_key.into())?;
|
|
576
|
+
let query = v8_to_string(scope, query_obj);
|
|
577
|
+
Some(super::TitanAsyncOp::DbQuery { conn, query })
|
|
578
|
+
},
|
|
579
|
+
"fs_read" => {
|
|
580
|
+
let path_key = v8_str(scope, "path");
|
|
581
|
+
let path_obj = data_obj.get(scope, path_key.into())?;
|
|
582
|
+
let path = v8_to_string(scope, path_obj);
|
|
583
|
+
Some(super::TitanAsyncOp::FsRead { path })
|
|
584
|
+
},
|
|
585
|
+
_ => None
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
fn native_drift_call(scope: &mut v8::HandleScope, mut args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue) {
|
|
590
|
+
let runtime_ptr = unsafe { args.get_isolate() }.get_data(0) as *mut super::TitanRuntime;
|
|
591
|
+
let runtime = unsafe { &mut *runtime_ptr };
|
|
592
|
+
// let isolate_id = runtime.id; // We can use runtime.id directly later
|
|
593
|
+
|
|
594
|
+
let arg0 = args.get(0);
|
|
595
|
+
|
|
596
|
+
let (async_op, op_type) = if arg0.is_array() {
|
|
597
|
+
let arr = v8::Local::<v8::Array>::try_from(arg0).unwrap();
|
|
598
|
+
let mut ops = Vec::new();
|
|
599
|
+
for i in 0..arr.length() {
|
|
600
|
+
let op_val = arr.get_index(scope, i).unwrap();
|
|
601
|
+
if let Some(op) = parse_async_op(scope, op_val) {
|
|
602
|
+
ops.push(op);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
(super::TitanAsyncOp::Batch(ops), "batch".to_string())
|
|
606
|
+
} else {
|
|
607
|
+
match parse_async_op(scope, arg0) {
|
|
608
|
+
Some(op) => {
|
|
609
|
+
let t = match &op {
|
|
610
|
+
super::TitanAsyncOp::Fetch { .. } => "fetch",
|
|
611
|
+
super::TitanAsyncOp::DbQuery { .. } => "db_query",
|
|
612
|
+
super::TitanAsyncOp::FsRead { .. } => "fs_read",
|
|
613
|
+
_ => "unknown"
|
|
614
|
+
};
|
|
615
|
+
(op, t.to_string())
|
|
616
|
+
},
|
|
617
|
+
None => {
|
|
618
|
+
throw(scope, "drift() requires an async operation or array of operations");
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
};
|
|
623
|
+
|
|
624
|
+
let runtime_ptr = unsafe { args.get_isolate() }.get_data(0) as *mut super::TitanRuntime;
|
|
625
|
+
let runtime = unsafe { &mut *runtime_ptr };
|
|
626
|
+
|
|
627
|
+
// Extract request_id from globalThis.__titan_req.__titan_request_id
|
|
628
|
+
let req_id = {
|
|
629
|
+
let context = scope.get_current_context();
|
|
630
|
+
let global = context.global(scope);
|
|
631
|
+
let req_key = v8_str(scope, "__titan_req");
|
|
632
|
+
if let Some(req_obj_val) = global.get(scope, req_key.into()) {
|
|
633
|
+
if req_obj_val.is_object() {
|
|
634
|
+
let req_obj = req_obj_val.to_object(scope).unwrap();
|
|
635
|
+
let id_key = v8_str(scope, "__titan_request_id");
|
|
636
|
+
req_obj.get(scope, id_key.into()).unwrap().uint32_value(scope).unwrap_or(0)
|
|
637
|
+
} else { 0 }
|
|
638
|
+
} else { 0 }
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
runtime.drift_counter += 1;
|
|
642
|
+
let drift_id = runtime.drift_counter;
|
|
643
|
+
|
|
644
|
+
if req_id != 0 {
|
|
645
|
+
runtime.drift_to_request.insert(drift_id, req_id);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// --- REPLAY CHECK ---
|
|
649
|
+
// If the result exists, return it immediately (Replay Phase)
|
|
650
|
+
// IMPORTANT: Use .get() not .remove() to allow multiple drifts in the same action
|
|
651
|
+
if let Some(res) = runtime.completed_drifts.get(&drift_id) {
|
|
652
|
+
let json_str = serde_json::to_string(res).unwrap_or_else(|_| "null".to_string());
|
|
653
|
+
let v8_str = v8::String::new(scope, &json_str).unwrap();
|
|
654
|
+
let mut try_catch = v8::TryCatch::new(scope);
|
|
655
|
+
if let Some(val) = v8::json::parse(&mut try_catch, v8_str) {
|
|
656
|
+
retval.set(val);
|
|
657
|
+
} else {
|
|
658
|
+
retval.set(v8::null(&mut try_catch).into());
|
|
659
|
+
}
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
let (tx, rx) = tokio::sync::oneshot::channel::<super::WorkerAsyncResult>();
|
|
664
|
+
|
|
665
|
+
// Send to global async executor
|
|
666
|
+
let req = super::AsyncOpRequest {
|
|
667
|
+
op: async_op,
|
|
668
|
+
drift_id,
|
|
669
|
+
request_id: req_id,
|
|
670
|
+
op_type,
|
|
671
|
+
respond_tx: tx,
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
if let Err(e) = runtime.global_async_tx.try_send(req) {
|
|
675
|
+
println!("[Titan] Drift Call Failed to queue: {}", e);
|
|
676
|
+
retval.set(v8::null(scope).into());
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// --- SUSPENSION THROW ---
|
|
681
|
+
// We throw a specific exception to halt execution. The Runtime catches this,
|
|
682
|
+
// frees the worker, and waits for the async result.
|
|
683
|
+
|
|
684
|
+
// Trigger Tokio task completion handling in a separate bridge
|
|
685
|
+
let tokio_handle = runtime.tokio_handle.clone();
|
|
686
|
+
let worker_tx = runtime.worker_tx.clone();
|
|
687
|
+
let isolate_id = runtime.id;
|
|
688
|
+
|
|
689
|
+
tokio_handle.spawn(async move {
|
|
690
|
+
if let Ok(res) = rx.await {
|
|
691
|
+
// Signal the pool to RESUME (REPLAY) this specific isolate
|
|
692
|
+
let _ = worker_tx.send(crate::runtime::WorkerCommand::Resume {
|
|
693
|
+
isolate_id,
|
|
694
|
+
drift_id,
|
|
695
|
+
result: res,
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
});
|
|
699
|
+
|
|
700
|
+
throw(scope, "__SUSPEND__");
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
fn native_finish_request(scope: &mut v8::HandleScope, mut args: v8::FunctionCallbackArguments, _retval: v8::ReturnValue) {
|
|
704
|
+
let request_id = args.get(0).uint32_value(scope).unwrap_or(0);
|
|
705
|
+
let result_val = args.get(1);
|
|
706
|
+
|
|
707
|
+
let json = super::v8_to_json(scope, result_val);
|
|
708
|
+
|
|
709
|
+
let runtime_ptr = unsafe { args.get_isolate() }.get_data(0) as *mut super::TitanRuntime;
|
|
710
|
+
let runtime = unsafe { &mut *runtime_ptr };
|
|
711
|
+
|
|
712
|
+
let timings = runtime.request_timings.remove(&request_id).unwrap_or_default();
|
|
713
|
+
|
|
714
|
+
// Cleanup drift mapping for this request
|
|
715
|
+
runtime.drift_to_request.retain(|drift_id, v| {
|
|
716
|
+
if *v == request_id {
|
|
717
|
+
runtime.completed_drifts.remove(drift_id);
|
|
718
|
+
false
|
|
719
|
+
} else {
|
|
720
|
+
true
|
|
721
|
+
}
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
if let Some(tx) = runtime.pending_requests.remove(&request_id) {
|
|
725
|
+
let _ = tx.send(crate::runtime::WorkerResult { json, timings });
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
pub async fn run_single_op(op: super::TitanAsyncOp) -> serde_json::Value {
|
|
730
|
+
match op {
|
|
731
|
+
super::TitanAsyncOp::Fetch { url, method, body, headers } => {
|
|
732
|
+
let client = get_http_client();
|
|
733
|
+
let mut req = client.request(method.parse().unwrap_or(reqwest::Method::GET), &url);
|
|
734
|
+
if let Some(b) = body { req = req.body(b); }
|
|
735
|
+
for (k, v) in headers {
|
|
736
|
+
if let (Ok(name), Ok(val)) = (reqwest::header::HeaderName::from_bytes(k.as_bytes()), reqwest::header::HeaderValue::from_str(&v)) {
|
|
737
|
+
req = req.header(name, val);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
match req.send().await {
|
|
741
|
+
Ok(res) => {
|
|
742
|
+
let status = res.status().as_u16();
|
|
743
|
+
let text = res.text().await.unwrap_or_default();
|
|
744
|
+
serde_json::json!({ "status": status, "body": text, "ok": true })
|
|
745
|
+
},
|
|
746
|
+
Err(e) => serde_json::json!({ "error": e.to_string(), "ok": false })
|
|
747
|
+
}
|
|
748
|
+
},
|
|
749
|
+
super::TitanAsyncOp::FsRead { path } => {
|
|
750
|
+
let root = super::PROJECT_ROOT.get().cloned().unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
|
|
751
|
+
let joined = root.join(&path);
|
|
752
|
+
|
|
753
|
+
// Basic security check
|
|
754
|
+
if let Ok(target) = joined.canonicalize() {
|
|
755
|
+
if target.starts_with(&root.canonicalize().unwrap_or(root)) {
|
|
756
|
+
match std::fs::read_to_string(&target) {
|
|
757
|
+
Ok(content) => serde_json::json!(content),
|
|
758
|
+
Err(e) => serde_json::json!({ "error": format!("File read failed: {}", e) })
|
|
759
|
+
}
|
|
760
|
+
} else {
|
|
761
|
+
serde_json::json!({ "error": "Path escapes project root" })
|
|
762
|
+
}
|
|
763
|
+
} else {
|
|
764
|
+
serde_json::json!({ "error": format!("File not found: {}", path) })
|
|
765
|
+
}
|
|
766
|
+
},
|
|
767
|
+
super::TitanAsyncOp::DbQuery { conn, query } => {
|
|
768
|
+
tokio::task::spawn_blocking(move || {
|
|
769
|
+
let mut pool = DB_POOL.lock().unwrap();
|
|
770
|
+
if let Some(map) = pool.as_mut() {
|
|
771
|
+
if let Some(client) = map.get_mut(&conn) {
|
|
772
|
+
return match client.query(&query, &[]) {
|
|
773
|
+
Ok(rows) => {
|
|
774
|
+
let mut result = Vec::new();
|
|
775
|
+
for row in rows {
|
|
776
|
+
let mut obj = serde_json::Map::new();
|
|
777
|
+
for (i, column) in row.columns().iter().enumerate() {
|
|
778
|
+
let col_name = column.name();
|
|
779
|
+
let col_value: serde_json::Value = if let Ok(val) = row.try_get::<_, Option<String>>(i) {
|
|
780
|
+
serde_json::json!(val)
|
|
781
|
+
} else if let Ok(val) = row.try_get::<_, Option<i32>>(i) {
|
|
782
|
+
serde_json::json!(val)
|
|
783
|
+
} else if let Ok(val) = row.try_get::<_, Option<i64>>(i) {
|
|
784
|
+
serde_json::json!(val)
|
|
785
|
+
} else if let Ok(val) = row.try_get::<_, Option<f64>>(i) {
|
|
786
|
+
serde_json::json!(val)
|
|
787
|
+
} else if let Ok(val) = row.try_get::<_, Option<bool>>(i) {
|
|
788
|
+
serde_json::json!(val)
|
|
789
|
+
} else {
|
|
790
|
+
serde_json::Value::Null
|
|
791
|
+
};
|
|
792
|
+
obj.insert(col_name.to_string(), col_value);
|
|
793
|
+
}
|
|
794
|
+
result.push(serde_json::Value::Object(obj));
|
|
795
|
+
}
|
|
796
|
+
serde_json::Value::Array(result)
|
|
797
|
+
},
|
|
798
|
+
Err(e) => serde_json::json!({ "error": e.to_string() })
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
serde_json::json!({ "error": "Database connection not found" })
|
|
803
|
+
}).await.unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }))
|
|
804
|
+
},
|
|
805
|
+
_ => serde_json::json!({ "error": "Invalid operation" })
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
pub async fn run_async_operation(op: super::TitanAsyncOp) -> serde_json::Value {
|
|
810
|
+
match op {
|
|
811
|
+
super::TitanAsyncOp::Batch(ops) => {
|
|
812
|
+
let mut set = tokio::task::JoinSet::new();
|
|
813
|
+
for (i, op) in ops.into_iter().enumerate() {
|
|
814
|
+
set.spawn(async move {
|
|
815
|
+
(i, run_single_op(op).await)
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
let mut results_map = std::collections::BTreeMap::new();
|
|
819
|
+
while let Some(res) = set.join_next().await {
|
|
820
|
+
if let Ok((i, val)) = res {
|
|
821
|
+
results_map.insert(i, val);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
serde_json::Value::Array(results_map.into_values().collect())
|
|
825
|
+
},
|
|
826
|
+
_ => run_single_op(op).await
|
|
827
|
+
}
|
|
828
|
+
}
|