1use std::collections::HashMap;
72use std::sync::{Arc, Mutex};
73use std::time::{Duration, Instant};
74
75use futures_util::stream::{SplitSink, SplitStream};
76use futures_util::{SinkExt, StreamExt};
77use tokio::sync::mpsc;
78use tokio_tungstenite::{tungstenite::Message, MaybeTlsStream, WebSocketStream};
79
80use crate::backend::reactive::types::InjectionRequest;
81use crate::messaging::{BridgeHealth, BridgeStatus, OutboundMsg};
82
83use super::rest;
84use super::types::{AckFrame, EventsApiPayload, SlackEvent, SocketEnvelope};
85
86const RECONNECT_DELAY_SECS: u64 = 5;
87const MAX_RECONNECT_DELAY_SECS: u64 = 60;
88
89const DEAD_CONN_TIMEOUT_SECS: u64 = 300;
93
94const CHANNEL_MIN_SPACING: Duration = Duration::from_millis(1100);
97
98const HELLO_TIMEOUT_SECS: u64 = 10;
100
101type WsStream = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;
102type WsWrite = SplitSink<WsStream, Message>;
103type WsRead = SplitStream<WsStream>;
104
105struct WsHalf {
106 write: WsWrite,
107 read: WsRead,
108}
109
110pub async fn run_bridge(
113 app_token: String,
114 bot_token: String,
115 channel_id: String,
116 target_agent: Option<String>,
117 http: reqwest::Client,
118 outbound_rx: mpsc::UnboundedReceiver<OutboundMsg>,
119 health: Arc<Mutex<BridgeHealth>>,
120) {
121 let outbound_http = http.clone();
122 let default_channel = channel_id.clone();
123 tokio::join!(
124 run_socket_loop(app_token, channel_id, target_agent, http, health),
125 run_outbound_loop(outbound_http, bot_token, default_channel, outbound_rx),
126 );
127}
128
129async fn run_socket_loop(
137 app_token: String,
138 channel_id: String,
139 target_agent: Option<String>,
140 http: reqwest::Client,
141 health: Arc<Mutex<BridgeHealth>>,
142) {
143 let mut delay_secs = RECONNECT_DELAY_SECS;
144
145 loop {
146 {
147 let mut h = health.lock().unwrap();
148 h.status = BridgeStatus::Connecting;
149 }
150
151 let session_start = Instant::now();
152
153 match connect_and_run(&app_token, &channel_id, &target_agent, &http, &health).await {
154 Ok(()) => {
155 tracing::info!("slack_bridge: session ended cleanly");
156 }
157 Err(e) => {
158 tracing::warn!("slack_bridge: session error: {e}");
159 let mut h = health.lock().unwrap();
160 h.status = BridgeStatus::Error;
161 h.error = Some(e);
162 h.reconnect_count += 1;
163 }
164 }
165
166 if session_start.elapsed().as_secs() > 30 {
167 delay_secs = RECONNECT_DELAY_SECS;
168 }
169
170 {
171 let mut h = health.lock().unwrap();
172 if h.status != BridgeStatus::Error {
173 h.status = BridgeStatus::Disconnected;
174 }
175 }
176
177 tokio::time::sleep(Duration::from_secs(delay_secs)).await;
178 delay_secs = (delay_secs * 2).min(MAX_RECONNECT_DELAY_SECS);
179 }
180}
181
182async fn connect_and_run(
183 app_token: &str,
184 channel_id: &str,
185 target_agent: &Option<String>,
186 http: &reqwest::Client,
187 health: &Arc<Mutex<BridgeHealth>>,
188) -> Result<(), String> {
189 let mut primary = open_and_await_hello(app_token, http).await?;
190
191 {
192 let mut h = health.lock().unwrap();
193 h.status = BridgeStatus::Connected;
194 h.error = None;
195 h.last_event_at = Some(unix_secs());
196 }
197 tracing::info!("slack_bridge: connected (hello received)");
198
199 run_session(app_token, channel_id, target_agent, http, health, &mut primary).await
200}
201
202async fn open_and_await_hello(app_token: &str, http: &reqwest::Client) -> Result<WsHalf, String> {
206 let url = rest::open_connection(http, app_token).await?;
207 tracing::debug!(
208 "slack_bridge: opened connection ({})",
209 rest::redact_ticket(&url)
210 );
211
212 let request = tokio_tungstenite::tungstenite::http::Request::builder()
213 .uri(&url)
214 .body(())
215 .map_err(|e| format!("slack_bridge: build ws request: {e}"))?;
216
217 let (ws_stream, _) = crate::muxbus::ws_connect::connect(request)
218 .await
219 .map_err(|e| format!("slack_bridge: ws connect: {e}"))?;
220
221 let (write, mut read) = ws_stream.split();
222
223 match tokio::time::timeout(Duration::from_secs(HELLO_TIMEOUT_SECS), read.next()).await {
224 Ok(Some(Ok(Message::Text(text)))) => match serde_json::from_str::<SocketEnvelope>(&text) {
225 Ok(SocketEnvelope::Hello(_)) => Ok(WsHalf { write, read }),
226 Ok(_) => Err("slack_bridge: expected hello as first frame, got a different envelope type".to_string()),
227 Err(e) => Err(format!("slack_bridge: parse first frame: {e}")),
228 },
229 Ok(Some(Ok(_))) => Err("slack_bridge: expected hello as first frame, got a non-text frame".to_string()),
230 Ok(Some(Err(e))) => Err(format!("slack_bridge: ws recv error awaiting hello: {e}")),
231 Ok(None) => Err("slack_bridge: socket closed before hello".to_string()),
232 Err(_) => Err("slack_bridge: timed out waiting for hello".to_string()),
233 }
234}
235
236async fn next_frame(
241 old: &mut Option<WsHalf>,
242) -> Option<Result<Message, tokio_tungstenite::tungstenite::Error>> {
243 match old {
244 Some(half) => half.read.next().await,
245 None => std::future::pending().await,
246 }
247}
248
249enum FrameOutcome {
250 Continue,
251 WarningReceived,
252 Closed,
253}
254
255async fn run_session(
263 app_token: &str,
264 channel_id: &str,
265 target_agent: &Option<String>,
266 http: &reqwest::Client,
267 health: &Arc<Mutex<BridgeHealth>>,
268 primary: &mut WsHalf,
269) -> Result<(), String> {
270 let mut old: Option<WsHalf> = None;
271 let mut cutover_pending = false;
272
273 let mut cutover_connect: std::pin::Pin<
274 Box<dyn std::future::Future<Output = Result<WsHalf, String>> + Send>,
275 > = Box::pin(std::future::pending());
276
277 let mut dead_conn_sleep = Box::pin(tokio::time::sleep(Duration::from_secs(
278 DEAD_CONN_TIMEOUT_SECS,
279 )));
280
281 loop {
282 tokio::select! {
283 _ = &mut dead_conn_sleep => {
285 return Err(format!(
286 "no frames received for {DEAD_CONN_TIMEOUT_SECS}s — treating connection as dead"
287 ));
288 }
289
290 result = &mut cutover_connect, if cutover_pending => {
292 cutover_pending = false;
293 cutover_connect = Box::pin(std::future::pending());
294 match result {
295 Ok(new_half) => {
296 tracing::info!("slack_bridge: cutover connection ready (hello received) — promoting to primary");
297 let retiring = std::mem::replace(primary, new_half);
298 old = Some(retiring);
299 dead_conn_sleep = Box::pin(tokio::time::sleep(Duration::from_secs(DEAD_CONN_TIMEOUT_SECS)));
300 let mut h = health.lock().unwrap();
301 h.last_event_at = Some(unix_secs());
302 }
303 Err(e) => {
304 tracing::warn!("slack_bridge: cutover connect failed: {e} — staying on current primary until it closes");
309 }
310 }
311 }
312
313 frame = primary.read.next() => {
315 match frame {
316 None => return Ok(()),
317 Some(Err(e)) => return Err(format!("ws recv (primary): {e}")),
318 Some(Ok(msg)) => {
319 dead_conn_sleep = Box::pin(tokio::time::sleep(Duration::from_secs(DEAD_CONN_TIMEOUT_SECS)));
320 let outcome = handle_frame(msg, &mut primary.write, channel_id, target_agent, health).await?;
321 match outcome {
322 FrameOutcome::Continue => {}
323 FrameOutcome::Closed => return Ok(()),
324 FrameOutcome::WarningReceived => {
325 if cutover_pending || old.is_some() {
345 tracing::debug!(
346 "slack_bridge: disconnect warning while a cutover is already in flight or draining — ignoring"
347 );
348 } else {
349 tracing::info!("slack_bridge: disconnect warning received — starting make-before-break reconnect");
350 cutover_pending = true;
351 let app_token = app_token.to_string();
352 let http = http.clone();
353 cutover_connect = Box::pin(async move { open_and_await_hello(&app_token, &http).await });
354 }
355 }
356 }
357 }
358 }
359 }
360
361 frame = next_frame(&mut old), if old.is_some() => {
364 match frame {
365 None | Some(Err(_)) => {
366 tracing::debug!("slack_bridge: old socket closed/errored after cutover — discarding");
367 old = None;
368 }
369 Some(Ok(msg)) => {
370 if let Some(half) = old.as_mut() {
374 match handle_frame(msg, &mut half.write, channel_id, target_agent, health).await {
375 Ok(FrameOutcome::Closed) => {
376 tracing::info!("slack_bridge: old socket closed cleanly after cutover");
377 old = None;
378 }
379 Ok(_) => {}
380 Err(e) => {
381 tracing::debug!("slack_bridge: old socket error after cutover (harmless — draining): {e}");
382 old = None;
383 }
384 }
385 }
386 }
387 }
388 }
389 }
390 }
391}
392
393async fn handle_frame(
397 msg: Message,
398 write: &mut WsWrite,
399 channel_id: &str,
400 target_agent: &Option<String>,
401 health: &Arc<Mutex<BridgeHealth>>,
402) -> Result<FrameOutcome, String> {
403 match msg {
404 Message::Text(text) => {
405 let envelope: SocketEnvelope = match serde_json::from_str(&text) {
406 Ok(e) => e,
407 Err(e) => {
408 tracing::warn!("slack_bridge: parse error: {e}");
409 return Ok(FrameOutcome::Continue);
410 }
411 };
412
413 match envelope {
414 SocketEnvelope::Hello(_) => {
415 tracing::debug!("slack_bridge: hello frame on an already-active socket");
416 Ok(FrameOutcome::Continue)
417 }
418 SocketEnvelope::EventsApi(ev) => {
419 ack_envelope(write, &ev.envelope_id).await?;
420 route_event(ev.payload, channel_id, target_agent, health);
421 Ok(FrameOutcome::Continue)
422 }
423 SocketEnvelope::SlashCommands(ev) => {
424 ack_envelope(write, &ev.envelope_id).await?;
428 tracing::debug!("slack_bridge: received slash_commands envelope (not handled — out of scope for this PR)");
429 Ok(FrameOutcome::Continue)
430 }
431 SocketEnvelope::Disconnect(d) => {
432 if d.reason.as_deref() == Some("warning") {
433 Ok(FrameOutcome::WarningReceived)
434 } else {
435 tracing::info!("slack_bridge: disconnect frame (reason={:?})", d.reason);
436 Ok(FrameOutcome::Closed)
437 }
438 }
439 SocketEnvelope::Unknown => {
440 tracing::debug!("slack_bridge: unhandled envelope type");
441 Ok(FrameOutcome::Continue)
442 }
443 }
444 }
445 Message::Ping(data) => {
446 let _ = write.send(Message::Pong(data)).await;
447 Ok(FrameOutcome::Continue)
448 }
449 Message::Close(_) => Ok(FrameOutcome::Closed),
450 _ => Ok(FrameOutcome::Continue),
451 }
452}
453
454async fn ack_envelope(write: &mut WsWrite, envelope_id: &str) -> Result<(), String> {
458 let ack = AckFrame {
459 envelope_id: envelope_id.to_string(),
460 };
461 let ack_json = serde_json::to_string(&ack).unwrap_or_default();
462 write
463 .send(Message::Text(ack_json.into()))
464 .await
465 .map_err(|e| format!("slack_bridge: ack send: {e}"))
466}
467
468fn should_route(event: &SlackEvent, channel_id: &str) -> bool {
472 if event.bot_id.is_some() {
473 return false; }
475 if event.type_ != "message" && event.type_ != "app_mention" {
476 return false;
477 }
478 event.channel.as_deref() == Some(channel_id) }
480
481fn route_event(
482 payload: Option<EventsApiPayload>,
483 channel_id: &str,
484 target_agent: &Option<String>,
485 health: &Arc<Mutex<BridgeHealth>>,
486) {
487 let Some(event) = payload.and_then(|p| p.event) else {
488 return;
489 };
490
491 if !should_route(&event, channel_id) {
492 return;
493 }
494
495 {
496 let mut h = health.lock().unwrap();
497 h.last_event_at = Some(unix_secs());
498 }
499
500 let Some(target) = target_agent else {
501 tracing::debug!("slack_bridge: event in #{channel_id} (no target agent configured)");
502 return;
503 };
504
505 let user = event.user.as_deref().unwrap_or("unknown");
506 let text = event.text.as_deref().unwrap_or("");
507 let envelope = format!("[Slack #{channel_id} @{user}]: {text}");
508
509 let req = InjectionRequest {
510 target_agent: target.clone(),
511 message: envelope,
512 source_agent: Some("slack".to_string()),
513 request_id: event.ts.clone(),
514 priority: None,
515 jekt_tier: None,
516 delivery_tier: Some("wan".to_string()),
517 forward_hops: 0,
518 ..Default::default()
519 };
520 let result = crate::server::jekt_entry::inject_from_bridge(req, text);
521 if result.success {
522 tracing::debug!("slack_bridge: injected msg from {user} to agent {target}");
523 } else {
524 tracing::warn!(
525 "slack_bridge: inject to agent {target} failed: {:?}",
526 result.error
527 );
528 }
529}
530
531async fn run_outbound_loop(
534 http: reqwest::Client,
535 bot_token: String,
536 default_channel_id: String,
537 mut outbound_rx: mpsc::UnboundedReceiver<OutboundMsg>,
538) {
539 let mut channel_last_sent: HashMap<String, Instant> = HashMap::new();
543 let mut channel_backoff_until: HashMap<String, Instant> = HashMap::new();
544 let mut channel_backoff_secs: HashMap<String, u64> = HashMap::new();
545
546 while let Some(msg) = outbound_rx.recv().await {
547 handle_outbound(
548 &http,
549 &bot_token,
550 &default_channel_id,
551 msg,
552 &mut channel_last_sent,
553 &mut channel_backoff_until,
554 &mut channel_backoff_secs,
555 )
556 .await;
557 }
558}
559
560fn resolve_channel_id(channel_id: &str, default_channel_id: &str) -> Option<String> {
563 if !channel_id.is_empty() {
564 return Some(channel_id.to_string());
565 }
566 if default_channel_id.is_empty() {
567 return None;
568 }
569 Some(default_channel_id.to_string())
570}
571
572fn next_backoff_secs(current: u64) -> u64 {
576 (current * 2).min(MAX_RECONNECT_DELAY_SECS)
577}
578
579async fn handle_outbound(
580 http: &reqwest::Client,
581 bot_token: &str,
582 default_channel_id: &str,
583 msg: OutboundMsg,
584 channel_last_sent: &mut HashMap<String, Instant>,
585 channel_backoff_until: &mut HashMap<String, Instant>,
586 channel_backoff_secs: &mut HashMap<String, u64>,
587) {
588 let Some(channel_id) = resolve_channel_id(&msg.channel_id, default_channel_id) else {
589 tracing::warn!(
590 "slack_bridge: send dropped — no channel_id (empty channel_id and no messaging:slack:channel configured)"
591 );
592 return;
593 };
594
595 if let Some(until) = channel_backoff_until.get(&channel_id).copied() {
596 let now = Instant::now();
597 if now < until {
598 tokio::time::sleep(until - now).await;
599 }
600 channel_backoff_until.remove(&channel_id);
601 }
602
603 if let Some(last) = channel_last_sent.get(&channel_id) {
604 let elapsed = last.elapsed();
605 if elapsed < CHANNEL_MIN_SPACING {
606 tokio::time::sleep(CHANNEL_MIN_SPACING - elapsed).await;
607 }
608 }
609
610 match rest::post_message(http, bot_token, &channel_id, &msg).await {
611 Ok(()) => {
612 channel_last_sent.insert(channel_id.clone(), Instant::now());
613 channel_backoff_secs.remove(&channel_id);
614 }
615 Err(e) if e.retry_after.is_some() => {
616 let retry_after = e.retry_after.unwrap();
618 tracing::warn!(
619 "slack_bridge: rate limited sending to #{channel_id}, retry_after={retry_after}s — waiting then retrying once"
620 );
621 tokio::time::sleep(Duration::from_secs(retry_after)).await;
622
623 match rest::post_message(http, bot_token, &channel_id, &msg).await {
624 Ok(()) => {
625 channel_last_sent.insert(channel_id.clone(), Instant::now());
626 channel_backoff_secs.remove(&channel_id);
627 }
628 Err(e2) if e2.retry_after.is_some() => {
629 tracing::warn!(
632 "slack_bridge: retry after rate limit still rate-limited for #{channel_id}: {e2}"
633 );
634 let current = channel_backoff_secs
635 .get(&channel_id)
636 .copied()
637 .unwrap_or(RECONNECT_DELAY_SECS);
638 channel_backoff_until.insert(channel_id.clone(), Instant::now() + Duration::from_secs(current));
639 channel_backoff_secs.insert(channel_id, next_backoff_secs(current));
640 }
641 Err(e2) => {
642 tracing::warn!(
647 "slack_bridge: retry after rate limit failed for #{channel_id} for an unrelated reason: {e2}"
648 );
649 }
650 }
651 }
652 Err(e) => {
653 tracing::warn!("slack_bridge: send to #{channel_id} failed: {e}");
654 }
655 }
656}
657
658fn unix_secs() -> u64 {
659 agentmux_common::time::now_secs_u64()
660}
661
662#[cfg(test)]
663mod tests {
664 use super::*;
665 use super::super::types::SlackEvent;
666
667 fn event(type_: &str, channel: Option<&str>, bot_id: Option<&str>) -> SlackEvent {
668 SlackEvent {
669 type_: type_.to_string(),
670 channel: channel.map(str::to_string),
671 user: Some("U1".to_string()),
672 text: Some("hi".to_string()),
673 ts: Some("123.4".to_string()),
674 bot_id: bot_id.map(str::to_string),
675 }
676 }
677
678 #[test]
679 fn should_route_accepts_message_in_configured_channel() {
680 let e = event("message", Some("C1"), None);
681 assert!(should_route(&e, "C1"));
682 }
683
684 #[test]
685 fn should_route_accepts_app_mention() {
686 let e = event("app_mention", Some("C1"), None);
687 assert!(should_route(&e, "C1"));
688 }
689
690 #[test]
691 fn should_route_rejects_other_channel() {
692 let e = event("message", Some("C2"), None);
693 assert!(!should_route(&e, "C1"));
694 }
695
696 #[test]
697 fn should_route_rejects_missing_channel() {
698 let e = event("message", None, None);
699 assert!(!should_route(&e, "C1"));
700 }
701
702 #[test]
703 fn should_route_rejects_bot_authored_events() {
704 let e = event("message", Some("C1"), Some("B1"));
705 assert!(!should_route(&e, "C1"));
706 }
707
708 #[test]
709 fn should_route_rejects_unrelated_event_types() {
710 let e = event("channel_join", Some("C1"), None);
711 assert!(!should_route(&e, "C1"));
712 }
713
714 #[test]
715 fn resolve_channel_id_uses_explicit_channel_when_present() {
716 assert_eq!(resolve_channel_id("C1", "C_default"), Some("C1".to_string()));
717 }
718
719 #[test]
720 fn resolve_channel_id_falls_back_to_default_when_empty() {
721 assert_eq!(resolve_channel_id("", "C_default"), Some("C_default".to_string()));
722 }
723
724 #[test]
725 fn resolve_channel_id_none_when_both_empty() {
726 assert_eq!(resolve_channel_id("", ""), None);
727 }
728
729 #[test]
730 fn next_backoff_secs_doubles() {
731 assert_eq!(next_backoff_secs(5), 10);
732 assert_eq!(next_backoff_secs(10), 20);
733 }
734
735 #[test]
736 fn next_backoff_secs_caps_at_max() {
737 assert_eq!(next_backoff_secs(45), MAX_RECONNECT_DELAY_SECS);
738 assert_eq!(next_backoff_secs(60), MAX_RECONNECT_DELAY_SECS);
739 }
740
741 #[test]
744 fn duplicate_warning_while_cutover_pending_is_a_noop_decision() {
745 let cutover_pending = true;
750 let should_start_new_cutover = !cutover_pending;
751 assert!(!should_start_new_cutover);
752 }
753
754 #[test]
755 fn fresh_warning_when_not_pending_starts_cutover() {
756 let cutover_pending = false;
757 let should_start_new_cutover = !cutover_pending;
758 assert!(should_start_new_cutover);
759 }
760}