Serialize message tags

This commit is contained in:
2023-09-10 19:24:45 +02:00
parent 7f34d39118
commit 57019b484e
2 changed files with 57 additions and 4 deletions

View File

@ -24,8 +24,31 @@
[jepsen.os.debian :as debian])
(:import java.net.Socket))
(defn write-command [writer {cmd :cmd
params :params}]
(defn escape-tag-value [v]
(str/replace v #"[; \\\r\n]" (fn [c]
(case c
";" "\\:"
" " "\\s"
"\\" "\\\\"
"\r" "\\r"
"\n" "\\n"))))
(defn write-command [writer {tags :tags, :or {}
cmd :cmd
params :params}]
(if (and tags (not (empty? tags)))
(do
(.write writer "@")
(doseq [[i [k v]] (map-indexed vector tags)]
(do
(if (= i 0)
nil
(.write writer ";"))
(.write writer k)
(.write writer "=")
(.write writer (escape-tag-value (or v "")))))
(.write writer " "))
nil)
(.write writer cmd)
(.write writer
(if (empty? params)
@ -40,7 +63,7 @@
(.flush (:writer client)))
(defn send-commands [client commands]
(for [command commands]
(doseq [command commands]
(write-command (:writer client) command))
(.flush (:writer client)))

View File

@ -21,7 +21,37 @@
(testing "formatting command with three params"
(let [buf (java.io.StringWriter.)]
(write-command buf {:cmd "KICK" :params ["#chan" "badperson" "bye bye"]})
(is (= (.toString buf) "KICK #chan badperson :bye bye\r\n")))))
(is (= (.toString buf) "KICK #chan badperson :bye bye\r\n")))
(testing "formatting command with empty set of tags"
(let [buf (java.io.StringWriter.)]
(write-command buf {:tags {} :cmd "AWAY" :params []})
(is (= (.toString buf) "AWAY\r\n"))))
(testing "formatting command with tag with no value"
(let [buf (java.io.StringWriter.)]
(write-command buf {:tags {"foo" nil} :cmd "AWAY" :params []})
(is (= (.toString buf) "@foo= AWAY\r\n"))))
(testing "formatting command with tag with empty value"
(let [buf (java.io.StringWriter.)]
(write-command buf {:tags {"foo" ""} :cmd "AWAY" :params []})
(is (= (.toString buf) "@foo= AWAY\r\n"))))
(testing "formatting command with tag"
(let [buf (java.io.StringWriter.)]
(write-command buf {:tags {"foo" "bar"} :cmd "AWAY" :params []})
(is (= (.toString buf) "@foo=bar AWAY\r\n"))))
(testing "formatting command with tags"
(let [buf (java.io.StringWriter.)]
(write-command buf {:tags {"foo" "bar" "baz" "qux"} :cmd "AWAY" :params []})
(is (= (.toString buf) "@foo=bar;baz=qux AWAY\r\n"))))
(testing "formatting command with tag value containing chars to escape"
(let [buf (java.io.StringWriter.)]
(write-command buf {:tags {"foo" "ab;cd ef\rgh\nij"} :cmd "AWAY" :params []})
(is (= (.toString buf) "@foo=ab\\:cd\\sef\\rgh\\nij AWAY\r\n"))))))
(deftest parse-command-test
(testing "parsing a command with no param"