~ihabunek/triglav

ref: 7bdb88d4d88886e08c456f7ee012d7a343a73731 triglav/lib/mix/tasks/triglav/validate_routes.ex -rw-r--r-- 4.8 KiB
7bdb88d4Ivan Habunek Split validation from persisting errors 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
defmodule Mix.Tasks.Triglav.ValidateRoutes do
  use Mix.Task

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

  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)
    {opts, _} = OptionParser.parse!(args, strict: [dry_run: :boolean])

    {time, _} = :timer.tc(fn -> validate_routes(opts) end)
    time_seconds = :erlang.float_to_binary(time / 1_000_000, decimals: 2)
    Logger.info("Done. Took #{time_seconds} seconds.")
  end

  # TODO: extract code from mix task into own module

  defmodule ValidationResults do
    @type t :: %__MODULE__{
            osm_state: OsmState.t(),
            zet_feed_info: FeedInfo.t(),
            to_create: [Error.t()],
            to_resolve: [Error.t()],
            history: ErrorHistory.t()
          }

    defstruct [
      :osm_state,
      :zet_feed_info,
      :to_create,
      :to_resolve,
      :history
    ]
  end

  @spec validate_routes(Keyword.t()) :: :ok | :error
  def validate_routes(opts) do
    dry_run = Keyword.get(opts, :dry_run, false)

    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.")

      _ ->
        %{history: history} = results = do_validate(osm_state, zet_feed_info)

        Logger.info("Routes validated")
        Logger.info("Found #{history.created_count} new error(s)")
        Logger.info("Found #{history.resolved_count} resolved error(s)")

        if dry_run do
          Logger.info("Dry run. Not persisting errors.")
        else
          Logger.info("Persisting errors.")

          case persist_errors(results) do
            {:ok, _} ->
              Logger.info("Successfully persisted errors.")

            {:error, failed_operation, failed_value, _changes} ->
              Logger.error("Failed persisting errors")
              Logger.error("Failed operation:\n#{inspect(failed_operation, pretty: true)}")
              Logger.error("Failed value:\n#{inspect(failed_value, pretty: true)}")
          end
        end
    end
  end

  def 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()
    old_errors_map = Map.new(old_errors, fn e -> {Error.signature(e), e} end)

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

    old_sigs = old_errors_map |> Map.keys() |> MapSet.new()
    new_sigs = new_errors_map |> Map.keys() |> MapSet.new()

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

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

    history = %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
    }

    %ValidationResults{
      osm_state: osm_state,
      zet_feed_info: zet_feed_info,
      to_create: to_create,
      to_resolve: to_resolve,
      history: history
    }
  end

  def persist_errors(%ValidationResults{
        history: history,
        to_resolve: to_resolve,
        to_create: to_create
      }) do
    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 history.created_count > 0 or history.resolved_count > 0 do
          Repo.insert(history)
        else
          {:ok, nil}
        end
      end)

    Repo.transaction(multi)
  end
end