;; This Source Code Form is subject to the terms of the Mozilla Public ;; License, v. 2.0. If a copy of the MPL was not distributed with this ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; ;; Copyright (c) 2020 UXBOX Labs SL (ns uxbox.services.notifications "A websocket based notifications mechanism." (:require [clojure.tools.logging :as log] [clojure.core.async :as a :refer [>! > (t/str->bytes message) (t/decode))) (defn- encode-message [message] (->> (t/encode message) (t/bytes->str))) ;; --- Redis Interactions (defn- publish [channel message] (vu/go-try (let [message (encode-message message)] (! output message))))) (defn- close-all! [{:keys [sch] :as ws}] (a/close! sch) (.close ^java.lang.AutoCloseable ws)) (defn start-loop! [{:keys [input output sch on-error] :as ws}] (vu/go-try (loop [] (let [timeout (a/timeout 30000) [val port] (a/alts! [input sch timeout])] ;; (prn "alts" val "from" (cond (= port input) "input" ;; (= port sch) "redis" ;; :else "timeout")) (cond ;; Process message coming from connected client (and (= port input) (not (nil? val))) (do (! output (encode-message {:type :ping})) (recur)) :else nil))))) (defn- on-subscribed [{:keys [on-error] :as ws} sch] (let [ws (assoc ws :sch sch)] (a/go (try ( (redis/subscribe (str fid)) (p/finally (fn [sch error] (if error (on-error error) (on-subscribed ws sch)))))))