team-ljyzipelo

공개

디스크 공간 부족을 전용 오류로 구분함

작성자
시로사키 하나
작성 시각
커밋
39de76aa90830abfee777e7cc56fb47a490905ac
부모
6ede861
이 시점의 파일 보기

변경된 파일 13개

+283-47
수정experiments/rust-archive-worker/README.md+3-3
@@ -13,11 +13,11 @@
1313
1414## 스트리밍과 자원 정리
1515
16삭제: 기존 revision 2의 필드와 tag 및 공동 합의한 입력/출력 기본 한도를 유지합니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 압축비 거부 제거와 여유 공간 검사의 frontend 확인은 PR에서 별도로 받습니다. 세부 계약은 contract.json의 streaming_limits에 있습니다.
16추가: revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도를 유지하고, 히나타 님과 합의한 공간 부족 오류 DiskFull(tag 13)을 추가합니다. 구버전 앱은 새 tag를 거부하므로 앱 오류 변환과 화면 매핑을 작업자와 함께 갱신해야 합니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 세부 계약은 contract.json의 streaming_limits에 있습니다.
1717
1818- 압축비는 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다.
19삭제: - 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. ZIP/7z 해제 전에는 전체 임시 해제량과 선택한 출력량을 볼륨별로 합산해 검사하고, 게시 전에도 출력 공간을 재검사합니다. 미리 해제 크기를 알 수 없는 GZ/TAR.GZ는 각 해제 청크를 쓰기 전에 임시 저장소 공간을 확인합니다. Linux 64비트는 열린 핸들의 [fstatvfs](https://man7.org/linux/man-pages/man3/fstatvfs.3.html), Windows는 핸들에서 얻은 디렉터리의 [GetDiskFreeSpaceExW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexw)를 사용합니다. 조회 실패와 부족은 기존 Io로 반환합니다.
20삭제: - 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 이 정책의 frontend 계약 확인은 PR에서 별도로 받습니다.
19추가: - 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. ZIP/7z 해제 전에는 전체 임시 해제량과 선택한 출력량을 볼륨별로 합산해 검사하고, 게시 전에도 출력 공간을 재검사합니다. 미리 해제 크기를 알 수 없는 GZ/TAR.GZ는 각 해제 청크를 쓰기 전에 임시 저장소 공간을 확인합니다. Linux 64비트는 열린 핸들의 [fstatvfs](https://man7.org/linux/man-pages/man3/fstatvfs.3.html), Windows는 핸들에서 얻은 디렉터리의 [GetDiskFreeSpaceExW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexw)를 사용합니다. 공간 부족은 DiskFull(13), 조회 실패와 권한 등 다른 I/O 오류는 Io(8)로 반환합니다. 실제 생성/쓰기/동기화의 공간 부족에도 같은 구분을 적용합니다. Windows의 공간 부족 코드 39와 112는 [공식 오류 목록](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-)을 따릅니다.
20추가: - 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 오류 문구는 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"이며, detail 문자열을 오류 판정에 사용하지 않습니다.
2121- 입력과 검증된 해제 내용은 임시 파일에 저장합니다. Linux는 [O_TMPFILE](https://man7.org/linux/man-pages/man2/open.2.html), 이를 지원하지 않는 Linux 파일시스템에서는 0600 난수 파일을 배타적으로 만든 즉시 unlink하고 링크 수 0을 확인합니다. Windows는 배타적 [DELETE_ON_CLOSE 파일](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew)을 사용합니다. 마지막 핸들이 닫히면 제거되며 임시 파일명에 아카이브 내부 이름을 사용하지 않습니다. 디스크에는 입력 사본, 해제 내용과 현재 출력 임시 파일이 동시에 필요할 수 있습니다. 임시 폴더가 tmpfs이면 해당 파일 내용은 프로세스 RSS 외의 시스템 메모리를 사용합니다.
2222- 64 MiB는 ZIP/TAR/GZ/TAR.GZ 해제 작업자 프로세스의 피크 RSS 시험 목표입니다. OS 메모리 강제 격리나 모든 아카이브의 보장을 뜻하지 않습니다. 7z와 생성은 이 RSS 목표에 포함하지 않습니다. 입력 크기와 무관한 메타데이터 예산은 유지합니다.
2323- Linux는 시작 시 부모 PID를 캡처하고 [getppid](https://man7.org/linux/man-pages/man2/getpid.2.html) 변경을 확인합니다. Windows는 부모 프로세스 핸들과 생성 시간을 확인한 뒤 [WaitForSingleObject](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject)로 생존을 검사합니다. 부모가 사라지면 checkpoint에서 Io로 중단하고 임시 출력을 정리합니다. 이미 게시한 파일/디렉터리는 유지하며 OS의 블로킹 I/O 강제 중단을 보장하지 않습니다. 기존 단발 요청을 위해 stdin EOF만으로 취소하지 않습니다.
수정experiments/rust-archive-worker/contract.json+30-6
@@ -39,7 +39,7 @@
3939 "Output": "entry_id:optional, relative_name, disposition Created|PartialRetained|Removed|CommitUncertain; only this job outputs.",
4040 "Terminal": {
4141 "outcome": "Completed|Failed|Cancelled",
42삭제: "error": "None|Integrity|UnsupportedFormat|UnsupportedFeature|WrongPassword|UnsafePath|Conflict|Limit|Io|Protocol|Internal|SourceChanged|InvalidRequest",
42추가: "error": "None|Integrity|UnsupportedFormat|UnsupportedFeature|WrongPassword|UnsafePath|Conflict|Limit|Io|Protocol|Internal|SourceChanged|InvalidRequest|DiskFull",
4343 "publication": "None|Partial|Complete|Uncertain",
4444 "created_count": "u64",
4545 "retained_partial_count": "u64",
@@ -86,7 +86,8 @@
8686 "coordination": {
8787 "frontend_message_id": "41a0e5a5-27d0-437f-805d-d39313082096",
8888 "basis": "Revision 2 list identity, explicit raw GZip output naming and cancellation acknowledgement are implemented. Field order and tags remain unchanged.",
89삭제: "streaming_frontend_message_id": "59142fd4-22d3-4dc5-a875-5347e1b054da"
89추가: "streaming_frontend_message_id": "59142fd4-22d3-4dc5-a875-5347e1b054da",
90추가: "disk_full_frontend_message_id": "3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1"
9091 },
9192 "list_identity": {
9293 "ListId": {
@@ -143,7 +144,7 @@
143144 "regression": "Preserve existing format bytes and round-trip SevenZip in ListEnd/ListId."
144145 },
145146 "streaming_limits": {
146삭제: "agreement": "Revision 2 fields, tags and frame encoding unchanged. Ratio-rejection removal and disk-space advisory checks are proposed under manager decision d6bc0d37-89d1-4cd2-a00b-883b5eb23ec0; frontend confirmation pending.",
147추가: "agreement": "Revision 2 fields and frame encoding unchanged. Ratio-rejection removal and advisory disk-space checks follow manager decision d6bc0d37-89d1-4cd2-a00b-883b5eb23ec0. DiskFull tag 13 and preserving Io tag 8 for query/access failures were agreed with frontend in message 3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1.",
147148 "default_input_bytes": 18446744073709551615,
148149 "default_output_bytes": 17179869184,
149150 "default_entries": 10000,
@@ -153,11 +154,34 @@
153154 "tar_ratio": "Plain TAR copies declared nonoverlapping ranges within the captured input. The sum of file sizes cannot exceed output quota.",
154155 "arithmetic": "Checked u64 offsets and totals; free-space block-to-byte conversion uses u128 to avoid multiplication overflow.",
155156 "memory_target": "ZIP/TAR/GZ/TAR.GZ List/Extract: worker process peak RSS <=64 MiB in Linux regression with independently generated 1 GiB payloads. This is a measured target, not an OS-enforced RSS cap. Metadata budget remains 8 MiB.",
156삭제: "staging": "64 KiB buffers; immutable input capture and verified decoded content use private temporary files that are removed on last-handle close. No decoded content is published until the entire catalog and integrity checks succeed. Temporary disk usage can include the archive plus expanded content plus current destination temporary file; disk exhaustion fails with Io and closes/removes unpublished data.",
157추가: "staging": "64 KiB buffers; immutable input capture and verified decoded content use private temporary files that are removed on last-handle close. No decoded content is published until the entire catalog and integrity checks succeed. Temporary disk usage can include the archive plus expanded content plus current destination temporary file; disk exhaustion fails with DiskFull and closes/removes unpublished data.",
157158 "legacy": "7z and ZIP creation retain separate 64 MiB input /128 MiB output caps until their streaming implementation. The slice-based archive parser also retains these legacy memory bounds.",
158159 "parent_lifetime": "Capture native parent before reading Start. At decode/read/write/password checkpoints, fail Io if parent is gone; close anonymous staging and remove current unpublished destination temp. stdin EOF alone remains valid for one-shot requests. Already published entries and directories are reported and retained. A blocked OS file operation cannot be forcibly interrupted by this cooperative guard.",
159삭제: "disk_space": "Advisory free-space checks use opened Linux x86_64 filesystem handles (fstatvfs) or the Windows handle-derived directory (GetDiskFreeSpaceExW). Before ZIP/7z decoding and before publication, group remaining staging and selected output logical bytes by volume. For GZip with unknown expanded size, check staging space before each decoded chunk, then preflight selected output. Input capture also checks its snapshot space. Query failure or insufficient space returns existing Io tag 8. Checks do not reserve space or account for every metadata/block-allocation overhead; later ENOSPC still closes staging and removes current unpublished output.",
160추가: "disk_space": "Advisory free-space checks use opened Linux x86_64 filesystem handles (fstatvfs) or the Windows handle-derived directory (GetDiskFreeSpaceExW). Before ZIP/7z decoding and before publication, group remaining staging and selected output logical bytes by volume. For GZip with unknown expanded size, check staging space before each decoded chunk, then preflight selected output. Input capture also checks its snapshot space. Insufficient space returns DiskFull tag 13. Query failure and other I/O errors retain Io tag 8. Checks do not reserve space or account for every metadata/block-allocation overhead; later ENOSPC still closes staging and removes current unpublished output.",
160161 "remaining_risk": "High compression ratios within 16 GiB may expand fully onto disk. Resource duration, cooperative cancellation and measured memory target remain. Free-space checks can race with other disk users; already published outputs are retained on failure."
161162 },
162삭제: "validation": "Implementation results belong in the PR verification record. No OS sandbox or native Windows execution claim."
163추가: "validation": "Implementation results belong in the PR verification record. No OS sandbox or native Windows execution claim.",
164추가: "error_tags": {
165추가: "None": 0,
166추가: "Integrity": 1,
167추가: "UnsupportedFormat": 2,
168추가: "UnsupportedFeature": 3,
169추가: "WrongPassword": 4,
170추가: "UnsafePath": 5,
171추가: "Conflict": 6,
172추가: "Limit": 7,
173추가: "Io": 8,
174추가: "Protocol": 9,
175추가: "Internal": 10,
176추가: "SourceChanged": 11,
177추가: "InvalidRequest": 12,
178추가: "DiskFull": 13
179추가: },
180추가: "disk_full_extension": {
181추가: "agreement_message_id": "3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1",
182추가: "compatibility": "Existing error tags 0 through 12, fields, message tags, revision 2 and frame version stay unchanged. Older clients reject error 13; app error mapping and worker must be updated together before integration.",
183추가: "mapping": "Insufficient preflight space and StorageFull I/O failures return DiskFull 13. Windows ERROR_HANDLE_DISK_FULL 39 and ERROR_DISK_FULL 112 also map to DiskFull. Query failure, permission errors and other I/O failures return Io 8. No error classification by localized detail text.",
184추가: "detail": "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요",
185추가: "publication": "Keep existing publication, durability and cleanup semantics. DiskFull does not imply rollback or absence of previously published outputs."
186추가: }
163187}
수정experiments/rust-archive-worker/src/filesystem.rs+34-22
@@ -232,7 +232,7 @@ mod platform {
232232 let n = CString::new(n).map_err(|_| ErrorCode::UnsafePath)?;
233233 // 고정 부모 안에 새 전용 디렉터리를 생성함.
234234 if unsafe { mkdirat(self.file.as_raw_fd(), n.as_ptr(), 0o700) } != 0 {
235삭제: return Err(ErrorCode::Io);
235추가: return Err(crate::space::io_error(std::io::Error::last_os_error()));
236236 }
237237 let file = open(
238238 &self.file,
@@ -289,11 +289,11 @@ mod platform {
289289 unsafe { unlinkat(self.file.as_raw_fd(), n.as_ptr(), 0) == 0 }
290290 }
291291 pub fn sync(&self) -> Durability {
292삭제: if self.file.sync_all().is_ok() {
293삭제: Durability::Synced
294삭제: } else {
295삭제: Durability::Failed
296삭제: }
292추가: self.sync_checked().unwrap_or(Durability::Failed)
293추가: }
294추가: pub(crate) fn sync_checked(&self) -> Result<Durability> {
295추가: self.file.sync_all().map_err(crate::space::io_error)?;
296추가: Ok(Durability::Synced)
297297 }
298298 }
299299}
@@ -361,7 +361,7 @@ mod platform {
361361 if !create {
362362 return Ok(None);
363363 }
364삭제: std::fs::create_dir(&p).map_err(|_| ErrorCode::Io)?;
364추가: std::fs::create_dir(&p).map_err(crate::space::io_error)?;
365365 }
366366 Err(_) => return Err(ErrorCode::Io),
367367 }
@@ -394,6 +394,9 @@ mod platform {
394394 pub fn sync(&self) -> Durability {
395395 Durability::Unconfirmed
396396 }
397추가: pub(crate) fn sync_checked(&self) -> Result<Durability> {
398추가: Ok(Durability::Unconfirmed)
399추가: }
397400 }
398401}
399402#[cfg(not(any(target_os = "linux", windows)))]
@@ -463,13 +466,16 @@ pub(crate) fn preflight_space(
463466 }
464467 Ok(())
465468}
466삭제: pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability)> {
469추가: pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability, Option<ErrorCode>)> {
467470 let (d, leaf) = parent(root, name, false)?.ok_or(ErrorCode::Io)?;
468471 if d.child(&leaf, false)?.is_some() {
469삭제: return Ok((false, Durability::NotApplicable));
472추가: return Ok((false, Durability::NotApplicable, None));
470473 }
471474 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
472삭제: Ok((true, d.sync()))
475추가: Ok(match d.sync_checked() {
476추가: Ok(durability) => (true, durability, None),
477추가: Err(error) => (true, Durability::Failed, Some(error)),
478추가: })
473479}
474480pub struct Published {
475481 pub created: bool,
@@ -523,7 +529,7 @@ pub fn publish_reader(
523529 if e.kind() == std::io::ErrorKind::AlreadyExists {
524530 ErrorCode::Conflict
525531 } else {
526삭제: ErrorCode::Io
532추가: crate::space::io_error(e)
527533 }
528534 })?;
529535 let written = (|| {
@@ -537,29 +543,33 @@ pub fn publish_reader(
537543 if n == 0 {
538544 return Err(ErrorCode::Io);
539545 }
540삭제: file.write_all(&buffer[..n]).map_err(|_| ErrorCode::Io)?;
546추가: file.write_all(&buffer[..n])
547추가: .map_err(crate::space::io_error)?;
541548 remaining -= n as u64;
542549 }
543삭제: file.sync_all().map_err(|_| ErrorCode::Io)
550추가: file.sync_all().map_err(crate::space::io_error)
544551 })();
545삭제: let closed = close(file).map_err(|_| ErrorCode::Io);
552추가: let closed = close(file).map_err(crate::space::io_error);
546553 let mut finish = written.and(closed).and_then(|_| check(true));
547554 if finish.is_ok() {
548555 match dir.link(&temp, &leaf) {
549556 Ok(()) => {
550557 result.created = true;
551삭제: result.durability = dir.sync();
552삭제: if result.durability == Durability::Failed {
553삭제: finish = Err(ErrorCode::Io);
558추가: match dir.sync_checked() {
559추가: Ok(durability) => result.durability = durability,
560추가: Err(error) => {
561추가: result.durability = Durability::Failed;
562추가: finish = Err(error);
563추가: }
554564 }
555565 }
556566 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
557567 finish = Err(ErrorCode::Conflict)
558568 }
559삭제: Err(_) => {
569추가: Err(error) => {
560570 result.uncertain = true;
561571 result.durability = Durability::Unconfirmed;
562삭제: finish = Err(ErrorCode::Io);
572추가: finish = Err(crate::space::io_error(error));
563573 }
564574 }
565575 }
@@ -574,9 +584,11 @@ pub fn publish_reader(
574584 finish = Err(ErrorCode::Io);
575585 }
576586 }
577삭제: if result.created && dir.sync() == Durability::Failed {
578삭제: result.durability = Durability::Failed;
579삭제: finish = Err(ErrorCode::Io);
587추가: if result.created {
588추가: if let Err(error) = dir.sync_checked() {
589추가: result.durability = Durability::Failed;
590추가: finish = Err(error);
591추가: }
580592 }
581593 finish
582594 })();
수정experiments/rust-archive-worker/src/protocol.rs+1-0
@@ -221,6 +221,7 @@ pub enum ErrorCode {
221221 Internal,
222222 SourceChanged,
223223 InvalidRequest,
224추가: DiskFull,
224225}
225226#[derive(Clone, Copy, Debug, PartialEq, Eq)]
226227pub enum Publication {
수정experiments/rust-archive-worker/src/runtime.rs+7-3
@@ -379,7 +379,8 @@ impl<W: Write> Job<W> {
379379 filesystem::preflight_space(&root, &output_sizes, None)?;
380380 for name in dirs {
381381 self.check()?;
382삭제: let (created, durability) = filesystem::directory(&root, &name)?;
382추가: let (created, durability, sync_error) =
383추가: filesystem::directory(&root, &name)?;
383384 if created {
384385 self.terminal.created_count += 1;
385386 self.terminal.publication = Publication::Partial;
@@ -389,8 +390,8 @@ impl<W: Write> Job<W> {
389390 relative_name: name,
390391 disposition: Disposition::Created,
391392 })?;
392삭제: if durability == Durability::Failed {
393삭제: return Err(ErrorCode::Io);
393추가: if let Some(error) = sync_error {
394추가: return Err(error);
394395 }
395396 }
396397 }
@@ -612,6 +613,9 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
612613 ErrorCode::None => "취소됨",
613614 ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원",
614615 ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함",
616추가: ErrorCode::DiskFull => {
617추가: "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
618추가: }
615619 ErrorCode::Io => {
616620 "파일을 읽거나 쓰지 못했습니다. 디스크 여유 공간과 접근 권한을 확인하세요"
617621 }
수정experiments/rust-archive-worker/src/space.rs+18-1
@@ -14,7 +14,7 @@ pub(crate) fn ensure(file: &File, bytes: u64) -> Result<()> {
1414 if bytes == 0 || bytes as u128 <= available(file)? {
1515 Ok(())
1616 } else {
17삭제: Err(ErrorCode::Io)
17추가: Err(ErrorCode::DiskFull)
1818 }
1919}
2020
@@ -121,3 +121,20 @@ fn available(file: &File) -> Result<u128> {
121121 }
122122 Ok(free as u128)
123123}
124추가:
125추가: // 공간 부족만 전용 오류로 변환함.
126추가: pub(crate) fn io_error(error: std::io::Error) -> ErrorCode {
127추가: #[cfg(windows)]
128추가: if matches!(error.raw_os_error(), Some(39 | 112)) {
129추가: return ErrorCode::DiskFull;
130추가: }
131추가: if error.kind() == std::io::ErrorKind::StorageFull {
132추가: ErrorCode::DiskFull
133추가: } else {
134추가: ErrorCode::Io
135추가: }
136추가: }
137추가:
138추가: #[cfg(test)]
139추가: #[path = "../../../tests/rust-archive-worker/space_errors.rs"]
140추가: mod tests;
수정experiments/rust-archive-worker/src/spool.rs+10-5
@@ -13,14 +13,18 @@ pub(crate) fn temporary() -> Result<File> {
1313 {
1414 use std::os::unix::fs::OpenOptionsExt;
1515 // 이름 없는 임시 파일은 마지막 핸들을 닫으면 제거됨.
16삭제: if let Ok(file) = OpenOptions::new()
16추가: match OpenOptions::new()
1717 .read(true)
1818 .write(true)
1919 .custom_flags(0x410000 | 0x80)
2020 .mode(0o600)
2121 .open(std::env::temp_dir())
2222 {
23삭제: return Ok(file);
23추가: Ok(file) => return Ok(file),
24추가: Err(ref error) if error.kind() == std::io::ErrorKind::StorageFull => {
25추가: return Err(ErrorCode::DiskFull);
26추가: }
27추가: Err(_) => {}
2428 }
2529 let mut random = [0; 16];
2630 crate::crypto::random(&mut random)?;
@@ -36,7 +40,7 @@ pub(crate) fn temporary() -> Result<File> {
3640 .mode(0o600)
3741 .custom_flags(0x20000)
3842 .open(&path)
39삭제: .map_err(|_| ErrorCode::Io)?;
43추가: .map_err(crate::space::io_error)?;
4044 std::fs::remove_file(path).map_err(|_| ErrorCode::Io)?;
4145 use std::os::unix::fs::MetadataExt;
4246 if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 {
@@ -62,7 +66,7 @@ pub(crate) fn temporary() -> Result<File> {
6266 .custom_flags(0x04000000 | 0x00200000)
6367 .attributes(0x100)
6468 .open(std::env::temp_dir().join(format!("zipelo-{name}.tmp")))
65삭제: .map_err(|_| ErrorCode::Io)
69추가: .map_err(crate::space::io_error)
6670 }
6771}
6872
@@ -121,7 +125,8 @@ impl Snapshot {
121125 .checked_add(n as u64)
122126 .filter(|n| *n <= limit)
123127 .ok_or(ErrorCode::Limit)?;
124삭제: file.write_all(&buffer[..n]).map_err(|_| ErrorCode::Io)?;
128추가: file.write_all(&buffer[..n])
129추가: .map_err(crate::space::io_error)?;
125130 hash.update(&buffer[..n]);
126131 }
127132 let after = source.metadata().map_err(|_| ErrorCode::Io)?;
수정experiments/rust-archive-worker/src/streaming.rs+1-1
@@ -36,7 +36,7 @@ fn add(a: u64, b: u64) -> Result<u64> {
3636 a.checked_add(b).ok_or(ErrorCode::Integrity)
3737}
3838fn io<T>(v: std::io::Result<T>) -> Result<T> {
39삭제: v.map_err(|_| ErrorCode::Io)
39추가: v.map_err(crate::space::io_error)
4040}
4141
4242pub(crate) struct Catalog {
수정experiments/rust-archive-worker/src/wire.rs+1-1
@@ -133,7 +133,7 @@ enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3});
133133enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5});
134134enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3});
135135enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2});
136삭제: enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12});
136추가: enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12,DiskFull=13});
137137enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3});
138138enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3});
139139enumeration!(Cleanup{Complete=0,Failed=1,Unconfirmed=2});
수정tests/rust-archive-worker/hardening.rs+79-3
@@ -433,7 +433,13 @@ mod linux {
433433 }
434434 #[test]
435435 fn enospc_at_create_or_after_partial_write_cleans_output() {
436삭제: for mode in ["create-full", "full", "stage-full"] {
436추가: for mode in [
437추가: "create-full",
438추가: "full",
439추가: "stage-full",
440추가: "temp-full",
441추가: "sync-full",
442추가: ] {
437443 let s = Scratch::new();
438444 generate(&s, "store", 1024 * 1024);
439445 fs::write(s.0.join("preserve"), b"original").unwrap();
@@ -442,7 +448,11 @@ mod linux {
442448 assert_eq!(wait(child.id()).0, 0);
443449 let events = events(&s);
444450 let t = terminal(&events);
445삭제: assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}");
451추가: assert_eq!(t.error, ErrorCode::DiskFull, "{mode}: {events:?}");
452추가: assert_eq!(
453추가: t.detail,
454추가: "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
455추가: );
446456 assert_eq!(t.publication, Publication::None);
447457 assert_eq!(t.retained_partial_count, 0);
448458 assert_eq!(t.cleanup, Cleanup::Complete);
@@ -465,7 +475,12 @@ mod linux {
465475 assert_eq!(wait(child.id()).0, 0);
466476 let events = events(&s);
467477 let t = terminal(&events);
468삭제: assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}");
478추가: let expected = if mode == "space-error" {
479추가: ErrorCode::Io
480추가: } else {
481추가: ErrorCode::DiskFull
482추가: };
483추가: assert_eq!(t.error, expected, "{mode}: {events:?}");
469484 assert_eq!(t.publication, Publication::None);
470485 assert_eq!(t.cleanup, Cleanup::Complete);
471486 assert_eq!(t.created_count, 0);
@@ -476,6 +491,67 @@ mod linux {
476491 }
477492 }
478493 #[test]
494추가: fn disk_full_during_directory_sync_retains_reported_outputs() {
495추가: for nested in [false, true] {
496추가: let s = Scratch::new();
497추가: fs::write(s.0.join("source"), vec![0; 1024]).unwrap();
498추가: let name = if nested {
499추가: "folder/payload.bin"
500추가: } else {
501추가: "payload.bin"
502추가: };
503추가: let created = execute(Start {
504추가: action: Action::CreateZip {
505추가: sources: vec![Source {
506추가: path: s.path("source"),
507추가: archive_name: name.into(),
508추가: }],
509추가: output_file: s.path("input"),
510추가: method: Method::Store,
511추가: encryption: Encryption::None,
512추가: },
513추가: limits: Limits::default(),
514추가: });
515추가: assert_eq!(terminal(&created).outcome, Outcome::Completed);
516추가: let request = start(&s, false, Limits::default().output);
517추가: let child = spawn(&s, request, Some("dir-sync-full"));
518추가: assert_eq!(wait(child.id()).0, 0);
519추가: let events = events(&s);
520추가: let t = terminal(&events);
521추가: assert_eq!(t.error, ErrorCode::DiskFull, "{events:?}");
522추가: assert_eq!(t.publication, Publication::Partial);
523추가: assert_eq!(t.created_count, 1);
524추가: assert_eq!(t.durability, Durability::Failed);
525추가: assert_eq!(t.cleanup, Cleanup::Complete);
526추가: assert_eq!(t.retained_partial_count, 0);
527추가: assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
528추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
529추가: if nested {
530추가: assert_eq!(fs::read_dir(s.0.join("output/folder")).unwrap().count(), 0);
531추가: } else {
532추가: assert_zero_file(&s.0.join("output/payload.bin"), 1024);
533추가: }
534추가: }
535추가: }
536추가: #[test]
537추가: fn permission_and_generic_write_errors_remain_io() {
538추가: for mode in ["create-denied", "write-io"] {
539추가: let s = Scratch::new();
540추가: generate(&s, "store", 1024 * 1024);
541추가: let request = start(&s, false, Limits::default().output);
542추가: let child = spawn(&s, request, Some(mode));
543추가: assert_eq!(wait(child.id()).0, 0);
544추가: let events = events(&s);
545추가: let t = terminal(&events);
546추가: assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}");
547추가: assert_eq!(t.publication, Publication::None);
548추가: assert_eq!(t.retained_partial_count, 0);
549추가: assert_eq!(t.cleanup, Cleanup::Complete);
550추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
551추가: assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
552추가: }
553추가: }
554추가: #[test]
479555 fn anonymous_tempfile_fallback_unlinks_before_use() {
480556 let s = Scratch::new();
481557 generate(&s, "store", 1024 * 1024);
수정tests/rust-archive-worker/io_fault.c+23-2
@@ -13,6 +13,7 @@
1313static ssize_t (*real_write)(int, const void *, size_t);
1414static int (*real_openat)(int, const char *, int, ...);
1515static int (*real_open64)(const char *, int, ...);
16추가: static int (*real_fsync)(int);
1617static int (*real_fstatvfs)(int, struct statvfs *);
1718static int started;
1819
@@ -20,6 +21,7 @@ __attribute__((constructor)) static void initialize(void) {
2021 real_write = dlsym(RTLD_NEXT, "write");
2122 real_openat = dlsym(RTLD_NEXT, "openat");
2223 real_open64 = dlsym(RTLD_NEXT, "open64");
24추가: real_fsync = dlsym(RTLD_NEXT, "fsync");
2325 real_fstatvfs = dlsym(RTLD_NEXT, "fstatvfs");
2426}
2527
@@ -43,8 +45,9 @@ int openat(int fd, const char *path, int flags, ...) {
4345 va_end(args);
4446 }
4547 const char *fault = getenv("ZIPELO_TEST_FAULT");
46삭제: if (fault && !strcmp(fault, "create-full") && !strncmp(path, ".zipelo-", 8)) {
47삭제: errno = ENOSPC;
48추가: if (fault && (!strcmp(fault, "create-full") || !strcmp(fault, "create-denied"))
49추가: && !strncmp(path, ".zipelo-", 8)) {
50추가: errno = !strcmp(fault, "create-full") ? ENOSPC : EACCES;
4851 return -1;
4952 }
5053 return real_openat(fd, path, flags, mode);
@@ -59,6 +62,11 @@ int open64(const char *path, int flags, ...) {
5962 va_end(args);
6063 }
6164 const char *fault = getenv("ZIPELO_TEST_FAULT");
65추가: if (fault && !strcmp(fault, "temp-full")
66추가: && (((flags & O_TMPFILE) == O_TMPFILE) || strstr(path, "/zipelo-"))) {
67추가: errno = ENOSPC;
68추가: return -1;
69추가: }
6270 if (fault && !strcmp(fault, "fallback") && ((flags & O_TMPFILE) == O_TMPFILE)) {
6371 int marker = real_openat(AT_FDCWD, getenv("ZIPELO_TEST_MARKER"), O_CREAT | O_WRONLY, 0600);
6472 if (marker >= 0) close(marker);
@@ -71,6 +79,7 @@ int open64(const char *path, int flags, ...) {
7179ssize_t write(int fd, const void *bytes, size_t count) {
7280 const char *fault = getenv("ZIPELO_TEST_FAULT");
7381 if (!fault || !output_file(fd)) return real_write(fd, bytes, count);
82추가: if (!strcmp(fault, "write-io")) { errno = EIO; return -1; }
7483 if (!strcmp(fault, "full") || !strcmp(fault, "stage-full")) {
7584 if (!started++) return real_write(fd, bytes, count < 7 ? count : 7);
7685 errno = ENOSPC;
@@ -104,3 +113,15 @@ int fstatvfs(int fd, struct statvfs *value) {
104113 value->f_bavail = !strcmp(fault, "space-combined") ? (1536 * 1024) / value->f_frsize : 0;
105114 return 0;
106115}
116추가:
117추가: int fsync(int fd) {
118추가: const char *fault = getenv("ZIPELO_TEST_FAULT");
119추가: struct stat st;
120추가: int directory_full = fault && !strcmp(fault, "dir-sync-full")
121추가: && !fstat(fd, &st) && S_ISDIR(st.st_mode);
122추가: if (directory_full || (fault && !strcmp(fault, "sync-full") && output_file(fd))) {
123추가: errno = ENOSPC;
124추가: return -1;
125추가: }
126추가: return real_fsync(fd);
127추가: }
수정tests/rust-archive-worker/main.rs+41-0
@@ -1552,3 +1552,44 @@ fn seven_zip_reference_reader_accepts_synthetic_fixtures() {
15521552}
15531553
15541554mod hardening;
1555추가:
1556추가: #[test]
1557추가: fn disk_full_error_tag_preserves_previous_tags_and_rejects_unknown() {
1558추가: for (tag, error) in [
1559추가: ErrorCode::None,
1560추가: ErrorCode::Integrity,
1561추가: ErrorCode::UnsupportedFormat,
1562추가: ErrorCode::UnsupportedFeature,
1563추가: ErrorCode::WrongPassword,
1564추가: ErrorCode::UnsafePath,
1565추가: ErrorCode::Conflict,
1566추가: ErrorCode::Limit,
1567추가: ErrorCode::Io,
1568추가: ErrorCode::Protocol,
1569추가: ErrorCode::Internal,
1570추가: ErrorCode::SourceChanged,
1571추가: ErrorCode::InvalidRequest,
1572추가: ErrorCode::DiskFull,
1573추가: ]
1574추가: .into_iter()
1575추가: .enumerate()
1576추가: {
1577추가: let message = Message::Terminal(Terminal {
1578추가: outcome: Outcome::Failed,
1579추가: error,
1580추가: publication: Publication::None,
1581추가: created_count: 0,
1582추가: retained_partial_count: 0,
1583추가: durability: Durability::NotApplicable,
1584추가: cleanup: Cleanup::Complete,
1585추가: detail: String::new(),
1586추가: });
1587추가: let mut bytes = Vec::new();
1588추가: Writer::new(&mut bytes, 17).send(&message).unwrap();
1589추가: assert_eq!(bytes[33], tag as u8);
1590추가: let decoded = Reader::new(bytes.as_slice()).read().unwrap().unwrap().2;
1591추가: assert_eq!(terminal(&[decoded]).error, error);
1592추가: bytes[33] = 14;
1593추가: assert!(Reader::new(bytes.as_slice()).read().is_err());
1594추가: }
1595추가: }
추가tests/rust-archive-worker/space_errors.rs+35-0
@@ -0,0 +1,35 @@
1추가: use super::*;
2추가: use std::io::{Error, ErrorKind};
3추가:
4추가: #[test]
5추가: fn storage_full_is_distinct_from_other_io_errors() {
6추가: assert_eq!(io_error(ErrorKind::StorageFull.into()), ErrorCode::DiskFull);
7추가: for kind in [
8추가: ErrorKind::PermissionDenied,
9추가: ErrorKind::Other,
10추가: ErrorKind::NotFound,
11추가: ] {
12추가: assert_eq!(io_error(kind.into()), ErrorCode::Io);
13추가: }
14추가: }
15추가:
16추가: #[cfg(target_os = "linux")]
17추가: #[test]
18추가: fn native_linux_enospc_is_disk_full() {
19추가: assert_eq!(io_error(Error::from_raw_os_error(28)), ErrorCode::DiskFull);
20추가: for code in [5, 13, 39, 112] {
21추가: assert_eq!(io_error(Error::from_raw_os_error(code)), ErrorCode::Io);
22추가: }
23추가: }
24추가:
25추가: #[cfg(windows)]
26추가: #[test]
27추가: fn native_windows_disk_full_codes_are_distinct_from_access_denied() {
28추가: for code in [39, 112] {
29추가: assert_eq!(
30추가: io_error(Error::from_raw_os_error(code)),
31추가: ErrorCode::DiskFull
32추가: );
33추가: }
34추가: assert_eq!(io_error(Error::from_raw_os_error(5)), ErrorCode::Io);
35추가: }