[#582] Optimized federation retirement by reducing the number of SQL calls
[akkoma] / lib / pleroma / instances / instance.ex
1 defmodule Pleroma.Instances.Instance do
2 @moduledoc "Instance."
3
4 alias Pleroma.Instances
5 alias Pleroma.Instances.Instance
6
7 use Ecto.Schema
8
9 import Ecto.{Query, Changeset}
10
11 alias Pleroma.Repo
12
13 schema "instances" do
14 field(:host, :string)
15 field(:unreachable_since, :naive_datetime)
16
17 timestamps()
18 end
19
20 defdelegate host(url_or_host), to: Instances
21
22 def changeset(struct, params \\ %{}) do
23 struct
24 |> cast(params, [:host, :unreachable_since])
25 |> validate_required([:host])
26 |> unique_constraint(:host)
27 end
28
29 def filter_reachable([]), do: %{}
30
31 def filter_reachable(urls_or_hosts) when is_list(urls_or_hosts) do
32 hosts =
33 urls_or_hosts
34 |> Enum.map(&(&1 && host(&1)))
35 |> Enum.filter(&(to_string(&1) != ""))
36
37 unreachable_since_by_host =
38 Repo.all(
39 from(i in Instance,
40 where: i.host in ^hosts,
41 select: {i.host, i.unreachable_since}
42 )
43 )
44 |> Map.new(& &1)
45
46 reachability_datetime_threshold = Instances.reachability_datetime_threshold()
47
48 for entry <- Enum.filter(urls_or_hosts, &is_binary/1) do
49 host = host(entry)
50 unreachable_since = unreachable_since_by_host[host]
51
52 if !unreachable_since ||
53 NaiveDateTime.compare(unreachable_since, reachability_datetime_threshold) == :gt do
54 {entry, unreachable_since}
55 end
56 end
57 |> Enum.filter(& &1)
58 |> Map.new(& &1)
59 end
60
61 def reachable?(url_or_host) when is_binary(url_or_host) do
62 !Repo.one(
63 from(i in Instance,
64 where:
65 i.host == ^host(url_or_host) and
66 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
67 select: true
68 )
69 )
70 end
71
72 def reachable?(_), do: true
73
74 def set_reachable(url_or_host) when is_binary(url_or_host) do
75 with host <- host(url_or_host),
76 %Instance{} = existing_record <- Repo.get_by(Instance, %{host: host}) do
77 {:ok, _instance} =
78 existing_record
79 |> changeset(%{unreachable_since: nil})
80 |> Repo.update()
81 end
82 end
83
84 def set_reachable(_), do: {:error, nil}
85
86 def set_unreachable(url_or_host, unreachable_since \\ nil)
87
88 def set_unreachable(url_or_host, unreachable_since) when is_binary(url_or_host) do
89 unreachable_since = unreachable_since || DateTime.utc_now()
90 host = host(url_or_host)
91 existing_record = Repo.get_by(Instance, %{host: host})
92
93 changes = %{unreachable_since: unreachable_since}
94
95 cond do
96 is_nil(existing_record) ->
97 %Instance{}
98 |> changeset(Map.put(changes, :host, host))
99 |> Repo.insert()
100
101 existing_record.unreachable_since &&
102 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt ->
103 {:ok, existing_record}
104
105 true ->
106 existing_record
107 |> changeset(changes)
108 |> Repo.update()
109 end
110 end
111
112 def set_unreachable(_, _), do: {:error, nil}
113 end