Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Make the SSE early-stop test wait for the server to stop (#85034)

Andrei Simionescu7b1f5711b6fb
diff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.clj
index 3c3b67f4a2e..d143f5e70af 100644
--- a/test/metabase/metabot/self_test.clj
+++ b/test/metabase/metabot/self_test.clj
@@ -39,7 +39,8 @@
[metabase.util.json :as json]
[metabase.util.log.capture :as log.capture]
[metabase.util.malli :as mu]
- [metabase.util.malli.registry :as mr]))
+ [metabase.util.malli.registry :as mr]
+ [ring.adapter.jetty :as jetty]))
(set! *warn-on-reflection* true)
@@ -427,6 +428,54 @@
(self.core/sse-reducible istream))]
(is (= ["msg-0" "msg-1" "msg-2"] result)))))
+(deftest sse-reducible-stops-response-test
+ (let [total 500
+ sent (atom 0)
+ stopped (promise)
+ handler (fn [_req]
+ (let [out (java.io.PipedOutputStream.)
+ in (java.io.PipedInputStream. out 65536)]
+ (future
+ (try
+ (dotimes [i total]
+ (.write out (.getBytes (test-util/make-sse [(str "msg-" i)])))
+ (.flush out)
+ (swap! sent inc)
+ (Thread/sleep 10))
+ (catch Exception _)
+ (finally
+ (try (.close out)
+ (catch Exception _))
+ (deliver stopped true))))
+ {:status 200
+ :headers {"Content-Type" "text/event-stream"
+ "Cache-Control" "no-cache"}
+ :body in}))
+ server (jetty/run-jetty handler {:port 0
+ :join? false
+ :output-buffer-size 1})
+ url (str "http://localhost:" (.. server getURI getPort))
+ opts {:method :post :url url :as :stream}]
+ (try
+ ;; Held through the checks, so that a garbage-collected socket can't stop the server in sse-reducible's place
+ (with-open [^java.io.Closeable body (self.core/abort-on-close (http/request opts) opts)]
+ (let [reducible (self.core/sse-reducible body)
+ ;; Take only 2 items, which should trigger early termination
+ result (reduce (fn [acc item]
+ (if (< (count acc) 2)
+ (conj acc item)
+ (reduced acc)))
+ []
+ reducible)]
+ (is (= ["msg-0" "msg-1"] result))
+ (is (deref stopped 10000 false)
+ "the server was still writing 10 s after the client stopped reading")
+ (is (< @sent (/ total 2))
+ (str "the server kept writing after the client stopped reading: it wrote "
+ @sent " of " total " messages"))))
+ (finally
+ (.stop server)))))
+
(deftest lite-aisdk-xf-test
(testing "streams text deltas immediately instead of batching"
(let [chunks [{:type :start :messageId "msg-1"}