-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathpool_executor.rs
More file actions
4100 lines (3581 loc) · 146 KB
/
pool_executor.rs
File metadata and controls
4100 lines (3581 loc) · 146 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Pool-based Plugin Executor
//!
//! This module provides execution of pre-compiled JavaScript plugins via
//! a persistent Piscina worker pool, replacing the per-request ts-node approach.
//!
//! Communication with the Node.js pool server happens via Unix socket using
//! a JSON-line protocol.
use std::collections::HashMap;
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::oneshot;
use uuid::Uuid;
use crate::constants::{
ADMIN_REQUEST_TIMEOUT_SECS, DEFAULT_PLUGIN_TIMEOUT_SECONDS, PLUGIN_TIMEOUT_BUFFER_SECONDS,
};
use super::config::get_config;
use super::connection::{ConnectionPool, PoolConnection};
use super::health::{
CircuitBreaker, CircuitState, DeadServerIndicator, HealthStatus, ProcessStatus,
};
use super::protocol::{PoolError, PoolRequest, PoolResponse};
use super::shared_socket::get_shared_socket_service;
use super::{LogEntry, PluginError, PluginHandlerPayload, ScriptResult};
/// Request queue entry for throttling
struct QueuedRequest {
plugin_id: String,
compiled_code: Option<String>,
plugin_path: Option<String>,
params: serde_json::Value,
headers: Option<HashMap<String, Vec<String>>>,
socket_path: String,
http_request_id: Option<String>,
timeout_secs: Option<u64>,
route: Option<String>,
config: Option<serde_json::Value>,
method: Option<String>,
query: Option<serde_json::Value>,
response_tx: oneshot::Sender<Result<ScriptResult, PluginError>>,
}
/// Parsed health check result fields extracted from pool server JSON response.
///
/// This struct replaces a complex tuple return type to satisfy Clippy's
/// `type_complexity` lint and improve readability.
#[derive(Debug, Default, PartialEq)]
pub struct ParsedHealthResult {
pub status: String,
pub uptime_ms: Option<u64>,
pub memory: Option<u64>,
pub pool_completed: Option<u64>,
pub pool_queued: Option<u64>,
pub success_rate: Option<f64>,
}
/// Manages the pool server process and connections
pub struct PoolManager {
socket_path: String,
process: tokio::sync::Mutex<Option<Child>>,
initialized: Arc<AtomicBool>,
/// Lock to prevent concurrent restarts (thundering herd)
restart_lock: tokio::sync::Mutex<()>,
/// Connection pool for reusing connections
connection_pool: Arc<ConnectionPool>,
/// Request queue for throttling/backpressure (multi-consumer channel)
request_tx: async_channel::Sender<QueuedRequest>,
/// Actual configured queue size (for error messages)
max_queue_size: usize,
/// Flag indicating if health check is needed (set by background task)
health_check_needed: Arc<AtomicBool>,
/// Consecutive failure count for health checks
consecutive_failures: Arc<AtomicU32>,
/// Circuit breaker for automatic degradation under GC pressure
circuit_breaker: Arc<CircuitBreaker>,
/// Last successful restart time (for backoff calculation)
last_restart_time_ms: Arc<AtomicU64>,
/// Is currently in recovery mode (gradual ramp-up)
recovery_mode: Arc<AtomicBool>,
/// Requests allowed during recovery (gradual increase)
recovery_allowance: Arc<AtomicU32>,
/// Shutdown signal for background tasks (queue workers, health check, etc.)
shutdown_signal: Arc<tokio::sync::Notify>,
}
impl Default for PoolManager {
fn default() -> Self {
Self::new()
}
}
impl PoolManager {
/// Base heap size in MB for the pool server process.
/// This provides the minimum memory needed for the Node.js runtime and core pool infrastructure.
const BASE_HEAP_MB: usize = 512;
/// Concurrency divisor for heap calculation.
/// Heap is incremented for every N concurrent requests to scale with load.
const CONCURRENCY_DIVISOR: usize = 10;
/// Heap increment in MB per CONCURRENCY_DIVISOR concurrent requests.
/// Formula: BASE_HEAP_MB + ((max_concurrency / CONCURRENCY_DIVISOR) * HEAP_INCREMENT_PER_DIVISOR_MB)
/// This accounts for additional memory needed per concurrent plugin execution context.
const HEAP_INCREMENT_PER_DIVISOR_MB: usize = 32;
/// Maximum heap size in MB (hard cap) for the pool server process.
/// Prevents excessive memory allocation that could cause system instability.
/// Set to 8GB (8192 MB) as a reasonable upper bound for Node.js processes.
const MAX_HEAP_MB: usize = 8192;
/// Calculate heap size based on concurrency level.
///
/// Formula: BASE_HEAP_MB + ((max_concurrency / CONCURRENCY_DIVISOR) * HEAP_INCREMENT_PER_DIVISOR_MB)
/// Result is capped at MAX_HEAP_MB.
///
/// This scales memory allocation with expected load while maintaining a reasonable minimum.
pub fn calculate_heap_size(max_concurrency: usize) -> usize {
let calculated = Self::BASE_HEAP_MB
+ ((max_concurrency / Self::CONCURRENCY_DIVISOR) * Self::HEAP_INCREMENT_PER_DIVISOR_MB);
calculated.min(Self::MAX_HEAP_MB)
}
/// Format a result value from the pool response into a string.
///
/// If the value is already a string, returns it directly.
/// Otherwise, serializes it to JSON.
pub fn format_return_value(value: Option<serde_json::Value>) -> String {
value
.map(|v| {
if v.is_string() {
v.as_str().unwrap_or("").to_string()
} else {
serde_json::to_string(&v).unwrap_or_default()
}
})
.unwrap_or_default()
}
/// Parse a successful pool response into a ScriptResult.
///
/// Converts logs from PoolLogEntry to LogEntry and extracts the return value.
pub fn parse_success_response(response: PoolResponse) -> ScriptResult {
let logs: Vec<LogEntry> = response
.logs
.map(|logs| logs.into_iter().map(|l| l.into()).collect())
.unwrap_or_default();
ScriptResult {
logs,
error: String::new(),
return_value: Self::format_return_value(response.result),
trace: Vec::new(),
}
}
/// Parse a failed pool response into a PluginError.
///
/// Extracts error details and converts logs for inclusion in the error payload.
pub fn parse_error_response(response: PoolResponse) -> PluginError {
let logs: Vec<LogEntry> = response
.logs
.map(|logs| logs.into_iter().map(|l| l.into()).collect())
.unwrap_or_default();
let error = response.error.unwrap_or(PoolError {
message: "Unknown error".to_string(),
code: None,
status: None,
details: None,
});
PluginError::HandlerError(Box::new(PluginHandlerPayload {
message: error.message,
status: error.status.unwrap_or(500),
code: error.code,
details: error.details,
logs: Some(logs),
traces: None,
}))
}
/// Parse a pool response into either a success result or an error.
///
/// This is the main entry point for response parsing, dispatching to
/// either parse_success_response or parse_error_response based on the success flag.
pub fn parse_pool_response(response: PoolResponse) -> Result<ScriptResult, PluginError> {
if response.success {
Ok(Self::parse_success_response(response))
} else {
Err(Self::parse_error_response(response))
}
}
/// Parse health check result JSON into individual fields.
///
/// Extracts status, uptime, memory usage, pool stats, and success rate
/// from the nested JSON structure returned by the pool server.
pub fn parse_health_result(result: &serde_json::Value) -> ParsedHealthResult {
ParsedHealthResult {
status: result
.get("status")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string(),
uptime_ms: result.get("uptime").and_then(|v| v.as_u64()),
memory: result
.get("memory")
.and_then(|v| v.get("heapUsed"))
.and_then(|v| v.as_u64()),
pool_completed: result
.get("pool")
.and_then(|v| v.get("completed"))
.and_then(|v| v.as_u64()),
pool_queued: result
.get("pool")
.and_then(|v| v.get("queued"))
.and_then(|v| v.as_u64()),
success_rate: result
.get("execution")
.and_then(|v| v.get("successRate"))
.and_then(|v| v.as_f64()),
}
}
/// Create a new PoolManager with default socket path
pub fn new() -> Self {
Self::init(format!("/tmp/relayer-plugin-pool-{}.sock", Uuid::new_v4()))
}
/// Create a new PoolManager with custom socket path
pub fn with_socket_path(socket_path: String) -> Self {
Self::init(socket_path)
}
/// Common initialization logic
fn init(socket_path: String) -> Self {
let config = get_config();
let max_connections = config.pool_max_connections;
let max_queue_size = config.pool_max_queue_size;
let (tx, rx) = async_channel::bounded(max_queue_size);
let connection_pool = Arc::new(ConnectionPool::new(socket_path.clone(), max_connections));
let connection_pool_clone = connection_pool.clone();
let shutdown_signal = Arc::new(tokio::sync::Notify::new());
Self::spawn_queue_workers(
rx,
connection_pool_clone,
config.pool_workers,
shutdown_signal.clone(),
);
let health_check_needed = Arc::new(AtomicBool::new(false));
let consecutive_failures = Arc::new(AtomicU32::new(0));
let circuit_breaker = Arc::new(CircuitBreaker::new());
let last_restart_time_ms = Arc::new(AtomicU64::new(0));
let recovery_mode = Arc::new(AtomicBool::new(false));
let recovery_allowance = Arc::new(AtomicU32::new(0));
Self::spawn_health_check_task(
health_check_needed.clone(),
config.health_check_interval_secs,
shutdown_signal.clone(),
);
Self::spawn_recovery_task(
recovery_mode.clone(),
recovery_allowance.clone(),
shutdown_signal.clone(),
);
Self {
connection_pool,
socket_path,
process: tokio::sync::Mutex::new(None),
initialized: Arc::new(AtomicBool::new(false)),
restart_lock: tokio::sync::Mutex::new(()),
request_tx: tx,
max_queue_size,
health_check_needed,
consecutive_failures,
circuit_breaker,
last_restart_time_ms,
recovery_mode,
recovery_allowance,
shutdown_signal,
}
}
/// Spawn background task to gradually increase recovery allowance
fn spawn_recovery_task(
recovery_mode: Arc<AtomicBool>,
recovery_allowance: Arc<AtomicU32>,
shutdown_signal: Arc<tokio::sync::Notify>,
) {
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_millis(500));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
biased;
_ = shutdown_signal.notified() => {
tracing::debug!("Recovery task received shutdown signal");
break;
}
_ = interval.tick() => {
if recovery_mode.load(Ordering::Relaxed) {
let current = recovery_allowance.load(Ordering::Relaxed);
if current < 100 {
let new_allowance = (current + 10).min(100);
recovery_allowance.store(new_allowance, Ordering::Relaxed);
tracing::debug!(
allowance = new_allowance,
"Recovery mode: increasing request allowance"
);
} else {
recovery_mode.store(false, Ordering::Relaxed);
tracing::info!("Recovery mode complete - full capacity restored");
}
}
}
}
}
});
}
/// Spawn background task to set health check flag periodically
fn spawn_health_check_task(
health_check_needed: Arc<AtomicBool>,
interval_secs: u64,
shutdown_signal: Arc<tokio::sync::Notify>,
) {
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(interval_secs));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
biased;
_ = shutdown_signal.notified() => {
tracing::debug!("Health check task received shutdown signal");
break;
}
_ = interval.tick() => {
health_check_needed.store(true, Ordering::Relaxed);
}
}
}
});
}
/// Spawn multiple worker tasks to process queued requests concurrently
fn spawn_queue_workers(
rx: async_channel::Receiver<QueuedRequest>,
connection_pool: Arc<ConnectionPool>,
configured_workers: usize,
shutdown_signal: Arc<tokio::sync::Notify>,
) {
let num_workers = if configured_workers > 0 {
configured_workers
} else {
std::thread::available_parallelism()
.map(|n| n.get().clamp(4, 32))
.unwrap_or(8)
};
tracing::info!(num_workers = num_workers, "Starting request queue workers");
for worker_id in 0..num_workers {
let rx_clone = rx.clone();
let pool_clone = connection_pool.clone();
let shutdown = shutdown_signal.clone();
tokio::spawn(async move {
loop {
tokio::select! {
biased;
_ = shutdown.notified() => {
tracing::debug!(worker_id = worker_id, "Request queue worker received shutdown signal");
break;
}
request_result = rx_clone.recv() => {
let request = match request_result {
Ok(r) => r,
Err(_) => break,
};
let start = std::time::Instant::now();
let plugin_id = request.plugin_id.clone();
let result = Self::execute_plugin_internal(
&pool_clone,
request.plugin_id,
request.compiled_code,
request.plugin_path,
request.params,
request.headers,
request.socket_path,
request.http_request_id,
request.timeout_secs,
request.route,
request.config,
request.method,
request.query,
)
.await;
let elapsed = start.elapsed();
if let Err(ref e) = result {
let error_str = format!("{e:?}");
if error_str.contains("shutdown") || error_str.contains("Shutdown") {
tracing::debug!(
worker_id = worker_id,
plugin_id = %plugin_id,
"Plugin execution cancelled during shutdown"
);
} else {
tracing::warn!(
worker_id = worker_id,
plugin_id = %plugin_id,
elapsed_ms = elapsed.as_millis() as u64,
error = ?e,
"Plugin execution failed"
);
}
} else if elapsed.as_secs() > 1 {
tracing::debug!(
worker_id = worker_id,
plugin_id = %plugin_id,
elapsed_ms = elapsed.as_millis() as u64,
"Slow plugin execution"
);
}
let _ = request.response_tx.send(result);
}
}
}
tracing::debug!(worker_id = worker_id, "Request queue worker exited");
});
}
}
/// Spawn a rate-limited stderr reader to prevent log flooding
fn spawn_rate_limited_stderr_reader(stderr: tokio::process::ChildStderr) {
tokio::spawn(async move {
let reader = BufReader::new(stderr);
let mut lines = reader.lines();
let mut last_log_time = std::time::Instant::now();
let mut suppressed_count = 0u64;
let min_interval = Duration::from_millis(100);
while let Ok(Some(line)) = lines.next_line().await {
let now = std::time::Instant::now();
let elapsed = now.duration_since(last_log_time);
if elapsed >= min_interval {
if suppressed_count > 0 {
tracing::warn!(
target: "pool_server",
suppressed = suppressed_count,
"... ({} lines suppressed due to rate limiting)",
suppressed_count
);
suppressed_count = 0;
}
tracing::error!(target: "pool_server", "{}", line);
last_log_time = now;
} else {
suppressed_count += 1;
if suppressed_count.is_multiple_of(100) {
tracing::warn!(
target: "pool_server",
suppressed = suppressed_count,
"Pool server producing excessive stderr output"
);
}
}
}
if suppressed_count > 0 {
tracing::warn!(
target: "pool_server",
suppressed = suppressed_count,
"Pool server stderr closed ({} final lines suppressed)",
suppressed_count
);
}
});
}
/// Execute plugin with optional pre-acquired permit (unified fast/slow path)
#[allow(clippy::too_many_arguments)]
async fn execute_with_permit(
connection_pool: &Arc<ConnectionPool>,
permit: Option<tokio::sync::OwnedSemaphorePermit>,
plugin_id: String,
compiled_code: Option<String>,
plugin_path: Option<String>,
params: serde_json::Value,
headers: Option<HashMap<String, Vec<String>>>,
socket_path: String,
http_request_id: Option<String>,
timeout_secs: Option<u64>,
route: Option<String>,
config: Option<serde_json::Value>,
method: Option<String>,
query: Option<serde_json::Value>,
) -> Result<ScriptResult, PluginError> {
let mut conn = connection_pool.acquire_with_permit(permit).await?;
let request = PoolRequest::Execute(Box::new(super::protocol::ExecuteRequest {
task_id: Uuid::new_v4().to_string(),
plugin_id: plugin_id.clone(),
compiled_code,
plugin_path,
params,
headers,
socket_path,
http_request_id,
timeout: timeout_secs.map(|s| s * 1000),
route,
config,
method,
query,
}));
// Add buffer so the Node.js timeout fires first with a structured response;
// this Rust timeout is a backstop if the Node.js process hangs.
let configured_timeout = timeout_secs.unwrap_or(DEFAULT_PLUGIN_TIMEOUT_SECONDS);
let backstop_timeout = configured_timeout + PLUGIN_TIMEOUT_BUFFER_SECONDS;
let response = conn
.send_request_with_timeout(&request, backstop_timeout)
.await?;
// Use extracted parsing function for cleaner code and testability
Self::parse_pool_response(response)
}
/// Internal execution method (wrapper for execute_with_permit)
#[allow(clippy::too_many_arguments)]
async fn execute_plugin_internal(
connection_pool: &Arc<ConnectionPool>,
plugin_id: String,
compiled_code: Option<String>,
plugin_path: Option<String>,
params: serde_json::Value,
headers: Option<HashMap<String, Vec<String>>>,
socket_path: String,
http_request_id: Option<String>,
timeout_secs: Option<u64>,
route: Option<String>,
config: Option<serde_json::Value>,
method: Option<String>,
query: Option<serde_json::Value>,
) -> Result<ScriptResult, PluginError> {
Self::execute_with_permit(
connection_pool,
None,
plugin_id,
compiled_code,
plugin_path,
params,
headers,
socket_path,
http_request_id,
timeout_secs,
route,
config,
method,
query,
)
.await
}
/// Check if the pool manager has been initialized.
///
/// This is useful for health checks to determine if the plugin pool
/// is expected to be running.
pub async fn is_initialized(&self) -> bool {
self.initialized.load(Ordering::Acquire)
}
/// Start the pool server if not already running
pub async fn ensure_started(&self) -> Result<(), PluginError> {
if self.initialized.load(Ordering::Acquire) {
return Ok(());
}
let _startup_guard = self.restart_lock.lock().await;
if self.initialized.load(Ordering::Acquire) {
return Ok(());
}
self.start_pool_server().await?;
self.initialized.store(true, Ordering::Release);
Ok(())
}
/// Ensure pool is started and healthy, with auto-recovery on failure
async fn ensure_started_and_healthy(&self) -> Result<(), PluginError> {
self.ensure_started().await?;
if !self.health_check_needed.load(Ordering::Relaxed) {
return Ok(());
}
if self
.health_check_needed
.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
return Ok(());
}
self.check_and_restart_if_needed().await
}
/// Check process status and restart if needed
async fn check_and_restart_if_needed(&self) -> Result<(), PluginError> {
// Check process status without holding restart lock
let process_status = {
let mut process_guard = self.process.lock().await;
if let Some(child) = process_guard.as_mut() {
match child.try_wait() {
Ok(Some(exit_status)) => {
tracing::warn!(
exit_status = ?exit_status,
"Pool server process has exited"
);
*process_guard = None;
ProcessStatus::Exited
}
Ok(None) => ProcessStatus::Running,
Err(e) => {
tracing::warn!(
error = %e,
"Failed to check pool server process status, assuming dead"
);
*process_guard = None;
ProcessStatus::Unknown
}
}
} else {
ProcessStatus::NoProcess
}
};
// Determine if restart is needed
let needs_restart = match process_status {
ProcessStatus::Running => {
let socket_exists = std::path::Path::new(&self.socket_path).exists();
if !socket_exists {
tracing::warn!(
socket_path = %self.socket_path,
"Pool server socket file missing, needs restart"
);
true
} else {
false
}
}
ProcessStatus::Exited | ProcessStatus::Unknown | ProcessStatus::NoProcess => {
tracing::warn!("Pool server not running, needs restart");
true
}
};
// Only acquire restart lock if restart is actually needed
if needs_restart {
let _restart_guard = self.restart_lock.lock().await;
self.consecutive_failures.fetch_add(1, Ordering::Relaxed);
self.restart_internal().await?;
self.consecutive_failures.store(0, Ordering::Relaxed);
}
Ok(())
}
/// Clean up socket file with retry logic
async fn cleanup_socket_file(socket_path: &str) {
let max_cleanup_attempts = 5;
let mut attempts = 0;
while attempts < max_cleanup_attempts {
match std::fs::remove_file(socket_path) {
Ok(_) => break,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => break,
Err(e) => {
attempts += 1;
if attempts >= max_cleanup_attempts {
tracing::warn!(
socket_path = %socket_path,
error = %e,
"Failed to remove socket file after {} attempts, proceeding anyway",
max_cleanup_attempts
);
break;
}
let delay_ms = 10 * (1 << attempts.min(3));
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
}
}
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
/// Spawn the pool server process with proper configuration
async fn spawn_pool_server_process(
socket_path: &str,
context: &str,
) -> Result<Child, PluginError> {
let pool_server_path = std::env::current_dir()
.map(|cwd| cwd.join("plugins/lib/pool-server.ts").display().to_string())
.unwrap_or_else(|_| "plugins/lib/pool-server.ts".to_string());
let config = get_config();
// Use extracted function for heap calculation
let pool_server_heap_mb = Self::calculate_heap_size(config.max_concurrency);
// Log warning if heap was capped (for observability)
let uncapped_heap = Self::BASE_HEAP_MB
+ ((config.max_concurrency / Self::CONCURRENCY_DIVISOR)
* Self::HEAP_INCREMENT_PER_DIVISOR_MB);
if uncapped_heap > Self::MAX_HEAP_MB {
tracing::warn!(
calculated_heap_mb = uncapped_heap,
capped_heap_mb = pool_server_heap_mb,
max_concurrency = config.max_concurrency,
"Pool server heap calculation exceeded 8GB cap"
);
}
tracing::info!(
socket_path = %socket_path,
heap_mb = pool_server_heap_mb,
max_concurrency = config.max_concurrency,
context = context,
"Spawning plugin pool server"
);
let node_options = format!("--max-old-space-size={pool_server_heap_mb} --expose-gc");
let mut child = Command::new("ts-node")
.arg("--transpile-only")
.arg(&pool_server_path)
.arg(socket_path)
.env("NODE_OPTIONS", node_options)
.env("PLUGIN_MAX_CONCURRENCY", config.max_concurrency.to_string())
.env(
"PLUGIN_POOL_MIN_THREADS",
config.nodejs_pool_min_threads.to_string(),
)
.env(
"PLUGIN_POOL_MAX_THREADS",
config.nodejs_pool_max_threads.to_string(),
)
.env(
"PLUGIN_POOL_CONCURRENT_TASKS",
config.nodejs_pool_concurrent_tasks.to_string(),
)
.env(
"PLUGIN_POOL_IDLE_TIMEOUT",
config.nodejs_pool_idle_timeout_ms.to_string(),
)
.env(
"PLUGIN_WORKER_HEAP_MB",
config.nodejs_worker_heap_mb.to_string(),
)
.env(
"PLUGIN_POOL_SOCKET_BACKLOG",
config.pool_socket_backlog.to_string(),
)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| {
PluginError::PluginExecutionError(format!("Failed to {context} pool server: {e}"))
})?;
if let Some(stderr) = child.stderr.take() {
Self::spawn_rate_limited_stderr_reader(stderr);
}
if let Some(stdout) = child.stdout.take() {
let reader = BufReader::new(stdout);
let mut lines = reader.lines();
let timeout_result = tokio::time::timeout(Duration::from_secs(10), async {
while let Ok(Some(line)) = lines.next_line().await {
if line.contains("POOL_SERVER_READY") {
return Ok(());
}
}
Err(PluginError::PluginExecutionError(
"Pool server did not send ready signal".to_string(),
))
})
.await;
match timeout_result {
Ok(Ok(())) => {
tracing::info!(context = context, "Plugin pool server ready");
}
Ok(Err(e)) => return Err(e),
Err(_) => {
return Err(PluginError::PluginExecutionError(format!(
"Timeout waiting for pool server to {context}"
)))
}
}
}
Ok(child)
}
async fn start_pool_server(&self) -> Result<(), PluginError> {
let mut process_guard = self.process.lock().await;
if process_guard.is_some() {
return Ok(());
}
Self::cleanup_socket_file(&self.socket_path).await;
let child = Self::spawn_pool_server_process(&self.socket_path, "start").await?;
*process_guard = Some(child);
Ok(())
}
/// Execute a plugin via the pool
#[allow(clippy::too_many_arguments)]
pub async fn execute_plugin(
&self,
plugin_id: String,
compiled_code: Option<String>,
plugin_path: Option<String>,
params: serde_json::Value,
headers: Option<HashMap<String, Vec<String>>>,
socket_path: String,
http_request_id: Option<String>,
timeout_secs: Option<u64>,
route: Option<String>,
config: Option<serde_json::Value>,
method: Option<String>,
query: Option<serde_json::Value>,
) -> Result<ScriptResult, PluginError> {
let rid = http_request_id.as_deref().unwrap_or("unknown");
let effective_timeout = timeout_secs.unwrap_or(DEFAULT_PLUGIN_TIMEOUT_SECONDS);
tracing::debug!(
plugin_id = %plugin_id,
http_request_id = %rid,
timeout_secs = effective_timeout,
"Pool execute request received"
);
let recovery_allowance = if self.recovery_mode.load(Ordering::Relaxed) {
Some(self.recovery_allowance.load(Ordering::Relaxed))
} else {
None
};
if !self
.circuit_breaker
.should_allow_request(recovery_allowance)
{
let state = self.circuit_breaker.state();
tracing::warn!(
plugin_id = %plugin_id,
circuit_state = ?state,
recovery_allowance = ?recovery_allowance,
"Request rejected by circuit breaker"
);
return Err(PluginError::PluginExecutionError(
"Plugin system temporarily unavailable due to high load. Please retry shortly."
.to_string(),
));
}
let start_time = Instant::now();
self.ensure_started_and_healthy().await?;
tracing::debug!(
plugin_id = %plugin_id,
http_request_id = %rid,
"Pool execute start (healthy/started)"
);
let circuit_breaker = self.circuit_breaker.clone();
match self.connection_pool.semaphore.clone().try_acquire_owned() {
Ok(permit) => {
tracing::debug!(
plugin_id = %plugin_id,
http_request_id = %rid,
"Pool execute acquired connection permit (fast path)"
);
let result = Self::execute_with_permit(
&self.connection_pool,
Some(permit),
plugin_id,
compiled_code,
plugin_path,
params,
headers,
socket_path,
http_request_id,
timeout_secs,
route,
config,
method,
query,
)
.await;
let elapsed_ms = start_time.elapsed().as_millis() as u32;
match &result {
Ok(_) => circuit_breaker.record_success(elapsed_ms),
Err(e) => {
// Only count infrastructure errors for circuit breaker, not business errors
// Business errors (RPC failures, plugin logic errors) mean the pool is healthy
if Self::is_dead_server_error(e) {
circuit_breaker.record_failure();
tracing::warn!(
error = %e,
"Detected dead pool server error, triggering health check for restart"
);
self.health_check_needed.store(true, Ordering::Relaxed);
} else {
// Plugin executed but returned error - infrastructure is healthy
circuit_breaker.record_success(elapsed_ms);
}
}
}
tracing::debug!(
elapsed_ms = elapsed_ms,
result_ok = result.is_ok(),
"Pool execute finished (fast path)"
);
result
}
Err(_) => {
tracing::debug!(
plugin_id = %plugin_id,
http_request_id = %rid,
"Pool execute queueing (no permits)"
);
let (response_tx, response_rx) = oneshot::channel();
let queued_request = QueuedRequest {
plugin_id,
compiled_code,
plugin_path,
params,
headers,
socket_path,
http_request_id,
timeout_secs,
route,
config,
method,
query,
response_tx,
};
let result = match self.request_tx.try_send(queued_request) {
Ok(()) => {
let queue_len = self.request_tx.len();
if queue_len > self.max_queue_size / 2 {
tracing::warn!(
queue_len = queue_len,
max_queue_size = self.max_queue_size,
"Plugin queue is over 50% capacity"
);
}
// Add timeout to response_rx to prevent hung requests if worker crashes.
// Must exceed the Rust backstop (T + PLUGIN_TIMEOUT_BUFFER_SECONDS)
// so the inner timeout layers fire first.
let response_timeout = timeout_secs