File size: 5,176 Bytes
086f82d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""Download or reconstruct the frozen inputs for one sample task."""

import argparse
import gzip
import hashlib
import json
import os
import shutil
import sys
import tempfile
from contextlib import nullcontext
from pathlib import Path, PurePosixPath
from urllib.request import Request, urlopen


ROOT = Path(__file__).resolve().parent
TASKS = ROOT
CHUNK_SIZE = 1024 * 1024


def validate_input(path, record):
    if not path.is_file():
        raise ValueError(f"Missing input: {path}")
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        while chunk := stream.read(CHUNK_SIZE):
            digest.update(chunk)
    if path.stat().st_size != record["bytes"] or digest.hexdigest() != record["sha256"]:
        raise ValueError(f"Input does not match the recorded size and SHA-256: {path}")


def output_path(task_dir, name):
    relative = PurePosixPath(name)
    if (
        relative.is_absolute()
        or ".." in relative.parts
        or "\\" in name
        or ":" in name
        or relative.parts[:1] != ("inputs",)
    ):
        raise ValueError(f"Invalid input path: {name}")
    target = task_dir.joinpath(*relative.parts).resolve()
    if not target.is_relative_to(task_dir):
        raise ValueError(f"Input path escapes the task directory: {name}")
    return target


def reconstruct_wfs(response, record):
    data = json.loads(response.read(65537))
    if not isinstance(data, dict) or {
        key: value for key, value in data.items() if key != "timeStamp"
    } != {
        "type": "FeatureCollection",
        "features": [],
        "totalFeatures": 0,
        "numberMatched": 0,
        "numberReturned": 0,
        "crs": None,
    }:
        raise ValueError("The Marine Regions response differs from the frozen empty CHE collection.")
    data["timeStamp"] = record["reconstruction"]["frozen_timestamp"]
    order = record["reconstruction"]["field_order"]
    return json.dumps({key: data[key] for key in order}, separators=(",", ":")).encode("utf-8")


def prepare(task_dir, record, verify_only):
    target = output_path(task_dir, record["path"])
    if target.exists() or verify_only or record["method"] == "bundled":
        validate_input(target, record)
        print(f"Verified {record['path']}")
        return

    target.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(dir=target.parent) as scratch:
        partial = Path(scratch) / "input"
        request = Request(record["url"], headers={"Accept-Encoding": "gzip"})
        with urlopen(request, timeout=60) as response, partial.open("wb") as dest:
            encoding = response.headers.get("Content-Encoding", "identity").lower()
            if encoding not in {"gzip", "identity"}:
                raise ValueError(f"Unexpected HTTP content encoding: {encoding}")
            transport = gzip.GzipFile(fileobj=response) if encoding == "gzip" else nullcontext(response)
            with transport as source:
                if record["method"] == "download":
                    shutil.copyfileobj(source, dest, length=CHUNK_SIZE)
                elif record["method"] == "reconstruct_text":
                    recipe = record["reconstruction"]
                    payload = source.read().replace(b"\r\n", b"\n")
                    old, new = recipe["old"].encode("utf-8"), recipe["new"].encode("utf-8")
                    if payload.count(old) != 1:
                        raise ValueError("The pinned upstream text no longer matches the input recipe.")
                    dest.write(payload.replace(old, new))
                elif record["method"] == "reconstruct_marine_regions_wfs":
                    dest.write(reconstruct_wfs(source, record))
                else:
                    raise ValueError(f"Unknown input method: {record['method']}")
        validate_input(partial, record)
        if target.exists():
            validate_input(target, record)
        else:
            os.replace(partial, target)
    print(f"Prepared and verified {record['path']}")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("case_id", choices=sorted(p.name for p in TASKS.iterdir() if p.is_dir() and (p / "input_manifest.json").is_file()))
    parser.add_argument("--verify-only", action="store_true", help="Check local files without downloading.")
    args = parser.parse_args()
    task_dir = (TASKS / args.case_id).resolve()
    data = json.loads((task_dir / "input_manifest.json").read_text(encoding="utf-8"))
    pending = []
    try:
        for record in data["inputs"]:
            if record["method"] == "manual_reconstruction" and not output_path(task_dir, record["path"]).is_file():
                pending.append(record["path"])
                continue
            prepare(task_dir, record, args.verify_only)
    except (OSError, ValueError) as error:
        print(error, file=sys.stderr)
        return 1
    if pending:
        print("Files requiring the documented reconstruction:", file=sys.stderr)
        for path in pending:
            print(f"  {path}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())