telemetry.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. """Anonymous telemetry for Reflex."""
  2. from __future__ import annotations
  3. import asyncio
  4. import dataclasses
  5. import multiprocessing
  6. import platform
  7. import warnings
  8. from contextlib import suppress
  9. from datetime import datetime, timezone
  10. import httpx
  11. import psutil
  12. from reflex import constants
  13. from reflex.config import environment
  14. from reflex.utils import console
  15. from reflex.utils.prerequisites import ensure_reflex_installation_id, get_project_hash
  16. UTC = timezone.utc
  17. POSTHOG_API_URL: str = "https://app.posthog.com/capture/"
  18. def get_os() -> str:
  19. """Get the operating system.
  20. Returns:
  21. The operating system.
  22. """
  23. return platform.system()
  24. def get_detailed_platform_str() -> str:
  25. """Get the detailed os/platform string.
  26. Returns:
  27. The platform string
  28. """
  29. return platform.platform()
  30. def get_python_version() -> str:
  31. """Get the Python version.
  32. Returns:
  33. The Python version.
  34. """
  35. # Remove the "+" from the version string in case user is using a pre-release version.
  36. return platform.python_version().rstrip("+")
  37. def get_reflex_version() -> str:
  38. """Get the Reflex version.
  39. Returns:
  40. The Reflex version.
  41. """
  42. return constants.Reflex.VERSION
  43. def get_cpu_count() -> int:
  44. """Get the number of CPUs.
  45. Returns:
  46. The number of CPUs.
  47. """
  48. return multiprocessing.cpu_count()
  49. def get_memory() -> int:
  50. """Get the total memory in MB.
  51. Returns:
  52. The total memory in MB.
  53. """
  54. try:
  55. return psutil.virtual_memory().total >> 20
  56. except ValueError: # needed to pass ubuntu test
  57. return 0
  58. def _raise_on_missing_project_hash() -> bool:
  59. """Check if an error should be raised when project hash is missing.
  60. When running reflex with --backend-only, or doing database migration
  61. operations, there is no requirement for a .web directory, so the reflex.json
  62. file may not exist, and this should not be considered an error.
  63. Returns:
  64. False when compilation should be skipped (i.e. no .web directory is required).
  65. Otherwise return True.
  66. """
  67. return not environment.REFLEX_SKIP_COMPILE.get()
  68. def _prepare_event(event: str, **kwargs) -> dict:
  69. """Prepare the event to be sent to the PostHog server.
  70. Args:
  71. event: The event name.
  72. kwargs: Additional data to send with the event.
  73. Returns:
  74. The event data.
  75. """
  76. from reflex.utils.prerequisites import get_cpu_info
  77. installation_id = ensure_reflex_installation_id()
  78. project_hash = get_project_hash(raise_on_fail=_raise_on_missing_project_hash())
  79. if installation_id is None or project_hash is None:
  80. console.debug(
  81. f"Could not get installation_id or project_hash: {installation_id}, {project_hash}"
  82. )
  83. return {}
  84. stamp = datetime.now(UTC).isoformat()
  85. cpuinfo = get_cpu_info()
  86. additional_keys = ["template", "context", "detail", "user_uuid"]
  87. additional_fields = {
  88. key: value for key in additional_keys if (value := kwargs.get(key)) is not None
  89. }
  90. return {
  91. "api_key": "phc_JoMo0fOyi0GQAooY3UyO9k0hebGkMyFJrrCw1Gt5SGb",
  92. "event": event,
  93. "properties": {
  94. "distinct_id": installation_id,
  95. "distinct_app_id": project_hash,
  96. "user_os": get_os(),
  97. "user_os_detail": get_detailed_platform_str(),
  98. "reflex_version": get_reflex_version(),
  99. "python_version": get_python_version(),
  100. "cpu_count": get_cpu_count(),
  101. "memory": get_memory(),
  102. "cpu_info": dataclasses.asdict(cpuinfo) if cpuinfo else {},
  103. **additional_fields,
  104. },
  105. "timestamp": stamp,
  106. }
  107. def _send_event(event_data: dict) -> bool:
  108. try:
  109. httpx.post(POSTHOG_API_URL, json=event_data)
  110. except Exception:
  111. return False
  112. else:
  113. return True
  114. def _send(event: str, telemetry_enabled: bool | None, **kwargs):
  115. from reflex.config import get_config
  116. # Get the telemetry_enabled from the config if it is not specified.
  117. if telemetry_enabled is None:
  118. telemetry_enabled = get_config().telemetry_enabled
  119. # Return if telemetry is disabled.
  120. if not telemetry_enabled:
  121. return False
  122. with suppress(Exception):
  123. event_data = _prepare_event(event, **kwargs)
  124. if not event_data:
  125. return False
  126. return _send_event(event_data)
  127. def send(event: str, telemetry_enabled: bool | None = None, **kwargs):
  128. """Send anonymous telemetry for Reflex.
  129. Args:
  130. event: The event name.
  131. telemetry_enabled: Whether to send the telemetry (If None, get from config).
  132. kwargs: Additional data to send with the event.
  133. """
  134. async def async_send(event: str, telemetry_enabled: bool | None, **kwargs):
  135. return _send(event, telemetry_enabled, **kwargs)
  136. try:
  137. # Within an event loop context, send the event asynchronously.
  138. asyncio.create_task(async_send(event, telemetry_enabled, **kwargs))
  139. except RuntimeError:
  140. # If there is no event loop, send the event synchronously.
  141. warnings.filterwarnings("ignore", category=RuntimeWarning)
  142. _send(event, telemetry_enabled, **kwargs)
  143. def send_error(error: Exception, context: str):
  144. """Send an error event.
  145. Args:
  146. error: The error to send.
  147. context: The context of the error (e.g. "frontend" or "backend")
  148. Returns:
  149. Whether the telemetry was sent successfully.
  150. """
  151. return send("error", detail=type(error).__name__, context=context)