File size: 6,510 Bytes
4ad9219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env python3
"""对同一冻结官方文件做可恢复Range并发传输,不改变视频/QA选择。"""
import concurrent.futures
import datetime
import hashlib
import json
import os
from pathlib import Path
import shutil
import threading
import time
import urllib.request
from download_assets import ROOT, atomic, sha, asset_path, merge_target, record_asset_path


def parallel_download(item, workers=16, block_bytes=16*1024**2):
    path=asset_path(item);path.parent.mkdir(parents=True,exist_ok=True)
    receipt=ROOT/'provenance/downloads'/(item['destination'].replace('/','__')+'.json')
    directory=path.with_name(path.name+'.range-parts');directory.mkdir(exist_ok=True)
    legacy=path.with_name(path.name+'.incomplete')
    started=time.monotonic();guard=threading.Lock();completed={};errors=[]
    ranges=[(index,offset,min(block_bytes,item['size']-offset)) for index,offset in enumerate(range(0,item['size'],block_bytes))]
    for index,offset,size in ranges:
        dest=directory/f'{index:06d}.part'
        if dest.exists() and dest.stat().st_size==size:
            completed[index]=size
        elif legacy.exists() and legacy.stat().st_size>=offset+size:
            # 原顺序下载的完整前缀直接复用,不丢弃已传输内容。
            with legacy.open('rb') as source:
                source.seek(offset);block=source.read(size)
            dest.write_bytes(block);completed[index]=size

    def progress(status):
        with guard:
            value=dict(item,status=status,bytes=sum(completed.values()),range_completed=len(completed),
                       storage_path=str(path),
                       range_total=len(ranges),range_workers=workers,elapsed_seconds=time.monotonic()-started,
                       errors=errors[-10:],updated_at=datetime.datetime.now(datetime.timezone.utc).isoformat())
            atomic(receipt,value)

    def fetch(spec):
        index,offset,size=spec;dest=directory/f'{index:06d}.part'
        if index in completed:return
        attempt=0
        while True:
            attempt+=1
            try:
                routes=json.loads((ROOT/'coordination/download_routes.json').read_text())
                transfer=dict(item,**routes.get(item['destination'],{}))
                if transfer['sha256']!=item['sha256']:raise RuntimeError('禁止改变冻结SHA256')
                if shutil.disk_usage(directory).free<80*1024**3+block_bytes*workers:
                    raise RuntimeError('并发传输空间余量不足,等待,不删除用户数据')
                opener=urllib.request.build_opener(urllib.request.ProxyHandler({
                    'http':transfer.get('proxy','http://127.0.0.1:8118'),
                    'https':transfer.get('proxy','http://127.0.0.1:8118')}))
                request=urllib.request.Request(transfer['url'],headers={'Range':f'bytes={offset}-{offset+size-1}'})
                with opener.open(request,timeout=90) as response:
                    if response.status!=206 or not response.headers.get('Content-Range','').startswith(f'bytes {offset}-'):
                        raise RuntimeError('服务端未遵守Range')
                    with dest.open('wb') as out:
                        count=0
                        while True:
                            block=response.read(256*1024)
                            if not block:break
                            out.write(block);count+=len(block)
                            if count>size:
                                dest.unlink(missing_ok=True)
                                raise RuntimeError('Range响应超过请求范围')
                    if count!=size:
                        dest.unlink(missing_ok=True)
                        raise RuntimeError('Range响应大小不足')
                with guard:completed[index]=size
                progress('downloading_parallel')
                return
            except Exception as exc:
                dest.unlink(missing_ok=True)
                with guard:errors.append(dict(block=index,attempt=attempt,type=type(exc).__name__))
                progress('retrying_parallel')
                time.sleep(min(120,2**min(attempt,6)))
    progress('downloading_parallel')
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
        list(pool.map(fetch,ranges))
    final=merge_target(item,path)
    legacy_assembled=final.with_name(final.name+'.assembling')
    if legacy_assembled.exists() and legacy_assembled.stat().st_size==item['size']:
        shutil.copyfile(legacy_assembled, final)
        legacy_assembled.unlink(missing_ok=True)
    digest=hashlib.sha256()
    if final.exists() and final.stat().st_size==item['size']:
        with final.open('rb') as stream:
            for block in iter(lambda:stream.read(8*1024**2),b''):
                digest.update(block)
    else:
        with final.open('wb') as out:
            for index,_,size in ranges:
                with (directory/f'{index:06d}.part').open('rb') as source:
                    for block in iter(lambda:source.read(4*1024**2),b''):
                        while shutil.disk_usage(final.parent).free<80*1024**3+len(block):
                            progress('waiting_merge_space');time.sleep(30)
                        digest.update(block);out.write(block)
    if final.stat().st_size!=item['size'] or digest.hexdigest()!=item['sha256']:
        final.unlink(missing_ok=True)
        raise RuntimeError('并发合并SHA256失败;保留全部分块供诊断与重合并')
    if item['destination'].startswith('data/training_archives/'):
        record_asset_path(item,final,'official_whole_SHA256_verified; range_parts_at_'+str(directory))
    proof=dict(item,status='verified',bytes=item['size'],sha256=digest.hexdigest(),range_workers=workers,
               range_blocks=len(ranges),elapsed_seconds=time.monotonic()-started,errors=errors,
               reused_legacy_prefix_bytes=legacy.stat().st_size if legacy.exists() else 0)
    proof.update(storage_path=str(final),range_parts_storage_path=str(directory))
    atomic(receipt,proof)
    atomic(ROOT/'provenance'/(path.name+'.range-transfer.json'),proof)
    # 只清理本项目已校验合并成功的传输分块。
    shutil.rmtree(directory);legacy.unlink(missing_ok=True)
    print(json.dumps(dict(file=item['destination'],status='verified',parallel_workers=workers,
                          seconds=time.monotonic()-started),ensure_ascii=False),flush=True)
    return str(final)