WIP: Supervisor-based plugin base

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
2020-07-12 12:19:14 -07:00
parent e2a746709d
commit 9679c46e15
10 changed files with 33 additions and 71 deletions

View File

@@ -79,7 +79,7 @@ defmodule Omnibot.Plugin.Base do
end
end
#@callback handle_msg(irc :: pid(), msg :: %Omnibot.Irc.Msg{}) :: any
@callback handle_msg(irc :: pid(), msg :: %Omnibot.Irc.Msg{}) :: any
@callback on_msg(irc :: pid(), msg :: %Omnibot.Irc.Msg{}) :: any
@callback on_channel_msg(irc :: pid(), channel :: String.t(), nick :: String.t(), line :: String.t()) :: any
@callback on_channel_msg(

View File

@@ -1,50 +0,0 @@
defmodule Omnibot.Plugin.GenServer do
defmacro __using__([]) do
quote do
use Omnibot.Plugin.Base
use GenServer
def start_link(opts) do
cfg = opts[:cfg]
state = opts[:state]
GenServer.start_link(__MODULE__, {cfg, state}, opts)
end
def cfg() do
GenServer.call(__MODULE__, :cfg)
end
def state() do
GenServer.call(__MODULE__, :state)
end
def update_state(update) do
GenServer.cast(__MODULE__, {:state, update})
end
## Server callbacks
@impl GenServer
def init({cfg, state}) do
state = state || on_init(cfg)
{:ok, {cfg, state}}
end
@impl GenServer
def handle_call(:cfg, _from, {cfg, state}) do
{:reply, cfg, {cfg, state}}
end
@impl GenServer
def handle_call(:state, _from, {cfg, state}) do
{:reply, state, {cfg, state}}
end
@impl GenServer
def handle_cast({:state, update}, {cfg, state}) do
{:noreply, {cfg, apply(update, [state])}}
end
end
end
end

View File

@@ -1,4 +1,4 @@
defmodule Omnibot.Plugin.Supervisor do
defmodule Omnibot.Plugin do
@default_opts [include_base: true, opts: [strategy: :one_for_one]]
defmodule CfgState do
@@ -32,31 +32,44 @@ defmodule Omnibot.Plugin.Supervisor do
end
def cfg() do
Omnibot.Plugin.Supervisor.CfgState.cfg(__MODULE__.CfgState)
Omnibot.Plugin.CfgState.cfg(__MODULE__.CfgState)
end
def state() do
Omnibot.Plugin.Supervisor.CfgState.state(__MODULE__.CfgState)
Omnibot.Plugin.CfgState.state(__MODULE__.CfgState)
end
def update_state(fun) do
Omnibot.Plugin.Supervisor.CfgState.update_state(__MODULE__.CfgState, fun)
Omnibot.Plugin.CfgState.update_state(__MODULE__.CfgState, fun)
end
@impl Omnibot.Plugin.Base
def handle_msg(irc, msg) do
GenServer.cast(__MODULE__, {:handle_msg, irc, msg})
end
@impl Omnibot.Plugin
def children(_cfg, _state), do: []
## Server callbacks
@impl Supervisor
def init({cfg, state}) do
base_children = [
{Omnibot.Plugin.Supervisor.CfgState, cfg: cfg, state: state, name: __MODULE__.CfgState},
{Omnibot.Plugin.CfgState, cfg: cfg, state: state, name: __MODULE__.CfgState},
]
children =
(if unquote(opts[:include_base]), do: base_children, else: []) ++ children(cfg, state)
Supervisor.init(children, unquote(opts[:opts]))
end
@behaviour Omnibot.Plugin.Supervisor
def handle_cast({:handle_msg, irc, msg}, state) do
on_msg(irc, msg)
{:noreply, state}
end
@behaviour Omnibot.Plugin
defoverridable Omnibot.Plugin
end
end