axelson

axelson

Scenic Core Team

Has anyone written a credo rule to only allow scheduling with time interval tuples?

Has anyone written a credo rule that will forbid calling schedule_in with a raw number?

i.e. instead of:

new(arguments, schedule_in: 60 * 1_000)

I want only this to be allowed:

new(arguments, schedule_in: {60, :hours})

Most Liked

sodapopcan

sodapopcan

Ok, here’s my pass.

This is assuming you want to pass the tuple syntax so that is what it checks for and anything else is considered and error.

It defaults to looking for modules with Worker suffixes though you can also specify a custom suffix, a namespace, or both. So use like so in your credo config:

{MyChecks, worker_suffix: "Job"}

This does NOT handle the case of importing new/2 because that’s just kinda evil :sweat_smile: Happy to add it, though.

If you specify both :worker_suffix and :worker_namespace they both must match. IE you could (for some reason) have MyApp.Workers.AWorkerThisIsNot… though not sure why you would want to do that.

EDIT: Oops left some temp stuff in for reporting… sorta fixed it, sorta (ie, "Some trigger")

defmodule MyChecks.ObanNew do
  use Credo.Check

  @opts [:worker_suffix, :worker_namespace]

  @impl true
  def run(source_file, params \\ []) do
    params =
      if not Enum.any?(@opts, &Keyword.has_key?(params, &1)) do
        Keyword.merge(params, worker_suffix: "Worker")
      else
        params
      end

    issue_meta = IssueMeta.for(source_file, params)

    Credo.Code.prewalk(source_file, &traverse(&1, &2, issue_meta, params))
  end

  defp traverse(
         {{:., _, [{_, _, aliases}, :new]}, meta, [_, opts]} = ast,
         issues,
         issue_meta,
         params
       ) do
    if worker?(aliases, params) do
      case opts[:schedule_in] do
        nil -> {ast, issues}
        {_, _} -> {ast, issues}
        _ -> {ast, issues ++ [issue_for("Some trigger", meta[:line], issue_meta)]}
      end
    else
      {ast, issues}
    end
  end

  defp traverse(ast, issues, _issue_meta, _params) do
    {ast, issues}
  end

  defp worker?(pieces, params) do
    pieces = Enum.map(pieces, &Atom.to_string/1)

    if params[:worker_namespace] != nil and params[:worker_suffix] != nil do
      Enum.any?(pieces, &(&1 == params[:worker_namespace])) &&
        Enum.any?(pieces, &String.ends_with?(&1, params[:worker_suffix]))
    else
      Enum.any?(pieces, fn piece ->
        cond do
          params[:worker_namespace] != nil ->
            piece == params[:worker_namespace]

          params[:worker_suffix] != nil ->
            String.ends_with?(piece, params[:worker_suffix])

          true ->
            false
        end
      end)
    end
  end

  defp issue_for(trigger, line_no, issue_meta) do
    format_issue(
      issue_meta,
      message: "Please use tuple syntax for `shedule_in` option",
      trigger: trigger,
      line_no: line_no
    )
  end
end

and tests:

defmodule MyChecks.ObanNewTest do
  use Credo.Test.Case

  alias MyChecks.ObanNew

  test "schedule_in must use tuple syntax" do
    """
    defmodule CredoSampleModule do
      def foo do
        MyApp.FooWorker.new("something", schedule_in: {60, :hours})
      end
    end
    """
    |> to_source_file()
    |> run_check(ObanNew)
    |> refute_issues()
  end

  test "schedule_in errors if using integer" do
    """
    defmodule CredoSampleModule do
      def foo do
        MyApp.FooWorker.new("something", schedule_in: 400 * 1000)
      end
    end
    """
    |> to_source_file()
    |> run_check(ObanNew)
    |> assert_issue()
  end

  test "ignores modules not ending with `Worker`" do
    """
    defmodule CredoSampleModule do
      def foo do
        NonWorkerModule.new("something", schedule_in: 400 * 1000)
      end
    end
    """
    |> to_source_file()
    |> run_check(ObanNew)
    |> refute_issues()
  end

  test "allows specifying custom suffix" do
    """
    defmodule CredoSampleModule do
      def foo do
        MyJob.new("something", schedule_in: 400 * 1000)
      end
    end
    """
    |> to_source_file()
    |> run_check(ObanNew, worker_suffix: "Job")
    |> assert_issue()
  end

  test "allow specifying a namespace" do
    """
    defmodule CredoSampleModule do
      def foo do
        MyJobs.Doit.new("something", schedule_in: 400 * 1000)
      end
    end
    """
    |> to_source_file()
    |> run_check(ObanNew, worker_namespace: "MyJobs")
    |> assert_issue()
  end

  test "allow specifying namespace and suffix" do
    """
    defmodule CredoSampleModule do
      def foo do
        MyJobs.SomeWorker.new("something", schedule_in: 400 * 1000)
      end
    end
    """
    |> to_source_file()
    |> run_check(ObanNew, worker_namespace: "MyJobs", worker_suffix: "Worker")
    |> assert_issue()

    """
    defmodule CredoSampleModule do
      def foo do
        MyJobs.Unrelated.new("something", schedule_in: 400 * 1000)
      end
    end
    """
    |> to_source_file()
    |> run_check(ObanNew, worker_namespace: "MyJobs", worker_suffix: "Worker")
    |> refute_issues()

    """
    defmodule CredoSampleModule do
      def foo do
        NonObanModuleEndingInWorker.new("something", schedule_in: 400 * 1000)
      end
    end
    """
    |> to_source_file()
    |> run_check(ObanNew, worker_namespace: "MyJobs", worker_suffix: "Worker")
    |> refute_issues()
  end
end
sodapopcan

sodapopcan

Well that’s no fun :frowning:

But if you’re going to keep going… this solution is Good Enough :tm: but not perfect as it checks any new function.

Ideally you want to ensure that new belongs to a worker. One idea is to include an option to specify a worker namespace or suffix, for example {MyCheck.ObanSchdeduleIn, namespace: [:MyApp, :Workers]}.

axelson

axelson

Scenic Core Team

I haven’t sorted it out yet. I’ll give @meraj_enigma’s version a try. And I wonder how we could construct a bunch of test cases to ensure that there aren’t any false positives. Maybe we could run it against a bunch of projects from GitHub/hex.pm with some that do and some that don’t use Oban.

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement