team-ljyzipelo

공개

Merge pull request #127 from Team-LJY/features/sevenzip-create

LZMA2 7z 생성과 형식 선택 지원
작성자
LeeJunyoung
작성 시각
커밋
23eb52d0f31aae84929bdbd0d72481ba5b714133
이 시점의 파일 보기

변경된 파일 35개

+2,016-82

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

추가docs/sevenzip-create-design.md+90-0
@@ -0,0 +1,90 @@
1추가: # 7z 생성 설계와 작업자 계약안
2추가:
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-진행과-완료-판단)을 따른다.
4추가:
5추가: ## 1. 이번 지원 범위
6추가:
7추가: - 생성 형식은 단일 .7z이고 기본 압축은 LZMA2다. 일반 파일, 한글을 포함한 UTF-8 상대 이름, 빈 파일과 모든 폴더 항목을 보존한다. 원본 폴더를 지정하면 그 이름 아래의 상대 구조를 보존한다.
8추가: - non-solid로 고정한다. 데이터가 있는 파일마다 독립된 LZMA2 coder와 pack stream을 만들고 파일 사이에 사전을 공유하지 않는다. 파일을 골라 풀 때 선행 파일을 처리하지 않으며 여러 파일의 압축률 최적화는 후속 범위다.
9추가: - 본문 암호화와 헤더 암호화는 지원하지 않는다. 파일명도 공개된다. 암호가 필요한 사용자는 기존 AES ZIP 생성을 사용한다. 7z를 선택한 상태에서 암호를 무시하거나 ZIP으로 바꾸어 저장하지 않는다.
10추가: - solid, 암호화, 분할 생성, SFX, 기존 아카이브 수정, 필터 체인과 사용자 지정 사전/스레드/압축 등급은 이번 범위에서 제외한다. 링크와 특수 파일을 일반 파일로 변환하지 않는다. RAR 제외 결정을 유지한다.
11추가: - 파일 내용과 상대 경로, 빈 파일/폴더 구조가 보존 대상이다. 원본 소유자, ACL, xattr와 모든 시각/실행 권한의 복원 및 생성 바이트의 재현성은 약속하지 않는다.
12추가:
13추가: ## 2. 라이브러리 선택과 고지
14추가:
15추가: 선택안은 이미 고정된 lzma-rust2 =0.25.0을 유지하고 std,xz에 encoder 기능만 더하는 것이다. 이 구현에서 해당 기능을 활성화했으며 lockfile 패키지는 추가하지 않았다. 컨테이너는 아래의 좁은 7z 작성기를 자체 MIT 코드로 구현한다. 압축 알고리즘 자체를 새로 구현하거나 외부 7z 명령을 제품에서 호출하지 않는다.
16추가:
17추가: - [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)을 함께 확인했다.
18추가: - [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 등도 추가된다. 넓은 작성기 대신 기존 입력/예산/취소 정책에 맞춘 작은 컨테이너를 우선 검토한다. 이는 크기나 성능을 측정해 얻은 결론은 아니다.
19추가: - 기존 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추가: - 2026-11-14 OSV의 패키지/버전 조회는 권고를 반환하지 않았고 RustSec 패키지명 검색 결과도 없었다. 전체 최신 의존성 권고 DB 감사는 하지 않았다. 새 encoder 실행 시험은 아래 검증 범위를 따른다. 구현 PR에서 고정 버전과 실제 기능 트리의 RustSec 권고 적용 여부를 다시 확인하고 확인 불가 항목을 기록한다. 후보 선택만으로 취약점 부재나 배포 적합성을 선언하지 않는다.
21추가: - 도입 PR에는 선택 이유와 정확한 활성 기능을 적는다. packaging/licenses.py의 실제 작업자 Cargo.lock 고지에 lzma-rust2의 버전, Apache 원문과 원문 해시가 포함되는지 회귀로 확인한다. encoder 추가 전후의 전이 의존성을 비교하고 새 원문이 빠지면 배포 검증을 실패시킨다. 고지 생성기의 공용 변경이 필요하면 담당 범위를 합의한 뒤 수정한다. 이 구현에서는 기존 패키지의 encoder 기능만 켰으며 실제 고지 원문과 해시 및 기능 제한 회귀를 실행한다.
22추가:
23추가: ## 3. 작성기와 헤더
24추가:
25추가: - 입력 수집은 create_sources::Plan과 Source, 검증한 파일 핸들 및 spool::Snapshot을 재사용한다. 라이브러리에 원본 경로를 넘겨 다시 열거나 자체 디렉터리 탐색을 시키지 않는다. 원본은 읽기 전용으로 열며 사용자가 고른 출력 경로를 쓰기/자르기로 직접 열지 않는다.
26추가: - 단일 스레드 Lzma2Writer를 사용하고 preset 1에서 사전을 1 MiB로 명시한다. 사용자 옵션으로 확대하지 않는다. 새 인코더는 이전 파일의 상태를 유지하지 않는다. [upstream 작성기와 메모리 추정 API](https://docs.rs/crate/lzma-rust2/latest/source/src/enc/lzma2_writer.rs)를 근거로 인코더 생성 전 추정치의 KiB를 checked 연산으로 바꾸고 32 MiB 이내인지 확인한다. 실제 RSS 목표와는 구분한다.
27추가: - 시그니처/StartHeader와 CRC, PackInfo, UnpackInfo, SubStreamsInfo, FilesInfo 및 EOF의 비압축 NextHeader를 작성한다. LZMA2 coder ID는 0x21이며 실제 사전 설정과 맞는 속성을 쓴다. 각 데이터 스트림의 압축/원본 크기와 CRC32를 기록한다. CRC32는 이미 사용하는 zlib-rs를 재사용한다. 오프셋, 길이 합계와 헤더 길이는 u64 checked 연산으로 처리한다.
28추가: - 파일명은 유효한 UTF-8 계획에서 UTF-16LE로 변환한다. 빈 파일/폴더에는 데이터 스트림을 만들지 않고 EmptyStream과 EmptyFile 구분 및 디렉터리 속성을 기록한다. 원본 파일이 없고 빈 폴더만 있는 묶음도 유효하게 작성한다. 빈 원본 목록 자체는 InvalidRequest로 거부한다.
29추가: - [공식 7z 형식 안내](https://www.7-zip.org/7z.html)와 기존 seven_zip.rs 해독기가 처리하는 기본 구조만 사용한다. encoded header, external metadata, additional streams와 anti 항목은 생성하지 않는다. LZMA2 내부의 비압축 청크는 허용하지만 별도 Copy 압축 선택은 추가하지 않는다.
30추가: - finish와 헤더 패치의 모든 오류를 반환하고 성공 여부를 Drop에 의존하지 않는다. 완성한 비공개 파일을 기존 7z 구조 검사기로 열어 시작/다음 헤더 CRC, 스트림 범위와 계획의 이름/종류/길이를 대조한 뒤 게시한다. 이 검사는 전체 payload를 다시 해독하는 무결성 검증을 뜻하지 않는다. 전체 해독과 원본 해시 대조는 아래 수용 시험에서 수행한다.
31추가: - 지원 부분의 헤더를 직접 유지하는 비용은 남는다. 계약 동의 후 첫 구현에서 독립 도구의 기본/빈 항목 호환과 인코더 메모리/취소 경계를 먼저 검증한다. 통과하지 않으면 지원 범위를 몰래 바꾸지 않고 이 PR에서 후보 및 계약을 다시 협의한다.
32추가:
33추가: ## 4. 작업자와 앱 계약안
34추가:
35추가: 현재 기준은 과거 C# 문서가 아닌 [작업자 README](../experiments/rust-archive-worker/README.md), protocol.rs, wire.rs와 contract.json이다. 아래 확장 계약은 합의되었고 공용 타입과 바이트 인코딩은 반영했다. 작업자와 앱 연동의 구현 상태는 위 상태 및 contract.json의 seven_zip_create.status로 구분한다.
36추가:
37추가: ### 요청과 바이트 순서
38추가:
39추가: - Action과 ActionKind 끝에 CreateSevenZip=4를 추가한다. List=0, Extract=1, CreateZip=2, Preview=3과 기존 Format::SevenZip=4는 유지한다. 프레임 ZAW1의 version=1, 32바이트 헤더, 1 MiB 본문 상한과 종류 번호는 바꾸지 않는다.
40추가: - 새 action의 필드 순서는 sources:Vec<Source>, output_file:NativePath, method:SevenZipMethod, solid:bool, encryption:Encryption이다. Source는 기존 path:NativePath, archive_name:UTF-8 String 순서다. Vec/String의 u32 길이, 정수 little-endian과 NativePath 인코딩도 유지한다. sources와 NativePath 벡터의 기존 32,768개 상한, String의 32,768 UTF-8 바이트 상한과 전체 프레임 상한을 유지하며 자원 승인으로 전송 상한을 늘리지 않는다.
41추가: - SevenZipMethod는 별도 u8 enum으로 Lzma2=0만 정의한다. ZIP의 Method(Store=0, Deflate=1)는 변경하지 않는다. solid의 지원 값은 false이고 encryption은 기존 None=0만 지원한다. 기존 Aes256=1과 solid=true를 구조상 유효한 요청으로 받더라도 Accepted 뒤 UnsupportedFeature로 끝내며, 원본 탐색, 자원 질문, 암호 질문과 출력 생성은 시작하지 않는다. 알 수 없는 enum/bool 값과 잔여 본문은 기존대로 Protocol이다.
42추가: - 일반 Start(kind 1)와 StartGuarded(kind 6, interactive=false)에 허용한다. StartInteractive와 interactive=true에는 허용하지 않는다. 앱은 기본 생성 요청부터 기존 큰 작업 승인 경로인 StartGuarded를 사용한다. 제한을 낮추는 기존 Start 호출은 자원 질문 없이 유지한다.
43추가: - output_file은 사용자가 고른 절대 파일 경로다. 형식은 action으로 결정하며 확장자로 ZIP 생성에 우회하지 않는다. 앱의 운영체제 기본 저장 창은 .7z 형식을 제안한다. 기존 목적지가 있으면 ZIP 생성과 같이 Conflict로 중단하며 이 단계에서는 덮어쓰기 질문/승인이나 자동 이름 변경을 추가하지 않는다.
44추가: - 구버전 앱/작업자는 새 action을 거부할 수 있다. 앱과 작업자를 같은 빌드로 배포하고 실패 시 ZIP/일반 Start/다른 작업자에 자동 재시도하지 않는다. 계약 동의 뒤 공용 타입, codec, contract.json과 앱 변환을 함께 갱신한다.
45추가:
46추가: ### 이벤트와 완료 판단
47추가:
48추가: - Accepted.action과 ResourceRequired.action에 CreateSevenZip=4를 사용한다. 이 action의 Accepted.encryption은 false다. 기존 ZIP 및 다른 action의 암호 capability 의미는 유지한다. 새 메시지, 오류 코드와 별도 대형 결과 전송은 추가하지 않는다.
49추가: - 기존 ResourceRequired/Reply, Progress, Output, Cancel/CancelAck와 Terminal을 사용한다. 7z 생성에는 PasswordRequired와 ConflictRequired를 보내지 않는다. 질문 응답의 job_id/challenge_id/scope와 오래된 응답 거부 규칙을 유지한다.
50추가: - Scan은 계획 수집, Read는 스냅샷 입력, Write는 인코딩/스테이징/목적지 복사, Verify는 헤더/계획 검사, Commit은 게시 단계다. 원본 합계가 확정되면 읽기의 total_bytes에 사용한다. 압축 결과 길이나 검증 총량을 모르면 None으로 두고 진행률을 추측하지 않는다. 단계별 바이트를 원본 크기에 중복 합산하지 않는다.
51추가: - 정상 Output은 entry_id=None, relative_name=실제 목적지 기본 이름, disposition=Created 한 개다. 그 전에는 내부 파일마다 Output을 보내지 않는다. 정상 Terminal은 Completed, error=None, publication=Complete, created_count=1이며 정리 및 플랫폼 내구성은 실제 결과를 따른다.
52추가: - 게시 전 실패/취소에는 정상 Output이 없어야 하며 publication=None, created_count=0이다. 작업 소유 목적지 임시 파일의 정리가 실패하면 기존 PartialRetained 및 retained_partial_count/cleanup으로 실제 이름을 보고한다. 게시 후 동기화/정리 실패와 불명확한 게시에는 기존 Failed, Uncertain/CommitUncertain 및 실제 출력 집계를 유지한다. 성공이나 파일 부재를 합성하지 않는다.
53추가: - 앱은 일치하는 Terminal, stdout/stderr EOF와 소유 자식 회수를 모두 확인한 뒤 결과를 확정한다. CancelAck는 취소 완료가 아니며 게시 직전 cutoff 뒤의 TooLate와 실제 게시 결과를 우선한다. 작업자 사망이나 늦은 취소로 저장 완료를 취소 또는 자동 rollback으로 바꾸지 않는다.
54추가:
55추가: ## 5. 입력, 자원과 취소
56추가:
57추가: - ZIP과 같은 원본 계획을 사용한다. 파일/폴더 모두 항목 수에 포함하며 파일 논리 바이트 합계에 min(limits.input,limits.output)을 적용한다. 기본은 16 GiB/10,000개, 유효한 자원 승인 뒤에는 요청한 ceiling 안에서 최대 64 GiB/200,000개다. 압축된 생성물 길이를 논리 원본 합계 대신 승인 기준으로 삼지 않는다.
58추가: - 기존 64개 경로 구성 요소, 승인 전 8 MiB/32,768 노드 및 승인 뒤 64 MiB/262,144 노드 메타데이터 예산을 유지한다. UTF-16 이름, 스트림 정보, CRC와 오프셋 배열 및 헤더 버퍼도 할당 전에 예산에 반영한다. 입력 전체나 파일 전체를 메모리 배열에 담지 않고 현재 파일만 64 KiB 이하로 복사한다.
59추가: - Plan의 경로 안전, 이름/접두 경로 및 대소문자 충돌, 원본 객체/종류/크기/수정 시각 대조를 재사용한다. 심볼릭 링크, reparse point, 특수 파일과 안전하지 않은 이름은 전체 작업을 거부한다. 탐색 뒤 교체와 감지된 변경은 SourceChanged다. 전체 폴더 트리의 원자적 스냅샷이나 같은 길이/시각으로 위장한 모든 변경 감지를 약속하지 않는다.
60추가: - 원본 사본, 압축 결과와 게시용 복사본의 동시 공간을 볼륨별로 계산한다. LZMA2 청크는 최소 1바이트의 원본당 최대 3바이트 순증과 종료 1바이트를 허용하는 4*길이+1의 보수적 상한을 checked 연산으로 검사하고 각 실제 쓰기 전에도 여유 공간을 확인한다. 사전 확인은 공간 예약이 아니며 ENOSPC는 DiskFull, 그 밖의 저장 오류는 Io로 유지한다. 생성물 및 디스크 공간을 원본 바이트 예산과 혼동하지 않는다.
61추가: - 승인 전 전체 300초, 승인 뒤 실제 진행이 없는 60초와 질문 응답 대기 300초 정책을 유지한다. 성공한 읽기/압축 쓰기/헤더 처리/계획 검증과 정리만 실제 활동으로 기록한다. 단순 check나 UI 알림으로 시간을 연장하지 않는다.
62추가: - 입력 청크, 인코더 출력, 파일 경계, finish 전후, 헤더 seek/패치와 게시 직전에 취소 및 부모 생존을 확인한다. 압축 출력 Writer에도 감시기를 연결해 라이브러리 내부 쓰기 오류의 원인을 보존한다. 단일 스레드 인코더 한 호출 안의 CPU 처리와 OS 블로킹 I/O를 즉시 강제 중단한다고 보장하지 않는다. 부모/취소 확인 간격과 작은 파일 다수의 응답성도 시험한다.
63추가: - 1 MiB 사전의 대표 1 GiB 표본에서 기존 64 MiB 피크 RSS 목표를 측정한다. 큰 작업 허용은 인코더 사전/스레드를 늘리는 승인이 아니며 프로세스 전체 메모리의 강제 상한을 뜻하지 않는다.
64추가:
65추가: ## 6. 저장과 정리
66추가:
67추가: 1. 목적지 부모를 기존 Dir로 고정하고 경로/기존 목적지를 사전 검사한다. 원본과 같은 이름, 기존 파일/링크에는 쓰지 않는다.
68추가: 2. 원본 계획과 소스 스냅샷을 만들고 비공개 spool 임시 파일에 완성된 7z를 작성한다. finish, 구조 검사와 Plan::verify가 실패하면 게시하지 않는다.
69추가: 3. 완성 길이에 맞춰 목적지 공간을 확인하고 기존 publish_reader_steps의 새 파일 경로(replace=None)에 전달한다. 파일 sync와 close 오류를 확인한 뒤 배타적으로 게시한다. 사전검사 뒤 나타난 목적지도 Conflict로 거부한다.
70추가: 4. 게시 직전에도 계획과 취소를 확인한다. 원본 폴더 안에 저장할 때는 게시 임시 파일 부모의 객체 ID를 계획과 대조하고, 그 폴더만 수정 시각 대신 원래 자식 목록을 다시 확인한다. 원래 목록은 탐색 때 이미 예산에 반영한 이름을 보존한다. 게시자가 열린 파일에서 기록한 정확한 임시 이름과 객체 ID 하나만 제외하며, 같은 접두 이름의 사용자 파일, 원본 추가/누락/이름 변경과 기존 항목의 객체/종류/크기/수정 시각 변경은 거부한다. 열거 전후 폴더 시각이 바뀌어도 거부한다. 확인과 게시 사이의 원자적 트랜잭션이나 잠깐 추가됐다 사라진 항목까지 감지한다고 약속하지 않는다. 게시 후 부모 sync와 정리 결과를 실제 내구성/부분 출력으로 보고한다. 불명확한 결과를 덮어 재시도하지 않는다.
71추가: 5. 비공개 입력/생성물은 핸들을 닫아 제거하고 목적지 임시 파일만 기존 소유 확인 정책으로 정리한다. 무관한 파일이나 이미 게시한 파일을 삭제하지 않는다. 강제 종료/전원 손실 뒤 자동 정리까지 보장하지 않는다.
72추가:
73추가: ## 7. 구현 후 수용 시험
74추가:
75추가: 아래는 수용 시험 기준이다. Linux에서 새 정수/비트맵과 인코딩 경계, 독립 7-Zip 26.00/Zipelo의 한글/보조 평면 이름 및 빈 구조 왕복, 취소/쓰기/finish/헤더 seek와 패치/게시 실패를 검증했다. 1 GiB 대표 생성은 11,168 KiB RSS와 약 20.8초를 기록했다. 이는 단일 표본 측정이며 모든 입력의 성능이나 OS 강제 상한이 아니다. 전체 local, 라이선스 시험과 플랫폼별 수행 결과는 PR 본문과 tests/work/7zc의 로그를 따른다. 71aa755의 Windows/Wayland 실제 생성 통합은 PR 본문에 기록되어 있다. 내부 저장 오탐 수정 뒤의 GUI 실기는 재실행하지 않았으며 독립 재리뷰는 남았다. 시험 코드는 루트 tests/에만 두며 일회성 자료, 도구, 캐시와 로그는 tests/work/7zc 한 곳에 모은다. TMPDIR과 CARGO_TARGET_DIR을 그 하위에 명시하고 사본 안에 작업 폴더나 빌드 캐시를 다시 만들지 않는다. PR 병합/종료 뒤 담당자가 정리한다.
76추가:
77추가: - 일반 파일, 압축되는/난수 내용, 한글 및 여러 단계 경로, 혼합 파일/폴더, 빈 파일, 빈 폴더, 빈 폴더만 있는 묶음과 여러 최상위 원본을 만든다. Zipelo 목록/해제와 독립 7-Zip의 테스트/목록/해제를 각각 실행해 상대 경로, 항목 종류, 파일 크기와 SHA256을 원본 manifest와 대조한다. 압축 아카이브 바이트 자체의 일치는 요구하지 않는다.
78추가: - 독립 설계 리뷰의 후속 기준으로 MainStreamsInfo/kEnd 계층, 32바이트 기준 NextHeaderOffset, 가변 UINT64와 고정 REAL_UINT64 구분을 확인한다. EmptyFile 비트 수는 전체 파일 수가 아닌 empty stream 수이며 혼합 빈 항목 7/8/9개와 정수 경계 127/128, 16383/16384를 포함한다.
79추가: - 독립 도구의 상세 목록으로 LZMA2, non-solid와 비암호화를 확인한다. 헤더/스트림 CRC와 작은 경계, 64 KiB 경계, 4 GiB 크기/오프셋 인코딩 및 비압축 헤더 상한을 시험한다. 큰 수치는 축소 상한/메타데이터 표본 검증과 실제 대용량 실행을 구분한다.
80추가: - 자원 기본/승인 경계, 거부와 취소, 파일/폴더 수 합산, 메타데이터 및 산술 오버플로, 위험 경로, 링크/특수 파일, 원본/부모 교체, 목적지 새 파일 출현과 기존 파일 보존을 검증한다. 파일 크기와 무관하게 큰 배열이 생기지 않는지 확인한다.
81추가: - 캡처/압축/finish/헤더 패치/게시 직전 취소, 부모 종료, 임시/목적지 디스크 부족, write/seek/sync/close/게시/정리 실패를 주입한다. 게시 전에는 완성 파일이 없어야 하며 실패/취소를 Completed로 표시하지 않아야 한다. 게시 뒤 실패와 강제 종료에서는 실제 게시 및 정리 상태를 대조한다.
82추가: - codec 양방향 및 잘린 본문/알 수 없는 tag/잔여 필드, solid/암호화 미지원, 암호/충돌 질문 부재, 구버전 거부의 무자동재시도, job/challenge/sequence/종료 중복과 EOF/자식 회수 오류를 시험한다. 기존 ZIP의 Store/Deflate/AES 생성과 해제는 회귀를 유지한다.
83추가: - 최종 구현에서 python3 tests/ci/run_rust.py local 결과와 라이선스 고지 시험, 메모리/취소 근거를 PR 본문에 적는다. Linux 시험과 Windows 교차 빌드를 Windows 실제 실행과 구분한다. Windows와 Wayland의 기본 파일/폴더 선택, 형식 선택과 저장, 미지원 암호 안내, 큰 작업 허용, 취소와 실패 화면은 별도로 확인한다.
84추가:
85추가: ## 8. 합의와 담당 인계
86추가:
87추가: - 하나는 이 계약과 backend 작성기, 공용 타입/codec 및 작업자 회귀를 담당한다. 히나타의 계약 동의와 카논의 설계 리뷰가 확인되어 공용 타입 인계 단계에 착수했다. 실제 작성기를 반영했으며 새 파일로 Windows/Wayland 통합 검증을 인계한다.
88추가: - 계약 동의 뒤 공용 타입 반영 커밋을 히나타에게 전달한다. 히나타는 기존 생성 화면의 ZIP/7z 형식 선택, .7z 기본 저장 형식, 암호/방식 선택 제한, 새 ActionKind 변환과 수신 검증을 담당한다. 화면이 바뀌는 구현 PR에 --ui-scenario 목록/시험과 docs/ui-scenario-guide.md를 함께 갱신한다. 별도 디자인 변경이나 애니메이션을 추가하지 않는다.
89추가: - 카논의 설계와 실패 경계 리뷰는 완료되었으며 구현 후 독립 7-Zip 호환 검증 및 재리뷰는 별도 요청한다. 도구 버전/옵션, 원본과 해제 manifest 및 플랫폼별 실행 범위를 남긴다. 도구를 제품에 번들하지 않는다.
90추가: - 설계 문서의 정적 검토와 링크/공백 검사는 제품 빌드나 호환 검증이 아니다. 이번 backend 추가분은 UI 변경 없음이다. 같은 PR의 형식 선택과 시나리오는 이미 반영되었고 71aa755에서 Windows/Wayland 실제 파일 통합을 확인했다. 내부 저장 오탐 수정 뒤 독립 재리뷰가 끝날 때까지 초안을 유지한다.
수정docs/ui-scenario-guide.md+11-0
@@ -181,3 +181,14 @@ Ubuntu 제거 안내는 패키지 관리자 터미널 출력입니다. 이전
181181- split-source-changed: 목록 이후 조각 변경 시 다시 열기 안내.
182182
183183운영체제 기본 열기 창에서 같은 폴더의 첫 조각 `.7z.001`을 선택한다. 분할 묶음은 최대 999개이며 목록 열람 성공은 전체 데이터 무결성 검증 완료를 뜻하지 않는다. 실제 분할 파일 처리는 작업자 구현 후 독립 도구 표본으로 확인한다. Windows와 Wayland에서 첫 조각 선택, 누락 이름, .001 재시도 안내와 닫기를 확인하며, 위 디자인 상황은 실제 파일 검증을 대신하지 않는다.
184추가:
185추가: ## 7z 만들기 상황
186추가:
187추가: - create-sevenzip: 기존 만들기 창의 ZIP/7z 선택, LZMA2 고정과 암호 미지원 안내.
188추가: - create-sevenzip-progress: 7z 생성 진행과 취소 버튼.
189추가: - create-sevenzip-complete: 7z 파일의 저장 완료와 실제 저장 경로.
190추가: - create-sevenzip-error: 7z 저장 실패와 재시도.
191추가: - create-sevenzip-cancelled: 게시 전 취소 완료와 출력 없음.
192추가: - create-sevenzip-resource: 7z 생성의 큰 작업 허용 질문.
193추가:
194추가: 7z를 선택하면 입력한 ZIP 암호와 실행 취소 기록을 지우며, ZIP으로 돌아와도 암호를 복원하지 않는다. 기본 저장 창은 .7z를 제안하며 암호가 필요하면 ZIP을 선택한다. 이 상황들은 가짜 작업자로 화면을 구성하므로 실제 7z 생성과 독립 도구 호환 시험을 대신하지 않는다.
수정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+16-2
@@ -1,6 +1,6 @@
11# Rust archive worker
22
3삭제: 별도 프로세스의 stdin/stdout으로 revision 3 요청을 처리합니다. 제품 앱이 공유 codec으로 연결하며 프로세스 분리는 OS sandbox를 뜻하지 않습니다. 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다.
3추가: 별도 프로세스의 stdin/stdout으로 revision 3 요청을 처리합니다. 제품 앱이 공유 codec으로 연결하며 프로세스 분리는 OS sandbox를 뜻하지 않습니다. 기존 작업의 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다.
44
55- ZIP32/ZIP64 Store/Deflate 목록과 해제, ZIP32/ZIP64 생성, 기본 TAR/USTAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. 다중 볼륨, UTF-8로 해석할 수 없는 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다.
66- ZIP 이름: UTF-8 플래그(비트 11)가 있으면 이름이 UTF-8이어야 하며 아니면 Integrity입니다. 플래그가 없으면 CRC가 원래 이름과 맞는 Info-ZIP Unicode Path 확장 필드(0x7075, 버전 1)를 우선 쓰고, 다음으로 UTF-8로 유효한 이름 바이트를 그대로 씁니다(Linux/macOS 도구의 기본 동작). CRC가 다르거나 버전이 다른 확장 필드는 무시합니다. 그 밖의 CP437/CP949 등 레거시 이름은 코드 페이지를 추측하지 않고 UnsupportedFeature로 거부합니다. 어느 경로로 얻은 이름이든 같은 경로 안전성 검사와 충돌 검사를 거칩니다.
@@ -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,6 +69,20 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
6969
70707z의 Copy/LZMA/LZMA2 입력과 solid 출력은 고정 버퍼와 임시 파일로 처리합니다. 모든 폴더와 하위 스트림의 CRC와 크기 검증이 끝난 뒤 기존 게시 경로를 사용합니다. ZIP 생성의 압축 및 AES 처리도 64 KiB 버퍼를 사용하며 여유 공간 사전 검사와 실제 쓰기의 DiskFull 구분을 적용합니다. 공간 예약을 보장하지 않으므로 다른 프로세스와의 경쟁으로 쓰기가 실패할 수 있습니다.
7171
72추가: ## 7z 생성
73추가:
74추가: [합의된 설계](../../docs/sevenzip-create-design.md)의 단일 .7z 작성을 구현했습니다. 압축 방식은 LZMA2, 1 MiB 사전과 non-solid이며 본문/헤더 암호화, 분할 생성과 SFX는 지원하지 않습니다. 원본 파일과 폴더, 한글 및 UTF-16 보조 평면 이름, 빈 파일과 빈 폴더를 보존합니다. RAR 제외 정책은 유지합니다.
75추가:
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 실제 생성 통합 검증과 독립 리뷰는 별도입니다.
85추가:
7286## ZIP 생성 입력
7387
7488원본에 일반 파일과 폴더를 함께 지정할 수 있습니다. 각 archive_name을 최상위 이름으로 쓰고 폴더 안의 상대 경로와 빈 폴더를 보존합니다. 재귀 수집된 파일과 폴더 모두 항목 수 한도에 포함하며 파일 크기 합계에는 기존 16 GiB 기본 한도를 적용합니다. 이름 충돌과 한도는 암호 요청 전에 검사합니다.
수정experiments/rust-archive-worker/contract.json+30-2
@@ -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.",
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.",
@@ -35,7 +35,7 @@
3535 "ResourceReply": "Kind 7: challenge_id:u64,scope:ResourceScope,allow:bool. Frame job_id and exact outstanding challenge_id/scope must match once. Reject premature, stale, duplicate and cross-kind replies as Protocol. False cancels the job without further processing."
3636 },
3737 "events": {
38삭제: "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation.",
38추가: "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation. CreateSevenZip explicitly reports encryption=false; existing action capabilities are unchanged.",
3939 "Entry": "entry_id, name, kind File|Directory|Link|Other, declared sizes, encrypted; ordinal u32 IDs belong to this List job only until its ListEnd token and Completed Terminal are confirmed. Metadata only, no CRC success claim.",
4040 "ListEnd": "entry_count:u32 and list_id:ListId for a complete listing. Entry IDs are deterministic zero-based ordinals in archive traversal order. App associates this token with this job entries only after Completed Terminal, both stream EOFs and successful child wait/exit.",
4141 "PasswordRequired": "challenge_id, attempt and purpose Decrypt|Encrypt; no secret diagnostics.",
@@ -239,5 +239,33 @@
239239 "metadata": "Only after a valid ResourceReply(allow=true) for this job, select 64 MiB MetadataBudget and 262144 nodes, including ZIP/TAR/7z parsing, decoded 7z headers, XZ index/block bounds, member/path validation, implicit output parents and source planning. Legacy Start/StartInteractive, unapproved guarded jobs and slice APIs keep 8 MiB and 32768 nodes. Merely requesting expanded ceilings does not grant a larger budget. Names and source paths still consume checked byte budgets and implicit parents consume nodes, so long/deep paths can hit the metadata cap before 200000 entries. Approved source-path/pending-name copies consume bytes without duplicating their entry node. Expanded metadata jobs do not retain a universal 64 MiB RSS target.",
240240 "client": "Normal app jobs use StartGuarded with the existing 16 GiB and 10000-entry limits. Known selection/file estimates request expanded ceilings before processing. After a Limit result, offer an explicit expanded retry only after Terminal, both EOFs and child reap, with Publication::None, zero created/partial counts and complete cleanup. Retry uses a new job ID and requires fresh approval; existing or uncertain output instead shows the saved location and detailed result. App output records, including implicit parent directories, grow to 262144 nodes after any valid resource approval. Catalog entries grow to 200000 only for jobs granted the entries scope. Unapproved output records and catalogs without an entries grant retain their existing 100000 caps. Resource approval, ratio, retry and partial-output UI scenarios, tests and docs/ui-scenario-guide.md are implemented. Native Windows/Wayland verification remains separate.",
241241 "tests": "Use numeric 16/64 GiB and 10000/200000 policy boundaries, scaled worker limits, a compressed 257 MiB zero stream, and a virtual clock for the 60-second stall. Include client approval/retry tests in tests/rust-app-ui/guarded.rs and real-worker flows in tests/rust-app-real-worker/guarded_flows.rs. Do not write 64 GiB in tests."
242추가: },
243추가: "action_tags": {
244추가: "List": 0,
245추가: "Extract": 1,
246추가: "CreateZip": 2,
247추가: "Preview": 3,
248추가: "CreateSevenZip": 4
249추가: },
250추가: "seven_zip_method_tags": {
251추가: "Lzma2": 0
252추가: },
253추가: "seven_zip_create": {
254추가: "status": "worker-implemented; frontend-integrated; real-file-native-integration-and-independent-review-pending",
255추가: "agreement": {
256추가: "frontend_message_id": "770f1004-0a2b-4fc6-aafd-7f705c8f6c9e",
257추가: "frontend_review": "https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903269732",
258추가: "design_review": "https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903282961"
259추가: },
260추가: "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.",
261추가: "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.",
262추가: "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": "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.",
264추가: "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.",
265추가: "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.",
266추가: "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": "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."
242270 }
243271}
수정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+80-3
@@ -180,6 +180,7 @@ pub(super) struct Planned {
180180 path: PathBuf,
181181 object: SourceObject,
182182 modified: Option<SystemTime>,
183추가: children: Vec<String>,
183184}
184185impl Planned {
185186 pub fn open(&self) -> Result<Input> {
@@ -196,6 +197,56 @@ impl Planned {
196197 && metadata.is_dir() == (self.member.entry.kind == EntryKind::Directory)
197198 && (metadata.is_dir() || metadata.len() == self.member.entry.size))
198199 }
200추가: fn verify_with_temporary(
201추가: &self,
202추가: temporary: &filesystem::PublicationTemp,
203추가: check: &mut impl crate::resources::Monitor,
204추가: ) -> Result<()> {
205추가: let input = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
206추가: let before = input.file.metadata().map_err(crate::space::io_error)?;
207추가: if !before.is_dir() || filesystem::object(&input.file)? != self.object {
208추가: return Err(ErrorCode::SourceChanged);
209추가: }
210추가: // 게시 임시 파일의 부모만 시각 대신 원래 항목과 소유 객체를 대조함.
211추가: let mut count = 0;
212추가: let mut found = false;
213추가: for entry in input.children(&self.path)? {
214추가: check.check()?;
215추가: let name = entry.map_err(crate::space::io_error)?.file_name();
216추가: let name = name.to_str().ok_or(ErrorCode::SourceChanged)?;
217추가: if name == temporary.name {
218추가: let child = input
219추가: .open_child(&self.path, name)
220추가: .map_err(|_| ErrorCode::SourceChanged)?;
221추가: if found
222추가: || !child
223추가: .file
224추가: .metadata()
225추가: .map_err(crate::space::io_error)?
226추가: .is_file()
227추가: || filesystem::object(&child.file)? != temporary.object
228추가: {
229추가: return Err(ErrorCode::SourceChanged);
230추가: }
231추가: found = true;
232추가: } else if self
233추가: .children
234추가: .binary_search_by(|leaf| leaf.as_str().cmp(name))
235추가: .is_ok()
236추가: {
237추가: count += 1;
238추가: } else {
239추가: return Err(ErrorCode::SourceChanged);
240추가: }
241추가: crate::resources::completed(Ok(()), check)?;
242추가: }
243추가: let after = input.file.metadata().map_err(crate::space::io_error)?;
244추가: if !found || count != self.children.len() || before.modified().ok() != after.modified().ok()
245추가: {
246추가: return Err(ErrorCode::SourceChanged);
247추가: }
248추가: Ok(())
249추가: }
199250}
200251pub(super) struct Plan {
201252 pub items: Vec<Planned>,
@@ -283,6 +334,7 @@ impl Plan {
283334 None,
284335 )?;
285336 crate::resources::completed(Ok(()), check)?;
337추가: let index = self.items.len();
286338 self.items.push(Planned {
287339 member: Member {
288340 entry: Entry {
@@ -302,6 +354,7 @@ impl Plan {
302354 path: path.clone(),
303355 object: crate::resources::completed(filesystem::object(&input.file), check)?,
304356 modified: metadata.modified().ok(),
357추가: children: Vec::new(),
305358 });
306359 if directory {
307360 let mut children = Vec::new();
@@ -328,13 +381,21 @@ impl Plan {
328381 crate::resources::completed(Ok(()), check)?;
329382 }
330383 children.sort();
331삭제: for leaf in children {
332삭제: let child = crate::resources::completed(input.open_child(&path, &leaf), check)?;
333삭제: self.visit(path.join(&leaf), format!("{name}/{leaf}"), child, check)?;
384추가: for leaf in &children {
385추가: let child = crate::resources::completed(input.open_child(&path, leaf), check)?;
386추가: self.visit(path.join(leaf), format!("{name}/{leaf}"), child, check)?;
334387 }
388추가: self.items[index].children = children;
335389 }
336390 Ok(())
337391 }
392추가: pub fn reserve_metadata(
393추가: &mut self,
394추가: bytes: usize,
395추가: check: &impl crate::resources::Monitor,
396추가: ) -> Result<()> {
397추가: self.budget.charge_bytes(bytes, check.metadata_limits())
398추가: }
338399 pub fn verify(&self, check: &mut impl crate::resources::Monitor) -> Result<()> {
339400 for item in &self.items {
340401 check.check()?;
@@ -343,6 +404,22 @@ impl Plan {
343404 }
344405 Ok(())
345406 }
407추가: pub fn verify_for_publication(
408추가: &self,
409추가: temporary: &filesystem::PublicationTemp,
410추가: check: &mut impl crate::resources::Monitor,
411추가: ) -> Result<()> {
412추가: for item in &self.items {
413추가: check.check()?;
414추가: if item.member.entry.kind == EntryKind::Directory && item.object == temporary.parent {
415추가: item.verify_with_temporary(temporary, check)?;
416추가: } else {
417추가: item.open()?;
418추가: }
419추가: crate::resources::completed(Ok(()), check)?;
420추가: }
421추가: Ok(())
422추가: }
346423}
347424
348425#[cfg(test)]
수정experiments/rust-archive-worker/src/filesystem.rs+16-5
@@ -615,7 +615,7 @@ pub(crate) fn directory_with(
615615 check: &mut impl Monitor,
616616) -> Result<(bool, Durability, Option<ErrorCode>)> {
617617 directory_steps(root, name, &mut |step| match step {
618삭제: PublishStep::Check | PublishStep::Commit => check.check(),
618추가: PublishStep::Check | PublishStep::Commit(_) => check.check(),
619619 PublishStep::Activity => check.activity(),
620620 })
621621}
@@ -629,7 +629,7 @@ pub(crate) fn directory_steps(
629629 if completed(d.child(&leaf, false), &mut PublicationMonitor(check))?.is_some() {
630630 return Ok((false, Durability::NotApplicable, None));
631631 }
632삭제: check(PublishStep::Commit)?;
632추가: check(PublishStep::Commit(None))?;
633633 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
634634 let progress_error = completed(Ok(()), &mut PublicationMonitor(check)).err();
635635 Ok(match d.sync_checked() {
@@ -684,14 +684,19 @@ pub fn publish_reader_mode(
684684) -> Published {
685685 publish_reader_steps(root, name, data, length, replace, &mut |step| match step {
686686 PublishStep::Check => check(false),
687삭제: PublishStep::Commit => check(true),
687추가: PublishStep::Commit(_) => check(true),
688688 PublishStep::Activity => Ok(()),
689689 })
690690}
691추가: pub(crate) struct PublicationTemp {
692추가: pub parent: SourceObject,
693추가: pub name: String,
694추가: pub object: SourceObject,
695추가: }
691696pub(crate) enum PublishStep {
692697 Check,
693698 Activity,
694삭제: Commit,
699추가: Commit(Option<PublicationTemp>),
695700}
696701struct PublicationMonitor<'a, F>(&'a mut F);
697702impl<F: FnMut(PublishStep) -> Result<()>> Monitor for PublicationMonitor<'_, F> {
@@ -744,7 +749,13 @@ pub(crate) fn publish_reader_steps(
744749 crate::space::io_error(e)
745750 }
746751 })?;
752추가: let mut temporary = None;
747753 let written = (|| {
754추가: temporary = Some(PublicationTemp {
755추가: parent: object(dir.handle())?,
756추가: name: temp.clone(),
757추가: object: object(&file)?,
758추가: });
748759 completed(Ok(()), &mut PublicationMonitor(check))?;
749760 completed(
750761 crate::space::ensure(&file, length),
@@ -780,7 +791,7 @@ pub(crate) fn publish_reader_steps(
780791 &mut PublicationMonitor(check),
781792 );
782793 let mut finish = written.and(closed).and_then(|_| {
783삭제: check(PublishStep::Commit)?;
794추가: check(PublishStep::Commit(temporary))?;
784795 // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함.
785796 if let Some(expected) = replace {
786797 if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref()
수정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/protocol.rs+13-0
@@ -201,6 +201,10 @@ pub enum Method {
201201 Deflate,
202202}
203203#[derive(Clone, Copy, Debug, PartialEq, Eq)]
204추가: pub enum SevenZipMethod {
205추가: Lzma2,
206추가: }
207추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
204208pub enum Encryption {
205209 None,
206210 Aes256,
@@ -233,6 +237,13 @@ pub enum Action {
233237 entry_id: u32,
234238 list_id: ListId,
235239 },
240추가: CreateSevenZip {
241추가: sources: Vec<Source>,
242추가: output_file: NativePath,
243추가: method: SevenZipMethod,
244추가: solid: bool,
245추가: encryption: Encryption,
246추가: },
236247}
237248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
238249pub enum ActionKind {
@@ -240,6 +251,7 @@ pub enum ActionKind {
240251 Extract,
241252 CreateZip,
242253 Preview,
254추가: CreateSevenZip,
243255}
244256impl Action {
245257 pub fn kind(&self) -> ActionKind {
@@ -248,6 +260,7 @@ impl Action {
248260 Self::Extract { .. } => ActionKind::Extract,
249261 Self::CreateZip { .. } => ActionKind::CreateZip,
250262 Self::Preview { .. } => ActionKind::Preview,
263추가: Self::CreateSevenZip { .. } => ActionKind::CreateSevenZip,
251264 }
252265 }
253266}
수정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+73-5
@@ -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,
@@ -283,8 +284,19 @@ impl<W: Write> Job<W> {
283284 self.source_group = Some(group);
284285 self.split_result(result)
285286 }
286삭제: fn verify_before_publication(&mut self) -> Result<()> {
287추가: fn verify_before_publication(
288추가: &mut self,
289추가: temporary: Option<&filesystem::PublicationTemp>,
290추가: ) -> Result<()> {
287291 if !self.source_verified_for_publication {
292추가: if let Some(plan) = self.creation_plan.take() {
293추가: let result = match temporary {
294추가: Some(temporary) => plan.verify_for_publication(temporary, self),
295추가: None => plan.verify(self),
296추가: };
297추가: self.creation_plan = Some(plan);
298추가: result?;
299추가: }
288300 self.verify_split()?;
289301 self.source_verified_for_publication = true;
290302 }
@@ -294,8 +306,11 @@ impl<W: Write> Job<W> {
294306 match step {
295307 filesystem::PublishStep::Check => self.check(),
296308 filesystem::PublishStep::Activity => completed(Ok(()), self),
297삭제: filesystem::PublishStep::Commit => {
298삭제: self.verify_before_publication()?;
309추가: filesystem::PublishStep::Commit(temporary) => {
310추가: self.verify_before_publication(temporary.as_ref())?;
311추가: if let Some(plan) = &self.creation_plan {
312추가: self.progress(Stage::Commit, 0, None, plan.items.len() as u32)?;
313추가: }
299314 if last { self.cutoff() } else { self.check() }
300315 }
301316 }
@@ -545,9 +560,23 @@ impl<W: Write> Job<W> {
545560 let limits = self.budget.as_ref().map_or(start.limits, |b| b.ceiling);
546561 self.event(Message::Accepted {
547562 action: start.action.kind(),
548삭제: encryption: true,
563추가: encryption: !matches!(start.action, Action::CreateSevenZip { .. }),
549564 })?;
550565 self.check()?;
566추가: if let Action::CreateSevenZip {
567추가: sources,
568추가: solid,
569추가: encryption,
570추가: ..
571추가: } = &start.action
572추가: {
573추가: if *solid || *encryption != Encryption::None {
574추가: return Err(ErrorCode::UnsupportedFeature);
575추가: }
576추가: if sources.is_empty() {
577추가: return Err(ErrorCode::InvalidRequest);
578추가: }
579추가: }
551580 if let Some(budget) = &self.budget {
552581 let scope = ResourceScope {
553582 output: budget.ceiling.output > budget.soft.output,
@@ -865,7 +894,7 @@ impl<W: Write> Job<W> {
865894 )?;
866895 }
867896 // 건너뛰기 등 실제 게시가 없을 때도 완료 전에 원본을 확인함.
868삭제: self.verify_before_publication()?;
897추가: self.verify_before_publication(None)?;
869898 if !self.interactive || self.terminal.created_count != 0 {
870899 self.terminal.publication = Publication::Complete;
871900 }
@@ -921,12 +950,50 @@ impl<W: Write> Job<W> {
921950 self.output_reader(&root, &name, &mut data, length, None, true, None)?;
922951 self.terminal.publication = Publication::Complete;
923952 }
953추가: Action::CreateSevenZip {
954추가: sources,
955추가: output_file,
956추가: ..
957추가: } => {
958추가: let output = output_file.to_path()?;
959추가: let leaf = output
960추가: .file_name()
961추가: .and_then(|n| n.to_str())
962추가: .ok_or(ErrorCode::InvalidRequest)?;
963추가: let name = archive::valid_name(leaf, false)?;
964추가: let root = completed(
965추가: Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?),
966추가: self,
967추가: )?;
968추가: filesystem::preflight_mode_with(
969추가: &root,
970추가: &[(name.clone(), EntryKind::File)],
971추가: false,
972추가: self,
973추가: )?;
974추가: self.progress(Stage::Scan, 0, None, 0)?;
975추가: let mut plan = crate::create::plan(&sources, limits, self)?;
976추가: let (mut data, length) = crate::seven_zip_create::archive(&mut plan, limits, self)?;
977추가: filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?;
978추가: self.creation_plan = Some(plan);
979추가: self.output_reader(&root, &name, &mut data, length, None, true, None)?;
980추가: self.terminal.publication = Publication::Complete;
981추가: }
924982 }
925983 self.cutoff()?;
926984 Ok(())
927985 }
928986}
929987impl<W: Write> Monitor for Job<W> {
988추가: fn progress(
989추가: &mut self,
990추가: stage: Stage,
991추가: bytes: u64,
992추가: total: Option<u64>,
993추가: entries: u32,
994추가: ) -> Result<()> {
995추가: Job::progress(self, stage, bytes, total, entries)
996추가: }
930997 fn metadata_limits(&self) -> archive::MetadataLimits {
931998 self.budget
932999 .as_ref()
@@ -1108,6 +1175,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
11081175 remaining_choice: None,
11091176 source_group: None,
11101177 source_verified_for_publication: false,
1178추가: creation_plan: None,
11111179 parent,
11121180 started: Instant::now(),
11131181 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<()>,
수정experiments/rust-archive-worker/src/wire.rs+23-1
@@ -137,8 +137,9 @@ macro_rules! enumeration { ($t:ident {$($v:ident=$n:expr),*$(,)?}) => { impl Wir
137137} }; }
138138enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3,SevenZip=4});
139139enumeration!(Method{Store=0,Deflate=1});
140추가: enumeration!(SevenZipMethod{Lzma2=0});
140141enumeration!(Encryption{None=0,Aes256=1});
141삭제: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3});
142추가: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3,CreateSevenZip=4});
142143enumeration!(PreviewFormat{Utf8Text=0,Rgba8=1});
143144enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3});
144145enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5});
@@ -385,6 +386,20 @@ impl Wire for Action {
385386 entry_id.enc(e)?;
386387 list_id.enc(e)
387388 }
389추가: Self::CreateSevenZip {
390추가: sources,
391추가: output_file,
392추가: method,
393추가: solid,
394추가: encryption,
395추가: } => {
396추가: 4u8.enc(e)?;
397추가: sources.enc(e)?;
398추가: output_file.enc(e)?;
399추가: method.enc(e)?;
400추가: solid.enc(e)?;
401추가: encryption.enc(e)
402추가: }
388403 }
389404 }
390405 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
@@ -410,6 +425,13 @@ impl Wire for Action {
410425 entry_id: Wire::dec(d)?,
411426 list_id: Wire::dec(d)?,
412427 }),
428추가: 4 => Ok(Self::CreateSevenZip {
429추가: sources: Wire::dec(d)?,
430추가: output_file: Wire::dec(d)?,
431추가: method: Wire::dec(d)?,
432추가: solid: Wire::dec(d)?,
433추가: encryption: Wire::dec(d)?,
434추가: }),
413435 _ => Err(invalid()),
414436 }
415437 }
수정experiments/rust-ui-memory-app/src/archive_dialog.rs+24-12
@@ -8,6 +8,7 @@ pub enum Purpose {
88 Destination,
99 Retry,
1010 SaveZip,
11추가: SaveSevenZip,
1112 SaveGzip,
1213 RetryGzip,
1314}
@@ -110,6 +111,7 @@ fn choose_portal(request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String>
110111 let filters = match request.purpose {
111112 Purpose::Open => archive_filters(),
112113 Purpose::SaveZip => vec![("ZIP 압축파일", vec!["zip".into()])],
114추가: Purpose::SaveSevenZip => vec![("7z 압축파일", vec!["7z".into()])],
113115 _ => Vec::new(),
114116 }
115117 .into_iter()
@@ -128,18 +130,22 @@ fn choose_portal(request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String>
128130 .collect::<Vec<_>>();
129131 portal_response(pollster::block_on(async move {
130132 let selected = match request.purpose {
131삭제: Purpose::SaveZip | Purpose::SaveGzip | Purpose::RetryGzip => SaveFileRequest::default()
132삭제: .title(if request.purpose == Purpose::SaveZip {
133삭제: "ZIP 파일 저장"
134삭제: } else {
135삭제: "압축 해제 파일 저장"
136삭제: })
137삭제: .current_name(Some(request.file_name.as_str()))
138삭제: .filters(filters)
139삭제: .current_folder::<&PathBuf>(Some(&request.directory))?
140삭제: .send()
141삭제: .await?
142삭제: .response()?,
133추가: Purpose::SaveZip | Purpose::SaveSevenZip | Purpose::SaveGzip | Purpose::RetryGzip => {
134추가: SaveFileRequest::default()
135추가: .title(if request.purpose == Purpose::SaveSevenZip {
136추가: "7z 파일 저장"
137추가: } else if request.purpose == Purpose::SaveZip {
138추가: "ZIP 파일 저장"
139추가: } else {
140추가: "압축 해제 파일 저장"
141추가: })
142추가: .current_name(Some(request.file_name.as_str()))
143추가: .filters(filters)
144추가: .current_folder::<&PathBuf>(Some(&request.directory))?
145추가: .send()
146추가: .await?
147추가: .response()?
148추가: }
143149 purpose => OpenFileRequest::default()
144150 .title(match purpose {
145151 Purpose::Open => "압축파일 열기",
@@ -194,6 +200,12 @@ fn choose_native(request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String>
194200 .set_file_name(request.file_name)
195201 .save_file()
196202 .map(|path| vec![path]),
203추가: Purpose::SaveSevenZip => dialog
204추가: .set_title("7z 파일 저장")
205추가: .set_file_name(request.file_name)
206추가: .add_filter("7z 압축파일", &["7z"])
207추가: .save_file()
208추가: .map(|path| vec![path]),
197209 Purpose::SaveZip => dialog
198210 .set_title("ZIP 파일 저장")
199211 .set_file_name(request.file_name)
수정experiments/rust-ui-memory-app/src/archive_process.rs+18-0
@@ -201,6 +201,24 @@ fn start_to_wire(start: ui::Start) -> wire::Start {
201201 entry_id,
202202 list_id: list_to_wire(list_id),
203203 },
204추가: ui::Start::CreateSevenZip {
205추가: sources,
206추가: output_file,
207추가: } => wire::Action::CreateSevenZip {
208추가: sources: sources
209추가: .into_iter()
210추가: .map(|(path, archive_name)| wire::Source {
211추가: path: wire::NativePath::from_path(&crate::archive_path::worker_path(&path)),
212추가: archive_name,
213추가: })
214추가: .collect(),
215추가: output_file: wire::NativePath::from_path(&crate::archive_path::worker_path(
216추가: &output_file,
217추가: )),
218추가: method: wire::SevenZipMethod::Lzma2,
219추가: solid: false,
220추가: encryption: wire::Encryption::None,
221추가: },
204222 ui::Start::CreateZip {
205223 sources,
206224 output_file,
수정experiments/rust-ui-memory-app/src/archive_screen.rs+135-31
@@ -22,7 +22,7 @@ use std::{
2222const WORK_WIDTH: f32 = 480.0;
2323const CREATE_WIDTH: f32 = 560.0;
2424/// 처음 열 때의 높이. 그다음부터는 내용 높이에 맞춤.
25삭제: const CREATE_MIN_HEIGHT: f32 = 300.0;
25추가: const CREATE_MIN_HEIGHT: f32 = 560.0;
2626const CREATE_LIST_HEIGHT: f32 = 288.0;
2727
2828/// ZIP 만들기 창 목록의 한 행. 디스크에서 읽은 파일이나 폴더임.
@@ -208,6 +208,7 @@ pub struct ArchiveApp {
208208 create: bool,
209209 selected_only: bool,
210210 method: Method,
211추가: seven_zip: bool,
211212 dialogs: Box<dyn Dialogs>,
212213 picker: Option<(Purpose, std::sync::mpsc::Receiver<DialogAnswer>)>,
213214 preview_open: bool,
@@ -277,6 +278,7 @@ impl ArchiveApp {
277278 create: false,
278279 selected_only: false,
279280 method: Method::Deflate,
281추가: seven_zip: false,
280282 dialogs: Box::new(NativeDialogs),
281283 picker: None,
282284 preview_open: false,
@@ -342,7 +344,7 @@ impl ArchiveApp {
342344 pub fn show_create(&mut self, encrypted: bool) {
343345 if !self.model.busy() {
344346 self.create = true;
345삭제: self.aes256 = encrypted;
347추가: self.aes256 = encrypted && !self.seven_zip;
346348 self.ui_error = None;
347349 }
348350 }
@@ -517,7 +519,11 @@ impl ArchiveApp {
517519 } else {
518520 first.file_stem()
519521 };
520삭제: self.zip_name = format!("{}.zip", name.unwrap_or_default().to_string_lossy());
522추가: self.zip_name = format!(
523추가: "{}.{}",
524추가: name.unwrap_or_default().to_string_lossy(),
525추가: if self.seven_zip { "7z" } else { "zip" }
526추가: );
521527 }
522528 }
523529 for path in paths {
@@ -596,11 +602,12 @@ impl ArchiveApp {
596602 if self.sources.is_empty() {
597603 return;
598604 }
599삭제: if !self.zip_name.to_ascii_lowercase().ends_with(".zip") {
600삭제: self.zip_name.push_str(".zip");
605추가: let extension = if self.seven_zip { ".7z" } else { ".zip" };
606추가: if !self.zip_name.to_ascii_lowercase().ends_with(extension) {
607추가: self.zip_name.push_str(extension);
601608 }
602609 if !valid_leaf(&self.zip_name) {
603삭제: self.ui_error = Some("ZIP 파일 이름을 확인하세요".into());
610추가: self.ui_error = Some("압축파일 이름을 확인하세요".into());
604611 return;
605612 }
606613 let output_file = self.zip_folder.join(&self.zip_name);
@@ -619,6 +626,15 @@ impl ArchiveApp {
619626 };
620627 sources.push((path.clone(), name.to_owned()));
621628 }
629추가: if self.seven_zip
630추가: && (self.aes256
631추가: || !self.zip_password.is_empty()
632추가: || !self.zip_password_confirm.is_empty())
633추가: {
634추가: self.ui_error =
635추가: Some("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요".into());
636추가: return;
637추가: }
622638 if !self.zip_password_ready() {
623639 self.ui_error = Some("두 암호가 같은지 확인하세요".into());
624640 return;
@@ -627,12 +643,20 @@ impl ArchiveApp {
627643 self.directories.clear();
628644 // 암호는 ZIP 만들기 창에서 받아 두었다가 작업자가 요청하면 넘김.
629645 let password = self.aes256.then(|| std::mem::take(&mut self.zip_password));
630삭제: if self.start(Start::CreateZip {
631삭제: sources,
632삭제: output_file,
633삭제: method: self.method,
634삭제: aes256: self.aes256,
635삭제: }) {
646추가: let request = if self.seven_zip {
647추가: Start::CreateSevenZip {
648추가: sources,
649추가: output_file,
650추가: }
651추가: } else {
652추가: Start::CreateZip {
653추가: sources,
654추가: output_file,
655추가: method: self.method,
656추가: aes256: self.aes256,
657추가: }
658추가: };
659추가: if self.start(request) {
636660 self.create = false;
637661 self.create_win = WorkWindow::default();
638662 self.clear_zip_password();
@@ -657,7 +681,7 @@ impl ArchiveApp {
657681 _ => purpose,
658682 };
659683 let directory = match purpose {
660삭제: Purpose::SaveZip => self.zip_folder.clone(),
684추가: Purpose::SaveZip | Purpose::SaveSevenZip => self.zip_folder.clone(),
661685 Purpose::Destination | Purpose::SaveGzip => self
662686 .model
663687 .archive
@@ -769,8 +793,8 @@ impl ArchiveApp {
769793 }
770794 }
771795 // 저장 위치를 고르는 사이 ZIP 만들기 창을 닫았으면 아무 작업도 시작하지 않음.
772삭제: Purpose::SaveZip if !self.create => {}
773삭제: Purpose::SaveZip => {
796추가: Purpose::SaveZip | Purpose::SaveSevenZip if !self.create => {}
797추가: Purpose::SaveZip | Purpose::SaveSevenZip => {
774798 if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
775799 self.zip_name = name.to_owned();
776800 self.zip_folder = path.parent().unwrap_or(Path::new("/")).to_path_buf();
@@ -799,7 +823,13 @@ impl ArchiveApp {
799823 }
800824 self.extract_selection(selection);
801825 }
826추가: Start::CreateSevenZip { .. } => {
827추가: self.set_seven_zip(true);
828추가: self.create = true;
829추가: self.begin_zip();
830추가: }
802831 Start::CreateZip { aes256, .. } => {
832추가: self.set_seven_zip(false);
803833 self.create = true;
804834 if aes256 {
805835 // 암호는 보관하지 않으므로 ZIP 만들기 창에서 다시 받음.
@@ -1867,7 +1897,10 @@ impl ArchiveApp {
18671897 let title = if self.model.busy() {
18681898 present::activity_text(
18691899 &self.model,
1870삭제: matches!(self.last_request, Some(Start::CreateZip { .. })),
1900추가: matches!(
1901추가: self.last_request,
1902추가: Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
1903추가: ),
18711904 )
18721905 .to_owned()
18731906 } else {
@@ -1959,7 +1992,10 @@ impl ArchiveApp {
19591992 if error.starts_with("암호는") {
19601993 error.as_str()
19611994 } else {
1962삭제: if matches!(self.last_request, Some(Start::CreateZip { .. })) {
1995추가: if matches!(
1996추가: self.last_request,
1997추가: Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
1998추가: ) {
19631999 "저장 위치와 추가한 항목을 확인하세요"
19642000 } else {
19652001 "풀 위치와 선택한 항목을 확인하세요"
@@ -1977,7 +2013,10 @@ impl ArchiveApp {
19772013 });
19782014 return;
19792015 }
1980삭제: let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
2016추가: let creating = matches!(
2017추가: self.last_request,
2018추가: Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
2019추가: );
19812020 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
19822021 let title = present::activity_text(&self.model, creating);
19832022 ui.strong(title);
@@ -2034,7 +2073,10 @@ impl ArchiveApp {
20342073 fn result(&mut self, ui: &mut egui::Ui) {
20352074 let t = self.model.terminal.clone();
20362075 let listing = matches!(self.last_request, Some(Start::List { .. }));
2037삭제: let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
2076추가: let creating = matches!(
2077추가: self.last_request,
2078추가: Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
2079추가: );
20382080 let resolved_targets = present::resolved_targets(
20392081 self.targets.as_ref(),
20402082 &self.model.entries,
@@ -2087,7 +2129,11 @@ impl ArchiveApp {
20872129 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
20882130 let title = if success {
20892131 if creating {
2090삭제: "ZIP 파일을 만들었습니다"
2132추가: if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
2133추가: "7z 파일을 만들었습니다"
2134추가: } else {
2135추가: "ZIP 파일을 만들었습니다"
2136추가: }
20912137 } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) {
20922138 "모든 파일을 건너뛰었습니다"
20932139 } else {
@@ -2098,7 +2144,11 @@ impl ArchiveApp {
20982144 } else if listing {
20992145 "압축파일을 열지 못했습니다"
21002146 } else if creating {
2101삭제: "ZIP 파일을 만들지 못했습니다"
2147추가: if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
2148추가: "7z 파일을 만들지 못했습니다"
2149추가: } else {
2150추가: "ZIP 파일을 만들지 못했습니다"
2151추가: }
21022152 } else {
21032153 "압축을 풀지 못했습니다"
21042154 };
@@ -2136,9 +2186,10 @@ impl ArchiveApp {
21362186 .show(ui, |ui| {
21372187 if success && t.as_ref().is_some_and(|t| t.created_count > 0) {
21382188 let path = match self.last_request.as_ref() {
2139삭제: Some(Start::CreateZip { output_file, .. }) => {
2140삭제: output_file.display().to_string()
2141삭제: }
2189추가: Some(
2190추가: Start::CreateZip { output_file, .. }
2191추가: | Start::CreateSevenZip { output_file, .. },
2192추가: ) => output_file.display().to_string(),
21422193 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
21432194 };
21442195 theme::bounded_text(ui, &path, ui.available_width());
@@ -2204,7 +2255,11 @@ impl ArchiveApp {
22042255 )
22052256 {
22062257 ui.label(if creating {
2207삭제: "ZIP 파일을 만들지 않았습니다"
2258추가: if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
2259추가: "7z 파일을 만들지 않았습니다"
2260추가: } else {
2261추가: "ZIP 파일을 만들지 않았습니다"
2262추가: }
22082263 } else {
22092264 "아무 파일도 풀지 않았습니다"
22102265 });
@@ -2376,9 +2431,10 @@ impl ArchiveApp {
23762431 }
23772432 if folder {
23782433 let path = match self.last_request.as_ref() {
2379삭제: Some(Start::CreateZip { output_file, .. }) => {
2380삭제: output_file.parent().unwrap_or(Path::new("/"))
2381삭제: }
2434추가: Some(
2435추가: Start::CreateZip { output_file, .. }
2436추가: | Start::CreateSevenZip { output_file, .. },
2437추가: ) => output_file.parent().unwrap_or(Path::new("/")),
23822438 _ => self.destination.as_path(),
23832439 };
23842440 match present::folder_command(path).spawn() {
@@ -2432,7 +2488,11 @@ impl ArchiveApp {
24322488 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
24332489 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
24342490 ui.horizontal(|ui| {
2435삭제: ui.heading("ZIP 만들기");
2491추가: ui.heading(if self.seven_zip {
2492추가: "7z 만들기"
2493추가: } else {
2494추가: "ZIP 만들기"
2495추가: });
24362496 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
24372497 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
24382498 close = button.clicked();
@@ -2448,7 +2508,11 @@ impl ArchiveApp {
24482508 return;
24492509 }
24502510 let id = egui::ViewportId::from_hash_of("archive-create");
2451삭제: let title = "ZIP 만들기 — Zipelo";
2511추가: let title = if self.seven_zip {
2512추가: "7z 만들기 — Zipelo"
2513추가: } else {
2514추가: "ZIP 만들기 — Zipelo"
2515추가: };
24522516 let custom_frame = self.custom_frame;
24532517 if !self.create_win.open {
24542518 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
@@ -2531,7 +2595,38 @@ impl ArchiveApp {
25312595 .inner
25322596 }
25332597
2598추가: fn set_seven_zip(&mut self, selected: bool) {
2599추가: if self.seven_zip == selected {
2600추가: return;
2601추가: }
2602추가: self.seven_zip = selected;
2603추가: self.aes256 = false;
2604추가: self.clear_zip_password();
2605추가: self.ui_error = None;
2606추가: let name = self.zip_name.clone();
2607추가: let lower = name.to_ascii_lowercase();
2608추가: let stem = if lower.ends_with(".zip") {
2609추가: &name[..name.len() - 4]
2610추가: } else if lower.ends_with(".7z") {
2611추가: &name[..name.len() - 3]
2612추가: } else {
2613추가: &name
2614추가: };
2615추가: self.zip_name = format!("{stem}{}", if selected { ".7z" } else { ".zip" });
2616추가: }
2617추가:
25342618 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
2619추가: let mut selected = self.seven_zip;
2620추가: ui.horizontal(|ui| {
2621추가: ui.label("형식");
2622추가: ui.selectable_value(&mut selected, false, "ZIP");
2623추가: ui.selectable_value(&mut selected, true, "7z");
2624추가: if selected {
2625추가: ui.label("LZMA2");
2626추가: }
2627추가: });
2628추가: self.set_seven_zip(selected);
2629추가:
25352630 let rows = self.create_rows();
25362631 let root = self.create_root();
25372632
@@ -2670,6 +2765,10 @@ impl ArchiveApp {
26702765 }
26712766
26722767 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
2768추가: if self.seven_zip {
2769추가: ui.label("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요");
2770추가: return false;
2771추가: }
26732772 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
26742773 theme::pointer(&check);
26752774 theme::focus(&check);
@@ -2743,7 +2842,11 @@ impl ArchiveApp {
27432842 })
27442843 .inner;
27452844 if compress {
2746삭제: self.open_picker(Purpose::SaveZip);
2845추가: self.open_picker(if self.seven_zip {
2846추가: Purpose::SaveSevenZip
2847추가: } else {
2848추가: Purpose::SaveZip
2849추가: });
27472850 }
27482851 cancel
27492852 }
@@ -2769,6 +2872,7 @@ impl ArchiveApp {
27692872 ActionKind::List => "압축파일 목록 열기",
27702873 ActionKind::Extract => "압축 해제",
27712874 ActionKind::CreateZip => "ZIP 만들기",
2875추가: ActionKind::CreateSevenZip => "7z 만들기",
27722876 ActionKind::Preview => "파일 미리보기",
27732877 });
27742878 if question.scope.ratio {
수정experiments/rust-ui-memory-app/src/archive_ui.rs+17-3
@@ -69,6 +69,10 @@ pub enum Start {
6969 entry_id: u32,
7070 list_id: ListId,
7171 },
72추가: CreateSevenZip {
73추가: sources: Vec<(PathBuf, String)>,
74추가: output_file: PathBuf,
75추가: },
7276 CreateZip {
7377 sources: Vec<(PathBuf, String)>,
7478 output_file: PathBuf,
@@ -476,7 +480,8 @@ impl Model {
476480 }
477481 }
478482 pub fn begin(&mut self, start: Start, factory: &mut dyn Factory) -> bool {
479삭제: let expanded = self.needs_expansion(&start);
483추가: let expanded =
484추가: matches!(start, Start::CreateSevenZip { .. }) || self.needs_expansion(&start);
480485 self.begin_with_limits(start, factory, expanded)
481486 }
482487 pub fn estimated_usage(&self) -> ResourceUsage {
@@ -513,7 +518,7 @@ impl Model {
513518 .iter()
514519 .try_fold(0u64, |sum, e| sum.checked_add(e.bytes?));
515520 }
516삭제: Start::CreateZip { sources, .. } => {
521추가: Start::CreateZip { sources, .. } | Start::CreateSevenZip { sources, .. } => {
517522 usage.estimated_bytes = sources.iter().try_fold(0u64, |sum, (path, _)| {
518523 let m = std::fs::symlink_metadata(path).ok()?;
519524 if !m.is_file() {
@@ -643,6 +648,10 @@ impl Model {
643648 sources,
644649 output_file,
645650 ..
651추가: }
652추가: | Start::CreateSevenZip {
653추가: sources,
654추가: output_file,
646655 } => {
647656 !sources.is_empty()
648657 && output_file.is_absolute()
@@ -1100,6 +1109,9 @@ impl Model {
11001109 }
11011110 }
11021111 Event::Accepted { encryption } => {
1112추가: if matches!(run.start, Start::CreateSevenZip { .. }) && encryption {
1113추가: self.error = Some("7z 생성의 암호 응답이 유효하지 않습니다".into());
1114추가: }
11031115 if run.accepted {
11041116 self.error = Some("작업 승인 중복".into());
11051117 }
@@ -1144,7 +1156,8 @@ impl Model {
11441156 if run.cancel_sequence.is_some() {
11451157 return;
11461158 }
1147삭제: if self.challenge.is_some()
1159추가: if matches!(run.start, Start::CreateSevenZip { .. })
1160추가: || self.challenge.is_some()
11481161 || self.resource.is_some()
11491162 || challenge_id <= run.last_challenge
11501163 || self.conflict.is_some()
@@ -1163,6 +1176,7 @@ impl Model {
11631176 Start::List { .. } => ActionKind::List,
11641177 Start::Extract { .. } => ActionKind::Extract,
11651178 Start::CreateZip { .. } => ActionKind::CreateZip,
1179추가: Start::CreateSevenZip { .. } => ActionKind::CreateSevenZip,
11661180 Start::Preview { .. } => ActionKind::Preview,
11671181 };
11681182 let hard = Limits {
수정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-app-ui/capture.rs+5-0
@@ -236,6 +236,11 @@ impl Connection for CaptureConnection {
236236 durability: Durability::NotApplicable,
237237 cleanup: Cleanup::Complete,
238238 }),
239추가: Start::CreateSevenZip { output_file, .. } => {
240추가: self.create_name =
241추가: Some(output_file.file_name().unwrap().to_string_lossy().into());
242추가: self.finish(false);
243추가: }
239244 Start::CreateZip {
240245 output_file,
241246 aes256,
수정tests/rust-app-ui/conflict_codec.rs+33-0
@@ -107,3 +107,36 @@ fn volume_problem_adapter_preserves_native_filename_and_rejects_other_actions()
107107 Some(ui::ErrorCode::MissingVolume)
108108 );
109109}
110추가:
111추가: #[test]
112추가: fn sevenzip_creation_adapter_preserves_paths_and_fixed_options() {
113추가: let source = std::env::current_dir().unwrap().join("원본");
114추가: let output = source.with_file_name("결과.7z");
115추가: let converted = start_to_wire(ui::Start::CreateSevenZip {
116추가: sources: vec![(source.clone(), "원본".into())],
117추가: output_file: output.clone(),
118추가: });
119추가: match converted.action {
120추가: wire::Action::CreateSevenZip {
121추가: sources,
122추가: output_file,
123추가: method,
124추가: solid,
125추가: encryption,
126추가: } => {
127추가: assert_eq!(sources[0].archive_name, "원본");
128추가: assert_eq!(
129추가: sources[0].path,
130추가: wire::NativePath::from_path(&crate::archive_path::worker_path(&source))
131추가: );
132추가: assert_eq!(
133추가: output_file,
134추가: wire::NativePath::from_path(&crate::archive_path::worker_path(&output))
135추가: );
136추가: assert_eq!(method, wire::SevenZipMethod::Lzma2);
137추가: assert!(!solid);
138추가: assert_eq!(encryption, wire::Encryption::None);
139추가: }
140추가: other => panic!("잘못된 생성 형식: {other:?}"),
141추가: }
142추가: }
수정tests/rust-app-ui/create_window.rs+46-0
@@ -636,3 +636,49 @@ fn native_picker_lowers_child_windows_and_restores_their_position_and_level() {
636636 }
637637 }
638638}
639추가:
640추가: #[test]
641추가: fn sevenzip_selection_clears_zip_password_and_sends_only_supported_options() {
642추가: let scratch = Folder::new();
643추가: let factory = FakeFactory::default();
644추가: let (mut app, ctx) = create_from_folder(&scratch, &factory);
645추가: policy_click(&ctx, &mut app, "암호로 보호하기");
646추가: text(&ctx, &mut app, "zip-password-input", "previous-secret");
647추가: text(&ctx, &mut app, "zip-password-confirm", "previous-secret");
648추가: policy_click(&ctx, &mut app, "7z");
649추가: let shown = policy_render(&ctx, &mut app, vec![]);
650추가: assert!(shown.iter().any(|(s, _)| s == "LZMA2"));
651추가: assert!(!shown.iter().any(|(s, _)| s == "암호 확인"));
652추가: policy_click(&ctx, &mut app, "ZIP");
653추가: policy_click(&ctx, &mut app, "암호로 보호하기");
654추가: policy_click(&ctx, &mut app, "압축하기");
655추가: assert_eq!(factory.state.borrow().starts.len(), 1);
656추가: policy_click(&ctx, &mut app, "7z");
657추가: let dialogs = TestDialogs::default();
658추가: app.set_dialogs(Box::new(dialogs.clone()));
659추가: policy_click(&ctx, &mut app, "압축하기");
660추가: let state = dialogs.0.borrow();
661추가: let save = state.requests.last().unwrap();
662추가: assert_eq!(save.purpose, Purpose::SaveSevenZip);
663추가: assert_eq!(save.file_name, "photos.7z");
664추가: assert!(matches!(factory.state.borrow().starts.last(),
665추가: Some(Start::CreateSevenZip { sources, output_file })
666추가: if sources.len() == 1 && sources[0].1 == "photos" && output_file.ends_with("photos.7z")));
667추가: assert!(!factory.state.borrow().password_seen);
668추가: }
669추가:
670추가: #[test]
671추가: fn cancelling_sevenzip_save_keeps_selected_format_without_starting() {
672추가: let scratch = Folder::new();
673추가: let factory = FakeFactory::default();
674추가: let (mut app, ctx) = create_from_folder(&scratch, &factory);
675추가: policy_click(&ctx, &mut app, "7z");
676추가: let dialogs = TestDialogs::default();
677추가: dialogs.0.borrow_mut().cancel_save = true;
678추가: app.set_dialogs(Box::new(dialogs));
679추가: policy_click(&ctx, &mut app, "압축하기");
680추가: assert_eq!(factory.state.borrow().starts.len(), 1);
681추가: let shown = policy_render(&ctx, &mut app, vec![]);
682추가: assert!(shown.iter().any(|(s, _)| s == "7z 만들기"));
683추가: assert!(shown.iter().any(|(s, _)| s == "LZMA2"));
684추가: }
수정tests/rust-app-ui/dialogs.rs+2-1
@@ -23,7 +23,8 @@ impl Dialogs for TestDialogs {
2323 if let Some(answer) = state.answers.pop_front() {
2424 return Ok(answer);
2525 }
26삭제: if request.purpose == Purpose::SaveZip && !state.cancel_save {
26추가: if matches!(request.purpose, Purpose::SaveZip | Purpose::SaveSevenZip) && !state.cancel_save
27추가: {
2728 let name = state.save_name.take().unwrap_or(request.file_name);
2829 return Ok(Some(vec![request.directory.join(name)]));
2930 }
수정tests/rust-app-ui/regressions.rs+78-0
@@ -875,3 +875,81 @@ mod presentation;
875875mod windows_paths;
876876
877877mod guarded;
878추가:
879추가: #[test]
880추가: fn sevenzip_creation_rejects_password_prompts_and_encrypted_acceptance() {
881추가: for encrypted in [false, true] {
882추가: let mut f = FakeFactory::default();
883추가: f.state.borrow_mut().manual = true;
884추가: let mut m = Model::default();
885추가: assert!(m.begin(
886추가: Start::CreateSevenZip {
887추가: sources: vec![(path("source"), "source".into())],
888추가: output_file: path("output.7z"),
889추가: },
890추가: &mut f
891추가: ));
892추가: f.state.borrow_mut().frame(Event::Accepted {
893추가: encryption: encrypted,
894추가: });
895추가: if !encrypted {
896추가: f.state.borrow_mut().frame(Event::PasswordRequired {
897추가: challenge_id: 1,
898추가: attempt: 1,
899추가: encrypt: true,
900추가: });
901추가: }
902추가: for _ in 0..10 {
903추가: m.poll();
904추가: }
905추가: assert!(m.error.is_some());
906추가: assert!(m.challenge.is_none());
907추가: }
908추가: }
909추가:
910추가: #[test]
911추가: fn sevenzip_creation_waits_for_both_eofs_and_child_reap() {
912추가: let mut f = FakeFactory::default();
913추가: f.state.borrow_mut().manual = true;
914추가: let mut m = Model::default();
915추가: assert!(m.begin(
916추가: Start::CreateSevenZip {
917추가: sources: vec![(path("source"), "source".into())],
918추가: output_file: path("output.7z"),
919추가: },
920추가: &mut f
921추가: ));
922추가: {
923추가: let mut s = f.state.borrow_mut();
924추가: s.frame(Event::Accepted { encryption: false });
925추가: s.frame(Event::Output {
926추가: entry_id: None,
927추가: relative_name: "output.7z".into(),
928추가: disposition: Disposition::Created,
929추가: });
930추가: s.frame(Event::Terminal(Terminal {
931추가: outcome: Outcome::Completed,
932추가: error: None,
933추가: publication: Publication::Complete,
934추가: created_count: 1,
935추가: retained_partial_count: 0,
936추가: durability: Durability::Synced,
937추가: cleanup: Cleanup::Complete,
938추가: }));
939추가: }
940추가: m.poll();
941추가: assert!(!m.confirmed);
942추가: f.state.borrow_mut().queue.push_back(HostEvent::StdoutEof);
943추가: m.poll();
944추가: assert!(!m.confirmed);
945추가: f.state.borrow_mut().queue.push_back(HostEvent::StderrEof);
946추가: m.poll();
947추가: assert!(!m.confirmed);
948추가: f.state
949추가: .borrow_mut()
950추가: .queue
951추가: .push_back(HostEvent::Exited { success: true });
952추가: pump(&mut m);
953추가: assert!(m.confirmed);
954추가: assert!(m.error.is_none());
955추가: }
수정tests/rust-app-ui/scenario_tests.rs+6-0
@@ -140,6 +140,12 @@ fn every_listed_scenario_draws_and_keeps_its_expected_screen() {
140140 "extract-unsynced" => "파일을 디스크에 완전히 저장했는지 확인하지 못했습니다",
141141 "source-changed" => "압축파일 다시 열기",
142142 "gzip-conflict" => "다른 이름으로 저장",
143추가: "create-sevenzip" => "7z는 암호를 지원하지 않습니다",
144추가: "create-sevenzip-progress" => "파일을 저장하는 중",
145추가: "create-sevenzip-complete" => "7z 파일을 만들었습니다",
146추가: "create-sevenzip-error" => "7z 파일을 만들지 못했습니다",
147추가: "create-sevenzip-cancelled" => "작업을 취소했습니다",
148추가: "create-sevenzip-resource" => "큰 작업을 허용할까요?",
143149 "create-error" => "ZIP 파일을 만들지 못했습니다",
144150 "password-create" => "암호 확인",
145151 "folder" => "바다.jpg",
수정tests/rust-app-ui/scenarios.rs+47-12
@@ -21,6 +21,13 @@ macro_rules! catalog {
2121}
2222
2323catalog! {
24추가: "create-sevenzip" => "7z 형식 선택과 LZMA2 및 암호 미지원 안내",
25추가: "create-sevenzip-progress" => "7z 만들기 진행과 취소",
26추가: "create-sevenzip-complete" => "7z 만들기 완료",
27추가: "create-sevenzip-error" => "7z 만들기 저장 실패",
28추가: "create-sevenzip-cancelled" => "7z 만들기 취소 완료",
29추가: "create-sevenzip-resource" => "7z 만들기의 큰 작업 승인",
30추가:
2431 "split-archive" => "분할 7z 목록과 미리보기 비활성화",
2532 "split-first-volume" => "첫 조각의 정확한 파일명 안내",
2633 "split-missing-volume" => "누락 조각 파일명과 재시도 안내",
@@ -511,7 +518,7 @@ impl Scenario {
511518 }
512519 return app;
513520 }
514삭제: "create" | "create-encrypted" => {
521추가: "create" | "create-encrypted" | "create-sevenzip" => {
515522 app.sources = vec![base.join("읽어주세요.txt"), base.join("사진")];
516523 app.scenario_sources = Some(std::rc::Rc::new(vec![
517524 SourceRow {
@@ -526,10 +533,12 @@ impl Scenario {
526533 },
527534 ]));
528535 app.show_create(self.name == "create-encrypted");
536추가: app.set_seven_zip(self.name == "create-sevenzip");
529537 return app;
530538 }
531539 _ => {}
532540 }
541추가: let seven_zip = self.name.starts_with("create-sevenzip");
533542 let creating = self.name.starts_with("create-") || self.name == "password-create";
534543 let listing_error = matches!(self.name, "unsupported" | "damaged");
535544 if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
@@ -544,7 +553,12 @@ impl Scenario {
544553 }];
545554 app.gzip_name = "여행 자료".into();
546555 }
547삭제: let request = if creating {
556추가: let request = if seven_zip {
557추가: Start::CreateSevenZip {
558추가: sources: vec![(base.join("사진"), "사진".into())],
559추가: output_file: base.join("여행 자료.7z"),
560추가: }
561추가: } else if creating {
548562 Start::CreateZip {
549563 sources: vec![(base.join("사진"), "사진".into())],
550564 output_file: base.join("여행 자료.zip"),
@@ -564,7 +578,12 @@ impl Scenario {
564578 }
565579 };
566580 app.targets = Some(if creating {
567삭제: BTreeSet::from(["여행 자료.zip".into()])
581추가: BTreeSet::from([if seven_zip {
582추가: "여행 자료.7z"
583추가: } else {
584추가: "여행 자료.zip"
585추가: }
586추가: .into()])
568587 } else if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
569588 BTreeSet::from(["여행 자료".into()])
570589 } else {
@@ -588,13 +607,19 @@ impl Scenario {
588607 assert!(app.start(request));
589608 {
590609 let mut state = state.borrow_mut();
591삭제: state.frame(Event::Accepted { encryption: true });
610추가: state.frame(Event::Accepted {
611추가: encryption: !seven_zip,
612추가: });
592613 match self.name {
593삭제: "resource-approval" | "resource-ratio" => {
594삭제: let expanded = self.name == "resource-approval";
614추가: "resource-approval" | "resource-ratio" | "create-sevenzip-resource" => {
615추가: let expanded = self.name != "resource-ratio";
595616 state.frame(Event::ResourceRequired(ResourceChallenge {
596617 id: 1,
597삭제: action: ActionKind::Extract,
618추가: action: if seven_zip {
619추가: ActionKind::CreateSevenZip
620추가: } else {
621추가: ActionKind::Extract
622추가: },
598623 scope: ResourceScope {
599624 output: expanded,
600625 entries: expanded,
@@ -723,7 +748,10 @@ impl Scenario {
723748 encrypt: self.name == "password-create",
724749 })
725750 }
726삭제: "extract-complete" | "create-complete" | "extract-unsynced" => {
751추가: "extract-complete"
752추가: | "create-complete"
753추가: | "create-sevenzip-complete"
754추가: | "extract-unsynced" => {
727755 let names = app.targets.as_ref().unwrap();
728756 for name in names {
729757 state.frame(Event::Output {
@@ -751,7 +779,9 @@ impl Scenario {
751779 HostEvent::Exited { success: true },
752780 ]);
753781 }
754삭제: "extract-cancelled" => state.finish(Outcome::Cancelled, Publication::None),
782추가: "extract-cancelled" | "create-sevenzip-cancelled" => {
783추가: state.finish(Outcome::Cancelled, Publication::None)
784추가: }
755785 "extract-partial" | "extract-uncertain" => {
756786 let partial = self.name == "extract-partial";
757787 if partial {
@@ -780,14 +810,19 @@ impl Scenario {
780810 HostEvent::Exited { success: true },
781811 ]);
782812 }
783삭제: "conflict" | "gzip-conflict" | "unsupported" | "damaged" | "source-changed"
784삭제: | "create-error" => {
813추가: "conflict"
814추가: | "gzip-conflict"
815추가: | "unsupported"
816추가: | "damaged"
817추가: | "source-changed"
818추가: | "create-error"
819추가: | "create-sevenzip-error" => {
785820 state.frame(Event::Terminal(Terminal {
786821 outcome: Outcome::Failed,
787822 error: Some(match self.name {
788823 "conflict" | "gzip-conflict" => ErrorCode::Conflict,
789824 "source-changed" => ErrorCode::SourceChanged,
790삭제: "create-error" => ErrorCode::DiskFull,
825추가: "create-error" | "create-sevenzip-error" => ErrorCode::DiskFull,
791826 "unsupported" => ErrorCode::UnsupportedFormat,
792827 _ => ErrorCode::Integrity,
793828 }),
수정tests/rust-archive-worker/create_sources.rs+80-2
@@ -4,8 +4,9 @@ static NEXT: AtomicU64 = AtomicU64::new(0);
44struct Scratch(PathBuf);
55impl Scratch {
66 fn new() -> Self {
7삭제: let root =
8삭제: Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/rust-archive-worker/runs");
7추가: let root = std::env::var_os("TMPDIR")
8추가: .map(PathBuf::from)
9추가: .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp"));
910 fs::create_dir_all(&root).unwrap();
1011 let path = root.join(format!(
1112 "sources-{}-{}",
@@ -105,3 +106,80 @@ fn pinned_directory_enumeration_does_not_follow_replacement_link() {
105106 assert!(input.open_child(&path, "secret").is_err());
106107 assert!(matches!(Input::open(&path), Err(ErrorCode::UnsafePath)));
107108}
109추가:
110추가: #[test]
111추가: fn publication_exception_requires_the_exact_parent_name_and_temporary_object() {
112추가: for mismatch in [
113추가: "parent",
114추가: "name",
115추가: "object",
116추가: "missing",
117추가: "replacement",
118추가: "directory",
119추가: ] {
120추가: let s = Scratch::new();
121추가: fs::create_dir(s.0.join("folder")).unwrap();
122추가: fs::write(s.0.join("folder/source"), b"original").unwrap();
123추가: let plan = Plan::new(&[s.source("folder")], Limits::default(), &mut || Ok(())).unwrap();
124추가: let path = s.0.join("folder/.zipelo-owned.tmp");
125추가: fs::write(&path, b"archive").unwrap();
126추가: let mut temporary = filesystem::PublicationTemp {
127추가: parent: filesystem::object(&Input::open(&s.0.join("folder")).unwrap().file).unwrap(),
128추가: name: ".zipelo-owned.tmp".into(),
129추가: object: filesystem::object(&Input::open(&path).unwrap().file).unwrap(),
130추가: };
131추가: assert_eq!(plan.verify(&mut || Ok(())), Err(ErrorCode::SourceChanged));
132추가: assert_eq!(
133추가: plan.verify_for_publication(&temporary, &mut || Ok(())),
134추가: Ok(())
135추가: );
136추가: match mismatch {
137추가: "parent" => temporary.parent = temporary.object.clone(),
138추가: "name" => temporary.name = ".zipelo-other.tmp".into(),
139추가: "object" => temporary.object = temporary.parent.clone(),
140추가: "missing" => fs::remove_file(&path).unwrap(),
141추가: "replacement" => {
142추가: fs::rename(&path, s.0.join("owned")).unwrap();
143추가: fs::write(&path, b"foreign").unwrap();
144추가: }
145추가: "directory" => {
146추가: fs::rename(s.0.join("folder"), s.0.join("previous")).unwrap();
147추가: fs::create_dir(s.0.join("folder")).unwrap();
148추가: }
149추가: _ => unreachable!(),
150추가: }
151추가: assert_eq!(
152추가: plan.verify_for_publication(&temporary, &mut || Ok(())),
153추가: Err(ErrorCode::SourceChanged),
154추가: "{mismatch}"
155추가: );
156추가: }
157추가: }
158추가:
159추가: #[test]
160추가: fn publication_directory_enumeration_remains_cancellable() {
161추가: let s = Scratch::new();
162추가: fs::create_dir(s.0.join("folder")).unwrap();
163추가: for index in 0..20 {
164추가: fs::write(s.0.join(format!("folder/{index}")), b"x").unwrap();
165추가: }
166추가: let plan = Plan::new(&[s.source("folder")], Limits::default(), &mut || Ok(())).unwrap();
167추가: let path = s.0.join("folder/.zipelo-owned.tmp");
168추가: fs::write(&path, b"archive").unwrap();
169추가: let temporary = filesystem::PublicationTemp {
170추가: parent: filesystem::object(&Input::open(&s.0.join("folder")).unwrap().file).unwrap(),
171추가: name: ".zipelo-owned.tmp".into(),
172추가: object: filesystem::object(&Input::open(&path).unwrap().file).unwrap(),
173추가: };
174추가: let mut calls = 0;
175추가: let result = plan.verify_for_publication(&temporary, &mut || {
176추가: calls += 1;
177추가: if calls == 12 {
178추가: Err(ErrorCode::None)
179추가: } else {
180추가: Ok(())
181추가: }
182추가: });
183추가: assert_eq!(result, Err(ErrorCode::None));
184추가: assert_eq!(calls, 12);
185추가: }
수정tests/rust-archive-worker/main.rs+4-0
@@ -1625,3 +1625,7 @@ mod compressed_tar;
16251625mod guarded;
16261626
16271627mod split_runtime;
1628추가:
1629추가: mod seven_zip_create;
1630추가:
1631추가: mod seven_zip_create_runtime;
수정tests/rust-archive-worker/preview_wire.rs+1-1
@@ -412,7 +412,7 @@ fn preview_action_kind_keeps_all_existing_tags() {
412412 matches!(decoded(&bytes), Message::Accepted { action: actual, encryption: true } if actual == action)
413413 );
414414 }
415삭제: reject_decode(&raw(100, &[4, 1]));
415추가: reject_decode(&raw(100, &[5, 1]));
416416 reject_decode(&raw(8, &[]));
417417 reject_decode(&raw(114, &[]));
418418}
추가tests/rust-archive-worker/seven_zip_create.rs+413-0
@@ -0,0 +1,413 @@
1추가: use super::*;
2추가:
3추가: fn request(windows: bool) -> Action {
4추가: let (source, output_file) = if windows {
5추가: (
6추가: NativePath::Windows("C:\\s".encode_utf16().collect()),
7추가: NativePath::Windows("C:\\o.7z".encode_utf16().collect()),
8추가: )
9추가: } else {
10추가: (
11추가: NativePath::Unix(b"/s".to_vec()),
12추가: NativePath::Unix(b"/o.7z".to_vec()),
13추가: )
14추가: };
15추가: Action::CreateSevenZip {
16추가: sources: vec![Source {
17추가: path: source,
18추가: archive_name: "한글".to_owned(),
19추가: }],
20추가: output_file,
21추가: method: SevenZipMethod::Lzma2,
22추가: solid: false,
23추가: encryption: Encryption::None,
24추가: }
25추가: }
26추가:
27추가: fn start(action: Action) -> Start {
28추가: Start {
29추가: action,
30추가: limits: Limits::default(),
31추가: }
32추가: }
33추가:
34추가: fn guarded(start: Start) -> GuardedStart {
35추가: GuardedStart {
36추가: ceiling: Limits {
37추가: input: start.limits.input,
38추가: output: 64 * 1024 * 1024 * 1024,
39추가: entries: 200_000,
40추가: },
41추가: start,
42추가: interactive: false,
43추가: }
44추가: }
45추가:
46추가: fn encode(message: &Message) -> Vec<u8> {
47추가: let mut bytes = Vec::new();
48추가: Writer::new(&mut bytes, 17).send(message).unwrap();
49추가: bytes
50추가: }
51추가:
52추가: fn decode(bytes: &[u8]) -> Message {
53추가: let mut reader = Reader::new(bytes);
54추가: let (job, sequence, message) = reader.read().unwrap().unwrap();
55추가: assert_eq!((job, sequence), (17, 0));
56추가: assert!(reader.read().unwrap().is_none());
57추가: message
58추가: }
59추가:
60추가: fn raw(kind: u16, body: &[u8]) -> Vec<u8> {
61추가: let mut bytes = b"ZAW1\x01\x00".to_vec();
62추가: bytes.extend(kind.to_le_bytes());
63추가: bytes.extend((body.len() as u32).to_le_bytes());
64추가: bytes.extend([0; 4]);
65추가: bytes.extend(17u64.to_le_bytes());
66추가: bytes.extend(0u64.to_le_bytes());
67추가: bytes.extend(body);
68추가: bytes
69추가: }
70추가:
71추가: fn reject_encode(message: Message) {
72추가: let mut bytes = Vec::new();
73추가: assert_eq!(
74추가: Writer::new(&mut bytes, 17)
75추가: .send(&message)
76추가: .unwrap_err()
77추가: .kind(),
78추가: std::io::ErrorKind::InvalidData
79추가: );
80추가: assert!(bytes.is_empty());
81추가: }
82추가:
83추가: fn reject_decode(bytes: &[u8]) {
84추가: assert_eq!(
85추가: Reader::new(bytes).read().unwrap_err().kind(),
86추가: std::io::ErrorKind::InvalidData
87추가: );
88추가: }
89추가:
90추가: #[test]
91추가: fn request_preserves_agreed_field_order_and_native_encodings() {
92추가: for windows in [false, true] {
93추가: let start = start(request(windows));
94추가: assert_eq!(start.action.kind(), ActionKind::CreateSevenZip);
95추가: let mut expected = vec![4, 1, 0, 0, 0];
96추가: if windows {
97추가: expected.extend(b"\x02\x04\x00\x00\x00C\x00:\x00\\\x00s\x00");
98추가: } else {
99추가: expected.extend(b"\x01\x02\x00\x00\x00/s");
100추가: }
101추가: expected.extend(b"\x06\x00\x00\x00\xed\x95\x9c\xea\xb8\x80");
102추가: if windows {
103추가: expected.extend(b"\x02\x07\x00\x00\x00C\x00:\x00\\\x00o\x00.\x007\x00z\x00");
104추가: } else {
105추가: expected.extend(b"\x01\x05\x00\x00\x00/o.7z");
106추가: }
107추가: expected.extend([0, 0, 0]);
108추가: expected.extend(u64::MAX.to_le_bytes());
109추가: expected.extend((16u64 * 1024 * 1024 * 1024).to_le_bytes());
110추가: expected.extend(10_000u32.to_le_bytes());
111추가: let bytes = encode(&Message::Start(start.clone()));
112추가: assert_eq!(bytes, raw(1, &expected));
113추가: match decode(&bytes) {
114추가: Message::Start(actual) => assert_eq!(actual, start),
115추가: other => panic!("{other:?}"),
116추가: }
117추가: let guarded = guarded(start);
118추가: assert!(guarded.valid());
119추가: expected.extend(u64::MAX.to_le_bytes());
120추가: expected.extend((64u64 * 1024 * 1024 * 1024).to_le_bytes());
121추가: expected.extend(200_000u32.to_le_bytes());
122추가: expected.push(0);
123추가: let bytes = encode(&Message::StartGuarded(guarded.clone()));
124추가: assert_eq!(bytes, raw(6, &expected));
125추가: match decode(&bytes) {
126추가: Message::StartGuarded(actual) => assert_eq!(actual, guarded),
127추가: other => panic!("{other:?}"),
128추가: }
129추가: }
130추가: }
131추가:
132추가: #[test]
133추가: fn unsupported_options_remain_structurally_valid_without_silent_conversion() {
134추가: for solid in [false, true] {
135추가: for encryption in [Encryption::None, Encryption::Aes256] {
136추가: let mut action = request(false);
137추가: if let Action::CreateSevenZip {
138추가: solid: actual_solid,
139추가: encryption: actual_encryption,
140추가: ..
141추가: } = &mut action
142추가: {
143추가: *actual_solid = solid;
144추가: *actual_encryption = encryption;
145추가: }
146추가: let start = start(action);
147추가: match decode(&encode(&Message::Start(start.clone()))) {
148추가: Message::Start(actual) => assert_eq!(actual, start),
149추가: other => panic!("{other:?}"),
150추가: }
151추가: }
152추가: }
153추가: }
154추가:
155추가: #[test]
156추가: fn creation_never_accepts_interactive_conflict_requests() {
157추가: let start = start(request(false));
158추가: reject_encode(Message::StartInteractive(start.clone()));
159추가: let bytes = encode(&Message::Start(start.clone()));
160추가: reject_decode(&raw(4, &bytes[32..]));
161추가: let mut guarded = guarded(start);
162추가: guarded.interactive = true;
163추가: assert!(!guarded.valid());
164추가: reject_encode(Message::StartGuarded(guarded));
165추가: let mut bytes = encode(&Message::StartGuarded(self::guarded(self::start(request(
166추가: false,
167추가: )))));
168추가: *bytes.last_mut().unwrap() = 1;
169추가: reject_decode(&bytes);
170추가: }
171추가:
172추가: #[test]
173추가: fn truncated_unknown_and_trailing_creation_fields_are_rejected() {
174추가: for windows in [false, true] {
175추가: let bytes = encode(&Message::Start(start(request(windows))));
176추가: let body = &bytes[32..];
177추가: for length in 0..body.len() {
178추가: reject_decode(&raw(1, &body[..length]));
179추가: }
180추가: let mut trailing = body.to_vec();
181추가: trailing.push(0);
182추가: reject_decode(&raw(1, &trailing));
183추가: let method = body.len() - 20 - 3;
184추가: for (at, value) in [(0, 5), (method, 1), (method + 1, 2), (method + 2, 2)] {
185추가: let mut body = body.to_vec();
186추가: body[at] = value;
187추가: reject_decode(&raw(1, &body));
188추가: }
189추가: }
190추가: }
191추가:
192추가: #[test]
193추가: fn guarded_approval_never_expands_source_vector_string_or_path_wire_limits() {
194추가: let mut action = request(false);
195추가: if let Action::CreateSevenZip { sources, .. } = &mut action {
196추가: sources[0].archive_name = "a".repeat(32_768);
197추가: }
198추가: let guarded = guarded(start(action.clone()));
199추가: assert!(matches!(
200추가: decode(&encode(&Message::StartGuarded(guarded))),
201추가: Message::StartGuarded(_)
202추가: ));
203추가: if let Action::CreateSevenZip { sources, .. } = &mut action {
204추가: sources[0].archive_name.push('a');
205추가: }
206추가: reject_encode(Message::StartGuarded(self::guarded(start(action))));
207추가: for windows in [false, true] {
208추가: let mut action = request(windows);
209추가: if let Action::CreateSevenZip { sources, .. } = &mut action {
210추가: sources[0].path = if windows {
211추가: NativePath::Windows(vec![b'a' as u16; 32_769])
212추가: } else {
213추가: NativePath::Unix(vec![b'a'; 32_769])
214추가: };
215추가: }
216추가: reject_encode(Message::StartGuarded(self::guarded(start(action))));
217추가: }
218추가: let mut action = request(false);
219추가: if let Action::CreateSevenZip { sources, .. } = &mut action {
220추가: *sources = vec![sources[0].clone(); 32_769];
221추가: }
222추가: reject_encode(Message::StartGuarded(self::guarded(start(action))));
223추가: let bytes = encode(&Message::StartGuarded(self::guarded(start(request(false)))));
224추가: for at in [1, 6, 12] {
225추가: let mut body = bytes[32..].to_vec();
226추가: body[at..at + 4].copy_from_slice(&32_769u32.to_le_bytes());
227추가: reject_decode(&raw(6, &body));
228추가: }
229추가: }
230추가:
231추가: #[test]
232추가: fn action_kind_events_keep_existing_tags_and_append_creation_tag_four() {
233추가: for (tag, action) in [
234추가: ActionKind::List,
235추가: ActionKind::Extract,
236추가: ActionKind::CreateZip,
237추가: ActionKind::Preview,
238추가: ActionKind::CreateSevenZip,
239추가: ]
240추가: .into_iter()
241추가: .enumerate()
242추가: {
243추가: let encryption = action != ActionKind::CreateSevenZip;
244추가: let bytes = encode(&Message::Accepted { action, encryption });
245추가: assert_eq!(bytes, raw(100, &[tag as u8, u8::from(encryption)]));
246추가: assert!(
247추가: matches!(decode(&bytes), Message::Accepted { action: actual, encryption: value } if actual == action && value == encryption)
248추가: );
249추가: let scope = ResourceScope {
250추가: entries: true,
251추가: ..ResourceScope::default()
252추가: };
253추가: let bytes = encode(&Message::ResourceRequired {
254추가: challenge_id: 23,
255추가: action,
256추가: scope,
257추가: usage: ResourceUsage::default(),
258추가: soft_limits: Limits::default(),
259추가: ceiling: guarded(start(request(false))).ceiling,
260추가: });
261추가: assert_eq!(bytes[32 + 8], tag as u8);
262추가: assert!(
263추가: matches!(decode(&bytes), Message::ResourceRequired { action: actual, scope: value, .. } if actual == action && value == scope)
264추가: );
265추가: let mut body = bytes[32..].to_vec();
266추가: body[8] = 5;
267추가: reject_decode(&raw(110, &body));
268추가: }
269추가: reject_decode(&raw(100, &[5, 0]));
270추가: }
271추가:
272추가: #[test]
273추가: fn zip_methods_and_existing_request_bytes_stay_independent() {
274추가: for (tag, method) in [(0, Method::Store), (1, Method::Deflate)] {
275추가: let action = Action::CreateZip {
276추가: sources: Vec::new(),
277추가: output_file: NativePath::Unix(b"/a.zip".to_vec()),
278추가: method,
279추가: encryption: Encryption::Aes256,
280추가: };
281추가: let start = start(action);
282추가: let mut body = b"\x02\x00\x00\x00\x00\x01\x06\x00\x00\x00/a.zip".to_vec();
283추가: body.extend([tag, 1]);
284추가: body.extend(u64::MAX.to_le_bytes());
285추가: body.extend((16u64 * 1024 * 1024 * 1024).to_le_bytes());
286추가: body.extend(10_000u32.to_le_bytes());
287추가: assert_eq!(encode(&Message::Start(start.clone())), raw(1, &body));
288추가: assert!(matches!(decode(&raw(1, &body)), Message::Start(actual) if actual == start));
289추가: body[16] = 2;
290추가: reject_decode(&raw(1, &body));
291추가: }
292추가: }
293추가:
294추가: struct Temporary(PathBuf);
295추가: impl Temporary {
296추가: fn new() -> Self {
297추가: let root = std::env::var_os("TMPDIR")
298추가: .map(PathBuf::from)
299추가: .unwrap_or_else(|| {
300추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")
301추가: });
302추가: fs::create_dir_all(&root).unwrap();
303추가: let path = root.canonicalize().unwrap().join(format!(
304추가: "zipelo-seven-create-{}-{}",
305추가: std::process::id(),
306추가: NEXT.fetch_add(1, Ordering::Relaxed)
307추가: ));
308추가: fs::create_dir(&path).unwrap();
309추가: Self(path)
310추가: }
311추가: fn run(&self, message: Message) -> Vec<Message> {
312추가: let output = self.0.join("saved.7z");
313추가: fs::write(&output, b"existing user data").unwrap();
314추가: let bytes = encode(&message);
315추가: let mut child = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
316추가: .env("TMPDIR", self.0.join("unavailable-temp"))
317추가: .env("TMP", self.0.join("unavailable-temp"))
318추가: .env("TEMP", self.0.join("unavailable-temp"))
319추가: .stdin(Stdio::piped())
320추가: .stdout(Stdio::piped())
321추가: .stderr(Stdio::piped())
322추가: .spawn()
323추가: .unwrap();
324추가: child.stdin.take().unwrap().write_all(&bytes).unwrap();
325추가: let output = child.wait_with_output().unwrap();
326추가: assert!(output.status.success(), "{:?}", output.stderr);
327추가: assert!(output.stderr.is_empty());
328추가: let mut reader = Reader::new(output.stdout.as_slice());
329추가: let mut events = Vec::new();
330추가: while let Some((job, _, message)) = reader.read().unwrap() {
331추가: assert_eq!(job, 17);
332추가: events.push(message);
333추가: }
334추가: assert_eq!(
335추가: fs::read(self.0.join("saved.7z")).unwrap(),
336추가: b"existing user data"
337추가: );
338추가: assert_eq!(fs::read_dir(&self.0).unwrap().count(), 1);
339추가: events
340추가: }
341추가: }
342추가: impl Drop for Temporary {
343추가: fn drop(&mut self) {
344추가: fs::remove_dir_all(&self.0).expect("7z 생성 시험 임시 폴더 정리에 실패함");
345추가: }
346추가: }
347추가:
348추가: #[test]
349추가: fn unsupported_options_fail_before_questions_or_file_access() {
350추가: let temporary = Temporary::new();
351추가: for solid in [false, true] {
352추가: for encryption in [Encryption::None, Encryption::Aes256] {
353추가: if !solid && encryption == Encryption::None {
354추가: continue;
355추가: }
356추가: for kind in [1, 6, 7] {
357추가: let action = Action::CreateSevenZip {
358추가: sources: vec![Source {
359추가: path: NativePath::from_path(&temporary.0.join("missing/source")),
360추가: archive_name: "source".to_owned(),
361추가: }],
362추가: output_file: NativePath::from_path(&temporary.0.join("saved.7z")),
363추가: method: SevenZipMethod::Lzma2,
364추가: solid,
365추가: encryption,
366추가: };
367추가: let start = start(action);
368추가: let message = if kind == 1 {
369추가: Message::Start(start)
370추가: } else {
371추가: let mut guarded = guarded(start);
372추가: if kind == 7 {
373추가: guarded.ceiling = guarded.start.limits;
374추가: }
375추가: Message::StartGuarded(guarded)
376추가: };
377추가: let events = temporary.run(message);
378추가: assert_eq!(events.len(), 2, "{events:?}");
379추가: assert!(matches!(
380추가: events[0],
381추가: Message::Accepted {
382추가: action: ActionKind::CreateSevenZip,
383추가: encryption: false
384추가: }
385추가: ));
386추가: let terminal = terminal(&events);
387추가: assert_eq!(terminal.outcome, Outcome::Failed);
388추가: assert_eq!(terminal.error, ErrorCode::UnsupportedFeature);
389추가: assert_eq!(terminal.publication, Publication::None);
390추가: assert_eq!(terminal.created_count, 0);
391추가: assert_eq!(terminal.retained_partial_count, 0);
392추가: assert_eq!(terminal.cleanup, Cleanup::Complete);
393추가: assert_eq!(terminal.durability, Durability::NotApplicable);
394추가: }
395추가: }
396추가: }
397추가: }
398추가:
399추가: #[test]
400추가: fn existing_runtime_encryption_capability_is_preserved() {
401추가: let temporary = Temporary::new();
402추가: let events = temporary.run(Message::Start(start(Action::List {
403추가: archive: NativePath::from_path(&temporary.0.join("missing.zip")),
404추가: })));
405추가: assert!(matches!(
406추가: events[0],
407추가: Message::Accepted {
408추가: action: ActionKind::List,
409추가: encryption: true
410추가: }
411추가: ));
412추가: assert_eq!(terminal(&events).outcome, Outcome::Failed);
413추가: }
추가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

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기