File size: 11,537 Bytes
3374e90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//! JS Pool — the main interface for the host engine.
//!
//! JsPool manages a pool of worker threads, each running a QuickJS runtime.
//! It routes JS evaluation requests to workers with plugin affinity.
//! The pool grows on demand up to `max_workers` when all worker queues are full.

use crate::config::JsPoolConfig;
use crate::error::JsError;
use crate::worker::{JsResult, JsTask, JsTaskKind, JsWorker};
use crossbeam_channel::{self, Sender};
use parking_lot::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;

/// The JS pool — the main interface for the host engine.
pub struct JsPool {
    workers: Mutex<Vec<std::thread::JoinHandle<()>>>,
    task_senders: Mutex<Vec<Sender<JsTask>>>,
    /// Lock-free worker count for fast affinity selection.
    worker_count: AtomicUsize,
    shutdown: Arc<AtomicBool>,
    config: JsPoolConfig,
}

impl JsPool {
    /// Create a new JS pool with the given configuration.
    pub fn new(config: JsPoolConfig) -> Result<Self, JsError> {
        let num_workers = config.initial_workers;
        let shutdown = Arc::new(AtomicBool::new(false));
        let mut workers = Vec::with_capacity(num_workers);
        let mut task_senders = Vec::with_capacity(num_workers);

        for id in 0..num_workers {
            let (tx, rx) = crossbeam_channel::bounded::<JsTask>(256);
            let handle = JsWorker::spawn(id, config.clone(), rx, shutdown.clone());
            workers.push(handle);
            task_senders.push(tx);
        }

        Ok(Self {
            workers: Mutex::new(workers),
            task_senders: Mutex::new(task_senders),
            worker_count: AtomicUsize::new(num_workers),
            shutdown,
            config,
        })
    }

    /// Evaluate a JavaScript string and return the result as JSON.
    /// Uses simple one-shot evaluation with default timeout.
    /// `input` is injected as the global variable `input` before eval.
    pub fn eval_js(&self, plugin_id: &str, code: &str, input: &str) -> Result<String, JsError> {
        self.eval_js_opts(
            plugin_id,
            code,
            input,
            None,
            self.config.default_timeout_ms,
        )
    }

    /// Evaluate JavaScript with options.
    pub fn eval_js_opts(
        &self,
        plugin_id: &str,
        code: &str,
        input: &str,
        filename: Option<String>,
        timeout_ms: u32,
    ) -> Result<String, JsError> {
        if self.shutdown.load(Ordering::Acquire) {
            return Err(JsError::PoolShutdown);
        }

        let (reply_tx, reply_rx) = crossbeam_channel::bounded::<JsResult>(1);

        let task = JsTask {
            plugin_id: plugin_id.to_string(),
            kind: JsTaskKind::Eval {
                code: code.to_string(),
                input: input.to_string(),
                filename,
                timeout_ms,
            },
            reply: reply_tx,
        };

        self.dispatch_task(plugin_id, task)?;

        match reply_rx.recv_timeout(std::time::Duration::from_millis(
            (timeout_ms as u64).max(self.config.default_timeout_ms as u64) + 2000,
        )) {
            Ok(result) => result.result,
            Err(_) => Err(JsError::Timeout(timeout_ms)),
        }
    }

    /// Call a named JavaScript function.
    /// `fn_source` is evaluated on first call (or if the source hash changes).
    /// `args_json` is passed as a single string argument (no eval of user data).
    pub fn call_js_fn(
        &self,
        plugin_id: &str,
        name: &str,
        fn_source: &str,
        args_json: &str,
    ) -> Result<String, JsError> {
        if self.shutdown.load(Ordering::Acquire) {
            return Err(JsError::PoolShutdown);
        }

        let (reply_tx, reply_rx) = crossbeam_channel::bounded::<JsResult>(1);

        let task = JsTask {
            plugin_id: plugin_id.to_string(),
            kind: JsTaskKind::CallFn {
                name: name.to_string(),
                fn_source: fn_source.to_string(),
                args_json: args_json.to_string(),
                timeout_ms: self.config.default_timeout_ms,
            },
            reply: reply_tx,
        };

        self.dispatch_task(plugin_id, task)?;

        match reply_rx.recv_timeout(std::time::Duration::from_millis(
            self.config.default_timeout_ms as u64 + 2000,
        )) {
            Ok(result) => result.result,
            Err(_) => Err(JsError::Timeout(self.config.default_timeout_ms)),
        }
    }

    /// Clear a named JS function from a plugin's context.
    pub fn clear_js_fn(&self, plugin_id: &str, name: &str) -> Result<u8, JsError> {
        if self.shutdown.load(Ordering::Acquire) {
            return Err(JsError::PoolShutdown);
        }

        let (reply_tx, reply_rx) = crossbeam_channel::bounded::<JsResult>(1);

        let task = JsTask {
            plugin_id: plugin_id.to_string(),
            kind: JsTaskKind::ClearFn {
                name: name.to_string(),
            },
            reply: reply_tx,
        };

        self.dispatch_task(plugin_id, task)?;

        match reply_rx.recv_timeout(std::time::Duration::from_millis(
            self.config.default_timeout_ms as u64 + 2000,
        )) {
            Ok(result) => result.result.map(|_| 0),
            Err(_) => Err(JsError::Timeout(self.config.default_timeout_ms)),
        }
    }

    /// Evict a plugin's JS context (called on plugin uninstall).
    pub fn evict_plugin(&self, plugin_id: &str) {
        if self.shutdown.load(Ordering::Acquire) {
            return;
        }

        // Send evict to all workers since we don't know which one has the context
        let senders = self.task_senders.lock();
        for tx in senders.iter() {
            let (reply_tx, reply_rx) = crossbeam_channel::bounded::<JsResult>(1);
            let task = JsTask {
                plugin_id: plugin_id.to_string(),
                kind: JsTaskKind::Evict,
                reply: reply_tx,
            };
            let _ = tx.send(task);
            let _ = reply_rx.recv_timeout(std::time::Duration::from_secs(2));
        }
    }

    /// Dispatch a task to a worker with plugin affinity.
    ///
    /// Strategy:
    /// 1. Try the affinity worker first (hash-based).
    /// 2. If full, try any other worker with capacity (overflow routing).
    /// 3. If all full and pool < max_workers, grow the pool and retry.
    /// 4. If still can't dispatch, return PoolBusy.
    fn dispatch_task(&self, plugin_id: &str, mut task: JsTask) -> Result<(), JsError> {
        if self.shutdown.load(Ordering::Acquire) {
            return Err(JsError::PoolShutdown);
        }

        // Step 1: Try affinity worker first
        let affinity_idx = self.select_worker(plugin_id);
        {
            let senders = self.task_senders.lock();
            if let Some(tx) = senders.get(affinity_idx) {
                match tx.try_send(task) {
                    Ok(()) => return Ok(()),
                    Err(crossbeam_channel::TrySendError::Disconnected(_)) => {
                        return Err(JsError::PoolShutdown);
                    }
                    Err(crossbeam_channel::TrySendError::Full(t)) => {
                        // Recover the task for overflow routing
                        task = t;
                    }
                }
            }
        }

        // Step 2: Overflow routing — try any other worker with capacity
        {
            let senders = self.task_senders.lock();
            let count = senders.len();
            for i in 0..count {
                if i == affinity_idx {
                    continue;
                }
                if let Some(tx) = senders.get(i) {
                    match tx.try_send(task) {
                        Ok(()) => return Ok(()),
                        Err(crossbeam_channel::TrySendError::Disconnected(_)) => {
                            return Err(JsError::PoolShutdown);
                        }
                        Err(crossbeam_channel::TrySendError::Full(t)) => {
                            task = t;
                            continue;
                        }
                    }
                }
            }
        }

        // Step 3: All full — try to grow the pool if under max_workers
        if self.maybe_grow() {
            // The newly added worker is at the end — try it first since it's
            // guaranteed to have an empty queue
            let senders = self.task_senders.lock();
            if let Some(tx) = senders.last() {
                match tx.try_send(task) {
                    Ok(()) => return Ok(()),
                    Err(crossbeam_channel::TrySendError::Disconnected(_)) => {
                        return Err(JsError::PoolShutdown);
                    }
                    Err(crossbeam_channel::TrySendError::Full(_)) => {
                        // Extremely unlikely but possible under heavy contention
                    }
                }
            }
        }

        // Step 4: Still can't dispatch
        Err(JsError::PoolBusy)
    }

    /// Select a worker for a given plugin_id.
    /// Uses hash-based affinity so the same plugin always goes to the same worker.
    fn select_worker(&self, plugin_id: &str) -> usize {
        let hash = simple_hash(plugin_id);
        let count = self.worker_count.load(Ordering::Acquire);
        if count == 0 {
            0
        } else {
            (hash as usize) % count
        }
    }

    /// Try to spawn additional workers if the pool is under max_workers.
    /// Returns `true` if at least one new worker was added.
    fn maybe_grow(&self) -> bool {
        let current = self.worker_count.load(Ordering::Acquire);
        if current >= self.config.max_workers {
            return false;
        }

        // Double-check under lock to avoid over-spawning
        let mut senders = self.task_senders.lock();
        let mut workers = self.workers.lock();
        let count = senders.len();

        if count >= self.config.max_workers {
            return false;
        }

        let new_id = count;
        let (tx, rx) = crossbeam_channel::bounded::<JsTask>(256);
        let handle = JsWorker::spawn(new_id, self.config.clone(), rx, self.shutdown.clone());
        workers.push(handle);
        senders.push(tx);

        // Update lock-free counter after the worker is registered
        self.worker_count.store(count + 1, Ordering::Release);

        tracing::info!(
            old_count = count,
            new_count = count + 1,
            max = self.config.max_workers,
            "JS pool grew — added worker"
        );

        true
    }
}

impl Drop for JsPool {
    fn drop(&mut self) {
        // SeqCst ensures all other threads see shutdown=true BEFORE we clear senders
        self.shutdown.store(true, Ordering::SeqCst);
        // Fence: nothing before this point reorders after
        std::sync::atomic::fence(Ordering::SeqCst);
        // Drop senders to signal workers to stop
        self.task_senders.lock().clear();
        // Join all worker threads
        let mut workers = self.workers.lock();
        for handle in workers.drain(..) {
            let _ = handle.join();
        }
    }
}

/// Simple FNV-1a hash for plugin_id -> worker affinity.
pub fn simple_hash(s: &str) -> u64 {
    let mut hash: u64 = 0xcbf29ce484222325;
    for byte in s.bytes() {
        hash ^= byte as u64;
        hash = hash.wrapping_mul(0x100000001b3);
    }
    hash
}