Make sure a notification is not sent again within 12 hours

pull/453/head
Uku Taht 6 years ago
parent 54f70717c4
commit 11c9bdc328

@ -18,6 +18,11 @@ defmodule Plausible.Site.SpikeNotification do
|> unique_constraint(:site)
end
def was_sent(schema) do
schema
|> change(last_sent: NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second))
end
def add_recipient(report, recipient) do
report
|> change(recipients: report.recipients ++ [recipient])

@ -1,19 +1,20 @@
defmodule Plausible.Workers.SpikeNotifier do
use Plausible.Repo
alias Plausible.Stats.Query
alias Plausible.Site.SpikeNotification
use Oban.Worker, queue: :spike_notifications
@at_most_every "12 hours"
@impl Oban.Worker
def perform(_args, _job, clickhouse \\ Plausible.Stats.Clickhouse) do
notifications = Repo.all(
from sn in Plausible.Site.SpikeNotification,
from sn in SpikeNotification,
where: is_nil(sn.last_sent),
or_where: sn.last_sent < fragment("now() - INTERVAL ?", @at_most_every)
or_where: sn.last_sent < fragment("now() - INTERVAL ?", @at_most_every),
preload: :site
)
for notification <- notifications do
notification = Repo.preload(notification, :site)
query = Query.from(notification.site.timezone, %{"period" => "realtime"})
current_visitors = clickhouse.current_visitors(notification.site, query)
notify(notification, current_visitors)
@ -25,6 +26,9 @@ defmodule Plausible.Workers.SpikeNotifier do
for recipient <- notification.recipients do
send_notification(recipient, notification.site, current_visitors)
end
notification
|> SpikeNotification.was_sent()
|> Repo.update
end
end

@ -34,9 +34,16 @@ defmodule Plausible.Workers.SpikeNotifierTest do
test "does not notify anyone if a notification already went out in the last 12 hours" do
site = insert(:site)
insert(:spike_notification, site: site, threshold: 10, recipients: ["jerod@example.com", "uku@example.com"], last_sent: Timex.now())
insert(:spike_notification, site: site, threshold: 10, recipients: ["uku@example.com"])
clickhouse_stub = stub(Plausible.Stats.Clickhouse, :current_visitors, fn _site, _query -> 10 end)
SpikeNotifier.perform(nil, nil, clickhouse_stub)
assert_email_delivered_with(
subject: "Traffic spike on #{site.domain}",
to: [nil: "uku@example.com"]
)
SpikeNotifier.perform(nil, nil, clickhouse_stub)
assert_no_emails_delivered()

Loading…
Cancel
Save