Current section

Files

Jump to
riptide lib riptide command.ex
Raw

lib/riptide/command.ex

defmodule Riptide.Command do
require Logger
@callback handle_call(msg :: any(), from :: any(), state :: any()) ::
{:reply, any(), any()} | nil
@callback handle_cast(msg :: any(), from :: any(), state :: any()) :: {:noreply, any()} | nil
@callback handle_info(msg :: any(), from :: any(), state :: any()) :: {:noreply, any()} | nil
defmacro(__using__(_opts)) do
quote do
@behaviour Riptide.Command
@before_compile Riptide.Command
end
end
def process_message(commands, msg, fun, from, state) do
[Riptide.Command.Echo | commands]
|> Stream.map(&safe_trigger(&1, fun, msg, from, state))
|> Stream.filter(fn result -> result !== nil end)
|> Enum.at(0)
|> case do
nil -> {:error, :invalid_message, state}
result -> result
end
end
def safe_trigger(mod, fun, msg, from, state) do
try do
apply(mod, fun, [msg, from, state])
rescue
e ->
:error
|> Exception.format(e, __STACKTRACE__)
|> Logger.error(crash_reason: {e, __STACKTRACE__})
{:error, e, state}
catch
_, e ->
:throw
|> Exception.format(e, __STACKTRACE__)
|> Logger.error(crash_reason: {e, __STACKTRACE__})
{:error, e, state}
end
end
defmacro __before_compile__(_opts) do
quote do
def handle_call(msg, from, state), do: nil
def handle_cast(msg, _from, state), do: nil
def handle_info(msg, _from, state), do: nil
end
end
end
defmodule Riptide.Command.Echo do
use Riptide.Command
def handle_call(%{action: "riptide.echo", body: body}, _, state) do
{:reply, body, state}
end
end