This commit is contained in:
Nicholas Kariniemi 2014-09-24 06:20:19 +03:00
parent 0d2d619a1b
commit 31b6d40aef

View file

@ -6,36 +6,44 @@
;; Server state
(def states (ref []))
(def to-db (atom nil))
(defn make-client [in client-state states]
(let [out (chan)
full-sync! (fn []
(let [new-client (dosync (let [state (sync/get-current-state @states)]
(defmulti handle-message (fn [msg states client-state] (:type msg)))
(defn full-sync! [msg states client-state]
(let [new-client (dosync (let [state (sync/get-current-state @states)]
(ref-set client-state state)))]
(println "full-sync!")
(a/put! out (message/full-sync new-client))))]
(a/go-loop
[]
(when-let [msg (<! in)]
(condp = (:type msg)
:new-state (let [diff-result (sync/diff-states (:new-states msg) @client-state)
{:keys [diff shadow-hash]} diff-result
out-msg (message/diff-msg diff shadow-hash)]
(println "new-state!")
(a/put! out out-msg))
:diff (dosync
(println "diff!")
(let [{:keys [diff shadow-hash]} msg
apply-result (sync/apply-diff @states diff shadow-hash)
{:keys [new-states new-shadow full-sync?]} apply-result]
(ref-set states new-states)
(ref-set client-state new-shadow)
(when full-sync? (full-sync!))))
:full-sync (full-sync!)
nil)
(recur)))
(message/full-sync new-client)))
(defmethod handle-message :full-sync [msg states client-state]
(full-sync! msg states client-state))
(defmethod handle-message :new-state [msg states client-state]
(let [diff-result (sync/diff-states (:new-states msg) @client-state)
{:keys [diff shadow-hash]} diff-result]
(println "new-state!")
(message/diff-msg diff shadow-hash)))
(defmethod handle-message :diff [msg states client-state]
(dosync
(println "diff!")
(let [{:keys [diff shadow-hash]} msg
apply-result (sync/apply-diff @states diff shadow-hash)
{:keys [new-states new-shadow full-sync?]} apply-result]
(ref-set states new-states)
(ref-set client-state new-shadow)
(when full-sync? (full-sync! msg states client-state)))))
(defn make-client-agent [in initial-states]
(let [out (chan)]
(a/go-loop [client-state sync/empty-state
states initial-states]
(if-let [msg (<! in)]
(do (when-let [{:keys [new-client new-states]} (handle-message msg states client-state)]
(>! >client response))
(recur))
(remove-watch states client-id)))
out))
(defn sync-new-client! [>client <client]
@ -46,11 +54,11 @@
client-state (ref sync/empty-state)]
(add-watch states client-id (fn [_ _ _ new-states] (a/put! state-changes new-states)))
(a/pipe (a/merge [<client state-change-events]) events)
(let [out (make-client events client-state states)]
(a/go-loop [] (if-let [v (<! out)]
(do (>! >client v)
(recur))
(remove-watch states client-id))))))
(a/go-loop [] (if-let [msg (<! in)]
(do (when-let [response (handle-message msg states client-state)]
(>! >client response))
(recur))
(remove-watch states client-id)))))
(defn init [_to-db grubs recipes]
(dosync (ref-set states (sync/initial-state grubs recipes)))