Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

Fix worker pool socket connection on Windows

tilakpatel2290ad5a406e01
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/worker.py b/fincept-terminal-desktop/src-tauri/resources/scripts/worker.py
index f2ff67301..512ca1dd1 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/worker.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/worker.py
@@ -1,8 +1,10 @@
#!/usr/bin/env python3
"""
Python Worker Process - Persistent process with ThreadPoolExecutor
-Communicates with Rust via Unix Domain Sockets using MessagePack
+Communicates with Rust via Named Pipes (Windows) or Unix Domain Sockets
Single process handles multiple requests concurrently using threads
+
+IMPORTANT: This worker LISTENS (server mode), Rust CONNECTS (client mode)
"""
import sys
@@ -12,111 +14,194 @@ import traceback
import importlib.util
import socket
import struct
-import msgpack
+import threading
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
-import threading
+
+# Try to import msgpack, fall back to json if not available
+try:
+ import msgpack
+ USE_MSGPACK = True
+except ImportError:
+ USE_MSGPACK = False
+ print("[Worker] msgpack not available, using JSON fallback", file=sys.stderr, flush=True)
+
class PythonWorker:
def __init__(self, socket_name, worker_id, num_threads=4):
self.socket_name = socket_name
self.worker_id = worker_id
self.num_threads = num_threads
- self.socket = None
+ self.server_socket = None
+ self.client_socket = None
self.running = True
self.executor = ThreadPoolExecutor(max_workers=num_threads)
+ self.send_lock = threading.Lock()
print(f"[Worker {worker_id}] Initializing with {num_threads} threads", file=sys.stderr, flush=True)
print(f"[Worker {worker_id}] Python: {sys.version}", file=sys.stderr, flush=True)
print(f"[Worker {worker_id}] Socket: {socket_name}", file=sys.stderr, flush=True)
- def connect_socket(self):
- """Connect to Unix domain socket or Windows named pipe"""
+ def start_server(self):
+ """Create socket/pipe and listen for Rust connection"""
if sys.platform == 'win32':
- # Windows named pipe
- import win32pipe, win32file
- pipe_path = f"\\\\.\\pipe\\{self.socket_name}"
- print(f"[Worker {self.worker_id}] Connecting to named pipe: {pipe_path}", file=sys.stderr, flush=True)
+ self._start_windows_pipe_server()
+ else:
+ self._start_unix_socket_server()
- # Wait for Rust to create the pipe
- while self.running:
- try:
- self.socket = win32file.CreateFile(
- pipe_path,
- win32file.GENERIC_READ | win32file.GENERIC_WRITE,
- 0,
- None,
- win32file.OPEN_EXISTING,
- 0,
- None
- )
- print(f"[Worker {self.worker_id}] Connected to named pipe", file=sys.stderr, flush=True)
- break
- except Exception as e:
- import time
- time.sleep(0.1)
+ def _start_windows_pipe_server(self):
+ """Create Windows named pipe server"""
+ try:
+ import win32pipe
+ import win32file
+ import pywintypes
+ except ImportError:
+ # Fallback to TCP socket on localhost for Windows without pywin32
+ print(f"[Worker {self.worker_id}] pywin32 not available, using TCP fallback", file=sys.stderr, flush=True)
+ self._start_tcp_server()
+ return
+
+ pipe_name = f"\\\\.\\pipe\\{self.socket_name}"
+ print(f"[Worker {self.worker_id}] Creating named pipe: {pipe_name}", file=sys.stderr, flush=True)
+
+ try:
+ # Create named pipe (server mode)
+ self.server_socket = win32pipe.CreateNamedPipe(
+ pipe_name,
+ win32pipe.PIPE_ACCESS_DUPLEX,
+ win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT,
+ 1, # Max instances
+ 65536, # Out buffer size
+ 65536, # In buffer size
+ 0, # Default timeout
+ None # Security attributes
+ )
+
+ print(f"[Worker {self.worker_id}] Named pipe created, waiting for connection...", file=sys.stderr, flush=True)
+
+ # Wait for client (Rust) to connect
+ win32pipe.ConnectNamedPipe(self.server_socket, None)
+ self.client_socket = self.server_socket # Use same handle for read/write
+
+ print(f"[Worker {self.worker_id}] Client connected to named pipe", file=sys.stderr, flush=True)
+
+ except pywintypes.error as e:
+ print(f"[Worker {self.worker_id}] Named pipe error: {e}, falling back to TCP", file=sys.stderr, flush=True)
+ self._start_tcp_server()
+
+ def _start_unix_socket_server(self):
+ """Create Unix domain socket server"""
+ # Determine socket path
+ if self.socket_name.startswith('/'):
+ sock_path = self.socket_name
else:
- # Unix domain socket
- if self.socket_name.startswith('/'):
- sock_path = self.socket_name
- else:
- sock_path = f"/tmp/{self.socket_name}"
+ sock_path = f"/tmp/{self.socket_name}"
- print(f"[Worker {self.worker_id}] Connecting to socket: {sock_path}", file=sys.stderr, flush=True)
+ # Remove existing socket file if present
+ try:
+ os.unlink(sock_path)
+ except FileNotFoundError:
+ pass
- self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ print(f"[Worker {self.worker_id}] Creating Unix socket: {sock_path}", file=sys.stderr, flush=True)
- # Wait for Rust to create the socket
- import time
- for i in range(50): # 5 seconds total
- try:
- self.socket.connect(sock_path)
- print(f"[Worker {self.worker_id}] Connected to socket", file=sys.stderr, flush=True)
- break
- except Exception as e:
- if i == 49:
- raise
- time.sleep(0.1)
+ self.server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.server_socket.bind(sock_path)
+ self.server_socket.listen(1)
- def read_message(self):
- """Read a MessagePack message from socket"""
- if sys.platform == 'win32':
- import win32file
- # Read length (4 bytes)
- _, len_bytes = win32file.ReadFile(self.socket, 4)
- msg_len = struct.unpack('<I', len_bytes)[0]
+ print(f"[Worker {self.worker_id}] Listening for connection...", file=sys.stderr, flush=True)
- # Read message
- _, msg_bytes = win32file.ReadFile(self.socket, msg_len)
- return msgpack.unpackb(msg_bytes, raw=False)
- else:
- # Read length (4 bytes)
- len_bytes = self.socket.recv(4)
- if not len_bytes:
- return None
+ # Accept one connection from Rust
+ self.client_socket, addr = self.server_socket.accept()
+ print(f"[Worker {self.worker_id}] Client connected", file=sys.stderr, flush=True)
- msg_len = struct.unpack('<I', len_bytes)[0]
+ def _start_tcp_server(self):
+ """Fallback TCP server on localhost (cross-platform)"""
+ # Use port based on worker ID to avoid conflicts
+ base_port = 19876
+ port = base_port + int(self.socket_name.split('-')[-1]) if '-' in self.socket_name else base_port
- # Read message
- msg_bytes = b''
- while len(msg_bytes) < msg_len:
- chunk = self.socket.recv(msg_len - len(msg_bytes))
- if not chunk:
- break
- msg_bytes += chunk
+ print(f"[Worker {self.worker_id}] Creating TCP socket on port {port}", file=sys.stderr, flush=True)
+
+ self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.server_socket.bind(('127.0.0.1', port))
+ self.server_socket.listen(1)
+
+ # Write port to a temp file so Rust can find it
+ port_file = Path(os.environ.get('TEMP', '/tmp')) / f"{self.socket_name}.port"
+ port_file.write_text(str(port))
+ print(f"[Worker {self.worker_id}] Port file: {port_file}", file=sys.stderr, flush=True)
+
+ print(f"[Worker {self.worker_id}] Listening on TCP port {port}...", file=sys.stderr, flush=True)
- return msgpack.unpackb(msg_bytes, raw=False)
+ # Accept one connection from Rust
+ self.client_socket, addr = self.server_socket.accept()
+ print(f"[Worker {self.worker_id}] Client connected from {addr}", file=sys.stderr, flush=True)
+
+ def read_message(self):
+ """Read a MessagePack/JSON message from socket"""
+ try:
+ if sys.platform == 'win32' and hasattr(self, 'using_pipe') and self.using_pipe:
+ import win32file
+ # Read length (4 bytes)
+ _, len_bytes = win32file.ReadFile(self.client_socket, 4)
+ if len(len_bytes) < 4:
+ return None
+ msg_len = struct.unpack('<I', len_bytes)[0]
+
+ # Read message
+ _, msg_bytes = win32file.ReadFile(self.client_socket, msg_len)
+ else:
+ # TCP or Unix socket
+ len_bytes = self._recv_exact(4)
+ if not len_bytes or len(len_bytes) < 4:
+ return None
+
+ msg_len = struct.unpack('<I', len_bytes)[0]
+ msg_bytes = self._recv_exact(msg_len)
+ if not msg_bytes:
+ return None
+
+ if USE_MSGPACK:
+ return msgpack.unpackb(msg_bytes, raw=False)
+ else:
+ return json.loads(msg_bytes.decode('utf-8'))
+
+ except Exception as e:
+ print(f"[Worker {self.worker_id}] Error reading message: {e}", file=sys.stderr, flush=True)
+ return None
+
+ def _recv_exact(self, n):
+ """Receive exactly n bytes from socket"""
+ data = b''
+ while len(data) < n:
+ chunk = self.client_socket.recv(n - len(data))
+ if not chunk:
+ return None
+ data += chunk
+ return data
def send_message(self, message):
- """Send a MessagePack message to socket"""
- msg_bytes = msgpack.packb(message, use_bin_type=True)
- len_bytes = struct.pack('<I', len(msg_bytes))
+ """Send a MessagePack/JSON message to socket"""
+ with self.send_lock:
+ try:
+ if USE_MSGPACK:
+ msg_bytes = msgpack.packb(message, use_bin_type=True)
+ else:
+ msg_bytes = json.dumps(message).encode('utf-8')
- if sys.platform == 'win32':
- import win32file
- win32file.WriteFile(self.socket, len_bytes + msg_bytes)
- else:
- self.socket.sendall(len_bytes + msg_bytes)
+ len_bytes = struct.pack('<I', len(msg_bytes))
+
+ if sys.platform == 'win32' and hasattr(self, 'using_pipe') and self.using_pipe:
+ import win32file
+ win32file.WriteFile(self.client_socket, len_bytes + msg_bytes)
+ else:
+ self.client_socket.sendall(len_bytes + msg_bytes)
+
+ except Exception as e:
+ print(f"[Worker {self.worker_id}] Error sending message: {e}", file=sys.stderr, flush=True)
def execute_script(self, task):
"""Execute a Python script and return the result"""
@@ -126,7 +211,6 @@ class PythonWorker:
task_id = task['task_id']
print(f"[Worker {self.worker_id}] Executing: {script_path}", file=sys.stderr, flush=True)
- print(f"[Worker {self.worker_id}] Args: {args}", file=sys.stderr, flush=True)
# Check if script exists
if not os.path.exists(script_path):
@@ -185,7 +269,7 @@ class PythonWorker:
try:
response = future.result()
self.send_message(response)
- print(f"[Worker {self.worker_id}] Task {response['task_id']} completed and sent", file=sys.stderr, flush=True)
+ print(f"[Worker {self.worker_id}] Task {response['task_id']} completed", file=sys.stderr, flush=True)
except Exception as e:
print(f"[Worker {self.worker_id}] ERROR sending response: {e}", file=sys.stderr, flush=True)
traceback.print_exc()
@@ -193,62 +277,68 @@ class PythonWorker:
def run(self):
"""Main worker loop - handles multiple concurrent requests via thread pool"""
try:
- self.connect_socket()
+ # Start server and wait for Rust to connect
+ self.start_server()
print(f"[Worker {self.worker_id}] Ready to accept tasks (thread pool with {self.num_threads} threads)", file=sys.stderr, flush=True)
while self.running:
- try:
- # Read task from socket (can handle multiple tasks)
- task = self.read_message()
+ # Read next task from socket
+ task = self.read_message()
+ if task is None:
+ print(f"[Worker {self.worker_id}] Connection closed", file=sys.stderr, flush=True)
+ break
- if task is None:
- print(f"[Worker {self.worker_id}] Connection closed", file=sys.stderr, flush=True)
- break
+ print(f"[Worker {self.worker_id}] Received task: {task.get('task_id', 'unknown')}", file=sys.stderr, flush=True)
- print(f"[Worker {self.worker_id}] Received task: {task.get('task_id')}", file=sys.stderr, flush=True)
+ # Submit task to thread pool
+ future = self.executor.submit(self.execute_script, task)
+ future.add_done_callback(self.handle_task_completion)
- # Submit execution to thread pool (runs in background - NO BLOCKING)
- future = self.executor.submit(self.execute_script, task)
+ except KeyboardInterrupt:
+ print(f"[Worker {self.worker_id}] Shutting down...", file=sys.stderr, flush=True)
+ except Exception as e:
+ print(f"[Worker {self.worker_id}] FATAL ERROR: {e}", file=sys.stderr, flush=True)
+ traceback.print_exc()
+ finally:
+ self.shutdown()
+
+ def shutdown(self):
+ """Clean up resources"""
+ self.running = False
+ self.executor.shutdown(wait=False)
+
+ if self.client_socket:
+ try:
+ if sys.platform == 'win32' and hasattr(self, 'using_pipe') and self.using_pipe:
+ import win32file
+ win32file.CloseHandle(self.client_socket)
+ else:
+ self.client_socket.close()
+ except:
+ pass
- # Add callback to send response when done (non-blocking)
- future.add_done_callback(self.handle_task_completion)
+ if self.server_socket and self.server_socket != self.client_socket:
+ try:
+ self.server_socket.close()
+ except:
+ pass
- print(f"[Worker {self.worker_id}] Task submitted to thread pool", file=sys.stderr, flush=True)
+ print(f"[Worker {self.worker_id}] Shutdown complete", file=sys.stderr, flush=True)
- except KeyboardInterrupt:
- print(f"[Worker {self.worker_id}] Interrupted", file=sys.stderr, flush=True)
- break
- except Exception as e:
- print(f"[Worker {self.worker_id}] ERROR in main loop: {e}", file=sys.stderr, flush=True)
- traceback.print_exc()
- finally:
- # Shutdown thread pool
- print(f"[Worker {self.worker_id}] Shutting down thread pool...", file=sys.stderr, flush=True)
- self.executor.shutdown(wait=True)
-
- if self.socket:
- try:
- if sys.platform == 'win32':
- import win32file
- win32file.CloseHandle(self.socket)
- else:
- self.socket.close()
- except:
- pass
-
- print(f"[Worker {self.worker_id}] Shutdown complete", file=sys.stderr, flush=True)
-
-
-if __name__ == '__main__':
- if len(sys.argv) < 4:
- print("Usage: worker.py <socket_name> <worker_id> <num_threads>", file=sys.stderr)
+def main():
+ if len(sys.argv) < 3:
+ print("Usage: worker.py <socket_name> <worker_id> [num_threads]", file=sys.stderr)
sys.exit(1)
socket_name = sys.argv[1]
worker_id = int(sys.argv[2])
- num_threads = int(sys.argv[3])
+ num_threads = int(sys.argv[3]) if len(sys.argv) > 3 else 4
worker = PythonWorker(socket_name, worker_id, num_threads)
worker.run()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs b/fincept-terminal-desktop/src-tauri/src/worker_pool.rs
index 8ceeb5d81..0996ad115 100644
--- a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs
+++ b/fincept-terminal-desktop/src-tauri/src/worker_pool.rs
@@ -214,16 +214,33 @@ impl WorkerPool {
eprintln!("[Worker {}] Process spawned, PID: {:?}", worker_id, process.id());
- // Wait a bit for worker to start listening (minimal delay)
- tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
-
- // Connect to worker's socket
- let socket = LocalSocketStream::connect(
- socket_name.to_ns_name::<GenericNamespaced>()
- .map_err(|e| format!("Failed to create socket name: {}", e))?
- ).map_err(|e| format!("Failed to connect to worker {}: {}", worker_id, e))?;
+ // Wait for worker to start listening with retry logic
+ // Python worker creates server socket, so we need to wait for it
+ let mut socket: Option<LocalSocketStream> = None;
+ let max_retries = 50; // 5 seconds total (50 * 100ms)
+
+ for attempt in 0..max_retries {
+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+
+ match LocalSocketStream::connect(
+ socket_name.to_ns_name::<GenericNamespaced>()
+ .map_err(|e| format!("Failed to create socket name: {}", e))?
+ ) {
+ Ok(s) => {
+ socket = Some(s);
+ eprintln!("[Worker {}] Connected to socket after {} attempts", worker_id, attempt + 1);
+ break;
+ }
+ Err(e) => {
+ if attempt == max_retries - 1 {
+ return Err(format!("Failed to connect to worker {} after {} attempts: {}", worker_id, max_retries, e));
+ }
+ // Continue retrying silently
+ }
+ }
+ }
- eprintln!("[Worker {}] Connected to socket", worker_id);
+ let socket = socket.ok_or_else(|| format!("Failed to connect to worker {}", worker_id))?;
Ok(Worker {
process,