@simplexai/localmodels-win32-x64 0.1.0-dev.59 → 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 +126 -107
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +107 -44
- package/modules/localmodels/apple_sensors.py +431 -0
- package/modules/localmodels/auth_proxy.py +185 -19
- package/modules/localmodels/bifrost_admin.py +30 -0
- package/modules/localmodels/bifrost_checks.py +2 -2
- package/modules/localmodels/bifrost_config.py +132 -9
- package/modules/localmodels/bifrost_models.py +1 -1
- package/modules/localmodels/catalog.json +509 -54
- package/modules/localmodels/catalog.py +21 -4
- package/modules/localmodels/catalog_add.py +42 -11
- 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.py +983 -0
- package/modules/localmodels/custom_hub_http.py +579 -0
- package/modules/localmodels/custom_probe.py +451 -0
- package/modules/localmodels/debug_mode.py +13 -0
- package/modules/localmodels/debug_stub_server.py +156 -1
- package/modules/localmodels/deploy.py +38 -7
- package/modules/localmodels/deploy_steps.py +5 -0
- package/modules/localmodels/download-mirrors.json +20 -0
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
- package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
- package/modules/localmodels/engines-whisper-b5454.json +120 -1
- package/modules/localmodels/engines.py +38 -8
- package/modules/localmodels/estimator.py +60 -7
- package/modules/localmodels/gateway.py +48 -3
- package/modules/localmodels/gateway_app_bifrost.py +18 -18
- package/modules/localmodels/gateway_bifrost.py +102 -16
- package/modules/localmodels/gateway_cli.py +14 -80
- package/modules/localmodels/gateway_server.py +88 -16
- package/modules/localmodels/gguf.py +6 -0
- 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/host_sensors.py +704 -0
- package/modules/localmodels/install.py +4 -4
- package/modules/localmodels/library_cli.py +181 -3
- package/modules/localmodels/library_custom.py +831 -0
- package/modules/localmodels/library_elastic.py +35 -7
- package/modules/localmodels/library_gateway.py +94 -32
- package/modules/localmodels/library_jobs.py +76 -11
- package/modules/localmodels/library_kept.py +50 -6
- package/modules/localmodels/library_model.py +254 -2
- package/modules/localmodels/library_pricing.py +83 -4
- package/modules/localmodels/library_serve.py +178 -60
- package/modules/localmodels/library_smoke.py +315 -0
- package/modules/localmodels/library_state.py +77 -1
- package/modules/localmodels/library_status.py +126 -4
- package/modules/localmodels/npm_transport.py +4 -58
- package/modules/localmodels/nvml_ctypes.py +431 -0
- package/modules/localmodels/plan_envelope.py +14 -6
- package/modules/localmodels/recommend_cli.py +2 -1
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/remote_ops.py +120 -665
- package/modules/localmodels/remote_ops_common.py +729 -0
- package/modules/localmodels/remote_ops_download.py +396 -241
- 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 -65
- package/modules/localmodels/remote_ops_remove.py +30 -22
- package/modules/localmodels/remote_ops_service.py +103 -95
- package/modules/localmodels/remote_ops_verify.py +113 -65
- package/modules/localmodels/runtime-lock.json +19 -19
- package/modules/localmodels/runtime_cli.py +15 -5
- package/modules/localmodels/runtime_io.py +54 -1
- package/modules/localmodels/service_control.py +32 -1
- package/modules/localmodels/service_wiring.py +2 -3
- package/modules/localmodels/service_worker.py +6 -2
- package/modules/localmodels/services_cli.py +35 -27
- package/modules/localmodels/source_byok.py +3 -5
- 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_lifecycle.py +2 -2
- package/modules/localmodels/stack_memory.py +14 -3
- package/modules/localmodels/stack_suite.py +9 -10
- package/modules/localmodels/stack_summary.py +4 -4
- package/modules/localmodels/stack_view.py +77 -53
- package/modules/localmodels/stack_view_demo.py +36 -5
- package/modules/localmodels/stack_view_events.py +147 -12
- package/modules/localmodels/stack_view_gpu.py +97 -17
- package/modules/localmodels/stack_view_llm.py +16 -1
- package/modules/localmodels/stack_view_measure.py +4 -1
- package/modules/localmodels/stack_view_schema.py +54 -8
- package/modules/localmodels/stack_view_serve.py +40 -3
- package/modules/localmodels/stack_view_slots.py +89 -10
- package/modules/localmodels/stack_view_telemetry.py +163 -0
- package/modules/localmodels/stack_view_text.py +5 -2
- package/modules/localmodels/stack_view_tick.py +658 -0
- package/modules/localmodels/stack_view_words.py +4 -0
- package/modules/localmodels/{strata-poly-serve-0.2.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
- package/modules/localmodels/suite.py +3 -1
- package/modules/localmodels/telemetry_math.py +538 -0
- package/modules/localmodels/transport.py +3 -2
- package/modules/localmodels/tui_views.py +2 -2
- package/modules/localmodels/web/view/view.js +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +123 -104
- package/modules/{simplex_localmodels-0.1.0.dev59.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/localmodels/bifrost_datasheet.py +0 -53
- package/modules/localmodels/bifrost_provider.py +0 -88
- package/modules/localmodels/bifrost_unit.py +0 -99
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +0 -94
- package/modules/localmodels/gateway_switch.py +0 -51
- package/modules/localmodels/library_floor.py +0 -78
- package/modules/localmodels/service_stop.py +0 -52
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -2,9 +2,9 @@
|
|
|
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
|
|
@@ -16,171 +16,24 @@ import shutil
|
|
|
16
16
|
import threading
|
|
17
17
|
import time
|
|
18
18
|
import urllib.error
|
|
19
|
-
import urllib.parse
|
|
20
|
-
import urllib.request
|
|
21
19
|
from typing import Iterator, Tuple
|
|
22
20
|
|
|
23
21
|
try:
|
|
24
22
|
from localmodels import (
|
|
25
23
|
process_identity_linux,
|
|
26
|
-
|
|
24
|
+
remote_ops_common,
|
|
27
25
|
remote_ops_mirrors,
|
|
28
26
|
remote_ops_prepare,
|
|
29
27
|
remote_ops_ranges,
|
|
30
28
|
)
|
|
31
29
|
except ImportError: # run as a bare file from this directory
|
|
32
30
|
import process_identity_linux # type: ignore[import-not-found,no-redef]
|
|
33
|
-
import
|
|
31
|
+
import remote_ops_common # type: ignore[import-not-found,no-redef]
|
|
34
32
|
import remote_ops_mirrors # type: ignore[import-not-found,no-redef]
|
|
35
33
|
import remote_ops_prepare # type: ignore[import-not-found,no-redef]
|
|
36
34
|
import remote_ops_ranges # type: ignore[import-not-found,no-redef]
|
|
37
35
|
|
|
38
|
-
_Ranked = Tuple["
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def act_engine(p: remote_ops.EngineParams) -> None:
|
|
42
|
-
"""Unpack the pinned release archives into p['dir']."""
|
|
43
|
-
directory = remote_ops._expand(p["dir"])
|
|
44
|
-
binary = os.path.join(directory, p.get("binary") or "llama-server")
|
|
45
|
-
done_marker = os.path.join(directory, ".complete")
|
|
46
|
-
expected = ",".join(a["sha256"] for a in p["assets"])
|
|
47
|
-
if os.path.exists(done_marker) and remote_ops._read(done_marker).strip() == expected:
|
|
48
|
-
remote_ops.emit("result", binary=binary, reused=True)
|
|
49
|
-
return
|
|
50
|
-
with remote_ops_mirrors.engine_lock(directory):
|
|
51
|
-
if os.path.exists(done_marker) and remote_ops._read(done_marker).strip() == expected:
|
|
52
|
-
remote_ops.emit("result", binary=binary, reused=True)
|
|
53
|
-
return
|
|
54
|
-
os.makedirs(directory, exist_ok=True)
|
|
55
|
-
cache = os.path.join(os.path.dirname(directory), ".archives")
|
|
56
|
-
active_region = p.get("region")
|
|
57
|
-
for i in remote_ops.each_file(
|
|
58
|
-
[(os.path.join(cache, a["name"]), a["size_bytes"]) for a in p["assets"]]
|
|
59
|
-
):
|
|
60
|
-
a = p["assets"][i]
|
|
61
|
-
archive = os.path.join(cache, a["name"])
|
|
62
|
-
switched = remote_ops.fetch(
|
|
63
|
-
a["url"],
|
|
64
|
-
archive,
|
|
65
|
-
a["sha256"],
|
|
66
|
-
a["size_bytes"],
|
|
67
|
-
a["name"],
|
|
68
|
-
npm_copies(a),
|
|
69
|
-
active_region,
|
|
70
|
-
)
|
|
71
|
-
if switched in ("cn", "global"):
|
|
72
|
-
active_region = switched
|
|
73
|
-
remote_ops.unpack(archive, directory, tuple(a.get("members") or ()))
|
|
74
|
-
if not os.access(binary, os.X_OK):
|
|
75
|
-
raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
|
|
76
|
-
remote_ops._write(done_marker, expected)
|
|
77
|
-
remote_ops.emit("result", binary=binary, reused=False)
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
def _verified_reuse_source(source: str, sha256: str, label: str) -> bool:
|
|
81
|
-
receipt = source + ".sha256"
|
|
82
|
-
try:
|
|
83
|
-
if os.path.isfile(receipt) and remote_ops._read(receipt).strip() == sha256:
|
|
84
|
-
return True
|
|
85
|
-
except (OSError, UnicodeError):
|
|
86
|
-
pass
|
|
87
|
-
if remote_ops._sha256(source, label) != sha256:
|
|
88
|
-
remote_ops.emit(
|
|
89
|
-
"log",
|
|
90
|
-
message=(
|
|
91
|
-
f"the existing copy of {label} has a SHA256 mismatch; downloading instead: {source}"
|
|
92
|
-
),
|
|
93
|
-
)
|
|
94
|
-
return False
|
|
95
|
-
return True
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def _link_copy(source: str, dest: str, sha256: str, size: int, label: str) -> None:
|
|
99
|
-
"""Hard-link (same device) or copy (cross-device) a verified copy the host already has;
|
|
100
|
-
any mismatch or error falls back to downloading."""
|
|
101
|
-
if os.path.exists(dest) or not os.path.isfile(source) or os.path.getsize(source) != size:
|
|
102
|
-
return
|
|
103
|
-
dest_dir = os.path.dirname(dest) or "."
|
|
104
|
-
os.makedirs(dest_dir, exist_ok=True)
|
|
105
|
-
if not _verified_reuse_source(source, sha256, label):
|
|
106
|
-
return
|
|
107
|
-
same_dev = os.stat(source).st_dev == os.stat(dest_dir).st_dev
|
|
108
|
-
if not same_dev:
|
|
109
|
-
free = shutil.disk_usage(dest_dir).free
|
|
110
|
-
if free < size:
|
|
111
|
-
remote_ops.emit(
|
|
112
|
-
"log",
|
|
113
|
-
message=(
|
|
114
|
-
f"not enough disk space to copy {label} "
|
|
115
|
-
f"({size} bytes needed, {free} free); downloading instead"
|
|
116
|
-
),
|
|
117
|
-
)
|
|
118
|
-
return
|
|
119
|
-
tmp = f"{dest}.reuse.{os.getpid()}"
|
|
120
|
-
with contextlib.suppress(OSError):
|
|
121
|
-
os.unlink(tmp)
|
|
122
|
-
try:
|
|
123
|
-
if same_dev:
|
|
124
|
-
os.link(source, tmp)
|
|
125
|
-
else:
|
|
126
|
-
shutil.copyfile(source, tmp)
|
|
127
|
-
os.replace(tmp, dest)
|
|
128
|
-
except OSError as exc:
|
|
129
|
-
with contextlib.suppress(OSError):
|
|
130
|
-
os.unlink(tmp)
|
|
131
|
-
remote_ops.emit(
|
|
132
|
-
"log",
|
|
133
|
-
message=f"could not reuse {source} for {label} ({exc}); downloading instead",
|
|
134
|
-
)
|
|
135
|
-
return
|
|
136
|
-
except BaseException:
|
|
137
|
-
with contextlib.suppress(OSError):
|
|
138
|
-
os.unlink(tmp)
|
|
139
|
-
raise
|
|
140
|
-
remote_ops._write(dest + ".sha256", sha256)
|
|
141
|
-
remote_ops._store_cached(dest, sha256, size)
|
|
142
|
-
remote_ops.emit(
|
|
143
|
-
"progress",
|
|
144
|
-
phase="download",
|
|
145
|
-
file=label,
|
|
146
|
-
done=size,
|
|
147
|
-
total=size,
|
|
148
|
-
bytes_per_s=size,
|
|
149
|
-
source="cache",
|
|
150
|
-
connections=0,
|
|
151
|
-
**remote_ops.step_fields(size),
|
|
152
|
-
)
|
|
153
|
-
remote_ops.emit("log", message="verified and reused the local file " + source)
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
def act_download(p: remote_ops.DownloadParams) -> None:
|
|
157
|
-
for f in p["files"]:
|
|
158
|
-
dest, label = remote_ops._expand(f["dest"]), os.path.basename(f["dest"])
|
|
159
|
-
if f.get("reuse"):
|
|
160
|
-
reuse = os.path.realpath(remote_ops._expand(f["reuse"]))
|
|
161
|
-
_link_copy(reuse, dest, f["sha256"], f["size_bytes"], label)
|
|
162
|
-
if not p.get("preparation"):
|
|
163
|
-
remote_ops_prepare.verify_reused_outputs(p["files"])
|
|
164
|
-
files = [f for f in p["files"] if not f.get("generated")]
|
|
165
|
-
active_region = p.get("region")
|
|
166
|
-
for i in remote_ops.each_file(
|
|
167
|
-
[(remote_ops._expand(f["dest"]), f["size_bytes"]) for f in files]
|
|
168
|
-
):
|
|
169
|
-
f = files[i]
|
|
170
|
-
dest, label = remote_ops._expand(f["dest"]), os.path.basename(f["dest"])
|
|
171
|
-
if not f["url"] and not os.path.exists(dest + ".sha256"):
|
|
172
|
-
raise RuntimeError(
|
|
173
|
-
f"{f['dest']} has no download URL, and the reusable copy failed the SHA256 check"
|
|
174
|
-
)
|
|
175
|
-
switched = remote_ops.fetch(
|
|
176
|
-
f["url"], dest, f["sha256"], f["size_bytes"], label, f.get("mirrors"), active_region
|
|
177
|
-
)
|
|
178
|
-
if switched in ("cn", "global"):
|
|
179
|
-
active_region = switched
|
|
180
|
-
if p.get("preparation"):
|
|
181
|
-
remote_ops_prepare.prepare(p["preparation"], p["files"], active_region)
|
|
182
|
-
remote_ops.emit("result", files=len(p["files"]))
|
|
183
|
-
|
|
36
|
+
_Ranked = Tuple["remote_ops_common.Source", bool] # a source and whether it serves byte ranges
|
|
184
37
|
|
|
185
38
|
# Weights and pinned archives are verified by SHA256, so any source serving the same bytes is
|
|
186
39
|
# safe: ``fetch`` concurrently probes candidates, ranks them by actual throughput, downloads in
|
|
@@ -193,36 +46,26 @@ PROBE_SAMPLE_S = 3.0 # once sampled for 3s, stop reading slow mirrors instead o
|
|
|
193
46
|
# also probe the opposite region's mirrors so a misclassified region or throttled upstream
|
|
194
47
|
# immediately yields to a faster mirror (e.g., 880 KB/s Tsinghua beating 39 KB/s official PyPI).
|
|
195
48
|
CROSS_REGION_PROBE_BPS = 2_000_000
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
# range took up to 3 s (a redirect, then TLS to the CDN), so a slow start is not a stall.
|
|
217
|
-
CLAIM_STALL_S = 20.0
|
|
218
|
-
CLAIM_RATE_WINDOW_S = 10.0
|
|
219
|
-
STEAL_POLL_S = 0.5 # how often an idle connection looks for a range to steal
|
|
220
|
-
ATTEMPTS = 5
|
|
221
|
-
# A connection's progress moves once per read, so reads stay small: an 8 MiB read at 2-3 MB/s
|
|
222
|
-
# per connection made the 2 s rate jump in 4 MiB/s steps (often 0). The rate shown is the
|
|
223
|
-
# average over RATE_WINDOW_S, so a stall or burst of one connection does not swing the ETA.
|
|
224
|
-
READ_BYTES = 1 << 20
|
|
225
|
-
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
|
+
|
|
226
69
|
WEB = remote_ops_mirrors.WEB
|
|
227
70
|
SOURCE_HOSTS = remote_ops_mirrors.SOURCE_HOSTS
|
|
228
71
|
GLOBAL_HOSTS = remote_ops_mirrors.GLOBAL_HOSTS
|
|
@@ -240,23 +83,21 @@ alternates = remote_ops_mirrors.alternates
|
|
|
240
83
|
npm_copies = remote_ops_mirrors.npm_copies
|
|
241
84
|
candidates = remote_ops_mirrors.candidates
|
|
242
85
|
_web = remote_ops_mirrors.is_web
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
kept_bytes = remote_ops_mirrors.kept_bytes
|
|
247
|
-
discard = remote_ops_mirrors.discard
|
|
248
|
-
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
|
|
249
89
|
bind_to_parent = process_identity_linux.bind_to_parent
|
|
90
|
+
Rate = remote_ops_mirrors.Rate
|
|
250
91
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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
|
|
254
97
|
|
|
255
98
|
|
|
256
|
-
def
|
|
257
|
-
|
|
258
|
-
request.add_header("Range", f"bytes={start}-{end - 1}")
|
|
259
|
-
return request
|
|
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)
|
|
260
101
|
|
|
261
102
|
|
|
262
103
|
def _range_total(response: object) -> int | None:
|
|
@@ -273,7 +114,9 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
|
|
|
273
114
|
want = min(size, PROBE_BYTES)
|
|
274
115
|
start, got = time.monotonic(), 0
|
|
275
116
|
try:
|
|
276
|
-
with
|
|
117
|
+
with remote_ops_common.open_url(
|
|
118
|
+
remote_ops_common.build_request(url, 0, want), timeout=PROBE_TIMEOUT_S
|
|
119
|
+
) as r:
|
|
277
120
|
status = getattr(r, "status", 200)
|
|
278
121
|
length = str(r.headers.get("Content-Length", ""))
|
|
279
122
|
ranged = status == 206 and _range_total(r) == size
|
|
@@ -299,13 +142,10 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
|
|
|
299
142
|
return got / max(1e-3, time.monotonic() - start), ranged
|
|
300
143
|
|
|
301
144
|
|
|
302
|
-
LONE_SMALL_BYTES = 1 << 20
|
|
303
|
-
|
|
304
|
-
|
|
305
145
|
def _probe_many(
|
|
306
|
-
sources: list[
|
|
146
|
+
sources: list[remote_ops_common.Source],
|
|
307
147
|
size: int,
|
|
308
|
-
) -> list[tuple[
|
|
148
|
+
) -> list[tuple[remote_ops_common.Source, tuple[float, bool] | None]]:
|
|
309
149
|
"""Probe ``sources`` concurrently so multi-mirror ranking completes in one RTT window."""
|
|
310
150
|
if not sources:
|
|
311
151
|
return []
|
|
@@ -313,7 +153,7 @@ def _probe_many(
|
|
|
313
153
|
return [(sources[0], probe(sources[0]["url"], size))]
|
|
314
154
|
results: list[tuple[float, bool] | None] = [None] * len(sources)
|
|
315
155
|
|
|
316
|
-
def run_one(idx: int, src:
|
|
156
|
+
def run_one(idx: int, src: remote_ops_common.Source) -> None:
|
|
317
157
|
results[idx] = probe(src["url"], size)
|
|
318
158
|
|
|
319
159
|
threads = [
|
|
@@ -328,10 +168,10 @@ def _probe_many(
|
|
|
328
168
|
|
|
329
169
|
|
|
330
170
|
def rank(
|
|
331
|
-
sources: list[
|
|
171
|
+
sources: list[remote_ops_common.Source],
|
|
332
172
|
size: int,
|
|
333
173
|
label: str,
|
|
334
|
-
unreachable: list[
|
|
174
|
+
unreachable: list[remote_ops_common.Source] | None = None,
|
|
335
175
|
) -> list[_Ranked]:
|
|
336
176
|
"""The sources fastest first, each with whether it serves ranges; ones that failed the probe
|
|
337
177
|
go last in plan order (and into ``unreachable``), so a passing hiccup still leaves them as
|
|
@@ -353,19 +193,19 @@ def rank(
|
|
|
353
193
|
measured.append((-result[0], i, (source, result[1])))
|
|
354
194
|
notes.append("{} {:.1f} MB/s".format(source["source"], result[0] / 1e6))
|
|
355
195
|
if len(sources) > 1:
|
|
356
|
-
|
|
196
|
+
remote_ops_common.emit(
|
|
357
197
|
"log", message="download sources for {}: {}".format(label, ", ".join(notes))
|
|
358
198
|
)
|
|
359
199
|
return [r for _, _, r in sorted(measured)] + failed
|
|
360
200
|
|
|
361
201
|
|
|
362
202
|
def _probe_batch(
|
|
363
|
-
batch: list[
|
|
203
|
+
batch: list[remote_ops_common.Source],
|
|
364
204
|
size: int,
|
|
365
205
|
region: str,
|
|
366
206
|
tier: int,
|
|
367
|
-
failed: list[
|
|
368
|
-
demoted: list[
|
|
207
|
+
failed: list[remote_ops_common.Source],
|
|
208
|
+
demoted: list[remote_ops_common.Source],
|
|
369
209
|
notes: list[str],
|
|
370
210
|
scored: list[tuple[float, int, int, int, _Ranked]],
|
|
371
211
|
probe_speeds: dict[str, float] | None,
|
|
@@ -388,12 +228,12 @@ def _probe_batch(
|
|
|
388
228
|
|
|
389
229
|
|
|
390
230
|
def _ordered_public(
|
|
391
|
-
own: list[
|
|
392
|
-
public_s: list[
|
|
231
|
+
own: list[remote_ops_common.Source],
|
|
232
|
+
public_s: list[remote_ops_common.Source],
|
|
393
233
|
size: int,
|
|
394
234
|
label: str,
|
|
395
235
|
region: str,
|
|
396
|
-
failed: list[
|
|
236
|
+
failed: list[remote_ops_common.Source],
|
|
397
237
|
probe_speeds: dict[str, float] | None,
|
|
398
238
|
) -> Iterator[_Ranked]:
|
|
399
239
|
public_probe = [s for s in public_s if not s.get("member")]
|
|
@@ -408,13 +248,15 @@ def _ordered_public(
|
|
|
408
248
|
primary = sorted([s for s in public_probe if side(s["url"]) == "cn"], key=cn_rank)
|
|
409
249
|
secondary = sorted([s for s in public_probe if side(s["url"]) != "cn"], key=cn_rank)
|
|
410
250
|
else:
|
|
411
|
-
primary = [
|
|
251
|
+
primary = [
|
|
252
|
+
s for s in own if not s.get("member") and not remote_ops_common.non_public(s["url"])
|
|
253
|
+
]
|
|
412
254
|
primary_urls = {s["url"] for s in primary}
|
|
413
255
|
secondary = [s for s in public_probe if s["url"] not in primary_urls]
|
|
414
256
|
|
|
415
257
|
notes: list[str] = []
|
|
416
258
|
scored: list[tuple[float, int, int, int, _Ranked]] = []
|
|
417
|
-
demoted: list[
|
|
259
|
+
demoted: list[remote_ops_common.Source] = []
|
|
418
260
|
best_primary = (
|
|
419
261
|
_probe_batch(primary, size, region, 0, failed, demoted, notes, scored, probe_speeds)
|
|
420
262
|
if primary
|
|
@@ -424,7 +266,7 @@ def _ordered_public(
|
|
|
424
266
|
if cross_probed:
|
|
425
267
|
_probe_batch(secondary, size, region, 1, failed, demoted, notes, scored, probe_speeds)
|
|
426
268
|
if notes:
|
|
427
|
-
|
|
269
|
+
remote_ops_common.emit(
|
|
428
270
|
"log", message=f"download sources for {label} (region {region}): {', '.join(notes)}"
|
|
429
271
|
)
|
|
430
272
|
|
|
@@ -442,11 +284,11 @@ def _ordered_public(
|
|
|
442
284
|
|
|
443
285
|
|
|
444
286
|
def ordered(
|
|
445
|
-
sources: list[
|
|
287
|
+
sources: list[remote_ops_common.Source],
|
|
446
288
|
size: int,
|
|
447
289
|
label: str,
|
|
448
290
|
region: str | None,
|
|
449
|
-
failed: list[
|
|
291
|
+
failed: list[remote_ops_common.Source],
|
|
450
292
|
probe_speeds: dict[str, float] | None = None,
|
|
451
293
|
) -> Iterator[_Ranked]:
|
|
452
294
|
"""Dynamic speed-first source ordering with tiered cross-region probing."""
|
|
@@ -456,8 +298,8 @@ def ordered(
|
|
|
456
298
|
yield from ((s, False) for s in own if s.get("member"))
|
|
457
299
|
return
|
|
458
300
|
all_sources = own + extra
|
|
459
|
-
local_s = [s for s in all_sources if
|
|
460
|
-
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"])]
|
|
461
303
|
if local_s:
|
|
462
304
|
local_probe = [s for s in local_s if not s.get("member")]
|
|
463
305
|
if local_probe:
|
|
@@ -467,19 +309,8 @@ def ordered(
|
|
|
467
309
|
yield from _ordered_public(own, public_s, size, label, region, failed, probe_speeds)
|
|
468
310
|
|
|
469
311
|
|
|
470
|
-
class SlowTransferError(RuntimeError):
|
|
471
|
-
"""Sustained transfer throughput dropped below SLOW_BYTES_PER_S; switch to another host."""
|
|
472
|
-
|
|
473
|
-
def __init__(self, bytes_per_s: int) -> None:
|
|
474
|
-
self.bytes_per_s = bytes_per_s
|
|
475
|
-
super().__init__(
|
|
476
|
-
f"download too slow ({bytes_per_s / 1024:.0f} KB/s < "
|
|
477
|
-
f"{SLOW_BYTES_PER_S / 1024:.0f} KB/s)"
|
|
478
|
-
)
|
|
479
|
-
|
|
480
|
-
|
|
481
312
|
def transfer(
|
|
482
|
-
source:
|
|
313
|
+
source: remote_ops_common.Source,
|
|
483
314
|
part: str,
|
|
484
315
|
size: int,
|
|
485
316
|
label: str,
|
|
@@ -493,25 +324,349 @@ def transfer(
|
|
|
493
324
|
that turns out not to serve ranges is read once as one plain stream from the start."""
|
|
494
325
|
if ranged:
|
|
495
326
|
count = remote_ops_ranges.connections_for(source)
|
|
496
|
-
job = remote_ops_ranges.
|
|
327
|
+
job = remote_ops_ranges.Transfer(
|
|
497
328
|
source["url"],
|
|
498
329
|
part,
|
|
499
330
|
size,
|
|
500
|
-
remote_ops_ranges.
|
|
331
|
+
remote_ops_ranges.resume_ranges(part, size, count),
|
|
501
332
|
attempts=attempts,
|
|
502
333
|
connections=count,
|
|
503
334
|
)
|
|
504
|
-
remote_ops_ranges.
|
|
505
|
-
|
|
506
|
-
|
|
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)
|
|
507
340
|
return
|
|
508
|
-
discard(part)
|
|
341
|
+
remote_ops_common.discard(part)
|
|
509
342
|
open(part, "wb").close()
|
|
510
|
-
job = remote_ops_ranges.
|
|
511
|
-
remote_ops_ranges.
|
|
512
|
-
|
|
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)
|
|
513
348
|
|
|
514
349
|
|
|
515
350
|
DEFAULT_TRANSFER = transfer
|
|
516
351
|
|
|
517
|
-
|
|
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)
|