registry.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Utilities for working with registries."""
  2. import httpx
  3. from reflex.config import environment
  4. from reflex.utils import console, net
  5. def latency(registry: str) -> int:
  6. """Get the latency of a registry.
  7. Args:
  8. registry (str): The URL of the registry.
  9. Returns:
  10. int: The latency of the registry in microseconds.
  11. """
  12. try:
  13. time_to_respond = net.get(registry, timeout=2).elapsed.microseconds
  14. except httpx.HTTPError:
  15. console.info(f"Failed to connect to {registry}.")
  16. return 10_000_000
  17. else:
  18. console.debug(f"Latency of {registry}: {time_to_respond}")
  19. return time_to_respond
  20. def average_latency(registry: str, attempts: int = 3) -> int:
  21. """Get the average latency of a registry.
  22. Args:
  23. registry: The URL of the registry.
  24. attempts: The number of attempts to make. Defaults to 10.
  25. Returns:
  26. The average latency of the registry in microseconds.
  27. """
  28. registry_latency = sum(latency(registry) for _ in range(attempts)) // attempts
  29. console.debug(f"Average latency of {registry}: {registry_latency}")
  30. return registry_latency
  31. def _get_best_registry() -> str:
  32. """Get the best registry based on latency.
  33. Returns:
  34. The best registry.
  35. """
  36. console.debug("Getting best registry...")
  37. registries = [
  38. "https://registry.npmjs.org",
  39. "https://r.cnpmjs.org",
  40. ]
  41. best_registry = min(registries, key=average_latency)
  42. console.debug(f"Best registry: {best_registry}")
  43. return best_registry
  44. def get_npm_registry() -> str:
  45. """Get npm registry. If environment variable is set, use it first.
  46. Returns:
  47. The npm registry.
  48. """
  49. return environment.NPM_CONFIG_REGISTRY.get() or _get_best_registry()