team-ljyzipelo

공개

LZMA2 방식의 7z 생성을 구현함

작성자
시로사키 하나
작성 시각
커밋
71aa755fd87b339102748d841e0b15d5d35e388e
부모
41ac7e4
이 시점의 파일 보기

변경된 파일 18개

+1,508-30
수정docs/sevenzip-create-design.md+9-9
@@ -1,6 +1,6 @@
11# 7z 생성 설계와 작업자 계약안
22
3삭제: 상태: frontend 계약 동의와 독립 설계 리뷰 완료. [앱 계약 승인](https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903269732)과 [설계 리뷰](https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903282961)는 03ca5c5 기준이다. 공용 타입, codec과 contract.json을 반영했으며 실제 작성기, 의존성 기능 변경과 화면 연동은 아직 없다. 현재 모든 CreateSevenZip 요청은 Accepted(encryption=false) 뒤 자원 질문이나 파일 접근 없이 UnsupportedFeature로 종료한다. 아래 작성기 설계와 수용 시험은 구현/호환 통과를 뜻하지 않는다. [PLANS 8.9](PLANS.md#89-7z-만들기)와 [8.13](PLANS.md#813-진행과-완료-판단)을 따른다.
3추가: 상태: frontend 계약 동의와 독립 설계 리뷰 뒤 공용 타입, 앱 화면과 backend 작성기를 구현했다. [앱 계약 승인](https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903269732)과 [설계 리뷰](https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903282961)는 03ca5c5 기준이며 구현 승인을 뜻하지 않는다. 실제 작성기는 LZMA2/non-solid/비암호화를 처리하며 solid 또는 암호 요청만 질문과 파일 접근 전에 UnsupportedFeature로 끝낸다. Linux의 독립 7-Zip과 Zipelo 왕복 및 실패 시험은 수행했으며 Windows/Wayland 실제 생성 통합 검증과 구현 독립 리뷰는 남았다. [PLANS 8.9](PLANS.md#89-7z-만들기)와 [8.13](PLANS.md#813-진행과-완료-판단)을 따른다.
44
55## 1. 이번 지원 범위
66
@@ -12,13 +12,13 @@
1212
1313## 2. 라이브러리 선택과 고지
1414
15삭제: 우선안은 이미 고정된 lzma-rust2 =0.25.0을 유지하고 현재 std,xz에 encoder 기능만 더하는 것이다. 컨테이너는 아래의 좁은 7z 작성기를 자체 MIT 코드로 구현한다. 압축 알고리즘 자체를 새로 구현하거나 외부 7z 명령을 제품에서 호출하지 않는다.
15추가: 선택안은 이미 고정된 lzma-rust2 =0.25.0을 유지하고 std,xz에 encoder 기능만 더하는 것이다. 이 구현에서 해당 기능을 활성화했으며 lockfile 패키지는 추가하지 않았다. 컨테이너는 아래의 좁은 7z 작성기를 자체 MIT 코드로 구현한다. 압축 알고리즘 자체를 새로 구현하거나 외부 7z 명령을 제품에서 호출하지 않는다.
1616
1717- [lzma-rust2 manifest](https://docs.rs/crate/lzma-rust2/latest/source/Cargo.toml.orig)는 열람 시 0.25.0, Apache-2.0을 명시한다. encoder 기능은 별도 전이 의존성이 없는 기능이며 Rust 인코더를 활성화한다. liblzma는 upstream 개발 의존성이므로 제품에 넣지 않는다. default-features=false와 기존 기능을 명시적으로 유지하며 optimization과 다중 스레드 작성기는 사용하지 않는다. [라이선스 원문](https://docs.rs/crate/lzma-rust2/latest/source/LICENSE)을 함께 확인했다.
1818- [sevenz-rust2 manifest](https://docs.rs/crate/sevenz-rust2/latest/source/Cargo.toml.orig)는 열람 시 0.24.1, Apache-2.0이며 compress만 활성화하는 컨테이너 작성기 후보다. util의 경로 재귀 수집 대신 검증된 핸들을 넘겨야 한다. 이 버전은 lzma-rust2 0.23 계열을 요구하므로 현재 0.25.0과 중복될 수 있고 crc32fast 등도 추가된다. 넓은 작성기 대신 기존 입력/예산/취소 정책에 맞춘 작은 컨테이너를 우선 검토한다. 이는 크기나 성능을 측정해 얻은 결론은 아니다.
1919- 기존 sevenz-rust는 후보에서 제외한다. [RUSTSEC-2026-0246](https://rustsec.org/advisories/RUSTSEC-2026-0246.html)은 유지보수 중단을, [RUSTSEC-2026-0245](https://rustsec.org/advisories/RUSTSEC-2026-0245.html)는 그 패키지의 해제 API 경로 이탈을 알린다. 이 권고는 이름이 다른 sevenz-rust2나 lzma-rust2의 취약점 유무를 판정하는 근거가 아니다.
20삭제: - 전체 최신 권고 DB 감사와 새 encoder 실행 시험은 하지 않았다. 구현 PR에서 고정 버전과 실제 기능 트리의 RustSec 권고 적용 여부를 다시 확인하고 확인 불가 항목을 기록한다. 후보 선택만으로 취약점 부재나 배포 적합성을 선언하지 않는다.
21삭제: - 도입 PR에는 선택 이유와 정확한 활성 기능을 적는다. packaging/licenses.py의 실제 작업자 Cargo.lock 고지에 lzma-rust2의 버전, Apache 원문과 원문 해시가 포함되는지 회귀로 확인한다. encoder 추가 전후의 전이 의존성을 비교하고 새 원문이 빠지면 배포 검증을 실패시킨다. 고지 생성기의 공용 변경이 필요하면 담당 범위를 합의한 뒤 수정한다. 이번 설계 PR에는 라이브러리를 도입하지 않는다.
20추가: - 2026-11-14 OSV의 패키지/버전 조회는 권고를 반환하지 않았고 RustSec 패키지명 검색 결과도 없었다. 전체 최신 의존성 권고 DB 감사는 하지 않았다. 새 encoder 실행 시험은 아래 검증 범위를 따른다. 구현 PR에서 고정 버전과 실제 기능 트리의 RustSec 권고 적용 여부를 다시 확인하고 확인 불가 항목을 기록한다. 후보 선택만으로 취약점 부재나 배포 적합성을 선언하지 않는다.
21추가: - 도입 PR에는 선택 이유와 정확한 활성 기능을 적는다. packaging/licenses.py의 실제 작업자 Cargo.lock 고지에 lzma-rust2의 버전, Apache 원문과 원문 해시가 포함되는지 회귀로 확인한다. encoder 추가 전후의 전이 의존성을 비교하고 새 원문이 빠지면 배포 검증을 실패시킨다. 고지 생성기의 공용 변경이 필요하면 담당 범위를 합의한 뒤 수정한다. 이 구현에서는 기존 패키지의 encoder 기능만 켰으며 실제 고지 원문과 해시 및 기능 제한 회귀를 실행한다.
2222
2323## 3. 작성기와 헤더
2424
@@ -32,7 +32,7 @@
3232
3333## 4. 작업자와 앱 계약안
3434
35삭제: 현재 기준은 과거 C# 문서가 아닌 [작업자 README](../experiments/rust-archive-worker/README.md), protocol.rs, wire.rs와 contract.json이다. 아래 확장 계약은 합의되었고 공용 타입과 바이트 인코딩은 반영했다. 실제 작성기와 앱 연동의 구현 상태는 위 상태 및 contract.json의 seven_zip_create.status로 구분한다.
35추가: 현재 기준은 과거 C# 문서가 아닌 [작업자 README](../experiments/rust-archive-worker/README.md), protocol.rs, wire.rs와 contract.json이다. 아래 확장 계약은 합의되었고 공용 타입과 바이트 인코딩은 반영했다. 작업자와 앱 연동의 구현 상태는 위 상태 및 contract.json의 seven_zip_create.status로 구분한다.
3636
3737### 요청과 바이트 순서
3838
@@ -57,7 +57,7 @@
5757- ZIP과 같은 원본 계획을 사용한다. 파일/폴더 모두 항목 수에 포함하며 파일 논리 바이트 합계에 min(limits.input,limits.output)을 적용한다. 기본은 16 GiB/10,000개, 유효한 자원 승인 뒤에는 요청한 ceiling 안에서 최대 64 GiB/200,000개다. 압축된 생성물 길이를 논리 원본 합계 대신 승인 기준으로 삼지 않는다.
5858- 기존 64개 경로 구성 요소, 승인 전 8 MiB/32,768 노드 및 승인 뒤 64 MiB/262,144 노드 메타데이터 예산을 유지한다. UTF-16 이름, 스트림 정보, CRC와 오프셋 배열 및 헤더 버퍼도 할당 전에 예산에 반영한다. 입력 전체나 파일 전체를 메모리 배열에 담지 않고 현재 파일만 64 KiB 이하로 복사한다.
5959- Plan의 경로 안전, 이름/접두 경로 및 대소문자 충돌, 원본 객체/종류/크기/수정 시각 대조를 재사용한다. 심볼릭 링크, reparse point, 특수 파일과 안전하지 않은 이름은 전체 작업을 거부한다. 탐색 뒤 교체와 감지된 변경은 SourceChanged다. 전체 폴더 트리의 원자적 스냅샷이나 같은 길이/시각으로 위장한 모든 변경 감지를 약속하지 않는다.
60삭제: - 원본 사본, 압축 결과와 게시용 복사본의 동시 공간을 볼륨별로 계산한다. LZMA2 패킹의 보수적 크기 상한은 실제 작성기 분기에서 도출해 checked 연산으로 검사하고 각 실제 쓰기 전에도 여유 공간을 확인한다. 사전 확인은 공간 예약이 아니며 ENOSPC는 DiskFull, 그 밖의 저장 오류는 Io로 유지한다. 생성물 및 디스크 공간을 원본 바이트 예산과 혼동하지 않는다.
60추가: - 원본 사본, 압축 결과와 게시용 복사본의 동시 공간을 볼륨별로 계산한다. LZMA2 청크는 최소 1바이트의 원본당 최대 3바이트 순증과 종료 1바이트를 허용하는 4*길이+1의 보수적 상한을 checked 연산으로 검사하고 각 실제 쓰기 전에도 여유 공간을 확인한다. 사전 확인은 공간 예약이 아니며 ENOSPC는 DiskFull, 그 밖의 저장 오류는 Io로 유지한다. 생성물 및 디스크 공간을 원본 바이트 예산과 혼동하지 않는다.
6161- 승인 전 전체 300초, 승인 뒤 실제 진행이 없는 60초와 질문 응답 대기 300초 정책을 유지한다. 성공한 읽기/압축 쓰기/헤더 처리/계획 검증과 정리만 실제 활동으로 기록한다. 단순 check나 UI 알림으로 시간을 연장하지 않는다.
6262- 입력 청크, 인코더 출력, 파일 경계, finish 전후, 헤더 seek/패치와 게시 직전에 취소 및 부모 생존을 확인한다. 압축 출력 Writer에도 감시기를 연결해 라이브러리 내부 쓰기 오류의 원인을 보존한다. 단일 스레드 인코더 한 호출 안의 CPU 처리와 OS 블로킹 I/O를 즉시 강제 중단한다고 보장하지 않는다. 부모/취소 확인 간격과 작은 파일 다수의 응답성도 시험한다.
6363- 1 MiB 사전의 대표 1 GiB 표본에서 기존 64 MiB 피크 RSS 목표를 측정한다. 큰 작업 허용은 인코더 사전/스레드를 늘리는 승인이 아니며 프로세스 전체 메모리의 강제 상한을 뜻하지 않는다.
@@ -72,7 +72,7 @@
7272
7373## 7. 구현 후 수용 시험
7474
75삭제: 아래는 아직 수행하지 않은 검증 계획이다. 시험 코드는 루트 tests/에만 두며 일회성 자료, 도구, 캐시와 로그는 tests/work/7zc 한 곳에 모은다. TMPDIR과 CARGO_TARGET_DIR을 그 하위에 명시하고 사본 안에 작업 폴더나 빌드 캐시를 다시 만들지 않는다. PR 병합/종료 뒤 담당자가 정리한다.
75추가: 아래는 수용 시험 기준이다. Linux에서 새 정수/비트맵과 인코딩 경계, 독립 7-Zip 26.00/Zipelo의 한글/보조 평면 이름 및 빈 구조 왕복, 취소/쓰기/finish/헤더 seek와 패치/게시 실패를 검증했다. 1 GiB 대표 생성은 11,168 KiB RSS와 약 20.8초를 기록했다. 이는 단일 표본 측정이며 모든 입력의 성능이나 OS 강제 상한이 아니다. 전체 local, 라이선스 시험과 플랫폼별 수행 결과는 PR 본문과 tests/work/7zc의 로그를 따른다. Windows/Wayland 실제 생성 통합과 구현 독립 리뷰는 아직 남았다. 시험 코드는 루트 tests/에만 두며 일회성 자료, 도구, 캐시와 로그는 tests/work/7zc 한 곳에 모은다. TMPDIR과 CARGO_TARGET_DIR을 그 하위에 명시하고 사본 안에 작업 폴더나 빌드 캐시를 다시 만들지 않는다. PR 병합/종료 뒤 담당자가 정리한다.
7676
7777- 일반 파일, 압축되는/난수 내용, 한글 및 여러 단계 경로, 혼합 파일/폴더, 빈 파일, 빈 폴더, 빈 폴더만 있는 묶음과 여러 최상위 원본을 만든다. Zipelo 목록/해제와 독립 7-Zip의 테스트/목록/해제를 각각 실행해 상대 경로, 항목 종류, 파일 크기와 SHA256을 원본 manifest와 대조한다. 압축 아카이브 바이트 자체의 일치는 요구하지 않는다.
7878- 독립 설계 리뷰의 후속 기준으로 MainStreamsInfo/kEnd 계층, 32바이트 기준 NextHeaderOffset, 가변 UINT64와 고정 REAL_UINT64 구분을 확인한다. EmptyFile 비트 수는 전체 파일 수가 아닌 empty stream 수이며 혼합 빈 항목 7/8/9개와 정수 경계 127/128, 16383/16384를 포함한다.
@@ -84,7 +84,7 @@
8484
8585## 8. 합의와 담당 인계
8686
87삭제: - 하나는 이 계약과 backend 작성기, 공용 타입/codec 및 작업자 회귀를 담당한다. 히나타의 계약 동의와 카논의 설계 리뷰가 확인되어 공용 타입 인계 단계에 착수했다. 실제 작성기는 후속 구현이다.
87추가: - 하나는 이 계약과 backend 작성기, 공용 타입/codec 및 작업자 회귀를 담당한다. 히나타의 계약 동의와 카논의 설계 리뷰가 확인되어 공용 타입 인계 단계에 착수했다. 실제 작성기를 반영했으며 새 파일로 Windows/Wayland 통합 검증을 인계한다.
8888- 계약 동의 뒤 공용 타입 반영 커밋을 히나타에게 전달한다. 히나타는 기존 생성 화면의 ZIP/7z 형식 선택, .7z 기본 저장 형식, 암호/방식 선택 제한, 새 ActionKind 변환과 수신 검증을 담당한다. 화면이 바뀌는 구현 PR에 --ui-scenario 목록/시험과 docs/ui-scenario-guide.md를 함께 갱신한다. 별도 디자인 변경이나 애니메이션을 추가하지 않는다.
8989- 카논의 설계와 실패 경계 리뷰는 완료되었으며 구현 후 독립 7-Zip 호환 검증 및 재리뷰는 별도 요청한다. 도구 버전/옵션, 원본과 해제 manifest 및 플랫폼별 실행 범위를 남긴다. 도구를 제품에 번들하지 않는다.
90삭제: - 설계 문서의 정적 검토와 링크/공백 검사는 제품 빌드나 호환 검증이 아니다. 이번 PR은 UI 변경 없음이며 구현 시작 조건과 아직 수행하지 않은 시험을 명시한 초안으로 유지한다.
90추가: - 설계 문서의 정적 검토와 링크/공백 검사는 제품 빌드나 호환 검증이 아니다. 이번 backend 추가분은 UI 변경 없음이다. 같은 PR의 형식 선택과 시나리오는 이미 반영되어 있으며 실제 파일의 Windows/Wayland 통합 및 구현 독립 리뷰가 끝날 때까지 초안을 유지한다.
수정experiments/rust-archive-worker/Cargo.toml+1-1
@@ -11,7 +11,7 @@ png = "=0.18.1"
1111zune-jpeg = { package = "zipelo-jpeg", path = "vendor/zune-jpeg", default-features = false, features = ["std"] }
1212zune-core = { version = "=0.5.3", default-features = false, features = ["std"] }
1313bzip2 = "=0.6.1"
14삭제: lzma-rust2 = { version = "=0.25.0", default-features = false, features = ["std", "xz"] }
14추가: lzma-rust2 = { version = "=0.25.0", default-features = false, features = ["std", "xz", "encoder"] }
1515aes = { version = "=0.8.4", features = ["zeroize"] }
1616hmac = "=0.12.1"
1717pbkdf2 = { version = "=0.12.2", default-features = false, features = ["hmac"] }
수정experiments/rust-archive-worker/README.md+12-8
@@ -49,7 +49,7 @@ XZ의 헤더, 인덱스, 푸터 CRC와 역방향 크기 및 전체 선언 해제
4949의존성 선택 근거는 다음과 같습니다.
5050
5151- [bzip2 0.6.1](https://docs.rs/crate/bzip2/0.6.1/source/Cargo.toml)은 MIT OR Apache-2.0이며 기본 백엔드가 Rust 구현인 libbz2-rs-sys입니다. 고정 lockfile은 libbz2-rs-sys 0.2.6(bzip2-1.0.6 자유 라이선스)을 선택하고 Rust 할당자를 사용합니다. C 구현인 bzip2-sys 기능과 stdio/C 할당자는 활성화하지 않습니다.
52삭제: - [lzma-rust2 0.25.0](https://docs.rs/lzma-rust2/latest/lzma_rust2/struct.XzReader.html)은 Apache-2.0의 Rust 구현입니다. std와 xz만 활성화해 인코더와 다중 스레드 구현을 제외하고 사전 할당 전 메모리 제한을 적용합니다. CRC와 인덱스 레코드 개수를 검증하며 연결 스트림을 끝까지 읽습니다. 레코드별 크기는 작업자가 별도로 대조합니다.
52추가: - [lzma-rust2 0.25.0](https://docs.rs/lzma-rust2/latest/lzma_rust2/struct.XzReader.html)은 Apache-2.0의 Rust 구현입니다. TAR.XZ에는 std와 xz를 사용하며 7z 생성을 위해 encoder도 활성화합니다. optimization 기본 기능은 끄고 사전 할당 전 메모리 제한을 적용합니다. CRC와 인덱스 레코드 개수를 검증하며 연결 스트림을 끝까지 읽습니다. 레코드별 크기는 작업자가 별도로 대조합니다.
5353- 두 라이브러리와 새 전이 의존성의 원문은 Cargo 체크섬을 대조하는 기존 packaging/licenses.py가 고지에 자동 포함합니다. tests/release-packages/test_compressed_tar_licenses.py는 실제 고지에 세 압축 라이브러리의 원문과 해시가 포함되고 C 압축 백엔드가 없는지 확인합니다.
5454- 2026-11-13 [RUSTSEC-2023-0004](https://rustsec.org/advisories/RUSTSEC-2023-0004.html)의 bzip2 DoS 권고와 수정 범위(>=0.4.4)를 확인했습니다. 고정 lockfile의 bzip2 0.6.1은 수정 범위에 해당하므로 이 권고의 영향을 받지 않습니다. 새 전이 sha2 0.11.1은 RUSTSEC-2021-0100의 수정 범위(>=0.9.8)에 해당합니다. 전체 최신 DB 자동 감사와 취약점 부재를 보장하는 확인은 수행하지 않았습니다.
5555
@@ -69,15 +69,19 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
6969
70707z의 Copy/LZMA/LZMA2 입력과 solid 출력은 고정 버퍼와 임시 파일로 처리합니다. 모든 폴더와 하위 스트림의 CRC와 크기 검증이 끝난 뒤 기존 게시 경로를 사용합니다. ZIP 생성의 압축 및 AES 처리도 64 KiB 버퍼를 사용하며 여유 공간 사전 검사와 실제 쓰기의 DiskFull 구분을 적용합니다. 공간 예약을 보장하지 않으므로 다른 프로세스와의 경쟁으로 쓰기가 실패할 수 있습니다.
7171
72삭제: ## 7z 생성 계약과 구현 상태
72추가: ## 7z 생성
7373
74삭제: [합의된 설계](../../docs/sevenzip-create-design.md)에 따라 공용 타입과 codec을 추가했습니다. 실제 7z 작성기와 앱 형식 선택은 아직 미구현입니다. 현재 CreateSevenZip 요청은 Accepted(encryption=false) 뒤 UnsupportedFeature로 종료하며 원본, 목적지와 임시 파일을 열거나 자원/암호/충돌 질문을 보내지 않습니다. 정상 옵션도 이 경로로 명시적으로 실패하며 ZIP으로 우회하지 않습니다.
74추가: [합의된 설계](../../docs/sevenzip-create-design.md)의 단일 .7z 작성을 구현했습니다. 압축 방식은 LZMA2, 1 MiB 사전과 non-solid이며 본문/헤더 암호화, 분할 생성과 SFX는 지원하지 않습니다. 원본 파일과 폴더, 한글 및 UTF-16 보조 평면 이름, 빈 파일과 빈 폴더를 보존합니다. RAR 제외 정책은 유지합니다.
7575
76삭제: - Action과 ActionKind의 CreateSevenZip tag는 4입니다. 필드 순서는 sources:Vec<Source>, output_file:NativePath, method:SevenZipMethod, solid:bool, encryption:Encryption입니다. Source는 기존 path와 archive_name 순서이며 SevenZipMethod는 Lzma2=0만 정의합니다. ZIP Method의 Store=0, Deflate=1과 기존 모든 tag/프레임은 유지합니다.
77삭제: - Start 또는 StartGuarded(interactive=false)에 허용합니다. StartInteractive와 guarded interactive=true는 양방향 codec에서 거부합니다. 확대 ceiling도 sources/경로 Vec의 32,768개, String의 32,768 UTF-8 바이트와 1 MiB 프레임 전송 상한을 늘리지 않습니다. ResourceRequired.action도 새 tag 4를 전송할 수 있지만 현재 미구현 작성기는 질문 전에 실패합니다.
78삭제: - 구현 목표는 LZMA2, non-solid, 본문/헤더 암호화 없음입니다. solid=true와 Aes256은 구조상 유효하지만 Supported로 간주하지 않으며 질문/출력 전 UnsupportedFeature입니다. 알 수 없는 enum/bool과 잔여 본문은 codec 오류입니다. 구버전이나 다른 형식으로 자동 재시도하지 않습니다.
79삭제: - 향후 작성기는 ZIP과 같은 원본 계획, 취소, 자원 승인, 비공개 스테이징과 배타적 게시 경로를 재사용합니다. 기존 목적지를 덮어쓰지 않으며 성공에는 최종 아카이브 하나의 Output Created와 Complete/created_count=1이 필요합니다. 앱의 확정 조건은 기존 Terminal, 양쪽 EOF와 자식 회수 그대로입니다. 실제 게시 후 오류와 정리 실패를 성공/무출력으로 바꾸지 않습니다.
80삭제: - tests/rust-archive-worker/seven_zip_create.rs는 요청 바이트, Unix/Windows 경로, tag/옵션/전송 경계와 현재 미지원 동작의 무질문/무게시 및 기존 파일 보존을 검증합니다. 실제 인코딩, 독립 도구 호환과 OS 화면 시험의 근거는 아닙니다. 의존성/encoder 기능은 이 인계에서 바꾸지 않습니다.
76추가: - Action과 ActionKind의 CreateSevenZip tag는 4입니다. 필드 순서는 sources:Vec<Source>, output_file:NativePath, method:SevenZipMethod, solid:bool, encryption:Encryption이며 SevenZipMethod는 Lzma2=0입니다. 기존 ZIP 태그/프레임은 유지합니다. Start 또는 StartGuarded(interactive=false)만 허용하며 전송 상한은 자원 승인으로 확대하지 않습니다.
77추가: - Accepted.encryption=false입니다. solid=true 또는 Aes256은 Accepted 뒤 자원/암호/충돌 질문이나 파일 접근 전에 UnsupportedFeature로 끝납니다. 빈 원본 목록은 InvalidRequest입니다. ZIP이나 구버전으로 자동 우회하지 않습니다.
78추가: - 기존 소스 계획과 검증한 핸들로 파일별 스냅샷을 캡처하고 독립 LZMA2 스트림을 만듭니다. 비압축 NextHeader와 CRC를 기록하고 기존 구조 검사기로 이름/종류/크기를 대조합니다. 계획의 메타데이터 예산에 UTF-16 헤더, 검증용 사본과 스트림 배열을 함께 반영합니다. 실제 payload 전체 해독은 수용 시험에서 별도로 수행합니다.
79추가: - 기존 16 GiB/10,000개 및 승인 뒤 최대 64 GiB/200,000개 정책을 따르며 메타데이터 상한은 독립적입니다. 순차 복사 버퍼는 64 KiB이고 인코더 추정 메모리가 32 MiB를 넘으면 거부합니다. 파일별 패킹 상한은 upstream 청크 분기를 보수적으로 계산한 4*원본 길이+1이며 캡처와 새 패킹, 헤더의 동시 임시 공간을 사전 검사합니다. 압축되는 입력도 이 보수적 검사로 공간 부족이 될 수 있습니다. 실제 쓰기와 목적지 복사도 별도로 공간을 검사하며 공간을 예약하지는 않습니다.
80추가: - finish와 헤더 seek/패치 오류를 전파하고 Drop으로 성공을 결정하지 않습니다. 게시용 복사/sync/close 뒤 실제 게시 직전에 원본 계획을 다시 확인하며 배타적 게시만 사용합니다. 기존 목적지나 사전 검사 뒤 나타난 파일은 보존합니다. 전체 폴더의 원자적 스냅샷이나 게시와 원본 재검증의 원자성을 보장하지 않습니다.
81추가: - Scan/Read/Write/Verify/Commit 진행과 기존 취소, 부모 생존/시간 제한을 사용합니다. 인코더 출력에서도 취소를 확인하지만 단일 CPU 호출이나 블로킹 OS I/O를 즉시 중단하지는 않습니다. 생성물 하나의 Output Created와 Complete/created_count=1만 성공입니다. 게시 후 오류와 실제 내구성/정리 상태를 그대로 보고하며 앱은 Terminal, 양쪽 EOF와 자식 회수까지 확인합니다.
82추가: - lzma-rust2 =0.25.0의 std,xz,encoder만 사용합니다. encoder 기능은 추가 전이 의존성이 없고 Apache-2.0 원문은 기존 packaging/licenses.py 고지에 포함합니다. tests/release-packages/test_compressed_tar_licenses.py에서 실제 원문과 해시, 고정 버전 및 기능을 확인합니다. 기본/optimization 기능과 liblzma 개발 의존성은 제품에 포함하지 않습니다.
83추가: - 2026-11-14 OSV에 lzma-rust2 0.25.0을 조회했을 때 알려진 권고가 반환되지 않았습니다. RustSec 패키지명 검색도 결과가 없었으며 전체 의존성 감사나 취약점 부재를 뜻하지 않습니다. 정확한 질의와 결과는 PR의 검증 기록에 남깁니다.
84추가: - tests/rust-archive-worker/seven_zip_create_fields.rs와 seven_zip_create_runtime.rs는 정수/비트맵/버퍼 경계, 원본/목적지 변경, 자원 승인, 취소와 저장 실패를 검사합니다. ZIPELO_TEST_7ZIP에 독립 7-Zip 실행 파일을 지정하면 실제 test/list/extract와 SHA256/구조 대조도 수행합니다. 도구를 지정하지 않은 실행은 독립 7-Zip 검증 근거가 아닙니다. 1 GiB 메모리 회귀는 Linux에서 실행합니다. Windows/Wayland 실제 생성 통합 검증과 독립 리뷰는 별도입니다.
8185
8286## ZIP 생성 입력
8387
수정experiments/rust-archive-worker/contract.json+7-6
@@ -26,7 +26,7 @@
2626 "archive_names": "Separate validated UTF-8 relative names; entry IDs are opaque ordinal u32, not paths."
2727 },
2828 "commands": {
29삭제: "Start": "Exactly once: List{archive}, Extract{archive,destination,selection:All|EntryIds{ids:[u32]},list_id:optional<ListId>,gzip_output_name:optional<UTF8>}, CreateZip{sources:[source_path,archive_name],output_file,method:Store|Deflate,encryption:None|Aes256}. App supplies job_id; caller can lower worker hard limits. Extract destination is always an absolute output directory. EntryIds requires list_id; All may supply list_id to bind extraction to a displayed list. CreateSevenZip{sources:[Source{path:NativePath,archive_name:UTF8}],output_file:NativePath,method:SevenZipMethod,solid:bool,encryption:Encryption} appends action tag 4. Shared types and codec are implemented; the pending writer returns UnsupportedFeature after Accepted before file access or questions.",
29추가: "Start": "Exactly once: List{archive}, Extract{archive,destination,selection:All|EntryIds{ids:[u32]},list_id:optional<ListId>,gzip_output_name:optional<UTF8>}, CreateZip{sources:[source_path,archive_name],output_file,method:Store|Deflate,encryption:None|Aes256}. App supplies job_id; caller can lower worker hard limits. Extract destination is always an absolute output directory. EntryIds requires list_id; All may supply list_id to bind extraction to a displayed list. CreateSevenZip{sources:[Source{path:NativePath,archive_name:UTF8}],output_file:NativePath,method:SevenZipMethod,solid:bool,encryption:Encryption} appends action tag 4. Shared types, codec and the LZMA2 non-solid writer are implemented. Unsupported solid/encryption options fail after Accepted before file access or questions.",
3030 "Password": "Matching outstanding challenge_id:u64 and max1024 UTF-8 bytes; never log, Debug, echo or persist secrets.",
3131 "Cancel": "Matching header job_id and empty body; command header sequence identifies the request. See CancelAck. Request acceptance is separate from final outcome. EOF alone is not successful cancellation.",
3232 "StartInteractive": "Kind 4, body identical to Start with action restricted to Extract. Exactly one initial Start or StartInteractive. Invalid non-Extract action is rejected by the shared encoder and decoder. Opt in to interactive regular-file conflicts; never retry through legacy Start or an older worker automatically. Worker runtime supports the agreed choices; client activation and native UI integration are verified separately.",
@@ -229,7 +229,7 @@
229229 "guarded_resources": {
230230 "status": "worker-and-client-implemented; native Windows/Wayland verification pending",
231231 "agreement": "Frontend flow agreement 6fe5a494-7d5a-4bda-a7d3-831fb43e9238 and manager policy b3a743d2-10de-495c-8fdb-ecf2a5f3b453. Frame version 1, revision 3 messages and enum tags remain unchanged; this is an explicit opt-in extension.",
232삭제: "admission": "After Accepted, request the output and/or entries scopes that ceiling increases above Start limits before capturing input or planning sources. Usage estimates and actuals are unknown at this point; report current staging-volume free space. The caller must show the requested ceilings and unknown values, not invent estimates. An earlier confirmation is needed because input capture itself can exceed 300 seconds. Each granted scope is confined to this job. Exception during CreateSevenZip writer development: safe UnsupportedFeature refusal precedes all resource questions and temporary-file access; this is not an implementation of creation.",
232추가: "admission": "After Accepted, request the output and/or entries scopes that ceiling increases above Start limits before capturing input or planning sources. Usage estimates and actuals are unknown at this point; report current staging-volume free space. The caller must show the requested ceilings and unknown values, not invent estimates. An earlier confirmation is needed because input capture itself can exceed 300 seconds. Each granted scope is confined to this job.",
233233 "ratio": "Request ratio scope separately when expanded bytes are at least 256 MiB and strictly exceed compressed bytes times 1000. Check ZIP members and aggregate payload totals, 7z solid folders and totals, and complete compressed TAR/GZip streams. Use u128 arithmetic; unknown compressed length does not become zero. No ratio warning for legacy requests.",
234234 "accounting": "Monitor declared catalog sums and counts, real decoded bytes, per-stream ratios and source-plan sums. Decoders must match verified declared lengths before publication. For compressed TAR/GZip the expanded stream includes headers/padding. ZIP creation ceiling counts source logical bytes; ZIP/container/encryption overhead is separately space-checked.",
235235 "disk": "Continue staging/destination volume preflight and per-chunk space checks after approval. available_bytes is advisory free space on the current observation storage volume, not a reservation or all-volume total. Unknown storage is None. Preserve DiskFull, partial publication, durability and cleanup semantics.",
@@ -251,7 +251,7 @@
251251 "Lzma2": 0
252252 },
253253 "seven_zip_create": {
254삭제: "status": "shared-types-codec-and-safe-refusal-implemented; writer-and-app-integration-pending",
254추가: "status": "worker-implemented; frontend-integrated; real-file-native-integration-and-independent-review-pending",
255255 "agreement": {
256256 "frontend_message_id": "770f1004-0a2b-4fc6-aafd-7f705c8f6c9e",
257257 "frontend_review": "https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903269732",
@@ -260,11 +260,12 @@
260260 "request": "Append Action::CreateSevenZip and ActionKind::CreateSevenZip=4. Field order: sources:Vec<Source>,output_file:NativePath,method:SevenZipMethod(u8 Lzma2=0),solid:bool,encryption:Encryption(u8 None=0,Aes256=1). Source remains path:NativePath,archive_name:UTF8. Preserve ZIP Method Store=0,Deflate=1, all previous tags, frame version and fields.",
261261 "admission": "Start and StartGuarded(interactive=false) are valid. Shared encoder and decoder reject StartInteractive and guarded interactive=true. Sources, native path vectors and strings retain the 32768 item/UTF8-byte bounds and the 1 MiB frame bound even with an expanded ceiling. No automatic fallback to ZIP, Start or an older worker.",
262262 "options": "Target support is single-file .7z with LZMA2, non-solid and no body/header encryption. Structurally valid solid=true or Aes256 requests must fail UnsupportedFeature after Accepted, before source enumeration, resource/password/conflict questions or outputs. Unknown enum/bool tags and trailing fields are protocol errors.",
263삭제: "implementation_boundary": "Until the writer is implemented, every CreateSevenZip request, including Lzma2/solid=false/None, takes this same safe UnsupportedFeature path before resource admission and temporary-file creation. Accepted is not a creation capability or success claim. Do not release the format selector as a working feature yet.",
263추가: "implementation_boundary": "LZMA2 non-solid creation is implemented. Shared source planning, 64 KiB snapshots and writes, private staging, checked header metadata and exclusive publication are used. Unsupported solid/encryption options fail before admission and file access. Native UI real-file integration and independent review remain separate.",
264264 "events": "Accepted.action and future ResourceRequired.action use tag 4; Accepted.encryption=false. Future writer reuses Progress Scan/Read/Write/Verify/Commit and guarded resource approval. Unknown totals remain None. No PasswordRequired or ConflictRequired. Exactly one normal Output Created for the published archive, entry_id=None and relative_name=actual destination leaf; not one Output per archive member.",
265265 "publication": "Future writer uses ZIP source planning, consistency checks, private file-backed staging and exclusive publication (replace=None). Existing or newly appeared destination returns Conflict without overwrite. Completed requires publication Complete and created_count=1. Prepublication failure/cancel has publication None and zero created/retained counts unless owned temporary cleanup actually failed. Preserve actual postpublication errors, durability, cleanup and uncertain state.",
266266 "lifecycle": "Reuse Cancel/CancelAck/Terminal and matching job/challenge/sequence validation. CancelAck is not completion; app requires Terminal, both stream EOFs and owned child wait. No synthetic rollback after publication.",
267삭제: "dependencies": "No dependency or feature change in the common-types handoff. lzma-rust2 encoder selection, notices, current advisory applicability and actual compatibility require writer implementation and validation.",
268삭제: "design": "docs/sevenzip-create-design.md"
267추가: "dependencies": "Existing lzma-rust2 =0.25.0 enables std,xz,encoder with default features disabled. No new lockfile package; encoder=[] adds no transitive dependency. Apache-2.0 originals and hashes are checked through packaging/licenses.py. OSV query on 2026-11-14 returned no advisory for this package/version; this is not a full dependency audit or a vulnerability-free claim.",
268추가: "design": "docs/sevenzip-create-design.md",
269추가: "validation": "Round-trip SHA256 and structure in Zipelo and independent 7-Zip 26.00 with ZIPELO_TEST_7ZIP set; 1 GiB creation RSS regression; cancellation, metadata/byte limits, encoder finish/header write/seek/patch failures, destination write/sync and postpublication sync failures. Results and platform limits are recorded in PR127."
269270 }
270271}
수정experiments/rust-archive-worker/src/archive.rs+3-0
@@ -53,6 +53,9 @@ impl MetadataBudget {
5353 self.nodes = nodes;
5454 Ok(())
5555 }
56추가: pub(crate) fn charge_bytes(&mut self, bytes: usize, limits: MetadataLimits) -> Result<()> {
57추가: self.charge_cost(bytes, 0, limits)
58추가: }
5659 pub(crate) fn charge(&mut self, name: &str) -> Result<()> {
5760 self.charge_with(name, MetadataLimits::default())
5861 }
수정experiments/rust-archive-worker/src/create_sources.rs+7-0
@@ -335,6 +335,13 @@ impl Plan {
335335 }
336336 Ok(())
337337 }
338추가: pub fn reserve_metadata(
339추가: &mut self,
340추가: bytes: usize,
341추가: check: &impl crate::resources::Monitor,
342추가: ) -> Result<()> {
343추가: self.budget.charge_bytes(bytes, check.metadata_limits())
344추가: }
338345 pub fn verify(&self, check: &mut impl crate::resources::Monitor) -> Result<()> {
339346 for item in &self.items {
340347 check.check()?;
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -11,6 +11,7 @@ pub mod protocol;
1111pub mod resources;
1212pub mod runtime;
1313mod seven_zip;
14추가: mod seven_zip_create;
1415mod space;
1516mod split_seven_zip;
1617mod spool;
수정experiments/rust-archive-worker/src/resources.rs+9-0
@@ -8,6 +8,15 @@ pub trait Monitor {
88 crate::archive::MetadataLimits::default()
99 }
1010 fn check(&mut self) -> Result<()>;
11추가: fn progress(
12추가: &mut self,
13추가: _stage: Stage,
14추가: _bytes: u64,
15추가: _total: Option<u64>,
16추가: _entries: u32,
17추가: ) -> Result<()> {
18추가: self.check()
19추가: }
1120 fn activity(&mut self) -> Result<()> {
1221 self.check()
1322 }
수정experiments/rust-archive-worker/src/runtime.rs+61-4
@@ -41,6 +41,7 @@ struct Job<W> {
4141 remaining_choice: Option<ConflictChoice>,
4242 source_group: Option<crate::split_seven_zip::Group>,
4343 source_verified_for_publication: bool,
44추가: creation_plan: Option<crate::create::Plan>,
4445 started: Instant,
4546 terminal: Terminal,
4647 parent: crate::parent::Parent,
@@ -285,6 +286,11 @@ impl<W: Write> Job<W> {
285286 }
286287 fn verify_before_publication(&mut self) -> Result<()> {
287288 if !self.source_verified_for_publication {
289추가: if let Some(plan) = self.creation_plan.take() {
290추가: let result = plan.verify(self);
291추가: self.creation_plan = Some(plan);
292추가: result?;
293추가: }
288294 self.verify_split()?;
289295 self.source_verified_for_publication = true;
290296 }
@@ -296,6 +302,9 @@ impl<W: Write> Job<W> {
296302 filesystem::PublishStep::Activity => completed(Ok(()), self),
297303 filesystem::PublishStep::Commit => {
298304 self.verify_before_publication()?;
305추가: if let Some(plan) = &self.creation_plan {
306추가: self.progress(Stage::Commit, 0, None, plan.items.len() as u32)?;
307추가: }
299308 if last { self.cutoff() } else { self.check() }
300309 }
301310 }
@@ -548,9 +557,19 @@ impl<W: Write> Job<W> {
548557 encryption: !matches!(start.action, Action::CreateSevenZip { .. }),
549558 })?;
550559 self.check()?;
551삭제: // 작성기 구현 전에는 자원 승인과 파일 접근을 시작하지 않음.
552삭제: if matches!(start.action, Action::CreateSevenZip { .. }) {
553삭제: return Err(ErrorCode::UnsupportedFeature);
560추가: if let Action::CreateSevenZip {
561추가: sources,
562추가: solid,
563추가: encryption,
564추가: ..
565추가: } = &start.action
566추가: {
567추가: if *solid || *encryption != Encryption::None {
568추가: return Err(ErrorCode::UnsupportedFeature);
569추가: }
570추가: if sources.is_empty() {
571추가: return Err(ErrorCode::InvalidRequest);
572추가: }
554573 }
555574 if let Some(budget) = &self.budget {
556575 let scope = ResourceScope {
@@ -925,13 +944,50 @@ impl<W: Write> Job<W> {
925944 self.output_reader(&root, &name, &mut data, length, None, true, None)?;
926945 self.terminal.publication = Publication::Complete;
927946 }
928삭제: Action::CreateSevenZip { .. } => return Err(ErrorCode::UnsupportedFeature),
947추가: Action::CreateSevenZip {
948추가: sources,
949추가: output_file,
950추가: ..
951추가: } => {
952추가: let output = output_file.to_path()?;
953추가: let leaf = output
954추가: .file_name()
955추가: .and_then(|n| n.to_str())
956추가: .ok_or(ErrorCode::InvalidRequest)?;
957추가: let name = archive::valid_name(leaf, false)?;
958추가: let root = completed(
959추가: Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?),
960추가: self,
961추가: )?;
962추가: filesystem::preflight_mode_with(
963추가: &root,
964추가: &[(name.clone(), EntryKind::File)],
965추가: false,
966추가: self,
967추가: )?;
968추가: self.progress(Stage::Scan, 0, None, 0)?;
969추가: let mut plan = crate::create::plan(&sources, limits, self)?;
970추가: let (mut data, length) = crate::seven_zip_create::archive(&mut plan, limits, self)?;
971추가: filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?;
972추가: self.creation_plan = Some(plan);
973추가: self.output_reader(&root, &name, &mut data, length, None, true, None)?;
974추가: self.terminal.publication = Publication::Complete;
975추가: }
929976 }
930977 self.cutoff()?;
931978 Ok(())
932979 }
933980}
934981impl<W: Write> Monitor for Job<W> {
982추가: fn progress(
983추가: &mut self,
984추가: stage: Stage,
985추가: bytes: u64,
986추가: total: Option<u64>,
987추가: entries: u32,
988추가: ) -> Result<()> {
989추가: Job::progress(self, stage, bytes, total, entries)
990추가: }
935991 fn metadata_limits(&self) -> archive::MetadataLimits {
936992 self.budget
937993 .as_ref()
@@ -1113,6 +1169,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
11131169 remaining_choice: None,
11141170 source_group: None,
11151171 source_verified_for_publication: false,
1172추가: creation_plan: None,
11161173 parent,
11171174 started: Instant::now(),
11181175 terminal: Terminal {
추가experiments/rust-archive-worker/src/seven_zip_create.rs+453-0
@@ -0,0 +1,453 @@
1추가: use crate::{create::Plan, protocol::*, resources::Monitor, spool};
2추가: use lzma_rust2::{Lzma2Options, Lzma2Writer};
3추가: use std::{
4추가: fs::File,
5추가: io::{Read, Seek, SeekFrom, Write},
6추가: time::{Duration, Instant},
7추가: };
8추가: use zlib_rs::crc32::crc32;
9추가:
10추가: type Result<T> = std::result::Result<T, ErrorCode>;
11추가: const DICTIONARY: u32 = 1024 * 1024;
12추가: const DICTIONARY_PROPERTY: u8 = 16;
13추가:
14추가: fn io<T>(value: std::io::Result<T>) -> Result<T> {
15추가: value.map_err(crate::space::io_error)
16추가: }
17추가: fn options() -> Result<Lzma2Options> {
18추가: let mut options = Lzma2Options::with_preset(1);
19추가: options.lzma_options.dict_size = DICTIONARY;
20추가: let memory = u64::from(options.lzma_options.get_memory_usage())
21추가: .checked_mul(1024)
22추가: .ok_or(ErrorCode::Limit)?;
23추가: if memory > 32 * 1024 * 1024 {
24추가: return Err(ErrorCode::Limit);
25추가: }
26추가: Ok(options)
27추가: }
28추가: fn packed_bound(length: u64) -> Result<u64> {
29추가: // 한 바이트 이상인 청크의 최대 순증 3바이트와 마지막 종료 바이트를 포함함.
30추가: length
31추가: .checked_mul(4)
32추가: .and_then(|n| n.checked_add(1))
33추가: .ok_or(ErrorCode::Limit)
34추가: }
35추가:
36추가: #[derive(Clone, Copy)]
37추가: struct Stream {
38추가: size: u64,
39추가: packed: u64,
40추가: crc: u32,
41추가: packed_crc: u32,
42추가: }
43추가: struct Sink<'a, M> {
44추가: file: &'a mut File,
45추가: check: &'a mut M,
46추가: error: Option<ErrorCode>,
47추가: written: u64,
48추가: bound: u64,
49추가: crc: u32,
50추가: base: u64,
51추가: entries: u32,
52추가: reported: Instant,
53추가: }
54추가: impl<M: Monitor> Write for Sink<'_, M> {
55추가: fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
56추가: let result = (|| {
57추가: self.check.check()?;
58추가: let bytes = &bytes[..bytes.len().min(65_536)];
59추가: let end = self
60추가: .written
61추가: .checked_add(bytes.len() as u64)
62추가: .ok_or(ErrorCode::Limit)?;
63추가: if end > self.bound {
64추가: return Err(ErrorCode::Limit);
65추가: }
66추가: crate::space::ensure(self.file, bytes.len() as u64)?;
67추가: let n = io(self.file.write(bytes))?;
68추가: self.written += n as u64;
69추가: self.crc = crc32(self.crc, &bytes[..n]);
70추가: if n != 0 {
71추가: crate::resources::completed(Ok(()), self.check)?;
72추가: if self.reported.elapsed() >= Duration::from_millis(100) {
73추가: self.check.progress(
74추가: Stage::Write,
75추가: self.base + self.written,
76추가: None,
77추가: self.entries,
78추가: )?;
79추가: self.reported = Instant::now();
80추가: }
81추가: }
82추가: Ok(n)
83추가: })();
84추가: result.map_err(|error| {
85추가: self.error = Some(error);
86추가: std::io::Error::other("7z stream write failed")
87추가: })
88추가: }
89추가: fn flush(&mut self) -> std::io::Result<()> {
90추가: self.file.flush()
91추가: }
92추가: }
93추가: fn pack(
94추가: input: &mut File,
95추가: length: u64,
96추가: output: &mut File,
97추가: entries: u32,
98추가: check: &mut impl Monitor,
99추가: ) -> Result<Stream> {
100추가: let settings = options()?;
101추가: let base = io(output.stream_position())?
102추가: .checked_sub(32)
103추가: .ok_or(ErrorCode::Internal)?;
104추가: let mut sink = Sink {
105추가: file: output,
106추가: check,
107추가: error: None,
108추가: written: 0,
109추가: bound: packed_bound(length)?,
110추가: crc: 0,
111추가: base,
112추가: entries,
113추가: reported: Instant::now(),
114추가: };
115추가: let result = (|| {
116추가: io(input.rewind())?;
117추가: let mut input = input.take(length);
118추가: let mut encoder = Lzma2Writer::new(&mut sink, settings);
119추가: let mut buffer = [0; 65_536];
120추가: let mut read = 0u64;
121추가: let mut crc = 0;
122추가: loop {
123추가: encoder.inner_mut().check.check()?;
124추가: let n = io(input.read(&mut buffer))?;
125추가: if n == 0 {
126추가: break;
127추가: }
128추가: crate::resources::completed(Ok(()), encoder.inner_mut().check)?;
129추가: read = read.checked_add(n as u64).ok_or(ErrorCode::Limit)?;
130추가: crc = crc32(crc, &buffer[..n]);
131추가: io(encoder.write_all(&buffer[..n]))?;
132추가: }
133추가: if read != length {
134추가: return Err(ErrorCode::SourceChanged);
135추가: }
136추가: encoder.inner_mut().check.check()?;
137추가: io(encoder.finish())?;
138추가: Ok(crc)
139추가: })();
140추가: if let Some(error) = sink.error {
141추가: return Err(error);
142추가: }
143추가: let crc = result?;
144추가: sink.check.check()?;
145추가: sink.check
146추가: .progress(Stage::Write, base + sink.written, None, entries)?;
147추가: Ok(Stream {
148추가: size: length,
149추가: packed: sink.written,
150추가: crc,
151추가: packed_crc: sink.crc,
152추가: })
153추가: }
154추가:
155추가: struct Header(Vec<u8>);
156추가: impl Header {
157추가: fn new(capacity: usize) -> Result<Self> {
158추가: let mut bytes = Vec::new();
159추가: bytes
160추가: .try_reserve_exact(capacity)
161추가: .map_err(|_| ErrorCode::Limit)?;
162추가: Ok(Self(bytes))
163추가: }
164추가: fn put(&mut self, bytes: &[u8]) {
165추가: self.0.extend_from_slice(bytes);
166추가: }
167추가: fn integer(&mut self, value: u64) {
168추가: for extra in 0..8 {
169추가: if value < (1u64 << (7 * (extra + 1))) {
170추가: let prefix = if extra == 0 { 0 } else { 0xffu8 << (8 - extra) };
171추가: self.0.push(prefix | (value >> (8 * extra)) as u8);
172추가: self.put(&value.to_le_bytes()[..extra]);
173추가: return;
174추가: }
175추가: }
176추가: self.0.push(0xff);
177추가: self.put(&value.to_le_bytes());
178추가: }
179추가: fn property(&mut self, id: u8, size: usize) {
180추가: self.0.push(id);
181추가: self.integer(size as u64);
182추가: }
183추가: fn bits(&mut self, values: impl Iterator<Item = bool>) {
184추가: let mut byte = 0;
185추가: let mut used = 0;
186추가: for value in values {
187추가: if value {
188추가: byte |= 0x80 >> used;
189추가: }
190추가: used += 1;
191추가: if used == 8 {
192추가: self.0.push(byte);
193추가: byte = 0;
194추가: used = 0;
195추가: }
196추가: }
197추가: if used != 0 {
198추가: self.0.push(byte);
199추가: }
200추가: }
201추가: }
202추가: fn empty(item: &crate::create_sources::Planned) -> bool {
203추가: item.member.entry.size == 0
204추가: }
205추가: fn header(
206추가: plan: &Plan,
207추가: streams: &[Stream],
208추가: names: usize,
209추가: capacity: usize,
210추가: check: &mut impl Monitor,
211추가: ) -> Result<Header> {
212추가: let mut out = Header::new(capacity)?;
213추가: out.put(&[1]);
214추가: if !streams.is_empty() {
215추가: out.put(&[4, 6, 0]);
216추가: out.integer(streams.len() as u64);
217추가: out.put(&[9]);
218추가: for stream in streams {
219추가: out.integer(stream.packed);
220추가: check.check()?;
221추가: }
222추가: out.put(&[10, 1]);
223추가: for stream in streams {
224추가: out.put(&stream.packed_crc.to_le_bytes());
225추가: }
226추가: out.put(&[0, 7, 11]);
227추가: out.integer(streams.len() as u64);
228추가: out.put(&[0]);
229추가: for _ in streams {
230추가: out.put(&[1, 0x21, 0x21, 1, DICTIONARY_PROPERTY]);
231추가: check.check()?;
232추가: }
233추가: out.put(&[12]);
234추가: for stream in streams {
235추가: out.integer(stream.size);
236추가: }
237추가: out.put(&[10, 1]);
238추가: for stream in streams {
239추가: out.put(&stream.crc.to_le_bytes());
240추가: }
241추가: out.put(&[0, 8, 0, 0]);
242추가: }
243추가: out.put(&[5]);
244추가: out.integer(plan.items.len() as u64);
245추가: let empties = plan.items.iter().filter(|p| empty(p)).count();
246추가: if empties != 0 {
247추가: out.property(14, plan.items.len().div_ceil(8));
248추가: out.bits(plan.items.iter().map(empty));
249추가: out.property(15, empties.div_ceil(8));
250추가: out.bits(
251추가: plan.items
252추가: .iter()
253추가: .filter(|p| empty(p))
254추가: .map(|p| p.member.entry.kind == EntryKind::File),
255추가: );
256추가: }
257추가: out.property(17, names.checked_add(1).ok_or(ErrorCode::Limit)?);
258추가: out.put(&[0]);
259추가: for item in &plan.items {
260추가: for unit in item
261추가: .member
262추가: .entry
263추가: .name
264추가: .encode_utf16()
265추가: .chain(std::iter::once(0))
266추가: {
267추가: out.put(&unit.to_le_bytes());
268추가: }
269추가: crate::resources::completed(Ok(()), check)?;
270추가: }
271추가: out.property(
272추가: 21,
273추가: plan.items
274추가: .len()
275추가: .checked_mul(4)
276추가: .and_then(|n| n.checked_add(2))
277추가: .ok_or(ErrorCode::Limit)?,
278추가: );
279추가: out.put(&[1, 0]);
280추가: for item in &plan.items {
281추가: let attributes: u32 = if item.member.entry.kind == EntryKind::Directory {
282추가: 0x10
283추가: } else {
284추가: 0x20
285추가: };
286추가: out.put(&attributes.to_le_bytes());
287추가: check.check()?;
288추가: }
289추가: out.put(&[0, 0]);
290추가: if out.0.len() > capacity {
291추가: return Err(ErrorCode::Internal);
292추가: }
293추가: Ok(out)
294추가: }
295추가: fn write(output: &mut File, bytes: &[u8], check: &mut impl Monitor) -> Result<()> {
296추가: for chunk in bytes.chunks(65_536) {
297추가: check.check()?;
298추가: crate::space::ensure(output, chunk.len() as u64)?;
299추가: io(output.write_all(chunk))?;
300추가: crate::resources::completed(Ok(()), check)?;
301추가: }
302추가: Ok(())
303추가: }
304추가: struct Verify<'a, M>(&'a mut M);
305추가: impl<M: Monitor> Monitor for Verify<'_, M> {
306추가: fn metadata_limits(&self) -> crate::archive::MetadataLimits {
307추가: self.0.metadata_limits()
308추가: }
309추가: fn check(&mut self) -> Result<()> {
310추가: self.0.check()
311추가: }
312추가: fn activity(&mut self) -> Result<()> {
313추가: self.0.activity()
314추가: }
315추가: }
316추가:
317추가: pub(crate) fn archive(
318추가: plan: &mut Plan,
319추가: limits: Limits,
320추가: check: &mut impl Monitor,
321추가: ) -> Result<(File, u64)> {
322추가: if plan.items.is_empty() {
323추가: return Err(ErrorCode::InvalidRequest);
324추가: }
325추가: let mut names = 0usize;
326추가: let mut total = 0u64;
327추가: for item in &plan.items {
328추가: check.check()?;
329추가: names = item
330추가: .member
331추가: .entry
332추가: .name
333추가: .encode_utf16()
334추가: .count()
335추가: .checked_add(1)
336추가: .and_then(|n| n.checked_mul(2))
337추가: .and_then(|n| names.checked_add(n))
338추가: .ok_or(ErrorCode::Limit)?;
339추가: total = total
340추가: .checked_add(item.member.entry.size)
341추가: .filter(|n| *n <= limits.input.min(limits.output))
342추가: .ok_or(ErrorCode::Limit)?;
343추가: }
344추가: let capacity = plan
345추가: .items
346추가: .len()
347추가: .checked_mul(96)
348추가: .and_then(|n| n.checked_add(names))
349추가: .and_then(|n| n.checked_add(128))
350추가: .ok_or(ErrorCode::Limit)?;
351추가: // 헤더 두 사본, 검증 목록과 스트림 배열을 기존 계획 예산에 함께 반영함.
352추가: let metadata = capacity
353추가: .checked_mul(3)
354추가: .and_then(|n| n.checked_add(plan.items.len().checked_mul(256)?))
355추가: .ok_or(ErrorCode::Limit)?;
356추가: plan.reserve_metadata(metadata, check)?;
357추가: let mut streams = Vec::new();
358추가: streams
359추가: .try_reserve_exact(plan.items.len())
360추가: .map_err(|_| ErrorCode::Limit)?;
361추가: let mut output = spool::temporary()?;
362추가: write(&mut output, &[0; 32], check)?;
363추가: let mut read = 0u64;
364추가: for (index, source) in plan.items.iter().enumerate() {
365추가: check.check()?;
366추가: let length = source.member.entry.size;
367추가: let mut input = crate::resources::completed(source.open(), check)?;
368추가: if !empty(source) {
369추가: let required = length
370추가: .checked_add(packed_bound(length)?)
371추가: .and_then(|n| n.checked_add(capacity as u64))
372추가: .ok_or(ErrorCode::Limit)?;
373추가: crate::space::ensure(&output, required)?;
374추가: check.progress(Stage::Read, read, Some(total), index as u32)?;
375추가: let mut snapshot = spool::Snapshot::capture_reporting(
376추가: &mut input.file,
377추가: length,
378추가: &mut |step| match step {
379추가: spool::Step::Check => check.check(),
380추가: spool::Step::Activity => crate::resources::completed(Ok(()), check),
381추가: spool::Step::Read { bytes, .. } => {
382추가: check.progress(Stage::Read, read + bytes, Some(total), index as u32)
383추가: }
384추가: },
385추가: )?;
386추가: if snapshot.len != length {
387추가: return Err(ErrorCode::SourceChanged);
388추가: }
389추가: check.progress(
390추가: Stage::Write,
391추가: io(output.stream_position())? - 32,
392추가: None,
393추가: index as u32,
394추가: )?;
395추가: streams.push(pack(
396추가: &mut snapshot.file,
397추가: length,
398추가: &mut output,
399추가: index as u32,
400추가: check,
401추가: )?);
402추가: read += length;
403추가: }
404추가: crate::resources::completed(Ok(()), check)?;
405추가: }
406추가: let at = io(output.stream_position())?;
407추가: let header = header(plan, &streams, names, capacity, check)?;
408추가: let mut start = [0; 32];
409추가: start[..8].copy_from_slice(b"7z\xbc\xaf\x27\x1c\x00\x04");
410추가: start[12..20].copy_from_slice(&at.checked_sub(32).ok_or(ErrorCode::Internal)?.to_le_bytes());
411추가: start[20..28].copy_from_slice(&(header.0.len() as u64).to_le_bytes());
412추가: start[28..32].copy_from_slice(&crc32(0, &header.0).to_le_bytes());
413추가: let crc = crc32(0, &start[12..]);
414추가: start[8..12].copy_from_slice(&crc.to_le_bytes());
415추가: write(&mut output, &header.0, check)?;
416추가: drop(header);
417추가: let length = io(output.stream_position())?;
418추가: check.check()?;
419추가: io(output.seek(SeekFrom::Start(0)))?;
420추가: write(&mut output, &start, check)?;
421추가: check.progress(Stage::Verify, 0, None, plan.items.len() as u32)?;
422추가: let catalog = crate::seven_zip::open(
423추가: &mut output,
424추가: length,
425추가: Limits {
426추가: input: length,
427추가: ..limits
428추가: },
429추가: false,
430추가: &mut Verify(check),
431추가: )?;
432추가: if catalog.members.len() != plan.items.len() {
433추가: return Err(ErrorCode::Integrity);
434추가: }
435추가: for (actual, expected) in catalog.members.iter().zip(&plan.items) {
436추가: let expected = &expected.member.entry;
437추가: if actual.entry.name != expected.name
438추가: || actual.entry.kind != expected.kind
439추가: || actual.entry.size != expected.size
440추가: {
441추가: return Err(ErrorCode::Integrity);
442추가: }
443추가: crate::resources::completed(Ok(()), check)?;
444추가: }
445추가: drop(catalog);
446추가: plan.verify(check)?;
447추가: io(output.rewind())?;
448추가: Ok((output, length))
449추가: }
450추가:
451추가: #[cfg(test)]
452추가: #[path = "../../../tests/rust-archive-worker/seven_zip_create_fields.rs"]
453추가: mod tests;
수정experiments/rust-archive-worker/src/spool.rs+1-1
@@ -139,7 +139,7 @@ impl Snapshot {
139139 Step::Read { .. } => check.check(),
140140 })
141141 }
142삭제: fn capture_reporting(
142추가: pub(crate) fn capture_reporting(
143143 source: &mut File,
144144 limit: u64,
145145 step: &mut impl FnMut(Step) -> Result<()>,
수정tests/release-packages/test_compressed_tar_licenses.py+12-0
@@ -3,6 +3,7 @@
33import importlib.util
44from pathlib import Path
55import unittest
6추가: import tomllib
67
78
89ROOT = Path(__file__).resolve().parents[2]
@@ -12,6 +13,17 @@ SPEC.loader.exec_module(LICENSES)
1213
1314
1415class CompressedTarLicenses(unittest.TestCase):
16추가: def test_seven_zip_encoder_reuses_pure_rust_package(self):
17추가: manifest = ROOT / "experiments/rust-archive-worker/Cargo.toml"
18추가: dependency = tomllib.loads(manifest.read_text())["dependencies"]["lzma-rust2"]
19추가: self.assertEqual(dependency["version"], "=0.25.0")
20추가: self.assertFalse(dependency["default-features"])
21추가: self.assertEqual(set(dependency["features"]), {"std", "xz", "encoder"})
22추가: package = next(p for p in LICENSES.metadata(manifest) if p["name"] == "lzma-rust2")
23추가: original = tomllib.loads((Path(package["manifest_path"]).parent / "Cargo.toml.orig").read_text())
24추가: self.assertEqual(original["features"]["encoder"], [])
25추가: self.assertEqual(original["package"]["license"], "Apache-2.0")
26추가:
1527 def test_registry_originals_are_in_generated_worker_notice(self):
1628 manifest = ROOT / "experiments/rust-archive-worker/Cargo.toml"
1729 records = LICENSES.inventory([manifest])
수정tests/rust-archive-worker/main.rs+2-0
@@ -1627,3 +1627,5 @@ mod guarded;
16271627mod split_runtime;
16281628
16291629mod seven_zip_create;
1630추가:
1631추가: mod seven_zip_create_runtime;
수정tests/rust-archive-worker/seven_zip_create.rs+4-1
@@ -346,10 +346,13 @@ impl Drop for Temporary {
346346}
347347
348348#[test]
349삭제: fn pending_writer_and_unsupported_options_fail_before_questions_or_file_access() {
349추가: fn unsupported_options_fail_before_questions_or_file_access() {
350350 let temporary = Temporary::new();
351351 for solid in [false, true] {
352352 for encryption in [Encryption::None, Encryption::Aes256] {
353추가: if !solid && encryption == Encryption::None {
354추가: continue;
355추가: }
353356 for kind in [1, 6, 7] {
354357 let action = Action::CreateSevenZip {
355358 sources: vec![Source {
추가tests/rust-archive-worker/seven_zip_create_fault.c+47-0
@@ -0,0 +1,47 @@
1추가: #define _GNU_SOURCE
2추가: #include <dlfcn.h>
3추가: #include <errno.h>
4추가: #include <stdlib.h>
5추가: #include <string.h>
6추가: #include <unistd.h>
7추가:
8추가: static int archive_fd = -1;
9추가: static int finished;
10추가: static ssize_t (*original_write)(int, const void *, size_t);
11추가: static off64_t (*original_seek)(int, off64_t, int);
12추가:
13추가: __attribute__((constructor)) static void initialize(void) {
14추가: original_write = dlsym(RTLD_NEXT, "write");
15추가: original_seek = dlsym(RTLD_NEXT, "lseek64");
16추가: }
17추가:
18추가: ssize_t write(int fd, const void *data, size_t count) {
19추가: const unsigned char *bytes = data;
20추가: if (archive_fd < 0 && count == 32 && !memcmp(bytes, (unsigned char[32]){0}, 32)) {
21추가: archive_fd = fd;
22추가: return original_write(fd, data, count);
23추가: }
24추가: const char *fault = getenv("ZIPELO_7Z_FAULT");
25추가: if (fd == archive_fd && fault) {
26추가: if (!strcmp(fault, "encode-full")) { errno = ENOSPC; return -1; }
27추가: if (count == 1 && bytes[0] == 0) {
28추가: finished = 1;
29추가: if (!strcmp(fault, "finish-full")) { errno = ENOSPC; return -1; }
30추가: }
31추가: if (!strcmp(fault, "header-write") && finished && count > 1 && bytes[0] == 1) {
32추가: errno = EIO; return -1;
33추가: }
34추가: if (!strcmp(fault, "header-patch") && count == 32 && !memcmp(bytes, "7z", 2)) {
35추가: errno = EIO; return -1;
36추가: }
37추가: }
38추가: return original_write(fd, data, count);
39추가: }
40추가:
41추가: off64_t lseek64(int fd, off64_t offset, int whence) {
42추가: const char *fault = getenv("ZIPELO_7Z_FAULT");
43추가: if (fd == archive_fd && finished && fault && !strcmp(fault, "header-seek") && offset == 0 && whence == SEEK_SET) {
44추가: errno = EIO; return -1;
45추가: }
46추가: return original_seek(fd, offset, whence);
47추가: }
추가tests/rust-archive-worker/seven_zip_create_fields.rs+167-0
@@ -0,0 +1,167 @@
1추가: use super::*;
2추가:
3추가: #[test]
4추가: fn uint64_boundaries_match_the_seven_zip_encoding() {
5추가: for (value, expected) in [
6추가: (0, vec![0]),
7추가: (127, vec![0x7f]),
8추가: (128, vec![0x80, 0x80]),
9추가: (16_383, vec![0xbf, 0xff]),
10추가: (16_384, vec![0xc0, 0, 0x40]),
11추가: (u32::MAX as u64, vec![0xf0, 0xff, 0xff, 0xff, 0xff]),
12추가: (1u64 << 32, vec![0xf1, 0, 0, 0, 0]),
13추가: (1u64 << 56, vec![0xff, 0, 0, 0, 0, 0, 0, 0, 1]),
14추가: (u64::MAX, vec![0xff; 9]),
15추가: ] {
16추가: let mut header = Header::new(9).unwrap();
17추가: header.integer(value);
18추가: assert_eq!(header.0, expected, "{value}");
19추가: }
20추가: }
21추가:
22추가: #[test]
23추가: fn bitmap_boundaries_keep_only_the_empty_stream_subset() {
24추가: for (count, expected) in [(7, vec![0xaa]), (8, vec![0xaa]), (9, vec![0xaa, 0x80])] {
25추가: let mut header = Header::new(2).unwrap();
26추가: header.bits((0..count).map(|n| n % 2 == 0));
27추가: assert_eq!(header.0, expected);
28추가: }
29추가: let mut header = Header::new(2).unwrap();
30추가: header.bits([true, false, false, true, true, false, true, false, true].into_iter());
31추가: assert_eq!(header.0, [0x9a, 0x80]);
32추가: }
33추가:
34추가: #[test]
35추가: fn encoder_dictionary_memory_and_packed_bound_are_checked() {
36추가: let settings = options().unwrap();
37추가: assert_eq!(settings.lzma_options.dict_size, 1_048_576);
38추가: assert!(settings.lzma_options.get_memory_usage() <= 32 * 1024);
39추가: assert_eq!(
40추가: (2 | (DICTIONARY_PROPERTY as u32 & 1)) << (DICTIONARY_PROPERTY / 2 + 11),
41추가: DICTIONARY
42추가: );
43추가: assert_eq!(packed_bound(0), Ok(1));
44추가: assert_eq!(packed_bound(65_536), Ok(262_145));
45추가: assert_eq!(packed_bound(u64::MAX / 4), Ok(u64::MAX - 2));
46추가: assert_eq!(packed_bound(u64::MAX / 4 + 1), Err(ErrorCode::Limit));
47추가: }
48추가:
49추가: #[test]
50추가: fn encoding_preserves_source_crc_and_respects_stream_boundaries() {
51추가: use lzma_rust2::Lzma2Reader;
52추가: for size in [1, 65_535, 65_536, 65_537, 131_081] {
53추가: let expected: Vec<u8> = (0..size).map(|n| ((n * 73 + n / 17) % 251) as u8).collect();
54추가: let mut input = spool::temporary().unwrap();
55추가: input.write_all(&expected).unwrap();
56추가: let mut output = spool::temporary().unwrap();
57추가: output.write_all(&[0; 32]).unwrap();
58추가: let stream = pack(&mut input, size as u64, &mut output, 0, &mut || Ok(())).unwrap();
59추가: assert_eq!(stream.size, size as u64);
60추가: assert_eq!(stream.crc, crc32(0, &expected));
61추가: assert!(stream.packed <= packed_bound(size as u64).unwrap());
62추가: output.seek(SeekFrom::Start(32)).unwrap();
63추가: let mut actual = Vec::new();
64추가: Lzma2Reader::new(output.take(stream.packed), DICTIONARY, None)
65추가: .read_to_end(&mut actual)
66추가: .unwrap();
67추가: assert_eq!(actual, expected);
68추가: }
69추가: }
70추가:
71추가: #[test]
72추가: fn monitored_encoder_output_preserves_cancellation_error() {
73추가: let mut file = spool::temporary().unwrap();
74추가: let mut check = || Err(ErrorCode::None);
75추가: let mut sink = Sink {
76추가: file: &mut file,
77추가: check: &mut check,
78추가: error: None,
79추가: written: 0,
80추가: bound: 1,
81추가: crc: 0,
82추가: base: 0,
83추가: entries: 0,
84추가: reported: Instant::now(),
85추가: };
86추가: assert!(sink.write_all(b"x").is_err());
87추가: assert_eq!(sink.error, Some(ErrorCode::None));
88추가: assert_eq!(sink.written, 0);
89추가: }
90추가:
91추가: #[test]
92추가: fn every_encoding_checkpoint_preserves_cooperative_cancellation() {
93추가: struct Stop {
94추가: at: usize,
95추가: seen: usize,
96추가: }
97추가: impl Monitor for Stop {
98추가: fn check(&mut self) -> Result<()> {
99추가: self.seen += 1;
100추가: if self.at == self.seen {
101추가: Err(ErrorCode::None)
102추가: } else {
103추가: Ok(())
104추가: }
105추가: }
106추가: }
107추가: let mut input = spool::temporary().unwrap();
108추가: input.write_all(b"checkpoint").unwrap();
109추가: let mut maximum = Stop {
110추가: at: usize::MAX,
111추가: seen: 0,
112추가: };
113추가: let mut output = spool::temporary().unwrap();
114추가: output.write_all(&[0; 32]).unwrap();
115추가: pack(&mut input, 10, &mut output, 0, &mut maximum).unwrap();
116추가: for at in 1..=maximum.seen {
117추가: let mut output = spool::temporary().unwrap();
118추가: output.write_all(&[0; 32]).unwrap();
119추가: let result = pack(&mut input, 10, &mut output, 0, &mut Stop { at, seen: 0 });
120추가: assert!(matches!(result, Err(ErrorCode::None)), "checkpoint {at}");
121추가: }
122추가: }
123추가:
124추가: #[test]
125추가: fn header_metadata_is_charged_before_source_capture() {
126추가: use std::path::PathBuf;
127추가: let root = std::env::var_os("TMPDIR")
128추가: .map(PathBuf::from)
129추가: .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp"));
130추가: std::fs::create_dir_all(&root).unwrap();
131추가: let root = root
132추가: .canonicalize()
133추가: .unwrap()
134추가: .join(format!("7zc-budget-{}", std::process::id()));
135추가: std::fs::create_dir(&root).unwrap();
136추가: let path = root.join("empty");
137추가: std::fs::write(&path, b"").unwrap();
138추가: let mut plan = Plan::new(
139추가: &[Source {
140추가: path: NativePath::from_path(&path),
141추가: archive_name: "empty".into(),
142추가: }],
143추가: Limits::default(),
144추가: &mut || Ok(()),
145추가: )
146추가: .unwrap();
147추가: struct Tiny;
148추가: impl Monitor for Tiny {
149추가: fn metadata_limits(&self) -> crate::archive::MetadataLimits {
150추가: crate::archive::MetadataLimits {
151추가: bytes: 1,
152추가: ..Default::default()
153추가: }
154추가: }
155추가: fn check(&mut self) -> Result<()> {
156추가: Ok(())
157추가: }
158추가: fn progress(&mut self, _: Stage, _: u64, _: Option<u64>, _: u32) -> Result<()> {
159추가: panic!("헤더 예산 검사 전 캡처가 시작됨")
160추가: }
161추가: }
162추가: assert!(matches!(
163추가: archive(&mut plan, Limits::default(), &mut Tiny),
164추가: Err(ErrorCode::Limit)
165추가: ));
166추가: std::fs::remove_dir_all(root).unwrap();
167추가: }
추가tests/rust-archive-worker/seven_zip_create_memory.py+61-0
@@ -0,0 +1,61 @@
1추가: """1 GiB 입력의 7z 작성 메모리와 게시 결과를 검증함."""
2추가:
3추가: import json
4추가: import os
5추가: from pathlib import Path
6추가: import struct
7추가: import subprocess
8추가: import sys
9추가: import tempfile
10추가: import time
11추가:
12추가:
13추가: def native(path):
14추가: value = os.fsencode(path)
15추가: return b"\x01" + struct.pack("<I", len(value)) + value
16추가:
17추가:
18추가: with tempfile.TemporaryDirectory(prefix="7zc-memory-", dir=os.environ["TMPDIR"]) as temporary:
19추가: root = Path(temporary)
20추가: source = root / "source"
21추가: with source.open("xb") as output:
22추가: output.truncate(1024 * 1024 * 1024)
23추가: archive = root / "result.7z"
24추가: body = b"\x04" + struct.pack("<I", 1) + native(source)
25추가: body += struct.pack("<I", 11) + b"payload.bin" + native(archive)
26추가: body += b"\x00\x00\x00" + struct.pack("<QQI", 2**64 - 1, 16 * 1024**3, 10000)
27추가: frame = b"ZAW1" + struct.pack("<HHIIQQ", 1, 1, len(body), 0, 17, 0) + body
28추가: started = time.monotonic()
29추가: result = subprocess.run(
30추가: ["/usr/bin/time", "-f", "%M", "-o", str(root / "rss"), sys.argv[1]],
31추가: input=frame, capture_output=True, timeout=180,
32추가: env={**os.environ, "TMPDIR": str(root), "TMP": str(root), "TEMP": str(root)},
33추가: )
34추가: assert result.returncode == 0, result.stderr
35추가: assert not result.stderr, result.stderr
36추가: at = 0
37추가: terminal = None
38추가: outputs = 0
39추가: while at < len(result.stdout):
40추가: magic, version, kind, size, reserved, job, sequence = struct.unpack_from("<4sHHIIQQ", result.stdout, at)
41추가: assert (magic, version, reserved, job) == (b"ZAW1", 1, 0, 17)
42추가: at += 32
43추가: payload = result.stdout[at:at + size]
44추가: assert len(payload) == size
45추가: at += size
46추가: if kind == 105:
47추가: outputs += 1
48추가: if kind == 106:
49추가: assert at == len(result.stdout)
50추가: terminal = payload
51추가: assert terminal[:3] == b"\x00\x00\x02", terminal
52추가: assert struct.unpack_from("<QQ", terminal, 3) == (1, 0)
53추가: assert outputs == 1 and archive.is_file()
54추가: rss = int((root / "rss").read_text())
55추가: assert rss <= 64 * 1024, rss
56추가: print(json.dumps({
57추가: "seven_zip_creation_input_bytes": source.stat().st_size,
58추가: "archive_bytes": archive.stat().st_size,
59추가: "peak_rss_kib": rss,
60추가: "elapsed_seconds": round(time.monotonic() - started, 3),
61추가: }))
추가tests/rust-archive-worker/seven_zip_create_runtime.rs+651-0
@@ -0,0 +1,651 @@
1추가: use super::*;
2추가: use std::{io::Read, process::Child, sync::mpsc, time::Duration};
3추가:
4추가: fn private_dir(path: &std::path::Path) {
5추가: let mut builder = fs::DirBuilder::new();
6추가: #[cfg(unix)]
7추가: {
8추가: use std::os::unix::fs::DirBuilderExt;
9추가: builder.mode(0o700);
10추가: }
11추가: builder.create(path).unwrap();
12추가: }
13추가: struct Case(PathBuf);
14추가: impl Case {
15추가: fn new() -> Self {
16추가: let root = std::env::var_os("TMPDIR")
17추가: .map(PathBuf::from)
18추가: .unwrap_or_else(|| {
19추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")
20추가: });
21추가: fs::create_dir_all(&root).unwrap();
22추가: let path = root.canonicalize().unwrap().join(format!(
23추가: "zipelo-7zc-{}-{}",
24추가: std::process::id(),
25추가: NEXT.fetch_add(1, Ordering::Relaxed)
26추가: ));
27추가: private_dir(&path);
28추가: private_dir(&path.join("tmp"));
29추가: Self(path)
30추가: }
31추가: fn path(&self, name: &str) -> NativePath {
32추가: NativePath::from_path(&self.0.join(name))
33추가: }
34추가: fn request(&self, names: &[&str]) -> Start {
35추가: Start {
36추가: action: Action::CreateSevenZip {
37추가: sources: names
38추가: .iter()
39추가: .map(|name| Source {
40추가: path: self.path(name),
41추가: archive_name: (*name).to_owned(),
42추가: })
43추가: .collect(),
44추가: output_file: self.path("result.7z"),
45추가: method: SevenZipMethod::Lzma2,
46추가: solid: false,
47추가: encryption: Encryption::None,
48추가: },
49추가: limits: Limits::default(),
50추가: }
51추가: }
52추가: fn command(&self) -> Command {
53추가: let mut cmd = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"));
54추가: cmd.env("TMPDIR", self.0.join("tmp"))
55추가: .env("TMP", self.0.join("tmp"))
56추가: .env("TEMP", self.0.join("tmp"));
57추가: cmd
58추가: }
59추가: fn run(&self, message: Message) -> Vec<Message> {
60추가: self.run_with(&mut self.command(), message, |_| Vec::new())
61추가: }
62추가: fn run_with(
63추가: &self,
64추가: command: &mut Command,
65추가: message: Message,
66추가: mut respond: impl FnMut(&Message) -> Vec<Message>,
67추가: ) -> Vec<Message> {
68추가: struct Running(Child);
69추가: impl Drop for Running {
70추가: fn drop(&mut self) {
71추가: let _ = self.0.kill();
72추가: let _ = self.0.wait();
73추가: }
74추가: }
75추가: let mut child = Running(
76추가: command
77추가: .stdin(Stdio::piped())
78추가: .stdout(Stdio::piped())
79추가: .stderr(Stdio::piped())
80추가: .spawn()
81추가: .unwrap(),
82추가: );
83추가: let mut writer = Writer::new(child.0.stdin.take().unwrap(), 17);
84추가: writer.send(&message).unwrap();
85추가: let stdout = child.0.stdout.take().unwrap();
86추가: let mut stderr = child.0.stderr.take().unwrap();
87추가: let diagnostic = std::thread::spawn(move || {
88추가: let mut bytes = Vec::new();
89추가: stderr.read_to_end(&mut bytes).unwrap();
90추가: bytes
91추가: });
92추가: let (send, receive) = mpsc::sync_channel(128);
93추가: let reader = std::thread::spawn(move || {
94추가: let mut reader = Reader::new(stdout);
95추가: loop {
96추가: let frame = reader.read();
97추가: let end = !matches!(frame, Ok(Some(_)));
98추가: if send.send(frame).is_err() || end {
99추가: break;
100추가: }
101추가: }
102추가: });
103추가: let mut events = Vec::new();
104추가: while let Some((job, _, event)) = receive
105추가: .recv_timeout(Duration::from_secs(120))
106추가: .expect("worker timeout")
107추가: .unwrap()
108추가: {
109추가: assert_eq!(job, 17);
110추가: for reply in respond(&event) {
111추가: writer.send(&reply).unwrap();
112추가: }
113추가: events.push(event);
114추가: }
115추가: drop(writer);
116추가: reader.join().unwrap();
117추가: assert!(child.0.wait().unwrap().success());
118추가: assert!(diagnostic.join().unwrap().is_empty());
119추가: assert!(matches!(events.last(), Some(Message::Terminal(_))));
120추가: assert_eq!(
121추가: events
122추가: .iter()
123추가: .filter(|e| matches!(e, Message::Terminal(_)))
124추가: .count(),
125추가: 1
126추가: );
127추가: assert_eq!(fs::read_dir(self.0.join("tmp")).unwrap().count(), 0);
128추가: events
129추가: }
130추가: fn list(&self) -> Vec<Message> {
131추가: self.run(Message::Start(Start {
132추가: action: Action::List {
133추가: archive: self.path("result.7z"),
134추가: },
135추가: limits: Limits::default(),
136추가: }))
137추가: }
138추가: fn extract(&self, destination: &str) -> Vec<Message> {
139추가: private_dir(&self.0.join(destination));
140추가: self.run(Message::Start(Start {
141추가: action: Action::Extract {
142추가: archive: self.path("result.7z"),
143추가: destination: self.path(destination),
144추가: selection: Selection::All,
145추가: list_id: None,
146추가: gzip_output_name: None,
147추가: },
148추가: limits: Limits::default(),
149추가: }))
150추가: }
151추가: }
152추가: impl Drop for Case {
153추가: fn drop(&mut self) {
154추가: fs::remove_dir_all(&self.0).expect("7z 작성 시험 폴더 정리에 실패함");
155추가: }
156추가: }
157추가: fn success(events: &[Message]) {
158추가: let t = terminal(events);
159추가: assert_eq!(t.outcome, Outcome::Completed, "{events:?}");
160추가: assert_eq!(t.error, ErrorCode::None);
161추가: assert!(events.iter().any(|e| matches!(
162추가: e,
163추가: Message::Progress {
164추가: stage: Stage::Commit,
165추가: ..
166추가: }
167추가: )));
168추가: assert_eq!(t.publication, Publication::Complete);
169추가: assert_eq!(t.created_count, 1);
170추가: assert_eq!(t.retained_partial_count, 0);
171추가: assert_eq!(t.cleanup, Cleanup::Complete);
172추가: assert_eq!(
173추가: events
174추가: .iter()
175추가: .filter(|e| matches!(e, Message::Output { .. }))
176추가: .count(),
177추가: 1
178추가: );
179추가: assert!(events.iter().any(|e| matches!(e, Message::Output { entry_id: None, relative_name, disposition: Disposition::Created } if relative_name == "result.7z")));
180추가: assert!(!events.iter().any(|e| matches!(
181추가: e,
182추가: Message::PasswordRequired { .. } | Message::ConflictRequired { .. }
183추가: )));
184추가: }
185추가: fn failure(events: &[Message], error: ErrorCode) {
186추가: let t = terminal(events);
187추가: assert_eq!(t.error, error, "{events:?}");
188추가: assert_eq!(
189추가: t.outcome,
190추가: if error == ErrorCode::None {
191추가: Outcome::Cancelled
192추가: } else {
193추가: Outcome::Failed
194추가: }
195추가: );
196추가: assert_eq!(t.publication, Publication::None);
197추가: assert_eq!(t.created_count, 0);
198추가: assert_eq!(t.retained_partial_count, 0);
199추가: assert_eq!(t.cleanup, Cleanup::Complete);
200추가: assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
201추가: }
202추가: fn tree(root: &std::path::Path) -> std::collections::BTreeMap<String, Option<[u8; 32]>> {
203추가: use sha2::{Digest, Sha256};
204추가: fn walk(
205추가: root: &std::path::Path,
206추가: at: &std::path::Path,
207추가: result: &mut std::collections::BTreeMap<String, Option<[u8; 32]>>,
208추가: ) {
209추가: for entry in fs::read_dir(at).unwrap() {
210추가: let path = entry.unwrap().path();
211추가: let name = path
212추가: .strip_prefix(root)
213추가: .unwrap()
214추가: .to_str()
215추가: .unwrap()
216추가: .replace('\\', "/");
217추가: if path.is_dir() {
218추가: result.insert(name, None);
219추가: walk(root, &path, result);
220추가: } else {
221추가: result.insert(name, Some(Sha256::digest(fs::read(path).unwrap()).into()));
222추가: }
223추가: }
224추가: }
225추가: let mut result = std::collections::BTreeMap::new();
226추가: walk(root, root, &mut result);
227추가: result
228추가: }
229추가:
230추가: #[test]
231추가: fn mixed_unicode_files_and_empty_bitmap_boundaries_round_trip() {
232추가: for count in [7, 8, 9] {
233추가: let c = Case::new();
234추가: fs::create_dir_all(c.0.join("원본/폴더/빈 폴더")).unwrap();
235추가: fs::write(c.0.join("원본/가.txt"), "한글 자료\n".repeat(1000)).unwrap();
236추가: fs::write(
237추가: c.0.join("원본/폴더/z"),
238추가: (0..131_081)
239추가: .map(|n| ((n * 73) % 251) as u8)
240추가: .collect::<Vec<_>>(),
241추가: )
242추가: .unwrap();
243추가: for index in 0..count - 3 {
244추가: fs::write(c.0.join(format!("원본/빈-{index}")), b"").unwrap();
245추가: }
246추가: fs::write(c.0.join("원본/\u{20000}.txt"), b"UTF-16 surrogate pair").unwrap();
247추가: let mut state = 0x1234_5678u32;
248추가: let noise: Vec<u8> = (0..131_081)
249추가: .map(|_| {
250추가: state ^= state << 13;
251추가: state ^= state >> 17;
252추가: state ^= state << 5;
253추가: state as u8
254추가: })
255추가: .collect();
256추가: fs::write(c.0.join("원본/noise.bin"), noise).unwrap();
257추가: let expected = tree(&c.0.join("원본"));
258추가: let events = c.run(Message::Start(c.request(&["원본"])));
259추가: success(&events);
260추가: assert!(matches!(
261추가: events[0],
262추가: Message::Accepted {
263추가: action: ActionKind::CreateSevenZip,
264추가: encryption: false
265추가: }
266추가: ));
267추가: let list = c.list();
268추가: assert_eq!(terminal(&list).outcome, Outcome::Completed, "{list:?}");
269추가: let extracted = c.extract("decoded");
270추가: assert_eq!(
271추가: terminal(&extracted).outcome,
272추가: Outcome::Completed,
273추가: "{extracted:?}"
274추가: );
275추가: assert_eq!(tree(&c.0.join("decoded/원본")), expected);
276추가: if let Some(tool) = std::env::var_os("ZIPELO_TEST_7ZIP") {
277추가: for operation in ["t", "l"] {
278추가: let output = Command::new(&tool)
279추가: .args([operation, "-slt"])
280추가: .arg(c.0.join("result.7z"))
281추가: .output()
282추가: .unwrap();
283추가: assert!(
284추가: output.status.success(),
285추가: "{}",
286추가: String::from_utf8_lossy(&output.stdout)
287추가: );
288추가: if operation == "l" {
289추가: let text = String::from_utf8_lossy(&output.stdout);
290추가: assert!(text.contains("Method = LZMA2:20"), "{text}");
291추가: assert!(text.contains("Solid = -"), "{text}");
292추가: assert!(!text.contains("Encrypted = +"));
293추가: }
294추가: }
295추가: let output = Command::new(tool)
296추가: .args(["x", "-y"])
297추가: .arg(c.0.join("result.7z"))
298추가: .arg(format!("-o{}", c.0.join("independent").display()))
299추가: .output()
300추가: .unwrap();
301추가: assert!(
302추가: output.status.success(),
303추가: "{}",
304추가: String::from_utf8_lossy(&output.stdout)
305추가: );
306추가: assert_eq!(tree(&c.0.join("independent/원본")), expected);
307추가: }
308추가: }
309추가: }
310추가:
311추가: #[test]
312추가: fn archives_with_only_empty_files_and_directories_are_valid() {
313추가: for directory in [false, true] {
314추가: let c = Case::new();
315추가: if directory {
316추가: fs::create_dir_all(c.0.join("empty/nested")).unwrap();
317추가: } else {
318추가: fs::write(c.0.join("empty"), b"").unwrap();
319추가: }
320추가: success(&c.run(Message::Start(c.request(&["empty"]))));
321추가: let extracted = c.extract("decoded");
322추가: assert_eq!(
323추가: terminal(&extracted).outcome,
324추가: Outcome::Completed,
325추가: "{extracted:?}"
326추가: );
327추가: assert_eq!(c.0.join("decoded/empty").is_dir(), directory);
328추가: if let Some(tool) = std::env::var_os("ZIPELO_TEST_7ZIP") {
329추가: assert!(
330추가: Command::new(tool)
331추가: .arg("t")
332추가: .arg(c.0.join("result.7z"))
333추가: .output()
334추가: .unwrap()
335추가: .status
336추가: .success()
337추가: );
338추가: }
339추가: }
340추가: }
341추가:
342추가: #[test]
343추가: fn existing_output_empty_sources_limits_and_links_are_rejected() {
344추가: let c = Case::new();
345추가: fs::write(c.0.join("source"), b"abcdef").unwrap();
346추가: fs::write(c.0.join("result.7z"), b"preserve").unwrap();
347추가: failure(
348추가: &c.run(Message::Start(c.request(&["source"]))),
349추가: ErrorCode::Conflict,
350추가: );
351추가: assert_eq!(fs::read(c.0.join("result.7z")).unwrap(), b"preserve");
352추가: fs::remove_file(c.0.join("result.7z")).unwrap();
353추가: failure(
354추가: &c.run(Message::Start(c.request(&[]))),
355추가: ErrorCode::InvalidRequest,
356추가: );
357추가: for bytes in [5, 6, 7] {
358추가: let mut start = c.request(&["source"]);
359추가: start.limits.input = bytes;
360추가: start.limits.output = bytes;
361추가: let events = c.run(Message::Start(start));
362추가: if bytes == 5 {
363추가: failure(&events, ErrorCode::Limit);
364추가: } else {
365추가: success(&events);
366추가: fs::remove_file(c.0.join("result.7z")).unwrap();
367추가: }
368추가: }
369추가: #[cfg(unix)]
370추가: {
371추가: std::os::unix::fs::symlink(c.0.join("source"), c.0.join("link")).unwrap();
372추가: failure(
373추가: &c.run(Message::Start(c.request(&["link"]))),
374추가: ErrorCode::UnsafePath,
375추가: );
376추가: }
377추가: assert!(!c.0.join("result.7z").exists());
378추가: }
379추가:
380추가: #[test]
381추가: fn guarded_approval_decline_and_cancel_preserve_creation_rules() {
382추가: let c = Case::new();
383추가: fs::write(c.0.join("source"), b"abcdef").unwrap();
384추가: for allow in [false, true] {
385추가: let mut start = c.request(&["source"]);
386추가: start.limits.output = 5;
387추가: let message = Message::StartGuarded(GuardedStart {
388추가: ceiling: Limits {
389추가: output: 6,
390추가: ..start.limits
391추가: },
392추가: start,
393추가: interactive: false,
394추가: });
395추가: let mut questions = 0;
396추가: let events = c.run_with(&mut c.command(), message, |event| {
397추가: if let Message::ResourceRequired {
398추가: challenge_id,
399추가: action,
400추가: scope,
401추가: ..
402추가: } = event
403추가: {
404추가: assert_eq!(*action, ActionKind::CreateSevenZip);
405추가: questions += 1;
406추가: vec![Message::ResourceReply {
407추가: challenge_id: *challenge_id,
408추가: scope: *scope,
409추가: allow,
410추가: }]
411추가: } else {
412추가: Vec::new()
413추가: }
414추가: });
415추가: assert_eq!(questions, 1);
416추가: if allow {
417추가: success(&events);
418추가: fs::remove_file(c.0.join("result.7z")).unwrap();
419추가: } else {
420추가: failure(&events, ErrorCode::None);
421추가: assert!(!c.0.join("result.7z").exists());
422추가: }
423추가: }
424추가: }
425추가:
426추가: #[test]
427추가: fn cancel_during_snapshot_or_encoding_publishes_nothing() {
428추가: for stage in [Stage::Read, Stage::Write] {
429추가: let c = Case::new();
430추가: fs::File::create(c.0.join("source"))
431추가: .unwrap()
432추가: .set_len(128 * 1024 * 1024)
433추가: .unwrap();
434추가: let mut sent = false;
435추가: let events = c.run_with(
436추가: &mut c.command(),
437추가: Message::Start(c.request(&["source"])),
438추가: |event| {
439추가: if !sent
440추가: && matches!(event, Message::Progress { stage: actual, processed_bytes, .. } if *actual == stage && (stage == Stage::Read || *processed_bytes > 0))
441추가: {
442추가: sent = true;
443추가: vec![Message::Cancel]
444추가: } else {
445추가: Vec::new()
446추가: }
447추가: },
448추가: );
449추가: assert!(sent);
450추가: failure(&events, ErrorCode::None);
451추가: assert!(!c.0.join("result.7z").exists());
452추가: assert!(events.iter().any(|e| matches!(
453추가: e,
454추가: Message::CancelAck {
455추가: status: CancelStatus::Requested,
456추가: ..
457추가: }
458추가: )));
459추가: }
460추가: }
461추가:
462추가: #[cfg(target_os = "linux")]
463추가: fn shim(c: &Case, file: &str) -> PathBuf {
464추가: let output = c.0.join("fault.so");
465추가: let status = Command::new("cc")
466추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
467추가: .arg(
468추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
469추가: .join("../../tests/rust-archive-worker")
470추가: .join(file),
471추가: )
472추가: .args(["-ldl", "-o"])
473추가: .arg(&output)
474추가: .status()
475추가: .unwrap();
476추가: assert!(status.success());
477추가: output
478추가: }
479추가:
480추가: #[cfg(target_os = "linux")]
481추가: #[test]
482추가: fn storage_failures_keep_real_publication_and_cleanup_state() {
483추가: for fault in [
484추가: "temp-full",
485추가: "space-stage",
486추가: "create-full",
487추가: "create-denied",
488추가: "full",
489추가: "write-io",
490추가: "sync-full",
491추가: "dir-sync-full",
492추가: ] {
493추가: let c = Case::new();
494추가: fs::write(c.0.join("source"), b"a".repeat(100_000)).unwrap();
495추가: let mut command = c.command();
496추가: command
497추가: .env("LD_PRELOAD", shim(&c, "io_fault.c"))
498추가: .env("ZIPELO_TEST_FAULT", fault)
499추가: .env("ZIPELO_TEST_MARKER", c.0.join("marker"));
500추가: let events = c.run_with(&mut command, Message::Start(c.request(&["source"])), |_| {
501추가: Vec::new()
502추가: });
503추가: let error = if matches!(fault, "create-denied" | "write-io") {
504추가: ErrorCode::Io
505추가: } else {
506추가: ErrorCode::DiskFull
507추가: };
508추가: if fault == "dir-sync-full" {
509추가: let t = terminal(&events);
510추가: assert_eq!(t.error, error, "{events:?}");
511추가: assert_eq!(t.outcome, Outcome::Failed);
512추가: assert_eq!(t.created_count, 1);
513추가: assert_eq!(t.durability, Durability::Failed);
514추가: assert!(c.0.join("result.7z").is_file());
515추가: } else {
516추가: failure(&events, error);
517추가: assert!(!c.0.join("result.7z").exists());
518추가: }
519추가: assert!(!fs::read_dir(&c.0).unwrap().any(|entry| {
520추가: entry
521추가: .unwrap()
522추가: .file_name()
523추가: .to_string_lossy()
524추가: .starts_with(".zipelo-")
525추가: }));
526추가: }
527추가: }
528추가:
529추가: #[cfg(target_os = "linux")]
530추가: #[test]
531추가: fn source_changes_new_destination_and_cancel_before_publication_are_preserved() {
532추가: for operation in ["source", "destination", "cancel"] {
533추가: let c = Case::new();
534추가: fs::write(c.0.join("source"), b"a".repeat(100_000)).unwrap();
535추가: let marker = c.0.join("marker");
536추가: let release = c.0.join("release");
537추가: let mut command = c.command();
538추가: command
539추가: .env("LD_PRELOAD", shim(&c, "io_fault.c"))
540추가: .env("ZIPELO_TEST_FAULT", "pause")
541추가: .env("ZIPELO_TEST_MARKER", &marker)
542추가: .env("ZIPELO_TEST_RELEASE", &release);
543추가: let mut changed = false;
544추가: let events = c.run_with(
545추가: &mut command,
546추가: Message::Start(c.request(&["source"])),
547추가: |event| {
548추가: if !changed
549추가: && matches!(
550추가: event,
551추가: Message::Progress {
552추가: stage: Stage::Write,
553추가: total_bytes: Some(_),
554추가: ..
555추가: }
556추가: )
557추가: {
558추가: let until = std::time::Instant::now() + Duration::from_secs(5);
559추가: while !marker.exists() {
560추가: assert!(std::time::Instant::now() < until);
561추가: std::thread::sleep(Duration::from_millis(2));
562추가: }
563추가: match operation {
564추가: "source" => fs::write(c.0.join("source"), b"changed").unwrap(),
565추가: "destination" => fs::write(c.0.join("result.7z"), b"user data").unwrap(),
566추가: _ => {}
567추가: }
568추가: changed = true;
569추가: let replies = if operation == "cancel" {
570추가: vec![Message::Cancel]
571추가: } else {
572추가: Vec::new()
573추가: };
574추가: fs::write(&release, b"resume").unwrap();
575추가: replies
576추가: } else {
577추가: Vec::new()
578추가: }
579추가: },
580추가: );
581추가: assert!(changed);
582추가: failure(
583추가: &events,
584추가: match operation {
585추가: "source" => ErrorCode::SourceChanged,
586추가: "destination" => ErrorCode::Conflict,
587추가: _ => ErrorCode::None,
588추가: },
589추가: );
590추가: if operation == "destination" {
591추가: assert_eq!(fs::read(c.0.join("result.7z")).unwrap(), b"user data");
592추가: } else {
593추가: assert!(!c.0.join("result.7z").exists());
594추가: }
595추가: }
596추가: }
597추가:
598추가: #[cfg(target_os = "linux")]
599추가: #[test]
600추가: fn encoder_finish_header_write_seek_and_patch_errors_publish_nothing() {
601추가: for fault in [
602추가: "encode-full",
603추가: "finish-full",
604추가: "header-write",
605추가: "header-seek",
606추가: "header-patch",
607추가: ] {
608추가: let c = Case::new();
609추가: fs::write(
610추가: c.0.join("source"),
611추가: b"x".repeat(if fault == "encode-full" {
612추가: 3 * 1024 * 1024
613추가: } else {
614추가: 123
615추가: }),
616추가: )
617추가: .unwrap();
618추가: let mut command = c.command();
619추가: command
620추가: .env("LD_PRELOAD", shim(&c, "seven_zip_create_fault.c"))
621추가: .env("ZIPELO_7Z_FAULT", fault);
622추가: let events = c.run_with(&mut command, Message::Start(c.request(&["source"])), |_| {
623추가: Vec::new()
624추가: });
625추가: failure(
626추가: &events,
627추가: if fault.ends_with("full") {
628추가: ErrorCode::DiskFull
629추가: } else {
630추가: ErrorCode::Io
631추가: },
632추가: );
633추가: assert!(!c.0.join("result.7z").exists());
634추가: }
635추가: }
636추가:
637추가: #[cfg(target_os = "linux")]
638추가: #[test]
639추가: fn gigabyte_creation_stays_below_64_mib_peak_rss() {
640추가: assert!(
641추가: Command::new("python3")
642추가: .arg(
643추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
644추가: .join("../../tests/rust-archive-worker/seven_zip_create_memory.py")
645추가: )
646추가: .arg(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
647추가: .status()
648추가: .unwrap()
649추가: .success()
650추가: );
651추가: }