| 1 | use crate::archive_ui as ui; |
| 2 | use std::{ |
| 3 | cell::RefCell, |
| 4 | io::{self, Read, Write}, |
| 5 | path::PathBuf, |
| 6 | process::{Command, Stdio}, |
| 7 | rc::Rc, |
| 8 | sync::{ |
| 9 | Arc, Mutex, |
| 10 | atomic::{AtomicBool, Ordering}, |
| 11 | mpsc::{self, Receiver, SyncSender}, |
| 12 | }, |
| 13 | thread::{self, JoinHandle}, |
| 14 | time::{Duration, Instant}, |
| 15 | }; |
| 16 | use worker_protocol::{protocol as wire, wire as codec}; |
| 17 | |
| 18 | macro_rules! convert_enum { |
| 19 | ($name:ident, $from:ty, $to:ty, $($variant:ident),+) => { |
| 20 | fn $name(value: $from) -> $to { |
| 21 | match value { $(<$from>::$variant => <$to>::$variant),+ } |
| 22 | } |
| 23 | }; |
| 24 | } |
| 25 | convert_enum!( |
| 26 | format_to_wire, |
| 27 | ui::Format, |
| 28 | wire::Format, |
| 29 | Zip, |
| 30 | Tar, |
| 31 | Gzip, |
| 32 | TarGzip, |
| 33 | SevenZip |
| 34 | ); |
| 35 | convert_enum!( |
| 36 | format_to_ui, |
| 37 | wire::Format, |
| 38 | ui::Format, |
| 39 | Zip, |
| 40 | Tar, |
| 41 | Gzip, |
| 42 | TarGzip, |
| 43 | SevenZip |
| 44 | ); |
| 45 | convert_enum!( |
| 46 | kind_to_ui, |
| 47 | wire::EntryKind, |
| 48 | ui::Kind, |
| 49 | File, |
| 50 | Directory, |
| 51 | Link, |
| 52 | Other |
| 53 | ); |
| 54 | convert_enum!( |
| 55 | stage_to_ui, |
| 56 | wire::Stage, |
| 57 | ui::Stage, |
| 58 | Scan, |
| 59 | Read, |
| 60 | Decode, |
| 61 | Write, |
| 62 | Verify, |
| 63 | Commit |
| 64 | ); |
| 65 | convert_enum!( |
| 66 | disposition_to_ui, |
| 67 | wire::Disposition, |
| 68 | ui::Disposition, |
| 69 | Created, |
| 70 | PartialRetained, |
| 71 | Removed, |
| 72 | CommitUncertain |
| 73 | ); |
| 74 | convert_enum!( |
| 75 | outcome_to_ui, |
| 76 | wire::Outcome, |
| 77 | ui::Outcome, |
| 78 | Completed, |
| 79 | Failed, |
| 80 | Cancelled |
| 81 | ); |
| 82 | convert_enum!( |
| 83 | publication_to_ui, |
| 84 | wire::Publication, |
| 85 | ui::Publication, |
| 86 | None, |
| 87 | Partial, |
| 88 | Complete, |
| 89 | Uncertain |
| 90 | ); |
| 91 | convert_enum!( |
| 92 | durability_to_ui, |
| 93 | wire::Durability, |
| 94 | ui::Durability, |
| 95 | NotApplicable, |
| 96 | Synced, |
| 97 | Unconfirmed, |
| 98 | Failed |
| 99 | ); |
| 100 | convert_enum!( |
| 101 | cleanup_to_ui, |
| 102 | wire::Cleanup, |
| 103 | ui::Cleanup, |
| 104 | Complete, |
| 105 | Failed, |
| 106 | Unconfirmed |
| 107 | ); |
| 108 | convert_enum!( |
| 109 | cancel_to_ui, |
| 110 | wire::CancelStatus, |
| 111 | ui::CancelStatus, |
| 112 | Requested, |
| 113 | AlreadyRequested, |
| 114 | TooLate, |
| 115 | Finished |
| 116 | ); |
| 117 | fn list_to_wire(id: ui::ListId) -> wire::ListId { |
| 118 | wire::ListId { |
| 119 | catalog_version: id.catalog_version, |
| 120 | format: format_to_wire(id.format), |
| 121 | source_object: match id.source_object { |
| 122 | ui::SourceObject::Unix { device, inode } => wire::SourceObject::Unix { device, inode }, |
| 123 | ui::SourceObject::Windows { volume, file_id } => wire::SourceObject::Windows { |
| 124 | volume_serial: volume, |
| 125 | file_id, |
| 126 | }, |
| 127 | }, |
| 128 | archive_bytes: id.archive_bytes, |
| 129 | archive_sha256: id.archive_sha256, |
| 130 | } |
| 131 | } |
| 132 | fn list_to_ui(id: wire::ListId) -> ui::ListId { |
| 133 | ui::ListId { |
| 134 | catalog_version: id.catalog_version, |
| 135 | format: format_to_ui(id.format), |
| 136 | source_object: match id.source_object { |
| 137 | wire::SourceObject::Unix { device, inode } => ui::SourceObject::Unix { device, inode }, |
| 138 | wire::SourceObject::Windows { |
| 139 | volume_serial, |
| 140 | file_id, |
| 141 | } => ui::SourceObject::Windows { |
| 142 | volume: volume_serial, |
| 143 | file_id, |
| 144 | }, |
| 145 | }, |
| 146 | archive_bytes: id.archive_bytes, |
| 147 | archive_sha256: id.archive_sha256, |
| 148 | } |
| 149 | } |
| 150 | fn start_to_wire(start: ui::Start) -> wire::Start { |
| 151 | let action = match start { |
| 152 | ui::Start::List { archive } => wire::Action::List { |
| 153 | archive: wire::NativePath::from_path(&archive), |
| 154 | }, |
| 155 | ui::Start::Extract { |
| 156 | archive, |
| 157 | destination, |
| 158 | selection, |
| 159 | list_id, |
| 160 | gzip_output_name, |
| 161 | } => wire::Action::Extract { |
| 162 | archive: wire::NativePath::from_path(&archive), |
| 163 | destination: wire::NativePath::from_path(&destination), |
| 164 | selection: match selection { |
| 165 | ui::Selection::All => wire::Selection::All, |
| 166 | ui::Selection::EntryIds(ids) => wire::Selection::EntryIds(ids), |
| 167 | }, |
| 168 | list_id: Some(list_to_wire(list_id)), |
| 169 | gzip_output_name, |
| 170 | }, |
| 171 | ui::Start::CreateZip { |
| 172 | sources, |
| 173 | output_file, |
| 174 | method, |
| 175 | aes256, |
| 176 | } => wire::Action::CreateZip { |
| 177 | sources: sources |
| 178 | .into_iter() |
| 179 | .map(|(path, archive_name)| wire::Source { |
| 180 | path: wire::NativePath::from_path(&path), |
| 181 | archive_name, |
| 182 | }) |
| 183 | .collect(), |
| 184 | output_file: wire::NativePath::from_path(&output_file), |
| 185 | method: match method { |
| 186 | ui::Method::Store => wire::Method::Store, |
| 187 | ui::Method::Deflate => wire::Method::Deflate, |
| 188 | }, |
| 189 | encryption: if aes256 { |
| 190 | wire::Encryption::Aes256 |
| 191 | } else { |
| 192 | wire::Encryption::None |
| 193 | }, |
| 194 | }, |
| 195 | }; |
| 196 | wire::Start { |
| 197 | action, |
| 198 | limits: wire::Limits::default(), |
| 199 | } |
| 200 | } |
| 201 | fn error_to_ui(error: wire::ErrorCode) -> Option<ui::ErrorCode> { |
| 202 | Some(match error { |
| 203 | wire::ErrorCode::None => return None, |
| 204 | wire::ErrorCode::Integrity => ui::ErrorCode::Integrity, |
| 205 | wire::ErrorCode::UnsupportedFormat => ui::ErrorCode::UnsupportedFormat, |
| 206 | wire::ErrorCode::UnsupportedFeature => ui::ErrorCode::UnsupportedFeature, |
| 207 | wire::ErrorCode::WrongPassword => ui::ErrorCode::WrongPassword, |
| 208 | wire::ErrorCode::UnsafePath => ui::ErrorCode::UnsafePath, |
| 209 | wire::ErrorCode::Conflict => ui::ErrorCode::Conflict, |
| 210 | wire::ErrorCode::Limit => ui::ErrorCode::Limit, |
| 211 | wire::ErrorCode::Io => ui::ErrorCode::Io, |
| 212 | wire::ErrorCode::DiskFull => ui::ErrorCode::DiskFull, |
| 213 | wire::ErrorCode::Protocol => ui::ErrorCode::Protocol, |
| 214 | wire::ErrorCode::Internal => ui::ErrorCode::Internal, |
| 215 | wire::ErrorCode::SourceChanged => ui::ErrorCode::SourceChanged, |
| 216 | wire::ErrorCode::InvalidRequest => ui::ErrorCode::InvalidRequest, |
| 217 | }) |
| 218 | } |
| 219 | fn event_to_ui( |
| 220 | message: wire::Message, |
| 221 | expected: Option<wire::ActionKind>, |
| 222 | ) -> Result<ui::Event, ()> { |
| 223 | Ok(match message { |
| 224 | wire::Message::Accepted { action, encryption } if expected == Some(action) => { |
| 225 | ui::Event::Accepted { encryption } |
| 226 | } |
| 227 | wire::Message::Entry(entry) => ui::Event::Entry(ui::Entry { |
| 228 | id: entry.entry_id, |
| 229 | name: entry.name, |
| 230 | kind: kind_to_ui(entry.kind), |
| 231 | bytes: Some(entry.size), |
| 232 | packed: Some(entry.compressed_size), |
| 233 | encrypted: entry.encrypted, |
| 234 | }), |
| 235 | wire::Message::ListEnd { |
| 236 | entry_count, |
| 237 | list_id, |
| 238 | } => ui::Event::ListEnd { |
| 239 | entry_count, |
| 240 | list_id: list_to_ui(list_id), |
| 241 | }, |
| 242 | wire::Message::PasswordRequired { |
| 243 | challenge_id, |
| 244 | attempt, |
| 245 | purpose, |
| 246 | } => ui::Event::PasswordRequired { |
| 247 | challenge_id, |
| 248 | attempt, |
| 249 | encrypt: purpose == wire::PasswordPurpose::Encrypt, |
| 250 | }, |
| 251 | wire::Message::Progress { |
| 252 | stage, |
| 253 | processed_bytes, |
| 254 | total_bytes, |
| 255 | completed_entries, |
| 256 | } => ui::Event::Progress { |
| 257 | stage: stage_to_ui(stage), |
| 258 | processed: processed_bytes, |
| 259 | total: total_bytes, |
| 260 | completed_entries: completed_entries.into(), |
| 261 | }, |
| 262 | wire::Message::Output { |
| 263 | entry_id, |
| 264 | relative_name, |
| 265 | disposition, |
| 266 | } => ui::Event::Output { |
| 267 | entry_id, |
| 268 | relative_name, |
| 269 | disposition: disposition_to_ui(disposition), |
| 270 | }, |
| 271 | wire::Message::CancelAck { |
| 272 | request_sequence, |
| 273 | status, |
| 274 | } => ui::Event::CancelAck { |
| 275 | request_sequence, |
| 276 | status: cancel_to_ui(status), |
| 277 | }, |
| 278 | wire::Message::Terminal(terminal) => ui::Event::Terminal(ui::Terminal { |
| 279 | outcome: outcome_to_ui(terminal.outcome), |
| 280 | error: error_to_ui(terminal.error), |
| 281 | publication: publication_to_ui(terminal.publication), |
| 282 | created_count: terminal.created_count, |
| 283 | retained_partial_count: terminal.retained_partial_count, |
| 284 | durability: durability_to_ui(terminal.durability), |
| 285 | cleanup: cleanup_to_ui(terminal.cleanup), |
| 286 | }), |
| 287 | _ => return Err(()), |
| 288 | }) |
| 289 | } |
| 290 | |
| 291 | // 실제 파이프 쓰기는 백그라운드에서 수행하고 UI에서는 한 프레임만 직렬화함. |
| 292 | #[derive(Clone, Default)] |
| 293 | struct FrameBuffer(Rc<RefCell<Vec<u8>>>); |
| 294 | impl Write for FrameBuffer { |
| 295 | fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { |
| 296 | let mut buffer = self.0.borrow_mut(); |
| 297 | if buffer.len().saturating_add(bytes.len()) > codec::MAX_BODY + 32 { |
| 298 | return Err(io::Error::other("요청 프레임 한도 초과")); |
| 299 | } |
| 300 | buffer.extend_from_slice(bytes); |
| 301 | Ok(bytes.len()) |
| 302 | } |
| 303 | fn flush(&mut self) -> io::Result<()> { |
| 304 | Ok(()) |
| 305 | } |
| 306 | } |
| 307 | struct Frame(Vec<u8>, bool); |
| 308 | impl Drop for Frame { |
| 309 | fn drop(&mut self) { |
| 310 | self.0.fill(0); |
| 311 | } |
| 312 | } |
| 313 | fn notify(events: &SyncSender<ui::HostEvent>, event: ui::HostEvent) -> bool { |
| 314 | events.send(event).is_ok() |
| 315 | } |
| 316 | fn fault(events: &SyncSender<ui::HostEvent>, stop: &AtomicBool, message: &str) { |
| 317 | stop.store(true, Ordering::Release); |
| 318 | notify(events, ui::HostEvent::Fault(message.into())); |
| 319 | } |
| 320 | |
| 321 | pub struct ProcessFactory { |
| 322 | worker: PathBuf, |
| 323 | } |
| 324 | impl ProcessFactory { |
| 325 | pub fn new(worker: PathBuf) -> Self { |
| 326 | Self { worker } |
| 327 | } |
| 328 | pub fn sibling() -> Result<Self, String> { |
| 329 | let executable = |
| 330 | std::env::current_exe().map_err(|_| "앱 실행 위치를 확인하지 못했습니다")?; |
| 331 | let parent = executable.parent().ok_or("앱 실행 폴더가 없습니다")?; |
| 332 | Ok(Self::new(parent.join(if cfg!(windows) { |
| 333 | "zipelo-archive-worker.exe" |
| 334 | } else { |
| 335 | "zipelo-archive-worker" |
| 336 | }))) |
| 337 | } |
| 338 | } |
| 339 | impl ui::Factory for ProcessFactory { |
| 340 | fn connect(&mut self, job_id: u64) -> Result<Box<dyn ui::Connection>, String> { |
| 341 | if !self.worker.is_absolute() || job_id == 0 { |
| 342 | return Err("작업자 경로 또는 작업 ID가 올바르지 않습니다".into()); |
| 343 | } |
| 344 | let (send, requests) = mpsc::sync_channel::<Frame>(8); |
| 345 | let (events, receive) = mpsc::sync_channel(64); |
| 346 | let (ready, started) = mpsc::sync_channel(1); |
| 347 | let stop = Arc::new(AtomicBool::new(false)); |
| 348 | let done = Arc::new(AtomicBool::new(false)); |
| 349 | let expected = Arc::new(Mutex::new(None)); |
| 350 | let worker = self.worker.clone(); |
| 351 | let worker_stop = stop.clone(); |
| 352 | let worker_done = done.clone(); |
| 353 | let worker_expected = expected.clone(); |
| 354 | let supervisor = thread::Builder::new() |
| 355 | .name("zipelo-worker-owner".into()) |
| 356 | .spawn(move || { |
| 357 | let mut command = Command::new(worker); |
| 358 | command |
| 359 | .stdin(Stdio::piped()) |
| 360 | .stdout(Stdio::piped()) |
| 361 | .stderr(Stdio::piped()); |
| 362 | #[cfg(windows)] |
| 363 | { |
| 364 | use std::os::windows::process::CommandExt; |
| 365 | command.creation_flags(0x08000000); |
| 366 | } |
| 367 | let child = match command.spawn() { |
| 368 | Ok(child) => child, |
| 369 | Err(_) => { |
| 370 | let _ = ready.send(Err( |
| 371 | "작업자를 실행하지 못했습니다. 앱과 작업자를 함께 설치하세요" |
| 372 | .to_string(), |
| 373 | )); |
| 374 | return; |
| 375 | } |
| 376 | }; |
| 377 | if ready.send(Ok(())).is_err() { |
| 378 | let mut child = child; |
| 379 | let _ = child.kill(); |
| 380 | let _ = child.wait(); |
| 381 | return; |
| 382 | } |
| 383 | supervise( |
| 384 | child, |
| 385 | job_id, |
| 386 | requests, |
| 387 | events, |
| 388 | worker_stop, |
| 389 | worker_done, |
| 390 | worker_expected, |
| 391 | ); |
| 392 | }) |
| 393 | .map_err(|_| "작업자 관리 스레드를 시작하지 못했습니다")?; |
| 394 | match started.recv() { |
| 395 | Ok(Ok(())) => { |
| 396 | let buffer = FrameBuffer::default(); |
| 397 | Ok(Box::new(ProcessConnection { |
| 398 | job_id, |
| 399 | next: 0, |
| 400 | writer: codec::Writer::new(buffer.clone(), job_id), |
| 401 | buffer, |
| 402 | send: Some(send), |
| 403 | receive: Some(receive), |
| 404 | stop, |
| 405 | supervisor: Some(supervisor), |
| 406 | expected, |
| 407 | done, |
| 408 | disconnected: false, |
| 409 | reaped: false, |
| 410 | })) |
| 411 | } |
| 412 | result => { |
| 413 | stop.store(true, Ordering::Release); |
| 414 | drop(send); |
| 415 | drop(receive); |
| 416 | let _ = supervisor.join(); |
| 417 | Err(result |
| 418 | .ok() |
| 419 | .and_then(Result::err) |
| 420 | .unwrap_or_else(|| "작업자 시작 결과가 없습니다".into())) |
| 421 | } |
| 422 | } |
| 423 | } |
| 424 | } |
| 425 | struct ProcessConnection { |
| 426 | job_id: u64, |
| 427 | next: u64, |
| 428 | writer: codec::Writer<FrameBuffer>, |
| 429 | buffer: FrameBuffer, |
| 430 | send: Option<SyncSender<Frame>>, |
| 431 | receive: Option<Receiver<ui::HostEvent>>, |
| 432 | stop: Arc<AtomicBool>, |
| 433 | supervisor: Option<JoinHandle<()>>, |
| 434 | expected: Arc<Mutex<Option<wire::ActionKind>>>, |
| 435 | done: Arc<AtomicBool>, |
| 436 | disconnected: bool, |
| 437 | reaped: bool, |
| 438 | } |
| 439 | impl ui::Connection for ProcessConnection { |
| 440 | fn send(&mut self, request: ui::Request) -> Result<(), String> { |
| 441 | if self.stop.load(Ordering::Acquire) |
| 442 | || request.job_id != self.job_id |
| 443 | || request.sequence != self.next |
| 444 | || self.next >= codec::MAX_FRAMES |
| 445 | { |
| 446 | self.stop.store(true, Ordering::Release); |
| 447 | return Err("작업자 요청 채널이 닫혔거나 순서가 올바르지 않습니다".into()); |
| 448 | } |
| 449 | let is_cancel = matches!(request.command, ui::Command::Cancel); |
| 450 | let message = match request.command { |
| 451 | ui::Command::Start(start) => { |
| 452 | let start = start_to_wire(start); |
| 453 | *self.expected.lock().map_err(|_| { |
| 454 | self.stop.store(true, Ordering::Release); |
| 455 | "작업자 요청 상태 오류" |
| 456 | })? = Some(start.action.kind()); |
| 457 | wire::Message::Start(start) |
| 458 | } |
| 459 | ui::Command::Cancel => wire::Message::Cancel, |
| 460 | ui::Command::Password { |
| 461 | challenge_id, |
| 462 | secret, |
| 463 | } => wire::Message::Password { |
| 464 | challenge_id, |
| 465 | secret: wire::Secret(secret.as_bytes().to_vec()), |
| 466 | }, |
| 467 | }; |
| 468 | if self.writer.send(&message).is_err() { |
| 469 | self.buffer.0.borrow_mut().fill(0); |
| 470 | self.buffer.0.borrow_mut().clear(); |
| 471 | self.stop.store(true, Ordering::Release); |
| 472 | return Err("작업자 요청을 직렬화하지 못했습니다".into()); |
| 473 | } |
| 474 | let bytes = Frame(std::mem::take(&mut *self.buffer.0.borrow_mut()), is_cancel); |
| 475 | if self.send.as_ref().unwrap().try_send(bytes).is_err() { |
| 476 | if is_cancel && self.done.load(Ordering::Acquire) { |
| 477 | self.next += 1; |
| 478 | return Ok(()); |
| 479 | } |
| 480 | self.stop.store(true, Ordering::Release); |
| 481 | return Err("작업자 요청 대기열이 닫혔거나 가득 찼습니다".into()); |
| 482 | } |
| 483 | self.next += 1; |
| 484 | Ok(()) |
| 485 | } |
| 486 | fn poll(&mut self) -> Option<ui::HostEvent> { |
| 487 | match self.receive.as_ref()?.try_recv() { |
| 488 | Ok(event) => { |
| 489 | if matches!(event, ui::HostEvent::Exited { .. }) { |
| 490 | self.reaped = true; |
| 491 | } |
| 492 | Some(event) |
| 493 | } |
| 494 | Err(mpsc::TryRecvError::Empty) => None, |
| 495 | Err(mpsc::TryRecvError::Disconnected) if !self.reaped && !self.disconnected => { |
| 496 | self.disconnected = true; |
| 497 | Some(ui::HostEvent::Fault( |
| 498 | "작업자 통신 스레드가 종료됐습니다".into(), |
| 499 | )) |
| 500 | } |
| 501 | Err(_) => None, |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | impl Drop for ProcessConnection { |
| 506 | fn drop(&mut self) { |
| 507 | self.stop.store(true, Ordering::Release); |
| 508 | self.send.take(); |
| 509 | self.receive.take(); |
| 510 | if let Some(supervisor) = self.supervisor.take() { |
| 511 | let _ = supervisor.join(); |
| 512 | } |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | fn supervise( |
| 517 | mut child: std::process::Child, |
| 518 | job_id: u64, |
| 519 | requests: Receiver<Frame>, |
| 520 | events: SyncSender<ui::HostEvent>, |
| 521 | stop: Arc<AtomicBool>, |
| 522 | done: Arc<AtomicBool>, |
| 523 | expected: Arc<Mutex<Option<wire::ActionKind>>>, |
| 524 | ) { |
| 525 | let mut input = child.stdin.take().unwrap(); |
| 526 | let mut output = child.stdout.take().unwrap(); |
| 527 | let mut errors = child.stderr.take().unwrap(); |
| 528 | let mut threads = Vec::new(); |
| 529 | let cancel_write_failed = Arc::new(AtomicBool::new(false)); |
| 530 | let terminal_received = Arc::new(AtomicBool::new(false)); |
| 531 | let failed_cancel = cancel_write_failed.clone(); |
| 532 | let tx = events.clone(); |
| 533 | let abort = stop.clone(); |
| 534 | let finished = done.clone(); |
| 535 | threads.push( |
| 536 | thread::Builder::new() |
| 537 | .name("zipelo-worker-input".into()) |
| 538 | .spawn(move || { |
| 539 | while !finished.load(Ordering::Acquire) && !abort.load(Ordering::Acquire) { |
| 540 | match requests.recv_timeout(Duration::from_millis(10)) { |
| 541 | Ok(frame) => { |
| 542 | if input |
| 543 | .write_all(&frame.0) |
| 544 | .and_then(|_| input.flush()) |
| 545 | .is_err() |
| 546 | { |
| 547 | if frame.1 { |
| 548 | // 취소 쓰기 실패는 응답과 실제 종료 결과를 확인한 뒤 판단함. |
| 549 | failed_cancel.store(true, Ordering::Release); |
| 550 | } else { |
| 551 | fault(&tx, &abort, "작업자 요청 파이프 쓰기에 실패했습니다"); |
| 552 | } |
| 553 | break; |
| 554 | } |
| 555 | } |
| 556 | Err(mpsc::RecvTimeoutError::Timeout) => {} |
| 557 | Err(_) => break, |
| 558 | } |
| 559 | } |
| 560 | }), |
| 561 | ); |
| 562 | let tx = events.clone(); |
| 563 | let abort = stop.clone(); |
| 564 | let received_terminal = terminal_received.clone(); |
| 565 | threads.push( |
| 566 | thread::Builder::new() |
| 567 | .name("zipelo-worker-output".into()) |
| 568 | .spawn(move || { |
| 569 | let eof; |
| 570 | { |
| 571 | let mut reader = codec::Reader::new(&mut output); |
| 572 | eof = loop { |
| 573 | match reader.read() { |
| 574 | Ok(Some((job, sequence, message))) => { |
| 575 | let action = expected.lock().ok().and_then(|value| *value); |
| 576 | let event = event_to_ui(message, action); |
| 577 | if job != job_id || event.is_err() { |
| 578 | fault(&tx, &abort, "작업자 응답이 요청과 일치하지 않습니다"); |
| 579 | break false; |
| 580 | } |
| 581 | if matches!(event, Ok(ui::Event::Terminal(_))) { |
| 582 | received_terminal.store(true, Ordering::Release); |
| 583 | } |
| 584 | if !notify( |
| 585 | &tx, |
| 586 | ui::HostEvent::Frame { |
| 587 | job_id: job, |
| 588 | sequence, |
| 589 | event: event.unwrap(), |
| 590 | }, |
| 591 | ) { |
| 592 | return; |
| 593 | } |
| 594 | } |
| 595 | Ok(None) => break true, |
| 596 | Err(_) => { |
| 597 | fault(&tx, &abort, "작업자 응답 프레임을 읽지 못했습니다"); |
| 598 | break false; |
| 599 | } |
| 600 | } |
| 601 | }; |
| 602 | } |
| 603 | if eof || io::copy(&mut output, &mut io::sink()).is_ok() { |
| 604 | notify(&tx, ui::HostEvent::StdoutEof); |
| 605 | } |
| 606 | }), |
| 607 | ); |
| 608 | let tx = events.clone(); |
| 609 | let abort = stop.clone(); |
| 610 | threads.push( |
| 611 | thread::Builder::new() |
| 612 | .name("zipelo-worker-errors".into()) |
| 613 | .spawn(move || { |
| 614 | let mut bytes = [0u8; 4096]; |
| 615 | loop { |
| 616 | match errors.read(&mut bytes) { |
| 617 | Ok(0) => { |
| 618 | notify(&tx, ui::HostEvent::StderrEof); |
| 619 | break; |
| 620 | } |
| 621 | Ok(_) => {} |
| 622 | Err(error) if error.kind() == io::ErrorKind::Interrupted => {} |
| 623 | Err(_) => { |
| 624 | fault(&tx, &abort, "작업자 오류 파이프를 읽지 못했습니다"); |
| 625 | break; |
| 626 | } |
| 627 | } |
| 628 | } |
| 629 | }), |
| 630 | ); |
| 631 | let mut handles = Vec::new(); |
| 632 | for result in threads { |
| 633 | match result { |
| 634 | Ok(handle) => handles.push(handle), |
| 635 | Err(_) => fault(&events, &stop, "작업자 통신 스레드를 시작하지 못했습니다"), |
| 636 | } |
| 637 | } |
| 638 | let started = Instant::now(); |
| 639 | let status = loop { |
| 640 | if started.elapsed() >= Duration::from_secs(310) { |
| 641 | fault(&events, &stop, "작업자 처리 제한 시간을 초과했습니다"); |
| 642 | } |
| 643 | if stop.load(Ordering::Acquire) { |
| 644 | let _ = child.kill(); |
| 645 | } |
| 646 | match child.try_wait() { |
| 647 | Ok(Some(status)) => break Some(status), |
| 648 | Ok(None) => thread::sleep(Duration::from_millis(10)), |
| 649 | Err(_) => { |
| 650 | fault(&events, &stop, "작업자 종료 상태를 확인하지 못했습니다"); |
| 651 | let _ = child.kill(); |
| 652 | break child.wait().ok(); |
| 653 | } |
| 654 | } |
| 655 | }; |
| 656 | done.store(true, Ordering::Release); |
| 657 | for handle in handles { |
| 658 | if handle.join().is_err() { |
| 659 | fault(&events, &stop, "작업자 통신 스레드 회수에 실패했습니다"); |
| 660 | } |
| 661 | } |
| 662 | if cancel_write_failed.load(Ordering::Acquire) |
| 663 | && !(terminal_received.load(Ordering::Acquire) |
| 664 | && status.as_ref().is_some_and(|status| status.success())) |
| 665 | { |
| 666 | fault(&events, &stop, "작업자 요청 파이프 쓰기에 실패했습니다"); |
| 667 | } |
| 668 | if let Some(status) = status { |
| 669 | // 회수와 모든 파이프 핸들 정리가 끝난 뒤에만 닫기 허용 근거를 전달함. |
| 670 | notify(&events, ui::HostEvent::CleanupComplete); |
| 671 | notify( |
| 672 | &events, |
| 673 | ui::HostEvent::Exited { |
| 674 | success: status.success(), |
| 675 | }, |
| 676 | ); |
| 677 | } |
| 678 | } |