Packages
riptide
0.1.14
0.5.2
0.5.1
0.5.0-beta9
0.5.0-beta8
0.5.0-beta7
0.5.0-beta6
0.5.0-beta5
0.5.0-beta4
0.5.0-beta3
0.5.0-beta2
0.5.0-beta11
0.5.0-beta10
0.5.0-beta
0.4.6
0.4.5
0.4.4
0.4.3
0.4.2
0.4.1
0.4.0
0.3.13
0.3.12
0.3.11
0.3.10
0.3.9
0.3.8
0.3.7
0.3.6
0.3.5
0.3.4
0.3.3
0.3.2
0.3.1
0.3.0
0.3.0-bd63a38
0.2.79
0.2.78
0.2.74
0.2.4
0.2.3
0.2.2
0.2.1
0.2.0
0.1.15
0.1.14
0.1.13
0.1.12
0.1.11
0.1.10
0.1.9
0.1.8
0.1.7
0.1.6
0.1.5
0.1.4
0.1.3
0.1.2
0.1.1
0.1.0
A data first framework for building realtime applications
Current section
Files
Jump to
Current section
Files
lib/riptide/websocket.ex
defmodule Riptide.Websocket do
@behaviour :cowboy_websocket
def init(req, state) do
{
:cowboy_websocket,
req,
Map.put(state, :data, %{}),
%{
compress: true,
idle_timeout: :timer.hours(24)
}
}
end
def terminate(_reason, _req, state) do
state.commands
|> Riptide.Processor.process_commands(:disconnect, :handle_info, __MODULE__, state)
|> Riptide.Processor.process_response(nil, state)
:ok
end
def websocket_init(state) do
:timer.send_interval(:timer.seconds(30), :ping_send)
{:ok, state}
end
def websocket_handle({:text, msg}, state) do
Riptide.Processor.process(state.commands, msg, __MODULE__, state)
|> case do
{:reply, value, state} -> {:reply, {:text, value}, state}
{:noreply, state} -> {:ok, state}
end
end
def websocket_handle(_msg, state) do
{:ok, state}
end
def websocket_info(:ping_send, state) do
{:reply, :ping, state}
end
def websocket_info({:call, from, action, body}, state) do
{text, next} = Riptide.Processor.build_call(from, action, body, state)
{:reply, {:text, text}, next}
end
def websocket_info({ref, msg}, state) when is_reference(ref) do
{key, tasks} = Map.pop(state.tasks, ref)
Process.demonitor(ref, [:flush])
case msg do
{:reply, value} ->
{:reply, {:text, Riptide.Processor.build_reply(key, "reply", value)},
%{state | tasks: tasks}}
{:error, error} ->
{:reply, {:text, Riptide.Processor.build_reply(key, "error", error)},
%{state | tasks: tasks}}
end
end
def websocket_info(msg, state) do
state.commands
|> Riptide.Processor.process_commands(msg, :handle_info, __MODULE__, state)
|> Riptide.Processor.process_response(nil, state)
|> case do
{:reply, value, state} -> {:reply, {:text, value}, state}
{:noreply, state} -> {:ok, state}
end
end
def call(pid, action, body) do
send(pid, {:call, {self(), make_ref()}, action, body})
loop()
end
defp loop() do
receive do
{ref, result} when is_reference(ref) ->
result
result ->
send(self(), result)
loop()
end
end
end