team-ljyzipelo

공개
207줄7.2 KB
1"""고정 크기 버퍼로 새 스트리밍 한도의 독립 경계 표본을 생성함."""
2
3import argparse
4import gzip
5import hashlib
6import io
7import json
8from pathlib import Path
9import struct
10import tarfile
11import zipfile
12import zlib
13
14
15ROOT = Path(__file__).resolve().parents[2]
16GIB = 1024 ** 3
17CHUNK = 64 * 1024
18INPUT_LIMIT = 2 ** 64 - 1
19OUTPUT_LIMIT = 16 * GIB
20RATIO_LIMIT = 1000
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 if artifact["decoded_bytes"] > artifact["ratio_input_bytes"] * RATIO_LIMIT:
103 failed.append("ratio")
104 return failed
105
106
107def build(directory, large=False):
108 directory = Path(directory).resolve()
109 directory.relative_to(ROOT / "tests")
110 directory.mkdir(mode=0o700, parents=True, exist_ok=False)
111 cases = []
112 artifacts = {}
113
114 def add(name, size, compressed, category, boundaries, level=6, packed_size=None):
115 path = directory / name
116 if name.endswith(".zip"):
117 write_zip(path, size, compressed, level)
118 expanded = size
119 with zipfile.ZipFile(path) as archive:
120 ratio_input = archive.getinfo(NAME).compress_size
121 archive_format = "Zip"
122 elif name.endswith(".tar.gz"):
123 write_targz(path, size, compressed)
124 expanded = tar_size(size)
125 ratio_input = path.stat().st_size
126 archive_format = "TarGzip"
127 else:
128 write_ratio_gzip(path, size, packed_size)
129 expanded = size
130 ratio_input = path.stat().st_size
131 archive_format = "Gzip"
132 artifact = {
133 "format": archive_format,
134 "archive_bytes": path.stat().st_size,
135 "payload_bytes": size,
136 "decoded_bytes": expanded,
137 "ratio_input_bytes": ratio_input,
138 "sha256": digest(path),
139 }
140 artifacts[name] = artifact
141 for suffix, output_limit, exceeded in boundaries:
142 limits = {"input": INPUT_LIMIT, "output": output_limit, "entries": 10000}
143 assert violations(artifact, limits) == exceeded, (name, suffix, artifact)
144 failed = bool(exceeded)
145 cases.append({
146 "id": name + "-" + suffix,
147 "file": name,
148 "category": category,
149 "limits": limits,
150 "violated_limits": exceeded,
151 "expected": {
152 "outcome": "Failed" if failed else "Completed",
153 "error": "Limit" if failed else "None",
154 "publication": "None" if failed else "Complete",
155 "created_count": 0 if failed else 1,
156 "retained_partial_count": 0,
157 "output_events": 0 if failed else 1,
158 },
159 })
160
161 for name, size in (("boundary.zip", CHUNK), ("boundary.tar.gz", CHUNK - 1536)):
162 add(name, size, True, "output-boundary", [
163 ("below", CHUNK + 1, []),
164 ("equal", CHUNK, []),
165 ("above", CHUNK - 1, ["output"]),
166 ])
167 for suffix, delta in (("below", -1), ("equal", 0), ("above", 1)):
168 add("ratio-" + suffix + ".gz", 2_000_000 + delta, True, "ratio-boundary", [
169 ("default", OUTPUT_LIMIT, ["ratio"] if delta > 0 else []),
170 ], packed_size=2000)
171 for extension in ("zip", "tar.gz"):
172 add("ratio-only." + extension, 16 * 1024 ** 2, True, "ratio-limit", [
173 ("default", OUTPUT_LIMIT, ["ratio"]),
174 ])
175 if large:
176 for extension in ("zip", "tar.gz"):
177 add("large-input." + extension, GIB, False, "large-input-success", [
178 ("default", OUTPUT_LIMIT, []),
179 ])
180 add("output-only.zip", OUTPUT_LIMIT + 1, True, "hard-output-limit", [
181 ("default", OUTPUT_LIMIT, ["output"]),
182 ], level=1)
183 manifest = {
184 "policy": {"revision": 2, "input": INPUT_LIMIT, "output": OUTPUT_LIMIT, "ratio": RATIO_LIMIT},
185 "large": large,
186 "worker_execution_verified": False,
187 "generator_chunk_bytes": CHUNK,
188 "artifacts": artifacts,
189 "cases": cases,
190 }
191 (directory / "expectations.json").write_text(
192 json.dumps(manifest, ensure_ascii=False, indent=4) + "\n", encoding="utf-8"
193 )
194 return manifest
195
196
197def main():
198 parser = argparse.ArgumentParser()
199 parser.add_argument("--output", required=True, type=Path, help="tests 아래의 새 디렉터리")
200 parser.add_argument("--large", action="store_true", help="1 GiB 성공과 16 GiB 초과 표본도 생성함")
201 args = parser.parse_args()
202 manifest = build(args.output, args.large)
203 print(f"{len(manifest['cases'])} cases: {args.output / 'expectations.json'}")
204
205
206if __name__ == "__main__":
207 main()