Current section

Files

Jump to
step_flow lib step_flow controllers jobs.ex
Raw

lib/step_flow/controllers/jobs.ex

defmodule StepFlow.Controllers.Jobs do
@moduledoc false
alias StepFlow.Jobs.Job
alias StepFlow.Jobs.Status
@doc """
Returns a formatted message for AMQP orders.
## Examples
iex> get_message(job)
%{job_id: 123, parameters: [{id: "input", type: "string", value: "/path/to/input"}]}
"""
def get_message(%Job{} = job) do
%{
job_id: job.id,
parameters: job.parameters
}
end
@doc """
Returns the last updated status of a list of status.
Sometimes a processing status can be consumed concurrently with an error message
putting the last job status as processing even though the job should be considered
as in error. To deal with that, we do not naively sort with the inserted_at field.
"""
def get_last_status(status) when is_list(status) do
sorted_status =
status
|> Enum.sort(fn state_1, state_2 ->
case NaiveDateTime.compare(state_1.inserted_at, state_2.inserted_at) do
:lt -> false
:gt -> true
:eq -> state_1.id > state_2.id
end
end)
up_to_last_retry_status =
case Enum.find_index(sorted_status, fn state -> state.state == :retrying end) do
nil ->
sorted_status
index ->
sorted_status
|> Enum.slice(0..index)
end
case Enum.find(up_to_last_retry_status, nil, fn state ->
state.state == :completed or state.state == :error
end) do
nil -> up_to_last_retry_status |> List.first()
state -> state
end
end
def get_last_status(%Status{} = status), do: status
def get_last_status(_status), do: nil
@doc """
Returns the last status id of a list of status.
"""
def get_last_status_id(status) when is_list(status) do
status
|> Enum.sort(fn state_1, state_2 ->
state_1.id < state_2.id
end)
|> List.last()
end
def get_last_status_id(%Status{} = status), do: status
def get_last_status_id(_status), do: nil
@doc """
Returns action linked to status
"""
def get_action(status) do
case status.state do
:queued -> "create"
:ready_to_init -> "init_process"
:ready_to_start -> "start_process"
:update -> "update_process"
:stopped -> "delete"
:error -> "delete"
_ -> "none"
end
end
@doc """
Returns action linked to status as parameter
"""
def get_action_parameter(status) do
action = get_action(status)
[%{"id" => "action", "type" => "string", "value" => action}]
end
end