;;; mattermost-protocol.el --- TCP JSONL protocol handler -*- lexical-binding: t; -*- (require 'json) (require 'mattermost-custom) (defvar mattermost--process nil "The process object for the bridge connection.") (defvar mattermost--pending-requests (make-hash-table :test 'equal) "Hash table of pending requests indexed by ID.") (defvar mattermost--input-buffer "" "Accumulator for incomplete TCP chunks.") (defun mattermost-connect-to-bridge () "Connect to the running Rust bridge." (interactive) (when (and (boundp 'mattermost--process) mattermost--process (process-live-p mattermost--process)) (delete-process mattermost--process)) (setq mattermost--process (open-network-stream "mattermost-bridge" "*mattermost-log*" mattermost-bridge-host mattermost-bridge-port)) ;; Очищаем буфер при новом подключении (setq mattermost--input-buffer "") (set-process-filter mattermost--process #'mattermost--process-filter) (message "[MM-PROTOCOL] Connected to Mattermost bridge.")) (defun mattermost--process-filter (_proc output) "Handle OUTPUT from the bridge process with proper chunk buffering." ;; Добавляем новые данные к накопителю (setq mattermost--input-buffer (concat mattermost--input-buffer output)) ;; Разбиваем по переносам строк (let ((lines (split-string mattermost--input-buffer "\n" t))) ;; Последняя строка может быть неполной — сохраняем её на следующий вызов (if (string-suffix-p "\n" output) (setq mattermost--input-buffer "") (setq mattermost--input-buffer (car (last lines))) ;; Убираем последний (неполный) элемент из списка для обработки (setq lines (butlast lines))) (dolist (line lines) ;; ДОБАВЛЕНО: :array-type 'list чтобы JSON-массивы становились списками, а не векторами (let ((msg (ignore-errors (json-parse-string line :object-type 'plist :array-type 'list)))) (if msg (let ((id (plist-get msg :id)) (type (plist-get msg :type))) (cond ((string= type "response") (let ((cb (gethash id mattermost--pending-requests))) (if cb (progn (funcall cb msg) (remhash id mattermost--pending-requests)) (message "[MM-PROTOCOL] WARNING: No callback for id=%s" id)))) ((string= type "event") (mattermost--handle-event msg)))) (message "[MM-PROTOCOL] Failed to parse JSON: %S" (substring line 0 (min 100 (length line))))))))) (defun mattermost--send-request (method params callback) "Send a request with METHOD and PARAMS, calling CALLBACK on response." (let* ((id (format "req-%d" (random 100000))) ;; 1. Создаем реальный payload для отправки (payload (list :id id :type "request" :method method :params params)) (json-str (concat (json-encode payload) "\n")) ;; 2. Создаем копию ТОЛЬКО для логирования (safe-params (copy-tree params))) ;; Маскируем пароль в копии для лога (when (plist-get safe-params :password) (plist-put safe-params :password "***MASKED***")) (let ((safe-payload (list :id id :type "request" :method method :params safe-params))) (message "[MM-PROTOCOL] Sending request id=%s method=%s" id method)) (puthash id callback mattermost--pending-requests) ;; Отправляем реальный json-str с настоящим паролем! (process-send-string mattermost--process json-str))) (defun mattermost--handle-event (_msg) "Handle an asynchronous event MSG from the bridge." ;; TODO: Fan out events to buffers ) (provide 'mattermost-protocol)