Skip to content

Instantly share code, notes, and snippets.

@rwat
Last active May 3, 2018 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwat/8df479c160f76f15cd87e93e33ffdc34 to your computer and use it in GitHub Desktop.
Save rwat/8df479c160f76f15cd87e93e33ffdc34 to your computer and use it in GitHub Desktop.
(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