perf(ui): remove redundant history refresh after send_post
The message now appears automatically via WebSocket fan-out, eliminating the extra get_history round-trip.
This commit is contained in:
@@ -17,7 +17,8 @@ mm-store.workspace = true
|
||||
mm-web.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
# Объединяем workspace = true с дополнительной фичей "sync" (нужна для broadcast::channel)
|
||||
tokio = { workspace = true, features = ["sync"] }
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use mm_client::ws::WsConnection;
|
||||
use mm_core::{BridgeError, ErrorKind, ServerId, User};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConnectionState {
|
||||
@@ -15,15 +17,22 @@ pub struct ConnectionState {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AppState {
|
||||
connections: Arc<Mutex<HashMap<ServerId, ConnectionState>>>,
|
||||
event_tx: broadcast::Sender<Value>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new() -> Self {
|
||||
let (tx, _) = broadcast::channel(100); // Буфер до 100 событий
|
||||
Self {
|
||||
connections: Arc::new(Mutex::new(HashMap::new())),
|
||||
event_tx: tx,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subscribe_events(&self) -> broadcast::Receiver<Value> {
|
||||
self.event_tx.subscribe()
|
||||
}
|
||||
|
||||
pub fn get_connection(&self, server_id: &ServerId) -> Result<ConnectionState, BridgeError> {
|
||||
self.connections
|
||||
.lock()
|
||||
@@ -40,6 +49,7 @@ impl AppState {
|
||||
pub async fn start_ws(&self, server_id: &ServerId) -> Result<(), BridgeError> {
|
||||
let state = self.get_connection(server_id)?;
|
||||
let sid = server_id.clone();
|
||||
let event_tx = self.event_tx.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
match WsConnection::new(&state.url, &state.token).await {
|
||||
@@ -48,8 +58,35 @@ impl AppState {
|
||||
loop {
|
||||
match ws.next_event().await {
|
||||
Ok(Some(event_data)) => {
|
||||
tracing::debug!(server_id = %sid, "WS Event: {}", event_data);
|
||||
// TODO: Fan out to Emacs clients
|
||||
// Пытаемся распарсить и нормализовать событие 'posted'
|
||||
if let Ok(json_val) = serde_json::from_str::<Value>(&event_data) {
|
||||
if let Some(event_type) =
|
||||
json_val.get("event").and_then(|v| v.as_str())
|
||||
{
|
||||
if event_type == "posted" {
|
||||
if let Some(data) = json_val.get("data") {
|
||||
// Mattermost присылает post как строку, содержащую JSON
|
||||
if let Some(post_str) =
|
||||
data.get("post").and_then(|v| v.as_str())
|
||||
{
|
||||
if let Ok(post_obj) =
|
||||
serde_json::from_str::<Value>(post_str)
|
||||
{
|
||||
let normalized = serde_json::json!({
|
||||
"type": "event",
|
||||
"method": "posted",
|
||||
"params": {
|
||||
"post": post_obj
|
||||
}
|
||||
});
|
||||
// Игнорируем ошибку, если нет подписчиков (Emacs отключён)
|
||||
let _ = event_tx.send(normalized);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
tracing::warn!(server_id = %sid, "WebSocket closed");
|
||||
|
||||
@@ -122,6 +122,14 @@ pub fn encode_response(response: &Response) -> Result<String, BridgeError> {
|
||||
Ok(line)
|
||||
}
|
||||
|
||||
/// Encodes a standalone event (not tied to a specific request ID)
|
||||
pub fn encode_event(event_payload: &Value) -> Result<String, BridgeError> {
|
||||
let mut line = serde_json::to_string(event_payload)
|
||||
.map_err(|err| BridgeError::new(ErrorKind::InternalError, err.to_string()))?;
|
||||
line.push('\n');
|
||||
Ok(line)
|
||||
}
|
||||
|
||||
pub fn pong_result() -> Value {
|
||||
json!({ "pong": true })
|
||||
}
|
||||
|
||||
@@ -1,25 +1,65 @@
|
||||
use crate::app::App;
|
||||
use crate::protocol;
|
||||
use anyhow::Context;
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
pub async fn handle_client(app: App, stream: TcpStream) -> std::io::Result<()> {
|
||||
pub async fn handle_client(app: App, stream: TcpStream) -> anyhow::Result<()> {
|
||||
let peer = stream.peer_addr().ok();
|
||||
tracing::info!(?peer, "client connected");
|
||||
|
||||
let (read_half, mut write_half) = stream.into_split();
|
||||
let mut lines = BufReader::new(read_half).lines();
|
||||
let (read_half, write_half) = stream.into_split();
|
||||
let mut reader = BufReader::new(read_half);
|
||||
let mut lines = reader.lines();
|
||||
|
||||
while let Some(line) = lines.next_line().await? {
|
||||
// Обёртка для безопасного совместного использования writer между двумя задачами
|
||||
let writer = Arc::new(Mutex::new(write_half));
|
||||
|
||||
// Подписываемся на события моста (WebSocket fan-out)
|
||||
let mut event_rx = app.state.subscribe_events();
|
||||
|
||||
// Запускаем фоновую задачу для отправки асинхронных событий в этот TCP-сокет
|
||||
let writer_for_events = Arc::clone(&writer);
|
||||
let writer_handle = tokio::spawn(async move {
|
||||
while let Ok(event) = event_rx.recv().await {
|
||||
if let Ok(line) = protocol::encode_event(&event) {
|
||||
let mut w = writer_for_events.lock().await;
|
||||
if w.write_all(line.as_bytes()).await.is_err() {
|
||||
break;
|
||||
}
|
||||
if w.flush().await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Основной цикл чтения запросов от Emacs
|
||||
let mut result = Ok(());
|
||||
while let Some(line) = lines.next_line().await.context("read line failed")? {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let response = app.response_line(&line).await;
|
||||
write_half.write_all(response.as_bytes()).await?;
|
||||
write_half.flush().await?;
|
||||
{
|
||||
let mut w = writer.lock().await;
|
||||
if w.write_all(response.as_bytes()).await.is_err() {
|
||||
result = Err(anyhow::anyhow!("client disconnected during write"));
|
||||
break;
|
||||
}
|
||||
if w.flush().await.is_err() {
|
||||
result = Err(anyhow::anyhow!("client disconnected during flush"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Отменяем задачу записи событий при отключении клиента
|
||||
writer_handle.abort();
|
||||
|
||||
tracing::info!(?peer, "client disconnected");
|
||||
Ok(())
|
||||
result
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user