Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions lib/hexdocs/tmp_dir.ex
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ defmodule Hexdocs.TmpDir do
dir
end

def await_cleanup(pid) do
GenServer.call(__MODULE__, {:await_cleanup, pid}, 5000)
end

defp track(path) do
pid = self()
:ets.insert(@table, {pid, path})
Expand All @@ -42,7 +46,7 @@ defmodule Hexdocs.TmpDir do
def init(_opts) do
Process.flag(:trap_exit, true)
:ets.new(@table, [:named_table, :duplicate_bag, :public])
{:ok, %{monitors: MapSet.new()}}
{:ok, %{monitors: MapSet.new(), waiters: %{}}}
end

@impl true
Expand All @@ -55,10 +59,29 @@ defmodule Hexdocs.TmpDir do
end
end

def handle_call({:await_cleanup, pid}, from, state) do
if pid in state.monitors do
waiters = Map.update(state.waiters, pid, [from], &[from | &1])
{:noreply, %{state | waiters: waiters}}
else
{:reply, :ok, state}
end
end

@impl true
def handle_info({:DOWN, _ref, :process, pid, _reason}, state) do
cleanup_pid(pid)
{:noreply, %{state | monitors: MapSet.delete(state.monitors, pid)}}

for from <- Map.get(state.waiters, pid, []) do
GenServer.reply(from, :ok)
end

{:noreply,
%{
state
| monitors: MapSet.delete(state.monitors, pid),
waiters: Map.delete(state.waiters, pid)
}}
end

@impl true
Expand Down
15 changes: 3 additions & 12 deletions test/hexdocs/tmp_dir_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ defmodule Hexdocs.TmpDirTest do
send(test_pid, {:paths, file, dir})
end)

ref = Process.monitor(task_pid)
assert_receive {:paths, file, dir}
wait_for_cleanup(task_pid, ref)
Hexdocs.TmpDir.await_cleanup(task_pid)

refute File.exists?(file)
refute File.exists?(dir)
Expand All @@ -42,9 +41,8 @@ defmodule Hexdocs.TmpDirTest do
raise "crash"
end)

ref = Process.monitor(task_pid)
assert_receive {:paths, file, dir}
wait_for_cleanup(task_pid, ref)
Hexdocs.TmpDir.await_cleanup(task_pid)

refute File.exists?(file)
refute File.exists?(dir)
Expand All @@ -65,9 +63,8 @@ defmodule Hexdocs.TmpDirTest do
send(test_pid, {:paths, paths})
end)

ref = Process.monitor(task_pid)
assert_receive {:paths, paths}
wait_for_cleanup(task_pid, ref)
Hexdocs.TmpDir.await_cleanup(task_pid)

for {file, dir} <- paths do
refute File.exists?(file)
Expand All @@ -82,10 +79,4 @@ defmodule Hexdocs.TmpDirTest do
assert File.exists?(file)
assert File.dir?(dir)
end

defp wait_for_cleanup(task_pid, ref) do
assert_receive {:DOWN, ^ref, :process, ^task_pid, _}, 5000
# Sync with the GenServer to ensure the :DOWN cleanup has been processed
:sys.get_state(Hexdocs.TmpDir)
end
end
Loading