team-ljyzipelo

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