| 1 |
|
defmodule Agent.Session do |
| 2 |
|
use GenServer |
| 3 |
|
|
| 4 |
|
import Agent.Spawn, only: [run: 3] |
| 5 |
|
import Agent.Ask, only: [reply: 3] |
| 6 |
|
import Agent.Log, only: [reply: 1] |
| 7 |
|
import GenServer, only: [start_link: 3, call: 3, cast: 2] |
| 8 |
|
import Keyword, only: [fetch!: 2, get: 3] |
| 9 |
|
import Map, only: [put: 3] |
| 10 |
|
import Utils.Normalize, only: [name: 1] |
| 11 |
|
import System, only: [get_env: 1] |
| 12 |
|
|
| 13 |
|
def start_link(opts) do |
| 14 |
:-( |
folder = fetch!(opts, :folder) |
| 15 |
:-( |
normalized = name(fetch!(opts, :name)) |
| 16 |
:-( |
via = via(normalized, folder) |
| 17 |
:-( |
start_link(__MODULE__, opts, name: via) |
| 18 |
|
end |
| 19 |
|
|
| 20 |
|
defp via(normalized, folder) do |
| 21 |
:-( |
metadata = %{kind: :headless, folder: folder} |
| 22 |
:-( |
{:via, Registry, {ElitaRegistry, normalized, metadata}} |
| 23 |
|
end |
| 24 |
|
|
| 25 |
:-( |
def ask(pid, message), do: call(pid, {:ask, message}, :infinity) |
| 26 |
:-( |
def forward(pid, message), do: cast(pid, {:cast, message}) |
| 27 |
:-( |
def fetch(pid), do: call(pid, :fetch, :infinity) |
| 28 |
|
|
| 29 |
|
@impl true |
| 30 |
:-( |
def init(opts) do |
| 31 |
|
{:ok, state(opts)} |
| 32 |
|
end |
| 33 |
|
|
| 34 |
|
defp state(opts) do |
| 35 |
:-( |
base(opts) |> setup() |> merge(opts) |
| 36 |
|
end |
| 37 |
|
|
| 38 |
:-( |
defp base(opts), do: %{name: fetch!(opts, :name), folder: fetch!(opts, :folder)} |
| 39 |
|
|
| 40 |
:-( |
defp setup(state), do: state |> put(:tape, tape()) |
| 41 |
|
|
| 42 |
|
defp merge(state, opts) do |
| 43 |
|
state |
| 44 |
|
|> put(:self, get(opts, :self, nil)) |
| 45 |
:-( |
|> put(:runner, get(opts, :runner, &run/3)) |
| 46 |
:-( |
|> put(:skip_logs, get(opts, :skip_logs, false)) |
| 47 |
|
end |
| 48 |
|
|
| 49 |
:-( |
defp tape, do: get_env("TAPE") |
| 50 |
|
|
| 51 |
|
@impl true |
| 52 |
|
def handle_call({:ask, message}, _from, state) do |
| 53 |
:-( |
body = %{messages: [%{content: message}]} |
| 54 |
:-( |
response = process(message, state, body) |
| 55 |
:-( |
{:reply, {:ok, response}, state} |
| 56 |
|
end |
| 57 |
|
|
| 58 |
|
@impl true |
| 59 |
|
def handle_call({:act, message}, _from, state) do |
| 60 |
:-( |
response = state.runner.(message, state.folder, state.self) |
| 61 |
:-( |
{:reply, response, state} |
| 62 |
|
end |
| 63 |
|
|
| 64 |
|
@impl true |
| 65 |
|
def handle_call(:fetch, _from, state) do |
| 66 |
:-( |
{:reply, state, state} |
| 67 |
|
end |
| 68 |
|
|
| 69 |
|
defp process("log", state, _body) do |
| 70 |
:-( |
reply(state.name) |
| 71 |
|
end |
| 72 |
|
|
| 73 |
|
defp process(message, state, body) do |
| 74 |
:-( |
reply(message, body, state) |
| 75 |
|
end |
| 76 |
|
|
| 77 |
|
@impl true |
| 78 |
:-( |
def handle_cast({:cast, message}, state) do |
| 79 |
:-( |
state.runner.(message, state.folder, state.self) |
| 80 |
|
{:noreply, state} |
| 81 |
|
end |
| 82 |
|
end |