team-ljyzipelo

공개
226줄7.7 KB
1use std::{cell::RefCell, collections::VecDeque, rc::Rc};
2use zipelo_ui_memory_app::archive_ui::*;
3
4#[derive(Default)]
5pub struct State {
6 pub requests: Vec<(u64, &'static str)>,
7 pub starts: Vec<Start>,
8 pub password_seen: bool,
9 pub conflict_replies: Vec<(u64, ConflictChoice, bool)>,
10 /// 마지막으로 받은 암호 원문. 화면에서 입력한 암호가 그대로 전달됐는지 확인할 때 씀.
11 pub password: Vec<u8>,
12 pub job: u64,
13 sequence: u64,
14 pub queue: VecDeque<HostEvent>,
15 pub manual: bool,
16 pub list_format: Option<Format>,
17 pub fail_start: bool,
18 pub dropped_connections: usize,
19 pause: bool,
20}
21#[derive(Default, Clone)]
22pub struct FakeFactory {
23 pub state: Rc<RefCell<State>>,
24}
25impl FakeFactory {
26 pub fn manual() -> Self {
27 let f = Self::default();
28 f.state.borrow_mut().manual = true;
29 f
30 }
31}
32impl State {
33 pub fn frame(&mut self, event: Event) {
34 let sequence = self.sequence;
35 self.sequence += 1;
36 self.queue.push_back(HostEvent::Frame {
37 job_id: self.job,
38 sequence,
39 event,
40 });
41 }
42 pub fn finish(&mut self, outcome: Outcome, publication: Publication) {
43 self.frame(Event::Terminal(Terminal {
44 outcome,
45 error: None,
46 publication,
47 created_count: if publication == Publication::Complete {
48 1
49 } else {
50 0
51 },
52 retained_partial_count: 0,
53 durability: Durability::Synced,
54 cleanup: Cleanup::Complete,
55 }));
56 self.queue.push_back(HostEvent::StdoutEof);
57 self.queue.push_back(HostEvent::StderrEof);
58 self.queue.push_back(HostEvent::Exited { success: true });
59 }
60 fn complete_action(&mut self) {
61 match self.starts.last().cloned().unwrap() {
62 Start::List { archive } => {
63 self.frame(Event::Entry(Entry {
64 id: 0,
65 name: "읽어주세요.txt".into(),
66 kind: Kind::File,
67 bytes: Some(31),
68 packed: Some(54),
69 encrypted: false,
70 }));
71 let format = self.list_format.unwrap_or_else(|| {
72 if archive.extension().is_some_and(|x| x == "gz") {
73 Format::Gzip
74 } else {
75 Format::Zip
76 }
77 });
78 self.frame(Event::ListEnd {
79 entry_count: 1,
80 list_id: ListId {
81 catalog_version: 1,
82 format,
83 source_object: SourceObject::Unix {
84 device: 1,
85 inode: 1,
86 },
87 archive_bytes: 54,
88 archive_sha256: [7; 32],
89 },
90 });
91 self.finish(Outcome::Completed, Publication::None);
92 }
93 _ => {
94 self.frame(Event::Progress {
95 stage: Stage::Write,
96 processed: 31,
97 total: Some(31),
98 completed_entries: 1,
99 });
100 self.frame(Event::Output {
101 entry_id: Some(0),
102 relative_name: "읽어주세요.txt".into(),
103 disposition: Disposition::Created,
104 });
105 self.finish(Outcome::Completed, Publication::Complete);
106 }
107 }
108 }
109}
110struct FakeConnection {
111 state: Rc<RefCell<State>>,
112}
113impl Drop for FakeConnection {
114 fn drop(&mut self) {
115 self.state.borrow_mut().dropped_connections += 1;
116 }
117}
118impl Factory for FakeFactory {
119 fn connect(&mut self, job: u64) -> Result<Box<dyn Connection>, String> {
120 let mut s = self.state.borrow_mut();
121 s.job = job;
122 s.sequence = 0;
123 s.queue.clear();
124 s.pause = false;
125 Ok(Box::new(FakeConnection {
126 state: self.state.clone(),
127 }))
128 }
129}
130impl Connection for FakeConnection {
131 fn send(&mut self, request: Request) -> Result<(), String> {
132 let mut s = self.state.borrow_mut();
133 assert_eq!(s.job, request.job_id);
134 match request.command {
135 Command::Start(start) => {
136 if let Start::Extract {
137 list_id,
138 gzip_output_name,
139 ..
140 } = &start
141 {
142 let valid = match list_id.format {
143 Format::Gzip => gzip_output_name.as_deref().is_some_and(valid_leaf),
144 _ => gzip_output_name.is_none(),
145 };
146 if !valid {
147 return Err("형식에 맞지 않는 GZIP 출력명".into());
148 }
149 }
150 s.requests.push((request.sequence, "start"));
151 s.starts.push(start.clone());
152 if s.fail_start {
153 return Err("Start 전송 실패".into());
154 }
155 if !s.manual {
156 s.frame(Event::Accepted { encryption: false });
157 s.frame(Event::Progress {
158 stage: Stage::Scan,
159 processed: 0,
160 total: None,
161 completed_entries: 0,
162 });
163 if matches!(&start,Start::List {archive} if archive.file_name().is_some_and(|n|n.to_string_lossy().contains("locked")))
164 {
165 s.frame(Event::PasswordRequired {
166 challenge_id: 17,
167 attempt: 1,
168 encrypt: false,
169 });
170 } else {
171 s.complete_action();
172 }
173 }
174 }
175 Command::Password {
176 challenge_id,
177 secret,
178 } => {
179 assert_eq!(challenge_id, 17);
180 assert!(!secret.as_bytes().is_empty());
181 s.password_seen = true;
182 s.password = secret.as_bytes().to_vec();
183 s.requests.push((request.sequence, "password"));
184 if !s.manual {
185 s.complete_action();
186 }
187 }
188 Command::ConflictReply {
189 challenge_id,
190 choice,
191 apply_to_remaining,
192 } => {
193 s.requests.push((request.sequence, "conflict"));
194 s.conflict_replies
195 .push((challenge_id, choice, apply_to_remaining));
196 }
197 Command::Cancel => {
198 s.requests.push((request.sequence, "cancel"));
199 if !s.manual {
200 let consumed = s
201 .queue
202 .iter()
203 .filter(|e| matches!(e, HostEvent::Frame { .. }))
204 .count() as u64;
205 s.sequence -= consumed;
206 s.queue.clear();
207 s.frame(Event::CancelAck {
208 request_sequence: request.sequence,
209 status: CancelStatus::Requested,
210 });
211 s.finish(Outcome::Cancelled, Publication::None);
212 }
213 }
214 }
215 Ok(())
216 }
217 fn poll(&mut self) -> Option<HostEvent> {
218 let mut s = self.state.borrow_mut();
219 if s.pause {
220 s.pause = false;
221 return None;
222 }
223 s.pause = true;
224 s.queue.pop_front()
225 }
226}