From a4dbcf828724199fc6c131668fb32a7740c5cb16 Mon Sep 17 00:00:00 2001 From: James Brechtel Date: Thu, 11 Jun 2026 12:44:16 -0400 Subject: [PATCH] feat: add SSE process filter for stream parsing --- noise-sse.el | 21 +++++++++++++++++++++ test/noise-sse-test.el | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/noise-sse.el b/noise-sse.el index c5fa6cf..f10934d 100644 --- a/noise-sse.el +++ b/noise-sse.el @@ -50,5 +50,26 @@ Returns nil for empty or invalid events." (json-parse-string json-str) (error nil))))))) +(defvar noise-sse--buffer "" + "Buffer for partial SSE event data.") + +(defun noise-sse--filter (proc string) + "Process filter for SSE connection. +Buffers incoming STRING and processes complete events." + (setq noise-sse--buffer (concat noise-sse--buffer string)) + (while (string-match "\n\n" noise-sse--buffer) + (let ((event-end (match-beginning 0)) + (event-start 0)) + (let ((event-str (substring noise-sse--buffer event-start event-end))) + (setq noise-sse--buffer + (substring noise-sse--buffer (+ event-end 2))) + (when-let ((event (noise-sse--parse-event event-str))) + (noise-sse--handle-event event)))))) + +(defun noise-sse--handle-event (event) + "Handle a parsed SSE EVENT. +This function will be overridden in noise-receive to process envelopes." + (message "SSE event received: %s" event)) + (provide 'noise-sse) ;;; noise-sse.el ends here diff --git a/test/noise-sse-test.el b/test/noise-sse-test.el index baade5f..00c80f2 100644 --- a/test/noise-sse-test.el +++ b/test/noise-sse-test.el @@ -55,5 +55,26 @@ (noise-sse--increase-reconnect-delay) (should (= 60 noise-sse--reconnect-delay)))) +(ert-deftest noise-sse--filter-processes-complete-event () + "Process filter parses and calls handler for complete events." + (let ((processed-events '())) + (cl-letf (((symbol-function 'noise-sse--handle-event) + (lambda (event) (push event processed-events)))) + (let ((noise-sse--buffer "")) + (noise-sse--filter nil "data: {\"type\":\"message\"}\n\n") + (should (= 1 (length processed-events))) + (should (hash-table-p (car processed-events))))))) + +(ert-deftest noise-sse--filter-buffers-incomplete-event () + "Process filter buffers incomplete events until newline." + (let ((processed-events '())) + (cl-letf (((symbol-function 'noise-sse--handle-event) + (lambda (event) (push event processed-events)))) + (let ((noise-sse--buffer "")) + (noise-sse--filter nil "data: {\"type\":\"message\"") + (should (= 0 (length processed-events))) + (noise-sse--filter nil "}\n\n") + (should (= 1 (length processed-events))))))) + (provide 'noise-sse-test) ;;; noise-sse-test.el ends here