@simplexai/localmodels-darwin-x64 0.1.0-dev.60 → 0.1.0-dev.61
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 +73 -60
- 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/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_serve.py +69 -13
- 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 +729 -0
- package/modules/localmodels/remote_ops_download.py +397 -381
- package/modules/localmodels/remote_ops_mirrors.py +26 -65
- package/modules/localmodels/remote_ops_prepare.py +43 -35
- package/modules/localmodels/remote_ops_ranges.py +98 -62
- 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/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 +772 -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 +3 -2
- package/modules/localmodels/tui_views.py +2 -2
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +70 -57
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.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.dev61.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.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,21 @@ 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
|
-
_AUTH_HEADERS: dict[str, str] = {}
|
|
269
|
-
_BLOCKED_AUTH_HOSTS = frozenset({"hf-mirror.com", "www.hf-mirror.com"})
|
|
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
|
+
set_auth_headers = remote_ops_common.set_auth_headers
|
|
93
|
+
validate_redirect_url = remote_ops_common.validate_redirect_url
|
|
94
|
+
SafeRedirectHandler = remote_ops_common.SafeRedirectHandler
|
|
95
|
+
build_request = remote_ops_common.build_request
|
|
96
|
+
open_url = remote_ops_common.open_url
|
|
312
97
|
|
|
313
98
|
|
|
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)
|
|
99
|
+
def npm_transfer(source: remote_ops_common.Source, part: str, size: int, label: str) -> None:
|
|
100
|
+
remote_ops_mirrors.npm_transfer(source, part, size, label, overhead=NPM_OVERHEAD_BYTES)
|
|
399
101
|
|
|
400
102
|
|
|
401
103
|
def _range_total(response: object) -> int | None:
|
|
@@ -412,7 +114,9 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
|
|
|
412
114
|
want = min(size, PROBE_BYTES)
|
|
413
115
|
start, got = time.monotonic(), 0
|
|
414
116
|
try:
|
|
415
|
-
with open_url(
|
|
117
|
+
with remote_ops_common.open_url(
|
|
118
|
+
remote_ops_common.build_request(url, 0, want), timeout=PROBE_TIMEOUT_S
|
|
119
|
+
) as r:
|
|
416
120
|
status = getattr(r, "status", 200)
|
|
417
121
|
length = str(r.headers.get("Content-Length", ""))
|
|
418
122
|
ranged = status == 206 and _range_total(r) == size
|
|
@@ -438,13 +142,10 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
|
|
|
438
142
|
return got / max(1e-3, time.monotonic() - start), ranged
|
|
439
143
|
|
|
440
144
|
|
|
441
|
-
LONE_SMALL_BYTES = 1 << 20
|
|
442
|
-
|
|
443
|
-
|
|
444
145
|
def _probe_many(
|
|
445
|
-
sources: list[
|
|
146
|
+
sources: list[remote_ops_common.Source],
|
|
446
147
|
size: int,
|
|
447
|
-
) -> list[tuple[
|
|
148
|
+
) -> list[tuple[remote_ops_common.Source, tuple[float, bool] | None]]:
|
|
448
149
|
"""Probe ``sources`` concurrently so multi-mirror ranking completes in one RTT window."""
|
|
449
150
|
if not sources:
|
|
450
151
|
return []
|
|
@@ -452,7 +153,7 @@ def _probe_many(
|
|
|
452
153
|
return [(sources[0], probe(sources[0]["url"], size))]
|
|
453
154
|
results: list[tuple[float, bool] | None] = [None] * len(sources)
|
|
454
155
|
|
|
455
|
-
def run_one(idx: int, src:
|
|
156
|
+
def run_one(idx: int, src: remote_ops_common.Source) -> None:
|
|
456
157
|
results[idx] = probe(src["url"], size)
|
|
457
158
|
|
|
458
159
|
threads = [
|
|
@@ -467,10 +168,10 @@ def _probe_many(
|
|
|
467
168
|
|
|
468
169
|
|
|
469
170
|
def rank(
|
|
470
|
-
sources: list[
|
|
171
|
+
sources: list[remote_ops_common.Source],
|
|
471
172
|
size: int,
|
|
472
173
|
label: str,
|
|
473
|
-
unreachable: list[
|
|
174
|
+
unreachable: list[remote_ops_common.Source] | None = None,
|
|
474
175
|
) -> list[_Ranked]:
|
|
475
176
|
"""The sources fastest first, each with whether it serves ranges; ones that failed the probe
|
|
476
177
|
go last in plan order (and into ``unreachable``), so a passing hiccup still leaves them as
|
|
@@ -492,19 +193,19 @@ def rank(
|
|
|
492
193
|
measured.append((-result[0], i, (source, result[1])))
|
|
493
194
|
notes.append("{} {:.1f} MB/s".format(source["source"], result[0] / 1e6))
|
|
494
195
|
if len(sources) > 1:
|
|
495
|
-
|
|
196
|
+
remote_ops_common.emit(
|
|
496
197
|
"log", message="download sources for {}: {}".format(label, ", ".join(notes))
|
|
497
198
|
)
|
|
498
199
|
return [r for _, _, r in sorted(measured)] + failed
|
|
499
200
|
|
|
500
201
|
|
|
501
202
|
def _probe_batch(
|
|
502
|
-
batch: list[
|
|
203
|
+
batch: list[remote_ops_common.Source],
|
|
503
204
|
size: int,
|
|
504
205
|
region: str,
|
|
505
206
|
tier: int,
|
|
506
|
-
failed: list[
|
|
507
|
-
demoted: list[
|
|
207
|
+
failed: list[remote_ops_common.Source],
|
|
208
|
+
demoted: list[remote_ops_common.Source],
|
|
508
209
|
notes: list[str],
|
|
509
210
|
scored: list[tuple[float, int, int, int, _Ranked]],
|
|
510
211
|
probe_speeds: dict[str, float] | None,
|
|
@@ -527,12 +228,12 @@ def _probe_batch(
|
|
|
527
228
|
|
|
528
229
|
|
|
529
230
|
def _ordered_public(
|
|
530
|
-
own: list[
|
|
531
|
-
public_s: list[
|
|
231
|
+
own: list[remote_ops_common.Source],
|
|
232
|
+
public_s: list[remote_ops_common.Source],
|
|
532
233
|
size: int,
|
|
533
234
|
label: str,
|
|
534
235
|
region: str,
|
|
535
|
-
failed: list[
|
|
236
|
+
failed: list[remote_ops_common.Source],
|
|
536
237
|
probe_speeds: dict[str, float] | None,
|
|
537
238
|
) -> Iterator[_Ranked]:
|
|
538
239
|
public_probe = [s for s in public_s if not s.get("member")]
|
|
@@ -547,13 +248,15 @@ def _ordered_public(
|
|
|
547
248
|
primary = sorted([s for s in public_probe if side(s["url"]) == "cn"], key=cn_rank)
|
|
548
249
|
secondary = sorted([s for s in public_probe if side(s["url"]) != "cn"], key=cn_rank)
|
|
549
250
|
else:
|
|
550
|
-
primary = [
|
|
251
|
+
primary = [
|
|
252
|
+
s for s in own if not s.get("member") and not remote_ops_common.non_public(s["url"])
|
|
253
|
+
]
|
|
551
254
|
primary_urls = {s["url"] for s in primary}
|
|
552
255
|
secondary = [s for s in public_probe if s["url"] not in primary_urls]
|
|
553
256
|
|
|
554
257
|
notes: list[str] = []
|
|
555
258
|
scored: list[tuple[float, int, int, int, _Ranked]] = []
|
|
556
|
-
demoted: list[
|
|
259
|
+
demoted: list[remote_ops_common.Source] = []
|
|
557
260
|
best_primary = (
|
|
558
261
|
_probe_batch(primary, size, region, 0, failed, demoted, notes, scored, probe_speeds)
|
|
559
262
|
if primary
|
|
@@ -563,7 +266,7 @@ def _ordered_public(
|
|
|
563
266
|
if cross_probed:
|
|
564
267
|
_probe_batch(secondary, size, region, 1, failed, demoted, notes, scored, probe_speeds)
|
|
565
268
|
if notes:
|
|
566
|
-
|
|
269
|
+
remote_ops_common.emit(
|
|
567
270
|
"log", message=f"download sources for {label} (region {region}): {', '.join(notes)}"
|
|
568
271
|
)
|
|
569
272
|
|
|
@@ -581,11 +284,11 @@ def _ordered_public(
|
|
|
581
284
|
|
|
582
285
|
|
|
583
286
|
def ordered(
|
|
584
|
-
sources: list[
|
|
287
|
+
sources: list[remote_ops_common.Source],
|
|
585
288
|
size: int,
|
|
586
289
|
label: str,
|
|
587
290
|
region: str | None,
|
|
588
|
-
failed: list[
|
|
291
|
+
failed: list[remote_ops_common.Source],
|
|
589
292
|
probe_speeds: dict[str, float] | None = None,
|
|
590
293
|
) -> Iterator[_Ranked]:
|
|
591
294
|
"""Dynamic speed-first source ordering with tiered cross-region probing."""
|
|
@@ -595,8 +298,8 @@ def ordered(
|
|
|
595
298
|
yield from ((s, False) for s in own if s.get("member"))
|
|
596
299
|
return
|
|
597
300
|
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
|
|
301
|
+
local_s = [s for s in all_sources if remote_ops_common.non_public(s["url"])]
|
|
302
|
+
public_s = [s for s in all_sources if not remote_ops_common.non_public(s["url"])]
|
|
600
303
|
if local_s:
|
|
601
304
|
local_probe = [s for s in local_s if not s.get("member")]
|
|
602
305
|
if local_probe:
|
|
@@ -606,19 +309,8 @@ def ordered(
|
|
|
606
309
|
yield from _ordered_public(own, public_s, size, label, region, failed, probe_speeds)
|
|
607
310
|
|
|
608
311
|
|
|
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
312
|
def transfer(
|
|
621
|
-
source:
|
|
313
|
+
source: remote_ops_common.Source,
|
|
622
314
|
part: str,
|
|
623
315
|
size: int,
|
|
624
316
|
label: str,
|
|
@@ -632,25 +324,349 @@ def transfer(
|
|
|
632
324
|
that turns out not to serve ranges is read once as one plain stream from the start."""
|
|
633
325
|
if ranged:
|
|
634
326
|
count = remote_ops_ranges.connections_for(source)
|
|
635
|
-
job = remote_ops_ranges.
|
|
327
|
+
job = remote_ops_ranges.Transfer(
|
|
636
328
|
source["url"],
|
|
637
329
|
part,
|
|
638
330
|
size,
|
|
639
|
-
remote_ops_ranges.
|
|
331
|
+
remote_ops_ranges.resume_ranges(part, size, count),
|
|
640
332
|
attempts=attempts,
|
|
641
333
|
connections=count,
|
|
642
334
|
)
|
|
643
|
-
remote_ops_ranges.
|
|
644
|
-
|
|
645
|
-
|
|
335
|
+
remote_ops_ranges.run_transfer(
|
|
336
|
+
job, source, label, ranged=True, allow_slow_switch=allow_slow_switch
|
|
337
|
+
)
|
|
338
|
+
if not (job.errors and isinstance(job.errors[0], remote_ops_ranges.NoRangeError)):
|
|
339
|
+
remote_ops_ranges.finish_transfer(job, label)
|
|
646
340
|
return
|
|
647
|
-
discard(part)
|
|
341
|
+
remote_ops_common.discard(part)
|
|
648
342
|
open(part, "wb").close()
|
|
649
|
-
job = remote_ops_ranges.
|
|
650
|
-
remote_ops_ranges.
|
|
651
|
-
|
|
343
|
+
job = remote_ops_ranges.Transfer(source["url"], part, size, [[0, size, 0]], attempts=attempts)
|
|
344
|
+
remote_ops_ranges.run_transfer(
|
|
345
|
+
job, source, label, ranged=False, allow_slow_switch=allow_slow_switch
|
|
346
|
+
)
|
|
347
|
+
remote_ops_ranges.finish_transfer(job, label)
|
|
652
348
|
|
|
653
349
|
|
|
654
350
|
DEFAULT_TRANSFER = transfer
|
|
655
351
|
|
|
656
|
-
|
|
352
|
+
|
|
353
|
+
def _transfer_once(
|
|
354
|
+
source: remote_ops_common.Source,
|
|
355
|
+
part: str,
|
|
356
|
+
size: int,
|
|
357
|
+
label: str,
|
|
358
|
+
ranged: bool,
|
|
359
|
+
*,
|
|
360
|
+
probed_bad: bool,
|
|
361
|
+
allow_slow: bool,
|
|
362
|
+
) -> None:
|
|
363
|
+
if source.get("member"):
|
|
364
|
+
npm_transfer(source, part, size, label)
|
|
365
|
+
return
|
|
366
|
+
if probed_bad:
|
|
367
|
+
if allow_slow:
|
|
368
|
+
transfer(source, part, size, label, ranged, attempts=1, allow_slow_switch=True)
|
|
369
|
+
else:
|
|
370
|
+
transfer(source, part, size, label, ranged, attempts=1)
|
|
371
|
+
return
|
|
372
|
+
if allow_slow:
|
|
373
|
+
transfer(source, part, size, label, ranged, allow_slow_switch=True)
|
|
374
|
+
else:
|
|
375
|
+
transfer(source, part, size, label, ranged)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _fallback(
|
|
379
|
+
region: str | None,
|
|
380
|
+
used: remote_ops_common.Source,
|
|
381
|
+
failed: list[remote_ops_common.Source],
|
|
382
|
+
probe_speeds: dict[str, float] | None = None,
|
|
383
|
+
) -> str | None:
|
|
384
|
+
"""The other region, when ``used`` is on its side and either a source on the region's own
|
|
385
|
+
side failed/was slow-aborted first, or cross-region speed probing proved the other side was
|
|
386
|
+
decisively faster (>= 2x) while every probed preferred source was below
|
|
387
|
+
``CROSS_REGION_PROBE_BPS``. A neutral source (GitHub, a LAN or user mirror) never switches."""
|
|
388
|
+
other = side(used["url"])
|
|
389
|
+
if region not in ("cn", "global") or other in ("", region):
|
|
390
|
+
return None
|
|
391
|
+
mine = [s for s in failed if side(s["url"]) == region]
|
|
392
|
+
if mine:
|
|
393
|
+
return other
|
|
394
|
+
if probe_speeds:
|
|
395
|
+
used_speed = probe_speeds.get(used["url"], 0.0)
|
|
396
|
+
pref_speeds = [
|
|
397
|
+
bps for candidate_url, bps in probe_speeds.items() if side(candidate_url) == region
|
|
398
|
+
]
|
|
399
|
+
if (
|
|
400
|
+
used_speed > 0
|
|
401
|
+
and pref_speeds
|
|
402
|
+
and max(pref_speeds) < CROSS_REGION_PROBE_BPS
|
|
403
|
+
and used_speed >= 2.0 * max(pref_speeds)
|
|
404
|
+
):
|
|
405
|
+
return other
|
|
406
|
+
return None
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def fetch(
|
|
410
|
+
url: str,
|
|
411
|
+
dest: str,
|
|
412
|
+
sha256: str,
|
|
413
|
+
size: int,
|
|
414
|
+
label: str,
|
|
415
|
+
mirrors: list[remote_ops_common.Source] | None = None,
|
|
416
|
+
region: str | None = None,
|
|
417
|
+
) -> str | None:
|
|
418
|
+
"""Download ``url`` (or another source of the same pinned bytes: ``mirrors`` and, given a
|
|
419
|
+
``region``, the alternates that region adds) to ``dest`` unless a verified copy exists.
|
|
420
|
+
Resumes a .part file, from any source. Returns the region to switch to when the region's
|
|
421
|
+
own side failed or was decisively outperformed by the other side (also reported as
|
|
422
|
+
``region_fallback`` on the log event), else None."""
|
|
423
|
+
marker = dest + ".sha256"
|
|
424
|
+
if remote_ops_common.existing_verified(dest, marker, sha256, size, label):
|
|
425
|
+
return None
|
|
426
|
+
free = shutil.disk_usage(os.path.dirname(dest)).free
|
|
427
|
+
part = dest + ".part"
|
|
428
|
+
had_part = os.path.exists(part)
|
|
429
|
+
have = remote_ops_common.kept_bytes(part, size)
|
|
430
|
+
if have > size:
|
|
431
|
+
remote_ops_common.discard(part)
|
|
432
|
+
had_part, have = False, 0
|
|
433
|
+
if size - have > free:
|
|
434
|
+
raise RuntimeError(f"low disk space: {label} needs {size - have} more bytes, {free} free")
|
|
435
|
+
sources: list[remote_ops_common.Source] = [{"source": source_name(url), "url": url}]
|
|
436
|
+
sources += [m for m in mirrors or [] if m.get("url") and m["url"] != url]
|
|
437
|
+
error: Exception | None = None
|
|
438
|
+
failed: list[remote_ops_common.Source] = []
|
|
439
|
+
slow_urls: set[str] = set()
|
|
440
|
+
fresh_retried: set[str] = set()
|
|
441
|
+
deferred_slow: list[tuple[remote_ops_common.Source, bool]] = []
|
|
442
|
+
immediate: list[tuple[remote_ops_common.Source, bool]] = []
|
|
443
|
+
probe_speeds: dict[str, float] = {}
|
|
444
|
+
stream = iter(ordered(sources, size, label, region, failed, probe_speeds))
|
|
445
|
+
upcoming = next(stream, None)
|
|
446
|
+
supports_slow = transfer is DEFAULT_TRANSFER
|
|
447
|
+
|
|
448
|
+
while immediate or upcoming is not None or deferred_slow:
|
|
449
|
+
if immediate:
|
|
450
|
+
source, ranged = immediate.pop(0)
|
|
451
|
+
elif upcoming is not None:
|
|
452
|
+
source, ranged = upcoming
|
|
453
|
+
upcoming = next(stream, None)
|
|
454
|
+
else:
|
|
455
|
+
source, ranged = deferred_slow.pop(0)
|
|
456
|
+
probed_bad = any(f["url"] == source["url"] for f in failed)
|
|
457
|
+
has_more = (
|
|
458
|
+
bool(immediate)
|
|
459
|
+
or upcoming is not None
|
|
460
|
+
or any(s["url"] not in slow_urls for s, _ in deferred_slow)
|
|
461
|
+
)
|
|
462
|
+
allow_slow = supports_slow and has_more and source["url"] not in slow_urls
|
|
463
|
+
resumed_prior = os.path.exists(part) and os.path.getsize(part) > 0
|
|
464
|
+
try:
|
|
465
|
+
_transfer_once(
|
|
466
|
+
source, part, size, label, ranged, probed_bad=probed_bad, allow_slow=allow_slow
|
|
467
|
+
)
|
|
468
|
+
except SlowTransferError as exc:
|
|
469
|
+
remote_ops_common.emit(
|
|
470
|
+
"log",
|
|
471
|
+
message=(
|
|
472
|
+
f"download from {source['source']} is too slow for {label} ({exc}); "
|
|
473
|
+
"switching source"
|
|
474
|
+
),
|
|
475
|
+
)
|
|
476
|
+
error = exc
|
|
477
|
+
slow_urls.add(source["url"])
|
|
478
|
+
deferred_slow.append((source, ranged))
|
|
479
|
+
failed.append(source)
|
|
480
|
+
continue
|
|
481
|
+
except Exception as exc: # noqa: BLE001 - the next source is tried, the last re-raised
|
|
482
|
+
remote_ops_common.emit(
|
|
483
|
+
"log",
|
|
484
|
+
message=(
|
|
485
|
+
f"download from {source['source']} stopped, {label}: "
|
|
486
|
+
f"{remote_ops_common.redact_text(str(exc))}"
|
|
487
|
+
),
|
|
488
|
+
)
|
|
489
|
+
error = exc
|
|
490
|
+
failed.append(source)
|
|
491
|
+
continue
|
|
492
|
+
mismatch = remote_ops_common.check_part(part, sha256, size, label, source["source"])
|
|
493
|
+
if mismatch is not None:
|
|
494
|
+
error = mismatch
|
|
495
|
+
remote_ops_common.discard(part)
|
|
496
|
+
if resumed_prior and source["url"] not in fresh_retried:
|
|
497
|
+
fresh_retried.add(source["url"])
|
|
498
|
+
immediate.append((source, ranged))
|
|
499
|
+
continue
|
|
500
|
+
remote_ops_common.discard(part + ".ranges") # the record only; part is renamed
|
|
501
|
+
os.replace(part, dest)
|
|
502
|
+
if sha256:
|
|
503
|
+
remote_ops_common.write_text(marker, sha256)
|
|
504
|
+
remote_ops_common.store_cached(dest, sha256, size)
|
|
505
|
+
else:
|
|
506
|
+
remote_ops_common.write_text(marker, remote_ops_common.sha256_file(dest, label))
|
|
507
|
+
switch = _fallback(region, source, failed, probe_speeds)
|
|
508
|
+
extra = {"region_fallback": switch} if switch else {}
|
|
509
|
+
remote_ops_common.emit(
|
|
510
|
+
"log", message=f"downloaded and verified {label} from {source['source']}", **extra
|
|
511
|
+
)
|
|
512
|
+
return switch
|
|
513
|
+
if not had_part and remote_ops_common.kept_bytes(part, size) == 0:
|
|
514
|
+
remote_ops_common.discard(part)
|
|
515
|
+
raise error or RuntimeError(f"{label} has no download source")
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def act_engine(p: remote_ops_common.EngineParams) -> None:
|
|
519
|
+
"""Unpack the pinned release archives into p['dir']."""
|
|
520
|
+
directory = remote_ops_common.expand(p["dir"])
|
|
521
|
+
binary = os.path.join(directory, p.get("binary") or "llama-server")
|
|
522
|
+
done_marker = os.path.join(directory, ".complete")
|
|
523
|
+
expected = ",".join(a["sha256"] for a in p["assets"])
|
|
524
|
+
if os.path.exists(done_marker) and remote_ops_common.read_text(done_marker).strip() == expected:
|
|
525
|
+
remote_ops_common.emit("result", binary=binary, reused=True)
|
|
526
|
+
return
|
|
527
|
+
with remote_ops_mirrors.engine_lock(directory):
|
|
528
|
+
if (
|
|
529
|
+
os.path.exists(done_marker)
|
|
530
|
+
and remote_ops_common.read_text(done_marker).strip() == expected
|
|
531
|
+
):
|
|
532
|
+
remote_ops_common.emit("result", binary=binary, reused=True)
|
|
533
|
+
return
|
|
534
|
+
os.makedirs(directory, exist_ok=True)
|
|
535
|
+
cache = os.path.join(os.path.dirname(directory), ".archives")
|
|
536
|
+
active_region = p.get("region")
|
|
537
|
+
for i in remote_ops_common.each_file(
|
|
538
|
+
[(os.path.join(cache, a["name"]), a["size_bytes"]) for a in p["assets"]]
|
|
539
|
+
):
|
|
540
|
+
a = p["assets"][i]
|
|
541
|
+
archive = os.path.join(cache, a["name"])
|
|
542
|
+
switched = fetch(
|
|
543
|
+
a["url"],
|
|
544
|
+
archive,
|
|
545
|
+
a["sha256"],
|
|
546
|
+
a["size_bytes"],
|
|
547
|
+
a["name"],
|
|
548
|
+
npm_copies(a),
|
|
549
|
+
active_region,
|
|
550
|
+
)
|
|
551
|
+
if switched in ("cn", "global"):
|
|
552
|
+
active_region = switched
|
|
553
|
+
remote_ops_common.unpack(archive, directory, tuple(a.get("members") or ()))
|
|
554
|
+
if not os.access(binary, os.X_OK):
|
|
555
|
+
raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
|
|
556
|
+
remote_ops_common.write_text(done_marker, expected)
|
|
557
|
+
remote_ops_common.emit("result", binary=binary, reused=False)
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _verified_reuse_source(source: str, sha256: str, label: str) -> bool:
|
|
561
|
+
receipt = source + ".sha256"
|
|
562
|
+
try:
|
|
563
|
+
if os.path.isfile(receipt) and remote_ops_common.read_text(receipt).strip() == sha256:
|
|
564
|
+
return True
|
|
565
|
+
except (OSError, UnicodeError):
|
|
566
|
+
pass
|
|
567
|
+
if remote_ops_common.sha256_file(source, label) != sha256:
|
|
568
|
+
remote_ops_common.emit(
|
|
569
|
+
"log",
|
|
570
|
+
message=(
|
|
571
|
+
f"the existing copy of {label} has a SHA256 mismatch; downloading instead: {source}"
|
|
572
|
+
),
|
|
573
|
+
)
|
|
574
|
+
return False
|
|
575
|
+
return True
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def _link_copy(source: str, dest: str, sha256: str, size: int, label: str) -> None:
|
|
579
|
+
"""Hard-link (same device) or copy (cross-device) a verified copy the host already has;
|
|
580
|
+
any mismatch or error falls back to downloading."""
|
|
581
|
+
if os.path.exists(dest) or not os.path.isfile(source) or os.path.getsize(source) != size:
|
|
582
|
+
return
|
|
583
|
+
dest_dir = os.path.dirname(dest) or "."
|
|
584
|
+
os.makedirs(dest_dir, exist_ok=True)
|
|
585
|
+
if not _verified_reuse_source(source, sha256, label):
|
|
586
|
+
return
|
|
587
|
+
same_dev = os.stat(source).st_dev == os.stat(dest_dir).st_dev
|
|
588
|
+
if not same_dev:
|
|
589
|
+
free = shutil.disk_usage(dest_dir).free
|
|
590
|
+
if free < size:
|
|
591
|
+
remote_ops_common.emit(
|
|
592
|
+
"log",
|
|
593
|
+
message=(
|
|
594
|
+
f"not enough disk space to copy {label} "
|
|
595
|
+
f"({size} bytes needed, {free} free); downloading instead"
|
|
596
|
+
),
|
|
597
|
+
)
|
|
598
|
+
return
|
|
599
|
+
tmp = f"{dest}.reuse.{os.getpid()}"
|
|
600
|
+
with contextlib.suppress(OSError):
|
|
601
|
+
os.unlink(tmp)
|
|
602
|
+
try:
|
|
603
|
+
if same_dev:
|
|
604
|
+
os.link(source, tmp)
|
|
605
|
+
else:
|
|
606
|
+
shutil.copyfile(source, tmp)
|
|
607
|
+
os.replace(tmp, dest)
|
|
608
|
+
except OSError as exc:
|
|
609
|
+
with contextlib.suppress(OSError):
|
|
610
|
+
os.unlink(tmp)
|
|
611
|
+
remote_ops_common.emit(
|
|
612
|
+
"log",
|
|
613
|
+
message=f"could not reuse {source} for {label} ({exc}); downloading instead",
|
|
614
|
+
)
|
|
615
|
+
return
|
|
616
|
+
except BaseException:
|
|
617
|
+
with contextlib.suppress(OSError):
|
|
618
|
+
os.unlink(tmp)
|
|
619
|
+
raise
|
|
620
|
+
remote_ops_common.write_text(dest + ".sha256", sha256)
|
|
621
|
+
remote_ops_common.store_cached(dest, sha256, size)
|
|
622
|
+
remote_ops_common.emit(
|
|
623
|
+
"progress",
|
|
624
|
+
phase="download",
|
|
625
|
+
file=label,
|
|
626
|
+
done=size,
|
|
627
|
+
total=size,
|
|
628
|
+
bytes_per_s=size,
|
|
629
|
+
source="cache",
|
|
630
|
+
connections=0,
|
|
631
|
+
**remote_ops_common.step_fields(size),
|
|
632
|
+
)
|
|
633
|
+
remote_ops_common.emit("log", message="verified and reused the local file " + source)
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def act_download(p: remote_ops_common.DownloadParams) -> None:
|
|
637
|
+
remote_ops_common.set_auth_headers(p.get("auth_headers"))
|
|
638
|
+
try:
|
|
639
|
+
for f in p["files"]:
|
|
640
|
+
dest, label = remote_ops_common.expand(f["dest"]), os.path.basename(f["dest"])
|
|
641
|
+
if f.get("reuse") and f.get("sha256"):
|
|
642
|
+
reuse = os.path.realpath(remote_ops_common.expand(f["reuse"]))
|
|
643
|
+
_link_copy(reuse, dest, f["sha256"], f["size_bytes"], label)
|
|
644
|
+
if not p.get("preparation"):
|
|
645
|
+
remote_ops_prepare.verify_reused_outputs(p["files"])
|
|
646
|
+
files = [f for f in p["files"] if not f.get("generated")]
|
|
647
|
+
active_region = p.get("region")
|
|
648
|
+
for i in remote_ops_common.each_file(
|
|
649
|
+
[(remote_ops_common.expand(f["dest"]), f["size_bytes"]) for f in files]
|
|
650
|
+
):
|
|
651
|
+
f = files[i]
|
|
652
|
+
dest, label = remote_ops_common.expand(f["dest"]), os.path.basename(f["dest"])
|
|
653
|
+
if not f["url"] and not os.path.exists(dest + ".sha256"):
|
|
654
|
+
raise RuntimeError(
|
|
655
|
+
f"{f['dest']} has no download URL, and the reusable copy failed the SHA256 check"
|
|
656
|
+
)
|
|
657
|
+
switched = fetch(
|
|
658
|
+
f["url"],
|
|
659
|
+
dest,
|
|
660
|
+
f["sha256"],
|
|
661
|
+
f["size_bytes"],
|
|
662
|
+
label,
|
|
663
|
+
f.get("mirrors"),
|
|
664
|
+
active_region,
|
|
665
|
+
)
|
|
666
|
+
if switched in ("cn", "global"):
|
|
667
|
+
active_region = switched
|
|
668
|
+
if p.get("preparation"):
|
|
669
|
+
remote_ops_prepare.prepare(p["preparation"], p["files"], active_region, fetch_fn=fetch)
|
|
670
|
+
remote_ops_common.emit("result", files=len(p["files"]))
|
|
671
|
+
finally:
|
|
672
|
+
remote_ops_common.set_auth_headers(None)
|