Current section

Files

Jump to
rindle lib rindle workers purge_storage.ex
Raw

lib/rindle/workers/purge_storage.ex

defmodule Rindle.Workers.PurgeStorage do
@moduledoc false
use Oban.Worker, queue: :rindle_purge, max_attempts: 3
alias Rindle.Config
alias Rindle.Domain.{MediaAsset, MediaAttachment, MediaVariant}
import Ecto.Query
@impl Oban.Worker
def perform(%Oban.Job{args: %{"asset_id" => asset_id, "profile" => profile_name}}) do
repo = Config.repo()
profile_module = String.to_existing_atom(profile_name)
if attachments_exist?(repo, asset_id) do
:ok
else
purge_asset(repo, profile_module, asset_id)
end
end
defp attachments_exist?(repo, asset_id) do
repo.exists?(from attachment in MediaAttachment, where: attachment.asset_id == ^asset_id)
end
defp purge_asset(repo, profile_module, asset_id) do
# 1. Collect all storage keys to delete
# We load variants before potentially deleting the asset from DB
variant_keys =
repo.all(from v in MediaVariant, where: v.asset_id == ^asset_id, select: v.storage_key)
asset = repo.get(MediaAsset, asset_id)
source_key = if asset, do: asset.storage_key, else: nil
# 2. Execute deletions
Enum.each(variant_keys, fn key ->
if key, do: Rindle.delete(profile_module, key)
end)
if source_key do
Rindle.delete(profile_module, source_key)
end
# 3. Cleanup DB records if they still exist
# This ensures that the purge is complete.
if asset do
repo.delete!(asset)
end
:ok
end
end