lib/step_flow/metrics/job_instrumenter.ex

defmodule StepFlow.Metrics.JobInstrumenter do
  @moduledoc """
  Prometheus metrics instrumenter to call jobs metric collectors
  """
  use Prometheus.Metric
  alias StepFlow.Jobs

  def setup do
    Prometheus.Registry.register_collector(StepFlow.Metrics.JobsPendingCollector)

    Counter.declare(
      name: :step_flow_jobs_status_total,
      help: "Number of jobs by status.",
      labels: [:name, :status]
    )

    Gauge.declare(
      name: :step_flow_jobs_processing,
      help: "Number of jobs currently processing.",
      labels: [:name]
    )

    jobs_processing = Jobs.get_processing_jobs_by_type()

    Enum.each(jobs_processing, fn %{name: name, value: value} ->
      Gauge.set([name: :step_flow_jobs_processing, labels: [name]], value)
    end)
  end

  def inc(:step_flow_jobs_status_total, job_name, job_status) do
    if StepFlow.Configuration.metrics_enabled?() do
      case job_status do
        "created" ->
          Counter.inc(
            name: :step_flow_jobs_status_total,
            labels: [job_name, job_status]
          )

          Gauge.inc(
            name: :step_flow_jobs_processing,
            labels: [job_name]
          )

        "error" ->
          Counter.inc(
            name: :step_flow_jobs_status_total,
            labels: [job_name, job_status]
          )

          Gauge.dec(
            name: :step_flow_jobs_processing,
            labels: [job_name]
          )

        "stopped" ->
          Counter.inc(
            name: :step_flow_jobs_status_total,
            labels: [job_name, job_status]
          )

          Gauge.dec(
            name: :step_flow_jobs_processing,
            labels: [job_name]
          )

        "completed" ->
          Counter.inc(
            name: :step_flow_jobs_status_total,
            labels: [job_name, job_status]
          )

          Gauge.dec(
            name: :step_flow_jobs_processing,
            labels: [job_name]
          )

        _ ->
          :ok
      end
    end
  end
end