telemetry.py 5.4 KB

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