team-ljyzipelo

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