@simplexai/localmodels-linux-x64 0.1.0-dev.55 → 0.1.0-dev.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +41 -36
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/bifrost_admin.py +336 -0
- package/modules/localmodels/bifrost_checks.py +12 -2
- package/modules/localmodels/bifrost_config.py +13 -5
- package/modules/localmodels/catalog.json +2 -1
- package/modules/localmodels/engines.py +24 -1
- package/modules/localmodels/library_floor.py +3 -1
- package/modules/localmodels/library_gateway.py +26 -4
- package/modules/localmodels/library_jobs.py +44 -6
- package/modules/localmodels/library_kept.py +117 -0
- package/modules/localmodels/library_model.py +1 -0
- package/modules/localmodels/library_order.py +234 -0
- package/modules/localmodels/library_poly.py +20 -16
- package/modules/localmodels/library_pricing.py +8 -1
- package/modules/localmodels/library_serve.py +9 -3
- package/modules/localmodels/library_state.py +12 -2
- package/modules/localmodels/library_status.py +2 -0
- package/modules/localmodels/llm_rank.py +11 -8
- package/modules/localmodels/mirrors.py +464 -0
- package/modules/localmodels/recommend.py +2 -2
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/region.py +457 -42
- package/modules/localmodels/remote_ops.py +130 -33
- package/modules/localmodels/remote_ops_download.py +313 -273
- package/modules/localmodels/remote_ops_mirrors.py +290 -0
- package/modules/localmodels/runtime-lock.json +19 -19
- package/modules/localmodels/runtime_io.py +2 -4
- package/modules/localmodels/setup_inspection.py +4 -0
- package/modules/localmodels/stack_auto.py +38 -5
- package/modules/localmodels/stack_compose.py +2 -1
- package/modules/localmodels/stack_try.py +4 -1
- package/modules/localmodels/transport.py +1 -0
- package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/RECORD +38 -33
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -1,18 +1,21 @@
|
|
|
1
|
-
"""The network region every download orders its sources by
|
|
1
|
+
"""The network region and per-ecosystem mirror profile every download orders its sources by.
|
|
2
2
|
|
|
3
|
-
One process resolves
|
|
3
|
+
One process resolves the region once, lazily, the first time something is about to be downloaded:
|
|
4
4
|
|
|
5
5
|
1. ``SIMPLEX_REGION`` (or the CLI's ``--region``, which sets it) when it is ``cn`` or ``global``;
|
|
6
6
|
``auto`` or unset means not forced. Linger passes the region it resolved this way.
|
|
7
|
-
2.
|
|
8
|
-
|
|
9
|
-
``
|
|
7
|
+
2. ``SIMPLEX_REGION_FILE`` (when set by Linger to share ``<home>/runtime/region.json``) or
|
|
8
|
+
``$LOCALMODELS_STATE/region.json`` when it is younger than ``STALE_AFTER`` (6 hours) and its
|
|
9
|
+
``network_fingerprint`` matches the current proxy environment.
|
|
10
|
+
3. A multi-signal concurrent speed probe covering npm (pinned pi tarball race), PyPI (official
|
|
11
|
+
vs Tsinghua / Aliyun / USTC / Tencent), and Model Hub (Hugging Face vs hf-mirror / ModelScope).
|
|
12
|
+
Recording per-ecosystem winners in ``region.json["ecosystems"]`` prevents a Cloudflare Anycast
|
|
13
|
+
edge on npm from locking mainland China hosts onto slow PyPI or Hugging Face endpoints.
|
|
10
14
|
|
|
11
15
|
The region only reorders sources; it never removes one, and a SHA256 pin stays the only thing
|
|
12
|
-
that decides whether downloaded bytes are accepted. A download whose preferred side failed
|
|
13
|
-
|
|
14
|
-
with ``method: fallback``.
|
|
15
|
-
in its own home.
|
|
16
|
+
that decides whether downloaded bytes are accepted. A download whose preferred side failed or
|
|
17
|
+
was decisively outperformed by the other side switches the region (``fallback_to``) and rewrites
|
|
18
|
+
``region.json`` with ``method: fallback``.
|
|
16
19
|
"""
|
|
17
20
|
|
|
18
21
|
from __future__ import annotations
|
|
@@ -21,21 +24,25 @@ import configparser
|
|
|
21
24
|
import datetime as dt
|
|
22
25
|
import json
|
|
23
26
|
import os
|
|
27
|
+
import re
|
|
28
|
+
import stat
|
|
24
29
|
import sys
|
|
25
30
|
import threading
|
|
26
31
|
from collections.abc import Mapping, MutableMapping, Sequence
|
|
27
32
|
from pathlib import Path
|
|
28
|
-
from typing import TypeVar
|
|
33
|
+
from typing import Any, TypeVar
|
|
29
34
|
|
|
30
|
-
from localmodels import npm_transport
|
|
35
|
+
from localmodels import mirrors, npm_transport
|
|
36
|
+
from localmodels.mirrors import EcosystemName, EcosystemRecord, Side
|
|
31
37
|
|
|
32
38
|
SCHEMA = "simplex.region/v1"
|
|
33
39
|
REGIONS = ("global", "cn")
|
|
34
40
|
ENV = "SIMPLEX_REGION"
|
|
35
|
-
|
|
41
|
+
FILE_ENV = "SIMPLEX_REGION_FILE"
|
|
42
|
+
STALE_AFTER = dt.timedelta(hours=6)
|
|
36
43
|
HF_API = "https://huggingface.co"
|
|
37
44
|
HF_MIRROR = "https://hf-mirror.com"
|
|
38
|
-
PYPI_MIRROR = "https://
|
|
45
|
+
PYPI_MIRROR = "https://pypi.tuna.tsinghua.edu.cn/simple/"
|
|
39
46
|
# A user's own Python index wins over the region: any of these variables, or an index in a pip
|
|
40
47
|
# or uv configuration file, leaves pip and uv as they are.
|
|
41
48
|
INDEX_VARIABLES = ("PIP_INDEX_URL", "UV_DEFAULT_INDEX", "UV_INDEX_URL", "UV_INDEX")
|
|
@@ -44,6 +51,7 @@ TOOL_LOCK = Path(__file__).with_name("tools.json")
|
|
|
44
51
|
T = TypeVar("T")
|
|
45
52
|
_LOCK = threading.Lock()
|
|
46
53
|
_resolved: str | None = None # this process's region once known (fallback included)
|
|
54
|
+
_ecosystems: dict[EcosystemName, EcosystemRecord] = {}
|
|
47
55
|
|
|
48
56
|
|
|
49
57
|
def forced(env: Mapping[str, str]) -> str | None:
|
|
@@ -54,39 +62,130 @@ def forced(env: Mapping[str, str]) -> str | None:
|
|
|
54
62
|
return None if value == "auto" else value
|
|
55
63
|
|
|
56
64
|
|
|
57
|
-
def
|
|
58
|
-
|
|
59
|
-
|
|
65
|
+
def _expand_home(raw: str, env: Mapping[str, str]) -> Path:
|
|
66
|
+
if raw == "~" or raw.startswith(("~/", "~\\")):
|
|
67
|
+
home = env.get("HOME") or env.get("USERPROFILE")
|
|
68
|
+
if home:
|
|
69
|
+
return Path(home) / raw[2:] if len(raw) > 2 else Path(home)
|
|
70
|
+
return Path(raw).expanduser()
|
|
60
71
|
|
|
61
72
|
|
|
62
|
-
def
|
|
63
|
-
|
|
73
|
+
def region_path(env: Mapping[str, str] | None = None) -> Path:
|
|
74
|
+
source = os.environ if env is None else env
|
|
75
|
+
shared = (source.get(FILE_ENV) or "").strip()
|
|
76
|
+
if shared:
|
|
77
|
+
return _expand_home(shared, source)
|
|
78
|
+
state = source.get("LOCALMODELS_STATE", "~/.local/state/localmodels")
|
|
79
|
+
return _expand_home(state, source) / "region.json"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
_DEFAULT_REGION_PATH = region_path
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _resolve_region_path(env: Mapping[str, str] | None = None) -> Path:
|
|
86
|
+
if region_path is _DEFAULT_REGION_PATH:
|
|
87
|
+
return _DEFAULT_REGION_PATH(env)
|
|
88
|
+
try:
|
|
89
|
+
return region_path(env)
|
|
90
|
+
except TypeError:
|
|
91
|
+
return region_path()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _parse_ecosystems(raw: object) -> dict[EcosystemName, EcosystemRecord]:
|
|
95
|
+
if not isinstance(raw, dict):
|
|
96
|
+
return {}
|
|
97
|
+
found: dict[EcosystemName, EcosystemRecord] = {}
|
|
98
|
+
for name in mirrors.ECOSYSTEMS:
|
|
99
|
+
if name in raw:
|
|
100
|
+
valid = mirrors.valid_ecosystem_record(raw[name], ecosystem=name)
|
|
101
|
+
if valid is not None:
|
|
102
|
+
found[name] = valid
|
|
103
|
+
return found
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _read_regular_text(path: Path, *, max_bytes: int = 64 << 10) -> str | None:
|
|
107
|
+
try:
|
|
108
|
+
st = os.lstat(path)
|
|
109
|
+
if not stat.S_ISREG(st.st_mode) or st.st_size > max_bytes:
|
|
110
|
+
return None
|
|
111
|
+
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
|
|
112
|
+
fd = os.open(path, flags)
|
|
113
|
+
try:
|
|
114
|
+
with os.fdopen(fd, "r", encoding="utf-8") as fh:
|
|
115
|
+
return fh.read(max_bytes + 1)
|
|
116
|
+
except BaseException:
|
|
117
|
+
try:
|
|
118
|
+
os.close(fd)
|
|
119
|
+
except OSError:
|
|
120
|
+
pass
|
|
121
|
+
raise
|
|
122
|
+
except (OSError, UnicodeError):
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def saved(
|
|
127
|
+
now: dt.datetime | None = None,
|
|
128
|
+
env: Mapping[str, str] | None = None,
|
|
129
|
+
) -> dict[str, Any] | None:
|
|
130
|
+
"""The saved region document when valid, younger than STALE_AFTER, and matching proxy state."""
|
|
131
|
+
text = _read_regular_text(_resolve_region_path(env))
|
|
132
|
+
if text is None or len(text.encode("utf-8")) > (64 << 10):
|
|
133
|
+
return None
|
|
64
134
|
try:
|
|
65
|
-
doc = json.loads(
|
|
135
|
+
doc = json.loads(text)
|
|
66
136
|
when = dt.datetime.fromisoformat(str(doc["resolved_at"]).replace("Z", "+00:00"))
|
|
67
|
-
except (
|
|
137
|
+
except (ValueError, KeyError, TypeError):
|
|
68
138
|
return None
|
|
69
139
|
if (
|
|
70
140
|
not isinstance(doc, dict)
|
|
71
141
|
or doc.get("schema") != SCHEMA
|
|
72
142
|
or doc.get("region") not in REGIONS
|
|
143
|
+
or doc.get("method") not in mirrors.VALID_METHODS
|
|
73
144
|
or when.tzinfo is None
|
|
74
145
|
):
|
|
75
146
|
return None
|
|
147
|
+
stored_fp = doc.get("network_fingerprint")
|
|
148
|
+
if isinstance(stored_fp, str) and stored_fp:
|
|
149
|
+
active_env = os.environ if env is None else env
|
|
150
|
+
if stored_fp != mirrors.network_fingerprint(active_env):
|
|
151
|
+
return None
|
|
76
152
|
age = (now or dt.datetime.now(dt.timezone.utc)) - when
|
|
77
153
|
return doc if dt.timedelta(0) <= age <= STALE_AFTER else None
|
|
78
154
|
|
|
79
155
|
|
|
80
|
-
def save(
|
|
156
|
+
def save(
|
|
157
|
+
region: str,
|
|
158
|
+
method: str,
|
|
159
|
+
*,
|
|
160
|
+
ecosystems: Mapping[EcosystemName, EcosystemRecord] | None = None,
|
|
161
|
+
env: Mapping[str, str] | None = None,
|
|
162
|
+
) -> None:
|
|
81
163
|
"""Write region.json owner-only and atomically; a state directory that cannot be written
|
|
82
164
|
costs only the next run a probe."""
|
|
83
|
-
|
|
165
|
+
active_env = os.environ if env is None else env
|
|
166
|
+
fp = mirrors.network_fingerprint(active_env)
|
|
167
|
+
merged: dict[EcosystemName, EcosystemRecord] = {}
|
|
168
|
+
if ecosystems is not None:
|
|
169
|
+
merged.update(ecosystems)
|
|
170
|
+
else:
|
|
171
|
+
existing = saved(env=active_env)
|
|
172
|
+
if existing is not None:
|
|
173
|
+
for name, rec in _parse_ecosystems(existing.get("ecosystems")).items():
|
|
174
|
+
if rec["region"] == region:
|
|
175
|
+
merged[name] = rec
|
|
176
|
+
for name, rec in _ecosystems.items():
|
|
177
|
+
if rec["region"] == region:
|
|
178
|
+
merged[name] = rec
|
|
179
|
+
doc: dict[str, Any] = {
|
|
84
180
|
"schema": SCHEMA,
|
|
85
181
|
"region": region,
|
|
86
182
|
"resolved_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
|
|
87
183
|
"method": method,
|
|
184
|
+
"network_fingerprint": fp,
|
|
88
185
|
}
|
|
89
|
-
|
|
186
|
+
if merged:
|
|
187
|
+
doc["ecosystems"] = dict(merged)
|
|
188
|
+
path = _resolve_region_path(active_env)
|
|
90
189
|
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
|
91
190
|
try:
|
|
92
191
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -97,37 +196,122 @@ def save(region: str, method: str) -> None:
|
|
|
97
196
|
tmp.unlink(missing_ok=True)
|
|
98
197
|
|
|
99
198
|
|
|
199
|
+
def _combine_signals(
|
|
200
|
+
npm_winner: str | None,
|
|
201
|
+
pypi_record: EcosystemRecord | None,
|
|
202
|
+
hub_record: EcosystemRecord | None,
|
|
203
|
+
) -> str | None:
|
|
204
|
+
"""Decide the overall download region from multi-ecosystem probe results.
|
|
205
|
+
|
|
206
|
+
PyPI and Model Hub carry the heaviest payloads (hundreds of MB to 10+ GB) and exhibit a
|
|
207
|
+
sharp global-vs-China throughput gap, whereas npm's Cloudflare Anycast edge can sometimes
|
|
208
|
+
answer fast from China. When heavy-ecosystem signals pick ``cn``, they prevent a false
|
|
209
|
+
``global`` classification on a tie.
|
|
210
|
+
"""
|
|
211
|
+
votes: list[str] = []
|
|
212
|
+
if npm_winner in REGIONS:
|
|
213
|
+
votes.append(npm_winner)
|
|
214
|
+
if pypi_record is not None:
|
|
215
|
+
votes.append(pypi_record["region"])
|
|
216
|
+
if hub_record is not None:
|
|
217
|
+
votes.append(hub_record["region"])
|
|
218
|
+
if not votes:
|
|
219
|
+
return None
|
|
220
|
+
cn_votes = votes.count("cn")
|
|
221
|
+
global_votes = votes.count("global")
|
|
222
|
+
if cn_votes > global_votes:
|
|
223
|
+
return "cn"
|
|
224
|
+
if global_votes > cn_votes:
|
|
225
|
+
return "global"
|
|
226
|
+
# Tie (e.g., npm=global vs pypi=cn): prefer cn when a heavy ecosystem (PyPI or Model Hub)
|
|
227
|
+
# measured faster in China.
|
|
228
|
+
if (pypi_record and pypi_record["region"] == "cn") or (
|
|
229
|
+
hub_record and hub_record["region"] == "cn"
|
|
230
|
+
):
|
|
231
|
+
return "cn"
|
|
232
|
+
return npm_winner or "global"
|
|
233
|
+
|
|
234
|
+
|
|
100
235
|
def probe(env: Mapping[str, str]) -> str | None:
|
|
101
|
-
"""
|
|
236
|
+
"""Multi-signal concurrent speed probe across npm, PyPI, and Model Hub."""
|
|
102
237
|
pi = json.loads(TOOL_LOCK.read_text(encoding="utf-8"))["pi"]
|
|
103
|
-
|
|
238
|
+
npm_result: list[str | None] = [None]
|
|
239
|
+
pypi_result: list[EcosystemRecord | None] = [None]
|
|
240
|
+
hub_result: list[EcosystemRecord | None] = [None]
|
|
104
241
|
|
|
242
|
+
def run_npm() -> None:
|
|
243
|
+
npm_result[0] = npm_transport.race(pi["package"], pi["version"], env)
|
|
105
244
|
|
|
106
|
-
def
|
|
245
|
+
def run_pypi() -> None:
|
|
246
|
+
pypi_result[0] = mirrors.probe_ecosystem("pypi")
|
|
247
|
+
|
|
248
|
+
def run_hub() -> None:
|
|
249
|
+
hub_result[0] = mirrors.probe_ecosystem("model_hub")
|
|
250
|
+
|
|
251
|
+
threads = [
|
|
252
|
+
threading.Thread(target=run_npm, daemon=True),
|
|
253
|
+
threading.Thread(target=run_pypi, daemon=True),
|
|
254
|
+
threading.Thread(target=run_hub, daemon=True),
|
|
255
|
+
]
|
|
256
|
+
for thread in threads:
|
|
257
|
+
thread.start()
|
|
258
|
+
for thread in threads:
|
|
259
|
+
thread.join(timeout=6.0)
|
|
260
|
+
|
|
261
|
+
measured: dict[EcosystemName, EcosystemRecord] = {}
|
|
262
|
+
if pypi_result[0] is not None:
|
|
263
|
+
measured["pypi"] = pypi_result[0]
|
|
264
|
+
if hub_result[0] is not None:
|
|
265
|
+
measured["model_hub"] = hub_result[0]
|
|
266
|
+
if npm_result[0] in REGIONS:
|
|
267
|
+
side_val: Side = "cn" if npm_result[0] == "cn" else "global"
|
|
268
|
+
url = npm_transport.REGISTRIES[side_val]
|
|
269
|
+
other = npm_transport.REGISTRIES["global" if side_val == "cn" else "cn"]
|
|
270
|
+
measured["npm"] = {
|
|
271
|
+
"region": side_val,
|
|
272
|
+
"name": "npm-npmmirror" if side_val == "cn" else "npm-official",
|
|
273
|
+
"url": url,
|
|
274
|
+
"bytes_per_second": 0,
|
|
275
|
+
"candidates": [url, other],
|
|
276
|
+
"measured_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
|
|
277
|
+
"method": "probe",
|
|
278
|
+
}
|
|
279
|
+
if measured:
|
|
280
|
+
with _LOCK:
|
|
281
|
+
_ecosystems.update(measured)
|
|
282
|
+
return _combine_signals(npm_result[0], pypi_result[0], hub_result[0])
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def current_region(env: Mapping[str, str] | None = None) -> str:
|
|
107
286
|
"""This process's region, resolved on first use (see the module docstring)."""
|
|
108
287
|
global _resolved
|
|
109
|
-
|
|
110
|
-
explicit = forced(
|
|
288
|
+
active_env = os.environ if env is None else env
|
|
289
|
+
explicit = forced(active_env)
|
|
111
290
|
with _LOCK:
|
|
112
291
|
if explicit is not None:
|
|
113
292
|
if _resolved != explicit:
|
|
114
|
-
|
|
293
|
+
for name in [k for k, rec in _ecosystems.items() if rec["region"] != explicit]:
|
|
294
|
+
_ecosystems.pop(name, None)
|
|
295
|
+
found = saved(env=active_env)
|
|
115
296
|
if found is None or found["region"] != explicit:
|
|
116
|
-
save(explicit, "env")
|
|
297
|
+
save(explicit, "env", env=active_env)
|
|
298
|
+
elif found is not None:
|
|
299
|
+
_ecosystems.update(_parse_ecosystems(found.get("ecosystems")))
|
|
117
300
|
_resolved = explicit
|
|
118
301
|
return explicit
|
|
119
302
|
if _resolved is not None:
|
|
120
303
|
return _resolved
|
|
121
|
-
found = saved()
|
|
304
|
+
found = saved(env=active_env)
|
|
122
305
|
if found is not None:
|
|
306
|
+
_ecosystems.update(_parse_ecosystems(found.get("ecosystems")))
|
|
123
307
|
_resolved = found["region"]
|
|
124
308
|
return _resolved
|
|
125
|
-
winner = probe(
|
|
309
|
+
winner = probe(active_env)
|
|
126
310
|
with _LOCK:
|
|
127
311
|
if _resolved is None:
|
|
128
312
|
_resolved = winner or "global"
|
|
129
313
|
if winner is not None:
|
|
130
|
-
save(winner, "probe")
|
|
314
|
+
save(winner, "probe", ecosystems=dict(_ecosystems), env=active_env)
|
|
131
315
|
print(f"localmodels: download region {_resolved}", file=sys.stderr)
|
|
132
316
|
return _resolved
|
|
133
317
|
|
|
@@ -143,8 +327,10 @@ def fallback_to(region: str, env: MutableMapping[str, str] | None = None) -> Non
|
|
|
143
327
|
changed = _resolved != region or env.get(ENV) not in (None, "", "auto", region)
|
|
144
328
|
_resolved = region
|
|
145
329
|
env[ENV] = region
|
|
330
|
+
for name in [k for k, rec in _ecosystems.items() if rec["region"] != region]:
|
|
331
|
+
_ecosystems.pop(name, None)
|
|
146
332
|
if changed:
|
|
147
|
-
save(region, "fallback")
|
|
333
|
+
save(region, "fallback", env=env)
|
|
148
334
|
print(f"localmodels: download region switched to {region}", file=sys.stderr)
|
|
149
335
|
|
|
150
336
|
|
|
@@ -161,6 +347,76 @@ def prefer(region: str, global_sources: Sequence[T], cn_sources: Sequence[T]) ->
|
|
|
161
347
|
return [*first, *second]
|
|
162
348
|
|
|
163
349
|
|
|
350
|
+
def ecosystem_record(
|
|
351
|
+
ecosystem: EcosystemName,
|
|
352
|
+
env: Mapping[str, str] | None = None,
|
|
353
|
+
*,
|
|
354
|
+
allow_probe: bool = True,
|
|
355
|
+
) -> EcosystemRecord | None:
|
|
356
|
+
"""Return the cached or freshly speed-probed selection for ``ecosystem``."""
|
|
357
|
+
active_env = os.environ if env is None else env
|
|
358
|
+
explicit = forced(active_env)
|
|
359
|
+
with _LOCK:
|
|
360
|
+
cached = _ecosystems.get(ecosystem)
|
|
361
|
+
if cached is None:
|
|
362
|
+
doc = saved(env=active_env)
|
|
363
|
+
if doc is not None:
|
|
364
|
+
parsed = _parse_ecosystems(doc.get("ecosystems"))
|
|
365
|
+
with _LOCK:
|
|
366
|
+
_ecosystems.update(parsed)
|
|
367
|
+
cached = _ecosystems.get(ecosystem)
|
|
368
|
+
if cached is not None and (explicit is None or cached["region"] == explicit):
|
|
369
|
+
return cached
|
|
370
|
+
if not allow_probe:
|
|
371
|
+
return None
|
|
372
|
+
side_filter: Side | None = (
|
|
373
|
+
"cn" if explicit == "cn" else "global" if explicit == "global" else None
|
|
374
|
+
)
|
|
375
|
+
measured = mirrors.probe_ecosystem(ecosystem, side_filter=side_filter)
|
|
376
|
+
if measured is None:
|
|
377
|
+
return None
|
|
378
|
+
with _LOCK:
|
|
379
|
+
_ecosystems[ecosystem] = measured
|
|
380
|
+
reg = _resolved or explicit or measured["region"]
|
|
381
|
+
save(reg, "probe", ecosystems=dict(_ecosystems), env=active_env)
|
|
382
|
+
return measured
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def ecosystem_candidates(
|
|
386
|
+
ecosystem: EcosystemName, env: Mapping[str, str] | None = None
|
|
387
|
+
) -> list[str]:
|
|
388
|
+
"""Cached speed-ranked base URLs for ``ecosystem`` when available, else empty."""
|
|
389
|
+
record = ecosystem_record(ecosystem, env=env, allow_probe=False)
|
|
390
|
+
return list(record["candidates"]) if record is not None else []
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def order_urls_for_region(
|
|
394
|
+
url: str, global_urls: Sequence[str], cn_urls: Sequence[str]
|
|
395
|
+
) -> list[str]:
|
|
396
|
+
"""Order ``global_urls`` and ``cn_urls`` by active region and cached ecosystem speed rank."""
|
|
397
|
+
cn = list(cn_urls)
|
|
398
|
+
eco: EcosystemName | None = (
|
|
399
|
+
"node"
|
|
400
|
+
if url.startswith("https://nodejs.org/dist/")
|
|
401
|
+
else "pypi"
|
|
402
|
+
if url.startswith("https://files.pythonhosted.org/packages/")
|
|
403
|
+
else "npm"
|
|
404
|
+
if url.startswith("https://registry.npmjs.org/")
|
|
405
|
+
else None
|
|
406
|
+
)
|
|
407
|
+
if eco is not None and len(cn) > 1:
|
|
408
|
+
ranked = [mirrors.canonical_host(item) for item in ecosystem_candidates(eco)]
|
|
409
|
+
if ranked:
|
|
410
|
+
cn.sort(
|
|
411
|
+
key=lambda item: (
|
|
412
|
+
ranked.index(mirrors.canonical_host(item))
|
|
413
|
+
if mirrors.canonical_host(item) in ranked
|
|
414
|
+
else len(ranked)
|
|
415
|
+
)
|
|
416
|
+
)
|
|
417
|
+
return prefer(current_region(), global_urls, cn)
|
|
418
|
+
|
|
419
|
+
|
|
164
420
|
def side_of_endpoint(endpoint: str) -> str:
|
|
165
421
|
return "cn" if endpoint.rstrip("/") == HF_MIRROR else "global"
|
|
166
422
|
|
|
@@ -211,6 +467,23 @@ def _config_files(env: Mapping[str, str]) -> list[Path]:
|
|
|
211
467
|
return found
|
|
212
468
|
|
|
213
469
|
|
|
470
|
+
_TOML_INDEX_RE = re.compile(r"^\s*(?:index-url|default-index|index)\s*=", re.IGNORECASE)
|
|
471
|
+
_NPMRC_REGISTRY_RE = re.compile(r"^\s*registry\s*=", re.IGNORECASE)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _env_get_fold(env: Mapping[str, str], name: str) -> str:
|
|
475
|
+
direct = env.get(name, "").strip()
|
|
476
|
+
if direct:
|
|
477
|
+
return direct
|
|
478
|
+
target = name.lower()
|
|
479
|
+
for key in sorted(env):
|
|
480
|
+
if key.lower() == target:
|
|
481
|
+
value = env[key].strip()
|
|
482
|
+
if value:
|
|
483
|
+
return value
|
|
484
|
+
return ""
|
|
485
|
+
|
|
486
|
+
|
|
214
487
|
def _names_index(path: Path) -> bool:
|
|
215
488
|
try:
|
|
216
489
|
text = path.read_text(encoding="utf-8")
|
|
@@ -218,8 +491,9 @@ def _names_index(path: Path) -> bool:
|
|
|
218
491
|
return False
|
|
219
492
|
if path.suffix == ".toml":
|
|
220
493
|
return any(
|
|
221
|
-
line.strip().startswith(
|
|
494
|
+
line.strip().startswith("[[index]]") or bool(_TOML_INDEX_RE.match(line))
|
|
222
495
|
for line in text.splitlines()
|
|
496
|
+
if not line.lstrip().startswith("#")
|
|
223
497
|
)
|
|
224
498
|
parser = configparser.ConfigParser(interpolation=None)
|
|
225
499
|
try:
|
|
@@ -230,15 +504,156 @@ def _names_index(path: Path) -> bool:
|
|
|
230
504
|
|
|
231
505
|
|
|
232
506
|
def user_index_configured(env: Mapping[str, str]) -> bool:
|
|
233
|
-
if any(env
|
|
507
|
+
if any(_env_get_fold(env, name) for name in INDEX_VARIABLES):
|
|
234
508
|
return True
|
|
235
509
|
return any(_names_index(path) for path in _config_files(env))
|
|
236
510
|
|
|
237
511
|
|
|
512
|
+
def _npmrc_paths(env: Mapping[str, str]) -> list[Path]:
|
|
513
|
+
paths: list[Path] = []
|
|
514
|
+
custom = _env_get_fold(env, "NPM_CONFIG_USERCONFIG")
|
|
515
|
+
if custom and custom != os.devnull:
|
|
516
|
+
paths.append(Path(custom).expanduser())
|
|
517
|
+
home_val = _env_get_fold(env, "HOME") or _env_get_fold(env, "USERPROFILE")
|
|
518
|
+
if home_val:
|
|
519
|
+
paths.append(Path(home_val).expanduser() / ".npmrc")
|
|
520
|
+
return paths
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _names_npm_registry(path: Path) -> bool:
|
|
524
|
+
try:
|
|
525
|
+
text = path.read_text(encoding="utf-8")
|
|
526
|
+
except (OSError, UnicodeError):
|
|
527
|
+
return False
|
|
528
|
+
for line in text.splitlines():
|
|
529
|
+
stripped = line.strip()
|
|
530
|
+
if not stripped or stripped.startswith(("#", ";")):
|
|
531
|
+
continue
|
|
532
|
+
if _NPMRC_REGISTRY_RE.match(line):
|
|
533
|
+
return True
|
|
534
|
+
return False
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def user_npm_configured(env: Mapping[str, str]) -> bool:
|
|
538
|
+
if _env_get_fold(env, "npm_config_registry") or _env_get_fold(env, "pnpm_config_registry"):
|
|
539
|
+
return True
|
|
540
|
+
return any(_names_npm_registry(path) for path in _npmrc_paths(env))
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def select_pypi_index(env: Mapping[str, str]) -> str | None:
|
|
544
|
+
"""Fastest PyPI index URL to inject for pip/uv, or None when official PyPI should be used."""
|
|
545
|
+
explicit = forced(env)
|
|
546
|
+
if explicit == "global":
|
|
547
|
+
return None
|
|
548
|
+
reg = explicit if explicit is not None else current_region(env)
|
|
549
|
+
record = ecosystem_record("pypi", env=env, allow_probe=True)
|
|
550
|
+
if explicit == "cn":
|
|
551
|
+
if record is not None and record["region"] == "cn":
|
|
552
|
+
return record["url"]
|
|
553
|
+
cn_record = mirrors.probe_ecosystem("pypi", side_filter="cn")
|
|
554
|
+
if cn_record is not None:
|
|
555
|
+
with _LOCK:
|
|
556
|
+
_ecosystems["pypi"] = cn_record
|
|
557
|
+
save("cn", "probe", ecosystems=dict(_ecosystems), env=env)
|
|
558
|
+
return cn_record["url"]
|
|
559
|
+
return PYPI_MIRROR
|
|
560
|
+
if record is not None:
|
|
561
|
+
return record["url"] if record["region"] == "cn" else None
|
|
562
|
+
return PYPI_MIRROR if reg == "cn" else None
|
|
563
|
+
|
|
564
|
+
|
|
238
565
|
def pip_environment(env: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
239
|
-
"""The environment for a hash-locked pip or uv install:
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
566
|
+
"""The environment for a hash-locked pip or uv install: chooses the fastest speed-tested
|
|
567
|
+
PyPI index (Tsinghua, Aliyun, USTC, Tencent, or official) unless the user configured one.
|
|
568
|
+
The lock's hashes still decide what installs."""
|
|
569
|
+
result = dict(os.environ if env is None else env)
|
|
570
|
+
if user_index_configured(result):
|
|
571
|
+
return result
|
|
572
|
+
chosen = select_pypi_index(result)
|
|
573
|
+
if chosen:
|
|
574
|
+
result.update(PIP_INDEX_URL=chosen, UV_DEFAULT_INDEX=chosen)
|
|
575
|
+
return result
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def _pick_cn_url(
|
|
579
|
+
ecosystem: EcosystemName,
|
|
580
|
+
reg: str,
|
|
581
|
+
env: Mapping[str, str],
|
|
582
|
+
*,
|
|
583
|
+
allow_probe: bool,
|
|
584
|
+
) -> str | None:
|
|
585
|
+
rec = ecosystem_record(ecosystem, env=env, allow_probe=allow_probe)
|
|
586
|
+
if rec is not None:
|
|
587
|
+
return rec["url"] if rec["region"] == "cn" else None
|
|
588
|
+
return mirrors.default_cn_url(ecosystem) if reg == "cn" else None
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def _apply_homebrew_env(
|
|
592
|
+
result: dict[str, str],
|
|
593
|
+
reg: str,
|
|
594
|
+
*,
|
|
595
|
+
allow_probe: bool,
|
|
596
|
+
) -> None:
|
|
597
|
+
if (
|
|
598
|
+
sys.platform != "darwin"
|
|
599
|
+
or _env_get_fold(result, "HOMEBREW_API_DOMAIN")
|
|
600
|
+
or _env_get_fold(result, "HOMEBREW_BOTTLE_DOMAIN")
|
|
601
|
+
):
|
|
602
|
+
return
|
|
603
|
+
brew_url = _pick_cn_url("homebrew", reg, result, allow_probe=allow_probe)
|
|
604
|
+
if not brew_url:
|
|
605
|
+
return
|
|
606
|
+
result["HOMEBREW_API_DOMAIN"] = brew_url
|
|
607
|
+
host = mirrors.canonical_host(brew_url)
|
|
608
|
+
if host == "mirrors.tuna.tsinghua.edu.cn":
|
|
609
|
+
result["HOMEBREW_BOTTLE_DOMAIN"] = "https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles"
|
|
610
|
+
elif host == "mirrors.ustc.edu.cn":
|
|
611
|
+
result["HOMEBREW_BOTTLE_DOMAIN"] = "https://mirrors.ustc.edu.cn/homebrew-bottles"
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _format_goproxy(primary: str) -> str:
|
|
615
|
+
chain = [primary]
|
|
616
|
+
for fallback in ("https://goproxy.cn", "https://goproxy.io"):
|
|
617
|
+
if fallback not in chain:
|
|
618
|
+
chain.append(fallback)
|
|
619
|
+
return "|".join([*chain, "direct"])
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def language_environment(
|
|
623
|
+
env: Mapping[str, str] | None = None,
|
|
624
|
+
*,
|
|
625
|
+
allow_probe: bool = False,
|
|
626
|
+
) -> dict[str, str]:
|
|
627
|
+
"""Build mirror environment variables across Python, npm, Go, Rust, and Model Hub.
|
|
628
|
+
|
|
629
|
+
Respects every user-configured variable and config file (never overwrites them) and defaults
|
|
630
|
+
to cached speed-test results (``allow_probe=False``) so callers on hot paths add zero RTT.
|
|
631
|
+
"""
|
|
632
|
+
result = dict(os.environ if env is None else env)
|
|
633
|
+
explicit = forced(result)
|
|
634
|
+
if explicit == "global":
|
|
635
|
+
return result
|
|
636
|
+
reg = explicit or current_region(result)
|
|
637
|
+
|
|
638
|
+
if not user_index_configured(result):
|
|
639
|
+
if pypi_url := _pick_cn_url("pypi", reg, result, allow_probe=allow_probe):
|
|
640
|
+
result["PIP_INDEX_URL"] = pypi_url
|
|
641
|
+
result["UV_DEFAULT_INDEX"] = pypi_url
|
|
642
|
+
if not user_npm_configured(result):
|
|
643
|
+
if npm_url := _pick_cn_url("npm", reg, result, allow_probe=allow_probe):
|
|
644
|
+
result["npm_config_registry"] = npm_url
|
|
645
|
+
result["pnpm_config_registry"] = npm_url
|
|
646
|
+
if not _env_get_fold(result, "GOPROXY"):
|
|
647
|
+
if go_url := _pick_cn_url("go", reg, result, allow_probe=allow_probe):
|
|
648
|
+
result["GOPROXY"] = _format_goproxy(go_url)
|
|
649
|
+
if not _env_get_fold(result, "RUSTUP_DIST_SERVER") and not _env_get_fold(
|
|
650
|
+
result, "RUSTUP_UPDATE_ROOT"
|
|
651
|
+
):
|
|
652
|
+
if rust_url := _pick_cn_url("rust", reg, result, allow_probe=allow_probe):
|
|
653
|
+
result["RUSTUP_DIST_SERVER"] = rust_url
|
|
654
|
+
result["RUSTUP_UPDATE_ROOT"] = rust_url.rstrip("/") + "/rustup"
|
|
655
|
+
if not _env_get_fold(result, "HF_ENDPOINT"):
|
|
656
|
+
if _pick_cn_url("model_hub", reg, result, allow_probe=allow_probe) is not None:
|
|
657
|
+
result["HF_ENDPOINT"] = HF_MIRROR
|
|
658
|
+
_apply_homebrew_env(result, reg, allow_probe=allow_probe)
|
|
659
|
+
return result
|