team-ljyzipelo

공개

충돌 선택 공용 타입과 코덱을 추가함

작성자
시로사키 하나
작성 시각
커밋
6ee28153efb356c3eb885cc95a17f9f0647ef85d
부모
38ea811
이 시점의 파일 보기

변경된 파일 6개

+376-10
수정experiments/rust-archive-worker/README.md+14-2
@@ -57,15 +57,27 @@ 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추가: 공용 타입과 codec만 준비된 단계입니다. 현재 실행 경로는 revision 2의 `Start`를 유지하며 `StartInteractive`는 아직 처리하지 않습니다. 충돌 런타임 구현과 앱 연동 검증이 끝나기 전에는 새 요청을 실제 기능에 활성화하지 않습니다. 이 상태는 덮어쓰기 기능의 구현 완료를 뜻하지 않습니다.
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 이름은 작업자가 같은 폴더 안의 미사용 번호 이름으로 정합니다. 일괄 적용은 현재 작업의 남은 일반 파일 충돌에만 적용합니다. 질문은 한 번에 하나이며 잘못되거나 중복된 응답은 Protocol, 답변 전 EOF도 Protocol입니다. 취소를 처리하고 기존 300초 제한에 대기 시간을 포함합니다.
78추가: - 전부 건너뛰고 새 출력도 없으면 Completed, Publication::None, created_count=0, Durability::NotApplicable입니다. 새 폴더가 만들어졌다면 해당 Output과 실제 집계를 유지합니다. 교체는 created_count에 포함하며 건너뛰기는 제외합니다.
79추가: - 런타임의 목표는 전체 무결성 검증 후 질문하고 목적지 임시 파일 기록, 검증, sync와 close를 마친 뒤 교체하는 것입니다. 교체 전 실패에는 원본을 보존하고 교체 후 오류에는 실제 게시, 내구성과 정리 상태를 보고합니다. 전체 작업의 원상 복구를 약속하지 않습니다.
80추가:
6981## 검증과 의존성
7082
7183시험은 `tests/rust-archive-worker`에 있습니다. Python 표준 라이브러리로 만든 ZIP/TAR/GZ fixture와 실제 자식 프로세스를 사용합니다. 전체 검증 명령은 저장소 루트의 `python3 tests/ci/run_rust.py local`입니다. Windows 교차 빌드는 실제 Windows 실행 검증을 대신하지 않습니다.
수정experiments/rust-archive-worker/contract.json+36-8
@@ -1,5 +1,5 @@
11{
2삭제: "status": "implemented-streaming-runtime",
2추가: "status": "revision-3-codec-ready-runtime-pending",
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. Runtime support is pending in this commit.",
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 and binary codec ready; conflict runtime and frontend integration are not implemented or verified by this commit. Existing revision 2 Start execution remains unchanged."
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 {
@@ -192,5 +202,23 @@
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": "codec-ready-runtime-pending",
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.",
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": "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."
195223 }
196224}
수정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/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/main.rs+2-0
@@ -1609,3 +1609,5 @@ fn disk_full_error_tag_preserves_previous_tags_and_rejects_unknown() {
16091609mod folder_inputs;
16101610
16111611mod zip_names;
1612추가:
1613추가: mod conflict_wire;