Skip to content

Instantly share code, notes, and snippets.

@rwat
Created April 30, 2018 14:10
Show Gist options
  • Save rwat/31e0487bab2bb166ee79079439d0fb57 to your computer and use it in GitHub Desktop.
Save rwat/31e0487bab2bb166ee79079439d0fb57 to your computer and use it in GitHub Desktop.
(ns pg.web.messaging
(:require [cljs.core.async :refer [>! <! chan put! take! timeout close!] :as async]
[ajax.core :refer [GET POST]]
[pg.util :as util]
)
(:require-macros [cljs.core.async.macros :refer [alt! go go-loop]]))
(def temp-start-time (util/local-instval))
;; these are the only functions and vars exported from this namespace
(declare add-tap-input)
(declare del-tap-input)
(def request-count (atom 0))
(def ^:private input (chan 20))
(def pending-output (atom []))
(def notify-output (chan (async/sliding-buffer 1)))
(let [in-mult (async/mult input)]
(defn add-tap-input
[ch]
(async/tap in-mult ch))
(defn del-tap-input
[ch]
(async/untap in-mult ch)))
(defn temp-continue-time? ;;;; TEMPORARY
"Return true when running for less than 3 minutes"
[]
(when (< (util/local-instval)
(+ temp-start-time (* 180 1000)))
true))
(declare send-message)
(defn handler
"Take received messages and send them to the main input chan. Continue
polling loop to server."
[msg]
(println "handler: " msg)
(when-not (= :none msg)
(put! input msg))
(when (and (zero? (swap! request-count dec))
(temp-continue-time?)) ;;;; TEMPORARY
(send-message)))
(defn error-handler
[]
(swap! request-count dec)
(println "error-handler was called"))
(defn send-message
[& [msg]]
(swap! request-count inc)
(POST "/message" {:params (or msg {})
:handler handler
:error-handler error-handler}))
(defn message
[msg]
(swap! pending-output conj msg)
(put! notify-output true))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(go-loop [msg (<! notify-output)]
(comment "implements throttling of messages to 100ms batches")
(let [[msgs _] (reset-vals! pending-output [])]
(when (seq msgs)
(send-message msgs))
(<! (timeout 100))
(recur (<! notify-output))))
;; TEMPORARY - start loop
(message {:key "value"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment