Merge pull request #128 from Team-LJY/features/zip-recovery
ZIP32 손상 복구 작업자와 공용 계약 구현
- 작성자
- LeeJunyoung
- 작성 시각
- 커밋
3a77cfd41f44e32cc08af339dbb609905f0d0685
변경된 파일 43개
+1,952-53변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.
| @@ -192,3 +192,22 @@ Ubuntu 제거 안내는 패키지 관리자 터미널 출력입니다. 이전 | ||
| 192 | 192 | - create-sevenzip-resource: 7z 생성의 큰 작업 허용 질문. |
| 193 | 193 | |
| 194 | 194 | 7z를 선택하면 입력한 ZIP 암호와 실행 취소 기록을 지우며, ZIP으로 돌아와도 암호를 복원하지 않는다. 기본 저장 창은 .7z를 제안하며 암호가 필요하면 ZIP을 선택한다. 이 상황들은 가짜 작업자로 화면을 구성하므로 실제 7z 생성과 독립 도구 호환 시험을 대신하지 않는다. |
| 195 | 추가: | |
| 196 | 추가: ### ZIP 복구 | |
| 197 | 추가: | |
| 198 | 추가: 손상 오류에서 "복구본 저장 위치 선택"을 누르면 운영체제 기본 저장 창이 열립니다. | |
| 199 | 추가: 원본을 수정하지 않고 새 ZIP을 만들며, 기존 파일은 덮어쓰지 않습니다. | |
| 200 | 추가: 복구본 저장 완료와 일부 복구를 구분하고, 일부 복구본을 열어도 유실 경고를 유지합니다. | |
| 201 | 추가: 검증된 항목도 손상 전 원본과 동일하다는 보증은 아닙니다. | |
| 202 | 추가: | |
| 203 | 추가: - recovery-progress: 항목 분석 중에는 전체 개수나 완료율을 추정하지 않습니다. | |
| 204 | 추가: - recovery-complete: 검증과 저장, 작업자 종료를 확인한 복구본입니다. | |
| 205 | 추가: - recovery-partial: 유실 항목을 구분하고 저장된 부분 복구본을 열 수 있습니다. | |
| 206 | 추가: - recovery-unknown: 전체 목록을 알 수 없어 추가 유실 여부를 확인할 수 없습니다. | |
| 207 | 추가: - recovery-impossible: 복구 가능한 항목과 생성된 복구본이 없습니다. | |
| 208 | 추가: - recovery-cancelled: 취소 종료와 출력 없음 상태입니다. | |
| 209 | 추가: - recovery-retained: 저장 실패 뒤 남은 임시 파일의 실제 경로와 정리 경고를 표시합니다. 완성된 복구본으로 열지 않습니다. | |
| 210 | 추가: - recovery-save-error: 분석이 끝났어도 저장 실패를 완료로 표시하지 않습니다. | |
| 211 | 추가: - recovery-resource: 원본 제한은 유지하면서 압축률 예산 승인을 확인합니다. | |
| 212 | 추가: | |
| 213 | 추가: 예: `Zipelo --ui-scenario recovery-partial`. 상황 명령은 가짜 작업자만 사용합니다. |
| @@ -0,0 +1,110 @@ | ||
| 1 | 추가: # ZIP 손상 복구 설계와 작업자 계약안 | |
| 2 | 추가: | |
| 3 | 추가: 상태: 히나타가 결과/경고 의미와 오류 태그 15/16에 재동의했다. 공용 타입, codec과 ZIP32 복구 작업자를 구현했으며 frontend 연동과 독립 구현 리뷰는 남아 있다. [PLANS 8.10](PLANS.md#810-손상-파일-복구)과 [8.13](PLANS.md#813-진행과-완료-판단)을 따른다. [작업자 계약](../experiments/rust-archive-worker/contract.json)의 zip_recovery_proposal 키는 초기 문서와의 연결을 위해 유지하지만 status에 명시한 태그는 활성 상태다. Frame version 1, revision 3와 기존 태그 및 일반 목록/해제의 엄격한 검사는 유지한다. | |
| 4 | 추가: | |
| 5 | 추가: 결과 계약 [동의](https://github.com/Team-LJY/zipelo/pull/128#pullrequestreview-5904112564)와 오류 숫자 [재동의](https://github.com/Team-LJY/zipelo/pull/128#pullrequestreview-5904158997)를 확인했다. 초기 14/15 제안이 기존 MissingVolume=14와 충돌한 기록은 보존하며 실제 활성 값은 RecoveryIncomplete=15, RecoveryImpossible=16이다. | |
| 6 | 추가: | |
| 7 | 추가: ## 1. 복구 범위와 한계 | |
| 8 | 추가: | |
| 9 | 추가: - 첫 구현 입력은 단일 볼륨 ZIP32의 비암호화 Store/Deflate 일반 파일과 빈 파일/폴더다. ZIP64 입력, 분할 ZIP, SFX, 암호화된 중앙 목록과 그 밖의 압축 방식은 첫 복구 범위에서 제외한다. 정상 ZIP64/암호 ZIP의 기존 목록/해제 지원을 축소하지 않는다. | |
| 10 | 추가: - 복구 대상은 중앙 디렉터리/EOCD 손상 또는 누락, 온전한 중앙 목록으로 범위를 정할 수 있는 로컬 서명/CRC/크기 필드 손상이다. 본문 손상과 중간 절단에서는 검증 가능한 다른 항목만 구한다. 이름, 경계나 원본 내용 자체를 추측해 되살리지 않는다. | |
| 11 | 추가: - 정상 중앙 목록 안의 암호/미지원 항목은 내용을 내보내지 않고 Unverified로 보고한다. 아카이브 전체의 ZIP64, 분할, SFX 또는 중앙 암호화가 명확하면 UnsupportedFeature로 중단하며 더 약한 로컬 탐색으로 우회하지 않는다. | |
| 12 | 추가: - 원본 ZIP은 읽기 전용이다. 성공 여부와 무관하게 원본과 같은 파일, 하드 링크, 기존 목적지에 쓰거나 원본을 덮어쓰지 않는다. 복구본은 새 파일 하나이며 불완전한 내용의 바이트 조각이나 임의 이름의 파일을 추가하지 않는다. | |
| 13 | 추가: - 파일 내용과 안전한 상대 이름/종류가 보존 대상이다. 서명, ACL, 실행 권한, 소유자, 주석, 알 수 없는 extra field와 모든 시각을 복원한다고 약속하지 않는다. CRC 검증은 원래 작성자의 진위나 악의적인 위조 부재를 뜻하지 않는다. | |
| 14 | 추가: | |
| 15 | 추가: ## 2. 경계와 검증 근거 | |
| 16 | 추가: | |
| 17 | 추가: 형식 판단은 [PKWARE APPNOTE 6.3.10](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)의 4.3.7, 4.3.9, 4.3.12와 4.3.16을 참고한다. 로컬 헤더, 파일 데이터와 선택적 data descriptor 및 중앙 목록을 구분하는 명세이며 손상 복구 알고리즘이나 복구 보증을 제공하지 않는다. 아래의 신뢰 기준은 Zipelo의 보수적인 설계 선택이다. | |
| 18 | 추가: | |
| 19 | 추가: ### CentralDirectory 모드 | |
| 20 | 추가: | |
| 21 | 추가: - EOCD, 중앙 목록 범위/항목 수, 이름/extra field, 디스크 번호와 모든 참조 범위를 독립적으로 검증한다. 참조된 payload가 중앙 목록을 침범하거나 항목 범위가 겹치고 중복되면 정상 목록으로 신뢰하지 않는다. 모든 로컬 항목 범위가 오프셋 0부터 중앙 목록 시작까지 빈틈없이 이어지고 중앙 항목과 1:1로 대응할 때만 전체 목록의 완전성을 확인한다. 공백/불명 범위가 있으면 중앙 항목의 데이터가 맞아도 unknown_loss=true, known_entries=None이며 완전 복구가 아니다. 손상된 목록의 일부 항목 수를 전체 항목 수로 사용하지 않는다. | |
| 22 | 추가: - 로컬 헤더의 이름/extra 길이, raw 이름, flags와 방식이 온전하고 중앙 목록과 맞아 payload 시작이 하나로 정해져야 한다. 이때 로컬 서명, CRC 또는 크기 필드만 중앙 근거로 재구성할 수 있다. 시작 위치/이름/방식이 모호하면 그 항목은 Unverified이고 payload를 복사하지 않는다. | |
| 23 | 추가: - bit 3 항목은 중앙 목록으로 정한 정확한 압축 범위와 지원하는 descriptor의 CRC/크기가 모두 맞을 때만 검증한다. 서명 유무를 구분하며 descriptor 서명을 검색해 데이터 끝을 추측하지 않는다. ZIP64 extra/크기 sentinel이 있으면 첫 입력 범위 밖으로 처리한다. | |
| 24 | 추가: - CRC나 디코딩에 실패하더라도 온전한 중앙 목록이 정한 비중첩 경계로 다음 항목을 검사한다. 범위 자체의 모순은 로컬 목록으로 안전하게 다시 시작할 수 있는지 별도로 판단하며, unsafe path나 자원/저장 오류를 손상 복구로 숨기지 않는다. | |
| 25 | 추가: | |
| 26 | 추가: ### LocalChain 모드 | |
| 27 | 추가: | |
| 28 | 추가: - 사용할 수 있는 중앙 목록이 없으면 오프셋 0부터 연속한 로컬 헤더만 걷는다. bit 3이 꺼져 있고 명시된 ZIP32 크기와 온전한 이름/길이 필드로 다음 위치가 결정되는 항목만 검사한다. | |
| 29 | 추가: - 본문 CRC가 틀려도 완전한 범위가 알려진 항목은 Lost로 기록하고 그 끝에서 다음 헤더를 검사한다. 범위가 EOF를 넘는 절단, 해석 불가 헤더 또는 경계를 알 수 없는 descriptor를 만나면 탐색을 멈춘다. 구조로 확인한 후보의 절단/불명 경계만 Lost/Unverified로 기록하며, 정체를 알 수 없는 꼬리 바이트에 가짜 항목/이름/개수를 만들지 않고 unknown_loss로 남긴다. 다음 정상 멤버를 찾으려고 본문 안의 PK 바이트를 검색하지 않는다. | |
| 30 | 추가: - 중앙 목록 위치나 EOF까지 도달해 모든 관측 항목이 검증되어도 원래 전체 목록이 맞다는 증거는 없다. known_entries=None, unknown_loss=true로 유지하며 유실 0개 또는 완전 복구로 표시하지 않는다. 누락된 파일명이나 개수를 만들어내지 않는다. | |
| 31 | 추가: - 중앙 속성이 없는 경우 안전한 이름의 일반 파일/빈 폴더만 새 일반 속성으로 작성한다. 링크/권한을 추측해 복원하지 않으며 누락 메타데이터를 경고에 남긴다. | |
| 32 | 추가: | |
| 33 | 추가: ### 내보낼 항목의 공통 조건 | |
| 34 | 추가: | |
| 35 | 추가: - 온전한 헤더에서 얻은 압축 범위/예상 크기/CRC와 실제 결과가 모두 맞아야 한다. Deflate는 실제 종료와 정확한 입력 소비를 요구하며 초과/짧은 출력, 남은 압축 바이트와 CRC 불일치는 Lost다. Store도 크기와 CRC를 검사한다. 새로 계산한 CRC로 깨진 원본 CRC를 덮어 정당화하지 않는다. | |
| 36 | 추가: - 검증된 파일의 SHA256을 계산해 결과에 싣고 손상 표본의 외부 기대 해시와 대조한다. 이 해시 자체는 원본의 손상 전 내용을 증명하지 않는다. 검증에 실패한 부분 내용은 복구본에 넣지 않는다. | |
| 37 | 추가: - 절대/상위/장치/예약/대체 스트림 이름, 이름/접두 경로의 대소문자 충돌, 확인된 링크와 특수 파일은 기존 전체 작업의 UnsafePath/Conflict 정책으로 거부한다. 겹친 범위나 추측한 이름에 자동 이름 변경/평탄화 예외를 두지 않는다. | |
| 38 | 추가: | |
| 39 | 추가: ## 3. 원본 보존, 출력과 자원 | |
| 40 | 추가: | |
| 41 | 추가: 1. 원본 일반 파일을 안전한 읽기 핸들로 고정하고 기존 spool::Snapshot에 전체 SHA256과 함께 캡처한다. 경로, 객체, 길이와 수정 메타데이터 변화는 SourceChanged로 거부한다. 모든 파싱/디코딩은 이 비공개 스냅샷에서만 수행한다. | |
| 42 | 추가: 2. 검증된 데이터는 비공개 파일 spool에만 두고 새 비암호화 Store ZIP을 작성한다. 기존 ZIP/ZIP64 작성기의 컨테이너 경계를 재사용하되 사용자 경로의 임시 원본 파일로 변환하지 않는다. Store 복구본은 원본보다 커질 수 있다. 결과 크기가 요구하면 기존 ZIP64 출력 작성을 쓰며 ZIP64 입력 복구 지원을 뜻하지 않는다. | |
| 43 | 추가: 3. 새 헤더는 안전한 이름, 실제 검증된 크기/CRC와 일반 파일/폴더 속성만 기록한다. 원본의 주석/미확인 extra/권한/서명은 복사하지 않는다. 완성된 비공개 ZIP을 엄격한 일반 판독기로 다시 열어 항목과 SHA256을 검사한다. | |
| 44 | 추가: 4. 실제 게시 직전에 원본 객체/길이/메타데이터와 전체 해시를 한 번 재확인한다. 동시 변경을 발견하면 SourceChanged로 중단한다. 이는 파일시스템 전체의 원자적 잠금이나 변경 후 원상복원까지 감지하는 보장이 아니다. | |
| 45 | 추가: 5. 목적지 부모는 기존 Dir로 고정하고 새 파일의 배타적 게시(replace=None)를 쓴다. 캡처/검증 중 새로 나타난 목적지도 Conflict이며 덮어쓰기 질문이나 자동 대체 이름을 추가하지 않는다. fsync/close/게시/부모 sync와 정리 결과를 실제 상태로 보고한다. | |
| 46 | 추가: 6. 취소와 실패는 소유 비공개 spool 및 게시 임시 파일만 정리한다. 게시 뒤 실패/프로세스 손실에는 실제 출력/내구성/불명확 상태를 보존한다. 이미 저장한 부분 복구본을 성공처럼 표시하거나 자동 삭제/rollback하지 않는다. | |
| 47 | 추가: | |
| 48 | 추가: - 복구 입력은 min(호출자 input 상한, 4 GiB)로 제한한다. 4 GiB 초과 원본은 최초 복구 지원 범위 밖이므로 UnsupportedFeature이고 승인으로 늘리거나 큰 작업 재시도를 제안하지 않는다. 호출자가 더 낮춘 input 상한 초과는 기존 Limit이다. 기존 다른 작업의 입력 한도를 바꾸지 않는다. decoded bytes/후보 수는 기본 16 GiB/10000, 명시적 승인 뒤 요청 ceiling 안에서 최대 64 GiB/200000이다. 손실/미확인 후보와 실패 전 실제 디코딩 바이트도 예산에 포함한다. 같은 검증 데이터를 ZIP 작성/게시로 복사하는 바이트는 논리 해제량으로 중복 집계하지 않는다. | |
| 49 | 추가: - 이름, 후보/범위/결과 레코드, SHA 배열, spool 인덱스와 암묵 부모를 할당 전에 기존 메타데이터 예산에 넣는다. 승인 전 8 MiB/32768 노드, 유효한 승인 뒤 64 MiB/262144 노드이며 한 이름 4096바이트, 구성 요소 255바이트, 깊이 64의 기존 경로 제한과 프레임/문자열 제한을 유지한다. | |
| 50 | 추가: - 복사/CRC/디코딩은 64 KiB 청크와 checked u64 오프셋을 쓴다. 동일 범위를 여러 후보 방식으로 재시도하지 않는다. 기존 압축률 질문, 부모 생존, 승인 전 전체 300초/승인 뒤 실제 진행 없는 60초 및 질문 대기 300초 정책을 유지한다. 반복 check나 하트비트를 진짜 진행으로 세지 않는다. | |
| 51 | 추가: - 원본 스냅샷, 검증된 멤버 spool, 완성 ZIP과 목적지 임시 파일의 동시 공간을 볼륨별로 검사하고 각 실제 쓰기에서도 확인한다. 권고 여유 공간은 예약이 아니며 ENOSPC는 DiskFull, 다른 저장 실패는 Io다. Limit/UnsafePath/SourceChanged/저장 실패를 Lost로 낮춰 계속 게시하지 않는다. | |
| 52 | 추가: - 새 의존성은 제안하지 않는다. 이미 쓰는 zlib-rs의 CRC/Deflate, SHA256, 안전한 spool과 ZIP 작성기를 재사용한다. 이번 문서는 의존성 보안 감사나 성능/RSS 검증 결과가 아니다. | |
| 53 | 추가: | |
| 54 | 추가: ## 4. 앱과 작업자 계약 제안 | |
| 55 | 추가: | |
| 56 | 추가: 이 절의 숫자와 결과 의미는 공동 합의되었고 공용 타입과 codec에 반영했다. Frame version=1, 32바이트 헤더, 1 MiB body, 방향별 sequence, 32768 문자열/벡터 전송 상한과 기존 revision 3를 유지한다. 기존 Preview kind 111~113과 VolumeProblem kind 114를 재사용하지 않는다. 실제 wire의 MissingVolume=14도 유지한다. 기존 contract.json의 error_tags 색인은 이 오류를 누락하므로 새 태그 검사는 문서 색인뿐 아니라 활성 wire와 대조한다. 초기 제안의 복구 오류 14/15는 충돌하여 아래 15/16으로 정정하고 재합의했다. 결과 의미와 다른 숫자는 동일하다. | |
| 57 | 추가: | |
| 58 | 추가: ### 요청과 이벤트 | |
| 59 | 추가: | |
| 60 | 추가: - Action::RecoverZip 및 ActionKind::RecoverZip=5를 사용한다. 요청 필드 순서는 archive:NativePath, output_file:NativePath다. Start(kind 1)와 StartGuarded(kind 6, interactive=false)에 허용하며 StartInteractive 및 interactive=true는 양쪽 codec에서 거부한다. Accepted.encryption=false이고 PasswordRequired/ConflictRequired를 보내지 않는다. 기존 ResourceRequired.action에 같은 새 태그를 사용한다. | |
| 61 | 추가: - RecoveryEntry(kind 115): candidate_id:u32, source_offset:u64, name:Option<UTF8>, kind:Option<EntryKind>, status:RecoveryStatus, reason:RecoveryReason, declared_size:Option<u64>, verified_size:Option<u64>, sha256:Option<[u8;32]> 순서다. 중앙 목록의 후보도 로컬 오프셋 순으로 정렬한 0 기반 ID를 한 번씩 보낸다. 일반 Entry/ListEnd/ListId나 preview 프레임은 보내지 않는다. | |
| 62 | 추가: - RecoveryMode는 CentralDirectory=0, LocalChain=1이다. RecoveryStatus는 Verified=0, Lost=1, Unverified=2다. RecoveryReason은 None=0, HeaderRebuilt=1, Truncated=2, CrcMismatch=3, DecodeFailure=4, BoundaryUnknown=5, UnsupportedFeature=6, MetadataMissing=7이다. 유효 reason은 Verified에서 None/HeaderRebuilt/MetadataMissing, Lost에서 Truncated/CrcMismatch/DecodeFailure, Unverified에서 BoundaryUnknown/UnsupportedFeature/MetadataMissing다. 서로 모순되는 조합은 Protocol이다. | |
| 63 | 추가: - Verified에는 확정된 이름이 필요하다. Verified 파일은 declared_size와 verified_size가 같고 SHA256을 가지며 Verified 폴더는 두 크기 0, 해시 None이다. Lost/Unverified에는 verified_size나 SHA256을 싣지 않는다. 불명 이름은 None이며 불명 크기를 0으로 만들지 않는다. kind는 Some(File)/Some(Directory)만 허용하고 판별 불가 후보는 None이다. Verified에는 확정된 kind가 필요하며 링크/특수 종류를 일반 파일로 위장하지 않는다. 이름은 평문 UI에서만 제한 길이로 렌더링하고 경로나 markup으로 실행하지 않는다. | |
| 64 | 추가: - RecoveryEnd(kind 116): mode, source_bytes:u64, source_sha256:[u8;32], known_entries:Option<u32>, verified_entries:u32, lost_entries:u32, unverified_entries:u32, unknown_loss:bool 순서다. 완료된 분석에 한 번만 보내며 실제 게시 전에 보낸다. 집계는 전송한 레코드와 일치해야 하고 중앙 모드에서 연속 범위와 1:1 대응까지 확인한 경우만 known_entries=집계 합, unknown_loss=false다. 중앙 근거가 있어도 불명 공백/범위가 있으면 known_entries=None, unknown_loss=true다. 로컬 모드는 항상 known_entries=None, unknown_loss=true다. 요약 수신은 저장 성공이 아니다. | |
| 65 | 추가: - candidate_id는 이 복구 작업의 결과 ID이며 원본 List EntryIds로 재사용하지 않는다. 복구본을 열려면 명시적 새 List 작업과 새 ListId가 필요하다. 알 수 없는 태그/필드/추가 본문과 중복/오래된 메시지는 Protocol로 거부한다. 앱/작업자는 같은 빌드로 배포하고 다른 형식, 일반 Start 또는 구버전 작업자로 자동 우회하지 않는다. | |
| 66 | 추가: - Progress는 기존 Scan/Read/Decode/Write/Verify/Commit을 사용한다. 알 수 없는 총량은 None이며 후보 조사/검증과 실제 파일 저장을 구분한다. 개별 Verified 레코드는 내부 검증 결과일 뿐 저장한 파일을 뜻하지 않는다. | |
| 67 | 추가: | |
| 68 | 추가: ### 최종 결과와 게시 | |
| 69 | 추가: | |
| 70 | 추가: - 복구본 하나의 실제 Output Created는 entry_id=None, relative_name=목적지 기본 이름이다. 멤버별 Output은 보내지 않는다. 원본 전체 목록을 알고 모든 알려진 항목을 검증했으며 유실/미확인/unknown_loss가 없고 게시/마무리가 성공한 경우에만 Completed/None, publication=Complete, created_count=1이다. | |
| 71 | 추가: - 검증된 항목이 하나 이상이지만 유실, 미확인 또는 불명 전체 목록이 있으면 복구본을 저장한 뒤 Failed/RecoveryIncomplete(새 ErrorCode=15), publication=Complete, created_count=1로 끝낸다. 여기서 Complete는 ZIP 파일 하나의 게시 완료이지 원본 전체의 완전 복구가 아니다. UI는 실패 일반 문구로 복구본을 숨기거나 완전 복구 성공으로 바꾸지 않는다. | |
| 72 | 추가: - 원본이 엄격한 일반 판독/내용 검증까지 통과하고 재구성할 헤더 손상이 없으면 복구 대상이 아니다. RecoverZip을 직접 요청했더라도 InvalidRequest와 출력 0개로 끝내며 정상 control.zip을 자동 재작성하지 않는다. | |
| 73 | 추가: - 검증된 항목이 하나도 없으면 Failed/RecoveryImpossible(새 ErrorCode=16), publication=None, created_count=0으로 끝내고 빈 복구본을 만들지 않는다. 저장/경로/자원/변경/프로토콜 오류와 취소가 생기면 그 실제 오류가 부분 복구 업무 결과보다 우선한다. | |
| 74 | 추가: - 게시 전 실패/취소에는 완성 파일이 없으며 소유 임시 파일 정리 실패만 기존 PartialRetained/cleanup/retained 집계로 보고한다. 게시 후 오류에는 기존 Failed와 실제 Output, durability/cleanup, CommitUncertain/Uncertain을 유지한다. Terminal은 마지막 프레임 하나이고 CancelAck는 완료 증거가 아니다. | |
| 75 | 추가: - 앱은 일치하는 Terminal, stdout/stderr EOF와 소유 자식 회수가 모두 끝난 뒤 결과를 확정한다. 부분 복구본이 있거나 게시/정리가 불명확하면 대형 한도 자동 재시도/닫기 후 자동 재실행을 하지 않는다. 취소 cutoff 뒤 TooLate와 실제 게시 결과도 기존대로 존중한다. | |
| 76 | 추가: | |
| 77 | 추가: ## 5. 화면 인계 기준 | |
| 78 | 추가: | |
| 79 | 추가: - 일반 목록/해제의 Integrity에 복구본 만들기를 명시적으로 제안할 수 있으나 조용히 느슨한 파서를 적용하거나 자동 저장하지 않는다. 사용자가 별도 복구본 생성을 선택하면 운영체제 기본 저장 창에서 새 ZIP 경로를 고른다. 원본을 바꾸지 않으며 일부 자료는 복구할 수 없다는 안내를 먼저 제공한다. | |
| 80 | 추가: - 결과는 검증되어 포함됨, 유실됨, 무결성 미확인을 각각 표시하고 사유를 구분한다. 모르는 파일명/원래 총수는 알 수 없음으로 표시하며 유실 0개나 진행률 100%를 추측하지 않는다. 완전한 목록이 있을 때도 파일별 CRC 검증을 원본 진위 보증으로 표현하지 않는다. | |
| 81 | 추가: - 정상 완료는 복구본 저장 완료, 부분 결과는 일부 항목만 복구함과 전체 목록/무결성 미확인 경고 및 실제 저장 위치를 보여준다. 복구 불가는 복구 가능한 항목 없음으로 구분한다. 세부 결과를 일반 파일 목록 선택과 섞지 않는다. | |
| 82 | 추가: - 복구본은 일반 ZIP이며 별도 sidecar 보고서나 영구 인증서를 자동 생성하지 않는다. 이번 작업의 경고를 결과 화면과 명시적 복구본 열기 전환에 유지한다. 나중의 독립적인 일반 ZIP 목록은 원본에서 무엇이 유실됐는지 증명하지 않으며 완전 복구 판정으로 다시 사용하지 않는다. | |
| 83 | 추가: - frontend 구현 시 --ui-scenario에 복구 진행, 완전/부분/불가 결과, 미확인 목록, 취소, 저장 실패와 자원 질문을 추가하고 해당 시험 및 docs/ui-scenario-guide.md를 같은 PR에서 갱신한다. 현재 backend 변경에는 UI 변경 없음이다. frontend의 화면/시나리오 연동은 같은 PR의 후속 작업이다. | |
| 84 | 추가: | |
| 85 | 추가: ## 6. 손상 표본과 수용 기준 | |
| 86 | 추가: | |
| 87 | 추가: 카논이 같은 features/zip-recovery 브랜치의 [손상 표본과 기대 manifest](../tests/zip-recovery-fixtures/README.md)를 담당한다. 3844170의 README와 expectations.json을 읽어 설계 분류를 대조했다. missing-directory.zip과 broken-eocd.zip은 각 6개, middle-truncated.zip은 앞 4개, body-corrupt.zip은 CRC 실패 항목을 제외한 5개, unrecoverable.zip은 0개가 기대값이다. 이 손상 표본의 유효 항목은 LocalChain 조건으로 처리하므로 전체 목록 불명 경고를 유지한다. control.zip은 정상 열기 대조군이며 복구본을 게시하지 않는다. 이는 기대값의 정적 대조이며 제품 실행이나 표본 시험 통과를 대신하지 않는다. backend는 담당 표본을 동시에 작성하거나 수정하지 않는다. d525c7c의 broken-local-header.zip은 중앙 목록/EOCD와 본문을 보존하고 로컬 서명만 손상했다. 6개 검증 항목, CentralDirectory, known_entries=6과 unknown_loss=false를 기대하는 완전 복구 판정 표본이며 기대값을 읽어 대조했다. 카논의 표본 검증과 실제 작업자 복구 실행은 별개다. | |
| 88 | 추가: | |
| 89 | 추가: - 헤더 손상: 중앙 목록/EOCD 손상은 LocalChain으로 검증된 파일이 기대 SHA256/구조와 맞아도 unknown_loss 경고를 유지한다. 온전한 중앙 목록과 로컬 CRC/서명/크기 손상은 모든 항목 검증 시 완전한 복구본 저장 판정이 가능하다. | |
| 90 | 추가: - 중간 절단: 절단 전 온전한 항목만 포함하고 잘린 항목/이후 불명 부분을 정상으로 세지 않는다. 본문 손상: 온전한 중앙 목록의 다른 항목만 포함하며 CRC 불일치를 Lost로 보고한다. 복구 불가: 검증 항목 0개, 완성 출력 0개다. | |
| 91 | 추가: - 모든 표본에서 원본의 작업 전/후 SHA256 및 실제 원본 바이트가 같아야 한다. 복구 가능한 파일은 손상 전 독립 기대 manifest와 비교하고 Zipelo 및 독립 도구로 복구본을 풀어 파일 해시/상대 구조를 대조한다. 새로 계산한 결과 해시만으로 원본과 같다고 판단하지 않는다. | |
| 92 | 추가: - PK 바이트가 든 본문, 위조 EOCD/중앙 목록, 겹친 범위/잘못된 길이, UTF-8/한글/빈 항목, data descriptor 경계, ZIP64/암호/분할/SFX 제외, unsafe path/충돌/링크와 프레임/후보 수/메타데이터 제한을 포함한다. 이름 추측이나 본문 내 서명 재탐색 없이 실패/부분 결과가 결정돼야 한다. | |
| 93 | 추가: - 취소/부모 종료/원본 변경, 기존 및 검증 중 나타난 목적지, 쓰기/close/sync/부모 sync/정리 오류를 주입하고 실제 파일/Terminal/Output/내구성과 맞는지 확인한다. 손상과 무관한 Limit/DiskFull 등을 Lost로 가려 게시해서는 안 된다. | |
| 94 | 추가: - 계약 동의 뒤 backend 회귀와 python3 tests/ci/run_rust.py local 전체 결과, frontend 화면/시나리오 시험, Windows/Wayland 실기 및 독립 구현 리뷰를 PR 본문에 기록한다. 현재 직접 검증한 backend 회귀에는 6종 실제 작업자 복구와 독립 Python ZIP 검증, 원본 보존 및 실패 주입이 포함된다. 전체 local 결과와 미실행 Windows/Wayland 실기는 PR 본문에서 구분한다. 성능/RSS의 별도 복구 전용 대용량 실기는 아직 수행하지 않았다. | |
| 95 | 추가: | |
| 96 | 추가: ## 7. 구현 순서와 문서 관리 | |
| 97 | 추가: | |
| 98 | 추가: 1. 결과 계약과 오류 숫자의 재합의를 확인하여 제품 타입/codec/탐색기/작성기를 구현했다. 카논의 표본 대조 리뷰와 독립 기대 해시를 backend 수용 시험에 반영했다. | |
| 99 | 추가: 2. 공용 타입/codec과 backend 커밋 및 작업 경로를 전달하며 frontend 결과 화면과 해당 시나리오/시험은 히나타가 담당한다. 프레임 숫자와 결과 조합이 바뀌면 다시 함께 합의한다. | |
| 100 | 추가: 3. 표본 기대 결과를 변경할 필요가 생기면 작성자와 근거를 먼저 합의한다. 실패를 숨기려고 표본이나 기존 엄격한 파서를 약화하지 않는다. | |
| 101 | 추가: 4. 구현/실기 증거가 모인 뒤에만 README/릴리스 노트의 실제 지원 범위를 갱신하고 총관리자의 리뷰/병합 절차를 따른다. 원본 수정과 모든 손상 복구 보장은 완료 기준에 포함하지 않는다. | |
| 102 | 추가: | |
| 103 | 추가: 작업 사본은 tests/work/zip-recovery/r이다. 캐시/임시/검증 자료는 사본 밖 tests/work/zip-recovery 한 곳에만 두고, 이후 실행 시 TMPDIR과 CARGO_TARGET_DIR을 그 하위로 지정한다. PR 병합/종료 뒤 만든 사람이 작업 폴더를 정리하며 진행 중인 다른 담당자 자료는 지우지 않는다. | |
| 104 | 추가: | |
| 105 | 추가: ## 8. 구현과 검증 위치 | |
| 106 | 추가: | |
| 107 | 추가: - backend 탐색/검증/원본 재확인은 zip_recovery.rs, Store 출력은 create.rs의 ZIP64 필드/중앙 목록 마무리를 재사용한다. 검증된 payload는 하나의 비공개 spool로 모으고 손상 항목의 임시 바이트는 되돌린다. CRC 또는 디코더 실패 전에 처리한 바이트도 자원 사용량에 남긴다. | |
| 108 | 추가: - 결과 파일을 일반 streaming 판독기로 다시 검증하고 항목 SHA256을 대조한다. 이 재검증/복사는 논리 해제량을 중복 과금하지 않으며 취소와 실제 진행 검사는 유지한다. 원본 변경 검사는 마지막 게시 callback 안에서 수행한다. | |
| 109 | 추가: - 제품 회귀는 tests/rust-archive-worker/recovery.rs와 recovery_checks.rs에 있다. tests/ci/test_zip_recovery_contract.py의 텍스트 읽기는 UTF-8을 명시하며 기존 오류 및 새 태그를 실제 wire와 비교한다. 기존 시험의 미등록 태그 경계는 새 할당 뒤 값으로 조정했다. 긴 소켓 시험은 열린 출력 폴더의 proc fd 경로로 같은 객체를 만들어 SUN_LEN에 의존하지 않는다. | |
| 110 | 추가: - frontend의 메시지 처리, 결과 화면, --ui-scenario/가이드와 Windows/Wayland 실제 실행은 별도 담당 검증이며 backend 시험 통과로 완료를 대신 선언하지 않는다. |
| @@ -26,7 +26,7 @@ | ||
| 26 | 26 | "archive_names": "Separate validated UTF-8 relative names; entry IDs are opaque ordinal u32, not paths." |
| 27 | 27 | }, |
| 28 | 28 | "commands": { |
| 29 | 삭제: "Start": "Exactly once: List{archive}, Extract{archive,destination,selection:All|EntryIds{ids:[u32]},list_id:optional<ListId>,gzip_output_name:optional<UTF8>}, CreateZip{sources:[source_path,archive_name],output_file,method:Store|Deflate,encryption:None|Aes256}. App supplies job_id; caller can lower worker hard limits. Extract destination is always an absolute output directory. EntryIds requires list_id; All may supply list_id to bind extraction to a displayed list. CreateSevenZip{sources:[Source{path:NativePath,archive_name:UTF8}],output_file:NativePath,method:SevenZipMethod,solid:bool,encryption:Encryption} appends action tag 4. Shared types, codec and the LZMA2 non-solid writer are implemented. Unsupported solid/encryption options fail after Accepted before file access or questions.", | |
| 29 | 추가: "Start": "Exactly once: List{archive}, Extract{archive,destination,selection:All|EntryIds{ids:[u32]},list_id:optional<ListId>,gzip_output_name:optional<UTF8>}, CreateZip{sources:[source_path,archive_name],output_file,method:Store|Deflate,encryption:None|Aes256}. App supplies job_id; caller can lower worker hard limits. Extract destination is always an absolute output directory. EntryIds requires list_id; All may supply list_id to bind extraction to a displayed list. CreateSevenZip{sources:[Source{path:NativePath,archive_name:UTF8}],output_file:NativePath,method:SevenZipMethod,solid:bool,encryption:Encryption} appends action tag 4. Shared types, codec and the LZMA2 non-solid writer are implemented. Unsupported solid/encryption options fail after Accepted before file access or questions. RecoverZip{archive:NativePath,output_file:NativePath} appends action tag 5; Start and noninteractive StartGuarded only.", | |
| 30 | 30 | "Password": "Matching outstanding challenge_id:u64 and max1024 UTF-8 bytes; never log, Debug, echo or persist secrets.", |
| 31 | 31 | "Cancel": "Matching header job_id and empty body; command header sequence identifies the request. See CancelAck. Request acceptance is separate from final outcome. EOF alone is not successful cancellation.", |
| 32 | 32 | "StartInteractive": "Kind 4, body identical to Start with action restricted to Extract. Exactly one initial Start or StartInteractive. Invalid non-Extract action is rejected by the shared encoder and decoder. Opt in to interactive regular-file conflicts; never retry through legacy Start or an older worker automatically. Worker runtime supports the agreed choices; client activation and native UI integration are verified separately.", |
| @@ -35,7 +35,7 @@ | ||
| 35 | 35 | "ResourceReply": "Kind 7: challenge_id:u64,scope:ResourceScope,allow:bool. Frame job_id and exact outstanding challenge_id/scope must match once. Reject premature, stale, duplicate and cross-kind replies as Protocol. False cancels the job without further processing." |
| 36 | 36 | }, |
| 37 | 37 | "events": { |
| 38 | 삭제: "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation. CreateSevenZip explicitly reports encryption=false; existing action capabilities are unchanged.", | |
| 38 | 추가: "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation. CreateSevenZip explicitly reports encryption=false; existing action capabilities are unchanged. RecoverZip also reports encryption=false.", | |
| 39 | 39 | "Entry": "entry_id, name, kind File|Directory|Link|Other, declared sizes, encrypted; ordinal u32 IDs belong to this List job only until its ListEnd token and Completed Terminal are confirmed. Metadata only, no CRC success claim.", |
| 40 | 40 | "ListEnd": "entry_count:u32 and list_id:ListId for a complete listing. Entry IDs are deterministic zero-based ordinals in archive traversal order. App associates this token with this job entries only after Completed Terminal, both stream EOFs and successful child wait/exit.", |
| 41 | 41 | "PasswordRequired": "challenge_id, attempt and purpose Decrypt|Encrypt; no secret diagnostics.", |
| @@ -43,7 +43,7 @@ | ||
| 43 | 43 | "Output": "entry_id:optional, relative_name, disposition Created|PartialRetained|Removed|CommitUncertain; only this job outputs.", |
| 44 | 44 | "Terminal": { |
| 45 | 45 | "outcome": "Completed|Failed|Cancelled", |
| 46 | 삭제: "error": "None|Integrity|UnsupportedFormat|UnsupportedFeature|WrongPassword|UnsafePath|Conflict|Limit|Io|Protocol|Internal|SourceChanged|InvalidRequest|DiskFull", | |
| 46 | 추가: "error": "None|Integrity|UnsupportedFormat|UnsupportedFeature|WrongPassword|UnsafePath|Conflict|Limit|Io|Protocol|Internal|SourceChanged|InvalidRequest|DiskFull|MissingVolume|RecoveryIncomplete|RecoveryImpossible", | |
| 47 | 47 | "publication": "None|Partial|Complete|Uncertain", |
| 48 | 48 | "created_count": "u64", |
| 49 | 49 | "retained_partial_count": "u64", |
| @@ -62,7 +62,51 @@ | ||
| 62 | 62 | }, |
| 63 | 63 | "ConflictRequired": "Kind 108: challenge_id:u64, entry_id:u32, relative_name:UTF8, incoming_size:u64, existing_size:u64. One ordinary-file conflict at a time, after complete archive integrity validation. All three choices are permitted; links and file/directory type conflicts remain rejected.", |
| 64 | 64 | "ConflictResolved": "Kind 109: entry_id:u32, relative_name:UTF8, choice:ConflictChoice(u8). Emit for every resolved conflict, including automatically applied choices. This records the action and resolved name, not successful publication; successful overwrite or rename also requires Output Created. Skip emits no Output Created.", |
| 65 | 삭제: "ResourceRequired": "Kind 110: challenge_id:u64,action:ActionKind,scope:ResourceScope,usage:ResourceUsage,soft_limits:Limits,ceiling:Limits. ResourceScope is output:bool,entries:bool,ratio:bool. ResourceUsage fields in order are estimated_bytes:Option<u64>,actual_bytes:Option<u64>,estimated_entries:Option<u32>,actual_entries:Option<u32>,compressed_bytes:Option<u64>,ratio_output_bytes:Option<u64>,available_bytes:Option<u64>. None is unknown, not zero." | |
| 65 | 추가: "ResourceRequired": "Kind 110: challenge_id:u64,action:ActionKind,scope:ResourceScope,usage:ResourceUsage,soft_limits:Limits,ceiling:Limits. ResourceScope is output:bool,entries:bool,ratio:bool. ResourceUsage fields in order are estimated_bytes:Option<u64>,actual_bytes:Option<u64>,estimated_entries:Option<u32>,actual_entries:Option<u32>,compressed_bytes:Option<u64>,ratio_output_bytes:Option<u64>,available_bytes:Option<u64>. None is unknown, not zero.", | |
| 66 | 추가: "RecoveryEntry": { | |
| 67 | 추가: "fields_in_order": [ | |
| 68 | 추가: "candidate_id:u32", | |
| 69 | 추가: "source_offset:u64", | |
| 70 | 추가: "name:Option<UTF8>", | |
| 71 | 추가: "kind:Option<EntryKind>", | |
| 72 | 추가: "status:RecoveryStatus", | |
| 73 | 추가: "reason:RecoveryReason", | |
| 74 | 추가: "declared_size:Option<u64>", | |
| 75 | 추가: "verified_size:Option<u64>", | |
| 76 | 추가: "sha256:Option<[u8;32]>" | |
| 77 | 추가: ], | |
| 78 | 추가: "constraints": "One stable zero-based ordinal per known candidate, ordered by source local offset, with no duplicates. IDs are not List EntryIds. Name is absent rather than invented if unknown; strings/frame budgets remain unchanged. Only Some(File), Some(Directory) or unknown None; Verified requires a known kind. Never invent a type for an unknown candidate. Verified file has exact sizes and SHA256, directory has size zero and no hash. Lost/Unverified have no verified_size or hash. Unknown enum/field combinations are Protocol. Findings before final result are not saved outputs. Verified requires a known name and equal declared/verified sizes; verified directories have both sizes zero and no hash. Validate the explicit status/reason matrix. Source offsets strictly increase and must fall within source_bytes at summary validation; sums use checked arithmetic.", | |
| 79 | 추가: "valid_reasons": { | |
| 80 | 추가: "Verified": [ | |
| 81 | 추가: "None", | |
| 82 | 추가: "HeaderRebuilt", | |
| 83 | 추가: "MetadataMissing" | |
| 84 | 추가: ], | |
| 85 | 추가: "Lost": [ | |
| 86 | 추가: "Truncated", | |
| 87 | 추가: "CrcMismatch", | |
| 88 | 추가: "DecodeFailure" | |
| 89 | 추가: ], | |
| 90 | 추가: "Unverified": [ | |
| 91 | 추가: "BoundaryUnknown", | |
| 92 | 추가: "UnsupportedFeature", | |
| 93 | 추가: "MetadataMissing" | |
| 94 | 추가: ] | |
| 95 | 추가: } | |
| 96 | 추가: }, | |
| 97 | 추가: "RecoveryEnd": { | |
| 98 | 추가: "fields_in_order": [ | |
| 99 | 추가: "mode:RecoveryMode", | |
| 100 | 추가: "source_bytes:u64", | |
| 101 | 추가: "source_sha256:[u8;32]", | |
| 102 | 추가: "known_entries:Option<u32>", | |
| 103 | 추가: "verified_entries:u32", | |
| 104 | 추가: "lost_entries:u32", | |
| 105 | 추가: "unverified_entries:u32", | |
| 106 | 추가: "unknown_loss:bool" | |
| 107 | 추가: ], | |
| 108 | 추가: "constraints": "At most one summary after completed analysis and before publication. Counts equal emitted findings. Only a central inventory with one-to-one contiguous complete local coverage has known_entries equal to the count sum and unknown_loss=false. Missing inventory, gaps or ambiguous spans give known_entries=None and unknown_loss=true, including in CentralDirectory mode. LocalChain always has None/true. Unknown bytes never create a fabricated candidate or zero loss claim. No ListEnd/ListId or ordinary Entry/preview frames for recovery. A summary alone is not success or proof that a file exists." | |
| 109 | 추가: } | |
| 66 | 110 | }, |
| 67 | 111 | "lifecycle": [ |
| 68 | 112 | "Exactly one Start or StartInteractive; no automatic retry or fallback. Password/Cancel remain readable during work. ConflictReply is accepted only for a matching outstanding interactive conflict.", |
| @@ -189,7 +233,10 @@ | ||
| 189 | 233 | "Internal": 10, |
| 190 | 234 | "SourceChanged": 11, |
| 191 | 235 | "InvalidRequest": 12, |
| 192 | 삭제: "DiskFull": 13 | |
| 236 | 추가: "DiskFull": 13, | |
| 237 | 추가: "MissingVolume": 14, | |
| 238 | 추가: "RecoveryIncomplete": 15, | |
| 239 | 추가: "RecoveryImpossible": 16 | |
| 193 | 240 | }, |
| 194 | 241 | "disk_full_extension": { |
| 195 | 242 | "agreement_message_id": "3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1", |
| @@ -245,7 +292,8 @@ | ||
| 245 | 292 | "Extract": 1, |
| 246 | 293 | "CreateZip": 2, |
| 247 | 294 | "Preview": 3, |
| 248 | 삭제: "CreateSevenZip": 4 | |
| 295 | 추가: "CreateSevenZip": 4, | |
| 296 | 추가: "RecoverZip": 5 | |
| 249 | 297 | }, |
| 250 | 298 | "seven_zip_method_tags": { |
| 251 | 299 | "Lzma2": 0 |
| @@ -267,5 +315,129 @@ | ||
| 267 | 315 | "dependencies": "Existing lzma-rust2 =0.25.0 enables std,xz,encoder with default features disabled. No new lockfile package; encoder=[] adds no transitive dependency. Apache-2.0 originals and hashes are checked through packaging/licenses.py. OSV query on 2026-11-14 returned no advisory for this package/version; this is not a full dependency audit or a vulnerability-free claim.", |
| 268 | 316 | "design": "docs/sevenzip-create-design.md", |
| 269 | 317 | "validation": "Round-trip SHA256 and structure in Zipelo and independent 7-Zip 26.00 with ZIPELO_TEST_7ZIP set; 1 GiB creation RSS regression; cancellation, metadata/byte limits, encoder finish/header write/seek/patch failures, destination write/sync and postpublication sync failures. Results and platform limits are recorded in PR127." |
| 318 | 추가: }, | |
| 319 | 추가: "zip_recovery_proposal": { | |
| 320 | 추가: "status": "jointly-agreed; shared-types-codec-and-worker-implemented; frontend-integration-and-independent-implementation-review-pending", | |
| 321 | 추가: "design": "docs/zip-recovery-design.md", | |
| 322 | 추가: "basis": "PLANS 8.10. Joint result/warning and corrected tag agreement complete. RecoverZip=5, RecoveryEntry/End=115/116 and errors 15/16 are active; preserve MissingVolume=14 and all other existing tags, frame version 1 and revision 3.", | |
| 323 | 추가: "request": { | |
| 324 | 추가: "action": "RecoverZip", | |
| 325 | 추가: "proposed_action_tag": 5, | |
| 326 | 추가: "fields_in_order": [ | |
| 327 | 추가: "archive:NativePath", | |
| 328 | 추가: "output_file:NativePath" | |
| 329 | 추가: ], | |
| 330 | 추가: "admission": "Start or StartGuarded(interactive=false). Reject StartInteractive or interactive=true in both codec directions. Accepted.encryption=false. Reuse existing resource questions; no password/conflict question and no automatic fallback." | |
| 331 | 추가: }, | |
| 332 | 추가: "input_scope": "Initial input support: single-volume non-SFX ZIP32, unencrypted Store or Deflate. ZIP64 input, split/SFX, central encryption, unsupported compression and encrypted-only archives are outside initial repair scope. Existing ordinary list/extract support is unchanged. A clearly identified archive-wide unsupported feature fails UnsupportedFeature without downgrade.", | |
| 333 | 추가: "discovery": { | |
| 334 | 추가: "CentralDirectory": "Use only a fully bounded EOCD/central inventory with exact counts, structural/name validation and nonoverlapping member spans. Repair local signature, CRC or size fields only if the central inventory and intact local name/extra lengths, flags/method/name determine one payload range. Data descriptors require this inventory and exact supported descriptor validation. A complete original inventory additionally requires one-to-one, contiguous local spans from offset zero to the central-directory start. Unaccounted gaps or ambiguous spans force unknown_loss=true and known_entries=None even when the known central entries verify.", | |
| 335 | 추가: "LocalChain": "If there is no usable central inventory, walk complete local records consecutively from offset zero using known ZIP32 lengths and bit3=false. Skip a corrupt payload only when its complete range is known. Stop at a truncated/ambiguous header or unknown descriptor boundary. Never scan payload bytes for a new PK signature or guess names/sizes. Inventory completeness is unknown even when every observed member verifies. Emit a finding only for a structurally established candidate; unrecognized tail bytes create no synthetic entry or count and remain unknown_loss." | |
| 336 | 추가: }, | |
| 337 | 추가: "verification": "Only export supported regular-file or empty-directory candidates with stable safe names and exact bounded lengths. Deflate must reach its real stream end and consume exactly its compressed range; decoded length and CRC32 must match independent header evidence. Compute SHA256 of verified file bytes for result/fixture comparison; a new hash or recomputed CRC cannot make corrupt data valid. CRC evidence is not cryptographic authenticity. Never export raw or partial corrupt bytes.", | |
| 338 | 추가: "proposed_tags": { | |
| 339 | 추가: "RecoveryMode": { | |
| 340 | 추가: "CentralDirectory": 0, | |
| 341 | 추가: "LocalChain": 1 | |
| 342 | 추가: }, | |
| 343 | 추가: "RecoveryStatus": { | |
| 344 | 추가: "Verified": 0, | |
| 345 | 추가: "Lost": 1, | |
| 346 | 추가: "Unverified": 2 | |
| 347 | 추가: }, | |
| 348 | 추가: "RecoveryReason": { | |
| 349 | 추가: "None": 0, | |
| 350 | 추가: "HeaderRebuilt": 1, | |
| 351 | 추가: "Truncated": 2, | |
| 352 | 추가: "CrcMismatch": 3, | |
| 353 | 추가: "DecodeFailure": 4, | |
| 354 | 추가: "BoundaryUnknown": 5, | |
| 355 | 추가: "UnsupportedFeature": 6, | |
| 356 | 추가: "MetadataMissing": 7 | |
| 357 | 추가: }, | |
| 358 | 추가: "ErrorCode": { | |
| 359 | 추가: "RecoveryIncomplete": 15, | |
| 360 | 추가: "RecoveryImpossible": 16 | |
| 361 | 추가: }, | |
| 362 | 추가: "event_kinds": { | |
| 363 | 추가: "RecoveryEntry": 115, | |
| 364 | 추가: "RecoveryEnd": 116 | |
| 365 | 추가: } | |
| 366 | 추가: }, | |
| 367 | 추가: "RecoveryEntry": { | |
| 368 | 추가: "fields_in_order": [ | |
| 369 | 추가: "candidate_id:u32", | |
| 370 | 추가: "source_offset:u64", | |
| 371 | 추가: "name:Option<UTF8>", | |
| 372 | 추가: "kind:Option<EntryKind>", | |
| 373 | 추가: "status:RecoveryStatus", | |
| 374 | 추가: "reason:RecoveryReason", | |
| 375 | 추가: "declared_size:Option<u64>", | |
| 376 | 추가: "verified_size:Option<u64>", | |
| 377 | 추가: "sha256:Option<[u8;32]>" | |
| 378 | 추가: ], | |
| 379 | 추가: "constraints": "One stable zero-based ordinal per known candidate, ordered by source local offset, with no duplicates. IDs are not List EntryIds. Name is absent rather than invented if unknown; strings/frame budgets remain unchanged. Only Some(File), Some(Directory) or unknown None; Verified requires a known kind. Never invent a type for an unknown candidate. Verified file has exact sizes and SHA256, directory has size zero and no hash. Lost/Unverified have no verified_size or hash. Unknown enum/field combinations are Protocol. Findings before final result are not saved outputs. Verified requires a known name and equal declared/verified sizes; verified directories have both sizes zero and no hash. Validate the explicit status/reason matrix. Source offsets strictly increase and must fall within source_bytes at summary validation; sums use checked arithmetic.", | |
| 380 | 추가: "valid_reasons": { | |
| 381 | 추가: "Verified": [ | |
| 382 | 추가: "None", | |
| 383 | 추가: "HeaderRebuilt", | |
| 384 | 추가: "MetadataMissing" | |
| 385 | 추가: ], | |
| 386 | 추가: "Lost": [ | |
| 387 | 추가: "Truncated", | |
| 388 | 추가: "CrcMismatch", | |
| 389 | 추가: "DecodeFailure" | |
| 390 | 추가: ], | |
| 391 | 추가: "Unverified": [ | |
| 392 | 추가: "BoundaryUnknown", | |
| 393 | 추가: "UnsupportedFeature", | |
| 394 | 추가: "MetadataMissing" | |
| 395 | 추가: ] | |
| 396 | 추가: } | |
| 397 | 추가: }, | |
| 398 | 추가: "RecoveryEnd": { | |
| 399 | 추가: "fields_in_order": [ | |
| 400 | 추가: "mode:RecoveryMode", | |
| 401 | 추가: "source_bytes:u64", | |
| 402 | 추가: "source_sha256:[u8;32]", | |
| 403 | 추가: "known_entries:Option<u32>", | |
| 404 | 추가: "verified_entries:u32", | |
| 405 | 추가: "lost_entries:u32", | |
| 406 | 추가: "unverified_entries:u32", | |
| 407 | 추가: "unknown_loss:bool" | |
| 408 | 추가: ], | |
| 409 | 추가: "constraints": "At most one summary after completed analysis and before publication. Counts equal emitted findings. Only a central inventory with one-to-one contiguous complete local coverage has known_entries equal to the count sum and unknown_loss=false. Missing inventory, gaps or ambiguous spans give known_entries=None and unknown_loss=true, including in CentralDirectory mode. LocalChain always has None/true. Unknown bytes never create a fabricated candidate or zero loss claim. No ListEnd/ListId or ordinary Entry/preview frames for recovery. A summary alone is not success or proof that a file exists." | |
| 410 | 추가: }, | |
| 411 | 추가: "output": "Build one new nonencrypted ZIP using Store and the existing safe ZIP/ZIP64 writer, safe normalized relative names, verified file bytes and explicit regular/directory attributes. Do not copy comments, unknown extra fields, symlink/permission attributes or signatures. ZIP64 output is permitted when reconstructed Store sizes require it; ZIP64 input repair remains unsupported initially. Verify the completed private output with the strict reader and per-file hashes before exclusive publication. Do not create a sidecar report or silently extract/reopen it.", | |
| 412 | 추가: "terminal": { | |
| 413 | 추가: "complete": "Completed/None only with a complete central inventory, all known members verified, no loss/unverified count or unknown_loss, one actual Output Created, publication Complete and successful finalization. Display this as a saved recovery copy, not a modified original.", | |
| 414 | 추가: "incomplete_saved": "If at least one verified item is published but any known loss/unverified item or unknown inventory remains: Failed/RecoveryIncomplete, publication Complete, created_count=1. Complete describes the one ZIP artifact publication only, never full source recovery. Keep the artifact and show the warning; do not offer automatic large-limit retry or rollback.", | |
| 415 | 추가: "impossible": "No verified items: Failed/RecoveryImpossible, publication None, zero created/retained outputs unless owned temporary cleanup actually failed.", | |
| 416 | 추가: "fatal_or_cancel": "Limit, UnsafePath, SourceChanged, DiskFull, Io, Conflict, Protocol or cancellation override recovery business summaries. Before publication keep no complete output; preserve actual cleanup/retained/uncertain state. After publication preserve actual Output/durability/cleanup and never synthesize absence or rollback.", | |
| 417 | 추가: "healthy_source": "If the strict normal parser and content verification pass without any header reconstruction needed, reject an explicitly requested RecoverZip with InvalidRequest and zero outputs. A healthy control ZIP remains the normal-list control and is never silently rewritten." | |
| 418 | 추가: }, | |
| 419 | 추가: "source_and_publication": "Capture read-only through pinned safe handles into one private snapshot with full source SHA256. All parsing uses that snapshot. Revalidate source identity/length/metadata and full hash once before publication; detected changes abort SourceChanged. Never open the original or any preexisting destination for write/truncate. Same-path/hard-link/existing/newly appeared destination conflicts are never replaced. Reuse existing publication cutoff, fsync/close, owned temporary cleanup and post-verification destination checks.", | |
| 420 | 추가: "resources": "Recovery-only source input cap is min(caller input quota, 4 GiB). More than 4 GiB is outside initial recovery support and returns UnsupportedFeature with no expanded retry; exceeding a lower caller quota keeps Limit. Resource approval cannot expand source input. Reuse existing 16 GiB/10000 decoded-byte/candidate defaults and explicit guarded ceilings up to 64 GiB/200000. Count lost/unverified candidates and bytes actually decoded before failure. Include result records, names, spans, staging indexes and implicit parents in metadata budgets before allocation: 8 MiB/32768 nodes, or 64 MiB/262144 after a valid grant. Use 64 KiB chunks, checked u64 ranges, bounded strings/frames, ZIP ratio challenges and the existing 300-second/60-second/parent lifetime policies. No per-byte candidate restarts. Disk accounting includes input snapshot, verified member spools, built ZIP and destination temp by actual volume; permission or advisory space checks do not reserve storage.", | |
| 421 | 추가: "client": "Explicit recovery-copy action and native ZIP save dialog; never weaken or silently retry ordinary List/Extract. Show Verified/Lost/Unverified with typed reasons and distinguish unknown inventory from zero loss. Keep recovery findings separate from the ordinary catalog; read a saved copy in a new explicit job with a fresh ListId. Retain partial-warning context when opening a copy, and do not present an ordinary later ZIP listing as proof that all original data was recovered. Result details are job data, not an authenticated permanent recovery certificate.", | |
| 422 | 추가: "lifecycle": "Preserve job/sequence/challenge validation, resource approval, CancelAck and exactly one final Terminal. Confirm results only after matching Terminal, both EOFs and owned-child wait. No new security settings or dependency changes. Frontend agreement is recorded; UI scenarios and native integration remain frontend work.", | |
| 423 | 추가: "fixtures": { | |
| 424 | 추가: "basis_commit": "d525c7c23796b06048180c3b3d2bbaee8075989e", | |
| 425 | 추가: "manifest": "tests/zip-recovery-fixtures/expectations.json", | |
| 426 | 추가: "static_expected_verified_counts": { | |
| 427 | 추가: "missing-directory.zip": 6, | |
| 428 | 추가: "broken-eocd.zip": 6, | |
| 429 | 추가: "middle-truncated.zip": 4, | |
| 430 | 추가: "body-corrupt.zip": 5, | |
| 431 | 추가: "unrecoverable.zip": 0, | |
| 432 | 추가: "broken-local-header.zip": 6 | |
| 433 | 추가: }, | |
| 434 | 추가: "comparison": "Read-only comparison of fixture expectations, not worker execution. The intact-central broken-local-header.zip expects CentralDirectory, known_entries=6 and unknown_loss=false. The other damaged samples lack a usable central inventory and retain unknown_loss." | |
| 435 | 추가: }, | |
| 436 | 추가: "tag_correction": "Initial errors 14/15 collided with live MissingVolume=14. Joint correction preserves MissingVolume=14 and activates RecoveryIncomplete=15 and RecoveryImpossible=16. Regression checks consult live wire, not only the historical contract index.", | |
| 437 | 추가: "agreement": { | |
| 438 | 추가: "frontend_result_review": "https://github.com/Team-LJY/zipelo/pull/128#pullrequestreview-5904112564", | |
| 439 | 추가: "frontend_corrected_tag_review": "https://github.com/Team-LJY/zipelo/pull/128#pullrequestreview-5904158997" | |
| 440 | 추가: }, | |
| 441 | 추가: "validation": "Backend tests cover all six damaged fixtures against independent expected SHA256, Python ZIP verification, source byte preservation, healthy/control rejection, exact Deflate/descriptor boundaries, input/output/candidate caps, source and destination changes, cancellation, staging/publication ENOSPC/IO/sync errors, and decoded bytes before errors. Full local/native results are recorded in PR128." | |
| 270 | 442 | } |
| 271 | 443 | } |
| @@ -288,6 +288,19 @@ pub(crate) fn zip( | ||
| 288 | 288 | central.extend(extra); |
| 289 | 289 | crate::resources::completed(Ok(()), check)?; |
| 290 | 290 | } |
| 291 | 추가: finish_directory(&mut output, ¢ral, plan.items.len(), have_zip64, check)?; | |
| 292 | 추가: plan.verify(check)?; | |
| 293 | 추가: let size = io(output.stream_position())?; | |
| 294 | 추가: io(output.rewind())?; | |
| 295 | 추가: Ok((output, size)) | |
| 296 | 추가: } | |
| 297 | 추가: fn finish_directory( | |
| 298 | 추가: output: &mut File, | |
| 299 | 추가: central: &[u8], | |
| 300 | 추가: count: usize, | |
| 301 | 추가: have_zip64: bool, | |
| 302 | 추가: check: &mut impl crate::resources::Monitor, | |
| 303 | 추가: ) -> Result<()> { | |
| 291 | 304 | check.check()?; |
| 292 | 305 | let at = io(output.stream_position())?; |
| 293 | 306 | crate::space::ensure(&output, central.len() as u64 + 98)?; |
| @@ -297,7 +310,7 @@ pub(crate) fn zip( | ||
| 297 | 310 | let large_at = io(output.stream_position())?; |
| 298 | 311 | let mut end = Vec::new(); |
| 299 | 312 | if have_zip64 |
| 300 | 삭제: || plan.items.len() >= u16::MAX as usize | |
| 313 | 추가: || count >= u16::MAX as usize | |
| 301 | 314 | || at >= u32::MAX as u64 |
| 302 | 315 | || central.len() >= u32::MAX as usize |
| 303 | 316 | { |
| @@ -307,8 +320,8 @@ pub(crate) fn zip( | ||
| 307 | 320 | put16(&mut end, 45); |
| 308 | 321 | put32(&mut end, 0); |
| 309 | 322 | put32(&mut end, 0); |
| 310 | 삭제: put64(&mut end, plan.items.len() as u64); | |
| 311 | 삭제: put64(&mut end, plan.items.len() as u64); | |
| 323 | 추가: put64(&mut end, count as u64); | |
| 324 | 추가: put64(&mut end, count as u64); | |
| 312 | 325 | put64(&mut end, central.len() as u64); |
| 313 | 326 | put64(&mut end, at); |
| 314 | 327 | end.extend(b"PK\x06\x07"); |
| @@ -327,17 +340,137 @@ pub(crate) fn zip( | ||
| 327 | 340 | end.extend(b"PK\x05\x06"); |
| 328 | 341 | put16(&mut end, 0); |
| 329 | 342 | put16(&mut end, 0); |
| 330 | 삭제: put16(&mut end, plan.items.len() as u16); | |
| 331 | 삭제: put16(&mut end, plan.items.len() as u16); | |
| 343 | 추가: put16(&mut end, count as u16); | |
| 344 | 추가: put16(&mut end, count as u16); | |
| 332 | 345 | put32(&mut end, central.len() as u32); |
| 333 | 346 | put32(&mut end, at as u32); |
| 334 | 347 | put16(&mut end, 0); |
| 335 | 348 | } |
| 336 | 349 | crate::resources::completed(io(output.write_all(&end)), check)?; |
| 337 | 삭제: plan.verify(check)?; | |
| 338 | 삭제: let size = io(output.stream_position())?; | |
| 350 | 추가: Ok(()) | |
| 351 | 추가: } | |
| 352 | 추가: | |
| 353 | 추가: pub(crate) fn recovered_zip( | |
| 354 | 추가: findings: &[RecoveryEntry], | |
| 355 | 추가: offsets: &[u64], | |
| 356 | 추가: input: &mut File, | |
| 357 | 추가: check: &mut impl crate::resources::Monitor, | |
| 358 | 추가: ) -> Result<(File, u64)> { | |
| 359 | 추가: if findings.len() != offsets.len() { | |
| 360 | 추가: return Err(ErrorCode::Internal); | |
| 361 | 추가: } | |
| 362 | 추가: let mut output = spool::temporary()?; | |
| 363 | 추가: let mut central = Vec::new(); | |
| 364 | 추가: let mut metadata = crate::archive::MetadataBudget::default(); | |
| 365 | 추가: let mut count = 0; | |
| 366 | 추가: let mut wide = false; | |
| 367 | 추가: let mut buffer = [0; 65536]; | |
| 368 | 추가: for (entry, offset) in findings.iter().zip(offsets) { | |
| 369 | 추가: if entry.status != RecoveryStatus::Verified { | |
| 370 | 추가: continue; | |
| 371 | 추가: } | |
| 372 | 추가: check.check()?; | |
| 373 | 추가: let directory = entry.kind == Some(EntryKind::Directory); | |
| 374 | 추가: let name = entry.name.as_ref().ok_or(ErrorCode::Internal)?; | |
| 375 | 추가: metadata.charge_with(name, check.metadata_limits())?; | |
| 376 | 추가: let name = if directory { | |
| 377 | 추가: format!("{name}/") | |
| 378 | 추가: } else { | |
| 379 | 추가: name.clone() | |
| 380 | 추가: }; | |
| 381 | 추가: let size = entry.verified_size.ok_or(ErrorCode::Internal)?; | |
| 382 | 추가: io(input.seek(std::io::SeekFrom::Start(*offset)))?; | |
| 383 | 추가: let mut left = size; | |
| 384 | 추가: let mut crc = 0; | |
| 385 | 추가: while left != 0 { | |
| 386 | 추가: check.check()?; | |
| 387 | 추가: let n = io(input.read(&mut buffer[..left.min(65536) as usize]))?; | |
| 388 | 추가: if n == 0 { | |
| 389 | 추가: return Err(ErrorCode::Internal); | |
| 390 | 추가: } | |
| 391 | 추가: crc = crc32(crc, &buffer[..n]); | |
| 392 | 추가: left -= n as u64; | |
| 393 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 394 | 추가: } | |
| 395 | 추가: let at = io(output.stream_position())?; | |
| 396 | 추가: let big = size >= u32::MAX as u64; | |
| 397 | 추가: wide |= big || at >= u32::MAX as u64; | |
| 398 | 추가: let ext = zip64_extra(size, size, None); | |
| 399 | 추가: let mut header = b"PK\x03\x04".to_vec(); | |
| 400 | 추가: for value in [if big { 45 } else { 20 }, 0x0800, 0, 0, 33] { | |
| 401 | 추가: put16(&mut header, value); | |
| 402 | 추가: } | |
| 403 | 추가: put32(&mut header, crc); | |
| 404 | 추가: for _ in 0..2 { | |
| 405 | 추가: put32(&mut header, if big { u32::MAX } else { size as u32 }); | |
| 406 | 추가: } | |
| 407 | 추가: put16(&mut header, name.len() as u16); | |
| 408 | 추가: put16(&mut header, ext.len() as u16); | |
| 409 | 추가: header.extend(name.as_bytes()); | |
| 410 | 추가: header.extend(ext); | |
| 411 | 추가: crate::space::ensure( | |
| 412 | 추가: &output, | |
| 413 | 추가: size.checked_add(header.len() as u64) | |
| 414 | 추가: .ok_or(ErrorCode::Limit)?, | |
| 415 | 추가: )?; | |
| 416 | 추가: crate::resources::completed(io(output.write_all(&header)), check)?; | |
| 417 | 추가: io(input.seek(std::io::SeekFrom::Start(*offset)))?; | |
| 418 | 추가: let mut left = size; | |
| 419 | 추가: while left != 0 { | |
| 420 | 추가: check.check()?; | |
| 421 | 추가: let n = io(input.read(&mut buffer[..left.min(65536) as usize]))?; | |
| 422 | 추가: if n == 0 { | |
| 423 | 추가: return Err(ErrorCode::Internal); | |
| 424 | 추가: } | |
| 425 | 추가: crate::space::ensure(&output, n as u64)?; | |
| 426 | 추가: crate::resources::completed(io(output.write_all(&buffer[..n])), check)?; | |
| 427 | 추가: left -= n as u64; | |
| 428 | 추가: } | |
| 429 | 추가: let ext = zip64_extra(size, size, Some(at)); | |
| 430 | 추가: central.extend(b"PK\x01\x02"); | |
| 431 | 추가: for value in [ | |
| 432 | 추가: 0x032d, | |
| 433 | 추가: if big || at >= u32::MAX as u64 { 45 } else { 20 }, | |
| 434 | 추가: 0x0800, | |
| 435 | 추가: 0, | |
| 436 | 추가: 0, | |
| 437 | 추가: 33, | |
| 438 | 추가: ] { | |
| 439 | 추가: put16(&mut central, value); | |
| 440 | 추가: } | |
| 441 | 추가: put32(&mut central, crc); | |
| 442 | 추가: for _ in 0..2 { | |
| 443 | 추가: put32(&mut central, if big { u32::MAX } else { size as u32 }); | |
| 444 | 추가: } | |
| 445 | 추가: put16(&mut central, name.len() as u16); | |
| 446 | 추가: put16(&mut central, ext.len() as u16); | |
| 447 | 추가: for _ in 0..3 { | |
| 448 | 추가: put16(&mut central, 0); | |
| 449 | 추가: } | |
| 450 | 추가: put32( | |
| 451 | 추가: &mut central, | |
| 452 | 추가: if directory { | |
| 453 | 추가: (0o40700 << 16) | 0x10 | |
| 454 | 추가: } else { | |
| 455 | 추가: 0o100600 << 16 | |
| 456 | 추가: }, | |
| 457 | 추가: ); | |
| 458 | 추가: put32( | |
| 459 | 추가: &mut central, | |
| 460 | 추가: if at >= u32::MAX as u64 { | |
| 461 | 추가: u32::MAX | |
| 462 | 추가: } else { | |
| 463 | 추가: at as u32 | |
| 464 | 추가: }, | |
| 465 | 추가: ); | |
| 466 | 추가: central.extend(name.as_bytes()); | |
| 467 | 추가: central.extend(ext); | |
| 468 | 추가: count += 1; | |
| 469 | 추가: } | |
| 470 | 추가: finish_directory(&mut output, ¢ral, count, wide, check)?; | |
| 471 | 추가: let len = io(output.stream_position())?; | |
| 339 | 472 | io(output.rewind())?; |
| 340 | 삭제: Ok((output, size)) | |
| 473 | 추가: Ok((output, len)) | |
| 341 | 474 | } |
| 342 | 475 | |
| 343 | 476 | #[cfg(test)] |
| @@ -17,3 +17,4 @@ mod split_seven_zip; | ||
| 17 | 17 | mod spool; |
| 18 | 18 | mod streaming; |
| 19 | 19 | pub mod wire; |
| 20 | 추가: mod zip_recovery; |
| @@ -237,6 +237,10 @@ pub enum Action { | ||
| 237 | 237 | entry_id: u32, |
| 238 | 238 | list_id: ListId, |
| 239 | 239 | }, |
| 240 | 추가: RecoverZip { | |
| 241 | 추가: archive: NativePath, | |
| 242 | 추가: output_file: NativePath, | |
| 243 | 추가: }, | |
| 240 | 244 | CreateSevenZip { |
| 241 | 245 | sources: Vec<Source>, |
| 242 | 246 | output_file: NativePath, |
| @@ -252,6 +256,7 @@ pub enum ActionKind { | ||
| 252 | 256 | CreateZip, |
| 253 | 257 | Preview, |
| 254 | 258 | CreateSevenZip, |
| 259 | 추가: RecoverZip, | |
| 255 | 260 | } |
| 256 | 261 | impl Action { |
| 257 | 262 | pub fn kind(&self) -> ActionKind { |
| @@ -261,6 +266,7 @@ impl Action { | ||
| 261 | 266 | Self::CreateZip { .. } => ActionKind::CreateZip, |
| 262 | 267 | Self::Preview { .. } => ActionKind::Preview, |
| 263 | 268 | Self::CreateSevenZip { .. } => ActionKind::CreateSevenZip, |
| 269 | 추가: Self::RecoverZip { .. } => ActionKind::RecoverZip, | |
| 264 | 270 | } |
| 265 | 271 | } |
| 266 | 272 | } |
| @@ -357,6 +363,8 @@ pub enum ErrorCode { | ||
| 357 | 363 | InvalidRequest, |
| 358 | 364 | DiskFull, |
| 359 | 365 | MissingVolume, |
| 366 | 추가: RecoveryIncomplete, | |
| 367 | 추가: RecoveryImpossible, | |
| 360 | 368 | } |
| 361 | 369 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 362 | 370 | pub enum VolumeProblemReason { |
| @@ -501,6 +509,8 @@ pub enum Message { | ||
| 501 | 509 | reason: VolumeProblemReason, |
| 502 | 510 | volume: NativePath, |
| 503 | 511 | }, |
| 512 | 추가: RecoveryEntry(RecoveryEntry), | |
| 513 | 추가: RecoveryEnd(RecoveryEnd), | |
| 504 | 514 | Terminal(Terminal), |
| 505 | 515 | CancelAck { |
| 506 | 516 | request_sequence: u64, |
| @@ -519,3 +529,124 @@ pub enum Message { | ||
| 519 | 529 | choice: ConflictChoice, |
| 520 | 530 | }, |
| 521 | 531 | } |
| 532 | 추가: | |
| 533 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 534 | 추가: pub enum RecoveryMode { | |
| 535 | 추가: CentralDirectory, | |
| 536 | 추가: LocalChain, | |
| 537 | 추가: } | |
| 538 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 539 | 추가: pub enum RecoveryStatus { | |
| 540 | 추가: Verified, | |
| 541 | 추가: Lost, | |
| 542 | 추가: Unverified, | |
| 543 | 추가: } | |
| 544 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 545 | 추가: pub enum RecoveryReason { | |
| 546 | 추가: None, | |
| 547 | 추가: HeaderRebuilt, | |
| 548 | 추가: Truncated, | |
| 549 | 추가: CrcMismatch, | |
| 550 | 추가: DecodeFailure, | |
| 551 | 추가: BoundaryUnknown, | |
| 552 | 추가: UnsupportedFeature, | |
| 553 | 추가: MetadataMissing, | |
| 554 | 추가: } | |
| 555 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 556 | 추가: pub struct RecoveryEntry { | |
| 557 | 추가: pub candidate_id: u32, | |
| 558 | 추가: pub source_offset: u64, | |
| 559 | 추가: pub name: Option<String>, | |
| 560 | 추가: pub kind: Option<EntryKind>, | |
| 561 | 추가: pub status: RecoveryStatus, | |
| 562 | 추가: pub reason: RecoveryReason, | |
| 563 | 추가: pub declared_size: Option<u64>, | |
| 564 | 추가: pub verified_size: Option<u64>, | |
| 565 | 추가: pub sha256: Option<[u8; 32]>, | |
| 566 | 추가: } | |
| 567 | 추가: impl RecoveryEntry { | |
| 568 | 추가: pub fn valid(&self) -> bool { | |
| 569 | 추가: if self.name.as_ref().is_some_and(|name| name.is_empty()) { | |
| 570 | 추가: return false; | |
| 571 | 추가: } | |
| 572 | 추가: if !matches!( | |
| 573 | 추가: self.kind, | |
| 574 | 추가: None | Some(EntryKind::File | EntryKind::Directory) | |
| 575 | 추가: ) { | |
| 576 | 추가: return false; | |
| 577 | 추가: } | |
| 578 | 추가: match self.status { | |
| 579 | 추가: RecoveryStatus::Verified => { | |
| 580 | 추가: if self.name.as_ref().is_none_or(|name| name.is_empty()) | |
| 581 | 추가: || !matches!( | |
| 582 | 추가: self.reason, | |
| 583 | 추가: RecoveryReason::None | |
| 584 | 추가: | RecoveryReason::HeaderRebuilt | |
| 585 | 추가: | RecoveryReason::MetadataMissing | |
| 586 | 추가: ) | |
| 587 | 추가: || self.declared_size.is_none() | |
| 588 | 추가: || self.declared_size != self.verified_size | |
| 589 | 추가: { | |
| 590 | 추가: return false; | |
| 591 | 추가: } | |
| 592 | 추가: match self.kind { | |
| 593 | 추가: Some(EntryKind::File) => self.sha256.is_some(), | |
| 594 | 추가: Some(EntryKind::Directory) => { | |
| 595 | 추가: self.declared_size == Some(0) && self.sha256.is_none() | |
| 596 | 추가: } | |
| 597 | 추가: _ => false, | |
| 598 | 추가: } | |
| 599 | 추가: } | |
| 600 | 추가: RecoveryStatus::Lost => { | |
| 601 | 추가: self.verified_size.is_none() | |
| 602 | 추가: && self.sha256.is_none() | |
| 603 | 추가: && matches!( | |
| 604 | 추가: self.reason, | |
| 605 | 추가: RecoveryReason::Truncated | |
| 606 | 추가: | RecoveryReason::CrcMismatch | |
| 607 | 추가: | RecoveryReason::DecodeFailure | |
| 608 | 추가: ) | |
| 609 | 추가: } | |
| 610 | 추가: RecoveryStatus::Unverified => { | |
| 611 | 추가: self.verified_size.is_none() | |
| 612 | 추가: && self.sha256.is_none() | |
| 613 | 추가: && matches!( | |
| 614 | 추가: self.reason, | |
| 615 | 추가: RecoveryReason::BoundaryUnknown | |
| 616 | 추가: | RecoveryReason::UnsupportedFeature | |
| 617 | 추가: | RecoveryReason::MetadataMissing | |
| 618 | 추가: ) | |
| 619 | 추가: } | |
| 620 | 추가: } | |
| 621 | 추가: } | |
| 622 | 추가: } | |
| 623 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 624 | 추가: pub struct RecoveryEnd { | |
| 625 | 추가: pub mode: RecoveryMode, | |
| 626 | 추가: pub source_bytes: u64, | |
| 627 | 추가: pub source_sha256: [u8; 32], | |
| 628 | 추가: pub known_entries: Option<u32>, | |
| 629 | 추가: pub verified_entries: u32, | |
| 630 | 추가: pub lost_entries: u32, | |
| 631 | 추가: pub unverified_entries: u32, | |
| 632 | 추가: pub unknown_loss: bool, | |
| 633 | 추가: } | |
| 634 | 추가: impl RecoveryEnd { | |
| 635 | 추가: pub fn valid(&self) -> bool { | |
| 636 | 추가: let total = self | |
| 637 | 추가: .verified_entries | |
| 638 | 추가: .checked_add(self.lost_entries) | |
| 639 | 추가: .and_then(|n| n.checked_add(self.unverified_entries)); | |
| 640 | 추가: let Some(total) = total else { | |
| 641 | 추가: return false; | |
| 642 | 추가: }; | |
| 643 | 추가: match (self.mode, self.known_entries, self.unknown_loss) { | |
| 644 | 추가: (RecoveryMode::CentralDirectory, Some(known), false) => known == total, | |
| 645 | 추가: (_, None, true) => true, | |
| 646 | 추가: _ => false, | |
| 647 | 추가: } | |
| 648 | 추가: } | |
| 649 | 추가: pub fn complete(&self) -> bool { | |
| 650 | 추가: self.valid() && !self.unknown_loss && self.lost_entries == 0 && self.unverified_entries == 0 | |
| 651 | 추가: } | |
| 652 | 추가: } |
| @@ -42,6 +42,7 @@ struct Job<W> { | ||
| 42 | 42 | source_group: Option<crate::split_seven_zip::Group>, |
| 43 | 43 | source_verified_for_publication: bool, |
| 44 | 44 | creation_plan: Option<crate::create::Plan>, |
| 45 | 추가: recovery: Option<crate::zip_recovery::Recovery>, | |
| 45 | 46 | started: Instant, |
| 46 | 47 | terminal: Terminal, |
| 47 | 48 | parent: crate::parent::Parent, |
| @@ -297,6 +298,11 @@ impl<W: Write> Job<W> { | ||
| 297 | 298 | self.creation_plan = Some(plan); |
| 298 | 299 | result?; |
| 299 | 300 | } |
| 301 | 추가: if let Some(mut recovery) = self.recovery.take() { | |
| 302 | 추가: let result = recovery.verify_source(self); | |
| 303 | 추가: self.recovery = Some(recovery); | |
| 304 | 추가: result?; | |
| 305 | 추가: } | |
| 300 | 306 | self.verify_split()?; |
| 301 | 307 | self.source_verified_for_publication = true; |
| 302 | 308 | } |
| @@ -560,7 +566,10 @@ impl<W: Write> Job<W> { | ||
| 560 | 566 | let limits = self.budget.as_ref().map_or(start.limits, |b| b.ceiling); |
| 561 | 567 | self.event(Message::Accepted { |
| 562 | 568 | action: start.action.kind(), |
| 563 | 삭제: encryption: !matches!(start.action, Action::CreateSevenZip { .. }), | |
| 569 | 추가: encryption: !matches!( | |
| 570 | 추가: start.action, | |
| 571 | 추가: Action::CreateSevenZip { .. } | Action::RecoverZip { .. } | |
| 572 | 추가: ), | |
| 564 | 573 | })?; |
| 565 | 574 | self.check()?; |
| 566 | 575 | if let Action::CreateSevenZip { |
| @@ -589,6 +598,46 @@ impl<W: Write> Job<W> { | ||
| 589 | 598 | } |
| 590 | 599 | } |
| 591 | 600 | match start.action { |
| 601 | 추가: Action::RecoverZip { | |
| 602 | 추가: archive: source, | |
| 603 | 추가: output_file, | |
| 604 | 추가: } => { | |
| 605 | 추가: let source = source.to_path()?; | |
| 606 | 추가: let output = output_file.to_path()?; | |
| 607 | 추가: let leaf = output | |
| 608 | 추가: .file_name() | |
| 609 | 추가: .and_then(|n| n.to_str()) | |
| 610 | 추가: .ok_or(ErrorCode::InvalidRequest)?; | |
| 611 | 추가: let name = archive::valid_name(leaf, false)?; | |
| 612 | 추가: let root = completed( | |
| 613 | 추가: Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?), | |
| 614 | 추가: self, | |
| 615 | 추가: )?; | |
| 616 | 추가: filesystem::preflight_mode_with( | |
| 617 | 추가: &root, | |
| 618 | 추가: &[(name.clone(), EntryKind::File)], | |
| 619 | 추가: false, | |
| 620 | 추가: self, | |
| 621 | 추가: )?; | |
| 622 | 추가: self.progress(Stage::Scan, 0, None, 0)?; | |
| 623 | 추가: let mut recovery = crate::zip_recovery::Recovery::open(&source, limits, self)?; | |
| 624 | 추가: for finding in &recovery.findings { | |
| 625 | 추가: self.event(Message::RecoveryEntry(finding.clone()))?; | |
| 626 | 추가: } | |
| 627 | 추가: self.event(Message::RecoveryEnd(recovery.summary.clone()))?; | |
| 628 | 추가: if recovery.summary.verified_entries == 0 { | |
| 629 | 추가: return Err(ErrorCode::RecoveryImpossible); | |
| 630 | 추가: } | |
| 631 | 추가: let incomplete = !recovery.summary.complete(); | |
| 632 | 추가: let (mut data, length) = recovery.build(limits, self)?; | |
| 633 | 추가: filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?; | |
| 634 | 추가: self.recovery = Some(recovery); | |
| 635 | 추가: self.output_reader(&root, &name, &mut data, length, None, true, None)?; | |
| 636 | 추가: self.terminal.publication = Publication::Complete; | |
| 637 | 추가: if incomplete { | |
| 638 | 추가: return Err(ErrorCode::RecoveryIncomplete); | |
| 639 | 추가: } | |
| 640 | 추가: } | |
| 592 | 641 | Action::List { |
| 593 | 642 | archive: ref source, |
| 594 | 643 | } |
| @@ -1176,6 +1225,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 1176 | 1225 | source_group: None, |
| 1177 | 1226 | source_verified_for_publication: false, |
| 1178 | 1227 | creation_plan: None, |
| 1228 | 추가: recovery: None, | |
| 1179 | 1229 | parent, |
| 1180 | 1230 | started: Instant::now(), |
| 1181 | 1231 | terminal: Terminal { |
| @@ -139,13 +139,16 @@ enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3,SevenZip=4}); | ||
| 139 | 139 | enumeration!(Method{Store=0,Deflate=1}); |
| 140 | 140 | enumeration!(SevenZipMethod{Lzma2=0}); |
| 141 | 141 | enumeration!(Encryption{None=0,Aes256=1}); |
| 142 | 삭제: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3,CreateSevenZip=4}); | |
| 142 | 추가: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3,CreateSevenZip=4,RecoverZip=5}); | |
| 143 | 추가: enumeration!(RecoveryMode{CentralDirectory=0,LocalChain=1}); | |
| 144 | 추가: enumeration!(RecoveryStatus{Verified=0,Lost=1,Unverified=2}); | |
| 145 | 추가: enumeration!(RecoveryReason{None=0,HeaderRebuilt=1,Truncated=2,CrcMismatch=3,DecodeFailure=4,BoundaryUnknown=5,UnsupportedFeature=6,MetadataMissing=7}); | |
| 143 | 146 | enumeration!(PreviewFormat{Utf8Text=0,Rgba8=1}); |
| 144 | 147 | enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3}); |
| 145 | 148 | enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5}); |
| 146 | 149 | enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3}); |
| 147 | 150 | enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2}); |
| 148 | 삭제: 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}); | |
| 151 | 추가: 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,RecoveryIncomplete=15,RecoveryImpossible=16}); | |
| 149 | 152 | enumeration!(VolumeProblemReason{FirstVolumeRequired=0,MissingVolume=1,IncompleteSet=2}); |
| 150 | 153 | enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3}); |
| 151 | 154 | enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3}); |
| @@ -212,6 +215,72 @@ impl Wire for PreviewInfo { | ||
| 212 | 215 | Ok(info) |
| 213 | 216 | } |
| 214 | 217 | } |
| 218 | 추가: impl Wire for RecoveryEntry { | |
| 219 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 220 | 추가: if !self.valid() { | |
| 221 | 추가: return Err(invalid()); | |
| 222 | 추가: } | |
| 223 | 추가: self.candidate_id.enc(e)?; | |
| 224 | 추가: self.source_offset.enc(e)?; | |
| 225 | 추가: self.name.enc(e)?; | |
| 226 | 추가: self.kind.enc(e)?; | |
| 227 | 추가: self.status.enc(e)?; | |
| 228 | 추가: self.reason.enc(e)?; | |
| 229 | 추가: self.declared_size.enc(e)?; | |
| 230 | 추가: self.verified_size.enc(e)?; | |
| 231 | 추가: self.sha256.enc(e)?; | |
| 232 | 추가: Ok(()) | |
| 233 | 추가: } | |
| 234 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 235 | 추가: let value = Self { | |
| 236 | 추가: candidate_id: Wire::dec(d)?, | |
| 237 | 추가: source_offset: Wire::dec(d)?, | |
| 238 | 추가: name: Wire::dec(d)?, | |
| 239 | 추가: kind: Wire::dec(d)?, | |
| 240 | 추가: status: Wire::dec(d)?, | |
| 241 | 추가: reason: Wire::dec(d)?, | |
| 242 | 추가: declared_size: Wire::dec(d)?, | |
| 243 | 추가: verified_size: Wire::dec(d)?, | |
| 244 | 추가: sha256: Wire::dec(d)?, | |
| 245 | 추가: }; | |
| 246 | 추가: if !value.valid() { | |
| 247 | 추가: return Err(invalid()); | |
| 248 | 추가: } | |
| 249 | 추가: Ok(value) | |
| 250 | 추가: } | |
| 251 | 추가: } | |
| 252 | 추가: impl Wire for RecoveryEnd { | |
| 253 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 254 | 추가: if !self.valid() { | |
| 255 | 추가: return Err(invalid()); | |
| 256 | 추가: } | |
| 257 | 추가: self.mode.enc(e)?; | |
| 258 | 추가: self.source_bytes.enc(e)?; | |
| 259 | 추가: self.source_sha256.enc(e)?; | |
| 260 | 추가: self.known_entries.enc(e)?; | |
| 261 | 추가: self.verified_entries.enc(e)?; | |
| 262 | 추가: self.lost_entries.enc(e)?; | |
| 263 | 추가: self.unverified_entries.enc(e)?; | |
| 264 | 추가: self.unknown_loss.enc(e)?; | |
| 265 | 추가: Ok(()) | |
| 266 | 추가: } | |
| 267 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 268 | 추가: let value = Self { | |
| 269 | 추가: mode: Wire::dec(d)?, | |
| 270 | 추가: source_bytes: Wire::dec(d)?, | |
| 271 | 추가: source_sha256: Wire::dec(d)?, | |
| 272 | 추가: known_entries: Wire::dec(d)?, | |
| 273 | 추가: verified_entries: Wire::dec(d)?, | |
| 274 | 추가: lost_entries: Wire::dec(d)?, | |
| 275 | 추가: unverified_entries: Wire::dec(d)?, | |
| 276 | 추가: unknown_loss: Wire::dec(d)?, | |
| 277 | 추가: }; | |
| 278 | 추가: if !value.valid() { | |
| 279 | 추가: return Err(invalid()); | |
| 280 | 추가: } | |
| 281 | 추가: Ok(value) | |
| 282 | 추가: } | |
| 283 | 추가: } | |
| 215 | 284 | structure!(Source { path, archive_name }); |
| 216 | 285 | structure!(Start { action, limits }); |
| 217 | 286 | structure!(GuardedStart { |
| @@ -346,6 +415,14 @@ impl Wire for Selection { | ||
| 346 | 415 | impl Wire for Action { |
| 347 | 416 | fn enc(&self, e: &mut Encoder) -> io::Result<()> { |
| 348 | 417 | match self { |
| 418 | 추가: Self::RecoverZip { | |
| 419 | 추가: archive, | |
| 420 | 추가: output_file, | |
| 421 | 추가: } => { | |
| 422 | 추가: 5u8.enc(e)?; | |
| 423 | 추가: archive.enc(e)?; | |
| 424 | 추가: output_file.enc(e) | |
| 425 | 추가: } | |
| 349 | 426 | Self::List { archive } => { |
| 350 | 427 | 0u8.enc(e)?; |
| 351 | 428 | archive.enc(e) |
| @@ -425,6 +502,10 @@ impl Wire for Action { | ||
| 425 | 502 | entry_id: Wire::dec(d)?, |
| 426 | 503 | list_id: Wire::dec(d)?, |
| 427 | 504 | }), |
| 505 | 추가: 5 => Ok(Self::RecoverZip { | |
| 506 | 추가: archive: Wire::dec(d)?, | |
| 507 | 추가: output_file: Wire::dec(d)?, | |
| 508 | 추가: }), | |
| 428 | 509 | 4 => Ok(Self::CreateSevenZip { |
| 429 | 510 | sources: Wire::dec(d)?, |
| 430 | 511 | output_file: Wire::dec(d)?, |
| @@ -520,6 +601,9 @@ impl Message { | ||
| 520 | 601 | 110 |
| 521 | 602 | } |
| 522 | 603 | Self::Accepted { action, encryption } => { |
| 604 | 추가: if *action == ActionKind::RecoverZip && *encryption { | |
| 605 | 추가: return Err(invalid()); | |
| 606 | 추가: } | |
| 523 | 607 | action.enc(&mut e)?; |
| 524 | 608 | encryption.enc(&mut e)?; |
| 525 | 609 | 100 |
| @@ -607,6 +691,14 @@ impl Message { | ||
| 607 | 691 | volume.enc(&mut e)?; |
| 608 | 692 | 114 |
| 609 | 693 | } |
| 694 | 추가: Self::RecoveryEntry(v) => { | |
| 695 | 추가: v.enc(&mut e)?; | |
| 696 | 추가: 115 | |
| 697 | 추가: } | |
| 698 | 추가: Self::RecoveryEnd(v) => { | |
| 699 | 추가: v.enc(&mut e)?; | |
| 700 | 추가: 116 | |
| 701 | 추가: } | |
| 610 | 702 | Self::Terminal(v) => { |
| 611 | 703 | if v.detail.len() > 4096 { |
| 612 | 704 | return Err(invalid()); |
| @@ -717,10 +809,16 @@ impl Message { | ||
| 717 | 809 | soft_limits: Wire::dec(&mut d)?, |
| 718 | 810 | ceiling: Wire::dec(&mut d)?, |
| 719 | 811 | }, |
| 720 | 삭제: 100 => Self::Accepted { | |
| 721 | 삭제: action: Wire::dec(&mut d)?, | |
| 722 | 삭제: encryption: Wire::dec(&mut d)?, | |
| 723 | 삭제: }, | |
| 812 | 추가: 100 => { | |
| 813 | 추가: let action = Wire::dec(&mut d)?; | |
| 814 | 추가: let encryption = Wire::dec(&mut d)?; | |
| 815 | 추가: if action == ActionKind::RecoverZip && encryption { | |
| 816 | 추가: return Err(invalid()); | |
| 817 | 추가: } | |
| 818 | 추가: Self::Accepted { action, encryption } | |
| 819 | 추가: } | |
| 820 | 추가: 115 => Self::RecoveryEntry(Wire::dec(&mut d)?), | |
| 821 | 추가: 116 => Self::RecoveryEnd(Wire::dec(&mut d)?), | |
| 724 | 822 | 101 => Self::Entry(Wire::dec(&mut d)?), |
| 725 | 823 | 102 => Self::ListEnd { |
| 726 | 824 | entry_count: Wire::dec(&mut d)?, |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기| @@ -7,6 +7,7 @@ pub enum Purpose { | ||
| 7 | 7 | Folder, |
| 8 | 8 | Destination, |
| 9 | 9 | Retry, |
| 10 | 추가: SaveRecoveryZip, | |
| 10 | 11 | SaveZip, |
| 11 | 12 | SaveSevenZip, |
| 12 | 13 | SaveGzip, |
| @@ -110,7 +111,7 @@ fn choose_portal(request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String> | ||
| 110 | 111 | use ashpd::desktop::file_chooser::{FileFilter, OpenFileRequest, SaveFileRequest}; |
| 111 | 112 | let filters = match request.purpose { |
| 112 | 113 | Purpose::Open => archive_filters(), |
| 113 | 삭제: Purpose::SaveZip => vec![("ZIP 압축파일", vec!["zip".into()])], | |
| 114 | 추가: Purpose::SaveZip | Purpose::SaveRecoveryZip => vec![("ZIP 압축파일", vec!["zip".into()])], | |
| 114 | 115 | Purpose::SaveSevenZip => vec![("7z 압축파일", vec!["7z".into()])], |
| 115 | 116 | _ => Vec::new(), |
| 116 | 117 | } |
| @@ -130,22 +131,26 @@ fn choose_portal(request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String> | ||
| 130 | 131 | .collect::<Vec<_>>(); |
| 131 | 132 | portal_response(pollster::block_on(async move { |
| 132 | 133 | let selected = match request.purpose { |
| 133 | 삭제: Purpose::SaveZip | Purpose::SaveSevenZip | Purpose::SaveGzip | Purpose::RetryGzip => { | |
| 134 | 삭제: SaveFileRequest::default() | |
| 135 | 삭제: .title(if request.purpose == Purpose::SaveSevenZip { | |
| 136 | 삭제: "7z 파일 저장" | |
| 137 | 삭제: } else if request.purpose == Purpose::SaveZip { | |
| 138 | 삭제: "ZIP 파일 저장" | |
| 139 | 삭제: } else { | |
| 140 | 삭제: "압축 해제 파일 저장" | |
| 141 | 삭제: }) | |
| 142 | 삭제: .current_name(Some(request.file_name.as_str())) | |
| 143 | 삭제: .filters(filters) | |
| 144 | 삭제: .current_folder::<&PathBuf>(Some(&request.directory))? | |
| 145 | 삭제: .send() | |
| 146 | 삭제: .await? | |
| 147 | 삭제: .response()? | |
| 148 | 삭제: } | |
| 134 | 추가: Purpose::SaveRecoveryZip | |
| 135 | 추가: | Purpose::SaveZip | |
| 136 | 추가: | Purpose::SaveSevenZip | |
| 137 | 추가: | Purpose::SaveGzip | |
| 138 | 추가: | Purpose::RetryGzip => SaveFileRequest::default() | |
| 139 | 추가: .title(if request.purpose == Purpose::SaveRecoveryZip { | |
| 140 | 추가: "복구본을 새 ZIP 파일로 저장" | |
| 141 | 추가: } else if request.purpose == Purpose::SaveSevenZip { | |
| 142 | 추가: "7z 파일 저장" | |
| 143 | 추가: } else if request.purpose == Purpose::SaveZip { | |
| 144 | 추가: "ZIP 파일 저장" | |
| 145 | 추가: } else { | |
| 146 | 추가: "압축 해제 파일 저장" | |
| 147 | 추가: }) | |
| 148 | 추가: .current_name(Some(request.file_name.as_str())) | |
| 149 | 추가: .filters(filters) | |
| 150 | 추가: .current_folder::<&PathBuf>(Some(&request.directory))? | |
| 151 | 추가: .send() | |
| 152 | 추가: .await? | |
| 153 | 추가: .response()?, | |
| 149 | 154 | purpose => OpenFileRequest::default() |
| 150 | 155 | .title(match purpose { |
| 151 | 156 | Purpose::Open => "압축파일 열기", |
| @@ -206,6 +211,12 @@ fn choose_native(request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String> | ||
| 206 | 211 | .add_filter("7z 압축파일", &["7z"]) |
| 207 | 212 | .save_file() |
| 208 | 213 | .map(|path| vec![path]), |
| 214 | 추가: Purpose::SaveRecoveryZip => dialog | |
| 215 | 추가: .set_title("복구본을 새 ZIP 파일로 저장") | |
| 216 | 추가: .set_file_name(request.file_name) | |
| 217 | 추가: .add_filter("ZIP 압축파일", &["zip"]) | |
| 218 | 추가: .save_file() | |
| 219 | 추가: .map(|path| vec![path]), | |
| 209 | 220 | Purpose::SaveZip => dialog |
| 210 | 221 | .set_title("ZIP 파일 저장") |
| 211 | 222 | .set_file_name(request.file_name) |
| @@ -19,6 +19,8 @@ pub const FOLDER_ERROR: &str = "풀 위치 폴더를 만들 수 없습니다. | ||
| 19 | 19 | |
| 20 | 20 | pub fn error_text(code: ErrorCode) -> &'static str { |
| 21 | 21 | match code { |
| 22 | 추가: ErrorCode::RecoveryIncomplete => "일부 항목만 복구했습니다. 복구본과 경고를 확인하세요.", | |
| 23 | 추가: ErrorCode::RecoveryImpossible => "복구 가능한 항목이 없습니다.", | |
| 22 | 24 | ErrorCode::MissingVolume => { |
| 23 | 25 | "분할 압축파일의 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 .001을 다시 여세요" |
| 24 | 26 | } |
| @@ -201,6 +201,15 @@ fn start_to_wire(start: ui::Start) -> wire::Start { | ||
| 201 | 201 | entry_id, |
| 202 | 202 | list_id: list_to_wire(list_id), |
| 203 | 203 | }, |
| 204 | 추가: ui::Start::RecoverZip { | |
| 205 | 추가: archive, | |
| 206 | 추가: output_file, | |
| 207 | 추가: } => wire::Action::RecoverZip { | |
| 208 | 추가: archive: wire::NativePath::from_path(&crate::archive_path::worker_path(&archive)), | |
| 209 | 추가: output_file: wire::NativePath::from_path(&crate::archive_path::worker_path( | |
| 210 | 추가: &output_file, | |
| 211 | 추가: )), | |
| 212 | 추가: }, | |
| 204 | 213 | ui::Start::CreateSevenZip { |
| 205 | 214 | sources, |
| 206 | 215 | output_file, |
| @@ -253,6 +262,8 @@ fn start_to_wire(start: ui::Start) -> wire::Start { | ||
| 253 | 262 | } |
| 254 | 263 | fn error_to_ui(error: wire::ErrorCode) -> Option<ui::ErrorCode> { |
| 255 | 264 | Some(match error { |
| 265 | 추가: wire::ErrorCode::RecoveryIncomplete => ui::ErrorCode::RecoveryIncomplete, | |
| 266 | 추가: wire::ErrorCode::RecoveryImpossible => ui::ErrorCode::RecoveryImpossible, | |
| 256 | 267 | wire::ErrorCode::MissingVolume => ui::ErrorCode::MissingVolume, |
| 257 | 268 | wire::ErrorCode::None => return None, |
| 258 | 269 | wire::ErrorCode::Integrity => ui::ErrorCode::Integrity, |
| @@ -275,6 +286,12 @@ fn event_to_ui( | ||
| 275 | 286 | expected: Option<wire::ActionKind>, |
| 276 | 287 | ) -> Result<ui::Event, ()> { |
| 277 | 288 | Ok(match message { |
| 289 | 추가: wire::Message::RecoveryEntry(entry) if expected == Some(wire::ActionKind::RecoverZip) => { | |
| 290 | 추가: ui::Event::RecoveryEntry(entry) | |
| 291 | 추가: } | |
| 292 | 추가: wire::Message::RecoveryEnd(end) if expected == Some(wire::ActionKind::RecoverZip) => { | |
| 293 | 추가: ui::Event::RecoveryEnd(end) | |
| 294 | 추가: } | |
| 278 | 295 | wire::Message::VolumeProblem { reason, volume } |
| 279 | 296 | if matches!( |
| 280 | 297 | expected, |
| @@ -243,6 +243,7 @@ pub struct ArchiveApp { | ||
| 243 | 243 | list_focused: bool, |
| 244 | 244 | marquee: Option<Marquee>, |
| 245 | 245 | last_request: Option<Start>, |
| 246 | 추가: recovery_warning: Option<(PathBuf, String)>, | |
| 246 | 247 | targets: Option<BTreeSet<String>>, |
| 247 | 248 | directories: BTreeSet<String>, |
| 248 | 249 | dismissed: bool, |
| @@ -308,6 +309,7 @@ impl ArchiveApp { | ||
| 308 | 309 | list_focused: false, |
| 309 | 310 | marquee: None, |
| 310 | 311 | last_request: None, |
| 312 | 추가: recovery_warning: None, | |
| 311 | 313 | targets: None, |
| 312 | 314 | directories: BTreeSet::new(), |
| 313 | 315 | dismissed: false, |
| @@ -450,6 +452,13 @@ impl ArchiveApp { | ||
| 450 | 452 | if self.model.busy() { |
| 451 | 453 | return; |
| 452 | 454 | } |
| 455 | 추가: if self | |
| 456 | 추가: .recovery_warning | |
| 457 | 추가: .as_ref() | |
| 458 | 추가: .is_some_and(|(path, _)| path != &archive) | |
| 459 | 추가: { | |
| 460 | 추가: self.recovery_warning = None; | |
| 461 | 추가: } | |
| 453 | 462 | self.clear_password(); |
| 454 | 463 | self.destination = present::default_destination(&archive); |
| 455 | 464 | self.automatic_destination = true; |
| @@ -468,6 +477,12 @@ impl ArchiveApp { | ||
| 468 | 477 | if self.picker.is_some() { |
| 469 | 478 | return false; |
| 470 | 479 | } |
| 480 | 추가: if matches!(request, Start::RecoverZip { .. }) { | |
| 481 | 추가: self.work = WorkWindow { | |
| 482 | 추가: height: 480.0, | |
| 483 | 추가: ..WorkWindow::default() | |
| 484 | 추가: }; | |
| 485 | 추가: } | |
| 471 | 486 | self.last_request = Some(request.clone()); |
| 472 | 487 | self.dismissed = false; |
| 473 | 488 | self.details = false; |
| @@ -682,7 +697,7 @@ impl ArchiveApp { | ||
| 682 | 697 | }; |
| 683 | 698 | let directory = match purpose { |
| 684 | 699 | Purpose::SaveZip | Purpose::SaveSevenZip => self.zip_folder.clone(), |
| 685 | 삭제: Purpose::Destination | Purpose::SaveGzip => self | |
| 700 | 추가: Purpose::SaveRecoveryZip | Purpose::Destination | Purpose::SaveGzip => self | |
| 686 | 701 | .model |
| 687 | 702 | .archive |
| 688 | 703 | .as_ref() |
| @@ -700,7 +715,16 @@ impl ArchiveApp { | ||
| 700 | 715 | let request = DialogRequest { |
| 701 | 716 | purpose, |
| 702 | 717 | directory, |
| 703 | 삭제: file_name: if matches!(purpose, Purpose::SaveGzip | Purpose::RetryGzip) { | |
| 718 | 추가: file_name: if purpose == Purpose::SaveRecoveryZip { | |
| 719 | 추가: let stem = self | |
| 720 | 추가: .model | |
| 721 | 추가: .archive | |
| 722 | 추가: .as_ref() | |
| 723 | 추가: .and_then(|p| p.file_stem()) | |
| 724 | 추가: .unwrap_or_default() | |
| 725 | 추가: .to_string_lossy(); | |
| 726 | 추가: format!("{stem}-recovered.zip") | |
| 727 | 추가: } else if matches!(purpose, Purpose::SaveGzip | Purpose::RetryGzip) { | |
| 704 | 728 | self.gzip_name.clone() |
| 705 | 729 | } else { |
| 706 | 730 | self.zip_name.clone() |
| @@ -734,6 +758,14 @@ impl ArchiveApp { | ||
| 734 | 758 | Ok(Some(paths)) if !paths.is_empty() => { |
| 735 | 759 | let path = paths[0].clone(); |
| 736 | 760 | match purpose { |
| 761 | 추가: Purpose::SaveRecoveryZip => { | |
| 762 | 추가: if let Some(archive) = self.model.archive.clone() { | |
| 763 | 추가: self.start(Start::RecoverZip { | |
| 764 | 추가: archive, | |
| 765 | 추가: output_file: path, | |
| 766 | 추가: }); | |
| 767 | 추가: } | |
| 768 | 추가: } | |
| 737 | 769 | Purpose::Open => { |
| 738 | 770 | if std::fs::symlink_metadata(&path) |
| 739 | 771 | .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink()) |
| @@ -812,7 +844,7 @@ impl ArchiveApp { | ||
| 812 | 844 | if let Some(request) = self.last_request.clone() { |
| 813 | 845 | match request { |
| 814 | 846 | Start::List { archive } => self.open_path(archive), |
| 815 | 삭제: Start::Preview { .. } => {} | |
| 847 | 추가: Start::Preview { .. } | Start::RecoverZip { .. } => {} | |
| 816 | 848 | Start::Extract { |
| 817 | 849 | selection, |
| 818 | 850 | gzip_output_name, |
| @@ -1066,6 +1098,9 @@ impl ArchiveApp { | ||
| 1066 | 1098 | .inner_margin(egui::Margin::ZERO), |
| 1067 | 1099 | ) |
| 1068 | 1100 | .show(root, |ui| { |
| 1101 | 추가: if let Some((_, warning)) = &self.recovery_warning { | |
| 1102 | 추가: ui.colored_label(theme::WARNING, warning); | |
| 1103 | 추가: } | |
| 1069 | 1104 | if self.model.archive.is_some() { |
| 1070 | 1105 | self.archive_list(ui); |
| 1071 | 1106 | } else { |
| @@ -1998,7 +2033,11 @@ impl ArchiveApp { | ||
| 1998 | 2033 | ) { |
| 1999 | 2034 | "저장 위치와 추가한 항목을 확인하세요" |
| 2000 | 2035 | } else { |
| 2001 | 삭제: "풀 위치와 선택한 항목을 확인하세요" | |
| 2036 | 추가: if matches!(self.last_request, Some(Start::RecoverZip { .. })) { | |
| 2037 | 추가: "원본과 다른 새 복구본 저장 위치를 선택하세요" | |
| 2038 | 추가: } else { | |
| 2039 | 추가: "풀 위치와 선택한 항목을 확인하세요" | |
| 2040 | 추가: } | |
| 2002 | 2041 | } |
| 2003 | 2042 | }, |
| 2004 | 2043 | ); |
| @@ -2006,6 +2045,20 @@ impl ArchiveApp { | ||
| 2006 | 2045 | } |
| 2007 | 2046 | |
| 2008 | 2047 | fn progress(&mut self, ui: &mut egui::Ui) { |
| 2048 | 추가: if matches!(self.last_request, Some(Start::RecoverZip { .. })) { | |
| 2049 | 추가: ui.strong("ZIP 복구 중"); | |
| 2050 | 추가: ui.label(if self.model.recovery_end.is_some() { | |
| 2051 | 추가: "분석 완료 / 복구본 저장과 작업자 종료 확인 중" | |
| 2052 | 추가: } else { | |
| 2053 | 추가: "원본을 분석하고 있습니다. 전체 항목 수는 아직 알 수 없습니다." | |
| 2054 | 추가: }); | |
| 2055 | 추가: ui.label(format!( | |
| 2056 | 추가: "확인한 항목 {}개", | |
| 2057 | 추가: self.model.recovery_entries.len() | |
| 2058 | 추가: )); | |
| 2059 | 추가: self.cancel_action(ui, false); | |
| 2060 | 추가: return; | |
| 2061 | 추가: } | |
| 2009 | 2062 | if self.model.resource.is_some() { |
| 2010 | 2063 | ui.horizontal(|ui| { |
| 2011 | 2064 | ui.label("사용자 허용을 기다리고 있습니다"); |
| @@ -2070,7 +2123,160 @@ impl ArchiveApp { | ||
| 2070 | 2123 | }); |
| 2071 | 2124 | } |
| 2072 | 2125 | |
| 2126 | 추가: fn recovery_result(&mut self, ui: &mut egui::Ui) { | |
| 2127 | 추가: let t = self.model.terminal.as_ref(); | |
| 2128 | 추가: let summary = self.model.recovery_end.as_ref(); | |
| 2129 | 추가: let confirmed = self.model.confirmed && self.model.error.is_none(); | |
| 2130 | 추가: let saved = confirmed | |
| 2131 | 추가: && t.is_some_and(|t| t.publication == Publication::Complete && t.created_count == 1) | |
| 2132 | 추가: && summary.is_some_and(|s| s.verified_entries > 0); | |
| 2133 | 추가: let partial = summary.is_some_and(|s| !s.complete()); | |
| 2134 | 추가: let title = if !confirmed { | |
| 2135 | 추가: "복구 결과를 확정할 수 없음" | |
| 2136 | 추가: } else if saved && partial { | |
| 2137 | 추가: "일부 항목만 복구함" | |
| 2138 | 추가: } else if saved && t.is_some_and(|t| t.outcome == Outcome::Completed) { | |
| 2139 | 추가: "복구본 저장 완료" | |
| 2140 | 추가: } else if t.is_some_and(|t| t.error == Some(ErrorCode::RecoveryImpossible)) { | |
| 2141 | 추가: "복구 가능한 항목 없음" | |
| 2142 | 추가: } else if t.is_some_and(|t| t.outcome == Outcome::Cancelled) { | |
| 2143 | 추가: "복구를 취소했습니다" | |
| 2144 | 추가: } else { | |
| 2145 | 추가: "복구본 저장을 완료하지 못했습니다" | |
| 2146 | 추가: }; | |
| 2147 | 추가: ui.heading(title); | |
| 2148 | 추가: ui.label( | |
| 2149 | 추가: "원본은 수정하지 않습니다. 검증 통과는 손상 전 내용과 동일하다는 보증이 아닙니다.", | |
| 2150 | 추가: ); | |
| 2151 | 추가: let output = match &self.last_request { | |
| 2152 | 추가: Some(Start::RecoverZip { output_file, .. }) => output_file.clone(), | |
| 2153 | 추가: _ => return, | |
| 2154 | 추가: }; | |
| 2155 | 추가: if saved | |
| 2156 | 추가: || self | |
| 2157 | 추가: .model | |
| 2158 | 추가: .outputs | |
| 2159 | 추가: .iter() | |
| 2160 | 추가: .any(|(_, d)| matches!(d, Disposition::Created | Disposition::CommitUncertain)) | |
| 2161 | 추가: { | |
| 2162 | 추가: theme::bounded_text(ui, &output.display().to_string(), ui.available_width()); | |
| 2163 | 추가: } | |
| 2164 | 추가: for (name, _) in self | |
| 2165 | 추가: .model | |
| 2166 | 추가: .outputs | |
| 2167 | 추가: .iter() | |
| 2168 | 추가: .filter(|(_, d)| *d == Disposition::PartialRetained) | |
| 2169 | 추가: { | |
| 2170 | 추가: let retained = output.parent().unwrap_or(Path::new("")).join(name); | |
| 2171 | 추가: theme::bounded_text( | |
| 2172 | 추가: ui, | |
| 2173 | 추가: &format!("남은 임시 파일: {}", retained.display()), | |
| 2174 | 추가: ui.available_width(), | |
| 2175 | 추가: ); | |
| 2176 | 추가: } | |
| 2177 | 추가: if let Some(error) = &self.model.error { | |
| 2178 | 추가: ui.colored_label(theme::WARNING, error); | |
| 2179 | 추가: } | |
| 2180 | 추가: if let Some(t) = t { | |
| 2181 | 추가: if let Some(code) = t.error { | |
| 2182 | 추가: ui.label(present::error_text(code)); | |
| 2183 | 추가: } | |
| 2184 | 추가: for warning in present::publication_warnings( | |
| 2185 | 추가: Some(t), | |
| 2186 | 추가: self.model.confirmed, | |
| 2187 | 추가: Some(&BTreeSet::from([output | |
| 2188 | 추가: .file_name() | |
| 2189 | 추가: .unwrap_or_default() | |
| 2190 | 추가: .to_string_lossy() | |
| 2191 | 추가: .into_owned()])), | |
| 2192 | 추가: &BTreeSet::new(), | |
| 2193 | 추가: &self.model.outputs, | |
| 2194 | 추가: ) { | |
| 2195 | 추가: ui.colored_label(theme::WARNING, warning); | |
| 2196 | 추가: } | |
| 2197 | 추가: if let Some(warning) = present::durability_warning(t.durability) { | |
| 2198 | 추가: ui.colored_label(theme::WARNING, warning); | |
| 2199 | 추가: } | |
| 2200 | 추가: } | |
| 2201 | 추가: let notice = summary.map(|s| { | |
| 2202 | 추가: format!( | |
| 2203 | 추가: "검증되어 포함됨 {}개 / 유실됨 {}개 / 무결성 미확인 {}개{}", | |
| 2204 | 추가: s.verified_entries, | |
| 2205 | 추가: s.lost_entries, | |
| 2206 | 추가: s.unverified_entries, | |
| 2207 | 추가: if s.unknown_loss { | |
| 2208 | 추가: " / 전체 목록을 알 수 없어 추가 유실 여부를 확인할 수 없습니다" | |
| 2209 | 추가: } else { | |
| 2210 | 추가: "" | |
| 2211 | 추가: } | |
| 2212 | 추가: ) | |
| 2213 | 추가: }); | |
| 2214 | 추가: if let Some(notice) = ¬ice { | |
| 2215 | 추가: ui.label(notice); | |
| 2216 | 추가: } | |
| 2217 | 추가: egui::ScrollArea::vertical() | |
| 2218 | 추가: .id_salt("recovery-findings") | |
| 2219 | 추가: .max_height(220.0) | |
| 2220 | 추가: .show_rows(ui, 24.0, self.model.recovery_entries.len(), |ui, rows| { | |
| 2221 | 추가: for entry in &self.model.recovery_entries[rows] { | |
| 2222 | 추가: let status = match entry.status { | |
| 2223 | 추가: RecoveryStatus::Verified => "검증되어 포함됨", | |
| 2224 | 추가: RecoveryStatus::Lost => "유실됨", | |
| 2225 | 추가: RecoveryStatus::Unverified => "무결성 미확인", | |
| 2226 | 추가: }; | |
| 2227 | 추가: let reason = match entry.reason { | |
| 2228 | 추가: RecoveryReason::None => "내용 검증 통과", | |
| 2229 | 추가: RecoveryReason::HeaderRebuilt => "헤더 재구성", | |
| 2230 | 추가: RecoveryReason::Truncated => "파일 절단", | |
| 2231 | 추가: RecoveryReason::CrcMismatch => "CRC 불일치", | |
| 2232 | 추가: RecoveryReason::DecodeFailure => "압축 데이터 손상", | |
| 2233 | 추가: RecoveryReason::BoundaryUnknown => "항목 경계 불명", | |
| 2234 | 추가: RecoveryReason::UnsupportedFeature => "지원하지 않는 기능", | |
| 2235 | 추가: RecoveryReason::MetadataMissing => "메타정보 누락", | |
| 2236 | 추가: }; | |
| 2237 | 추가: theme::bounded_text( | |
| 2238 | 추가: ui, | |
| 2239 | 추가: &format!( | |
| 2240 | 추가: "{status} / {reason}: {}", | |
| 2241 | 추가: entry.name.as_deref().unwrap_or("이름 확인 불가") | |
| 2242 | 추가: ), | |
| 2243 | 추가: ui.available_width(), | |
| 2244 | 추가: ); | |
| 2245 | 추가: } | |
| 2246 | 추가: }); | |
| 2247 | 추가: if saved && theme::action(ui, "복구본 열기", true, true).clicked() { | |
| 2248 | 추가: self.recovery_warning = partial.then(|| (output.clone(), notice.unwrap_or_default())); | |
| 2249 | 추가: self.open_path(output); | |
| 2250 | 추가: } | |
| 2251 | 추가: if self.model.can_retry_expanded() | |
| 2252 | 추가: && theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked() | |
| 2253 | 추가: { | |
| 2254 | 추가: self.model.retry_expanded(self.factory.as_mut()); | |
| 2255 | 추가: } | |
| 2256 | 추가: } | |
| 2257 | 추가: | |
| 2073 | 2258 | fn result(&mut self, ui: &mut egui::Ui) { |
| 2259 | 추가: if matches!(self.last_request, Some(Start::RecoverZip { .. })) { | |
| 2260 | 추가: self.recovery_result(ui); | |
| 2261 | 추가: return; | |
| 2262 | 추가: } | |
| 2263 | 추가: if self.model.confirmed | |
| 2264 | 추가: && self.model.error.is_none() | |
| 2265 | 추가: && self | |
| 2266 | 추가: .model | |
| 2267 | 추가: .terminal | |
| 2268 | 추가: .as_ref() | |
| 2269 | 추가: .is_some_and(|t| t.error == Some(ErrorCode::Integrity)) | |
| 2270 | 추가: && matches!( | |
| 2271 | 추가: self.last_request, | |
| 2272 | 추가: Some(Start::List { .. } | Start::Extract { .. }) | |
| 2273 | 추가: ) | |
| 2274 | 추가: { | |
| 2275 | 추가: ui.label("원본을 바꾸지 않고 새 ZIP 복구본을 만듭니다. 일부 항목은 복구되지 않을 수 있습니다."); | |
| 2276 | 추가: if theme::action(ui, "복구본 저장 위치 선택", true, true).clicked() { | |
| 2277 | 추가: self.open_picker(Purpose::SaveRecoveryZip); | |
| 2278 | 추가: } | |
| 2279 | 추가: } | |
| 2074 | 2280 | let t = self.model.terminal.clone(); |
| 2075 | 2281 | let listing = matches!(self.last_request, Some(Start::List { .. })); |
| 2076 | 2282 | let creating = matches!( |
| @@ -2873,6 +3079,7 @@ impl ArchiveApp { | ||
| 2873 | 3079 | ActionKind::Extract => "압축 해제", |
| 2874 | 3080 | ActionKind::CreateZip => "ZIP 만들기", |
| 2875 | 3081 | ActionKind::CreateSevenZip => "7z 만들기", |
| 3082 | 추가: ActionKind::RecoverZip => "ZIP 복구", | |
| 2876 | 3083 | ActionKind::Preview => "파일 미리보기", |
| 2877 | 3084 | }); |
| 2878 | 3085 | if question.scope.ratio { |
| @@ -69,6 +69,10 @@ pub enum Start { | ||
| 69 | 69 | entry_id: u32, |
| 70 | 70 | list_id: ListId, |
| 71 | 71 | }, |
| 72 | 추가: RecoverZip { | |
| 73 | 추가: archive: PathBuf, | |
| 74 | 추가: output_file: PathBuf, | |
| 75 | 추가: }, | |
| 72 | 76 | CreateSevenZip { |
| 73 | 77 | sources: Vec<(PathBuf, String)>, |
| 74 | 78 | output_file: PathBuf, |
| @@ -184,6 +188,8 @@ pub enum Outcome { | ||
| 184 | 188 | } |
| 185 | 189 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 186 | 190 | pub enum ErrorCode { |
| 191 | 추가: RecoveryIncomplete, | |
| 192 | 추가: RecoveryImpossible, | |
| 187 | 193 | MissingVolume, |
| 188 | 194 | Integrity, |
| 189 | 195 | UnsupportedFormat, |
| @@ -237,7 +243,8 @@ pub struct Terminal { | ||
| 237 | 243 | pub cleanup: Cleanup, |
| 238 | 244 | } |
| 239 | 245 | pub use worker_protocol::protocol::{ |
| 240 | 삭제: ActionKind, Limits, NativePath, PreviewFormat, PreviewInfo, ResourceScope, ResourceUsage, | |
| 246 | 추가: ActionKind, Limits, NativePath, PreviewFormat, PreviewInfo, RecoveryEnd, RecoveryEntry, | |
| 247 | 추가: RecoveryMode, RecoveryReason, RecoveryStatus, ResourceScope, ResourceUsage, | |
| 241 | 248 | VolumeProblemReason, |
| 242 | 249 | }; |
| 243 | 250 | |
| @@ -295,6 +302,8 @@ pub struct ResourceChallenge { | ||
| 295 | 302 | |
| 296 | 303 | #[derive(Clone, Debug)] |
| 297 | 304 | pub enum Event { |
| 305 | 추가: RecoveryEntry(RecoveryEntry), | |
| 306 | 추가: RecoveryEnd(RecoveryEnd), | |
| 298 | 307 | VolumeProblem(VolumeProblem), |
| 299 | 308 | PreviewBegin(PreviewInfo), |
| 300 | 309 | PreviewChunk { |
| @@ -370,6 +379,7 @@ impl Factory for Unavailable { | ||
| 370 | 379 | } |
| 371 | 380 | } |
| 372 | 381 | struct Running { |
| 382 | 추가: recovery_metadata: usize, | |
| 373 | 383 | volume_problem: Option<VolumeProblem>, |
| 374 | 384 | preview: Option<PreviewBuffer>, |
| 375 | 385 | preview_discarded: bool, |
| @@ -406,6 +416,8 @@ pub enum Close { | ||
| 406 | 416 | } |
| 407 | 417 | #[derive(Default)] |
| 408 | 418 | pub struct Model { |
| 419 | 추가: pub recovery_entries: Vec<RecoveryEntry>, | |
| 420 | 추가: pub recovery_end: Option<RecoveryEnd>, | |
| 409 | 421 | pub volume_problem: Option<VolumeProblem>, |
| 410 | 422 | running: Option<Running>, |
| 411 | 423 | pub preview: Option<Preview>, |
| @@ -539,7 +551,7 @@ impl Model { | ||
| 539 | 551 | .iter() |
| 540 | 552 | .try_fold(0u64, |sum, e| sum.checked_add(e.bytes?)); |
| 541 | 553 | } |
| 542 | 삭제: Start::List { .. } => {} | |
| 554 | 추가: Start::List { .. } | Start::RecoverZip { .. } => {} | |
| 543 | 555 | } |
| 544 | 556 | usage |
| 545 | 557 | } |
| @@ -604,6 +616,10 @@ impl Model { | ||
| 604 | 616 | .map(|e| e.id) |
| 605 | 617 | .collect(); |
| 606 | 618 | let validation = match &start { |
| 619 | 추가: Start::RecoverZip { | |
| 620 | 추가: archive, | |
| 621 | 추가: output_file, | |
| 622 | 추가: } => archive.is_absolute() && output_file.is_absolute() && archive != output_file, | |
| 607 | 623 | Start::List { archive } => archive.is_absolute(), |
| 608 | 624 | Start::Preview { |
| 609 | 625 | archive, |
| @@ -699,6 +715,8 @@ impl Model { | ||
| 699 | 715 | self.selected.clear(); |
| 700 | 716 | } |
| 701 | 717 | self.next_id = id; |
| 718 | 추가: self.recovery_entries.clear(); | |
| 719 | 추가: self.recovery_end = None; | |
| 702 | 720 | self.terminal = None; |
| 703 | 721 | self.volume_problem = None; |
| 704 | 722 | self.retry_start = None; |
| @@ -713,6 +731,7 @@ impl Model { | ||
| 713 | 731 | self.error = send_error; |
| 714 | 732 | self.confirmed = false; |
| 715 | 733 | self.running = Some(Running { |
| 734 | 추가: recovery_metadata: 0, | |
| 716 | 735 | volume_problem: None, |
| 717 | 736 | preview: None, |
| 718 | 737 | preview_discarded: false, |
| @@ -1036,6 +1055,59 @@ impl Model { | ||
| 1036 | 1055 | return; |
| 1037 | 1056 | } |
| 1038 | 1057 | match event { |
| 1058 | 추가: Event::RecoveryEntry(entry) => { | |
| 1059 | 추가: let budget = if run.granted.any() { | |
| 1060 | 추가: 64 * 1024 * 1024 | |
| 1061 | 추가: } else { | |
| 1062 | 추가: 8 * 1024 * 1024 | |
| 1063 | 추가: }; | |
| 1064 | 추가: let used = run.recovery_metadata; | |
| 1065 | 추가: if !matches!(run.start, Start::RecoverZip { .. }) | |
| 1066 | 추가: || self.recovery_end.is_some() | |
| 1067 | 추가: || !entry.valid() | |
| 1068 | 추가: || entry.candidate_id as usize != self.recovery_entries.len() | |
| 1069 | 추가: || entry.name.as_ref().is_some_and(|n| { | |
| 1070 | 추가: n.len() > 4096 || !valid_relative(n.trim_end_matches('/')) | |
| 1071 | 추가: }) | |
| 1072 | 추가: || self | |
| 1073 | 추가: .recovery_entries | |
| 1074 | 추가: .last() | |
| 1075 | 추가: .is_some_and(|e| e.source_offset >= entry.source_offset) | |
| 1076 | 추가: || self.recovery_entries.len() | |
| 1077 | 추가: >= if run.granted.entries { 200_000 } else { 10_000 } | |
| 1078 | 추가: || used + 128 + entry.name.as_ref().map_or(0, String::len) > budget | |
| 1079 | 추가: { | |
| 1080 | 추가: self.error = Some("복구 항목 응답이 유효하지 않습니다".into()); | |
| 1081 | 추가: } else { | |
| 1082 | 추가: run.recovery_metadata += | |
| 1083 | 추가: 128 + entry.name.as_ref().map_or(0, String::len); | |
| 1084 | 추가: self.recovery_entries.push(entry); | |
| 1085 | 추가: } | |
| 1086 | 추가: } | |
| 1087 | 추가: Event::RecoveryEnd(summary) => { | |
| 1088 | 추가: let count = |status| { | |
| 1089 | 추가: self.recovery_entries | |
| 1090 | 추가: .iter() | |
| 1091 | 추가: .filter(|e| e.status == status) | |
| 1092 | 추가: .count() as u32 | |
| 1093 | 추가: }; | |
| 1094 | 추가: if !matches!(run.start, Start::RecoverZip { .. }) | |
| 1095 | 추가: || self.recovery_end.is_some() | |
| 1096 | 추가: || !summary.valid() | |
| 1097 | 추가: || summary.source_bytes > 4 * 1024 * 1024 * 1024 | |
| 1098 | 추가: || self | |
| 1099 | 추가: .recovery_entries | |
| 1100 | 추가: .iter() | |
| 1101 | 추가: .any(|e| e.source_offset >= summary.source_bytes) | |
| 1102 | 추가: || summary.verified_entries != count(RecoveryStatus::Verified) | |
| 1103 | 추가: || summary.lost_entries != count(RecoveryStatus::Lost) | |
| 1104 | 추가: || summary.unverified_entries != count(RecoveryStatus::Unverified) | |
| 1105 | 추가: { | |
| 1106 | 추가: self.error = Some("복구 요약이 항목과 일치하지 않습니다".into()); | |
| 1107 | 추가: } else { | |
| 1108 | 추가: self.recovery_end = Some(summary); | |
| 1109 | 추가: } | |
| 1110 | 추가: } | |
| 1039 | 1111 | Event::VolumeProblem(problem) => { |
| 1040 | 1112 | if run.cancel_sequence.is_some() { |
| 1041 | 1113 | return; |
| @@ -1109,7 +1181,11 @@ impl Model { | ||
| 1109 | 1181 | } |
| 1110 | 1182 | } |
| 1111 | 1183 | Event::Accepted { encryption } => { |
| 1112 | 삭제: if matches!(run.start, Start::CreateSevenZip { .. }) && encryption { | |
| 1184 | 추가: if matches!( | |
| 1185 | 추가: run.start, | |
| 1186 | 추가: Start::CreateSevenZip { .. } | Start::RecoverZip { .. } | |
| 1187 | 추가: ) && encryption | |
| 1188 | 추가: { | |
| 1113 | 1189 | self.error = Some("7z 생성의 암호 응답이 유효하지 않습니다".into()); |
| 1114 | 1190 | } |
| 1115 | 1191 | if run.accepted { |
| @@ -1156,8 +1232,10 @@ impl Model { | ||
| 1156 | 1232 | if run.cancel_sequence.is_some() { |
| 1157 | 1233 | return; |
| 1158 | 1234 | } |
| 1159 | 삭제: if matches!(run.start, Start::CreateSevenZip { .. }) | |
| 1160 | 삭제: || self.challenge.is_some() | |
| 1235 | 추가: if matches!( | |
| 1236 | 추가: run.start, | |
| 1237 | 추가: Start::CreateSevenZip { .. } | Start::RecoverZip { .. } | |
| 1238 | 추가: ) || self.challenge.is_some() | |
| 1161 | 1239 | || self.resource.is_some() |
| 1162 | 1240 | || challenge_id <= run.last_challenge |
| 1163 | 1241 | || self.conflict.is_some() |
| @@ -1178,6 +1256,7 @@ impl Model { | ||
| 1178 | 1256 | Start::CreateZip { .. } => ActionKind::CreateZip, |
| 1179 | 1257 | Start::CreateSevenZip { .. } => ActionKind::CreateSevenZip, |
| 1180 | 1258 | Start::Preview { .. } => ActionKind::Preview, |
| 1259 | 추가: Start::RecoverZip { .. } => ActionKind::RecoverZip, | |
| 1181 | 1260 | }; |
| 1182 | 1261 | let hard = Limits { |
| 1183 | 1262 | input: u64::MAX, |
| @@ -1261,8 +1340,36 @@ impl Model { | ||
| 1261 | 1340 | Event::Output { |
| 1262 | 1341 | relative_name, |
| 1263 | 1342 | disposition, |
| 1264 | 삭제: .. | |
| 1343 | 추가: entry_id, | |
| 1265 | 1344 | } => { |
| 1345 | 추가: if let Start::RecoverZip { output_file, .. } = &run.start { | |
| 1346 | 추가: let final_output = matches!( | |
| 1347 | 추가: disposition, | |
| 1348 | 추가: Disposition::Created | Disposition::CommitUncertain | |
| 1349 | 추가: ); | |
| 1350 | 추가: let valid_output = if final_output { | |
| 1351 | 추가: output_file.file_name().and_then(|n| n.to_str()) | |
| 1352 | 추가: == Some(relative_name.as_str()) | |
| 1353 | 추가: && !self.outputs.iter().any(|(_, d)| { | |
| 1354 | 추가: matches!( | |
| 1355 | 추가: d, | |
| 1356 | 추가: Disposition::Created | Disposition::CommitUncertain | |
| 1357 | 추가: ) | |
| 1358 | 추가: }) | |
| 1359 | 추가: } else { | |
| 1360 | 추가: valid_leaf(&relative_name) | |
| 1361 | 추가: && (disposition != Disposition::PartialRetained | |
| 1362 | 추가: || output_file.file_name().and_then(|n| n.to_str()) | |
| 1363 | 추가: != Some(relative_name.as_str())) | |
| 1364 | 추가: && !self.outputs.iter().any(|(name, d)| { | |
| 1365 | 추가: name == &relative_name && *d == disposition | |
| 1366 | 추가: }) | |
| 1367 | 추가: }; | |
| 1368 | 추가: if entry_id.is_some() || self.recovery_end.is_none() || !valid_output { | |
| 1369 | 추가: self.error = Some("복구본 출력 응답이 유효하지 않습니다".into()); | |
| 1370 | 추가: return; | |
| 1371 | 추가: } | |
| 1372 | 추가: } | |
| 1266 | 1373 | if matches!(run.start, Start::Preview { .. }) { |
| 1267 | 1374 | self.error = Some("미리보기 중 파일 출력이 보고됐습니다".into()); |
| 1268 | 1375 | return; |
| @@ -1292,6 +1399,42 @@ impl Model { | ||
| 1292 | 1399 | } |
| 1293 | 1400 | } |
| 1294 | 1401 | Event::Terminal(t) => { |
| 1402 | 추가: if matches!(run.start, Start::RecoverZip { .. }) { | |
| 1403 | 추가: let business = t.outcome == Outcome::Completed | |
| 1404 | 추가: || matches!( | |
| 1405 | 추가: t.error, | |
| 1406 | 추가: Some( | |
| 1407 | 추가: ErrorCode::RecoveryIncomplete | |
| 1408 | 추가: | ErrorCode::RecoveryImpossible | |
| 1409 | 추가: ) | |
| 1410 | 추가: ); | |
| 1411 | 추가: if business | |
| 1412 | 추가: && !self.recovery_end.as_ref().is_some_and(|s| { | |
| 1413 | 추가: if s.verified_entries == 0 { | |
| 1414 | 추가: t.outcome == Outcome::Failed | |
| 1415 | 추가: && t.error == Some(ErrorCode::RecoveryImpossible) | |
| 1416 | 추가: && t.publication == Publication::None | |
| 1417 | 추가: && t.created_count == 0 | |
| 1418 | 추가: && self.outputs.is_empty() | |
| 1419 | 추가: } else { | |
| 1420 | 추가: t.publication == Publication::Complete | |
| 1421 | 추가: && t.created_count == 1 | |
| 1422 | 추가: && self.outputs.len() == 1 | |
| 1423 | 추가: && self.outputs[0].1 == Disposition::Created | |
| 1424 | 추가: && if s.complete() { | |
| 1425 | 추가: t.outcome == Outcome::Completed && t.error.is_none() | |
| 1426 | 추가: } else { | |
| 1427 | 추가: t.outcome == Outcome::Failed | |
| 1428 | 추가: && t.error | |
| 1429 | 추가: == Some(ErrorCode::RecoveryIncomplete) | |
| 1430 | 추가: } | |
| 1431 | 추가: } | |
| 1432 | 추가: }) | |
| 1433 | 추가: { | |
| 1434 | 추가: self.error = | |
| 1435 | 추가: Some("복구 결과와 저장 상태가 일치하지 않습니다".into()); | |
| 1436 | 추가: } | |
| 1437 | 추가: } | |
| 1295 | 1438 | if run.cancel_sequence.is_none() |
| 1296 | 1439 | && run.volume_problem.as_ref().is_some_and(|problem| { |
| 1297 | 1440 | t.outcome != Outcome::Failed |
| @@ -1463,6 +1606,8 @@ pub fn terminal_lines(t: &Terminal) -> Vec<String> { | ||
| 1463 | 1606 | if let Some(error) = t.error { |
| 1464 | 1607 | lines.push( |
| 1465 | 1608 | match error { |
| 1609 | 추가: ErrorCode::RecoveryIncomplete => "일부 항목만 복구했습니다", | |
| 1610 | 추가: ErrorCode::RecoveryImpossible => "복구 가능한 항목이 없습니다", | |
| 1466 | 1611 | ErrorCode::MissingVolume => "분할 압축파일의 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 첫 조각을 다시 여세요", |
| 1467 | 1612 | ErrorCode::Integrity => "압축파일이 손상됐습니다", |
| 1468 | 1613 | ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다", |
| @@ -0,0 +1,72 @@ | ||
| 1 | 추가: import json | |
| 2 | 추가: from pathlib import Path | |
| 3 | 추가: import re | |
| 4 | 추가: import unittest | |
| 5 | 추가: | |
| 6 | 추가: | |
| 7 | 추가: ROOT = Path(__file__).resolve().parents[2] | |
| 8 | 추가: | |
| 9 | 추가: | |
| 10 | 추가: def enum_tags(source, name): | |
| 11 | 추가: match = re.search(r"enumeration!\(\s*" + name + r"\s*\{([^}]+)\}", source) | |
| 12 | 추가: if match is None: | |
| 13 | 추가: raise ValueError("활성 enum을 찾지 못함: " + name) | |
| 14 | 추가: tags = {key: int(value) for key, value in re.findall(r"(\w+)\s*=\s*(\d+)", match[1])} | |
| 15 | 추가: if not tags or len(set(tags.values())) != len(tags): | |
| 16 | 추가: raise ValueError("활성 enum의 태그가 비어 있거나 충돌함") | |
| 17 | 추가: return tags | |
| 18 | 추가: | |
| 19 | 추가: | |
| 20 | 추가: def check_extension(active, proposed): | |
| 21 | 추가: occupied = {value: name for name, value in active.items()} | |
| 22 | 추가: for name, value in proposed.items(): | |
| 23 | 추가: if name in active and active[name] != value: | |
| 24 | 추가: raise ValueError("기존 태그를 바꾸는 제안임: " + name) | |
| 25 | 추가: if value in occupied and occupied[value] != name: | |
| 26 | 추가: raise ValueError("기존 태그와 충돌함: " + name) | |
| 27 | 추가: occupied[value] = name | |
| 28 | 추가: | |
| 29 | 추가: | |
| 30 | 추가: class ZipRecoveryContractTests(unittest.TestCase): | |
| 31 | 추가: @classmethod | |
| 32 | 추가: def setUpClass(cls): | |
| 33 | 추가: worker = ROOT / "experiments" / "rust-archive-worker" | |
| 34 | 추가: cls.wire = (worker / "src" / "wire.rs").read_text(encoding="utf-8") | |
| 35 | 추가: cls.contract = json.loads((worker / "contract.json").read_text(encoding="utf-8")) | |
| 36 | 추가: cls.proposal = cls.contract["zip_recovery_proposal"] | |
| 37 | 추가: | |
| 38 | 추가: def test_error_tags_are_checked_against_live_wire(self): | |
| 39 | 추가: active = enum_tags(self.wire, "ErrorCode") | |
| 40 | 추가: self.assertEqual(active["MissingVolume"], 14) | |
| 41 | 추가: check_extension(active, self.contract["error_tags"]) | |
| 42 | 추가: check_extension(active, self.proposal["proposed_tags"]["ErrorCode"]) | |
| 43 | 추가: | |
| 44 | 추가: def test_original_error_tag_collision_is_rejected(self): | |
| 45 | 추가: active = enum_tags(self.wire, "ErrorCode") | |
| 46 | 추가: with self.assertRaises(ValueError): | |
| 47 | 추가: check_extension(active, {"RecoveryIncomplete": 14, "RecoveryImpossible": 15}) | |
| 48 | 추가: | |
| 49 | 추가: def test_action_tag_does_not_alias_existing_action(self): | |
| 50 | 추가: active = enum_tags(self.wire, "ActionKind") | |
| 51 | 추가: request = self.proposal["request"] | |
| 52 | 추가: check_extension(active, {request["action"]: request["proposed_action_tag"]}) | |
| 53 | 추가: | |
| 54 | 추가: def test_event_kinds_do_not_alias_existing_messages(self): | |
| 55 | 추가: decoder = self.wire.split("let m = match kind {", 1)[1] | |
| 56 | 추가: branches = re.findall( | |
| 57 | 추가: r"^ {12}(\d+) => (.*?)(?=^ {12}(?:\d+|_) =>)", | |
| 58 | 추가: decoder, | |
| 59 | 추가: flags=re.MULTILINE | re.DOTALL, | |
| 60 | 추가: ) | |
| 61 | 추가: active = {} | |
| 62 | 추가: for tag, branch in branches: | |
| 63 | 추가: name = re.search(r"Self::(\w+)", branch) | |
| 64 | 추가: self.assertIsNotNone(name) | |
| 65 | 추가: active[name[1]] = int(tag) | |
| 66 | 추가: self.assertEqual(active["VolumeProblem"], 114) | |
| 67 | 추가: self.assertEqual(active["PreviewEnd"], 113) | |
| 68 | 추가: check_extension(active, self.proposal["proposed_tags"]["event_kinds"]) | |
| 69 | 추가: | |
| 70 | 추가: | |
| 71 | 추가: if __name__ == "__main__": | |
| 72 | 추가: unittest.main() |
| @@ -0,0 +1,20 @@ | ||
| 1 | 추가: from pathlib import Path | |
| 2 | 추가: import subprocess | |
| 3 | 추가: import sys | |
| 4 | 추가: import unittest | |
| 5 | 추가: | |
| 6 | 추가: | |
| 7 | 추가: class ZipRecoveryFixtureTests(unittest.TestCase): | |
| 8 | 추가: def test_corpus_and_recovered_output_checks(self): | |
| 9 | 추가: verifier = Path(__file__).resolve().parents[1] / "zip-recovery-fixtures" / "verify.py" | |
| 10 | 추가: result = subprocess.run( | |
| 11 | 추가: [sys.executable, "-B", str(verifier)], | |
| 12 | 추가: capture_output=True, | |
| 13 | 추가: text=True, | |
| 14 | 추가: timeout=30, | |
| 15 | 추가: ) | |
| 16 | 추가: self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | |
| 17 | 추가: | |
| 18 | 추가: | |
| 19 | 추가: if __name__ == "__main__": | |
| 20 | 추가: unittest.main() |
| @@ -11,8 +11,7 @@ static NEXT: AtomicU64 = AtomicU64::new(0); | ||
| 11 | 11 | struct Scratch(PathBuf); |
| 12 | 12 | impl Scratch { |
| 13 | 13 | fn new() -> Self { |
| 14 | 삭제: let root = | |
| 15 | 삭제: Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/rust-app-real-worker/runs"); | |
| 14 | 추가: let root = std::env::temp_dir().join("app-real-worker"); | |
| 16 | 15 | fs::create_dir_all(&root).unwrap(); |
| 17 | 16 | let path = root.join(format!( |
| 18 | 17 | "{}-{}", |
| @@ -699,3 +698,48 @@ fn cancel_racing_exit_without_terminal_remains_unconfirmed() { | ||
| 699 | 698 | mod guarded_flows; |
| 700 | 699 | |
| 701 | 700 | mod preview_catalog; |
| 701 | 추가: | |
| 702 | 추가: #[test] | |
| 703 | 추가: fn recovery_adapter_confirms_complete_partial_and_impossible_without_changing_source() { | |
| 704 | 추가: use sha2::{Digest, Sha256}; | |
| 705 | 추가: let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/zip-recovery-fixtures"); | |
| 706 | 추가: for (name, expected, count) in [ | |
| 707 | 추가: ("broken-local-header.zip", None, 1), | |
| 708 | 추가: ( | |
| 709 | 추가: "missing-directory.zip", | |
| 710 | 추가: Some(ErrorCode::RecoveryIncomplete), | |
| 711 | 추가: 1, | |
| 712 | 추가: ), | |
| 713 | 추가: ("body-corrupt.zip", Some(ErrorCode::RecoveryIncomplete), 1), | |
| 714 | 추가: ("unrecoverable.zip", Some(ErrorCode::RecoveryImpossible), 0), | |
| 715 | 추가: ] { | |
| 716 | 추가: let scratch = Scratch::new(); | |
| 717 | 추가: let source = scratch.path("source.zip"); | |
| 718 | 추가: fs::copy(fixtures.join(name), &source).unwrap(); | |
| 719 | 추가: let before = Sha256::digest(fs::read(&source).unwrap()); | |
| 720 | 추가: let output = scratch.path("recovered.zip"); | |
| 721 | 추가: let mut model = Model::default(); | |
| 722 | 추가: let (mut factory, observed) = observed_factory(); | |
| 723 | 추가: assert!(model.begin( | |
| 724 | 추가: Start::RecoverZip { | |
| 725 | 추가: archive: source.clone(), | |
| 726 | 추가: output_file: output.clone() | |
| 727 | 추가: }, | |
| 728 | 추가: &mut factory | |
| 729 | 추가: )); | |
| 730 | 추가: wait(&mut model); | |
| 731 | 추가: assert!(model.confirmed, "{name}: {:?}", model.error); | |
| 732 | 추가: let terminal = model.terminal.as_ref().unwrap(); | |
| 733 | 추가: assert_eq!(terminal.error, expected, "{name}"); | |
| 734 | 추가: assert_eq!(terminal.created_count, count); | |
| 735 | 추가: assert_eq!(output.exists(), count == 1); | |
| 736 | 추가: assert_eq!(Sha256::digest(fs::read(source).unwrap()), before); | |
| 737 | 추가: assert_reaped(&observed); | |
| 738 | 추가: if count == 1 { | |
| 739 | 추가: assert!(model.begin(Start::List { archive: output }, &mut factory)); | |
| 740 | 추가: wait(&mut model); | |
| 741 | 추가: completed(&model); | |
| 742 | 추가: assert!(model.list_id.is_some()); | |
| 743 | 추가: } | |
| 744 | 추가: } | |
| 745 | 추가: } |
| @@ -236,6 +236,9 @@ impl Connection for CaptureConnection { | ||
| 236 | 236 | durability: Durability::NotApplicable, |
| 237 | 237 | cleanup: Cleanup::Complete, |
| 238 | 238 | }), |
| 239 | 추가: Start::RecoverZip { .. } => { | |
| 240 | 추가: return Err("복구 상황은 --ui-scenario로 확인함".into()); | |
| 241 | 추가: } | |
| 239 | 242 | Start::CreateSevenZip { output_file, .. } => { |
| 240 | 243 | self.create_name = |
| 241 | 244 | Some(output_file.file_name().unwrap().to_string_lossy().into()); |
| @@ -23,7 +23,10 @@ impl Dialogs for TestDialogs { | ||
| 23 | 23 | if let Some(answer) = state.answers.pop_front() { |
| 24 | 24 | return Ok(answer); |
| 25 | 25 | } |
| 26 | 삭제: if matches!(request.purpose, Purpose::SaveZip | Purpose::SaveSevenZip) && !state.cancel_save | |
| 26 | 추가: if matches!( | |
| 27 | 추가: request.purpose, | |
| 28 | 추가: Purpose::SaveZip | Purpose::SaveSevenZip | Purpose::SaveRecoveryZip | |
| 29 | 추가: ) && !state.cancel_save | |
| 27 | 30 | { |
| 28 | 31 | let name = state.save_name.take().unwrap_or(request.file_name); |
| 29 | 32 | return Ok(Some(vec![request.directory.join(name)])); |
| @@ -503,6 +503,110 @@ mod widgets { | ||
| 503 | 503 | ); |
| 504 | 504 | } |
| 505 | 505 | |
| 506 | 추가: #[test] | |
| 507 | 추가: fn recovery_save_uses_native_dialog_and_partial_copy_keeps_warning_when_opened() { | |
| 508 | 추가: let scratch = Folder::new(); | |
| 509 | 추가: let factory = FakeFactory::manual(); | |
| 510 | 추가: let archive = scratch.0.join("손상.zip"); | |
| 511 | 추가: let output = scratch.0.join("복구본.zip"); | |
| 512 | 추가: let mut app = ArchiveApp::new(Box::new(factory.clone()), Some(archive.clone()), false); | |
| 513 | 추가: { | |
| 514 | 추가: let mut state = factory.state.borrow_mut(); | |
| 515 | 추가: state.frame(Event::Accepted { encryption: false }); | |
| 516 | 추가: state.frame(Event::Terminal(Terminal { | |
| 517 | 추가: outcome: Outcome::Failed, | |
| 518 | 추가: error: Some(ErrorCode::Integrity), | |
| 519 | 추가: publication: Publication::None, | |
| 520 | 추가: created_count: 0, | |
| 521 | 추가: retained_partial_count: 0, | |
| 522 | 추가: durability: Durability::NotApplicable, | |
| 523 | 추가: cleanup: Cleanup::Complete, | |
| 524 | 추가: })); | |
| 525 | 추가: state.queue.extend([ | |
| 526 | 추가: HostEvent::StdoutEof, | |
| 527 | 추가: HostEvent::StderrEof, | |
| 528 | 추가: HostEvent::Exited { success: true }, | |
| 529 | 추가: ]); | |
| 530 | 추가: } | |
| 531 | 추가: pump(&mut app.model); | |
| 532 | 추가: let dialogs = TestDialogs::default(); | |
| 533 | 추가: dialogs | |
| 534 | 추가: .0 | |
| 535 | 추가: .borrow_mut() | |
| 536 | 추가: .answers | |
| 537 | 추가: .push_back(Some(vec![output.clone()])); | |
| 538 | 추가: app.set_dialogs(Box::new(dialogs.clone())); | |
| 539 | 추가: let ctx = egui::Context::default(); | |
| 540 | 추가: click(&ctx, &mut app, "복구본 저장 위치 선택"); | |
| 541 | 추가: assert_eq!( | |
| 542 | 추가: dialogs.0.borrow().requests[0].purpose, | |
| 543 | 추가: Purpose::SaveRecoveryZip | |
| 544 | 추가: ); | |
| 545 | 추가: assert_eq!( | |
| 546 | 추가: dialogs.0.borrow().requests[0].file_name, | |
| 547 | 추가: "손상-recovered.zip" | |
| 548 | 추가: ); | |
| 549 | 추가: assert!( | |
| 550 | 추가: matches!(factory.state.borrow().starts.last(), Some(Start::RecoverZip { archive: actual, output_file }) if actual == &archive && output_file == &output) | |
| 551 | 추가: ); | |
| 552 | 추가: { | |
| 553 | 추가: let mut state = factory.state.borrow_mut(); | |
| 554 | 추가: state.frame(Event::Accepted { encryption: false }); | |
| 555 | 추가: state.frame(Event::RecoveryEntry(RecoveryEntry { | |
| 556 | 추가: candidate_id: 0, | |
| 557 | 추가: source_offset: 0, | |
| 558 | 추가: name: Some("내용.txt".into()), | |
| 559 | 추가: kind: Some(worker_protocol::protocol::EntryKind::File), | |
| 560 | 추가: status: RecoveryStatus::Verified, | |
| 561 | 추가: reason: RecoveryReason::MetadataMissing, | |
| 562 | 추가: declared_size: Some(0), | |
| 563 | 추가: verified_size: Some(0), | |
| 564 | 추가: sha256: Some([1; 32]), | |
| 565 | 추가: })); | |
| 566 | 추가: state.frame(Event::RecoveryEnd(RecoveryEnd { | |
| 567 | 추가: mode: RecoveryMode::LocalChain, | |
| 568 | 추가: source_bytes: 128, | |
| 569 | 추가: source_sha256: [2; 32], | |
| 570 | 추가: known_entries: None, | |
| 571 | 추가: verified_entries: 1, | |
| 572 | 추가: lost_entries: 0, | |
| 573 | 추가: unverified_entries: 0, | |
| 574 | 추가: unknown_loss: true, | |
| 575 | 추가: })); | |
| 576 | 추가: state.frame(Event::Output { | |
| 577 | 추가: entry_id: None, | |
| 578 | 추가: relative_name: "복구본.zip".into(), | |
| 579 | 추가: disposition: Disposition::Created, | |
| 580 | 추가: }); | |
| 581 | 추가: state.frame(Event::Terminal(Terminal { | |
| 582 | 추가: outcome: Outcome::Failed, | |
| 583 | 추가: error: Some(ErrorCode::RecoveryIncomplete), | |
| 584 | 추가: publication: Publication::Complete, | |
| 585 | 추가: created_count: 1, | |
| 586 | 추가: retained_partial_count: 0, | |
| 587 | 추가: durability: Durability::Synced, | |
| 588 | 추가: cleanup: Cleanup::Complete, | |
| 589 | 추가: })); | |
| 590 | 추가: state.queue.extend([ | |
| 591 | 추가: HostEvent::StdoutEof, | |
| 592 | 추가: HostEvent::StderrEof, | |
| 593 | 추가: HostEvent::Exited { success: true }, | |
| 594 | 추가: ]); | |
| 595 | 추가: } | |
| 596 | 추가: pump(&mut app.model); | |
| 597 | 추가: assert!(app.model.confirmed, "{:?}", app.model.error); | |
| 598 | 추가: click(&ctx, &mut app, "복구본 열기"); | |
| 599 | 추가: assert!( | |
| 600 | 추가: matches!(factory.state.borrow().starts.last(), Some(Start::List { archive }) if archive == &output) | |
| 601 | 추가: ); | |
| 602 | 추가: let labels = render(&ctx, &mut app, vec![]); | |
| 603 | 추가: assert!( | |
| 604 | 추가: labels | |
| 605 | 추가: .iter() | |
| 606 | 추가: .any(|(text, _)| text.contains("전체 목록을 알 수 없어")) | |
| 607 | 추가: ); | |
| 608 | 추가: } | |
| 609 | 추가: | |
| 506 | 610 | fn loaded(scratch: &Folder, factory: &FakeFactory) -> ArchiveApp { |
| 507 | 611 | let mut app = ArchiveApp::new( |
| 508 | 612 | Box::new(factory.clone()), |
| @@ -0,0 +1,244 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: use worker_protocol::protocol::EntryKind; | |
| 3 | 추가: | |
| 4 | 추가: fn begin() -> (Model, FakeFactory) { | |
| 5 | 추가: let mut model = Model::default(); | |
| 6 | 추가: let mut factory = FakeFactory::manual(); | |
| 7 | 추가: assert!(model.begin( | |
| 8 | 추가: Start::RecoverZip { | |
| 9 | 추가: archive: path("damaged.zip"), | |
| 10 | 추가: output_file: path("recovered.zip"), | |
| 11 | 추가: }, | |
| 12 | 추가: &mut factory | |
| 13 | 추가: )); | |
| 14 | 추가: factory | |
| 15 | 추가: .state | |
| 16 | 추가: .borrow_mut() | |
| 17 | 추가: .frame(Event::Accepted { encryption: false }); | |
| 18 | 추가: (model, factory) | |
| 19 | 추가: } | |
| 20 | 추가: fn entry() -> RecoveryEntry { | |
| 21 | 추가: RecoveryEntry { | |
| 22 | 추가: candidate_id: 0, | |
| 23 | 추가: source_offset: 0, | |
| 24 | 추가: name: Some("한글.txt".into()), | |
| 25 | 추가: kind: Some(EntryKind::File), | |
| 26 | 추가: status: RecoveryStatus::Verified, | |
| 27 | 추가: reason: RecoveryReason::HeaderRebuilt, | |
| 28 | 추가: declared_size: Some(4), | |
| 29 | 추가: verified_size: Some(4), | |
| 30 | 추가: sha256: Some([1; 32]), | |
| 31 | 추가: } | |
| 32 | 추가: } | |
| 33 | 추가: fn summary(partial: bool) -> RecoveryEnd { | |
| 34 | 추가: RecoveryEnd { | |
| 35 | 추가: mode: if partial { | |
| 36 | 추가: RecoveryMode::LocalChain | |
| 37 | 추가: } else { | |
| 38 | 추가: RecoveryMode::CentralDirectory | |
| 39 | 추가: }, | |
| 40 | 추가: source_bytes: 128, | |
| 41 | 추가: source_sha256: [2; 32], | |
| 42 | 추가: known_entries: (!partial).then_some(1), | |
| 43 | 추가: verified_entries: 1, | |
| 44 | 추가: lost_entries: 0, | |
| 45 | 추가: unverified_entries: 0, | |
| 46 | 추가: unknown_loss: partial, | |
| 47 | 추가: } | |
| 48 | 추가: } | |
| 49 | 추가: fn result(partial: bool) -> Terminal { | |
| 50 | 추가: Terminal { | |
| 51 | 추가: outcome: if partial { | |
| 52 | 추가: Outcome::Failed | |
| 53 | 추가: } else { | |
| 54 | 추가: Outcome::Completed | |
| 55 | 추가: }, | |
| 56 | 추가: error: partial.then_some(ErrorCode::RecoveryIncomplete), | |
| 57 | 추가: publication: Publication::Complete, | |
| 58 | 추가: created_count: 1, | |
| 59 | 추가: retained_partial_count: 0, | |
| 60 | 추가: durability: Durability::Synced, | |
| 61 | 추가: cleanup: Cleanup::Complete, | |
| 62 | 추가: } | |
| 63 | 추가: } | |
| 64 | 추가: fn reports(factory: &FakeFactory, partial: bool) { | |
| 65 | 추가: let mut s = factory.state.borrow_mut(); | |
| 66 | 추가: s.frame(Event::RecoveryEntry(entry())); | |
| 67 | 추가: s.frame(Event::RecoveryEnd(summary(partial))); | |
| 68 | 추가: s.frame(Event::Output { | |
| 69 | 추가: entry_id: None, | |
| 70 | 추가: relative_name: "recovered.zip".into(), | |
| 71 | 추가: disposition: Disposition::Created, | |
| 72 | 추가: }); | |
| 73 | 추가: s.frame(Event::Terminal(result(partial))); | |
| 74 | 추가: } | |
| 75 | 추가: fn eof(factory: &FakeFactory) { | |
| 76 | 추가: factory.state.borrow_mut().queue.extend([ | |
| 77 | 추가: HostEvent::StdoutEof, | |
| 78 | 추가: HostEvent::StderrEof, | |
| 79 | 추가: HostEvent::Exited { success: true }, | |
| 80 | 추가: ]); | |
| 81 | 추가: } | |
| 82 | 추가: #[test] | |
| 83 | 추가: fn recovery_requires_terminal_both_eofs_and_reap_even_for_saved_partial() { | |
| 84 | 추가: for partial in [false, true] { | |
| 85 | 추가: let (mut model, factory) = begin(); | |
| 86 | 추가: reports(&factory, partial); | |
| 87 | 추가: for _ in 0..20 { | |
| 88 | 추가: model.poll(); | |
| 89 | 추가: } | |
| 90 | 추가: assert!(model.busy()); | |
| 91 | 추가: assert!(!model.confirmed); | |
| 92 | 추가: eof(&factory); | |
| 93 | 추가: pump(&mut model); | |
| 94 | 추가: assert!(model.confirmed, "{:?}", model.error); | |
| 95 | 추가: assert_eq!(model.recovery_end.as_ref().unwrap().unknown_loss, partial); | |
| 96 | 추가: assert!(model.entries.is_empty()); | |
| 97 | 추가: assert!(model.list_id.is_none()); | |
| 98 | 추가: assert!(!model.can_retry_expanded()); | |
| 99 | 추가: } | |
| 100 | 추가: } | |
| 101 | 추가: #[test] | |
| 102 | 추가: fn recovery_rejects_wrong_ids_offsets_names_and_unverified_hashes() { | |
| 103 | 추가: for change in 0..5 { | |
| 104 | 추가: let (mut model, factory) = begin(); | |
| 105 | 추가: let mut e = entry(); | |
| 106 | 추가: match change { | |
| 107 | 추가: 0 => e.candidate_id = 1, | |
| 108 | 추가: 1 => e.name = Some("../outside".into()), | |
| 109 | 추가: 2 => e.status = RecoveryStatus::Lost, | |
| 110 | 추가: 3 => e.verified_size = Some(5), | |
| 111 | 추가: _ => e.name = Some("x".repeat(4097)), | |
| 112 | 추가: } | |
| 113 | 추가: factory.state.borrow_mut().frame(Event::RecoveryEntry(e)); | |
| 114 | 추가: for _ in 0..5 { | |
| 115 | 추가: model.poll(); | |
| 116 | 추가: } | |
| 117 | 추가: assert!(model.error.is_some(), "{change}"); | |
| 118 | 추가: assert!(model.recovery_entries.is_empty()); | |
| 119 | 추가: } | |
| 120 | 추가: } | |
| 121 | 추가: #[test] | |
| 122 | 추가: fn recovery_rejects_duplicate_end_wrong_counts_and_false_success() { | |
| 123 | 추가: for change in 0..4 { | |
| 124 | 추가: let (mut model, factory) = begin(); | |
| 125 | 추가: let mut s = factory.state.borrow_mut(); | |
| 126 | 추가: s.frame(Event::RecoveryEntry(entry())); | |
| 127 | 추가: let mut end = summary(change == 3); | |
| 128 | 추가: if change == 0 { | |
| 129 | 추가: end.verified_entries = 2; | |
| 130 | 추가: } | |
| 131 | 추가: if change == 1 { | |
| 132 | 추가: end.source_bytes = 0; | |
| 133 | 추가: } | |
| 134 | 추가: s.frame(Event::RecoveryEnd(end)); | |
| 135 | 추가: if change == 2 { | |
| 136 | 추가: s.frame(Event::RecoveryEnd(summary(false))); | |
| 137 | 추가: } | |
| 138 | 추가: s.frame(Event::Output { | |
| 139 | 추가: entry_id: None, | |
| 140 | 추가: relative_name: "recovered.zip".into(), | |
| 141 | 추가: disposition: Disposition::Created, | |
| 142 | 추가: }); | |
| 143 | 추가: s.frame(Event::Terminal(result(false))); | |
| 144 | 추가: drop(s); | |
| 145 | 추가: eof(&factory); | |
| 146 | 추가: pump(&mut model); | |
| 147 | 추가: assert!(!model.confirmed, "{change}"); | |
| 148 | 추가: assert!(model.error.is_some()); | |
| 149 | 추가: } | |
| 150 | 추가: } | |
| 151 | 추가: #[test] | |
| 152 | 추가: fn recovery_summary_is_not_a_saved_artifact() { | |
| 153 | 추가: let (mut model, factory) = begin(); | |
| 154 | 추가: let mut s = factory.state.borrow_mut(); | |
| 155 | 추가: s.frame(Event::RecoveryEntry(entry())); | |
| 156 | 추가: s.frame(Event::RecoveryEnd(summary(false))); | |
| 157 | 추가: s.frame(Event::Terminal(result(false))); | |
| 158 | 추가: drop(s); | |
| 159 | 추가: eof(&factory); | |
| 160 | 추가: pump(&mut model); | |
| 161 | 추가: assert!(!model.confirmed); | |
| 162 | 추가: assert!(model.outputs.is_empty()); | |
| 163 | 추가: } | |
| 164 | 추가: | |
| 165 | 추가: #[test] | |
| 166 | 추가: fn recovery_retains_temporary_paths_with_and_without_a_publication_report() { | |
| 167 | 추가: for final_disposition in [ | |
| 168 | 추가: None, | |
| 169 | 추가: Some(Disposition::Created), | |
| 170 | 추가: Some(Disposition::CommitUncertain), | |
| 171 | 추가: ] { | |
| 172 | 추가: let (mut model, factory) = begin(); | |
| 173 | 추가: let mut state = factory.state.borrow_mut(); | |
| 174 | 추가: state.frame(Event::RecoveryEntry(entry())); | |
| 175 | 추가: state.frame(Event::RecoveryEnd(summary(false))); | |
| 176 | 추가: if let Some(disposition) = final_disposition { | |
| 177 | 추가: state.frame(Event::Output { | |
| 178 | 추가: entry_id: None, | |
| 179 | 추가: relative_name: "recovered.zip".into(), | |
| 180 | 추가: disposition, | |
| 181 | 추가: }); | |
| 182 | 추가: } | |
| 183 | 추가: state.frame(Event::Output { | |
| 184 | 추가: entry_id: None, | |
| 185 | 추가: relative_name: ".zipelo-42-1.tmp".into(), | |
| 186 | 추가: disposition: Disposition::PartialRetained, | |
| 187 | 추가: }); | |
| 188 | 추가: state.frame(Event::Terminal(Terminal { | |
| 189 | 추가: outcome: Outcome::Failed, | |
| 190 | 추가: error: Some(ErrorCode::Io), | |
| 191 | 추가: publication: match final_disposition { | |
| 192 | 추가: None => Publication::None, | |
| 193 | 추가: Some(Disposition::Created) => Publication::Partial, | |
| 194 | 추가: _ => Publication::Uncertain, | |
| 195 | 추가: }, | |
| 196 | 추가: created_count: u64::from(final_disposition == Some(Disposition::Created)), | |
| 197 | 추가: retained_partial_count: 1, | |
| 198 | 추가: durability: Durability::Unconfirmed, | |
| 199 | 추가: cleanup: Cleanup::Failed, | |
| 200 | 추가: })); | |
| 201 | 추가: drop(state); | |
| 202 | 추가: eof(&factory); | |
| 203 | 추가: pump(&mut model); | |
| 204 | 추가: assert!(model.confirmed, "{:?}", model.error); | |
| 205 | 추가: assert!( | |
| 206 | 추가: model | |
| 207 | 추가: .outputs | |
| 208 | 추가: .contains(&(".zipelo-42-1.tmp".into(), Disposition::PartialRetained)) | |
| 209 | 추가: ); | |
| 210 | 추가: assert!(!model.can_retry_expanded()); | |
| 211 | 추가: } | |
| 212 | 추가: } | |
| 213 | 추가: | |
| 214 | 추가: #[test] | |
| 215 | 추가: fn recovery_output_validation_still_rejects_wrong_fields_and_duplicates() { | |
| 216 | 추가: for case in 0..6 { | |
| 217 | 추가: let (mut model, factory) = begin(); | |
| 218 | 추가: let mut state = factory.state.borrow_mut(); | |
| 219 | 추가: state.frame(Event::RecoveryEntry(entry())); | |
| 220 | 추가: state.frame(Event::RecoveryEnd(summary(false))); | |
| 221 | 추가: let (entry_id, name, disposition) = match case { | |
| 222 | 추가: 0 => (Some(0), ".zipelo-42-1.tmp", Disposition::PartialRetained), | |
| 223 | 추가: 1 => (None, "../outside.tmp", Disposition::PartialRetained), | |
| 224 | 추가: 2 => (None, "other.zip", Disposition::Created), | |
| 225 | 추가: 3 => (None, "recovered.zip", Disposition::PartialRetained), | |
| 226 | 추가: 4 => (None, "recovered.zip", Disposition::Created), | |
| 227 | 추가: _ => (None, ".zipelo-42-1.tmp", Disposition::PartialRetained), | |
| 228 | 추가: }; | |
| 229 | 추가: let report = Event::Output { | |
| 230 | 추가: entry_id, | |
| 231 | 추가: relative_name: name.into(), | |
| 232 | 추가: disposition, | |
| 233 | 추가: }; | |
| 234 | 추가: state.frame(report.clone()); | |
| 235 | 추가: if case >= 4 { | |
| 236 | 추가: state.frame(report); | |
| 237 | 추가: } | |
| 238 | 추가: drop(state); | |
| 239 | 추가: for _ in 0..20 { | |
| 240 | 추가: model.poll(); | |
| 241 | 추가: } | |
| 242 | 추가: assert!(model.error.is_some(), "{case}"); | |
| 243 | 추가: } | |
| 244 | 추가: } |
| @@ -5,6 +5,7 @@ mod fake; | ||
| 5 | 5 | #[cfg(feature = "ui")] |
| 6 | 6 | mod native_dialogs; |
| 7 | 7 | mod preview; |
| 8 | 추가: mod recovery; | |
| 8 | 9 | mod split_volumes; |
| 9 | 10 | use fake::*; |
| 10 | 11 | use std::path::PathBuf; |
| @@ -95,6 +95,35 @@ fn every_listed_scenario_draws_and_keeps_its_expected_screen() { | ||
| 95 | 95 | app.model.error |
| 96 | 96 | ); |
| 97 | 97 | assert!(app.model.input_error.is_none(), "{}", scenario.name); |
| 98 | 추가: if scenario.name.starts_with("recovery-") { | |
| 99 | 추가: let expected = match scenario.name { | |
| 100 | 추가: "recovery-complete" => "복구본 저장 완료", | |
| 101 | 추가: "recovery-partial" => "일부 항목만 복구함", | |
| 102 | 추가: "recovery-unknown" => "전체 목록을 알 수 없어", | |
| 103 | 추가: "recovery-impossible" => "복구 가능한 항목 없음", | |
| 104 | 추가: "recovery-save-error" | "recovery-retained" => { | |
| 105 | 추가: "복구본 저장을 완료하지 못했습니다" | |
| 106 | 추가: } | |
| 107 | 추가: "recovery-cancelled" => "복구를 취소했습니다", | |
| 108 | 추가: "recovery-resource" => "이 작업 허용", | |
| 109 | 추가: _ => "ZIP 복구 중", | |
| 110 | 추가: }; | |
| 111 | 추가: assert!(labels.contains(expected), "{}: {labels}", scenario.name); | |
| 112 | 추가: assert_eq!( | |
| 113 | 추가: labels.contains("복구본 열기"), | |
| 114 | 추가: matches!( | |
| 115 | 추가: scenario.name, | |
| 116 | 추가: "recovery-complete" | "recovery-partial" | "recovery-unknown" | |
| 117 | 추가: ) | |
| 118 | 추가: ); | |
| 119 | 추가: assert!(!labels.contains("100%")); | |
| 120 | 추가: if scenario.name == "recovery-retained" { | |
| 121 | 추가: assert!(labels.contains("남은 임시 파일:"), "{labels}"); | |
| 122 | 추가: assert!(labels.contains(".zipelo-42-1.tmp"), "{labels}"); | |
| 123 | 추가: assert!(app.model.confirmed); | |
| 124 | 추가: assert!(!app.model.can_retry_expanded()); | |
| 125 | 추가: } | |
| 126 | 추가: } | |
| 98 | 127 | if scenario.name == "split-archive" { |
| 99 | 128 | assert!(app.model.list_id.as_ref().unwrap().is_split()); |
| 100 | 129 | assert!(!app.model.can_preview()); |
| @@ -21,6 +21,16 @@ macro_rules! catalog { | ||
| 21 | 21 | } |
| 22 | 22 | |
| 23 | 23 | catalog! { |
| 24 | 추가: "recovery-progress" => "ZIP 복구 분석과 저장 확인 전 대기", | |
| 25 | 추가: "recovery-complete" => "전체 항목을 검증한 복구본 저장 완료", | |
| 26 | 추가: "recovery-partial" => "유실 항목이 있는 복구본과 경고", | |
| 27 | 추가: "recovery-unknown" => "전체 목록 불명의 추가 유실 경고", | |
| 28 | 추가: "recovery-impossible" => "복구 가능한 항목 없음과 출력 없음", | |
| 29 | 추가: "recovery-cancelled" => "복구 취소와 출력 없음", | |
| 30 | 추가: "recovery-retained" => "복구 저장 실패 뒤 남은 임시 파일 경로와 정리 경고", | |
| 31 | 추가: "recovery-save-error" => "복구 분석 뒤 저장 실패", | |
| 32 | 추가: "recovery-resource" => "복구 작업의 자원 승인", | |
| 33 | 추가: | |
| 24 | 34 | "create-sevenzip" => "7z 형식 선택과 LZMA2 및 암호 미지원 안내", |
| 25 | 35 | "create-sevenzip-progress" => "7z 만들기 진행과 취소", |
| 26 | 36 | "create-sevenzip-complete" => "7z 만들기 완료", |
| @@ -538,6 +548,147 @@ impl Scenario { | ||
| 538 | 548 | } |
| 539 | 549 | _ => {} |
| 540 | 550 | } |
| 551 | 추가: if self.name.starts_with("recovery-") { | |
| 552 | 추가: let request = Start::RecoverZip { | |
| 553 | 추가: archive, | |
| 554 | 추가: output_file: base.join("복구본.zip"), | |
| 555 | 추가: }; | |
| 556 | 추가: app.last_request = Some(request.clone()); | |
| 557 | 추가: app.model.begin(request, app.factory.as_mut()); | |
| 558 | 추가: let mut state = state.borrow_mut(); | |
| 559 | 추가: state.frame(Event::Accepted { encryption: false }); | |
| 560 | 추가: if self.name == "recovery-resource" { | |
| 561 | 추가: state.frame(Event::ResourceRequired(ResourceChallenge { | |
| 562 | 추가: id: 1, | |
| 563 | 추가: action: ActionKind::RecoverZip, | |
| 564 | 추가: scope: ResourceScope { | |
| 565 | 추가: ratio: true, | |
| 566 | 추가: ..Default::default() | |
| 567 | 추가: }, | |
| 568 | 추가: usage: ResourceUsage::default(), | |
| 569 | 추가: soft_limits: Limits::default(), | |
| 570 | 추가: ceiling: Limits::default(), | |
| 571 | 추가: })); | |
| 572 | 추가: } else if self.name == "recovery-progress" { | |
| 573 | 추가: state.frame(Event::Progress { | |
| 574 | 추가: stage: Stage::Scan, | |
| 575 | 추가: processed: 1024, | |
| 576 | 추가: total: None, | |
| 577 | 추가: completed_entries: 1, | |
| 578 | 추가: }); | |
| 579 | 추가: } else if self.name == "recovery-cancelled" { | |
| 580 | 추가: state.finish(Outcome::Cancelled, Publication::None); | |
| 581 | 추가: } else { | |
| 582 | 추가: let impossible = self.name == "recovery-impossible"; | |
| 583 | 추가: let partial = self.name == "recovery-partial"; | |
| 584 | 추가: let unknown = self.name == "recovery-unknown"; | |
| 585 | 추가: let retained = self.name == "recovery-retained"; | |
| 586 | 추가: let failed = self.name == "recovery-save-error" || retained; | |
| 587 | 추가: state.frame(Event::RecoveryEntry(RecoveryEntry { | |
| 588 | 추가: candidate_id: 0, | |
| 589 | 추가: source_offset: 0, | |
| 590 | 추가: name: Some("읽어주세요.txt".into()), | |
| 591 | 추가: kind: Some(worker_protocol::protocol::EntryKind::File), | |
| 592 | 추가: status: if impossible { | |
| 593 | 추가: RecoveryStatus::Lost | |
| 594 | 추가: } else { | |
| 595 | 추가: RecoveryStatus::Verified | |
| 596 | 추가: }, | |
| 597 | 추가: reason: if impossible { | |
| 598 | 추가: RecoveryReason::Truncated | |
| 599 | 추가: } else { | |
| 600 | 추가: RecoveryReason::HeaderRebuilt | |
| 601 | 추가: }, | |
| 602 | 추가: declared_size: Some(4), | |
| 603 | 추가: verified_size: (!impossible).then_some(4), | |
| 604 | 추가: sha256: (!impossible).then_some([1; 32]), | |
| 605 | 추가: })); | |
| 606 | 추가: if partial { | |
| 607 | 추가: state.frame(Event::RecoveryEntry(RecoveryEntry { | |
| 608 | 추가: candidate_id: 1, | |
| 609 | 추가: source_offset: 128, | |
| 610 | 추가: name: Some("사진.png".into()), | |
| 611 | 추가: kind: Some(worker_protocol::protocol::EntryKind::File), | |
| 612 | 추가: status: RecoveryStatus::Lost, | |
| 613 | 추가: reason: RecoveryReason::CrcMismatch, | |
| 614 | 추가: declared_size: Some(10), | |
| 615 | 추가: verified_size: None, | |
| 616 | 추가: sha256: None, | |
| 617 | 추가: })); | |
| 618 | 추가: } | |
| 619 | 추가: state.frame(Event::RecoveryEnd(RecoveryEnd { | |
| 620 | 추가: mode: if unknown { | |
| 621 | 추가: RecoveryMode::LocalChain | |
| 622 | 추가: } else { | |
| 623 | 추가: RecoveryMode::CentralDirectory | |
| 624 | 추가: }, | |
| 625 | 추가: source_bytes: 256, | |
| 626 | 추가: source_sha256: [2; 32], | |
| 627 | 추가: known_entries: (!unknown).then_some(if partial { 2 } else { 1 }), | |
| 628 | 추가: verified_entries: u32::from(!impossible), | |
| 629 | 추가: lost_entries: u32::from(impossible || partial), | |
| 630 | 추가: unverified_entries: 0, | |
| 631 | 추가: unknown_loss: unknown, | |
| 632 | 추가: })); | |
| 633 | 추가: if !impossible && !failed { | |
| 634 | 추가: state.frame(Event::Output { | |
| 635 | 추가: entry_id: None, | |
| 636 | 추가: relative_name: "복구본.zip".into(), | |
| 637 | 추가: disposition: Disposition::Created, | |
| 638 | 추가: }); | |
| 639 | 추가: } | |
| 640 | 추가: if retained { | |
| 641 | 추가: state.frame(Event::Output { | |
| 642 | 추가: entry_id: None, | |
| 643 | 추가: relative_name: ".zipelo-42-1.tmp".into(), | |
| 644 | 추가: disposition: Disposition::PartialRetained, | |
| 645 | 추가: }); | |
| 646 | 추가: } | |
| 647 | 추가: state.frame(Event::Terminal(Terminal { | |
| 648 | 추가: outcome: if partial || unknown || impossible || failed { | |
| 649 | 추가: Outcome::Failed | |
| 650 | 추가: } else { | |
| 651 | 추가: Outcome::Completed | |
| 652 | 추가: }, | |
| 653 | 추가: error: if failed { | |
| 654 | 추가: Some(ErrorCode::DiskFull) | |
| 655 | 추가: } else if impossible { | |
| 656 | 추가: Some(ErrorCode::RecoveryImpossible) | |
| 657 | 추가: } else if partial || unknown { | |
| 658 | 추가: Some(ErrorCode::RecoveryIncomplete) | |
| 659 | 추가: } else { | |
| 660 | 추가: None | |
| 661 | 추가: }, | |
| 662 | 추가: publication: if impossible || failed { | |
| 663 | 추가: Publication::None | |
| 664 | 추가: } else { | |
| 665 | 추가: Publication::Complete | |
| 666 | 추가: }, | |
| 667 | 추가: created_count: u64::from(!impossible && !failed), | |
| 668 | 추가: retained_partial_count: u64::from(retained), | |
| 669 | 추가: durability: if impossible || failed { | |
| 670 | 추가: Durability::NotApplicable | |
| 671 | 추가: } else { | |
| 672 | 추가: Durability::Synced | |
| 673 | 추가: }, | |
| 674 | 추가: cleanup: if retained { | |
| 675 | 추가: Cleanup::Failed | |
| 676 | 추가: } else { | |
| 677 | 추가: Cleanup::Complete | |
| 678 | 추가: }, | |
| 679 | 추가: })); | |
| 680 | 추가: state.queue.extend([ | |
| 681 | 추가: HostEvent::StdoutEof, | |
| 682 | 추가: HostEvent::StderrEof, | |
| 683 | 추가: HostEvent::Exited { success: true }, | |
| 684 | 추가: ]); | |
| 685 | 추가: } | |
| 686 | 추가: drop(state); | |
| 687 | 추가: for _ in 0..30 { | |
| 688 | 추가: app.model.poll(); | |
| 689 | 추가: } | |
| 690 | 추가: return app; | |
| 691 | 추가: } | |
| 541 | 692 | let seven_zip = self.name.starts_with("create-sevenzip"); |
| 542 | 693 | let creating = self.name.starts_with("create-") || self.name == "password-create"; |
| 543 | 694 | let listing_error = matches!(self.name, "unsupported" | "damaged"); |
| @@ -542,7 +542,10 @@ fn links_and_special_entries_are_not_interactive() { | ||
| 542 | 542 | 0 => symlink(s.0.join("outside"), s.0.join("output/a")).unwrap(), |
| 543 | 543 | 1 => symlink(s.0.join("missing"), s.0.join("output/a")).unwrap(), |
| 544 | 544 | _ => { |
| 545 | 삭제: listener = UnixListener::bind(s.0.join("output/a")).unwrap(); | |
| 545 | 추가: use std::os::fd::AsRawFd; | |
| 546 | 추가: let directory = fs::File::open(s.0.join("output")).unwrap(); | |
| 547 | 추가: listener = UnixListener::bind(format!("/proc/self/fd/{}/a", directory.as_raw_fd())) | |
| 548 | 추가: .unwrap(); | |
| 546 | 549 | let _ = &listener; |
| 547 | 550 | } |
| 548 | 551 | } |
| @@ -1601,7 +1601,7 @@ fn disk_full_error_tag_preserves_previous_tags_and_rejects_unknown() { | ||
| 1601 | 1601 | assert_eq!(bytes[33], tag as u8); |
| 1602 | 1602 | let decoded = Reader::new(bytes.as_slice()).read().unwrap().unwrap().2; |
| 1603 | 1603 | assert_eq!(terminal(&[decoded]).error, error); |
| 1604 | 삭제: bytes[33] = 15; | |
| 1604 | 추가: bytes[33] = 17; | |
| 1605 | 1605 | assert!(Reader::new(bytes.as_slice()).read().is_err()); |
| 1606 | 1606 | } |
| 1607 | 1607 | } |
| @@ -1629,3 +1629,5 @@ mod split_runtime; | ||
| 1629 | 1629 | mod seven_zip_create; |
| 1630 | 1630 | |
| 1631 | 1631 | mod seven_zip_create_runtime; |
| 1632 | 추가: | |
| 1633 | 추가: mod recovery; |
| @@ -0,0 +1,127 @@ | ||
| 1 | 추가: import hashlib | |
| 2 | 추가: import io | |
| 3 | 추가: import json | |
| 4 | 추가: from pathlib import Path | |
| 5 | 추가: import struct | |
| 6 | 추가: import sys | |
| 7 | 추가: import zipfile | |
| 8 | 추가: | |
| 9 | 추가: | |
| 10 | 추가: class StreamingBuffer(io.BytesIO): | |
| 11 | 추가: def seekable(self): | |
| 12 | 추가: return False | |
| 13 | 추가: | |
| 14 | 추가: def seek(self, *args): | |
| 15 | 추가: raise io.UnsupportedOperation("seek") | |
| 16 | 추가: | |
| 17 | 추가: | |
| 18 | 추가: def create(folder, variant): | |
| 19 | 추가: descriptor = bool(variant & 1) | |
| 20 | 추가: damaged_payload_header = bool(variant & 2) | |
| 21 | 추가: forged_empty_member = bool(variant & 32) | |
| 22 | 추가: first_data = b"" if forged_empty_member else b"first content" | |
| 23 | 추가: nested_comment = bool(variant & 4) or forged_empty_member | |
| 24 | 추가: padding = 13 if variant & 8 else 0 | |
| 25 | 추가: | |
| 26 | 추가: def archive(payload): | |
| 27 | 추가: buffer = StreamingBuffer() if descriptor else io.BytesIO() | |
| 28 | 추가: with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as writer: | |
| 29 | 추가: members = [("first.txt", first_data), ("second.bin", payload)] | |
| 30 | 추가: for name, data in members: | |
| 31 | 추가: info = zipfile.ZipInfo(name, (2024, 1, 1, 0, 0, 0)) | |
| 32 | 추가: if name == "second.bin" and variant & 2048: | |
| 33 | 추가: info.compress_type = zipfile.ZIP_DEFLATED | |
| 34 | 추가: writer.writestr(info, data, compresslevel=0) | |
| 35 | 추가: return bytearray(buffer.getvalue()) | |
| 36 | 추가: | |
| 37 | 추가: original = archive(b"") | |
| 38 | 추가: real_end = len(original) - 22 | |
| 39 | 추가: directory = struct.unpack_from("<I", original, real_end + 16)[0] | |
| 40 | 추가: first_len = 46 + sum(struct.unpack_from("<HHH", original, directory + 28)) | |
| 41 | 추가: payload_size = padding + first_len + 22 | |
| 42 | 추가: original = archive(bytes(payload_size)) | |
| 43 | 추가: real_end = len(original) - 22 | |
| 44 | 추가: directory = struct.unpack_from("<I", original, real_end + 16)[0] | |
| 45 | 추가: local = struct.unpack_from("<I", original, directory + first_len + 42)[0] | |
| 46 | 추가: name_len, extra_len = struct.unpack_from("<HH", original, local + 26) | |
| 47 | 추가: data_at = local + 30 + name_len + extra_len | |
| 48 | 추가: if variant & 2048: | |
| 49 | 추가: prefix = b"\x01" + struct.pack("<HH", payload_size, payload_size ^ 0xFFFF) | |
| 50 | 추가: assert original[data_at : data_at + 5] == prefix | |
| 51 | 추가: data_at += 5 | |
| 52 | 추가: fake_cd = original[directory : directory + first_len] | |
| 53 | 추가: fake_end = bytearray(original[real_end : real_end + 22]) | |
| 54 | 추가: comment_cd_bytes = fake_cd | |
| 55 | 추가: if forged_empty_member: | |
| 56 | 추가: comment_cd_bytes = bytearray(46) | |
| 57 | 추가: comment_cd_bytes[:4] = b"PK\x01\x02" | |
| 58 | 추가: local_flags = struct.unpack_from("<H", original, directory + 6)[0] | |
| 59 | 추가: struct.pack_into("<H", comment_cd_bytes, 8, local_flags) | |
| 60 | 추가: struct.pack_into("<I", comment_cd_bytes, 42, directory) | |
| 61 | 추가: comment_size = len(comment_cd_bytes) + 22 if nested_comment else 0 | |
| 62 | 추가: struct.pack_into( | |
| 63 | 추가: "<HHIIH", | |
| 64 | 추가: fake_end, | |
| 65 | 추가: 8, | |
| 66 | 추가: 1, | |
| 67 | 추가: 1, | |
| 68 | 추가: first_len, | |
| 69 | 추가: data_at + padding, | |
| 70 | 추가: len(original) + comment_size - data_at - payload_size, | |
| 71 | 추가: ) | |
| 72 | 추가: if variant & 1024: | |
| 73 | 추가: first_data_at = 30 + len("first.txt") | |
| 74 | 추가: fake_packed = data_at + padding - first_data_at | |
| 75 | 추가: struct.pack_into("<II", fake_cd, 20, fake_packed, fake_packed) | |
| 76 | 추가: payload = bytes(padding) + fake_cd + fake_end | |
| 77 | 추가: original = archive(payload) | |
| 78 | 추가: if nested_comment: | |
| 79 | 추가: comment_cd = len(original) | |
| 80 | 추가: comment_end = bytearray(original[-22:]) | |
| 81 | 추가: struct.pack_into( | |
| 82 | 추가: "<HHIIH", comment_end, 8, 1, 1, len(comment_cd_bytes), comment_cd, 0 | |
| 83 | 추가: ) | |
| 84 | 추가: struct.pack_into("<H", original, real_end + 20, comment_size) | |
| 85 | 추가: original.extend(comment_cd_bytes + comment_end) | |
| 86 | 추가: damaged = local if damaged_payload_header else 0 | |
| 87 | 추가: original[damaged : damaged + 4] = b"BAD!" | |
| 88 | 추가: if variant & 16: | |
| 89 | 추가: struct.pack_into("<I", original, local + 14, 0x12345678) | |
| 90 | 추가: size_mode = (variant >> 6) & 7 | |
| 91 | 추가: if size_mode == 1: | |
| 92 | 추가: struct.pack_into("<I", original, local + 18, 0) | |
| 93 | 추가: elif size_mode == 2: | |
| 94 | 추가: struct.pack_into("<I", original, local + 22, 0) | |
| 95 | 추가: elif size_mode == 3: | |
| 96 | 추가: struct.pack_into("<II", original, local + 18, 0, 0) | |
| 97 | 추가: elif size_mode == 4: | |
| 98 | 추가: struct.pack_into("<II", original, local + 18, 1, 1) | |
| 99 | 추가: elif size_mode == 5: | |
| 100 | 추가: struct.pack_into("<II", original, local + 18, 0x00FFFFFF, 0x00FFFFFF) | |
| 101 | 추가: if variant & 512: | |
| 102 | 추가: struct.pack_into("<I", original, local + 14, 0) | |
| 103 | 추가: (folder / "damaged.zip").write_bytes(original) | |
| 104 | 추가: expected = { | |
| 105 | 추가: "first.txt": hashlib.sha256(first_data).hexdigest(), | |
| 106 | 추가: "second.bin": hashlib.sha256(payload).hexdigest(), | |
| 107 | 추가: } | |
| 108 | 추가: (folder / "expected.json").write_text(json.dumps(expected), encoding="utf-8") | |
| 109 | 추가: | |
| 110 | 추가: | |
| 111 | 추가: def verify(folder): | |
| 112 | 추가: expected = json.loads((folder / "expected.json").read_text(encoding="utf-8")) | |
| 113 | 추가: with zipfile.ZipFile(folder / "recovered.zip") as archive: | |
| 114 | 추가: assert len(archive.infolist()) == len(expected) | |
| 115 | 추가: assert set(archive.namelist()) == set(expected) | |
| 116 | 추가: assert archive.testzip() is None | |
| 117 | 추가: for name, digest in expected.items(): | |
| 118 | 추가: assert hashlib.sha256(archive.read(name)).hexdigest() == digest, name | |
| 119 | 추가: | |
| 120 | 추가: | |
| 121 | 추가: if __name__ == "__main__": | |
| 122 | 추가: if sys.argv[1] == "create": | |
| 123 | 추가: create(Path(sys.argv[2]), int(sys.argv[3])) | |
| 124 | 추가: elif sys.argv[1] == "verify": | |
| 125 | 추가: verify(Path(sys.argv[2])) | |
| 126 | 추가: else: | |
| 127 | 추가: raise ValueError("unknown mode") |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기