@simplexai/localmodels-linux-arm64 0.1.0-dev.60 → 0.1.0-dev.62
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 +78 -64
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +5 -3
- package/modules/localmodels/auth_proxy.py +185 -19
- package/modules/localmodels/catalog.json +363 -0
- package/modules/localmodels/catalog.py +1 -1
- package/modules/localmodels/catalog_add.py +5 -5
- package/modules/localmodels/catalog_license.py +2 -0
- package/modules/localmodels/catalog_recipes.py +2 -0
- package/modules/localmodels/cli_parser.py +6 -2
- package/modules/localmodels/context_policy.py +40 -4
- package/modules/localmodels/custom_hub_http.py +27 -104
- package/modules/localmodels/debug_mode.py +13 -0
- package/modules/localmodels/debug_stub_server.py +156 -1
- package/modules/localmodels/deploy.py +11 -2
- package/modules/localmodels/download-mirrors.json +12 -0
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
- package/modules/localmodels/engines-whisper-b5454.json +120 -1
- package/modules/localmodels/gateway_app_bifrost.py +14 -14
- package/modules/localmodels/gateway_bifrost.py +4 -1
- package/modules/localmodels/gateway_cli.py +14 -80
- package/modules/localmodels/gateway_server.py +88 -16
- package/modules/localmodels/gpu_specs.py +35 -1
- package/modules/localmodels/harness.py +1 -2
- package/modules/localmodels/hf_repo.py +12 -4
- package/modules/localmodels/install.py +4 -4
- package/modules/localmodels/library_jobs.py +4 -0
- package/modules/localmodels/library_serve.py +69 -13
- package/modules/localmodels/memcalc_load.py +9 -4
- package/modules/localmodels/npm_transport.py +4 -58
- package/modules/localmodels/recommend_cli.py +2 -1
- package/modules/localmodels/remote_ops.py +120 -713
- package/modules/localmodels/remote_ops_common.py +670 -0
- package/modules/localmodels/remote_ops_download.py +399 -381
- package/modules/localmodels/remote_ops_mirrors.py +27 -66
- package/modules/localmodels/remote_ops_prepare.py +43 -35
- package/modules/localmodels/remote_ops_ranges.py +102 -63
- package/modules/localmodels/remote_ops_redirect.py +393 -0
- package/modules/localmodels/remote_ops_remove.py +30 -22
- package/modules/localmodels/remote_ops_service.py +102 -95
- package/modules/localmodels/remote_ops_verify.py +94 -63
- package/modules/localmodels/runtime_cli.py +15 -5
- package/modules/localmodels/runtime_io.py +54 -1
- package/modules/localmodels/source_cli.py +136 -23
- package/modules/localmodels/speech-sv.txt +93 -0
- package/modules/localmodels/speech_admission.py +437 -0
- package/modules/localmodels/speech_catalog.py +170 -0
- package/modules/localmodels/speech_cli.py +273 -0
- package/modules/localmodels/speech_jobs.py +776 -0
- package/modules/localmodels/speech_model.py +404 -0
- package/modules/localmodels/speech_serve.py +287 -0
- package/modules/localmodels/speech_server.py +837 -0
- package/modules/localmodels/speech_state.py +697 -0
- package/modules/localmodels/speech_worker_sensevoice.py +255 -0
- package/modules/localmodels/speech_workers.py +783 -0
- package/modules/localmodels/stack.py +0 -33
- package/modules/localmodels/stack_auto.py +5 -3
- package/modules/localmodels/stack_aux_gpu.py +45 -4
- package/modules/localmodels/stack_capacity.py +77 -8
- package/modules/localmodels/stack_cli.py +16 -1
- package/modules/localmodels/stack_compose.py +1 -1
- package/modules/localmodels/stack_down.py +24 -1
- package/modules/localmodels/stack_hardware.py +57 -88
- package/modules/localmodels/stack_hardware_text.py +4 -59
- package/modules/localmodels/stack_memory.py +13 -3
- package/modules/localmodels/stack_suite.py +9 -10
- package/modules/localmodels/stack_summary.py +4 -4
- package/modules/localmodels/stack_view_llm.py +1 -1
- package/modules/localmodels/transport.py +4 -2
- package/modules/localmodels/tui_views.py +2 -2
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/RECORD +75 -61
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/NOTICE +9 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -2,197 +2,38 @@
|
|
|
2
2
|
"""remote_ops ``engine`` and ``download`` actions: fetch, verify and unpack pinned artifacts.
|
|
3
3
|
|
|
4
4
|
Part of the remote_ops bundle shipped to the target as one stdin payload (transport.BUNDLES):
|
|
5
|
-
standard library only, Python 3.8+. Shared primitives
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
standard library only, Python 3.8+. Shared primitives live in ``remote_ops_common`` and lower
|
|
6
|
+
siblings (``remote_ops_mirrors``, ``remote_ops_ranges``, ``remote_ops_prepare``), keeping the
|
|
7
|
+
bundle strictly acyclic.
|
|
8
8
|
"""
|
|
9
9
|
|
|
10
10
|
from __future__ import annotations
|
|
11
11
|
|
|
12
12
|
import contextlib
|
|
13
13
|
import http.client
|
|
14
|
-
import ipaddress
|
|
15
14
|
import os
|
|
16
15
|
import shutil
|
|
17
|
-
import socket
|
|
18
16
|
import threading
|
|
19
17
|
import time
|
|
20
18
|
import urllib.error
|
|
21
|
-
import
|
|
22
|
-
import urllib.request
|
|
23
|
-
from typing import Any, Iterator, Tuple
|
|
19
|
+
from typing import Iterator, Tuple
|
|
24
20
|
|
|
25
21
|
try:
|
|
26
22
|
from localmodels import (
|
|
27
23
|
process_identity_linux,
|
|
28
|
-
|
|
24
|
+
remote_ops_common,
|
|
29
25
|
remote_ops_mirrors,
|
|
30
26
|
remote_ops_prepare,
|
|
31
27
|
remote_ops_ranges,
|
|
32
28
|
)
|
|
33
29
|
except ImportError: # run as a bare file from this directory
|
|
34
30
|
import process_identity_linux # type: ignore[import-not-found,no-redef]
|
|
35
|
-
import
|
|
31
|
+
import remote_ops_common # type: ignore[import-not-found,no-redef]
|
|
36
32
|
import remote_ops_mirrors # type: ignore[import-not-found,no-redef]
|
|
37
33
|
import remote_ops_prepare # type: ignore[import-not-found,no-redef]
|
|
38
34
|
import remote_ops_ranges # type: ignore[import-not-found,no-redef]
|
|
39
35
|
|
|
40
|
-
_Ranked = Tuple["
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
def act_engine(p: remote_ops.EngineParams) -> None:
|
|
44
|
-
"""Unpack the pinned release archives into p['dir']."""
|
|
45
|
-
directory = remote_ops._expand(p["dir"])
|
|
46
|
-
binary = os.path.join(directory, p.get("binary") or "llama-server")
|
|
47
|
-
done_marker = os.path.join(directory, ".complete")
|
|
48
|
-
expected = ",".join(a["sha256"] for a in p["assets"])
|
|
49
|
-
if os.path.exists(done_marker) and remote_ops._read(done_marker).strip() == expected:
|
|
50
|
-
remote_ops.emit("result", binary=binary, reused=True)
|
|
51
|
-
return
|
|
52
|
-
with remote_ops_mirrors.engine_lock(directory):
|
|
53
|
-
if os.path.exists(done_marker) and remote_ops._read(done_marker).strip() == expected:
|
|
54
|
-
remote_ops.emit("result", binary=binary, reused=True)
|
|
55
|
-
return
|
|
56
|
-
os.makedirs(directory, exist_ok=True)
|
|
57
|
-
cache = os.path.join(os.path.dirname(directory), ".archives")
|
|
58
|
-
active_region = p.get("region")
|
|
59
|
-
for i in remote_ops.each_file(
|
|
60
|
-
[(os.path.join(cache, a["name"]), a["size_bytes"]) for a in p["assets"]]
|
|
61
|
-
):
|
|
62
|
-
a = p["assets"][i]
|
|
63
|
-
archive = os.path.join(cache, a["name"])
|
|
64
|
-
switched = remote_ops.fetch(
|
|
65
|
-
a["url"],
|
|
66
|
-
archive,
|
|
67
|
-
a["sha256"],
|
|
68
|
-
a["size_bytes"],
|
|
69
|
-
a["name"],
|
|
70
|
-
npm_copies(a),
|
|
71
|
-
active_region,
|
|
72
|
-
)
|
|
73
|
-
if switched in ("cn", "global"):
|
|
74
|
-
active_region = switched
|
|
75
|
-
remote_ops.unpack(archive, directory, tuple(a.get("members") or ()))
|
|
76
|
-
if not os.access(binary, os.X_OK):
|
|
77
|
-
raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
|
|
78
|
-
remote_ops._write(done_marker, expected)
|
|
79
|
-
remote_ops.emit("result", binary=binary, reused=False)
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
def _verified_reuse_source(source: str, sha256: str, label: str) -> bool:
|
|
83
|
-
receipt = source + ".sha256"
|
|
84
|
-
try:
|
|
85
|
-
if os.path.isfile(receipt) and remote_ops._read(receipt).strip() == sha256:
|
|
86
|
-
return True
|
|
87
|
-
except (OSError, UnicodeError):
|
|
88
|
-
pass
|
|
89
|
-
if remote_ops._sha256(source, label) != sha256:
|
|
90
|
-
remote_ops.emit(
|
|
91
|
-
"log",
|
|
92
|
-
message=(
|
|
93
|
-
f"the existing copy of {label} has a SHA256 mismatch; downloading instead: {source}"
|
|
94
|
-
),
|
|
95
|
-
)
|
|
96
|
-
return False
|
|
97
|
-
return True
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
def _link_copy(source: str, dest: str, sha256: str, size: int, label: str) -> None:
|
|
101
|
-
"""Hard-link (same device) or copy (cross-device) a verified copy the host already has;
|
|
102
|
-
any mismatch or error falls back to downloading."""
|
|
103
|
-
if os.path.exists(dest) or not os.path.isfile(source) or os.path.getsize(source) != size:
|
|
104
|
-
return
|
|
105
|
-
dest_dir = os.path.dirname(dest) or "."
|
|
106
|
-
os.makedirs(dest_dir, exist_ok=True)
|
|
107
|
-
if not _verified_reuse_source(source, sha256, label):
|
|
108
|
-
return
|
|
109
|
-
same_dev = os.stat(source).st_dev == os.stat(dest_dir).st_dev
|
|
110
|
-
if not same_dev:
|
|
111
|
-
free = shutil.disk_usage(dest_dir).free
|
|
112
|
-
if free < size:
|
|
113
|
-
remote_ops.emit(
|
|
114
|
-
"log",
|
|
115
|
-
message=(
|
|
116
|
-
f"not enough disk space to copy {label} "
|
|
117
|
-
f"({size} bytes needed, {free} free); downloading instead"
|
|
118
|
-
),
|
|
119
|
-
)
|
|
120
|
-
return
|
|
121
|
-
tmp = f"{dest}.reuse.{os.getpid()}"
|
|
122
|
-
with contextlib.suppress(OSError):
|
|
123
|
-
os.unlink(tmp)
|
|
124
|
-
try:
|
|
125
|
-
if same_dev:
|
|
126
|
-
os.link(source, tmp)
|
|
127
|
-
else:
|
|
128
|
-
shutil.copyfile(source, tmp)
|
|
129
|
-
os.replace(tmp, dest)
|
|
130
|
-
except OSError as exc:
|
|
131
|
-
with contextlib.suppress(OSError):
|
|
132
|
-
os.unlink(tmp)
|
|
133
|
-
remote_ops.emit(
|
|
134
|
-
"log",
|
|
135
|
-
message=f"could not reuse {source} for {label} ({exc}); downloading instead",
|
|
136
|
-
)
|
|
137
|
-
return
|
|
138
|
-
except BaseException:
|
|
139
|
-
with contextlib.suppress(OSError):
|
|
140
|
-
os.unlink(tmp)
|
|
141
|
-
raise
|
|
142
|
-
remote_ops._write(dest + ".sha256", sha256)
|
|
143
|
-
remote_ops._store_cached(dest, sha256, size)
|
|
144
|
-
remote_ops.emit(
|
|
145
|
-
"progress",
|
|
146
|
-
phase="download",
|
|
147
|
-
file=label,
|
|
148
|
-
done=size,
|
|
149
|
-
total=size,
|
|
150
|
-
bytes_per_s=size,
|
|
151
|
-
source="cache",
|
|
152
|
-
connections=0,
|
|
153
|
-
**remote_ops.step_fields(size),
|
|
154
|
-
)
|
|
155
|
-
remote_ops.emit("log", message="verified and reused the local file " + source)
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
def act_download(p: remote_ops.DownloadParams) -> None:
|
|
159
|
-
set_auth_headers(p.get("auth_headers"))
|
|
160
|
-
try:
|
|
161
|
-
for f in p["files"]:
|
|
162
|
-
dest, label = remote_ops._expand(f["dest"]), os.path.basename(f["dest"])
|
|
163
|
-
if f.get("reuse") and f.get("sha256"):
|
|
164
|
-
reuse = os.path.realpath(remote_ops._expand(f["reuse"]))
|
|
165
|
-
_link_copy(reuse, dest, f["sha256"], f["size_bytes"], label)
|
|
166
|
-
if not p.get("preparation"):
|
|
167
|
-
remote_ops_prepare.verify_reused_outputs(p["files"])
|
|
168
|
-
files = [f for f in p["files"] if not f.get("generated")]
|
|
169
|
-
active_region = p.get("region")
|
|
170
|
-
for i in remote_ops.each_file(
|
|
171
|
-
[(remote_ops._expand(f["dest"]), f["size_bytes"]) for f in files]
|
|
172
|
-
):
|
|
173
|
-
f = files[i]
|
|
174
|
-
dest, label = remote_ops._expand(f["dest"]), os.path.basename(f["dest"])
|
|
175
|
-
if not f["url"] and not os.path.exists(dest + ".sha256"):
|
|
176
|
-
raise RuntimeError(
|
|
177
|
-
f"{f['dest']} has no download URL, and the reusable copy failed the SHA256 check"
|
|
178
|
-
)
|
|
179
|
-
switched = remote_ops.fetch(
|
|
180
|
-
f["url"],
|
|
181
|
-
dest,
|
|
182
|
-
f["sha256"],
|
|
183
|
-
f["size_bytes"],
|
|
184
|
-
label,
|
|
185
|
-
f.get("mirrors"),
|
|
186
|
-
active_region,
|
|
187
|
-
)
|
|
188
|
-
if switched in ("cn", "global"):
|
|
189
|
-
active_region = switched
|
|
190
|
-
if p.get("preparation"):
|
|
191
|
-
remote_ops_prepare.prepare(p["preparation"], p["files"], active_region)
|
|
192
|
-
remote_ops.emit("result", files=len(p["files"]))
|
|
193
|
-
finally:
|
|
194
|
-
set_auth_headers(None)
|
|
195
|
-
|
|
36
|
+
_Ranked = Tuple["remote_ops_common.Source", bool] # a source and whether it serves byte ranges
|
|
196
37
|
|
|
197
38
|
# Weights and pinned archives are verified by SHA256, so any source serving the same bytes is
|
|
198
39
|
# safe: ``fetch`` concurrently probes candidates, ranks them by actual throughput, downloads in
|
|
@@ -205,36 +46,26 @@ PROBE_SAMPLE_S = 3.0 # once sampled for 3s, stop reading slow mirrors instead o
|
|
|
205
46
|
# also probe the opposite region's mirrors so a misclassified region or throttled upstream
|
|
206
47
|
# immediately yields to a faster mirror (e.g., 880 KB/s Tsinghua beating 39 KB/s official PyPI).
|
|
207
48
|
CROSS_REGION_PROBE_BPS = 2_000_000
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
# range took up to 3 s (a redirect, then TLS to the CDN), so a slow start is not a stall.
|
|
229
|
-
CLAIM_STALL_S = 20.0
|
|
230
|
-
CLAIM_RATE_WINDOW_S = 10.0
|
|
231
|
-
STEAL_POLL_S = 0.5 # how often an idle connection looks for a range to steal
|
|
232
|
-
ATTEMPTS = 5
|
|
233
|
-
# A connection's progress moves once per read, so reads stay small: an 8 MiB read at 2-3 MB/s
|
|
234
|
-
# per connection made the 2 s rate jump in 4 MiB/s steps (often 0). The rate shown is the
|
|
235
|
-
# average over RATE_WINDOW_S, so a stall or burst of one connection does not swing the ETA.
|
|
236
|
-
READ_BYTES = 1 << 20
|
|
237
|
-
RATE_WINDOW_S = 10.0
|
|
49
|
+
LONE_SMALL_BYTES = 1 << 20
|
|
50
|
+
RATE_WINDOW_S = remote_ops_mirrors.RATE_WINDOW_S
|
|
51
|
+
|
|
52
|
+
# Public re-exports from lower bundle modules so existing callers keep one import surface.
|
|
53
|
+
SLOW_WINDOW_S = remote_ops_ranges.SLOW_WINDOW_S
|
|
54
|
+
SLOW_BYTES_PER_S = remote_ops_ranges.SLOW_BYTES_PER_S
|
|
55
|
+
SLOW_MIN_REMAINING_S = remote_ops_ranges.SLOW_MIN_REMAINING_S
|
|
56
|
+
CONNECTIONS = remote_ops_ranges.CONNECTIONS
|
|
57
|
+
SOURCE_CONNECTIONS = remote_ops_ranges.SOURCE_CONNECTIONS
|
|
58
|
+
MIN_SEGMENT_BYTES = remote_ops_ranges.MIN_SEGMENT_BYTES
|
|
59
|
+
STEAL_MIN_S = remote_ops_ranges.STEAL_MIN_S
|
|
60
|
+
STEAL_MIN_BYTES = remote_ops_ranges.STEAL_MIN_BYTES
|
|
61
|
+
CLAIM_GRACE_S = remote_ops_ranges.CLAIM_GRACE_S
|
|
62
|
+
CLAIM_STALL_S = remote_ops_ranges.CLAIM_STALL_S
|
|
63
|
+
CLAIM_RATE_WINDOW_S = remote_ops_ranges.CLAIM_RATE_WINDOW_S
|
|
64
|
+
STEAL_POLL_S = remote_ops_ranges.STEAL_POLL_S
|
|
65
|
+
ATTEMPTS = remote_ops_ranges.ATTEMPTS
|
|
66
|
+
READ_BYTES = remote_ops_ranges.READ_BYTES
|
|
67
|
+
SlowTransferError = remote_ops_ranges.SlowTransferError
|
|
68
|
+
|
|
238
69
|
WEB = remote_ops_mirrors.WEB
|
|
239
70
|
SOURCE_HOSTS = remote_ops_mirrors.SOURCE_HOSTS
|
|
240
71
|
GLOBAL_HOSTS = remote_ops_mirrors.GLOBAL_HOSTS
|
|
@@ -252,150 +83,23 @@ alternates = remote_ops_mirrors.alternates
|
|
|
252
83
|
npm_copies = remote_ops_mirrors.npm_copies
|
|
253
84
|
candidates = remote_ops_mirrors.candidates
|
|
254
85
|
_web = remote_ops_mirrors.is_web
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
kept_bytes = remote_ops_mirrors.kept_bytes
|
|
259
|
-
discard = remote_ops_mirrors.discard
|
|
260
|
-
clear_link = remote_ops_mirrors.clear_link
|
|
86
|
+
kept_bytes = remote_ops_common.kept_bytes
|
|
87
|
+
discard = remote_ops_common.discard
|
|
88
|
+
clear_link = remote_ops_common.clear_link
|
|
261
89
|
bind_to_parent = process_identity_linux.bind_to_parent
|
|
90
|
+
Rate = remote_ops_mirrors.Rate
|
|
262
91
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
_LOCAL_SUFFIXES = (".localhost", ".local", ".internal", ".home.arpa")
|
|
271
|
-
_STDLIB_URLOPEN = urllib.request.urlopen
|
|
272
|
-
ALLOW_INSECURE_LOOPBACK_FOR_TESTS = False
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
def set_auth_headers(headers: dict[str, str] | None) -> None:
|
|
276
|
-
"""Set in-memory host-scoped Authorization headers for the active download step."""
|
|
277
|
-
_AUTH_HEADERS.clear()
|
|
278
|
-
if headers:
|
|
279
|
-
for host, value in headers.items():
|
|
280
|
-
clean_host = str(host).strip().lower()
|
|
281
|
-
clean_val = str(value).strip()
|
|
282
|
-
if clean_host and clean_val and clean_host not in _BLOCKED_AUTH_HOSTS:
|
|
283
|
-
_AUTH_HEADERS[clean_host] = clean_val
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
def _url_origin(raw_url: str) -> tuple[str, str, int]:
|
|
287
|
-
split = urllib.parse.urlsplit(raw_url)
|
|
288
|
-
scheme = split.scheme.lower()
|
|
289
|
-
host = (split.hostname or "").lower().rstrip(".")
|
|
290
|
-
port = split.port
|
|
291
|
-
if port is None:
|
|
292
|
-
port = 443 if scheme == "https" else (80 if scheme == "http" else 0)
|
|
293
|
-
return (scheme, host, port)
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
def _ip_blocked(raw_ip: str) -> bool:
|
|
297
|
-
addr = ipaddress.ip_address(raw_ip.split("%", 1)[0])
|
|
298
|
-
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None:
|
|
299
|
-
addr = addr.ipv4_mapped
|
|
300
|
-
if not addr.is_global:
|
|
301
|
-
return True
|
|
302
|
-
return any(
|
|
303
|
-
(
|
|
304
|
-
addr.is_loopback,
|
|
305
|
-
addr.is_private,
|
|
306
|
-
addr.is_link_local,
|
|
307
|
-
addr.is_multicast,
|
|
308
|
-
addr.is_unspecified,
|
|
309
|
-
addr.is_reserved,
|
|
310
|
-
)
|
|
311
|
-
)
|
|
92
|
+
UnsafeRedirectError = remote_ops_common.UnsafeRedirectError
|
|
93
|
+
is_hf_mirror_host = remote_ops_common.is_hf_mirror_host
|
|
94
|
+
set_auth_headers = remote_ops_common.set_auth_headers
|
|
95
|
+
validate_redirect_url = remote_ops_common.validate_redirect_url
|
|
96
|
+
SafeRedirectHandler = remote_ops_common.SafeRedirectHandler
|
|
97
|
+
build_request = remote_ops_common.build_request
|
|
98
|
+
open_url = remote_ops_common.open_url
|
|
312
99
|
|
|
313
100
|
|
|
314
|
-
def
|
|
315
|
-
|
|
316
|
-
scheme, host, port = _url_origin(target_url)
|
|
317
|
-
if scheme != "https" and not (ALLOW_INSECURE_LOOPBACK_FOR_TESTS and scheme == "http"):
|
|
318
|
-
raise urllib.error.URLError(f"redirect refused: non-HTTPS scheme {scheme!r}")
|
|
319
|
-
if not host:
|
|
320
|
-
raise urllib.error.URLError("redirect refused: missing target host")
|
|
321
|
-
if ALLOW_INSECURE_LOOPBACK_FOR_TESTS:
|
|
322
|
-
return
|
|
323
|
-
if host == "localhost" or any(host.endswith(suffix) for suffix in _LOCAL_SUFFIXES):
|
|
324
|
-
raise urllib.error.URLError(f"redirect refused: local hostname {host!r}")
|
|
325
|
-
try:
|
|
326
|
-
if _ip_blocked(host):
|
|
327
|
-
raise urllib.error.URLError(f"redirect refused: non-public IP {host!r}")
|
|
328
|
-
return
|
|
329
|
-
except ValueError:
|
|
330
|
-
pass
|
|
331
|
-
try:
|
|
332
|
-
records = socket.getaddrinfo(host, port or 443, type=socket.SOCK_STREAM)
|
|
333
|
-
except OSError as exc:
|
|
334
|
-
raise urllib.error.URLError(
|
|
335
|
-
f"redirect refused: DNS lookup failed for {host!r}: {exc}"
|
|
336
|
-
) from None
|
|
337
|
-
if not records:
|
|
338
|
-
raise urllib.error.URLError(f"redirect refused: empty DNS answer for {host!r}")
|
|
339
|
-
for entry in records:
|
|
340
|
-
candidate_ip = str(entry[4][0])
|
|
341
|
-
try:
|
|
342
|
-
blocked = _ip_blocked(candidate_ip)
|
|
343
|
-
except ValueError:
|
|
344
|
-
raise urllib.error.URLError(f"redirect refused: invalid IP for {host!r}") from None
|
|
345
|
-
if blocked:
|
|
346
|
-
raise urllib.error.URLError(f"redirect refused: non-public IP for {host!r}")
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
class SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
350
|
-
"""Enforce HTTPS + anti-SSRF on redirects and strip Authorization on any origin change."""
|
|
351
|
-
|
|
352
|
-
def redirect_request(
|
|
353
|
-
self,
|
|
354
|
-
req: urllib.request.Request,
|
|
355
|
-
fp: Any,
|
|
356
|
-
code: int,
|
|
357
|
-
msg: str,
|
|
358
|
-
headers: Any,
|
|
359
|
-
newurl: str,
|
|
360
|
-
) -> urllib.request.Request | None:
|
|
361
|
-
resolved = urllib.parse.urljoin(req.full_url, newurl)
|
|
362
|
-
validate_redirect_url(resolved)
|
|
363
|
-
redirected = super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
364
|
-
if redirected is None:
|
|
365
|
-
return None
|
|
366
|
-
if _url_origin(req.full_url) != _url_origin(resolved):
|
|
367
|
-
for bag in (redirected.headers, redirected.unredirected_hdrs):
|
|
368
|
-
for key in list(bag.keys()):
|
|
369
|
-
if key.lower() == "authorization":
|
|
370
|
-
del bag[key]
|
|
371
|
-
return redirected
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
def build_request(
|
|
375
|
-
url: str, start: int | None = None, end: int | None = None
|
|
376
|
-
) -> urllib.request.Request:
|
|
377
|
-
request = urllib.request.Request(url, headers={"User-Agent": "localmodels-deploy"})
|
|
378
|
-
if start is not None and end is not None:
|
|
379
|
-
request.add_header("Range", f"bytes={start}-{end - 1}")
|
|
380
|
-
scheme, host, _ = _url_origin(url)
|
|
381
|
-
https_ok = scheme == "https" or (ALLOW_INSECURE_LOOPBACK_FOR_TESTS and scheme == "http")
|
|
382
|
-
if https_ok and host and host not in _BLOCKED_AUTH_HOSTS and host in _AUTH_HEADERS:
|
|
383
|
-
request.add_header("Authorization", _AUTH_HEADERS[host])
|
|
384
|
-
return request
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
def open_url(request: urllib.request.Request, timeout: float) -> Any:
|
|
388
|
-
https_live = (
|
|
389
|
-
request.full_url.lower().startswith("https://")
|
|
390
|
-
and urllib.request.urlopen is _STDLIB_URLOPEN
|
|
391
|
-
)
|
|
392
|
-
if request.has_header("Authorization") or https_live:
|
|
393
|
-
return urllib.request.build_opener(SafeRedirectHandler()).open(request, timeout=timeout)
|
|
394
|
-
return urllib.request.urlopen(request, timeout=timeout)
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
def _ranged_request(url: str, start: int, end: int) -> urllib.request.Request:
|
|
398
|
-
return build_request(url, start, end)
|
|
101
|
+
def npm_transfer(source: remote_ops_common.Source, part: str, size: int, label: str) -> None:
|
|
102
|
+
remote_ops_mirrors.npm_transfer(source, part, size, label, overhead=NPM_OVERHEAD_BYTES)
|
|
399
103
|
|
|
400
104
|
|
|
401
105
|
def _range_total(response: object) -> int | None:
|
|
@@ -412,7 +116,9 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
|
|
|
412
116
|
want = min(size, PROBE_BYTES)
|
|
413
117
|
start, got = time.monotonic(), 0
|
|
414
118
|
try:
|
|
415
|
-
with open_url(
|
|
119
|
+
with remote_ops_common.open_url(
|
|
120
|
+
remote_ops_common.build_request(url, 0, want), timeout=PROBE_TIMEOUT_S
|
|
121
|
+
) as r:
|
|
416
122
|
status = getattr(r, "status", 200)
|
|
417
123
|
length = str(r.headers.get("Content-Length", ""))
|
|
418
124
|
ranged = status == 206 and _range_total(r) == size
|
|
@@ -438,13 +144,10 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
|
|
|
438
144
|
return got / max(1e-3, time.monotonic() - start), ranged
|
|
439
145
|
|
|
440
146
|
|
|
441
|
-
LONE_SMALL_BYTES = 1 << 20
|
|
442
|
-
|
|
443
|
-
|
|
444
147
|
def _probe_many(
|
|
445
|
-
sources: list[
|
|
148
|
+
sources: list[remote_ops_common.Source],
|
|
446
149
|
size: int,
|
|
447
|
-
) -> list[tuple[
|
|
150
|
+
) -> list[tuple[remote_ops_common.Source, tuple[float, bool] | None]]:
|
|
448
151
|
"""Probe ``sources`` concurrently so multi-mirror ranking completes in one RTT window."""
|
|
449
152
|
if not sources:
|
|
450
153
|
return []
|
|
@@ -452,7 +155,7 @@ def _probe_many(
|
|
|
452
155
|
return [(sources[0], probe(sources[0]["url"], size))]
|
|
453
156
|
results: list[tuple[float, bool] | None] = [None] * len(sources)
|
|
454
157
|
|
|
455
|
-
def run_one(idx: int, src:
|
|
158
|
+
def run_one(idx: int, src: remote_ops_common.Source) -> None:
|
|
456
159
|
results[idx] = probe(src["url"], size)
|
|
457
160
|
|
|
458
161
|
threads = [
|
|
@@ -467,10 +170,10 @@ def _probe_many(
|
|
|
467
170
|
|
|
468
171
|
|
|
469
172
|
def rank(
|
|
470
|
-
sources: list[
|
|
173
|
+
sources: list[remote_ops_common.Source],
|
|
471
174
|
size: int,
|
|
472
175
|
label: str,
|
|
473
|
-
unreachable: list[
|
|
176
|
+
unreachable: list[remote_ops_common.Source] | None = None,
|
|
474
177
|
) -> list[_Ranked]:
|
|
475
178
|
"""The sources fastest first, each with whether it serves ranges; ones that failed the probe
|
|
476
179
|
go last in plan order (and into ``unreachable``), so a passing hiccup still leaves them as
|
|
@@ -492,19 +195,19 @@ def rank(
|
|
|
492
195
|
measured.append((-result[0], i, (source, result[1])))
|
|
493
196
|
notes.append("{} {:.1f} MB/s".format(source["source"], result[0] / 1e6))
|
|
494
197
|
if len(sources) > 1:
|
|
495
|
-
|
|
198
|
+
remote_ops_common.emit(
|
|
496
199
|
"log", message="download sources for {}: {}".format(label, ", ".join(notes))
|
|
497
200
|
)
|
|
498
201
|
return [r for _, _, r in sorted(measured)] + failed
|
|
499
202
|
|
|
500
203
|
|
|
501
204
|
def _probe_batch(
|
|
502
|
-
batch: list[
|
|
205
|
+
batch: list[remote_ops_common.Source],
|
|
503
206
|
size: int,
|
|
504
207
|
region: str,
|
|
505
208
|
tier: int,
|
|
506
|
-
failed: list[
|
|
507
|
-
demoted: list[
|
|
209
|
+
failed: list[remote_ops_common.Source],
|
|
210
|
+
demoted: list[remote_ops_common.Source],
|
|
508
211
|
notes: list[str],
|
|
509
212
|
scored: list[tuple[float, int, int, int, _Ranked]],
|
|
510
213
|
probe_speeds: dict[str, float] | None,
|
|
@@ -527,12 +230,12 @@ def _probe_batch(
|
|
|
527
230
|
|
|
528
231
|
|
|
529
232
|
def _ordered_public(
|
|
530
|
-
own: list[
|
|
531
|
-
public_s: list[
|
|
233
|
+
own: list[remote_ops_common.Source],
|
|
234
|
+
public_s: list[remote_ops_common.Source],
|
|
532
235
|
size: int,
|
|
533
236
|
label: str,
|
|
534
237
|
region: str,
|
|
535
|
-
failed: list[
|
|
238
|
+
failed: list[remote_ops_common.Source],
|
|
536
239
|
probe_speeds: dict[str, float] | None,
|
|
537
240
|
) -> Iterator[_Ranked]:
|
|
538
241
|
public_probe = [s for s in public_s if not s.get("member")]
|
|
@@ -547,13 +250,15 @@ def _ordered_public(
|
|
|
547
250
|
primary = sorted([s for s in public_probe if side(s["url"]) == "cn"], key=cn_rank)
|
|
548
251
|
secondary = sorted([s for s in public_probe if side(s["url"]) != "cn"], key=cn_rank)
|
|
549
252
|
else:
|
|
550
|
-
primary = [
|
|
253
|
+
primary = [
|
|
254
|
+
s for s in own if not s.get("member") and not remote_ops_common.non_public(s["url"])
|
|
255
|
+
]
|
|
551
256
|
primary_urls = {s["url"] for s in primary}
|
|
552
257
|
secondary = [s for s in public_probe if s["url"] not in primary_urls]
|
|
553
258
|
|
|
554
259
|
notes: list[str] = []
|
|
555
260
|
scored: list[tuple[float, int, int, int, _Ranked]] = []
|
|
556
|
-
demoted: list[
|
|
261
|
+
demoted: list[remote_ops_common.Source] = []
|
|
557
262
|
best_primary = (
|
|
558
263
|
_probe_batch(primary, size, region, 0, failed, demoted, notes, scored, probe_speeds)
|
|
559
264
|
if primary
|
|
@@ -563,7 +268,7 @@ def _ordered_public(
|
|
|
563
268
|
if cross_probed:
|
|
564
269
|
_probe_batch(secondary, size, region, 1, failed, demoted, notes, scored, probe_speeds)
|
|
565
270
|
if notes:
|
|
566
|
-
|
|
271
|
+
remote_ops_common.emit(
|
|
567
272
|
"log", message=f"download sources for {label} (region {region}): {', '.join(notes)}"
|
|
568
273
|
)
|
|
569
274
|
|
|
@@ -581,11 +286,11 @@ def _ordered_public(
|
|
|
581
286
|
|
|
582
287
|
|
|
583
288
|
def ordered(
|
|
584
|
-
sources: list[
|
|
289
|
+
sources: list[remote_ops_common.Source],
|
|
585
290
|
size: int,
|
|
586
291
|
label: str,
|
|
587
292
|
region: str | None,
|
|
588
|
-
failed: list[
|
|
293
|
+
failed: list[remote_ops_common.Source],
|
|
589
294
|
probe_speeds: dict[str, float] | None = None,
|
|
590
295
|
) -> Iterator[_Ranked]:
|
|
591
296
|
"""Dynamic speed-first source ordering with tiered cross-region probing."""
|
|
@@ -595,8 +300,8 @@ def ordered(
|
|
|
595
300
|
yield from ((s, False) for s in own if s.get("member"))
|
|
596
301
|
return
|
|
597
302
|
all_sources = own + extra
|
|
598
|
-
local_s = [s for s in all_sources if
|
|
599
|
-
public_s = [s for s in all_sources if not
|
|
303
|
+
local_s = [s for s in all_sources if remote_ops_common.non_public(s["url"])]
|
|
304
|
+
public_s = [s for s in all_sources if not remote_ops_common.non_public(s["url"])]
|
|
600
305
|
if local_s:
|
|
601
306
|
local_probe = [s for s in local_s if not s.get("member")]
|
|
602
307
|
if local_probe:
|
|
@@ -606,19 +311,8 @@ def ordered(
|
|
|
606
311
|
yield from _ordered_public(own, public_s, size, label, region, failed, probe_speeds)
|
|
607
312
|
|
|
608
313
|
|
|
609
|
-
class SlowTransferError(RuntimeError):
|
|
610
|
-
"""Sustained transfer throughput dropped below SLOW_BYTES_PER_S; switch to another host."""
|
|
611
|
-
|
|
612
|
-
def __init__(self, bytes_per_s: int) -> None:
|
|
613
|
-
self.bytes_per_s = bytes_per_s
|
|
614
|
-
super().__init__(
|
|
615
|
-
f"download too slow ({bytes_per_s / 1024:.0f} KB/s < "
|
|
616
|
-
f"{SLOW_BYTES_PER_S / 1024:.0f} KB/s)"
|
|
617
|
-
)
|
|
618
|
-
|
|
619
|
-
|
|
620
314
|
def transfer(
|
|
621
|
-
source:
|
|
315
|
+
source: remote_ops_common.Source,
|
|
622
316
|
part: str,
|
|
623
317
|
size: int,
|
|
624
318
|
label: str,
|
|
@@ -632,25 +326,349 @@ def transfer(
|
|
|
632
326
|
that turns out not to serve ranges is read once as one plain stream from the start."""
|
|
633
327
|
if ranged:
|
|
634
328
|
count = remote_ops_ranges.connections_for(source)
|
|
635
|
-
job = remote_ops_ranges.
|
|
329
|
+
job = remote_ops_ranges.Transfer(
|
|
636
330
|
source["url"],
|
|
637
331
|
part,
|
|
638
332
|
size,
|
|
639
|
-
remote_ops_ranges.
|
|
333
|
+
remote_ops_ranges.resume_ranges(part, size, count),
|
|
640
334
|
attempts=attempts,
|
|
641
335
|
connections=count,
|
|
642
336
|
)
|
|
643
|
-
remote_ops_ranges.
|
|
644
|
-
|
|
645
|
-
|
|
337
|
+
remote_ops_ranges.run_transfer(
|
|
338
|
+
job, source, label, ranged=True, allow_slow_switch=allow_slow_switch
|
|
339
|
+
)
|
|
340
|
+
if not (job.errors and isinstance(job.errors[0], remote_ops_ranges.NoRangeError)):
|
|
341
|
+
remote_ops_ranges.finish_transfer(job, label)
|
|
646
342
|
return
|
|
647
|
-
discard(part)
|
|
343
|
+
remote_ops_common.discard(part)
|
|
648
344
|
open(part, "wb").close()
|
|
649
|
-
job = remote_ops_ranges.
|
|
650
|
-
remote_ops_ranges.
|
|
651
|
-
|
|
345
|
+
job = remote_ops_ranges.Transfer(source["url"], part, size, [[0, size, 0]], attempts=attempts)
|
|
346
|
+
remote_ops_ranges.run_transfer(
|
|
347
|
+
job, source, label, ranged=False, allow_slow_switch=allow_slow_switch
|
|
348
|
+
)
|
|
349
|
+
remote_ops_ranges.finish_transfer(job, label)
|
|
652
350
|
|
|
653
351
|
|
|
654
352
|
DEFAULT_TRANSFER = transfer
|
|
655
353
|
|
|
656
|
-
|
|
354
|
+
|
|
355
|
+
def _transfer_once(
|
|
356
|
+
source: remote_ops_common.Source,
|
|
357
|
+
part: str,
|
|
358
|
+
size: int,
|
|
359
|
+
label: str,
|
|
360
|
+
ranged: bool,
|
|
361
|
+
*,
|
|
362
|
+
probed_bad: bool,
|
|
363
|
+
allow_slow: bool,
|
|
364
|
+
) -> None:
|
|
365
|
+
if source.get("member"):
|
|
366
|
+
npm_transfer(source, part, size, label)
|
|
367
|
+
return
|
|
368
|
+
if probed_bad:
|
|
369
|
+
if allow_slow:
|
|
370
|
+
transfer(source, part, size, label, ranged, attempts=1, allow_slow_switch=True)
|
|
371
|
+
else:
|
|
372
|
+
transfer(source, part, size, label, ranged, attempts=1)
|
|
373
|
+
return
|
|
374
|
+
if allow_slow:
|
|
375
|
+
transfer(source, part, size, label, ranged, allow_slow_switch=True)
|
|
376
|
+
else:
|
|
377
|
+
transfer(source, part, size, label, ranged)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _fallback(
|
|
381
|
+
region: str | None,
|
|
382
|
+
used: remote_ops_common.Source,
|
|
383
|
+
failed: list[remote_ops_common.Source],
|
|
384
|
+
probe_speeds: dict[str, float] | None = None,
|
|
385
|
+
) -> str | None:
|
|
386
|
+
"""The other region, when ``used`` is on its side and either a source on the region's own
|
|
387
|
+
side failed/was slow-aborted first, or cross-region speed probing proved the other side was
|
|
388
|
+
decisively faster (>= 2x) while every probed preferred source was below
|
|
389
|
+
``CROSS_REGION_PROBE_BPS``. A neutral source (GitHub, a LAN or user mirror) never switches."""
|
|
390
|
+
other = side(used["url"])
|
|
391
|
+
if region not in ("cn", "global") or other in ("", region):
|
|
392
|
+
return None
|
|
393
|
+
mine = [s for s in failed if side(s["url"]) == region]
|
|
394
|
+
if mine:
|
|
395
|
+
return other
|
|
396
|
+
if probe_speeds:
|
|
397
|
+
used_speed = probe_speeds.get(used["url"], 0.0)
|
|
398
|
+
pref_speeds = [
|
|
399
|
+
bps for candidate_url, bps in probe_speeds.items() if side(candidate_url) == region
|
|
400
|
+
]
|
|
401
|
+
if (
|
|
402
|
+
used_speed > 0
|
|
403
|
+
and pref_speeds
|
|
404
|
+
and max(pref_speeds) < CROSS_REGION_PROBE_BPS
|
|
405
|
+
and used_speed >= 2.0 * max(pref_speeds)
|
|
406
|
+
):
|
|
407
|
+
return other
|
|
408
|
+
return None
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def fetch(
|
|
412
|
+
url: str,
|
|
413
|
+
dest: str,
|
|
414
|
+
sha256: str,
|
|
415
|
+
size: int,
|
|
416
|
+
label: str,
|
|
417
|
+
mirrors: list[remote_ops_common.Source] | None = None,
|
|
418
|
+
region: str | None = None,
|
|
419
|
+
) -> str | None:
|
|
420
|
+
"""Download ``url`` (or another source of the same pinned bytes: ``mirrors`` and, given a
|
|
421
|
+
``region``, the alternates that region adds) to ``dest`` unless a verified copy exists.
|
|
422
|
+
Resumes a .part file, from any source. Returns the region to switch to when the region's
|
|
423
|
+
own side failed or was decisively outperformed by the other side (also reported as
|
|
424
|
+
``region_fallback`` on the log event), else None."""
|
|
425
|
+
marker = dest + ".sha256"
|
|
426
|
+
if remote_ops_common.existing_verified(dest, marker, sha256, size, label):
|
|
427
|
+
return None
|
|
428
|
+
free = shutil.disk_usage(os.path.dirname(dest)).free
|
|
429
|
+
part = dest + ".part"
|
|
430
|
+
had_part = os.path.exists(part)
|
|
431
|
+
have = remote_ops_common.kept_bytes(part, size)
|
|
432
|
+
if have > size:
|
|
433
|
+
remote_ops_common.discard(part)
|
|
434
|
+
had_part, have = False, 0
|
|
435
|
+
if size - have > free:
|
|
436
|
+
raise RuntimeError(f"low disk space: {label} needs {size - have} more bytes, {free} free")
|
|
437
|
+
sources: list[remote_ops_common.Source] = [{"source": source_name(url), "url": url}]
|
|
438
|
+
sources += [m for m in mirrors or [] if m.get("url") and m["url"] != url]
|
|
439
|
+
error: Exception | None = None
|
|
440
|
+
failed: list[remote_ops_common.Source] = []
|
|
441
|
+
slow_urls: set[str] = set()
|
|
442
|
+
fresh_retried: set[str] = set()
|
|
443
|
+
deferred_slow: list[tuple[remote_ops_common.Source, bool]] = []
|
|
444
|
+
immediate: list[tuple[remote_ops_common.Source, bool]] = []
|
|
445
|
+
probe_speeds: dict[str, float] = {}
|
|
446
|
+
stream = iter(ordered(sources, size, label, region, failed, probe_speeds))
|
|
447
|
+
upcoming = next(stream, None)
|
|
448
|
+
supports_slow = transfer is DEFAULT_TRANSFER
|
|
449
|
+
|
|
450
|
+
while immediate or upcoming is not None or deferred_slow:
|
|
451
|
+
if immediate:
|
|
452
|
+
source, ranged = immediate.pop(0)
|
|
453
|
+
elif upcoming is not None:
|
|
454
|
+
source, ranged = upcoming
|
|
455
|
+
upcoming = next(stream, None)
|
|
456
|
+
else:
|
|
457
|
+
source, ranged = deferred_slow.pop(0)
|
|
458
|
+
probed_bad = any(f["url"] == source["url"] for f in failed)
|
|
459
|
+
has_more = (
|
|
460
|
+
bool(immediate)
|
|
461
|
+
or upcoming is not None
|
|
462
|
+
or any(s["url"] not in slow_urls for s, _ in deferred_slow)
|
|
463
|
+
)
|
|
464
|
+
allow_slow = supports_slow and has_more and source["url"] not in slow_urls
|
|
465
|
+
resumed_prior = os.path.exists(part) and os.path.getsize(part) > 0
|
|
466
|
+
try:
|
|
467
|
+
_transfer_once(
|
|
468
|
+
source, part, size, label, ranged, probed_bad=probed_bad, allow_slow=allow_slow
|
|
469
|
+
)
|
|
470
|
+
except SlowTransferError as exc:
|
|
471
|
+
remote_ops_common.emit(
|
|
472
|
+
"log",
|
|
473
|
+
message=(
|
|
474
|
+
f"download from {source['source']} is too slow for {label} ({exc}); "
|
|
475
|
+
"switching source"
|
|
476
|
+
),
|
|
477
|
+
)
|
|
478
|
+
error = exc
|
|
479
|
+
slow_urls.add(source["url"])
|
|
480
|
+
deferred_slow.append((source, ranged))
|
|
481
|
+
failed.append(source)
|
|
482
|
+
continue
|
|
483
|
+
except Exception as exc: # noqa: BLE001 - the next source is tried, the last re-raised
|
|
484
|
+
remote_ops_common.emit(
|
|
485
|
+
"log",
|
|
486
|
+
message=(
|
|
487
|
+
f"download from {source['source']} stopped, {label}: "
|
|
488
|
+
f"{remote_ops_common.redact_text(str(exc))}"
|
|
489
|
+
),
|
|
490
|
+
)
|
|
491
|
+
error = exc
|
|
492
|
+
failed.append(source)
|
|
493
|
+
continue
|
|
494
|
+
mismatch = remote_ops_common.check_part(part, sha256, size, label, source["source"])
|
|
495
|
+
if mismatch is not None:
|
|
496
|
+
error = mismatch
|
|
497
|
+
remote_ops_common.discard(part)
|
|
498
|
+
if resumed_prior and source["url"] not in fresh_retried:
|
|
499
|
+
fresh_retried.add(source["url"])
|
|
500
|
+
immediate.append((source, ranged))
|
|
501
|
+
continue
|
|
502
|
+
remote_ops_common.discard(part + ".ranges") # the record only; part is renamed
|
|
503
|
+
os.replace(part, dest)
|
|
504
|
+
if sha256:
|
|
505
|
+
remote_ops_common.write_text(marker, sha256)
|
|
506
|
+
remote_ops_common.store_cached(dest, sha256, size)
|
|
507
|
+
else:
|
|
508
|
+
remote_ops_common.write_text(marker, remote_ops_common.sha256_file(dest, label))
|
|
509
|
+
switch = _fallback(region, source, failed, probe_speeds)
|
|
510
|
+
extra = {"region_fallback": switch} if switch else {}
|
|
511
|
+
remote_ops_common.emit(
|
|
512
|
+
"log", message=f"downloaded and verified {label} from {source['source']}", **extra
|
|
513
|
+
)
|
|
514
|
+
return switch
|
|
515
|
+
if not had_part and remote_ops_common.kept_bytes(part, size) == 0:
|
|
516
|
+
remote_ops_common.discard(part)
|
|
517
|
+
raise error or RuntimeError(f"{label} has no download source")
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def act_engine(p: remote_ops_common.EngineParams) -> None:
|
|
521
|
+
"""Unpack the pinned release archives into p['dir']."""
|
|
522
|
+
directory = remote_ops_common.expand(p["dir"])
|
|
523
|
+
binary = os.path.join(directory, p.get("binary") or "llama-server")
|
|
524
|
+
done_marker = os.path.join(directory, ".complete")
|
|
525
|
+
expected = ",".join(a["sha256"] for a in p["assets"])
|
|
526
|
+
if os.path.exists(done_marker) and remote_ops_common.read_text(done_marker).strip() == expected:
|
|
527
|
+
remote_ops_common.emit("result", binary=binary, reused=True)
|
|
528
|
+
return
|
|
529
|
+
with remote_ops_mirrors.engine_lock(directory):
|
|
530
|
+
if (
|
|
531
|
+
os.path.exists(done_marker)
|
|
532
|
+
and remote_ops_common.read_text(done_marker).strip() == expected
|
|
533
|
+
):
|
|
534
|
+
remote_ops_common.emit("result", binary=binary, reused=True)
|
|
535
|
+
return
|
|
536
|
+
os.makedirs(directory, exist_ok=True)
|
|
537
|
+
cache = os.path.join(os.path.dirname(directory), ".archives")
|
|
538
|
+
active_region = p.get("region")
|
|
539
|
+
for i in remote_ops_common.each_file(
|
|
540
|
+
[(os.path.join(cache, a["name"]), a["size_bytes"]) for a in p["assets"]]
|
|
541
|
+
):
|
|
542
|
+
a = p["assets"][i]
|
|
543
|
+
archive = os.path.join(cache, a["name"])
|
|
544
|
+
switched = fetch(
|
|
545
|
+
a["url"],
|
|
546
|
+
archive,
|
|
547
|
+
a["sha256"],
|
|
548
|
+
a["size_bytes"],
|
|
549
|
+
a["name"],
|
|
550
|
+
npm_copies(a),
|
|
551
|
+
active_region,
|
|
552
|
+
)
|
|
553
|
+
if switched in ("cn", "global"):
|
|
554
|
+
active_region = switched
|
|
555
|
+
remote_ops_common.unpack(archive, directory, tuple(a.get("members") or ()))
|
|
556
|
+
if not os.access(binary, os.X_OK):
|
|
557
|
+
raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
|
|
558
|
+
remote_ops_common.write_text(done_marker, expected)
|
|
559
|
+
remote_ops_common.emit("result", binary=binary, reused=False)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _verified_reuse_source(source: str, sha256: str, label: str) -> bool:
|
|
563
|
+
receipt = source + ".sha256"
|
|
564
|
+
try:
|
|
565
|
+
if os.path.isfile(receipt) and remote_ops_common.read_text(receipt).strip() == sha256:
|
|
566
|
+
return True
|
|
567
|
+
except (OSError, UnicodeError):
|
|
568
|
+
pass
|
|
569
|
+
if remote_ops_common.sha256_file(source, label) != sha256:
|
|
570
|
+
remote_ops_common.emit(
|
|
571
|
+
"log",
|
|
572
|
+
message=(
|
|
573
|
+
f"the existing copy of {label} has a SHA256 mismatch; downloading instead: {source}"
|
|
574
|
+
),
|
|
575
|
+
)
|
|
576
|
+
return False
|
|
577
|
+
return True
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _link_copy(source: str, dest: str, sha256: str, size: int, label: str) -> None:
|
|
581
|
+
"""Hard-link (same device) or copy (cross-device) a verified copy the host already has;
|
|
582
|
+
any mismatch or error falls back to downloading."""
|
|
583
|
+
if os.path.exists(dest) or not os.path.isfile(source) or os.path.getsize(source) != size:
|
|
584
|
+
return
|
|
585
|
+
dest_dir = os.path.dirname(dest) or "."
|
|
586
|
+
os.makedirs(dest_dir, exist_ok=True)
|
|
587
|
+
if not _verified_reuse_source(source, sha256, label):
|
|
588
|
+
return
|
|
589
|
+
same_dev = os.stat(source).st_dev == os.stat(dest_dir).st_dev
|
|
590
|
+
if not same_dev:
|
|
591
|
+
free = shutil.disk_usage(dest_dir).free
|
|
592
|
+
if free < size:
|
|
593
|
+
remote_ops_common.emit(
|
|
594
|
+
"log",
|
|
595
|
+
message=(
|
|
596
|
+
f"not enough disk space to copy {label} "
|
|
597
|
+
f"({size} bytes needed, {free} free); downloading instead"
|
|
598
|
+
),
|
|
599
|
+
)
|
|
600
|
+
return
|
|
601
|
+
tmp = f"{dest}.reuse.{os.getpid()}"
|
|
602
|
+
with contextlib.suppress(OSError):
|
|
603
|
+
os.unlink(tmp)
|
|
604
|
+
try:
|
|
605
|
+
if same_dev:
|
|
606
|
+
os.link(source, tmp)
|
|
607
|
+
else:
|
|
608
|
+
shutil.copyfile(source, tmp)
|
|
609
|
+
os.replace(tmp, dest)
|
|
610
|
+
except OSError as exc:
|
|
611
|
+
with contextlib.suppress(OSError):
|
|
612
|
+
os.unlink(tmp)
|
|
613
|
+
remote_ops_common.emit(
|
|
614
|
+
"log",
|
|
615
|
+
message=f"could not reuse {source} for {label} ({exc}); downloading instead",
|
|
616
|
+
)
|
|
617
|
+
return
|
|
618
|
+
except BaseException:
|
|
619
|
+
with contextlib.suppress(OSError):
|
|
620
|
+
os.unlink(tmp)
|
|
621
|
+
raise
|
|
622
|
+
remote_ops_common.write_text(dest + ".sha256", sha256)
|
|
623
|
+
remote_ops_common.store_cached(dest, sha256, size)
|
|
624
|
+
remote_ops_common.emit(
|
|
625
|
+
"progress",
|
|
626
|
+
phase="download",
|
|
627
|
+
file=label,
|
|
628
|
+
done=size,
|
|
629
|
+
total=size,
|
|
630
|
+
bytes_per_s=size,
|
|
631
|
+
source="cache",
|
|
632
|
+
connections=0,
|
|
633
|
+
**remote_ops_common.step_fields(size),
|
|
634
|
+
)
|
|
635
|
+
remote_ops_common.emit("log", message="verified and reused the local file " + source)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def act_download(p: remote_ops_common.DownloadParams) -> None:
|
|
639
|
+
remote_ops_common.set_auth_headers(p.get("auth_headers"))
|
|
640
|
+
try:
|
|
641
|
+
for f in p["files"]:
|
|
642
|
+
dest, label = remote_ops_common.expand(f["dest"]), os.path.basename(f["dest"])
|
|
643
|
+
if f.get("reuse") and f.get("sha256"):
|
|
644
|
+
reuse = os.path.realpath(remote_ops_common.expand(f["reuse"]))
|
|
645
|
+
_link_copy(reuse, dest, f["sha256"], f["size_bytes"], label)
|
|
646
|
+
if not p.get("preparation"):
|
|
647
|
+
remote_ops_prepare.verify_reused_outputs(p["files"])
|
|
648
|
+
files = [f for f in p["files"] if not f.get("generated")]
|
|
649
|
+
active_region = p.get("region")
|
|
650
|
+
for i in remote_ops_common.each_file(
|
|
651
|
+
[(remote_ops_common.expand(f["dest"]), f["size_bytes"]) for f in files]
|
|
652
|
+
):
|
|
653
|
+
f = files[i]
|
|
654
|
+
dest, label = remote_ops_common.expand(f["dest"]), os.path.basename(f["dest"])
|
|
655
|
+
if not f["url"] and not os.path.exists(dest + ".sha256"):
|
|
656
|
+
raise RuntimeError(
|
|
657
|
+
f"{f['dest']} has no download URL, and the reusable copy failed the SHA256 check"
|
|
658
|
+
)
|
|
659
|
+
switched = fetch(
|
|
660
|
+
f["url"],
|
|
661
|
+
dest,
|
|
662
|
+
f["sha256"],
|
|
663
|
+
f["size_bytes"],
|
|
664
|
+
label,
|
|
665
|
+
f.get("mirrors"),
|
|
666
|
+
active_region,
|
|
667
|
+
)
|
|
668
|
+
if switched in ("cn", "global"):
|
|
669
|
+
active_region = switched
|
|
670
|
+
if p.get("preparation"):
|
|
671
|
+
remote_ops_prepare.prepare(p["preparation"], p["files"], active_region, fetch_fn=fetch)
|
|
672
|
+
remote_ops_common.emit("result", files=len(p["files"]))
|
|
673
|
+
finally:
|
|
674
|
+
remote_ops_common.set_auth_headers(None)
|