team-ljyzipelo

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