ForgeCredoChecks.UnsupervisedSpawn (forge_credo_checks v0.7.0)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of high and works with any version of Elixir.

Explanation

Long-lived processes belong under a supervisor, not a raw spawn.

Why

spawn/1,3, spawn_link/1,3, spawn_monitor/1,3, and Process.spawn start a process with no supervisor: nothing restarts it after a crash, its start and shutdown ordering relative to the rest of the tree is undefined, and it is invisible to supervision-tree introspection. A crash becomes permanent absence rather than a restart.

Start fixed processes as supervisor children and runtime-created ones under a DynamicSupervisor. For fire-and-forget work use Task.Supervisor.start_child/2; for awaited work use Task.Supervisor.async_nolink/3.

Bad

spawn(fn -> do_work() end)
spawn_link(MyMod, :loop, [state])

Good

Task.Supervisor.start_child(MyApp.TaskSupervisor, fn -> do_work() end)
DynamicSupervisor.start_child(MyApp.Sup, {MyWorker, arg})

Configuration

excluded_paths is a list of patterns (regexes or substrings) matched against each file's path; a file that matches is skipped. Use it where a different convention legitimately applies, such as test files that create unsupervised processes on purpose (an orphan-reaping test cannot use a supervised process):

{ForgeCredoChecks.UnsupervisedSpawn, excluded_paths: [~r/_test\.exs$/]}

Check-Specific Parameters

There are no specific parameters for this check.

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.