ammocpr/lib/ammoprices/scraping/scrape_job.ex
Graham McIntire ae7e117b23
Prune listings that disappear from retailer scrapes
When a product no longer appears in a successful scrape for its
retailer+caliber, mark it out of stock. After each scrape cycle, hard
delete any product whose last_seen_at is older than 30 days (snapshots
cascade via FK). A zero-result scrape leaves existing listings alone so
a parse failure or transient site glitch can't nuke the catalog.
2026-04-22 15:41:40 -05:00

66 lines
1.8 KiB
Elixir

defmodule Ammoprices.Scraping.ScrapeJob do
@moduledoc false
use Oban.Worker,
queue: :scraping,
max_attempts: 3,
unique: [period: :infinity, states: [:available, :scheduled, :executing, :retryable]]
alias Ammoprices.Catalog
alias Ammoprices.Scraping.Runner
@scrapers [
Ammoprices.Scraping.Retailers.LuckyGunner,
Ammoprices.Scraping.Retailers.SgAmmo,
Ammoprices.Scraping.Retailers.TargetSportsUsa,
Ammoprices.Scraping.Retailers.TrueShotAmmo,
Ammoprices.Scraping.Retailers.PalmettoStateArmory,
Ammoprices.Scraping.Retailers.BulkAmmo,
Ammoprices.Scraping.Retailers.Natchez
]
# Products not seen for this many days are hard-deleted after each scrape cycle.
@stale_product_days 30
@impl Oban.Worker
def perform(_job) do
calibers = Catalog.list_calibers()
for scraper <- @scrapers, caliber <- calibers do
scrape_delay()
Runner.run(scraper, caliber)
end
prune_stale_products()
Phoenix.PubSub.broadcast(Ammoprices.PubSub, "prices:updated", {:prices_updated, %{}})
schedule_next()
:ok
end
defp prune_stale_products do
cutoff = DateTime.add(DateTime.utc_now(), -@stale_product_days, :day)
Catalog.delete_stale_products(cutoff)
end
@doc false
def schedule_next do
{min, max} = Application.get_env(:ammoprices, :scrape_interval_seconds, {25_200, 43_200})
delay_seconds = Enum.random(min..max)
%{}
|> new(scheduled_at: DateTime.add(DateTime.utc_now(), delay_seconds, :second))
|> Oban.insert()
end
# Random delay between requests: 10-20 minutes in prod, 0 in test
defp scrape_delay do
{min, max} = Application.get_env(:ammoprices, :scrape_delay_ms, {600_000, 1_200_000})
delay = Enum.random(min..max)
if delay > 0 do
Process.sleep(delay)
end
end
end