Skip to content

Commit

Permalink
use different registry when in china, fixes #3700 (#3702)
Browse files Browse the repository at this point in the history
  • Loading branch information
adhami3310 committed Aug 12, 2024
1 parent 0eff63e commit 910bcdb
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
2 changes: 2 additions & 0 deletions reflex/constants/installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ class Bun(SimpleNamespace):
WINDOWS_INSTALL_URL = (
"https://raw.githubusercontent.com/reflex-dev/reflex/main/scripts/install.ps1"
)
# Path of the bunfig file
CONFIG_PATH = "bunfig.toml"


# FNM config.
Expand Down
10 changes: 10 additions & 0 deletions reflex/utils/prerequisites.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from reflex.config import Config, get_config
from reflex.utils import console, path_ops, processes
from reflex.utils.format import format_library_name
from reflex.utils.registry import _get_best_registry

CURRENTLY_INSTALLING_NODE = False

Expand Down Expand Up @@ -577,6 +578,15 @@ def initialize_package_json():
code = _compile_package_json()
output_path.write_text(code)

best_registry = _get_best_registry()
bun_config_path = get_web_dir() / constants.Bun.CONFIG_PATH
bun_config_path.write_text(
f"""
[install]
registry = "{best_registry}"
"""
)


def init_reflex_json(project_hash: int | None):
"""Write the hash of the Reflex project to a REFLEX_JSON.
Expand Down
48 changes: 48 additions & 0 deletions reflex/utils/registry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Utilities for working with registries."""

import httpx

from reflex.utils import console


def latency(registry: str) -> int:
"""Get the latency of a registry.
Args:
registry (str): The URL of the registry.
Returns:
int: The latency of the registry in microseconds.
"""
try:
return httpx.get(registry).elapsed.microseconds
except httpx.HTTPError:
console.info(f"Failed to connect to {registry}.")
return 10_000_000


def average_latency(registry, attempts: int = 3) -> int:
"""Get the average latency of a registry.
Args:
registry (str): The URL of the registry.
attempts (int): The number of attempts to make. Defaults to 10.
Returns:
int: The average latency of the registry in microseconds.
"""
return sum(latency(registry) for _ in range(attempts)) // attempts


def _get_best_registry() -> str:
"""Get the best registry based on latency.
Returns:
str: The best registry.
"""
registries = [
"https://registry.npmjs.org",
"https://r.cnpmjs.org",
]

return min(registries, key=average_latency)

1 comment on commit 910bcdb

@reigadegr
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

好耶!这下会方便很多

Please sign in to comment.