mirror of
https://github.com/discourse/discourse.git
synced 2024-11-25 00:43:24 +08:00
d91456fd53
This adds the ability to collect stats without exposing them
among other stats via API.
The most important thing I wanted to achieve is to provide
an API where stats are not exposed by default, and a developer
has to explicitly specify that they should be
exposed (`expose_via_api: true`). Implementing an opposite
solution would be simpler, but that's less safe in terms of
potential security issues.
When working on this, I had to refactor the current solution.
I would go even further with the refactoring, but the next steps
seem to be going too far in changing the solution we have,
and that would also take more time. Two things that can be
improved in the future:
1. Data structures for holding stats can be further improved
2. Core stats are hard-coded in the About template (it's hard
to fix it without correcting data structures first, see point 1):
63a0700d45/app/views/about/index.html.erb (L61-L101)
The most significant refactorings are:
1. Introducing the `Stat` model
2. Aligning the way the core and the plugin stats' are registered
62 lines
1.5 KiB
Ruby
62 lines
1.5 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
class Stat
|
|
def initialize(name, show_in_ui: false, expose_via_api: false, &block)
|
|
@name = name
|
|
@show_in_ui = show_in_ui
|
|
@expose_via_api = expose_via_api
|
|
@block = block
|
|
end
|
|
|
|
attr_reader :name, :expose_via_api, :show_in_ui
|
|
|
|
def calculate
|
|
@block.call.transform_keys { |key| build_key(key) }
|
|
rescue StandardError => err
|
|
Discourse.warn_exception(err, message: "Unexpected error when collecting #{@name} About stats.")
|
|
{}
|
|
end
|
|
|
|
def self.all_stats
|
|
calculate(_all_stats)
|
|
end
|
|
|
|
def self.api_stats
|
|
calculate(_api_stats)
|
|
end
|
|
|
|
private
|
|
|
|
def build_key(key)
|
|
"#{@name}_#{key}".to_sym
|
|
end
|
|
|
|
def self._all_stats
|
|
core_stats.concat(plugin_stats)
|
|
end
|
|
|
|
def self.calculate(stats)
|
|
stats.map { |stat| stat.calculate }.reduce(Hash.new, :merge)
|
|
end
|
|
|
|
def self.core_stats
|
|
[
|
|
Stat.new("topics", show_in_ui: true, expose_via_api: true) { Statistics.topics },
|
|
Stat.new("posts", show_in_ui: true, expose_via_api: true) { Statistics.posts },
|
|
Stat.new("users", show_in_ui: true, expose_via_api: true) { Statistics.users },
|
|
Stat.new("active_users", show_in_ui: true, expose_via_api: true) { Statistics.active_users },
|
|
Stat.new("likes", show_in_ui: true, expose_via_api: true) { Statistics.likes },
|
|
]
|
|
end
|
|
|
|
def self._api_stats
|
|
_all_stats.select { |stat| stat.expose_via_api }
|
|
end
|
|
|
|
def self.plugin_stats
|
|
DiscoursePluginRegistry.stats
|
|
end
|
|
|
|
private_class_method :_all_stats, :calculate, :core_stats, :_api_stats, :plugin_stats
|
|
end
|