refactor(downloader): judge every 206, 416 and 200 ranged answer in one range_answer verdict

This commit is contained in:
imSp4rky
2026-12-04 14:46:56 -07:00
parent 89b3e77d18
commit bec5354293
6 changed files with 526 additions and 242 deletions
-10
View File
@@ -15,7 +15,6 @@ from unshackle.core.downloaders.requests import (
TAIL_BOOST_MIN_SEGMENT_SIZE, TAIL_BOOST_MIN_SEGMENT_SIZE,
TAIL_BOOST_PART_SIZE, TAIL_BOOST_PART_SIZE,
AdaptiveWorkerController, AdaptiveWorkerController,
has_range_header,
plan_tail_parts, plan_tail_parts,
requests, requests,
split_ranges, split_ranges,
@@ -314,15 +313,6 @@ def test_tail_boost_does_not_engage_early_or_saturated() -> None:
assert not tail_boost_engages(remaining=5, pending=10, target=8) # over-subscribed: spare < 0 assert not tail_boost_engages(remaining=5, pending=10, target=8) # over-subscribed: spare < 0
def test_has_range_header_detects_byte_range_slices() -> None:
# items carrying a Range header are byte-range slices; ranged-parallel must skip them
assert has_range_header({"url": "u", "headers": {"Range": "bytes=0-99"}})
assert has_range_header({"url": "u", "headers": {"range": "bytes=0-99"}}) # case-insensitive
assert not has_range_header({"url": "u", "headers": {"Authorization": "Bearer x"}})
assert not has_range_header({"url": "u", "headers": {}})
assert not has_range_header({"url": "u"})
def test_download_context_adaptive_default_false() -> None: def test_download_context_adaptive_default_false() -> None:
ctx = DownloadContext(save_path=Path("x.mp4"), save_dir=Path("."), progress=partial(lambda **_: None)) ctx = DownloadContext(save_path=Path("x.mp4"), save_dir=Path("."), progress=partial(lambda **_: None))
assert ctx.adaptive_workers is False assert ctx.adaptive_workers is False
+1 -46
View File
@@ -6,7 +6,7 @@ import pytest
import requests as rq import requests as rq
from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import download, has_range_header, parse_content_range, request_range from unshackle.core.downloaders.requests import download
from unshackle.core.downloaders.requests import requests as requests_downloader from unshackle.core.downloaders.requests import requests as requests_downloader
# the package re-exports the `requests` function, shadowing the module of the same name # the package re-exports the `requests` function, shadowing the module of the same name
@@ -299,48 +299,3 @@ def test_batch_larger_than_the_queue_window_downloads_every_segment(tmp_path, se
assert not consumer.is_alive(), "downloader never finished the batch" assert not consumer.is_alive(), "downloader never finished the batch"
assert advanced == len(urls) assert advanced == len(urls)
assert sorted(p.name for p in tmp_path.iterdir() if p.suffix == ".mp4") == [f"{i:02}.mp4" for i in range(6)] assert sorted(p.name for p in tmp_path.iterdir() if p.suffix == ".mp4") == [f"{i:02}.mp4" for i in range(6)]
@pytest.mark.parametrize(
("item", "expected"),
[
({}, False),
({"headers": None}, False),
({"headers": {}}, False),
({"headers": {"Accept": "*/*"}}, False),
({"headers": {"Range": "bytes=0-127"}}, True),
({"headers": {"range": "bytes=0-127"}}, True),
],
)
def test_has_range_header(item, expected):
assert has_range_header(item) is expected
@pytest.mark.parametrize(
("value", "expected"),
[
(None, None),
("", None),
("garbage", None),
("bytes */400000", None),
("bytes 0-399999/400000", (0, 399999, 400000)),
("BYTES 150000-399999/*", (150000, 399999, None)),
(b"bytes 5-9/10", (5, 9, 10)),
],
)
def test_parse_content_range(value, expected):
assert parse_content_range(value) == expected
@pytest.mark.parametrize(
("headers", "expected"),
[
({}, None),
({"Accept": "*/*"}, None),
({"Range": "bytes=-500"}, None),
({"Range": "bytes=100-"}, (100, None)),
({"range": "bytes=100-227"}, (100, 227)),
],
)
def test_request_range(headers, expected):
assert request_range(headers) == expected
+264
View File
@@ -0,0 +1,264 @@
"""The range verdict: request mode x status x Content-Range -> verdict, as a table."""
import pytest
from unshackle.core.downloaders.ranges import Answer, Mode, Verdict, has_range_header, range_answer
pytestmark = pytest.mark.unit
W, A, F, RESTART, REJECT = Verdict.WRITE, Verdict.APPEND, Verdict.FINISHED, Verdict.RESTART, Verdict.REJECT
def rng(value: str | None) -> dict[str, str]:
return {} if value is None else {"Range": value}
@pytest.mark.parametrize(
("item", "expected"),
[
({}, False),
({"headers": None}, False),
({"headers": {}}, False),
({"headers": {"Accept": "*/*"}}, False),
({"headers": {"Range": "bytes=0-127"}}, True),
({"headers": {"range": "bytes=0-127"}}, True),
],
)
def test_has_range_header(item, expected):
assert has_range_header(item) is expected
@pytest.mark.parametrize(
("requested", "status", "content_range", "known", "kwargs", "expected"),
[
(None, 200, None, None, {"length": 100}, Answer(W, 100, 100)),
(None, 200, None, None, {}, Answer(W, None, 0)),
(None, 200, None, 80, {"length": 100}, Answer(W, 80, 100)),
(None, 204, None, None, {}, Answer(W, None, 0)),
(None, 416, "bytes */100", None, {}, Answer(W, None, 0)),
(None, 206, None, None, {}, Answer(W, None, 0)),
(None, 206, "garbage", None, {}, Answer(W, None, 0)),
(None, 206, "bytes 0-99/100", None, {}, Answer(W, 100, 0, (0, 99, 100))),
(None, 206, "bytes 0-49/*", None, {}, Answer(W, None, 0, (0, 49, None))),
(
None,
206,
"bytes 5-99/100",
None,
{},
Answer(REJECT, None, 0, reason="206 body starts at byte 5, expected 0"),
),
(None, 206, "bytes 5-99/100", 100, {}, Answer(W, 100, 0)),
("bytes=40-", 416, "bytes */40", None, {}, Answer(F, None, 0)),
("bytes=40-", 416, "bytes */40", 40, {}, Answer(F, 40, 0)),
(
"bytes=40-",
416,
"bytes */40",
100,
{},
Answer(RESTART, 100, 0, reason="resume from byte 40 got a 416, complete length 40"),
),
(
"bytes=40-",
416,
"bytes */100",
None,
{},
Answer(RESTART, None, 0, reason="resume from byte 40 got a 416, complete length 100"),
),
(
"bytes=40-",
416,
None,
None,
{},
Answer(RESTART, None, 0, reason="resume from byte 40 got a 416, complete length None"),
),
("bytes=40-", 206, "bytes 40-99/100", None, {"length": 60}, Answer(A, 100, 60, (40, 99, 100))),
("bytes=40-", 206, b"BYTES 40-99/*", 100, {}, Answer(A, 100, 0, (40, 99, None))),
("bytes=40-59", 206, "bytes 40-59/100", None, {}, Answer(A, 100, 0, (40, 59, 100))),
(
"bytes=40-",
206,
"bytes 40-99/100",
None,
{"encoded": True},
Answer(RESTART, 100, 0, reason="resume from byte 40 came back content-encoded"),
),
("bytes=40-", 206, "bytes 0-99/100", None, {}, Answer(W, 100, 0, (0, 99, 100))),
("bytes=40-", 206, "bytes 0-99/100", 120, {}, Answer(W, 120, 0)),
(
"bytes=40-",
206,
"bytes 0-49/100",
None,
{},
Answer(RESTART, None, 0, reason="resume from byte 40 got Content-Range (0, 49, 100)"),
),
(
"bytes=40-",
206,
"bytes 30-99/100",
None,
{},
Answer(RESTART, None, 0, reason="resume from byte 40 got Content-Range (30, 99, 100)"),
),
(
"bytes=40-",
206,
"bytes 0-99/*",
None,
{},
Answer(RESTART, None, 0, reason="resume from byte 40 got Content-Range (0, 99, None)"),
),
(
"bytes=40-",
206,
None,
None,
{},
Answer(RESTART, None, 0, reason="resume from byte 40 got Content-Range None"),
),
("bytes=40-", 200, None, None, {"length": 100}, Answer(W, 100, 100)),
("bytes=40-", 503, None, 100, {}, Answer(W, 100, 0)),
],
)
def test_resume(requested, status, content_range, known, kwargs, expected):
assert range_answer(Mode.RESUME, rng(requested), status, content_range, total=known, **kwargs) == expected
PART = (100, 199)
@pytest.mark.parametrize(
("requested", "status", "content_range", "expected"),
[
("bytes=100-199", 206, "bytes 100-199/1000", Answer(W, None, 0, (100, 199, 1000))),
("bytes=150-199", 206, "bytes 150-199/*", Answer(W, None, 0, (150, 199, None))),
("bytes=100-149", 206, "bytes 100-140/1000", Answer(W, None, 0, (100, 140, 1000))),
("bytes=100-199", 200, None, Answer(REJECT, None, 0, reason="expected 206 for ranged part, got 200")),
("bytes=100-199", 416, "bytes */1000", Answer(REJECT, None, 0, reason="expected 206 for ranged part, got 416")),
("bytes=100-199", 206, None, Answer(REJECT, None, 0, reason="part 100-199 got Content-Range None")),
(
"bytes=150-199",
206,
"bytes 100-199/1000",
Answer(REJECT, None, 0, reason="part 100-199 got Content-Range (100, 199, 1000)"),
),
(
"bytes=100-149",
206,
"bytes 100-199/1000",
Answer(REJECT, None, 0, reason="part 100-199 got Content-Range (100, 199, 1000)"),
),
(
"bytes=100-199",
206,
"bytes 100-199/199",
Answer(REJECT, None, 0, reason="part 100-199 got Content-Range (100, 199, 199)"),
),
("bytes=100-199", 206, "bytes 100-199/200", Answer(W, None, 0, (100, 199, 200))),
],
)
def test_part(requested, status, content_range, expected):
assert range_answer(Mode.PART, rng(requested), status, content_range, part=PART) == expected
@pytest.mark.parametrize(
("requested", "status", "content_range", "kwargs", "expected"),
[
("bytes=100-227", 206, "bytes 100-227/1000", {"length": 999}, Answer(W, None, 128, (100, 227, 1000))),
(
"bytes=100-227",
206,
"bytes 100-227/1000",
{"length": 50, "encoded": True},
Answer(W, None, 50, (100, 227, 1000)),
),
("bytes=100-", 206, "bytes 100-999/1000", {}, Answer(W, None, 900, (100, 999, 1000))),
("bytes=900-1099", 206, "bytes 900-999/1000", {}, Answer(W, None, 100, (900, 999, 1000))),
("bytes=900-999,0-9", 206, "bytes 900-999/1000", {}, Answer(W, None, 100, (900, 999, 1000))),
("bytes=-500", 206, "bytes 500-999/1000", {"length": 500}, Answer(W, None, 500)),
(
"bytes=900-1099",
206,
"bytes 900-999/*",
{},
Answer(REJECT, None, 0, reason="byte-range segment got Content-Range (900, 999, None), expected 900-1099"),
),
(
"bytes=100-227",
206,
"bytes 0-999/1000",
{},
Answer(REJECT, None, 0, reason="byte-range segment got Content-Range (0, 999, 1000), expected 100-227"),
),
(
"bytes=100-227",
206,
"bytes 100-199/1000",
{},
Answer(REJECT, None, 0, reason="byte-range segment got Content-Range (100, 199, 1000), expected 100-227"),
),
(
"bytes=100-",
206,
None,
{},
Answer(REJECT, None, 0, reason="byte-range segment got Content-Range None, expected 100-"),
),
("bytes=0-99", 200, None, {"length": 100}, Answer(W, None, 100)),
(" bytes=0-99 ", 200, None, {"length": 100}, Answer(W, None, 100)),
(
"bytes=0-99",
200,
None,
{"length": 101},
Answer(REJECT, None, 101, reason="expected 206 for byte-range segment, got 200"),
),
("bytes=0-99", 200, None, {}, Answer(REJECT, None, 0, reason="expected 206 for byte-range segment, got 200")),
(
"bytes=10-99",
200,
None,
{"length": 100},
Answer(REJECT, None, 100, reason="expected 206 for byte-range segment, got 200"),
),
(
"bytes=10-109",
200,
None,
{"length": 100},
Answer(REJECT, None, 100, reason="expected 206 for byte-range segment, got 200"),
),
(
"bytes=0-",
200,
None,
{"length": 100},
Answer(REJECT, None, 100, reason="expected 206 for byte-range segment, got 200"),
),
(
"bytes=0-99,200-299",
200,
None,
{"length": 100},
Answer(REJECT, None, 100, reason="expected 206 for byte-range segment, got 200"),
),
(
"bytes=0-99",
416,
"bytes */50",
{},
Answer(REJECT, None, 0, reason="expected 206 for byte-range segment, got 416"),
),
],
)
def test_item(requested, status, content_range, kwargs, expected):
assert range_answer(Mode.ITEM, rng(requested), status, content_range, **kwargs) == expected
def test_item_reads_the_range_header_in_any_case():
answer = range_answer(Mode.ITEM, {"range": "bytes=100-227"}, 206, "bytes 100-227/1000")
assert answer.content_range == (100, 227, 1000)
+217
View File
@@ -0,0 +1,217 @@
"""The one verdict on a ranged answer: may this response's bytes go at the offset the request asked for."""
from __future__ import annotations
import re
from collections.abc import Mapping
from dataclasses import dataclass
from enum import Enum
from typing import Any
ContentRange = tuple[int, int, int | None]
class Mode(Enum):
"""What the request asks for.
RESUME is a whole file, from byte 0 or from the end of its partial. PART is one sub-range of a parallel ranged
download, written at its offset in a shared file. ITEM is a byte-range slice that the item's own Range names.
"""
RESUME = "resume"
PART = "part"
ITEM = "item"
class Verdict(Enum):
"""What to do with the body.
WRITE it from the request start (byte 0 in RESUME) or APPEND it to the partial. FINISHED: the partial is whole.
RESTART discards the partial and fails the attempt; REJECT fails the attempt and keeps the partial.
"""
WRITE = "write"
APPEND = "append"
FINISHED = "finished"
RESTART = "restart"
REJECT = "reject"
@dataclass(frozen=True)
class Answer:
"""A verdict with the complete length known after it, the body length to expect, and the error line.
``content_range`` is the response's Content-Range only when the verdict proved that it answers the request.
"""
verdict: Verdict
total: int | None
length: int
content_range: ContentRange | None = None
reason: str = ""
def _range_value(headers: Mapping[str, Any] | None) -> str | None:
"""The value of a Range header in ``headers``, any case. Gives None when there is none."""
return next((str(v) for k, v in (headers or {}).items() if str(k).lower() == "range"), None)
def has_range_header(item: dict[str, Any]) -> bool:
"""True when a URL item's per-request headers already carry a Range.
Such an item is itself a byte-range slice of a larger resource (DASH SegmentBase,
HLS EXT-X-BYTERANGE). Probing or part-mode would clobber that Range and fetch the
wrong bytes, so ranged-parallel strategies must skip these items entirely.
"""
return _range_value(item.get("headers")) is not None
def range_answer(
mode: Mode,
headers: Mapping[str, Any] | None,
status: int,
content_range: str | bytes | None,
*,
length: int = 0,
encoded: bool = False,
total: int | None = None,
part: tuple[int, int] | None = None,
) -> Answer:
"""Judge a response to a request with ``headers`` from its status and Content-Range header.
``length`` is the declared body length (0 when unknown), ``total`` the complete length known before this
response, and ``part`` the inclusive ``(offset, end)`` of the part a PART request belongs to. A 416 to a
resume gets FINISHED or RESTART; the caller raises any other HTTP error status before it acts on the verdict.
"""
value = _range_value(headers) or ""
if isinstance(content_range, bytes):
content_range = content_range.decode("latin1", "replace")
header = str(content_range or "").strip()
if mode is Mode.PART:
if part is None:
raise ValueError("a PART answer needs the part's (offset, end)")
return _part_answer(value, status, header, length, total, part)
if mode is Mode.ITEM:
return _item_answer(value, status, header, length, encoded, total)
return _resume_answer(value, status, header, length, encoded, total)
def _resume_answer(value: str, status: int, header: str, length: int, encoded: bool, total: int | None) -> Answer:
"""A 416 at the partial's end finishes it; a 206 must start at the partial or prove the whole body from zero.
Some servers answer ``bytes=X-`` with a 206 for the whole resource, which is byte-identical to a 200.
"""
requested = _request_range(value)
start = requested[0] if requested else 0
if start and status == 416:
complete = _unsatisfied_length(header)
if complete == start and total in (None, start):
return Answer(Verdict.FINISHED, total, length)
reason = f"resume from byte {start} got a 416, complete length {complete}"
return Answer(Verdict.RESTART, total, length, reason=reason)
content_range = _parse_content_range(header)
if start and status == 206:
if content_range is not None and content_range[0] == start:
if content_range[2] is not None:
total = content_range[2]
if encoded:
return Answer(
Verdict.RESTART, total, length, reason=f"resume from byte {start} came back content-encoded"
)
return Answer(Verdict.APPEND, total, length, content_range)
whole = (
content_range is not None
and content_range[2] is not None
and content_range[:2] == (0, content_range[2] - 1)
)
if not whole:
reason = f"resume from byte {start} got Content-Range {content_range!r}"
return Answer(Verdict.RESTART, total, length, reason=reason)
if total is None and status == 200:
return Answer(Verdict.WRITE, length or None, length)
if total is None and status == 206 and content_range is not None:
if content_range[0] != 0:
return Answer(
Verdict.REJECT, total, length, reason=f"206 body starts at byte {content_range[0]}, expected 0"
)
return Answer(Verdict.WRITE, content_range[2], length, content_range)
return Answer(Verdict.WRITE, total, length)
def _part_answer(value: str, status: int, header: str, length: int, total: int | None, part: tuple[int, int]) -> Answer:
"""A part needs a 206 at its own start that ends within the request, from a resource still longer than the part.
A wrong start lands bytes at the wrong offset in the shared file, an end past the request spills into a sibling
part, and a complete length at or below the part's end means the resource changed under the part plan.
"""
offset, end = part
if status != 206:
return Answer(Verdict.REJECT, total, length, reason=f"expected 206 for ranged part, got {status}")
requested = _request_range(value)
content_range = _parse_content_range(header)
if (
requested is None
or content_range is None
or content_range[0] != requested[0]
or (requested[1] is not None and content_range[1] > requested[1])
or (content_range[2] is not None and content_range[2] <= end)
):
return Answer(Verdict.REJECT, total, length, reason=f"part {offset}-{end} got Content-Range {content_range!r}")
return Answer(Verdict.WRITE, total, length, content_range)
def _item_answer(value: str, status: int, header: str, length: int, encoded: bool, total: int | None) -> Answer:
"""A slice needs a 206 for its own range, or a 200 whose whole body is exactly the slice from byte 0.
RFC 9110 lets a server ignore Range and answer 200 with the whole resource, and clamps a range end past the
resource to its last byte. A slice whose Range does not parse as ``bytes=start-...`` takes any 206 unproven.
"""
if status != 206:
whole = status == 200 and re.fullmatch(r"bytes=(\d+)-(\d+)", value.strip())
if whole and length > 0 and int(whole[1]) == 0 and length == int(whole[2]) + 1:
return Answer(Verdict.WRITE, total, length)
return Answer(Verdict.REJECT, total, length, reason=f"expected 206 for byte-range segment, got {status}")
requested = _request_range(value)
if requested is None:
return Answer(Verdict.WRITE, total, length)
start, end = requested
content_range = _parse_content_range(header)
if (
content_range is None
or content_range[0] != start
or not (
end is None
or content_range[1] == end
or (content_range[2] is not None and content_range[1] == content_range[2] - 1 and end >= content_range[2])
)
):
expected = f"{start}-{end if end is not None else ''}"
return Answer(
Verdict.REJECT,
total,
length,
reason=f"byte-range segment got Content-Range {content_range!r}, expected {expected}",
)
return Answer(Verdict.WRITE, total, length if encoded else content_range[1] - content_range[0] + 1, content_range)
def _request_range(value: str) -> tuple[int, int | None] | None:
"""A Range value as ``(start, end)``, ``end`` None when open-ended. Gives None when not ``bytes=start-...``."""
match = re.match(r"bytes=(\d+)-(\d+)?", value.strip())
if not match:
return None
return int(match.group(1)), int(match.group(2)) if match.group(2) else None
def _parse_content_range(value: str) -> ContentRange | None:
"""A 206's Content-Range as ``(start, end, total)``, ``total`` None for ``*``. Gives None when absent or unparseable."""
match = re.fullmatch(r"bytes\s+(\d+)-(\d+)/(\d+|\*)", value, re.IGNORECASE)
if not match:
return None
return int(match.group(1)), int(match.group(2)), None if match.group(3) == "*" else int(match.group(3))
def _unsatisfied_length(value: str) -> int | None:
"""A 416's ``bytes */N`` Content-Range as N. Gives None when absent or unknown."""
match = re.fullmatch(r"bytes\s+\*/(\d+)", value, re.IGNORECASE)
return int(match.group(1)) if match else None
+22 -165
View File
@@ -33,6 +33,7 @@ from rich import filesize
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DownloadCancelled from unshackle.core.constants import DOWNLOAD_CANCELLED, DownloadCancelled
from unshackle.core.downloaders.ranges import Mode, Verdict, has_range_header, range_answer
from unshackle.core.remote_protocol import APIErrorCode, coded from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.utilities import get_debug_logger, get_extension, log_event from unshackle.core.utilities import get_debug_logger, get_extension, log_event
from unshackle.core.utils import run_proxy from unshackle.core.utils import run_proxy
@@ -627,91 +628,6 @@ def probe_ranged(url: str, session: Any, **kwargs: Any) -> tuple[int, bool]:
pass pass
def has_range_header(item: dict[str, Any]) -> bool:
"""True when a URL item's per-request headers already carry a Range.
Such an item is itself a byte-range slice of a larger resource (DASH SegmentBase,
HLS EXT-X-BYTERANGE). Probing or part-mode would clobber that Range and fetch the
wrong bytes, so ranged-parallel strategies must skip these items entirely.
"""
return any(k.lower() == "range" for k in (item.get("headers") or {}))
def range_covers_full_body(headers: MutableMapping[str, Any], content_length: int) -> bool:
"""True when a 200 body is exactly the bytes the item's Range slice asked for.
A server may ignore Range and answer 200 with the whole resource (RFC 9110
permits this). That body is only the right bytes when the slice starts at byte 0
and spans exactly the full body. Anything else (open-ended, multi-range, nonzero
start, span mismatch) stays fail-closed.
"""
value = str(next((v for k, v in headers.items() if k.lower() == "range"), ""))
match = re.fullmatch(r"bytes=(\d+)-(\d+)", value.strip())
if not match or content_length <= 0:
return False
start, end = int(match.group(1)), int(match.group(2))
return start == 0 and content_length == end + 1
def parse_content_range(value: Any) -> tuple[int, int, int | None] | None:
"""Parse a 206's ``Content-Range`` into ``(start, end, total)``. Gives None when absent or unparseable.
``total`` is None for an unknown complete length (``*``). None fails closed: a caller
must not place bytes at an offset it cannot prove the server agreed to.
"""
if isinstance(value, bytes):
value = value.decode("latin1", "replace")
match = re.fullmatch(r"bytes\s+(\d+)-(\d+)/(\d+|\*)", str(value or "").strip(), re.IGNORECASE)
if not match:
return None
return int(match.group(1)), int(match.group(2)), None if match.group(3) == "*" else int(match.group(3))
def parse_content_range_unsatisfied(value: Any) -> int | None:
"""Parse a 416's ``Content-Range`` into the complete length. Gives None when absent or unknown.
A 416 answers with ``bytes */N`` (or ``bytes */*``), which the 206 form does not cover.
"""
if isinstance(value, bytes):
value = value.decode("latin1", "replace")
match = re.fullmatch(r"bytes\s+\*/(\d+)", str(value or "").strip(), re.IGNORECASE)
return int(match.group(1)) if match else None
def range_clamped_to_end(content_range: tuple[int, int, int | None], slice_end: int) -> bool:
"""Whether a 206 stops early only because the requested range ends past the resource.
RFC 9110 clamps a range end at or beyond the complete length to the last byte, so the
response still carries the whole slice. Some manifests author such ranges.
"""
_, end, total = content_range
return total is not None and end == total - 1 and slice_end >= total
def range_answers(content_range: tuple[int, int, int | None] | None, slice_range: tuple[int, int | None]) -> bool:
"""Whether a 206's parsed ``Content-Range`` carries the requested ``(start, end)`` slice."""
start, end = slice_range
return (
content_range is not None
and content_range[0] == start
and (end is None or content_range[1] == end or range_clamped_to_end(content_range, end))
)
def request_range(headers: MutableMapping[str, Any]) -> tuple[int, int | None] | None:
"""
The request's ``Range`` as ``(start, end)``. Gives None when absent or not ``bytes=start-...``.
``end`` is None for an open-ended ``bytes=start-``, which the caller cannot hold a
response to.
"""
value = str(next((v for k, v in headers.items() if str(k).lower() == "range"), ""))
match = re.match(r"bytes=(\d+)-(\d+)?", value.strip())
if not match:
return None
return int(match.group(1)), int(match.group(2)) if match.group(2) else None
def split_ranges(size: int, max_parts: int | None, part_target: int) -> list[tuple[int, int]]: def split_ranges(size: int, max_parts: int | None, part_target: int) -> list[tuple[int, int]]:
"""Split ``[0, size)`` into inclusive ``[start, end]`` byte ranges with no gaps or overlaps. """Split ``[0, size)`` into inclusive ``[start, end]`` byte ranges with no gaps or overlaps.
@@ -963,6 +879,8 @@ def download(
_time = time.monotonic _time = time.monotonic
item_range = has_range_header(kwargs) item_range = has_range_header(kwargs)
mode = Mode.PART if part_mode else Mode.ITEM if item_range else Mode.RESUME
part = (part_offset, part_end) if part_offset is not None and part_end is not None else None
attempts = 1 attempts = 1
outages = 0 outages = 0
@@ -1016,13 +934,22 @@ def download(
stream = transport.get(url, **request_kwargs) stream = transport.get(url, **request_kwargs)
if (not part_mode) and (not item_range) and resume_offset > 0 and stream.status_code == 416: answer = range_answer(
complete = parse_content_range_unsatisfied(stream.header("Content-Range")) mode,
req_headers,
stream.status_code,
stream.header("Content-Range"),
length=stream.content_length,
encoded=stream.content_encoded,
total=known_total,
part=part,
)
known_total = answer.total
if answer.verdict is Verdict.FINISHED:
try: try:
stream.close() stream.close()
except Exception: except Exception:
pass pass
if complete == resume_offset and known_total in (None, resume_offset):
if not segmented and not progress_seeded: if not segmented and not progress_seeded:
# nothing is read on this path, so the bar has to be seeded here # nothing is read on this path, so the bar has to be seeded here
progress_seeded = True progress_seeded = True
@@ -1033,87 +960,17 @@ def download(
if segmented: if segmented:
yield dict(advance=1) yield dict(advance=1)
break break
if answer.verdict is Verdict.RESTART:
tmp_file.unlink(missing_ok=True) tmp_file.unlink(missing_ok=True)
raise OSError(f"resume from byte {resume_offset} got a 416, complete length {complete}") raise OSError(answer.reason)
stream.raise_for_status() stream.raise_for_status()
if answer.verdict is Verdict.REJECT:
# item_range 206s reflect the slice's own Range, not a resume; those retries rewrite in "wb" raise OSError(answer.reason)
resumed = (not part_mode) and (not item_range) and resume_offset > 0 and stream.status_code == 206 resumed = answer.verdict is Verdict.APPEND
if resumed: if not part_mode and not resumed:
content_range = parse_content_range(stream.header("Content-Range"))
if content_range is None or content_range[0] != resume_offset:
# some servers answer `bytes=X-` with a 206 for the whole resource;
# appending that body would misplace every byte after the partial. A
# proven full-resource-from-zero body is byte-identical to a 200, so
# keep the response and rewrite from scratch; anything else (alien
# start, prefix slice, no provable placement) restarts clean like a 416
start, end, total = content_range or (None, None, None)
if start == 0 and total is not None and end == total - 1:
resumed = False
resume_offset = 0 resume_offset = 0
else: content_length = answer.length
tmp_file.unlink(missing_ok=True)
raise OSError(f"resume from byte {resume_offset} got Content-Range {content_range!r}")
elif content_range[2] is not None:
known_total = content_range[2]
if (not part_mode) and resume_offset > 0 and not resumed:
resume_offset = 0
if part_mode and part_offset is not None and part_end is not None: # spelled so mypy narrows
if stream.status_code != 206:
raise OSError(f"expected 206 for ranged part, got {stream.status_code}")
content_range = parse_content_range(stream.header("Content-Range"))
if (
content_range is None
or content_range[0] != part_offset + written
or (chunk_end is not None and content_range[1] > chunk_end)
or (content_range[2] is not None and content_range[2] <= part_end)
):
# a wrong start would land bytes at the wrong offset in the shared file,
# an end past what this request asked for would spill into a sibling
# part's region, and a total at or below part_end means the resource
# changed under the part plan; fail the attempt before any byte is written
raise OSError(f"part {part_offset}-{part_end} got Content-Range {content_range!r}")
content_length = stream.content_length
if known_total is None and not part_mode and not item_range and stream.status_code == 200:
# a 200 carries the whole resource, so its length is the complete length
known_total = content_length or None
if known_total is None and not part_mode and not item_range and stream.status_code == 206:
fresh_range = parse_content_range(stream.header("Content-Range"))
if fresh_range is not None:
if fresh_range[0] != resume_offset:
raise OSError(f"206 body starts at byte {fresh_range[0]}, expected {resume_offset}")
known_total = fresh_range[2]
if item_range and not part_mode and stream.status_code != 206:
# server ignored the slice's Range and sent the whole parent (RFC 9110 allows
# a 200 here); writing that as the segment would silently corrupt the merge, so
# fail the attempt unless the slice spans the whole resource, in which case the
# 200 body is byte-identical to the 206 and safe to keep
if not (stream.status_code == 200 and range_covers_full_body(req_headers, content_length)):
raise OSError(f"expected 206 for byte-range segment, got {stream.status_code}")
if item_range and not part_mode and stream.status_code == 206:
# a 206 for a different range than the slice asked for (e.g. the whole parent,
# or the short range a size-capping CDN chose to serve) would be written as the
# whole segment and silently corrupt the merge
slice_range = request_range(req_headers)
if slice_range is not None:
slice_start, slice_end = slice_range
content_range = parse_content_range(stream.header("Content-Range"))
if content_range is None or not range_answers(content_range, slice_range):
raise OSError(
f"byte-range segment got Content-Range {content_range!r}, "
f"expected {slice_start}-{slice_end if slice_end is not None else ''}"
)
if not stream.content_encoded:
content_length = content_range[1] - content_range[0] + 1
if resumed and stream.content_encoded:
tmp_file.unlink(missing_ok=True)
raise OSError(f"resume from byte {resume_offset} came back content-encoded")
limiter = speed_limiter limiter = speed_limiter
chunk_size = adaptive_chunk_size(content_length) chunk_size = adaptive_chunk_size(content_length)
+7 -6
View File
@@ -28,7 +28,7 @@ from requests import Session
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.downloaders.requests import parse_content_range, range_answers, request_range from unshackle.core.downloaders.ranges import Mode, range_answer
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
from unshackle.core.drm.cenc import COMMON_ID, PLACEHOLDER_KIDS, PLAYREADY_ID, common_pssh_kids from unshackle.core.drm.cenc import COMMON_ID, PLACEHOLDER_KIDS, PLAYREADY_ID, common_pssh_kids
from unshackle.core.drm.segment_decrypt import SegmentPool, can_use, make_decrypter from unshackle.core.drm.segment_decrypt import SegmentPool, can_use, make_decrypter
@@ -1199,14 +1199,15 @@ class DASH:
init_url = urljoin(rep_base_url, init_attrs.get("sourceURL") or "") init_url = urljoin(rep_base_url, init_attrs.get("sourceURL") or "")
same_file = init_url == rep_base_url same_file = init_url == rep_base_url
init_range_header = {"Range": f"bytes={init_range}"} if init_range else None init_range_header = {"Range": f"bytes={init_range}"} if init_range else None
slice_range = request_range(init_range_header) if init_range_header else None
if (same_file and init_range) or (not same_file and probe_kid): if (same_file and init_range) or (not same_file and probe_kid):
res = unrecorded(session, "get", init_url, headers=init_range_header, stream=True) res = unrecorded(session, "get", init_url, headers=init_range_header, stream=True)
res.raise_for_status() res.raise_for_status()
content_range = parse_content_range(res.headers.get("Content-Range")) content_range = None
if init_range_header and not ( if init_range_header:
res.status_code == 206 and slice_range and range_answers(content_range, slice_range) content_range = range_answer(
): Mode.ITEM, init_range_header, res.status_code, res.headers.get("Content-Range")
).content_range
if content_range is None:
res.close() res.close()
raise click.ClickException( raise click.ClickException(
f"Init range {init_range} of {safe_display_url(init_url)} got {res.status_code} " f"Init range {init_range} of {safe_display_url(init_url)} got {res.status_code} "