diff options
Diffstat (limited to 'lib/app')
-rw-r--r-- | lib/app/chat.ex | 22 |
1 files changed, 15 insertions, 7 deletions
diff --git a/lib/app/chat.ex b/lib/app/chat.ex index 696e53c..b93e7b3 100644 --- a/lib/app/chat.ex +++ b/lib/app/chat.ex @@ -19,6 +19,8 @@ defmodule SApp.Chat do use GenServer + alias SData.MerkleList, as: ML + @doc """ Start a process that connects to a given channel """ @@ -30,7 +32,7 @@ defmodule SApp.Chat do Initialize channel process. """ def init(channel) do - {:ok, store} = SData.MerkleList.start_link(&msg_cmp/2) + store = ML.new(&msg_cmp/2) manifest = {:chat, channel} id = SData.term_hash manifest @@ -76,13 +78,13 @@ defmodule SApp.Chat do msgitem = {(System.os_time :seconds), Shard.Identity.get_nickname(), msg} - GenServer.cast(state.store, {:insert, msgitem}) + new_state = %{state | store: ML.insert(state.store, msgitem)} for peer <- state.peers do - push_messages(state, peer, nil, 5) + push_messages(new_state, peer, nil, 5) end - {:noreply, state} + {:noreply, new_state} end @doc """ @@ -110,12 +112,13 @@ defmodule SApp.Chat do Shard.Manager.send(peer_id, {state.id, {:manifest, state.manifest}}) {:get, start} -> push_messages(peer_id, state, start, 20) {:info, _start, list, rest} -> - if rest != nil and not GenServer.call(state.store, {:has, rest}) do + if rest != nil and not ML.has(state.store, rest) do Shard.Manager.send(peer_id, {state.id, {:get, rest}}) end + who = self() spawn_link(fn -> Process.sleep 1000 - GenServer.cast(state.store, {:insert_many, list, (fn msg -> msg_callback(state.channel, msg) end)}) + GenServer.cast(who, {:deferred_insert, list}) end) _ -> nil end @@ -127,8 +130,13 @@ defmodule SApp.Chat do end end + def handle_cast({:deferred_insert, list}, state) do + new_store = ML.insert_many(state.store, list, (fn msg -> msg_callback(state.channel, msg) end)) + %{state | store: new_store} + end + defp push_messages(state, to, start, num) do - case GenServer.call(state.store, {:read, start, num}) do + case ML.read(state.store, start, num) do {:ok, list, rest} -> Shard.Manager.send(to, {state.id, {:info, start, list, rest}}) _ -> nil |