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

Files touched

--- 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
+

Review this PR

Python practice