충돌 작업자를 연동하고 실제 파일 흐름을 검증함
- 작성자
- 호시노 히나타
- 작성 시각
- 커밋
7b7e617779a2dce391121b5b6b56da4af51b6337
변경된 파일 15개
+1,340-68| @@ -96,10 +96,11 @@ python3 tests/ci/run_rust.py local | ||
| 96 | 96 | |
| 97 | 97 | ## 파일 충돌 선택과 결과 |
| 98 | 98 | |
| 99 | 추가: - gzip-conflict-choice: 단일 GZ 파일의 충돌 선택 창. 저장 창에서 고른 이름과 세 선택을 확인한다. | |
| 99 | 100 | - conflict-choice: 파일 경로와 기존 크기, 새 크기 및 덮어쓰기, 건너뛰기, 이름 바꿔 저장을 확인합니다. Tab으로 이동하고 Space로 선택할 수 있으며 Escape 또는 작업 취소는 전체 작업을 취소합니다. |
| 100 | 101 | - conflict-apply: "나머지 파일에도 같게 적용"이 켜진 상태입니다. 현재 작업의 남은 일반 파일 충돌에만 적용하며 이름 바꿔 저장은 같은 폴더에 번호를 붙입니다. |
| 101 | 102 | - extract-skipped: 모든 파일을 건너뛴 정상 완료입니다. 생성된 파일이 없으며 저장 실패 경고가 없어야 합니다. |
| 102 | 103 | - extract-renamed: 실제 저장된 새 이름을 표시합니다. 이름 변경 결과만으로 저장 성공을 판정하지 않고 별도의 생성 보고와 완료 집계가 일치해야 합니다. |
| 103 | 104 | - extract-rename-failed: 새 이름을 정한 뒤 실제 생성 보고 없이 I/O 오류가 난 결과입니다. 실패 원인과 "아무 파일도 풀지 않았습니다"를 표시하고 "이름 바꿔 저장" 완료 안내는 표시하지 않아야 합니다. 일부 파일이 저장된 뒤 실패한 경우에도 생성 보고가 있는 이름만 저장 완료로 표시합니다. |
| 104 | 105 | |
| 105 | 삭제: 현재 충돌 화면과 클라이언트 연동은 준비 단계입니다. 작업자 런타임이 완성되기 전에는 실제 추출 요청을 기존 Start로 유지하며 StartInteractive를 보내지 않습니다. 위 명령은 실제 파일을 쓰지 않는 개발용 화면 미리보기입니다. | |
| 106 | 추가: 실제 추출은 revision 3의 StartInteractive를 보내며 ZIP, 7z, TAR 계열과 단일 GZ의 파일 충돌에 같은 선택 창을 사용합니다. 목록 읽기와 ZIP 만들기는 기존 Start를 유지합니다. 위 명령은 실제 파일을 쓰지 않는 개발용 화면 미리보기입니다. 파일 기반 버튼 연동은 tests/rust-app-real-worker/conflict_flows.rs에서 확인하며, 운영체제별 실제 창 확인은 별도입니다. |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # Rust archive worker |
| 2 | 2 | |
| 3 | 삭제: 별도 프로세스의 stdin/stdout으로 revision 2 요청을 처리합니다. 제품 앱이 공유 codec으로 연결하며 프로세스 분리는 OS sandbox를 뜻하지 않습니다. 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다. | |
| 3 | 추가: 별도 프로세스의 stdin/stdout으로 revision 3 요청을 처리합니다. 제품 앱이 공유 codec으로 연결하며 프로세스 분리는 OS sandbox를 뜻하지 않습니다. 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다. | |
| 4 | 4 | |
| 5 | 5 | - ZIP32/ZIP64 Store/Deflate 목록과 해제, ZIP32/ZIP64 생성, 기본 TAR/USTAR, GZ, TAR.GZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. 다중 볼륨, UTF-8로 해석할 수 없는 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다. |
| 6 | 6 | - ZIP 이름: UTF-8 플래그(비트 11)가 있으면 이름이 UTF-8이어야 하며 아니면 Integrity입니다. 플래그가 없으면 CRC가 원래 이름과 맞는 Info-ZIP Unicode Path 확장 필드(0x7075, 버전 1)를 우선 쓰고, 다음으로 UTF-8로 유효한 이름 바이트를 그대로 씁니다(Linux/macOS 도구의 기본 동작). CRC가 다르거나 버전이 다른 확장 필드는 무시합니다. 그 밖의 CP437/CP949 등 레거시 이름은 코드 페이지를 추측하지 않고 UnsupportedFeature로 거부합니다. 어느 경로로 얻은 이름이든 같은 경로 안전성 검사와 충돌 검사를 거칩니다. |
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | - ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다. |
| 11 | 11 | - 출력 폴더는 미리 존재해야 합니다. Linux는 소유 UID가 같고 group/other 쓰기가 없는 폴더만 허용합니다. openat/O_NOFOLLOW로 디렉터리를 고정하고 새 임시 파일을 배타적으로 만든 뒤 hard link로 게시합니다. 기존 파일과 링크를 덮어쓰지 않습니다. Windows는 reparse point를 거부하고 부모 디렉터리 핸들에서 delete sharing을 제한합니다. |
| 12 | 12 | - 파일 sync/close는 게시 전에 확인합니다. 게시 후 부모 sync와 임시 파일 정리 실패는 게시 사실과 따로 보고합니다. Windows의 디렉터리 내구성은 Unconfirmed입니다. hard link의 결과가 불명확하면 CommitUncertain/Uncertain이며 자동 재시도나 rollback은 없습니다. |
| 13 | 삭제: - 생성한 디렉터리와 게시한 파일은 취소 시 유지하고 Output으로 보고합니다. 실패한 임시 파일 정리는 실제 임시 이름과 PartialRetained로 보고합니다. 임시 파일 생성과 일부 쓰기 뒤 ENOSPC 주입 시험은 Linux에서 수행합니다. close/sync/link 장애 주입과 Windows 실기 검증은 아직 수행하지 않았습니다. | |
| 13 | 추가: - 생성한 디렉터리와 게시한 파일은 취소 시 유지하고 Output으로 보고합니다. 실패한 임시 파일 정리는 실제 임시 이름과 PartialRetained로 보고합니다. 임시 파일 생성과 일부 쓰기 뒤 ENOSPC, 파일 sync와 교체 호출 실패, 게시 후 디렉터리 sync 실패 주입 시험은 Linux에서 수행합니다. close 장애 주입과 Windows 실기 검증은 아직 수행하지 않았습니다. | |
| 14 | 14 | |
| 15 | 15 | ## 스트리밍과 자원 정리 |
| 16 | 16 | |
| @@ -68,15 +68,19 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도 | ||
| 68 | 68 | |
| 69 | 69 | ## revision 3 충돌 계약 |
| 70 | 70 | |
| 71 | 삭제: 공용 타입과 codec만 준비된 단계입니다. 현재 실행 경로는 revision 2의 `Start`를 유지하며 `StartInteractive`는 아직 처리하지 않습니다. 충돌 런타임 구현과 앱 연동 검증이 끝나기 전에는 새 요청을 실제 기능에 활성화하지 않습니다. 이 상태는 덮어쓰기 기능의 구현 완료를 뜻하지 않습니다. | |
| 71 | 추가: 작업자는 `StartInteractive`로 시작한 압축 해제에서 덮어쓰기, 건너뛰기와 이름 바꿔 저장을 처리합니다. 기존 `Start`는 이름 충돌 시 중단합니다. 앱의 활성화와 실제 UI 연동은 별도 PR에서 검증합니다. | |
| 72 | 72 | |
| 73 | 73 | - `StartInteractive(Start)`는 kind 4이며 기존 Start body를 그대로 사용합니다. Extract만 허용하고 List와 CreateZip은 codec에서 거부합니다. 기존 Start=1의 충돌 시 중단 동작과 모든 기존 필드 및 tag는 유지하며 구버전 작업자로 자동 재시도하지 않습니다. |
| 74 | 74 | - `ConflictChoice`는 Overwrite=0, Skip=1, Rename=2입니다. `ConflictReply`(5)는 challenge_id u64, choice u8, apply_to_remaining bool 순서입니다. |
| 75 | 75 | - `ConflictRequired`(108)는 challenge_id u64, entry_id u32, relative_name String, incoming_size u64, existing_size u64 순서입니다. 일반 파일끼리의 충돌에 세 선택을 허용하며 폴더끼리는 합치고 파일과 폴더 충돌 및 링크는 차단합니다. |
| 76 | 76 | - `ConflictResolved`(109)는 entry_id u32, relative_name String, choice u8 순서입니다. 일괄 적용에도 항목마다 보내며 저장 성공을 뜻하지 않습니다. 교체와 이름 변경의 게시 성공은 기존 `Output::Created`로 별도 확인하고 건너뛰기에는 Created를 보내지 않습니다. |
| 77 | 삭제: - Rename 이름은 작업자가 같은 폴더 안의 미사용 번호 이름으로 정합니다. 일괄 적용은 현재 작업의 남은 일반 파일 충돌에만 적용합니다. 질문은 한 번에 하나이며 잘못되거나 중복된 응답은 Protocol, 답변 전 EOF도 Protocol입니다. 취소를 처리하고 기존 300초 제한에 대기 시간을 포함합니다. | |
| 77 | 추가: - Rename 이름은 작업자가 같은 폴더 안에서 `파일명 (1).확장자` 형태의 미사용 번호 이름으로 정합니다. 기존 이름과 뒤에 처리할 항목의 경로도 피하며, 긴 이름은 UTF-8 경계를 보존해 255바이트 안으로 줄입니다. 일괄 적용은 현재 작업의 남은 일반 파일 충돌에만 적용합니다. 질문은 한 번에 하나이며 잘못되거나 중복된 응답은 Protocol, 답변 전 EOF도 Protocol입니다. 취소를 처리하고 기존 300초 제한에 대기 시간을 포함합니다. | |
| 78 | 78 | - 전부 건너뛰고 새 출력도 없으면 Completed, Publication::None, created_count=0, Durability::NotApplicable입니다. 새 폴더가 만들어졌다면 해당 Output과 실제 집계를 유지합니다. 교체는 created_count에 포함하며 건너뛰기는 제외합니다. |
| 79 | 삭제: - 런타임의 목표는 전체 무결성 검증 후 질문하고 목적지 임시 파일 기록, 검증, sync와 close를 마친 뒤 교체하는 것입니다. 교체 전 실패에는 원본을 보존하고 교체 후 오류에는 실제 게시, 내구성과 정리 상태를 보고합니다. 전체 작업의 원상 복구를 약속하지 않습니다. | |
| 79 | 추가: - 런타임은 전체 무결성 검증 후 질문하고 목적지 임시 파일 기록, 검증, sync와 close를 마친 뒤 교체합니다. 교체 전 실패에는 원본을 보존하고 교체 후 오류에는 실제 게시, 내구성과 정리 상태를 보고합니다. 전체 작업의 원상 복구를 약속하지 않습니다. | |
| 80 | 추가: | |
| 81 | 추가: 덮어쓰기 직전에 기존 파일과 부모의 식별자, 크기와 수정 시각을 다시 비교하며 변경이 감지되면 Conflict로 중단합니다. Linux에서는 고정 부모의 renameat, Windows에서는 같은 폴더의 MoveFileExW(REPLACE_EXISTING)를 사용하며 원본을 먼저 지우지 않습니다. 기존 파일의 다른 hard link는 수정하지 않습니다. 같은 계정의 동시 수정과 검사 직후 경합을 원자적으로 비교하거나 전체 작업을 되돌리는 기능은 아닙니다. Windows의 폴더 내구성은 기존처럼 Unconfirmed이며 전원 차단 뒤 복구를 보장하지 않습니다. | |
| 82 | 추가: | |
| 83 | 추가: 교체 동작의 근거는 [Linux rename](https://man7.org/linux/man-pages/man2/rename.2.html)과 [Microsoft MoveFileExW](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw)입니다. | |
| 80 | 84 | |
| 81 | 85 | ## 검증과 의존성 |
| 82 | 86 |
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | { |
| 2 | 삭제: "status": "revision-3-codec-ready-runtime-pending", | |
| 2 | 추가: "status": "revision-3-worker-implemented", | |
| 3 | 3 | "version": 1, |
| 4 | 4 | "scope": "One job per separately spawned Rust worker; shared binary codec. Process separation is not an OS sandbox.", |
| 5 | 5 | "frame": { |
| @@ -29,7 +29,7 @@ | ||
| 29 | 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.", |
| 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 | 삭제: "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. Runtime support is pending in this commit.", | |
| 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.", | |
| 33 | 33 | "ConflictReply": "Kind 5: challenge_id:u64, choice:ConflictChoice(u8), apply_to_remaining:bool. Match the one outstanding conflict challenge exactly once. Applying to remaining affects only later regular-file conflicts in this job." |
| 34 | 34 | }, |
| 35 | 35 | "events": { |
| @@ -96,7 +96,7 @@ | ||
| 96 | 96 | "87ff39f9-f7fe-4efc-bd2e-d73ab3246356" |
| 97 | 97 | ], |
| 98 | 98 | "conflict_backend_message_id": "64e29128-e8a2-45e5-8577-db84a66feaa9", |
| 99 | 삭제: "revision_3_status": "Joint agreement complete. Types and binary codec ready; conflict runtime and frontend integration are not implemented or verified by this commit. Existing revision 2 Start execution remains unchanged." | |
| 99 | 추가: "revision_3_status": "Joint agreement complete. Types, codec and interactive worker runtime implemented; frontend activation and native UI integration remain separate." | |
| 100 | 100 | }, |
| 101 | 101 | "list_identity": { |
| 102 | 102 | "ListId": { |
| @@ -209,16 +209,17 @@ | ||
| 209 | 209 | "Rename": 2 |
| 210 | 210 | }, |
| 211 | 211 | "extract_conflicts": { |
| 212 | 삭제: "status": "codec-ready-runtime-pending", | |
| 212 | 추가: "status": "worker-implemented", | |
| 213 | 213 | "compatibility": "Preserve frame version 1, every existing message kind, field order and enum tag. Add StartInteractive=4, ConflictReply=5, ConflictRequired=108 and ConflictResolved=109. Older workers reject kind 4 before output. Do not automatically retry, overwrite or fall back.", |
| 214 | 214 | "legacy": "Start keeps its existing abort-on-conflict behavior. List and CreateZip never accept interactive conflict mode. Existing limits, source identity, integrity checks and path guards remain mandatory.", |
| 215 | 215 | "scope": "Only ordinary-file/ordinary-file collisions. Merge existing directories as before; reject file/directory type collisions, symbolic links, reparse points and other special entries. Complete integrity validation of the entire catalog precedes conflict questions and destination publication.", |
| 216 | 삭제: "rename": "Worker selects an unused numbered sibling in the same directory under the validated output root. The app never supplies an arbitrary replacement path. Revalidate the chosen destination before publication.", | |
| 216 | 추가: "rename": "Worker selects an unused numbered sibling in the same directory under the validated output root. The app never supplies an arbitrary replacement path. Revalidate the chosen destination before publication. Avoid all selected archive output paths and prior generated names. Preserve UTF-8 boundaries when shortening a leaf to 255 bytes; try at most 10000 numbered candidates.", | |
| 217 | 217 | "wait": "At most one outstanding conflict or password challenge. Reject premature, stale or duplicate replies with Protocol. Cancel remains readable during a conflict wait. EOF without a reply fails Protocol; the existing 300-second job duration includes waits.", |
| 218 | 218 | "apply_to_remaining": "Keep the chosen policy only for the remaining ordinary-file conflicts in this job. Emit ConflictResolved for every such entry even without another question. Never carry the policy to another job or a file/directory or link collision.", |
| 219 | 219 | "events": "ConflictResolved reports an action and resolved relative name, not storage success. For overwrite and rename, Output Created separately confirms publication; skip has no Created output. On later errors preserve publication, durability and cleanup distinctions.", |
| 220 | 220 | "overwrite": "Write, verify, sync and close a new owned temporary file in the destination directory before replacing the existing ordinary file. A pre-replacement failure preserves the original. After replacement, report actual publication and durability; do not claim whole-job rollback.", |
| 221 | 221 | "counts": "created_count includes published replacement files and newly created files/directories; excludes skipped files. If all files are skipped and no new directory or other output is created, finish Completed/None with created_count=0 and Durability NotApplicable. Newly created directories retain their Output events and actual counts even if all files are skipped.", |
| 222 | 삭제: "implementation_boundary": "This commit provides the agreed protocol types and codec only. The current runtime rejects StartInteractive as an unsupported initial message. Do not enable interactive requests in a shipping client until worker implementation and integration checks finish." | |
| 222 | 추가: "implementation_boundary": "Worker supports StartInteractive extraction. Frontend activation and native Windows/Wayland integration require separate verification. Existing Start remains exclusive and aborts on file conflicts.", | |
| 223 | 추가: "target_revalidation": "Before replacement compare parent and file native identities, size and modification time with the question-time observation. Detected changes fail Conflict. This is not atomic compare-and-replace against concurrent writes by the same account." | |
| 223 | 224 | } |
| 224 | 225 | } |
| @@ -10,6 +10,32 @@ use std::sync::atomic::{AtomicU64, Ordering}; | ||
| 10 | 10 | |
| 11 | 11 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 12 | 12 | static TEMP: AtomicU64 = AtomicU64::new(0); |
| 13 | 추가: #[derive(Debug, PartialEq, Eq)] | |
| 14 | 추가: pub struct Existing { | |
| 15 | 추가: parent: SourceObject, | |
| 16 | 추가: object: SourceObject, | |
| 17 | 추가: pub size: u64, | |
| 18 | 추가: modified: std::time::SystemTime, | |
| 19 | 추가: } | |
| 20 | 추가: fn existing_file(parent: &File, file: File) -> Result<Existing> { | |
| 21 | 추가: let metadata = file.metadata().map_err(|_| ErrorCode::Io)?; | |
| 22 | 추가: if !metadata.is_file() { | |
| 23 | 추가: return Err(ErrorCode::UnsafePath); | |
| 24 | 추가: } | |
| 25 | 추가: #[cfg(windows)] | |
| 26 | 추가: { | |
| 27 | 추가: use std::os::windows::fs::MetadataExt; | |
| 28 | 추가: if metadata.file_attributes() & 0x400 != 0 { | |
| 29 | 추가: return Err(ErrorCode::UnsafePath); | |
| 30 | 추가: } | |
| 31 | 추가: } | |
| 32 | 추가: Ok(Existing { | |
| 33 | 추가: parent: object(parent)?, | |
| 34 | 추가: object: object(&file)?, | |
| 35 | 추가: size: metadata.len(), | |
| 36 | 추가: modified: metadata.modified().map_err(|_| ErrorCode::Io)?, | |
| 37 | 추가: }) | |
| 38 | 추가: } | |
| 13 | 39 | pub struct Snapshot { |
| 14 | 40 | pub bytes: Vec<u8>, |
| 15 | 41 | pub object: SourceObject, |
| @@ -163,6 +189,7 @@ mod platform { | ||
| 163 | 189 | fn openat(fd: i32, path: *const i8, flags: i32, ...) -> i32; |
| 164 | 190 | fn mkdirat(fd: i32, path: *const i8, mode: u32) -> i32; |
| 165 | 191 | fn linkat(fd: i32, path: *const i8, newfd: i32, newpath: *const i8, flags: i32) -> i32; |
| 192 | 추가: fn renameat(fd: i32, path: *const i8, newfd: i32, newpath: *const i8) -> i32; | |
| 166 | 193 | fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32; |
| 167 | 194 | fn geteuid() -> u32; |
| 168 | 195 | } |
| @@ -262,6 +289,31 @@ mod platform { | ||
| 262 | 289 | Err(_) => Err(ErrorCode::Io), |
| 263 | 290 | } |
| 264 | 291 | } |
| 292 | 추가: pub fn existing(&self, n: &str) -> Result<Option<Existing>> { | |
| 293 | 추가: match open(&self.file, std::ffi::OsStr::new(n), 0x200000) { | |
| 294 | 추가: Ok(file) => existing_file(&self.file, file).map(Some), | |
| 295 | 추가: Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), | |
| 296 | 추가: Err(_) => Err(ErrorCode::Io), | |
| 297 | 추가: } | |
| 298 | 추가: } | |
| 299 | 추가: pub fn replace(&self, from: &str, to: &str) -> std::io::Result<()> { | |
| 300 | 추가: let from = CString::new(from).unwrap(); | |
| 301 | 추가: let to = CString::new(to).unwrap(); | |
| 302 | 추가: // 고정 부모 안에서 완성된 임시 파일로 원본 이름을 교체함. | |
| 303 | 추가: if unsafe { | |
| 304 | 추가: renameat( | |
| 305 | 추가: self.file.as_raw_fd(), | |
| 306 | 추가: from.as_ptr(), | |
| 307 | 추가: self.file.as_raw_fd(), | |
| 308 | 추가: to.as_ptr(), | |
| 309 | 추가: ) | |
| 310 | 추가: } == 0 | |
| 311 | 추가: { | |
| 312 | 추가: Ok(()) | |
| 313 | 추가: } else { | |
| 314 | 추가: Err(std::io::Error::last_os_error()) | |
| 315 | 추가: } | |
| 316 | 추가: } | |
| 265 | 317 | pub fn create(&self, n: &str) -> std::io::Result<File> { |
| 266 | 318 | open(&self.file, std::ffi::OsStr::new(n), 1 | 0x40 | 0x80) |
| 267 | 319 | } |
| @@ -377,6 +429,45 @@ mod platform { | ||
| 377 | 429 | Err(_) => Err(ErrorCode::Io), |
| 378 | 430 | } |
| 379 | 431 | } |
| 432 | 추가: pub fn existing(&self, n: &str) -> Result<Option<Existing>> { | |
| 433 | 추가: match OpenOptions::new() | |
| 434 | 추가: .access_mode(0x80) | |
| 435 | 추가: .share_mode(7) | |
| 436 | 추가: .custom_flags(0x02000000 | 0x00200000) | |
| 437 | 추가: .open(self.path.join(n)) | |
| 438 | 추가: { | |
| 439 | 추가: Ok(file) => existing_file(self.handle(), file).map(Some), | |
| 440 | 추가: Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), | |
| 441 | 추가: Err(_) => Err(ErrorCode::Io), | |
| 442 | 추가: } | |
| 443 | 추가: } | |
| 444 | 추가: pub fn replace(&self, from: &str, to: &str) -> std::io::Result<()> { | |
| 445 | 추가: use std::os::windows::ffi::OsStrExt; | |
| 446 | 추가: unsafe extern "system" { | |
| 447 | 추가: fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32; | |
| 448 | 추가: } | |
| 449 | 추가: let extended = |name: &str| { | |
| 450 | 추가: [92u16, 92, 63, 92] | |
| 451 | 추가: .into_iter() | |
| 452 | 추가: .chain( | |
| 453 | 추가: self.path | |
| 454 | 추가: .join(name) | |
| 455 | 추가: .as_os_str() | |
| 456 | 추가: .encode_wide() | |
| 457 | 추가: .map(|unit| if unit == 47 { 92 } else { unit }), | |
| 458 | 추가: ) | |
| 459 | 추가: .chain(Some(0)) | |
| 460 | 추가: .collect::<Vec<_>>() | |
| 461 | 추가: }; | |
| 462 | 추가: let from = extended(from); | |
| 463 | 추가: let to = extended(to); | |
| 464 | 추가: // 같은 부모의 이름만 교체하고 복사나 사전 삭제는 하지 않음. | |
| 465 | 추가: if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), 1) } != 0 { | |
| 466 | 추가: Ok(()) | |
| 467 | 추가: } else { | |
| 468 | 추가: Err(std::io::Error::last_os_error()) | |
| 469 | 추가: } | |
| 470 | 추가: } | |
| 380 | 471 | pub fn create(&self, n: &str) -> std::io::Result<File> { |
| 381 | 472 | OpenOptions::new() |
| 382 | 473 | .write(true) |
| @@ -414,11 +505,30 @@ fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>> | ||
| 414 | 505 | } |
| 415 | 506 | Ok(Some((d, leaf.to_owned()))) |
| 416 | 507 | } |
| 508 | 추가: pub fn existing(root: &Dir, name: &str) -> Result<Option<Existing>> { | |
| 509 | 추가: valid_name(name, false)?; | |
| 510 | 추가: match parent(root, name, false)? { | |
| 511 | 추가: Some((dir, leaf)) => dir.existing(&leaf), | |
| 512 | 추가: None => Ok(None), | |
| 513 | 추가: } | |
| 514 | 추가: } | |
| 515 | 추가: pub fn unused(root: &Dir, name: &str) -> Result<bool> { | |
| 516 | 추가: valid_name(name, false)?; | |
| 517 | 추가: match parent(root, name, false)? { | |
| 518 | 추가: Some((dir, leaf)) => dir.absent(&leaf), | |
| 519 | 추가: None => Ok(true), | |
| 520 | 추가: } | |
| 521 | 추가: } | |
| 417 | 522 | pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> { |
| 523 | 추가: preflight_mode(root, names, false) | |
| 524 | 추가: } | |
| 525 | 추가: pub fn preflight_mode(root: &Dir, names: &[(String, EntryKind)], interactive: bool) -> Result<()> { | |
| 418 | 526 | for (name, kind) in names { |
| 419 | 527 | if let Some((d, leaf)) = parent(root, name, false)? { |
| 420 | 528 | if *kind == EntryKind::Directory { |
| 421 | 529 | let _ = d.child(&leaf, false)?; |
| 530 | 추가: } else if interactive { | |
| 531 | 추가: d.existing(&leaf)?; | |
| 422 | 532 | } else if !d.absent(&leaf)? { |
| 423 | 533 | return Err(ErrorCode::Conflict); |
| 424 | 534 | } |
| @@ -507,6 +617,16 @@ pub fn publish_reader( | ||
| 507 | 617 | data: &mut impl Read, |
| 508 | 618 | length: u64, |
| 509 | 619 | check: &mut impl FnMut(bool) -> Result<()>, |
| 620 | 추가: ) -> Published { | |
| 621 | 추가: publish_reader_mode(root, name, data, length, None, check) | |
| 622 | 추가: } | |
| 623 | 추가: pub fn publish_reader_mode( | |
| 624 | 추가: root: &Dir, | |
| 625 | 추가: name: &str, | |
| 626 | 추가: data: &mut impl Read, | |
| 627 | 추가: length: u64, | |
| 628 | 추가: replace: Option<&Existing>, | |
| 629 | 추가: check: &mut impl FnMut(bool) -> Result<()>, | |
| 510 | 630 | ) -> Published { |
| 511 | 631 | let mut result = Published { |
| 512 | 632 | created: false, |
| @@ -550,10 +670,24 @@ pub fn publish_reader( | ||
| 550 | 670 | file.sync_all().map_err(crate::space::io_error) |
| 551 | 671 | })(); |
| 552 | 672 | let closed = close(file).map_err(crate::space::io_error); |
| 553 | 삭제: let mut finish = written.and(closed).and_then(|_| check(true)); | |
| 673 | 추가: let mut finish = written.and(closed).and_then(|_| { | |
| 674 | 추가: if let Some(expected) = replace { | |
| 675 | 추가: if dir.existing(&leaf)?.as_ref() != Some(expected) { | |
| 676 | 추가: return Err(ErrorCode::Conflict); | |
| 677 | 추가: } | |
| 678 | 추가: } | |
| 679 | 추가: check(true) | |
| 680 | 추가: }); | |
| 681 | 추가: let mut temp_consumed = false; | |
| 554 | 682 | if finish.is_ok() { |
| 555 | 삭제: match dir.link(&temp, &leaf) { | |
| 683 | 추가: let published = if replace.is_some() { | |
| 684 | 추가: dir.replace(&temp, &leaf) | |
| 685 | 추가: } else { | |
| 686 | 추가: dir.link(&temp, &leaf) | |
| 687 | 추가: }; | |
| 688 | 추가: match published { | |
| 556 | 689 | Ok(()) => { |
| 690 | 추가: temp_consumed = replace.is_some(); | |
| 557 | 691 | result.created = true; |
| 558 | 692 | match dir.sync_checked() { |
| 559 | 693 | Ok(durability) => result.durability = durability, |
| @@ -573,7 +707,7 @@ pub fn publish_reader( | ||
| 573 | 707 | } |
| 574 | 708 | } |
| 575 | 709 | } |
| 576 | 삭제: if !dir.remove(&temp) { | |
| 710 | 추가: if !temp_consumed && !dir.remove(&temp) { | |
| 577 | 711 | result.cleanup = Cleanup::Failed; |
| 578 | 712 | result.retained = 1; |
| 579 | 713 | result.retained_name = Some(match name.rsplit_once('/') { |
| @@ -12,12 +12,18 @@ use std::{ | ||
| 12 | 12 | }; |
| 13 | 13 | |
| 14 | 14 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 15 | 추가: #[derive(PartialEq, Eq)] | |
| 16 | 추가: enum Challenge { | |
| 17 | 추가: Password(u64), | |
| 18 | 추가: Conflict(u64), | |
| 19 | 추가: } | |
| 15 | 20 | struct State<W> { |
| 16 | 21 | writer: Writer<W>, |
| 17 | 22 | cancelled: bool, |
| 18 | 23 | phase: u8, |
| 19 | 24 | fault: Option<ErrorCode>, |
| 20 | 삭제: challenge: Option<u64>, | |
| 25 | 추가: challenge: Option<Challenge>, | |
| 26 | 추가: conflict_reply: Option<(ConflictChoice, bool)>, | |
| 21 | 27 | password: Option<Secret>, |
| 22 | 28 | input_closed: bool, |
| 23 | 29 | } |
| @@ -25,6 +31,8 @@ struct Job<W> { | ||
| 25 | 31 | state: Arc<Mutex<State<W>>>, |
| 26 | 32 | wake: Arc<Condvar>, |
| 27 | 33 | next_challenge: u64, |
| 34 | 추가: interactive: bool, | |
| 35 | 추가: remaining_choice: Option<ConflictChoice>, | |
| 28 | 36 | started: Instant, |
| 29 | 37 | terminal: Terminal, |
| 30 | 38 | parent: crate::parent::Parent, |
| @@ -36,7 +44,7 @@ impl<W: Write> Job<W> { | ||
| 36 | 44 | let id = self.next_challenge; |
| 37 | 45 | let state_ref = Arc::clone(&self.state); |
| 38 | 46 | let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; |
| 39 | 삭제: state.challenge = Some(id); | |
| 47 | 추가: state.challenge = Some(Challenge::Password(id)); | |
| 40 | 48 | state |
| 41 | 49 | .writer |
| 42 | 50 | .send(&Message::PasswordRequired { |
| @@ -70,6 +78,87 @@ impl<W: Write> Job<W> { | ||
| 70 | 78 | } |
| 71 | 79 | } |
| 72 | 80 | |
| 81 | 추가: fn conflict(&mut self, entry: &Entry, existing_size: u64) -> Result<ConflictChoice> { | |
| 82 | 추가: self.check()?; | |
| 83 | 추가: if let Some(choice) = self.remaining_choice { | |
| 84 | 추가: return Ok(choice); | |
| 85 | 추가: } | |
| 86 | 추가: self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; | |
| 87 | 추가: let id = self.next_challenge; | |
| 88 | 추가: let state_ref = Arc::clone(&self.state); | |
| 89 | 추가: let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; | |
| 90 | 추가: state.challenge = Some(Challenge::Conflict(id)); | |
| 91 | 추가: state | |
| 92 | 추가: .writer | |
| 93 | 추가: .send(&Message::ConflictRequired { | |
| 94 | 추가: challenge_id: id, | |
| 95 | 추가: entry_id: entry.entry_id, | |
| 96 | 추가: relative_name: entry.name.clone(), | |
| 97 | 추가: incoming_size: entry.size, | |
| 98 | 추가: existing_size, | |
| 99 | 추가: }) | |
| 100 | 추가: .map_err(|_| ErrorCode::Io)?; | |
| 101 | 추가: loop { | |
| 102 | 추가: self.parent.check()?; | |
| 103 | 추가: if let Some(error) = state.fault { | |
| 104 | 추가: return Err(error); | |
| 105 | 추가: } | |
| 106 | 추가: if state.cancelled { | |
| 107 | 추가: return Err(ErrorCode::None); | |
| 108 | 추가: } | |
| 109 | 추가: if let Some((choice, apply)) = state.conflict_reply.take() { | |
| 110 | 추가: if apply { | |
| 111 | 추가: self.remaining_choice = Some(choice); | |
| 112 | 추가: } | |
| 113 | 추가: return Ok(choice); | |
| 114 | 추가: } | |
| 115 | 추가: if state.input_closed { | |
| 116 | 추가: return Err(ErrorCode::Protocol); | |
| 117 | 추가: } | |
| 118 | 추가: if self.started.elapsed() > Duration::from_secs(300) { | |
| 119 | 추가: return Err(ErrorCode::Limit); | |
| 120 | 추가: } | |
| 121 | 추가: state = self | |
| 122 | 추가: .wake | |
| 123 | 추가: .wait_timeout(state, Duration::from_millis(50)) | |
| 124 | 추가: .map_err(|_| ErrorCode::Internal)? | |
| 125 | 추가: .0; | |
| 126 | 추가: } | |
| 127 | 추가: } | |
| 128 | 추가: fn rename(&mut self, root: &Dir, name: &str, reserved: &BTreeSet<String>) -> Result<String> { | |
| 129 | 추가: let (prefix, leaf) = name.rsplit_once('/').unwrap_or(("", name)); | |
| 130 | 추가: let (stem, extension) = match leaf.rsplit_once('.') { | |
| 131 | 추가: Some((stem, ext)) if !stem.is_empty() => (stem, format!(".{ext}")), | |
| 132 | 추가: _ => (leaf, String::new()), | |
| 133 | 추가: }; | |
| 134 | 추가: for index in 1..=10000 { | |
| 135 | 추가: self.check()?; | |
| 136 | 추가: fn clip(text: &str, bytes: usize) -> &str { | |
| 137 | 추가: let mut end = text.len().min(bytes); | |
| 138 | 추가: while !text.is_char_boundary(end) { | |
| 139 | 추가: end -= 1; | |
| 140 | 추가: } | |
| 141 | 추가: &text[..end] | |
| 142 | 추가: } | |
| 143 | 추가: let suffix = format!(" ({index})"); | |
| 144 | 추가: let extension = clip(&extension, 255 - suffix.len() - 4).trim_end_matches(['.', ' ']); | |
| 145 | 추가: let stem = clip(stem, 255 - suffix.len() - extension.len()); | |
| 146 | 추가: let stem = if stem.is_empty() { "file" } else { stem }; | |
| 147 | 추가: let leaf = format!("{stem}{suffix}{extension}"); | |
| 148 | 추가: let candidate = if prefix.is_empty() { | |
| 149 | 추가: leaf | |
| 150 | 추가: } else { | |
| 151 | 추가: format!("{prefix}/{leaf}") | |
| 152 | 추가: }; | |
| 153 | 추가: archive::valid_name(&candidate, false)?; | |
| 154 | 추가: if !reserved.contains(&candidate.to_lowercase()) | |
| 155 | 추가: && filesystem::unused(root, &candidate)? | |
| 156 | 추가: { | |
| 157 | 추가: return Ok(candidate); | |
| 158 | 추가: } | |
| 159 | 추가: } | |
| 160 | 추가: Err(ErrorCode::Conflict) | |
| 161 | 추가: } | |
| 73 | 162 | fn event(&mut self, event: Message) -> Result<()> { |
| 74 | 163 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 75 | 164 | state.writer.send(&event).map_err(|_| { |
| @@ -122,6 +211,7 @@ impl<W: Write> Job<W> { | ||
| 122 | 211 | length: u64, |
| 123 | 212 | id: Option<u32>, |
| 124 | 213 | last: bool, |
| 214 | 추가: replace: Option<&filesystem::Existing>, | |
| 125 | 215 | ) -> Result<()> { |
| 126 | 216 | self.check()?; |
| 127 | 217 | self.progress( |
| @@ -130,7 +220,7 @@ impl<W: Write> Job<W> { | ||
| 130 | 220 | Some(length), |
| 131 | 221 | self.terminal.created_count as u32, |
| 132 | 222 | )?; |
| 133 | 삭제: let p = filesystem::publish_reader(root, name, data, length, &mut |commit| { | |
| 223 | 추가: let p = filesystem::publish_reader_mode(root, name, data, length, replace, &mut |commit| { | |
| 134 | 224 | if commit && last { |
| 135 | 225 | self.cutoff() |
| 136 | 226 | } else { |
| @@ -366,8 +456,12 @@ impl<W: Write> Job<W> { | ||
| 366 | 456 | .iter() |
| 367 | 457 | .map(|m| (m.entry.name.clone(), EntryKind::File)), |
| 368 | 458 | ); |
| 369 | 삭제: filesystem::preflight(&root, &names)?; | |
| 459 | 추가: filesystem::preflight_mode(&root, &names, self.interactive)?; | |
| 370 | 460 | filesystem::preflight_space(&root, &output_sizes, None)?; |
| 461 | 추가: let mut reserved = names | |
| 462 | 추가: .iter() | |
| 463 | 추가: .map(|(name, _)| name.to_lowercase()) | |
| 464 | 추가: .collect::<BTreeSet<_>>(); | |
| 371 | 465 | for name in dirs { |
| 372 | 466 | self.check()?; |
| 373 | 467 | let (created, durability, sync_error) = |
| @@ -389,16 +483,45 @@ impl<W: Write> Job<W> { | ||
| 389 | 483 | for (index, m) in files.iter().enumerate() { |
| 390 | 484 | data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize])) |
| 391 | 485 | .map_err(|_| ErrorCode::Io)?; |
| 486 | 추가: self.check()?; | |
| 487 | 추가: let existing = if self.interactive { | |
| 488 | 추가: filesystem::existing(&root, &m.entry.name)? | |
| 489 | 추가: } else { | |
| 490 | 추가: None | |
| 491 | 추가: }; | |
| 492 | 추가: let mut name = m.entry.name.clone(); | |
| 493 | 추가: let mut replace = None; | |
| 494 | 추가: if let Some(ref existing) = existing { | |
| 495 | 추가: let choice = self.conflict(&m.entry, existing.size)?; | |
| 496 | 추가: self.check()?; | |
| 497 | 추가: if choice == ConflictChoice::Rename { | |
| 498 | 추가: name = self.rename(&root, &name, &reserved)?; | |
| 499 | 추가: reserved.insert(name.to_lowercase()); | |
| 500 | 추가: } else if choice == ConflictChoice::Overwrite { | |
| 501 | 추가: replace = Some(existing); | |
| 502 | 추가: } | |
| 503 | 추가: self.event(Message::ConflictResolved { | |
| 504 | 추가: entry_id: m.entry.entry_id, | |
| 505 | 추가: relative_name: name.clone(), | |
| 506 | 추가: choice, | |
| 507 | 추가: })?; | |
| 508 | 추가: if choice == ConflictChoice::Skip { | |
| 509 | 추가: continue; | |
| 510 | 추가: } | |
| 511 | 추가: } | |
| 392 | 512 | self.output_reader( |
| 393 | 513 | &root, |
| 394 | 삭제: &m.entry.name, | |
| 514 | 추가: &name, | |
| 395 | 515 | &mut (&mut data).take(m.entry.size), |
| 396 | 516 | m.entry.size, |
| 397 | 517 | Some(m.entry.entry_id), |
| 398 | 518 | index + 1 == files.len(), |
| 519 | 추가: replace, | |
| 399 | 520 | )?; |
| 400 | 521 | } |
| 401 | 삭제: self.terminal.publication = Publication::Complete; | |
| 522 | 추가: if !self.interactive || self.terminal.created_count != 0 { | |
| 523 | 추가: self.terminal.publication = Publication::Complete; | |
| 524 | 추가: } | |
| 402 | 525 | } |
| 403 | 526 | } |
| 404 | 527 | Action::CreateZip { |
| @@ -433,7 +556,7 @@ impl<W: Write> Job<W> { | ||
| 433 | 556 | &mut || self.check(), |
| 434 | 557 | )?; |
| 435 | 558 | filesystem::preflight_space(&root, &[(name.clone(), length)], None)?; |
| 436 | 삭제: self.output_reader(&root, &name, &mut data, length, None, true)?; | |
| 559 | 추가: self.output_reader(&root, &name, &mut data, length, None, true, None)?; | |
| 437 | 560 | self.terminal.publication = Publication::Complete; |
| 438 | 561 | } |
| 439 | 562 | } |
| @@ -451,11 +574,15 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 451 | 574 | let (job, _, message) = reader |
| 452 | 575 | .read()? |
| 453 | 576 | .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?; |
| 454 | 삭제: let Message::Start(start) = message else { | |
| 455 | 삭제: return Err(std::io::Error::new( | |
| 456 | 삭제: std::io::ErrorKind::InvalidData, | |
| 457 | 삭제: "Start required", | |
| 458 | 삭제: )); | |
| 577 | 추가: let (start, interactive) = match message { | |
| 578 | 추가: Message::Start(start) => (start, false), | |
| 579 | 추가: Message::StartInteractive(start) => (start, true), | |
| 580 | 추가: _ => { | |
| 581 | 추가: return Err(std::io::Error::new( | |
| 582 | 추가: std::io::ErrorKind::InvalidData, | |
| 583 | 추가: "Start required", | |
| 584 | 추가: )); | |
| 585 | 추가: } | |
| 459 | 586 | }; |
| 460 | 587 | let state = Arc::new(Mutex::new(State { |
| 461 | 588 | writer: Writer::new(output, job), |
| @@ -463,6 +590,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 463 | 590 | phase: 0, |
| 464 | 591 | fault: None, |
| 465 | 592 | challenge: None, |
| 593 | 추가: conflict_reply: None, | |
| 466 | 594 | password: None, |
| 467 | 595 | input_closed: false, |
| 468 | 596 | })); |
| @@ -494,7 +622,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 494 | 622 | secret, |
| 495 | 623 | } => { |
| 496 | 624 | if state.phase != 0 |
| 497 | 삭제: || state.challenge != Some(challenge_id) | |
| 625 | 추가: || state.challenge != Some(Challenge::Password(challenge_id)) | |
| 498 | 626 | || state.password.is_some() |
| 499 | 627 | { |
| 500 | 628 | state.fault = Some(ErrorCode::Protocol); |
| @@ -506,6 +634,24 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 506 | 634 | } |
| 507 | 635 | control_wake.notify_all(); |
| 508 | 636 | } |
| 637 | 추가: Message::ConflictReply { | |
| 638 | 추가: challenge_id, | |
| 639 | 추가: choice, | |
| 640 | 추가: apply_to_remaining, | |
| 641 | 추가: } => { | |
| 642 | 추가: if state.phase != 0 | |
| 643 | 추가: || state.challenge != Some(Challenge::Conflict(challenge_id)) | |
| 644 | 추가: || state.conflict_reply.is_some() | |
| 645 | 추가: { | |
| 646 | 추가: state.fault = Some(ErrorCode::Protocol); | |
| 647 | 추가: } else { | |
| 648 | 추가: state.challenge = None; | |
| 649 | 추가: if !state.cancelled { | |
| 650 | 추가: state.conflict_reply = Some((choice, apply_to_remaining)); | |
| 651 | 추가: } | |
| 652 | 추가: } | |
| 653 | 추가: control_wake.notify_all(); | |
| 654 | 추가: } | |
| 509 | 655 | Message::Cancel => { |
| 510 | 656 | let status = match state.phase { |
| 511 | 657 | 2 => CancelStatus::Finished, |
| @@ -540,6 +686,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 540 | 686 | state: Arc::clone(&state), |
| 541 | 687 | wake, |
| 542 | 688 | next_challenge: 0, |
| 689 | 추가: interactive, | |
| 690 | 추가: remaining_choice: None, | |
| 543 | 691 | parent, |
| 544 | 692 | started: Instant::now(), |
| 545 | 693 | terminal: Terminal { |
| @@ -568,6 +716,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 568 | 716 | state.phase = 2; |
| 569 | 717 | state.challenge = None; |
| 570 | 718 | state.password = None; |
| 719 | 추가: state.conflict_reply = None; | |
| 571 | 720 | if let Some(error) = state.fault.or(error) { |
| 572 | 721 | context.terminal.error = error; |
| 573 | 722 | context.terminal.outcome = if error == ErrorCode::None { |
| @@ -500,7 +500,11 @@ impl ui::Connection for ProcessConnection { | ||
| 500 | 500 | self.stop.store(true, Ordering::Release); |
| 501 | 501 | "작업자 요청 상태 오류" |
| 502 | 502 | })? = Some(start.action.kind()); |
| 503 | 삭제: wire::Message::Start(start) | |
| 503 | 추가: if start.action.kind() == wire::ActionKind::Extract { | |
| 504 | 추가: wire::Message::StartInteractive(start) | |
| 505 | 추가: } else { | |
| 506 | 추가: wire::Message::Start(start) | |
| 507 | 추가: } | |
| 504 | 508 | } |
| 505 | 509 | ui::Command::ConflictReply { |
| 506 | 510 | challenge_id, |
| @@ -0,0 +1,231 @@ | ||
| 1 | 추가: fn conflict_fixture(scratch: &Scratch) -> (PathBuf, PathBuf) { | |
| 2 | 추가: use worker_protocol::{archive, protocol}; | |
| 3 | 추가: let members = ["기록.txt", "사진.txt"] | |
| 4 | 추가: .into_iter() | |
| 5 | 추가: .enumerate() | |
| 6 | 추가: .map(|(id, name)| archive::Member { | |
| 7 | 추가: entry: protocol::Entry { | |
| 8 | 추가: entry_id: id as u32, | |
| 9 | 추가: name: name.into(), | |
| 10 | 추가: kind: protocol::EntryKind::File, | |
| 11 | 추가: size: 3, | |
| 12 | 추가: compressed_size: 3, | |
| 13 | 추가: encrypted: false, | |
| 14 | 추가: }, | |
| 15 | 추가: data: b"new".to_vec(), | |
| 16 | 추가: }) | |
| 17 | 추가: .collect::<Vec<_>>(); | |
| 18 | 추가: let archive = scratch.path("충돌.zip"); | |
| 19 | 추가: fs::write( | |
| 20 | 추가: &archive, | |
| 21 | 추가: archive::create_zip( | |
| 22 | 추가: &members, | |
| 23 | 추가: protocol::Method::Store, | |
| 24 | 추가: protocol::Limits::default(), | |
| 25 | 추가: &mut || Ok(()), | |
| 26 | 추가: ) | |
| 27 | 추가: .unwrap(), | |
| 28 | 추가: ) | |
| 29 | 추가: .unwrap(); | |
| 30 | 추가: let output = make_directory(&scratch.path("output")); | |
| 31 | 추가: for name in ["기록.txt", "사진.txt"] { | |
| 32 | 추가: fs::write(output.join(name), b"original").unwrap(); | |
| 33 | 추가: } | |
| 34 | 추가: (archive, output) | |
| 35 | 추가: } | |
| 36 | 추가: | |
| 37 | 추가: impl Screen { | |
| 38 | 추가: fn start_conflicting_extract(&mut self, output: &Path) { | |
| 39 | 추가: self.app.choose_destination(output.to_path_buf()); | |
| 40 | 추가: self.dialogs | |
| 41 | 추가: .0 | |
| 42 | 추가: .borrow_mut() | |
| 43 | 추가: .answers | |
| 44 | 추가: .push_back(Some(vec![output.to_path_buf()])); | |
| 45 | 추가: self.click("압축해제"); | |
| 46 | 추가: assert!(self.app.model.busy()); | |
| 47 | 추가: } | |
| 48 | 추가: | |
| 49 | 추가: fn await_conflict(&mut self) -> Conflict { | |
| 50 | 추가: let deadline = Instant::now() + Duration::from_secs(10); | |
| 51 | 추가: loop { | |
| 52 | 추가: self.render(vec![]); | |
| 53 | 추가: if let Some(conflict) = &self.app.model.conflict { | |
| 54 | 추가: return conflict.clone(); | |
| 55 | 추가: } | |
| 56 | 추가: assert!( | |
| 57 | 추가: self.app.model.busy(), | |
| 58 | 추가: "충돌 질문 전에 종료됨: {:?}", | |
| 59 | 추가: self.app.model.terminal | |
| 60 | 추가: ); | |
| 61 | 추가: assert!(Instant::now() < deadline, "충돌 질문 시간 초과"); | |
| 62 | 추가: std::thread::sleep(Duration::from_millis(2)); | |
| 63 | 추가: } | |
| 64 | 추가: } | |
| 65 | 추가: | |
| 66 | 추가: fn settle_conflict_result(&mut self) { | |
| 67 | 추가: let deadline = Instant::now() + Duration::from_secs(10); | |
| 68 | 추가: while self.app.model.busy() { | |
| 69 | 추가: self.render(vec![]); | |
| 70 | 추가: assert!(Instant::now() < deadline, "충돌 결과 시간 초과"); | |
| 71 | 추가: std::thread::sleep(Duration::from_millis(2)); | |
| 72 | 추가: } | |
| 73 | 추가: assert!(self.app.model.confirmed, "{}", self.app.model.status()); | |
| 74 | 추가: assert!(self.app.model.conflict.is_none()); | |
| 75 | 추가: } | |
| 76 | 추가: } | |
| 77 | 추가: | |
| 78 | 추가: #[test] | |
| 79 | 추가: fn real_conflicts_follow_widget_choices_and_apply_remaining() { | |
| 80 | 추가: for (label, choice) in [ | |
| 81 | 추가: ("덮어쓰기", ConflictChoice::Overwrite), | |
| 82 | 추가: ("건너뛰기", ConflictChoice::Skip), | |
| 83 | 추가: ("이름 바꿔 저장", ConflictChoice::Rename), | |
| 84 | 추가: ] { | |
| 85 | 추가: for apply in [false, true] { | |
| 86 | 추가: let scratch = Scratch::new(); | |
| 87 | 추가: let (archive, output) = conflict_fixture(&scratch); | |
| 88 | 추가: let (factory, observed) = observed_factory(); | |
| 89 | 추가: let mut screen = Screen::new(factory); | |
| 90 | 추가: screen.open(&archive); | |
| 91 | 추가: screen.start_conflicting_extract(&output); | |
| 92 | 추가: let first = screen.await_conflict(); | |
| 93 | 추가: assert_eq!(first.incoming_size, 3); | |
| 94 | 추가: assert_eq!(first.existing_size, 8); | |
| 95 | 추가: if apply { | |
| 96 | 추가: screen.click("나머지 파일에도 같게 적용"); | |
| 97 | 추가: } | |
| 98 | 추가: screen.click(label); | |
| 99 | 추가: if !apply { | |
| 100 | 추가: let second = screen.await_conflict(); | |
| 101 | 추가: assert_ne!(first.challenge_id, second.challenge_id); | |
| 102 | 추가: assert_ne!(first.entry_id, second.entry_id); | |
| 103 | 추가: screen.click(label); | |
| 104 | 추가: } | |
| 105 | 추가: screen.settle_conflict_result(); | |
| 106 | 추가: completed(&screen.app.model); | |
| 107 | 추가: assert_eq!(screen.app.model.resolutions.len(), 2); | |
| 108 | 추가: assert!( | |
| 109 | 추가: screen | |
| 110 | 추가: .app | |
| 111 | 추가: .model | |
| 112 | 추가: .resolutions | |
| 113 | 추가: .iter() | |
| 114 | 추가: .all(|r| r.choice == choice) | |
| 115 | 추가: ); | |
| 116 | 추가: let terminal = screen.app.model.terminal.as_ref().unwrap(); | |
| 117 | 추가: assert_eq!( | |
| 118 | 추가: terminal.created_count, | |
| 119 | 추가: if choice == ConflictChoice::Skip { 0 } else { 2 } | |
| 120 | 추가: ); | |
| 121 | 추가: assert_eq!( | |
| 122 | 추가: terminal.publication, | |
| 123 | 추가: if choice == ConflictChoice::Skip { | |
| 124 | 추가: Publication::None | |
| 125 | 추가: } else { | |
| 126 | 추가: Publication::Complete | |
| 127 | 추가: } | |
| 128 | 추가: ); | |
| 129 | 추가: for name in ["기록.txt", "사진.txt"] { | |
| 130 | 추가: assert_eq!( | |
| 131 | 추가: fs::read(output.join(name)).unwrap(), | |
| 132 | 추가: if choice == ConflictChoice::Overwrite { | |
| 133 | 추가: b"new".as_slice() | |
| 134 | 추가: } else { | |
| 135 | 추가: b"original".as_slice() | |
| 136 | 추가: } | |
| 137 | 추가: ); | |
| 138 | 추가: } | |
| 139 | 추가: for resolution in &screen.app.model.resolutions { | |
| 140 | 추가: if choice == ConflictChoice::Rename { | |
| 141 | 추가: assert_eq!( | |
| 142 | 추가: fs::read(output.join(&resolution.relative_name)).unwrap(), | |
| 143 | 추가: b"new" | |
| 144 | 추가: ); | |
| 145 | 추가: assert!(resolution.relative_name.contains(" (1)")); | |
| 146 | 추가: } | |
| 147 | 추가: } | |
| 148 | 추가: let shown = screen | |
| 149 | 추가: .render(vec![]) | |
| 150 | 추가: .into_iter() | |
| 151 | 추가: .map(|(t, _)| t) | |
| 152 | 추가: .collect::<Vec<_>>() | |
| 153 | 추가: .join("\n"); | |
| 154 | 추가: assert!( | |
| 155 | 추가: shown.contains(if choice == ConflictChoice::Skip { | |
| 156 | 추가: "모든 파일을 건너뛰었습니다" | |
| 157 | 추가: } else { | |
| 158 | 추가: "압축을 풀었습니다" | |
| 159 | 추가: }), | |
| 160 | 추가: "{shown}" | |
| 161 | 추가: ); | |
| 162 | 추가: assert!(!shown.contains("저장이 끝났는지"), "{shown}"); | |
| 163 | 추가: assert_reaped(&observed); | |
| 164 | 추가: } | |
| 165 | 추가: } | |
| 166 | 추가: } | |
| 167 | 추가: | |
| 168 | 추가: #[test] | |
| 169 | 추가: fn real_conflict_cancel_button_and_escape_preserve_originals() { | |
| 170 | 추가: for escape in [false, true] { | |
| 171 | 추가: let scratch = Scratch::new(); | |
| 172 | 추가: let (archive, output) = conflict_fixture(&scratch); | |
| 173 | 추가: let (factory, observed) = observed_factory(); | |
| 174 | 추가: let mut screen = Screen::new(factory); | |
| 175 | 추가: screen.open(&archive); | |
| 176 | 추가: screen.start_conflicting_extract(&output); | |
| 177 | 추가: screen.await_conflict(); | |
| 178 | 추가: if escape { | |
| 179 | 추가: screen.escape(); | |
| 180 | 추가: } else { | |
| 181 | 추가: screen.click("작업 취소"); | |
| 182 | 추가: } | |
| 183 | 추가: screen.settle_conflict_result(); | |
| 184 | 추가: assert_eq!( | |
| 185 | 추가: screen.app.model.terminal.as_ref().unwrap().outcome, | |
| 186 | 추가: Outcome::Cancelled | |
| 187 | 추가: ); | |
| 188 | 추가: assert!(screen.app.model.outputs.is_empty()); | |
| 189 | 추가: for name in ["기록.txt", "사진.txt"] { | |
| 190 | 추가: assert_eq!(fs::read(output.join(name)).unwrap(), b"original"); | |
| 191 | 추가: } | |
| 192 | 추가: assert_reaped(&observed); | |
| 193 | 추가: } | |
| 194 | 추가: } | |
| 195 | 추가: | |
| 196 | 추가: #[test] | |
| 197 | 추가: fn target_changed_during_real_question_fails_without_saved_name_notice() { | |
| 198 | 추가: let scratch = Scratch::new(); | |
| 199 | 추가: let (archive, output) = conflict_fixture(&scratch); | |
| 200 | 추가: let (factory, observed) = observed_factory(); | |
| 201 | 추가: let mut screen = Screen::new(factory); | |
| 202 | 추가: screen.open(&archive); | |
| 203 | 추가: screen.start_conflicting_extract(&output); | |
| 204 | 추가: let conflict = screen.await_conflict(); | |
| 205 | 추가: fs::write( | |
| 206 | 추가: output.join(&conflict.relative_name), | |
| 207 | 추가: b"changed after question", | |
| 208 | 추가: ) | |
| 209 | 추가: .unwrap(); | |
| 210 | 추가: screen.click("덮어쓰기"); | |
| 211 | 추가: screen.settle_conflict_result(); | |
| 212 | 추가: assert_eq!( | |
| 213 | 추가: screen.app.model.terminal.as_ref().unwrap().outcome, | |
| 214 | 추가: Outcome::Failed | |
| 215 | 추가: ); | |
| 216 | 추가: assert_eq!(screen.app.model.terminal.as_ref().unwrap().created_count, 0); | |
| 217 | 추가: assert!(screen.app.model.outputs.is_empty()); | |
| 218 | 추가: assert_eq!( | |
| 219 | 추가: fs::read(output.join(&conflict.relative_name)).unwrap(), | |
| 220 | 추가: b"changed after question" | |
| 221 | 추가: ); | |
| 222 | 추가: let shown = screen | |
| 223 | 추가: .render(vec![]) | |
| 224 | 추가: .into_iter() | |
| 225 | 추가: .map(|(t, _)| t) | |
| 226 | 추가: .collect::<Vec<_>>() | |
| 227 | 추가: .join("\n"); | |
| 228 | 추가: assert!(shown.contains("압축을 풀지 못했습니다"), "{shown}"); | |
| 229 | 추가: assert!(!shown.contains("이름 바꿔 저장:"), "{shown}"); | |
| 230 | 추가: assert_reaped(&observed); | |
| 231 | 추가: } |
| @@ -304,12 +304,17 @@ mod screen { | ||
| 304 | 304 | self.settle(); |
| 305 | 305 | assert_eq!( |
| 306 | 306 | self.app.model.terminal.as_ref().unwrap().publication, |
| 307 | 삭제: Publication::Complete | |
| 307 | 추가: if self.app.model.terminal.as_ref().unwrap().created_count == 0 { | |
| 308 | 추가: Publication::None | |
| 309 | 추가: } else { | |
| 310 | 추가: Publication::Complete | |
| 311 | 추가: } | |
| 308 | 312 | ); |
| 309 | 313 | } |
| 310 | 314 | } |
| 311 | 315 | include!("password_flows.rs"); |
| 312 | 316 | include!("selection_flows.rs"); |
| 317 | 추가: include!("conflict_flows.rs"); | |
| 313 | 318 | include!("native_dialog_flows.rs"); |
| 314 | 319 | |
| 315 | 320 | fn archive_flow(name: &str, format: Format) { |
| @@ -5,12 +5,13 @@ fn native_fixture(scratch: &Scratch, fixture: &str, name: &str) -> PathBuf { | ||
| 5 | 5 | .join("../../tests/rust-app-real-worker/fixtures") |
| 6 | 6 | .join(fixture), |
| 7 | 7 | &target, |
| 8 | 삭제: ).unwrap(); | |
| 8 | 추가: ) | |
| 9 | 추가: .unwrap(); | |
| 9 | 10 | target |
| 10 | 11 | } |
| 11 | 12 | |
| 12 | 13 | #[test] |
| 13 | 삭제: fn raw_gzip_save_dialog_corrects_names_and_preserves_cancel_and_conflict_retry() { | |
| 14 | 추가: fn raw_gzip_save_dialog_corrects_names_and_preserves_cancel_and_conflict_choice() { | |
| 14 | 15 | use zipelo_ui_memory_app::archive_dialog::Purpose; |
| 15 | 16 | let mut names = vec![".gz", "report.GZ", "report.Gz", "report.gz"]; |
| 16 | 17 | #[cfg(unix)] |
| @@ -23,41 +24,46 @@ fn raw_gzip_save_dialog_corrects_names_and_preserves_cancel_and_conflict_retry() | ||
| 23 | 24 | let (factory, observed) = observed_factory(); |
| 24 | 25 | let mut screen = Screen::new(factory); |
| 25 | 26 | screen.open(&archive); |
| 26 | 삭제: assert_eq!(screen.app.model.list_id.as_ref().unwrap().format, Format::Gzip); | |
| 27 | 추가: assert_eq!( | |
| 28 | 추가: screen.app.model.list_id.as_ref().unwrap().format, | |
| 29 | 추가: Format::Gzip | |
| 30 | 추가: ); | |
| 27 | 31 | screen.click("압축해제"); |
| 28 | 32 | assert!(!screen.app.model.busy()); |
| 29 | 33 | assert_eq!(observed.borrow().jobs.len(), 1); |
| 30 | 34 | let request = screen.dialogs.0.borrow().requests.last().unwrap().clone(); |
| 31 | 35 | assert_eq!(request.purpose, Purpose::SaveGzip); |
| 32 | 36 | assert_eq!(request.directory, scratch.0); |
| 33 | 삭제: assert_eq!(request.file_name, if name == ".gz" || name.contains(':') { "압축 해제 파일" } else { "report" }); | |
| 37 | 추가: assert_eq!( | |
| 38 | 추가: request.file_name, | |
| 39 | 추가: if name == ".gz" || name.contains(':') { | |
| 40 | 추가: "압축 해제 파일" | |
| 41 | 추가: } else { | |
| 42 | 추가: "report" | |
| 43 | 추가: } | |
| 44 | 추가: ); | |
| 34 | 45 | let existing = output.join("기존 파일.txt"); |
| 35 | 46 | fs::write(&existing, b"preserve").unwrap(); |
| 36 | 삭제: screen.dialogs.0.borrow_mut().answers.push_back(Some(vec![existing.clone()])); | |
| 47 | 추가: screen | |
| 48 | 추가: .dialogs | |
| 49 | 추가: .0 | |
| 50 | 추가: .borrow_mut() | |
| 51 | 추가: .answers | |
| 52 | 추가: .push_back(Some(vec![existing.clone()])); | |
| 37 | 53 | screen.click("압축해제"); |
| 38 | 삭제: let deadline = Instant::now() + Duration::from_secs(10); | |
| 39 | 삭제: while screen.app.model.busy() { | |
| 40 | 삭제: screen.render(vec![]); | |
| 41 | 삭제: assert!(Instant::now() < deadline); | |
| 42 | 삭제: std::thread::sleep(Duration::from_millis(2)); | |
| 43 | 삭제: } | |
| 44 | 삭제: assert_eq!(screen.app.model.terminal.as_ref().unwrap().error, Some(ErrorCode::Conflict)); | |
| 45 | 삭제: assert_eq!(fs::read(&existing).unwrap(), b"preserve"); | |
| 46 | 삭제: screen.click("다른 이름으로 저장"); | |
| 47 | 삭제: assert!(!screen.app.model.busy()); | |
| 48 | 삭제: assert_eq!(observed.borrow().jobs.len(), 2); | |
| 49 | 삭제: assert_eq!(screen.dialogs.0.borrow().requests.last().unwrap().purpose, Purpose::RetryGzip); | |
| 50 | 삭제: let saved = output.join("사용자 이름.txt"); | |
| 51 | 삭제: screen.dialogs.0.borrow_mut().answers.push_back(Some(vec![saved.clone()])); | |
| 52 | 삭제: screen.click("다른 이름으로 저장"); | |
| 53 | 삭제: screen.settle(); | |
| 54 | 추가: let conflict = screen.await_conflict(); | |
| 55 | 추가: assert_eq!(conflict.relative_name, "기존 파일.txt"); | |
| 56 | 추가: screen.click("이름 바꿔 저장"); | |
| 57 | 추가: screen.settle_conflict_result(); | |
| 58 | 추가: completed(&screen.app.model); | |
| 59 | 추가: let saved = output.join("기존 파일 (1).txt"); | |
| 54 | 60 | assert_eq!(fs::read(saved).unwrap(), b"Zipelo real worker flow\n"); |
| 55 | 61 | assert_eq!(fs::read(existing).unwrap(), b"preserve"); |
| 56 | 62 | assert_eq!(fs::read(&archive).unwrap(), original); |
| 57 | 63 | assert!(matches!( |
| 58 | 64 | observed.borrow().starts.last(), |
| 59 | 65 | Some(Start::Extract { destination, gzip_output_name: Some(name), .. }) |
| 60 | 삭제: if destination == &output && name == "사용자 이름.txt" | |
| 66 | 추가: if destination == &output && name == "기존 파일.txt" | |
| 61 | 67 | )); |
| 62 | 68 | assert_reaped(&observed); |
| 63 | 69 | } |
| @@ -73,13 +79,24 @@ fn mixed_case_zip_names_open_and_extract_through_native_dialog_responses() { | ||
| 73 | 79 | let output = make_directory(&scratch.path("output")); |
| 74 | 80 | let (factory, observed) = observed_factory(); |
| 75 | 81 | let mut screen = Screen::new(factory); |
| 76 | 삭제: screen.dialogs.0.borrow_mut().answers.push_back(Some(vec![archive.clone()])); | |
| 82 | 추가: screen | |
| 83 | 추가: .dialogs | |
| 84 | 추가: .0 | |
| 85 | 추가: .borrow_mut() | |
| 86 | 추가: .answers | |
| 87 | 추가: .push_back(Some(vec![archive.clone()])); | |
| 77 | 88 | screen.click("열기"); |
| 78 | 89 | screen.settle(); |
| 79 | 90 | assert_eq!(screen.dialogs.0.borrow().requests[0].purpose, Purpose::Open); |
| 80 | 삭제: assert_eq!(screen.app.model.list_id.as_ref().unwrap().format, Format::Zip); | |
| 91 | 추가: assert_eq!( | |
| 92 | 추가: screen.app.model.list_id.as_ref().unwrap().format, | |
| 93 | 추가: Format::Zip | |
| 94 | 추가: ); | |
| 81 | 95 | screen.extract(&output); |
| 82 | 삭제: assert_eq!(fs::read(output.join("content.txt")).unwrap(), b"Zipelo real worker flow\n"); | |
| 96 | 추가: assert_eq!( | |
| 97 | 추가: fs::read(output.join("content.txt")).unwrap(), | |
| 98 | 추가: b"Zipelo real worker flow\n" | |
| 99 | 추가: ); | |
| 83 | 100 | assert_eq!(fs::read(archive).unwrap(), original); |
| 84 | 101 | assert_reaped(&observed); |
| 85 | 102 | } |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # 앱 화면 흐름 시험 |
| 2 | 2 | |
| 3 | 삭제: 가짜 작업자는 합의된 계약의 의미를 따르는 프론트엔드 어댑터임. revision 3의 충돌 요청과 응답은 가짜 작업자로 검증하며 실제 StartInteractive 활성화와 파일 기반 통합 검증은 작업자 런타임 구현 후 진행함. 바이너리 codec, 실제 프로세스 실행, 파일 읽기와 쓰기, 암호 해독은 수행하지 않음. 실제 codec은 backend 소유이며 이 PR에서 중복 구현하지 않음. | |
| 3 | 추가: 가짜 작업자는 합의된 계약의 의미를 따르는 프론트엔드 어댑터임. revision 3의 충돌 요청과 응답은 가짜 작업자로 검증함. 실제 StartInteractive와 화면 버튼의 파일 기반 통합 시험은 tests/rust-app-real-worker/conflict_flows.rs에서 별도로 실행함. 바이너리 codec, 실제 프로세스 실행, 파일 읽기와 쓰기, 암호 해독은 수행하지 않음. 실제 codec은 backend 소유이며 이 PR에서 중복 구현하지 않음. | |
| 4 | 4 | |
| 5 | 5 | `python3 tests/ci/run_rust.py local`은 기존 시험과 새 `archive_ui` 시험을 all-features로 실행함. Windows 결과는 교차 빌드이며 Windows 실제 실행은 별도 확인해야 함. |
| 6 | 6 |
| @@ -96,7 +96,9 @@ fn every_listed_scenario_draws_and_keeps_its_expected_screen() { | ||
| 96 | 96 | ); |
| 97 | 97 | assert!(app.model.input_error.is_none(), "{}", scenario.name); |
| 98 | 98 | let expected = match scenario.name { |
| 99 | 삭제: "conflict-choice" | "conflict-apply" => "나머지 파일에도 같게 적용", | |
| 99 | 추가: "conflict-choice" | "conflict-apply" | "gzip-conflict-choice" => { | |
| 100 | 추가: "나머지 파일에도 같게 적용" | |
| 101 | 추가: } | |
| 100 | 102 | "extract-skipped" => "모든 파일을 건너뛰었습니다", |
| 101 | 103 | "extract-rename-failed" => "아무 파일도 풀지 않았습니다", |
| 102 | 104 | "extract-renamed" => "이름 바꿔 저장: 읽어주세요 (1).txt", |
| @@ -21,6 +21,7 @@ macro_rules! catalog { | ||
| 21 | 21 | } |
| 22 | 22 | |
| 23 | 23 | catalog! { |
| 24 | 추가: "gzip-conflict-choice" => "단일 GZ 파일의 충돌 선택", | |
| 24 | 25 | "conflict-choice" => "같은 이름 파일의 세 가지 처리 선택", |
| 25 | 26 | "conflict-apply" => "남은 충돌에 같은 선택 적용", |
| 26 | 27 | "extract-skipped" => "모든 파일을 건너뛴 정상 완료", |
| @@ -167,11 +168,13 @@ impl Scenario { | ||
| 167 | 168 | if self.name == "empty" { |
| 168 | 169 | return app; |
| 169 | 170 | } |
| 170 | 삭제: let archive = base.join(if self.name == "gzip-conflict" { | |
| 171 | 삭제: "여행 자료.gz" | |
| 172 | 삭제: } else { | |
| 173 | 삭제: "여행 자료.zip" | |
| 174 | 삭제: }); | |
| 171 | 추가: let archive = base.join( | |
| 172 | 추가: if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") { | |
| 173 | 추가: "여행 자료.gz" | |
| 174 | 추가: } else { | |
| 175 | 추가: "여행 자료.zip" | |
| 176 | 추가: }, | |
| 177 | 추가: ); | |
| 175 | 178 | app.model.archive = Some(archive.clone()); |
| 176 | 179 | app.model.entries = entries(self.name == "many-items"); |
| 177 | 180 | app.model.list_id = Some(ListId { |
| @@ -236,7 +239,7 @@ impl Scenario { | ||
| 236 | 239 | } |
| 237 | 240 | let creating = self.name.starts_with("create-") || self.name == "password-create"; |
| 238 | 241 | let listing_error = matches!(self.name, "unsupported" | "damaged"); |
| 239 | 삭제: if self.name == "gzip-conflict" { | |
| 242 | 추가: if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") { | |
| 240 | 243 | app.model.list_id.as_mut().unwrap().format = Format::Gzip; |
| 241 | 244 | app.model.entries = vec![Entry { |
| 242 | 245 | id: 0, |
| @@ -263,12 +266,13 @@ impl Scenario { | ||
| 263 | 266 | destination: app.destination.clone(), |
| 264 | 267 | selection: Selection::All, |
| 265 | 268 | list_id: app.model.list_id.clone().unwrap(), |
| 266 | 삭제: gzip_output_name: (self.name == "gzip-conflict").then(|| app.gzip_name.clone()), | |
| 269 | 추가: gzip_output_name: (matches!(self.name, "gzip-conflict" | "gzip-conflict-choice")) | |
| 270 | 추가: .then(|| app.gzip_name.clone()), | |
| 267 | 271 | } |
| 268 | 272 | }; |
| 269 | 273 | app.targets = Some(if creating { |
| 270 | 274 | BTreeSet::from(["여행 자료.zip".into()]) |
| 271 | 삭제: } else if self.name == "gzip-conflict" { | |
| 275 | 추가: } else if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") { | |
| 272 | 276 | BTreeSet::from(["여행 자료".into()]) |
| 273 | 277 | } else { |
| 274 | 278 | BTreeSet::from([ |
| @@ -290,11 +294,20 @@ impl Scenario { | ||
| 290 | 294 | let mut state = state.borrow_mut(); |
| 291 | 295 | state.frame(Event::Accepted { encryption: true }); |
| 292 | 296 | match self.name { |
| 293 | 삭제: "conflict-choice" | "conflict-apply" => { | |
| 297 | 추가: "conflict-choice" | "conflict-apply" | "gzip-conflict-choice" => { | |
| 294 | 298 | state.frame(Event::ConflictRequired(Conflict { |
| 295 | 299 | challenge_id: 29, |
| 296 | 삭제: entry_id: 1, | |
| 297 | 삭제: relative_name: "읽어주세요.txt".into(), | |
| 300 | 추가: entry_id: if self.name == "gzip-conflict-choice" { | |
| 301 | 추가: 0 | |
| 302 | 추가: } else { | |
| 303 | 추가: 1 | |
| 304 | 추가: }, | |
| 305 | 추가: relative_name: if self.name == "gzip-conflict-choice" { | |
| 306 | 추가: "여행 자료" | |
| 307 | 추가: } else { | |
| 308 | 추가: "읽어주세요.txt" | |
| 309 | 추가: } | |
| 310 | 추가: .into(), | |
| 298 | 311 | incoming_size: 1_287_952, |
| 299 | 312 | existing_size: 2048, |
| 300 | 313 | })); |
| @@ -0,0 +1,702 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: use sha2::{Digest, Sha256}; | |
| 3 | 추가: use std::{ | |
| 4 | 추가: io::Read, | |
| 5 | 추가: process::{Child, ChildStdin}, | |
| 6 | 추가: sync::mpsc, | |
| 7 | 추가: time::{Duration, Instant}, | |
| 8 | 추가: }; | |
| 9 | 추가: | |
| 10 | 추가: struct Running(Child); | |
| 11 | 추가: impl Drop for Running { | |
| 12 | 추가: fn drop(&mut self) { | |
| 13 | 추가: let _ = self.0.kill(); | |
| 14 | 추가: let _ = self.0.wait(); | |
| 15 | 추가: } | |
| 16 | 추가: } | |
| 17 | 추가: fn directory(s: &Scratch, name: &str) { | |
| 18 | 추가: let path = s.0.join(name); | |
| 19 | 추가: fs::create_dir_all(&path).unwrap(); | |
| 20 | 추가: #[cfg(unix)] | |
| 21 | 추가: { | |
| 22 | 추가: use std::os::unix::fs::PermissionsExt; | |
| 23 | 추가: let mut current = path.as_path(); | |
| 24 | 추가: while current != s.0 { | |
| 25 | 추가: fs::set_permissions(current, fs::Permissions::from_mode(0o700)).unwrap(); | |
| 26 | 추가: current = current.parent().unwrap(); | |
| 27 | 추가: } | |
| 28 | 추가: } | |
| 29 | 추가: } | |
| 30 | 추가: fn request(s: &Scratch) -> Start { | |
| 31 | 추가: Start { | |
| 32 | 추가: action: Action::Extract { | |
| 33 | 추가: archive: s.path("input"), | |
| 34 | 추가: destination: s.path("output"), | |
| 35 | 추가: selection: Selection::All, | |
| 36 | 추가: list_id: None, | |
| 37 | 추가: gzip_output_name: None, | |
| 38 | 추가: }, | |
| 39 | 추가: limits: Limits::default(), | |
| 40 | 추가: } | |
| 41 | 추가: } | |
| 42 | 추가: fn fixture(s: &Scratch, names: &[&str]) { | |
| 43 | 추가: let members = names | |
| 44 | 추가: .iter() | |
| 45 | 추가: .enumerate() | |
| 46 | 추가: .map(|(id, name)| archive::Member { | |
| 47 | 추가: entry: Entry { | |
| 48 | 추가: entry_id: id as u32, | |
| 49 | 추가: name: (*name).into(), | |
| 50 | 추가: kind: EntryKind::File, | |
| 51 | 추가: size: PAYLOAD.len() as u64, | |
| 52 | 추가: compressed_size: PAYLOAD.len() as u64, | |
| 53 | 추가: encrypted: false, | |
| 54 | 추가: }, | |
| 55 | 추가: data: PAYLOAD.to_vec(), | |
| 56 | 추가: }) | |
| 57 | 추가: .collect::<Vec<_>>(); | |
| 58 | 추가: let zip = | |
| 59 | 추가: archive::create_zip(&members, Method::Store, Limits::default(), &mut || Ok(())).unwrap(); | |
| 60 | 추가: fs::write(s.0.join("input"), zip).unwrap(); | |
| 61 | 추가: directory(s, "output"); | |
| 62 | 추가: #[cfg(unix)] | |
| 63 | 추가: { | |
| 64 | 추가: use std::os::unix::fs::PermissionsExt; | |
| 65 | 추가: fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap(); | |
| 66 | 추가: } | |
| 67 | 추가: for name in names { | |
| 68 | 추가: let path = s.0.join("output").join(name); | |
| 69 | 추가: directory( | |
| 70 | 추가: s, | |
| 71 | 추가: path.parent() | |
| 72 | 추가: .unwrap() | |
| 73 | 추가: .strip_prefix(&s.0) | |
| 74 | 추가: .unwrap() | |
| 75 | 추가: .to_str() | |
| 76 | 추가: .unwrap(), | |
| 77 | 추가: ); | |
| 78 | 추가: fs::write(path, b"original").unwrap(); | |
| 79 | 추가: } | |
| 80 | 추가: } | |
| 81 | 추가: fn reply(id: u64, choice: ConflictChoice, apply: bool) -> Message { | |
| 82 | 추가: Message::ConflictReply { | |
| 83 | 추가: challenge_id: id, | |
| 84 | 추가: choice, | |
| 85 | 추가: apply_to_remaining: apply, | |
| 86 | 추가: } | |
| 87 | 추가: } | |
| 88 | 추가: fn run( | |
| 89 | 추가: s: &Scratch, | |
| 90 | 추가: start: Start, | |
| 91 | 추가: fault: Option<&str>, | |
| 92 | 추가: initial: Vec<Message>, | |
| 93 | 추가: mut respond: impl FnMut(&Message) -> Option<Vec<Message>>, | |
| 94 | 추가: ) -> Vec<Message> { | |
| 95 | 추가: let mut command = s.worker(); | |
| 96 | 추가: command | |
| 97 | 추가: .stdin(Stdio::piped()) | |
| 98 | 추가: .stdout(Stdio::piped()) | |
| 99 | 추가: .stderr(Stdio::piped()); | |
| 100 | 추가: #[cfg(target_os = "linux")] | |
| 101 | 추가: if let Some(fault) = fault { | |
| 102 | 추가: let shim = s.0.join("io_fault.so"); | |
| 103 | 추가: assert!( | |
| 104 | 추가: Command::new("cc") | |
| 105 | 추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"]) | |
| 106 | 추가: .arg( | |
| 107 | 추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 108 | 추가: .join("../../tests/rust-archive-worker/io_fault.c") | |
| 109 | 추가: ) | |
| 110 | 추가: .arg("-ldl") | |
| 111 | 추가: .arg("-o") | |
| 112 | 추가: .arg(&shim) | |
| 113 | 추가: .status() | |
| 114 | 추가: .unwrap() | |
| 115 | 추가: .success() | |
| 116 | 추가: ); | |
| 117 | 추가: command | |
| 118 | 추가: .env("LD_PRELOAD", shim) | |
| 119 | 추가: .env("ZIPELO_TEST_FAULT", fault) | |
| 120 | 추가: .env("ZIPELO_TEST_MARKER", s.0.join("paused")) | |
| 121 | 추가: .env("ZIPELO_TEST_RELEASE", s.0.join("release")); | |
| 122 | 추가: } | |
| 123 | 추가: #[cfg(not(target_os = "linux"))] | |
| 124 | 추가: assert!(fault.is_none()); | |
| 125 | 추가: let mut child = Running(command.spawn().unwrap()); | |
| 126 | 추가: let mut writer: Option<Writer<ChildStdin>> = | |
| 127 | 추가: Some(Writer::new(child.0.stdin.take().unwrap(), 17)); | |
| 128 | 추가: writer | |
| 129 | 추가: .as_mut() | |
| 130 | 추가: .unwrap() | |
| 131 | 추가: .send(&Message::StartInteractive(start)) | |
| 132 | 추가: .unwrap(); | |
| 133 | 추가: for message in initial { | |
| 134 | 추가: writer.as_mut().unwrap().send(&message).unwrap(); | |
| 135 | 추가: } | |
| 136 | 추가: let stdout = child.0.stdout.take().unwrap(); | |
| 137 | 추가: let mut stderr = child.0.stderr.take().unwrap(); | |
| 138 | 추가: let errors = std::thread::spawn(move || { | |
| 139 | 추가: let mut bytes = Vec::new(); | |
| 140 | 추가: stderr.read_to_end(&mut bytes).unwrap(); | |
| 141 | 추가: bytes | |
| 142 | 추가: }); | |
| 143 | 추가: let (send, receive) = mpsc::channel(); | |
| 144 | 추가: let reader = std::thread::spawn(move || { | |
| 145 | 추가: let mut reader = Reader::new(stdout); | |
| 146 | 추가: loop { | |
| 147 | 추가: let frame = reader.read(); | |
| 148 | 추가: let done = !matches!(frame, Ok(Some(_))); | |
| 149 | 추가: if send.send(frame).is_err() || done { | |
| 150 | 추가: break; | |
| 151 | 추가: } | |
| 152 | 추가: } | |
| 153 | 추가: }); | |
| 154 | 추가: let mut events = Vec::new(); | |
| 155 | 추가: loop { | |
| 156 | 추가: let Some((job, _, event)) = receive | |
| 157 | 추가: .recv_timeout(Duration::from_secs(15)) | |
| 158 | 추가: .expect("worker response timeout") | |
| 159 | 추가: .unwrap() | |
| 160 | 추가: else { | |
| 161 | 추가: break; | |
| 162 | 추가: }; | |
| 163 | 추가: assert_eq!(job, 17); | |
| 164 | 추가: if let Some(commands) = respond(&event) { | |
| 165 | 추가: if commands.is_empty() { | |
| 166 | 추가: writer = None; | |
| 167 | 추가: } else { | |
| 168 | 추가: for command in commands { | |
| 169 | 추가: writer.as_mut().unwrap().send(&command).unwrap(); | |
| 170 | 추가: } | |
| 171 | 추가: } | |
| 172 | 추가: } | |
| 173 | 추가: let done = matches!(event, Message::Terminal(_)); | |
| 174 | 추가: events.push(event); | |
| 175 | 추가: if done { | |
| 176 | 추가: writer = None; | |
| 177 | 추가: } | |
| 178 | 추가: } | |
| 179 | 추가: assert!(child.0.wait().unwrap().success(), "{events:?}"); | |
| 180 | 추가: reader.join().unwrap(); | |
| 181 | 추가: assert!(errors.join().unwrap().is_empty()); | |
| 182 | 추가: assert!(matches!(events.last(), Some(Message::Terminal(_)))); | |
| 183 | 추가: events | |
| 184 | 추가: } | |
| 185 | 추가: fn choose(s: &Scratch, choice: ConflictChoice, apply: bool) -> Vec<Message> { | |
| 186 | 추가: run(s, request(s), None, vec![], |event| match event { | |
| 187 | 추가: Message::ConflictRequired { challenge_id, .. } => { | |
| 188 | 추가: Some(vec![reply(*challenge_id, choice, apply)]) | |
| 189 | 추가: } | |
| 190 | 추가: _ => None, | |
| 191 | 추가: }) | |
| 192 | 추가: } | |
| 193 | 추가: fn count(events: &[Message], predicate: impl Fn(&Message) -> bool) -> usize { | |
| 194 | 추가: events.iter().filter(|event| predicate(event)).count() | |
| 195 | 추가: } | |
| 196 | 추가: fn questions(events: &[Message]) -> usize { | |
| 197 | 추가: count(events, |e| matches!(e, Message::ConflictRequired { .. })) | |
| 198 | 추가: } | |
| 199 | 추가: fn created(events: &[Message]) -> usize { | |
| 200 | 추가: count(events, |e| { | |
| 201 | 추가: matches!( | |
| 202 | 추가: e, | |
| 203 | 추가: Message::Output { | |
| 204 | 추가: disposition: Disposition::Created, | |
| 205 | 추가: .. | |
| 206 | 추가: } | |
| 207 | 추가: ) | |
| 208 | 추가: }) | |
| 209 | 추가: } | |
| 210 | 추가: fn hash(path: &std::path::Path) -> Vec<u8> { | |
| 211 | 추가: Sha256::digest(fs::read(path).unwrap()).to_vec() | |
| 212 | 추가: } | |
| 213 | 추가: | |
| 214 | 추가: #[test] | |
| 215 | 추가: fn three_choices_and_apply_remaining_report_every_entry() { | |
| 216 | 추가: for choice in [ | |
| 217 | 추가: ConflictChoice::Overwrite, | |
| 218 | 추가: ConflictChoice::Skip, | |
| 219 | 추가: ConflictChoice::Rename, | |
| 220 | 추가: ] { | |
| 221 | 추가: for apply in [false, true] { | |
| 222 | 추가: let s = Scratch::new(); | |
| 223 | 추가: fixture(&s, &["a.txt", "b.txt"]); | |
| 224 | 추가: let before = hash(&s.0.join("output/a.txt")); | |
| 225 | 추가: let events = choose(&s, choice, apply); | |
| 226 | 추가: let t = terminal(&events); | |
| 227 | 추가: assert_eq!(t.outcome, Outcome::Completed, "{events:?}"); | |
| 228 | 추가: assert_eq!(questions(&events), if apply { 1 } else { 2 }); | |
| 229 | 추가: assert_eq!( | |
| 230 | 추가: count(&events, |e| matches!(e, Message::ConflictResolved { .. })), | |
| 231 | 추가: 2 | |
| 232 | 추가: ); | |
| 233 | 추가: for name in ["a", "b"] { | |
| 234 | 추가: let original = s.0.join(format!("output/{name}.txt")); | |
| 235 | 추가: if choice == ConflictChoice::Overwrite { | |
| 236 | 추가: assert_eq!(fs::read(original).unwrap(), PAYLOAD); | |
| 237 | 추가: } else { | |
| 238 | 추가: assert_eq!(hash(&original), before); | |
| 239 | 추가: } | |
| 240 | 추가: if choice == ConflictChoice::Rename { | |
| 241 | 추가: assert_eq!( | |
| 242 | 추가: fs::read(s.0.join(format!("output/{name} (1).txt"))).unwrap(), | |
| 243 | 추가: PAYLOAD | |
| 244 | 추가: ); | |
| 245 | 추가: } | |
| 246 | 추가: } | |
| 247 | 추가: let skipped = choice == ConflictChoice::Skip; | |
| 248 | 추가: assert_eq!(t.created_count, if skipped { 0 } else { 2 }); | |
| 249 | 추가: assert_eq!(created(&events), t.created_count as usize); | |
| 250 | 추가: assert_eq!( | |
| 251 | 추가: t.publication, | |
| 252 | 추가: if skipped { | |
| 253 | 추가: Publication::None | |
| 254 | 추가: } else { | |
| 255 | 추가: Publication::Complete | |
| 256 | 추가: } | |
| 257 | 추가: ); | |
| 258 | 추가: assert_eq!(t.cleanup, Cleanup::Complete); | |
| 259 | 추가: if skipped { | |
| 260 | 추가: assert_eq!(t.durability, Durability::NotApplicable); | |
| 261 | 추가: } | |
| 262 | 추가: assert_eq!( | |
| 263 | 추가: fs::read_dir(s.0.join("output")).unwrap().count(), | |
| 264 | 추가: if choice == ConflictChoice::Rename { | |
| 265 | 추가: 4 | |
| 266 | 추가: } else { | |
| 267 | 추가: 2 | |
| 268 | 추가: } | |
| 269 | 추가: ); | |
| 270 | 추가: } | |
| 271 | 추가: } | |
| 272 | 추가: } | |
| 273 | 추가: #[test] | |
| 274 | 추가: fn rename_avoids_existing_names_and_later_archive_paths() { | |
| 275 | 추가: let s = Scratch::new(); | |
| 276 | 추가: fixture(&s, &["폴더/자료.txt", "폴더/자료 (1).txt"]); | |
| 277 | 추가: fs::write(s.0.join("output/폴더/자료 (2).txt"), b"keep").unwrap(); | |
| 278 | 추가: let events = choose(&s, ConflictChoice::Rename, true); | |
| 279 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 280 | 추가: assert_eq!( | |
| 281 | 추가: fs::read(s.0.join("output/폴더/자료 (3).txt")).unwrap(), | |
| 282 | 추가: PAYLOAD | |
| 283 | 추가: ); | |
| 284 | 추가: assert_eq!( | |
| 285 | 추가: fs::read(s.0.join("output/폴더/자료 (1) (1).txt")).unwrap(), | |
| 286 | 추가: PAYLOAD | |
| 287 | 추가: ); | |
| 288 | 추가: assert_eq!( | |
| 289 | 추가: fs::read(s.0.join("output/폴더/자료 (2).txt")).unwrap(), | |
| 290 | 추가: b"keep" | |
| 291 | 추가: ); | |
| 292 | 추가: } | |
| 293 | 추가: #[test] | |
| 294 | 추가: fn mixed_choices_and_non_conflicting_files() { | |
| 295 | 추가: let s = Scratch::new(); | |
| 296 | 추가: fixture(&s, &["a", "b", "c", "new"]); | |
| 297 | 추가: fs::remove_file(s.0.join("output/new")).unwrap(); | |
| 298 | 추가: let mut index = 0; | |
| 299 | 추가: let events = run(&s, request(&s), None, vec![], |event| match event { | |
| 300 | 추가: Message::ConflictRequired { | |
| 301 | 추가: challenge_id, | |
| 302 | 추가: incoming_size, | |
| 303 | 추가: existing_size, | |
| 304 | 추가: .. | |
| 305 | 추가: } => { | |
| 306 | 추가: assert_eq!(*incoming_size, PAYLOAD.len() as u64); | |
| 307 | 추가: assert_eq!(*existing_size, 8); | |
| 308 | 추가: let choice = [ | |
| 309 | 추가: ConflictChoice::Overwrite, | |
| 310 | 추가: ConflictChoice::Skip, | |
| 311 | 추가: ConflictChoice::Rename, | |
| 312 | 추가: ][index]; | |
| 313 | 추가: index += 1; | |
| 314 | 추가: Some(vec![reply(*challenge_id, choice, false)]) | |
| 315 | 추가: } | |
| 316 | 추가: _ => None, | |
| 317 | 추가: }); | |
| 318 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 319 | 추가: assert_eq!(terminal(&events).created_count, 3); | |
| 320 | 추가: assert_eq!(fs::read(s.0.join("output/a")).unwrap(), PAYLOAD); | |
| 321 | 추가: assert_eq!(fs::read(s.0.join("output/b")).unwrap(), b"original"); | |
| 322 | 추가: assert_eq!(fs::read(s.0.join("output/c (1)")).unwrap(), PAYLOAD); | |
| 323 | 추가: assert_eq!(fs::read(s.0.join("output/new")).unwrap(), PAYLOAD); | |
| 324 | 추가: } | |
| 325 | 추가: #[test] | |
| 326 | 추가: fn cancel_waiting_for_choice_preserves_originals() { | |
| 327 | 추가: let s = Scratch::new(); | |
| 328 | 추가: fixture(&s, &["a"]); | |
| 329 | 추가: let before = hash(&s.0.join("output/a")); | |
| 330 | 추가: let events = run(&s, request(&s), None, vec![], |e| { | |
| 331 | 추가: matches!(e, Message::ConflictRequired { .. }).then(|| vec![Message::Cancel]) | |
| 332 | 추가: }); | |
| 333 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}"); | |
| 334 | 추가: assert_eq!(terminal(&events).publication, Publication::None); | |
| 335 | 추가: assert_eq!(created(&events), 0); | |
| 336 | 추가: assert_eq!(hash(&s.0.join("output/a")), before); | |
| 337 | 추가: assert!(events.iter().any(|e| matches!( | |
| 338 | 추가: e, | |
| 339 | 추가: Message::CancelAck { | |
| 340 | 추가: status: CancelStatus::Requested, | |
| 341 | 추가: .. | |
| 342 | 추가: } | |
| 343 | 추가: ))); | |
| 344 | 추가: } | |
| 345 | 추가: #[test] | |
| 346 | 추가: fn cancellation_keeps_earlier_replacement() { | |
| 347 | 추가: let s = Scratch::new(); | |
| 348 | 추가: fixture(&s, &["a", "b"]); | |
| 349 | 추가: let events = run(&s, request(&s), None, vec![], |e| match e { | |
| 350 | 추가: Message::ConflictRequired { | |
| 351 | 추가: challenge_id, | |
| 352 | 추가: entry_id: 0, | |
| 353 | 추가: .. | |
| 354 | 추가: } => Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)]), | |
| 355 | 추가: Message::ConflictRequired { .. } => Some(vec![Message::Cancel]), | |
| 356 | 추가: _ => None, | |
| 357 | 추가: }); | |
| 358 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}"); | |
| 359 | 추가: assert_eq!(terminal(&events).publication, Publication::Partial); | |
| 360 | 추가: assert_eq!(terminal(&events).created_count, 1); | |
| 361 | 추가: assert_eq!(fs::read(s.0.join("output/a")).unwrap(), PAYLOAD); | |
| 362 | 추가: assert_eq!(fs::read(s.0.join("output/b")).unwrap(), b"original"); | |
| 363 | 추가: } | |
| 364 | 추가: #[test] | |
| 365 | 추가: fn eof_stale_duplicate_and_wrong_kind_replies_fail_protocol() { | |
| 366 | 추가: for mode in 0..4 { | |
| 367 | 추가: let s = Scratch::new(); | |
| 368 | 추가: fixture(&s, &["a", "b"]); | |
| 369 | 추가: let events = run(&s, request(&s), None, vec![], |e| match e { | |
| 370 | 추가: Message::ConflictRequired { challenge_id, .. } => Some(match mode { | |
| 371 | 추가: 0 => vec![], | |
| 372 | 추가: 1 => vec![reply(challenge_id + 1, ConflictChoice::Skip, false)], | |
| 373 | 추가: 2 => vec![ | |
| 374 | 추가: reply(*challenge_id, ConflictChoice::Skip, false), | |
| 375 | 추가: reply(*challenge_id, ConflictChoice::Skip, false), | |
| 376 | 추가: ], | |
| 377 | 추가: _ => vec![Message::Password { | |
| 378 | 추가: challenge_id: *challenge_id, | |
| 379 | 추가: secret: Secret(vec![]), | |
| 380 | 추가: }], | |
| 381 | 추가: }), | |
| 382 | 추가: _ => None, | |
| 383 | 추가: }); | |
| 384 | 추가: assert_eq!( | |
| 385 | 추가: terminal(&events).error, | |
| 386 | 추가: ErrorCode::Protocol, | |
| 387 | 추가: "{mode}: {events:?}" | |
| 388 | 추가: ); | |
| 389 | 추가: assert_eq!(created(&events), 0); | |
| 390 | 추가: } | |
| 391 | 추가: } | |
| 392 | 추가: #[test] | |
| 393 | 추가: fn premature_reply_is_rejected() { | |
| 394 | 추가: let s = Scratch::new(); | |
| 395 | 추가: fixture(&s, &["a"]); | |
| 396 | 추가: let events = run( | |
| 397 | 추가: &s, | |
| 398 | 추가: request(&s), | |
| 399 | 추가: None, | |
| 400 | 추가: vec![reply(999, ConflictChoice::Skip, true)], | |
| 401 | 추가: |_| None, | |
| 402 | 추가: ); | |
| 403 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Protocol, "{events:?}"); | |
| 404 | 추가: assert_eq!(created(&events), 0); | |
| 405 | 추가: } | |
| 406 | 추가: #[test] | |
| 407 | 추가: fn password_and_conflict_share_distinct_challenges() { | |
| 408 | 추가: let s = Scratch::new(); | |
| 409 | 추가: fs::write(s.0.join("input"), AES_ZIP).unwrap(); | |
| 410 | 추가: directory(&s, "output"); | |
| 411 | 추가: fs::write(s.0.join("output/payload.bin"), b"original").unwrap(); | |
| 412 | 추가: let mut password_id = None; | |
| 413 | 추가: let events = run(&s, request(&s), None, vec![], |e| match e { | |
| 414 | 추가: Message::PasswordRequired { challenge_id, .. } => { | |
| 415 | 추가: password_id = Some(*challenge_id); | |
| 416 | 추가: Some(password_reply(*challenge_id, TEST_PASSWORD)) | |
| 417 | 추가: } | |
| 418 | 추가: Message::ConflictRequired { challenge_id, .. } => { | |
| 419 | 추가: assert_ne!(Some(*challenge_id), password_id); | |
| 420 | 추가: Some(vec![reply(*challenge_id, ConflictChoice::Skip, false)]) | |
| 421 | 추가: } | |
| 422 | 추가: _ => None, | |
| 423 | 추가: }); | |
| 424 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 425 | 추가: assert_eq!(questions(&events), 1); | |
| 426 | 추가: assert_eq!(created(&events), 0); | |
| 427 | 추가: } | |
| 428 | 추가: #[test] | |
| 429 | 추가: fn legacy_start_still_aborts_and_policy_does_not_cross_jobs() { | |
| 430 | 추가: let s = Scratch::new(); | |
| 431 | 추가: fixture(&s, &["a", "b"]); | |
| 432 | 추가: assert_eq!(terminal(&execute(request(&s))).error, ErrorCode::Conflict); | |
| 433 | 추가: assert_eq!(questions(&choose(&s, ConflictChoice::Skip, true)), 1); | |
| 434 | 추가: assert_eq!(questions(&choose(&s, ConflictChoice::Skip, false)), 2); | |
| 435 | 추가: } | |
| 436 | 추가: #[test] | |
| 437 | 추가: fn corruption_is_rejected_before_any_question_or_output() { | |
| 438 | 추가: let s = Scratch::new(); | |
| 439 | 추가: fixture(&s, &["a"]); | |
| 440 | 추가: let mut bytes = fs::read(s.0.join("input")).unwrap(); | |
| 441 | 추가: let at = bytes | |
| 442 | 추가: .windows(PAYLOAD.len()) | |
| 443 | 추가: .position(|b| b == PAYLOAD) | |
| 444 | 추가: .unwrap(); | |
| 445 | 추가: bytes[at] ^= 1; | |
| 446 | 추가: fs::write(s.0.join("input"), bytes).unwrap(); | |
| 447 | 추가: let events = run(&s, request(&s), None, vec![], |_| None); | |
| 448 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Integrity, "{events:?}"); | |
| 449 | 추가: assert_eq!(questions(&events), 0); | |
| 450 | 추가: assert_eq!(created(&events), 0); | |
| 451 | 추가: } | |
| 452 | 추가: #[test] | |
| 453 | 추가: fn raw_gzip_conflicts_use_explicit_name() { | |
| 454 | 추가: let s = Scratch::new(); | |
| 455 | 추가: fixture(&s, &["chosen.txt"]); | |
| 456 | 추가: fs::write(s.0.join("input"), include_bytes!("fixtures/sample.gz")).unwrap(); | |
| 457 | 추가: let mut start = request(&s); | |
| 458 | 추가: if let Action::Extract { | |
| 459 | 추가: gzip_output_name, .. | |
| 460 | 추가: } = &mut start.action | |
| 461 | 추가: { | |
| 462 | 추가: *gzip_output_name = Some("chosen.txt".into()); | |
| 463 | 추가: } | |
| 464 | 추가: let events = run(&s, start, None, vec![], |e| match e { | |
| 465 | 추가: Message::ConflictRequired { | |
| 466 | 추가: challenge_id, | |
| 467 | 추가: relative_name, | |
| 468 | 추가: .. | |
| 469 | 추가: } => { | |
| 470 | 추가: assert_eq!(relative_name, "chosen.txt"); | |
| 471 | 추가: Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)]) | |
| 472 | 추가: } | |
| 473 | 추가: _ => None, | |
| 474 | 추가: }); | |
| 475 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 476 | 추가: assert_eq!(fs::read(s.0.join("output/chosen.txt")).unwrap(), PAYLOAD); | |
| 477 | 추가: } | |
| 478 | 추가: #[test] | |
| 479 | 추가: fn file_directory_collisions_are_rejected_before_questions() { | |
| 480 | 추가: for path in ["a", "parent"] { | |
| 481 | 추가: let s = Scratch::new(); | |
| 482 | 추가: fixture(&s, &[if path == "a" { "a" } else { "parent/a" }]); | |
| 483 | 추가: let target = s.0.join("output").join(path); | |
| 484 | 추가: if path == "a" { | |
| 485 | 추가: fs::remove_file(&target).unwrap(); | |
| 486 | 추가: fs::create_dir(&target).unwrap(); | |
| 487 | 추가: } else { | |
| 488 | 추가: fs::remove_dir_all(&target).unwrap(); | |
| 489 | 추가: fs::write(&target, b"keep").unwrap(); | |
| 490 | 추가: } | |
| 491 | 추가: let events = run(&s, request(&s), None, vec![], |_| None); | |
| 492 | 추가: assert_eq!(terminal(&events).error, ErrorCode::UnsafePath, "{events:?}"); | |
| 493 | 추가: assert_eq!(questions(&events), 0); | |
| 494 | 추가: assert_eq!(created(&events), 0); | |
| 495 | 추가: } | |
| 496 | 추가: } | |
| 497 | 추가: #[test] | |
| 498 | 추가: fn newly_created_empty_directory_is_counted_when_files_are_skipped() { | |
| 499 | 추가: let s = Scratch::new(); | |
| 500 | 추가: directory(&s, "empty"); | |
| 501 | 추가: fs::write(s.0.join("source"), PAYLOAD).unwrap(); | |
| 502 | 추가: let events = execute(Start { | |
| 503 | 추가: action: Action::CreateZip { | |
| 504 | 추가: sources: vec![ | |
| 505 | 추가: Source { | |
| 506 | 추가: path: s.path("source"), | |
| 507 | 추가: archive_name: "a".into(), | |
| 508 | 추가: }, | |
| 509 | 추가: Source { | |
| 510 | 추가: path: s.path("empty"), | |
| 511 | 추가: archive_name: "empty".into(), | |
| 512 | 추가: }, | |
| 513 | 추가: ], | |
| 514 | 추가: output_file: s.path("input"), | |
| 515 | 추가: method: Method::Store, | |
| 516 | 추가: encryption: Encryption::None, | |
| 517 | 추가: }, | |
| 518 | 추가: limits: Limits::default(), | |
| 519 | 추가: }); | |
| 520 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 521 | 추가: directory(&s, "output"); | |
| 522 | 추가: fs::write(s.0.join("output/a"), b"original").unwrap(); | |
| 523 | 추가: let events = choose(&s, ConflictChoice::Skip, true); | |
| 524 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 525 | 추가: assert_eq!(terminal(&events).publication, Publication::Complete); | |
| 526 | 추가: assert_eq!(terminal(&events).created_count, 1); | |
| 527 | 추가: assert_eq!(created(&events), 1); | |
| 528 | 추가: assert!(s.0.join("output/empty").is_dir()); | |
| 529 | 추가: } | |
| 530 | 추가: | |
| 531 | 추가: #[cfg(target_os = "linux")] | |
| 532 | 추가: #[test] | |
| 533 | 추가: fn links_and_special_entries_are_not_interactive() { | |
| 534 | 추가: use std::os::unix::{fs::symlink, net::UnixListener}; | |
| 535 | 추가: for mode in 0..3 { | |
| 536 | 추가: let s = Scratch::new(); | |
| 537 | 추가: fixture(&s, &["a"]); | |
| 538 | 추가: fs::remove_file(s.0.join("output/a")).unwrap(); | |
| 539 | 추가: fs::write(s.0.join("outside"), b"keep").unwrap(); | |
| 540 | 추가: let listener; | |
| 541 | 추가: match mode { | |
| 542 | 추가: 0 => symlink(s.0.join("outside"), s.0.join("output/a")).unwrap(), | |
| 543 | 추가: 1 => symlink(s.0.join("missing"), s.0.join("output/a")).unwrap(), | |
| 544 | 추가: _ => { | |
| 545 | 추가: listener = UnixListener::bind(s.0.join("output/a")).unwrap(); | |
| 546 | 추가: let _ = &listener; | |
| 547 | 추가: } | |
| 548 | 추가: } | |
| 549 | 추가: let events = run(&s, request(&s), None, vec![], |_| None); | |
| 550 | 추가: assert_eq!(terminal(&events).error, ErrorCode::UnsafePath, "{events:?}"); | |
| 551 | 추가: assert_eq!(questions(&events), 0); | |
| 552 | 추가: assert_eq!(fs::read(s.0.join("outside")).unwrap(), b"keep"); | |
| 553 | 추가: } | |
| 554 | 추가: } | |
| 555 | 추가: #[cfg(target_os = "linux")] | |
| 556 | 추가: #[test] | |
| 557 | 추가: fn pre_replacement_failures_preserve_original_hash_and_remove_temps() { | |
| 558 | 추가: for mode in [ | |
| 559 | 추가: "create-full", | |
| 560 | 추가: "full", | |
| 561 | 추가: "sync-full", | |
| 562 | 추가: "write-io", | |
| 563 | 추가: "replace-fail", | |
| 564 | 추가: ] { | |
| 565 | 추가: let s = Scratch::new(); | |
| 566 | 추가: fixture(&s, &["a"]); | |
| 567 | 추가: let before = hash(&s.0.join("output/a")); | |
| 568 | 추가: let events = run(&s, request(&s), Some(mode), vec![], |e| match e { | |
| 569 | 추가: Message::ConflictRequired { challenge_id, .. } => { | |
| 570 | 추가: Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)]) | |
| 571 | 추가: } | |
| 572 | 추가: _ => None, | |
| 573 | 추가: }); | |
| 574 | 추가: assert_eq!( | |
| 575 | 추가: terminal(&events).outcome, | |
| 576 | 추가: Outcome::Failed, | |
| 577 | 추가: "{mode}: {events:?}" | |
| 578 | 추가: ); | |
| 579 | 추가: assert_eq!(created(&events), 0); | |
| 580 | 추가: assert_eq!(hash(&s.0.join("output/a")), before); | |
| 581 | 추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete); | |
| 582 | 추가: assert_eq!(terminal(&events).retained_partial_count, 0); | |
| 583 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1); | |
| 584 | 추가: } | |
| 585 | 추가: } | |
| 586 | 추가: #[cfg(target_os = "linux")] | |
| 587 | 추가: #[test] | |
| 588 | 추가: fn changed_target_is_not_replaced() { | |
| 589 | 추가: let s = Scratch::new(); | |
| 590 | 추가: fixture(&s, &["a"]); | |
| 591 | 추가: let events = run(&s, request(&s), None, vec![], |e| match e { | |
| 592 | 추가: Message::ConflictRequired { challenge_id, .. } => { | |
| 593 | 추가: fs::write(s.0.join("output/a"), b"changed by user").unwrap(); | |
| 594 | 추가: Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)]) | |
| 595 | 추가: } | |
| 596 | 추가: _ => None, | |
| 597 | 추가: }); | |
| 598 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Conflict, "{events:?}"); | |
| 599 | 추가: assert_eq!(created(&events), 0); | |
| 600 | 추가: assert_eq!(fs::read(s.0.join("output/a")).unwrap(), b"changed by user"); | |
| 601 | 추가: } | |
| 602 | 추가: #[cfg(target_os = "linux")] | |
| 603 | 추가: #[test] | |
| 604 | 추가: fn cancel_during_temporary_write_preserves_original_hash() { | |
| 605 | 추가: let s = Scratch::new(); | |
| 606 | 추가: fixture(&s, &["a"]); | |
| 607 | 추가: let before = hash(&s.0.join("output/a")); | |
| 608 | 추가: let mut cancelled = false; | |
| 609 | 추가: let events = run(&s, request(&s), Some("pause"), vec![], |e| match e { | |
| 610 | 추가: Message::ConflictRequired { challenge_id, .. } => { | |
| 611 | 추가: Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)]) | |
| 612 | 추가: } | |
| 613 | 추가: Message::Progress { | |
| 614 | 추가: stage: Stage::Write, | |
| 615 | 추가: .. | |
| 616 | 추가: } if !cancelled => { | |
| 617 | 추가: let deadline = Instant::now() + Duration::from_secs(5); | |
| 618 | 추가: while !s.0.join("paused").exists() { | |
| 619 | 추가: assert!(Instant::now() < deadline); | |
| 620 | 추가: std::thread::sleep(Duration::from_millis(5)); | |
| 621 | 추가: } | |
| 622 | 추가: cancelled = true; | |
| 623 | 추가: Some(vec![Message::Cancel]) | |
| 624 | 추가: } | |
| 625 | 추가: Message::CancelAck { | |
| 626 | 추가: status: CancelStatus::Requested, | |
| 627 | 추가: .. | |
| 628 | 추가: } => { | |
| 629 | 추가: fs::write(s.0.join("release"), []).unwrap(); | |
| 630 | 추가: None | |
| 631 | 추가: } | |
| 632 | 추가: _ => None, | |
| 633 | 추가: }); | |
| 634 | 추가: assert!(cancelled); | |
| 635 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}"); | |
| 636 | 추가: assert_eq!(hash(&s.0.join("output/a")), before); | |
| 637 | 추가: assert_eq!(created(&events), 0); | |
| 638 | 추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete); | |
| 639 | 추가: } | |
| 640 | 추가: #[cfg(target_os = "linux")] | |
| 641 | 추가: #[test] | |
| 642 | 추가: fn post_replacement_sync_error_reports_actual_publication() { | |
| 643 | 추가: let s = Scratch::new(); | |
| 644 | 추가: fixture(&s, &["a"]); | |
| 645 | 추가: let events = run( | |
| 646 | 추가: &s, | |
| 647 | 추가: request(&s), | |
| 648 | 추가: Some("dir-sync-full"), | |
| 649 | 추가: vec![], | |
| 650 | 추가: |e| match e { | |
| 651 | 추가: Message::ConflictRequired { challenge_id, .. } => { | |
| 652 | 추가: Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)]) | |
| 653 | 추가: } | |
| 654 | 추가: _ => None, | |
| 655 | 추가: }, | |
| 656 | 추가: ); | |
| 657 | 추가: assert_eq!(terminal(&events).error, ErrorCode::DiskFull, "{events:?}"); | |
| 658 | 추가: assert_eq!(terminal(&events).publication, Publication::Partial); | |
| 659 | 추가: assert_eq!(terminal(&events).created_count, 1); | |
| 660 | 추가: assert_eq!(terminal(&events).durability, Durability::Failed); | |
| 661 | 추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete); | |
| 662 | 추가: assert_eq!(fs::read(s.0.join("output/a")).unwrap(), PAYLOAD); | |
| 663 | 추가: assert_eq!(created(&events), 1); | |
| 664 | 추가: } | |
| 665 | 추가: | |
| 666 | 추가: #[test] | |
| 667 | 추가: fn rename_handles_maximum_utf8_filename_length() { | |
| 668 | 추가: let s = Scratch::new(); | |
| 669 | 추가: let name = format!("{}ab.txt", "가".repeat(83)); | |
| 670 | 추가: fixture(&s, &[&name]); | |
| 671 | 추가: let events = choose(&s, ConflictChoice::Rename, false); | |
| 672 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 673 | 추가: let renamed = events | |
| 674 | 추가: .iter() | |
| 675 | 추가: .find_map(|event| match event { | |
| 676 | 추가: Message::ConflictResolved { | |
| 677 | 추가: relative_name, | |
| 678 | 추가: choice: ConflictChoice::Rename, | |
| 679 | 추가: .. | |
| 680 | 추가: } => Some(relative_name), | |
| 681 | 추가: _ => None, | |
| 682 | 추가: }) | |
| 683 | 추가: .unwrap(); | |
| 684 | 추가: assert!(renamed.len() <= 255); | |
| 685 | 추가: assert!(renamed.ends_with(" (1).txt")); | |
| 686 | 추가: assert_eq!(fs::read(s.0.join("output").join(renamed)).unwrap(), PAYLOAD); | |
| 687 | 추가: assert_eq!( | |
| 688 | 추가: fs::read(s.0.join("output").join(name)).unwrap(), | |
| 689 | 추가: b"original" | |
| 690 | 추가: ); | |
| 691 | 추가: } | |
| 692 | 추가: #[cfg(target_os = "linux")] | |
| 693 | 추가: #[test] | |
| 694 | 추가: fn overwrite_does_not_modify_other_hard_links() { | |
| 695 | 추가: let s = Scratch::new(); | |
| 696 | 추가: fixture(&s, &["a"]); | |
| 697 | 추가: fs::hard_link(s.0.join("output/a"), s.0.join("outside")).unwrap(); | |
| 698 | 추가: let events = choose(&s, ConflictChoice::Overwrite, false); | |
| 699 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 700 | 추가: assert_eq!(fs::read(s.0.join("output/a")).unwrap(), PAYLOAD); | |
| 701 | 추가: assert_eq!(fs::read(s.0.join("outside")).unwrap(), b"original"); | |
| 702 | 추가: } |
| @@ -136,3 +136,10 @@ int fsync(int fd) { | ||
| 136 | 136 | } |
| 137 | 137 | return real_fsync(fd); |
| 138 | 138 | } |
| 139 | 추가: | |
| 140 | 추가: int renameat(int oldfd, const char *oldname, int newfd, const char *newname) { | |
| 141 | 추가: const char *fault = getenv("ZIPELO_TEST_FAULT"); | |
| 142 | 추가: if (fault && !strcmp(fault, "replace-fail")) { errno = EIO; return -1; } | |
| 143 | 추가: int (*real_renameat)(int, const char *, int, const char *) = dlsym(RTLD_NEXT, "renameat"); | |
| 144 | 추가: return real_renameat(oldfd, oldname, newfd, newname); | |
| 145 | 추가: } |
| @@ -1611,3 +1611,5 @@ mod folder_inputs; | ||
| 1611 | 1611 | mod zip_names; |
| 1612 | 1612 | |
| 1613 | 1613 | mod conflict_wire; |
| 1614 | 추가: | |
| 1615 | 추가: mod conflicts; |