team-ljyzipelo

공개

충돌 작업자를 연동하고 실제 파일 흐름을 검증함

작성자
호시노 히나타
작성 시각
커밋
7b7e617779a2dce391121b5b6b56da4af51b6337
이 시점의 파일 보기

변경된 파일 15개

+1,340-68
수정docs/ui-scenario-guide.md+2-1
@@ -96,10 +96,11 @@ python3 tests/ci/run_rust.py local
9696
9797## 파일 충돌 선택과 결과
9898
99추가: - gzip-conflict-choice: 단일 GZ 파일의 충돌 선택 창. 저장 창에서 고른 이름과 세 선택을 확인한다.
99100- conflict-choice: 파일 경로와 기존 크기, 새 크기 및 덮어쓰기, 건너뛰기, 이름 바꿔 저장을 확인합니다. Tab으로 이동하고 Space로 선택할 수 있으며 Escape 또는 작업 취소는 전체 작업을 취소합니다.
100101- conflict-apply: "나머지 파일에도 같게 적용"이 켜진 상태입니다. 현재 작업의 남은 일반 파일 충돌에만 적용하며 이름 바꿔 저장은 같은 폴더에 번호를 붙입니다.
101102- extract-skipped: 모든 파일을 건너뛴 정상 완료입니다. 생성된 파일이 없으며 저장 실패 경고가 없어야 합니다.
102103- extract-renamed: 실제 저장된 새 이름을 표시합니다. 이름 변경 결과만으로 저장 성공을 판정하지 않고 별도의 생성 보고와 완료 집계가 일치해야 합니다.
103104- extract-rename-failed: 새 이름을 정한 뒤 실제 생성 보고 없이 I/O 오류가 난 결과입니다. 실패 원인과 "아무 파일도 풀지 않았습니다"를 표시하고 "이름 바꿔 저장" 완료 안내는 표시하지 않아야 합니다. 일부 파일이 저장된 뒤 실패한 경우에도 생성 보고가 있는 이름만 저장 완료로 표시합니다.
104105
105삭제: 현재 충돌 화면과 클라이언트 연동은 준비 단계입니다. 작업자 런타임이 완성되기 전에는 실제 추출 요청을 기존 Start로 유지하며 StartInteractive를 보내지 않습니다. 위 명령은 실제 파일을 쓰지 않는 개발용 화면 미리보기입니다.
106추가: 실제 추출은 revision 3의 StartInteractive를 보내며 ZIP, 7z, TAR 계열과 단일 GZ의 파일 충돌에 같은 선택 창을 사용합니다. 목록 읽기와 ZIP 만들기는 기존 Start를 유지합니다. 위 명령은 실제 파일을 쓰지 않는 개발용 화면 미리보기입니다. 파일 기반 버튼 연동은 tests/rust-app-real-worker/conflict_flows.rs에서 확인하며, 운영체제별 실제 창 확인은 별도입니다.
수정experiments/rust-archive-worker/README.md+9-5
@@ -1,6 +1,6 @@
11# Rust archive worker
22
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 생성을 지원합니다.
44
55- ZIP32/ZIP64 Store/Deflate 목록과 해제, ZIP32/ZIP64 생성, 기본 TAR/USTAR, GZ, TAR.GZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. 다중 볼륨, UTF-8로 해석할 수 없는 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다.
66- ZIP 이름: UTF-8 플래그(비트 11)가 있으면 이름이 UTF-8이어야 하며 아니면 Integrity입니다. 플래그가 없으면 CRC가 원래 이름과 맞는 Info-ZIP Unicode Path 확장 필드(0x7075, 버전 1)를 우선 쓰고, 다음으로 UTF-8로 유효한 이름 바이트를 그대로 씁니다(Linux/macOS 도구의 기본 동작). CRC가 다르거나 버전이 다른 확장 필드는 무시합니다. 그 밖의 CP437/CP949 등 레거시 이름은 코드 페이지를 추측하지 않고 UnsupportedFeature로 거부합니다. 어느 경로로 얻은 이름이든 같은 경로 안전성 검사와 충돌 검사를 거칩니다.
@@ -10,7 +10,7 @@
1010- ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다.
1111- 출력 폴더는 미리 존재해야 합니다. Linux는 소유 UID가 같고 group/other 쓰기가 없는 폴더만 허용합니다. openat/O_NOFOLLOW로 디렉터리를 고정하고 새 임시 파일을 배타적으로 만든 뒤 hard link로 게시합니다. 기존 파일과 링크를 덮어쓰지 않습니다. Windows는 reparse point를 거부하고 부모 디렉터리 핸들에서 delete sharing을 제한합니다.
1212- 파일 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 실기 검증은 아직 수행하지 않았습니다.
1414
1515## 스트리밍과 자원 정리
1616
@@ -68,15 +68,19 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도
6868
6969## revision 3 충돌 계약
7070
71삭제: 공용 타입과 codec만 준비된 단계입니다. 현재 실행 경로는 revision 2의 `Start`를 유지하며 `StartInteractive`는 아직 처리하지 않습니다. 충돌 런타임 구현과 앱 연동 검증이 끝나기 전에는 새 요청을 실제 기능에 활성화하지 않습니다. 이 상태는 덮어쓰기 기능의 구현 완료를 뜻하지 않습니다.
71추가: 작업자는 `StartInteractive`로 시작한 압축 해제에서 덮어쓰기, 건너뛰기와 이름 바꿔 저장을 처리합니다. 기존 `Start`는 이름 충돌 시 중단합니다. 앱의 활성화와 실제 UI 연동은 별도 PR에서 검증합니다.
7272
7373- `StartInteractive(Start)`는 kind 4이며 기존 Start body를 그대로 사용합니다. Extract만 허용하고 List와 CreateZip은 codec에서 거부합니다. 기존 Start=1의 충돌 시 중단 동작과 모든 기존 필드 및 tag는 유지하며 구버전 작업자로 자동 재시도하지 않습니다.
7474- `ConflictChoice`는 Overwrite=0, Skip=1, Rename=2입니다. `ConflictReply`(5)는 challenge_id u64, choice u8, apply_to_remaining bool 순서입니다.
7575- `ConflictRequired`(108)는 challenge_id u64, entry_id u32, relative_name String, incoming_size u64, existing_size u64 순서입니다. 일반 파일끼리의 충돌에 세 선택을 허용하며 폴더끼리는 합치고 파일과 폴더 충돌 및 링크는 차단합니다.
7676- `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초 제한에 대기 시간을 포함합니다.
7878- 전부 건너뛰고 새 출력도 없으면 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)입니다.
8084
8185## 검증과 의존성
8286
수정experiments/rust-archive-worker/contract.json+7-6
@@ -1,5 +1,5 @@
11{
2삭제: "status": "revision-3-codec-ready-runtime-pending",
2추가: "status": "revision-3-worker-implemented",
33 "version": 1,
44 "scope": "One job per separately spawned Rust worker; shared binary codec. Process separation is not an OS sandbox.",
55 "frame": {
@@ -29,7 +29,7 @@
2929 "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.",
3030 "Password": "Matching outstanding challenge_id:u64 and max1024 UTF-8 bytes; never log, Debug, echo or persist secrets.",
3131 "Cancel": "Matching header job_id and empty body; command header sequence identifies the request. See CancelAck. Request acceptance is separate from final outcome. EOF alone is not successful cancellation.",
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.",
3333 "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."
3434 },
3535 "events": {
@@ -96,7 +96,7 @@
9696 "87ff39f9-f7fe-4efc-bd2e-d73ab3246356"
9797 ],
9898 "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."
100100 },
101101 "list_identity": {
102102 "ListId": {
@@ -209,16 +209,17 @@
209209 "Rename": 2
210210 },
211211 "extract_conflicts": {
212삭제: "status": "codec-ready-runtime-pending",
212추가: "status": "worker-implemented",
213213 "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.",
214214 "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.",
215215 "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.",
217217 "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.",
218218 "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.",
219219 "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.",
220220 "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.",
221221 "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."
223224 }
224225}
수정experiments/rust-archive-worker/src/filesystem.rs+137-3
@@ -10,6 +10,32 @@ use std::sync::atomic::{AtomicU64, Ordering};
1010
1111type Result<T> = std::result::Result<T, ErrorCode>;
1212static 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추가: }
1339pub struct Snapshot {
1440 pub bytes: Vec<u8>,
1541 pub object: SourceObject,
@@ -163,6 +189,7 @@ mod platform {
163189 fn openat(fd: i32, path: *const i8, flags: i32, ...) -> i32;
164190 fn mkdirat(fd: i32, path: *const i8, mode: u32) -> i32;
165191 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;
166193 fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32;
167194 fn geteuid() -> u32;
168195 }
@@ -262,6 +289,31 @@ mod platform {
262289 Err(_) => Err(ErrorCode::Io),
263290 }
264291 }
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추가: }
265317 pub fn create(&self, n: &str) -> std::io::Result<File> {
266318 open(&self.file, std::ffi::OsStr::new(n), 1 | 0x40 | 0x80)
267319 }
@@ -377,6 +429,45 @@ mod platform {
377429 Err(_) => Err(ErrorCode::Io),
378430 }
379431 }
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추가: }
380471 pub fn create(&self, n: &str) -> std::io::Result<File> {
381472 OpenOptions::new()
382473 .write(true)
@@ -414,11 +505,30 @@ fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>>
414505 }
415506 Ok(Some((d, leaf.to_owned())))
416507}
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추가: }
417522pub 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<()> {
418526 for (name, kind) in names {
419527 if let Some((d, leaf)) = parent(root, name, false)? {
420528 if *kind == EntryKind::Directory {
421529 let _ = d.child(&leaf, false)?;
530추가: } else if interactive {
531추가: d.existing(&leaf)?;
422532 } else if !d.absent(&leaf)? {
423533 return Err(ErrorCode::Conflict);
424534 }
@@ -507,6 +617,16 @@ pub fn publish_reader(
507617 data: &mut impl Read,
508618 length: u64,
509619 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<()>,
510630) -> Published {
511631 let mut result = Published {
512632 created: false,
@@ -550,10 +670,24 @@ pub fn publish_reader(
550670 file.sync_all().map_err(crate::space::io_error)
551671 })();
552672 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;
554682 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 {
556689 Ok(()) => {
690추가: temp_consumed = replace.is_some();
557691 result.created = true;
558692 match dir.sync_checked() {
559693 Ok(durability) => result.durability = durability,
@@ -573,7 +707,7 @@ pub fn publish_reader(
573707 }
574708 }
575709 }
576삭제: if !dir.remove(&temp) {
710추가: if !temp_consumed && !dir.remove(&temp) {
577711 result.cleanup = Cleanup::Failed;
578712 result.retained = 1;
579713 result.retained_name = Some(match name.rsplit_once('/') {
수정experiments/rust-archive-worker/src/runtime.rs+162-13
@@ -12,12 +12,18 @@ use std::{
1212};
1313
1414type Result<T> = std::result::Result<T, ErrorCode>;
15추가: #[derive(PartialEq, Eq)]
16추가: enum Challenge {
17추가: Password(u64),
18추가: Conflict(u64),
19추가: }
1520struct State<W> {
1621 writer: Writer<W>,
1722 cancelled: bool,
1823 phase: u8,
1924 fault: Option<ErrorCode>,
20삭제: challenge: Option<u64>,
25추가: challenge: Option<Challenge>,
26추가: conflict_reply: Option<(ConflictChoice, bool)>,
2127 password: Option<Secret>,
2228 input_closed: bool,
2329}
@@ -25,6 +31,8 @@ struct Job<W> {
2531 state: Arc<Mutex<State<W>>>,
2632 wake: Arc<Condvar>,
2733 next_challenge: u64,
34추가: interactive: bool,
35추가: remaining_choice: Option<ConflictChoice>,
2836 started: Instant,
2937 terminal: Terminal,
3038 parent: crate::parent::Parent,
@@ -36,7 +44,7 @@ impl<W: Write> Job<W> {
3644 let id = self.next_challenge;
3745 let state_ref = Arc::clone(&self.state);
3846 let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?;
39삭제: state.challenge = Some(id);
47추가: state.challenge = Some(Challenge::Password(id));
4048 state
4149 .writer
4250 .send(&Message::PasswordRequired {
@@ -70,6 +78,87 @@ impl<W: Write> Job<W> {
7078 }
7179 }
7280
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추가: }
73162 fn event(&mut self, event: Message) -> Result<()> {
74163 let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
75164 state.writer.send(&event).map_err(|_| {
@@ -122,6 +211,7 @@ impl<W: Write> Job<W> {
122211 length: u64,
123212 id: Option<u32>,
124213 last: bool,
214추가: replace: Option<&filesystem::Existing>,
125215 ) -> Result<()> {
126216 self.check()?;
127217 self.progress(
@@ -130,7 +220,7 @@ impl<W: Write> Job<W> {
130220 Some(length),
131221 self.terminal.created_count as u32,
132222 )?;
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| {
134224 if commit && last {
135225 self.cutoff()
136226 } else {
@@ -366,8 +456,12 @@ impl<W: Write> Job<W> {
366456 .iter()
367457 .map(|m| (m.entry.name.clone(), EntryKind::File)),
368458 );
369삭제: filesystem::preflight(&root, &names)?;
459추가: filesystem::preflight_mode(&root, &names, self.interactive)?;
370460 filesystem::preflight_space(&root, &output_sizes, None)?;
461추가: let mut reserved = names
462추가: .iter()
463추가: .map(|(name, _)| name.to_lowercase())
464추가: .collect::<BTreeSet<_>>();
371465 for name in dirs {
372466 self.check()?;
373467 let (created, durability, sync_error) =
@@ -389,16 +483,45 @@ impl<W: Write> Job<W> {
389483 for (index, m) in files.iter().enumerate() {
390484 data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize]))
391485 .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추가: }
392512 self.output_reader(
393513 &root,
394삭제: &m.entry.name,
514추가: &name,
395515 &mut (&mut data).take(m.entry.size),
396516 m.entry.size,
397517 Some(m.entry.entry_id),
398518 index + 1 == files.len(),
519추가: replace,
399520 )?;
400521 }
401삭제: self.terminal.publication = Publication::Complete;
522추가: if !self.interactive || self.terminal.created_count != 0 {
523추가: self.terminal.publication = Publication::Complete;
524추가: }
402525 }
403526 }
404527 Action::CreateZip {
@@ -433,7 +556,7 @@ impl<W: Write> Job<W> {
433556 &mut || self.check(),
434557 )?;
435558 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)?;
437560 self.terminal.publication = Publication::Complete;
438561 }
439562 }
@@ -451,11 +574,15 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
451574 let (job, _, message) = reader
452575 .read()?
453576 .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추가: }
459586 };
460587 let state = Arc::new(Mutex::new(State {
461588 writer: Writer::new(output, job),
@@ -463,6 +590,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
463590 phase: 0,
464591 fault: None,
465592 challenge: None,
593추가: conflict_reply: None,
466594 password: None,
467595 input_closed: false,
468596 }));
@@ -494,7 +622,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
494622 secret,
495623 } => {
496624 if state.phase != 0
497삭제: || state.challenge != Some(challenge_id)
625추가: || state.challenge != Some(Challenge::Password(challenge_id))
498626 || state.password.is_some()
499627 {
500628 state.fault = Some(ErrorCode::Protocol);
@@ -506,6 +634,24 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
506634 }
507635 control_wake.notify_all();
508636 }
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추가: }
509655 Message::Cancel => {
510656 let status = match state.phase {
511657 2 => CancelStatus::Finished,
@@ -540,6 +686,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
540686 state: Arc::clone(&state),
541687 wake,
542688 next_challenge: 0,
689추가: interactive,
690추가: remaining_choice: None,
543691 parent,
544692 started: Instant::now(),
545693 terminal: Terminal {
@@ -568,6 +716,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
568716 state.phase = 2;
569717 state.challenge = None;
570718 state.password = None;
719추가: state.conflict_reply = None;
571720 if let Some(error) = state.fault.or(error) {
572721 context.terminal.error = error;
573722 context.terminal.outcome = if error == ErrorCode::None {
수정experiments/rust-ui-memory-app/src/archive_process.rs+5-1
@@ -500,7 +500,11 @@ impl ui::Connection for ProcessConnection {
500500 self.stop.store(true, Ordering::Release);
501501 "작업자 요청 상태 오류"
502502 })? = 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추가: }
504508 }
505509 ui::Command::ConflictReply {
506510 challenge_id,
추가tests/rust-app-real-worker/conflict_flows.rs+231-0
@@ -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추가: }
수정tests/rust-app-real-worker/flows.rs+6-1
@@ -304,12 +304,17 @@ mod screen {
304304 self.settle();
305305 assert_eq!(
306306 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추가: }
308312 );
309313 }
310314 }
311315 include!("password_flows.rs");
312316 include!("selection_flows.rs");
317추가: include!("conflict_flows.rs");
313318 include!("native_dialog_flows.rs");
314319
315320 fn archive_flow(name: &str, format: Format) {
수정tests/rust-app-real-worker/native_dialog_flows.rs+42-25
@@ -5,12 +5,13 @@ fn native_fixture(scratch: &Scratch, fixture: &str, name: &str) -> PathBuf {
55 .join("../../tests/rust-app-real-worker/fixtures")
66 .join(fixture),
77 &target,
8삭제: ).unwrap();
8추가: )
9추가: .unwrap();
910 target
1011}
1112
1213#[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() {
1415 use zipelo_ui_memory_app::archive_dialog::Purpose;
1516 let mut names = vec![".gz", "report.GZ", "report.Gz", "report.gz"];
1617 #[cfg(unix)]
@@ -23,41 +24,46 @@ fn raw_gzip_save_dialog_corrects_names_and_preserves_cancel_and_conflict_retry()
2324 let (factory, observed) = observed_factory();
2425 let mut screen = Screen::new(factory);
2526 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추가: );
2731 screen.click("압축해제");
2832 assert!(!screen.app.model.busy());
2933 assert_eq!(observed.borrow().jobs.len(), 1);
3034 let request = screen.dialogs.0.borrow().requests.last().unwrap().clone();
3135 assert_eq!(request.purpose, Purpose::SaveGzip);
3236 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추가: );
3445 let existing = output.join("기존 파일.txt");
3546 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()]));
3753 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");
5460 assert_eq!(fs::read(saved).unwrap(), b"Zipelo real worker flow\n");
5561 assert_eq!(fs::read(existing).unwrap(), b"preserve");
5662 assert_eq!(fs::read(&archive).unwrap(), original);
5763 assert!(matches!(
5864 observed.borrow().starts.last(),
5965 Some(Start::Extract { destination, gzip_output_name: Some(name), .. })
60삭제: if destination == &output && name == "사용자 이름.txt"
66추가: if destination == &output && name == "기존 파일.txt"
6167 ));
6268 assert_reaped(&observed);
6369 }
@@ -73,13 +79,24 @@ fn mixed_case_zip_names_open_and_extract_through_native_dialog_responses() {
7379 let output = make_directory(&scratch.path("output"));
7480 let (factory, observed) = observed_factory();
7581 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()]));
7788 screen.click("열기");
7889 screen.settle();
7990 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추가: );
8195 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추가: );
83100 assert_eq!(fs::read(archive).unwrap(), original);
84101 assert_reaped(&observed);
85102 }
수정tests/rust-app-ui/README.md+1-1
@@ -1,6 +1,6 @@
11# 앱 화면 흐름 시험
22
3삭제: 가짜 작업자는 합의된 계약의 의미를 따르는 프론트엔드 어댑터임. revision 3의 충돌 요청과 응답은 가짜 작업자로 검증하며 실제 StartInteractive 활성화와 파일 기반 통합 검증은 작업자 런타임 구현 후 진행함. 바이너리 codec, 실제 프로세스 실행, 파일 읽기와 쓰기, 암호 해독은 수행하지 않음. 실제 codec은 backend 소유이며 이 PR에서 중복 구현하지 않음.
3추가: 가짜 작업자는 합의된 계약의 의미를 따르는 프론트엔드 어댑터임. revision 3의 충돌 요청과 응답은 가짜 작업자로 검증함. 실제 StartInteractive와 화면 버튼의 파일 기반 통합 시험은 tests/rust-app-real-worker/conflict_flows.rs에서 별도로 실행함. 바이너리 codec, 실제 프로세스 실행, 파일 읽기와 쓰기, 암호 해독은 수행하지 않음. 실제 codec은 backend 소유이며 이 PR에서 중복 구현하지 않음.
44
55`python3 tests/ci/run_rust.py local`은 기존 시험과 새 `archive_ui` 시험을 all-features로 실행함. Windows 결과는 교차 빌드이며 Windows 실제 실행은 별도 확인해야 함.
66
수정tests/rust-app-ui/scenario_tests.rs+3-1
@@ -96,7 +96,9 @@ fn every_listed_scenario_draws_and_keeps_its_expected_screen() {
9696 );
9797 assert!(app.model.input_error.is_none(), "{}", scenario.name);
9898 let expected = match scenario.name {
99삭제: "conflict-choice" | "conflict-apply" => "나머지 파일에도 같게 적용",
99추가: "conflict-choice" | "conflict-apply" | "gzip-conflict-choice" => {
100추가: "나머지 파일에도 같게 적용"
101추가: }
100102 "extract-skipped" => "모든 파일을 건너뛰었습니다",
101103 "extract-rename-failed" => "아무 파일도 풀지 않았습니다",
102104 "extract-renamed" => "이름 바꿔 저장: 읽어주세요 (1).txt",
수정tests/rust-app-ui/scenarios.rs+24-11
@@ -21,6 +21,7 @@ macro_rules! catalog {
2121}
2222
2323catalog! {
24추가: "gzip-conflict-choice" => "단일 GZ 파일의 충돌 선택",
2425 "conflict-choice" => "같은 이름 파일의 세 가지 처리 선택",
2526 "conflict-apply" => "남은 충돌에 같은 선택 적용",
2627 "extract-skipped" => "모든 파일을 건너뛴 정상 완료",
@@ -167,11 +168,13 @@ impl Scenario {
167168 if self.name == "empty" {
168169 return app;
169170 }
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추가: );
175178 app.model.archive = Some(archive.clone());
176179 app.model.entries = entries(self.name == "many-items");
177180 app.model.list_id = Some(ListId {
@@ -236,7 +239,7 @@ impl Scenario {
236239 }
237240 let creating = self.name.starts_with("create-") || self.name == "password-create";
238241 let listing_error = matches!(self.name, "unsupported" | "damaged");
239삭제: if self.name == "gzip-conflict" {
242추가: if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
240243 app.model.list_id.as_mut().unwrap().format = Format::Gzip;
241244 app.model.entries = vec![Entry {
242245 id: 0,
@@ -263,12 +266,13 @@ impl Scenario {
263266 destination: app.destination.clone(),
264267 selection: Selection::All,
265268 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()),
267271 }
268272 };
269273 app.targets = Some(if creating {
270274 BTreeSet::from(["여행 자료.zip".into()])
271삭제: } else if self.name == "gzip-conflict" {
275추가: } else if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
272276 BTreeSet::from(["여행 자료".into()])
273277 } else {
274278 BTreeSet::from([
@@ -290,11 +294,20 @@ impl Scenario {
290294 let mut state = state.borrow_mut();
291295 state.frame(Event::Accepted { encryption: true });
292296 match self.name {
293삭제: "conflict-choice" | "conflict-apply" => {
297추가: "conflict-choice" | "conflict-apply" | "gzip-conflict-choice" => {
294298 state.frame(Event::ConflictRequired(Conflict {
295299 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(),
298311 incoming_size: 1_287_952,
299312 existing_size: 2048,
300313 }));
추가tests/rust-archive-worker/conflicts.rs+702-0
@@ -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추가: }
수정tests/rust-archive-worker/io_fault.c+7-0
@@ -136,3 +136,10 @@ int fsync(int fd) {
136136 }
137137 return real_fsync(fd);
138138}
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추가: }
수정tests/rust-archive-worker/main.rs+2-0
@@ -1611,3 +1611,5 @@ mod folder_inputs;
16111611mod zip_names;
16121612
16131613mod conflict_wire;
1614추가:
1615추가: mod conflicts;