titanpl 6.0.0 → 7.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.
Files changed (227) hide show
  1. package/package.json +2 -6
  2. package/packages/cli/index.js +25 -11
  3. package/packages/cli/package.json +4 -4
  4. package/packages/cli/src/commands/build-ext.js +157 -0
  5. package/packages/cli/src/commands/build.js +12 -0
  6. package/packages/cli/src/commands/create.js +160 -0
  7. package/packages/cli/src/commands/init.js +5 -11
  8. package/packages/cli/src/commands/run-ext.js +104 -0
  9. package/{titanpl-sdk → packages/core-source}/LICENSE +1 -1
  10. package/packages/core-source/README.md +128 -0
  11. package/packages/core-source/V8_SERIALIZATION.md +125 -0
  12. package/packages/core-source/configure.js +50 -0
  13. package/packages/core-source/globals.d.ts +2238 -0
  14. package/packages/core-source/index.d.ts +515 -0
  15. package/packages/core-source/index.js +639 -0
  16. package/packages/core-source/jsconfig.json +12 -0
  17. package/packages/core-source/mkctx.config.json +7 -0
  18. package/packages/core-source/native/Cargo.lock +1559 -0
  19. package/packages/core-source/native/Cargo.toml +30 -0
  20. package/packages/core-source/native/src/crypto_impl.rs +139 -0
  21. package/packages/core-source/native/src/lib.rs +702 -0
  22. package/packages/core-source/native/src/storage_impl.rs +73 -0
  23. package/packages/core-source/native/src/v8_impl.rs +93 -0
  24. package/packages/core-source/package-lock.json +1464 -0
  25. package/packages/core-source/package.json +53 -0
  26. package/packages/core-source/tests/buffer.test.js +78 -0
  27. package/packages/core-source/tests/cookies.test.js +117 -0
  28. package/packages/core-source/tests/crypto.test.js +142 -0
  29. package/packages/core-source/tests/fs.test.js +176 -0
  30. package/packages/core-source/tests/ls.test.js +149 -0
  31. package/packages/core-source/tests/net.test.js +84 -0
  32. package/packages/core-source/tests/os.test.js +81 -0
  33. package/packages/core-source/tests/path.test.js +102 -0
  34. package/packages/core-source/tests/response.test.js +146 -0
  35. package/packages/core-source/tests/session.test.js +110 -0
  36. package/packages/core-source/tests/setup.js +325 -0
  37. package/packages/core-source/tests/time.test.js +57 -0
  38. package/packages/core-source/tests/url.test.js +82 -0
  39. package/packages/core-source/titan-ext.d.ts +2 -0
  40. package/packages/core-source/titan.json +9 -0
  41. package/packages/core-source/vitest.config.js +8 -0
  42. package/packages/engine-darwin-arm64/README.md +0 -2
  43. package/packages/engine-darwin-arm64/package.json +1 -1
  44. package/packages/engine-linux-x64/README.md +0 -2
  45. package/packages/engine-linux-x64/package.json +1 -1
  46. package/packages/engine-win32-x64/README.md +0 -1
  47. package/packages/engine-win32-x64/bin/titan-server.exe +0 -0
  48. package/packages/engine-win32-x64/package.json +1 -1
  49. package/packages/native/README.md +0 -1
  50. package/packages/native/index.d.ts +25 -4
  51. package/packages/native/index.js +7 -0
  52. package/packages/native/package.json +2 -2
  53. package/packages/native/t.native.d.ts +167 -2
  54. package/packages/packet/index.js +103 -94
  55. package/packages/packet/package.json +1 -1
  56. package/packages/route/package.json +1 -1
  57. package/packages/sdk/index.js +2 -0
  58. package/packages/sdk/package.json +18 -0
  59. package/packages/sdk/test/index.js +120 -0
  60. package/templates/common/_tanfig.json +19 -13
  61. package/templates/extension/index.d.ts +26 -22
  62. package/templates/extension/index.js +15 -15
  63. package/templates/extension/native/Cargo.toml +5 -3
  64. package/templates/extension/native/src/lib.rs +2 -3
  65. package/templates/extension/package.json +10 -20
  66. package/templates/extension/titan.json +5 -16
  67. package/templates/extension/utils/registerExtension.js +44 -0
  68. package/templates/js/package.json +8 -8
  69. package/templates/rust-js/package.json +5 -5
  70. package/templates/rust-ts/package.json +5 -5
  71. package/templates/ts/package.json +8 -8
  72. package/packages/packet/node_modules/typescript/LICENSE.txt +0 -55
  73. package/packages/packet/node_modules/typescript/README.md +0 -50
  74. package/packages/packet/node_modules/typescript/SECURITY.md +0 -41
  75. package/packages/packet/node_modules/typescript/ThirdPartyNoticeText.txt +0 -193
  76. package/packages/packet/node_modules/typescript/bin/tsc +0 -2
  77. package/packages/packet/node_modules/typescript/bin/tsserver +0 -2
  78. package/packages/packet/node_modules/typescript/lib/_tsc.js +0 -133818
  79. package/packages/packet/node_modules/typescript/lib/_tsserver.js +0 -659
  80. package/packages/packet/node_modules/typescript/lib/_typingsInstaller.js +0 -222
  81. package/packages/packet/node_modules/typescript/lib/cs/diagnosticMessages.generated.json +0 -2122
  82. package/packages/packet/node_modules/typescript/lib/de/diagnosticMessages.generated.json +0 -2122
  83. package/packages/packet/node_modules/typescript/lib/es/diagnosticMessages.generated.json +0 -2122
  84. package/packages/packet/node_modules/typescript/lib/fr/diagnosticMessages.generated.json +0 -2122
  85. package/packages/packet/node_modules/typescript/lib/it/diagnosticMessages.generated.json +0 -2122
  86. package/packages/packet/node_modules/typescript/lib/ja/diagnosticMessages.generated.json +0 -2122
  87. package/packages/packet/node_modules/typescript/lib/ko/diagnosticMessages.generated.json +0 -2122
  88. package/packages/packet/node_modules/typescript/lib/lib.d.ts +0 -22
  89. package/packages/packet/node_modules/typescript/lib/lib.decorators.d.ts +0 -384
  90. package/packages/packet/node_modules/typescript/lib/lib.decorators.legacy.d.ts +0 -22
  91. package/packages/packet/node_modules/typescript/lib/lib.dom.asynciterable.d.ts +0 -41
  92. package/packages/packet/node_modules/typescript/lib/lib.dom.d.ts +0 -39429
  93. package/packages/packet/node_modules/typescript/lib/lib.dom.iterable.d.ts +0 -571
  94. package/packages/packet/node_modules/typescript/lib/lib.es2015.collection.d.ts +0 -147
  95. package/packages/packet/node_modules/typescript/lib/lib.es2015.core.d.ts +0 -597
  96. package/packages/packet/node_modules/typescript/lib/lib.es2015.d.ts +0 -28
  97. package/packages/packet/node_modules/typescript/lib/lib.es2015.generator.d.ts +0 -77
  98. package/packages/packet/node_modules/typescript/lib/lib.es2015.iterable.d.ts +0 -605
  99. package/packages/packet/node_modules/typescript/lib/lib.es2015.promise.d.ts +0 -81
  100. package/packages/packet/node_modules/typescript/lib/lib.es2015.proxy.d.ts +0 -128
  101. package/packages/packet/node_modules/typescript/lib/lib.es2015.reflect.d.ts +0 -144
  102. package/packages/packet/node_modules/typescript/lib/lib.es2015.symbol.d.ts +0 -46
  103. package/packages/packet/node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts +0 -326
  104. package/packages/packet/node_modules/typescript/lib/lib.es2016.array.include.d.ts +0 -116
  105. package/packages/packet/node_modules/typescript/lib/lib.es2016.d.ts +0 -21
  106. package/packages/packet/node_modules/typescript/lib/lib.es2016.full.d.ts +0 -23
  107. package/packages/packet/node_modules/typescript/lib/lib.es2016.intl.d.ts +0 -31
  108. package/packages/packet/node_modules/typescript/lib/lib.es2017.arraybuffer.d.ts +0 -21
  109. package/packages/packet/node_modules/typescript/lib/lib.es2017.d.ts +0 -26
  110. package/packages/packet/node_modules/typescript/lib/lib.es2017.date.d.ts +0 -31
  111. package/packages/packet/node_modules/typescript/lib/lib.es2017.full.d.ts +0 -23
  112. package/packages/packet/node_modules/typescript/lib/lib.es2017.intl.d.ts +0 -44
  113. package/packages/packet/node_modules/typescript/lib/lib.es2017.object.d.ts +0 -49
  114. package/packages/packet/node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts +0 -135
  115. package/packages/packet/node_modules/typescript/lib/lib.es2017.string.d.ts +0 -45
  116. package/packages/packet/node_modules/typescript/lib/lib.es2017.typedarrays.d.ts +0 -53
  117. package/packages/packet/node_modules/typescript/lib/lib.es2018.asyncgenerator.d.ts +0 -77
  118. package/packages/packet/node_modules/typescript/lib/lib.es2018.asynciterable.d.ts +0 -53
  119. package/packages/packet/node_modules/typescript/lib/lib.es2018.d.ts +0 -24
  120. package/packages/packet/node_modules/typescript/lib/lib.es2018.full.d.ts +0 -24
  121. package/packages/packet/node_modules/typescript/lib/lib.es2018.intl.d.ts +0 -83
  122. package/packages/packet/node_modules/typescript/lib/lib.es2018.promise.d.ts +0 -30
  123. package/packages/packet/node_modules/typescript/lib/lib.es2018.regexp.d.ts +0 -37
  124. package/packages/packet/node_modules/typescript/lib/lib.es2019.array.d.ts +0 -79
  125. package/packages/packet/node_modules/typescript/lib/lib.es2019.d.ts +0 -24
  126. package/packages/packet/node_modules/typescript/lib/lib.es2019.full.d.ts +0 -24
  127. package/packages/packet/node_modules/typescript/lib/lib.es2019.intl.d.ts +0 -23
  128. package/packages/packet/node_modules/typescript/lib/lib.es2019.object.d.ts +0 -33
  129. package/packages/packet/node_modules/typescript/lib/lib.es2019.string.d.ts +0 -37
  130. package/packages/packet/node_modules/typescript/lib/lib.es2019.symbol.d.ts +0 -24
  131. package/packages/packet/node_modules/typescript/lib/lib.es2020.bigint.d.ts +0 -765
  132. package/packages/packet/node_modules/typescript/lib/lib.es2020.d.ts +0 -27
  133. package/packages/packet/node_modules/typescript/lib/lib.es2020.date.d.ts +0 -42
  134. package/packages/packet/node_modules/typescript/lib/lib.es2020.full.d.ts +0 -24
  135. package/packages/packet/node_modules/typescript/lib/lib.es2020.intl.d.ts +0 -474
  136. package/packages/packet/node_modules/typescript/lib/lib.es2020.number.d.ts +0 -28
  137. package/packages/packet/node_modules/typescript/lib/lib.es2020.promise.d.ts +0 -47
  138. package/packages/packet/node_modules/typescript/lib/lib.es2020.sharedmemory.d.ts +0 -99
  139. package/packages/packet/node_modules/typescript/lib/lib.es2020.string.d.ts +0 -44
  140. package/packages/packet/node_modules/typescript/lib/lib.es2020.symbol.wellknown.d.ts +0 -41
  141. package/packages/packet/node_modules/typescript/lib/lib.es2021.d.ts +0 -23
  142. package/packages/packet/node_modules/typescript/lib/lib.es2021.full.d.ts +0 -24
  143. package/packages/packet/node_modules/typescript/lib/lib.es2021.intl.d.ts +0 -166
  144. package/packages/packet/node_modules/typescript/lib/lib.es2021.promise.d.ts +0 -48
  145. package/packages/packet/node_modules/typescript/lib/lib.es2021.string.d.ts +0 -33
  146. package/packages/packet/node_modules/typescript/lib/lib.es2021.weakref.d.ts +0 -78
  147. package/packages/packet/node_modules/typescript/lib/lib.es2022.array.d.ts +0 -121
  148. package/packages/packet/node_modules/typescript/lib/lib.es2022.d.ts +0 -25
  149. package/packages/packet/node_modules/typescript/lib/lib.es2022.error.d.ts +0 -75
  150. package/packages/packet/node_modules/typescript/lib/lib.es2022.full.d.ts +0 -24
  151. package/packages/packet/node_modules/typescript/lib/lib.es2022.intl.d.ts +0 -145
  152. package/packages/packet/node_modules/typescript/lib/lib.es2022.object.d.ts +0 -26
  153. package/packages/packet/node_modules/typescript/lib/lib.es2022.regexp.d.ts +0 -39
  154. package/packages/packet/node_modules/typescript/lib/lib.es2022.string.d.ts +0 -25
  155. package/packages/packet/node_modules/typescript/lib/lib.es2023.array.d.ts +0 -924
  156. package/packages/packet/node_modules/typescript/lib/lib.es2023.collection.d.ts +0 -21
  157. package/packages/packet/node_modules/typescript/lib/lib.es2023.d.ts +0 -22
  158. package/packages/packet/node_modules/typescript/lib/lib.es2023.full.d.ts +0 -24
  159. package/packages/packet/node_modules/typescript/lib/lib.es2023.intl.d.ts +0 -56
  160. package/packages/packet/node_modules/typescript/lib/lib.es2024.arraybuffer.d.ts +0 -65
  161. package/packages/packet/node_modules/typescript/lib/lib.es2024.collection.d.ts +0 -29
  162. package/packages/packet/node_modules/typescript/lib/lib.es2024.d.ts +0 -26
  163. package/packages/packet/node_modules/typescript/lib/lib.es2024.full.d.ts +0 -24
  164. package/packages/packet/node_modules/typescript/lib/lib.es2024.object.d.ts +0 -29
  165. package/packages/packet/node_modules/typescript/lib/lib.es2024.promise.d.ts +0 -35
  166. package/packages/packet/node_modules/typescript/lib/lib.es2024.regexp.d.ts +0 -25
  167. package/packages/packet/node_modules/typescript/lib/lib.es2024.sharedmemory.d.ts +0 -68
  168. package/packages/packet/node_modules/typescript/lib/lib.es2024.string.d.ts +0 -29
  169. package/packages/packet/node_modules/typescript/lib/lib.es5.d.ts +0 -4601
  170. package/packages/packet/node_modules/typescript/lib/lib.es6.d.ts +0 -23
  171. package/packages/packet/node_modules/typescript/lib/lib.esnext.array.d.ts +0 -35
  172. package/packages/packet/node_modules/typescript/lib/lib.esnext.collection.d.ts +0 -96
  173. package/packages/packet/node_modules/typescript/lib/lib.esnext.d.ts +0 -29
  174. package/packages/packet/node_modules/typescript/lib/lib.esnext.decorators.d.ts +0 -28
  175. package/packages/packet/node_modules/typescript/lib/lib.esnext.disposable.d.ts +0 -193
  176. package/packages/packet/node_modules/typescript/lib/lib.esnext.error.d.ts +0 -24
  177. package/packages/packet/node_modules/typescript/lib/lib.esnext.float16.d.ts +0 -445
  178. package/packages/packet/node_modules/typescript/lib/lib.esnext.full.d.ts +0 -24
  179. package/packages/packet/node_modules/typescript/lib/lib.esnext.intl.d.ts +0 -21
  180. package/packages/packet/node_modules/typescript/lib/lib.esnext.iterator.d.ts +0 -148
  181. package/packages/packet/node_modules/typescript/lib/lib.esnext.promise.d.ts +0 -34
  182. package/packages/packet/node_modules/typescript/lib/lib.esnext.sharedmemory.d.ts +0 -25
  183. package/packages/packet/node_modules/typescript/lib/lib.scripthost.d.ts +0 -322
  184. package/packages/packet/node_modules/typescript/lib/lib.webworker.asynciterable.d.ts +0 -41
  185. package/packages/packet/node_modules/typescript/lib/lib.webworker.d.ts +0 -13150
  186. package/packages/packet/node_modules/typescript/lib/lib.webworker.importscripts.d.ts +0 -23
  187. package/packages/packet/node_modules/typescript/lib/lib.webworker.iterable.d.ts +0 -340
  188. package/packages/packet/node_modules/typescript/lib/pl/diagnosticMessages.generated.json +0 -2122
  189. package/packages/packet/node_modules/typescript/lib/pt-br/diagnosticMessages.generated.json +0 -2122
  190. package/packages/packet/node_modules/typescript/lib/ru/diagnosticMessages.generated.json +0 -2122
  191. package/packages/packet/node_modules/typescript/lib/tr/diagnosticMessages.generated.json +0 -2122
  192. package/packages/packet/node_modules/typescript/lib/tsc.js +0 -8
  193. package/packages/packet/node_modules/typescript/lib/tsserver.js +0 -8
  194. package/packages/packet/node_modules/typescript/lib/tsserverlibrary.d.ts +0 -17
  195. package/packages/packet/node_modules/typescript/lib/tsserverlibrary.js +0 -21
  196. package/packages/packet/node_modules/typescript/lib/typesMap.json +0 -497
  197. package/packages/packet/node_modules/typescript/lib/typescript.d.ts +0 -11437
  198. package/packages/packet/node_modules/typescript/lib/typescript.js +0 -200276
  199. package/packages/packet/node_modules/typescript/lib/typingsInstaller.js +0 -8
  200. package/packages/packet/node_modules/typescript/lib/watchGuard.js +0 -53
  201. package/packages/packet/node_modules/typescript/lib/zh-cn/diagnosticMessages.generated.json +0 -2122
  202. package/packages/packet/node_modules/typescript/lib/zh-tw/diagnosticMessages.generated.json +0 -2122
  203. package/packages/packet/node_modules/typescript/package.json +0 -120
  204. package/titanpl-sdk/README.md +0 -111
  205. package/titanpl-sdk/assets/titanpl-sdk.png +0 -0
  206. package/titanpl-sdk/bin/run.js +0 -274
  207. package/titanpl-sdk/index.js +0 -5
  208. package/titanpl-sdk/package-lock.json +0 -28
  209. package/titanpl-sdk/package.json +0 -40
  210. package/titanpl-sdk/templates/app/actions/hello.js +0 -5
  211. package/titanpl-sdk/templates/app/app.js +0 -7
  212. package/titanpl-sdk/templates/jsconfig.json +0 -19
  213. package/titanpl-sdk/templates/server/Cargo.toml +0 -52
  214. package/titanpl-sdk/templates/server/src/action_management.rs +0 -175
  215. package/titanpl-sdk/templates/server/src/errors.rs +0 -12
  216. package/titanpl-sdk/templates/server/src/extensions/builtin.rs +0 -1060
  217. package/titanpl-sdk/templates/server/src/extensions/external.rs +0 -338
  218. package/titanpl-sdk/templates/server/src/extensions/mod.rs +0 -580
  219. package/titanpl-sdk/templates/server/src/extensions/titan_core.js +0 -249
  220. package/titanpl-sdk/templates/server/src/fast_path.rs +0 -719
  221. package/titanpl-sdk/templates/server/src/main.rs +0 -607
  222. package/titanpl-sdk/templates/server/src/runtime.rs +0 -284
  223. package/titanpl-sdk/templates/server/src/utils.rs +0 -33
  224. package/titanpl-sdk/templates/titan/bundle.js +0 -259
  225. package/titanpl-sdk/templates/titan/dev.js +0 -390
  226. package/titanpl-sdk/templates/titan/error-box.js +0 -277
  227. package/titanpl-sdk/templates/titan/titan.js +0 -129
@@ -1,284 +0,0 @@
1
- //! Worker Pool Management (Performance Optimized)
2
- //!
3
- //! Features:
4
- //! 1. Work-stealing fallback strategy.
5
- //! 2. Bounded channel capacity for pipeline handling.
6
- //! 3. Batch-ready architecture for HTTP pipelining.
7
- //! 4. Zero-copy / deferred cloning where possible.
8
-
9
- use bytes::Bytes;
10
- use crossbeam::channel::{bounded, Sender, TrySendError};
11
- use std::sync::atomic::{AtomicUsize, Ordering};
12
- use std::thread;
13
- use tokio::sync::mpsc;
14
- use tokio::sync::oneshot;
15
- use smallvec::SmallVec;
16
-
17
- use crate::extensions::{self, AsyncOpRequest, TitanRuntime, WorkerAsyncResult};
18
-
19
- pub struct RuntimeManager {
20
- request_txs: Vec<Sender<WorkerCommand>>,
21
- round_robin_counter: AtomicUsize,
22
- num_workers: usize,
23
- _workers: Vec<thread::JoinHandle<()>>,
24
- }
25
-
26
- pub enum WorkerCommand {
27
- Request(RequestTask),
28
- Resume {
29
- drift_id: u32,
30
- result: WorkerAsyncResult,
31
- },
32
- }
33
-
34
- #[allow(dead_code)]
35
- pub struct RequestTask {
36
- pub action_name: String,
37
- pub body: Option<Bytes>,
38
- pub method: String,
39
- pub path: String,
40
- pub headers: SmallVec<[(String, String); 8]>,
41
- pub params: SmallVec<[(String, String); 4]>,
42
- pub query: SmallVec<[(String, String); 4]>,
43
- pub response_tx: oneshot::Sender<WorkerResult>,
44
- }
45
-
46
- pub struct WorkerResult {
47
- pub json: serde_json::Value,
48
- pub timings: Vec<(String, f64)>,
49
- }
50
-
51
- impl RuntimeManager {
52
- pub fn new(
53
- project_root: std::path::PathBuf,
54
- num_threads: usize,
55
- stack_size: usize,
56
- ) -> Self {
57
- let (async_tx, mut async_rx) = mpsc::channel::<AsyncOpRequest>(2048);
58
- let tokio_handle = tokio::runtime::Handle::current();
59
-
60
- // Spawn Tokio Async Handler (for drift operations)
61
- tokio_handle.spawn(async move {
62
- while let Some(req) = async_rx.recv().await {
63
- let drift_id = req.drift_id;
64
- let respond_tx = req.respond_tx;
65
- tokio::spawn(async move {
66
- let start = std::time::Instant::now();
67
- let result = extensions::builtin::run_async_operation(req.op).await;
68
- let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
69
- let _ = respond_tx.send(WorkerAsyncResult {
70
- drift_id,
71
- result,
72
- duration_ms,
73
- });
74
- });
75
- }
76
- });
77
-
78
- // Create worker channels
79
- let channel_capacity = 256;
80
- let mut workers = Vec::with_capacity(num_threads);
81
-
82
- let mut channels: Vec<(Sender<WorkerCommand>, crossbeam::channel::Receiver<WorkerCommand>)> =
83
- Vec::with_capacity(num_threads);
84
-
85
- for _ in 0..num_threads {
86
- let (tx, rx) = bounded(channel_capacity);
87
- channels.push((tx, rx));
88
- }
89
-
90
- let mut final_txs: Vec<Sender<WorkerCommand>> = Vec::with_capacity(num_threads);
91
- for (tx, _) in &channels {
92
- final_txs.push(tx.clone());
93
- }
94
-
95
- // Spawn Worker Threads
96
- for (i, (tx, rx)) in channels.into_iter().enumerate() {
97
- let my_tx = tx.clone();
98
- let root = project_root.clone();
99
- let handle = tokio_handle.clone();
100
- let async_tx = async_tx.clone();
101
-
102
- let handle = thread::Builder::new()
103
- .name(format!("titan-worker-{}", i))
104
- .stack_size(stack_size)
105
- .spawn(move || {
106
- let mut rt = extensions::init_runtime_worker(
107
- i,
108
- root,
109
- my_tx,
110
- handle,
111
- async_tx,
112
- stack_size,
113
- );
114
- rt.bind_to_isolate();
115
-
116
- loop {
117
- match rx.recv() {
118
- Ok(cmd) => match cmd {
119
- WorkerCommand::Request(task) => {
120
- handle_new_request(task, &mut rt);
121
- }
122
- WorkerCommand::Resume { drift_id, result } => {
123
- handle_resume(drift_id, result, &mut rt);
124
- }
125
- },
126
- Err(_) => break,
127
- }
128
- }
129
- })
130
- .expect("Failed to spawn worker");
131
-
132
- workers.push(handle);
133
- }
134
-
135
- Self {
136
- request_txs: final_txs,
137
- round_robin_counter: AtomicUsize::new(0),
138
- num_workers: num_threads,
139
- _workers: workers,
140
- }
141
- }
142
-
143
- /// Execute an action on a worker. Uses round-robin with work-stealing fallback.
144
- pub async fn execute(
145
- &self,
146
- action: String,
147
- method: String,
148
- path: String,
149
- body: Option<Bytes>,
150
- headers: SmallVec<[(String, String); 8]>,
151
- params: SmallVec<[(String, String); 4]>,
152
- query: SmallVec<[(String, String); 4]>,
153
- ) -> Result<(serde_json::Value, Vec<(String, f64)>), String> {
154
- let (tx, rx) = oneshot::channel();
155
- let task = RequestTask {
156
- action_name: action,
157
- body,
158
- method,
159
- path,
160
- headers,
161
- params,
162
- query,
163
- response_tx: tx,
164
- };
165
-
166
- // Work-Stealing Distribution
167
- let start_idx = self.round_robin_counter.fetch_add(1, Ordering::Relaxed) % self.num_workers;
168
- let mut cmd = WorkerCommand::Request(task);
169
-
170
- for attempt in 0..self.num_workers {
171
- let idx = (start_idx + attempt) % self.num_workers;
172
- match self.request_txs[idx].try_send(cmd) {
173
- Ok(()) => {
174
- return match rx.await {
175
- Ok(res) => Ok((res.json, res.timings)),
176
- Err(_) => Err("Worker channel closed".to_string()),
177
- };
178
- }
179
- Err(TrySendError::Full(returned)) => {
180
- cmd = returned;
181
- }
182
- Err(TrySendError::Disconnected(_)) => {
183
- return Err("Worker disconnected".to_string());
184
- }
185
- }
186
- }
187
-
188
- // All workers full — blocking send to the original target as last resort
189
- self.request_txs[start_idx]
190
- .send(cmd)
191
- .map_err(|e| e.to_string())?;
192
-
193
- match rx.await {
194
- Ok(res) => Ok((res.json, res.timings)),
195
- Err(_) => Err("Worker channel closed".to_string()),
196
- }
197
- }
198
- }
199
-
200
- /// Handle a new incoming request.
201
- ///
202
- /// OPTIMIZATION: Deferred cloning.
203
- /// Only stores data if drift (async suspend) happens.
204
- fn handle_new_request(task: RequestTask, rt: &mut TitanRuntime) {
205
- rt.request_counter += 1;
206
- let request_id = rt.request_counter;
207
-
208
- // Move response_tx into pending (partial move of task — other fields remain accessible)
209
- rt.pending_requests.insert(request_id, task.response_tx);
210
-
211
- let drift_count = rt.drift_counter;
212
- rt.request_start_counters.insert(request_id, drift_count);
213
-
214
- // Execute action — pass references, body is O(1) Bytes clone
215
- extensions::execute_action_optimized(
216
- rt,
217
- request_id,
218
- &task.action_name,
219
- task.body.clone(), // Bytes::clone() is O(1) refcount bump
220
- &task.method,
221
- &task.path,
222
- &task.headers,
223
- &task.params,
224
- &task.query,
225
- );
226
-
227
- // Deferred cloning decision
228
- if !rt.pending_requests.contains_key(&request_id) {
229
- // Completed synchronously — no data needed, minimal cleanup
230
- rt.request_start_counters.remove(&request_id);
231
- } else {
232
- // Suspended via drift — MOVE (not clone) data for resume replay.
233
- rt.active_requests.insert(
234
- request_id,
235
- extensions::RequestData {
236
- action_name: task.action_name,
237
- body: task.body,
238
- method: task.method,
239
- path: task.path,
240
- headers: task.headers.into_vec(),
241
- params: task.params.into_vec(),
242
- query: task.query.into_vec(),
243
- },
244
- );
245
- }
246
- }
247
-
248
- fn handle_resume(drift_id: u32, result: WorkerAsyncResult, rt: &mut TitanRuntime) {
249
- let req_id = rt.drift_to_request.get(&drift_id).copied().unwrap_or(0);
250
-
251
- let timing_type = if result.result.get("error").is_some() {
252
- "drift_error"
253
- } else {
254
- "drift"
255
- };
256
- rt.request_timings
257
- .entry(req_id)
258
- .or_default()
259
- .push((timing_type.to_string(), result.duration_ms));
260
-
261
- rt.completed_drifts.insert(drift_id, result.result);
262
-
263
- if let Some(req_data) = rt.active_requests.get(&req_id).cloned() {
264
- let start_counter = rt.request_start_counters.get(&req_id).copied().unwrap_or(0);
265
- rt.drift_counter = start_counter;
266
-
267
- extensions::execute_action_optimized(
268
- rt,
269
- req_id,
270
- &req_data.action_name,
271
- req_data.body,
272
- &req_data.method,
273
- &req_data.path,
274
- &req_data.headers,
275
- &req_data.params,
276
- &req_data.query,
277
- );
278
- }
279
-
280
- if req_id != 0 && !rt.pending_requests.contains_key(&req_id) {
281
- rt.active_requests.remove(&req_id);
282
- rt.request_start_counters.remove(&req_id);
283
- }
284
- }
@@ -1,33 +0,0 @@
1
- //! Terminal styling and utility functions.
2
-
3
- pub fn blue(s: &str) -> String {
4
- format!("\x1b[38;5;39m{}\x1b[0m", s)
5
- }
6
- pub fn white(s: &str) -> String {
7
- format!("\x1b[39m{}\x1b[0m", s)
8
- }
9
- pub fn yellow(s: &str) -> String {
10
- format!("\x1b[33m{}\x1b[0m", s)
11
- }
12
- pub fn green(s: &str) -> String {
13
- format!("\x1b[32m{}\x1b[0m", s)
14
- }
15
- pub fn gray(s: &str) -> String {
16
- format!("\x1b[90m{}\x1b[0m", s)
17
- }
18
- pub fn red(s: &str) -> String {
19
- format!("\x1b[31m{}\x1b[0m", s)
20
- }
21
-
22
- pub fn parse_expires_in(value: &str) -> Option<u64> {
23
- let (num, unit) = value.split_at(value.len() - 1);
24
- let n: u64 = num.parse().ok()?;
25
-
26
- match unit {
27
- "s" => Some(n),
28
- "m" => Some(n * 60),
29
- "h" => Some(n * 60 * 60),
30
- "d" => Some(n * 60 * 60 * 24),
31
- _ => None,
32
- }
33
- }
@@ -1,259 +0,0 @@
1
- /**
2
- * Bundle.js
3
- * Handles esbuild bundling with comprehensive error reporting
4
- * RULE: This file handles ALL esbuild errors and prints error boxes directly
5
- */
6
-
7
- import esbuild from 'esbuild';
8
- import path from 'path';
9
- import fs from 'fs';
10
- import { fileURLToPath } from 'url';
11
- import { createRequire } from 'module';
12
- import { renderErrorBox, parseEsbuildError } from './error-box.js';
13
-
14
- const __filename = fileURLToPath(import.meta.url);
15
- const __dirname = path.dirname(__filename);
16
-
17
- // Required for resolving node_modules inside ESM
18
- const require = createRequire(import.meta.url);
19
-
20
- /**
21
- * Titan Node Builtin Rewrite Map
22
- * Rewrites Node builtins to @titanpl/node shims
23
- */
24
- const NODE_BUILTIN_MAP = {
25
- "fs": "@titanpl/node/fs",
26
- "node:fs": "@titanpl/node/fs",
27
-
28
- "path": "@titanpl/node/path",
29
- "node:path": "@titanpl/node/path",
30
-
31
- "os": "@titanpl/node/os",
32
- "node:os": "@titanpl/node/os",
33
-
34
- "crypto": "@titanpl/node/crypto",
35
- "node:crypto": "@titanpl/node/crypto",
36
-
37
- "process": "@titanpl/node/process",
38
-
39
- "util": "@titanpl/node/util",
40
- "node:util": "@titanpl/node/util",
41
- };
42
-
43
- /**
44
- * Titan Node Compatibility Plugin
45
- * Rewrites require/import of Node builtins
46
- * Returns absolute paths (required by esbuild)
47
- */
48
- const titanNodeCompatPlugin = {
49
- name: "titan-node-compat",
50
- setup(build) {
51
- build.onResolve({ filter: /.*/ }, args => {
52
- if (NODE_BUILTIN_MAP[args.path]) {
53
- try {
54
- const resolved = require.resolve(NODE_BUILTIN_MAP[args.path]);
55
- return { path: resolved };
56
- } catch (e) {
57
- throw new Error(
58
- `[Titan] Failed to resolve Node shim: ${NODE_BUILTIN_MAP[args.path]}`
59
- );
60
- }
61
- }
62
- });
63
- }
64
- };
65
-
66
- /**
67
- * Get Titan version for error branding
68
- */
69
- function getTitanVersion() {
70
- try {
71
- const pkgPath = require.resolve("titanpl/package.json");
72
- return JSON.parse(fs.readFileSync(pkgPath, "utf-8")).version;
73
- } catch (e) {
74
- return "0.1.0";
75
- }
76
- }
77
-
78
- /**
79
- * Custom error class for bundle errors
80
- */
81
- export class BundleError extends Error {
82
- constructor(message, errors = [], warnings = []) {
83
- super(message);
84
- this.name = 'BundleError';
85
- this.errors = errors;
86
- this.warnings = warnings;
87
- this.isBundleError = true;
88
- }
89
- }
90
-
91
- /**
92
- * Validate entry file exists
93
- */
94
- async function validateEntryPoint(entryPoint) {
95
- const absPath = path.resolve(entryPoint);
96
-
97
- if (!fs.existsSync(absPath)) {
98
- throw new BundleError(
99
- `Entry point does not exist: ${entryPoint}`,
100
- [{ text: `Cannot find file: ${absPath}`, location: { file: entryPoint } }]
101
- );
102
- }
103
-
104
- try {
105
- await fs.promises.access(absPath, fs.constants.R_OK);
106
- } catch {
107
- throw new BundleError(
108
- `Entry point is not readable: ${entryPoint}`,
109
- [{ text: `Cannot read file: ${absPath}`, location: { file: entryPoint } }]
110
- );
111
- }
112
- }
113
-
114
- /**
115
- * Bundles a single file
116
- */
117
- export async function bundleFile(options) {
118
- const {
119
- entryPoint,
120
- outfile,
121
- format = 'iife',
122
- minify = false,
123
- sourcemap = false,
124
- platform = 'neutral',
125
- globalName = '__titan_exports',
126
- target = 'es2020',
127
- banner = {},
128
- footer = {}
129
- } = options;
130
-
131
- await validateEntryPoint(entryPoint);
132
-
133
- const outDir = path.dirname(outfile);
134
- await fs.promises.mkdir(outDir, { recursive: true });
135
-
136
- try {
137
- const result = await esbuild.build({
138
- entryPoints: [entryPoint],
139
- bundle: true,
140
- outfile,
141
- format,
142
- globalName,
143
- platform,
144
- target,
145
- banner,
146
- footer,
147
- minify,
148
- sourcemap,
149
- logLevel: 'silent',
150
- logLimit: 0,
151
- write: true,
152
- metafile: false,
153
- plugins: [titanNodeCompatPlugin],
154
- });
155
-
156
- if (result.errors?.length) {
157
- throw new BundleError(
158
- `Build failed with ${result.errors.length} error(s)`,
159
- result.errors,
160
- result.warnings || []
161
- );
162
- }
163
-
164
- } catch (err) {
165
- if (err.errors?.length) {
166
- throw new BundleError(
167
- `Build failed with ${err.errors.length} error(s)`,
168
- err.errors,
169
- err.warnings || []
170
- );
171
- }
172
-
173
- throw new BundleError(
174
- `Unexpected build error: ${err.message}`,
175
- [{ text: err.message, location: { file: entryPoint } }]
176
- );
177
- }
178
- }
179
-
180
- /**
181
- * Main bundler
182
- */
183
- export async function bundle() {
184
- const root = process.cwd();
185
- const actionsDir = path.join(root, 'app', 'actions');
186
- const bundleDir = path.join(root, 'server', 'src', 'actions');
187
-
188
- if (fs.existsSync(bundleDir)) {
189
- fs.rmSync(bundleDir, { recursive: true, force: true });
190
- }
191
- await fs.promises.mkdir(bundleDir, { recursive: true });
192
-
193
- if (!fs.existsSync(actionsDir)) return;
194
-
195
- const files = fs.readdirSync(actionsDir).filter(f =>
196
- (f.endsWith('.js') || f.endsWith('.ts')) && !f.endsWith('.d.ts')
197
- );
198
-
199
- for (const file of files) {
200
- const actionName = path.basename(file, path.extname(file));
201
- const entryPoint = path.join(actionsDir, file);
202
- const outfile = path.join(bundleDir, actionName + ".jsbundle");
203
-
204
- try {
205
- await bundleFile({
206
- entryPoint,
207
- outfile,
208
- format: 'iife',
209
- globalName: '__titan_exports',
210
- platform: 'node',
211
- target: 'es2020',
212
- banner: { js: "var Titan = t;" },
213
- footer: {
214
- js: `
215
- (function () {
216
- const fn =
217
- __titan_exports["${actionName}"] ||
218
- __titan_exports.default;
219
-
220
- if (typeof fn !== "function") {
221
- throw new Error("[Titan] Action '${actionName}' not found or not a function");
222
- }
223
-
224
- globalThis["${actionName}"] = globalThis.defineAction(fn);
225
- })();
226
- `
227
- }
228
- });
229
-
230
- } catch (error) {
231
-
232
- console.error();
233
-
234
- const titanVersion = getTitanVersion();
235
-
236
- if (error.isBundleError && error.errors?.length) {
237
- for (let i = 0; i < error.errors.length; i++) {
238
- const errorInfo = parseEsbuildError(error.errors[i]);
239
- if (error.errors.length > 1) {
240
- errorInfo.title = `Build Error ${i + 1}/${error.errors.length}`;
241
- }
242
- errorInfo.titanVersion = titanVersion;
243
- console.error(renderErrorBox(errorInfo));
244
- console.error();
245
- }
246
- } else {
247
- const errorInfo = {
248
- title: 'Build Error',
249
- file: entryPoint,
250
- message: error.message || 'Unknown error',
251
- titanVersion
252
- };
253
- console.error(renderErrorBox(errorInfo));
254
- }
255
-
256
- throw new Error('__TITAN_BUNDLE_FAILED__');
257
- }
258
- }
259
- }