team-ljyzipelo

공개
205줄7.0 KB
1"""고정 크기 버퍼로 새 스트리밍 한도의 독립 경계 표본을 생성함."""
2
3import argparse
4import gzip
5import hashlib
6import io
7import json
8import os
9from pathlib import Path
10import struct
11import tarfile
12import zipfile
13import zlib
14
15
16ROOT = Path(__file__).resolve().parents[2]
17GIB = 1024 ** 3
18CHUNK = 64 * 1024
19INPUT_LIMIT = 2 ** 64 - 1
20OUTPUT_LIMIT = 16 * GIB
21NAME = "payload.bin"
22
23
24class ZeroStream(io.RawIOBase):
25 def __init__(self, size):
26 self.remaining = size
27
28 def read(self, size=-1):
29 if size < 0 or size > CHUNK:
30 raise ValueError("표본 읽기는 64 KiB 이하로 제한함")
31 count = min(size, self.remaining)
32 self.remaining -= count
33 return bytes(count)
34
35
36def write_zip(path, size, compressed, level=6):
37 info = zipfile.ZipInfo(NAME, (1980, 1, 1, 0, 0, 0))
38 info.compress_type = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED
39 info._compresslevel = level
40 info.create_system = 3
41 info.external_attr = 0o100600 << 16
42 info.file_size = size
43 with zipfile.ZipFile(path, "x", compression=info.compress_type) as archive:
44 with archive.open(info, "w") as output:
45 source = ZeroStream(size)
46 while chunk := source.read(CHUNK):
47 output.write(chunk)
48
49
50def tar_size(size):
51 return 512 + ((size + 511) // 512) * 512 + 1024
52
53
54def write_targz(path, size, compressed):
55 info = tarfile.TarInfo(NAME)
56 info.size = size
57 info.mode = 0o600
58 info.mtime = 0
59 with path.open("xb") as raw:
60 with gzip.GzipFile(
61 filename="", mode="wb", fileobj=raw,
62 compresslevel=6 if compressed else 0, mtime=0,
63 ) as output:
64 output.write(info.tobuf(format=tarfile.USTAR_FORMAT))
65 source = ZeroStream(size)
66 while chunk := source.read(CHUNK):
67 output.write(chunk)
68 output.write(bytes((-size) % 512 + 1024))
69
70
71def write_ratio_gzip(path, size, packed_size):
72 compressor = zlib.compressobj(level=6, wbits=-15)
73 source = ZeroStream(size)
74 crc = 0
75 chunks = []
76 while chunk := source.read(CHUNK):
77 crc = zlib.crc32(chunk, crc)
78 chunks.append(compressor.compress(chunk))
79 data = b"".join(chunks) + compressor.flush()
80 padding = packed_size - 20 - len(data)
81 assert 0 <= padding <= 65535
82 header = bytes.fromhex("1f8b08040000000000ff") + struct.pack("<H", padding)
83 with path.open("xb") as output:
84 output.write(header + bytes(padding) + data + struct.pack("<II", crc, size))
85 assert path.stat().st_size == packed_size
86
87
88def digest(path):
89 value = hashlib.sha256()
90 with path.open("rb") as source:
91 while chunk := source.read(CHUNK):
92 value.update(chunk)
93 return value.hexdigest()
94
95
96def violations(artifact, limits):
97 failed = []
98 if artifact["archive_bytes"] > limits["input"]:
99 failed.append("input")
100 if artifact["decoded_bytes"] > limits["output"]:
101 failed.append("output")
102 return failed
103
104
105def build(directory, large=False):
106 directory = Path(directory).resolve()
107 directory.relative_to(Path(os.environ["ZIPELO_TEST_WORK_DIR"]).resolve())
108 directory.mkdir(mode=0o700, parents=True, exist_ok=False)
109 cases = []
110 artifacts = {}
111
112 def add(name, size, compressed, category, boundaries, level=6, packed_size=None):
113 path = directory / name
114 if name.endswith(".zip"):
115 write_zip(path, size, compressed, level)
116 expanded = size
117 with zipfile.ZipFile(path) as archive:
118 ratio_input = archive.getinfo(NAME).compress_size
119 archive_format = "Zip"
120 elif name.endswith(".tar.gz"):
121 write_targz(path, size, compressed)
122 expanded = tar_size(size)
123 ratio_input = path.stat().st_size
124 archive_format = "TarGzip"
125 else:
126 write_ratio_gzip(path, size, packed_size)
127 expanded = size
128 ratio_input = path.stat().st_size
129 archive_format = "Gzip"
130 artifact = {
131 "format": archive_format,
132 "archive_bytes": path.stat().st_size,
133 "payload_bytes": size,
134 "decoded_bytes": expanded,
135 "ratio_input_bytes": ratio_input,
136 "sha256": digest(path),
137 }
138 artifacts[name] = artifact
139 for suffix, output_limit, exceeded in boundaries:
140 limits = {"input": INPUT_LIMIT, "output": output_limit, "entries": 10000}
141 assert violations(artifact, limits) == exceeded, (name, suffix, artifact)
142 failed = bool(exceeded)
143 cases.append({
144 "id": name + "-" + suffix,
145 "file": name,
146 "category": category,
147 "limits": limits,
148 "violated_limits": exceeded,
149 "expected": {
150 "outcome": "Failed" if failed else "Completed",
151 "error": "Limit" if failed else "None",
152 "publication": "None" if failed else "Complete",
153 "created_count": 0 if failed else 1,
154 "retained_partial_count": 0,
155 "output_events": 0 if failed else 1,
156 },
157 })
158
159 for name, size in (("boundary.zip", CHUNK), ("boundary.tar.gz", CHUNK - 1536)):
160 add(name, size, True, "output-boundary", [
161 ("below", CHUNK + 1, []),
162 ("equal", CHUNK, []),
163 ("above", CHUNK - 1, ["output"]),
164 ])
165 for suffix, delta in (("below", -1), ("equal", 0), ("above", 1)):
166 add("ratio-" + suffix + ".gz", 2_000_000 + delta, True, "former-ratio-boundary", [
167 ("default", OUTPUT_LIMIT, []),
168 ], packed_size=2000)
169 for extension in ("zip", "tar.gz"):
170 add("ratio-only." + extension, 16 * 1024 ** 2, True, "high-ratio-success", [
171 ("default", OUTPUT_LIMIT, []),
172 ])
173 if large:
174 for extension in ("zip", "tar.gz"):
175 add("large-input." + extension, GIB, False, "large-input-success", [
176 ("default", OUTPUT_LIMIT, []),
177 ])
178 add("output-only.zip", OUTPUT_LIMIT + 1, True, "hard-output-limit", [
179 ("default", OUTPUT_LIMIT, ["output"]),
180 ], level=1)
181 manifest = {
182 "policy": {"revision": 2, "input": INPUT_LIMIT, "output": OUTPUT_LIMIT, "ratio": None},
183 "large": large,
184 "worker_execution_verified": False,
185 "generator_chunk_bytes": CHUNK,
186 "artifacts": artifacts,
187 "cases": cases,
188 }
189 (directory / "expectations.json").write_text(
190 json.dumps(manifest, ensure_ascii=False, indent=4) + "\n", encoding="utf-8"
191 )
192 return manifest
193
194
195def main():
196 parser = argparse.ArgumentParser()
197 parser.add_argument("--output", required=True, type=Path, help="tests 아래의 새 디렉터리")
198 parser.add_argument("--large", action="store_true", help="1 GiB 성공과 16 GiB 초과 표본도 생성함")
199 args = parser.parse_args()
200 manifest = build(args.output, args.large)
201 print(f"{len(manifest['cases'])} cases: {args.output / 'expectations.json'}")
202
203
204if __name__ == "__main__":
205 main()