farmbot_os/farmbot_ext/lib/farmbot_ext/api/dirty_worker.ex

135 lines
4.0 KiB
Elixir
Raw Normal View History

2019-03-05 11:38:25 -07:00
defmodule FarmbotExt.API.DirtyWorker do
@moduledoc "Handles uploading/downloading of data from the API."
2019-03-05 11:38:25 -07:00
alias FarmbotCore.Asset.{Private, Repo}
alias FarmbotExt.{API, API.DirtyWorker}
import API.View, only: [render: 2]
require Logger
use GenServer
@timeout 10000
@doc false
def child_spec(module) when is_atom(module) do
%{
2019-03-05 11:38:25 -07:00
id: {DirtyWorker, module},
start: {__MODULE__, :start_link, [[module: module, timeout: @timeout]]},
type: :worker,
restart: :permanent,
shutdown: 500
}
end
@doc "Start an instance of a DirtyWorker"
def start_link(args) do
GenServer.start_link(__MODULE__, args)
end
@impl GenServer
def init(args) do
# Logger.disable(self())
module = Keyword.fetch!(args, :module)
timeout = Keyword.get(args, :timeout, @timeout)
{:ok, %{module: module, timeout: timeout}, timeout}
end
@impl GenServer
def handle_info(:timeout, %{module: module} = state) do
dirty = Private.list_dirty(module)
local = Private.list_local(module)
2019-04-18 10:32:34 -06:00
{:noreply, state, {:continue, Enum.uniq(dirty ++ local)}}
end
@impl GenServer
def handle_continue([], state) do
{:noreply, state, state.timeout}
end
def handle_continue([dirty | rest], %{module: module} = state) do
2019-04-18 10:32:34 -06:00
Logger.info("[#{module} #{dirty.local_id} #{inspect(self())}] Handling dirty data")
case http_request(dirty, state) do
# Valid data
{:ok, %{status: s, body: body}} when s > 199 and s < 300 ->
2019-04-18 10:32:34 -06:00
Logger.debug(
"[#{module} #{dirty.local_id} #{inspect(self())}] HTTP request complete: #{s} ok"
)
dirty |> module.changeset(body) |> handle_changeset(rest, state)
# Invalid data
{:ok, %{status: s, body: %{} = body}} when s > 399 and s < 500 ->
2019-04-18 10:32:34 -06:00
Logger.debug(
"[#{module} #{dirty.local_id} #{inspect(self())}] HTTP request complete: #{s} error+body"
)
changeset = module.changeset(dirty)
Enum.reduce(body, changeset, fn {key, val}, changeset ->
Ecto.Changeset.add_error(changeset, key, val)
end)
|> handle_changeset(rest, state)
# Invalid data, but the API didn't say why
{:ok, %{status: s, body: _body}} when s > 399 and s < 500 ->
2019-04-18 10:32:34 -06:00
Logger.debug(
"[#{module} #{dirty.local_id} #{inspect(self())}] HTTP request complete: #{s} error"
)
module.changeset(dirty)
|> Map.put(:valid?, false)
|> handle_changeset(rest, state)
# HTTP Error. (500, network error, timeout etc.)
2019-03-25 10:41:58 -06:00
error ->
2019-04-18 10:32:34 -06:00
Logger.error(
"[#{module} #{dirty.local_id} #{inspect(self())}] HTTP Error: #{state.module} #{
inspect(error)
}"
)
{:noreply, state, @timeout}
end
end
# If the changeset was valid, update the record.
def handle_changeset(%{valid?: true} = changeset, rest, state) do
Logger.info("Successfully synced: #{state.module}")
Repo.update!(changeset)
|> Private.mark_clean!()
{:noreply, state, {:continue, rest}}
end
# If the changeset was invalid, delete the record.
# TODO(Connor) - Update the dirty field here, upload to rollbar?
def handle_changeset(%{valid?: false, data: data} = changeset, rest, state) do
message =
2019-04-18 10:32:34 -06:00
Enum.map(changeset.errors, fn
{key, {msg, _meta}} when is_binary(key) -> "\t#{key}: #{msg}"
{key, msg} when is_binary(key) -> "\t#{key}: #{msg}"
end)
|> Enum.join("\n")
2019-04-18 10:32:34 -06:00
Logger.error("Failed to sync: #{state.module} \n #{message}")
_ = Repo.delete!(data)
{:noreply, state, {:continue, rest}}
end
defp http_request(%{id: nil} = dirty, state) do
2019-04-18 10:32:34 -06:00
Logger.debug("#{state.module} clean request (post)")
path = state.module.path()
data = render(state.module, dirty)
API.post(API.client(), path, data)
end
defp http_request(dirty, state) do
2019-04-18 10:32:34 -06:00
Logger.debug("#{state.module} dirty request (patch)")
2019-08-12 15:00:03 -06:00
# IO.inspect(dirty, label: "PATCH")
path = Path.join(state.module.path(), to_string(dirty.id))
data = render(state.module, dirty)
API.patch(API.client(), path, data)
end
end