feat: add SSE process filter for stream parsing
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user