|
| 1 | +defmodule Plausible.Verification.Checks do |
| 2 | + @moduledoc """ |
| 3 | + Checks that are performed during site verification. |
| 4 | + Each module defined in `@checks` implements the `Plausible.Verification.Check` behaviour. |
| 5 | + Checks are normally run asynchronously, except when synchronous execution is optionally required |
| 6 | + for tests. Slowdowns can be optionally added, the user doesn't benefit from running the checks too quickly. |
| 7 | +
|
| 8 | + In async execution, each check notifies the caller by sending a message to it. |
| 9 | + """ |
| 10 | + alias Plausible.Verification.Checks |
| 11 | + alias Plausible.Verification.State |
| 12 | + |
| 13 | + require Logger |
| 14 | + |
| 15 | + @checks [ |
| 16 | + Checks.FetchBody, |
| 17 | + Checks.CSP, |
| 18 | + Checks.ScanBody, |
| 19 | + Checks.Snippet, |
| 20 | + Checks.SnippetCacheBust, |
| 21 | + Checks.Installation |
| 22 | + ] |
| 23 | + |
| 24 | + def run(url, data_domain, opts \\ []) do |
| 25 | + checks = Keyword.get(opts, :checks, @checks) |
| 26 | + report_to = Keyword.get(opts, :report_to, self()) |
| 27 | + async? = Keyword.get(opts, :async?, true) |
| 28 | + slowdown = Keyword.get(opts, :slowdown, 500) |
| 29 | + |
| 30 | + if async? do |
| 31 | + Task.start_link(fn -> do_run(url, data_domain, checks, report_to, slowdown) end) |
| 32 | + else |
| 33 | + do_run(url, data_domain, checks, report_to, slowdown) |
| 34 | + end |
| 35 | + end |
| 36 | + |
| 37 | + def interpret_diagnostics(%State{} = state) do |
| 38 | + Plausible.Verification.Diagnostics.interpret(state.diagnostics, state.url) |
| 39 | + end |
| 40 | + |
| 41 | + defp do_run(url, data_domain, checks, report_to, slowdown) do |
| 42 | + init_state = %State{url: url, data_domain: data_domain, report_to: report_to} |
| 43 | + |
| 44 | + state = |
| 45 | + Enum.reduce( |
| 46 | + checks, |
| 47 | + init_state, |
| 48 | + fn check, state -> |
| 49 | + state |
| 50 | + |> notify_start(check, slowdown) |
| 51 | + |> check.perform_safe() |
| 52 | + end |
| 53 | + ) |
| 54 | + |
| 55 | + notify_verification_end(state, slowdown) |
| 56 | + end |
| 57 | + |
| 58 | + defp notify_start(state, check, slowdown) do |
| 59 | + if is_pid(state.report_to) do |
| 60 | + if is_integer(slowdown) and slowdown > 0, do: :timer.sleep(slowdown) |
| 61 | + send(state.report_to, {:verification_check_start, {check, state}}) |
| 62 | + end |
| 63 | + |
| 64 | + state |
| 65 | + end |
| 66 | + |
| 67 | + defp notify_verification_end(state, slowdown) do |
| 68 | + if is_pid(state.report_to) do |
| 69 | + if is_integer(slowdown) and slowdown > 0, do: :timer.sleep(slowdown) |
| 70 | + send(state.report_to, {:verification_end, state}) |
| 71 | + end |
| 72 | + |
| 73 | + state |
| 74 | + end |
| 75 | +end |
0 commit comments