蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行真实 SQLite filedownlog + 本地回环 HTTP 206 两阶段多线程断点续传实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-download2.py
explore-tutorial-download2.py268 行
"""Offline Android resumable multi-thread download (SQLite filedownlog + HTTP 206 Range) verifier (Ch 93: tutorial-download2)."""
from __future__ import annotations

import hashlib
import http.client
import json
import math
import re
import sqlite3
import sys
import tempfile
import threading
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"

MEDIA_BYTES = bytes((i * 53 + 7) % 256 for i in range(9_000))
MEDIA_SHA = hashlib.sha256(MEDIA_BYTES).hexdigest()


class ResumableHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, format: str, *args) -> None:
        return

    def do_GET(self) -> None:
        if self.path not in {"/audio/twelve.mp3", "/download"}:
            self.send_response(404)
            self.send_header("Content-Length", "0")
            self.end_headers()
            return
        extra = {}
        if self.path == "/download":
            extra["Content-Disposition"] = 'attachment; filename="fallback_track.mp3"'
        rng = self.headers.get("Range")
        if rng:
            m = re.match(r"bytes=(\d+)-(\d*)", rng)
            if m:
                start = int(m.group(1))
                end = int(m.group(2)) if m.group(2) else len(MEDIA_BYTES) - 1
                end = min(end, len(MEDIA_BYTES) - 1)
                part = MEDIA_BYTES[start : end + 1]
                self.send_response(206)
                self.send_header("Content-Range", f"bytes {start}-{end}/{len(MEDIA_BYTES)}")
                self.send_header("Content-Length", str(len(part)))
                for k, v in extra.items():
                    self.send_header(k, v)
                self.end_headers()
                self.wfile.write(part)
                return
        self.send_response(200)
        self.send_header("Content-Length", str(len(MEDIA_BYTES)))
        for k, v in extra.items():
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(MEDIA_BYTES)


class FileServiceDB:
    """SQLite-backed progress store equivalent to DBOpenHelper + FileService."""

    def __init__(self, db_path: Path):
        self.db_path = db_path
        conn = sqlite3.connect(self.db_path)
        try:
            conn.execute(
                "CREATE TABLE IF NOT EXISTS filedownlog ("
                "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                "downpath VARCHAR(100), threadid INTEGER, downlength INTEGER)"
            )
            conn.commit()
        finally:
            conn.close()

    def save(self, path: str, thread_map: dict[int, int]) -> None:
        conn = sqlite3.connect(self.db_path)
        try:
            conn.execute("BEGIN")
            for tid, length in thread_map.items():
                conn.execute(
                    "INSERT INTO filedownlog(downpath, threadid, downlength) VALUES (?, ?, ?)",
                    (path, tid, length),
                )
            conn.commit()
        finally:
            conn.close()

    def get_data(self, path: str) -> dict[int, int]:
        conn = sqlite3.connect(self.db_path)
        try:
            rows = conn.execute(
                "SELECT threadid, downlength FROM filedownlog WHERE downpath = ? ORDER BY threadid",
                (path,),
            ).fetchall()
            return {tid: length for tid, length in rows}
        finally:
            conn.close()

    def update(self, path: str, thread_id: int, pos: int) -> None:
        conn = sqlite3.connect(self.db_path)
        try:
            conn.execute(
                "UPDATE filedownlog SET downlength = ? WHERE downpath = ? AND threadid = ?",
                (pos, path, thread_id),
            )
            conn.commit()
        finally:
            conn.close()

    def delete(self, path: str) -> None:
        conn = sqlite3.connect(self.db_path)
        try:
            conn.execute("DELETE FROM filedownlog WHERE downpath = ?", (path,))
            conn.commit()
        finally:
            conn.close()


def extract_filename(url_path: str, content_disposition: str | None) -> str:
    tail = url_path.rsplit("/", 1)[-1].strip()
    if tail and "." in tail:
        return tail
    if content_disposition:
        m = re.search(r'filename="?([^";]+)"?', content_disposition, re.IGNORECASE)
        if m:
            return m.group(1)
    return f"{uuid.uuid5(uuid.NAMESPACE_URL, url_path)}.tmp"


def main() -> None:
    cases = []
    server = ThreadingHTTPServer(("127.0.0.1", 0), ResumableHandler)
    port = server.server_address[1]
    url_path = "/audio/twelve.mp3"
    full_url = f"http://127.0.0.1:{port}{url_path}"
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        with tempfile.TemporaryDirectory() as tmp:
            tdir = Path(tmp)
            svc = FileServiceDB(tdir / "downs.db")
            save_file = tdir / "twelve.mp3"

            total_size = len(MEDIA_BYTES)
            n_threads = 3
            block = math.ceil(total_size / n_threads)  # 3000 bytes each
            with save_file.open("wb") as fh:
                fh.truncate(total_size)

            # Phase 1: Initialize 3 threads, download first 1000 bytes of each block, then simulate pause (exited=True)
            svc.save(full_url, {1: 0, 2: 0, 3: 0})
            for tid in range(1, n_threads + 1):
                start = block * (tid - 1)
                partial_end = start + 1000 - 1
                c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
                c.request("GET", url_path, headers={"Range": f"bytes={start}-{partial_end}"})
                r = c.getresponse()
                data = r.read()
                c.close()
                with save_file.open("r+b") as fh:
                    fh.seek(start)
                    fh.write(data)
                svc.update(full_url, tid, len(data))

            checkpoint = svc.get_data(full_url)
            actual1 = {"checkpoint": checkpoint, "partial_total": sum(checkpoint.values())}
            expected1 = {"checkpoint": {1: 1000, 2: 1000, 3: 1000}, "partial_total": 3000}
            cases.append({
                "name": "resumable_phase1_sqlite_checkpoint",
                "summary": "Verify Phase-1 partial HTTP 206 download persists per-thread byte offsets in SQLite filedownlog.",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Phase 2: Resume strictly from SQLite offsets using Range: bytes=startPos-endPos and clean DB on completion
            resumed = svc.get_data(full_url)
            range_headers_sent = []
            for tid in range(1, n_threads + 1):
                done = resumed[tid]
                start_pos = block * (tid - 1) + done
                end_pos = min(total_size - 1, block * tid - 1)
                rng_hdr = f"bytes={start_pos}-{end_pos}"
                range_headers_sent.append(rng_hdr)
                c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
                c.request("GET", url_path, headers={"Range": rng_hdr})
                r = c.getresponse()
                data = r.read()
                c.close()
                with save_file.open("r+b") as fh:
                    fh.seek(start_pos)
                    fh.write(data)
                done += len(data)
                svc.update(full_url, tid, done)

            final_map = svc.get_data(full_url)
            if sum(final_map.values()) == total_size:
                svc.delete(full_url)
            after_delete = svc.get_data(full_url)
            actual2 = {
                "range_headers": range_headers_sent,
                "final_total": sum(final_map.values()),
                "db_cleaned": after_delete == {},
                "sha_matches": hashlib.sha256(save_file.read_bytes()).hexdigest() == MEDIA_SHA,
            }
            expected2 = {
                "range_headers": ["bytes=1000-2999", "bytes=4000-5999", "bytes=7000-8999"],
                "final_total": 9000,
                "db_cleaned": True,
                "sha_matches": True,
            }
            cases.append({
                "name": "resumable_phase2_resume_and_cleanup",
                "summary": "Verify Phase-2 resumes from SQLite offsets via Range headers, verifies SHA-256, and deletes log rows.",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: Legacy FileService.getData cursor off-by-one bug demonstration
            rows = [(1, 1000), (2, 1000), (3, 1000)]
            # Legacy bug: cursor.moveToFirst() followed immediately by while(cursor.moveToNext()) skips row 0!
            buggy_read = rows[1:]
            fixed_read = rows[:]
            actual3 = {"legacy_bug_skips_thread1": len(buggy_read) == 2 and buggy_read[0][0] == 2, "fixed_reads_all_3": len(fixed_read) == 3}
            expected3 = {"legacy_bug_skips_thread1": True, "fixed_reads_all_3": True}
            cases.append({
                "name": "cursor_off_by_one_bug_check",
                "summary": "Verify why calling moveToFirst() before while(moveToNext()) drops the first thread record.",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: Filename resolution priority (URL path -> Content-Disposition -> UUID .tmp)
            fn_url = extract_filename("/audio/twelve.mp3", None)
            fn_disp = extract_filename("/download", 'attachment; filename="fallback_track.mp3"')
            fn_uuid = extract_filename("/download", None)
            actual4 = {
                "from_url": fn_url,
                "from_content_disposition": fn_disp,
                "from_uuid_fallback_ends_tmp": fn_uuid.endswith(".tmp"),
            }
            expected4 = {
                "from_url": "twelve.mp3",
                "from_content_disposition": "fallback_track.mp3",
                "from_uuid_fallback_ends_tmp": True,
            }
            cases.append({
                "name": "filename_extraction_fallback",
                "summary": "Verify filename resolution order: URL tail -> Content-Disposition header -> UUID.tmp fallback.",
                "expected": expected4,
                "actual": actual4,
                "passed": actual4 == expected4,
            })
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    sys.exit(main())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-download2-lab/explore-tutorial-download2.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-download2.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1870.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习