Skip to content

Commit

Permalink
feat: add Metrics class
Browse files Browse the repository at this point in the history
  • Loading branch information
wu-vincent committed Sep 8, 2024
1 parent e393a27 commit fb22234
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 12 deletions.
2 changes: 2 additions & 0 deletions src/endstone_bstats/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
from endstone_bstats._charts.simple_pie import SimplePie
from endstone_bstats._config import MetricsConfig
from endstone_bstats._errors import ChartDataError
from endstone_bstats._metrics import Metrics

__all__ = [
"Metrics",
"MetricsBase",
"MetricsConfig",
"CustomChart",
Expand Down
27 changes: 15 additions & 12 deletions src/endstone_bstats/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ def __init__(
server_uuid: uuid.UUID,
service_id: int,
enabled: bool,
platform_data_appender: Callable[[Dict[str, Any]], Dict[str, Any]],
service_data_appender: Callable[[Dict[str, Any]], Dict[str, Any]],
platform_data_appender: Callable[[Dict[str, Any]], None],
service_data_appender: Callable[[Dict[str, Any]], None],
task_submitter: Optional[Callable[[Callable[[], None]], None]],
check_service_enabled: Callable[[], bool],
error_logger: Callable[[str, Exception], None],
Expand All @@ -46,8 +46,8 @@ def __init__(
server_uuid (uuid.UUID): The server UUID.
service_id (int): The service ID.
enabled (bool): Whether or not data sending is enabled.
platform_data_appender (Callable[[Dict[str, Any]], Dict[str, Any]]): A consumer to append platform-specific data.
service_data_appender (Callable[[Dict[str, Any]], Dict[str, Any]]): A consumer to append service-specific data.
platform_data_appender (Callable[[Dict[str, Any]], None]): A consumer to append platform-specific data.
service_data_appender (Callable[[Dict[str, Any]], None]): A consumer to append service-specific data.
task_submitter (Optional[Callable[[Callable[[], None]], None]]): A consumer to handle the submit task.
check_service_enabled (Callable[[], bool]): A supplier to check if the service is still enabled.
error_logger (Callable[[str, Exception], None]): A consumer for error logging.
Expand Down Expand Up @@ -116,23 +116,26 @@ def _submit_data(self):
Constructs the JSON data and sends it to bStats.
"""

base_json = self._platform_data_appender({})
service_json = self._service_data_appender({})
platform_data = {}
self._platform_data_appender(platform_data)

service_data = {}
self._service_data_appender(service_data)

chart_data = []
for chart in self._custom_charts:
chart_data.append(
chart.get_request_json_object(self._error_logger, self._log_errors)
)

service_json["id"] = self._service_id
service_json["customCharts"] = chart_data
base_json["service"] = service_json
base_json["serverUUID"] = str(self._server_uuid)
# base_json["metricsVersion"] = self.METRICS_VERSION
service_data["id"] = self._service_id
service_data["customCharts"] = chart_data
platform_data["service"] = service_data
platform_data["serverUUID"] = str(self._server_uuid)
# platform_data["metricsVersion"] = self.METRICS_VERSION

try:
self._send_data(base_json)
self._send_data(platform_data)
except Exception as e:
if self._log_errors:
self._error_logger("Could not submit bStats metrics data", e)
Expand Down
85 changes: 85 additions & 0 deletions src/endstone_bstats/_metrics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import os
import platform
from functools import partial
from pathlib import Path
from typing import Any, Dict

from endstone.plugin import Plugin

from endstone_bstats._base import MetricsBase
from endstone_bstats._charts.custom_chart import CustomChart
from endstone_bstats._config import MetricsConfig


class Metrics:
def __init__(self, plugin: Plugin, service_id: int):
"""
Creates a new Metrics instance.
Args:
plugin (Plugin): Your plugin instance.
service_id (int): The id of the service.
It can be found at https://bstats.org/what-is-my-plugin-id
"""
self._plugin = plugin

# Get the config file
bstats_folder = Path(plugin.data_folder).parent / "bStats"
config_file = bstats_folder / "config.toml"
config = MetricsConfig(config_file, True)

self._metrics_base = MetricsBase(
platform="server-implementation",
server_uuid=config.server_uuid,
service_id=service_id,
enabled=config.enabled,
platform_data_appender=self.append_platform_data,
service_data_appender=self.append_service_data,
task_submitter=lambda task: partial(
plugin.server.scheduler.run_task, plugin, task
),
check_service_enabled=lambda: plugin.enabled,
error_logger=lambda msg, e: plugin.logger.warning(f"{msg}: {e}"),
info_logger=plugin.logger.info,
log_errors=config.log_errors_enabled,
log_sent_data=config.log_sent_data_enabled,
log_response_status_text=config.log_response_status_text_enabled,
)

def shutdown(self):
"""Shuts down the underlying scheduler service."""
self._metrics_base.shutdown()

def add_custom_chart(self, chart: CustomChart):
"""
Adds a custom chart.
Args:
chart (CustomChart): The chart to add.
"""
self._metrics_base.add_custom_chart(chart)

def append_platform_data(self, platform_data: Dict[str, Any]) -> None:
"""
Appends platform-specific data to the provided dict.
Args:
platform_data (Dict[str, Any]): The dict to append data to.
"""
# TODO: implement the following
platform_data["playerAmount"] = len(self._plugin.server.online_players)
# platform_data["onlineMode"] = 1 if Bukkit.get_online_mode() else 0

platform_data["osName"] = platform.system()
platform_data["osArch"] = platform.machine().lower()
platform_data["osVersion"] = platform.release()
platform_data["coreCount"] = os.cpu_count()

def append_service_data(self, service_data: Dict[str, Any]):
"""
Appends service-specific data to the provided dict.
Args:
service_data (Dict[str, Any]): The dict to append data to.
"""
service_data["pluginVersion"] = self._plugin.description.version

0 comments on commit fb22234

Please sign in to comment.