team-ljyzipelo

공개

Merge pull request #126 from Team-LJY/features/split-sevenzip

분할 7z 목록과 해제 지원
작성자
LeeJunyoung
작성 시각
커밋
c61cd2fd4514cba07badd62e579e05dc8f589c47
이 시점의 파일 보기

변경된 파일 58개

+2,289-49

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

수정docs/ui-scenario-guide.md+13-0
@@ -168,3 +168,16 @@ Ubuntu 제거 안내는 패키지 관리자 터미널 출력입니다. 이전
168168실제 압축파일에서는 파일 하나를 선택하고 [미리보기]를 직접 눌렀을 때만 읽기를 시작한다.
169169닫은 뒤 선택, 폴더 위치와 스크롤을 유지하고 실행 전 키보드 포커스로 돌아간다.
170170시나리오의 텍스트와 이미지는 화면 점검용이며 디코더 검증은 실제 압축파일로 별도 수행한다.
171추가:
172추가: ### 분할 7z
173추가:
174추가: 조각 오류와 제외 형식 안내는 주 창 안의 작업 결과 모달로 표시한다. 별도 결과 창 전환 없이 파일명과 재시도 방법을 확인할 수 있다.
175추가:
176추가: - split-archive: .7z.001 목록과 미리보기 비활성화. 분할 입력은 목록 보기와 풀기만 지원.
177추가: - split-first-volume: .7z.002 등 선택 시 필요한 .001의 정확한 이름 안내. 자동으로 다른 파일을 열지 않음.
178추가: - split-missing-volume: 확정된 중간 누락의 파일명과 같은 폴더에 모든 조각을 모은 뒤 .001을 다시 여는 방법 안내.
179추가: - split-incomplete: 불완전하거나 손상된 묶음 안내. 마지막 누락 파일명을 추측하지 않음.
180추가: - split-unsupported: 실제 분할 ZIP의 UnsupportedFeature 오류로 분할 ZIP, RAR과 분할 압축 만들기 미지원 안내를 표시한다. UnsupportedFormat도 같은 안내를 사용한다.
181추가: - split-source-changed: 목록 이후 조각 변경 시 다시 열기 안내.
182추가:
183추가: 운영체제 기본 열기 창에서 같은 폴더의 첫 조각 `.7z.001`을 선택한다. 분할 묶음은 최대 999개이며 목록 열람 성공은 전체 데이터 무결성 검증 완료를 뜻하지 않는다. 실제 분할 파일 처리는 작업자 구현 후 독립 도구 표본으로 확인한다. Windows와 Wayland에서 첫 조각 선택, 누락 이름, .001 재시도 안내와 닫기를 확인하며, 위 디자인 상황은 실제 파일 검증을 대신하지 않는다.
수정experiments/rust-archive-worker/README.md+56-0
@@ -175,3 +175,59 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
175175- PNG의 제한된 Decoder와 행/프레임 API는 [공식 문서](https://docs.rs/png/0.18.1/png/)를 참고한다. 라이브러리 내부 할당 제한을 작업자 전체 RSS의 강제 상한으로 표현하지 않는다. 엄격한 항목 길이, 치수와 결과 길이 검사를 별도로 적용한다.
176176- backend는 작업자 protocol.rs, wire.rs, runtime 및 디코더, 작업자 시험과 packaging/licenses.py 고지를 맡는다. frontend는 앱 재조립/전송 제어, 화면과 앱 시험, --ui-scenario 및 가이드를 맡는다. 같은 원격 브랜치는 양쪽 결과를 확인하며 순차 갱신하고 공용 타입 변경은 이 계약 합의 후 backend가 반영한다.
177177- 시험은 바이트/치수/픽셀 경계, UTF-8 청크 경계와 BOM, 형식 불일치/APNG/손상, 암호와 solid 예산, malformed/순서/중복/초과 전송, 64개 큐 역압과 디코딩 및 전송 중 취소, 늦은 완료 폐기와 정리 및 원본 해시 보존을 포함한다.
178추가:
179추가: ## 분할 7z 계약
180추가:
181추가: 상태: 2026-11-14 frontend 합의 완료. [PLANS 8.8](../../docs/PLANS.md)의 묶음 ListId, MissingVolume 및 VolumeProblem과 조각 탐색, 캡처, 재검증 및 실제 목록/해제를 구현했다. 같은 PR에서 앱 수신, 화면과 상황별 디버깅 명령을 연결했으며 실제 분할 파일의 Windows/Wayland 화면 통합 검증과 독립 리뷰는 남아 있다. 기준은 main ecad460이다.
182추가:
183추가: ### 지원 범위와 조각 탐색
184추가:
185추가: - 기존 List와 Extract 요청의 archive에 첫 조각의 NativePath를 넣는다. 새 Action이나 별도의 조각 경로 목록을 받지 않는다. 같은 폴더, 같은 기본 이름과 세 자리 ASCII 번호를 가진 .7z.001부터 .999까지를 숫자 순서로 처리한다. 최대 999개는 자원 승인으로 늘리지 않는다.
186추가: - 첫 조각이 아닌 .7z.002 등을 고르면 .7z.001의 정확한 기본 파일명을 안내하고 InvalidRequest로 끝낸다. 첫 조각을 자동으로 다시 열지 않는다. 분할 ZIP, .z01, RAR, 임의 이름과 분할 생성은 지원하지 않는다. 분할 입력의 Preview는 이번 범위에서 제외하고 UnsupportedFeature로 끝내며 일반 해제를 자동 실행하지 않는다.
187추가: - 전체 폴더의 이름 목록을 메모리에 모으지 않는다. 최대 999개 조각 상태만 유지하면서 디렉터리 항목마다 취소와 기한을 확인한다. 조각 수, 논리 오프셋과 합산 길이의 변환 및 덧셈은 모두 검사한다.
188추가: - 조각의 크기가 모두 같다고 가정하지 않는다. 이름과 연속 번호, 각 파일의 실제 길이 및 7z 헤더에 선언된 전체 논리 끝 위치를 검증한다. 빈 조각, 선언 길이보다 짧거나 긴 묶음과 초과 조각은 오류다. 마지막 조각 누락과 마지막 파일의 잘림을 구분할 정보가 없으면 누락 이름을 추측하지 않고 불완전한 묶음으로 안내한다.
189추가: - 중간 번호가 비어 있고 그 뒤 번호가 실제로 있으면 정확한 누락 이름을 안내한다. .009와 .010은 숫자 순서로 이어야 한다. 범위를 넘는 같은 이름의 .1000 조각이 발견되면 Limit로 거부하며 앞 999개만 임의로 처리하지 않는다.
190추가: - 다른 묶음의 혼입이나 순서가 바뀐 데이터는 7z 구조와 존재하는 CRC 등으로 검출 가능한 경우 거부한다. 형식에 원래 없는 조각별 식별 정보나 CRC가 없는 내용을 새로 검증했다고 보장하지 않는다. 조각 경계만 다른 동일한 논리 바이트열은 같은 7z 데이터로 해독할 수 있지만 묶음 동일성 토큰은 달라진다.
191추가:
192추가: ### 경로, 캡처와 변경 감지
193추가:
194추가: - 사용자가 지정한 첫 조각의 부모 디렉터리를 한 번 열어 고정하고 그 디렉터리의 식별자를 보관한다. 이후 형제 조각은 검증된 기본 파일명과 숫자 접미사로만 생성해 고정 부모 안에서 연다. 조각 이름에 포함된 경로 구분자나 상위 경로를 허용하지 않는다.
195추가: - 각 조각의 마지막 경로 요소를 링크를 따라가지 않는 방식으로 열고 핸들로 일반 파일인지 확인한다. Unix 심볼릭 링크와 Windows reparse point, 디렉터리 및 특수 파일을 거부한다. 부모 경로와 파일의 식별자를 다시 확인하며 디렉터리 교체나 고정 부모 밖으로의 경로 이탈은 UnsafePath 또는 SourceChanged로 중단한다.
196추가: - 각 파일의 핸들 식별자, 길이와 수정 시각을 읽기 전후에 비교하고 읽는 동안 SHA256을 구한다. 동일 파일 식별자가 여러 조각 이름으로 나타나는 별칭도 거부한다. 내용 검사를 수정 시각 비교만으로 대신하지 않는다.
197추가: - 논리 입력은 기존 이름 없는 임시 Snapshot에 64 KiB 이하 청크로 캡처한다. 파일 경계를 넘는 헤더와 데이터도 이어 읽으며 전체 크기의 메모리 배열이나 합친 영구 파일을 만들지 않는다. 원본 조각을 쓰거나 이름을 바꾸지 않는다. 입력 사본과 해독 스테이징 및 목적지 공간을 기존 정책으로 계산하고 임시 공간 실패를 보고한다.
198추가: - 캡처 뒤 모든 조각을 다시 열어 부모 및 파일 식별자, 길이와 내용 해시를 대조한다. 목록의 ListEnd 전과 해제의 첫 목적지 게시 전에도 전체 조각을 재검증한다. 목록 뒤 중간 또는 마지막 조각의 내용, 파일 식별자와 길이가 달라지거나 조각 수가 바뀌면 SourceChanged이며 확정된 중간 누락은 MissingVolume이다. 첫 게시 전 발견한 실패에는 Output을 보내지 않는다.
199추가: - 첫 게시 검증 여부는 출력 생성 개수와 별도로 보관한다. 기존 폴더를 건너뛸 때는 전체 원본을 다시 읽지 않고 실제 첫 폴더 생성 또는 파일 게시 직전에 한 번만 검증한다. 실제 게시가 없는 작업은 정상 완료 전에 한 번 검증하며, 충돌 질문에서 취소하면 게시용 검증을 시작하지 않는다.
200추가: - 이후 해독과 게시에는 검증한 불변 Snapshot만 사용한다. 마지막 재검증 직후 발생하는 동일 계정의 경합을 원자적으로 차단하거나 파일 시스템 전체의 동시 스냅샷을 제공한다고 보장하지 않는다. 이미 게시한 출력이 있는 일반 실패와 취소는 기존 실제 게시 및 정리 집계를 유지하며 작업 전체를 되돌린다고 안내하지 않는다.
201추가:
202추가: ### 묶음 ListId와 바이트 계약
203추가:
204추가: 프레임 헤더 버전 1, 본문 1 MiB 상한과 기존 필드 및 태그는 유지한다. 아래 확장을 공용 타입과 코덱에 추가했다. 구버전 작업자 거부 시 단일 파일 요청이나 일반 해제로 자동 재시도하지 않는다.
205추가:
206추가: - SourceObject에 SplitSevenZip { manifest_sha256: [u8; 32] }를 태그 3으로 추가한다. Unix=1과 Windows=2는 유지한다. 분할 7z의 ListId는 catalog_version=2, format=SevenZip, source_object=SplitSevenZip이어야 한다. archive_bytes는 모든 조각의 길이 합계이고 archive_sha256은 번호 순서로 이어진 논리 입력 바이트의 SHA256이다.
207추가: - 기존 단일 입력은 catalog_version=1과 Unix 또는 Windows 식별자를 그대로 사용한다. 버전, 형식과 SourceObject의 허용 조합을 코덱과 수신기에서 검증하고 그 밖의 조합은 Protocol로 거부한다. 첫 조각 하나의 식별자나 해시를 묶음 식별자로 사용하지 않는다.
208추가: - manifest_sha256의 입력은 ASCII `zipelo.split7z.v1`와 NUL 한 바이트, 부모 디렉터리의 Unix 또는 Windows SourceObject, 조각 수 u16, 각 조각의 번호 u16, 기본 파일명 NativePath, 파일의 Unix 또는 Windows SourceObject, 길이 u64, 내용 SHA256 32바이트 순서다. 조각은 번호 순서다. 정수는 little-endian이고 NativePath 및 단일 SourceObject는 기존 wire 인코딩을 재사용한다. 내부 성분에는 SplitSevenZip을 중첩하지 않는다.
209추가: - 앱은 ListId를 수정하지 않고 목록 이후 Extract에 그대로 전달한다. EntryIds의 필수 ListId 규칙은 유지한다. Selection::All과 list_id=None인 기존 일회성 요청 정책은 유지하되 이 경우에도 전체 묶음을 새로 캡처하고 검증한다. 토큰은 내용과 객체의 동일성을 확인하는 값이며 발신자 인증이나 파일 접근 권한을 부여하는 값은 아니다.
210추가:
211추가: ### 오류와 화면 전달
212추가:
213추가: - ErrorCode::MissingVolume을 기존 0~13 뒤 태그 14로 추가한다. 확정된 중간 조각 누락에만 사용한다. 목록 뒤 조각 교체, 길이 및 내용 변경은 SourceChanged, 불완전한 묶음이나 7z 무결성 실패는 Integrity, 안전하지 않은 경로는 UnsafePath, 읽기 실패는 Io, 합산 자원 상한이나 조각 수 초과는 Limit로 구분한다.
214추가: - Message::VolumeProblem을 kind 114로 추가한다. 본문은 reason u8, volume NativePath 순서다. reason은 FirstVolumeRequired=0, MissingVolume=1, IncompleteSet=2다. volume은 경로 구분자가 없는 기본 파일명이다. 앞의 두 사유는 정확히 필요한 .001 또는 누락 번호의 이름이고 IncompleteSet은 선택한 첫 조각의 이름이다. 불명확한 마지막 조각 이름을 필요한 파일로 단정하지 않는다.
215추가: - VolumeProblem은 Accepted 이후 Failed Terminal 전에 작업당 최대 한 번 보내는 오류 부가 정보다. 응답 메시지나 대기 질문은 추가하지 않는다. FirstVolumeRequired의 Terminal 오류는 InvalidRequest, MissingVolume은 MissingVolume, IncompleteSet은 Integrity다. 기대 ListId와의 불일치로 SourceChanged를 보내는 경우 VolumeProblem은 생략한다. 확정된 누락은 MissingVolume 알림과 오류로 유지한다.
216추가: - 앱은 활성 job_id에 속하는 알림만 보관하고 정상 Terminal과 양쪽 EOF 및 자식 회수를 확인한 뒤 기존 오류 화면에 반영한다. 알림만으로 성공이나 작업 종료를 판단하지 않는다. 다른 작업 ID, 중복 알림, Failed가 아닌 종료와 알림의 불일치는 Protocol로 처리한다. 취소하거나 다른 파일을 연 화면의 늦은 오류는 다시 표시하지 않는다.
217추가: - 파일명은 원래 NativePath로 전달하고 화면에서는 제어 문자를 안전하게 표시한다. 앱은 Terminal.detail 문자열에서 파일명을 파싱하지 않는다. 확정된 누락에는 표시된 이름의 조각을 같은 폴더에 모은 뒤 .001을 다시 열도록 안내한다. 불완전한 묶음에는 모든 조각의 존재와 손상을 확인하도록 안내하고 특정 파일의 누락을 단정하지 않는다. 알림의 이름으로 임의 파일을 찾거나 자동으로 여는 흐름은 없다.
218추가:
219추가: ### 자원, 취소와 검증 인계
220추가:
221추가: - Limits.input은 조각별이 아닌 전체 논리 입력의 합계에 한 번 적용한다. 재검증을 위한 실제 읽기 비용은 기한과 취소 감시에 포함하되 입력 바이트 예산을 두 번 소비하지 않는다. 해제 출력, 항목 수, 7z 메타데이터와 압축률 및 승인 후 상한도 조각 경계마다 초기화하지 않는다.
222추가: - 기존 ResourceRequired/Reply, 암호 질문, 충돌 및 취소와 자식 회수 정책을 유지한다. 기본 및 승인 상한, 메타데이터 정책과 질문 대기 시간은 변경하지 않는다. 탐색, 캡처, 재해시와 정리에서 성공한 작업을 진행 활동으로 기록하며 읽기와 해시 청크마다 취소를 확인한다.
223추가: - 탐색과 읽기 및 재검증에는 기존 Stage::Scan, Read, Verify를 사용한다. 합산 길이가 확정되기 전에는 total_bytes=None을 유지하며 길이를 추측하지 않는다. 조각별 대형 메시지 목록이나 새 데이터 큐는 추가하지 않는다.
224추가: - 작업자는 목록의 메타데이터 검증과 해제의 데이터 무결성 검증을 구분한다. 패킹 데이터는 기존 7z 해독과 무결성 검증을 통과한 뒤에만 게시하며, 목록 열람 성공을 전체 파일 데이터 검증 완료로 표현하지 않는다. 기존 지원 압축 방식과 암호 범위만 제공하고 새 해독 라이브러리는 도입하지 않는다.
225추가: - backend는 조각 탐색과 캡처, 묶음 동일성, 공용 타입 및 wire와 작업자 회귀 시험을 담당한다. frontend는 .001 열기와 제외 형식 및 조각 오류 안내, 묶음 ListId 보존, 분할 미리보기 실행 제한, 수신 검증, --ui-scenario와 가이드 및 Windows/Wayland 실기를 담당한다. 구현 변경은 계약 합의와 공용 타입 반영 뒤 파일 소유 범위를 나눠 연결한다.
226추가: - 독립 도구 표본의 목록과 해제 해시, 헤더 및 데이터의 조각 경계, .009/.010, 서로 다른 조각 길이, 999개와 초과, 중간 및 마지막 누락, 잘림, 검출 가능한 혼입과 순서 변경을 시험한다. 목록 후 중간/마지막 조각의 같은 길이 교체와 내용 변경, 실행 중 변경, 링크 및 부모 교체, 길이 오버플로와 합산 예산, 승인 후 한도, 암호, 취소와 충돌도 회귀로 확인한다.
227추가: - 새 시험 코드는 저장소 루트 tests/에만 둔다. 작업 파일과 캐시 및 일회성 로그는 프로젝트의 tests/work/split7z 한 곳에 두고 clone 안에 다시 tests/work나 생성용 tests/ci 캐시를 만들지 않는다. PR 병합 또는 종료 뒤 담당자가 해당 작업 폴더와 캐시를 정리한다.
228추가:
229추가: ### 독립 분할 표본
230추가:
231추가: - `tests/rust-archive-worker/fixtures/split7z/`는 Ubuntu `7zip 26.00+dfsg-1`의 7-Zip 26.00이 `-v64b`로 직접 만든 조각이다. 일반 solid LZMA2, 헤더 암호화와 본문 암호화 묶음을 포함한다. 테스트에만 쓰는 독립 실행 도구이며 제품 의존성이나 배포 파일에 추가하지 않는다.
232추가: - 생성기 `tests/rust-archive-worker/split_fixtures.py`가 독립 도구로 다시 풀어 원본 바이트와 비교하고 `manifest.json`에 도구 버전, 옵션, 각 조각과 논리 입력 및 해제 결과의 SHA256을 기록한다. 암호 표본의 공개 시험 암호는 `zipelo-split-test`다. 새 표본을 만들 때 `--tool`에 7-Zip 실행 파일을, `--work`와 `--output`에는 `tests/work/split7z` 아래의 비어 있는 별도 하위 폴더를 지정한다.
233추가: - 작업자 회귀 시험은 추적된 일반 표본의 두 파일을 풀어 기준 바이트와 해시를 대조한다. 암호화 표본은 기존 7z 정책대로 UnsupportedFeature이며 새 암호 지원이나 암호 질문을 추가하지 않는다. 목록 성공은 패킹 데이터 전체의 무결성 검증을 뜻하지 않는다.
수정experiments/rust-archive-worker/src/create_sources.rs+8-2
@@ -142,10 +142,16 @@ impl Input {
142142 Ok(())
143143 }
144144 fn open_child(&self, path: &Path, name: &str) -> Result<Self> {
145추가: self.open_named(path, std::ffi::OsStr::new(name))
146추가: }
147추가: pub(crate) fn open_named(&self, path: &Path, name: &std::ffi::OsStr) -> Result<Self> {
148추가: if !NativePath::from_path(Path::new(name)).is_basename() {
149추가: return Err(ErrorCode::UnsafePath);
150추가: }
145151 #[cfg(target_os = "linux")]
146152 {
147153 let _ = path;
148삭제: let file = Self::read(Self::child(&self.file, std::ffi::OsStr::new(name))?)?;
154추가: let file = Self::read(Self::child(&self.file, name)?)?;
149155 Self::validate(&file)?;
150156 Ok(Self { file })
151157 }
@@ -154,7 +160,7 @@ impl Input {
154160 Self::open(&path.join(name))
155161 }
156162 }
157삭제: fn children(&self, path: &Path) -> Result<fs::ReadDir> {
163추가: pub(crate) fn children(&self, path: &Path) -> Result<fs::ReadDir> {
158164 #[cfg(target_os = "linux")]
159165 {
160166 use std::os::fd::AsRawFd;
수정experiments/rust-archive-worker/src/filesystem.rs+19-5
@@ -614,17 +614,29 @@ pub(crate) fn directory_with(
614614 name: &str,
615615 check: &mut impl Monitor,
616616) -> Result<(bool, Durability, Option<ErrorCode>)> {
617삭제: let (d, leaf) = parent_with(root, name, false, check)?.ok_or(ErrorCode::Io)?;
618삭제: if completed(d.child(&leaf, false), check)?.is_some() {
617추가: directory_steps(root, name, &mut |step| match step {
618추가: PublishStep::Check | PublishStep::Commit => check.check(),
619추가: PublishStep::Activity => check.activity(),
620추가: })
621추가: }
622추가: pub(crate) fn directory_steps(
623추가: root: &Dir,
624추가: name: &str,
625추가: check: &mut impl FnMut(PublishStep) -> Result<()>,
626추가: ) -> Result<(bool, Durability, Option<ErrorCode>)> {
627추가: let (d, leaf) =
628추가: parent_with(root, name, false, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?;
629추가: if completed(d.child(&leaf, false), &mut PublicationMonitor(check))?.is_some() {
619630 return Ok((false, Durability::NotApplicable, None));
620631 }
632추가: check(PublishStep::Commit)?;
621633 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
622삭제: let progress_error = completed(Ok(()), check).err();
634추가: let progress_error = completed(Ok(()), &mut PublicationMonitor(check)).err();
623635 Ok(match d.sync_checked() {
624636 Ok(durability) => (
625637 true,
626638 durability,
627삭제: progress_error.or_else(|| completed(Ok(()), check).err()),
639추가: progress_error.or_else(|| completed(Ok(()), &mut PublicationMonitor(check)).err()),
628640 ),
629641 Err(error) => (true, Durability::Failed, Some(error)),
630642 })
@@ -768,6 +780,8 @@ pub(crate) fn publish_reader_steps(
768780 &mut PublicationMonitor(check),
769781 );
770782 let mut finish = written.and(closed).and_then(|_| {
783추가: check(PublishStep::Commit)?;
784추가: // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함.
771785 if let Some(expected) = replace {
772786 if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref()
773787 != Some(expected)
@@ -775,7 +789,7 @@ pub(crate) fn publish_reader_steps(
775789 return Err(ErrorCode::Conflict);
776790 }
777791 }
778삭제: check(PublishStep::Commit)
792추가: Ok(())
779793 });
780794 let mut temp_consumed = false;
781795 if finish.is_ok() {
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -12,6 +12,7 @@ pub mod resources;
1212pub mod runtime;
1313mod seven_zip;
1414mod space;
15추가: mod split_seven_zip;
1516mod spool;
1617mod streaming;
1718pub mod wire;
수정experiments/rust-archive-worker/src/protocol.rs+51-0
@@ -25,6 +25,22 @@ impl NativePath {
2525 Self::Windows(path.as_os_str().encode_wide().collect())
2626 }
2727 }
28추가: pub fn is_basename(&self) -> bool {
29추가: match self {
30추가: Self::Unix(bytes) => {
31추가: !bytes.is_empty()
32추가: && bytes != b"."
33추가: && bytes != b".."
34추가: && !bytes.iter().any(|byte| matches!(*byte, 0 | b'/' | b'\\'))
35추가: }
36추가: Self::Windows(units) => {
37추가: !units.is_empty()
38추가: && units != &[b'.' as u16]
39추가: && units != &[b'.' as u16, b'.' as u16]
40추가: && !units.iter().any(|unit| matches!(*unit, 0 | 47 | 92 | 58))
41추가: }
42추가: }
43추가: }
2844 pub fn to_path(&self) -> Result<PathBuf, ErrorCode> {
2945 #[cfg(unix)]
3046 if let Self::Unix(bytes) = self {
@@ -150,6 +166,9 @@ pub enum SourceObject {
150166 volume_serial: u64,
151167 file_id: [u8; 16],
152168 },
169추가: SplitSevenZip {
170추가: manifest_sha256: [u8; 32],
171추가: },
153172}
154173#[derive(Clone, Debug, PartialEq, Eq)]
155174pub struct ListId {
@@ -159,6 +178,18 @@ pub struct ListId {
159178 pub archive_bytes: u64,
160179 pub archive_sha256: [u8; 32],
161180}
181추가: impl ListId {
182추가: pub fn valid(&self) -> bool {
183추가: matches!(
184추가: (self.catalog_version, self.format, &self.source_object),
185추가: (
186추가: 1,
187추가: _,
188추가: SourceObject::Unix { .. } | SourceObject::Windows { .. }
189추가: ) | (2, Format::SevenZip, SourceObject::SplitSevenZip { .. })
190추가: )
191추가: }
192추가: }
162193#[derive(Clone, Debug, PartialEq, Eq)]
163194pub enum Selection {
164195 All,
@@ -312,6 +343,22 @@ pub enum ErrorCode {
312343 SourceChanged,
313344 InvalidRequest,
314345 DiskFull,
346추가: MissingVolume,
347추가: }
348추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
349추가: pub enum VolumeProblemReason {
350추가: FirstVolumeRequired,
351추가: MissingVolume,
352추가: IncompleteSet,
353추가: }
354추가: impl VolumeProblemReason {
355추가: pub fn terminal_error(self) -> ErrorCode {
356추가: match self {
357추가: Self::FirstVolumeRequired => ErrorCode::InvalidRequest,
358추가: Self::MissingVolume => ErrorCode::MissingVolume,
359추가: Self::IncompleteSet => ErrorCode::Integrity,
360추가: }
361추가: }
315362}
316363#[derive(Clone, Copy, Debug, PartialEq, Eq)]
317364pub enum Publication {
@@ -437,6 +484,10 @@ pub enum Message {
437484 total_bytes: u64,
438485 sha256: [u8; 32],
439486 },
487추가: VolumeProblem {
488추가: reason: VolumeProblemReason,
489추가: volume: NativePath,
490추가: },
440491 Terminal(Terminal),
441492 CancelAck {
442493 request_sequence: u64,
수정experiments/rust-archive-worker/src/runtime.rs+102-12
@@ -39,6 +39,8 @@ struct Job<W> {
3939 budget: Option<Budget>,
4040 watchdog: Watchdog,
4141 remaining_choice: Option<ConflictChoice>,
42추가: source_group: Option<crate::split_seven_zip::Group>,
43추가: source_verified_for_publication: bool,
4244 started: Instant,
4345 terminal: Terminal,
4446 parent: crate::parent::Parent,
@@ -249,6 +251,55 @@ impl<W: Write> Job<W> {
249251 ErrorCode::Io
250252 })
251253 }
254추가: fn split_result<T>(
255추가: &mut self,
256추가: result: std::result::Result<T, crate::split_seven_zip::Failure>,
257추가: ) -> Result<T> {
258추가: match result {
259추가: Ok(value) => Ok(value),
260추가: Err(failure) => {
261추가: self.check()?;
262추가: if let Some((reason, volume)) = failure.problem {
263추가: self.event(Message::VolumeProblem { reason, volume })?;
264추가: }
265추가: Err(failure.error)
266추가: }
267추가: }
268추가: }
269추가: fn verify_split(&mut self) -> Result<()> {
270추가: let Some(group) = self.source_group.take() else {
271추가: return Ok(());
272추가: };
273추가: let result = (|| {
274추가: self.progress(Stage::Verify, 0, None, 0)?;
275추가: group.verify(&mut |step| match step {
276추가: crate::spool::Step::Check => self.check(),
277추가: crate::spool::Step::Activity => completed(Ok(()), self),
278추가: crate::spool::Step::Read { bytes, total } => {
279추가: self.progress(Stage::Verify, bytes, Some(total), 0)
280추가: }
281추가: })
282추가: })();
283추가: self.source_group = Some(group);
284추가: self.split_result(result)
285추가: }
286추가: fn verify_before_publication(&mut self) -> Result<()> {
287추가: if !self.source_verified_for_publication {
288추가: self.verify_split()?;
289추가: self.source_verified_for_publication = true;
290추가: }
291추가: Ok(())
292추가: }
293추가: fn publication_step(&mut self, step: filesystem::PublishStep, last: bool) -> Result<()> {
294추가: match step {
295추가: filesystem::PublishStep::Check => self.check(),
296추가: filesystem::PublishStep::Activity => completed(Ok(()), self),
297추가: filesystem::PublishStep::Commit => {
298추가: self.verify_before_publication()?;
299추가: if last { self.cutoff() } else { self.check() }
300추가: }
301추가: }
302추가: }
252303 fn check(&mut self) -> Result<()> {
253304 self.parent.check()?;
254305 let state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
@@ -301,12 +352,7 @@ impl<W: Write> Job<W> {
301352 self.terminal.created_count as u32,
302353 )?;
303354 let p = filesystem::publish_reader_steps(root, name, data, length, replace, &mut |step| {
304삭제: match step {
305삭제: filesystem::PublishStep::Check => self.check(),
306삭제: filesystem::PublishStep::Activity => completed(Ok(()), self),
307삭제: filesystem::PublishStep::Commit if last => self.cutoff(),
308삭제: filesystem::PublishStep::Commit => self.check(),
309삭제: }
355추가: self.publication_step(step, last)
310356 });
311357 self.terminal.retained_partial_count += p.retained;
312358 if p.cleanup != Cleanup::Complete {
@@ -362,6 +408,12 @@ impl<W: Write> Job<W> {
362408 use sha2::{Digest, Sha256};
363409 use std::io::{Read, Seek, SeekFrom};
364410 let path = archive.to_path()?;
411추가: if crate::split_seven_zip::is_split(&path)
412추가: || crate::split_seven_zip::unsupported_split(&path)
413추가: || matches!(expected.source_object, SourceObject::SplitSevenZip { .. })
414추가: {
415추가: return Err(ErrorCode::UnsupportedFeature);
416추가: }
365417 self.progress(Stage::Read, 0, None, 0)?;
366418 let mut snapshot =
367419 crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| match step {
@@ -517,8 +569,38 @@ impl<W: Write> Job<W> {
517569 } => {
518570 let extract = matches!(start.action, Action::Extract { .. });
519571 let path = source.to_path()?;
520삭제: self.progress(Stage::Read, 0, None, 0)?;
521삭제: let mut snapshot =
572추가: self.progress(
573추가: if crate::split_seven_zip::is_split(&path) {
574추가: Stage::Scan
575추가: } else {
576추가: Stage::Read
577추가: },
578추가: 0,
579추가: None,
580추가: 0,
581추가: )?;
582추가: let expected = match &start.action {
583추가: Action::Extract { list_id, .. } => list_id.as_ref(),
584추가: _ => None,
585추가: };
586추가: let metadata_limits = self.metadata_limits();
587추가: let captured = crate::split_seven_zip::open(
588추가: &path,
589추가: expected,
590추가: limits.input,
591추가: metadata_limits,
592추가: &mut |step| match step {
593추가: crate::spool::Step::Check => self.check(),
594추가: crate::spool::Step::Activity => completed(Ok(()), self),
595추가: crate::spool::Step::Read { bytes, total } => {
596추가: self.progress(Stage::Read, bytes, Some(total), 0)
597추가: }
598추가: },
599추가: );
600추가: let mut snapshot = if let Some(captured) = self.split_result(captured)? {
601추가: self.source_group = Some(captured.group);
602추가: captured.snapshot
603추가: } else {
522604 crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| {
523605 match step {
524606 crate::spool::Step::Check => self.check(),
@@ -527,13 +609,14 @@ impl<W: Write> Job<W> {
527609 self.progress(Stage::Read, bytes, Some(total), 0)
528610 }
529611 }
530삭제: })?;
612추가: })?
613추가: };
531614 if let Action::Extract {
532615 list_id: Some(expected),
533616 ..
534617 } = &start.action
535618 {
536삭제: if expected.catalog_version != 1
619추가: if expected.catalog_version != if self.source_group.is_some() { 2 } else { 1 }
537620 || expected.source_object != snapshot.object
538621 || expected.archive_bytes != snapshot.len
539622 || expected.archive_sha256 != snapshot.hash
@@ -551,7 +634,7 @@ impl<W: Write> Job<W> {
551634 self,
552635 )?;
553636 let list_id = ListId {
554삭제: catalog_version: 1,
637추가: catalog_version: if self.source_group.is_some() { 2 } else { 1 },
555638 format: catalog.format,
556639 source_object: snapshot.object,
557640 archive_bytes: snapshot.len,
@@ -562,6 +645,7 @@ impl<W: Write> Job<W> {
562645 self.check()?;
563646 completed(self.event(Message::Entry(member.entry.clone())), self)?;
564647 }
648추가: self.verify_split()?;
565649 completed(
566650 self.event(Message::ListEnd {
567651 entry_count: catalog.members.len() as u32,
@@ -708,7 +792,9 @@ impl<W: Write> Job<W> {
708792 for name in dirs {
709793 self.check()?;
710794 let (created, durability, sync_error) =
711삭제: filesystem::directory_with(&root, &name, self)?;
795추가: filesystem::directory_steps(&root, &name, &mut |step| {
796추가: self.publication_step(step, false)
797추가: })?;
712798 if created {
713799 self.terminal.created_count += 1;
714800 self.terminal.publication = Publication::Partial;
@@ -778,6 +864,8 @@ impl<W: Write> Job<W> {
778864 replace,
779865 )?;
780866 }
867추가: // 건너뛰기 등 실제 게시가 없을 때도 완료 전에 원본을 확인함.
868추가: self.verify_before_publication()?;
781869 if !self.interactive || self.terminal.created_count != 0 {
782870 self.terminal.publication = Publication::Complete;
783871 }
@@ -1018,6 +1106,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
10181106 budget,
10191107 watchdog: Watchdog::new(),
10201108 remaining_choice: None,
1109추가: source_group: None,
1110추가: source_verified_for_publication: false,
10211111 parent,
10221112 started: Instant::now(),
10231113 terminal: Terminal {
수정experiments/rust-archive-worker/src/space.rs+1-0
@@ -7,6 +7,7 @@ pub(crate) fn volume(file: &File) -> Result<u64> {
77 Ok(match crate::filesystem::object(file)? {
88 SourceObject::Unix { device, .. } => device,
99 SourceObject::Windows { volume_serial, .. } => volume_serial,
10추가: SourceObject::SplitSevenZip { .. } => return Err(ErrorCode::Protocol),
1011 })
1112}
1213
추가experiments/rust-archive-worker/src/split_seven_zip.rs+580-0
@@ -0,0 +1,580 @@
1추가: use crate::{
2추가: create_sources::Input,
3추가: filesystem,
4추가: protocol::*,
5추가: spool::{Snapshot, Step},
6추가: };
7추가: use sha2::{Digest, Sha256};
8추가: use std::{
9추가: ffi::{OsStr, OsString},
10추가: fs::{File, Metadata},
11추가: io::{Read, Seek, Write},
12추가: path::{Path, PathBuf},
13추가: time::{Instant, SystemTime},
14추가: };
15추가:
16추가: const MAX_VOLUMES: usize = 999;
17추가: type Result<T> = std::result::Result<T, Failure>;
18추가:
19추가: #[derive(Debug)]
20추가: pub(crate) struct Failure {
21추가: pub error: ErrorCode,
22추가: pub problem: Option<(VolumeProblemReason, NativePath)>,
23추가: }
24추가: impl From<ErrorCode> for Failure {
25추가: fn from(error: ErrorCode) -> Self {
26추가: Self {
27추가: error,
28추가: problem: None,
29추가: }
30추가: }
31추가: }
32추가:
33추가: #[cfg(unix)]
34추가: fn units(name: &OsStr) -> Vec<u16> {
35추가: use std::os::unix::ffi::OsStrExt;
36추가: name.as_bytes()
37추가: .iter()
38추가: .map(|byte| u16::from(*byte))
39추가: .collect()
40추가: }
41추가: #[cfg(windows)]
42추가: fn units(name: &OsStr) -> Vec<u16> {
43추가: use std::os::windows::ffi::OsStrExt;
44추가: name.encode_wide().collect()
45추가: }
46추가: #[cfg(unix)]
47추가: fn native(name: &[u16]) -> OsString {
48추가: use std::os::unix::ffi::OsStringExt;
49추가: OsString::from_vec(name.iter().map(|unit| *unit as u8).collect())
50추가: }
51추가: #[cfg(windows)]
52추가: fn native(name: &[u16]) -> OsString {
53추가: use std::os::windows::ffi::OsStringExt;
54추가: OsString::from_wide(name)
55추가: }
56추가: fn equal_name(left: &[u16], right: &[u16]) -> bool {
57추가: #[cfg(unix)]
58추가: {
59추가: left == right
60추가: }
61추가: #[cfg(windows)]
62추가: {
63추가: unsafe extern "system" {
64추가: fn CompareStringOrdinal(
65추가: a: *const u16,
66추가: na: i32,
67추가: b: *const u16,
68추가: nb: i32,
69추가: ignore_case: i32,
70추가: ) -> i32;
71추가: }
72추가: if left.len() > 32768 || right.len() > 32768 {
73추가: return false;
74추가: }
75추가: // Windows의 파일명 비교와 같은 대소문자 규칙을 사용함.
76추가: unsafe {
77추가: CompareStringOrdinal(
78추가: left.as_ptr(),
79추가: left.len() as i32,
80추가: right.as_ptr(),
81추가: right.len() as i32,
82추가: 1,
83추가: ) == 2
84추가: }
85추가: }
86추가: }
87추가: fn number(suffix: &[u16]) -> Option<u32> {
88추가: if suffix.is_empty() || suffix.iter().any(|unit| !(48..=57).contains(unit)) {
89추가: return None;
90추가: }
91추가: Some(suffix.iter().fold(0u32, |value, digit| {
92추가: value
93추가: .saturating_mul(10)
94추가: .saturating_add(u32::from(*digit - 48))
95추가: }))
96추가: }
97추가: struct Name {
98추가: prefix: Vec<u16>,
99추가: selected: u32,
100추가: width: usize,
101추가: }
102추가: impl Name {
103추가: fn parse(path: &Path) -> Option<Self> {
104추가: let name = units(path.file_name()?);
105추가: let dot = name.iter().rposition(|unit| *unit == 46)?;
106추가: let prefix = &name[..=dot];
107추가: let suffix = &name[dot + 1..];
108추가: if prefix.len() < 4 || !matches!(&prefix[prefix.len() - 4..], [46, 55, 90 | 122, 46]) {
109추가: return None;
110추가: }
111추가: Some(Self {
112추가: prefix: prefix.to_vec(),
113추가: selected: number(suffix)?,
114추가: width: suffix.len(),
115추가: })
116추가: }
117추가: fn volume(&self, number: usize) -> NativePath {
118추가: let mut name = self.prefix.clone();
119추가: name.extend(format!("{number:03}").bytes().map(u16::from));
120추가: NativePath::from_path(Path::new(&native(&name)))
121추가: }
122추가: fn problem(&self, reason: VolumeProblemReason, index: usize) -> Failure {
123추가: Failure {
124추가: error: reason.terminal_error(),
125추가: problem: Some((reason, self.volume(index))),
126추가: }
127추가: }
128추가: fn incomplete(&self) -> Failure {
129추가: self.problem(VolumeProblemReason::IncompleteSet, 1)
130추가: }
131추가: }
132추가: pub(crate) fn is_split(path: &Path) -> bool {
133추가: Name::parse(path).is_some()
134추가: }
135추가: pub(crate) fn unsupported_split(path: &Path) -> bool {
136추가: let Some(leaf) = path.file_name() else {
137추가: return false;
138추가: };
139추가: let name = units(leaf);
140추가: let Some(dot) = name.iter().rposition(|unit| *unit == 46) else {
141추가: return false;
142추가: };
143추가: let suffix = &name[dot + 1..];
144추가: let numeric = number(suffix).is_some();
145추가: (numeric && dot >= 4 && matches!(&name[dot - 4..dot], [46, 90 | 122, 73 | 105, 80 | 112]))
146추가: || (suffix.len() == 3 && matches!(suffix[0], 90 | 122) && number(&suffix[1..]).is_some())
147추가: }
148추가:
149추가: struct Part {
150추가: name: OsString,
151추가: object: SourceObject,
152추가: length: u64,
153추가: modified: SystemTime,
154추가: hash: [u8; 32],
155추가: }
156추가: pub(crate) struct Group {
157추가: parent: Input,
158추가: path: PathBuf,
159추가: object: SourceObject,
160추가: name: Name,
161추가: parts: Vec<Part>,
162추가: total: u64,
163추가: metadata_limits: crate::archive::MetadataLimits,
164추가: }
165추가: pub(crate) struct Captured {
166추가: pub snapshot: Snapshot,
167추가: pub group: Group,
168추가: }
169추가: fn metadata(file: &File) -> std::result::Result<Metadata, ErrorCode> {
170추가: let metadata = file.metadata().map_err(crate::space::io_error)?;
171추가: if !metadata.is_file() {
172추가: return Err(ErrorCode::UnsafePath);
173추가: }
174추가: Ok(metadata)
175추가: }
176추가: fn combined_length(total: u64, next: u64) -> Result<u64> {
177추가: total
178추가: .checked_add(next)
179추가: .ok_or_else(|| ErrorCode::Limit.into())
180추가: }
181추가: impl Group {
182추가: fn scan(
183추가: &self,
184추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
185추가: ) -> Result<Vec<OsString>> {
186추가: let mut names: Vec<Option<OsString>> = (0..MAX_VOLUMES).map(|_| None).collect();
187추가: let mut metadata_bytes = 0usize;
188추가: step(Step::Check)?;
189추가: let entries = self.parent.children(&self.path)?;
190추가: step(Step::Activity)?;
191추가: for entry in entries {
192추가: step(Step::Check)?;
193추가: let leaf = entry.map_err(crate::space::io_error)?.file_name();
194추가: let value = units(&leaf);
195추가: if value.len() > self.name.prefix.len()
196추가: && equal_name(&value[..self.name.prefix.len()], &self.name.prefix)
197추가: {
198추가: let suffix = &value[self.name.prefix.len()..];
199추가: if let Some(index) = number(suffix) {
200추가: if index > MAX_VOLUMES as u32 {
201추가: return Err(ErrorCode::Limit.into());
202추가: }
203추가: if index == 0 || suffix.len() != 3 {
204추가: return Err(self.name.incomplete());
205추가: }
206추가: metadata_bytes = value
207추가: .len()
208추가: .checked_mul(8)
209추가: .and_then(|cost| cost.checked_add(256))
210추가: .and_then(|cost| metadata_bytes.checked_add(cost))
211추가: .filter(|cost| *cost <= self.metadata_limits.bytes)
212추가: .ok_or(ErrorCode::Limit)?;
213추가: if index as usize > self.metadata_limits.nodes {
214추가: return Err(ErrorCode::Limit.into());
215추가: }
216추가: let slot = &mut names[index as usize - 1];
217추가: if slot.is_some() {
218추가: return Err(self.name.incomplete());
219추가: }
220추가: *slot = Some(leaf);
221추가: }
222추가: }
223추가: step(Step::Activity)?;
224추가: }
225추가: let Some(last) = names.iter().rposition(Option::is_some) else {
226추가: return Ok(Vec::new());
227추가: };
228추가: names.truncate(last + 1);
229추가: names
230추가: .into_iter()
231추가: .enumerate()
232추가: .map(|(index, name)| {
233추가: name.ok_or_else(|| {
234추가: self.name
235추가: .problem(VolumeProblemReason::MissingVolume, index + 1)
236추가: })
237추가: })
238추가: .collect()
239추가: }
240추가: fn parent_unchanged(&self) -> Result<()> {
241추가: let named = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
242추가: if filesystem::object(&named.file)? != self.object
243추가: || !named
244추가: .file
245추가: .metadata()
246추가: .map_err(crate::space::io_error)?
247추가: .is_dir()
248추가: {
249추가: return Err(ErrorCode::SourceChanged.into());
250추가: }
251추가: Ok(())
252추가: }
253추가: fn open_part(
254추가: &self,
255추가: name: &OsStr,
256추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
257추가: ) -> Result<Input> {
258추가: match self.parent.open_named(&self.path, name) {
259추가: Ok(file) => {
260추가: step(Step::Activity)?;
261추가: Ok(file)
262추가: }
263추가: Err(error) => {
264추가: // 읽기 실패가 확정된 중간 누락인지 먼저 확인함.
265추가: if error == ErrorCode::Io {
266추가: let names = self.scan(step)?;
267추가: if !names.iter().any(|candidate| candidate == name) {
268추가: return Err(ErrorCode::SourceChanged.into());
269추가: }
270추가: }
271추가: Err(error.into())
272추가: }
273추가: }
274추가: }
275추가: fn matches(&self, part: &Part, input: &Input) -> Result<()> {
276추가: let data = metadata(&input.file)?;
277추가: if filesystem::object(&input.file)? != part.object
278추가: || data.len() != part.length
279추가: || data.modified().map_err(crate::space::io_error)? != part.modified
280추가: {
281추가: return Err(ErrorCode::SourceChanged.into());
282추가: }
283추가: Ok(())
284추가: }
285추가: fn read_part(
286추가: &self,
287추가: part: &Part,
288추가: output: &mut Option<&mut File>,
289추가: whole: &mut Sha256,
290추가: processed: &mut u64,
291추가: reported: &mut Instant,
292추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
293추가: ) -> Result<[u8; 32]> {
294추가: let mut input = self.open_part(&part.name, step)?;
295추가: self.matches(part, &input)?;
296추가: let mut hash = Sha256::new();
297추가: let mut read = 0u64;
298추가: let mut buffer = zeroize::Zeroizing::new([0; 65536]);
299추가: loop {
300추가: step(Step::Check)?;
301추가: let length = input
302추가: .file
303추가: .read(&mut buffer[..])
304추가: .map_err(crate::space::io_error)?;
305추가: step(Step::Activity)?;
306추가: if length == 0 {
307추가: break;
308추가: }
309추가: read = read
310추가: .checked_add(length as u64)
311추가: .filter(|n| *n <= part.length)
312추가: .ok_or(ErrorCode::SourceChanged)?;
313추가: if let Some(file) = output {
314추가: file.write_all(&buffer[..length])
315추가: .map_err(crate::space::io_error)?;
316추가: step(Step::Activity)?;
317추가: }
318추가: hash.update(&buffer[..length]);
319추가: whole.update(&buffer[..length]);
320추가: *processed = processed
321추가: .checked_add(length as u64)
322추가: .ok_or(ErrorCode::Limit)?;
323추가: if reported.elapsed() >= std::time::Duration::from_millis(200) {
324추가: step(Step::Read {
325추가: bytes: *processed,
326추가: total: self.total,
327추가: })?;
328추가: *reported = Instant::now();
329추가: }
330추가: }
331추가: if read != part.length {
332추가: return Err(ErrorCode::SourceChanged.into());
333추가: }
334추가: self.matches(part, &input)?;
335추가: let named = self.open_part(&part.name, step)?;
336추가: self.matches(part, &named)?;
337추가: Ok(hash.finalize().into())
338추가: }
339추가: fn manifest(&self) -> Result<[u8; 32]> {
340추가: let mut hash = Sha256::new();
341추가: hash.update(b"zipelo.split7z.v1\0");
342추가: hash.update(
343추가: crate::wire::encode_source_object(&self.object).map_err(|_| ErrorCode::Internal)?,
344추가: );
345추가: hash.update((self.parts.len() as u16).to_le_bytes());
346추가: for (index, part) in self.parts.iter().enumerate() {
347추가: hash.update(((index + 1) as u16).to_le_bytes());
348추가: hash.update(
349추가: crate::wire::encode_native_path(&NativePath::from_path(Path::new(&part.name)))
350추가: .map_err(|_| ErrorCode::Limit)?,
351추가: );
352추가: hash.update(
353추가: crate::wire::encode_source_object(&part.object).map_err(|_| ErrorCode::Internal)?,
354추가: );
355추가: hash.update(part.length.to_le_bytes());
356추가: hash.update(part.hash);
357추가: }
358추가: Ok(hash.finalize().into())
359추가: }
360추가: pub fn verify(
361추가: &self,
362추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
363추가: ) -> Result<()> {
364추가: step(Step::Check)?;
365추가: self.parent_unchanged()?;
366추가: let names = self.scan(step).map_err(|failure| {
367추가: if matches!(
368추가: failure.problem,
369추가: Some((VolumeProblemReason::IncompleteSet, _))
370추가: ) {
371추가: ErrorCode::SourceChanged.into()
372추가: } else {
373추가: failure
374추가: }
375추가: })?;
376추가: if names.len() != self.parts.len()
377추가: || names
378추가: .iter()
379추가: .zip(&self.parts)
380추가: .any(|(name, part)| *name != part.name)
381추가: {
382추가: return Err(ErrorCode::SourceChanged.into());
383추가: }
384추가: let mut processed = 0;
385추가: let mut whole = Sha256::new();
386추가: let mut reported = Instant::now();
387추가: for part in &self.parts {
388추가: step(Step::Check)?;
389추가: if self.read_part(
390추가: part,
391추가: &mut None,
392추가: &mut whole,
393추가: &mut processed,
394추가: &mut reported,
395추가: step,
396추가: )? != part.hash
397추가: {
398추가: return Err(ErrorCode::SourceChanged.into());
399추가: }
400추가: step(Step::Activity)?;
401추가: }
402추가: step(Step::Read {
403추가: bytes: processed,
404추가: total: self.total,
405추가: })?;
406추가: let final_names = self.scan(step).map_err(|failure| {
407추가: if matches!(
408추가: failure.problem,
409추가: Some((VolumeProblemReason::IncompleteSet, _))
410추가: ) {
411추가: ErrorCode::SourceChanged.into()
412추가: } else {
413추가: failure
414추가: }
415추가: })?;
416추가: if final_names != names {
417추가: return Err(ErrorCode::SourceChanged.into());
418추가: }
419추가: self.parent_unchanged()?;
420추가: Ok(())
421추가: }
422추가: }
423추가: pub(crate) fn open(
424추가: path: &Path,
425추가: expected: Option<&ListId>,
426추가: limit: u64,
427추가: metadata_limits: crate::archive::MetadataLimits,
428추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
429추가: ) -> Result<Option<Captured>> {
430추가: if unsupported_split(path) {
431추가: return Err(ErrorCode::UnsupportedFeature.into());
432추가: }
433추가: let Some(name) = Name::parse(path) else {
434추가: return Ok(None);
435추가: };
436추가: if !NativePath::from_path(Path::new(
437추가: path.file_name().ok_or(ErrorCode::InvalidRequest)?,
438추가: ))
439추가: .is_basename()
440추가: {
441추가: return Err(ErrorCode::UnsafePath.into());
442추가: }
443추가: if name.selected > MAX_VOLUMES as u32 {
444추가: return Err(ErrorCode::Limit.into());
445추가: }
446추가: if name.width != 3 {
447추가: return Err(ErrorCode::UnsupportedFeature.into());
448추가: }
449추가: if name.selected != 1 {
450추가: return Err(name.problem(VolumeProblemReason::FirstVolumeRequired, 1));
451추가: }
452추가: step(Step::Check)?;
453추가: let parent_path = path
454추가: .parent()
455추가: .ok_or(ErrorCode::InvalidRequest)?
456추가: .to_path_buf();
457추가: let parent = Input::open(&parent_path)?;
458추가: if !parent
459추가: .file
460추가: .metadata()
461추가: .map_err(crate::space::io_error)?
462추가: .is_dir()
463추가: {
464추가: return Err(ErrorCode::UnsafePath.into());
465추가: }
466추가: let object = filesystem::object(&parent.file)?;
467추가: let mut group = Group {
468추가: parent,
469추가: path: parent_path,
470추가: object,
471추가: name,
472추가: parts: Vec::new(),
473추가: total: 0,
474추가: metadata_limits,
475추가: };
476추가: let names = group.scan(step)?;
477추가: if names.is_empty() {
478추가: return Err(if expected.is_some() {
479추가: ErrorCode::SourceChanged
480추가: } else {
481추가: ErrorCode::Io
482추가: }
483추가: .into());
484추가: }
485추가: for name in names {
486추가: step(Step::Check)?;
487추가: let input = group.open_part(&name, step)?;
488추가: let data = metadata(&input.file)?;
489추가: let object = filesystem::object(&input.file)?;
490추가: if group.parts.iter().any(|part| part.object == object) {
491추가: return Err(ErrorCode::UnsafePath.into());
492추가: }
493추가: group.total = combined_length(group.total, data.len())?;
494추가: group.parts.push(Part {
495추가: name,
496추가: object,
497추가: length: data.len(),
498추가: modified: data.modified().map_err(crate::space::io_error)?,
499추가: hash: [0; 32],
500추가: });
501추가: step(Step::Activity)?;
502추가: }
503추가: if expected.is_some_and(|id| {
504추가: id.archive_bytes != group.total
505추가: || id.catalog_version != 2
506추가: || id.format != Format::SevenZip
507추가: || !matches!(id.source_object, SourceObject::SplitSevenZip { .. })
508추가: }) {
509추가: return Err(ErrorCode::SourceChanged.into());
510추가: }
511추가: if group.total > limit {
512추가: return Err(ErrorCode::Limit.into());
513추가: }
514추가: let mut file = crate::spool::temporary()?;
515추가: crate::space::ensure(&file, group.total)?;
516추가: let mut processed = 0;
517추가: let mut whole = Sha256::new();
518추가: let mut reported = Instant::now();
519추가: for index in 0..group.parts.len() {
520추가: let hash = group.read_part(
521추가: &group.parts[index],
522추가: &mut Some(&mut file),
523추가: &mut whole,
524추가: &mut processed,
525추가: &mut reported,
526추가: step,
527추가: )?;
528추가: group.parts[index].hash = hash;
529추가: step(Step::Activity)?;
530추가: }
531추가: step(Step::Read {
532추가: bytes: processed,
533추가: total: group.total,
534추가: })?;
535추가: let hash = whole.finalize().into();
536추가: let object = SourceObject::SplitSevenZip {
537추가: manifest_sha256: group.manifest()?,
538추가: };
539추가: if expected.is_some_and(|id| id.source_object != object || id.archive_sha256 != hash) {
540추가: return Err(ErrorCode::SourceChanged.into());
541추가: }
542추가: // 마지막 누락 이름을 추측하지 않고 논리 헤더 끝 위치를 검증함.
543추가: file.rewind().map_err(crate::space::io_error)?;
544추가: let mut header = [0; 32];
545추가: if group.parts.iter().any(|part| part.length == 0) || group.total < 32 {
546추가: return Err(group.name.incomplete());
547추가: }
548추가: file.read_exact(&mut header)
549추가: .map_err(crate::space::io_error)?;
550추가: if &header[..6] != b"7z\xbc\xaf\x27\x1c"
551추가: || zlib_rs::crc32::crc32(0, &header[12..])
552추가: != u32::from_le_bytes(header[8..12].try_into().unwrap())
553추가: {
554추가: return Err(group.name.incomplete());
555추가: }
556추가: let offset = u64::from_le_bytes(header[12..20].try_into().unwrap());
557추가: let length = u64::from_le_bytes(header[20..28].try_into().unwrap());
558추가: if 32u64
559추가: .checked_add(offset)
560추가: .and_then(|start| start.checked_add(length))
561추가: != Some(group.total)
562추가: {
563추가: return Err(group.name.incomplete());
564추가: }
565추가: group.verify(step)?;
566추가: file.rewind().map_err(crate::space::io_error)?;
567추가: Ok(Some(Captured {
568추가: snapshot: Snapshot {
569추가: file,
570추가: len: group.total,
571추가: object,
572추가: hash,
573추가: },
574추가: group,
575추가: }))
576추가: }
577추가:
578추가: #[cfg(test)]
579추가: #[path = "../../../tests/rust-archive-worker/split_capture.rs"]
580추가: mod tests;
수정experiments/rust-archive-worker/src/wire.rs+64-8
@@ -144,7 +144,8 @@ enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3});
144144enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5});
145145enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3});
146146enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2});
147삭제: enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12,DiskFull=13});
147추가: enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12,DiskFull=13,MissingVolume=14});
148추가: enumeration!(VolumeProblemReason{FirstVolumeRequired=0,MissingVolume=1,IncompleteSet=2});
148149enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3});
149150enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3});
150151enumeration!(Cleanup{Complete=0,Failed=1,Unconfirmed=2});
@@ -160,13 +161,31 @@ structure!(Limits {
160161 output,
161162 entries
162163});
163삭제: structure!(ListId {
164삭제: catalog_version,
165삭제: format,
166삭제: source_object,
167삭제: archive_bytes,
168삭제: archive_sha256
169삭제: });
164추가: impl Wire for ListId {
165추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> {
166추가: if !self.valid() {
167추가: return Err(invalid());
168추가: }
169추가: self.catalog_version.enc(e)?;
170추가: self.format.enc(e)?;
171추가: self.source_object.enc(e)?;
172추가: self.archive_bytes.enc(e)?;
173추가: self.archive_sha256.enc(e)
174추가: }
175추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
176추가: let id = Self {
177추가: catalog_version: Wire::dec(d)?,
178추가: format: Wire::dec(d)?,
179추가: source_object: Wire::dec(d)?,
180추가: archive_bytes: Wire::dec(d)?,
181추가: archive_sha256: Wire::dec(d)?,
182추가: };
183추가: if !id.valid() {
184추가: return Err(invalid());
185추가: }
186추가: Ok(id)
187추가: }
188추가: }
170189impl Wire for PreviewInfo {
171190 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
172191 if !self.valid() {
@@ -268,6 +287,10 @@ impl Wire for SourceObject {
268287 volume_serial.enc(e)?;
269288 file_id.enc(e)
270289 }
290추가: Self::SplitSevenZip { manifest_sha256 } => {
291추가: 3u8.enc(e)?;
292추가: manifest_sha256.enc(e)
293추가: }
271294 }
272295 }
273296 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
@@ -280,10 +303,27 @@ impl Wire for SourceObject {
280303 volume_serial: Wire::dec(d)?,
281304 file_id: Wire::dec(d)?,
282305 }),
306추가: 3 => Ok(Self::SplitSevenZip {
307추가: manifest_sha256: Wire::dec(d)?,
308추가: }),
283309 _ => Err(invalid()),
284310 }
285311 }
286312}
313추가: pub(crate) fn encode_source_object(value: &SourceObject) -> io::Result<Vec<u8>> {
314추가: encode_component(value)
315추가: }
316추가: pub(crate) fn encode_native_path(value: &NativePath) -> io::Result<Vec<u8>> {
317추가: encode_component(value)
318추가: }
319추가: fn encode_component(value: &impl Wire) -> io::Result<Vec<u8>> {
320추가: let mut encoder = Encoder {
321추가: bytes: Vec::new(),
322추가: selection_limit: LEGACY_VECTOR_ITEMS,
323추가: };
324추가: value.enc(&mut encoder)?;
325추가: Ok(encoder.bytes)
326추가: }
287327impl Wire for Selection {
288328 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
289329 match self {
@@ -537,6 +577,14 @@ impl Message {
537577 sha256.enc(&mut e)?;
538578 113
539579 }
580추가: Self::VolumeProblem { reason, volume } => {
581추가: if !volume.is_basename() {
582추가: return Err(invalid());
583추가: }
584추가: reason.enc(&mut e)?;
585추가: volume.enc(&mut e)?;
586추가: 114
587추가: }
540588 Self::Terminal(v) => {
541589 if v.detail.len() > 4096 {
542590 return Err(invalid());
@@ -702,6 +750,14 @@ impl Message {
702750 sha256: Wire::dec(&mut d)?,
703751 }
704752 }
753추가: 114 => {
754추가: let reason = Wire::dec(&mut d)?;
755추가: let volume = NativePath::dec(&mut d)?;
756추가: if !volume.is_basename() {
757추가: return Err(invalid());
758추가: }
759추가: Self::VolumeProblem { reason, volume }
760추가: }
705761 106 => {
706762 let t = Terminal::dec(&mut d)?;
707763 if t.detail.len() > 4096 {
수정experiments/rust-ui-memory-app/src/archive_dialog.rs+3-1
@@ -37,7 +37,9 @@ pub trait Dialogs {
3737
3838pub fn archive_filters() -> Vec<(&'static str, Vec<String>)> {
3939 let mut extensions = Vec::new();
40삭제: for extension in ["zip", "7z", "tar", "gz", "tgz", "tar.bz2", "tar.xz"] {
40추가: for extension in [
41추가: "zip", "7z", "7z.001", "tar", "gz", "tgz", "tar.bz2", "tar.xz",
42추가: ] {
4143 let mut variants = vec![String::new()];
4244 for character in extension.chars() {
4345 let mut next = Vec::new();
수정experiments/rust-ui-memory-app/src/archive_present.rs+52-0
@@ -19,6 +19,9 @@ pub const FOLDER_ERROR: &str = "풀 위치 폴더를 만들 수 없습니다.
1919
2020pub fn error_text(code: ErrorCode) -> &'static str {
2121 match code {
22추가: ErrorCode::MissingVolume => {
23추가: "분할 압축파일의 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 .001을 다시 여세요"
24추가: }
2225 ErrorCode::Integrity => "압축파일이 손상됐습니다",
2326 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
2427 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
@@ -425,3 +428,52 @@ pub fn operation_text(text: &str, creating: bool) -> String {
425428 text.to_owned()
426429 }
427430}
431추가:
432추가: pub fn volume_problem_text(problem: &VolumeProblem) -> String {
433추가: fn visible(c: char) -> String {
434추가: if c.is_control() || matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') {
435추가: c.escape_unicode().to_string()
436추가: } else {
437추가: c.to_string()
438추가: }
439추가: }
440추가: let name = match &problem.volume {
441추가: NativePath::Unix(bytes) => bytes
442추가: .utf8_chunks()
443추가: .map(|chunk| {
444추가: let mut text = chunk.valid().chars().map(visible).collect::<String>();
445추가: for byte in chunk.invalid() {
446추가: text.push_str(&format!("\\x{byte:02x}"));
447추가: }
448추가: text
449추가: })
450추가: .collect::<String>(),
451추가: NativePath::Windows(units) => char::decode_utf16(units.iter().copied())
452추가: .map(|c| {
453추가: c.map(visible)
454추가: .unwrap_or_else(|e| format!("\\u{{{:04x}}}", e.unpaired_surrogate()))
455추가: })
456추가: .collect::<String>(),
457추가: };
458추가: match problem.reason {
459추가: VolumeProblemReason::FirstVolumeRequired => format!("첫 조각 {name}을 선택해 다시 여세요."),
460추가: VolumeProblemReason::MissingVolume => {
461추가: format!("{name} 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 .001을 다시 여세요.")
462추가: }
463추가: VolumeProblemReason::IncompleteSet => format!(
464추가: "{name}의 분할 묶음이 불완전하거나 손상됐습니다. 모든 조각의 존재와 손상을 확인한 뒤 .001을 다시 여세요."
465추가: ),
466추가: }
467추가: }
468추가:
469추가: pub const SPLIT_SUPPORT: &str =
470추가: "분할 7z는 .7z.001부터 열 수 있습니다. 분할 ZIP과 RAR, 분할 압축 만들기는 지원하지 않습니다.";
471추가:
472추가: pub fn excluded_split(path: &Path) -> bool {
473추가: let name = path
474추가: .file_name()
475추가: .unwrap_or_default()
476추가: .to_string_lossy()
477추가: .to_ascii_lowercase();
478추가: name.ends_with(".zip.001") || name.ends_with(".z01") || name.ends_with(".rar")
479추가: }
수정experiments/rust-ui-memory-app/src/archive_process.rs+15-0
@@ -135,6 +135,9 @@ fn list_to_wire(id: ui::ListId) -> wire::ListId {
135135 catalog_version: id.catalog_version,
136136 format: format_to_wire(id.format),
137137 source_object: match id.source_object {
138추가: ui::SourceObject::SplitSevenZip { manifest_sha256 } => {
139추가: wire::SourceObject::SplitSevenZip { manifest_sha256 }
140추가: }
138141 ui::SourceObject::Unix { device, inode } => wire::SourceObject::Unix { device, inode },
139142 ui::SourceObject::Windows { volume, file_id } => wire::SourceObject::Windows {
140143 volume_serial: volume,
@@ -150,6 +153,9 @@ fn list_to_ui(id: wire::ListId) -> ui::ListId {
150153 catalog_version: id.catalog_version,
151154 format: format_to_ui(id.format),
152155 source_object: match id.source_object {
156추가: wire::SourceObject::SplitSevenZip { manifest_sha256 } => {
157추가: ui::SourceObject::SplitSevenZip { manifest_sha256 }
158추가: }
153159 wire::SourceObject::Unix { device, inode } => ui::SourceObject::Unix { device, inode },
154160 wire::SourceObject::Windows {
155161 volume_serial,
@@ -229,6 +235,7 @@ fn start_to_wire(start: ui::Start) -> wire::Start {
229235}
230236fn error_to_ui(error: wire::ErrorCode) -> Option<ui::ErrorCode> {
231237 Some(match error {
238추가: wire::ErrorCode::MissingVolume => ui::ErrorCode::MissingVolume,
232239 wire::ErrorCode::None => return None,
233240 wire::ErrorCode::Integrity => ui::ErrorCode::Integrity,
234241 wire::ErrorCode::UnsupportedFormat => ui::ErrorCode::UnsupportedFormat,
@@ -250,6 +257,14 @@ fn event_to_ui(
250257 expected: Option<wire::ActionKind>,
251258) -> Result<ui::Event, ()> {
252259 Ok(match message {
260추가: wire::Message::VolumeProblem { reason, volume }
261추가: if matches!(
262추가: expected,
263추가: Some(wire::ActionKind::List | wire::ActionKind::Extract)
264추가: ) =>
265추가: {
266추가: ui::Event::VolumeProblem(ui::VolumeProblem { reason, volume })
267추가: }
253268 wire::Message::Accepted { action, encryption } if expected == Some(action) => {
254269 ui::Event::Accepted { encryption }
255270 }
수정experiments/rust-ui-memory-app/src/archive_screen.rs+39-10
@@ -971,6 +971,13 @@ impl ArchiveApp {
971971 idle && self.can_preview() && !self.preview_open,
972972 false,
973973 )
974추가: .on_disabled_hover_text(
975추가: if self.model.list_id.as_ref().is_some_and(ListId::is_split) {
976추가: "분할 압축파일은 미리보기를 지원하지 않습니다"
977추가: } else {
978추가: "일반 파일 하나를 선택하세요"
979추가: },
980추가: )
974981 .clicked()
975982 {
976983 self.begin_preview(ui.ctx());
@@ -1778,11 +1785,18 @@ impl ArchiveApp {
17781785
17791786 fn limit_result_visible(&self) -> bool {
17801787 self.result_visible()
1781삭제: && self
1782삭제: .model
1783삭제: .terminal
1784삭제: .as_ref()
1785삭제: .is_some_and(|terminal| terminal.error == Some(ErrorCode::Limit))
1788추가: && (self.model.volume_problem.is_some()
1789추가: || self.model.terminal.as_ref().is_some_and(|terminal| {
1790추가: terminal.error == Some(ErrorCode::Limit)
1791추가: || (matches!(
1792추가: terminal.error,
1793추가: Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature)
1794추가: ) && self
1795추가: .model
1796추가: .archive
1797추가: .as_ref()
1798추가: .is_some_and(|p| present::excluded_split(p)))
1799추가: }))
17861800 }
17871801
17881802 fn limit_result_dialog(&mut self, ctx: &egui::Context) {
@@ -2128,12 +2142,27 @@ impl ArchiveApp {
21282142 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
21292143 };
21302144 theme::bounded_text(ui, &path, ui.available_width());
2145추가: } else if let Some(problem) = &self.model.volume_problem {
2146추가: ui.add(egui::Label::new(present::volume_problem_text(problem)).wrap());
21312147 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
2132삭제: ui.label(if creating && code == ErrorCode::SourceChanged {
2133삭제: "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요".to_owned()
2134삭제: } else {
2135삭제: present::operation_text(present::error_text(code), creating)
2136삭제: });
2148추가: ui.label(
2149추가: if matches!(
2150추가: code,
2151추가: ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature
2152추가: ) && self
2153추가: .model
2154추가: .archive
2155추가: .as_ref()
2156추가: .is_some_and(|p| present::excluded_split(p))
2157추가: {
2158추가: present::SPLIT_SUPPORT.to_owned()
2159추가: } else if creating && code == ErrorCode::SourceChanged {
2160추가: "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
2161추가: .to_owned()
2162추가: } else {
2163추가: present::operation_text(present::error_text(code), creating)
2164추가: },
2165추가: );
21372166 } else if let Some(error) = &self.model.error {
21382167 ui.label(present::operation_text(
21392168 present::client_error_text(error),
수정experiments/rust-ui-memory-app/src/archive_ui.rs+77-7
@@ -12,6 +12,7 @@ pub enum Format {
1212pub enum SourceObject {
1313 Unix { device: u64, inode: u64 },
1414 Windows { volume: u64, file_id: [u8; 16] },
15추가: SplitSevenZip { manifest_sha256: [u8; 32] },
1516}
1617#[derive(Clone, Debug, Eq, PartialEq)]
1718pub struct ListId {
@@ -21,6 +22,26 @@ pub struct ListId {
2122 pub archive_bytes: u64,
2223 pub archive_sha256: [u8; 32],
2324}
25추가: impl ListId {
26추가: pub fn valid(&self) -> bool {
27추가: matches!(
28추가: (self.catalog_version, self.format, &self.source_object),
29추가: (
30추가: 1,
31추가: _,
32추가: SourceObject::Unix { .. } | SourceObject::Windows { .. }
33추가: ) | (2, Format::SevenZip, SourceObject::SplitSevenZip { .. })
34추가: )
35추가: }
36추가: pub fn is_split(&self) -> bool {
37추가: matches!(self.source_object, SourceObject::SplitSevenZip { .. })
38추가: }
39추가: }
40추가: #[derive(Clone, Debug, Eq, PartialEq)]
41추가: pub struct VolumeProblem {
42추가: pub reason: VolumeProblemReason,
43추가: pub volume: NativePath,
44추가: }
2445#[derive(Clone, Debug, Eq, PartialEq)]
2546pub enum Selection {
2647 All,
@@ -159,6 +180,7 @@ pub enum Outcome {
159180}
160181#[derive(Clone, Copy, Debug, Eq, PartialEq)]
161182pub enum ErrorCode {
183추가: MissingVolume,
162184 Integrity,
163185 UnsupportedFormat,
164186 UnsupportedFeature,
@@ -211,7 +233,8 @@ pub struct Terminal {
211233 pub cleanup: Cleanup,
212234}
213235pub use worker_protocol::protocol::{
214삭제: ActionKind, Limits, PreviewFormat, PreviewInfo, ResourceScope, ResourceUsage,
236추가: ActionKind, Limits, NativePath, PreviewFormat, PreviewInfo, ResourceScope, ResourceUsage,
237추가: VolumeProblemReason,
215238};
216239
217240pub struct Preview {
@@ -268,6 +291,7 @@ pub struct ResourceChallenge {
268291
269292#[derive(Clone, Debug)]
270293pub enum Event {
294추가: VolumeProblem(VolumeProblem),
271295 PreviewBegin(PreviewInfo),
272296 PreviewChunk {
273297 entry_id: u32,
@@ -342,6 +366,7 @@ impl Factory for Unavailable {
342366 }
343367}
344368struct Running {
369추가: volume_problem: Option<VolumeProblem>,
345370 preview: Option<PreviewBuffer>,
346371 preview_discarded: bool,
347372 id: u64,
@@ -377,6 +402,7 @@ pub enum Close {
377402}
378403#[derive(Default)]
379404pub struct Model {
405추가: pub volume_problem: Option<VolumeProblem>,
380406 running: Option<Running>,
381407 pub preview: Option<Preview>,
382408 next_id: u64,
@@ -419,6 +445,7 @@ impl Model {
419445 }
420446 pub fn can_preview(&self) -> bool {
421447 self.can_extract()
448추가: && self.list_id.as_ref().is_some_and(|id| !id.is_split())
422449 && self.selected.len() == 1
423450 && self
424451 .entries
@@ -579,6 +606,8 @@ impl Model {
579606 list_id,
580607 } => {
581608 archive.is_absolute()
609추가: && list_id.valid()
610추가: && !list_id.is_split()
582611 && self.archive.as_ref() == Some(archive)
583612 && self.list_id.as_ref() == Some(list_id)
584613 && self
@@ -632,6 +661,7 @@ impl Model {
632661 };
633662 self.preview = None;
634663 let estimated = self.estimate(&start);
664추가: self.volume_problem = None;
635665 let mut connection = match factory.connect(id) {
636666 Ok(c) => c,
637667 Err(e) => {
@@ -661,6 +691,7 @@ impl Model {
661691 }
662692 self.next_id = id;
663693 self.terminal = None;
694추가: self.volume_problem = None;
664695 self.retry_start = None;
665696 self.resource = None;
666697 self.challenge = None;
@@ -673,6 +704,7 @@ impl Model {
673704 self.error = send_error;
674705 self.confirmed = false;
675706 self.running = Some(Running {
707추가: volume_problem: None,
676708 preview: None,
677709 preview_discarded: false,
678710 id,
@@ -928,14 +960,18 @@ impl Model {
928960 }
929961 }
930962 }
931삭제: if self
932삭제: .terminal
933삭제: .as_ref()
934삭제: .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
935삭제: {
963추가: if self.terminal.as_ref().is_some_and(|t| {
964추가: matches!(
965추가: t.error,
966추가: Some(ErrorCode::SourceChanged | ErrorCode::MissingVolume)
967추가: )
968추가: }) {
936969 self.list_id = None;
937970 self.selected.clear();
938971 }
972추가: if self.confirmed && run.cancel_sequence.is_none() {
973추가: self.volume_problem = run.volume_problem.take();
974추가: }
939975 self.retry_start = if !matches!(run.start, Start::Preview { .. })
940976 && !run.expanded
941977 && run.cancel_sequence.is_none()
@@ -991,6 +1027,19 @@ impl Model {
9911027 return;
9921028 }
9931029 match event {
1030추가: Event::VolumeProblem(problem) => {
1031추가: if run.cancel_sequence.is_some() {
1032추가: return;
1033추가: }
1034추가: if run.volume_problem.is_some()
1035추가: || !matches!(run.start, Start::List { .. } | Start::Extract { .. })
1036추가: || !problem.volume.is_basename()
1037추가: {
1038추가: self.error = Some("분할 조각 오류 응답이 유효하지 않습니다".into());
1039추가: } else {
1040추가: run.volume_problem = Some(problem);
1041추가: }
1042추가: }
9941043 Event::PreviewBegin(info) => {
9951044 if run.preview_discarded {
9961045 return;
@@ -1080,7 +1129,7 @@ impl Model {
10801129 } => {
10811130 if !matches!(run.start, Start::List { .. })
10821131 || run.list_end.is_some()
1083삭제: || list_id.catalog_version != 1
1132추가: || !list_id.valid()
10841133 {
10851134 self.error = Some("목록 완료 응답이 유효하지 않습니다".into());
10861135 } else {
@@ -1229,6 +1278,26 @@ impl Model {
12291278 }
12301279 }
12311280 Event::Terminal(t) => {
1281추가: if run.cancel_sequence.is_none()
1282추가: && run.volume_problem.as_ref().is_some_and(|problem| {
1283추가: t.outcome != Outcome::Failed
1284추가: || t.error
1285추가: != match problem.reason {
1286추가: VolumeProblemReason::FirstVolumeRequired => {
1287추가: Some(ErrorCode::InvalidRequest)
1288추가: }
1289추가: VolumeProblemReason::MissingVolume => {
1290추가: Some(ErrorCode::MissingVolume)
1291추가: }
1292추가: VolumeProblemReason::IncompleteSet => {
1293추가: Some(ErrorCode::Integrity)
1294추가: }
1295추가: }
1296추가: })
1297추가: {
1298추가: self.error =
1299추가: Some("분할 조각 오류와 종료 상태가 일치하지 않습니다".into());
1300추가: }
12321301 if matches!(run.start, Start::Preview { .. })
12331302 && (t.publication != Publication::None
12341303 || t.created_count != 0
@@ -1380,6 +1449,7 @@ pub fn terminal_lines(t: &Terminal) -> Vec<String> {
13801449 if let Some(error) = t.error {
13811450 lines.push(
13821451 match error {
1452추가: ErrorCode::MissingVolume => "분할 압축파일의 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 첫 조각을 다시 여세요",
13831453 ErrorCode::Integrity => "압축파일이 손상됐습니다",
13841454 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
13851455 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
수정tests/rust-app-ui/conflict_codec.rs+57-0
@@ -50,3 +50,60 @@ fn conflict_adapter_preserves_sizes_names_ids_and_choices() {
5050 }
5151 }
5252}
53추가:
54추가: #[test]
55추가: fn split_list_id_adapter_round_trip_preserves_manifest_and_logical_input() {
56추가: let id = ui::ListId {
57추가: catalog_version: 2,
58추가: format: ui::Format::SevenZip,
59추가: source_object: ui::SourceObject::SplitSevenZip {
60추가: manifest_sha256: [0xa5; 32],
61추가: },
62추가: archive_bytes: u64::MAX,
63추가: archive_sha256: [0x5a; 32],
64추가: };
65추가: let wire_id = list_to_wire(id.clone());
66추가: assert!(wire_id.valid());
67추가: assert_eq!(list_to_ui(wire_id), id);
68추가: }
69추가: #[test]
70추가: fn volume_problem_adapter_preserves_native_filename_and_rejects_other_actions() {
71추가: for volume in [
72추가: wire::NativePath::Unix(vec![0xff, 46, 55, 122]),
73추가: wire::NativePath::Windows(vec![0xd800, 46, 55, 122]),
74추가: ] {
75추가: for action in [
76추가: Some(wire::ActionKind::List),
77추가: Some(wire::ActionKind::Extract),
78추가: Some(wire::ActionKind::Preview),
79추가: Some(wire::ActionKind::CreateZip),
80추가: None,
81추가: ] {
82추가: let event = event_to_ui(
83추가: wire::Message::VolumeProblem {
84추가: reason: wire::VolumeProblemReason::MissingVolume,
85추가: volume: volume.clone(),
86추가: },
87추가: action,
88추가: );
89추가: if matches!(
90추가: action,
91추가: Some(wire::ActionKind::List | wire::ActionKind::Extract)
92추가: ) {
93추가: match event.unwrap() {
94추가: ui::Event::VolumeProblem(problem) => {
95추가: assert_eq!(problem.volume, volume);
96추가: assert_eq!(problem.reason, wire::VolumeProblemReason::MissingVolume);
97추가: }
98추가: _ => panic!("조각 오류 변환 누락"),
99추가: }
100추가: } else {
101추가: assert!(event.is_err());
102추가: }
103추가: }
104추가: }
105추가: assert_eq!(
106추가: error_to_ui(wire::ErrorCode::MissingVolume),
107추가: Some(ui::ErrorCode::MissingVolume)
108추가: );
109추가: }
수정tests/rust-app-ui/native_dialogs.rs+3-3
@@ -10,9 +10,9 @@ fn archive_filter_contains_every_case_variant_and_all_files_option() {
1010 assert_eq!(filters.len(), 2);
1111 assert_eq!(filters[0].0, "압축파일");
1212 let expected = [
13삭제: "zip", "ziP", "zIp", "zIP", "Zip", "ZiP", "ZIp", "ZIP", "7z", "7Z", "tar", "taR", "tAr",
14삭제: "tAR", "Tar", "TaR", "TAr", "TAR", "gz", "gZ", "Gz", "GZ", "tgz", "tgZ", "tGz", "tGZ",
15삭제: "Tgz", "TgZ", "TGz", "TGZ",
13추가: "zip", "ziP", "zIp", "zIP", "Zip", "ZiP", "ZIp", "ZIP", "7z", "7Z", "7z.001", "7Z.001",
14추가: "tar", "taR", "tAr", "tAR", "Tar", "TaR", "TAr", "TAR", "gz", "gZ", "Gz", "GZ", "tgz",
15추가: "tgZ", "tGz", "tGZ", "Tgz", "TgZ", "TGz", "TGZ",
1616 ]
1717 .into_iter()
1818 .map(str::to_owned)
수정tests/rust-app-ui/regressions.rs+1-0
@@ -5,6 +5,7 @@ mod fake;
55#[cfg(feature = "ui")]
66mod native_dialogs;
77mod preview;
8추가: mod split_volumes;
89use fake::*;
910use std::path::PathBuf;
1011use zipelo_ui_memory_app::archive_ui::*;
수정tests/rust-app-ui/scenario_tests.rs+96-0
@@ -95,7 +95,17 @@ fn every_listed_scenario_draws_and_keeps_its_expected_screen() {
9595 app.model.error
9696 );
9797 assert!(app.model.input_error.is_none(), "{}", scenario.name);
98추가: if scenario.name == "split-archive" {
99추가: assert!(app.model.list_id.as_ref().unwrap().is_split());
100추가: assert!(!app.model.can_preview());
101추가: }
98102 let expected = match scenario.name {
103추가: "split-archive" => "읽어주세요.txt",
104추가: "split-first-volume" => "첫 조각 여행.7z.001을 선택해 다시 여세요.",
105추가: "split-missing-volume" => "여행.7z.003 조각이 없습니다",
106추가: "split-incomplete" => "분할 묶음이 불완전하거나 손상됐습니다",
107추가: "split-unsupported" => "분할 ZIP과 RAR",
108추가: "split-source-changed" => "원본 파일이 바뀌었습니다",
99109 "preview-implicit-folder" => "자료",
100110 "preview-catalog-approval" | "preview-catalog-bytes-approval" => {
101111 "큰 작업을 허용할까요?"
@@ -555,3 +565,89 @@ fn preview_image_respects_renderer_texture_limit() {
555565 }
556566 assert!(image_seen);
557567}
568추가:
569추가: #[test]
570추가: fn split_errors_use_main_modal_without_native_child() {
571추가: for name in [
572추가: "split-first-volume",
573추가: "split-missing-volume",
574추가: "split-incomplete",
575추가: "split-unsupported",
576추가: ] {
577추가: let scenario = scenarios::parse(name).unwrap();
578추가: let mut app = scenario.build();
579추가: let ctx = egui::Context::default();
580추가: ctx.set_embed_viewports(false);
581추가: let mut labels = String::new();
582추가: for _ in 0..3 {
583추가: let mut output = ctx.run_ui(
584추가: egui::RawInput {
585추가: screen_rect: Some(egui::Rect::from_min_size(
586추가: egui::Pos2::ZERO,
587추가: egui::vec2(1060.0, 720.0),
588추가: )),
589추가: ..Default::default()
590추가: },
591추가: |ui| scenario.show(&mut app, ui),
592추가: );
593추가: labels = text(&output.shapes);
594추가: output.textures_delta.clear();
595추가: assert!(
596추가: output
597추가: .viewport_output
598추가: .keys()
599추가: .all(|id| *id == egui::ViewportId::ROOT),
600추가: "{name}"
601추가: );
602추가: }
603추가: assert!(labels.contains("작업 결과"), "{name}: {labels}");
604추가: }
605추가: }
606추가:
607추가: #[test]
608추가: fn excluded_split_errors_show_support_guidance_in_main_modal() {
609추가: use zipelo_ui_memory_app::archive_ui::ErrorCode;
610추가:
611추가: for code in [ErrorCode::UnsupportedFeature, ErrorCode::UnsupportedFormat] {
612추가: for archive in ["sample.zip.001", "sample.z01", "sample.rar", "sample.7z"] {
613추가: let scenario = scenarios::parse("split-unsupported").unwrap();
614추가: let mut app = scenario.build();
615추가: let ctx = egui::Context::default();
616추가: ctx.set_embed_viewports(false);
617추가: let input = || egui::RawInput {
618추가: screen_rect: Some(egui::Rect::from_min_size(
619추가: egui::Pos2::ZERO,
620추가: egui::vec2(1060.0, 720.0),
621추가: )),
622추가: ..Default::default()
623추가: };
624추가: for _ in 0..3 {
625추가: let mut output = ctx.run_ui(input(), |ui| scenario.show(&mut app, ui));
626추가: output.textures_delta.clear();
627추가: }
628추가: assert_eq!(
629추가: app.model.terminal.as_ref().unwrap().error,
630추가: Some(ErrorCode::UnsupportedFeature)
631추가: );
632추가: app.model.terminal.as_mut().unwrap().error = Some(code);
633추가: app.model.archive = Some(archive.into());
634추가: let mut output = ctx.run_ui(input(), |ui| scenario.show(&mut app, ui));
635추가: let labels = text(&output.shapes);
636추가: output.textures_delta.clear();
637추가: if archive == "sample.7z" {
638추가: assert!(!labels.contains("분할 ZIP과 RAR"));
639추가: } else {
640추가: assert!(
641추가: labels.contains("분할 ZIP과 RAR"),
642추가: "{code:?} {archive}: {labels}"
643추가: );
644추가: assert!(
645추가: output
646추가: .viewport_output
647추가: .keys()
648추가: .all(|id| *id == egui::ViewportId::ROOT)
649추가: );
650추가: }
651추가: }
652추가: }
653추가: }
수정tests/rust-app-ui/scenarios.rs+70-0
@@ -21,6 +21,12 @@ macro_rules! catalog {
2121}
2222
2323catalog! {
24추가: "split-archive" => "분할 7z 목록과 미리보기 비활성화",
25추가: "split-first-volume" => "첫 조각의 정확한 파일명 안내",
26추가: "split-missing-volume" => "누락 조각 파일명과 재시도 안내",
27추가: "split-incomplete" => "누락 이름을 단정하지 않는 불완전 묶음 안내",
28추가: "split-unsupported" => "분할 ZIP과 RAR 및 분할 생성 미지원 안내",
29추가: "split-source-changed" => "목록 이후 분할 조각 변경 안내",
2430 "preview-catalog-bytes-approval" => "16 GiB를 넘는 전체 목록의 미리보기 승인",
2531 "preview-catalog-approval" => "미리보기의 전체 목록 처리 예산 승인",
2632 "preview-loading" => "미리보기 로딩과 취소",
@@ -262,6 +268,70 @@ impl Scenario {
262268 archive_sha256: [7; 32],
263269 });
264270 app.model.confirmed = true;
271추가: if self.name.starts_with("split-") {
272추가: let archive = base.join(if self.name == "split-unsupported" {
273추가: "여행.zip.001"
274추가: } else {
275추가: "여행.7z.001"
276추가: });
277추가: app.model.archive = Some(archive.clone());
278추가: app.model.list_id = Some(ListId {
279추가: catalog_version: 2,
280추가: format: Format::SevenZip,
281추가: source_object: SourceObject::SplitSevenZip {
282추가: manifest_sha256: [9; 32],
283추가: },
284추가: archive_bytes: 2_700_000,
285추가: archive_sha256: [7; 32],
286추가: });
287추가: if self.name == "split-archive" {
288추가: app.model.selected.insert(1);
289추가: return app;
290추가: }
291추가: app.start(Start::List { archive });
292추가: let mut state = state.borrow_mut();
293추가: state.frame(Event::Accepted { encryption: false });
294추가: let reason = match self.name {
295추가: "split-first-volume" => Some(VolumeProblemReason::FirstVolumeRequired),
296추가: "split-missing-volume" => Some(VolumeProblemReason::MissingVolume),
297추가: "split-incomplete" => Some(VolumeProblemReason::IncompleteSet),
298추가: _ => None,
299추가: };
300추가: let error = match reason {
301추가: Some(VolumeProblemReason::FirstVolumeRequired) => ErrorCode::InvalidRequest,
302추가: Some(VolumeProblemReason::MissingVolume) => ErrorCode::MissingVolume,
303추가: Some(VolumeProblemReason::IncompleteSet) => ErrorCode::Integrity,
304추가: None if self.name == "split-source-changed" => ErrorCode::SourceChanged,
305추가: None => ErrorCode::UnsupportedFeature,
306추가: };
307추가: if let Some(reason) = reason {
308추가: state.frame(Event::VolumeProblem(VolumeProblem {
309추가: reason,
310추가: volume: NativePath::Unix(if reason == VolumeProblemReason::MissingVolume {
311추가: "여행.7z.003".as_bytes().to_vec()
312추가: } else {
313추가: "여행.7z.001".as_bytes().to_vec()
314추가: }),
315추가: }));
316추가: }
317추가: state.frame(Event::Terminal(Terminal {
318추가: outcome: Outcome::Failed,
319추가: error: Some(error),
320추가: publication: Publication::None,
321추가: created_count: 0,
322추가: retained_partial_count: 0,
323추가: durability: Durability::NotApplicable,
324추가: cleanup: Cleanup::Complete,
325추가: }));
326추가: state.queue.push_back(HostEvent::StdoutEof);
327추가: state.queue.push_back(HostEvent::StderrEof);
328추가: state.queue.push_back(HostEvent::Exited { success: true });
329추가: drop(state);
330추가: for _ in 0..32 {
331추가: app.model.poll();
332추가: }
333추가: return app;
334추가: }
265335 if self.name.starts_with("preview-") {
266336 app.model.selected = BTreeSet::from([1]);
267337 if self.name == "preview-implicit-folder" {
추가tests/rust-app-ui/split_volumes.rs+276-0
@@ -0,0 +1,276 @@
1추가: use super::*;
2추가:
3추가: fn split_id() -> ListId {
4추가: ListId {
5추가: catalog_version: 2,
6추가: format: Format::SevenZip,
7추가: source_object: SourceObject::SplitSevenZip {
8추가: manifest_sha256: [19; 32],
9추가: },
10추가: archive_bytes: 900,
11추가: archive_sha256: [23; 32],
12추가: }
13추가: }
14추가: fn setup() -> (Model, FakeFactory) {
15추가: let mut model = Model::default();
16추가: let mut factory = FakeFactory::manual();
17추가: assert!(model.begin(
18추가: Start::List {
19추가: archive: path("자료.7z.001")
20추가: },
21추가: &mut factory
22추가: ));
23추가: factory
24추가: .state
25추가: .borrow_mut()
26추가: .frame(Event::Accepted { encryption: false });
27추가: (model, factory)
28추가: }
29추가: fn problem(reason: VolumeProblemReason) -> VolumeProblem {
30추가: VolumeProblem {
31추가: reason,
32추가: volume: NativePath::Unix("자료.7z.003".as_bytes().to_vec()),
33추가: }
34추가: }
35추가: fn terminal(factory: &FakeFactory, outcome: Outcome, error: Option<ErrorCode>) {
36추가: factory.state.borrow_mut().frame(Event::Terminal(Terminal {
37추가: outcome,
38추가: error,
39추가: publication: Publication::None,
40추가: created_count: 0,
41추가: retained_partial_count: 0,
42추가: durability: Durability::NotApplicable,
43추가: cleanup: Cleanup::Complete,
44추가: }));
45추가: }
46추가: fn exited(factory: &FakeFactory) {
47추가: let mut state = factory.state.borrow_mut();
48추가: state.queue.push_back(HostEvent::StdoutEof);
49추가: state.queue.push_back(HostEvent::StderrEof);
50추가: state.queue.push_back(HostEvent::Exited { success: true });
51추가: }
52추가: #[test]
53추가: fn split_list_id_is_preserved_for_extract_and_preview_cannot_start() {
54추가: let (mut model, mut factory) = setup();
55추가: {
56추가: let mut state = factory.state.borrow_mut();
57추가: state.frame(Event::Entry(Entry {
58추가: id: 0,
59추가: name: "small.txt".into(),
60추가: kind: Kind::File,
61추가: bytes: Some(7),
62추가: packed: Some(9),
63추가: encrypted: false,
64추가: }));
65추가: state.frame(Event::ListEnd {
66추가: entry_count: 1,
67추가: list_id: split_id(),
68추가: });
69추가: }
70추가: terminal(&factory, Outcome::Completed, None);
71추가: exited(&factory);
72추가: pump(&mut model);
73추가: assert_eq!(model.list_id, Some(split_id()));
74추가: assert!(model.can_extract());
75추가: model.selected.insert(0);
76추가: assert!(!model.can_preview());
77추가: assert!(!model.begin_preview(&mut factory));
78추가: assert!(!model.begin(
79추가: Start::Preview {
80추가: archive: model.archive.clone().unwrap(),
81추가: entry_id: 0,
82추가: list_id: split_id()
83추가: },
84추가: &mut factory
85추가: ));
86추가: assert!(model.extract(path("output"), true, None, &mut factory));
87추가: assert!(
88추가: matches!(factory.state.borrow().starts.last(), Some(Start::Extract { list_id, .. }) if list_id == &split_id())
89추가: );
90추가: }
91추가: #[test]
92추가: fn split_list_id_rejects_invalid_version_format_and_source_combinations() {
93추가: for id in [
94추가: ListId {
95추가: catalog_version: 1,
96추가: ..split_id()
97추가: },
98추가: ListId {
99추가: format: Format::Zip,
100추가: ..split_id()
101추가: },
102추가: ListId {
103추가: source_object: SourceObject::Unix {
104추가: device: 1,
105추가: inode: 2,
106추가: },
107추가: ..split_id()
108추가: },
109추가: ] {
110추가: let (mut model, factory) = setup();
111추가: factory.state.borrow_mut().frame(Event::ListEnd {
112추가: entry_count: 0,
113추가: list_id: id,
114추가: });
115추가: terminal(&factory, Outcome::Completed, None);
116추가: exited(&factory);
117추가: pump(&mut model);
118추가: assert!(model.error.is_some());
119추가: assert!(model.list_id.is_none());
120추가: }
121추가: }
122추가: #[test]
123추가: fn volume_problem_waits_for_terminal_eofs_and_reap_and_clears_on_new_job() {
124추가: let (mut model, mut factory) = setup();
125추가: factory
126추가: .state
127추가: .borrow_mut()
128추가: .frame(Event::VolumeProblem(problem(
129추가: VolumeProblemReason::MissingVolume,
130추가: )));
131추가: terminal(&factory, Outcome::Failed, Some(ErrorCode::MissingVolume));
132추가: for _ in 0..32 {
133추가: model.poll();
134추가: assert!(model.volume_problem.is_none());
135추가: }
136추가: assert!(model.busy());
137추가: exited(&factory);
138추가: pump(&mut model);
139추가: assert!(model.confirmed);
140추가: assert_eq!(
141추가: model.volume_problem,
142추가: Some(problem(VolumeProblemReason::MissingVolume))
143추가: );
144추가: assert!(model.begin(
145추가: Start::List {
146추가: archive: path("next.zip")
147추가: },
148추가: &mut factory
149추가: ));
150추가: assert!(model.volume_problem.is_none());
151추가: }
152추가: #[test]
153추가: fn volume_problem_reason_requires_matching_failed_terminal() {
154추가: for reason in [
155추가: VolumeProblemReason::FirstVolumeRequired,
156추가: VolumeProblemReason::MissingVolume,
157추가: VolumeProblemReason::IncompleteSet,
158추가: ] {
159추가: for valid in [true, false] {
160추가: let (mut model, factory) = setup();
161추가: factory
162추가: .state
163추가: .borrow_mut()
164추가: .frame(Event::VolumeProblem(problem(reason)));
165추가: let error = match reason {
166추가: VolumeProblemReason::FirstVolumeRequired => ErrorCode::InvalidRequest,
167추가: VolumeProblemReason::MissingVolume => ErrorCode::MissingVolume,
168추가: VolumeProblemReason::IncompleteSet => ErrorCode::Integrity,
169추가: };
170추가: terminal(
171추가: &factory,
172추가: if valid {
173추가: Outcome::Failed
174추가: } else {
175추가: Outcome::Completed
176추가: },
177추가: Some(error),
178추가: );
179추가: exited(&factory);
180추가: pump(&mut model);
181추가: assert_eq!(model.confirmed, valid);
182추가: assert_eq!(model.volume_problem.is_some(), valid);
183추가: }
184추가: }
185추가: let (mut model, factory) = setup();
186추가: factory
187추가: .state
188추가: .borrow_mut()
189추가: .frame(Event::VolumeProblem(problem(
190추가: VolumeProblemReason::MissingVolume,
191추가: )));
192추가: terminal(&factory, Outcome::Failed, Some(ErrorCode::Integrity));
193추가: exited(&factory);
194추가: pump(&mut model);
195추가: assert!(!model.confirmed);
196추가: assert!(model.volume_problem.is_none());
197추가: }
198추가: #[test]
199추가: fn duplicate_or_unsafe_volume_names_are_rejected() {
200추가: for duplicate in [false, true] {
201추가: let (mut model, factory) = setup();
202추가: let mut value = problem(VolumeProblemReason::MissingVolume);
203추가: if !duplicate {
204추가: value.volume = NativePath::Unix(b"../outside.7z.003".to_vec());
205추가: }
206추가: factory
207추가: .state
208추가: .borrow_mut()
209추가: .frame(Event::VolumeProblem(value.clone()));
210추가: if duplicate {
211추가: factory
212추가: .state
213추가: .borrow_mut()
214추가: .frame(Event::VolumeProblem(value));
215추가: }
216추가: terminal(&factory, Outcome::Failed, Some(ErrorCode::MissingVolume));
217추가: exited(&factory);
218추가: pump(&mut model);
219추가: assert!(!model.confirmed);
220추가: assert!(model.volume_problem.is_none());
221추가: }
222추가: }
223추가: #[test]
224추가: fn cancellation_discards_late_volume_problem() {
225추가: let (mut model, factory) = setup();
226추가: for _ in 0..4 {
227추가: model.poll();
228추가: }
229추가: model.cancel();
230추가: factory
231추가: .state
232추가: .borrow_mut()
233추가: .frame(Event::VolumeProblem(problem(
234추가: VolumeProblemReason::MissingVolume,
235추가: )));
236추가: factory.state.borrow_mut().frame(Event::CancelAck {
237추가: request_sequence: 1,
238추가: status: CancelStatus::Requested,
239추가: });
240추가: terminal(&factory, Outcome::Cancelled, None);
241추가: exited(&factory);
242추가: pump(&mut model);
243추가: assert!(model.confirmed, "{:?}", model.error);
244추가: assert!(model.volume_problem.is_none());
245추가: }
246추가: #[test]
247추가: fn volume_filename_display_preserves_native_units_and_escapes_controls() {
248추가: use zipelo_ui_memory_app::archive_present::volume_problem_text;
249추가: let mut value = problem(VolumeProblemReason::MissingVolume);
250추가: value.volume = NativePath::Unix(b"a\n\xff.7z.003".to_vec());
251추가: let text = volume_problem_text(&value);
252추가: assert!(text.contains("a\\u{a}\\xff.7z.003"), "{text}");
253추가: assert!(!text.contains('\n'));
254추가: value.volume = NativePath::Windows(vec![0xd800, 0x202e, 46, 55, 122, 46, 48, 48, 51]);
255추가: let text = volume_problem_text(&value);
256추가: assert!(text.contains("\\u{d800}\\u{202e}.7z.003"), "{text}");
257추가: }
258추가:
259추가: #[test]
260추가: fn wrong_job_volume_problem_is_not_presented() {
261추가: let (mut model, factory) = setup();
262추가: factory
263추가: .state
264추가: .borrow_mut()
265추가: .frame(Event::VolumeProblem(problem(
266추가: VolumeProblemReason::MissingVolume,
267추가: )));
268추가: if let Some(HostEvent::Frame { job_id, .. }) = factory.state.borrow_mut().queue.back_mut() {
269추가: *job_id += 1;
270추가: }
271추가: terminal(&factory, Outcome::Failed, Some(ErrorCode::MissingVolume));
272추가: exited(&factory);
273추가: pump(&mut model);
274추가: assert!(!model.confirmed);
275추가: assert!(model.volume_problem.is_none());
276추가: }
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.001

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.002

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.003

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.004

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.005

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.006

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.007

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.008

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.009

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.010

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.001

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.002

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.003

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.004

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.005

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.006

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.007

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.008

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.009

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.010

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.011

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/manifest.json+215-0
@@ -0,0 +1,215 @@
1추가: {
2추가: "tool": "7-Zip (a) 26.00 (x64) : Copyright (c) 1999-2026 Igor Pavlov : 2026-02-12",
3추가: "source": "Ubuntu 7zip 26.00+dfsg-1",
4추가: "payload_sha256": {
5추가: "folder/hello.txt": "8f4e947bcb198177be3ee37336bcfad91ea6ac7e8ba574822ad9992594e25402",
6추가: "second.bin": "689388892d665f3bd6fcfbd95b3e92bb101ef323d81e85d55b8f2ac0dc341686"
7추가: },
8추가: "fixtures": {
9추가: "reference": {
10추가: "arguments": [
11추가: "a",
12추가: "-t7z",
13추가: "-m0=LZMA2",
14추가: "-md=1m",
15추가: "-ms=on",
16추가: "-mhc=off",
17추가: "-mta=off",
18추가: "-mtc=off",
19추가: "-mtm=off",
20추가: "-v64b"
21추가: ],
22추가: "parts": [
23추가: {
24추가: "name": "reference.7z.001",
25추가: "bytes": 64,
26추가: "sha256": "926cc1eccf417dc04de359b88be8e45f988a69de1cec76e1b996b04658b6a839"
27추가: },
28추가: {
29추가: "name": "reference.7z.002",
30추가: "bytes": 64,
31추가: "sha256": "dcbe0ab8bb6e25fd65917ecd2fee5bd433cacd8b446b8dcac3b4b74e2bf0b48a"
32추가: },
33추가: {
34추가: "name": "reference.7z.003",
35추가: "bytes": 64,
36추가: "sha256": "221ab44a6acbb1f1dfcf61b3b591ecf97b6b539fe54affdcf1e69f467a5a6386"
37추가: },
38추가: {
39추가: "name": "reference.7z.004",
40추가: "bytes": 64,
41추가: "sha256": "8f5574b9e8ce6ed7e8279c7ef3cc4ef95a1a798fef34e7b46dcc5f03b4d07f8f"
42추가: },
43추가: {
44추가: "name": "reference.7z.005",
45추가: "bytes": 64,
46추가: "sha256": "75abd8ed00ba5456353886a0fba0c8b84e80779bb739c2367f8e326ab7d064d6"
47추가: },
48추가: {
49추가: "name": "reference.7z.006",
50추가: "bytes": 64,
51추가: "sha256": "c25b47c4c2dba64e4b29d6f404d2b56e4588547beaf270fa05af256daad480e6"
52추가: },
53추가: {
54추가: "name": "reference.7z.007",
55추가: "bytes": 64,
56추가: "sha256": "81f2ee1ab21b6e102cb9b1ea2d22f94214bd77876b2e1ff9cecff47f9d02b805"
57추가: },
58추가: {
59추가: "name": "reference.7z.008",
60추가: "bytes": 64,
61추가: "sha256": "c0577df6e2af28ea14628147893be75d11c653e10a0df1281c234c87d6edf5e9"
62추가: },
63추가: {
64추가: "name": "reference.7z.009",
65추가: "bytes": 41,
66추가: "sha256": "509db208d2a0370d94cff9348cba5342752a0e4af32bf254acc281a0866a4cce"
67추가: }
68추가: ],
69추가: "logical_sha256": "66f0c5bba96b0eaa53b15c12cc233f2954df4ea5f3a7c01ae096f911dd2bfd6b"
70추가: },
71추가: "encrypted-header": {
72추가: "arguments": [
73추가: "a",
74추가: "-t7z",
75추가: "-m0=LZMA2",
76추가: "-md=1m",
77추가: "-ms=on",
78추가: "-mhc=off",
79추가: "-mta=off",
80추가: "-mtc=off",
81추가: "-mtm=off",
82추가: "-v64b",
83추가: "-pzipelo-split-test",
84추가: "-mhe=on"
85추가: ],
86추가: "parts": [
87추가: {
88추가: "name": "encrypted-header.7z.001",
89추가: "bytes": 64,
90추가: "sha256": "f1e82f9bc81de9f7930353e2ea3405e1861079a928b7293a8131d540ea44605c"
91추가: },
92추가: {
93추가: "name": "encrypted-header.7z.002",
94추가: "bytes": 64,
95추가: "sha256": "ef59571335763e52ab8c05cc902d10889a963b3ac9496c3bb397d6b0bd54a761"
96추가: },
97추가: {
98추가: "name": "encrypted-header.7z.003",
99추가: "bytes": 64,
100추가: "sha256": "f9dc1be239cf45306bf8980fa7ad63e89260f0f4502085688c028905eeada0f5"
101추가: },
102추가: {
103추가: "name": "encrypted-header.7z.004",
104추가: "bytes": 64,
105추가: "sha256": "4b64ed14cd8e659cbd154796ead55384bab5ab8a88f94ce308720f649b03cf48"
106추가: },
107추가: {
108추가: "name": "encrypted-header.7z.005",
109추가: "bytes": 64,
110추가: "sha256": "204ac069bcabfc0420450a619e4fd37d620bc1e25269162069c9c0978688a9ef"
111추가: },
112추가: {
113추가: "name": "encrypted-header.7z.006",
114추가: "bytes": 64,
115추가: "sha256": "698d9f22cfb818f6ffa7da166e763a0189f652d8fd765c4549cf2512c3869d17"
116추가: },
117추가: {
118추가: "name": "encrypted-header.7z.007",
119추가: "bytes": 64,
120추가: "sha256": "5c76cc10923601e5512ac60092945890cabe57112242d5c06c834353f9490966"
121추가: },
122추가: {
123추가: "name": "encrypted-header.7z.008",
124추가: "bytes": 64,
125추가: "sha256": "c08af61ef1f3c549e6c5bccc581549054e724ef02b5369dc152596bb1e4c6018"
126추가: },
127추가: {
128추가: "name": "encrypted-header.7z.009",
129추가: "bytes": 64,
130추가: "sha256": "f31af00c7cf084ce7be451f12e5deb4e6a32d843b49666e1dadf59dcd0c9bacf"
131추가: },
132추가: {
133추가: "name": "encrypted-header.7z.010",
134추가: "bytes": 64,
135추가: "sha256": "76ba20a1b63b7d2dbf59553bd923d621f190d18594732e0ac823d47b5d243b07"
136추가: },
137추가: {
138추가: "name": "encrypted-header.7z.011",
139추가: "bytes": 1,
140추가: "sha256": "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d"
141추가: }
142추가: ],
143추가: "logical_sha256": "d194a02a1d24154c6e2f7e3c959b23c20a330955c6496247d57412f262d278ae"
144추가: },
145추가: "encrypted-body": {
146추가: "arguments": [
147추가: "a",
148추가: "-t7z",
149추가: "-m0=LZMA2",
150추가: "-md=1m",
151추가: "-ms=on",
152추가: "-mhc=off",
153추가: "-mta=off",
154추가: "-mtc=off",
155추가: "-mtm=off",
156추가: "-v64b",
157추가: "-pzipelo-split-test",
158추가: "-mhe=off"
159추가: ],
160추가: "parts": [
161추가: {
162추가: "name": "encrypted-body.7z.001",
163추가: "bytes": 64,
164추가: "sha256": "e3e135f63bd6e4c5fb2a463987811ca0e295745904b4876f2d41e90be1edbd9b"
165추가: },
166추가: {
167추가: "name": "encrypted-body.7z.002",
168추가: "bytes": 64,
169추가: "sha256": "aedca6078c99f24c83f83b03f1fa48b1c2be5477871f0b16d23baa00c6237d3c"
170추가: },
171추가: {
172추가: "name": "encrypted-body.7z.003",
173추가: "bytes": 64,
174추가: "sha256": "0b812094951519250385c46d51e8ec25f78cd2343f659db517c45c592a0b25cf"
175추가: },
176추가: {
177추가: "name": "encrypted-body.7z.004",
178추가: "bytes": 64,
179추가: "sha256": "0e6a28d1553cb74fd3c7a2870332b6d49b98bf9357d3bfd48b04712fc7e105ca"
180추가: },
181추가: {
182추가: "name": "encrypted-body.7z.005",
183추가: "bytes": 64,
184추가: "sha256": "2bee9f4c138ae71ad35af650253768a778c3aacc0d34f6f1319213c59627cb5e"
185추가: },
186추가: {
187추가: "name": "encrypted-body.7z.006",
188추가: "bytes": 64,
189추가: "sha256": "6ceacdee4bff8191c4d0d96e8c59ba9a8d73a77c66aea0cf883019800dec175f"
190추가: },
191추가: {
192추가: "name": "encrypted-body.7z.007",
193추가: "bytes": 64,
194추가: "sha256": "73e7ce72aeee468967c3f4e5985eff4c650fa28082a715b5b229bdbc0c94f9ac"
195추가: },
196추가: {
197추가: "name": "encrypted-body.7z.008",
198추가: "bytes": 64,
199추가: "sha256": "dfee6881d0d0d06b6c90ac6afc38ea346e8577466963530d634bb51afd398848"
200추가: },
201추가: {
202추가: "name": "encrypted-body.7z.009",
203추가: "bytes": 64,
204추가: "sha256": "6744ff37e50ff527da6ce80515b582028e5a72e248a0aa1823737f56e6989a9e"
205추가: },
206추가: {
207추가: "name": "encrypted-body.7z.010",
208추가: "bytes": 10,
209추가: "sha256": "87d64a26149d54109ecd0e122979863a0488ab35e468dce5f061084480d5a1a8"
210추가: }
211추가: ],
212추가: "logical_sha256": "931110c31e093301c19ed6fc40fa18f58fc9502b14d4a0fd9fdbb1f7879e5a93"
213추가: }
214추가: }
215추가: }
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.001

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.002

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.003

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.004

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.005

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.006

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.007

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.008

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.009

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
수정tests/rust-archive-worker/main.rs+5-1
@@ -1601,7 +1601,7 @@ fn disk_full_error_tag_preserves_previous_tags_and_rejects_unknown() {
16011601 assert_eq!(bytes[33], tag as u8);
16021602 let decoded = Reader::new(bytes.as_slice()).read().unwrap().unwrap().2;
16031603 assert_eq!(terminal(&[decoded]).error, error);
1604삭제: bytes[33] = 14;
1604추가: bytes[33] = 15;
16051605 assert!(Reader::new(bytes.as_slice()).read().is_err());
16061606 }
16071607}
@@ -1614,6 +1614,8 @@ mod conflict_wire;
16141614
16151615mod preview_wire;
16161616
1617추가: mod split_volume_wire;
1618추가:
16171619mod preview_runtime;
16181620
16191621mod conflicts;
@@ -1621,3 +1623,5 @@ mod conflicts;
16211623mod compressed_tar;
16221624
16231625mod guarded;
1626추가:
1627추가: mod split_runtime;
추가tests/rust-archive-worker/split_capture.rs+485-0
@@ -0,0 +1,485 @@
1추가: use super::*;
2추가: use std::sync::atomic::{AtomicU64, Ordering};
3추가: static NEXT: AtomicU64 = AtomicU64::new(0);
4추가: struct Scratch(PathBuf);
5추가: impl Scratch {
6추가: fn new() -> Self {
7추가: let root = std::env::var_os("TMPDIR")
8추가: .map(PathBuf::from)
9추가: .unwrap_or_else(|| {
10추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")
11추가: });
12추가: std::fs::create_dir_all(&root).unwrap();
13추가: let path = root.canonicalize().unwrap().join(format!(
14추가: "zipelo-split-capture-{}-{}",
15추가: std::process::id(),
16추가: NEXT.fetch_add(1, Ordering::Relaxed)
17추가: ));
18추가: let builder = std::fs::DirBuilder::new();
19추가: #[cfg(unix)]
20추가: let mut builder = builder;
21추가: #[cfg(unix)]
22추가: {
23추가: use std::os::unix::fs::DirBuilderExt;
24추가: builder.mode(0o700);
25추가: }
26추가: builder.create(&path).unwrap();
27추가: Self(path)
28추가: }
29추가: fn split(&self, count: usize) -> Vec<u8> {
30추가: let bytes = include_bytes!("fixtures/7z/copy.7z");
31추가: for index in (0..count).rev() {
32추가: std::fs::write(
33추가: self.0.join(format!("sample.7z.{:03}", index + 1)),
34추가: &bytes[index * bytes.len() / count..(index + 1) * bytes.len() / count],
35추가: )
36추가: .unwrap();
37추가: }
38추가: bytes.to_vec()
39추가: }
40추가: fn first(&self) -> PathBuf {
41추가: self.0.join("sample.7z.001")
42추가: }
43추가: fn capture(&self) -> Captured {
44추가: open(
45추가: &self.first(),
46추가: None,
47추가: u64::MAX,
48추가: crate::archive::MetadataLimits::default(),
49추가: &mut |_| Ok(()),
50추가: )
51추가: .unwrap()
52추가: .unwrap()
53추가: }
54추가: }
55추가: impl Drop for Scratch {
56추가: fn drop(&mut self) {
57추가: std::fs::remove_dir_all(&self.0).expect("분할 조각 임시 폴더 정리에 실패함");
58추가: }
59추가: }
60추가: fn code<T>(result: Result<T>) -> ErrorCode {
61추가: match result {
62추가: Err(failure) => failure.error,
63추가: Ok(_) => panic!("오류가 필요함"),
64추가: }
65추가: }
66추가: fn token(capture: &Captured) -> ListId {
67추가: ListId {
68추가: catalog_version: 2,
69추가: format: Format::SevenZip,
70추가: source_object: capture.snapshot.object.clone(),
71추가: archive_bytes: capture.snapshot.len,
72추가: archive_sha256: capture.snapshot.hash,
73추가: }
74추가: }
75추가:
76추가: #[test]
77추가: fn concatenated_snapshot_and_manifest_include_every_native_component() {
78추가: let s = Scratch::new();
79추가: let original = s.split(11);
80추가: let mut captured = s.capture();
81추가: let mut actual = Vec::new();
82추가: captured.snapshot.file.read_to_end(&mut actual).unwrap();
83추가: assert_eq!(actual, original);
84추가: assert_eq!(
85추가: captured.snapshot.hash,
86추가: <[u8; 32]>::from(Sha256::digest(&original))
87추가: );
88추가: let group = &captured.group;
89추가: let mut bytes = b"zipelo.split7z.v1\0".to_vec();
90추가: fn object(bytes: &mut Vec<u8>, object: &SourceObject) {
91추가: match object {
92추가: SourceObject::Unix { device, inode } => {
93추가: bytes.push(1);
94추가: bytes.extend(device.to_le_bytes());
95추가: bytes.extend(inode.to_le_bytes());
96추가: }
97추가: SourceObject::Windows {
98추가: volume_serial,
99추가: file_id,
100추가: } => {
101추가: bytes.push(2);
102추가: bytes.extend(volume_serial.to_le_bytes());
103추가: bytes.extend(file_id);
104추가: }
105추가: _ => panic!("단일 객체가 필요함"),
106추가: }
107추가: }
108추가: object(&mut bytes, &group.object);
109추가: bytes.extend(11u16.to_le_bytes());
110추가: for (index, part) in group.parts.iter().enumerate() {
111추가: bytes.extend(((index + 1) as u16).to_le_bytes());
112추가: match NativePath::from_path(Path::new(&part.name)) {
113추가: NativePath::Unix(name) => {
114추가: bytes.push(1);
115추가: bytes.extend((name.len() as u32).to_le_bytes());
116추가: bytes.extend(name);
117추가: }
118추가: NativePath::Windows(name) => {
119추가: bytes.push(2);
120추가: bytes.extend((name.len() as u32).to_le_bytes());
121추가: for unit in name {
122추가: bytes.extend(unit.to_le_bytes());
123추가: }
124추가: }
125추가: }
126추가: object(&mut bytes, &part.object);
127추가: bytes.extend(part.length.to_le_bytes());
128추가: bytes.extend(part.hash);
129추가: }
130추가: assert_eq!(
131추가: captured.snapshot.object,
132추가: SourceObject::SplitSevenZip {
133추가: manifest_sha256: Sha256::digest(&bytes).into()
134추가: }
135추가: );
136추가: }
137추가:
138추가: #[test]
139추가: fn verification_hashes_middle_and_tail_even_when_size_and_time_are_restored() {
140추가: for index in [2, 3] {
141추가: let s = Scratch::new();
142추가: s.split(3);
143추가: let captured = s.capture();
144추가: let path = s.0.join(format!("sample.7z.{index:03}"));
145추가: let file = File::options().read(true).write(true).open(&path).unwrap();
146추가: let modified = file.metadata().unwrap().modified().unwrap();
147추가: let mut changed = std::fs::read(&path).unwrap();
148추가: changed[0] ^= 1;
149추가: std::fs::write(&path, changed).unwrap();
150추가: file.set_times(std::fs::FileTimes::new().set_modified(modified))
151추가: .unwrap();
152추가: assert_eq!(
153추가: code(captured.group.verify(&mut |_| Ok(()))),
154추가: ErrorCode::SourceChanged
155추가: );
156추가: }
157추가: }
158추가:
159추가: #[test]
160추가: fn capture_rechecks_parts_after_the_last_read() {
161추가: let s = Scratch::new();
162추가: s.split(3);
163추가: let mut changed = false;
164추가: let result = open(
165추가: &s.first(),
166추가: None,
167추가: u64::MAX,
168추가: crate::archive::MetadataLimits::default(),
169추가: &mut |step| {
170추가: if matches!(step, Step::Read { .. }) && !changed {
171추가: changed = true;
172추가: let p = s.0.join("sample.7z.002");
173추가: let mut bytes = std::fs::read(&p).unwrap();
174추가: bytes[0] ^= 1;
175추가: std::fs::write(p, bytes).unwrap();
176추가: }
177추가: Ok(())
178추가: },
179추가: );
180추가: assert!(changed);
181추가: assert_eq!(code(result), ErrorCode::SourceChanged);
182추가: }
183추가:
184추가: #[test]
185추가: fn verification_detects_parent_replacement_and_new_part_names() {
186추가: let s = Scratch::new();
187추가: s.split(3);
188추가: let captured = s.capture();
189추가: std::fs::write(s.0.join("sample.7z.004"), [0]).unwrap();
190추가: assert_eq!(
191추가: code(captured.group.verify(&mut |_| Ok(()))),
192추가: ErrorCode::SourceChanged
193추가: );
194추가: std::fs::remove_file(s.0.join("sample.7z.004")).unwrap();
195추가: let renamed = s.0.with_extension("old");
196추가: #[cfg(unix)]
197추가: {
198추가: std::fs::rename(&s.0, &renamed).unwrap();
199추가: std::fs::create_dir(&s.0).unwrap();
200추가: assert_eq!(
201추가: code(captured.group.verify(&mut |_| Ok(()))),
202추가: ErrorCode::SourceChanged
203추가: );
204추가: std::fs::remove_dir_all(renamed).unwrap();
205추가: }
206추가: #[cfg(windows)]
207추가: {
208추가: // 고정한 디렉터리는 Windows 공유 모드로 이름 변경을 차단함.
209추가: assert!(std::fs::rename(&s.0, &renamed).is_err());
210추가: captured.group.verify(&mut |_| Ok(())).unwrap();
211추가: }
212추가: }
213추가:
214추가: #[test]
215추가: fn scan_and_rehash_keep_cancellation_and_deadline_errors() {
216추가: for error in [ErrorCode::None, ErrorCode::Limit] {
217추가: let s = Scratch::new();
218추가: s.split(9);
219추가: for at in [1, 10, 50] {
220추가: let mut checks = 0;
221추가: assert_eq!(
222추가: code(open(
223추가: &s.first(),
224추가: None,
225추가: u64::MAX,
226추가: crate::archive::MetadataLimits::default(),
227추가: &mut |step| {
228추가: if matches!(step, Step::Check) {
229추가: checks += 1;
230추가: if checks == at {
231추가: return Err(error);
232추가: }
233추가: }
234추가: Ok(())
235추가: }
236추가: )),
237추가: error
238추가: );
239추가: }
240추가: let captured = s.capture();
241추가: for at in [1, 10, 40] {
242추가: let mut checks = 0;
243추가: assert_eq!(
244추가: code(captured.group.verify(&mut |step| {
245추가: if matches!(step, Step::Check) {
246추가: checks += 1;
247추가: if checks == at {
248추가: return Err(error);
249추가: }
250추가: }
251추가: Ok(())
252추가: })),
253추가: error
254추가: );
255추가: }
256추가: }
257추가: }
258추가:
259추가: #[test]
260추가: fn aggregate_input_and_metadata_limits_are_not_reset_per_part() {
261추가: let s = Scratch::new();
262추가: let bytes = s.split(11);
263추가: assert_eq!(
264추가: code(open(
265추가: &s.first(),
266추가: None,
267추가: bytes.len() as u64 - 1,
268추가: crate::archive::MetadataLimits::default(),
269추가: &mut |_| Ok(())
270추가: )),
271추가: ErrorCode::Limit
272추가: );
273추가: assert!(
274추가: open(
275추가: &s.first(),
276추가: None,
277추가: bytes.len() as u64,
278추가: crate::archive::MetadataLimits::default(),
279추가: &mut |_| Ok(())
280추가: )
281추가: .unwrap()
282추가: .is_some()
283추가: );
284추가: let metadata = crate::archive::MetadataLimits {
285추가: bytes: 512,
286추가: ..Default::default()
287추가: };
288추가: assert_eq!(
289추가: code(open(&s.first(), None, u64::MAX, metadata, &mut |_| Ok(()))),
290추가: ErrorCode::Limit
291추가: );
292추가: }
293추가:
294추가: #[cfg(unix)]
295추가: #[test]
296추가: fn capture_rejects_symlinks_hard_link_aliases_and_special_files() {
297추가: use std::os::unix::fs::symlink;
298추가: let s = Scratch::new();
299추가: s.split(3);
300추가: let first = s.first();
301추가: let second = s.0.join("sample.7z.002");
302추가: std::fs::remove_file(&second).unwrap();
303추가: symlink(&first, &second).unwrap();
304추가: assert_eq!(
305추가: code(open(
306추가: &first,
307추가: None,
308추가: u64::MAX,
309추가: Default::default(),
310추가: &mut |_| Ok(())
311추가: )),
312추가: ErrorCode::UnsafePath
313추가: );
314추가: std::fs::remove_file(&second).unwrap();
315추가: std::fs::hard_link(&first, &second).unwrap();
316추가: assert_eq!(
317추가: code(open(
318추가: &first,
319추가: None,
320추가: u64::MAX,
321추가: Default::default(),
322추가: &mut |_| Ok(())
323추가: )),
324추가: ErrorCode::UnsafePath
325추가: );
326추가: std::fs::remove_file(&second).unwrap();
327추가: std::fs::create_dir(&second).unwrap();
328추가: assert_eq!(
329추가: code(open(
330추가: &first,
331추가: None,
332추가: u64::MAX,
333추가: Default::default(),
334추가: &mut |_| Ok(())
335추가: )),
336추가: ErrorCode::UnsafePath
337추가: );
338추가: }
339추가:
340추가: #[test]
341추가: fn same_logical_data_with_different_part_boundaries_changes_group_identity() {
342추가: let s = Scratch::new();
343추가: s.split(3);
344추가: let captured = s.capture();
345추가: let expected = token(&captured);
346추가: let first = s.first();
347추가: let second = s.0.join("sample.7z.002");
348추가: let mut a = std::fs::read(&first).unwrap();
349추가: let mut b = std::fs::read(&second).unwrap();
350추가: a.push(b.remove(0));
351추가: std::fs::write(first, a).unwrap();
352추가: std::fs::write(second, b).unwrap();
353추가: let next = s.capture();
354추가: assert_eq!(next.snapshot.hash, captured.snapshot.hash);
355추가: assert_ne!(next.snapshot.object, captured.snapshot.object);
356추가: assert_eq!(
357추가: code(open(
358추가: &s.first(),
359추가: Some(&expected),
360추가: u64::MAX,
361추가: Default::default(),
362추가: &mut |_| Ok(())
363추가: )),
364추가: ErrorCode::SourceChanged
365추가: );
366추가: }
367추가:
368추가: #[test]
369추가: fn combined_lengths_reject_u64_overflow_without_changing_the_limit() {
370추가: assert_eq!(combined_length(u64::MAX - 1, 1).unwrap(), u64::MAX);
371추가: assert_eq!(code(combined_length(u64::MAX, 1)), ErrorCode::Limit);
372추가: assert_eq!(code(combined_length(u64::MAX - 1, 2)), ErrorCode::Limit);
373추가: }
374추가:
375추가: #[cfg(unix)]
376추가: #[test]
377추가: fn native_non_utf8_part_names_are_preserved_without_lossy_matching() {
378추가: use std::os::unix::ffi::OsStringExt;
379추가: let s = Scratch::new();
380추가: let original = s.split(3);
381추가: for index in 1..=3 {
382추가: let mut name = b"\xff\x01.7z.".to_vec();
383추가: name.extend(format!("{index:03}").bytes());
384추가: std::fs::rename(
385추가: s.0.join(format!("sample.7z.{index:03}")),
386추가: s.0.join(OsString::from_vec(name)),
387추가: )
388추가: .unwrap();
389추가: }
390추가: let path = s.0.join(OsString::from_vec(b"\xff\x01.7z.001".to_vec()));
391추가: let captured = open(&path, None, u64::MAX, Default::default(), &mut |_| Ok(()))
392추가: .unwrap()
393추가: .unwrap();
394추가: assert_eq!(
395추가: captured.snapshot.hash,
396추가: <[u8; 32]>::from(Sha256::digest(original))
397추가: );
398추가: assert_eq!(
399추가: NativePath::from_path(Path::new(&captured.group.parts[0].name)),
400추가: NativePath::Unix(b"\xff\x01.7z.001".to_vec())
401추가: );
402추가: }
403추가:
404추가: #[test]
405추가: fn disappearing_known_tail_is_a_source_change_before_reopen() {
406추가: let s = Scratch::new();
407추가: s.split(3);
408추가: let captured = s.capture();
409추가: std::fs::remove_file(s.0.join("sample.7z.003")).unwrap();
410추가: assert_eq!(
411추가: code(
412추가: captured
413추가: .group
414추가: .open_part(&captured.group.parts[2].name, &mut |_| Ok(()))
415추가: ),
416추가: ErrorCode::SourceChanged
417추가: );
418추가: }
419추가:
420추가: #[test]
421추가: fn scratch_uses_tmpdir_and_cleans_all_split_parts() {
422추가: let root = std::env::var_os("TMPDIR")
423추가: .map(PathBuf::from)
424추가: .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp"));
425추가: let path = {
426추가: let s = Scratch::new();
427추가: let root = root.canonicalize().unwrap();
428추가: assert_eq!(s.0.parent(), Some(root.as_path()));
429추가: s.split(11);
430추가: assert_eq!(std::fs::read_dir(&s.0).unwrap().count(), 11);
431추가: s.0.clone()
432추가: };
433추가: assert!(!path.exists());
434추가: }
435추가:
436추가: #[test]
437추가: fn scratch_exit_child() {
438추가: if std::env::var_os("ZIPELO_SPLIT_SCRATCH_EXIT_TEST").is_none() {
439추가: return;
440추가: }
441추가: let s = Scratch::new();
442추가: s.split(3);
443추가: // Drop이 실행되지 않는 종료를 재현함.
444추가: std::process::exit(73);
445추가: }
446추가:
447추가: #[test]
448추가: fn scratch_abrupt_exit_leaves_parts_only_under_tmpdir() {
449추가: let path = {
450추가: let s = Scratch::new();
451추가: let status = std::process::Command::new(std::env::current_exe().unwrap())
452추가: .args([
453추가: "--exact",
454추가: "split_seven_zip::tests::scratch_exit_child",
455추가: "--test-threads=1",
456추가: ])
457추가: .env("TMPDIR", &s.0)
458추가: .env("ZIPELO_SPLIT_SCRATCH_EXIT_TEST", "1")
459추가: .output()
460추가: .unwrap();
461추가: assert_eq!(status.status.code(), Some(73), "{status:?}");
462추가: let entries = std::fs::read_dir(&s.0)
463추가: .unwrap()
464추가: .collect::<std::io::Result<Vec<_>>>()
465추가: .unwrap();
466추가: assert_eq!(entries.len(), 1);
467추가: let leftover = entries[0].path();
468추가: assert_eq!(leftover.parent(), Some(s.0.as_path()));
469추가: assert!(
470추가: leftover
471추가: .file_name()
472추가: .unwrap()
473추가: .to_str()
474추가: .unwrap()
475추가: .starts_with("zipelo-split-capture-")
476추가: );
477추가: assert_eq!(std::fs::read_dir(&leftover).unwrap().count(), 3);
478추가: assert_eq!(
479추가: std::fs::read(leftover.join("sample.7z.001")).unwrap().len(),
480추가: include_bytes!("fixtures/7z/copy.7z").len() / 3
481추가: );
482추가: s.0.clone()
483추가: };
484추가: assert!(!path.exists());
485추가: }
추가tests/rust-archive-worker/split_fixtures.py

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

Raw로 열기
추가tests/rust-archive-worker/split_publication_cases.py

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

Raw로 열기
추가tests/rust-archive-worker/split_runtime.rs

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

Raw로 열기
추가tests/rust-archive-worker/split_volume_wire.rs

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

Raw로 열기