1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Stats do
10 alias Pleroma.CounterCache
14 @interval :timer.seconds(60)
26 if Pleroma.Config.get(:env) == :test, do: :ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo)
27 {:ok, nil, {:continue, :calculate_stats}}
30 @doc "Performs update stats"
32 GenServer.call(__MODULE__, :force_update)
35 @doc "Performs collect stats"
37 GenServer.cast(__MODULE__, :run_update)
40 @doc "Returns stats data"
41 @spec get_stats() :: %{
42 domain_count: non_neg_integer(),
43 status_count: non_neg_integer(),
44 user_count: non_neg_integer()
47 %{stats: stats} = GenServer.call(__MODULE__, :get_state)
52 @doc "Returns list peers"
53 @spec get_peers() :: list(String.t())
55 %{peers: peers} = GenServer.call(__MODULE__, :get_state)
60 @spec calculate_stat_data() :: %{
63 domain_count: non_neg_integer(),
64 status_count: non_neg_integer(),
65 user_count: non_neg_integer()
68 def calculate_stat_data do
72 select: fragment("distinct split_part(?, '@', 2)", u.nickname),
73 where: u.local != ^true
78 domain_count = Enum.count(peers)
80 status_count = Repo.aggregate(User.Query.build(%{local: true}), :sum, :note_count)
84 where: u.deactivated != true,
85 where: u.local == true,
86 where: not is_nil(u.nickname),
87 where: not u.invisible
90 user_count = Repo.aggregate(users_query, :count, :id)
95 domain_count: domain_count,
96 status_count: status_count || 0,
97 user_count: user_count
102 @spec get_status_visibility_count(String.t() | nil) :: map()
103 def get_status_visibility_count(instance \\ nil) do
104 if is_nil(instance) do
105 CounterCache.get_sum()
107 CounterCache.get_by_instance(instance)
112 def handle_continue(:calculate_stats, _) do
113 stats = calculate_stat_data()
114 Process.send_after(self(), :run_update, @interval)
119 def handle_call(:force_update, _from, _state) do
120 new_stats = calculate_stat_data()
121 {:reply, new_stats, new_stats}
125 def handle_call(:get_state, _from, state) do
126 {:reply, state, state}
130 def handle_cast(:run_update, _state) do
131 new_stats = calculate_stat_data()
133 {:noreply, new_stats}
137 def handle_info(:run_update, _) do
138 new_stats = calculate_stat_data()
139 Process.send_after(self(), :run_update, @interval)
140 {:noreply, new_stats}