stynx_code_tools/infrastructure/
question_bridge.rs1use std::sync::{Arc, Mutex};
2
3use tokio::sync::{mpsc, oneshot};
4
5pub struct QuestionRequest {
6 pub question: String,
7 pub responder: oneshot::Sender<Option<String>>,
8}
9
10#[derive(Clone)]
11pub struct QuestionBridge {
12 sender: mpsc::UnboundedSender<QuestionRequest>,
13}
14
15impl QuestionBridge {
16 pub fn new() -> (Self, mpsc::UnboundedReceiver<QuestionRequest>) {
17 let (tx, rx) = mpsc::unbounded_channel();
18 (Self { sender: tx }, rx)
19 }
20
21 pub async fn ask(&self, question: String) -> Option<String> {
22 let (tx, rx) = oneshot::channel();
23 let req = QuestionRequest { question, responder: tx };
24 if self.sender.send(req).is_err() {
25 return None;
26 }
27 rx.await.ok().flatten()
28 }
29}
30
31#[derive(Default)]
32pub struct OptionalQuestionBridge(Mutex<Option<QuestionBridge>>);
33
34impl OptionalQuestionBridge {
35 pub fn new() -> Self { Self(Mutex::new(None)) }
36 pub fn set(&self, b: QuestionBridge) { *self.0.lock().unwrap() = Some(b); }
37 pub fn get(&self) -> Option<QuestionBridge> { self.0.lock().unwrap().clone() }
38}
39
40pub type SharedQuestionBridge = Arc<OptionalQuestionBridge>;