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 {:ok, nil, {:continue, :calculate_stats}}
29 @doc "Performs update stats"
31 GenServer.call(__MODULE__, :force_update)
34 @doc "Performs collect stats"
36 GenServer.cast(__MODULE__, :run_update)
39 @doc "Returns stats data"
40 @spec get_stats() :: %{
41 domain_count: non_neg_integer(),
42 status_count: non_neg_integer(),
43 user_count: non_neg_integer()
46 %{stats: stats} = GenServer.call(__MODULE__, :get_state)
51 @doc "Returns list peers"
52 @spec get_peers() :: list(String.t())
54 %{peers: peers} = GenServer.call(__MODULE__, :get_state)
59 @spec calculate_stat_data() :: %{
62 domain_count: non_neg_integer(),
63 status_count: non_neg_integer(),
64 user_count: non_neg_integer()
67 def calculate_stat_data do
71 select: fragment("distinct split_part(?, '@', 2)", u.nickname),
72 where: u.local != ^true
77 domain_count = Enum.count(peers)
79 status_count = Repo.aggregate(User.Query.build(%{local: true}), :sum, :note_count)
83 where: u.deactivated != true,
84 where: u.local == true,
85 where: not is_nil(u.nickname),
86 where: not u.invisible
89 user_count = Repo.aggregate(users_query, :count, :id)
94 domain_count: domain_count,
95 status_count: status_count || 0,
96 user_count: user_count
101 @spec get_status_visibility_count(String.t() | nil) :: map()
102 def get_status_visibility_count(instance \\ nil) do
103 if is_nil(instance) do
104 CounterCache.get_sum()
106 CounterCache.get_by_instance(instance)
111 def handle_continue(:calculate_stats, _) do
112 stats = calculate_stat_data()
113 Process.send_after(self(), :run_update, @interval)
118 def handle_call(:force_update, _from, _state) do
119 new_stats = calculate_stat_data()
120 {:reply, new_stats, new_stats}
124 def handle_call(:get_state, _from, state) do
125 {:reply, state, state}
129 def handle_cast(:run_update, _state) do
130 new_stats = calculate_stat_data()
132 {:noreply, new_stats}
136 def handle_info(:run_update, _) do
137 new_stats = calculate_stat_data()
138 Process.send_after(self(), :run_update, @interval)
139 {:noreply, new_stats}