team-ljyzipelo

공개
908줄35 KB
1use crate::{
2 archive,
3 filesystem::{self, Dir},
4 protocol::*,
5 resources::{Budget, Monitor, Watchdog},
6 wire::{Reader, Writer},
7};
8use std::{
9 collections::BTreeSet,
10 io::{Read, Seek, SeekFrom, Write},
11 sync::{Arc, Condvar, Mutex},
12 time::{Duration, Instant},
13};
14
15type Result<T> = std::result::Result<T, ErrorCode>;
16#[derive(PartialEq, Eq)]
17enum Challenge {
18 Password(u64),
19 Conflict(u64),
20 Resource(u64, ResourceScope),
21}
22struct State<W> {
23 writer: Writer<W>,
24 cancelled: bool,
25 phase: u8,
26 fault: Option<ErrorCode>,
27 challenge: Option<Challenge>,
28 conflict_reply: Option<(ConflictChoice, bool)>,
29 password: Option<Secret>,
30 resource_reply: Option<bool>,
31 input_closed: bool,
32}
33struct Job<W> {
34 state: Arc<Mutex<State<W>>>,
35 wake: Arc<Condvar>,
36 next_challenge: u64,
37 interactive: bool,
38 action: ActionKind,
39 budget: Option<Budget>,
40 watchdog: Watchdog,
41 remaining_choice: Option<ConflictChoice>,
42 started: Instant,
43 terminal: Terminal,
44 parent: crate::parent::Parent,
45}
46impl<W: Write> Job<W> {
47 fn request_resource(
48 &mut self,
49 scope: ResourceScope,
50 mut usage: ResourceUsage,
51 storage: Option<&std::fs::File>,
52 ) -> Result<()> {
53 let budget = self.budget.as_ref().ok_or(ErrorCode::Internal)?;
54 let (soft_limits, ceiling) = (budget.soft, budget.ceiling);
55 if let Some(file) = storage {
56 usage.available_bytes =
57 Some(crate::space::available(file)?.min(u64::MAX as u128) as u64);
58 }
59 self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?;
60 let id = self.next_challenge;
61 let state_ref = Arc::clone(&self.state);
62 let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?;
63 if state.challenge.is_some() {
64 return Err(ErrorCode::Internal);
65 }
66 state.challenge = Some(Challenge::Resource(id, scope));
67 state
68 .writer
69 .send(&Message::ResourceRequired {
70 challenge_id: id,
71 action: self.action,
72 scope,
73 usage,
74 soft_limits,
75 ceiling,
76 })
77 .map_err(|_| ErrorCode::Io)?;
78 let waiting = Instant::now();
79 loop {
80 self.parent.check()?;
81 if let Some(error) = state.fault {
82 return Err(error);
83 }
84 if state.cancelled {
85 return Err(ErrorCode::None);
86 }
87 if let Some(allow) = state.resource_reply.take() {
88 if !allow {
89 return Err(ErrorCode::None);
90 }
91 self.budget
92 .as_mut()
93 .ok_or(ErrorCode::Internal)?
94 .grant(scope);
95 self.watchdog.resume(self.started.elapsed(), true);
96 return Ok(());
97 }
98 if state.input_closed {
99 return Err(ErrorCode::Protocol);
100 }
101 if waiting.elapsed() >= Duration::from_secs(300) {
102 return Err(ErrorCode::Limit);
103 }
104 state = self
105 .wake
106 .wait_timeout(state, Duration::from_millis(50))
107 .map_err(|_| ErrorCode::Internal)?
108 .0;
109 }
110 }
111 fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> {
112 self.check()?;
113 self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?;
114 let id = self.next_challenge;
115 let state_ref = Arc::clone(&self.state);
116 let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?;
117 state.challenge = Some(Challenge::Password(id));
118 state
119 .writer
120 .send(&Message::PasswordRequired {
121 challenge_id: id,
122 attempt,
123 purpose,
124 })
125 .map_err(|_| ErrorCode::Io)?;
126 let waiting = Instant::now();
127 loop {
128 self.parent.check()?;
129 if let Some(error) = state.fault {
130 return Err(error);
131 }
132 if state.cancelled {
133 return Err(ErrorCode::None);
134 }
135 if let Some(secret) = state.password.take() {
136 self.watchdog.resume(self.started.elapsed(), false);
137 return Ok(secret);
138 }
139 if state.input_closed {
140 return Err(ErrorCode::Protocol);
141 }
142 if if self.budget.is_some() {
143 waiting.elapsed() >= Duration::from_secs(300)
144 } else {
145 self.started.elapsed() > Duration::from_secs(300)
146 } {
147 return Err(ErrorCode::Limit);
148 }
149 state = self
150 .wake
151 .wait_timeout(state, Duration::from_millis(50))
152 .map_err(|_| ErrorCode::Internal)?
153 .0;
154 }
155 }
156
157 fn conflict(&mut self, entry: &Entry, existing_size: u64) -> Result<ConflictChoice> {
158 self.check()?;
159 if let Some(choice) = self.remaining_choice {
160 return Ok(choice);
161 }
162 self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?;
163 let id = self.next_challenge;
164 let state_ref = Arc::clone(&self.state);
165 let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?;
166 state.challenge = Some(Challenge::Conflict(id));
167 state
168 .writer
169 .send(&Message::ConflictRequired {
170 challenge_id: id,
171 entry_id: entry.entry_id,
172 relative_name: entry.name.clone(),
173 incoming_size: entry.size,
174 existing_size,
175 })
176 .map_err(|_| ErrorCode::Io)?;
177 let waiting = Instant::now();
178 loop {
179 self.parent.check()?;
180 if let Some(error) = state.fault {
181 return Err(error);
182 }
183 if state.cancelled {
184 return Err(ErrorCode::None);
185 }
186 if let Some((choice, apply)) = state.conflict_reply.take() {
187 if apply {
188 self.remaining_choice = Some(choice);
189 }
190 self.watchdog.resume(self.started.elapsed(), false);
191 return Ok(choice);
192 }
193 if state.input_closed {
194 return Err(ErrorCode::Protocol);
195 }
196 if if self.budget.is_some() {
197 waiting.elapsed() >= Duration::from_secs(300)
198 } else {
199 self.started.elapsed() > Duration::from_secs(300)
200 } {
201 return Err(ErrorCode::Limit);
202 }
203 state = self
204 .wake
205 .wait_timeout(state, Duration::from_millis(50))
206 .map_err(|_| ErrorCode::Internal)?
207 .0;
208 }
209 }
210 fn rename(&mut self, root: &Dir, name: &str, reserved: &BTreeSet<String>) -> Result<String> {
211 let (prefix, leaf) = name.rsplit_once('/').unwrap_or(("", name));
212 let (stem, extension) = match leaf.rsplit_once('.') {
213 Some((stem, ext)) if !stem.is_empty() => (stem, format!(".{ext}")),
214 _ => (leaf, String::new()),
215 };
216 for index in 1..=10000 {
217 self.check()?;
218 fn clip(text: &str, bytes: usize) -> &str {
219 let mut end = text.len().min(bytes);
220 while !text.is_char_boundary(end) {
221 end -= 1;
222 }
223 &text[..end]
224 }
225 let suffix = format!(" ({index})");
226 let extension = clip(&extension, 255 - suffix.len() - 4).trim_end_matches(['.', ' ']);
227 let stem = clip(stem, 255 - suffix.len() - extension.len());
228 let stem = if stem.is_empty() { "file" } else { stem };
229 let leaf = format!("{stem}{suffix}{extension}");
230 let candidate = if prefix.is_empty() {
231 leaf
232 } else {
233 format!("{prefix}/{leaf}")
234 };
235 archive::valid_name(&candidate, false)?;
236 if !reserved.contains(&candidate.to_lowercase())
237 && filesystem::unused(root, &candidate)?
238 {
239 return Ok(candidate);
240 }
241 }
242 Err(ErrorCode::Conflict)
243 }
244 fn event(&mut self, event: Message) -> Result<()> {
245 let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
246 state.writer.send(&event).map_err(|_| {
247 state.fault = Some(ErrorCode::Io);
248 ErrorCode::Io
249 })
250 }
251 fn check(&mut self) -> Result<()> {
252 self.parent.check()?;
253 let state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
254 if let Some(error) = state.fault {
255 return Err(error);
256 }
257 if state.cancelled && state.phase == 0 {
258 return Err(ErrorCode::None);
259 }
260 self.watchdog.check(self.started.elapsed())
261 }
262 fn cutoff(&mut self) -> Result<()> {
263 self.check()?;
264 let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
265 if state.phase == 0 && state.cancelled {
266 return Err(ErrorCode::None);
267 }
268 state.phase = 1;
269 Ok(())
270 }
271 fn progress(
272 &mut self,
273 stage: Stage,
274 bytes: u64,
275 total: Option<u64>,
276 entries: u32,
277 ) -> Result<()> {
278 self.event(Message::Progress {
279 stage,
280 processed_bytes: bytes,
281 total_bytes: total,
282 completed_entries: entries,
283 })
284 }
285 fn output_reader(
286 &mut self,
287 root: &Dir,
288 name: &str,
289 data: &mut impl Read,
290 length: u64,
291 id: Option<u32>,
292 last: bool,
293 replace: Option<&filesystem::Existing>,
294 ) -> Result<()> {
295 self.check()?;
296 self.progress(
297 Stage::Write,
298 0,
299 Some(length),
300 self.terminal.created_count as u32,
301 )?;
302 let mut first_chunk = true;
303 let p = filesystem::publish_reader_mode(root, name, data, length, replace, &mut |commit| {
304 if !first_chunk {
305 self.activity()?;
306 }
307 first_chunk = false;
308 if commit && last {
309 self.cutoff()
310 } else {
311 self.check()
312 }
313 });
314 self.terminal.retained_partial_count += p.retained;
315 if p.cleanup != Cleanup::Complete {
316 self.terminal.cleanup = p.cleanup;
317 }
318 if p.created {
319 self.terminal.created_count += 1;
320 self.terminal.publication = Publication::Partial;
321 self.terminal.durability = match (self.terminal.durability, p.durability) {
322 (Durability::Failed, _) | (_, Durability::Failed) => Durability::Failed,
323 (Durability::Unconfirmed, _) | (_, Durability::Unconfirmed) => {
324 Durability::Unconfirmed
325 }
326 _ => p.durability,
327 };
328 self.event(Message::Output {
329 entry_id: id,
330 relative_name: name.to_owned(),
331 disposition: Disposition::Created,
332 })?;
333 }
334 if p.uncertain {
335 self.terminal.publication = Publication::Uncertain;
336 self.terminal.durability = Durability::Unconfirmed;
337 self.event(Message::Output {
338 entry_id: id,
339 relative_name: name.to_owned(),
340 disposition: Disposition::CommitUncertain,
341 })?;
342 }
343 if p.retained != 0 {
344 self.event(Message::Output {
345 entry_id: id,
346 relative_name: p.retained_name.clone().ok_or(ErrorCode::Internal)?,
347 disposition: Disposition::PartialRetained,
348 })?;
349 }
350 if let Some(error) = p.error {
351 return Err(error);
352 }
353 Ok(())
354 }
355 fn run(&mut self, start: Start) -> Result<()> {
356 if !start.limits.valid() {
357 return Err(ErrorCode::InvalidRequest);
358 }
359 let limits = self.budget.as_ref().map_or(start.limits, |b| b.ceiling);
360 self.event(Message::Accepted {
361 action: start.action.kind(),
362 encryption: true,
363 })?;
364 self.check()?;
365 if let Some(budget) = &self.budget {
366 let scope = ResourceScope {
367 output: budget.ceiling.output > budget.soft.output,
368 entries: budget.ceiling.entries > budget.soft.entries,
369 ratio: false,
370 };
371 if scope.any() {
372 let temporary = crate::spool::temporary()?;
373 self.request_resource(scope, ResourceUsage::default(), Some(&temporary))?;
374 }
375 }
376 match start.action {
377 Action::List {
378 archive: ref source,
379 }
380 | Action::Extract {
381 archive: ref source,
382 ..
383 } => {
384 let extract = matches!(start.action, Action::Extract { .. });
385 let path = source.to_path()?;
386 self.progress(Stage::Read, 0, None, 0)?;
387 let mut snapshot =
388 crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| {
389 match step {
390 crate::spool::Step::Check => self.check(),
391 crate::spool::Step::Read { bytes, total } => {
392 self.activity()?;
393 self.progress(Stage::Read, bytes, Some(total), 0)
394 }
395 }
396 })?;
397 if let Action::Extract {
398 list_id: Some(expected),
399 ..
400 } = &start.action
401 {
402 if expected.catalog_version != 1
403 || expected.source_object != snapshot.object
404 || expected.archive_bytes != snapshot.len
405 || expected.archive_sha256 != snapshot.hash
406 {
407 return Err(ErrorCode::SourceChanged);
408 }
409 }
410 self.progress(Stage::Decode, snapshot.len, Some(snapshot.len), 0)?;
411 let mut catalog = crate::streaming::Catalog::open(
412 &mut snapshot.file,
413 snapshot.len,
414 limits,
415 false,
416 None,
417 self,
418 )?;
419 let list_id = ListId {
420 catalog_version: 1,
421 format: catalog.format,
422 source_object: snapshot.object,
423 archive_bytes: snapshot.len,
424 archive_sha256: snapshot.hash,
425 };
426 if !extract {
427 for member in &catalog.members {
428 self.check()?;
429 self.event(Message::Entry(member.entry.clone()))?;
430 }
431 self.event(Message::ListEnd {
432 entry_count: catalog.members.len() as u32,
433 list_id,
434 })?;
435 } else if let Action::Extract {
436 destination,
437 selection,
438 list_id: expected,
439 gzip_output_name,
440 ..
441 } = start.action
442 {
443 if expected
444 .as_ref()
445 .is_some_and(|expected| *expected != list_id)
446 {
447 return Err(ErrorCode::SourceChanged);
448 }
449 let selected = match selection {
450 Selection::All => None,
451 Selection::EntryIds(ids) => {
452 let n = ids.len();
453 let set = ids.into_iter().collect::<BTreeSet<_>>();
454 if expected.is_none()
455 || set.is_empty()
456 || n != set.len()
457 || set.iter().any(|id| *id as usize >= catalog.members.len())
458 {
459 return Err(ErrorCode::InvalidRequest);
460 }
461 Some(set)
462 }
463 };
464 if catalog
465 .members
466 .iter()
467 .any(|m| !matches!(m.entry.kind, EntryKind::File | EntryKind::Directory))
468 {
469 return Err(ErrorCode::UnsafePath);
470 }
471 if catalog.format == Format::Gzip {
472 let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?;
473 let checked = archive::valid_name(&name, false)
474 .map_err(|_| ErrorCode::InvalidRequest)?;
475 if checked.contains('/') {
476 return Err(ErrorCode::InvalidRequest);
477 }
478 catalog.members[0].entry.name = checked;
479 } else if gzip_output_name.is_some() {
480 return Err(ErrorCode::InvalidRequest);
481 }
482 let root = Dir::root(&destination.to_path()?)?;
483 let output_sizes = catalog
484 .members
485 .iter()
486 .filter(|m| {
487 m.entry.kind == EntryKind::File
488 && selected
489 .as_ref()
490 .is_none_or(|s| s.contains(&m.entry.entry_id))
491 })
492 .map(|m| (m.entry.name.clone(), m.entry.size))
493 .collect::<Vec<_>>();
494 let staged = if matches!(catalog.format, Format::Zip | Format::SevenZip) {
495 Some((
496 &catalog.data,
497 catalog.members.iter().try_fold(0u64, |sum, m| {
498 sum.checked_add(m.entry.size).ok_or(ErrorCode::Limit)
499 })?,
500 ))
501 } else {
502 None
503 };
504 // 선택 전에는 검증에 필요한 스테이징 공간만 계산함.
505 let initial_outputs = if self.interactive {
506 &[][..]
507 } else {
508 &output_sizes[..]
509 };
510 filesystem::preflight_space(&root, initial_outputs, staged)?;
511 let encrypted = catalog.members.iter().any(|m| m.entry.encrypted);
512 if matches!(catalog.format, Format::Zip | Format::SevenZip) {
513 for attempt in 1..=3 {
514 let secret = if encrypted {
515 Some(self.password(PasswordPurpose::Decrypt, attempt)?)
516 } else {
517 None
518 };
519 match crate::streaming::Catalog::open(
520 &mut snapshot.file,
521 snapshot.len,
522 limits,
523 true,
524 secret.as_ref().map(|s| s.0.as_slice()),
525 self,
526 ) {
527 Ok(decoded) => {
528 catalog = decoded;
529 break;
530 }
531 Err(ErrorCode::WrongPassword) if attempt < 3 => continue,
532 Err(error) => return Err(error),
533 }
534 }
535 }
536 let offsets = catalog.offsets;
537 let mut data = catalog.data;
538 let members = catalog
539 .members
540 .into_iter()
541 .filter(|m| {
542 selected
543 .as_ref()
544 .is_none_or(|s| s.contains(&m.entry.entry_id))
545 })
546 .collect::<Vec<_>>();
547 let dirs = archive::output_directories(&members)?;
548 let files = members
549 .iter()
550 .filter(|m| m.entry.kind == EntryKind::File)
551 .collect::<Vec<_>>();
552 let mut names = dirs
553 .iter()
554 .map(|n| (n.clone(), EntryKind::Directory))
555 .collect::<Vec<_>>();
556 names.extend(
557 files
558 .iter()
559 .map(|m| (m.entry.name.clone(), EntryKind::File)),
560 );
561 filesystem::preflight_mode(&root, &names, self.interactive)?;
562 if !self.interactive {
563 filesystem::preflight_space(&root, &output_sizes, None)?;
564 }
565 let mut reserved = names
566 .iter()
567 .map(|(name, _)| name.to_lowercase())
568 .collect::<BTreeSet<_>>();
569 for name in dirs {
570 self.check()?;
571 let (created, durability, sync_error) =
572 filesystem::directory(&root, &name)?;
573 if created {
574 self.terminal.created_count += 1;
575 self.terminal.publication = Publication::Partial;
576 self.terminal.durability = durability;
577 self.event(Message::Output {
578 entry_id: None,
579 relative_name: name,
580 disposition: Disposition::Created,
581 })?;
582 if let Some(error) = sync_error {
583 return Err(error);
584 }
585 }
586 }
587 for (index, m) in files.iter().enumerate() {
588 data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize]))
589 .map_err(|_| ErrorCode::Io)?;
590 self.check()?;
591 let existing = if self.interactive {
592 filesystem::existing(&root, &m.entry.name)?
593 } else {
594 None
595 };
596 let mut name = m.entry.name.clone();
597 let mut replace = None;
598 if let Some(ref existing) = existing {
599 let choice = self.conflict(&m.entry, existing.size)?;
600 self.check()?;
601 if choice == ConflictChoice::Rename {
602 name = self.rename(&root, &name, &reserved)?;
603 reserved.insert(name.to_lowercase());
604 } else if choice == ConflictChoice::Overwrite {
605 replace = Some(existing);
606 }
607 self.event(Message::ConflictResolved {
608 entry_id: m.entry.entry_id,
609 relative_name: name.clone(),
610 choice,
611 })?;
612 if choice == ConflictChoice::Skip {
613 continue;
614 }
615 }
616 if self.interactive {
617 // 건너뛴 파일을 제외하고 이번에 게시할 파일의 공간을 확인함.
618 filesystem::preflight_space(
619 &root,
620 &[(name.clone(), m.entry.size)],
621 None,
622 )?;
623 }
624 self.output_reader(
625 &root,
626 &name,
627 &mut (&mut data).take(m.entry.size),
628 m.entry.size,
629 Some(m.entry.entry_id),
630 index + 1 == files.len(),
631 replace,
632 )?;
633 }
634 if !self.interactive || self.terminal.created_count != 0 {
635 self.terminal.publication = Publication::Complete;
636 }
637 }
638 }
639 Action::CreateZip {
640 sources,
641 output_file,
642 method,
643 encryption,
644 } => {
645 let output = output_file.to_path()?;
646 let leaf = output
647 .file_name()
648 .and_then(|n| n.to_str())
649 .ok_or(ErrorCode::InvalidRequest)?;
650 let name = archive::valid_name(leaf, false)?;
651 let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?;
652 filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?;
653 let members = crate::create::plan(&sources, limits, self)?;
654 let secret = if encryption == Encryption::Aes256 {
655 let secret = self.password(PasswordPurpose::Encrypt, 1)?;
656 if secret.0.is_empty() {
657 return Err(ErrorCode::InvalidRequest);
658 }
659 Some(secret)
660 } else {
661 None
662 };
663 let (mut data, length) = crate::create::zip(
664 &members,
665 method,
666 limits,
667 secret.as_ref().map(|s| s.0.as_slice()),
668 self,
669 )?;
670 filesystem::preflight_space(&root, &[(name.clone(), length)], None)?;
671 self.output_reader(&root, &name, &mut data, length, None, true, None)?;
672 self.terminal.publication = Publication::Complete;
673 }
674 }
675 self.cutoff()?;
676 Ok(())
677 }
678}
679impl<W: Write> Monitor for Job<W> {
680 fn check(&mut self) -> Result<()> {
681 Job::check(self)
682 }
683 fn activity(&mut self) -> Result<()> {
684 self.check()?;
685 self.watchdog.activity(self.started.elapsed())
686 }
687 fn observe(&mut self, usage: ResourceUsage, storage: Option<&std::fs::File>) -> Result<()> {
688 self.check()?;
689 let Some(budget) = &self.budget else {
690 return Ok(());
691 };
692 let scope = budget.required(usage)?;
693 if !scope.any() {
694 return Ok(());
695 }
696 self.request_resource(scope, usage, storage)
697 }
698}
699
700pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
701 input: R,
702 output: W,
703) -> std::io::Result<()> {
704 let parent = crate::parent::Parent::capture()
705 .map_err(|_| std::io::Error::other("worker parent unavailable"))?;
706 let mut reader = Reader::new(input);
707 let (job, _, message) = reader
708 .read()?
709 .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?;
710 let (start, interactive, budget) = match message {
711 Message::Start(start) => (start, false, None),
712 Message::StartInteractive(start) => (start, true, None),
713 Message::StartGuarded(guarded) if guarded.valid() => {
714 let budget = Budget {
715 soft: guarded.start.limits,
716 ceiling: guarded.ceiling,
717 granted: ResourceScope::default(),
718 };
719 (guarded.start, guarded.interactive, Some(budget))
720 }
721 _ => {
722 return Err(std::io::Error::new(
723 std::io::ErrorKind::InvalidData,
724 "Start required",
725 ));
726 }
727 };
728 let state = Arc::new(Mutex::new(State {
729 writer: Writer::new(output, job),
730 cancelled: false,
731 phase: 0,
732 fault: None,
733 challenge: None,
734 conflict_reply: None,
735 password: None,
736 resource_reply: None,
737 input_closed: false,
738 }));
739 let wake = Arc::new(Condvar::new());
740 let control_wake = Arc::clone(&wake);
741 let control = Arc::clone(&state);
742 std::thread::spawn(move || {
743 loop {
744 let command = reader.read();
745 let Ok(Some((_, sequence, message))) = command else {
746 if let Ok(mut state) = control.lock() {
747 state.input_closed = true;
748 if command.is_err() && state.phase < 2 {
749 state.fault = Some(ErrorCode::Protocol);
750 }
751 control_wake.notify_all();
752 }
753 break;
754 };
755 let Ok(mut state) = control.lock() else {
756 break;
757 };
758 if state.phase == 3 {
759 break;
760 }
761 match message {
762 Message::Password {
763 challenge_id,
764 secret,
765 } => {
766 if state.phase != 0
767 || state.challenge != Some(Challenge::Password(challenge_id))
768 || state.password.is_some()
769 {
770 state.fault = Some(ErrorCode::Protocol);
771 } else {
772 state.challenge = None;
773 if !state.cancelled {
774 state.password = Some(secret);
775 }
776 }
777 control_wake.notify_all();
778 }
779 Message::ConflictReply {
780 challenge_id,
781 choice,
782 apply_to_remaining,
783 } => {
784 if state.phase != 0
785 || state.challenge != Some(Challenge::Conflict(challenge_id))
786 || state.conflict_reply.is_some()
787 {
788 state.fault = Some(ErrorCode::Protocol);
789 } else {
790 state.challenge = None;
791 if !state.cancelled {
792 state.conflict_reply = Some((choice, apply_to_remaining));
793 }
794 }
795 control_wake.notify_all();
796 }
797 Message::ResourceReply {
798 challenge_id,
799 scope,
800 allow,
801 } => {
802 if state.phase != 0
803 || state.challenge != Some(Challenge::Resource(challenge_id, scope))
804 || state.resource_reply.is_some()
805 {
806 state.fault = Some(ErrorCode::Protocol);
807 } else {
808 state.challenge = None;
809 if !state.cancelled {
810 state.resource_reply = Some(allow);
811 }
812 }
813 control_wake.notify_all();
814 }
815 Message::Cancel => {
816 let status = match state.phase {
817 2 => CancelStatus::Finished,
818 1 => CancelStatus::TooLate,
819 _ if state.cancelled => CancelStatus::AlreadyRequested,
820 _ => {
821 state.cancelled = true;
822 CancelStatus::Requested
823 }
824 };
825 control_wake.notify_all();
826 if state
827 .writer
828 .send(&Message::CancelAck {
829 request_sequence: sequence,
830 status,
831 })
832 .is_err()
833 {
834 state.fault = Some(ErrorCode::Io);
835 break;
836 }
837 }
838 _ => {
839 state.fault = Some(ErrorCode::Protocol);
840 break;
841 }
842 }
843 }
844 });
845 let mut context = Job {
846 state: Arc::clone(&state),
847 wake,
848 next_challenge: 0,
849 interactive,
850 action: start.action.kind(),
851 budget,
852 watchdog: Watchdog::new(),
853 remaining_choice: None,
854 parent,
855 started: Instant::now(),
856 terminal: Terminal {
857 outcome: Outcome::Completed,
858 error: ErrorCode::None,
859 publication: Publication::None,
860 created_count: 0,
861 retained_partial_count: 0,
862 durability: Durability::NotApplicable,
863 cleanup: Cleanup::Complete,
864 detail: String::new(),
865 },
866 };
867 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| context.run(start)));
868 let error = match result {
869 Ok(r) => r.err(),
870 Err(_) => {
871 context.terminal.publication = Publication::Uncertain;
872 context.terminal.cleanup = Cleanup::Unconfirmed;
873 Some(ErrorCode::Internal)
874 }
875 };
876 let mut state = state
877 .lock()
878 .map_err(|_| std::io::Error::other("worker state poisoned"))?;
879 state.phase = 2;
880 state.challenge = None;
881 state.password = None;
882 state.conflict_reply = None;
883 state.resource_reply = None;
884 if let Some(error) = state.fault.or(error) {
885 context.terminal.error = error;
886 context.terminal.outcome = if error == ErrorCode::None {
887 Outcome::Cancelled
888 } else {
889 Outcome::Failed
890 };
891 context.terminal.detail = match error {
892 ErrorCode::None => "취소됨",
893 ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원",
894 ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함",
895 ErrorCode::DiskFull => {
896 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
897 }
898 ErrorCode::Io => {
899 "파일을 읽거나 쓰지 못했습니다. 디스크 여유 공간과 접근 권한을 확인하세요"
900 }
901 _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함",
902 }
903 .to_owned();
904 }
905 state.writer.send(&Message::Terminal(context.terminal))?;
906 state.phase = 3;
907 Ok(())
908}