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
|
mm-web.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
tokio.workspace = true
|
# Объединяем workspace = true с дополнительной фичей "sync" (нужна для broadcast::channel)
|
||||||
|
tokio = { workspace = true, features = ["sync"] }
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
tracing-subscriber.workspace = true
|
tracing-subscriber.workspace = true
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
use mm_client::ws::WsConnection;
|
use mm_client::ws::WsConnection;
|
||||||
use mm_core::{BridgeError, ErrorKind, ServerId, User};
|
use mm_core::{BridgeError, ErrorKind, ServerId, User};
|
||||||
|
use serde_json::Value;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tokio::sync::broadcast;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct ConnectionState {
|
pub struct ConnectionState {
|
||||||
@@ -15,15 +17,22 @@ pub struct ConnectionState {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
connections: Arc<Mutex<HashMap<ServerId, ConnectionState>>>,
|
connections: Arc<Mutex<HashMap<ServerId, ConnectionState>>>,
|
||||||
|
event_tx: broadcast::Sender<Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
|
let (tx, _) = broadcast::channel(100); // Буфер до 100 событий
|
||||||
Self {
|
Self {
|
||||||
connections: Arc::new(Mutex::new(HashMap::new())),
|
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> {
|
pub fn get_connection(&self, server_id: &ServerId) -> Result<ConnectionState, BridgeError> {
|
||||||
self.connections
|
self.connections
|
||||||
.lock()
|
.lock()
|
||||||
@@ -40,6 +49,7 @@ impl AppState {
|
|||||||
pub async fn start_ws(&self, server_id: &ServerId) -> Result<(), BridgeError> {
|
pub async fn start_ws(&self, server_id: &ServerId) -> Result<(), BridgeError> {
|
||||||
let state = self.get_connection(server_id)?;
|
let state = self.get_connection(server_id)?;
|
||||||
let sid = server_id.clone();
|
let sid = server_id.clone();
|
||||||
|
let event_tx = self.event_tx.clone();
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
match WsConnection::new(&state.url, &state.token).await {
|
match WsConnection::new(&state.url, &state.token).await {
|
||||||
@@ -48,8 +58,35 @@ impl AppState {
|
|||||||
loop {
|
loop {
|
||||||
match ws.next_event().await {
|
match ws.next_event().await {
|
||||||
Ok(Some(event_data)) => {
|
Ok(Some(event_data)) => {
|
||||||
tracing::debug!(server_id = %sid, "WS Event: {}", event_data);
|
// Пытаемся распарсить и нормализовать событие 'posted'
|
||||||
// TODO: Fan out to Emacs clients
|
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) => {
|
Ok(None) => {
|
||||||
tracing::warn!(server_id = %sid, "WebSocket closed");
|
tracing::warn!(server_id = %sid, "WebSocket closed");
|
||||||
|
|||||||
@@ -122,6 +122,14 @@ pub fn encode_response(response: &Response) -> Result<String, BridgeError> {
|
|||||||
Ok(line)
|
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 {
|
pub fn pong_result() -> Value {
|
||||||
json!({ "pong": true })
|
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::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
use crate::app::App;
|
pub async fn handle_client(app: App, stream: TcpStream) -> anyhow::Result<()> {
|
||||||
|
|
||||||
pub async fn handle_client(app: App, stream: TcpStream) -> std::io::Result<()> {
|
|
||||||
let peer = stream.peer_addr().ok();
|
let peer = stream.peer_addr().ok();
|
||||||
tracing::info!(?peer, "client connected");
|
tracing::info!(?peer, "client connected");
|
||||||
|
|
||||||
let (read_half, mut write_half) = stream.into_split();
|
let (read_half, write_half) = stream.into_split();
|
||||||
let mut lines = BufReader::new(read_half).lines();
|
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() {
|
if line.trim().is_empty() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let response = app.response_line(&line).await;
|
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");
|
tracing::info!(?peer, "client disconnected");
|
||||||
Ok(())
|
result
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,8 +68,11 @@
|
|||||||
(time-str (if create-at
|
(time-str (if create-at
|
||||||
(format-time-string "%H:%M" (seconds-to-time (/ create-at 1000)))
|
(format-time-string "%H:%M" (seconds-to-time (/ create-at 1000)))
|
||||||
"??:??"))
|
"??:??"))
|
||||||
(user-id (or (plist-get post :user_id) "unknown")))
|
;; Используем user_display_name, если есть, иначе user_id
|
||||||
(insert (format "[%s] %s: %s\n" time-str user-id msg-text))))
|
(sender (or (plist-get post :user_display_name)
|
||||||
|
(plist-get post :user_id)
|
||||||
|
"unknown")))
|
||||||
|
(insert (format "[%s] %s: %s\n" time-str sender msg-text))))
|
||||||
|
|
||||||
(insert "\n")
|
(insert "\n")
|
||||||
(goto-char (point-max))))
|
(goto-char (point-max))))
|
||||||
@@ -81,7 +84,8 @@
|
|||||||
(mattermost-channel-load-history))
|
(mattermost-channel-load-history))
|
||||||
|
|
||||||
(defun mattermost-channel-send-message ()
|
(defun mattermost-channel-send-message ()
|
||||||
"Send a message to the current channel."
|
"Send a message to the current channel.
|
||||||
|
The message will appear automatically via WebSocket fan-out; no refresh needed."
|
||||||
(interactive)
|
(interactive)
|
||||||
(let* ((server-id mattermost--server-id)
|
(let* ((server-id mattermost--server-id)
|
||||||
(channel-id mattermost--channel-id)
|
(channel-id mattermost--channel-id)
|
||||||
@@ -97,9 +101,29 @@
|
|||||||
:message msg)
|
:message msg)
|
||||||
(lambda (response)
|
(lambda (response)
|
||||||
(if (plist-get response :ok)
|
(if (plist-get response :ok)
|
||||||
(progn
|
(message "[MM] Message sent. Waiting for WS echo...")
|
||||||
(message "[MM] Message sent successfully.")
|
|
||||||
(mattermost-channel-refresh))
|
|
||||||
(message "[MM] Failed to send message: %S" (plist-get response :error)))))))
|
(message "[MM] Failed to send message: %S" (plist-get response :error)))))))
|
||||||
|
|
||||||
|
(defun mattermost-channel-on-posted (params)
|
||||||
|
"Handle a 'posted' event. PARAMS should contain the 'post' plist."
|
||||||
|
(let* ((post (plist-get params :post))
|
||||||
|
(channel-id (plist-get post :channel_id))
|
||||||
|
(msg-text (or (plist-get post :message) ""))
|
||||||
|
(create-at (plist-get post :create_at))
|
||||||
|
(time-str (if create-at
|
||||||
|
(format-time-string "%H:%M" (seconds-to-time (/ create-at 1000)))
|
||||||
|
"??:??"))
|
||||||
|
(sender (or (plist-get post :user_display_name)
|
||||||
|
(plist-get post :user_id)
|
||||||
|
"unknown")))
|
||||||
|
(dolist (buf (buffer-list))
|
||||||
|
(with-current-buffer buf
|
||||||
|
(when (and (eq major-mode 'mattermost-channel-mode)
|
||||||
|
(string= mattermost--channel-id channel-id))
|
||||||
|
(let ((inhibit-read-only t))
|
||||||
|
(goto-char (point-max))
|
||||||
|
(insert (format "[%s] %s: %s\n" time-str sender msg-text))
|
||||||
|
(when (= (point) (point-max))
|
||||||
|
(goto-char (point-max)))))))))
|
||||||
|
|
||||||
(provide 'mattermost-channel)
|
(provide 'mattermost-channel)
|
||||||
|
|||||||
@@ -25,28 +25,21 @@
|
|||||||
mattermost-bridge-host
|
mattermost-bridge-host
|
||||||
mattermost-bridge-port))
|
mattermost-bridge-port))
|
||||||
|
|
||||||
;; Очищаем буфер при новом подключении
|
|
||||||
(setq mattermost--input-buffer "")
|
(setq mattermost--input-buffer "")
|
||||||
|
|
||||||
(set-process-filter mattermost--process #'mattermost--process-filter)
|
(set-process-filter mattermost--process #'mattermost--process-filter)
|
||||||
(message "[MM-PROTOCOL] Connected to Mattermost bridge."))
|
(message "[MM-PROTOCOL] Connected to Mattermost bridge."))
|
||||||
|
|
||||||
(defun mattermost--process-filter (_proc output)
|
(defun mattermost--process-filter (_proc output)
|
||||||
"Handle OUTPUT from the bridge process with proper chunk buffering."
|
"Handle OUTPUT from the bridge process with proper chunk buffering."
|
||||||
;; Добавляем новые данные к накопителю
|
|
||||||
(setq mattermost--input-buffer (concat mattermost--input-buffer output))
|
(setq mattermost--input-buffer (concat mattermost--input-buffer output))
|
||||||
|
|
||||||
;; Разбиваем по переносам строк
|
|
||||||
(let ((lines (split-string mattermost--input-buffer "\n" t)))
|
(let ((lines (split-string mattermost--input-buffer "\n" t)))
|
||||||
;; Последняя строка может быть неполной — сохраняем её на следующий вызов
|
|
||||||
(if (string-suffix-p "\n" output)
|
(if (string-suffix-p "\n" output)
|
||||||
(setq mattermost--input-buffer "")
|
(setq mattermost--input-buffer "")
|
||||||
(setq mattermost--input-buffer (car (last lines)))
|
(setq mattermost--input-buffer (car (last lines)))
|
||||||
;; Убираем последний (неполный) элемент из списка для обработки
|
|
||||||
(setq lines (butlast lines)))
|
(setq lines (butlast lines)))
|
||||||
|
|
||||||
(dolist (line lines)
|
(dolist (line lines)
|
||||||
;; ДОБАВЛЕНО: :array-type 'list чтобы JSON-массивы становились списками, а не векторами
|
|
||||||
(let ((msg (ignore-errors (json-parse-string line :object-type 'plist :array-type 'list))))
|
(let ((msg (ignore-errors (json-parse-string line :object-type 'plist :array-type 'list))))
|
||||||
(if msg
|
(if msg
|
||||||
(let ((id (plist-get msg :id))
|
(let ((id (plist-get msg :id))
|
||||||
@@ -67,13 +60,10 @@
|
|||||||
(defun mattermost--send-request (method params callback)
|
(defun mattermost--send-request (method params callback)
|
||||||
"Send a request with METHOD and PARAMS, calling CALLBACK on response."
|
"Send a request with METHOD and PARAMS, calling CALLBACK on response."
|
||||||
(let* ((id (format "req-%d" (random 100000)))
|
(let* ((id (format "req-%d" (random 100000)))
|
||||||
;; 1. Создаем реальный payload для отправки
|
|
||||||
(payload (list :id id :type "request" :method method :params params))
|
(payload (list :id id :type "request" :method method :params params))
|
||||||
(json-str (concat (json-encode payload) "\n"))
|
(json-str (concat (json-encode payload) "\n"))
|
||||||
;; 2. Создаем копию ТОЛЬКО для логирования
|
|
||||||
(safe-params (copy-tree params)))
|
(safe-params (copy-tree params)))
|
||||||
|
|
||||||
;; Маскируем пароль в копии для лога
|
|
||||||
(when (plist-get safe-params :password)
|
(when (plist-get safe-params :password)
|
||||||
(plist-put safe-params :password "***MASKED***"))
|
(plist-put safe-params :password "***MASKED***"))
|
||||||
|
|
||||||
@@ -81,12 +71,16 @@
|
|||||||
(message "[MM-PROTOCOL] Sending request id=%s method=%s" id method))
|
(message "[MM-PROTOCOL] Sending request id=%s method=%s" id method))
|
||||||
|
|
||||||
(puthash id callback mattermost--pending-requests)
|
(puthash id callback mattermost--pending-requests)
|
||||||
;; Отправляем реальный json-str с настоящим паролем!
|
|
||||||
(process-send-string mattermost--process json-str)))
|
(process-send-string mattermost--process json-str)))
|
||||||
|
|
||||||
(defun mattermost--handle-event (_msg)
|
(defun mattermost--handle-event (msg)
|
||||||
"Handle an asynchronous event MSG from the bridge."
|
"Handle an asynchronous event MSG from the bridge."
|
||||||
;; TODO: Fan out events to buffers
|
(let ((method (plist-get msg :method))
|
||||||
)
|
(params (plist-get msg :params)))
|
||||||
|
(cond
|
||||||
|
((string= method "posted")
|
||||||
|
(mattermost-channel-on-posted params))
|
||||||
|
(t
|
||||||
|
(message "[MM-DEBUG] Unhandled event method: %s" method)))))
|
||||||
|
|
||||||
(provide 'mattermost-protocol)
|
(provide 'mattermost-protocol)
|
||||||
|
|||||||
Reference in New Issue
Block a user