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