team-ljyzipelo

공개

Merge pull request #117 from Team-LJY/features/extract-conflict-worker

압축 해제 충돌 선택과 원본 보존 구현
작성자
LeeJunyoung
작성 시각
커밋
2091e25e573323bb97fee3219838ddb7f294c74a
이 시점의 파일 보기

변경된 파일 10개

+1,648-33
수정experiments/rust-archive-worker/README.md+21-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,14 +10,14 @@
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
1717revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도를 유지하고, 히나타 님과 합의한 공간 부족 오류 DiskFull(tag 13)을 추가합니다. 구버전 앱은 새 tag를 거부하므로 앱 오류 변환과 화면 매핑을 작업자와 함께 갱신해야 합니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 세부 계약은 contract.json의 streaming_limits에 있습니다.
1818
1919- 압축비는 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다.
20삭제: - 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. ZIP/7z 해제 전에는 전체 임시 해제량과 선택한 출력량을 볼륨별로 합산해 검사하고, 게시 전에도 출력 공간을 재검사합니다. 미리 해제 크기를 알 수 없는 GZ/TAR.GZ는 각 해제 청크를 쓰기 전에 임시 저장소 공간을 확인합니다. Linux 64비트는 열린 핸들의 [fstatvfs](https://man7.org/linux/man-pages/man3/fstatvfs.3.html), Windows는 핸들에서 얻은 디렉터리의 [GetDiskFreeSpaceExW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexw)를 사용합니다. 공간 부족은 DiskFull(13), 조회 실패와 권한 등 다른 I/O 오류는 Io(8)로 반환합니다. 실제 생성/쓰기/동기화의 공간 부족에도 같은 구분을 적용합니다. Windows의 공간 부족 코드 39와 112는 [공식 오류 목록](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-)을 따릅니다.
20추가: - 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. 기존 Start는 ZIP/7z 해제 전에 전체 임시 해제량과 선택한 출력량을 볼륨별로 합산해 검사하고, 게시 전에도 출력 공간을 재검사합니다. StartInteractive는 선택 전에는 무결성 검증에 필요한 임시 해제 공간만 확인하고, 선택 뒤 건너뛰지 않은 파일의 실제 저장 이름으로 게시 직전 공간을 확인합니다. 따라서 목적지 공간이 부족해도 충돌 파일을 전부 건너뛰거나 질문 중 취소할 수 있습니다. 미리 해제 크기를 알 수 없는 GZ/TAR.GZ는 각 해제 청크를 쓰기 전에 임시 저장소 공간을 확인합니다. Linux 64비트는 열린 핸들의 [fstatvfs](https://man7.org/linux/man-pages/man3/fstatvfs.3.html), Windows는 핸들에서 얻은 디렉터리의 [GetDiskFreeSpaceExW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexw)를 사용합니다. 공간 부족은 DiskFull(13), 조회 실패와 권한 등 다른 I/O 오류는 Io(8)로 반환합니다. 실제 생성/쓰기/동기화의 공간 부족에도 같은 구분을 적용합니다. Windows의 공간 부족 코드 39와 112는 [공식 오류 목록](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-)을 따릅니다.
2121- 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 오류 문구는 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"이며, detail 문자열을 오류 판정에 사용하지 않습니다.
2222- 입력과 검증된 해제 내용은 임시 파일에 저장합니다. Linux는 [O_TMPFILE](https://man7.org/linux/man-pages/man2/open.2.html), 이를 지원하지 않는 Linux 파일시스템에서는 0600 난수 파일을 배타적으로 만든 즉시 unlink하고 링크 수 0을 확인합니다. Windows는 배타적 [DELETE_ON_CLOSE 파일](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew)을 사용합니다. 마지막 핸들이 닫히면 제거되며 임시 파일명에 아카이브 내부 이름을 사용하지 않습니다. 디스크에는 입력 사본, 해제 내용과 현재 출력 임시 파일이 동시에 필요할 수 있습니다. 임시 폴더가 tmpfs이면 해당 파일 내용은 프로세스 RSS 외의 시스템 메모리를 사용합니다.
2323- 64 MiB는 ZIP/TAR/GZ/TAR.GZ/7z 해제와 ZIP 생성 작업자 프로세스의 피크 RSS 시험 목표입니다. OS 메모리 강제 격리나 모든 아카이브의 보장을 뜻하지 않습니다. 입력 크기와 무관한 메타데이터 예산은 유지합니다.
@@ -57,15 +57,31 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도
5757
5858## 공유 codec
5959
60삭제: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 2 원문입니다.
60추가: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 3 원문이며 `extract_conflicts.status`에서 구현 상태를 구분합니다.
6161
6262헤더는 ZAW1, version u16=1, kind u16, body length u32, reserved u32=0, job ID u64, sequence u64의 32바이트입니다. 양방향 sequence는 각각 0부터 시작합니다. body는 최대 1 MiB이며 한 방향당 최대 1,000,000프레임입니다. 잘린 프레임, 알 수 없는 tag, 잔여 payload, 잘못된 ID/sequence를 거부합니다.
6363
64삭제: - kind: Start=1, Password=2, Cancel=3, Accepted=100, Entry=101, ListEnd=102, PasswordRequired=103, Progress=104, Output=105, Terminal=106, CancelAck=107입니다.
64추가: - kind: Start=1, Password=2, Cancel=3, StartInteractive=4, ConflictReply=5, Accepted=100, Entry=101, ListEnd=102, PasswordRequired=103, Progress=104, Output=105, Terminal=106, CancelAck=107, ConflictRequired=108, ConflictResolved=109입니다. 새 kind의 런타임 지원 상태는 아래 revision 3 절을 따릅니다.
6565- body 필드는 `protocol.rs` 선언 순서입니다. enum은 선언 순서의 u8 tag이며 NativePath/SourceObject만 Unix=1, Windows=2입니다. bool/Option은 0 또는 1입니다. String/Vec는 u32 길이 뒤 원소를 저장하며 String은 UTF-8 바이트 길이입니다. `[u8; N]`은 길이 없이 N바이트입니다. action variant의 필드는 선언 순서를 사용합니다. Start는 action 뒤 limits(input u64, output u64, entries u32)입니다.
6666- Password의 비밀 값은 Debug에 노출되지 않습니다. 암호 작업은 PasswordRequired의 challenge_id와 일치하는 Password를 한 번 받습니다. 오래된 ID, 중복 또는 요청 전 암호는 Protocol 오류입니다. 비밀 값은 로그나 파일에 저장하지 않습니다.
6767- CancelAck.request_sequence는 요청 헤더 sequence입니다. Requested, AlreadyRequested, TooLate, Finished는 최종 결과와 별개입니다. 종료와 경합한 요청은 읽히지 않아 응답이 없을 수 있습니다. Terminal은 마지막 프레임이며 Failed/Cancelled도 정상 전달 뒤 프로세스 exit=0입니다. 앱은 Terminal과 stdout/stderr EOF, child wait를 모두 확인해야 합니다.
6868
69추가: ## revision 3 충돌 계약
70추가:
71추가: 작업자는 `StartInteractive`로 시작한 압축 해제에서 덮어쓰기, 건너뛰기와 이름 바꿔 저장을 처리합니다. 기존 `Start`는 이름 충돌 시 중단합니다. 앱의 활성화와 실제 UI 연동은 별도 PR에서 검증합니다.
72추가:
73추가: - `StartInteractive(Start)`는 kind 4이며 기존 Start body를 그대로 사용합니다. Extract만 허용하고 List와 CreateZip은 codec에서 거부합니다. 기존 Start=1의 충돌 시 중단 동작과 모든 기존 필드 및 tag는 유지하며 구버전 작업자로 자동 재시도하지 않습니다.
74추가: - `ConflictChoice`는 Overwrite=0, Skip=1, Rename=2입니다. `ConflictReply`(5)는 challenge_id u64, choice u8, apply_to_remaining bool 순서입니다.
75추가: - `ConflictRequired`(108)는 challenge_id u64, entry_id u32, relative_name String, incoming_size u64, existing_size u64 순서입니다. 일반 파일끼리의 충돌에 세 선택을 허용하며 폴더끼리는 합치고 파일과 폴더 충돌 및 링크는 차단합니다.
76추가: - `ConflictResolved`(109)는 entry_id u32, relative_name String, choice u8 순서입니다. 일괄 적용에도 항목마다 보내며 저장 성공을 뜻하지 않습니다. 교체와 이름 변경의 게시 성공은 기존 `Output::Created`로 별도 확인하고 건너뛰기에는 Created를 보내지 않습니다.
77추가: - Rename 이름은 작업자가 같은 폴더 안에서 `파일명 (1).확장자` 형태의 미사용 번호 이름으로 정합니다. 기존 이름과 뒤에 처리할 항목의 경로도 피하며, 긴 이름은 UTF-8 경계를 보존해 255바이트 안으로 줄입니다. 일괄 적용은 현재 작업의 남은 일반 파일 충돌에만 적용합니다. 질문은 한 번에 하나이며 잘못되거나 중복된 응답은 Protocol, 답변 전 EOF도 Protocol입니다. 취소를 처리하고 기존 300초 제한에 대기 시간을 포함합니다.
78추가: - 전부 건너뛰고 새 출력도 없으면 Completed, Publication::None, created_count=0, Durability::NotApplicable입니다. 새 폴더가 만들어졌다면 해당 Output과 실제 집계를 유지합니다. 교체는 created_count에 포함하며 건너뛰기는 제외합니다.
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)입니다.
84추가:
6985## 검증과 의존성
7086
7187시험은 `tests/rust-archive-worker`에 있습니다. Python 표준 라이브러리로 만든 ZIP/TAR/GZ fixture와 실제 자식 프로세스를 사용합니다. 전체 검증 명령은 저장소 루트의 `python3 tests/ci/run_rust.py local`입니다. Windows 교차 빌드는 실제 Windows 실행 검증을 대신하지 않습니다.
수정experiments/rust-archive-worker/contract.json+39-9
@@ -1,5 +1,5 @@
11{
2삭제: "status": "implemented-streaming-runtime",
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": {
@@ -28,7 +28,9 @@
2828 "commands": {
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.",
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."
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. Worker runtime supports the agreed choices; client activation and native UI integration are verified separately.",
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."
3234 },
3335 "events": {
3436 "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation.",
@@ -55,10 +57,12 @@
5557 "TooLate": "Final job completion/commit decision has been sealed so cancellation can no longer influence the outcome; final outcome may still be Failed or publication Uncertain. Previously created entries alone do not make a multi-entry job TooLate.",
5658 "Finished": "Business outcome has already been fixed, but Terminal has not yet been emitted. Does not establish success, EOF, child exit or reaping.",
5759 "ordering": "Each well-formed Cancel consumed before Terminal is acknowledged once before Terminal. Terminal is the last worker protocol frame. A Cancel racing with Terminal/exit may remain unread and have no acknowledgement; app uses Terminal plus EOF and wait, never synthesizes a worker acknowledgement or successful cancellation."
58삭제: }
60추가: },
61추가: "ConflictRequired": "Kind 108: challenge_id:u64, entry_id:u32, relative_name:UTF8, incoming_size:u64, existing_size:u64. One ordinary-file conflict at a time, after complete archive integrity validation. All three choices are permitted; links and file/directory type conflicts remain rejected.",
62추가: "ConflictResolved": "Kind 109: entry_id:u32, relative_name:UTF8, choice:ConflictChoice(u8). Emit for every resolved conflict, including automatically applied choices. This records the action and resolved name, not successful publication; successful overwrite or rename also requires Output Created. Skip emits no Output Created."
5963 },
6064 "lifecycle": [
61삭제: "Start once; no automatic retry or overwrite. Password/Cancel remain readable during work.",
65추가: "Exactly one Start or StartInteractive; no automatic retry or fallback. Password/Cancel remain readable during work. ConflictReply is accepted only for a matching outstanding interactive conflict.",
6266 "Parent drains both streams concurrently. Stdout is protocol only; stderr is bounded diagnostics without secrets.",
6367 "Exactly one Terminal ends business results and is the final worker protocol frame; CancelAck can precede but never follow it. Worker exits0 after delivered terminal, including Failed/Cancelled. Malformed protocol or crash can exit nonzero without terminal.",
6468 "App requires matching terminal, stdout/stderr EOF and owned child wait/exit before replacement/close. EOF/exit0 alone is not success.",
@@ -69,7 +73,7 @@
6973 "safe_output": [
7074 "Reject absolute/dotdot/drive/UNC/device/reserved/alternate-stream names and case/path collisions before writes.",
7175 "Reject archive links/special entries on extraction. Do not follow output parent symlinks/reparse points.",
72삭제: "Create output files exclusively; never truncate or write pre-existing files. GZip FNAME does not choose destination.",
76추가: "Legacy Start creates output files exclusively and never truncates or writes pre-existing files. StartInteractive may replace an existing ordinary file only after the agreed choice and complete temporary output validation. GZip FNAME does not choose destination.",
7377 "CRC/size/stream-end validation precedes committed output events; preserve commit/durability/cleanup distinctions."
7478 ],
7579 "pending": [
@@ -81,12 +85,18 @@
8185 "implementation_verified": false,
8286 "policy": "Human approved pure Rust RustCrypto under MIT/Apache. No home-grown AES or password KDF; approval alone does not enable encryption capability."
8387 },
84삭제: "revision": 2,
88추가: "revision": 3,
8589 "coordination": {
8690 "frontend_message_id": "41a0e5a5-27d0-437f-805d-d39313082096",
8791 "basis": "Revision 2 list identity, explicit raw GZip output naming and cancellation acknowledgement are implemented. Field order and tags remain unchanged.",
8892 "streaming_frontend_message_id": "59142fd4-22d3-4dc5-a875-5347e1b054da",
89삭제: "disk_full_frontend_message_id": "3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1"
93추가: "disk_full_frontend_message_id": "3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1",
94추가: "conflict_frontend_message_ids": [
95추가: "37815dda-3271-4f83-be4d-8da1a6e0c2ab",
96추가: "87ff39f9-f7fe-4efc-bd2e-d73ab3246356"
97추가: ],
98추가: "conflict_backend_message_id": "64e29128-e8a2-45e5-8577-db84a66feaa9",
99추가: "revision_3_status": "Joint agreement complete. Types, codec and interactive worker runtime implemented; frontend activation and native UI integration remain separate."
90100 },
91101 "list_identity": {
92102 "ListId": {
@@ -114,7 +124,7 @@
114124 "gzip_output_name": "Required Some(nonempty validated UTF-8 single leaf filename) for raw GZIP extraction, for both All and EntryIds. Reject absolute/drive/UNC/device/alternate-stream/reserved names, separators, dot/dotdot and invalid leaf names before creating outputs. Missing/invalid value returns InvalidRequest; no implicit basename or FNAME fallback.",
115125 "other_formats": "Must be None for ZIP, TAR and TAR_GZIP; reject Some as InvalidRequest rather than silently ignoring it. TAR_GZIP uses validated inner TAR member names.",
116126 "gzip_catalog": "Raw GZIP is one logical stream entry with entry_id0. Its listed display name is not an output path; entry selection still requires ListId.",
117삭제: "publication": "Resolve the supplied leaf under destination using the same no-follow and exclusive-create guards. Existing destination files return Conflict; never overwrite, rename to an automatic alternative or retry."
127추가: "publication": "Resolve the supplied leaf under destination using the same no-follow guards. Existing destination files return Conflict for legacy Start. StartInteractive follows the regular-file conflict policy; never automatically downgrade or retry through legacy Start."
118128 },
119129 "design_references": [
120130 {
@@ -156,7 +166,7 @@
156166 "staging": "64 KiB buffers; immutable input capture and verified decoded content use private temporary files that are removed on last-handle close. No decoded content is published until the entire catalog and integrity checks succeed. Temporary disk usage can include the archive plus expanded content plus current destination temporary file; disk exhaustion fails with DiskFull and closes/removes unpublished data.",
157167 "legacy": "The slice parser keeps 64 MiB input /128 MiB output caps; the slice ZIP builder keeps 128 MiB source/result caps. Runtime 7z and ZIP creation use streaming file paths.",
158168 "parent_lifetime": "Capture native parent before reading Start. At decode/read/write/password checkpoints, fail Io if parent is gone; close anonymous staging and remove current unpublished destination temp. stdin EOF alone remains valid for one-shot requests. Already published entries and directories are reported and retained. A blocked OS file operation cannot be forcibly interrupted by this cooperative guard.",
159삭제: "disk_space": "Advisory free-space checks use opened Linux x86_64 filesystem handles (fstatvfs) or the Windows handle-derived directory (GetDiskFreeSpaceExW). Before ZIP/7z decoding and before publication, group remaining staging and selected output logical bytes by volume. For GZip with unknown expanded size, check staging space before each decoded chunk, then preflight selected output. Input capture also checks its snapshot space. Insufficient space returns DiskFull tag 13. Query failure and other I/O errors retain Io tag 8. Checks do not reserve space or account for every metadata/block-allocation overhead; later ENOSPC still closes staging and removes current unpublished output.",
169추가: "disk_space": "Advisory free-space checks use opened Linux x86_64 filesystem handles (fstatvfs) or the Windows handle-derived directory (GetDiskFreeSpaceExW). Legacy Start groups remaining staging and selected output logical bytes by volume before ZIP/7z decoding and before publication. StartInteractive checks required staging before choices, then checks only the current non-skipped output at its resolved name immediately before publication; do not charge undecided or skipped files to the destination. For GZip with unknown expanded size, check staging space before each decoded chunk, then preflight selected output. Input capture also checks its snapshot space. Insufficient space returns DiskFull tag 13. Query failure and other I/O errors retain Io tag 8. Checks do not reserve space or account for every metadata/block-allocation overhead; later ENOSPC still closes staging and removes current unpublished output.",
160170 "remaining_risk": "High compression ratios within 16 GiB may expand fully onto disk. Resource duration, cooperative cancellation and measured memory target remain. Free-space checks can race with other disk users; already published outputs are retained on failure.",
161171 "seven_zip": "Copy, LZMA and LZMA2 use file-backed solid output with checked declared/actual output totals. Encoded headers remain limited to 8 MiB. Dictionary size remains at most 64 MiB; only the last 8 MiB is cached in memory and older dictionary bytes are read from the temporary output.",
162172 "create_zip": "The sum of source logical bytes cannot exceed min(input,output) quotas. output defaults to 16 GiB of uncompressed source content; ZIP container/encryption overhead may exceed that logical content quota. Capture one immutable source at a time, stream Store/Deflate and optional AES-256 through 64 KiB buffers, then publish the completed ZIP without replacing existing files. Emit ZIP64 sizes/offsets only when their 32-bit fields would overflow or equal the sentinel. Check staging and destination free space; StorageFull maps to DiskFull tag 13 and other I/O failures retain Io tag 8."
@@ -192,5 +202,25 @@
192202 "limits": "All expanded file and directory entries count toward entries (default 10000). Only file logical bytes count toward min(input,output), default output 16 GiB. Preserve 8 MiB metadata and 64-component name limits. Validate the complete plan and case-insensitive/path-prefix conflicts before requesting a password.",
193203 "consistency": "Capture each file from its validated open handle. Compare planned object identity, kind, size and modification time before capture and check planned objects again before publishing the completed ZIP; detected changes fail SourceChanged. This is not an atomic snapshot of an entire directory tree.",
194204 "encryption": "AES-256 protects file contents using the existing AE-2 encoding. Directory entries are stored as zero-byte unencrypted directory records; entry names remain visible, as with other ZIP entries."
205추가: },
206추가: "conflict_choice_tags": {
207추가: "Overwrite": 0,
208추가: "Skip": 1,
209추가: "Rename": 2
210추가: },
211추가: "extract_conflicts": {
212추가: "status": "worker-implemented",
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추가: "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추가: "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. 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추가: "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추가: "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추가: "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추가: "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추가: "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": "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.",
224추가: "disk_space": "Required input capture and complete integrity staging checks remain before conflict questions. Defer destination space checks until the current choice is resolved. Skip has no destination byte charge; overwrite, rename and non-conflicting files are checked immediately before their publication. Preserve legacy Start aggregate preflight, limits, per-write checks and partial-output reporting."
195225 }
196226}
수정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/protocol.rs+24-0
@@ -255,6 +255,12 @@ pub enum PasswordPurpose {
255255 Decrypt,
256256 Encrypt,
257257}
258추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
259추가: pub enum ConflictChoice {
260추가: Overwrite,
261추가: Skip,
262추가: Rename,
263추가: }
258264#[derive(Clone, Debug, PartialEq, Eq)]
259265pub struct Terminal {
260266 pub outcome: Outcome,
@@ -285,6 +291,12 @@ pub enum Message {
285291 secret: Secret,
286292 },
287293 Cancel,
294추가: StartInteractive(Start),
295추가: ConflictReply {
296추가: challenge_id: u64,
297추가: choice: ConflictChoice,
298추가: apply_to_remaining: bool,
299추가: },
288300 Accepted {
289301 action: ActionKind,
290302 encryption: bool,
@@ -315,4 +327,16 @@ pub enum Message {
315327 request_sequence: u64,
316328 status: CancelStatus,
317329 },
330추가: ConflictRequired {
331추가: challenge_id: u64,
332추가: entry_id: u32,
333추가: relative_name: String,
334추가: incoming_size: u64,
335추가: existing_size: u64,
336추가: },
337추가: ConflictResolved {
338추가: entry_id: u32,
339추가: relative_name: String,
340추가: choice: ConflictChoice,
341추가: },
318342}
수정experiments/rust-archive-worker/src/runtime.rs+180-15
@@ -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 {
@@ -315,7 +405,13 @@ impl<W: Write> Job<W> {
315405 } else {
316406 None
317407 };
318삭제: filesystem::preflight_space(&root, &output_sizes, staged)?;
408추가: // 선택 전에는 검증에 필요한 스테이징 공간만 계산함.
409추가: let initial_outputs = if self.interactive {
410추가: &[][..]
411추가: } else {
412추가: &output_sizes[..]
413추가: };
414추가: filesystem::preflight_space(&root, initial_outputs, staged)?;
319415 let encrypted = catalog.members.iter().any(|m| m.entry.encrypted);
320416 if matches!(catalog.format, Format::Zip | Format::SevenZip) {
321417 for attempt in 1..=3 {
@@ -366,8 +462,14 @@ impl<W: Write> Job<W> {
366462 .iter()
367463 .map(|m| (m.entry.name.clone(), EntryKind::File)),
368464 );
369삭제: filesystem::preflight(&root, &names)?;
370삭제: filesystem::preflight_space(&root, &output_sizes, None)?;
465추가: filesystem::preflight_mode(&root, &names, self.interactive)?;
466추가: if !self.interactive {
467추가: filesystem::preflight_space(&root, &output_sizes, None)?;
468추가: }
469추가: let mut reserved = names
470추가: .iter()
471추가: .map(|(name, _)| name.to_lowercase())
472추가: .collect::<BTreeSet<_>>();
371473 for name in dirs {
372474 self.check()?;
373475 let (created, durability, sync_error) =
@@ -389,16 +491,53 @@ impl<W: Write> Job<W> {
389491 for (index, m) in files.iter().enumerate() {
390492 data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize]))
391493 .map_err(|_| ErrorCode::Io)?;
494추가: self.check()?;
495추가: let existing = if self.interactive {
496추가: filesystem::existing(&root, &m.entry.name)?
497추가: } else {
498추가: None
499추가: };
500추가: let mut name = m.entry.name.clone();
501추가: let mut replace = None;
502추가: if let Some(ref existing) = existing {
503추가: let choice = self.conflict(&m.entry, existing.size)?;
504추가: self.check()?;
505추가: if choice == ConflictChoice::Rename {
506추가: name = self.rename(&root, &name, &reserved)?;
507추가: reserved.insert(name.to_lowercase());
508추가: } else if choice == ConflictChoice::Overwrite {
509추가: replace = Some(existing);
510추가: }
511추가: self.event(Message::ConflictResolved {
512추가: entry_id: m.entry.entry_id,
513추가: relative_name: name.clone(),
514추가: choice,
515추가: })?;
516추가: if choice == ConflictChoice::Skip {
517추가: continue;
518추가: }
519추가: }
520추가: if self.interactive {
521추가: // 건너뛴 파일을 제외하고 이번에 게시할 파일의 공간을 확인함.
522추가: filesystem::preflight_space(
523추가: &root,
524추가: &[(name.clone(), m.entry.size)],
525추가: None,
526추가: )?;
527추가: }
392528 self.output_reader(
393529 &root,
394삭제: &m.entry.name,
530추가: &name,
395531 &mut (&mut data).take(m.entry.size),
396532 m.entry.size,
397533 Some(m.entry.entry_id),
398534 index + 1 == files.len(),
535추가: replace,
399536 )?;
400537 }
401삭제: self.terminal.publication = Publication::Complete;
538추가: if !self.interactive || self.terminal.created_count != 0 {
539추가: self.terminal.publication = Publication::Complete;
540추가: }
402541 }
403542 }
404543 Action::CreateZip {
@@ -433,7 +572,7 @@ impl<W: Write> Job<W> {
433572 &mut || self.check(),
434573 )?;
435574 filesystem::preflight_space(&root, &[(name.clone(), length)], None)?;
436삭제: self.output_reader(&root, &name, &mut data, length, None, true)?;
575추가: self.output_reader(&root, &name, &mut data, length, None, true, None)?;
437576 self.terminal.publication = Publication::Complete;
438577 }
439578 }
@@ -451,11 +590,15 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
451590 let (job, _, message) = reader
452591 .read()?
453592 .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삭제: ));
593추가: let (start, interactive) = match message {
594추가: Message::Start(start) => (start, false),
595추가: Message::StartInteractive(start) => (start, true),
596추가: _ => {
597추가: return Err(std::io::Error::new(
598추가: std::io::ErrorKind::InvalidData,
599추가: "Start required",
600추가: ));
601추가: }
459602 };
460603 let state = Arc::new(Mutex::new(State {
461604 writer: Writer::new(output, job),
@@ -463,6 +606,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
463606 phase: 0,
464607 fault: None,
465608 challenge: None,
609추가: conflict_reply: None,
466610 password: None,
467611 input_closed: false,
468612 }));
@@ -494,7 +638,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
494638 secret,
495639 } => {
496640 if state.phase != 0
497삭제: || state.challenge != Some(challenge_id)
641추가: || state.challenge != Some(Challenge::Password(challenge_id))
498642 || state.password.is_some()
499643 {
500644 state.fault = Some(ErrorCode::Protocol);
@@ -506,6 +650,24 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
506650 }
507651 control_wake.notify_all();
508652 }
653추가: Message::ConflictReply {
654추가: challenge_id,
655추가: choice,
656추가: apply_to_remaining,
657추가: } => {
658추가: if state.phase != 0
659추가: || state.challenge != Some(Challenge::Conflict(challenge_id))
660추가: || state.conflict_reply.is_some()
661추가: {
662추가: state.fault = Some(ErrorCode::Protocol);
663추가: } else {
664추가: state.challenge = None;
665추가: if !state.cancelled {
666추가: state.conflict_reply = Some((choice, apply_to_remaining));
667추가: }
668추가: }
669추가: control_wake.notify_all();
670추가: }
509671 Message::Cancel => {
510672 let status = match state.phase {
511673 2 => CancelStatus::Finished,
@@ -540,6 +702,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
540702 state: Arc::clone(&state),
541703 wake,
542704 next_challenge: 0,
705추가: interactive,
706추가: remaining_choice: None,
543707 parent,
544708 started: Instant::now(),
545709 terminal: Terminal {
@@ -568,6 +732,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
568732 state.phase = 2;
569733 state.challenge = None;
570734 state.password = None;
735추가: state.conflict_reply = None;
571736 if let Some(error) = state.fault.or(error) {
572737 context.terminal.error = error;
573738 context.terminal.outcome = if error == ErrorCode::None {
수정experiments/rust-archive-worker/src/wire.rs+66-0
@@ -139,6 +139,7 @@ enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3});
139139enumeration!(Cleanup{Complete=0,Failed=1,Unconfirmed=2});
140140enumeration!(CancelStatus{Requested=0,AlreadyRequested=1,TooLate=2,Finished=3});
141141enumeration!(PasswordPurpose{Decrypt=0,Encrypt=1});
142추가: enumeration!(ConflictChoice{Overwrite=0,Skip=1,Rename=2});
142143macro_rules! structure {($t:ident {$($f:ident),*})=>{impl Wire for $t {
143144 fn enc(&self,e:&mut Encoder)->io::Result<()> {$(self.$f.enc(e)?;)*Ok(())}
144145 fn dec(d:&mut Decoder<'_>)->io::Result<Self> {Ok(Self {$($f:Wire::dec(d)?,)*})}
@@ -323,6 +324,23 @@ impl Message {
323324 2
324325 }
325326 Self::Cancel => 3,
327추가: Self::StartInteractive(v) => {
328추가: if !matches!(&v.action, Action::Extract { .. }) {
329추가: return Err(invalid());
330추가: }
331추가: v.enc(&mut e)?;
332추가: 4
333추가: }
334추가: Self::ConflictReply {
335추가: challenge_id,
336추가: choice,
337추가: apply_to_remaining,
338추가: } => {
339추가: challenge_id.enc(&mut e)?;
340추가: choice.enc(&mut e)?;
341추가: apply_to_remaining.enc(&mut e)?;
342추가: 5
343추가: }
326344 Self::Accepted { action, encryption } => {
327345 action.enc(&mut e)?;
328346 encryption.enc(&mut e)?;
@@ -387,6 +405,30 @@ impl Message {
387405 status.enc(&mut e)?;
388406 107
389407 }
408추가: Self::ConflictRequired {
409추가: challenge_id,
410추가: entry_id,
411추가: relative_name,
412추가: incoming_size,
413추가: existing_size,
414추가: } => {
415추가: challenge_id.enc(&mut e)?;
416추가: entry_id.enc(&mut e)?;
417추가: relative_name.enc(&mut e)?;
418추가: incoming_size.enc(&mut e)?;
419추가: existing_size.enc(&mut e)?;
420추가: 108
421추가: }
422추가: Self::ConflictResolved {
423추가: entry_id,
424추가: relative_name,
425추가: choice,
426추가: } => {
427추가: entry_id.enc(&mut e)?;
428추가: relative_name.enc(&mut e)?;
429추가: choice.enc(&mut e)?;
430추가: 109
431추가: }
390432 };
391433 Ok((kind, e.bytes))
392434 }
@@ -406,6 +448,18 @@ impl Message {
406448 }
407449 }
408450 3 => Self::Cancel,
451추가: 4 => {
452추가: let start = Start::dec(&mut d)?;
453추가: if !matches!(&start.action, Action::Extract { .. }) {
454추가: return Err(invalid());
455추가: }
456추가: Self::StartInteractive(start)
457추가: }
458추가: 5 => Self::ConflictReply {
459추가: challenge_id: Wire::dec(&mut d)?,
460추가: choice: Wire::dec(&mut d)?,
461추가: apply_to_remaining: Wire::dec(&mut d)?,
462추가: },
409463 100 => Self::Accepted {
410464 action: Wire::dec(&mut d)?,
411465 encryption: Wire::dec(&mut d)?,
@@ -442,6 +496,18 @@ impl Message {
442496 request_sequence: Wire::dec(&mut d)?,
443497 status: Wire::dec(&mut d)?,
444498 },
499추가: 108 => Self::ConflictRequired {
500추가: challenge_id: Wire::dec(&mut d)?,
501추가: entry_id: Wire::dec(&mut d)?,
502추가: relative_name: Wire::dec(&mut d)?,
503추가: incoming_size: Wire::dec(&mut d)?,
504추가: existing_size: Wire::dec(&mut d)?,
505추가: },
506추가: 109 => Self::ConflictResolved {
507추가: entry_id: Wire::dec(&mut d)?,
508추가: relative_name: Wire::dec(&mut d)?,
509추가: choice: Wire::dec(&mut d)?,
510추가: },
445511 _ => return Err(invalid()),
446512 };
447513 if d.at != b.len() {
추가tests/rust-archive-worker/conflict_wire.rs+234-0
@@ -0,0 +1,234 @@
1추가: use super::*;
2추가:
3추가: fn sample_start() -> Start {
4추가: Start {
5추가: action: Action::Extract {
6추가: archive: NativePath::Unix(b"/archive".to_vec()),
7추가: destination: NativePath::Unix(b"/output".to_vec()),
8추가: selection: Selection::All,
9추가: list_id: None,
10추가: gzip_output_name: None,
11추가: },
12추가: limits: Limits {
13추가: input: 7,
14추가: output: 8,
15추가: entries: 9,
16추가: },
17추가: }
18추가: }
19추가:
20추가: fn encoded(message: &Message) -> Vec<u8> {
21추가: let mut bytes = Vec::new();
22추가: Writer::new(&mut bytes, 17).send(message).unwrap();
23추가: bytes
24추가: }
25추가:
26추가: fn decoded(bytes: &[u8]) -> Message {
27추가: let mut reader = Reader::new(bytes);
28추가: let (job, sequence, message) = reader.read().unwrap().unwrap();
29추가: assert_eq!((job, sequence), (17, 0));
30추가: assert!(reader.read().unwrap().is_none());
31추가: message
32추가: }
33추가:
34추가: #[test]
35추가: fn interactive_start_preserves_legacy_body_and_frame_version() {
36추가: let start = sample_start();
37추가: let legacy = encoded(&Message::Start(start.clone()));
38추가: let interactive = encoded(&Message::StartInteractive(start.clone()));
39추가: let mut expected = legacy;
40추가: expected[6..8].copy_from_slice(&4u16.to_le_bytes());
41추가: assert_eq!(interactive, expected);
42추가: assert_eq!(&interactive[..6], b"ZAW1\x01\x00");
43추가: match decoded(&interactive) {
44추가: Message::StartInteractive(actual) => assert_eq!(actual, start),
45추가: other => panic!("unexpected frame: {other:?}"),
46추가: }
47추가: }
48추가:
49추가: #[test]
50추가: fn interactive_start_rejects_list_and_create_on_both_codec_directions() {
51추가: for action in [
52추가: Action::List {
53추가: archive: NativePath::Unix(b"/archive".to_vec()),
54추가: },
55추가: Action::CreateZip {
56추가: sources: Vec::new(),
57추가: output_file: NativePath::Unix(b"/output.zip".to_vec()),
58추가: method: Method::Store,
59추가: encryption: Encryption::None,
60추가: },
61추가: ] {
62추가: let start = Start {
63추가: action,
64추가: limits: Limits::default(),
65추가: };
66추가: let mut bytes = Vec::new();
67추가: assert!(
68추가: Writer::new(&mut bytes, 17)
69추가: .send(&Message::StartInteractive(start.clone()))
70추가: .is_err()
71추가: );
72추가: assert!(bytes.is_empty());
73추가: let mut frame = encoded(&Message::Start(start));
74추가: frame[6..8].copy_from_slice(&4u16.to_le_bytes());
75추가: assert_eq!(
76추가: Reader::new(frame.as_slice()).read().unwrap_err().kind(),
77추가: std::io::ErrorKind::InvalidData
78추가: );
79추가: }
80추가: }
81추가:
82추가: #[test]
83추가: fn conflict_reply_choices_and_apply_flag_have_stable_bytes() {
84추가: for (choice, tag) in [
85추가: (ConflictChoice::Overwrite, 0),
86추가: (ConflictChoice::Skip, 1),
87추가: (ConflictChoice::Rename, 2),
88추가: ] {
89추가: for apply_to_remaining in [false, true] {
90추가: let frame = encoded(&Message::ConflictReply {
91추가: challenge_id: 0x0807060504030201,
92추가: choice,
93추가: apply_to_remaining,
94추가: });
95추가: assert_eq!(&frame[6..12], &[5, 0, 10, 0, 0, 0]);
96추가: assert_eq!(
97추가: &frame[32..],
98추가: &[1, 2, 3, 4, 5, 6, 7, 8, tag, u8::from(apply_to_remaining)]
99추가: );
100추가: match decoded(&frame) {
101추가: Message::ConflictReply {
102추가: challenge_id,
103추가: choice: actual_choice,
104추가: apply_to_remaining: actual_apply,
105추가: } => {
106추가: assert_eq!(challenge_id, 0x0807060504030201);
107추가: assert_eq!(actual_choice, choice);
108추가: assert_eq!(actual_apply, apply_to_remaining);
109추가: }
110추가: other => panic!("unexpected frame: {other:?}"),
111추가: }
112추가: }
113추가: }
114추가: }
115추가:
116추가: #[test]
117추가: fn conflict_metadata_round_trips_unicode_names_and_full_width_sizes() {
118추가: let name = "자료/보고서.txt";
119추가: let required = encoded(&Message::ConflictRequired {
120추가: challenge_id: u64::MAX,
121추가: entry_id: u32::MAX,
122추가: relative_name: name.to_owned(),
123추가: incoming_size: u64::MAX - 1,
124추가: existing_size: u64::MAX - 2,
125추가: });
126추가: assert_eq!(&required[6..8], &108u16.to_le_bytes());
127추가: match decoded(&required) {
128추가: Message::ConflictRequired {
129추가: challenge_id,
130추가: entry_id,
131추가: relative_name,
132추가: incoming_size,
133추가: existing_size,
134추가: } => {
135추가: assert_eq!(challenge_id, u64::MAX);
136추가: assert_eq!(entry_id, u32::MAX);
137추가: assert_eq!(relative_name, name);
138추가: assert_eq!(incoming_size, u64::MAX - 1);
139추가: assert_eq!(existing_size, u64::MAX - 2);
140추가: }
141추가: other => panic!("unexpected frame: {other:?}"),
142추가: }
143추가: for choice in [
144추가: ConflictChoice::Overwrite,
145추가: ConflictChoice::Skip,
146추가: ConflictChoice::Rename,
147추가: ] {
148추가: let resolved = encoded(&Message::ConflictResolved {
149추가: entry_id: 23,
150추가: relative_name: "자료/보고서 (1).txt".to_owned(),
151추가: choice,
152추가: });
153추가: assert_eq!(&resolved[6..8], &109u16.to_le_bytes());
154추가: match decoded(&resolved) {
155추가: Message::ConflictResolved {
156추가: entry_id,
157추가: relative_name,
158추가: choice: actual,
159추가: } => {
160추가: assert_eq!(entry_id, 23);
161추가: assert_eq!(relative_name, "자료/보고서 (1).txt");
162추가: assert_eq!(actual, choice);
163추가: }
164추가: other => panic!("unexpected frame: {other:?}"),
165추가: }
166추가: }
167추가: }
168추가:
169추가: #[test]
170추가: fn conflict_frames_reject_unknown_choices_flags_utf8_and_kinds() {
171추가: let reply = encoded(&Message::ConflictReply {
172추가: challenge_id: 1,
173추가: choice: ConflictChoice::Skip,
174추가: apply_to_remaining: false,
175추가: });
176추가: for (offset, value) in [(40, 3), (41, 2)] {
177추가: let mut invalid = reply.clone();
178추가: invalid[offset] = value;
179추가: assert!(Reader::new(invalid.as_slice()).read().is_err());
180추가: }
181추가: let mut required = encoded(&Message::ConflictRequired {
182추가: challenge_id: 1,
183추가: entry_id: 2,
184추가: relative_name: "a".to_owned(),
185추가: incoming_size: 3,
186추가: existing_size: 4,
187추가: });
188추가: required[48] = 0xff;
189추가: assert!(Reader::new(required.as_slice()).read().is_err());
190추가: let mut resolved = encoded(&Message::ConflictResolved {
191추가: entry_id: 1,
192추가: relative_name: "a".to_owned(),
193추가: choice: ConflictChoice::Rename,
194추가: });
195추가: *resolved.last_mut().unwrap() = 3;
196추가: assert!(Reader::new(resolved.as_slice()).read().is_err());
197추가: let mut unknown = reply;
198추가: unknown[6..8].copy_from_slice(&110u16.to_le_bytes());
199추가: assert!(Reader::new(unknown.as_slice()).read().is_err());
200추가: }
201추가:
202추가: #[test]
203추가: fn conflict_frames_reject_truncation_and_trailing_fields() {
204추가: for message in [
205추가: Message::StartInteractive(sample_start()),
206추가: Message::ConflictReply {
207추가: challenge_id: 1,
208추가: choice: ConflictChoice::Overwrite,
209추가: apply_to_remaining: true,
210추가: },
211추가: Message::ConflictRequired {
212추가: challenge_id: 1,
213추가: entry_id: 2,
214추가: relative_name: "a".to_owned(),
215추가: incoming_size: 3,
216추가: existing_size: 4,
217추가: },
218추가: Message::ConflictResolved {
219추가: entry_id: 2,
220추가: relative_name: "a".to_owned(),
221추가: choice: ConflictChoice::Skip,
222추가: },
223추가: ] {
224추가: let frame = encoded(&message);
225추가: for length in 1..frame.len() {
226추가: assert!(Reader::new(&frame[..length]).read().is_err());
227추가: }
228추가: let mut trailing = frame;
229추가: trailing.push(0);
230추가: let length = (trailing.len() - 32) as u32;
231추가: trailing[8..12].copy_from_slice(&length.to_le_bytes());
232추가: assert!(Reader::new(trailing.as_slice()).read().is_err());
233추가: }
234추가: }
추가tests/rust-archive-worker/conflicts.rs+930-0
@@ -0,0 +1,930 @@
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추가: }
703추가:
704추가: #[cfg(target_os = "linux")]
705추가: #[test]
706추가: fn skip_all_ignores_destination_space_for_zip_tar_and_gzip() {
707추가: for format in ["zip", "tar", "gzip"] {
708추가: for apply in [false, true] {
709추가: let s = Scratch::new();
710추가: let names = match format {
711추가: "zip" => vec!["a", "b"],
712추가: "tar" => vec!["folder/hello.txt"],
713추가: _ => vec!["chosen.txt"],
714추가: };
715추가: fixture(&s, &names);
716추가: let mut start = request(&s);
717추가: if format == "tar" {
718추가: fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar")).unwrap();
719추가: } else if format == "gzip" {
720추가: fs::write(s.0.join("input"), include_bytes!("fixtures/sample.gz")).unwrap();
721추가: if let Action::Extract {
722추가: gzip_output_name, ..
723추가: } = &mut start.action
724추가: {
725추가: *gzip_output_name = Some("chosen.txt".into());
726추가: }
727추가: }
728추가: let before = names
729추가: .iter()
730추가: .map(|name| hash(&s.0.join("output").join(name)))
731추가: .collect::<Vec<_>>();
732추가: let events = run(
733추가: &s,
734추가: start,
735추가: Some("space-destination"),
736추가: vec![],
737추가: |event| match event {
738추가: Message::ConflictRequired { challenge_id, .. } => {
739추가: Some(vec![reply(*challenge_id, ConflictChoice::Skip, apply)])
740추가: }
741추가: _ => None,
742추가: },
743추가: );
744추가: assert_eq!(
745추가: terminal(&events).outcome,
746추가: Outcome::Completed,
747추가: "{format}/{apply}: {events:?}"
748추가: );
749추가: assert_eq!(terminal(&events).error, ErrorCode::None);
750추가: assert_eq!(terminal(&events).publication, Publication::None);
751추가: assert_eq!(terminal(&events).created_count, 0);
752추가: assert_eq!(terminal(&events).durability, Durability::NotApplicable);
753추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
754추가: assert_eq!(created(&events), 0);
755추가: let conflicts = if format == "zip" { 2 } else { 1 };
756추가: assert_eq!(questions(&events), if apply { 1 } else { conflicts });
757추가: assert_eq!(
758추가: count(&events, |event| matches!(
759추가: event,
760추가: Message::ConflictResolved {
761추가: choice: ConflictChoice::Skip,
762추가: ..
763추가: }
764추가: )),
765추가: conflicts
766추가: );
767추가: for (name, before) in names.iter().zip(before) {
768추가: assert_eq!(hash(&s.0.join("output").join(name)), before);
769추가: }
770추가: if format == "gzip" {
771추가: assert_eq!(
772추가: fs::read(s.0.join("output/chosen.txt")).unwrap(),
773추가: b"original"
774추가: );
775추가: }
776추가: assert!(
777추가: !s.0.join("paused").exists(),
778추가: "skipped files must not charge destination space"
779추가: );
780추가: }
781추가: }
782추가: }
783추가: #[cfg(target_os = "linux")]
784추가: #[test]
785추가: fn destination_space_is_checked_after_overwrite_or_rename_choice() {
786추가: for choice in [ConflictChoice::Overwrite, ConflictChoice::Rename] {
787추가: let s = Scratch::new();
788추가: fixture(&s, &["a", "b"]);
789추가: let before = hash(&s.0.join("output/a"));
790추가: let events = run(
791추가: &s,
792추가: request(&s),
793추가: Some("space-destination"),
794추가: vec![],
795추가: |event| match event {
796추가: Message::ConflictRequired { challenge_id, .. } => {
797추가: Some(vec![reply(*challenge_id, choice, true)])
798추가: }
799추가: _ => None,
800추가: },
801추가: );
802추가: assert_eq!(questions(&events), 1, "{events:?}");
803추가: assert_eq!(
804추가: count(&events, |event| matches!(
805추가: event,
806추가: Message::ConflictResolved { .. }
807추가: )),
808추가: 1
809추가: );
810추가: assert_eq!(terminal(&events).error, ErrorCode::DiskFull, "{events:?}");
811추가: assert_eq!(terminal(&events).publication, Publication::None);
812추가: assert_eq!(terminal(&events).created_count, 0);
813추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
814추가: assert_eq!(hash(&s.0.join("output/a")), before);
815추가: assert_eq!(hash(&s.0.join("output/b")), before);
816추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 2);
817추가: assert!(s.0.join("paused").exists());
818추가: }
819추가: }
820추가: #[cfg(target_os = "linux")]
821추가: #[test]
822추가: fn skipped_files_do_not_charge_space_for_remaining_publication() {
823추가: for choice in [
824추가: Some(ConflictChoice::Overwrite),
825추가: Some(ConflictChoice::Rename),
826추가: None,
827추가: ] {
828추가: let s = Scratch::new();
829추가: fixture(&s, &["a", "b", "c"]);
830추가: assert!(PAYLOAD.len() <= 64 && PAYLOAD.len() * 3 > 64);
831추가: if choice.is_none() {
832추가: fs::remove_file(s.0.join("output/c")).unwrap();
833추가: }
834추가: let events = run(
835추가: &s,
836추가: request(&s),
837추가: Some("space-one-output"),
838추가: vec![],
839추가: |event| match event {
840추가: Message::ConflictRequired {
841추가: challenge_id,
842추가: entry_id,
843추가: ..
844추가: } => {
845추가: let choice = if *entry_id < 2 {
846추가: ConflictChoice::Skip
847추가: } else {
848추가: choice.unwrap()
849추가: };
850추가: Some(vec![reply(*challenge_id, choice, false)])
851추가: }
852추가: _ => None,
853추가: },
854추가: );
855추가: assert_eq!(
856추가: terminal(&events).outcome,
857추가: Outcome::Completed,
858추가: "{choice:?}: {events:?}"
859추가: );
860추가: assert_eq!(terminal(&events).publication, Publication::Complete);
861추가: assert_eq!(terminal(&events).created_count, 1);
862추가: assert_eq!(created(&events), 1);
863추가: assert_eq!(questions(&events), if choice.is_some() { 3 } else { 2 });
864추가: assert_eq!(fs::read(s.0.join("output/a")).unwrap(), b"original");
865추가: assert_eq!(fs::read(s.0.join("output/b")).unwrap(), b"original");
866추가: let output = if choice == Some(ConflictChoice::Rename) {
867추가: "c (1)"
868추가: } else {
869추가: "c"
870추가: };
871추가: assert_eq!(fs::read(s.0.join("output").join(output)).unwrap(), PAYLOAD);
872추가: if choice == Some(ConflictChoice::Rename) {
873추가: assert_eq!(fs::read(s.0.join("output/c")).unwrap(), b"original");
874추가: }
875추가: assert!(s.0.join("paused").exists());
876추가: }
877추가: }
878추가: #[cfg(target_os = "linux")]
879추가: #[test]
880추가: fn insufficient_destination_space_does_not_prevent_cancellation() {
881추가: let s = Scratch::new();
882추가: fixture(&s, &["a"]);
883추가: let events = run(
884추가: &s,
885추가: request(&s),
886추가: Some("space-destination"),
887추가: vec![],
888추가: |event| matches!(event, Message::ConflictRequired { .. }).then(|| vec![Message::Cancel]),
889추가: );
890추가: assert_eq!(questions(&events), 1, "{events:?}");
891추가: assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}");
892추가: assert_eq!(terminal(&events).publication, Publication::None);
893추가: assert_eq!(fs::read(s.0.join("output/a")).unwrap(), b"original");
894추가: }
895추가: #[cfg(target_os = "linux")]
896추가: #[test]
897추가: fn interactive_staging_space_and_integrity_checks_remain_before_questions() {
898추가: for corrupt in [false, true] {
899추가: let s = Scratch::new();
900추가: fixture(&s, &["a"]);
901추가: if corrupt {
902추가: let mut bytes = fs::read(s.0.join("input")).unwrap();
903추가: let at = bytes
904추가: .windows(PAYLOAD.len())
905추가: .position(|bytes| bytes == PAYLOAD)
906추가: .unwrap();
907추가: bytes[at] ^= 1;
908추가: fs::write(s.0.join("input"), bytes).unwrap();
909추가: }
910추가: let fault = if corrupt {
911추가: "space-destination"
912추가: } else {
913추가: "space-stage"
914추가: };
915추가: let events = run(&s, request(&s), Some(fault), vec![], |_| None);
916추가: assert_eq!(
917추가: terminal(&events).error,
918추가: if corrupt {
919추가: ErrorCode::Integrity
920추가: } else {
921추가: ErrorCode::DiskFull
922추가: },
923추가: "{events:?}"
924추가: );
925추가: assert_eq!(questions(&events), 0);
926추가: assert_eq!(created(&events), 0);
927추가: assert_eq!(terminal(&events).publication, Publication::None);
928추가: assert_eq!(fs::read(s.0.join("output/a")).unwrap(), b"original");
929추가: }
930추가: }
수정tests/rust-archive-worker/io_fault.c+13-1
@@ -116,11 +116,16 @@ int fstatvfs(int fd, struct statvfs *value) {
116116 if (fstat(fd, &st)) return -1;
117117 int affected = !strcmp(fault, "space-error") || !strcmp(fault, "space-combined")
118118 || (!strcmp(fault, "space-stage") && S_ISREG(st.st_mode))
119삭제: || (!strcmp(fault, "space-destination") && S_ISDIR(st.st_mode));
119추가: || ((!strcmp(fault, "space-destination") || !strcmp(fault, "space-one-output")) && S_ISDIR(st.st_mode));
120120 if (!affected) return result;
121121 int marker = real_openat(AT_FDCWD, getenv("ZIPELO_TEST_MARKER"), O_CREAT | O_WRONLY, 0600);
122122 if (marker >= 0) close(marker);
123123 if (!strcmp(fault, "space-error")) { errno = EIO; return -1; }
124추가: if (!strcmp(fault, "space-one-output")) {
125추가: value->f_frsize = 1;
126추가: value->f_bavail = 64;
127추가: return 0;
128추가: }
124129 value->f_bavail = !strcmp(fault, "space-combined") ? (1536 * 1024) / value->f_frsize : 0;
125130 return 0;
126131}
@@ -136,3 +141,10 @@ int fsync(int fd) {
136141 }
137142 return real_fsync(fd);
138143}
144추가:
145추가: int renameat(int oldfd, const char *oldname, int newfd, const char *newname) {
146추가: const char *fault = getenv("ZIPELO_TEST_FAULT");
147추가: if (fault && !strcmp(fault, "replace-fail")) { errno = EIO; return -1; }
148추가: int (*real_renameat)(int, const char *, int, const char *) = dlsym(RTLD_NEXT, "renameat");
149추가: return real_renameat(oldfd, oldname, newfd, newname);
150추가: }
수정tests/rust-archive-worker/main.rs+4-0
@@ -1609,3 +1609,7 @@ fn disk_full_error_tag_preserves_previous_tags_and_rejects_unknown() {
16091609mod folder_inputs;
16101610
16111611mod zip_names;
1612추가:
1613추가: mod conflict_wire;
1614추가:
1615추가: mod conflicts;