Skip to content

Instantly share code, notes, and snippets.

@rwat rwat/pg.web.messaging.clj
Last active May 3, 2018

Embed
What would you like to do?
(ns pg.web.messaging
(:require [clojure.core.async :refer [>! <! >!! <!! alts! alts!! chan go go-loop thread timeout close!] :as async]
[pg.util :as util]
))
(def buffer-size 50)
(def wait-time (* 25 1000))
(comment "
{ /cid/ -> { :chan /chan/
:lastmsg /timestamp/
:connections /n/ }
}
")
(def client-data (atom {}))
(defn get-client-chan!
[cid]
(-> (swap! client-data
(fn [state]
(if (get-in state [cid :chan])
state
(assoc-in state
[cid :chan]
(chan (async/sliding-buffer buffer-size))))))
(get-in [cid :chan])))
(defn begin-request
[cid]
(swap! client-data
#(-> %
(update-in [cid :connections] (fnil inc 0))
(assoc-in [cid :lastmsg] (System/currentTimeMillis)))))
(defn end-request
[cid]
(swap! client-data update-in [cid :connections] (fnil dec 1)))
(defn msg-receive-long
[client-chan]
(let [[x port] (alts!! [client-chan (timeout wait-time)])]
(if (= port client-chan)
x
:none)))
(defn msg-receive-short
[client-chan]
(or
(util/maybe-take! client-chan)
:none))
(defn msg-receive
[cid]
(let [max-allowed-connections 2
connections (do (-> (begin-request cid)
(get-in [cid :connections])))
client-chan (get-client-chan! cid)]
(if (> connections max-allowed-connections)
(msg-receive-short client-chan)
(msg-receive-long client-chan))))
; TODO: write something that purges old/unused cid entries after a period of time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.