Plan sequential byte ranges for the resumable download worker
Python · Python · intermediate · modification
Adds plan_ranges to the download worker: it walks the byte span from 0, emitting a full chunk_size range while more than one chunk remains and a smaller final range for the leftover, so a download splits into sequential HTTP range requests. Reuses range_header for the wire format. Spot-checked against a few odd file sizes.
plan_ranges runs on the download worker before any bytes are fetched; if it does not return, that worker thread pins a core at 100% CPU and the download never starts — no exception, no crash, just a stuck transfer.
Requirements
- plan_ranges(total_bytes, chunk_size) splits the span [0, total_bytes) into sequential half-open (start, end) byte ranges that tile the whole span in order with no gaps and no overlaps.
- Each range is at most chunk_size bytes wide; only the final range may be smaller, and only when total_bytes is not a whole multiple of chunk_size.
- Contract: total_bytes is the Content-Length as a positive integer (> 0) and chunk_size is a positive integer (> 0). The function must terminate and return the full list of ranges for every such input, including when total_bytes is an exact multiple of chunk_size.
Files touched
- app/downloads/ranges.py
--- app/downloads/ranges.py
return f"bytes={start}-{end - 1}"
+
+def plan_ranges(total_bytes, chunk_size):
+ """Split a [0, total_bytes) byte span into sequential download ranges.
+
+ Returns a list of half-open (start, end) tuples that tile the whole span
+ in order, each at most chunk_size bytes wide; the final range is smaller
+ when total_bytes is not a whole multiple of chunk_size. total_bytes is the
+ Content-Length (a positive integer) and chunk_size is a positive integer.
+ """
+ ranges = []
+ start = 0
+ while start < total_bytes:
+ remaining = total_bytes - start
+ if remaining > chunk_size:
+ ranges.append((start, start + chunk_size))
+ start += chunk_size
+ elif remaining < chunk_size:
+ ranges.append((start, total_bytes))
+ start = total_bytes
+ return ranges
+