~ihabunek/triglav

ref: 5725e4080922882af88029a2e7dffdfc2f1b9911 triglav/lib/mix/tasks/triglav/validate_routes.ex -rw-r--r-- 3.5 KiB
5725e408Ivan Habunek Validate and regenerate derived data after update 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
defmodule Mix.Tasks.Triglav.ValidateRoutes do
  use Mix.Task

  alias Ecto.Multi
  alias Triglav.Repo
  alias Triglav.Schemas.Error
  alias Triglav.Schemas.ErrorHistory
  alias Triglav.Zet.Validator
  alias Triglav.Import.Geofabrik
  alias Triglav.Import.Zet

  import Ecto.Query
  require Logger

  @shortdoc "Validates routes and saves errors to the database, replaces any existing errors"

  @impl Mix.Task
  def run(_args) do
    Application.put_env(:triglav, :repo_only, true)
    {:ok, _} = Application.ensure_all_started(:triglav)

    Logger.info("Starting validation...")

    {time, _} = :timer.tc(&validate_routes/0)

    time_seconds = :erlang.float_to_binary(time / 1_000_000, decimals: 2)

    Logger.info("Done. Took #{time_seconds} seconds.")
  end

  @spec validate_routes() :: :ok | :error
  def validate_routes() do
    osm_state = Geofabrik.get_local_state()
    zet_feed_info = Zet.get_local_feed_info()

    case {osm_state, zet_feed_info} do
      {nil, _} ->
        Logger.warn("OSM data not loaded. Skipping validation.")

      {_, nil} ->
        Logger.warn("ZET data not loaded. Skipping validation.")

      _ ->
        do_validate(osm_state, zet_feed_info)
    end
  end

  defp do_validate(osm_state, zet_feed_info) do
    # Existing unresolved errors
    old_errors =
      from(e in Error, where: is_nil(e.resolved_at))
      |> Repo.all()
      |> Map.new(fn e -> {Error.signature(e), e} end)

    # Current set of errors from the validator
    new_errors =
      Validator.validate_all_routes()
      |> Map.new(fn e -> {Error.signature(e), e} end)

    old_sigs = old_errors |> Map.keys() |> MapSet.new()
    new_sigs = new_errors |> Map.keys() |> MapSet.new()

    to_create = MapSet.difference(new_sigs, old_sigs) |> Enum.map(&Map.get(new_errors, &1))
    to_resolve = MapSet.difference(old_sigs, new_sigs) |> Enum.map(&Map.get(old_errors, &1))

    old_count = map_size(old_errors)
    created_count = length(to_create)
    resolved_count = length(to_resolve)
    new_count = old_count + created_count - resolved_count

    now = DateTime.utc_now() |> DateTime.truncate(:second)
    multi = Multi.new()

    multi =
      to_resolve
      |> Enum.with_index()
      |> Enum.reduce(multi, fn {error, index}, multi ->
        changeset = Error.changeset(error, %{resolved_at: now})
        Multi.update(multi, {:resolve, index}, changeset)
      end)

    multi =
      to_create
      |> Enum.with_index()
      |> Enum.reduce(multi, fn {error, index}, multi ->
        Multi.insert(multi, {:create, index}, error)
      end)

    multi =
      Multi.run(multi, :history, fn _repo, _changes ->
        if created_count > 0 or resolved_count > 0 do
          %ErrorHistory{
            count: new_count,
            previous_count: old_count,
            created_count: created_count,
            resolved_count: resolved_count,
            zet_feed_version: zet_feed_info.version,
            osm_sequence_number: osm_state.sequence_number
          }
          |> Repo.insert()
        else
          {:ok, nil}
        end
      end)

    with {:ok, _} <- Repo.transaction(multi) do
      Logger.info("Routes validated")
      Logger.info("Created #{created_count} error(s)")
      Logger.info("Resolved #{resolved_count} error(s)")
      :ok
    else
      {:error, failed_operation, failed_value, _changes} ->
        Logger.error("Validation failed")
        Logger.error("Failed operation:\n#{inspect(failed_operation, pretty: true)}")
        Logger.error("Failed value:\n#{inspect(failed_value, pretty: true)}")
        :error
    end
  end
end