use std::collections::HashMap;
use std::sync::atomic::AtomicU64;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use crate::adapters::motherduck_bridge::errors::BridgeError;
#[derive(Debug, Clone)]
pub struct BridgeConnection {
pub cursor: Arc<BridgeCursor>,
}
#[derive(Debug)]
pub struct BridgeCursor {
pub id: u64,
pub process: Arc<BridgeProcess>,
}
impl Drop for BridgeCursor {
fn drop(&mut self) {
let close = serde_json::json!({"op": "close", "cursor": self.id});
let _ = self.process.lines.send(close.to_string());
}
}
#[derive(Debug)]
pub struct BridgeProcess {
pub python: String,
pub pid: u32,
pub lines: Sender<String>,
pub replies: Arc<Mutex<Replies>>,
pub next_request: AtomicU64,
pub next_cursor: AtomicU64,
pub stderr: Arc<Mutex<String>>,
pub writer: Option<std::thread::JoinHandle<()>>,
}
impl Drop for BridgeProcess {
fn drop(&mut self) {
self.lines = std::sync::mpsc::channel().0;
if let Some(writer) = self.writer.take() {
let _ = writer.join();
}
}
}
#[derive(Debug, Default)]
pub struct Replies {
pub waiting: HashMap<u64, Sender<Result<serde_json::Value, BridgeError>>>,
pub stopped: Option<String>,
}