1
0

telemetry.py 6.6 KB

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