Compare commits

...

4 Commits

Author SHA1 Message Date
Adrian Gruntkowski a7603c9e49
Improve import procedure to ensure no time range overlaps (#3970)
* Always scope import ID by site as well

* Do not schedule new import job if there are any site imports in progress

* Disable import buttons when any import is in progress

* Simplify `schedule_job/4` (h/t @RobertJoonas)
3 years ago
Adrian Gruntkowski cffff0340c
Handle Google API timeouts gracefully during imports (#3975) 3 years ago
Adrian Gruntkowski 33eed9d7db
Delete imports which have no stats (#3972) 3 years ago
Marko Saric e5b7f1afd0
Changing the copy of the locked screen (#3967)
changing the copy here as I think that in some situations the "we're still counting stats" message is now shown even to those dashboards where we've stopped counting stats so best to avoid that
3 years ago

@ -72,35 +72,36 @@ defmodule Plausible.DataMigration.SiteImports do
end_date = imported_stats_end_date(site.id, import_ids)
end_date =
if !end_date do
IO.puts(
"Site import #{site_import.id} (site ID #{site.id}) does not have any recorded stats. Setting end date to minimum."
)
if !end_date do
IO.puts(
"Site import #{site_import.id} (site ID #{site.id}) does not have any recorded stats. Removing it."
)
Date.add(site_import.start_date, 2)
else
end_date
end
end_date =
if Date.compare(end_date, site_import.end_date) in [:lt, :eq] do
end_date
else
IO.puts(
"Site import #{site_import.id} (site ID #{site.id}) computed end date is later than the current one. Skipping."
)
site_import.end_date
if site_import.legacy do
clear_imported_data(site, dry_run?)
end
site_import
|> Ecto.Changeset.change(end_date: end_date)
|> update!(dry_run?)
IO.puts(
"End date of site import #{site_import.id} (site ID #{site.id}) adjusted to #{end_date}"
)
delete!(site_import, dry_run?)
else
end_date =
if Date.compare(end_date, site_import.end_date) in [:lt, :eq] do
end_date
else
IO.puts(
"Site import #{site_import.id} (site ID #{site.id}) computed end date is later than the current one. Skipping."
)
site_import.end_date
end
site_import
|> Ecto.Changeset.change(end_date: end_date)
|> update!(dry_run?)
IO.puts(
"End date of site import #{site_import.id} (site ID #{site.id}) adjusted to #{end_date}"
)
end
end
IO.puts("Done processing site ID #{site.id}")
@ -149,6 +150,14 @@ defmodule Plausible.DataMigration.SiteImports do
end
end
defp clear_imported_data(site, false = _dry_run?) do
Repo.update_all(from(s in Site, where: s.id == ^site.id), set: [imported_data: nil])
end
defp clear_imported_data(site, true = _dry_run?) do
%{site | imported_data: nil}
end
defp update!(changeset, false = _dry_run?) do
Repo.update!(changeset)
end
@ -161,6 +170,14 @@ defmodule Plausible.DataMigration.SiteImports do
end
end
defp delete!(entity, false = _dry_run?) do
Repo.delete!(entity)
end
defp delete!(entity, true = _dry_run?) do
entity
end
defp max_date_query(schema, site_id, import_ids) do
from(q in schema,
where: q.site_id == ^site_id,

@ -140,7 +140,10 @@ defmodule Plausible.Google.GA4.HTTP do
{:error, %HTTPClient.Non200Error{} = error} when error.reason.status in [401, 403] ->
{:error, :authentication_failed}
{:error, %HTTPClient.Non200Error{} = error} ->
{:error, %{reason: :timeout}} ->
{:error, :timeout}
{:error, error} ->
Sentry.capture_message("Error listing GA4 accounts for user", extra: %{error: error})
{:error, :unknown}
end
@ -161,7 +164,10 @@ defmodule Plausible.Google.GA4.HTTP do
{:error, %HTTPClient.Non200Error{} = error} when error.reason.status in [404] ->
{:error, :not_found}
{:error, %HTTPClient.Non200Error{} = error} ->
{:error, %{reason: :timeout}} ->
{:error, :timeout}
{:error, error} ->
Sentry.capture_message("Error retrieving GA4 property #{property}",
extra: %{error: error}
)
@ -221,7 +227,10 @@ defmodule Plausible.Google.GA4.HTTP do
{:error, %HTTPClient.Non200Error{} = error} when error.reason.status in [401, 403] ->
{:error, :authentication_failed}
{:error, %HTTPClient.Non200Error{} = error} ->
{:error, %{reason: :timeout}} ->
{:error, :timeout}
{:error, error} ->
Sentry.capture_message("Error retrieving GA4 #{edge} date",
extra: %{error: error}
)

@ -108,7 +108,10 @@ defmodule Plausible.Google.UA.HTTP do
{:error, %HTTPClient.Non200Error{} = error} when error.reason.status in [401, 403] ->
{:error, :authentication_failed}
{:error, %HTTPClient.Non200Error{} = error} ->
{:error, %{reason: :timeout}} ->
{:error, :timeout}
{:error, error} ->
Sentry.capture_message("Error listing UA views for user", extra: %{error: error})
{:error, :unknown}
end
@ -170,7 +173,10 @@ defmodule Plausible.Google.UA.HTTP do
{:error, %HTTPClient.Non200Error{} = error} when error.reason.status in [401, 403] ->
{:error, :authentication_failed}
{:error, %HTTPClient.Non200Error{} = error} ->
{:error, %{reason: :timeout}} ->
{:error, :timeout}
{:error, error} ->
Sentry.capture_message("Error retrieving UA #{edge} date",
extra: %{error: error}
)

@ -62,9 +62,9 @@ defmodule Plausible.Imported do
}
end
@spec get_import(non_neg_integer()) :: SiteImport.t() | nil
def get_import(import_id) do
Repo.get(SiteImport, import_id)
@spec get_import(Site.t(), non_neg_integer()) :: SiteImport.t() | nil
def get_import(site, import_id) do
Repo.get_by(SiteImport, id: import_id, site_id: site.id)
end
defdelegate listen(), to: Imported.Importer
@ -83,6 +83,16 @@ defmodule Plausible.Imported do
end
end
@spec other_imports_in_progress?(SiteImport.t()) :: boolean()
def other_imports_in_progress?(site_import) do
Repo.exists?(
from(i in SiteImport,
where: i.site_id == ^site_import.site_id and i.id != ^site_import.id,
where: i.status in ^[SiteImport.pending(), SiteImport.importing()]
)
)
end
defp maybe_filter_by_status(query, nil), do: query
defp maybe_filter_by_status(query, status) do

@ -91,6 +91,7 @@ defmodule Plausible.Imported.Importer do
like LiveView, where notifications can be listened for via `handle_info/2`.
"""
alias Plausible.Imported
alias Plausible.Imported.SiteImport
alias Plausible.Repo
@ -98,7 +99,7 @@ defmodule Plausible.Imported.Importer do
@callback label() :: String.t()
@callback email_template() :: String.t()
@callback parse_args(map()) :: Keyword.t()
@callback import_data(Plausible.Imported.SiteImport.t(), Keyword.t()) :: :ok | {:error, any()}
@callback import_data(SiteImport.t(), Keyword.t()) :: :ok | {:error, any()}
@callback before_start(SiteImport.t()) :: :ok | {:ok, map()} | {:error, any()}
@callback on_success(SiteImport.t(), map()) :: :ok
@callback on_failure(SiteImport.t()) :: :ok
@ -108,7 +109,7 @@ defmodule Plausible.Imported.Importer do
@behaviour Plausible.Imported.Importer
@spec new_import(Plausible.Site.t(), Plausible.Auth.User.t(), Keyword.t()) ::
{:ok, Oban.Job.t()} | {:error, Ecto.Changeset.t()}
{:ok, Oban.Job.t()} | {:error, Ecto.Changeset.t() | :import_in_progress}
def new_import(site, user, opts) do
Plausible.Imported.Importer.new_import(name(), site, user, opts, &before_start/1)
end
@ -222,11 +223,15 @@ defmodule Plausible.Imported.Importer do
:ok = listen()
end
opts
|> Keyword.put(:import_id, site_import.id)
|> Map.new()
|> Plausible.Workers.ImportAnalytics.new()
|> Oban.insert()
if not Imported.other_imports_in_progress?(site_import) do
opts
|> Keyword.put(:import_id, site_import.id)
|> Map.new()
|> Plausible.Workers.ImportAnalytics.new()
|> Oban.insert()
else
{:error, :import_in_progress}
end
end
defp mark_complete(site_import, extra_data, on_success_fun) do

@ -96,6 +96,14 @@ defmodule PlausibleWeb.GoogleAnalyticsController do
)
|> redirect(external: redirect_route)
{:error, :timeout} ->
conn
|> put_flash(
:error,
"Google Analytics API has timed out. Please try again."
)
|> redirect(external: redirect_route)
{:error, _any} ->
conn
|> put_flash(
@ -168,6 +176,14 @@ defmodule PlausibleWeb.GoogleAnalyticsController do
)
|> redirect(external: redirect_route)
{:error, :timeout} ->
conn
|> put_flash(
:error,
"Google Analytics API has timed out. Please try again."
)
|> redirect(external: redirect_route)
{:error, _any} ->
conn
|> put_flash(
@ -225,6 +241,14 @@ defmodule PlausibleWeb.GoogleAnalyticsController do
)
|> redirect(external: redirect_route)
{:error, :timeout} ->
conn
|> put_flash(
:error,
"Google Analytics API has timed out. Please try again."
)
|> redirect(external: redirect_route)
{:error, :not_found} ->
conn
|> put_flash(
@ -265,48 +289,48 @@ defmodule PlausibleWeb.GoogleAnalyticsController do
Routes.site_path(conn, :settings_imports_exports, site.domain)
end
case Imported.check_dates(site, start_date, end_date) do
{:ok, start_date, end_date} ->
if Google.API.property?(property_or_view) do
{:ok, _} =
Imported.GoogleAnalytics4.new_import(
site,
current_user,
property: property_or_view,
label: property_or_view,
start_date: start_date,
end_date: end_date,
access_token: access_token,
refresh_token: refresh_token,
token_expires_at: expires_at
)
else
{:ok, _} =
Imported.UniversalAnalytics.new_import(
site,
current_user,
view_id: property_or_view,
label: property_or_view,
start_date: start_date,
end_date: end_date,
access_token: access_token,
refresh_token: refresh_token,
token_expires_at: expires_at,
legacy: legacy == "true"
)
end
import_opts = [
label: property_or_view,
start_date: start_date,
end_date: end_date,
access_token: access_token,
refresh_token: refresh_token,
token_expires_at: expires_at,
legacy: legacy == "true"
]
with {:ok, start_date, end_date} <- Imported.check_dates(site, start_date, end_date),
import_opts = [{:start_date, start_date}, {:end_date, end_date} | import_opts],
{:ok, _} <- schedule_job(site, current_user, property_or_view, import_opts) do
conn
|> put_flash(:success, "Import scheduled. An email will be sent when it completes.")
|> redirect(external: redirect_route)
else
{:error, :no_time_window} ->
conn
|> put_flash(:success, "Import scheduled. An email will be sent when it completes.")
|> put_flash(
:error,
"Import failed. No data could be imported because date range overlaps with existing data."
)
|> redirect(external: redirect_route)
{:error, :no_time_window} ->
{:error, :import_in_progress} ->
conn
|> put_flash(
:error,
"Import failed. No data could be imported because date range overlaps with existing data."
"There's another import still in progress. Please wait until it's completed or cancel it before starting a new one."
)
|> redirect(external: redirect_route)
end
end
defp schedule_job(site, current_user, property_or_view, opts) do
if Google.API.property?(property_or_view) do
opts = Keyword.put(opts, :property, property_or_view)
Imported.GoogleAnalytics4.new_import(site, current_user, opts)
else
opts = Keyword.put(opts, :view_id, property_or_view)
Imported.UniversalAnalytics.new_import(site, current_user, opts)
end
end
end

@ -652,7 +652,7 @@ defmodule PlausibleWeb.SiteController do
|> Plausible.Site.remove_imported_data()
|> Repo.update!()
site_import = Plausible.Imported.get_import(import_id) ->
site_import = Plausible.Imported.get_import(site, import_id) ->
Oban.cancel_all_jobs(
from(j in Oban.Job,
where:

@ -42,7 +42,39 @@ defmodule PlausibleWeb.Live.ImportsExportsSettings do
end
def render(assigns) do
import_in_progress? =
Enum.any?(
assigns.site_imports,
&(&1.live_status in [SiteImport.pending(), SiteImport.importing()])
)
assigns = assign(assigns, :import_in_progress?, import_in_progress?)
~H"""
<div class="mt-5 flex gap-x-4">
<.button_link
class="w-36 h-20"
theme="bright"
disabled={@import_in_progress?}
href={Plausible.Google.API.import_authorize_url(@site.id, "import", legacy: false)}
>
<img src="/images/icon/google_analytics_logo.svg" alt="Google Analytics import" />
</.button_link>
<.button_link
class="w-36 h-20"
theme="bright"
disabled={@import_in_progress?}
href={"/#{URI.encode_www_form(@site.domain)}/settings/import"}
>
<img class="h-16" src="/images/icon/csv_logo.svg" alt="New CSV import" />
</.button_link>
</div>
<p :if={@import_in_progress?} class="mt-4 text-red-400 text-sm">
No new imports can be started until the import in progress is completed or cancelled.
</p>
<header class="relative border-b border-gray-200 pb-4">
<h3 class="mt-8 text-md leading-6 font-medium text-gray-900 dark:text-gray-100">
Existing Imports

@ -10,24 +10,6 @@
<PlausibleWeb.Components.Generic.docs_info slug="google-analytics-import" />
</header>
<div class="mt-5 flex gap-x-4">
<PlausibleWeb.Components.Generic.button_link
class="w-36 h-20"
theme="bright"
href={Plausible.Google.API.import_authorize_url(@site.id, "import", legacy: false)}
>
<img src="/images/icon/google_analytics_logo.svg" alt="Google Analytics import" />
</PlausibleWeb.Components.Generic.button_link>
<PlausibleWeb.Components.Generic.button_link
class="w-36 h-20"
theme="bright"
href={"/#{URI.encode_www_form(@site.domain)}/settings/import"}
>
<img class="h-16" src="/images/icon/csv_logo.svg" alt="New CSV import" />
</PlausibleWeb.Components.Generic.button_link>
</div>
<%= live_render(@conn, PlausibleWeb.Live.ImportsExportsSettings,
session: %{"domain" => @site.domain}
) %>

@ -28,11 +28,11 @@
Please subscribe to the appropriate tier with the link below to access the stats again.
</p>
<p class="mt-6 text-sm text-gray-500">
You can check the
You can configure your
<.styled_link href={Routes.site_path(@conn, :settings_general, @site.domain)}>
site settings
</.styled_link>
and we're still counting the stats but your access to the dashboard is restricted.
but your access to the dashboard is restricted.
</p>
</div>
<div class="mt-6 w-full text-center">

@ -91,6 +91,22 @@ defmodule Plausible.DataMigration.SiteImportsTest do
assert site_import.source == :universal_analytics
end
test "removes site import when there are no stats" do
site =
insert(:site)
|> Site.start_import(~D[2021-01-02], ~D[2020-02-02], "Google Analytics", "ok")
|> Repo.update!()
_another_site_import = insert(:site_import, site: site)
assert capture_io(fn ->
assert :ok = SiteImports.run(dry_run?: false)
end) =~ "Processing 1 site"
site = Repo.reload!(site)
assert [] = Imported.list_all_imports(site)
end
test "leaves site and imports unchanged if everything fits" do
site =
insert(:site)

@ -43,7 +43,7 @@ defmodule Plausible.Imported.GoogleAnalytics4Test do
token_expires_at: DateTime.to_iso8601(past)
)
site_import = Plausible.Imported.get_import(job.args.import_id)
site_import = Plausible.Imported.get_import(site, job.args.import_id)
assert site_import.label == "properties/123456"

@ -139,6 +139,38 @@ defmodule PlausibleWeb.GoogleAnalyticsControllerTest do
"We were unable to authenticate your Google Analytics account"
end
test "redirects to #{view} on timeout error with flash error (legacy: #{legacy})", %{
conn: conn,
site: site
} do
expect(
Plausible.HTTPClient.Mock,
:get,
fn _url, _opts ->
{:error, %Mint.TransportError{reason: :timeout}}
end
)
conn =
conn
|> get("/#{site.domain}/import/google-analytics/property-or-view", %{
"access_token" => "token",
"refresh_token" => "foo",
"expires_at" => "2022-09-22T20:01:37.112777",
"legacy" => unquote(legacy)
})
assert redirected_to(conn, 302) ==
PlausibleWeb.Router.Helpers.site_path(
conn,
unquote(view),
site.domain
)
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
"Google Analytics API has timed out."
end
test "redirects to #{view} on list retrival failure with flash error (legacy: #{legacy})",
%{
conn: conn,
@ -460,6 +492,40 @@ defmodule PlausibleWeb.GoogleAnalyticsControllerTest do
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
"Google Analytics authentication seems to have expired."
end
test "redirects to #{view} on timeout with flash error (legacy: #{legacy})",
%{
conn: conn,
site: site
} do
expect(
Plausible.HTTPClient.Mock,
:post,
fn _url, _opts, _params ->
{:error, %Mint.TransportError{reason: :timeout}}
end
)
conn =
conn
|> post("/#{site.domain}/import/google-analytics/property-or-view", %{
"property_or_view" => "properties/428685906",
"access_token" => "token",
"refresh_token" => "foo",
"expires_at" => "2022-09-22T20:01:37.112777",
"legacy" => unquote(legacy)
})
assert redirected_to(conn, 302) ==
PlausibleWeb.Router.Helpers.site_path(
conn,
unquote(view),
site.domain
)
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
"Google Analytics API has timed out."
end
end
end
@ -624,6 +690,42 @@ defmodule PlausibleWeb.GoogleAnalyticsControllerTest do
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
"Google Analytics authentication seems to have expired."
end
test "redirects to #{view} on timeout with flash error (legacy: #{legacy})",
%{
conn: conn,
site: site
} do
expect(
Plausible.HTTPClient.Mock,
:get,
fn _url, _params ->
{:error, %Mint.TransportError{reason: :timeout}}
end
)
conn =
conn
|> get("/#{site.domain}/import/google-analytics/confirm", %{
"property_or_view" => "properties/428685906",
"access_token" => "token",
"refresh_token" => "foo",
"expires_at" => "2022-09-22T20:01:37.112777",
"start_date" => "2024-02-22",
"end_date" => "2024-02-26",
"legacy" => unquote(legacy)
})
assert redirected_to(conn, 302) ==
PlausibleWeb.Router.Helpers.site_path(
conn,
unquote(view),
site.domain
)
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
"Google Analytics API has timed out."
end
end
end
@ -753,6 +855,46 @@ defmodule PlausibleWeb.GoogleAnalyticsControllerTest do
)
end
test "does not start another import when there's any other in progress for the same site", %{
conn: conn,
site: site,
user: user
} do
{:ok, job} =
Plausible.Imported.NoopImporter.new_import(site, user,
start_date: ~D[2020-01-02],
end_date: ~D[2021-10-11]
)
post(conn, "/#{site.domain}/settings/google-import", %{
"property_or_view" => "properties/123456",
"start_date" => "2018-03-01",
"end_date" => "2022-03-01",
"access_token" => "token",
"refresh_token" => "foo",
"expires_at" => "2022-09-22T20:01:37.112777",
"legacy" => "false"
})
conn =
post(conn, "/#{site.domain}/settings/google-import", %{
"property_or_view" => "123456",
"start_date" => "2018-03-01",
"end_date" => "2022-03-01",
"access_token" => "token",
"refresh_token" => "foo",
"expires_at" => "2022-09-22T20:01:37.112777",
"legacy" => "true"
})
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
"There's another import still in progress."
assert [%{id: import_id, legacy: false}] = Plausible.Imported.list_all_imports(site)
assert job.args.import_id == import_id
end
for {legacy, view} <- [{"true", :settings_integrations}, {"false", :settings_imports_exports}] do
test "redirects to #{view} with no time window error flash error (legacy: #{legacy})", %{
conn: conn,

@ -680,6 +680,25 @@ defmodule PlausibleWeb.SiteControllerTest do
assert resp =~ "Google Analytics (123456)"
assert resp =~ "(98 page views)"
end
test "disables import buttons when there's import in progress", %{conn: conn, site: site} do
_site_import1 = insert(:site_import, site: site, status: SiteImport.completed())
_site_import2 = insert(:site_import, site: site, status: SiteImport.importing())
conn = get(conn, "/#{site.domain}/settings/imports-exports")
assert html_response(conn, 200) =~ "No new imports can be started"
end
test "enables import buttons when all imports are in completed or failed state", %{
conn: conn,
site: site
} do
_site_import1 = insert(:site_import, site: site, status: SiteImport.completed())
_site_import2 = insert(:site_import, site: site, status: SiteImport.failed())
conn = get(conn, "/#{site.domain}/settings/imports-exports")
refute html_response(conn, 200) =~ "No new imports can be started"
end
end
describe "GET /:website/settings/integrations for self-hosting" do

Loading…
Cancel
Save