team-ljyzipelo

공개

Merge pull request #135 from Team-LJY/fix/list-preview-no-copy

목록과 미리보기의 전체 원본 사본 제거
작성자
LeeJunyoung
작성 시각
커밋
bd72bbfb8f0d50e0ef92380bae20b8570057b8f5
이 시점의 파일 보기

변경된 파일 9개

+1,095-46
수정experiments/rust-archive-worker/src/runtime.rs+105-9
@@ -40,6 +40,8 @@ struct Job<W> {
4040 watchdog: Watchdog,
4141 remaining_choice: Option<ConflictChoice>,
4242 source_group: Option<crate::split_seven_zip::Group>,
43추가: direct_source: Option<crate::spool::DirectSource>,
44추가: direct_split: Option<crate::split_seven_zip::Direct>,
4345 source_verified_for_publication: bool,
4446 creation_plan: Option<crate::create::Plan>,
4547 recovery: Option<crate::zip_recovery::Recovery>,
@@ -419,6 +421,87 @@ impl<W: Write> Job<W> {
419421 }
420422 Ok(())
421423 }
424추가: fn direct_snapshot(
425추가: &mut self,
426추가: path: &std::path::Path,
427추가: limit: u64,
428추가: ) -> Result<crate::spool::Snapshot> {
429추가: let (snapshot, guard) =
430추가: crate::spool::Snapshot::open_direct(path, limit, &mut |step| match step {
431추가: crate::spool::Step::Check => self.check(),
432추가: crate::spool::Step::Activity => completed(Ok(()), self),
433추가: crate::spool::Step::Read { bytes, total } => {
434추가: self.progress(Stage::Read, bytes, Some(total), 0)
435추가: }
436추가: })?;
437추가: self.direct_source = Some(guard);
438추가: Ok(snapshot)
439추가: }
440추가: fn verify_direct(&mut self) -> Result<()> {
441추가: if let Some(mut source) = self.direct_source.take() {
442추가: let result = source.verify(&mut |step| match step {
443추가: crate::spool::Step::Check => self.check(),
444추가: crate::spool::Step::Activity => completed(Ok(()), self),
445추가: crate::spool::Step::Read { bytes, total } => {
446추가: self.progress(Stage::Verify, bytes, Some(total), 0)
447추가: }
448추가: });
449추가: self.direct_source = Some(source);
450추가: result?;
451추가: }
452추가: if let Some(source) = self.direct_split.take() {
453추가: let result = source.verify(&mut |step| match step {
454추가: crate::spool::Step::Check => self.check(),
455추가: crate::spool::Step::Activity => completed(Ok(()), self),
456추가: crate::spool::Step::Read { bytes, total } => {
457추가: self.progress(Stage::Verify, bytes, Some(total), 0)
458추가: }
459추가: });
460추가: self.direct_split = Some(source);
461추가: self.split_result(result)?;
462추가: }
463추가: Ok(())
464추가: }
465추가: fn list_direct_split(&mut self, path: &std::path::Path, limits: Limits) -> Result<()> {
466추가: let metadata_limits = self.metadata_limits();
467추가: let opened =
468추가: crate::split_seven_zip::open_direct(path, limits.input, metadata_limits, &mut |step| {
469추가: match step {
470추가: crate::spool::Step::Check => self.check(),
471추가: crate::spool::Step::Activity => completed(Ok(()), self),
472추가: crate::spool::Step::Read { bytes, total } => {
473추가: self.progress(Stage::Read, bytes, Some(total), 0)
474추가: }
475추가: }
476추가: });
477추가: let mut source = self.split_result(opened)?.ok_or(ErrorCode::Internal)?;
478추가: let length = source.len();
479추가: let object = self.split_result(source.object())?;
480추가: let hash = source.hash;
481추가: let result = crate::spool::retry_full(|| {
482추가: crate::seven_zip::open(&mut source, length, limits, false, self)
483추가: });
484추가: self.direct_split = Some(source);
485추가: let catalog = result?;
486추가: for member in &catalog.members {
487추가: self.check()?;
488추가: completed(self.event(Message::Entry(member.entry.clone())), self)?;
489추가: }
490추가: self.verify_direct()?;
491추가: completed(
492추가: self.event(Message::ListEnd {
493추가: entry_count: catalog.members.len() as u32,
494추가: list_id: ListId {
495추가: catalog_version: 2,
496추가: format: Format::SevenZip,
497추가: source_object: object,
498추가: archive_bytes: length,
499추가: archive_sha256: hash,
500추가: },
501추가: }),
502추가: self,
503추가: )
504추가: }
422505 fn preview(
423506 &mut self,
424507 archive: NativePath,
@@ -436,14 +519,7 @@ impl<W: Write> Job<W> {
436519 return Err(ErrorCode::UnsupportedFeature);
437520 }
438521 self.progress(Stage::Read, 0, None, 0)?;
439삭제: let mut snapshot =
440삭제: crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| match step {
441삭제: crate::spool::Step::Check => self.check(),
442삭제: crate::spool::Step::Activity => completed(Ok(()), self),
443삭제: crate::spool::Step::Read { bytes, total } => {
444삭제: self.progress(Stage::Read, bytes, Some(total), 0)
445삭제: }
446삭제: })?;
522추가: let mut snapshot = self.direct_snapshot(&path, limits.input)?;
447523 if expected.catalog_version != 1
448524 || expected.source_object != snapshot.object
449525 || expected.archive_bytes != snapshot.len
@@ -535,6 +611,7 @@ impl<W: Write> Job<W> {
535611 }
536612 let (info, bytes) = crate::preview::decode(kind, entry_id, bytes, self)?;
537613 self.check()?;
614추가: self.verify_direct()?;
538615 let hash: [u8; 32] = Sha256::digest(&bytes).into();
539616 completed(self.event(Message::PreviewBegin(info)), self)?;
540617 for (index, chunk) in bytes.chunks(MAX_PREVIEW_CHUNK_BYTES).enumerate() {
@@ -675,6 +752,9 @@ impl<W: Write> Job<W> {
675752 Action::Extract { list_id, .. } => list_id.as_ref(),
676753 _ => None,
677754 };
755추가: if !extract && crate::split_seven_zip::is_split(&path) {
756추가: return self.list_direct_split(&path, limits);
757추가: }
678758 let metadata_limits = self.metadata_limits();
679759 let captured = crate::split_seven_zip::open(
680760 &path,
@@ -692,6 +772,8 @@ impl<W: Write> Job<W> {
692772 let mut snapshot = if let Some(captured) = self.split_result(captured)? {
693773 self.source_group = Some(captured.group);
694774 captured.snapshot
775추가: } else if !extract {
776추가: self.direct_snapshot(&path, limits.input)?
695777 } else {
696778 crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| {
697779 match step {
@@ -738,6 +820,7 @@ impl<W: Write> Job<W> {
738820 completed(self.event(Message::Entry(member.entry.clone())), self)?;
739821 }
740822 self.verify_split()?;
823추가: self.verify_direct()?;
741824 completed(
742825 self.event(Message::ListEnd {
743826 entry_count: catalog.members.len() as u32,
@@ -1237,6 +1320,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
12371320 watchdog: Watchdog::new(),
12381321 remaining_choice: None,
12391322 source_group: None,
1323추가: direct_source: None,
1324추가: direct_split: None,
12401325 source_verified_for_publication: false,
12411326 creation_plan: None,
12421327 recovery: None,
@@ -1253,7 +1338,18 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
12531338 detail: String::new(),
12541339 },
12551340 };
1256삭제: let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| context.run(start)));
1341추가: let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1342추가: let result = context.run(start);
1343추가: if result.is_err()
1344추가: && !matches!(
1345추가: result,
1346추가: Err(ErrorCode::None | ErrorCode::Limit | ErrorCode::Protocol | ErrorCode::Internal)
1347추가: )
1348추가: {
1349추가: context.verify_direct()?;
1350추가: }
1351추가: result
1352추가: }));
12571353 let error = match result {
12581354 Ok(r) => r.err(),
12591355 Err(_) => {
수정experiments/rust-archive-worker/src/seven_zip.rs+7-7
@@ -276,7 +276,7 @@ impl Streams {
276276 }
277277 fn ranges(
278278 &self,
279삭제: input: &mut std::fs::File,
279추가: input: &mut (impl std::io::Read + std::io::Seek),
280280 data_end: u64,
281281 check: &mut impl crate::resources::Monitor,
282282 ) -> Result<Vec<(u64, u64)>> {
@@ -303,13 +303,13 @@ impl Streams {
303303 }
304304 fn decode_file(
305305 &self,
306삭제: input: &mut std::fs::File,
306추가: input: &mut (impl std::io::Read + std::io::Seek),
307307 ranges: &[(u64, u64)],
308308 output: &mut std::fs::File,
309309 selected: Option<usize>,
310310 check: &mut impl crate::resources::Monitor,
311311 ) -> Result<()> {
312삭제: use std::io::{Read, Seek, SeekFrom, Write};
312추가: use std::io::{Seek, SeekFrom, Write};
313313 let total = self
314314 .folders
315315 .iter()
@@ -407,12 +407,12 @@ impl Streams {
407407 }
408408}
409409fn digest(
410삭제: file: &mut std::fs::File,
410추가: file: &mut (impl std::io::Read + std::io::Seek),
411411 start: u64,
412412 size: u64,
413413 check: &mut impl crate::resources::Monitor,
414414) -> Result<u32> {
415삭제: use std::io::{Read, Seek, SeekFrom};
415추가: use std::io::SeekFrom;
416416 file.seek(SeekFrom::Start(start))
417417 .map_err(crate::space::io_error)?;
418418 let mut crc = 0;
@@ -589,7 +589,7 @@ fn files(
589589 Ok((members, stream_indices))
590590}
591591pub(crate) fn open(
592삭제: input: &mut std::fs::File,
592추가: input: &mut (impl std::io::Read + std::io::Seek),
593593 length: u64,
594594 limits: Limits,
595595 decode: bool,
@@ -598,7 +598,7 @@ pub(crate) fn open(
598598 open_selected(input, length, limits, decode, None, check)
599599}
600600pub(crate) fn open_selected(
601삭제: input: &mut std::fs::File,
601추가: input: &mut (impl std::io::Read + std::io::Seek),
602602 length: u64,
603603 limits: Limits,
604604 decode: bool,
수정experiments/rust-archive-worker/src/split_seven_zip.rs+195-2
@@ -448,13 +448,13 @@ impl Group {
448448 Ok(())
449449 }
450450}
451삭제: pub(crate) fn open(
451추가: fn discover(
452452 path: &Path,
453453 expected: Option<&ListId>,
454454 limit: u64,
455455 metadata_limits: crate::archive::MetadataLimits,
456456 step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
457삭제: ) -> Result<Option<Captured>> {
457추가: ) -> Result<Option<Group>> {
458458 if unsupported_split(path) {
459459 return Err(ErrorCode::UnsupportedFeature.into());
460460 }
@@ -539,6 +539,18 @@ pub(crate) fn open(
539539 if group.total > limit {
540540 return Err(ErrorCode::Limit.into());
541541 }
542추가: Ok(Some(group))
543추가: }
544추가: pub(crate) fn open(
545추가: path: &Path,
546추가: expected: Option<&ListId>,
547추가: limit: u64,
548추가: metadata_limits: crate::archive::MetadataLimits,
549추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
550추가: ) -> Result<Option<Captured>> {
551추가: let Some(mut group) = discover(path, expected, limit, metadata_limits, step)? else {
552추가: return Ok(None);
553추가: };
542554 let (mut file, hash) = loop {
543555 match group.capture(step) {
544556 Err(failure)
@@ -591,6 +603,187 @@ pub(crate) fn open(
591603 }))
592604}
593605
606추가: pub(crate) struct Direct {
607추가: group: Group,
608추가: changes: Vec<Option<(i64, i64)>>,
609추가: position: u64,
610추가: pub hash: [u8; 32],
611추가: }
612추가: impl Direct {
613추가: pub fn len(&self) -> u64 {
614추가: self.group.total
615추가: }
616추가: pub fn object(&self) -> Result<SourceObject> {
617추가: Ok(SourceObject::SplitSevenZip {
618추가: manifest_sha256: self.group.manifest()?,
619추가: })
620추가: }
621추가: fn matches(&self, index: usize, input: &Input) -> Result<()> {
622추가: let part = &self.group.parts[index];
623추가: let data = input.file.metadata().map_err(crate::space::io_error)?;
624추가: if !data.is_file()
625추가: || filesystem::object(&input.file)? != part.object
626추가: || data.len() != part.length
627추가: || data.modified().map_err(crate::space::io_error)? != part.modified
628추가: || crate::spool::change_stamp(&data) != self.changes[index]
629추가: {
630추가: return Err(ErrorCode::SourceChanged.into());
631추가: }
632추가: Ok(())
633추가: }
634추가: fn open_checked(
635추가: &self,
636추가: index: usize,
637추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
638추가: ) -> Result<Input> {
639추가: let input = self
640추가: .group
641추가: .open_part(&self.group.parts[index].name, step)
642추가: .map_err(|failure| {
643추가: if failure.error == ErrorCode::UnsafePath {
644추가: ErrorCode::SourceChanged.into()
645추가: } else {
646추가: failure
647추가: }
648추가: })?;
649추가: self.matches(index, &input)?;
650추가: Ok(input)
651추가: }
652추가: fn unchanged(
653추가: &self,
654추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
655추가: ) -> Result<()> {
656추가: for index in 0..self.group.parts.len() {
657추가: step(Step::Check)?;
658추가: self.open_checked(index, step)?;
659추가: }
660추가: Ok(())
661추가: }
662추가: pub fn verify(
663추가: &self,
664추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
665추가: ) -> Result<()> {
666추가: self.unchanged(step)?;
667추가: self.group.verify(step)?;
668추가: self.unchanged(step)
669추가: }
670추가: }
671추가: impl Read for Direct {
672추가: fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
673추가: let mut start = 0;
674추가: if output.is_empty() {
675추가: return Ok(0);
676추가: }
677추가: let source_error = |failure: Failure| {
678추가: std::io::Error::other(format!("분할 원본 읽기 실패: {:?}", failure.error))
679추가: };
680추가: for (index, part) in self.group.parts.iter().enumerate() {
681추가: let end = start + part.length;
682추가: if self.position < end {
683추가: let count = (end - self.position).min(output.len() as u64) as usize;
684추가: // 필요한 조각만 열어 핸들 사용량이 조각 수에 비례하지 않게 함.
685추가: let mut input = self
686추가: .open_checked(index, &mut |_| Ok(()))
687추가: .map_err(source_error)?;
688추가: input
689추가: .file
690추가: .seek(std::io::SeekFrom::Start(self.position - start))?;
691추가: let read = input.file.read(&mut output[..count]);
692추가: self.matches(index, &input).map_err(source_error)?;
693추가: let count = read?;
694추가: if count == 0 {
695추가: return Err(std::io::Error::new(
696추가: std::io::ErrorKind::UnexpectedEof,
697추가: "분할 원본이 변경됨",
698추가: ));
699추가: }
700추가: self.position += count as u64;
701추가: return Ok(count);
702추가: }
703추가: start = end;
704추가: }
705추가: Ok(0)
706추가: }
707추가: }
708추가: impl Seek for Direct {
709추가: fn seek(&mut self, position: std::io::SeekFrom) -> std::io::Result<u64> {
710추가: let next = match position {
711추가: std::io::SeekFrom::Start(n) => i128::from(n),
712추가: std::io::SeekFrom::Current(n) => i128::from(self.position) + i128::from(n),
713추가: std::io::SeekFrom::End(n) => i128::from(self.group.total) + i128::from(n),
714추가: };
715추가: self.position = u64::try_from(next).map_err(|_| {
716추가: std::io::Error::new(std::io::ErrorKind::InvalidInput, "잘못된 읽기 위치")
717추가: })?;
718추가: Ok(self.position)
719추가: }
720추가: }
721추가: pub(crate) fn open_direct(
722추가: path: &Path,
723추가: limit: u64,
724추가: metadata_limits: crate::archive::MetadataLimits,
725추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
726추가: ) -> Result<Option<Direct>> {
727추가: let Some(mut group) = discover(path, None, limit, metadata_limits, step)? else {
728추가: return Ok(None);
729추가: };
730추가: let mut changes = Vec::new();
731추가: for part in &group.parts {
732추가: let input = group.open_part(&part.name, step)?;
733추가: group.matches(part, &input)?;
734추가: changes.push(crate::spool::change_stamp(&metadata(&input.file)?));
735추가: }
736추가: let mut whole = Sha256::new();
737추가: let mut processed = 0;
738추가: let mut reported = Instant::now();
739추가: for index in 0..group.parts.len() {
740추가: group.parts[index].hash = group.read_part(
741추가: &group.parts[index],
742추가: &mut None,
743추가: &mut whole,
744추가: &mut processed,
745추가: &mut reported,
746추가: step,
747추가: )?;
748추가: }
749추가: step(Step::Read {
750추가: bytes: processed,
751추가: total: group.total,
752추가: })?;
753추가: let mut direct = Direct {
754추가: group,
755추가: changes,
756추가: position: 0,
757추가: hash: whole.finalize().into(),
758추가: };
759추가: let mut header = [0; 32];
760추가: if direct.group.parts.iter().any(|part| part.length == 0) || direct.len() < 32 {
761추가: return Err(direct.group.name.incomplete());
762추가: }
763추가: let header_read = direct
764추가: .read_exact(&mut header)
765추가: .map_err(crate::space::io_error);
766추가: direct.verify(step)?;
767추가: header_read?;
768추가: if &header[..6] != b"7z\xbc\xaf\x27\x1c"
769추가: || zlib_rs::crc32::crc32(0, &header[12..])
770추가: != u32::from_le_bytes(header[8..12].try_into().unwrap())
771추가: {
772추가: return Err(direct.group.name.incomplete());
773추가: }
774추가: let offset = u64::from_le_bytes(header[12..20].try_into().unwrap());
775추가: let length = u64::from_le_bytes(header[20..28].try_into().unwrap());
776추가: if 32u64
777추가: .checked_add(offset)
778추가: .and_then(|n| n.checked_add(length))
779추가: != Some(direct.len())
780추가: {
781추가: return Err(direct.group.name.incomplete());
782추가: }
783추가: direct.rewind().map_err(crate::space::io_error)?;
784추가: Ok(Some(direct))
785추가: }
786추가:
594787#[cfg(test)]
595788#[path = "../../../tests/rust-archive-worker/split_capture.rs"]
596789mod tests;
수정experiments/rust-archive-worker/src/spool.rs+143-0
@@ -271,7 +271,146 @@ pub(crate) struct Snapshot {
271271 pub object: SourceObject,
272272 pub hash: [u8; 32],
273273}
274추가: pub(crate) struct DirectSource {
275추가: file: File,
276추가: path: std::path::PathBuf,
277추가: object: SourceObject,
278추가: len: u64,
279추가: modified: std::time::SystemTime,
280추가: changed: Option<(i64, i64)>,
281추가: hash: [u8; 32],
282추가: }
283추가: pub(crate) fn change_stamp(metadata: &std::fs::Metadata) -> Option<(i64, i64)> {
284추가: #[cfg(unix)]
285추가: {
286추가: use std::os::unix::fs::MetadataExt;
287추가: Some((metadata.ctime(), metadata.ctime_nsec()))
288추가: }
289추가: #[cfg(windows)]
290추가: {
291추가: let _ = metadata;
292추가: None
293추가: }
294추가: }
295추가: fn source_options() -> OpenOptions {
296추가: let mut options = OpenOptions::new();
297추가: options.read(true);
298추가: #[cfg(unix)]
299추가: {
300추가: use std::os::unix::fs::OpenOptionsExt;
301추가: options.custom_flags(0x20000 | 0x800);
302추가: }
303추가: #[cfg(windows)]
304추가: {
305추가: use std::os::windows::fs::OpenOptionsExt;
306추가: options.share_mode(1);
307추가: }
308추가: options
309추가: }
310추가: impl DirectSource {
311추가: fn unchanged(&self) -> Result<()> {
312추가: let before = self.file.metadata().map_err(|_| ErrorCode::SourceChanged)?;
313추가: let named = source_options()
314추가: .open(&self.path)
315추가: .map_err(|_| ErrorCode::SourceChanged)?;
316추가: let after = named.metadata().map_err(|_| ErrorCode::SourceChanged)?;
317추가: for (file, metadata) in [(&self.file, before), (&named, after)] {
318추가: if !metadata.is_file()
319추가: || filesystem::object(file)? != self.object
320추가: || metadata.len() != self.len
321추가: || metadata.modified().map_err(|_| ErrorCode::SourceChanged)? != self.modified
322추가: || change_stamp(&metadata) != self.changed
323추가: {
324추가: return Err(ErrorCode::SourceChanged);
325추가: }
326추가: }
327추가: Ok(())
328추가: }
329추가: pub(crate) fn verify(&mut self, step: &mut impl FnMut(Step) -> Result<()>) -> Result<()> {
330추가: self.unchanged()?;
331추가: let hash = hash_source(&mut self.file, self.len, step)?;
332추가: self.unchanged()?;
333추가: if hash != self.hash {
334추가: return Err(ErrorCode::SourceChanged);
335추가: }
336추가: Ok(())
337추가: }
338추가: }
339추가: fn hash_source(
340추가: file: &mut File,
341추가: length: u64,
342추가: step: &mut impl FnMut(Step) -> Result<()>,
343추가: ) -> Result<[u8; 32]> {
344추가: file.rewind().map_err(|_| ErrorCode::Io)?;
345추가: let mut hash = Sha256::new();
346추가: let mut bytes = 0u64;
347추가: let mut buffer = zeroize::Zeroizing::new([0; 65536]);
348추가: let mut reported = std::time::Instant::now();
349추가: loop {
350추가: step(Step::Check)?;
351추가: let count = completed(file.read(&mut buffer[..]).map_err(|_| ErrorCode::Io), step)?;
352추가: if count == 0 {
353추가: break;
354추가: }
355추가: bytes = bytes
356추가: .checked_add(count as u64)
357추가: .filter(|n| *n <= length)
358추가: .ok_or(ErrorCode::SourceChanged)?;
359추가: hash.update(&buffer[..count]);
360추가: if reported.elapsed() >= std::time::Duration::from_millis(200) {
361추가: step(Step::Read {
362추가: bytes,
363추가: total: length,
364추가: })?;
365추가: reported = std::time::Instant::now();
366추가: }
367추가: }
368추가: if bytes != length {
369추가: return Err(ErrorCode::SourceChanged);
370추가: }
371추가: step(Step::Read {
372추가: bytes,
373추가: total: length,
374추가: })?;
375추가: file.rewind().map_err(|_| ErrorCode::Io)?;
376추가: Ok(hash.finalize().into())
377추가: }
274378impl Snapshot {
379추가: /// 열린 원본을 직접 읽고 작업 종료까지 같은 객체의 핸들을 유지함.
380추가: pub(crate) fn open_direct(
381추가: path: &Path,
382추가: limit: u64,
383추가: step: &mut impl FnMut(Step) -> Result<()>,
384추가: ) -> Result<(Self, DirectSource)> {
385추가: let mut file = completed(source_options().open(path).map_err(|_| ErrorCode::Io), step)?;
386추가: let metadata = file.metadata().map_err(|_| ErrorCode::Io)?;
387추가: if !metadata.is_file() {
388추가: return Err(ErrorCode::InvalidRequest);
389추가: }
390추가: if metadata.len() > limit {
391추가: return Err(ErrorCode::Limit);
392추가: }
393추가: let mut guard = DirectSource {
394추가: file: file.try_clone().map_err(|_| ErrorCode::Io)?,
395추가: path: path.to_path_buf(),
396추가: object: filesystem::object(&file)?,
397추가: len: metadata.len(),
398추가: modified: metadata.modified().map_err(|_| ErrorCode::Io)?,
399추가: changed: change_stamp(&metadata),
400추가: hash: [0; 32],
401추가: };
402추가: guard.hash = hash_source(&mut file, guard.len, step)?;
403추가: guard.unchanged()?;
404추가: Ok((
405추가: Self {
406추가: file,
407추가: len: guard.len,
408추가: object: guard.object.clone(),
409추가: hash: guard.hash,
410추가: },
411추가: guard,
412추가: ))
413추가: }
275414 /// 원본을 임시 파일로 복사하는 동안 읽은 바이트와 전체 크기를 함께 알림.
276415 pub fn open_reporting(
277416 path: &Path,
@@ -400,3 +539,7 @@ impl Snapshot {
400539 })
401540 }
402541}
542추가:
543추가: #[cfg(test)]
544추가: #[path = "../../../tests/rust-archive-worker/direct_source.rs"]
545추가: mod direct_source_tests;
추가tests/rust-archive-worker/direct_source.rs+115-0
@@ -0,0 +1,115 @@
1추가: use super::*;
2추가: use std::sync::atomic::{AtomicU64, Ordering};
3추가:
4추가: static NEXT: AtomicU64 = AtomicU64::new(0);
5추가: struct Source(std::path::PathBuf);
6추가: impl Source {
7추가: fn new() -> Self {
8추가: let root = std::env::var_os("TMPDIR")
9추가: .map(std::path::PathBuf::from)
10추가: .unwrap_or_else(|| {
11추가: std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")
12추가: });
13추가: std::fs::create_dir_all(&root).unwrap();
14추가: let path = root.join(format!(
15추가: "direct-source-{}-{}",
16추가: std::process::id(),
17추가: NEXT.fetch_add(1, Ordering::Relaxed)
18추가: ));
19추가: std::fs::create_dir(&path).unwrap();
20추가: std::fs::write(path.join("input"), vec![42; 1024 * 1024]).unwrap();
21추가: Self(path)
22추가: }
23추가: fn path(&self) -> std::path::PathBuf {
24추가: self.0.join("input")
25추가: }
26추가: }
27추가: impl Drop for Source {
28추가: fn drop(&mut self) {
29추가: std::fs::remove_dir_all(&self.0).unwrap();
30추가: }
31추가: }
32추가:
33추가: #[test]
34추가: fn direct_source_matches_copied_identity_length_and_hash() {
35추가: let source = Source::new();
36추가: let (direct, mut guard) =
37추가: Snapshot::open_direct(&source.path(), u64::MAX, &mut |_| Ok(())).unwrap();
38추가: let copied = Snapshot::open_reporting(&source.path(), u64::MAX, &mut |_| Ok(())).unwrap();
39추가: assert_eq!(direct.object, copied.object);
40추가: assert_eq!(direct.len, copied.len);
41추가: assert_eq!(direct.hash, copied.hash);
42추가: guard.verify(&mut |_| Ok(())).unwrap();
43추가: }
44추가:
45추가: #[cfg(unix)]
46추가: #[test]
47추가: fn direct_source_detects_same_size_and_restored_mtime_changes() {
48추가: let source = Source::new();
49추가: let (_, mut guard) = Snapshot::open_direct(&source.path(), u64::MAX, &mut |_| Ok(())).unwrap();
50추가: let modified = std::fs::metadata(source.path())
51추가: .unwrap()
52추가: .modified()
53추가: .unwrap();
54추가: let mut file = OpenOptions::new().write(true).open(source.path()).unwrap();
55추가: file.seek(SeekFrom::Start(512)).unwrap();
56추가: file.write_all(b"x").unwrap();
57추가: file.set_times(std::fs::FileTimes::new().set_modified(modified))
58추가: .unwrap();
59추가: assert!(matches!(
60추가: guard.verify(&mut |_| Ok(())),
61추가: Err(ErrorCode::SourceChanged)
62추가: ));
63추가: }
64추가:
65추가: #[cfg(unix)]
66추가: #[test]
67추가: fn direct_source_detects_named_replacement_even_when_open_handle_survives() {
68추가: let source = Source::new();
69추가: let (_, mut guard) = Snapshot::open_direct(&source.path(), u64::MAX, &mut |_| Ok(())).unwrap();
70추가: std::fs::rename(source.path(), source.0.join("old")).unwrap();
71추가: std::fs::write(source.path(), vec![42; 1024 * 1024]).unwrap();
72추가: assert!(matches!(
73추가: guard.verify(&mut |_| Ok(())),
74추가: Err(ErrorCode::SourceChanged)
75추가: ));
76추가: }
77추가:
78추가: #[cfg(windows)]
79추가: #[test]
80추가: fn direct_source_allows_existing_readers_and_blocks_writers_until_closed() {
81추가: use std::os::windows::fs::OpenOptionsExt;
82추가: let source = Source::new();
83추가: let reader = OpenOptions::new()
84추가: .read(true)
85추가: .share_mode(3)
86추가: .open(source.path())
87추가: .unwrap();
88추가: let (snapshot, guard) =
89추가: Snapshot::open_direct(&source.path(), u64::MAX, &mut |_| Ok(())).unwrap();
90추가: assert!(OpenOptions::new().read(true).open(source.path()).is_ok());
91추가: assert!(OpenOptions::new().write(true).open(source.path()).is_err());
92추가: drop((snapshot, guard, reader));
93추가: assert!(OpenOptions::new().write(true).open(source.path()).is_ok());
94추가: }
95추가:
96추가: #[cfg(unix)]
97추가: #[test]
98추가: fn direct_source_detects_transient_change_even_after_bytes_and_mtime_are_restored() {
99추가: let source = Source::new();
100추가: let (_, mut guard) = Snapshot::open_direct(&source.path(), u64::MAX, &mut |_| Ok(())).unwrap();
101추가: let modified = std::fs::metadata(source.path())
102추가: .unwrap()
103추가: .modified()
104추가: .unwrap();
105추가: let mut file = OpenOptions::new().write(true).open(source.path()).unwrap();
106추가: file.write_all(b"x").unwrap();
107추가: file.rewind().unwrap();
108추가: file.write_all(b"*").unwrap();
109추가: file.set_times(std::fs::FileTimes::new().set_modified(modified))
110추가: .unwrap();
111추가: assert!(matches!(
112추가: guard.verify(&mut |_| Ok(())),
113추가: Err(ErrorCode::SourceChanged)
114추가: ));
115추가: }
수정tests/rust-archive-worker/split_capture.rs+254-0
@@ -483,3 +483,257 @@ fn scratch_abrupt_exit_leaves_parts_only_under_tmpdir() {
483483 };
484484 assert!(!path.exists());
485485}
486추가:
487추가: #[test]
488추가: fn direct_reader_preserves_copy_hash_manifest_and_reads_across_volume_boundaries() {
489추가: use std::io::SeekFrom;
490추가: let s = Scratch::new();
491추가: let original = s.split(11);
492추가: let copied = s.capture();
493추가: let mut direct = open_direct(
494추가: &s.first(),
495추가: u64::MAX,
496추가: crate::archive::MetadataLimits::default(),
497추가: &mut |_| Ok(()),
498추가: )
499추가: .unwrap()
500추가: .unwrap();
501추가: assert_eq!(direct.hash, copied.snapshot.hash);
502추가: assert_eq!(direct.object().unwrap(), copied.snapshot.object);
503추가: assert_eq!(direct.len(), original.len() as u64);
504추가: for offset in [
505추가: 0,
506추가: 1,
507추가: original.len() / 11 - 1,
508추가: original.len() / 2,
509추가: original.len() - 1,
510추가: ] {
511추가: direct.seek(SeekFrom::Start(offset as u64)).unwrap();
512추가: let mut bytes = vec![0; (original.len() - offset).min(64)];
513추가: direct.read_exact(&mut bytes).unwrap();
514추가: assert_eq!(bytes, original[offset..offset + bytes.len()]);
515추가: }
516추가: direct.seek(SeekFrom::End(1)).unwrap();
517추가: assert_eq!(direct.read(&mut [0; 1]).unwrap(), 0);
518추가: assert!(direct.seek(SeekFrom::Start(0)).is_ok());
519추가: assert!(direct.seek(SeekFrom::Current(-1)).is_err());
520추가: direct.verify(&mut |_| Ok(())).unwrap();
521추가: }
522추가:
523추가: #[cfg(unix)]
524추가: #[test]
525추가: fn direct_reader_detects_transient_middle_volume_changes() {
526추가: use std::io::{SeekFrom, Write};
527추가: let s = Scratch::new();
528추가: s.split(11);
529추가: let direct = open_direct(
530추가: &s.first(),
531추가: u64::MAX,
532추가: crate::archive::MetadataLimits::default(),
533추가: &mut |_| Ok(()),
534추가: )
535추가: .unwrap()
536추가: .unwrap();
537추가: let path = s.0.join("sample.7z.006");
538추가: let original = std::fs::read(&path).unwrap();
539추가: let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
540추가: let mut file = std::fs::OpenOptions::new().write(true).open(path).unwrap();
541추가: file.write_all(&[original[0] ^ 1]).unwrap();
542추가: file.seek(SeekFrom::Start(0)).unwrap();
543추가: file.write_all(&original[..1]).unwrap();
544추가: file.set_times(std::fs::FileTimes::new().set_modified(modified))
545추가: .unwrap();
546추가: assert_eq!(
547추가: code(direct.verify(&mut |_| Ok(()))),
548추가: ErrorCode::SourceChanged
549추가: );
550추가: }
551추가:
552추가: #[cfg(unix)]
553추가: #[test]
554추가: fn direct_reader_detects_transient_change_during_final_verification() {
555추가: use std::io::{SeekFrom, Write};
556추가: let s = Scratch::new();
557추가: s.split(11);
558추가: let direct = open_direct(
559추가: &s.first(),
560추가: u64::MAX,
561추가: crate::archive::MetadataLimits::default(),
562추가: &mut |_| Ok(()),
563추가: )
564추가: .unwrap()
565추가: .unwrap();
566추가: let path = s.first();
567추가: let original = std::fs::read(&path).unwrap();
568추가: let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
569추가: let mut changed = false;
570추가: let result = direct.verify(&mut |step| {
571추가: if !changed && matches!(step, Step::Activity) {
572추가: let mut file = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
573추가: file.write_all(&[original[0] ^ 1]).unwrap();
574추가: file.seek(SeekFrom::Start(0)).unwrap();
575추가: file.write_all(&original[..1]).unwrap();
576추가: file.set_times(std::fs::FileTimes::new().set_modified(modified))
577추가: .unwrap();
578추가: changed = true;
579추가: }
580추가: Ok(())
581추가: });
582추가: assert!(changed);
583추가: assert_eq!(code(result), ErrorCode::SourceChanged);
584추가: }
585추가:
586추가: #[cfg(target_os = "linux")]
587추가: #[test]
588추가: fn direct_reader_low_fd_child() {
589추가: if std::env::var_os("ZIPELO_SPLIT_LOW_FD_CHILD").is_none() {
590추가: return;
591추가: }
592추가: use std::io::SeekFrom;
593추가: let s = Scratch::new();
594추가: let original = s.split(11);
595추가: let mut copied = s.capture();
596추가: let expected = token(&copied);
597추가: let catalog = crate::seven_zip::open(
598추가: &mut copied.snapshot.file,
599추가: expected.archive_bytes,
600추가: Limits::default(),
601추가: false,
602추가: &mut || Ok(()),
603추가: )
604추가: .unwrap();
605추가: let entries = catalog
606추가: .members
607추가: .iter()
608추가: .map(|m| m.entry.clone())
609추가: .collect::<Vec<_>>();
610추가: drop((catalog, copied));
611추가: let mut direct = open_direct(&s.first(), u64::MAX, Default::default(), &mut |_| Ok(()))
612추가: .unwrap()
613추가: .unwrap();
614추가: assert_eq!(direct.hash, expected.archive_sha256);
615추가: assert_eq!(direct.object().unwrap(), expected.source_object);
616추가: assert_eq!(direct.len(), expected.archive_bytes);
617추가: let mut bytes = Vec::new();
618추가: direct.read_to_end(&mut bytes).unwrap();
619추가: assert_eq!(bytes, original);
620추가: direct.seek(SeekFrom::End(-12)).unwrap();
621추가: let mut last = [0; 12];
622추가: direct.read_exact(&mut last).unwrap();
623추가: assert_eq!(last, original[original.len() - 12..]);
624추가: let catalog = crate::seven_zip::open(
625추가: &mut direct,
626추가: expected.archive_bytes,
627추가: Limits::default(),
628추가: false,
629추가: &mut || Ok(()),
630추가: )
631추가: .unwrap();
632추가: assert_eq!(
633추가: catalog
634추가: .members
635추가: .iter()
636추가: .map(|m| m.entry.clone())
637추가: .collect::<Vec<_>>(),
638추가: entries
639추가: );
640추가: drop(catalog);
641추가: direct.verify(&mut |_| Ok(())).unwrap();
642추가: assert_eq!(std::fs::read_dir(&s.0).unwrap().count(), 11);
643추가: }
644추가:
645추가: #[cfg(target_os = "linux")]
646추가: #[test]
647추가: fn direct_reader_with_sixteen_file_descriptors_lists_eleven_volumes() {
648추가: use std::os::unix::process::CommandExt;
649추가: #[repr(C)]
650추가: struct Limit {
651추가: soft: u64,
652추가: hard: u64,
653추가: }
654추가: unsafe extern "C" {
655추가: fn setrlimit(resource: i32, limit: *const Limit) -> i32;
656추가: }
657추가: let s = Scratch::new();
658추가: let mut command = std::process::Command::new(std::env::current_exe().unwrap());
659추가: command
660추가: .args([
661추가: "--exact",
662추가: "split_seven_zip::tests::direct_reader_low_fd_child",
663추가: "--test-threads=1",
664추가: ])
665추가: .env("TMPDIR", &s.0)
666추가: .env("ZIPELO_SPLIT_LOW_FD_CHILD", "1");
667추가: // 자식 프로세스의 파일 핸들 상한만 16으로 제한함.
668추가: unsafe {
669추가: command.pre_exec(|| {
670추가: if setrlimit(7, &Limit { soft: 16, hard: 16 }) == 0 {
671추가: Ok(())
672추가: } else {
673추가: Err(std::io::Error::last_os_error())
674추가: }
675추가: });
676추가: }
677추가: let result = command.output().unwrap();
678추가: assert!(
679추가: result.status.success(),
680추가: "stdout={} stderr={}",
681추가: String::from_utf8_lossy(&result.stdout),
682추가: String::from_utf8_lossy(&result.stderr)
683추가: );
684추가: assert_eq!(std::fs::read_dir(&s.0).unwrap().count(), 0);
685추가: }
686추가:
687추가: #[test]
688추가: fn direct_reader_reopens_volumes_and_rejects_same_content_replacement_before_read() {
689추가: use std::io::SeekFrom;
690추가: let s = Scratch::new();
691추가: let original = s.split(11);
692추가: let mut direct = open_direct(&s.first(), u64::MAX, Default::default(), &mut |_| Ok(()))
693추가: .unwrap()
694추가: .unwrap();
695추가: let path = s.0.join("sample.7z.006");
696추가: let bytes = std::fs::read(&path).unwrap();
697추가: let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
698추가: std::fs::rename(&path, s.0.join("previous")).unwrap();
699추가: std::fs::write(&path, bytes).unwrap();
700추가: std::fs::OpenOptions::new()
701추가: .write(true)
702추가: .open(&path)
703추가: .unwrap()
704추가: .set_times(std::fs::FileTimes::new().set_modified(modified))
705추가: .unwrap();
706추가: direct
707추가: .seek(SeekFrom::Start((5 * original.len() / 11) as u64))
708추가: .unwrap();
709추가: assert!(direct.read(&mut [0; 1]).is_err());
710추가: assert_eq!(
711추가: code(direct.verify(&mut |_| Ok(()))),
712추가: ErrorCode::SourceChanged
713추가: );
714추가: }
715추가:
716추가: #[test]
717추가: fn direct_reader_classifies_non_file_replacement_as_source_changed() {
718추가: let s = Scratch::new();
719추가: s.split(11);
720추가: let direct = open_direct(&s.first(), u64::MAX, Default::default(), &mut |_| Ok(()))
721추가: .unwrap()
722추가: .unwrap();
723추가: let path = s.0.join("sample.7z.006");
724추가: std::fs::rename(&path, s.0.join("previous")).unwrap();
725추가: std::fs::create_dir(&path).unwrap();
726추가: assert_eq!(
727추가: code(direct.verify(&mut |_| Ok(()))),
728추가: ErrorCode::SourceChanged
729추가: );
730추가: #[cfg(unix)]
731추가: {
732추가: std::fs::remove_dir(&path).unwrap();
733추가: std::os::unix::fs::symlink(s.0.join("previous"), &path).unwrap();
734추가: assert_eq!(
735추가: code(direct.verify(&mut |_| Ok(()))),
736추가: ErrorCode::SourceChanged
737추가: );
738추가: }
739추가: }
수정tests/rust-archive-worker/spool_fallback.rs+214-20
@@ -76,7 +76,7 @@ impl Case {
7676 if phase == "home" {
7777 command.env_remove("XDG_CACHE_HOME");
7878 }
79삭제: if phase == "changed" {
79추가: if phase.ends_with("changed") {
8080 command.env(
8181 "ZIPELO_SPOOL_SOURCE",
8282 match &action {
@@ -299,7 +299,7 @@ fn cache_source_and_system_locations_retry_creation_space_and_partial_quota_writ
299299 }
300300}
301301#[test]
302삭제: fn split_seven_zip_retries_all_locations_after_partial_quota_writes() {
302추가: fn split_seven_zip_lists_without_archive_sized_temporary_storage() {
303303 use sha2::{Digest, Sha256};
304304 for named in [false, true] {
305305 for phase in ["write", "space", "create"] {
@@ -310,7 +310,7 @@ fn split_seven_zip_retries_all_locations_after_partial_quota_writes() {
310310 let bytes = fs::read(c.archive("7z").to_path().unwrap()).unwrap();
311311 let zip = fs::read(c.archive("zip").to_path().unwrap()).unwrap();
312312 let events = c.run(Action::List { archive }, phase, mask, named);
313삭제: if mask == 7 {
313추가: if mask == 7 && phase == "create" {
314314 assert_eq!(
315315 terminal(&events).outcome,
316316 Outcome::Failed,
@@ -347,15 +347,16 @@ fn split_seven_zip_retries_all_locations_after_partial_quota_writes() {
347347 ));
348348 }
349349 let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
350삭제: for at in if mask == 1 {
351삭제: &['0', '1'][..]
350추가: if phase == "create" {
351추가: for at in if mask == 1 {
352추가: &['0', '1'][..]
353추가: } else {
354추가: &['0', '1', '2'][..]
355추가: } {
356추가: assert!(trace.contains(*at), "{phase}/{mask}/{named}: {trace}");
357추가: }
352358 } else {
353삭제: &['0', '1', '2'][..]
354삭제: } {
355삭제: assert!(trace.contains(*at), "{phase}/{mask}/{named}: {trace}");
356삭제: }
357삭제: if mask == 1 {
358삭제: assert!(!trace.contains('2'), "{trace}");
359추가: assert!(!trace.contains('1') && !trace.contains('2'), "{trace}");
359360 }
360361 for (path, original) in originals {
361362 assert_eq!(fs::read(path).unwrap(), original);
@@ -368,7 +369,7 @@ fn split_seven_zip_retries_all_locations_after_partial_quota_writes() {
368369}
369370
370371#[test]
371삭제: fn split_source_change_during_failed_copy_prevents_retry_success() {
372추가: fn split_source_change_during_direct_read_prevents_success() {
372373 for named in [false, true] {
373374 let mut c = Case::new();
374375 let (archive, originals) = c.split();
@@ -389,12 +390,205 @@ fn split_source_change_during_failed_copy_prevents_retry_success() {
389390 }
390391}
391392
393추가: #[test]
394추가: fn archive_larger_than_every_temporary_quota_lists_previews_and_extracts_with_same_id() {
395추가: use sha2::{Digest, Sha256};
396추가: use std::os::unix::fs::MetadataExt;
397추가: for named in [false, true] {
398추가: let mut c = Case::new();
399추가: let solid = c.list("7z", "quota", 7, named);
400추가: assert_eq!(terminal(&solid).outcome, Outcome::Completed, "{solid:?}");
401추가: assert!(
402추가: Command::new("python3")
403추가: .arg("-B")
404추가: .arg(
405추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
406추가: .join("../../tests/rust-archive-worker/spool_fallback_cases.py")
407추가: )
408추가: .arg(&c.scratch.0)
409추가: .arg("non-solid")
410추가: .status()
411추가: .unwrap()
412추가: .success()
413추가: );
414추가: for format in ["zip", "7z"] {
415추가: c.assert_preview(format, "quota", 7, named);
416추가: let events = c.list(format, "quota", 7, named);
417추가: let id = events
418추가: .iter()
419추가: .find_map(|event| match event {
420추가: Message::ListEnd { list_id, .. } => Some(list_id.clone()),
421추가: _ => None,
422추가: })
423추가: .unwrap();
424추가: let path = c.archive(format).to_path().unwrap();
425추가: let bytes = fs::read(&path).unwrap();
426추가: let metadata = fs::metadata(path).unwrap();
427추가: assert!(bytes.len() > 16 * 1024 * 1024);
428추가: assert_eq!(id.catalog_version, 1);
429추가: assert_eq!(id.archive_bytes, bytes.len() as u64);
430추가: assert_eq!(
431추가: id.archive_sha256.as_slice(),
432추가: Sha256::digest(&bytes).as_slice()
433추가: );
434추가: assert_eq!(
435추가: id.source_object,
436추가: SourceObject::Unix {
437추가: device: metadata.dev(),
438추가: inode: metadata.ino()
439추가: }
440추가: );
441추가: let output = c.scratch.0.join(format!("output-{format}"));
442추가: fs::DirBuilder::new().mode(0o700).create(&output).unwrap();
443추가: let extracted = execute(Start {
444추가: action: Action::Extract {
445추가: archive: c.archive(format),
446추가: destination: NativePath::from_path(&output),
447추가: selection: Selection::EntryIds(vec![0]),
448추가: list_id: Some(id),
449추가: gzip_output_name: None,
450추가: },
451추가: limits: Limits::default(),
452추가: });
453추가: assert_eq!(
454추가: terminal(&extracted).outcome,
455추가: Outcome::Completed,
456추가: "{extracted:?}"
457추가: );
458추가: assert_eq!(fs::read(output.join("preview.txt")).unwrap(), PAYLOAD);
459추가: }
460추가: let (archive, originals) = c.split();
461추가: let events = c.run(
462추가: Action::List {
463추가: archive: archive.clone(),
464추가: },
465추가: "quota",
466추가: 7,
467추가: named,
468추가: );
469추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
470추가: let id = events
471추가: .iter()
472추가: .find_map(|event| match event {
473추가: Message::ListEnd { list_id, .. } => Some(list_id.clone()),
474추가: _ => None,
475추가: })
476추가: .unwrap();
477추가: let output = c.scratch.0.join("output-split");
478추가: fs::DirBuilder::new().mode(0o700).create(&output).unwrap();
479추가: let extracted = execute(Start {
480추가: action: Action::Extract {
481추가: archive: archive.clone(),
482추가: destination: NativePath::from_path(&output),
483추가: selection: Selection::EntryIds(vec![0]),
484추가: list_id: Some(id.clone()),
485추가: gzip_output_name: None,
486추가: },
487추가: limits: Limits::default(),
488추가: });
489추가: assert_eq!(
490추가: terminal(&extracted).outcome,
491추가: Outcome::Completed,
492추가: "{extracted:?}"
493추가: );
494추가: assert_eq!(fs::read(output.join("preview.txt")).unwrap(), PAYLOAD);
495추가: let preview = c.run(
496추가: Action::Preview {
497추가: archive,
498추가: list_id: id,
499추가: entry_id: 0,
500추가: },
501추가: "quota",
502추가: 7,
503추가: named,
504추가: );
505추가: assert_eq!(terminal(&preview).error, ErrorCode::UnsupportedFeature);
506추가: for (path, bytes) in originals {
507추가: assert_eq!(fs::read(path).unwrap(), bytes);
508추가: }
509추가: }
510추가: }
511추가:
512추가: #[test]
513추가: fn source_change_after_initial_hash_rejects_list_and_preview_results() {
514추가: for named in [false, true] {
515추가: for format in ["zip", "7z"] {
516추가: let c = Case::new();
517추가: let events = c.list(format, "late-changed", 7, named);
518추가: assert_eq!(
519추가: terminal(&events).error,
520추가: ErrorCode::SourceChanged,
521추가: "{events:?}"
522추가: );
523추가: assert!(
524추가: !events
525추가: .iter()
526추가: .any(|event| matches!(event, Message::ListEnd { .. }))
527추가: );
528추가: let c = Case::new();
529추가: let events = c.list(format, "quota", 7, named);
530추가: let id = events
531추가: .iter()
532추가: .find_map(|event| match event {
533추가: Message::ListEnd { list_id, .. } => Some(list_id.clone()),
534추가: _ => None,
535추가: })
536추가: .unwrap();
537추가: let events = c.run(
538추가: Action::Preview {
539추가: archive: c.archive(format),
540추가: list_id: id,
541추가: entry_id: 0,
542추가: },
543추가: "late-changed",
544추가: 7,
545추가: named,
546추가: );
547추가: assert_eq!(
548추가: terminal(&events).error,
549추가: ErrorCode::SourceChanged,
550추가: "{events:?}"
551추가: );
552추가: assert!(!events.iter().any(|event| matches!(
553추가: event,
554추가: Message::PreviewBegin(_) | Message::PreviewEnd { .. }
555추가: )));
556추가: }
557추가: let mut c = Case::new();
558추가: let (archive, _) = c.split();
559추가: let events = c.run(Action::List { archive }, "late-changed", 7, named);
560추가: assert_eq!(
561추가: terminal(&events).error,
562추가: ErrorCode::SourceChanged,
563추가: "{events:?}"
564추가: );
565추가: assert!(
566추가: !events
567추가: .iter()
568추가: .any(|event| matches!(event, Message::ListEnd { .. }))
569추가: );
570추가: }
571추가: }
572추가:
392573#[test]
393574fn disk_full_requires_exhausting_all_three_locations_and_io_errors_stay_io() {
394575 for phase in ["create", "space", "write"] {
395576 let c = Case::new();
396577 for format in ["zip", "7z"] {
397삭제: let events = c.list(format, phase, 7, false);
578추가: let events = if phase == "create" {
579추가: c.list(format, phase, 7, false)
580추가: } else {
581추가: c.preview(
582추가: format,
583추가: if phase == "space" {
584추가: "stage-space"
585추가: } else {
586추가: phase
587추가: },
588추가: 7,
589추가: false,
590추가: )
591추가: };
398592 assert_eq!(
399593 terminal(&events).error,
400594 ErrorCode::DiskFull,
@@ -410,7 +604,11 @@ fn disk_full_requires_exhausting_all_three_locations_and_io_errors_stay_io() {
410604 }
411605 let c = Case::new();
412606 for phase in ["io", "denied"] {
413삭제: let events = c.list("zip", phase, 7, false);
607추가: let events = if phase == "io" {
608추가: c.preview("zip", phase, 7, false)
609추가: } else {
610추가: c.list("zip", phase, 7, false)
611추가: };
414612 assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}");
415613 }
416614}
@@ -478,7 +676,7 @@ fn default_home_cache_is_created_privately() {
478676}
479677
480678#[test]
481삭제: fn source_change_during_failed_copy_prevents_retry_success() {
679추가: fn source_change_during_direct_read_prevents_success() {
482680 let c = Case::new();
483681 let events = c.list("zip", "changed", 1, false);
484682 assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
@@ -487,11 +685,7 @@ fn source_change_during_failed_copy_prevents_retry_success() {
487685 ErrorCode::SourceChanged,
488686 "{events:?}"
489687 );
490삭제: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
491삭제: assert!(
492삭제: trace.contains('0') && !trace.contains('1') && !trace.contains('2'),
493삭제: "{trace}"
494삭제: );
688추가: assert!(!c.scratch.0.join("trace").exists());
495689}
496690
497691#[test]
수정tests/rust-archive-worker/spool_fallback_cases.py+24-1
@@ -3,7 +3,9 @@ from pathlib import Path
33import sys
44import zipfile
55
6삭제: from seven_zip_fixtures import archive
6추가: from seven_zip_fixtures import archive, integer, property_bytes, packed, streams, SIGNATURE
7추가: import struct
8추가: import zlib
79
810root = Path(sys.argv[1])
911payload = b"spool fallback preview\n"
@@ -16,3 +18,24 @@ with zipfile.ZipFile(
1618(root / "archive" / "input.7z").write_bytes(
1719 archive([("preview.txt", payload, 0x20), ("filler.bin", filler, 0x20)], method="copy")
1820)
21추가:
22추가: if len(sys.argv) > 2 and sys.argv[2] == "non-solid":
23추가: entries = [("preview.txt", payload), ("filler.bin", filler)]
24추가: packed_bytes = b"".join(data for _, data in entries)
25추가: sizes = b"".join(integer(len(data)) for _, data in entries)
26추가: digests = b"".join(struct.pack("<I", zlib.crc32(data)) for _, data in entries)
27추가: info = b"\x06\x00\x02\x09" + sizes + b"\x0a\x01" + digests + b"\x00"
28추가: info += b"\x07\x0b\x02\x00" + b"\x01\x01\x00" * 2
29추가: info += b"\x0c" + sizes + b"\x0a\x01" + digests + b"\x00\x08\x00\x00"
30추가: files = b"\x05\x02" + property_bytes(
31추가: 17, b"\x00" + b"".join(name.encode("utf-16le") + b"\x00\x00" for name, _ in entries)
32추가: )
33추가: files += property_bytes(21, b"\x01\x00" + struct.pack("<II", 0x20, 0x20))
34추가: header = b"\x01\x04" + info + files + b"\x00\x00"
35추가: encoded, coder = packed(header, "lzma")
36추가: next_header = b"\x17" + streams(len(packed_bytes), encoded, coder, header, [header])
37추가: packed_bytes += encoded
38추가: start = struct.pack("<QQI", len(packed_bytes), len(next_header), zlib.crc32(next_header))
39추가: (root / "archive" / "input.7z").write_bytes(
40추가: SIGNATURE + struct.pack("<I", zlib.crc32(start)) + start + packed_bytes + next_header
41추가: )
수정tests/rust-archive-worker/spool_location_fault.c+38-7
@@ -7,6 +7,9 @@
77#include <stdlib.h>
88#include <string.h>
99#include <sys/statvfs.h>
10추가: #include <sys/stat.h>
11추가: #include <sys/resource.h>
12추가: #include <signal.h>
1013#include <unistd.h>
1114
1215static int (*original_openat)(int, const char *, int, ...);
@@ -14,11 +17,19 @@ static int (*original_open64)(const char *, int, ...);
1417static ssize_t (*original_write)(int, const void *, size_t);
1518static int written[3];
1619static int snapshot_fd = -1;
20추가: static int source_changed;
21추가: static unsigned long long source_read;
1722
1823__attribute__((constructor)) static void initialize(void) {
1924 original_openat = dlsym(RTLD_NEXT, "openat");
2025 original_open64 = dlsym(RTLD_NEXT, "open64");
2126 original_write = dlsym(RTLD_NEXT, "write");
27추가: const char *phase = getenv("ZIPELO_SPOOL_PHASE");
28추가: if (phase && !strcmp(phase, "quota")) {
29추가: struct rlimit limit = {65536, 65536};
30추가: signal(SIGXFSZ, SIG_IGN);
31추가: if (setrlimit(RLIMIT_FSIZE, &limit)) _exit(99);
32추가: }
2233}
2334static int location(const char *path) {
2435 if (strstr(path, "/cache/")) return 0;
@@ -109,13 +120,6 @@ ssize_t write(int fd, const void *bytes, size_t count) {
109120 || !strcmp(phase, "changed") || !strcmp(phase, "io"))) {
110121 if (!strcmp(phase, "io")) { errno = EIO; return -1; }
111122 if (!written[at]++) return original_write(fd, bytes, count < 7 ? count : 7);
112삭제: if (!strcmp(phase, "changed")) {
113삭제: int source = original_openat(AT_FDCWD, getenv("ZIPELO_SPOOL_SOURCE"), O_WRONLY | O_APPEND);
114삭제: if (source >= 0) {
115삭제: original_write(source, "x", 1);
116삭제: close(source);
117삭제: }
118삭제: }
119123 errno = EDQUOT;
120124 return -1;
121125 }
@@ -132,5 +136,32 @@ int fstatvfs(int fd, struct statvfs *value) {
132136 value->f_frsize = 1;
133137 value->f_bavail = stage ? 0 : 1024;
134138 }
139추가: if (!result && affected(at) && phase && !strcmp(phase, "quota")) {
140추가: value->f_frsize = 1;
141추가: value->f_bavail = 65536;
142추가: }
135143 return result;
136144}
145추가:
146추가: ssize_t read(int fd, void *bytes, size_t count) {
147추가: ssize_t (*original)(int, void *, size_t) = dlsym(RTLD_NEXT, "read");
148추가: ssize_t length = original(fd, bytes, count);
149추가: const char *phase = getenv("ZIPELO_SPOOL_PHASE");
150추가: const char *source = getenv("ZIPELO_SPOOL_SOURCE");
151추가: char path[4096];
152추가: descriptor(fd, path, sizeof(path));
153추가: struct stat data;
154추가: if (length > 0 && source && !strcmp(path, source)) source_read += length;
155추가: int late = phase && !strcmp(phase, "late-changed") && !fstat(fd, &data)
156추가: && source_read > (unsigned long long)data.st_size;
157추가: if (length > 0 && !source_changed && phase && (!strcmp(phase, "changed") || late)
158추가: && source && !strcmp(path, source)) {
159추가: source_changed = 1;
160추가: int output = original_openat(AT_FDCWD, source, O_WRONLY | O_APPEND);
161추가: if (output >= 0) {
162추가: original_write(output, "x", 1);
163추가: close(output);
164추가: }
165추가: }
166추가: return length;
167추가: }