| 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 | convert_enum!( |
| 118 | conflict_to_wire, |
| 119 | ui::ConflictChoice, |
| 120 | wire::ConflictChoice, |
| 121 | Overwrite, |
| 122 | Skip, |
| 123 | Rename |
| 124 | ); |
| 125 | convert_enum!( |
| 126 | conflict_to_ui, |
| 127 | wire::ConflictChoice, |
| 128 | ui::ConflictChoice, |
| 129 | Overwrite, |
| 130 | Skip, |
| 131 | Rename |
| 132 | ); |
| 133 | fn list_to_wire(id: ui::ListId) -> wire::ListId { |
| 134 | wire::ListId { |
| 135 | catalog_version: id.catalog_version, |
| 136 | format: format_to_wire(id.format), |
| 137 | source_object: match id.source_object { |
| 138 | ui::SourceObject::Unix { device, inode } => wire::SourceObject::Unix { device, inode }, |
| 139 | ui::SourceObject::Windows { volume, file_id } => wire::SourceObject::Windows { |
| 140 | volume_serial: volume, |
| 141 | file_id, |
| 142 | }, |
| 143 | }, |
| 144 | archive_bytes: id.archive_bytes, |
| 145 | archive_sha256: id.archive_sha256, |
| 146 | } |
| 147 | } |
| 148 | fn list_to_ui(id: wire::ListId) -> ui::ListId { |
| 149 | ui::ListId { |
| 150 | catalog_version: id.catalog_version, |
| 151 | format: format_to_ui(id.format), |
| 152 | source_object: match id.source_object { |
| 153 | wire::SourceObject::Unix { device, inode } => ui::SourceObject::Unix { device, inode }, |
| 154 | wire::SourceObject::Windows { |
| 155 | volume_serial, |
| 156 | file_id, |
| 157 | } => ui::SourceObject::Windows { |
| 158 | volume: volume_serial, |
| 159 | file_id, |
| 160 | }, |
| 161 | }, |
| 162 | archive_bytes: id.archive_bytes, |
| 163 | archive_sha256: id.archive_sha256, |
| 164 | } |
| 165 | } |
| 166 | fn start_to_wire(start: ui::Start) -> wire::Start { |
| 167 | let action = match start { |
| 168 | ui::Start::List { archive } => wire::Action::List { |
| 169 | archive: wire::NativePath::from_path(&crate::archive_path::worker_path(&archive)), |
| 170 | }, |
| 171 | ui::Start::Extract { |
| 172 | archive, |
| 173 | destination, |
| 174 | selection, |
| 175 | list_id, |
| 176 | gzip_output_name, |
| 177 | } => wire::Action::Extract { |
| 178 | archive: wire::NativePath::from_path(&crate::archive_path::worker_path(&archive)), |
| 179 | destination: wire::NativePath::from_path(&crate::archive_path::worker_path( |
| 180 | &destination, |
| 181 | )), |
| 182 | selection: match selection { |
| 183 | ui::Selection::All => wire::Selection::All, |
| 184 | ui::Selection::EntryIds(ids) => wire::Selection::EntryIds(ids), |
| 185 | }, |
| 186 | list_id: Some(list_to_wire(list_id)), |
| 187 | gzip_output_name, |
| 188 | }, |
| 189 | ui::Start::CreateZip { |
| 190 | sources, |
| 191 | output_file, |
| 192 | method, |
| 193 | aes256, |
| 194 | } => wire::Action::CreateZip { |
| 195 | sources: sources |
| 196 | .into_iter() |
| 197 | .map(|(path, archive_name)| wire::Source { |
| 198 | path: wire::NativePath::from_path(&crate::archive_path::worker_path(&path)), |
| 199 | archive_name, |
| 200 | }) |
| 201 | .collect(), |
| 202 | output_file: wire::NativePath::from_path(&crate::archive_path::worker_path( |
| 203 | &output_file, |
| 204 | )), |
| 205 | method: match method { |
| 206 | ui::Method::Store => wire::Method::Store, |
| 207 | ui::Method::Deflate => wire::Method::Deflate, |
| 208 | }, |
| 209 | encryption: if aes256 { |
| 210 | wire::Encryption::Aes256 |
| 211 | } else { |
| 212 | wire::Encryption::None |
| 213 | }, |
| 214 | }, |
| 215 | }; |
| 216 | wire::Start { |
| 217 | action, |
| 218 | limits: wire::Limits::default(), |
| 219 | } |
| 220 | } |
| 221 | fn error_to_ui(error: wire::ErrorCode) -> Option<ui::ErrorCode> { |
| 222 | Some(match error { |
| 223 | wire::ErrorCode::None => return None, |
| 224 | wire::ErrorCode::Integrity => ui::ErrorCode::Integrity, |
| 225 | wire::ErrorCode::UnsupportedFormat => ui::ErrorCode::UnsupportedFormat, |
| 226 | wire::ErrorCode::UnsupportedFeature => ui::ErrorCode::UnsupportedFeature, |
| 227 | wire::ErrorCode::WrongPassword => ui::ErrorCode::WrongPassword, |
| 228 | wire::ErrorCode::UnsafePath => ui::ErrorCode::UnsafePath, |
| 229 | wire::ErrorCode::Conflict => ui::ErrorCode::Conflict, |
| 230 | wire::ErrorCode::Limit => ui::ErrorCode::Limit, |
| 231 | wire::ErrorCode::Io => ui::ErrorCode::Io, |
| 232 | wire::ErrorCode::DiskFull => ui::ErrorCode::DiskFull, |
| 233 | wire::ErrorCode::Protocol => ui::ErrorCode::Protocol, |
| 234 | wire::ErrorCode::Internal => ui::ErrorCode::Internal, |
| 235 | wire::ErrorCode::SourceChanged => ui::ErrorCode::SourceChanged, |
| 236 | wire::ErrorCode::InvalidRequest => ui::ErrorCode::InvalidRequest, |
| 237 | }) |
| 238 | } |
| 239 | fn event_to_ui( |
| 240 | message: wire::Message, |
| 241 | expected: Option<wire::ActionKind>, |
| 242 | ) -> Result<ui::Event, ()> { |
| 243 | Ok(match message { |
| 244 | wire::Message::Accepted { action, encryption } if expected == Some(action) => { |
| 245 | ui::Event::Accepted { encryption } |
| 246 | } |
| 247 | wire::Message::ResourceRequired { |
| 248 | challenge_id, |
| 249 | action, |
| 250 | scope, |
| 251 | usage, |
| 252 | soft_limits, |
| 253 | ceiling, |
| 254 | } if expected == Some(action) => ui::Event::ResourceRequired(ui::ResourceChallenge { |
| 255 | id: challenge_id, |
| 256 | action, |
| 257 | scope, |
| 258 | usage, |
| 259 | soft_limits, |
| 260 | ceiling, |
| 261 | }), |
| 262 | wire::Message::Entry(entry) => ui::Event::Entry(ui::Entry { |
| 263 | id: entry.entry_id, |
| 264 | name: entry.name, |
| 265 | kind: kind_to_ui(entry.kind), |
| 266 | bytes: Some(entry.size), |
| 267 | packed: Some(entry.compressed_size), |
| 268 | encrypted: entry.encrypted, |
| 269 | }), |
| 270 | wire::Message::ListEnd { |
| 271 | entry_count, |
| 272 | list_id, |
| 273 | } => ui::Event::ListEnd { |
| 274 | entry_count, |
| 275 | list_id: list_to_ui(list_id), |
| 276 | }, |
| 277 | wire::Message::PasswordRequired { |
| 278 | challenge_id, |
| 279 | attempt, |
| 280 | purpose, |
| 281 | } => ui::Event::PasswordRequired { |
| 282 | challenge_id, |
| 283 | attempt, |
| 284 | encrypt: purpose == wire::PasswordPurpose::Encrypt, |
| 285 | }, |
| 286 | wire::Message::ConflictRequired { |
| 287 | challenge_id, |
| 288 | entry_id, |
| 289 | relative_name, |
| 290 | incoming_size, |
| 291 | existing_size, |
| 292 | } if expected == Some(wire::ActionKind::Extract) => { |
| 293 | ui::Event::ConflictRequired(ui::Conflict { |
| 294 | challenge_id, |
| 295 | entry_id, |
| 296 | relative_name, |
| 297 | incoming_size, |
| 298 | existing_size, |
| 299 | }) |
| 300 | } |
| 301 | wire::Message::ConflictResolved { |
| 302 | entry_id, |
| 303 | relative_name, |
| 304 | choice, |
| 305 | } if expected == Some(wire::ActionKind::Extract) => { |
| 306 | ui::Event::ConflictResolved(ui::Resolution { |
| 307 | entry_id, |
| 308 | relative_name, |
| 309 | choice: conflict_to_ui(choice), |
| 310 | }) |
| 311 | } |
| 312 | wire::Message::Progress { |
| 313 | stage, |
| 314 | processed_bytes, |
| 315 | total_bytes, |
| 316 | completed_entries, |
| 317 | } => ui::Event::Progress { |
| 318 | stage: stage_to_ui(stage), |
| 319 | processed: processed_bytes, |
| 320 | total: total_bytes, |
| 321 | completed_entries: completed_entries.into(), |
| 322 | }, |
| 323 | wire::Message::Output { |
| 324 | entry_id, |
| 325 | relative_name, |
| 326 | disposition, |
| 327 | } => ui::Event::Output { |
| 328 | entry_id, |
| 329 | relative_name, |
| 330 | disposition: disposition_to_ui(disposition), |
| 331 | }, |
| 332 | wire::Message::CancelAck { |
| 333 | request_sequence, |
| 334 | status, |
| 335 | } => ui::Event::CancelAck { |
| 336 | request_sequence, |
| 337 | status: cancel_to_ui(status), |
| 338 | }, |
| 339 | wire::Message::Terminal(terminal) => ui::Event::Terminal(ui::Terminal { |
| 340 | outcome: outcome_to_ui(terminal.outcome), |
| 341 | error: error_to_ui(terminal.error), |
| 342 | publication: publication_to_ui(terminal.publication), |
| 343 | created_count: terminal.created_count, |
| 344 | retained_partial_count: terminal.retained_partial_count, |
| 345 | durability: durability_to_ui(terminal.durability), |
| 346 | cleanup: cleanup_to_ui(terminal.cleanup), |
| 347 | }), |
| 348 | _ => return Err(()), |
| 349 | }) |
| 350 | } |
| 351 | |
| 352 | // 실제 파이프 쓰기는 백그라운드에서 수행하고 UI에서는 한 프레임만 직렬화함. |
| 353 | #[derive(Clone, Default)] |
| 354 | struct FrameBuffer(Rc<RefCell<Vec<u8>>>); |
| 355 | impl Write for FrameBuffer { |
| 356 | fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { |
| 357 | let mut buffer = self.0.borrow_mut(); |
| 358 | if buffer.len().saturating_add(bytes.len()) > codec::MAX_BODY + 32 { |
| 359 | return Err(io::Error::other("요청 프레임 한도 초과")); |
| 360 | } |
| 361 | buffer.extend_from_slice(bytes); |
| 362 | Ok(bytes.len()) |
| 363 | } |
| 364 | fn flush(&mut self) -> io::Result<()> { |
| 365 | Ok(()) |
| 366 | } |
| 367 | } |
| 368 | struct Frame(Vec<u8>, bool); |
| 369 | impl Drop for Frame { |
| 370 | fn drop(&mut self) { |
| 371 | self.0.fill(0); |
| 372 | } |
| 373 | } |
| 374 | fn notify(events: &SyncSender<ui::HostEvent>, event: ui::HostEvent) -> bool { |
| 375 | events.send(event).is_ok() |
| 376 | } |
| 377 | fn fault(events: &SyncSender<ui::HostEvent>, stop: &AtomicBool, message: &str) { |
| 378 | stop.store(true, Ordering::Release); |
| 379 | notify(events, ui::HostEvent::Fault(message.into())); |
| 380 | } |
| 381 | |
| 382 | #[derive(Default)] |
| 383 | struct ResourceDeadline { |
| 384 | pending: Option<(u64, wire::ResourceScope)>, |
| 385 | approved: bool, |
| 386 | } |
| 387 | |
| 388 | pub struct ProcessFactory { |
| 389 | worker: PathBuf, |
| 390 | } |
| 391 | impl ProcessFactory { |
| 392 | pub fn new(worker: PathBuf) -> Self { |
| 393 | Self { worker } |
| 394 | } |
| 395 | pub fn sibling() -> Result<Self, String> { |
| 396 | let executable = |
| 397 | std::env::current_exe().map_err(|_| "앱 실행 위치를 확인하지 못했습니다")?; |
| 398 | let parent = executable.parent().ok_or("앱 실행 폴더가 없습니다")?; |
| 399 | Ok(Self::new(parent.join(if cfg!(windows) { |
| 400 | "zipelo-archive-worker.exe" |
| 401 | } else { |
| 402 | "zipelo-archive-worker" |
| 403 | }))) |
| 404 | } |
| 405 | } |
| 406 | impl ui::Factory for ProcessFactory { |
| 407 | fn connect(&mut self, job_id: u64) -> Result<Box<dyn ui::Connection>, String> { |
| 408 | if !self.worker.is_absolute() || job_id == 0 { |
| 409 | return Err("작업자 경로 또는 작업 ID가 올바르지 않습니다".into()); |
| 410 | } |
| 411 | let (send, requests) = mpsc::sync_channel::<Frame>(8); |
| 412 | let (events, receive) = mpsc::sync_channel(64); |
| 413 | let (ready, started) = mpsc::sync_channel(1); |
| 414 | let stop = Arc::new(AtomicBool::new(false)); |
| 415 | let done = Arc::new(AtomicBool::new(false)); |
| 416 | let expected = Arc::new(Mutex::new(None)); |
| 417 | let resources = Arc::new(Mutex::new(ResourceDeadline::default())); |
| 418 | let worker = self.worker.clone(); |
| 419 | let worker_stop = stop.clone(); |
| 420 | let worker_done = done.clone(); |
| 421 | let worker_expected = expected.clone(); |
| 422 | let worker_resources = resources.clone(); |
| 423 | let supervisor = thread::Builder::new() |
| 424 | .name("zipelo-worker-owner".into()) |
| 425 | .spawn(move || { |
| 426 | let mut command = Command::new(worker); |
| 427 | command |
| 428 | .stdin(Stdio::piped()) |
| 429 | .stdout(Stdio::piped()) |
| 430 | .stderr(Stdio::piped()); |
| 431 | #[cfg(windows)] |
| 432 | { |
| 433 | use std::os::windows::process::CommandExt; |
| 434 | command.creation_flags(0x08000000); |
| 435 | } |
| 436 | let child = match command.spawn() { |
| 437 | Ok(child) => child, |
| 438 | Err(_) => { |
| 439 | let _ = ready.send(Err( |
| 440 | "작업자를 실행하지 못했습니다. 앱과 작업자를 함께 설치하세요" |
| 441 | .to_string(), |
| 442 | )); |
| 443 | return; |
| 444 | } |
| 445 | }; |
| 446 | if ready.send(Ok(())).is_err() { |
| 447 | let mut child = child; |
| 448 | let _ = child.kill(); |
| 449 | let _ = child.wait(); |
| 450 | return; |
| 451 | } |
| 452 | supervise( |
| 453 | child, |
| 454 | job_id, |
| 455 | requests, |
| 456 | events, |
| 457 | worker_stop, |
| 458 | worker_done, |
| 459 | worker_expected, |
| 460 | worker_resources, |
| 461 | ); |
| 462 | }) |
| 463 | .map_err(|_| "작업자 관리 스레드를 시작하지 못했습니다")?; |
| 464 | match started.recv() { |
| 465 | Ok(Ok(())) => { |
| 466 | let buffer = FrameBuffer::default(); |
| 467 | Ok(Box::new(ProcessConnection { |
| 468 | job_id, |
| 469 | next: 0, |
| 470 | writer: codec::Writer::new(buffer.clone(), job_id), |
| 471 | buffer, |
| 472 | send: Some(send), |
| 473 | receive: Some(receive), |
| 474 | stop, |
| 475 | supervisor: Some(supervisor), |
| 476 | expected, |
| 477 | resources, |
| 478 | done, |
| 479 | disconnected: false, |
| 480 | reaped: false, |
| 481 | })) |
| 482 | } |
| 483 | result => { |
| 484 | stop.store(true, Ordering::Release); |
| 485 | drop(send); |
| 486 | drop(receive); |
| 487 | let _ = supervisor.join(); |
| 488 | Err(result |
| 489 | .ok() |
| 490 | .and_then(Result::err) |
| 491 | .unwrap_or_else(|| "작업자 시작 결과가 없습니다".into())) |
| 492 | } |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 | struct ProcessConnection { |
| 497 | job_id: u64, |
| 498 | next: u64, |
| 499 | writer: codec::Writer<FrameBuffer>, |
| 500 | buffer: FrameBuffer, |
| 501 | send: Option<SyncSender<Frame>>, |
| 502 | receive: Option<Receiver<ui::HostEvent>>, |
| 503 | stop: Arc<AtomicBool>, |
| 504 | supervisor: Option<JoinHandle<()>>, |
| 505 | expected: Arc<Mutex<Option<wire::ActionKind>>>, |
| 506 | resources: Arc<Mutex<ResourceDeadline>>, |
| 507 | done: Arc<AtomicBool>, |
| 508 | disconnected: bool, |
| 509 | reaped: bool, |
| 510 | } |
| 511 | impl ui::Connection for ProcessConnection { |
| 512 | fn send(&mut self, request: ui::Request) -> Result<(), String> { |
| 513 | if self.stop.load(Ordering::Acquire) |
| 514 | || request.job_id != self.job_id |
| 515 | || request.sequence != self.next |
| 516 | || self.next >= codec::MAX_FRAMES |
| 517 | { |
| 518 | self.stop.store(true, Ordering::Release); |
| 519 | return Err("작업자 요청 채널이 닫혔거나 순서가 올바르지 않습니다".into()); |
| 520 | } |
| 521 | let is_cancel = matches!(request.command, ui::Command::Cancel); |
| 522 | let expanded = matches!(&request.command, ui::Command::StartExpanded(_)); |
| 523 | let message = match request.command { |
| 524 | ui::Command::Start(start) | ui::Command::StartExpanded(start) => { |
| 525 | let start = start_to_wire(start); |
| 526 | *self.expected.lock().map_err(|_| { |
| 527 | self.stop.store(true, Ordering::Release); |
| 528 | "작업자 요청 상태 오류" |
| 529 | })? = Some(start.action.kind()); |
| 530 | let ceiling = if expanded { |
| 531 | wire::Limits { |
| 532 | input: u64::MAX, |
| 533 | output: 64 * 1024 * 1024 * 1024, |
| 534 | entries: 200_000, |
| 535 | } |
| 536 | } else { |
| 537 | wire::Limits::default() |
| 538 | }; |
| 539 | let interactive = start.action.kind() == wire::ActionKind::Extract; |
| 540 | wire::Message::StartGuarded(wire::GuardedStart { |
| 541 | start, |
| 542 | ceiling, |
| 543 | interactive, |
| 544 | }) |
| 545 | } |
| 546 | ui::Command::ResourceReply { |
| 547 | challenge_id, |
| 548 | scope, |
| 549 | allow, |
| 550 | } => wire::Message::ResourceReply { |
| 551 | challenge_id, |
| 552 | scope, |
| 553 | allow, |
| 554 | }, |
| 555 | ui::Command::ConflictReply { |
| 556 | challenge_id, |
| 557 | choice, |
| 558 | apply_to_remaining, |
| 559 | } => wire::Message::ConflictReply { |
| 560 | challenge_id, |
| 561 | choice: conflict_to_wire(choice), |
| 562 | apply_to_remaining, |
| 563 | }, |
| 564 | ui::Command::Cancel => wire::Message::Cancel, |
| 565 | ui::Command::Password { |
| 566 | challenge_id, |
| 567 | secret, |
| 568 | } => wire::Message::Password { |
| 569 | challenge_id, |
| 570 | secret: wire::Secret(secret.as_bytes().to_vec()), |
| 571 | }, |
| 572 | }; |
| 573 | if self.writer.send(&message).is_err() { |
| 574 | self.buffer.0.borrow_mut().fill(0); |
| 575 | self.buffer.0.borrow_mut().clear(); |
| 576 | self.stop.store(true, Ordering::Release); |
| 577 | return Err("작업자 요청을 직렬화하지 못했습니다".into()); |
| 578 | } |
| 579 | let mut resources = self.resources.lock().map_err(|_| { |
| 580 | self.stop.store(true, Ordering::Release); |
| 581 | "작업자 승인 상태 오류" |
| 582 | })?; |
| 583 | let bytes = Frame(std::mem::take(&mut *self.buffer.0.borrow_mut()), is_cancel); |
| 584 | if self.send.as_ref().unwrap().try_send(bytes).is_err() { |
| 585 | if is_cancel && self.done.load(Ordering::Acquire) { |
| 586 | self.next += 1; |
| 587 | return Ok(()); |
| 588 | } |
| 589 | self.stop.store(true, Ordering::Release); |
| 590 | return Err("작업자 요청 대기열이 닫혔거나 가득 찼습니다".into()); |
| 591 | } |
| 592 | if let wire::Message::ResourceReply { |
| 593 | challenge_id, |
| 594 | scope, |
| 595 | allow, |
| 596 | } = message |
| 597 | && resources.pending == Some((challenge_id, scope)) |
| 598 | { |
| 599 | resources.approved |= allow; |
| 600 | resources.pending = None; |
| 601 | } |
| 602 | self.next += 1; |
| 603 | Ok(()) |
| 604 | } |
| 605 | fn poll(&mut self) -> Option<ui::HostEvent> { |
| 606 | match self.receive.as_ref()?.try_recv() { |
| 607 | Ok(event) => { |
| 608 | if matches!(event, ui::HostEvent::Exited { .. }) { |
| 609 | self.reaped = true; |
| 610 | } |
| 611 | Some(event) |
| 612 | } |
| 613 | Err(mpsc::TryRecvError::Empty) => None, |
| 614 | Err(mpsc::TryRecvError::Disconnected) if !self.reaped && !self.disconnected => { |
| 615 | self.disconnected = true; |
| 616 | Some(ui::HostEvent::Fault( |
| 617 | "작업자 통신 스레드가 종료됐습니다".into(), |
| 618 | )) |
| 619 | } |
| 620 | Err(_) => None, |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 | impl Drop for ProcessConnection { |
| 625 | fn drop(&mut self) { |
| 626 | self.stop.store(true, Ordering::Release); |
| 627 | self.send.take(); |
| 628 | self.receive.take(); |
| 629 | if let Some(supervisor) = self.supervisor.take() { |
| 630 | let _ = supervisor.join(); |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | fn supervise( |
| 636 | mut child: std::process::Child, |
| 637 | job_id: u64, |
| 638 | requests: Receiver<Frame>, |
| 639 | events: SyncSender<ui::HostEvent>, |
| 640 | stop: Arc<AtomicBool>, |
| 641 | done: Arc<AtomicBool>, |
| 642 | expected: Arc<Mutex<Option<wire::ActionKind>>>, |
| 643 | resources: Arc<Mutex<ResourceDeadline>>, |
| 644 | ) { |
| 645 | let mut input = child.stdin.take().unwrap(); |
| 646 | let mut output = child.stdout.take().unwrap(); |
| 647 | let mut errors = child.stderr.take().unwrap(); |
| 648 | let mut threads = Vec::new(); |
| 649 | let cancel_write_failed = Arc::new(AtomicBool::new(false)); |
| 650 | let terminal_received = Arc::new(AtomicBool::new(false)); |
| 651 | let failed_cancel = cancel_write_failed.clone(); |
| 652 | let tx = events.clone(); |
| 653 | let abort = stop.clone(); |
| 654 | let finished = done.clone(); |
| 655 | threads.push( |
| 656 | thread::Builder::new() |
| 657 | .name("zipelo-worker-input".into()) |
| 658 | .spawn(move || { |
| 659 | while !finished.load(Ordering::Acquire) && !abort.load(Ordering::Acquire) { |
| 660 | match requests.recv_timeout(Duration::from_millis(10)) { |
| 661 | Ok(frame) => { |
| 662 | if input |
| 663 | .write_all(&frame.0) |
| 664 | .and_then(|_| input.flush()) |
| 665 | .is_err() |
| 666 | { |
| 667 | if frame.1 { |
| 668 | // 취소 쓰기 실패는 응답과 실제 종료 결과를 확인한 뒤 판단함. |
| 669 | failed_cancel.store(true, Ordering::Release); |
| 670 | } else { |
| 671 | fault(&tx, &abort, "작업자 요청 파이프 쓰기에 실패했습니다"); |
| 672 | } |
| 673 | break; |
| 674 | } |
| 675 | } |
| 676 | Err(mpsc::RecvTimeoutError::Timeout) => {} |
| 677 | Err(_) => break, |
| 678 | } |
| 679 | } |
| 680 | }), |
| 681 | ); |
| 682 | let tx = events.clone(); |
| 683 | let abort = stop.clone(); |
| 684 | let received_terminal = terminal_received.clone(); |
| 685 | let pending_resource = resources.clone(); |
| 686 | threads.push( |
| 687 | thread::Builder::new() |
| 688 | .name("zipelo-worker-output".into()) |
| 689 | .spawn(move || { |
| 690 | let eof; |
| 691 | { |
| 692 | let mut reader = codec::Reader::new(&mut output); |
| 693 | eof = loop { |
| 694 | match reader.read() { |
| 695 | Ok(Some((job, sequence, message))) => { |
| 696 | let action = expected.lock().ok().and_then(|value| *value); |
| 697 | let event = event_to_ui(message, action); |
| 698 | if job != job_id || event.is_err() { |
| 699 | fault(&tx, &abort, "작업자 응답이 요청과 일치하지 않습니다"); |
| 700 | break false; |
| 701 | } |
| 702 | if let Ok(ui::Event::ResourceRequired(question)) = &event { |
| 703 | if let Ok(mut state) = pending_resource.lock() { |
| 704 | state.pending = Some((question.id, question.scope)); |
| 705 | } else { |
| 706 | fault(&tx, &abort, "작업자 승인 상태 오류"); |
| 707 | break false; |
| 708 | } |
| 709 | } |
| 710 | if matches!(event, Ok(ui::Event::Terminal(_))) { |
| 711 | received_terminal.store(true, Ordering::Release); |
| 712 | } |
| 713 | if !notify( |
| 714 | &tx, |
| 715 | ui::HostEvent::Frame { |
| 716 | job_id: job, |
| 717 | sequence, |
| 718 | event: event.unwrap(), |
| 719 | }, |
| 720 | ) { |
| 721 | return; |
| 722 | } |
| 723 | } |
| 724 | Ok(None) => break true, |
| 725 | Err(_) => { |
| 726 | fault(&tx, &abort, "작업자 응답 프레임을 읽지 못했습니다"); |
| 727 | break false; |
| 728 | } |
| 729 | } |
| 730 | }; |
| 731 | } |
| 732 | if eof || io::copy(&mut output, &mut io::sink()).is_ok() { |
| 733 | notify(&tx, ui::HostEvent::StdoutEof); |
| 734 | } |
| 735 | }), |
| 736 | ); |
| 737 | let tx = events.clone(); |
| 738 | let abort = stop.clone(); |
| 739 | threads.push( |
| 740 | thread::Builder::new() |
| 741 | .name("zipelo-worker-errors".into()) |
| 742 | .spawn(move || { |
| 743 | let mut bytes = [0u8; 4096]; |
| 744 | loop { |
| 745 | match errors.read(&mut bytes) { |
| 746 | Ok(0) => { |
| 747 | notify(&tx, ui::HostEvent::StderrEof); |
| 748 | break; |
| 749 | } |
| 750 | Ok(_) => {} |
| 751 | Err(error) if error.kind() == io::ErrorKind::Interrupted => {} |
| 752 | Err(_) => { |
| 753 | fault(&tx, &abort, "작업자 오류 파이프를 읽지 못했습니다"); |
| 754 | break; |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | }), |
| 759 | ); |
| 760 | let mut handles = Vec::new(); |
| 761 | for result in threads { |
| 762 | match result { |
| 763 | Ok(handle) => handles.push(handle), |
| 764 | Err(_) => fault(&events, &stop, "작업자 통신 스레드를 시작하지 못했습니다"), |
| 765 | } |
| 766 | } |
| 767 | let started = Instant::now(); |
| 768 | let status = loop { |
| 769 | // 승인 뒤 실제 진행과 질문 대기 시간은 작업자의 60초 정체 감시로 판단함. |
| 770 | // 응답 프레임 간격을 실제 파일 처리 진행으로 간주하지 않음. |
| 771 | let approved = resources |
| 772 | .lock() |
| 773 | .map(|state| state.approved) |
| 774 | .unwrap_or(false); |
| 775 | if !approved && started.elapsed() >= Duration::from_secs(310) { |
| 776 | fault(&events, &stop, "작업자 처리 제한 시간을 초과했습니다"); |
| 777 | } |
| 778 | if stop.load(Ordering::Acquire) { |
| 779 | let _ = child.kill(); |
| 780 | } |
| 781 | match child.try_wait() { |
| 782 | Ok(Some(status)) => break Some(status), |
| 783 | Ok(None) => thread::sleep(Duration::from_millis(10)), |
| 784 | Err(_) => { |
| 785 | fault(&events, &stop, "작업자 종료 상태를 확인하지 못했습니다"); |
| 786 | let _ = child.kill(); |
| 787 | break child.wait().ok(); |
| 788 | } |
| 789 | } |
| 790 | }; |
| 791 | done.store(true, Ordering::Release); |
| 792 | for handle in handles { |
| 793 | if handle.join().is_err() { |
| 794 | fault(&events, &stop, "작업자 통신 스레드 회수에 실패했습니다"); |
| 795 | } |
| 796 | } |
| 797 | if cancel_write_failed.load(Ordering::Acquire) |
| 798 | && !(terminal_received.load(Ordering::Acquire) |
| 799 | && status.as_ref().is_some_and(|status| status.success())) |
| 800 | { |
| 801 | fault(&events, &stop, "작업자 요청 파이프 쓰기에 실패했습니다"); |
| 802 | } |
| 803 | if let Some(status) = status { |
| 804 | // 회수와 모든 파이프 핸들 정리가 끝난 뒤에만 닫기 허용 근거를 전달함. |
| 805 | notify(&events, ui::HostEvent::CleanupComplete); |
| 806 | notify( |
| 807 | &events, |
| 808 | ui::HostEvent::Exited { |
| 809 | success: status.success(), |
| 810 | }, |
| 811 | ); |
| 812 | } |
| 813 | } |
| 814 | |
| 815 | #[cfg(test)] |
| 816 | #[path = "../../../tests/rust-app-ui/conflict_codec.rs"] |
| 817 | mod conflict_codec_tests; |