@simplexai/localmodels-darwin-arm64 0.1.0-dev.54 → 0.1.0-dev.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +43 -38
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/bifrost_admin.py +336 -0
- package/modules/localmodels/bifrost_checks.py +12 -2
- package/modules/localmodels/bifrost_config.py +13 -5
- package/modules/localmodels/catalog.json +2 -1
- package/modules/localmodels/debug_mode.py +6 -3
- package/modules/localmodels/engines.py +24 -1
- package/modules/localmodels/library_floor.py +3 -1
- package/modules/localmodels/library_gateway.py +26 -4
- package/modules/localmodels/library_jobs.py +44 -6
- package/modules/localmodels/library_kept.py +117 -0
- package/modules/localmodels/library_model.py +1 -0
- package/modules/localmodels/library_order.py +234 -0
- package/modules/localmodels/library_poly.py +20 -16
- package/modules/localmodels/library_pricing.py +8 -1
- package/modules/localmodels/library_serve.py +9 -3
- package/modules/localmodels/library_state.py +12 -2
- package/modules/localmodels/library_status.py +2 -0
- package/modules/localmodels/llm_rank.py +11 -8
- package/modules/localmodels/mirrors.py +464 -0
- package/modules/localmodels/recommend.py +2 -2
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/region.py +457 -42
- package/modules/localmodels/remote_ops.py +130 -33
- package/modules/localmodels/remote_ops_download.py +313 -273
- package/modules/localmodels/remote_ops_mirrors.py +290 -0
- package/modules/localmodels/runtime-lock.json +19 -19
- package/modules/localmodels/runtime_io.py +2 -4
- package/modules/localmodels/runtime_releases.py +6 -0
- package/modules/localmodels/setup_inspection.py +4 -0
- package/modules/localmodels/stack_auto.py +38 -5
- package/modules/localmodels/stack_compose.py +2 -1
- package/modules/localmodels/stack_try.py +4 -1
- package/modules/localmodels/transport.py +1 -0
- package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/RECORD +40 -35
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -9,24 +9,22 @@ private-name imports.
|
|
|
9
9
|
|
|
10
10
|
from __future__ import annotations
|
|
11
11
|
|
|
12
|
-
import collections
|
|
13
12
|
import contextlib
|
|
14
13
|
import http.client
|
|
15
|
-
import json
|
|
16
14
|
import os
|
|
17
15
|
import shutil
|
|
18
|
-
import tarfile
|
|
19
16
|
import threading
|
|
20
17
|
import time
|
|
21
18
|
import urllib.error
|
|
22
19
|
import urllib.parse
|
|
23
20
|
import urllib.request
|
|
24
|
-
from typing import Iterator, Tuple
|
|
21
|
+
from typing import Any, Iterator, Tuple
|
|
25
22
|
|
|
26
23
|
try:
|
|
27
|
-
from localmodels import remote_ops, remote_ops_prepare
|
|
24
|
+
from localmodels import remote_ops, remote_ops_mirrors, remote_ops_prepare
|
|
28
25
|
except ImportError: # run as a bare file from this directory
|
|
29
26
|
import remote_ops # type: ignore[import-not-found,no-redef]
|
|
27
|
+
import remote_ops_mirrors # type: ignore[import-not-found,no-redef]
|
|
30
28
|
import remote_ops_prepare # type: ignore[import-not-found,no-redef]
|
|
31
29
|
|
|
32
30
|
_Ranked = Tuple["remote_ops.Source", bool] # a source and whether it serves byte ranges
|
|
@@ -43,20 +41,23 @@ def act_engine(p: remote_ops.EngineParams) -> None:
|
|
|
43
41
|
return
|
|
44
42
|
os.makedirs(directory, exist_ok=True)
|
|
45
43
|
cache = os.path.join(os.path.dirname(directory), ".archives")
|
|
44
|
+
active_region = p.get("region")
|
|
46
45
|
for i in remote_ops.each_file(
|
|
47
46
|
[(os.path.join(cache, a["name"]), a["size_bytes"]) for a in p["assets"]]
|
|
48
47
|
):
|
|
49
48
|
a = p["assets"][i]
|
|
50
49
|
archive = os.path.join(cache, a["name"])
|
|
51
|
-
remote_ops.fetch(
|
|
50
|
+
switched = remote_ops.fetch(
|
|
52
51
|
a["url"],
|
|
53
52
|
archive,
|
|
54
53
|
a["sha256"],
|
|
55
54
|
a["size_bytes"],
|
|
56
55
|
a["name"],
|
|
57
56
|
npm_copies(a),
|
|
58
|
-
|
|
57
|
+
active_region,
|
|
59
58
|
)
|
|
59
|
+
if switched in ("cn", "global"):
|
|
60
|
+
active_region = switched
|
|
60
61
|
remote_ops.unpack(archive, directory, tuple(a.get("members") or ()))
|
|
61
62
|
if not os.access(binary, os.X_OK):
|
|
62
63
|
raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
|
|
@@ -149,6 +150,7 @@ def act_download(p: remote_ops.DownloadParams) -> None:
|
|
|
149
150
|
if not p.get("preparation"):
|
|
150
151
|
remote_ops_prepare.verify_reused_outputs(p["files"])
|
|
151
152
|
files = [f for f in p["files"] if not f.get("generated")]
|
|
153
|
+
active_region = p.get("region")
|
|
152
154
|
for i in remote_ops.each_file(
|
|
153
155
|
[(remote_ops._expand(f["dest"]), f["size_bytes"]) for f in files]
|
|
154
156
|
):
|
|
@@ -158,19 +160,32 @@ def act_download(p: remote_ops.DownloadParams) -> None:
|
|
|
158
160
|
raise RuntimeError(
|
|
159
161
|
f"{f['dest']} has no download URL, and the reusable copy failed the SHA256 check"
|
|
160
162
|
)
|
|
161
|
-
remote_ops.fetch(
|
|
162
|
-
f["url"], dest, f["sha256"], f["size_bytes"], label, f.get("mirrors"),
|
|
163
|
+
switched = remote_ops.fetch(
|
|
164
|
+
f["url"], dest, f["sha256"], f["size_bytes"], label, f.get("mirrors"), active_region
|
|
163
165
|
)
|
|
166
|
+
if switched in ("cn", "global"):
|
|
167
|
+
active_region = switched
|
|
164
168
|
if p.get("preparation"):
|
|
165
|
-
remote_ops_prepare.prepare(p["preparation"], p["files"],
|
|
169
|
+
remote_ops_prepare.prepare(p["preparation"], p["files"], active_region)
|
|
166
170
|
remote_ops.emit("result", files=len(p["files"]))
|
|
167
171
|
|
|
168
172
|
|
|
169
|
-
# Weights
|
|
170
|
-
#
|
|
171
|
-
# ranges,
|
|
173
|
+
# Weights and pinned archives are verified by SHA256, so any source serving the same bytes is
|
|
174
|
+
# safe: ``fetch`` concurrently probes candidates, ranks them by actual throughput, downloads in
|
|
175
|
+
# parallel byte ranges, switches away from hosts that stall or throttle mid-transfer, and falls
|
|
176
|
+
# back cleanly on failure or digest mismatch.
|
|
172
177
|
PROBE_BYTES = 8 << 20
|
|
173
|
-
PROBE_TIMEOUT_S =
|
|
178
|
+
PROBE_TIMEOUT_S = 6.0
|
|
179
|
+
PROBE_SAMPLE_S = 3.0 # once sampled for 3s, stop reading slow mirrors instead of waiting 6-10s
|
|
180
|
+
# If the preferred region's fastest reachable candidate is slower than CROSS_REGION_PROBE_BPS,
|
|
181
|
+
# also probe the opposite region's mirrors so a misclassified region or throttled upstream
|
|
182
|
+
# immediately yields to a faster mirror (e.g., 880 KB/s Tsinghua beating 39 KB/s official PyPI).
|
|
183
|
+
CROSS_REGION_PROBE_BPS = 2_000_000
|
|
184
|
+
# Switch away from a transfer whose sustained throughput over SLOW_WINDOW_S stays below
|
|
185
|
+
# SLOW_BYTES_PER_S while more than SLOW_MIN_REMAINING_S of transfer time remains.
|
|
186
|
+
SLOW_WINDOW_S = 15.0
|
|
187
|
+
SLOW_BYTES_PER_S = 256 * 1024
|
|
188
|
+
SLOW_MIN_REMAINING_S = 30.0
|
|
174
189
|
SEGMENTS = 4
|
|
175
190
|
MIN_SEGMENT_BYTES = 64 << 20
|
|
176
191
|
ATTEMPTS = 5
|
|
@@ -179,106 +194,32 @@ ATTEMPTS = 5
|
|
|
179
194
|
# average over RATE_WINDOW_S, so a stall or burst of one connection does not swing the ETA.
|
|
180
195
|
READ_BYTES = 1 << 20
|
|
181
196
|
RATE_WINDOW_S = 10.0
|
|
182
|
-
WEB =
|
|
183
|
-
SOURCE_HOSTS =
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
# Region cn's order by label; within one rank the plan's order holds. A non-public source (a
|
|
205
|
-
# LAN registry or mirror, remote_ops.non_public) comes first, then ModelScope and the npm
|
|
206
|
-
# mirror, then another neutral source (a user's public mirror, the original GitHub asset), then
|
|
207
|
-
# hf-mirror.com, then the global hosts.
|
|
208
|
-
CN_RANK = {"modelscope": 1, "npmmirror": 1, "custom": 2, "hf-mirror": 3}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
def cn_rank(source: remote_ops.Source) -> int:
|
|
212
|
-
return 0 if remote_ops.non_public(source["url"]) else CN_RANK.get(source["source"], 4)
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
NPM_OVERHEAD_BYTES = 4 << 20
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
def _host_in(url: str, domains: tuple[str, ...]) -> bool:
|
|
219
|
-
host = (urllib.parse.urlsplit(url).hostname or "").lower()
|
|
220
|
-
return any(host == d or host.endswith("." + d) for d in domains)
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
def source_name(url: str) -> str:
|
|
224
|
-
"""The public label of a download URL: huggingface, hf-mirror, modelscope, npmmirror or
|
|
225
|
-
custom (never the URL)."""
|
|
226
|
-
for domain, name in SOURCE_HOSTS:
|
|
227
|
-
if _host_in(url, (domain,)):
|
|
228
|
-
return name
|
|
229
|
-
return "custom"
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
def side(url: str) -> str:
|
|
233
|
-
"""``cn``, ``global`` or "" (neutral) for a download URL."""
|
|
234
|
-
return "cn" if _host_in(url, CN_HOSTS) else "global" if _host_in(url, GLOBAL_HOSTS) else ""
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
def alternates(source: remote_ops.Source) -> list[remote_ops.Source]:
|
|
238
|
-
"""Other hosts that serve the same path: hf-mirror.com for huggingface.co, the npm mirror for
|
|
239
|
-
the npm registry and nodejs.org's releases, and the other way round."""
|
|
240
|
-
found: list[remote_ops.Source] = []
|
|
241
|
-
for pair in ALTERNATES:
|
|
242
|
-
for here, there in (pair, pair[::-1]):
|
|
243
|
-
if source["url"].startswith(here):
|
|
244
|
-
url = there + source["url"][len(here) :]
|
|
245
|
-
other: remote_ops.Source = {"source": source_name(url), "url": url}
|
|
246
|
-
if source.get("member"):
|
|
247
|
-
other["member"] = source["member"]
|
|
248
|
-
found.append(other)
|
|
249
|
-
return found
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
def npm_copies(asset: remote_ops.Archive) -> list[remote_ops.Source]:
|
|
253
|
-
"""The npm packages holding a byte-identical copy of ``asset`` (``npm_copy`` in the engine
|
|
254
|
-
and tool locks), on the npm registry and its China mirror; the copy is the package's file of
|
|
255
|
-
the asset's name, and its SHA256 pin is the asset's."""
|
|
256
|
-
copy = asset.get("npm_copy")
|
|
257
|
-
if not copy:
|
|
258
|
-
return []
|
|
259
|
-
name, version = copy["package"], copy["version"]
|
|
260
|
-
tail = f"{name}/-/{name.split('/')[-1]}-{version}.tgz"
|
|
261
|
-
return [
|
|
262
|
-
{"source": label, "url": f"{base}/{tail}", "member": "package/" + asset["name"]}
|
|
263
|
-
for label, base in NPM_REGISTRIES
|
|
264
|
-
]
|
|
197
|
+
WEB = remote_ops_mirrors.WEB
|
|
198
|
+
SOURCE_HOSTS = remote_ops_mirrors.SOURCE_HOSTS
|
|
199
|
+
GLOBAL_HOSTS = remote_ops_mirrors.GLOBAL_HOSTS
|
|
200
|
+
CN_HOSTS = remote_ops_mirrors.CN_HOSTS
|
|
201
|
+
MIRROR_GROUPS = remote_ops_mirrors.MIRROR_GROUPS
|
|
202
|
+
ALTERNATES = remote_ops_mirrors.ALTERNATES
|
|
203
|
+
NPM_REGISTRIES = remote_ops_mirrors.NPM_REGISTRIES
|
|
204
|
+
CN_RANK = remote_ops_mirrors.CN_RANK
|
|
205
|
+
NPM_OVERHEAD_BYTES = remote_ops_mirrors.NPM_OVERHEAD_BYTES
|
|
206
|
+
|
|
207
|
+
cn_rank = remote_ops_mirrors.cn_rank
|
|
208
|
+
source_name = remote_ops_mirrors.source_name
|
|
209
|
+
side = remote_ops_mirrors.side
|
|
210
|
+
alternates = remote_ops_mirrors.alternates
|
|
211
|
+
npm_copies = remote_ops_mirrors.npm_copies
|
|
212
|
+
candidates = remote_ops_mirrors.candidates
|
|
213
|
+
_web = remote_ops_mirrors.is_web
|
|
214
|
+
_state_path = remote_ops_mirrors.state_path
|
|
215
|
+
_load_ranges = remote_ops_mirrors.load_ranges
|
|
216
|
+
_save_ranges = remote_ops_mirrors.save_ranges
|
|
217
|
+
kept_bytes = remote_ops_mirrors.kept_bytes
|
|
218
|
+
discard = remote_ops_mirrors.discard
|
|
265
219
|
|
|
266
220
|
|
|
267
|
-
def
|
|
268
|
-
|
|
269
|
-
) -> tuple[list[remote_ops.Source], list[remote_ops.Source]]:
|
|
270
|
-
"""(the plan's own sources, the alternates added for the region), without duplicates."""
|
|
271
|
-
own: list[remote_ops.Source] = []
|
|
272
|
-
for s in sources:
|
|
273
|
-
if s.get("url") and all(s["url"] != o["url"] for o in own):
|
|
274
|
-
own.append(s)
|
|
275
|
-
extra: list[remote_ops.Source] = []
|
|
276
|
-
if region in ("cn", "global"):
|
|
277
|
-
for s in own:
|
|
278
|
-
for alt in alternates(s):
|
|
279
|
-
if all(alt["url"] != o["url"] for o in own + extra):
|
|
280
|
-
extra.append(alt)
|
|
281
|
-
return own, extra
|
|
221
|
+
def npm_transfer(source: remote_ops.Source, part: str, size: int, label: str) -> None:
|
|
222
|
+
remote_ops_mirrors.npm_transfer(source, part, size, label, overhead=NPM_OVERHEAD_BYTES)
|
|
282
223
|
|
|
283
224
|
|
|
284
225
|
def _ranged_request(url: str, start: int, end: int) -> urllib.request.Request:
|
|
@@ -295,8 +236,9 @@ def _range_total(response: object) -> int | None:
|
|
|
295
236
|
|
|
296
237
|
|
|
297
238
|
def probe(url: str, size: int) -> tuple[float, bool] | None:
|
|
298
|
-
"""Read
|
|
299
|
-
|
|
239
|
+
"""Read up to PROBE_BYTES (or for PROBE_SAMPLE_S on slow links) of ``url``: returns
|
|
240
|
+
(bytes per second, whether it serves byte ranges), or None when it fails or names another
|
|
241
|
+
size (so it cannot be the pinned file)."""
|
|
300
242
|
want = min(size, PROBE_BYTES)
|
|
301
243
|
start, got = time.monotonic(), 0
|
|
302
244
|
try:
|
|
@@ -308,19 +250,52 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
|
|
|
308
250
|
return None
|
|
309
251
|
if status != 206 and length.isdigit() and int(length) != size:
|
|
310
252
|
return None
|
|
311
|
-
|
|
312
|
-
|
|
253
|
+
read_fn = getattr(r, "read1", r.read)
|
|
254
|
+
while got < want:
|
|
255
|
+
elapsed = time.monotonic() - start
|
|
256
|
+
if elapsed >= PROBE_TIMEOUT_S:
|
|
257
|
+
break
|
|
258
|
+
if got > 0 and elapsed >= PROBE_SAMPLE_S:
|
|
259
|
+
break
|
|
260
|
+
chunk = read_fn(min(1 << 20, want - got))
|
|
313
261
|
if not chunk:
|
|
314
262
|
break
|
|
315
263
|
got += len(chunk)
|
|
316
264
|
except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
|
|
317
265
|
return None
|
|
266
|
+
if got <= 0 and want > 0:
|
|
267
|
+
return None
|
|
318
268
|
return got / max(1e-3, time.monotonic() - start), ranged
|
|
319
269
|
|
|
320
270
|
|
|
321
271
|
LONE_SMALL_BYTES = 1 << 20
|
|
322
272
|
|
|
323
273
|
|
|
274
|
+
def _probe_many(
|
|
275
|
+
sources: list[remote_ops.Source],
|
|
276
|
+
size: int,
|
|
277
|
+
) -> list[tuple[remote_ops.Source, tuple[float, bool] | None]]:
|
|
278
|
+
"""Probe ``sources`` concurrently so multi-mirror ranking completes in one RTT window."""
|
|
279
|
+
if not sources:
|
|
280
|
+
return []
|
|
281
|
+
if len(sources) == 1:
|
|
282
|
+
return [(sources[0], probe(sources[0]["url"], size))]
|
|
283
|
+
results: list[tuple[float, bool] | None] = [None] * len(sources)
|
|
284
|
+
|
|
285
|
+
def run_one(idx: int, src: remote_ops.Source) -> None:
|
|
286
|
+
results[idx] = probe(src["url"], size)
|
|
287
|
+
|
|
288
|
+
threads = [
|
|
289
|
+
threading.Thread(target=run_one, args=(i, s), daemon=True) for i, s in enumerate(sources)
|
|
290
|
+
]
|
|
291
|
+
for t in threads:
|
|
292
|
+
t.start()
|
|
293
|
+
deadline = time.monotonic() + PROBE_TIMEOUT_S + 2.0
|
|
294
|
+
for t in threads:
|
|
295
|
+
t.join(timeout=max(0.0, deadline - time.monotonic()))
|
|
296
|
+
return list(zip(sources, results))
|
|
297
|
+
|
|
298
|
+
|
|
324
299
|
def rank(
|
|
325
300
|
sources: list[remote_ops.Source],
|
|
326
301
|
size: int,
|
|
@@ -337,10 +312,9 @@ def rank(
|
|
|
337
312
|
measured: list[tuple[float, int, _Ranked]] = []
|
|
338
313
|
failed: list[_Ranked] = []
|
|
339
314
|
notes = []
|
|
340
|
-
for i, source in enumerate(sources):
|
|
341
|
-
result = probe(source["url"], size)
|
|
315
|
+
for i, (source, result) in enumerate(_probe_many(sources, size)):
|
|
342
316
|
if result is None: # try ranges anyway: a resumed .part must not restart on a hiccup
|
|
343
|
-
failed.append((source,
|
|
317
|
+
failed.append((source, _web(source)))
|
|
344
318
|
notes.append(source["source"] + " unreachable")
|
|
345
319
|
if unreachable is not None:
|
|
346
320
|
unreachable.append(source)
|
|
@@ -354,8 +328,86 @@ def rank(
|
|
|
354
328
|
return [r for _, _, r in sorted(measured)] + failed
|
|
355
329
|
|
|
356
330
|
|
|
357
|
-
def
|
|
358
|
-
|
|
331
|
+
def _probe_batch(
|
|
332
|
+
batch: list[remote_ops.Source],
|
|
333
|
+
size: int,
|
|
334
|
+
region: str,
|
|
335
|
+
tier: int,
|
|
336
|
+
failed: list[remote_ops.Source],
|
|
337
|
+
demoted: list[remote_ops.Source],
|
|
338
|
+
notes: list[str],
|
|
339
|
+
scored: list[tuple[float, int, int, int, _Ranked]],
|
|
340
|
+
probe_speeds: dict[str, float] | None,
|
|
341
|
+
) -> float:
|
|
342
|
+
best = 0.0
|
|
343
|
+
for idx, (src, res) in enumerate(_probe_many(batch, size)):
|
|
344
|
+
if res is None:
|
|
345
|
+
notes.append(src["source"] + " unreachable")
|
|
346
|
+
failed.append(src)
|
|
347
|
+
demoted.append(src)
|
|
348
|
+
continue
|
|
349
|
+
bps, ranged = res
|
|
350
|
+
if probe_speeds is not None:
|
|
351
|
+
probe_speeds[src["url"]] = bps
|
|
352
|
+
best = max(best, bps)
|
|
353
|
+
tie = cn_rank(src) if region == "cn" else idx
|
|
354
|
+
scored.append((-bps, tier, tie, idx, (src, ranged)))
|
|
355
|
+
notes.append("{} {:.2f} MB/s".format(src["source"], bps / 1e6))
|
|
356
|
+
return best
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _ordered_public(
|
|
360
|
+
own: list[remote_ops.Source],
|
|
361
|
+
public_s: list[remote_ops.Source],
|
|
362
|
+
size: int,
|
|
363
|
+
label: str,
|
|
364
|
+
region: str,
|
|
365
|
+
failed: list[remote_ops.Source],
|
|
366
|
+
probe_speeds: dict[str, float] | None,
|
|
367
|
+
) -> Iterator[_Ranked]:
|
|
368
|
+
public_probe = [s for s in public_s if not s.get("member")]
|
|
369
|
+
public_member = [s for s in public_s if s.get("member")]
|
|
370
|
+
cn_member = [s for s in public_member if side(s["url"]) == "cn"]
|
|
371
|
+
other_member = [s for s in public_member if side(s["url"]) != "cn"]
|
|
372
|
+
|
|
373
|
+
if region == "cn":
|
|
374
|
+
if cn_member and not any(side(s["url"]) == "cn" for s in public_probe):
|
|
375
|
+
yield from ((s, False) for s in cn_member)
|
|
376
|
+
cn_member = []
|
|
377
|
+
primary = sorted([s for s in public_probe if side(s["url"]) == "cn"], key=cn_rank)
|
|
378
|
+
secondary = sorted([s for s in public_probe if side(s["url"]) != "cn"], key=cn_rank)
|
|
379
|
+
else:
|
|
380
|
+
primary = [s for s in own if not s.get("member") and not remote_ops.non_public(s["url"])]
|
|
381
|
+
primary_urls = {s["url"] for s in primary}
|
|
382
|
+
secondary = [s for s in public_probe if s["url"] not in primary_urls]
|
|
383
|
+
|
|
384
|
+
notes: list[str] = []
|
|
385
|
+
scored: list[tuple[float, int, int, int, _Ranked]] = []
|
|
386
|
+
demoted: list[remote_ops.Source] = []
|
|
387
|
+
best_primary = (
|
|
388
|
+
_probe_batch(primary, size, region, 0, failed, demoted, notes, scored, probe_speeds)
|
|
389
|
+
if primary
|
|
390
|
+
else 0.0
|
|
391
|
+
)
|
|
392
|
+
cross_probed = bool(secondary and (not primary or best_primary < CROSS_REGION_PROBE_BPS))
|
|
393
|
+
if cross_probed:
|
|
394
|
+
_probe_batch(secondary, size, region, 1, failed, demoted, notes, scored, probe_speeds)
|
|
395
|
+
if notes:
|
|
396
|
+
remote_ops.emit(
|
|
397
|
+
"log", message=f"download sources for {label} (region {region}): {', '.join(notes)}"
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
scored.sort(key=lambda entry: (entry[0], entry[1], entry[2], entry[3]))
|
|
401
|
+
for _, _, _, _, ranked_entry in scored:
|
|
402
|
+
yield ranked_entry
|
|
403
|
+
tail_members = (cn_member, other_member) if region == "cn" else (other_member, cn_member)
|
|
404
|
+
yield from ((s, False) for s in tail_members[0])
|
|
405
|
+
if region == "cn" and not cross_probed:
|
|
406
|
+
yield from ((s, _web(s)) for s in secondary)
|
|
407
|
+
yield from ((s, False) for s in tail_members[1])
|
|
408
|
+
if region != "cn" and not cross_probed:
|
|
409
|
+
yield from ((s, _web(s)) for s in secondary)
|
|
410
|
+
yield from ((s, _web(s)) for s in demoted)
|
|
359
411
|
|
|
360
412
|
|
|
361
413
|
def ordered(
|
|
@@ -364,44 +416,41 @@ def ordered(
|
|
|
364
416
|
label: str,
|
|
365
417
|
region: str | None,
|
|
366
418
|
failed: list[remote_ops.Source],
|
|
419
|
+
probe_speeds: dict[str, float] | None = None,
|
|
367
420
|
) -> Iterator[_Ranked]:
|
|
368
|
-
"""
|
|
369
|
-
global, the plan's own sources keep that order and the cn alternates follow. In cn, the
|
|
370
|
-
CN_RANK order: each source is probed only when its turn comes, one that fails the probe is
|
|
371
|
-
added to ``failed`` and moved last, and the first that passes is used. npm packages (a
|
|
372
|
-
``member``) cannot be probed for the pinned size; they are tried as they come."""
|
|
421
|
+
"""Dynamic speed-first source ordering with tiered cross-region probing."""
|
|
373
422
|
own, extra = candidates(sources, region)
|
|
374
|
-
if region
|
|
423
|
+
if region not in ("cn", "global"):
|
|
375
424
|
yield from rank([s for s in own if not s.get("member")], size, label, failed)
|
|
376
|
-
|
|
377
|
-
rest.sort(key=lambda s: side(s["url"]) == "cn")
|
|
378
|
-
yield from ((s, _web(s) and not s.get("member")) for s in rest)
|
|
425
|
+
yield from ((s, False) for s in own if s.get("member"))
|
|
379
426
|
return
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
if
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
failed.append(source)
|
|
391
|
-
demoted.append(source)
|
|
392
|
-
continue
|
|
393
|
-
notes.append("{} {:.1f} MB/s".format(source["source"], result[0] / 1e6))
|
|
394
|
-
remote_ops.emit(
|
|
395
|
-
"log", message="download source for {} (region cn): {}".format(label, ", ".join(notes))
|
|
396
|
-
)
|
|
397
|
-
yield source, result[1]
|
|
398
|
-
yield from ((s, _web(s)) for s in demoted)
|
|
427
|
+
all_sources = own + extra
|
|
428
|
+
local_s = [s for s in all_sources if remote_ops.non_public(s["url"])]
|
|
429
|
+
public_s = [s for s in all_sources if not remote_ops.non_public(s["url"])]
|
|
430
|
+
if local_s:
|
|
431
|
+
local_probe = [s for s in local_s if not s.get("member")]
|
|
432
|
+
if local_probe:
|
|
433
|
+
yield from rank(local_probe, size, label, failed)
|
|
434
|
+
yield from ((s, False) for s in local_s if s.get("member"))
|
|
435
|
+
if public_s:
|
|
436
|
+
yield from _ordered_public(own, public_s, size, label, region, failed, probe_speeds)
|
|
399
437
|
|
|
400
438
|
|
|
401
439
|
class _NoRangeError(Exception):
|
|
402
440
|
"""The source stopped honouring byte ranges; the next source is tried."""
|
|
403
441
|
|
|
404
442
|
|
|
443
|
+
class SlowTransferError(RuntimeError):
|
|
444
|
+
"""Sustained transfer throughput dropped below SLOW_BYTES_PER_S; switch to another host."""
|
|
445
|
+
|
|
446
|
+
def __init__(self, bytes_per_s: int) -> None:
|
|
447
|
+
self.bytes_per_s = bytes_per_s
|
|
448
|
+
super().__init__(
|
|
449
|
+
f"download too slow ({bytes_per_s / 1024:.0f} KB/s < "
|
|
450
|
+
f"{SLOW_BYTES_PER_S / 1024:.0f} KB/s)"
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
|
|
405
454
|
def _split(start: int, end: int) -> list[list[int]]:
|
|
406
455
|
"""[start, end, done] segments of [start, end): SEGMENTS of them when each gets at least
|
|
407
456
|
MIN_SEGMENT_BYTES, fewer otherwise, never none for a non-empty range."""
|
|
@@ -410,43 +459,6 @@ def _split(start: int, end: int) -> list[list[int]]:
|
|
|
410
459
|
return [[s, min(end, s + step), s] for s in range(start, end, step)]
|
|
411
460
|
|
|
412
461
|
|
|
413
|
-
def _state_path(part: str) -> str:
|
|
414
|
-
return part + ".ranges"
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
def kept_bytes(part: str, size: int) -> int:
|
|
418
|
-
"""Bytes of ``part`` already downloaded: its ranges record when it has one, else its size."""
|
|
419
|
-
segments = _load_ranges(part, size)
|
|
420
|
-
if segments is not None:
|
|
421
|
-
return size - sum(end - done for _, end, done in segments)
|
|
422
|
-
return os.path.getsize(part) if os.path.exists(part) else 0
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
def _load_ranges(part: str, size: int) -> list[list[int]] | None:
|
|
426
|
-
try:
|
|
427
|
-
state = json.loads(remote_ops._read(_state_path(part)))
|
|
428
|
-
segments = [[int(a), int(b), int(c)] for a, b, c in state["segments"]]
|
|
429
|
-
except (OSError, ValueError, KeyError, TypeError):
|
|
430
|
-
return None
|
|
431
|
-
if state.get("size") != size or not os.path.exists(part) or os.path.getsize(part) != size:
|
|
432
|
-
return None
|
|
433
|
-
if any(not 0 <= start <= done <= end <= size for start, end, done in segments):
|
|
434
|
-
return None
|
|
435
|
-
return segments
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
def _save_ranges(part: str, size: int, segments: list[list[int]]) -> None:
|
|
439
|
-
path = _state_path(part)
|
|
440
|
-
remote_ops._write(path + ".tmp", json.dumps({"size": size, "segments": segments}))
|
|
441
|
-
os.replace(path + ".tmp", path)
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
def discard(part: str) -> None:
|
|
445
|
-
for path in (part, _state_path(part)):
|
|
446
|
-
if os.path.exists(path):
|
|
447
|
-
os.remove(path)
|
|
448
|
-
|
|
449
|
-
|
|
450
462
|
def _resume_ranges(part: str, size: int) -> list[list[int]]:
|
|
451
463
|
"""The segments still to fetch. A plain .part (a single-connection download of an earlier
|
|
452
464
|
version) is a finished prefix; the file is then sized so each range writes in place."""
|
|
@@ -484,8 +496,32 @@ class _Transfer:
|
|
|
484
496
|
) -> None:
|
|
485
497
|
self.url, self.part, self.size, self.segments = url, part, size, segments
|
|
486
498
|
self.attempts = ATTEMPTS if attempts is None else max(1, attempts)
|
|
487
|
-
self.lock, self.
|
|
499
|
+
self.lock, self.io_lock = threading.Lock(), threading.Lock()
|
|
500
|
+
self.stop = threading.Event()
|
|
488
501
|
self.errors: list[BaseException] = []
|
|
502
|
+
self._responses: list[Any] = []
|
|
503
|
+
|
|
504
|
+
def _track_response(self, resp: Any) -> None:
|
|
505
|
+
with self.lock:
|
|
506
|
+
self._responses.append(resp)
|
|
507
|
+
|
|
508
|
+
def _untrack_response(self, resp: Any) -> None:
|
|
509
|
+
with self.lock:
|
|
510
|
+
if resp in self._responses:
|
|
511
|
+
self._responses.remove(resp)
|
|
512
|
+
|
|
513
|
+
def stop_and_close(self) -> None:
|
|
514
|
+
with self.io_lock:
|
|
515
|
+
self.stop.set()
|
|
516
|
+
with self.lock:
|
|
517
|
+
active = list(self._responses)
|
|
518
|
+
for resp in active:
|
|
519
|
+
for target in (resp, getattr(resp, "fp", None)):
|
|
520
|
+
if target is not None:
|
|
521
|
+
try:
|
|
522
|
+
target.close()
|
|
523
|
+
except Exception: # noqa: BLE001
|
|
524
|
+
pass
|
|
489
525
|
|
|
490
526
|
def remaining(self) -> int:
|
|
491
527
|
with self.lock:
|
|
@@ -498,22 +534,36 @@ class _Transfer:
|
|
|
498
534
|
def _range(self, segment: list[int]) -> None:
|
|
499
535
|
done, end = segment[2], segment[1]
|
|
500
536
|
with urllib.request.urlopen(_ranged_request(self.url, done, end), timeout=60) as r:
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
537
|
+
self._track_response(r)
|
|
538
|
+
try:
|
|
539
|
+
if self.stop.is_set():
|
|
540
|
+
return
|
|
541
|
+
if getattr(r, "status", 200) != 206 or not str(
|
|
542
|
+
r.headers.get("Content-Range", "")
|
|
543
|
+
).startswith(f"bytes {done}-"):
|
|
544
|
+
raise _NoRangeError()
|
|
545
|
+
read_fn = getattr(r, "read1", r.read)
|
|
546
|
+
with self.io_lock:
|
|
547
|
+
if self.stop.is_set():
|
|
548
|
+
return
|
|
549
|
+
out = open(self.part, "r+b", buffering=0)
|
|
550
|
+
with out:
|
|
551
|
+
out.seek(done)
|
|
552
|
+
while done < end and not self.stop.is_set():
|
|
553
|
+
chunk = read_fn(min(READ_BYTES, end - done))
|
|
554
|
+
if not chunk:
|
|
555
|
+
break
|
|
556
|
+
with self.io_lock:
|
|
557
|
+
if self.stop.is_set():
|
|
558
|
+
break
|
|
559
|
+
view = memoryview(chunk)
|
|
560
|
+
while view:
|
|
561
|
+
view = view[out.write(view) or 0 :]
|
|
562
|
+
done += len(chunk)
|
|
563
|
+
with self.lock:
|
|
564
|
+
segment[2] = done
|
|
565
|
+
finally:
|
|
566
|
+
self._untrack_response(r)
|
|
517
567
|
if done < end and not self.stop.is_set():
|
|
518
568
|
raise http.client.IncompleteRead(b"", end - done)
|
|
519
569
|
|
|
@@ -525,18 +575,21 @@ class _Transfer:
|
|
|
525
575
|
except _NoRangeError as exc:
|
|
526
576
|
self.fail(exc)
|
|
527
577
|
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
|
|
578
|
+
if self.stop.is_set():
|
|
579
|
+
return
|
|
528
580
|
attempt += 1
|
|
529
581
|
if not _retryable(exc) or attempt >= self.attempts:
|
|
530
582
|
self.fail(exc)
|
|
531
583
|
return
|
|
532
584
|
self.stop.wait(min(30, 2**attempt))
|
|
533
585
|
except BaseException as exc: # noqa: BLE001 - reported by the main thread
|
|
534
|
-
self.
|
|
586
|
+
if not self.stop.is_set():
|
|
587
|
+
self.fail(exc)
|
|
535
588
|
|
|
536
589
|
def fail(self, exc: BaseException) -> None:
|
|
537
590
|
with self.lock:
|
|
538
591
|
self.errors.append(exc)
|
|
539
|
-
self.
|
|
592
|
+
self.stop_and_close()
|
|
540
593
|
|
|
541
594
|
|
|
542
595
|
def transfer(
|
|
@@ -547,68 +600,25 @@ def transfer(
|
|
|
547
600
|
ranged: bool,
|
|
548
601
|
*,
|
|
549
602
|
attempts: int | None = None,
|
|
603
|
+
allow_slow_switch: bool = False,
|
|
550
604
|
) -> None:
|
|
551
605
|
"""Fill ``part`` with all ``size`` bytes from ``source``, reporting progress events; raises
|
|
552
606
|
on failure with the kept ranges saved so the next call (or source) resumes them. A source
|
|
553
607
|
that turns out not to serve ranges is read once as one plain stream from the start."""
|
|
554
608
|
if ranged:
|
|
555
609
|
job = _Transfer(source["url"], part, size, _resume_ranges(part, size), attempts=attempts)
|
|
556
|
-
_run(job, source, label, ranged=True)
|
|
610
|
+
_run(job, source, label, ranged=True, allow_slow_switch=allow_slow_switch)
|
|
557
611
|
if not (job.errors and isinstance(job.errors[0], _NoRangeError)):
|
|
558
612
|
_finish(job, label)
|
|
559
613
|
return
|
|
560
614
|
discard(part)
|
|
561
615
|
open(part, "wb").close()
|
|
562
616
|
job = _Transfer(source["url"], part, size, [[0, size, 0]], attempts=attempts)
|
|
563
|
-
_run(job, source, label, ranged=False)
|
|
617
|
+
_run(job, source, label, ranged=False, allow_slow_switch=allow_slow_switch)
|
|
564
618
|
_finish(job, label)
|
|
565
619
|
|
|
566
620
|
|
|
567
|
-
|
|
568
|
-
"""Fill ``part`` with the ``member`` file of the npm package at ``source``: the package is
|
|
569
|
-
read in one bounded stream (an npm tarball is a gzip of the file, so a little larger than
|
|
570
|
-
it), then only that regular file of exactly ``size`` bytes is taken. The caller checks its
|
|
571
|
-
SHA256 against the asset's pin as for any other source."""
|
|
572
|
-
archive = part + ".npm"
|
|
573
|
-
cap = size + size // 64 + NPM_OVERHEAD_BYTES
|
|
574
|
-
request = urllib.request.Request(source["url"], headers={"User-Agent": "localmodels-deploy"})
|
|
575
|
-
got, start, mark = 0, time.monotonic(), time.monotonic()
|
|
576
|
-
try:
|
|
577
|
-
with urllib.request.urlopen(request, timeout=60) as r, open(archive, "wb") as out:
|
|
578
|
-
while True:
|
|
579
|
-
chunk = r.read(remote_ops._CHUNK)
|
|
580
|
-
if not chunk:
|
|
581
|
-
break
|
|
582
|
-
got += len(chunk)
|
|
583
|
-
if got > cap:
|
|
584
|
-
raise RuntimeError(f"the npm copy of {label} exceeds its size limit")
|
|
585
|
-
out.write(chunk)
|
|
586
|
-
if time.monotonic() - mark >= remote_ops._PROGRESS_EVERY_S:
|
|
587
|
-
mark = time.monotonic()
|
|
588
|
-
remote_ops.emit(
|
|
589
|
-
"progress",
|
|
590
|
-
phase="download",
|
|
591
|
-
file=label,
|
|
592
|
-
done=min(got, size),
|
|
593
|
-
total=size,
|
|
594
|
-
bytes_per_s=int(got / max(1e-3, mark - start)),
|
|
595
|
-
source=source["source"],
|
|
596
|
-
connections=1,
|
|
597
|
-
**remote_ops.step_fields(min(got, size)),
|
|
598
|
-
)
|
|
599
|
-
with tarfile.open(archive) as tar:
|
|
600
|
-
member = tar.getmember(source["member"])
|
|
601
|
-
stream = tar.extractfile(member) if member.isfile() and member.size == size else None
|
|
602
|
-
if stream is None:
|
|
603
|
-
raise RuntimeError(f"the npm copy of {label} does not hold a {size}-byte file")
|
|
604
|
-
discard(_state_path(part)) # part is rewritten whole, not resumed
|
|
605
|
-
with stream, open(part, "wb") as out:
|
|
606
|
-
shutil.copyfileobj(stream, out, remote_ops._CHUNK)
|
|
607
|
-
except KeyError:
|
|
608
|
-
raise RuntimeError(f"the npm copy of {label} does not hold {source['member']}") from None
|
|
609
|
-
finally:
|
|
610
|
-
if os.path.exists(archive):
|
|
611
|
-
os.remove(archive)
|
|
621
|
+
DEFAULT_TRANSFER = transfer
|
|
612
622
|
|
|
613
623
|
|
|
614
624
|
def _finish(job: _Transfer, label: str) -> None:
|
|
@@ -618,22 +628,17 @@ def _finish(job: _Transfer, label: str) -> None:
|
|
|
618
628
|
raise RuntimeError(f"{label} download stopped with bytes missing")
|
|
619
629
|
|
|
620
630
|
|
|
621
|
-
|
|
622
|
-
"""Bytes per second over the last ``window`` seconds of (time, bytes done) samples."""
|
|
623
|
-
|
|
624
|
-
def __init__(self, now: float, done: int, window: float | None = None) -> None:
|
|
625
|
-
self.window = RATE_WINDOW_S if window is None else window
|
|
626
|
-
self.samples: collections.deque[tuple[float, int]] = collections.deque([(now, done)])
|
|
627
|
-
|
|
628
|
-
def add(self, now: float, done: int) -> int:
|
|
629
|
-
while len(self.samples) > 1 and now - self.samples[1][0] >= self.window:
|
|
630
|
-
self.samples.popleft()
|
|
631
|
-
then, before = self.samples[0]
|
|
632
|
-
self.samples.append((now, done))
|
|
633
|
-
return int((done - before) / max(1e-3, now - then))
|
|
631
|
+
Rate = remote_ops_mirrors.Rate
|
|
634
632
|
|
|
635
633
|
|
|
636
|
-
def _run(
|
|
634
|
+
def _run(
|
|
635
|
+
job: _Transfer,
|
|
636
|
+
source: remote_ops.Source,
|
|
637
|
+
label: str,
|
|
638
|
+
*,
|
|
639
|
+
ranged: bool,
|
|
640
|
+
allow_slow_switch: bool = False,
|
|
641
|
+
) -> None:
|
|
637
642
|
if ranged:
|
|
638
643
|
threads = [
|
|
639
644
|
threading.Thread(target=job.worker, args=(s,), daemon=True)
|
|
@@ -646,7 +651,9 @@ def _run(job: _Transfer, source: remote_ops.Source, label: str, *, ranged: bool)
|
|
|
646
651
|
thread.start()
|
|
647
652
|
size = job.size
|
|
648
653
|
mark = time.monotonic()
|
|
649
|
-
|
|
654
|
+
initial_done = size - job.remaining()
|
|
655
|
+
meter = Rate(mark, initial_done)
|
|
656
|
+
slow_window_start, slow_window_done = mark, initial_done
|
|
650
657
|
while True:
|
|
651
658
|
alive = [t for t in threads if t.is_alive()] # the connections open during this interval
|
|
652
659
|
if not alive:
|
|
@@ -654,6 +661,16 @@ def _run(job: _Transfer, source: remote_ops.Source, label: str, *, ranged: bool)
|
|
|
654
661
|
for t in alive:
|
|
655
662
|
t.join(timeout=remote_ops._PROGRESS_EVERY_S / len(alive))
|
|
656
663
|
now, done = time.monotonic(), size - job.remaining()
|
|
664
|
+
if allow_slow_switch and not job.stop.is_set():
|
|
665
|
+
window_elapsed = now - slow_window_start
|
|
666
|
+
if window_elapsed >= SLOW_WINDOW_S:
|
|
667
|
+
window_rate = int((done - slow_window_done) / max(1e-3, window_elapsed))
|
|
668
|
+
remaining = max(0, size - done)
|
|
669
|
+
near_done = remaining <= SLOW_BYTES_PER_S * SLOW_MIN_REMAINING_S
|
|
670
|
+
if window_rate < SLOW_BYTES_PER_S and not near_done:
|
|
671
|
+
job.fail(SlowTransferError(window_rate))
|
|
672
|
+
break
|
|
673
|
+
slow_window_start, slow_window_done = now, done
|
|
657
674
|
if now - mark >= remote_ops._PROGRESS_EVERY_S:
|
|
658
675
|
remote_ops.emit(
|
|
659
676
|
"progress",
|
|
@@ -669,6 +686,12 @@ def _run(job: _Transfer, source: remote_ops.Source, label: str, *, ranged: bool)
|
|
|
669
686
|
mark = now
|
|
670
687
|
if ranged:
|
|
671
688
|
_save_ranges(job.part, size, job.snapshot())
|
|
689
|
+
if job.errors or any(t.is_alive() for t in threads):
|
|
690
|
+
job.stop_and_close()
|
|
691
|
+
deadline = time.monotonic() + 2.0
|
|
692
|
+
for t in threads:
|
|
693
|
+
if t.is_alive():
|
|
694
|
+
t.join(timeout=max(0.0, deadline - time.monotonic()))
|
|
672
695
|
if ranged:
|
|
673
696
|
_save_ranges(job.part, size, job.snapshot())
|
|
674
697
|
|
|
@@ -680,10 +703,27 @@ def _plain(job: _Transfer) -> None:
|
|
|
680
703
|
with urllib.request.urlopen(
|
|
681
704
|
urllib.request.Request(job.url, headers={"User-Agent": "localmodels-deploy"}),
|
|
682
705
|
timeout=60,
|
|
683
|
-
) as r
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
with job.
|
|
687
|
-
|
|
706
|
+
) as r:
|
|
707
|
+
job._track_response(r)
|
|
708
|
+
try:
|
|
709
|
+
with job.io_lock:
|
|
710
|
+
if job.stop.is_set():
|
|
711
|
+
return
|
|
712
|
+
out = open(job.part, "wb")
|
|
713
|
+
with out:
|
|
714
|
+
read_fn = getattr(r, "read1", r.read)
|
|
715
|
+
while not job.stop.is_set():
|
|
716
|
+
chunk = read_fn(READ_BYTES)
|
|
717
|
+
if not chunk:
|
|
718
|
+
break
|
|
719
|
+
with job.io_lock:
|
|
720
|
+
if job.stop.is_set():
|
|
721
|
+
break
|
|
722
|
+
out.write(chunk)
|
|
723
|
+
with job.lock:
|
|
724
|
+
segment[2] = min(segment[1], segment[2] + len(chunk))
|
|
725
|
+
finally:
|
|
726
|
+
job._untrack_response(r)
|
|
688
727
|
except BaseException as exc: # noqa: BLE001 - reported by the main thread
|
|
689
|
-
job.
|
|
728
|
+
if not job.stop.is_set():
|
|
729
|
+
job.fail(exc)
|