1
0

telemetry.py 5.6 KB

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