@simplexai/localmodels-linux-x64 0.1.0-dev.38 → 0.1.0-dev.39
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 +60 -54
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +4 -0
- package/modules/localmodels/bifrost_config.py +19 -0
- package/modules/localmodels/catalog.json +18 -6
- package/modules/localmodels/cli_parser.py +26 -3
- package/modules/localmodels/deploy.py +37 -9
- package/modules/localmodels/deploy_steps.py +6 -3
- package/modules/localmodels/download-mirrors.json +52 -4
- package/modules/localmodels/engines-b11583.json +20 -4
- package/modules/localmodels/engines-b12167.json +5 -1
- package/modules/localmodels/engines-strata-0.1.47.json +5 -1
- package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
- package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
- package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
- package/modules/localmodels/engines-whisper-b5454.json +5 -1
- package/modules/localmodels/engines.json +55 -11
- package/modules/localmodels/frontend.py +5 -2
- package/modules/localmodels/guard.py +15 -6
- package/modules/localmodels/harness.py +65 -33
- package/modules/localmodels/harness_gateway.py +9 -3
- package/modules/localmodels/hf_repo.py +15 -8
- package/modules/localmodels/library_gateway.py +15 -13
- package/modules/localmodels/metal_probe.py +16 -6
- package/modules/localmodels/npm_signatures.py +131 -0
- package/modules/localmodels/npm_transport.py +26 -10
- package/modules/localmodels/process_identity.py +21 -5
- package/modules/localmodels/region.py +244 -0
- package/modules/localmodels/remote_ops.py +69 -13
- package/modules/localmodels/remote_ops_download.py +210 -10
- package/modules/localmodels/remote_ops_prepare.py +61 -8
- package/modules/localmodels/runtime-lock.json +13 -13
- package/modules/localmodels/runtime_args.py +4 -2
- package/modules/localmodels/runtime_cli.py +19 -37
- package/modules/localmodels/runtime_discovery.py +30 -0
- package/modules/localmodels/runtime_install.py +81 -6
- package/modules/localmodels/runtime_io.py +61 -5
- package/modules/localmodels/runtime_pi.py +79 -0
- package/modules/localmodels/runtime_process.py +99 -15
- package/modules/localmodels/runtime_releases.py +51 -71
- package/modules/localmodels/service_probe.py +62 -4
- package/modules/localmodels/setup_inspection.py +21 -4
- package/modules/localmodels/setup_text.py +6 -0
- package/modules/localmodels/source_byok.py +484 -0
- package/modules/localmodels/source_byok_probe.py +275 -0
- package/modules/localmodels/source_cli.py +426 -0
- package/modules/localmodels/stack_args.py +2 -1
- package/modules/localmodels/stack_binding.py +47 -4
- package/modules/localmodels/stack_events.py +3 -0
- package/modules/localmodels/stack_hardware.py +17 -3
- package/modules/localmodels/tools.json +1364 -14
- package/modules/localmodels/transport.py +2 -0
- package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/RECORD +57 -51
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""The network region every download orders its sources by: ``cn`` (mainland China) or ``global``.
|
|
2
|
+
|
|
3
|
+
One process resolves it once, lazily, the first time something is about to be downloaded:
|
|
4
|
+
|
|
5
|
+
1. ``SIMPLEX_REGION`` (or the CLI's ``--region``, which sets it) when it is ``cn`` or ``global``;
|
|
6
|
+
``auto`` or unset means not forced. Linger passes the region it resolved this way.
|
|
7
|
+
2. ``$LOCALMODELS_STATE/region.json`` when it is younger than STALE_AFTER.
|
|
8
|
+
3. A probe: the same 256 KiB race of registry.npmjs.org against registry.npmmirror.com that
|
|
9
|
+
``npm_transport`` runs (5 s, the first to finish wins; both failing gives global, unsaved).
|
|
10
|
+
|
|
11
|
+
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 and
|
|
13
|
+
whose other side then succeeded switches the region (``fallback_to``) and rewrites region.json
|
|
14
|
+
with ``method: fallback``. The file schema is shared with Linger, which writes the same document
|
|
15
|
+
in its own home.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import configparser
|
|
21
|
+
import datetime as dt
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import sys
|
|
25
|
+
import threading
|
|
26
|
+
from collections.abc import Mapping, MutableMapping, Sequence
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import TypeVar
|
|
29
|
+
|
|
30
|
+
from localmodels import npm_transport
|
|
31
|
+
|
|
32
|
+
SCHEMA = "simplex.region/v1"
|
|
33
|
+
REGIONS = ("global", "cn")
|
|
34
|
+
ENV = "SIMPLEX_REGION"
|
|
35
|
+
STALE_AFTER = dt.timedelta(days=7)
|
|
36
|
+
HF_API = "https://huggingface.co"
|
|
37
|
+
HF_MIRROR = "https://hf-mirror.com"
|
|
38
|
+
PYPI_MIRROR = "https://mirrors.aliyun.com/pypi/simple/"
|
|
39
|
+
# A user's own Python index wins over the region: any of these variables, or an index in a pip
|
|
40
|
+
# or uv configuration file, leaves pip and uv as they are.
|
|
41
|
+
INDEX_VARIABLES = ("PIP_INDEX_URL", "UV_DEFAULT_INDEX", "UV_INDEX_URL", "UV_INDEX")
|
|
42
|
+
TOOL_LOCK = Path(__file__).with_name("tools.json")
|
|
43
|
+
|
|
44
|
+
T = TypeVar("T")
|
|
45
|
+
_LOCK = threading.Lock()
|
|
46
|
+
_resolved: str | None = None # this process's region once known (fallback included)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def forced(env: Mapping[str, str]) -> str | None:
|
|
50
|
+
"""``cn`` or ``global`` when the environment names one; None for auto or unset."""
|
|
51
|
+
value = (env.get(ENV) or "auto").strip()
|
|
52
|
+
if value not in ("auto", *REGIONS):
|
|
53
|
+
raise ValueError(f"{ENV} must be auto, global or cn")
|
|
54
|
+
return None if value == "auto" else value
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def region_path() -> Path:
|
|
58
|
+
state = os.environ.get("LOCALMODELS_STATE", "~/.local/state/localmodels")
|
|
59
|
+
return Path(state).expanduser() / "region.json"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def saved(now: dt.datetime | None = None) -> dict[str, str] | None:
|
|
63
|
+
"""The saved region document when it is valid and younger than STALE_AFTER."""
|
|
64
|
+
try:
|
|
65
|
+
doc = json.loads(region_path().read_text(encoding="utf-8"))
|
|
66
|
+
when = dt.datetime.fromisoformat(str(doc["resolved_at"]).replace("Z", "+00:00"))
|
|
67
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
68
|
+
return None
|
|
69
|
+
if (
|
|
70
|
+
not isinstance(doc, dict)
|
|
71
|
+
or doc.get("schema") != SCHEMA
|
|
72
|
+
or doc.get("region") not in REGIONS
|
|
73
|
+
or when.tzinfo is None
|
|
74
|
+
):
|
|
75
|
+
return None
|
|
76
|
+
age = (now or dt.datetime.now(dt.timezone.utc)) - when
|
|
77
|
+
return doc if dt.timedelta(0) <= age <= STALE_AFTER else None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def save(region: str, method: str) -> None:
|
|
81
|
+
"""Write region.json owner-only and atomically; a state directory that cannot be written
|
|
82
|
+
costs only the next run a probe."""
|
|
83
|
+
doc = {
|
|
84
|
+
"schema": SCHEMA,
|
|
85
|
+
"region": region,
|
|
86
|
+
"resolved_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
|
|
87
|
+
"method": method,
|
|
88
|
+
}
|
|
89
|
+
path = region_path()
|
|
90
|
+
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
|
91
|
+
try:
|
|
92
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
93
|
+
tmp.touch(0o600)
|
|
94
|
+
tmp.write_text(json.dumps(doc) + "\n", encoding="utf-8")
|
|
95
|
+
tmp.replace(path)
|
|
96
|
+
except OSError:
|
|
97
|
+
tmp.unlink(missing_ok=True)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def probe(env: Mapping[str, str]) -> str | None:
|
|
101
|
+
"""The faster npm registry for the pinned pi tarball, or None when neither answered."""
|
|
102
|
+
pi = json.loads(TOOL_LOCK.read_text(encoding="utf-8"))["pi"]
|
|
103
|
+
return npm_transport.race(pi["package"], pi["version"], env)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def current_region(env: MutableMapping[str, str] | None = None) -> str:
|
|
107
|
+
"""This process's region, resolved on first use (see the module docstring)."""
|
|
108
|
+
global _resolved
|
|
109
|
+
env = os.environ if env is None else env
|
|
110
|
+
explicit = forced(env)
|
|
111
|
+
with _LOCK:
|
|
112
|
+
if explicit is not None:
|
|
113
|
+
if _resolved != explicit:
|
|
114
|
+
found = saved()
|
|
115
|
+
if found is None or found["region"] != explicit:
|
|
116
|
+
save(explicit, "env")
|
|
117
|
+
_resolved = explicit
|
|
118
|
+
return explicit
|
|
119
|
+
if _resolved is not None:
|
|
120
|
+
return _resolved
|
|
121
|
+
found = saved()
|
|
122
|
+
if found is not None:
|
|
123
|
+
_resolved = found["region"]
|
|
124
|
+
return _resolved
|
|
125
|
+
winner = probe(env)
|
|
126
|
+
with _LOCK:
|
|
127
|
+
if _resolved is None:
|
|
128
|
+
_resolved = winner or "global"
|
|
129
|
+
if winner is not None:
|
|
130
|
+
save(winner, "probe")
|
|
131
|
+
print(f"localmodels: download region {_resolved}", file=sys.stderr)
|
|
132
|
+
return _resolved
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def fallback_to(region: str, env: MutableMapping[str, str] | None = None) -> None:
|
|
136
|
+
"""The other side served what the preferred side could not: use it from now on, here, in
|
|
137
|
+
child processes (``SIMPLEX_REGION``) and in later runs (region.json)."""
|
|
138
|
+
global _resolved
|
|
139
|
+
if region not in REGIONS:
|
|
140
|
+
return
|
|
141
|
+
env = os.environ if env is None else env
|
|
142
|
+
with _LOCK:
|
|
143
|
+
changed = _resolved != region or env.get(ENV) not in (None, "", "auto", region)
|
|
144
|
+
_resolved = region
|
|
145
|
+
env[ENV] = region
|
|
146
|
+
if changed:
|
|
147
|
+
save(region, "fallback")
|
|
148
|
+
print(f"localmodels: download region switched to {region}", file=sys.stderr)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def observe(event: Mapping[str, object]) -> None:
|
|
152
|
+
"""A remote_ops event that reports a region fallback (``region_fallback``) applies it."""
|
|
153
|
+
side = event.get("region_fallback")
|
|
154
|
+
if isinstance(side, str):
|
|
155
|
+
fallback_to(side)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def prefer(region: str, global_sources: Sequence[T], cn_sources: Sequence[T]) -> list[T]:
|
|
159
|
+
"""Every source, the region's own side first."""
|
|
160
|
+
first, second = (cn_sources, global_sources) if region == "cn" else (global_sources, cn_sources)
|
|
161
|
+
return [*first, *second]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def side_of_endpoint(endpoint: str) -> str:
|
|
165
|
+
return "cn" if endpoint.rstrip("/") == HF_MIRROR else "global"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def explicit_hub(api: str) -> bool:
|
|
169
|
+
"""The user named this Hub (``--hf-endpoint`` other than the default, or ``HF_ENDPOINT``):
|
|
170
|
+
their own trust choice, used alone and allowed to mint SHA256 pins."""
|
|
171
|
+
return api.rstrip("/") != HF_API or bool(os.environ.get("HF_ENDPOINT", "").strip())
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def hub_endpoints(api: str) -> list[str]:
|
|
175
|
+
"""The Hub endpoints to ask, in order, for lookups whose answer is checked against a pin
|
|
176
|
+
(or carries none). A user's own endpoint is the only one; the default Hugging Face gets
|
|
177
|
+
hf-mirror.com beside it, first in cn. A SHA256 pin is never minted from hf-mirror.com:
|
|
178
|
+
such lookups use ``api`` alone (deploy.hub_get ``mint``)."""
|
|
179
|
+
if explicit_hub(api):
|
|
180
|
+
return [api.rstrip("/")]
|
|
181
|
+
return prefer(current_region(), [HF_API], [HF_MIRROR])
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
MINT_REFUSAL = (
|
|
185
|
+
"cannot reach huggingface.co to pin {what}: SHA256 pins for files the catalog does not pin "
|
|
186
|
+
"come only from huggingface.co (hf-mirror.com may serve the bytes, never the pins); pass "
|
|
187
|
+
"--hf-endpoint URL or set HF_ENDPOINT to trust another Hub, or choose a catalog model"
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _config_files(env: Mapping[str, str]) -> list[Path]:
|
|
192
|
+
home = Path(env.get("HOME") or env.get("USERPROFILE") or "~").expanduser()
|
|
193
|
+
xdg = Path(env.get("XDG_CONFIG_HOME") or home / ".config")
|
|
194
|
+
appdata = Path(env["APPDATA"]) if env.get("APPDATA") else None
|
|
195
|
+
found = [
|
|
196
|
+
Path(env[name])
|
|
197
|
+
for name in ("PIP_CONFIG_FILE", "UV_CONFIG_FILE")
|
|
198
|
+
if env.get(name) and env[name] != os.devnull
|
|
199
|
+
]
|
|
200
|
+
found += [
|
|
201
|
+
home / ".pip" / "pip.conf",
|
|
202
|
+
xdg / "pip" / "pip.conf",
|
|
203
|
+
home / "Library" / "Application Support" / "pip" / "pip.conf",
|
|
204
|
+
Path("/etc/pip.conf"),
|
|
205
|
+
Path("/etc/xdg/pip/pip.conf"),
|
|
206
|
+
xdg / "uv" / "uv.toml",
|
|
207
|
+
Path("/etc/uv/uv.toml"),
|
|
208
|
+
]
|
|
209
|
+
if appdata is not None:
|
|
210
|
+
found += [appdata / "pip" / "pip.ini", appdata / "uv" / "uv.toml"]
|
|
211
|
+
return found
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _names_index(path: Path) -> bool:
|
|
215
|
+
try:
|
|
216
|
+
text = path.read_text(encoding="utf-8")
|
|
217
|
+
except (OSError, UnicodeError):
|
|
218
|
+
return False
|
|
219
|
+
if path.suffix == ".toml":
|
|
220
|
+
return any(
|
|
221
|
+
line.strip().startswith(("index-url", "default-index", "[[index]]", "index ="))
|
|
222
|
+
for line in text.splitlines()
|
|
223
|
+
)
|
|
224
|
+
parser = configparser.ConfigParser(interpolation=None)
|
|
225
|
+
try:
|
|
226
|
+
parser.read_string(text)
|
|
227
|
+
except configparser.Error:
|
|
228
|
+
return True # unreadable to us, but pip may read it: leave it alone
|
|
229
|
+
return any(parser.has_option(section, "index-url") for section in parser.sections())
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def user_index_configured(env: Mapping[str, str]) -> bool:
|
|
233
|
+
if any(env.get(name, "").strip() for name in INDEX_VARIABLES):
|
|
234
|
+
return True
|
|
235
|
+
return any(_names_index(path) for path in _config_files(env))
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def pip_environment(env: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
239
|
+
"""The environment for a hash-locked pip or uv install: in cn, without an index of the
|
|
240
|
+
user's own, the Alibaba Cloud PyPI mirror. The lock's hashes still decide what installs."""
|
|
241
|
+
env = dict(os.environ if env is None else env)
|
|
242
|
+
if not user_index_configured(env) and current_region() == "cn":
|
|
243
|
+
env.update(PIP_INDEX_URL=PYPI_MIRROR, UV_DEFAULT_INDEX=PYPI_MIRROR)
|
|
244
|
+
return env
|
|
@@ -22,6 +22,7 @@ from __future__ import annotations
|
|
|
22
22
|
import base64
|
|
23
23
|
import contextlib
|
|
24
24
|
import hashlib
|
|
25
|
+
import ipaddress
|
|
25
26
|
import json
|
|
26
27
|
import os
|
|
27
28
|
import shutil
|
|
@@ -31,6 +32,7 @@ import sys
|
|
|
31
32
|
import tarfile
|
|
32
33
|
import time
|
|
33
34
|
import urllib.error
|
|
35
|
+
import urllib.parse
|
|
34
36
|
import urllib.request
|
|
35
37
|
import zipfile
|
|
36
38
|
from collections.abc import Callable, Iterator
|
|
@@ -57,11 +59,15 @@ except ImportError: # run as a bare file; the siblings sit in this directory
|
|
|
57
59
|
import remote_ops_verify # type: ignore[import-not-found,no-redef]
|
|
58
60
|
|
|
59
61
|
|
|
60
|
-
class
|
|
61
|
-
source: str # public label: huggingface, modelscope or custom
|
|
62
|
+
class _Source(TypedDict):
|
|
63
|
+
source: str # public label: huggingface, hf-mirror, modelscope, npm, npmmirror or custom
|
|
62
64
|
url: str
|
|
63
65
|
|
|
64
66
|
|
|
67
|
+
class Source(_Source, total=False):
|
|
68
|
+
member: str # an npm package holding the file: its path inside the package tarball
|
|
69
|
+
|
|
70
|
+
|
|
65
71
|
class Download(TypedDict):
|
|
66
72
|
url: str
|
|
67
73
|
dest: str
|
|
@@ -75,13 +81,22 @@ class Reusable(Download, total=False):
|
|
|
75
81
|
generated: bool # a pinned output materialized by the approved preparation descriptor
|
|
76
82
|
|
|
77
83
|
|
|
78
|
-
class
|
|
84
|
+
class NpmCopy(TypedDict):
|
|
85
|
+
package: str # an npm package whose file ``name`` is this archive, byte for byte
|
|
86
|
+
version: str
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class _Archive(TypedDict):
|
|
79
90
|
name: str
|
|
80
91
|
url: str
|
|
81
92
|
sha256: str
|
|
82
93
|
size_bytes: int
|
|
83
94
|
|
|
84
95
|
|
|
96
|
+
class Archive(_Archive, total=False):
|
|
97
|
+
npm_copy: NpmCopy
|
|
98
|
+
|
|
99
|
+
|
|
85
100
|
class ServiceParams(TypedDict): # all start, stop and status need; the base of the rest
|
|
86
101
|
deploy_dir: str
|
|
87
102
|
service: str
|
|
@@ -97,6 +112,7 @@ class _Engine(TypedDict):
|
|
|
97
112
|
|
|
98
113
|
class EngineParams(_Engine, total=False):
|
|
99
114
|
binary: str # the executable the engine archive must contain (default llama-server)
|
|
115
|
+
region: str # cn or global: the order of the download sources (region.py)
|
|
100
116
|
|
|
101
117
|
|
|
102
118
|
class StrataPreparation(TypedDict):
|
|
@@ -119,6 +135,7 @@ class _DownloadParams(TypedDict):
|
|
|
119
135
|
|
|
120
136
|
class DownloadParams(_DownloadParams, total=False):
|
|
121
137
|
preparation: StrataPreparation
|
|
138
|
+
region: str # cn or global: the order of the download sources (region.py)
|
|
122
139
|
|
|
123
140
|
|
|
124
141
|
class _Install(ServiceParams):
|
|
@@ -242,6 +259,24 @@ def _home(value: str) -> str:
|
|
|
242
259
|
return os.path.expanduser(value) if value.startswith("~/") else value
|
|
243
260
|
|
|
244
261
|
|
|
262
|
+
PRIVATE_SUFFIXES = (".local", ".lan", ".internal", ".intranet", ".corp", ".home.arpa")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def non_public(url: str) -> bool:
|
|
266
|
+
"""A source that is not on the public internet: plain http, an IP literal in a private,
|
|
267
|
+
loopback or link-local range, or a single-label or private-suffix host name. Such a source
|
|
268
|
+
(a LAN registry, a user's own mirror) is never republished and is tried first, being near."""
|
|
269
|
+
parts = urllib.parse.urlsplit(url)
|
|
270
|
+
host = (parts.hostname or "").lower()
|
|
271
|
+
if parts.scheme != "https" or not host:
|
|
272
|
+
return True
|
|
273
|
+
try:
|
|
274
|
+
address = ipaddress.ip_address(host)
|
|
275
|
+
except ValueError:
|
|
276
|
+
return "." not in host or host.endswith(PRIVATE_SUFFIXES)
|
|
277
|
+
return not address.is_global
|
|
278
|
+
|
|
279
|
+
|
|
245
280
|
def _expand(path: str) -> str:
|
|
246
281
|
return os.path.abspath(os.path.expanduser(path))
|
|
247
282
|
|
|
@@ -349,20 +384,24 @@ def fetch(
|
|
|
349
384
|
size: int,
|
|
350
385
|
label: str,
|
|
351
386
|
mirrors: list[Source] | None = None,
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
387
|
+
region: str | None = None,
|
|
388
|
+
) -> str | None:
|
|
389
|
+
"""Download ``url`` (or another source of the same pinned bytes: ``mirrors`` and, given a
|
|
390
|
+
``region``, the alternates that region adds) to ``dest`` unless a verified copy exists.
|
|
391
|
+
Resumes a .part file, from any source. Returns the region to switch to when the region's
|
|
392
|
+
own side failed and the other side served the file (also reported as ``region_fallback``
|
|
393
|
+
on the log event), else None."""
|
|
355
394
|
marker = dest + ".sha256"
|
|
356
395
|
if os.path.exists(dest) and os.path.exists(marker) and _read(marker).strip() == sha256:
|
|
357
396
|
emit("log", message="verified, skipping " + label)
|
|
358
|
-
return
|
|
397
|
+
return None
|
|
359
398
|
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
|
360
399
|
if os.path.exists(dest) and os.path.getsize(dest) == size and _sha256(dest, label) == sha256:
|
|
361
400
|
_write(marker, sha256)
|
|
362
401
|
_store_cached(dest, sha256, size)
|
|
363
|
-
return
|
|
402
|
+
return None
|
|
364
403
|
if _restore_cached(dest, sha256, size, label):
|
|
365
|
-
return
|
|
404
|
+
return None
|
|
366
405
|
free = shutil.disk_usage(os.path.dirname(dest)).free
|
|
367
406
|
part = dest + ".part"
|
|
368
407
|
have = remote_ops_download.kept_bytes(part, size)
|
|
@@ -374,12 +413,17 @@ def fetch(
|
|
|
374
413
|
sources: list[Source] = [{"source": remote_ops_download.source_name(url), "url": url}]
|
|
375
414
|
sources += [m for m in mirrors or [] if m.get("url") and m["url"] != url]
|
|
376
415
|
error: Exception | None = None
|
|
377
|
-
|
|
416
|
+
failed: list[Source] = []
|
|
417
|
+
for source, ranged in remote_ops_download.ordered(sources, size, label, region, failed):
|
|
378
418
|
try:
|
|
379
|
-
|
|
419
|
+
if source.get("member"):
|
|
420
|
+
remote_ops_download.npm_transfer(source, part, size, label)
|
|
421
|
+
else:
|
|
422
|
+
remote_ops_download.transfer(source, part, size, label, ranged)
|
|
380
423
|
except Exception as exc: # noqa: BLE001 - the next source is tried, the last re-raised
|
|
381
424
|
emit("log", message=f"download from {source['source']} stopped, {label}: {exc}")
|
|
382
425
|
error = exc
|
|
426
|
+
failed.append(source)
|
|
383
427
|
continue
|
|
384
428
|
if os.path.getsize(part) != size:
|
|
385
429
|
error = RuntimeError(f"{label} size mismatch: {os.path.getsize(part)} != {size}")
|
|
@@ -395,11 +439,23 @@ def fetch(
|
|
|
395
439
|
os.replace(part, dest)
|
|
396
440
|
_write(marker, sha256)
|
|
397
441
|
_store_cached(dest, sha256, size)
|
|
398
|
-
|
|
399
|
-
|
|
442
|
+
switch = _fallback(region, source, failed)
|
|
443
|
+
extra = {"region_fallback": switch} if switch else {}
|
|
444
|
+
emit("log", message=f"downloaded and verified {label} from {source['source']}", **extra)
|
|
445
|
+
return switch
|
|
400
446
|
raise error or RuntimeError(f"{label} has no download source")
|
|
401
447
|
|
|
402
448
|
|
|
449
|
+
def _fallback(region: str | None, used: Source, failed: list[Source]) -> str | None:
|
|
450
|
+
"""The other region, when ``used`` is on its side and a source on the region's own side
|
|
451
|
+
failed first; a neutral source (GitHub, a LAN or user mirror) never switches."""
|
|
452
|
+
other = remote_ops_download.side(used["url"])
|
|
453
|
+
if region not in ("cn", "global") or other in ("", region):
|
|
454
|
+
return None
|
|
455
|
+
mine = [s for s in failed if remote_ops_download.side(s["url"]) == region]
|
|
456
|
+
return other if mine else None
|
|
457
|
+
|
|
458
|
+
|
|
403
459
|
def _relative(name: str) -> str:
|
|
404
460
|
while name.startswith("./"):
|
|
405
461
|
name = name[2:]
|