team-ljyzipelo

공개

Merge pull request #121 from Team-LJY/features/large-archive-limits

대용량 작업 승인과 작업자 자원 감시를 추가한다
작성자
LeeJunyoung
작성 시각
커밋
690274c7ac54c0ce57938f69da1dab2862d6b40b
이 시점의 파일 보기

변경된 파일 45개

+1,113-300

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

수정docs/ui-scenario-guide.md+28-1
@@ -109,10 +109,37 @@ python3 tests/ci/run_rust.py local
109109- extract-renamed: 실제 저장된 새 이름을 표시합니다. 이름 변경 결과만으로 저장 성공을 판정하지 않고 별도의 생성 보고와 완료 집계가 일치해야 합니다.
110110- extract-rename-failed: 새 이름을 정한 뒤 실제 생성 보고 없이 I/O 오류가 난 결과입니다. 실패 원인과 "아무 파일도 풀지 않았습니다"를 표시하고 "이름 바꿔 저장" 완료 안내는 표시하지 않아야 합니다. 일부 파일이 저장된 뒤 실패한 경우에도 생성 보고가 있는 이름만 저장 완료로 표시합니다.
111111
112삭제: 실제 추출은 revision 3의 StartInteractive를 보내며 ZIP, 7z, TAR 계열과 단일 GZ의 파일 충돌에 같은 선택 창을 사용합니다. 목록 읽기와 ZIP 만들기는 기존 Start를 유지합니다. 위 명령은 실제 파일을 쓰지 않는 개발용 화면 미리보기입니다. 파일 기반 버튼 연동은 tests/rust-app-real-worker/conflict_flows.rs에서 확인하며, 운영체제별 실제 창 확인은 별도입니다.
112추가: 실제 추출은 revision 3의 StartGuarded에 interactive=true를 보내며 ZIP, 7z, TAR 계열과 단일 GZ의 파일 충돌에 같은 선택 창을 사용합니다. 목록 읽기와 ZIP 만들기도 StartGuarded로 자원을 감시하며 충돌 질문은 추출에만 사용합니다. 위 명령은 실제 파일을 쓰지 않는 개발용 화면 미리보기입니다. 파일 기반 버튼 연동은 tests/rust-app-real-worker/conflict_flows.rs에서 확인하며, 운영체제별 실제 창 확인은 별도입니다.
113113
114114TAR.BZ2와 TAR.XZ의 자동 해제 폴더 이름은 미리보기에 표시되지 않는다. tests/rust-app-ui/presentation.rs의 이름 시험과 tests/rust-app-real-worker/compressed_tar_flows.rs의 실제 작업자 시험에서 복합 확장자 제거와 해제 결과를 확인한다.
115115
116추가: ## 큰 작업의 승인과 재시도
117추가:
118추가: - resource-approval: 목록에서 큰 작업임을 확인한 뒤 처리 전 승인을 묻는 화면
119추가: - resource-ratio: 압축률 경고와 미확인 예상값을 표시하는 화면
120추가: - resource-retry: 출력 없이 한도에 걸린 뒤 주 창 안의 모달에서 "한도를 늘려 다시 시도"를 고르는 화면
121추가: - resource-partial: 일부 파일을 저장한 뒤 한도에 걸려 주 창 안의 모달에서 저장 위치를 안내하는 화면
122추가:
123추가: 일반 작업은 16 GiB와 10,000개 한도를 유지하며 압축률을 감시합니다.
124추가: 목록이나 선택한 일반 파일의 크기로 한도 초과를 알면 처리 전에 작업자가 확대 승인을 묻습니다.
125추가: 미리 알 수 없는 폴더 내부와 압축파일은 기본 한도로 시작합니다.
126추가: 출력이 없고 임시 파일 정리와 작업자 종료가 확인된 한도 오류에서만 확대 재시도를 제공합니다.
127추가: 확대 재시도를 선택해도 작업자의 승인 질문에서 "이 작업 허용"을 눌러야 진행합니다.
128추가: 이미 저장되거나 일부 남은 파일, 저장 상태나 정리가 불확실한 작업은 확대 재시도를 제공하지 않습니다.
129추가:
130추가: 승인은 해당 작업과 질문 범위에만 적용합니다. 예상값, 실제값과 저장 볼륨의 여유 공간은 구분하며
131추가: 확인하지 못한 값은 "미확인"으로 표시합니다. 여유 공간은 예약이나 모든 볼륨의 합계가 아닙니다.
132추가: 승인 후에도 상한과 공간 검사를 유지합니다. 취소 버튼과 Escape는 승인 대기 중 작업을 취소합니다.
133추가: Enter만으로 허용하지 않습니다. 기존 작업자로 자동 재시도하지 않습니다.
134추가: 미리보기는 입력과 파일 쓰기를 막으며 실제 64 GiB 작업을 수행하지 않습니다.
135추가:
136추가: 승인된 작업의 목록 한도는 200,000개입니다. 출력 기록에는 압축파일에 따로 적혀 있지 않은
137추가: 상위 폴더도 포함되므로 작업자 메타데이터 정책과 같은 262,144개 노드까지 보관합니다.
138추가: 기본 작업의 출력 기록 한도는 100,000개를 유지합니다. 이 기록 정책 수정은 화면 요소를 바꾸지 않습니다.
139추가:
140추가: 한도 초과 결과는 별도 운영체제 창 대신 주 창 안의 모달로 표시합니다. Wayland에서도 파일 경로로 실행한 직후 Alt+Tab 없이 결과와 재시도 버튼이 보여야 합니다. "확인"으로 닫으며, 일부 출력이 남은 경우 확대 재시도는 제공하지 않습니다.
141추가:
142추가: 큰 작업을 허용한 뒤 파일 충돌이 발견되면 승인 창을 닫고 충돌 선택 창을 표시합니다. 승인과 충돌 질문은 동시에 표시하지 않으며, 같은 작업의 질문 번호를 이어서 검증합니다.
116143## 설치 프로그램의 제거 안내
117144
118145Windows NSIS 제거 프로그램은 앱과 별도의 실행 파일입니다. 이번 제거 안내는 Uninstall.exe 실행 후 확인 화면 앞에 표시되며 [기본 앱 설정 열기]로 Windows 설정을 엽니다. --ui-scenario uninstall-windows와 uninstall-settings-error로 안내 문구를 확인합니다. Ubuntu 터미널 안내는 uninstall-ubuntu-missing과 uninstall-ubuntu-unknown-user로 확인합니다. 이 네 상황은 외부 설치 프로그램과 터미널의 문구를 egui에 재현한 읽기 전용 미리보기이며, NSIS의 실제 배치나 운영체제 창 모양을 재현하지 않습니다. 버튼은 설정을 열거나 제거를 실행하지 않습니다. 다른 운영체제에서도 같은 안내를 확인할 수 있습니다.
수정experiments/rust-archive-worker/README.md+28-7
@@ -4,8 +4,9 @@
44
55- ZIP32/ZIP64 Store/Deflate 목록과 해제, ZIP32/ZIP64 생성, 기본 TAR/USTAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. 다중 볼륨, UTF-8로 해석할 수 없는 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다.
66- ZIP 이름: UTF-8 플래그(비트 11)가 있으면 이름이 UTF-8이어야 하며 아니면 Integrity입니다. 플래그가 없으면 CRC가 원래 이름과 맞는 Info-ZIP Unicode Path 확장 필드(0x7075, 버전 1)를 우선 쓰고, 다음으로 UTF-8로 유효한 이름 바이트를 그대로 씁니다(Linux/macOS 도구의 기본 동작). CRC가 다르거나 버전이 다른 확장 필드는 무시합니다. 그 밖의 CP437/CP949 등 레거시 이름은 코드 페이지를 추측하지 않고 UnsupportedFeature로 거부합니다. 어느 경로로 얻은 이름이든 같은 경로 안전성 검사와 충돌 검사를 거칩니다.
7삭제: - ZIP/TAR/GZ/TAR.GZ/7z 목록과 해제는 입력 기본 한도 u64::MAX, 해제 총량 16 GiB, 항목 10,000개입니다. 요청 limits는 이 값을 낮출 수 있습니다. 64 KiB 버퍼와 임시 파일로 입력과 검증 완료 payload를 처리해 모든 출력의 CRC, 크기와 경로를 게시 전에 검사합니다. checkpoint마다 취소, 부모 프로세스 생존과 300초 한도를 확인합니다. ZIP 생성은 원본을 하나씩 스냅샷으로 읽어 스트리밍으로 압축하며 원본 크기 합계에 16 GiB 한도를 적용합니다. ZIP64 크기와 오프셋은 필요한 항목에만 기록합니다. slice 기반 archive parser는 입력 64 MiB/출력 128 MiB, slice ZIP builder는 원본 및 결과 128 MiB 한도를 유지합니다.
8삭제: - 경로 깊이는 64개 구성 요소, 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다.
7추가: - ZIP/TAR/GZ/TAR.GZ/7z 목록과 해제는 입력 기본 한도 u64::MAX, 해제 총량 16 GiB, 항목 10,000개입니다. 기존 Start와 StartInteractive의 limits는 이 값을 낮출 수 있습니다. 별도 StartGuarded의 승인 흐름은 아래 절을 따릅니다. 64 KiB 버퍼와 임시 파일로 입력과 검증 완료 payload를 처리해 모든 출력의 CRC, 크기와 경로를 게시 전에 검사합니다. checkpoint마다 취소, 부모 프로세스 생존과 300초 한도를 확인합니다. ZIP 생성은 원본을 하나씩 스냅샷으로 읽어 스트리밍으로 압축하며 원본 크기 합계에 16 GiB 한도를 적용합니다. ZIP64 크기와 오프셋은 필요한 항목에만 기록합니다. slice 기반 archive parser는 입력 64 MiB/출력 128 MiB, slice ZIP builder는 원본 및 결과 128 MiB 한도를 유지합니다.
8추가: - 경로 깊이는 64개 구성 요소이며 승인 전 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 유효한 StartGuarded 자원 승인 후에만 각각 64 MiB와 262,144개로 확대합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다.
9추가: - 선택 ID 전송은 Start와 StartInteractive 및 항목 상한을 늘리지 않은 StartGuarded에서 기존 32,768개를 유지합니다. 항목 상한을 늘린 StartGuarded는 32,768개와 요청 ceiling.entries 중 큰 값까지 전송하며 최대 200,000개입니다. 전송만으로 승인이 성립하지 않으며 실제 처리는 일치하는 ResourceReply 허용 뒤에 시작합니다. 경로/문자열, 생성 원본 벡터와 프레임 한도는 확대하지 않습니다.
910- GZip 내부 형식은 완전한 USTAR magic이 있을 때만 TAR로 판별합니다. magic이 없는 영값 데이터는 길이와 무관하게 raw GZip으로 유지하며 명시 출력명이 필요합니다.
1011- ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다.
1112- 출력 폴더는 미리 존재해야 합니다. Linux는 소유 UID가 같고 group/other 쓰기가 없는 폴더만 허용합니다. openat/O_NOFOLLOW로 디렉터리를 고정하고 새 임시 파일을 배타적으로 만든 뒤 hard link로 게시합니다. 기존 파일과 링크를 덮어쓰지 않습니다. Windows는 reparse point를 거부하고 부모 디렉터리 핸들에서 delete sharing을 제한합니다.
@@ -16,7 +17,7 @@
1617
1718revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도를 유지하고, 히나타 님과 합의한 공간 부족 오류 DiskFull(tag 13)을 추가합니다. 구버전 앱은 새 tag를 거부하므로 앱 오류 변환과 화면 매핑을 작업자와 함께 갱신해야 합니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 세부 계약은 contract.json의 streaming_limits에 있습니다.
1819
19삭제: - 압축비는 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다.
20추가: - 기존 Start와 StartInteractive는 압축비를 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다.
2021- 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. 기존 Start는 ZIP/7z 해제 전에 전체 임시 해제량과 선택한 출력량을 볼륨별로 합산해 검사하고, 게시 전에도 출력 공간을 재검사합니다. StartInteractive는 선택 전에는 무결성 검증에 필요한 임시 해제 공간만 확인하고, 선택 뒤 건너뛰지 않은 파일의 실제 저장 이름으로 게시 직전 공간을 확인합니다. 따라서 목적지 공간이 부족해도 충돌 파일을 전부 건너뛰거나 질문 중 취소할 수 있습니다. 미리 해제 크기를 알 수 없는 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-)을 따릅니다.
2122- 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 오류 문구는 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"이며, detail 문자열을 오류 판정에 사용하지 않습니다.
2223- 입력과 검증된 해제 내용은 임시 파일에 저장합니다. 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 외의 시스템 메모리를 사용합니다.
@@ -29,7 +30,7 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도
2930비암호화 7z의 단일 입력/출력 coder인 Copy, LZMA와 LZMA2를 Rust 코드로 해독합니다. solid substream, 빈 파일/디렉터리, UTF-16LE 이름과 한 단계 압축 헤더를 처리합니다. 추가 라이브러리나 제품 외부 명령을 사용하지 않습니다. 형식 근거는 [7z 명세](https://www.7-zip.org/7z.html)와 [LZMA SDK 명세 안내](https://www.7-zip.org/sdk.html)입니다.
3031
3132- 시작 헤더/다음 헤더 CRC, packed/folder/substream CRC가 있을 때 해당 CRC와 크기, 스트림의 끝을 검증합니다. 경로, 충돌과 모든 선택 내용 검증이 끝난 뒤 기존 안전 게시 경로로 넘깁니다. 목록은 데이터 CRC 검증 성공을 뜻하지 않습니다.
32삭제: - 기본 입력 한도 u64::MAX, 해제 총량 16 GiB와 기존 항목/이름 한도를 적용합니다. 압축 해제된 헤더도 최대 8 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 최근 8 MiB 사전만 메모리에 두고 더 먼 참조는 임시 파일에서 읽습니다. 먼 거리 참조가 많은 파일은 추가 디스크 I/O가 발생합니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다.
33추가: - 기본 입력 한도 u64::MAX, 해제 총량 16 GiB와 기존 항목/이름 한도를 적용합니다. 압축 해제된 헤더는 승인 전 최대 8 MiB, 승인 후 최대 64 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 최근 8 MiB 사전만 메모리에 두고 더 먼 참조는 임시 파일에서 읽습니다. 먼 거리 참조가 많은 파일은 추가 디스크 I/O가 발생합니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다.
3334- 암호화 7z, 다중 coder 필터 체인(BCJ/BCJ2/Delta 등), PPMd/BZip2, 분할/SFX, external metadata, additional streams와 anti 항목은 미지원입니다. 링크, reparse point와 특수 Unix 항목은 거부합니다. 지원하지 않는 구조를 성공으로 처리하지 않습니다.
3435- solid 그룹의 압축 크기는 첫 substream에만 기록하고 나머지는 0으로 표시합니다. 각 파일의 정확한 비압축 크기는 유지합니다.
3536- 합성 표본은 Python 표준 lzma로 생성합니다. 별도로 시스템 libarchive가 만든 LZMA1/LZMA2 표본을 해제하고, 합성 표본도 libarchive 읽기 API로 검사합니다. libarchive는 Linux 시험의 독립 참조 도구이며 제품 의존성이 아닙니다. 시험 도구와 표본은 tests/rust-archive-worker 아래에 있습니다.
@@ -39,7 +40,7 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도
3940
4041TAR.BZ2와 TAR.XZ는 확장자가 아닌 BZh 및 XZ 매직으로 판별하고 비공개 임시 파일로 먼저 해제합니다. 연결된 BZip2/XZ 스트림은 하나의 TAR로 합치며 XZ의 4바이트 정렬 스트림 패딩도 허용합니다. 빈 TAR, USTAR 이름과 빈 폴더를 지원하지만 독립 BZ2/XZ 데이터 파일은 TAR가 아니면 거부합니다.
4142
42삭제: 해제 총량은 TAR 헤더와 패딩을 포함해 기존 16 GiB 이하이며 요청으로 낮출 수 있습니다. 64 KiB씩 실제 해제량을 확인하고 기록 전에 임시 저장소의 공간을 검사합니다. XZ는 블록별 LZMA2 디코더 메모리 32 MiB, 인덱스 8 MiB, 스트림 수와 스트림당 블록 수 각각 32,768을 상한으로 둡니다. 이 상한을 넘는 정상 파일도 Limit로 거부합니다. 해제 전체와 TAR 경로, 항목 종류 및 이름 충돌을 검증하기 전에는 목적지에 게시하지 않습니다. 출력 공간 검사, 안전한 충돌 처리, 취소와 300초 시간 제한도 기존 흐름을 사용합니다.
43추가: 해제 총량은 TAR 헤더와 패딩을 포함해 기존 16 GiB 이하이며 요청으로 낮출 수 있습니다. 64 KiB씩 실제 해제량을 확인하고 기록 전에 임시 저장소의 공간을 검사합니다. XZ는 블록별 LZMA2 디코더 메모리 32 MiB, 인덱스는 승인 전 8 MiB, 승인 후 64 MiB이며 스트림 수와 스트림당 블록 수는 각각 승인 전 32,768개, 승인 후 262,144개를 상한으로 둡니다. 이 상한을 넘는 정상 파일도 Limit로 거부합니다. 해제 전체와 TAR 경로, 항목 종류 및 이름 충돌을 검증하기 전에는 목적지에 게시하지 않습니다. 출력 공간 검사, 안전한 충돌 처리, 취소와 300초 시간 제한도 기존 흐름을 사용합니다.
4344
4445XZ의 헤더, 인덱스, 푸터 CRC와 역방향 크기 및 전체 선언 해제량을 확인하고 실제 해제량과 비교합니다. 각 블록의 헤더와 LZMA2 청크 경계를 따라 압축 길이와 해제량을 인덱스 레코드 및 선택적 헤더 크기와 대조하므로 다른 블록이나 연결 스트림의 크기 변조가 상쇄되어도 Integrity로 거부합니다. 지원하는 BCJ와 Delta 필터는 길이를 보존합니다. 이 사전 검사는 payload를 해제하거나 할당하지 않으며 기존 디코더가 청크 내용과 데이터 블록의 CRC32/CRC64/SHA256 검사를 수행한 뒤에만 게시합니다. [XZ 명세 4.3절](https://tukaani.org/xz/xz-file-format.txt)의 블록별 Unpadded Size와 Uncompressed Size 검사를 적용합니다. XZ의 Check=None도 형식대로 허용하므로 데이터 체크섬이 없는 파일의 내용 무결성을 보장하지 않습니다. TAR의 PAX/GNU 확장, 링크와 특수 항목의 기존 제한도 유지합니다.
4546
@@ -76,11 +77,11 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
7677
7778## 공유 codec
7879
79삭제: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 3 원문이며 `extract_conflicts.status`에서 구현 상태를 구분합니다.
80추가: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 3 원문이며 `extract_conflicts.status`와 `guarded_resources.status`에서 구현 및 화면 연동 상태를 구분합니다.
8081
8182헤더는 ZAW1, version u16=1, kind u16, body length u32, reserved u32=0, job ID u64, sequence u64의 32바이트입니다. 양방향 sequence는 각각 0부터 시작합니다. body는 최대 1 MiB이며 한 방향당 최대 1,000,000프레임입니다. 잘린 프레임, 알 수 없는 tag, 잔여 payload, 잘못된 ID/sequence를 거부합니다.
8283
83삭제: - kind: Start=1, Password=2, Cancel=3, StartInteractive=4, ConflictReply=5, Accepted=100, Entry=101, ListEnd=102, PasswordRequired=103, Progress=104, Output=105, Terminal=106, CancelAck=107, ConflictRequired=108, ConflictResolved=109입니다. 새 kind의 런타임 지원 상태는 아래 revision 3 절을 따릅니다.
84추가: - kind: Start=1, Password=2, Cancel=3, StartInteractive=4, ConflictReply=5, StartGuarded=6, ResourceReply=7, Accepted=100, Entry=101, ListEnd=102, PasswordRequired=103, Progress=104, Output=105, Terminal=106, CancelAck=107, ConflictRequired=108, ConflictResolved=109, ResourceRequired=110입니다. 충돌 및 자원 승인의 지원 상태는 아래 계약 절을 따릅니다.
8485- body 필드는 `protocol.rs` 선언 순서입니다. enum은 선언 순서의 u8 tag이며 NativePath/SourceObject만 Unix=1, Windows=2입니다. bool/Option은 0 또는 1입니다. String/Vec는 u32 길이 뒤 원소를 저장하며 String은 UTF-8 바이트 길이입니다. `[u8; N]`은 길이 없이 N바이트입니다. action variant의 필드는 선언 순서를 사용합니다. Start는 action 뒤 limits(input u64, output u64, entries u32)입니다.
8586- Password의 비밀 값은 Debug에 노출되지 않습니다. 암호 작업은 PasswordRequired의 challenge_id와 일치하는 Password를 한 번 받습니다. 오래된 ID, 중복 또는 요청 전 암호는 Protocol 오류입니다. 비밀 값은 로그나 파일에 저장하지 않습니다.
8687- CancelAck.request_sequence는 요청 헤더 sequence입니다. Requested, AlreadyRequested, TooLate, Finished는 최종 결과와 별개입니다. 종료와 경합한 요청은 읽히지 않아 응답이 없을 수 있습니다. Terminal은 마지막 프레임이며 Failed/Cancelled도 정상 전달 뒤 프로세스 exit=0입니다. 앱은 Terminal과 stdout/stderr EOF, child wait를 모두 확인해야 합니다.
@@ -101,6 +102,26 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
101102
102103교체 동작의 근거는 [Linux rename](https://man7.org/linux/man-pages/man2/rename.2.html)과 [Microsoft MoveFileExW](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw)입니다.
103104
105추가: ## 큰 작업의 명시적 승인 계약
106추가:
107추가: `StartGuarded`는 기존 요청과 분리된 선택적 확장입니다. 작업자와 앱의 요청 및 승인 화면 연동이 구현됐으며 `--ui-scenario` 상황, 시험과 [가이드](../../docs/ui-scenario-guide.md)도 반영됐습니다. 기존 `Start`와 `StartInteractive` 요청에는 자원 질문을 보내지 않습니다. 구버전 작업자가 새 요청을 거부하면 자동 재시도하지 않습니다.
108추가:
109추가: - kind 6의 본문은 `GuardedStart { start: Start, ceiling: Limits, interactive: bool }` 순서입니다. start.limits는 기존 16 GiB 및 10,000개 이하이고 ceiling은 이를 늘리되 64 GiB 및 200,000개 이하입니다. 입력 한도는 동일해야 합니다. interactive는 Extract에서만 허용하며 기존 암호와 충돌 처리를 함께 사용합니다.
110추가: - 작업자는 Accepted 뒤, 입력 캡처와 소스 탐색 전에 요청된 상한 확대 범위를 확인합니다. 입력 사본 작성부터 300초를 넘을 수 있으므로 승인을 먼저 받습니다. 이때 예상량과 실제량은 아직 미확인(None)이고 임시 저장 볼륨의 여유 공간을 알립니다. 허용 전에는 확대 한도가 적용되지 않으며 거부하면 Cancelled로 끝납니다. 앱의 일반 작업은 기존 16 GiB 및 10,000개 한도의 `StartGuarded`를 사용해 압축률을 감시합니다. 기존 `Start` 호출도 유지합니다.
111추가: - kind 110의 `ResourceRequired`는 challenge_id, action, scope, usage, soft_limits, ceiling 순서입니다. `ResourceScope`는 output, entries, ratio의 bool 세 개입니다. `ResourceUsage`는 estimated_bytes, actual_bytes, estimated_entries, actual_entries, compressed_bytes, ratio_output_bytes, available_bytes 순서이며 모두 Option입니다. 바이트는 u64, 항목 수는 u32입니다. 미확인은 0으로 바꾸지 않습니다. 여유 공간은 관찰 중인 저장 볼륨의 값이며 공간 예약이나 모든 볼륨의 합계가 아닙니다.
112추가: - kind 7의 `ResourceReply`는 challenge_id u64, scope, allow bool입니다. 프레임의 작업 ID, 현재 질문 ID와 요청한 scope가 모두 일치하는 응답 한 개만 허용합니다. 중복, 오래된 응답과 다른 종류의 질문 응답은 Protocol입니다. 승인은 해당 작업의 해당 범위에만 적용하며 재사용하지 않습니다.
113추가: - 해제량이 256 MiB 이상이고 압축률이 1,000배를 초과하면 ratio 범위를 별도로 묻습니다. ZIP은 항목별 크기와 전체 payload 합계, 7z는 solid 폴더와 전체, 압축 TAR와 GZip은 스트림 전체의 크기로 검사합니다. 예상량과 실제량을 구분하고 u128 곱셈으로 비교합니다. 승인 중에는 추가 해제와 쓰기를 멈추며 취소는 별도 제어 읽기에서 처리합니다.
114추가: - 승인 후에도 64 GiB와 200,000개 정책 상한, 메타데이터와 사전 예산, 경로 및 무결성, 임시 저장소와 목적지 공간 검사를 적용합니다. ZIP 생성은 원본 논리 크기 합계를 제한하며 ZIP 구조와 암호화로 늘어나는 저장 공간을 별도로 계산합니다. 이미 게시한 출력은 실패나 취소 시 유지하고 게시 및 정리 상태를 보고합니다.
115추가: - 승인된 작업은 전체 300초 대신 진행이 60초 동안 없을 때 Limit로 중단합니다. 성공한 읽기, 해독, 쓰기와 항목별 메타데이터 및 경로 검사를 공통 완료 함수로 기록합니다. 사전검사, 기존 폴더 조회와 생성, ZIP 헤더와 중앙 목록 기록, 목록 전송, 이름 후보와 덮어쓰기 재검사, 게시와 임시 파일 정리도 포함하며 반복 check와 UI 진행 알림만으로는 기한을 늘리지 않습니다. 한 단계 자체가 60초 이상 멈추면 완료 시에도 Limit로 처리하고 이미 만들어진 출력 집계와 정리는 유지합니다. 암호, 충돌과 자원 질문은 한 번에 하나이며 각 응답 대기는 300초입니다. 유효한 응답 뒤에는 사용자 대기 시간을 제외하고 정체 감시를 재개합니다. 기존 요청의 전체 300초 제한은 유지합니다. OS의 블로킹 I/O를 강제로 중단하는 보장은 아닙니다.
116추가:
117추가: 메타데이터 정책은 유효한 자원 승인 여부로 선택하며 요청의 ceiling만 늘려서는 확대되지 않습니다. 7z 압축 헤더 해독은 이 메타데이터 예산으로만 감시하며 파일 출력량과 압축률 집계에는 합치지 않습니다. 헤더 처리 중에도 취소와 진행 시각 감시는 유지하고 실제 파일 데이터에는 기존 출력량과 압축률 검사를 적용합니다. 원본 계획의 경로와 대기 이름은 확대 작업에서 같은 항목의 복사 비용으로 계산하고 노드를 중복 가산하지 않습니다. 이름 및 원본 경로의 바이트 비용과 암묵적 상위 폴더 노드는 계속 계산하므로 긴 경로나 많은 상위 폴더가 있으면 항목 200,000개 이전에도 Limit로 중단될 수 있습니다. 승인 전과 기존 slice API의 메타데이터 한도 및 계산 방식은 유지합니다. 기존 대용량 회귀의 64 MiB RSS 목표는 기본 메타데이터 정책의 측정값이며 확대 작업 전체의 메모리 상한을 뜻하지 않습니다.
118추가:
119추가: 앱은 목록이나 선택한 일반 파일의 크기로 한도 초과를 알 수 있으면 처리 전에 확대 승인을 요청합니다. 미확인 폴더 내부와 압축파일은 기본 한도로 시작합니다. 한도 오류 뒤 Terminal, 양쪽 EOF와 자식 회수가 확인되고 게시 없음, 생성 및 부분 잔존 0개, 정리 완료일 때만 "한도를 늘려 다시 시도"를 제공합니다. 선택하면 새 작업 ID로 시작해 다시 승인을 받습니다. 이미 출력이 있거나 결과가 불확실하면 확대 재시도 대신 저장 위치와 상세 결과를 안내합니다. 유효한 자원 승인 후에는 암묵적 상위 폴더를 포함한 앱 출력 기록 상한이 262,144개 노드로 늘어납니다. 목록은 항목 확대를 승인한 작업에서만 200,000개까지 받습니다. 자원 승인 전 출력 기록과 항목 확대 승인 전 목록은 기존 100,000개 상한을 유지합니다.
120추가:
121추가: 작업자의 짧은 이름 빈 ZIP 항목 200,000개 목록 시험과 앱 승인 및 재시도 시험을 반영했습니다. `resource-approval`, `resource-ratio`, `resource-retry`, `resource-partial` 상황과 가이드도 추가됐습니다. Windows와 Wayland의 실제 화면 및 입력 검증은 별도로 남아 있습니다.
122추가:
123추가: 시험은 실제 64 GiB를 쓰지 않고 수치 경계와 축소한 limits/ceiling을 사용합니다. `resource_budget.rs`는 16 GiB 아래/경계/초과, 64 GiB 초과, 10,000개 및 200,000개 경계, 압축률 경계와 가상 시계의 60초 정체를 검사합니다. `item_progress.rs`는 기존 빈 폴더 8개를 포함해 각 단계를 가상 10초씩 늦춘 실제 작업자와 단일 60초 정체의 출력 집계 및 정리를 검사합니다. `metadata_policy.rs`는 축소한 바이트와 노드 예산, 원본 계획과 암묵적 폴더 계산을 확인합니다. `guarded.rs`는 승인 전 메타데이터 거부, 승인 뒤 200,000개 목록, 실제 작업자 승인/거부, 오래된 응답, 암호/충돌 순서, 승인 뒤 공간 실패, 여러 형식과 작은 고압축 입력의 경고 및 취소를 검사합니다.
124추가:
104125## 검증과 의존성
105126
106127시험은 `tests/rust-archive-worker`에 있습니다. Python 표준 라이브러리로 만든 ZIP/TAR/GZ fixture와 실제 자식 프로세스를 사용합니다. 전체 검증 명령은 저장소 루트의 `python3 tests/ci/run_rust.py local`입니다. Windows 교차 빌드는 실제 Windows 실행 검증을 대신하지 않습니다.
수정experiments/rust-archive-worker/contract.json+22-5
@@ -30,7 +30,9 @@
3030 "Password": "Matching outstanding challenge_id:u64 and max1024 UTF-8 bytes; never log, Debug, echo or persist secrets.",
3131 "Cancel": "Matching header job_id and empty body; command header sequence identifies the request. See CancelAck. Request acceptance is separate from final outcome. EOF alone is not successful cancellation.",
3232 "StartInteractive": "Kind 4, body identical to Start with action restricted to Extract. Exactly one initial Start or StartInteractive. Invalid non-Extract action is rejected by the shared encoder and decoder. Opt in to interactive regular-file conflicts; never retry through legacy Start or an older worker automatically. Worker runtime supports the agreed choices; client activation and native UI integration are verified separately.",
33삭제: "ConflictReply": "Kind 5: challenge_id:u64, choice:ConflictChoice(u8), apply_to_remaining:bool. Match the one outstanding conflict challenge exactly once. Applying to remaining affects only later regular-file conflicts in this job."
33추가: "ConflictReply": "Kind 5: challenge_id:u64, choice:ConflictChoice(u8), apply_to_remaining:bool. Match the one outstanding conflict challenge exactly once. Applying to remaining affects only later regular-file conflicts in this job.",
34추가: "StartGuarded": "Kind 6: GuardedStart{start:Start,ceiling:Limits,interactive:bool}. Start limits keep legacy maxima. ceiling.input must equal start.limits.input; ceiling.output and entries may increase up to 64 GiB and 200000. interactive is valid only for Extract. No resource expansion takes effect before a matching ResourceReply. New workers never emit guarded challenges for Start or StartInteractive; older workers reject kind 6 without fallback.",
35추가: "ResourceReply": "Kind 7: challenge_id:u64,scope:ResourceScope,allow:bool. Frame job_id and exact outstanding challenge_id/scope must match once. Reject premature, stale, duplicate and cross-kind replies as Protocol. False cancels the job without further processing."
3436 },
3537 "events": {
3638 "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation.",
@@ -59,7 +61,8 @@
5961 "ordering": "Each well-formed Cancel consumed before Terminal is acknowledged once before Terminal. Terminal is the last worker protocol frame. A Cancel racing with Terminal/exit may remain unread and have no acknowledgement; app uses Terminal plus EOF and wait, never synthesizes a worker acknowledgement or successful cancellation."
6062 },
6163 "ConflictRequired": "Kind 108: challenge_id:u64, entry_id:u32, relative_name:UTF8, incoming_size:u64, existing_size:u64. One ordinary-file conflict at a time, after complete archive integrity validation. All three choices are permitted; links and file/directory type conflicts remain rejected.",
62삭제: "ConflictResolved": "Kind 109: entry_id:u32, relative_name:UTF8, choice:ConflictChoice(u8). Emit for every resolved conflict, including automatically applied choices. This records the action and resolved name, not successful publication; successful overwrite or rename also requires Output Created. Skip emits no Output Created."
64추가: "ConflictResolved": "Kind 109: entry_id:u32, relative_name:UTF8, choice:ConflictChoice(u8). Emit for every resolved conflict, including automatically applied choices. This records the action and resolved name, not successful publication; successful overwrite or rename also requires Output Created. Skip emits no Output Created.",
65추가: "ResourceRequired": "Kind 110: challenge_id:u64,action:ActionKind,scope:ResourceScope,usage:ResourceUsage,soft_limits:Limits,ceiling:Limits. ResourceScope is output:bool,entries:bool,ratio:bool. ResourceUsage fields in order are estimated_bytes:Option<u64>,actual_bytes:Option<u64>,estimated_entries:Option<u32>,actual_entries:Option<u32>,compressed_bytes:Option<u64>,ratio_output_bytes:Option<u64>,available_bytes:Option<u64>. None is unknown, not zero."
6366 },
6467 "lifecycle": [
6568 "Exactly one Start or StartInteractive; no automatic retry or fallback. Password/Cancel remain readable during work. ConflictReply is accepted only for a matching outstanding interactive conflict.",
@@ -162,13 +165,13 @@
162165 "gzip_ratio": "No compression-ratio rejection, including concatenated members. Aggregate decoded bytes, including TAR headers/padding, cannot exceed output quota.",
163166 "tar_ratio": "Plain TAR copies declared nonoverlapping ranges within the captured input. The sum of file sizes cannot exceed output quota.",
164167 "arithmetic": "Checked u64 offsets and totals; free-space block-to-byte conversion uses u128 to avoid multiplication overflow.",
165삭제: "memory_target": "ZIP/TAR/GZ/TAR.GZ/7z List/Extract and ZIP creation: 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.",
168추가: "memory_target": "ZIP/TAR/GZ/TAR.GZ/7z List/Extract and ZIP creation: 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. The 64 MiB RSS regression target uses the default 8 MiB metadata policy; approved expanded metadata jobs may use more RSS.",
166169 "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.",
167170 "legacy": "The slice parser keeps 64 MiB input /128 MiB output caps; the slice ZIP builder keeps 128 MiB source/result caps. Runtime 7z and ZIP creation use streaming file paths.",
168171 "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.",
169172 "disk_space": "Advisory free-space checks use opened Linux x86_64 filesystem handles (fstatvfs) or the Windows handle-derived directory (GetDiskFreeSpaceExW). Legacy Start groups remaining staging and selected output logical bytes by volume before ZIP/7z decoding and before publication. StartInteractive checks required staging before choices, then checks only the current non-skipped output at its resolved name immediately before publication; do not charge undecided or skipped files to the destination. 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.",
170173 "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.",
171삭제: "seven_zip": "Copy, LZMA and LZMA2 use file-backed solid output with checked declared/actual output totals. Encoded headers remain limited to 8 MiB. Dictionary size remains at most 64 MiB; only the last 8 MiB is cached in memory and older dictionary bytes are read from the temporary output.",
174추가: "seven_zip": "Copy, LZMA and LZMA2 use file-backed solid output with checked declared/actual output totals. Encoded headers are limited to the active metadata policy: 8 MiB before a valid resource grant, 64 MiB after it. Dictionary size remains at most 64 MiB; only the last 8 MiB is cached in memory and older dictionary bytes are read from the temporary output.",
172175 "create_zip": "The sum of source logical bytes cannot exceed min(input,output) quotas. output defaults to 16 GiB of uncompressed source content; ZIP container/encryption overhead may exceed that logical content quota. Capture one immutable source at a time, stream Store/Deflate and optional AES-256 through 64 KiB buffers, then publish the completed ZIP without replacing existing files. Emit ZIP64 sizes/offsets only when their 32-bit fields would overflow or equal the sentinel. Check staging and destination free space; StorageFull maps to DiskFull tag 13 and other I/O failures retain Io tag 8."
173176 },
174177 "validation": "Implementation results belong in the PR verification record. No OS sandbox or native Windows execution claim.",
@@ -199,7 +202,7 @@
199202 "agreement": "Proposed semantic extension under manager task 82093f56-73b7-4be4-ba6d-2597ffc2c6f7; frontend joint agreement is pending. Revision 2 fields, encoding, numeric quotas and error tags are unchanged.",
200203 "roots": "Each source may be a regular file or directory. archive_name names that root inside the ZIP; directory descendants retain relative paths and every directory, including empty directories, gets a trailing-slash ZIP entry.",
201204 "links": "Reject the whole job with UnsafePath for symbolic links, Windows reparse points, special files or unsafe/non-UTF-8 descendant names. Do not skip entries or follow external links. Open each path component without following links; enumerate pinned directories.",
202삭제: "limits": "All expanded file and directory entries count toward entries (default 10000). Only file logical bytes count toward min(input,output), default output 16 GiB. Preserve 8 MiB metadata and 64-component name limits. Validate the complete plan and case-insensitive/path-prefix conflicts before requesting a password.",
205추가: "limits": "All expanded file and directory entries count toward entries (default 10000). Only file logical bytes count toward min(input,output), default output 16 GiB. Keep 64-component names and the active metadata budget. Legacy/unapproved plans retain 8 MiB and 32768 nodes; resource-approved plans use 64 MiB and 262144 nodes. In approved source plans, path and pending-name copies consume bytes but share their entry node. Validate the complete plan and case-insensitive/path-prefix conflicts before requesting a password.",
203206 "consistency": "Capture each file from its validated open handle. Compare planned object identity, kind, size and modification time before capture and check planned objects again before publishing the completed ZIP; detected changes fail SourceChanged. This is not an atomic snapshot of an entire directory tree.",
204207 "encryption": "AES-256 protects file contents using the existing AE-2 encoding. Directory entries are stored as zero-byte unencrypted directory records; entry names remain visible, as with other ZIP entries."
205208 },
@@ -222,5 +225,19 @@
222225 "implementation_boundary": "Worker supports StartInteractive extraction. Frontend activation and native Windows/Wayland integration require separate verification. Existing Start remains exclusive and aborts on file conflicts.",
223226 "target_revalidation": "Before replacement compare parent and file native identities, size and modification time with the question-time observation. Detected changes fail Conflict. This is not atomic compare-and-replace against concurrent writes by the same account.",
224227 "disk_space": "Required input capture and complete integrity staging checks remain before conflict questions. Defer destination space checks until the current choice is resolved. Skip has no destination byte charge; overwrite, rename and non-conflicting files are checked immediately before their publication. Preserve legacy Start aggregate preflight, limits, per-write checks and partial-output reporting."
228추가: },
229추가: "guarded_resources": {
230추가: "status": "worker-and-client-implemented; native Windows/Wayland verification pending",
231추가: "agreement": "Frontend flow agreement 6fe5a494-7d5a-4bda-a7d3-831fb43e9238 and manager policy b3a743d2-10de-495c-8fdb-ecf2a5f3b453. Frame version 1, revision 3 messages and enum tags remain unchanged; this is an explicit opt-in extension.",
232추가: "admission": "After Accepted, request the output and/or entries scopes that ceiling increases above Start limits before capturing input or planning sources. Usage estimates and actuals are unknown at this point; report current staging-volume free space. The caller must show the requested ceilings and unknown values, not invent estimates. An earlier confirmation is needed because input capture itself can exceed 300 seconds. Each granted scope is confined to this job.",
233추가: "ratio": "Request ratio scope separately when expanded bytes are at least 256 MiB and strictly exceed compressed bytes times 1000. Check ZIP members and aggregate payload totals, 7z solid folders and totals, and complete compressed TAR/GZip streams. Use u128 arithmetic; unknown compressed length does not become zero. No ratio warning for legacy requests.",
234추가: "accounting": "Monitor declared catalog sums and counts, real decoded bytes, per-stream ratios and source-plan sums. Decoders must match verified declared lengths before publication. For compressed TAR/GZip the expanded stream includes headers/padding. ZIP creation ceiling counts source logical bytes; ZIP/container/encryption overhead is separately space-checked.",
235추가: "disk": "Continue staging/destination volume preflight and per-chunk space checks after approval. available_bytes is advisory free space on the current observation storage volume, not a reservation or all-volume total. Unknown storage is None. Preserve DiskFull, partial publication, durability and cleanup semantics.",
236추가: "waiting": "One resource, password or conflict challenge at a time. Pause processing while waiting; control reader remains live for Cancel. Response EOF fails Protocol. Guarded challenge wait is limited to 300 seconds per question; reset the inactivity clock after a valid reply, excluding the human wait.",
237추가: "time": "Legacy and unapproved jobs retain their whole-job 300-second deadline. After the first resource grant, use a 60-second inactivity deadline measured only from actual read/decode/write/metadata progress, not repeated cancellation checks or outgoing heartbeats. Cooperative checkpoints cannot forcibly interrupt a blocked OS call.",
238추가: "hard_ceiling": "Output/source bytes <=64 GiB and entries<=200000, including after approval. Caller may lower both ceilings for normal operation or scaled tests. Input quota cannot be expanded. Existing path, metadata, dictionary, frame and source-identity limits remain independent.",
239추가: "metadata": "Only after a valid ResourceReply(allow=true) for this job, select 64 MiB MetadataBudget and 262144 nodes, including ZIP/TAR/7z parsing, decoded 7z headers, XZ index/block bounds, member/path validation, implicit output parents and source planning. Legacy Start/StartInteractive, unapproved guarded jobs and slice APIs keep 8 MiB and 32768 nodes. Merely requesting expanded ceilings does not grant a larger budget. Names and source paths still consume checked byte budgets and implicit parents consume nodes, so long/deep paths can hit the metadata cap before 200000 entries. Approved source-path/pending-name copies consume bytes without duplicating their entry node. Expanded metadata jobs do not retain a universal 64 MiB RSS target.",
240추가: "client": "Normal app jobs use StartGuarded with the existing 16 GiB and 10000-entry limits. Known selection/file estimates request expanded ceilings before processing. After a Limit result, offer an explicit expanded retry only after Terminal, both EOFs and child reap, with Publication::None, zero created/partial counts and complete cleanup. Retry uses a new job ID and requires fresh approval; existing or uncertain output instead shows the saved location and detailed result. App output records, including implicit parent directories, grow to 262144 nodes after any valid resource approval. Catalog entries grow to 200000 only for jobs granted the entries scope. Unapproved output records and catalogs without an entries grant retain their existing 100000 caps. Resource approval, ratio, retry and partial-output UI scenarios, tests and docs/ui-scenario-guide.md are implemented. Native Windows/Wayland verification remains separate.",
241추가: "tests": "Use numeric 16/64 GiB and 10000/200000 policy boundaries, scaled worker limits, a compressed 257 MiB zero stream, and a virtual clock for the 60-second stall. Include client approval/retry tests in tests/rust-app-ui/guarded.rs and real-worker flows in tests/rust-app-real-worker/guarded_flows.rs. Do not write 64 GiB in tests."
225242 }
226243}
수정experiments/rust-archive-worker/src/archive.rs+103-30
@@ -7,30 +7,74 @@ pub const MAX_PATH_DEPTH: usize = 64;
77pub const MAX_METADATA_BYTES: usize = 8 * 1024 * 1024;
88pub const MAX_OUTPUT_NODES: usize = 32_768;
99
10추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
11추가: pub struct MetadataLimits {
12추가: pub(crate) bytes: usize,
13추가: pub(crate) nodes: usize,
14추가: pub(crate) enlarged: bool,
15추가: }
16추가: impl Default for MetadataLimits {
17추가: fn default() -> Self {
18추가: Self {
19추가: bytes: MAX_METADATA_BYTES,
20추가: nodes: MAX_OUTPUT_NODES,
21추가: enlarged: false,
22추가: }
23추가: }
24추가: }
25추가: impl MetadataLimits {
26추가: pub(crate) fn approved() -> Self {
27추가: Self {
28추가: bytes: 64 * 1024 * 1024,
29추가: nodes: 262_144,
30추가: enlarged: true,
31추가: }
32추가: }
33추가: }
34추가:
1035#[derive(Default)]
1136pub(crate) struct MetadataBudget {
1237 bytes: usize,
1338 nodes: usize,
1439}
1540impl MetadataBudget {
41추가: fn charge_cost(&mut self, bytes: usize, nodes: usize, limits: MetadataLimits) -> Result<()> {
42추가: let bytes = self
43추가: .bytes
44추가: .checked_add(bytes)
45추가: .filter(|n| *n <= limits.bytes)
46추가: .ok_or(ErrorCode::Limit)?;
47추가: let nodes = self
48추가: .nodes
49추가: .checked_add(nodes)
50추가: .filter(|n| *n <= limits.nodes)
51추가: .ok_or(ErrorCode::Limit)?;
52추가: self.bytes = bytes;
53추가: self.nodes = nodes;
54추가: Ok(())
55추가: }
1656 pub(crate) fn charge(&mut self, name: &str) -> Result<()> {
57추가: self.charge_with(name, MetadataLimits::default())
58추가: }
59추가: pub(crate) fn charge_with(&mut self, name: &str, limits: MetadataLimits) -> Result<()> {
1760 // 이름 복제와 인덱스 노드 비용을 할당 전에 계산함.
1861 let cost = name
1962 .len()
2063 .checked_mul(4)
2164 .and_then(|n| n.checked_add(256))
2265 .ok_or(ErrorCode::Limit)?;
23삭제: self.bytes = self
24삭제: .bytes
25삭제: .checked_add(cost)
26삭제: .filter(|n| *n <= MAX_METADATA_BYTES)
27삭제: .ok_or(ErrorCode::Limit)?;
28삭제: self.nodes = self
29삭제: .nodes
30삭제: .checked_add(1)
31삭제: .filter(|n| *n <= MAX_OUTPUT_NODES)
32삭제: .ok_or(ErrorCode::Limit)?;
33삭제: Ok(())
66추가: self.charge_cost(cost, 1, limits)
67추가: }
68추가: pub(crate) fn charge_copy(&mut self, name: &str, limits: MetadataLimits) -> Result<()> {
69추가: if !limits.enlarged {
70추가: return self.charge_with(name, limits);
71추가: }
72추가: // 확대 계획의 경로와 대기 이름은 기존 항목 노드에 속한 복사 비용임.
73추가: self.charge_cost(
74추가: name.len().checked_mul(4).ok_or(ErrorCode::Limit)?,
75추가: 0,
76추가: limits,
77추가: )
3478 }
3579}
3680
@@ -99,44 +143,61 @@ pub fn valid_name(name: &str, directory: bool) -> Result<String> {
99143 Ok(name.to_owned())
100144}
101145pub fn validate_members(members: &[Member]) -> Result<()> {
146추가: validate_members_with(members, &mut || Ok(()))
147추가: }
148추가: pub(crate) fn validate_members_with(
149추가: members: &[Member],
150추가: check: &mut impl crate::resources::Monitor,
151추가: ) -> Result<()> {
102152 let mut names = BTreeMap::<String, bool>::new();
103153 let mut budget = MetadataBudget::default();
104154 for member in members {
105삭제: budget.charge(&member.entry.name)?;
155추가: check.check()?;
156추가: budget.charge_with(&member.entry.name, check.metadata_limits())?;
106157 let directory = member.entry.kind == EntryKind::Directory;
107158 let name = valid_name(&member.entry.name, directory)?.to_lowercase();
108159 if names.insert(name, directory).is_some() {
109160 return Err(ErrorCode::Conflict);
110161 }
162추가: crate::resources::completed(Ok(()), check)?;
111163 }
112164 for name in names.keys() {
165추가: check.check()?;
113166 let mut parent = name.as_str();
114167 while let Some((p, _)) = parent.rsplit_once('/') {
115168 if names.get(p) == Some(&false) {
116169 return Err(ErrorCode::Conflict);
117170 }
118171 parent = p;
172추가: crate::resources::completed(Ok(()), check)?;
119173 }
174추가: crate::resources::completed(Ok(()), check)?;
120175 }
121176 Ok(())
122177}
123삭제: pub(crate) fn output_directories(members: &[Member]) -> Result<BTreeSet<String>> {
124삭제: validate_members(members)?;
178추가: pub(crate) fn output_directories(
179추가: members: &[Member],
180추가: check: &mut impl crate::resources::Monitor,
181추가: ) -> Result<BTreeSet<String>> {
182추가: validate_members_with(members, check)?;
125183 let mut budget = MetadataBudget::default();
126184 let mut dirs = BTreeSet::new();
127185 for member in members {
128삭제: budget.charge(&member.entry.name)?;
186추가: check.check()?;
187추가: budget.charge_with(&member.entry.name, check.metadata_limits())?;
129188 if member.entry.kind == EntryKind::Directory && !dirs.contains(member.entry.name.as_str()) {
130189 dirs.insert(member.entry.name.clone());
131190 }
132191 let mut name = member.entry.name.as_str();
133192 while let Some((parent, _)) = name.rsplit_once('/') {
134193 if !dirs.contains(parent) {
135삭제: budget.charge(parent)?;
194추가: budget.charge_with(parent, check.metadata_limits())?;
136195 dirs.insert(parent.to_owned());
137196 }
138197 name = parent;
198추가: crate::resources::completed(Ok(()), check)?;
139199 }
200추가: crate::resources::completed(Ok(()), check)?;
140201 }
141202 Ok(dirs)
142203}
@@ -158,13 +219,13 @@ fn inflate(
158219 input: &[u8],
159220 gzip: bool,
160221 limit: u64,
161삭제: check: &mut impl FnMut() -> Result<()>,
222추가: check: &mut impl crate::resources::Monitor,
162223) -> Result<(Vec<u8>, usize)> {
163224 let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
164225 let mut out = Vec::new();
165226 let mut buffer = [0; 65536];
166227 loop {
167삭제: check()?;
228추가: check.check()?;
168229 let before_in = stream.total_in();
169230 let before_out = stream.total_out();
170231 let status = stream
@@ -184,7 +245,11 @@ fn inflate(
184245 }
185246 }
186247}
187삭제: fn gzip(input: &[u8], limits: Limits, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> {
248추가: fn gzip(
249추가: input: &[u8],
250추가: limits: Limits,
251추가: check: &mut impl crate::resources::Monitor,
252추가: ) -> Result<Vec<u8>> {
188253 let mut at = 0;
189254 let mut result = Vec::new();
190255 while at < input.len() {
@@ -230,14 +295,14 @@ fn tar(
230295 input: &[u8],
231296 limits: Limits,
232297 decode: bool,
233삭제: check: &mut impl FnMut() -> Result<()>,
298추가: check: &mut impl crate::resources::Monitor,
234299) -> Result<Vec<Member>> {
235300 let mut at = 0;
236301 let mut members = Vec::new();
237302 let mut total = 0u64;
238303 let mut metadata = MetadataBudget::default();
239304 loop {
240삭제: check()?;
305추가: check.check()?;
241306 let header = part(input, at, 512)?;
242307 if header.iter().all(|b| *b == 0) {
243308 if part(input, at + 512, 512)?.iter().any(|b| *b != 0)
@@ -394,7 +459,7 @@ fn zip(
394459 limits: Limits,
395460 decode: bool,
396461 password: Option<&[u8]>,
397삭제: check: &mut impl FnMut() -> Result<()>,
462추가: check: &mut impl crate::resources::Monitor,
398463) -> Result<Vec<Member>> {
399464 if input.len() < 22 {
400465 return Err(ErrorCode::Integrity);
@@ -432,7 +497,7 @@ fn zip(
432497 let mut total = 0u64;
433498 let mut metadata = MetadataBudget::default();
434499 for id in 0..count {
435삭제: check()?;
500추가: check.check()?;
436501 let h = part(input, at, 46)?;
437502 if &h[..4] != b"PK\x01\x02" {
438503 return Err(ErrorCode::Integrity);
@@ -604,7 +669,7 @@ pub fn parse(
604669 input: &[u8],
605670 limits: Limits,
606671 decode: bool,
607삭제: check: &mut impl FnMut() -> Result<()>,
672추가: check: &mut impl crate::resources::Monitor,
608673) -> Result<Catalog> {
609674 parse_with_password(input, limits, decode, None, check)
610675}
@@ -613,7 +678,7 @@ pub fn parse_with_password(
613678 limits: Limits,
614679 decode: bool,
615680 password: Option<&[u8]>,
616삭제: check: &mut impl FnMut() -> Result<()>,
681추가: check: &mut impl crate::resources::Monitor,
617682) -> Result<Catalog> {
618683 if !limits.valid() {
619684 return Err(ErrorCode::Limit);
@@ -666,12 +731,16 @@ pub fn parse_with_password(
666731 }
667732 Err(ErrorCode::UnsupportedFormat)
668733}
669삭제: fn deflate(input: &[u8], limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> {
734추가: fn deflate(
735추가: input: &[u8],
736추가: limit: u64,
737추가: check: &mut impl crate::resources::Monitor,
738추가: ) -> Result<Vec<u8>> {
670739 let mut stream = Deflate::new(6, false, 15);
671740 let mut output = Vec::new();
672741 let mut buffer = [0; 65536];
673742 loop {
674삭제: check()?;
743추가: check.check()?;
675744 let a = stream.total_in();
676745 let b = stream.total_out();
677746 let status = stream
@@ -700,7 +769,7 @@ pub fn create_zip(
700769 members: &[Member],
701770 method: Method,
702771 limits: Limits,
703삭제: check: &mut impl FnMut() -> Result<()>,
772추가: check: &mut impl crate::resources::Monitor,
704773) -> Result<Vec<u8>> {
705774 create_zip_with_password(members, method, limits, None, check)
706775}
@@ -709,7 +778,7 @@ pub fn create_zip_with_password(
709778 method: Method,
710779 limits: Limits,
711780 password: Option<&[u8]>,
712삭제: check: &mut impl FnMut() -> Result<()>,
781추가: check: &mut impl crate::resources::Monitor,
713782) -> Result<Vec<u8>> {
714783 if !limits.valid() {
715784 return Err(ErrorCode::Limit);
@@ -723,7 +792,7 @@ pub fn create_zip_with_password(
723792 let mut cd = Vec::new();
724793 let mut total = 0u64;
725794 for m in members {
726삭제: check()?;
795추가: check.check()?;
727796 total = total
728797 .checked_add(m.data.len() as u64)
729798 .filter(|n| *n <= limits.output)
@@ -808,3 +877,7 @@ pub fn create_zip_with_password(
808877 bounded_append(&mut out, &end, limits.output)?;
809878 Ok(out)
810879}
880추가:
881추가: #[cfg(test)]
882추가: #[path = "../../../tests/rust-archive-worker/metadata_policy.rs"]
883추가: mod metadata_tests;
수정experiments/rust-archive-worker/src/compressed_tar.rs+64-22
@@ -1,4 +1,7 @@
1삭제: use crate::{protocol::ErrorCode, space, spool};
1추가: use crate::{
2추가: protocol::{ErrorCode, ResourceUsage},
3추가: space, spool,
4추가: };
25use std::{
36 cell::RefCell,
47 fs::File,
@@ -32,13 +35,22 @@ struct CheckedInput<'a, F> {
3235 check: &'a RefCell<&'a mut F>,
3336}
3437
35삭제: impl<F: FnMut() -> Result<()>> Read for CheckedInput<'_, F> {
38추가: impl<F: crate::resources::Monitor> Read for CheckedInput<'_, F> {
3639 fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
37삭제: (self.check.borrow_mut())().map_err(|error| io::Error::other(InputError(error)))?;
40추가: self.check
41추가: .borrow_mut()
42추가: .check()
43추가: .map_err(|error| io::Error::other(InputError(error)))?;
3844 let count = buffer.len().min(CHUNK);
39삭제: self.file
45추가: let n = self
46추가: .file
4047 .read(&mut buffer[..count])
41삭제: .map_err(|_| io::Error::other(InputError(ErrorCode::Io)))
48추가: .map_err(|_| io::Error::other(InputError(ErrorCode::Io)))?;
49추가: if n != 0 {
50추가: crate::resources::completed(Ok(()), &mut **self.check.borrow_mut())
51추가: .map_err(|e| io::Error::other(InputError(e)))?;
52추가: }
53추가: Ok(n)
4254 }
4355}
4456
@@ -60,14 +72,26 @@ pub(crate) fn decode(
6072 source: &mut File,
6173 compression: Compression,
6274 limit: u64,
63삭제: check: &mut impl FnMut() -> Result<()>,
75추가: check: &mut impl crate::resources::Monitor,
6476) -> Result<(File, u64)> {
65삭제: check()?;
77추가: check.check()?;
6678 let expected = if matches!(compression, Compression::Xz) {
6779 Some(xz_layout(source, limit, check)?)
6880 } else {
6981 None
7082 };
83추가: let packed_length = source.metadata().map_err(space::io_error)?.len();
84추가: if let Some(expected) = expected {
85추가: check.observe(
86추가: ResourceUsage {
87추가: estimated_bytes: Some(expected),
88추가: compressed_bytes: Some(packed_length),
89추가: ratio_output_bytes: Some(expected),
90추가: ..ResourceUsage::default()
91추가: },
92추가: Some(source),
93추가: )?;
94추가: }
7195 source.rewind().map_err(space::io_error)?;
7296 let mut output = spool::temporary()?;
7397 let check = RefCell::new(check);
@@ -88,7 +112,7 @@ pub(crate) fn decode(
88112 let mut buffer = Zeroizing::new([0; CHUNK]);
89113 let mut total = 0u64;
90114 loop {
91삭제: (check.borrow_mut())()?;
115추가: check.borrow_mut().check()?;
92116 let count = reader.read(&mut buffer[..]).map_err(decode_error)?;
93117 if count == 0 {
94118 break;
@@ -97,13 +121,24 @@ pub(crate) fn decode(
97121 .checked_add(count as u64)
98122 .filter(|total| *total <= limit)
99123 .ok_or(ErrorCode::Limit)?;
124추가: check.borrow_mut().observe(
125추가: ResourceUsage {
126추가: actual_bytes: Some(total),
127추가: compressed_bytes: Some(packed_length),
128추가: ratio_output_bytes: Some(total),
129추가: ..ResourceUsage::default()
130추가: },
131추가: Some(&output),
132추가: )?;
133추가: crate::resources::completed(Ok(()), &mut **check.borrow_mut())?;
100134 // 전체 검증 전에는 비공개 임시 파일에만 기록함.
101135 space::ensure(&output, count as u64)?;
102삭제: output
103삭제: .write_all(&buffer[..count])
104삭제: .map_err(space::io_error)?;
136추가: crate::resources::completed(
137추가: output.write_all(&buffer[..count]).map_err(space::io_error),
138추가: &mut **check.borrow_mut(),
139추가: )?;
105140 }
106삭제: (check.borrow_mut())()?;
141추가: check.borrow_mut().check()?;
107142 if expected.is_some_and(|expected| expected != total) {
108143 return Err(ErrorCode::Integrity);
109144 }
@@ -114,9 +149,9 @@ fn read_at(
114149 source: &mut File,
115150 offset: u64,
116151 bytes: &mut [u8],
117삭제: check: &mut impl FnMut() -> Result<()>,
152추가: check: &mut impl crate::resources::Monitor,
118153) -> Result<()> {
119삭제: check()?;
154추가: check.check()?;
120155 source
121156 .seek(std::io::SeekFrom::Start(offset))
122157 .map_err(space::io_error)?;
@@ -126,7 +161,8 @@ fn read_at(
126161 } else {
127162 ErrorCode::Io
128163 }
129삭제: })
164추가: })?;
165추가: crate::resources::completed(Ok(()), check)
130166}
131167
132168fn vli(bytes: &[u8], cursor: &mut usize) -> Result<u64> {
@@ -150,7 +186,7 @@ fn lzma2_size(
150186 mut at: u64,
151187 end: u64,
152188 expected: u64,
153삭제: check: &mut impl FnMut() -> Result<()>,
189추가: check: &mut impl crate::resources::Monitor,
154190) -> Result<()> {
155191 let mut size = 0u64;
156192 while at < end {
@@ -202,7 +238,7 @@ fn xz_block(
202238 unpadded: u64,
203239 size: u64,
204240 check_size: u64,
205삭제: check: &mut impl FnMut() -> Result<()>,
241추가: check: &mut impl crate::resources::Monitor,
206242) -> Result<()> {
207243 let mut header = [0; 1024];
208244 read_at(source, start, &mut header[..1], check)?;
@@ -262,7 +298,11 @@ fn xz_block(
262298}
263299
264300// 역방향 인덱스 검사는 디코더의 할당과 실제 해제량 검사보다 먼저 수행함.
265삭제: fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<u64> {
301추가: fn xz_layout(
302추가: source: &mut File,
303추가: limit: u64,
304추가: check: &mut impl crate::resources::Monitor,
305추가: ) -> Result<u64> {
266306 use zlib_rs::crc32::crc32;
267307 let mut end = source.metadata().map_err(space::io_error)?.len();
268308 let mut total = 0u64;
@@ -278,7 +318,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<(
278318 end = at;
279319 }
280320 streams += 1;
281삭제: if streams > crate::archive::MAX_OUTPUT_NODES {
321추가: if streams > check.metadata_limits().nodes {
282322 return Err(ErrorCode::Limit);
283323 }
284324 let footer_at = end.checked_sub(12).ok_or(ErrorCode::Integrity)?;
@@ -290,7 +330,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<(
290330 return Err(ErrorCode::Integrity);
291331 }
292332 let index_len = (u64::from(u32::from_le_bytes(footer[4..8].try_into().unwrap())) + 1) * 4;
293삭제: if index_len > crate::archive::MAX_METADATA_BYTES as u64 {
333추가: if index_len > check.metadata_limits().bytes as u64 {
294334 return Err(ErrorCode::Limit);
295335 }
296336 if index_len < 8 {
@@ -310,13 +350,13 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<(
310350 }
311351 let mut cursor = 1;
312352 let count = vli(&index[..data_end], &mut cursor)?;
313삭제: if count > crate::archive::MAX_OUTPUT_NODES as u64 {
353추가: if count > check.metadata_limits().nodes as u64 {
314354 return Err(ErrorCode::Limit);
315355 }
316356 let mut blocks = 0u64;
317357 let mut records = Vec::new();
318358 for _ in 0..count {
319삭제: check()?;
359추가: check.check()?;
320360 let unpadded = vli(&index[..data_end], &mut cursor)?;
321361 let size = vli(&index[..data_end], &mut cursor)?;
322362 if unpadded == 0 {
@@ -330,6 +370,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<(
330370 .filter(|total| *total <= limit)
331371 .ok_or(ErrorCode::Limit)?;
332372 records.push((unpadded, size));
373추가: crate::resources::completed(Ok(()), check)?;
333374 }
334375 if data_end - cursor > 3 || index[cursor..data_end].iter().any(|byte| *byte != 0) {
335376 return Err(ErrorCode::Integrity);
@@ -357,6 +398,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<(
357398 for (unpadded, size) in records {
358399 xz_block(source, block_at, unpadded, size, check_size, check)?;
359400 block_at += (unpadded + 3) & !3;
401추가: crate::resources::completed(Ok(()), check)?;
360402 }
361403 end = start;
362404 }
수정experiments/rust-archive-worker/src/create.rs+30-13
@@ -42,7 +42,7 @@ fn pack(
4242 length: u64,
4343 method: Method,
4444 output: &mut File,
45삭제: check: &mut impl FnMut() -> Result<()>,
45추가: check: &mut impl crate::resources::Monitor,
4646) -> Result<(u64, u32)> {
4747 io(input.rewind())?;
4848 let mut input = input.take(length);
@@ -52,14 +52,17 @@ fn pack(
5252 let mut size = 0u64;
5353 if method == Method::Store {
5454 loop {
55삭제: check()?;
55추가: check.check()?;
5656 let n = io(input.read(&mut buffer[..]))?;
5757 if n == 0 {
5858 break;
5959 }
60추가: crate::resources::completed(Ok(()), check)?;
61추가: crate::space::ensure(output, n as u64)?;
6062 crc = crc32(crc, &buffer[..n]);
6163 io(output.write_all(&buffer[..n]))?;
6264 size += n as u64;
65추가: crate::resources::completed(Ok(()), check)?;
6366 }
6467 if size != length {
6568 return Err(ErrorCode::SourceChanged);
@@ -68,12 +71,12 @@ fn pack(
6871 }
6972 let mut stream = Deflate::new(6, false, 15);
7073 loop {
71삭제: check()?;
74추가: check.check()?;
7275 let n = io(input.read(&mut buffer[..]))?;
7376 crc = crc32(crc, &buffer[..n]);
7477 let mut used = 0;
7578 loop {
76삭제: check()?;
79추가: check.check()?;
7780 let a = stream.total_in();
7881 let b = stream.total_out();
7982 let status = stream
@@ -89,7 +92,11 @@ fn pack(
8992 .map_err(|_| ErrorCode::Internal)?;
9093 used += (stream.total_in() - a) as usize;
9194 let written = (stream.total_out() - b) as usize;
95추가: crate::space::ensure(output, written as u64)?;
9296 io(output.write_all(&encoded[..written]))?;
97추가: if used != 0 || written != 0 {
98추가: crate::resources::completed(Ok(()), check)?;
99추가: }
93100 size = size.checked_add(written as u64).ok_or(ErrorCode::Limit)?;
94101 if status == Status::StreamEnd {
95102 if stream.total_in() != length {
@@ -110,7 +117,7 @@ pub(crate) use crate::create_sources::Plan;
110117pub(crate) fn plan(
111118 sources: &[Source],
112119 limits: Limits,
113삭제: check: &mut impl FnMut() -> Result<()>,
120추가: check: &mut impl crate::resources::Monitor,
114121) -> Result<Plan> {
115122 Plan::new(sources, limits, check)
116123}
@@ -119,7 +126,7 @@ pub(crate) fn zip(
119126 method: Method,
120127 limits: Limits,
121128 password: Option<&[u8]>,
122삭제: check: &mut impl FnMut() -> Result<()>,
129추가: check: &mut impl crate::resources::Monitor,
123130) -> Result<(File, u64)> {
124131 let mut output = spool::temporary()?;
125132 let mut central = Vec::new();
@@ -130,13 +137,13 @@ pub(crate) fn zip(
130137 let directory = member.entry.kind == EntryKind::Directory;
131138 let method = if directory { Method::Store } else { method };
132139 let password = if directory { None } else { password };
133삭제: check()?;
140추가: check.check()?;
134141 let remaining = limits
135142 .input
136143 .min(limits.output)
137144 .checked_sub(total)
138145 .ok_or(ErrorCode::Limit)?;
139삭제: let mut input = source.open()?;
146추가: let mut input = crate::resources::completed(source.open(), check)?;
140147 let mut snapshot = if directory {
141148 None
142149 } else {
@@ -217,6 +224,7 @@ pub(crate) fn zip(
217224 header.extend(name);
218225 header.extend(extra);
219226 io(output.write_all(&header))?;
227추가: crate::resources::completed(Ok(()), check)?;
220228 io(packed.rewind())?;
221229 if let Some(password) = password {
222230 crate::crypto::aes_encrypt_file(
@@ -229,12 +237,14 @@ pub(crate) fn zip(
229237 } else {
230238 let mut buffer = Zeroizing::new([0; 65536]);
231239 loop {
232삭제: check()?;
240추가: check.check()?;
233241 let n = io(packed.read(&mut buffer[..]))?;
234242 if n == 0 {
235243 break;
236244 }
245추가: crate::space::ensure(&output, n as u64)?;
237246 io(output.write_all(&buffer[..n]))?;
247추가: crate::resources::completed(Ok(()), check)?;
238248 }
239249 }
240250 let mut extra = zip64_extra(length, packed_size, Some(offset));
@@ -276,14 +286,21 @@ pub(crate) fn zip(
276286 );
277287 central.extend(name);
278288 central.extend(extra);
289추가: crate::resources::completed(Ok(()), check)?;
279290 }
280삭제: check()?;
291추가: check.check()?;
281292 let at = io(output.stream_position())?;
282293 crate::space::ensure(&output, central.len() as u64 + 98)?;
283삭제: io(output.write_all(&central))?;
294추가: if !central.is_empty() {
295추가: crate::resources::completed(io(output.write_all(&central)), check)?;
296추가: }
284297 let large_at = io(output.stream_position())?;
285298 let mut end = Vec::new();
286삭제: if have_zip64 || at >= u32::MAX as u64 || central.len() >= u32::MAX as usize {
299추가: if have_zip64
300추가: || plan.items.len() >= u16::MAX as usize
301추가: || at >= u32::MAX as u64
302추가: || central.len() >= u32::MAX as usize
303추가: {
287304 end.extend(b"PK\x06\x06");
288305 put64(&mut end, 44);
289306 put16(&mut end, 45);
@@ -316,7 +333,7 @@ pub(crate) fn zip(
316333 put32(&mut end, at as u32);
317334 put16(&mut end, 0);
318335 }
319삭제: io(output.write_all(&end))?;
336추가: crate::resources::completed(io(output.write_all(&end)), check)?;
320337 plan.verify(check)?;
321338 let size = io(output.stream_position())?;
322339 io(output.rewind())?;
수정experiments/rust-archive-worker/src/create_sources.rs+48-19
@@ -201,7 +201,7 @@ impl Plan {
201201 pub fn new(
202202 sources: &[Source],
203203 limits: Limits,
204삭제: check: &mut impl FnMut() -> Result<()>,
204추가: check: &mut impl crate::resources::Monitor,
205205 ) -> Result<Self> {
206206 if sources.len() > limits.entries as usize {
207207 return Err(ErrorCode::Limit);
@@ -214,26 +214,32 @@ impl Plan {
214214 };
215215 let mut roots = std::collections::BTreeSet::new();
216216 for source in sources {
217삭제: check()?;
217추가: check.check()?;
218218 let name = archive::valid_name(&source.archive_name, false)?;
219219 if !roots.insert(name.to_lowercase()) {
220220 return Err(ErrorCode::Conflict);
221221 }
222추가: crate::resources::completed(Ok(()), check)?;
222223 }
223224 for source in sources {
224225 let path = source.path.to_path()?;
225삭제: let input = Input::open(&path)?;
226추가: let input = crate::resources::completed(Input::open(&path), check)?;
226227 plan.visit(path, source.archive_name.clone(), input, check)?;
227228 }
228229 let members = plan
229230 .items
230231 .iter()
231삭제: .map(|p| Member {
232삭제: entry: p.member.entry.clone(),
233삭제: data: Vec::new(),
232추가: .map(|p| {
233추가: crate::resources::completed(
234추가: Ok(Member {
235추가: entry: p.member.entry.clone(),
236추가: data: Vec::new(),
237추가: }),
238추가: check,
239추가: )
234240 })
235삭제: .collect::<Vec<_>>();
236삭제: archive::validate_members(&members)?;
241추가: .collect::<Result<Vec<_>>>()?;
242추가: archive::validate_members_with(&members, check)?;
237243 Ok(plan)
238244 }
239245 fn visit(
@@ -241,23 +247,36 @@ impl Plan {
241247 path: PathBuf,
242248 name: String,
243249 input: Input,
244삭제: check: &mut impl FnMut() -> Result<()>,
250추가: check: &mut impl crate::resources::Monitor,
245251 ) -> Result<()> {
246삭제: check()?;
252추가: check.check()?;
247253 if self.items.len() >= self.limits.entries as usize {
248254 return Err(ErrorCode::Limit);
249255 }
250삭제: let metadata: Metadata = input.file.metadata().map_err(crate::space::io_error)?;
256추가: let metadata: Metadata = crate::resources::completed(
257추가: input.file.metadata().map_err(crate::space::io_error),
258추가: check,
259추가: )?;
251260 let directory = metadata.is_dir();
252261 let name = archive::valid_name(&name, directory)?;
253삭제: self.budget.charge(&name)?;
254삭제: self.budget.charge(&path.to_string_lossy())?;
262추가: self.budget.charge_with(&name, check.metadata_limits())?;
263추가: self.budget
264추가: .charge_copy(&path.to_string_lossy(), check.metadata_limits())?;
255265 let size = if directory { 0 } else { metadata.len() };
256266 self.total = self
257267 .total
258268 .checked_add(size)
259269 .filter(|n| *n <= self.limits.input.min(self.limits.output))
260270 .ok_or(ErrorCode::Limit)?;
271추가: check.observe(
272추가: ResourceUsage {
273추가: estimated_bytes: Some(self.total),
274추가: actual_entries: Some(self.items.len() as u32 + 1),
275추가: ..ResourceUsage::default()
276추가: },
277추가: None,
278추가: )?;
279추가: crate::resources::completed(Ok(()), check)?;
261280 self.items.push(Planned {
262281 member: Member {
263282 entry: Entry {
@@ -275,13 +294,13 @@ impl Plan {
275294 data: Vec::new(),
276295 },
277296 path: path.clone(),
278삭제: object: filesystem::object(&input.file)?,
297추가: object: crate::resources::completed(filesystem::object(&input.file), check)?,
279298 modified: metadata.modified().ok(),
280299 });
281300 if directory {
282301 let mut children = Vec::new();
283302 for entry in input.children(&path)? {
284삭제: check()?;
303추가: check.check()?;
285304 if self.items.len() + children.len() >= self.limits.entries as usize {
286305 return Err(ErrorCode::Limit);
287306 }
@@ -290,21 +309,31 @@ impl Plan {
290309 .file_name()
291310 .into_string()
292311 .map_err(|_| ErrorCode::UnsafePath)?;
293삭제: self.budget.charge(&leaf)?;
312추가: self.budget.charge_copy(&leaf, check.metadata_limits())?;
294313 children.push(leaf);
314추가: check.observe(
315추가: ResourceUsage {
316추가: estimated_bytes: Some(self.total),
317추가: estimated_entries: Some((self.items.len() + children.len()) as u32),
318추가: ..ResourceUsage::default()
319추가: },
320추가: None,
321추가: )?;
322추가: crate::resources::completed(Ok(()), check)?;
295323 }
296324 children.sort();
297325 for leaf in children {
298삭제: let child = input.open_child(&path, &leaf)?;
326추가: let child = crate::resources::completed(input.open_child(&path, &leaf), check)?;
299327 self.visit(path.join(&leaf), format!("{name}/{leaf}"), child, check)?;
300328 }
301329 }
302330 Ok(())
303331 }
304삭제: pub fn verify(&self, check: &mut impl FnMut() -> Result<()>) -> Result<()> {
332추가: pub fn verify(&self, check: &mut impl crate::resources::Monitor) -> Result<()> {
305333 for item in &self.items {
306삭제: check()?;
334추가: check.check()?;
307335 item.open()?;
336추가: crate::resources::completed(Ok(()), check)?;
308337 }
309338 Ok(())
310339 }
수정experiments/rust-archive-worker/src/crypto.rs+18-15
@@ -16,11 +16,11 @@ fn keys(password: &[u8], salt: &[u8]) -> Zeroizing<[u8; 66]> {
1616 pbkdf2::pbkdf2_hmac::<Sha1>(password, salt, 1000, result.as_mut());
1717 result
1818}
19삭제: fn ctr(bytes: &mut [u8], key: &[u8], check: &mut impl FnMut() -> Result<()>) -> Result<()> {
19추가: fn ctr(bytes: &mut [u8], key: &[u8], check: &mut impl crate::resources::Monitor) -> Result<()> {
2020 let cipher = Aes256::new_from_slice(key).map_err(|_| ErrorCode::Internal)?;
2121 for (index, chunk) in bytes.chunks_mut(16).enumerate() {
2222 if index % 4096 == 0 {
23삭제: check()?;
23추가: check.check()?;
2424 }
2525 // WinZip은 1부터 시작하는 리틀엔디언 카운터를 사용함.
2626 let mut block = ((index as u128) + 1).to_le_bytes().into();
@@ -35,11 +35,11 @@ fn ctr(bytes: &mut [u8], key: &[u8], check: &mut impl FnMut() -> Result<()>) ->
3535fn authenticate(
3636 key: &[u8],
3737 bytes: &[u8],
38삭제: check: &mut impl FnMut() -> Result<()>,
38추가: check: &mut impl crate::resources::Monitor,
3939) -> Result<Sha1Mac> {
4040 let mut mac = <Sha1Mac as Mac>::new_from_slice(key).map_err(|_| ErrorCode::Internal)?;
4141 for chunk in bytes.chunks(65536) {
42삭제: check()?;
42추가: check.check()?;
4343 mac.update(chunk);
4444 }
4545 Ok(mac)
@@ -47,12 +47,12 @@ fn authenticate(
4747pub(crate) fn aes_decrypt(
4848 packed: &[u8],
4949 password: &[u8],
50삭제: check: &mut impl FnMut() -> Result<()>,
50추가: check: &mut impl crate::resources::Monitor,
5151) -> Result<Zeroizing<Vec<u8>>> {
5252 if packed.len() < 28 {
5353 return Err(ErrorCode::Integrity);
5454 }
55삭제: check()?;
55추가: check.check()?;
5656 let key = keys(password, &packed[..16]);
5757 if !bool::from(key[64..].ct_eq(&packed[16..18])) {
5858 return Err(ErrorCode::WrongPassword);
@@ -69,9 +69,9 @@ pub(crate) fn aes_decrypt(
6969pub(crate) fn aes_encrypt(
7070 packed: &[u8],
7171 password: &[u8],
72삭제: check: &mut impl FnMut() -> Result<()>,
72추가: check: &mut impl crate::resources::Monitor,
7373) -> Result<Vec<u8>> {
74삭제: check()?;
74추가: check.check()?;
7575 let mut salt = [0; 16];
7676 random(&mut salt)?;
7777 let key = keys(password, &salt);
@@ -138,7 +138,7 @@ pub(crate) fn zipcrypto_decrypt(
138138 packed: &[u8],
139139 password: &[u8],
140140 verifier: u8,
141삭제: check: &mut impl FnMut() -> Result<()>,
141추가: check: &mut impl crate::resources::Monitor,
142142) -> Result<Zeroizing<Vec<u8>>> {
143143 if packed.len() < 12 {
144144 return Err(ErrorCode::Integrity);
@@ -150,7 +150,7 @@ pub(crate) fn zipcrypto_decrypt(
150150 let mut out = Zeroizing::new(Vec::with_capacity(packed.len() - 12));
151151 for (index, &byte) in packed.iter().enumerate() {
152152 if index % 65536 == 0 {
153삭제: check()?;
153추가: check.check()?;
154154 }
155155 let temp = key[2] | 2;
156156 let plain = byte ^ ((temp.wrapping_mul(temp ^ 1) >> 8) as u8);
@@ -191,7 +191,7 @@ impl Decryptor {
191191 password: &[u8],
192192 aes: bool,
193193 verifier: u8,
194삭제: check: &mut impl FnMut() -> Result<()>,
194추가: check: &mut impl crate::resources::Monitor,
195195 ) -> Result<(Self, u64, u64)> {
196196 use std::io::{Read, Seek, SeekFrom};
197197 file.seek(SeekFrom::Start(offset))
@@ -212,12 +212,13 @@ impl Decryptor {
212212 let mut remaining = length - 28;
213213 let mut buffer = [0; 65536];
214214 while remaining != 0 {
215삭제: check()?;
215추가: check.check()?;
216216 let n = remaining.min(buffer.len() as u64) as usize;
217217 file.read_exact(&mut buffer[..n])
218218 .map_err(|_| ErrorCode::Integrity)?;
219219 mac.update(&buffer[..n]);
220220 remaining -= n as u64;
221추가: crate::resources::completed(Ok(()), check)?;
221222 }
222223 let mut tag = [0; 10];
223224 file.read_exact(&mut tag)
@@ -301,10 +302,10 @@ pub(crate) fn aes_encrypt_file(
301302 length: u64,
302303 output: &mut std::fs::File,
303304 password: &[u8],
304삭제: check: &mut impl FnMut() -> Result<()>,
305추가: check: &mut impl crate::resources::Monitor,
305306) -> Result<()> {
306307 use std::io::{Read, Write};
307삭제: check()?;
308추가: check.check()?;
308309 let mut salt = [0; 16];
309310 random(&mut salt)?;
310311 let key = keys(password, &salt);
@@ -323,17 +324,19 @@ pub(crate) fn aes_encrypt_file(
323324 let mut remaining = length;
324325 let mut buffer = Zeroizing::new([0; 65536]);
325326 while remaining != 0 {
326삭제: check()?;
327추가: check.check()?;
327328 let n = remaining.min(buffer.len() as u64) as usize;
328329 input
329330 .read_exact(&mut buffer[..n])
330331 .map_err(crate::space::io_error)?;
331332 cipher.apply(&mut buffer[..n]);
332333 mac.update(&buffer[..n]);
334추가: crate::space::ensure(output, n as u64)?;
333335 output
334336 .write_all(&buffer[..n])
335337 .map_err(crate::space::io_error)?;
336338 remaining -= n as u64;
339추가: crate::resources::completed(Ok(()), check)?;
337340 }
338341 output
339342 .write_all(&mac.finalize().into_bytes()[..10])
수정experiments/rust-archive-worker/src/filesystem.rs+145-36
@@ -1,5 +1,6 @@
11use crate::archive::valid_name;
22use crate::protocol::*;
3추가: use crate::resources::{Monitor, completed};
34use sha2::{Digest, Sha256};
45use std::fs::{File, OpenOptions};
56use std::io::{Read, Write};
@@ -90,7 +91,7 @@ pub fn object(file: &File) -> Result<SourceObject> {
9091pub fn snapshot(
9192 path: &Path,
9293 limit: u64,
93삭제: check: &mut impl FnMut() -> Result<()>,
94추가: check: &mut impl crate::resources::Monitor,
9495) -> Result<Snapshot> {
9596 let mut options = OpenOptions::new();
9697 options.read(true);
@@ -117,7 +118,7 @@ pub fn snapshot(
117118 let mut hash = Sha256::new();
118119 let mut buffer = [0; 65536];
119120 loop {
120삭제: check()?;
121추가: check.check()?;
121122 let n = file.read(&mut buffer).map_err(|_| ErrorCode::Io)?;
122123 if n == 0 {
123124 break;
@@ -128,6 +129,7 @@ pub fn snapshot(
128129 bytes.try_reserve(n).map_err(|_| ErrorCode::Limit)?;
129130 bytes.extend_from_slice(&buffer[..n]);
130131 hash.update(&buffer[..n]);
132추가: completed(Ok(()), check)?;
131133 }
132134 let after = file.metadata().map_err(|_| ErrorCode::Io)?;
133135 let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?;
@@ -493,12 +495,17 @@ mod platform {
493495#[cfg(not(any(target_os = "linux", windows)))]
494496compile_error!("Archive worker supports Linux and Windows only");
495497pub use platform::Dir;
496삭제: fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>> {
498추가: fn parent_with(
499추가: root: &Dir,
500추가: name: &str,
501추가: create: bool,
502추가: check: &mut impl Monitor,
503추가: ) -> Result<Option<(Dir, String)>> {
497504 let mut parts = name.split('/').collect::<Vec<_>>();
498505 let leaf = parts.pop().ok_or(ErrorCode::UnsafePath)?;
499506 let mut d = root.duplicate()?;
500507 for p in parts {
501삭제: match d.child(p, create)? {
508추가: match completed(d.child(p, create), check)? {
502509 Some(child) => d = child,
503510 None => return Ok(None),
504511 }
@@ -506,25 +513,46 @@ fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>>
506513 Ok(Some((d, leaf.to_owned())))
507514}
508515pub fn existing(root: &Dir, name: &str) -> Result<Option<Existing>> {
516추가: existing_with(root, name, &mut || Ok(()))
517추가: }
518추가: pub(crate) fn existing_with(
519추가: root: &Dir,
520추가: name: &str,
521추가: check: &mut impl Monitor,
522추가: ) -> Result<Option<Existing>> {
509523 valid_name(name, false)?;
510삭제: match parent(root, name, false)? {
524추가: let result = match parent_with(root, name, false, check)? {
511525 Some((dir, leaf)) => dir.existing(&leaf),
512526 None => Ok(None),
513삭제: }
527추가: };
528추가: completed(result, check)
514529}
515530pub fn unused(root: &Dir, name: &str) -> Result<bool> {
531추가: unused_with(root, name, &mut || Ok(()))
532추가: }
533추가: pub(crate) fn unused_with(root: &Dir, name: &str, check: &mut impl Monitor) -> Result<bool> {
516534 valid_name(name, false)?;
517삭제: match parent(root, name, false)? {
535추가: let result = match parent_with(root, name, false, check)? {
518536 Some((dir, leaf)) => dir.absent(&leaf),
519537 None => Ok(true),
520삭제: }
538추가: };
539추가: completed(result, check)
521540}
522541pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> {
523542 preflight_mode(root, names, false)
524543}
525544pub fn preflight_mode(root: &Dir, names: &[(String, EntryKind)], interactive: bool) -> Result<()> {
545추가: preflight_mode_with(root, names, interactive, &mut || Ok(()))
546추가: }
547추가: pub(crate) fn preflight_mode_with(
548추가: root: &Dir,
549추가: names: &[(String, EntryKind)],
550추가: interactive: bool,
551추가: check: &mut impl Monitor,
552추가: ) -> Result<()> {
526553 for (name, kind) in names {
527삭제: if let Some((d, leaf)) = parent(root, name, false)? {
554추가: check.check()?;
555추가: if let Some((d, leaf)) = parent_with(root, name, false, check)? {
528556 if *kind == EntryKind::Directory {
529557 let _ = d.child(&leaf, false)?;
530558 } else if interactive {
@@ -533,13 +561,15 @@ pub fn preflight_mode(root: &Dir, names: &[(String, EntryKind)], interactive: bo
533561 return Err(ErrorCode::Conflict);
534562 }
535563 }
564추가: completed(Ok(()), check)?;
536565 }
537566 Ok(())
538567}
539삭제: pub(crate) fn preflight_space(
568추가: pub(crate) fn preflight_space_with(
540569 root: &Dir,
541570 files: &[(String, u64)],
542571 staging: Option<(&File, u64)>,
572추가: check: &mut impl Monitor,
543573) -> Result<()> {
544574 let mut volumes = std::collections::BTreeMap::<u64, (File, u64)>::new();
545575 let mut charge = |file: &File, bytes: u64| -> Result<()> {
@@ -556,7 +586,7 @@ pub(crate) fn preflight_space(
556586 Ok(())
557587 };
558588 if let Some((file, bytes)) = staging {
559삭제: charge(file, bytes)?;
589추가: completed(charge(file, bytes), check)?;
560590 }
561591 for (name, size) in files {
562592 valid_name(name, false)?;
@@ -564,26 +594,38 @@ pub(crate) fn preflight_space(
564594 let mut parts = name.split('/').collect::<Vec<_>>();
565595 parts.pop();
566596 for part in parts {
567삭제: match parent.child(part, false)? {
597추가: match completed(parent.child(part, false), check)? {
568598 Some(child) => parent = child,
569599 None => break,
570600 }
571601 }
572삭제: charge(parent.handle(), *size)?;
602추가: completed(charge(parent.handle(), *size), check)?;
573603 }
574604 for (file, bytes) in volumes.values() {
575삭제: crate::space::ensure(file, *bytes)?;
605추가: completed(crate::space::ensure(file, *bytes), check)?;
576606 }
577607 Ok(())
578608}
579609pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability, Option<ErrorCode>)> {
580삭제: let (d, leaf) = parent(root, name, false)?.ok_or(ErrorCode::Io)?;
581삭제: if d.child(&leaf, false)?.is_some() {
610추가: directory_with(root, name, &mut || Ok(()))
611추가: }
612추가: pub(crate) fn directory_with(
613추가: root: &Dir,
614추가: name: &str,
615추가: check: &mut impl Monitor,
616추가: ) -> Result<(bool, Durability, Option<ErrorCode>)> {
617추가: let (d, leaf) = parent_with(root, name, false, check)?.ok_or(ErrorCode::Io)?;
618추가: if completed(d.child(&leaf, false), check)?.is_some() {
582619 return Ok((false, Durability::NotApplicable, None));
583620 }
584621 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
622추가: let progress_error = completed(Ok(()), check).err();
585623 Ok(match d.sync_checked() {
586삭제: Ok(durability) => (true, durability, None),
624추가: Ok(durability) => (
625추가: true,
626추가: durability,
627추가: progress_error.or_else(|| completed(Ok(()), check).err()),
628추가: ),
587629 Err(error) => (true, Durability::Failed, Some(error)),
588630 })
589631}
@@ -627,6 +669,43 @@ pub fn publish_reader_mode(
627669 length: u64,
628670 replace: Option<&Existing>,
629671 check: &mut impl FnMut(bool) -> Result<()>,
672추가: ) -> Published {
673추가: publish_reader_steps(root, name, data, length, replace, &mut |step| match step {
674추가: PublishStep::Check => check(false),
675추가: PublishStep::Commit => check(true),
676추가: PublishStep::Activity => Ok(()),
677추가: })
678추가: }
679추가: pub(crate) enum PublishStep {
680추가: Check,
681추가: Activity,
682추가: Commit,
683추가: }
684추가: struct PublicationMonitor<'a, F>(&'a mut F);
685추가: impl<F: FnMut(PublishStep) -> Result<()>> Monitor for PublicationMonitor<'_, F> {
686추가: fn check(&mut self) -> Result<()> {
687추가: self.0(PublishStep::Check)
688추가: }
689추가: fn activity(&mut self) -> Result<()> {
690추가: self.0(PublishStep::Activity)
691추가: }
692추가: }
693추가: fn publication_activity(
694추가: finish: &mut Result<()>,
695추가: check: &mut impl FnMut(PublishStep) -> Result<()>,
696추가: ) {
697추가: let progress = completed(Ok(()), &mut PublicationMonitor(check));
698추가: if finish.is_ok() {
699추가: *finish = progress;
700추가: }
701추가: }
702추가: pub(crate) fn publish_reader_steps(
703추가: root: &Dir,
704추가: name: &str,
705추가: data: &mut impl Read,
706추가: length: u64,
707추가: replace: Option<&Existing>,
708추가: check: &mut impl FnMut(PublishStep) -> Result<()>,
630709) -> Published {
631710 let mut result = Published {
632711 created: false,
@@ -639,7 +718,8 @@ pub fn publish_reader_mode(
639718 };
640719 let prepared = (|| {
641720 valid_name(name, false)?;
642삭제: let (dir, leaf) = parent(root, name, true)?.ok_or(ErrorCode::Io)?;
721추가: let (dir, leaf) =
722추가: parent_with(root, name, true, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?;
643723 let temp = format!(
644724 ".zipelo-{}-{}.tmp",
645725 std::process::id(),
@@ -653,30 +733,49 @@ pub fn publish_reader_mode(
653733 }
654734 })?;
655735 let written = (|| {
656삭제: crate::space::ensure(&file, length)?;
736추가: completed(Ok(()), &mut PublicationMonitor(check))?;
737추가: completed(
738추가: crate::space::ensure(&file, length),
739추가: &mut PublicationMonitor(check),
740추가: )?;
657741 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
658742 let mut remaining = length;
659743 while remaining != 0 {
660삭제: check(false)?;
744추가: check(PublishStep::Check)?;
661745 let count = remaining.min(buffer.len() as u64) as usize;
662746 let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?;
663747 if n == 0 {
664748 return Err(ErrorCode::Io);
665749 }
666삭제: file.write_all(&buffer[..n])
667삭제: .map_err(crate::space::io_error)?;
750추가: completed(Ok(()), &mut PublicationMonitor(check))?;
751추가: completed(
752추가: crate::space::ensure(&file, n as u64),
753추가: &mut PublicationMonitor(check),
754추가: )?;
755추가: completed(
756추가: file.write_all(&buffer[..n]).map_err(crate::space::io_error),
757추가: &mut PublicationMonitor(check),
758추가: )?;
668759 remaining -= n as u64;
669760 }
670삭제: file.sync_all().map_err(crate::space::io_error)
761추가: completed(
762추가: file.sync_all().map_err(crate::space::io_error),
763추가: &mut PublicationMonitor(check),
764추가: )
671765 })();
672삭제: let closed = close(file).map_err(crate::space::io_error);
766추가: let closed = completed(
767추가: close(file).map_err(crate::space::io_error),
768추가: &mut PublicationMonitor(check),
769추가: );
673770 let mut finish = written.and(closed).and_then(|_| {
674771 if let Some(expected) = replace {
675삭제: if dir.existing(&leaf)?.as_ref() != Some(expected) {
772추가: if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref()
773추가: != Some(expected)
774추가: {
676775 return Err(ErrorCode::Conflict);
677776 }
678777 }
679삭제: check(true)
778추가: check(PublishStep::Commit)
680779 });
681780 let mut temp_consumed = false;
682781 if finish.is_ok() {
@@ -689,8 +788,12 @@ pub fn publish_reader_mode(
689788 Ok(()) => {
690789 temp_consumed = replace.is_some();
691790 result.created = true;
791추가: publication_activity(&mut finish, check);
692792 match dir.sync_checked() {
693삭제: Ok(durability) => result.durability = durability,
793추가: Ok(durability) => {
794추가: result.durability = durability;
795추가: publication_activity(&mut finish, check);
796추가: }
694797 Err(error) => {
695798 result.durability = Durability::Failed;
696799 finish = Err(error);
@@ -707,21 +810,27 @@ pub fn publish_reader_mode(
707810 }
708811 }
709812 }
710삭제: if !temp_consumed && !dir.remove(&temp) {
711삭제: result.cleanup = Cleanup::Failed;
712삭제: result.retained = 1;
713삭제: result.retained_name = Some(match name.rsplit_once('/') {
714삭제: Some((prefix, _)) => format!("{prefix}/{temp}"),
715삭제: None => temp.clone(),
716삭제: });
717삭제: if finish.is_ok() {
718삭제: finish = Err(ErrorCode::Io);
813추가: if !temp_consumed {
814추가: if dir.remove(&temp) {
815추가: publication_activity(&mut finish, check);
816추가: } else {
817추가: result.cleanup = Cleanup::Failed;
818추가: result.retained = 1;
819추가: result.retained_name = Some(match name.rsplit_once('/') {
820추가: Some((prefix, _)) => format!("{prefix}/{temp}"),
821추가: None => temp.clone(),
822추가: });
823추가: if finish.is_ok() {
824추가: finish = Err(ErrorCode::Io);
825추가: }
719826 }
720827 }
721828 if result.created {
722829 if let Err(error) = dir.sync_checked() {
723830 result.durability = Durability::Failed;
724831 finish = Err(error);
832추가: } else {
833추가: publication_activity(&mut finish, check);
725834 }
726835 }
727836 finish
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -7,6 +7,7 @@ pub mod filesystem;
77mod lzma;
88mod parent;
99pub mod protocol;
10추가: pub mod resources;
1011pub mod runtime;
1112mod seven_zip;
1213mod space;
수정experiments/rust-archive-worker/src/lzma.rs+18-4
@@ -26,6 +26,7 @@ impl<'a> History<'a> {
2626 }
2727 fn flush(&mut self) -> Result<()> {
2828 use std::io::Write;
29추가: crate::space::ensure(self.file, self.pending.len() as u64)?;
2930 self.file
3031 .write_all(&self.pending)
3132 .map_err(crate::space::io_error)?;
@@ -405,13 +406,25 @@ impl Model {
405406 dictionary: usize,
406407 target: u64,
407408 eos: bool,
408삭제: check: &mut impl FnMut() -> Result<()>,
409추가: check: &mut impl crate::resources::Monitor,
409410 ) -> Result<()> {
410411 let mut range = Range::new(input, length)?;
411412 let mut next_check = out.len();
412413 while out.len() < target {
413414 if out.len() >= next_check {
414삭제: check()?;
415추가: check.check()?;
416추가: if out.len() > next_check.saturating_sub(65536) {
417추가: crate::resources::completed(Ok(()), check)?;
418추가: }
419추가: check.observe(
420추가: crate::protocol::ResourceUsage {
421추가: actual_bytes: Some(
422추가: out.base.checked_add(out.len()).ok_or(ErrorCode::Limit)?,
423추가: ),
424추가: ..crate::protocol::ResourceUsage::default()
425추가: },
426추가: Some(out.file),
427추가: )?;
415428 next_check = out.len() + 65536;
416429 }
417430 if self.symbol(&mut range, out, history, dictionary, target)? {
@@ -442,7 +455,7 @@ pub(crate) fn decode_stream(
442455 lzma2: bool,
443456 size: u64,
444457 output: &mut std::fs::File,
445삭제: check: &mut impl FnMut() -> Result<()>,
458추가: check: &mut impl crate::resources::Monitor,
446459) -> Result<()> {
447460 use std::io::{BufReader, Read};
448461 crate::space::ensure(output, size)?;
@@ -492,8 +505,9 @@ pub(crate) fn decode_stream(
492505 let mut need_state = true;
493506 let mut model: Option<Model> = None;
494507 loop {
495삭제: check()?;
508추가: check.check()?;
496509 let control = byte(&mut reader)?;
510추가: crate::resources::completed(Ok(()), check)?;
497511 if control == 0 {
498512 let mut extra = [0];
499513 if reader.read(&mut extra).map_err(crate::space::io_error)? != 0 || out.len() != size {
수정experiments/rust-archive-worker/src/protocol.rs+52-0
@@ -82,6 +82,44 @@ impl Limits {
8282 && self.entries <= hard.entries
8383 }
8484}
85추가: #[derive(Clone, Debug, PartialEq, Eq)]
86추가: pub struct GuardedStart {
87추가: pub start: Start,
88추가: pub ceiling: Limits,
89추가: pub interactive: bool,
90추가: }
91추가: impl GuardedStart {
92추가: pub fn valid(&self) -> bool {
93추가: self.start.limits.valid()
94추가: && self.ceiling.input == self.start.limits.input
95추가: && self.ceiling.output >= self.start.limits.output
96추가: && self.ceiling.output <= 64 * 1024 * 1024 * 1024
97추가: && self.ceiling.entries >= self.start.limits.entries
98추가: && self.ceiling.entries <= 200_000
99추가: && (!self.interactive || matches!(self.start.action, Action::Extract { .. }))
100추가: }
101추가: }
102추가: #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
103추가: pub struct ResourceScope {
104추가: pub output: bool,
105추가: pub entries: bool,
106추가: pub ratio: bool,
107추가: }
108추가: impl ResourceScope {
109추가: pub fn any(self) -> bool {
110추가: self.output || self.entries || self.ratio
111추가: }
112추가: }
113추가: #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
114추가: pub struct ResourceUsage {
115추가: pub estimated_bytes: Option<u64>,
116추가: pub actual_bytes: Option<u64>,
117추가: pub estimated_entries: Option<u32>,
118추가: pub actual_entries: Option<u32>,
119추가: pub compressed_bytes: Option<u64>,
120추가: pub ratio_output_bytes: Option<u64>,
121추가: pub available_bytes: Option<u64>,
122추가: }
85123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86124pub enum Format {
87125 Zip,
@@ -292,6 +330,20 @@ pub enum Message {
292330 },
293331 Cancel,
294332 StartInteractive(Start),
333추가: StartGuarded(GuardedStart),
334추가: ResourceReply {
335추가: challenge_id: u64,
336추가: scope: ResourceScope,
337추가: allow: bool,
338추가: },
339추가: ResourceRequired {
340추가: challenge_id: u64,
341추가: action: ActionKind,
342추가: scope: ResourceScope,
343추가: usage: ResourceUsage,
344추가: soft_limits: Limits,
345추가: ceiling: Limits,
346추가: },
295347 ConflictReply {
296348 challenge_id: u64,
297349 choice: ConflictChoice,
추가experiments/rust-archive-worker/src/resources.rs+139-0
@@ -0,0 +1,139 @@
1추가: use crate::protocol::*;
2추가: use std::time::Duration;
3추가:
4추가: type Result<T> = std::result::Result<T, ErrorCode>;
5추가:
6추가: pub trait Monitor {
7추가: fn metadata_limits(&self) -> crate::archive::MetadataLimits {
8추가: crate::archive::MetadataLimits::default()
9추가: }
10추가: fn check(&mut self) -> Result<()>;
11추가: fn activity(&mut self) -> Result<()> {
12추가: self.check()
13추가: }
14추가: fn observe(&mut self, _usage: ResourceUsage, _storage: Option<&std::fs::File>) -> Result<()> {
15추가: self.check()
16추가: }
17추가: }
18추가: impl<F: FnMut() -> Result<()>> Monitor for F {
19추가: fn check(&mut self) -> Result<()> {
20추가: self()
21추가: }
22추가: }
23추가:
24추가: pub(crate) fn completed<T>(result: Result<T>, check: &mut impl Monitor) -> Result<T> {
25추가: let value = result?;
26추가: check.activity()?;
27추가: Ok(value)
28추가: }
29추가:
30추가: pub(crate) struct MetadataMonitor<'a, M>(pub &'a mut M);
31추가: impl<M: Monitor> Monitor for MetadataMonitor<'_, M> {
32추가: fn metadata_limits(&self) -> crate::archive::MetadataLimits {
33추가: self.0.metadata_limits()
34추가: }
35추가: fn check(&mut self) -> Result<()> {
36추가: self.0.check()
37추가: }
38추가: fn activity(&mut self) -> Result<()> {
39추가: self.0.activity()
40추가: }
41추가: fn observe(&mut self, usage: ResourceUsage, _storage: Option<&std::fs::File>) -> Result<()> {
42추가: self.check()?;
43추가: // 압축 헤더는 메타데이터 상한만 적용하며 파일 출력량에 합치지 않음.
44추가: if usage
45추가: .estimated_bytes
46추가: .into_iter()
47추가: .chain(usage.actual_bytes)
48추가: .any(|bytes| bytes > self.metadata_limits().bytes as u64)
49추가: {
50추가: return Err(ErrorCode::Limit);
51추가: }
52추가: Ok(())
53추가: }
54추가: }
55추가:
56추가: pub(crate) struct Budget {
57추가: pub soft: Limits,
58추가: pub ceiling: Limits,
59추가: pub granted: ResourceScope,
60추가: }
61추가: impl Budget {
62추가: pub fn metadata_limits(&self) -> crate::archive::MetadataLimits {
63추가: if self.granted.any() {
64추가: crate::archive::MetadataLimits::approved()
65추가: } else {
66추가: crate::archive::MetadataLimits::default()
67추가: }
68추가: }
69추가: pub fn required(&self, usage: ResourceUsage) -> Result<ResourceScope> {
70추가: let bytes = usage
71추가: .estimated_bytes
72추가: .into_iter()
73추가: .chain(usage.actual_bytes)
74추가: .max();
75추가: let entries = usage
76추가: .estimated_entries
77추가: .into_iter()
78추가: .chain(usage.actual_entries)
79추가: .max();
80추가: if bytes.is_some_and(|n| n > self.ceiling.output)
81추가: || entries.is_some_and(|n| n > self.ceiling.entries)
82추가: {
83추가: return Err(ErrorCode::Limit);
84추가: }
85추가: let ratio = match (usage.ratio_output_bytes, usage.compressed_bytes) {
86추가: (Some(output), Some(input)) => {
87추가: output >= 256 * 1024 * 1024 && u128::from(output) > u128::from(input) * 1000
88추가: }
89추가: _ => false,
90추가: };
91추가: Ok(ResourceScope {
92추가: output: !self.granted.output && bytes.is_some_and(|n| n > self.soft.output),
93추가: entries: !self.granted.entries && entries.is_some_and(|n| n > self.soft.entries),
94추가: ratio: !self.granted.ratio && ratio,
95추가: })
96추가: }
97추가: pub fn grant(&mut self, scope: ResourceScope) {
98추가: self.granted.output |= scope.output;
99추가: self.granted.entries |= scope.entries;
100추가: self.granted.ratio |= scope.ratio;
101추가: }
102추가: }
103추가:
104추가: pub(crate) struct Watchdog {
105추가: last_activity: Duration,
106추가: approved: bool,
107추가: }
108추가: impl Watchdog {
109추가: pub fn new() -> Self {
110추가: Self {
111추가: last_activity: Duration::ZERO,
112추가: approved: false,
113추가: }
114추가: }
115추가: pub fn check(&self, elapsed: Duration) -> Result<()> {
116추가: if if self.approved {
117추가: elapsed.saturating_sub(self.last_activity) >= Duration::from_secs(60)
118추가: } else {
119추가: elapsed > Duration::from_secs(300)
120추가: } {
121추가: Err(ErrorCode::Limit)
122추가: } else {
123추가: Ok(())
124추가: }
125추가: }
126추가: pub fn activity(&mut self, elapsed: Duration) -> Result<()> {
127추가: self.check(elapsed)?;
128추가: self.last_activity = elapsed;
129추가: Ok(())
130추가: }
131추가: pub fn resume(&mut self, elapsed: Duration, approved: bool) {
132추가: self.approved |= approved;
133추가: self.last_activity = elapsed;
134추가: }
135추가: }
136추가:
137추가: #[cfg(test)]
138추가: #[path = "../../../tests/rust-archive-worker/resource_budget.rs"]
139추가: mod tests;
수정experiments/rust-archive-worker/src/runtime.rs+280-106
@@ -2,6 +2,7 @@ use crate::{
22 archive,
33 filesystem::{self, Dir},
44 protocol::*,
5추가: resources::{Budget, Monitor, Watchdog, completed},
56 wire::{Reader, Writer},
67};
78use std::{
@@ -16,6 +17,7 @@ type Result<T> = std::result::Result<T, ErrorCode>;
1617enum Challenge {
1718 Password(u64),
1819 Conflict(u64),
20추가: Resource(u64, ResourceScope),
1921}
2022struct State<W> {
2123 writer: Writer<W>,
@@ -25,6 +27,7 @@ struct State<W> {
2527 challenge: Option<Challenge>,
2628 conflict_reply: Option<(ConflictChoice, bool)>,
2729 password: Option<Secret>,
30추가: resource_reply: Option<bool>,
2831 input_closed: bool,
2932}
3033struct Job<W> {
@@ -32,12 +35,79 @@ struct Job<W> {
3235 wake: Arc<Condvar>,
3336 next_challenge: u64,
3437 interactive: bool,
38추가: action: ActionKind,
39추가: budget: Option<Budget>,
40추가: watchdog: Watchdog,
3541 remaining_choice: Option<ConflictChoice>,
3642 started: Instant,
3743 terminal: Terminal,
3844 parent: crate::parent::Parent,
3945}
4046impl<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추가: }
41111 fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> {
42112 self.check()?;
43113 self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?;
@@ -53,6 +123,7 @@ impl<W: Write> Job<W> {
53123 purpose,
54124 })
55125 .map_err(|_| ErrorCode::Io)?;
126추가: let waiting = Instant::now();
56127 loop {
57128 self.parent.check()?;
58129 if let Some(error) = state.fault {
@@ -62,12 +133,17 @@ impl<W: Write> Job<W> {
62133 return Err(ErrorCode::None);
63134 }
64135 if let Some(secret) = state.password.take() {
136추가: self.watchdog.resume(self.started.elapsed(), false);
65137 return Ok(secret);
66138 }
67139 if state.input_closed {
68140 return Err(ErrorCode::Protocol);
69141 }
70삭제: if self.started.elapsed() > Duration::from_secs(300) {
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추가: } {
71147 return Err(ErrorCode::Limit);
72148 }
73149 state = self
@@ -98,6 +174,7 @@ impl<W: Write> Job<W> {
98174 existing_size,
99175 })
100176 .map_err(|_| ErrorCode::Io)?;
177추가: let waiting = Instant::now();
101178 loop {
102179 self.parent.check()?;
103180 if let Some(error) = state.fault {
@@ -110,12 +187,17 @@ impl<W: Write> Job<W> {
110187 if apply {
111188 self.remaining_choice = Some(choice);
112189 }
190추가: self.watchdog.resume(self.started.elapsed(), false);
113191 return Ok(choice);
114192 }
115193 if state.input_closed {
116194 return Err(ErrorCode::Protocol);
117195 }
118삭제: if self.started.elapsed() > Duration::from_secs(300) {
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추가: } {
119201 return Err(ErrorCode::Limit);
120202 }
121203 state = self
@@ -151,9 +233,10 @@ impl<W: Write> Job<W> {
151233 format!("{prefix}/{leaf}")
152234 };
153235 archive::valid_name(&candidate, false)?;
154삭제: if !reserved.contains(&candidate.to_lowercase())
155삭제: && filesystem::unused(root, &candidate)?
156삭제: {
236추가: let unused = !reserved.contains(&candidate.to_lowercase())
237추가: && filesystem::unused_with(root, &candidate, self)?;
238추가: completed(Ok(()), self)?;
239추가: if unused {
157240 return Ok(candidate);
158241 }
159242 }
@@ -168,9 +251,6 @@ impl<W: Write> Job<W> {
168251 }
169252 fn check(&mut self) -> Result<()> {
170253 self.parent.check()?;
171삭제: if self.started.elapsed() > Duration::from_secs(300) {
172삭제: return Err(ErrorCode::Limit);
173삭제: }
174254 let state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
175255 if let Some(error) = state.fault {
176256 return Err(error);
@@ -178,7 +258,7 @@ impl<W: Write> Job<W> {
178258 if state.cancelled && state.phase == 0 {
179259 return Err(ErrorCode::None);
180260 }
181삭제: Ok(())
261추가: self.watchdog.check(self.started.elapsed())
182262 }
183263 fn cutoff(&mut self) -> Result<()> {
184264 self.check()?;
@@ -220,11 +300,12 @@ impl<W: Write> Job<W> {
220300 Some(length),
221301 self.terminal.created_count as u32,
222302 )?;
223삭제: let p = filesystem::publish_reader_mode(root, name, data, length, replace, &mut |commit| {
224삭제: if commit && last {
225삭제: self.cutoff()
226삭제: } else {
227삭제: self.check()
303추가: let p = filesystem::publish_reader_steps(root, name, data, length, replace, &mut |step| {
304추가: match step {
305추가: filesystem::PublishStep::Check => self.check(),
306추가: filesystem::PublishStep::Activity => completed(Ok(()), self),
307추가: filesystem::PublishStep::Commit if last => self.cutoff(),
308추가: filesystem::PublishStep::Commit => self.check(),
228309 }
229310 });
230311 self.terminal.retained_partial_count += p.retained;
@@ -266,17 +347,32 @@ impl<W: Write> Job<W> {
266347 if let Some(error) = p.error {
267348 return Err(error);
268349 }
350추가: if p.created {
351추가: completed(Ok(()), self)?;
352추가: }
269353 Ok(())
270354 }
271355 fn run(&mut self, start: Start) -> Result<()> {
272356 if !start.limits.valid() {
273357 return Err(ErrorCode::InvalidRequest);
274358 }
359추가: let limits = self.budget.as_ref().map_or(start.limits, |b| b.ceiling);
275360 self.event(Message::Accepted {
276361 action: start.action.kind(),
277362 encryption: true,
278363 })?;
279364 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추가: }
280376 match start.action {
281377 Action::List {
282378 archive: ref source,
@@ -288,16 +384,16 @@ impl<W: Write> Job<W> {
288384 let extract = matches!(start.action, Action::Extract { .. });
289385 let path = source.to_path()?;
290386 self.progress(Stage::Read, 0, None, 0)?;
291삭제: let mut snapshot = crate::spool::Snapshot::open_reporting(
292삭제: &path,
293삭제: start.limits.input,
294삭제: &mut |step| match step {
295삭제: crate::spool::Step::Check => self.check(),
296삭제: crate::spool::Step::Read { bytes, total } => {
297삭제: self.progress(Stage::Read, bytes, Some(total), 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::Activity => completed(Ok(()), self),
392추가: crate::spool::Step::Read { bytes, total } => {
393추가: self.progress(Stage::Read, bytes, Some(total), 0)
394추가: }
298395 }
299삭제: },
300삭제: )?;
396추가: })?;
301397 if let Action::Extract {
302398 list_id: Some(expected),
303399 ..
@@ -315,10 +411,10 @@ impl<W: Write> Job<W> {
315411 let mut catalog = crate::streaming::Catalog::open(
316412 &mut snapshot.file,
317413 snapshot.len,
318삭제: start.limits,
414추가: limits,
319415 false,
320416 None,
321삭제: &mut || self.check(),
417추가: self,
322418 )?;
323419 let list_id = ListId {
324420 catalog_version: 1,
@@ -330,12 +426,15 @@ impl<W: Write> Job<W> {
330426 if !extract {
331427 for member in &catalog.members {
332428 self.check()?;
333삭제: self.event(Message::Entry(member.entry.clone()))?;
429추가: completed(self.event(Message::Entry(member.entry.clone())), self)?;
334430 }
335삭제: self.event(Message::ListEnd {
336삭제: entry_count: catalog.members.len() as u32,
337삭제: list_id,
338삭제: })?;
431추가: completed(
432추가: self.event(Message::ListEnd {
433추가: entry_count: catalog.members.len() as u32,
434추가: list_id,
435추가: }),
436추가: self,
437추가: )?;
339438 } else if let Action::Extract {
340439 destination,
341440 selection,
@@ -353,24 +452,24 @@ impl<W: Write> Job<W> {
353452 let selected = match selection {
354453 Selection::All => None,
355454 Selection::EntryIds(ids) => {
356삭제: let n = ids.len();
357삭제: let set = ids.into_iter().collect::<BTreeSet<_>>();
358삭제: if expected.is_none()
359삭제: || set.is_empty()
360삭제: || n != set.len()
361삭제: || set.iter().any(|id| *id as usize >= catalog.members.len())
362삭제: {
455추가: if expected.is_none() || ids.is_empty() {
363456 return Err(ErrorCode::InvalidRequest);
364457 }
458추가: let mut set = BTreeSet::new();
459추가: for id in ids {
460추가: if id as usize >= catalog.members.len() || !set.insert(id) {
461추가: return Err(ErrorCode::InvalidRequest);
462추가: }
463추가: completed(Ok(()), self)?;
464추가: }
365465 Some(set)
366466 }
367467 };
368삭제: if catalog
369삭제: .members
370삭제: .iter()
371삭제: .any(|m| !matches!(m.entry.kind, EntryKind::File | EntryKind::Directory))
372삭제: {
373삭제: return Err(ErrorCode::UnsafePath);
468추가: for member in &catalog.members {
469추가: if !matches!(member.entry.kind, EntryKind::File | EntryKind::Directory) {
470추가: return Err(ErrorCode::UnsafePath);
471추가: }
472추가: completed(Ok(()), self)?;
374473 }
375474 if catalog.format == Format::Gzip {
376475 let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?;
@@ -383,36 +482,33 @@ impl<W: Write> Job<W> {
383482 } else if gzip_output_name.is_some() {
384483 return Err(ErrorCode::InvalidRequest);
385484 }
386삭제: let root = Dir::root(&destination.to_path()?)?;
387삭제: let output_sizes = catalog
388삭제: .members
389삭제: .iter()
390삭제: .filter(|m| {
391삭제: m.entry.kind == EntryKind::File
392삭제: && selected
393삭제: .as_ref()
394삭제: .is_none_or(|s| s.contains(&m.entry.entry_id))
395삭제: })
396삭제: .map(|m| (m.entry.name.clone(), m.entry.size))
397삭제: .collect::<Vec<_>>();
398삭제: let staged = if matches!(catalog.format, Format::Zip | Format::SevenZip) {
399삭제: Some((
400삭제: &catalog.data,
401삭제: catalog.members.iter().try_fold(0u64, |sum, m| {
402삭제: sum.checked_add(m.entry.size).ok_or(ErrorCode::Limit)
403삭제: })?,
404삭제: ))
405삭제: } else {
406삭제: None
407삭제: };
485추가: let root = completed(Dir::root(&destination.to_path()?), self)?;
486추가: let mut output_sizes = Vec::new();
487추가: let mut staged_total = 0u64;
488추가: let mut encrypted = false;
489추가: for member in &catalog.members {
490추가: if member.entry.kind == EntryKind::File
491추가: && selected
492추가: .as_ref()
493추가: .is_none_or(|s| s.contains(&member.entry.entry_id))
494추가: {
495추가: output_sizes.push((member.entry.name.clone(), member.entry.size));
496추가: }
497추가: staged_total = staged_total
498추가: .checked_add(member.entry.size)
499추가: .ok_or(ErrorCode::Limit)?;
500추가: encrypted |= member.entry.encrypted;
501추가: completed(Ok(()), self)?;
502추가: }
503추가: let staged = matches!(catalog.format, Format::Zip | Format::SevenZip)
504추가: .then_some((&catalog.data, staged_total));
408505 // 선택 전에는 검증에 필요한 스테이징 공간만 계산함.
409506 let initial_outputs = if self.interactive {
410507 &[][..]
411508 } else {
412509 &output_sizes[..]
413510 };
414삭제: filesystem::preflight_space(&root, initial_outputs, staged)?;
415삭제: let encrypted = catalog.members.iter().any(|m| m.entry.encrypted);
511추가: filesystem::preflight_space_with(&root, initial_outputs, staged, self)?;
416512 if matches!(catalog.format, Format::Zip | Format::SevenZip) {
417513 for attempt in 1..=3 {
418514 let secret = if encrypted {
@@ -423,10 +519,10 @@ impl<W: Write> Job<W> {
423519 match crate::streaming::Catalog::open(
424520 &mut snapshot.file,
425521 snapshot.len,
426삭제: start.limits,
522추가: limits,
427523 true,
428524 secret.as_ref().map(|s| s.0.as_slice()),
429삭제: &mut || self.check(),
525추가: self,
430526 ) {
431527 Ok(decoded) => {
432528 catalog = decoded;
@@ -439,41 +535,46 @@ impl<W: Write> Job<W> {
439535 }
440536 let offsets = catalog.offsets;
441537 let mut data = catalog.data;
442삭제: let members = catalog
443삭제: .members
444삭제: .into_iter()
445삭제: .filter(|m| {
446삭제: selected
447삭제: .as_ref()
448삭제: .is_none_or(|s| s.contains(&m.entry.entry_id))
449삭제: })
450삭제: .collect::<Vec<_>>();
451삭제: let dirs = archive::output_directories(&members)?;
538추가: let mut members = Vec::new();
539추가: for member in catalog.members {
540추가: if selected
541추가: .as_ref()
542추가: .is_none_or(|s| s.contains(&member.entry.entry_id))
543추가: {
544추가: members.push(member);
545추가: }
546추가: completed(Ok(()), self)?;
547추가: }
548추가: let dirs = archive::output_directories(&members, self)?;
452549 let files = members
453550 .iter()
454551 .filter(|m| m.entry.kind == EntryKind::File)
455삭제: .collect::<Vec<_>>();
552추가: .map(|member| completed(Ok(member), self))
553추가: .collect::<Result<Vec<_>>>()?;
456554 let mut names = dirs
457555 .iter()
458삭제: .map(|n| (n.clone(), EntryKind::Directory))
459삭제: .collect::<Vec<_>>();
556추가: .map(|name| completed(Ok((name.clone(), EntryKind::Directory)), self))
557추가: .collect::<Result<Vec<_>>>()?;
460558 names.extend(
461559 files
462560 .iter()
463삭제: .map(|m| (m.entry.name.clone(), EntryKind::File)),
561추가: .map(|member| {
562추가: completed(Ok((member.entry.name.clone(), EntryKind::File)), self)
563추가: })
564추가: .collect::<Result<Vec<_>>>()?,
464565 );
465삭제: filesystem::preflight_mode(&root, &names, self.interactive)?;
566추가: filesystem::preflight_mode_with(&root, &names, self.interactive, self)?;
466567 if !self.interactive {
467삭제: filesystem::preflight_space(&root, &output_sizes, None)?;
568추가: filesystem::preflight_space_with(&root, &output_sizes, None, self)?;
468569 }
469570 let mut reserved = names
470571 .iter()
471삭제: .map(|(name, _)| name.to_lowercase())
472삭제: .collect::<BTreeSet<_>>();
572추가: .map(|(name, _)| completed(Ok(name.to_lowercase()), self))
573추가: .collect::<Result<BTreeSet<_>>>()?;
473574 for name in dirs {
474575 self.check()?;
475576 let (created, durability, sync_error) =
476삭제: filesystem::directory(&root, &name)?;
577추가: filesystem::directory_with(&root, &name, self)?;
477578 if created {
478579 self.terminal.created_count += 1;
479580 self.terminal.publication = Publication::Partial;
@@ -486,14 +587,18 @@ impl<W: Write> Job<W> {
486587 if let Some(error) = sync_error {
487588 return Err(error);
488589 }
590추가: completed(Ok(()), self)?;
489591 }
490592 }
491593 for (index, m) in files.iter().enumerate() {
492삭제: data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize]))
493삭제: .map_err(|_| ErrorCode::Io)?;
594추가: completed(
595추가: data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize]))
596추가: .map_err(|_| ErrorCode::Io),
597추가: self,
598추가: )?;
494599 self.check()?;
495600 let existing = if self.interactive {
496삭제: filesystem::existing(&root, &m.entry.name)?
601추가: filesystem::existing_with(&root, &m.entry.name, self)?
497602 } else {
498603 None
499604 };
@@ -508,21 +613,25 @@ impl<W: Write> Job<W> {
508613 } else if choice == ConflictChoice::Overwrite {
509614 replace = Some(existing);
510615 }
511삭제: self.event(Message::ConflictResolved {
512삭제: entry_id: m.entry.entry_id,
513삭제: relative_name: name.clone(),
514삭제: choice,
515삭제: })?;
616추가: completed(
617추가: self.event(Message::ConflictResolved {
618추가: entry_id: m.entry.entry_id,
619추가: relative_name: name.clone(),
620추가: choice,
621추가: }),
622추가: self,
623추가: )?;
516624 if choice == ConflictChoice::Skip {
517625 continue;
518626 }
519627 }
520628 if self.interactive {
521629 // 건너뛴 파일을 제외하고 이번에 게시할 파일의 공간을 확인함.
522삭제: filesystem::preflight_space(
630추가: filesystem::preflight_space_with(
523631 &root,
524632 &[(name.clone(), m.entry.size)],
525633 None,
634추가: self,
526635 )?;
527636 }
528637 self.output_reader(
@@ -552,9 +661,17 @@ impl<W: Write> Job<W> {
552661 .and_then(|n| n.to_str())
553662 .ok_or(ErrorCode::InvalidRequest)?;
554663 let name = archive::valid_name(leaf, false)?;
555삭제: let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?;
556삭제: filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?;
557삭제: let members = crate::create::plan(&sources, start.limits, &mut || self.check())?;
664추가: let root = completed(
665추가: Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?),
666추가: self,
667추가: )?;
668추가: filesystem::preflight_mode_with(
669추가: &root,
670추가: &[(name.clone(), EntryKind::File)],
671추가: false,
672추가: self,
673추가: )?;
674추가: let members = crate::create::plan(&sources, limits, self)?;
558675 let secret = if encryption == Encryption::Aes256 {
559676 let secret = self.password(PasswordPurpose::Encrypt, 1)?;
560677 if secret.0.is_empty() {
@@ -567,11 +684,11 @@ impl<W: Write> Job<W> {
567684 let (mut data, length) = crate::create::zip(
568685 &members,
569686 method,
570삭제: start.limits,
687추가: limits,
571688 secret.as_ref().map(|s| s.0.as_slice()),
572삭제: &mut || self.check(),
689추가: self,
573690 )?;
574삭제: filesystem::preflight_space(&root, &[(name.clone(), length)], None)?;
691추가: filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?;
575692 self.output_reader(&root, &name, &mut data, length, None, true, None)?;
576693 self.terminal.publication = Publication::Complete;
577694 }
@@ -580,6 +697,32 @@ impl<W: Write> Job<W> {
580697 Ok(())
581698 }
582699}
700추가: impl<W: Write> Monitor for Job<W> {
701추가: fn metadata_limits(&self) -> archive::MetadataLimits {
702추가: self.budget
703추가: .as_ref()
704추가: .map_or_else(archive::MetadataLimits::default, |b| b.metadata_limits())
705추가: }
706추가: fn check(&mut self) -> Result<()> {
707추가: Job::check(self)
708추가: }
709추가: fn activity(&mut self) -> Result<()> {
710추가: self.check()?;
711추가: self.watchdog.activity(self.started.elapsed())
712추가: }
713추가: fn observe(&mut self, usage: ResourceUsage, storage: Option<&std::fs::File>) -> Result<()> {
714추가: self.check()?;
715추가: let Some(budget) = &self.budget else {
716추가: return Ok(());
717추가: };
718추가: let scope = budget.required(usage)?;
719추가: if !scope.any() {
720추가: return Ok(());
721추가: }
722추가: self.request_resource(scope, usage, storage)
723추가: }
724추가: }
725추가:
583726pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
584727 input: R,
585728 output: W,
@@ -590,9 +733,17 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
590733 let (job, _, message) = reader
591734 .read()?
592735 .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?;
593삭제: let (start, interactive) = match message {
594삭제: Message::Start(start) => (start, false),
595삭제: Message::StartInteractive(start) => (start, true),
736추가: let (start, interactive, budget) = match message {
737추가: Message::Start(start) => (start, false, None),
738추가: Message::StartInteractive(start) => (start, true, None),
739추가: Message::StartGuarded(guarded) if guarded.valid() => {
740추가: let budget = Budget {
741추가: soft: guarded.start.limits,
742추가: ceiling: guarded.ceiling,
743추가: granted: ResourceScope::default(),
744추가: };
745추가: (guarded.start, guarded.interactive, Some(budget))
746추가: }
596747 _ => {
597748 return Err(std::io::Error::new(
598749 std::io::ErrorKind::InvalidData,
@@ -608,6 +759,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
608759 challenge: None,
609760 conflict_reply: None,
610761 password: None,
762추가: resource_reply: None,
611763 input_closed: false,
612764 }));
613765 let wake = Arc::new(Condvar::new());
@@ -668,6 +820,24 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
668820 }
669821 control_wake.notify_all();
670822 }
823추가: Message::ResourceReply {
824추가: challenge_id,
825추가: scope,
826추가: allow,
827추가: } => {
828추가: if state.phase != 0
829추가: || state.challenge != Some(Challenge::Resource(challenge_id, scope))
830추가: || state.resource_reply.is_some()
831추가: {
832추가: state.fault = Some(ErrorCode::Protocol);
833추가: } else {
834추가: state.challenge = None;
835추가: if !state.cancelled {
836추가: state.resource_reply = Some(allow);
837추가: }
838추가: }
839추가: control_wake.notify_all();
840추가: }
671841 Message::Cancel => {
672842 let status = match state.phase {
673843 2 => CancelStatus::Finished,
@@ -703,6 +873,9 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
703873 wake,
704874 next_challenge: 0,
705875 interactive,
876추가: action: start.action.kind(),
877추가: budget,
878추가: watchdog: Watchdog::new(),
706879 remaining_choice: None,
707880 parent,
708881 started: Instant::now(),
@@ -733,6 +906,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
733906 state.challenge = None;
734907 state.password = None;
735908 state.conflict_reply = None;
909추가: state.resource_reply = None;
736910 if let Some(error) = state.fault.or(error) {
737911 context.terminal.error = error;
738912 context.terminal.outcome = if error == ErrorCode::None {
수정experiments/rust-archive-worker/src/seven_zip.rs+95-26
@@ -1,5 +1,5 @@
11use crate::{
2삭제: archive::{MAX_METADATA_BYTES, Member, MetadataBudget, valid_name, validate_members},
2추가: archive::{Member, MetadataBudget, valid_name, validate_members_with},
33 protocol::*,
44};
55use std::collections::BTreeSet;
@@ -96,13 +96,17 @@ struct Streams {
9696 folders: Vec<Folder>,
9797}
9898impl Streams {
99삭제: fn read(r: &mut Reader<'_>, limits: Limits) -> Result<Self> {
99추가: fn read(
100추가: r: &mut Reader<'_>,
101추가: limits: Limits,
102추가: check: &mut impl crate::resources::Monitor,
103추가: ) -> Result<Self> {
100104 r.expect(6)?;
101105 let position = r.number(limits.input as usize)?;
102106 let count = r.number(limits.entries as usize)?;
103107 r.expect(9)?;
104108 let packed = (0..count)
105삭제: .map(|_| r.number(limits.input as usize))
109추가: .map(|_| crate::resources::completed(r.number(limits.input as usize), check))
106110 .collect::<Result<Vec<_>>>()?;
107111 let mut tag = r.byte()?;
108112 let packed_crcs = if tag == 10 {
@@ -157,6 +161,7 @@ impl Streams {
157161 sizes: Vec::new(),
158162 crcs: Vec::new(),
159163 });
164추가: crate::resources::completed(Ok(()), check)?;
160165 }
161166 r.expect(12)?;
162167 let mut total = 0usize;
@@ -166,11 +171,13 @@ impl Streams {
166171 .checked_add(folder.size)
167172 .filter(|n| *n <= limits.output as usize)
168173 .ok_or(ErrorCode::Limit)?;
174추가: crate::resources::completed(Ok(()), check)?;
169175 }
170176 let mut tag = r.byte()?;
171177 if tag == 10 {
172178 for (f, crc) in folders.iter_mut().zip(r.digests(num)?) {
173179 f.crc = crc;
180추가: crate::resources::completed(Ok(()), check)?;
174181 }
175182 tag = r.byte()?;
176183 }
@@ -190,6 +197,7 @@ impl Streams {
190197 .checked_add(*n)
191198 .filter(|n| *n <= limits.entries as usize)
192199 .ok_or(ErrorCode::Limit)?;
200추가: crate::resources::completed(Ok(()), check)?;
193201 }
194202 tag = r.byte()?;
195203 }
@@ -204,6 +212,7 @@ impl Streams {
204212 .filter(|n| *n <= folder.size)
205213 .ok_or(ErrorCode::Integrity)?;
206214 folder.sizes.push(n);
215추가: crate::resources::completed(Ok(()), check)?;
207216 }
208217 if *count > 0 {
209218 folder.sizes.push(folder.size - total);
@@ -229,6 +238,7 @@ impl Streams {
229238 } else {
230239 (0..*n).map(|_| digests.next().unwrap()).collect()
231240 };
241추가: crate::resources::completed(Ok(()), check)?;
232242 }
233243 if tag != 0 {
234244 return Err(ErrorCode::Integrity);
@@ -237,6 +247,7 @@ impl Streams {
237247 } else {
238248 for f in &mut folders {
239249 f.crcs.push(f.crc);
250추가: crate::resources::completed(Ok(()), check)?;
240251 }
241252 }
242253 if tag != 0 {
@@ -254,6 +265,7 @@ impl Streams {
254265 if *n == 0 && f.size != 0 {
255266 return Err(ErrorCode::Integrity);
256267 }
268추가: crate::resources::completed(Ok(()), check)?;
257269 }
258270 Ok(Self {
259271 position,
@@ -266,7 +278,7 @@ impl Streams {
266278 &self,
267279 input: &mut std::fs::File,
268280 data_end: u64,
269삭제: check: &mut impl FnMut() -> Result<()>,
281추가: check: &mut impl crate::resources::Monitor,
270282 ) -> Result<Vec<(u64, u64)>> {
271283 let mut at = 32u64
272284 .checked_add(self.position as u64)
@@ -285,6 +297,7 @@ impl Streams {
285297 }
286298 ranges.push((at, size));
287299 at = end;
300추가: crate::resources::completed(Ok(()), check)?;
288301 }
289302 Ok(ranges)
290303 }
@@ -293,16 +306,27 @@ impl Streams {
293306 input: &mut std::fs::File,
294307 ranges: &[(u64, u64)],
295308 output: &mut std::fs::File,
296삭제: check: &mut impl FnMut() -> Result<()>,
309추가: check: &mut impl crate::resources::Monitor,
297310 ) -> Result<()> {
298311 use std::io::{Read, Seek, SeekFrom, Write};
299312 let total = self.folders.iter().try_fold(0u64, |sum, f| {
300삭제: sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit)
313추가: crate::resources::completed(
314추가: sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit),
315추가: check,
316추가: )
301317 })?;
302318 crate::space::ensure(output, total)?;
303319 for (f, (start, size)) in self.folders.iter().zip(ranges) {
304삭제: check()?;
320추가: check.check()?;
305321 let base = output.stream_position().map_err(crate::space::io_error)?;
322추가: check.observe(
323추가: ResourceUsage {
324추가: compressed_bytes: Some(*size),
325추가: ratio_output_bytes: Some(f.size as u64),
326추가: ..ResourceUsage::default()
327추가: },
328추가: Some(output),
329추가: )?;
306330 input
307331 .seek(SeekFrom::Start(*start))
308332 .map_err(crate::space::io_error)?;
@@ -314,15 +338,17 @@ impl Streams {
314338 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
315339 let mut remaining = *size;
316340 while remaining != 0 {
317삭제: check()?;
341추가: check.check()?;
318342 let n = remaining.min(buffer.len() as u64) as usize;
319343 input
320344 .read_exact(&mut buffer[..n])
321345 .map_err(|_| ErrorCode::Integrity)?;
346추가: crate::space::ensure(output, n as u64)?;
322347 output
323348 .write_all(&buffer[..n])
324349 .map_err(crate::space::io_error)?;
325350 remaining -= n as u64;
351추가: crate::resources::completed(Ok(()), check)?;
326352 }
327353 }
328354 [3, 1, 1] | [0x21] => crate::lzma::decode_stream(
@@ -358,10 +384,14 @@ impl Streams {
358384 }
359385 }
360386 at = at.checked_add(*size as u64).ok_or(ErrorCode::Integrity)?;
387추가: crate::resources::completed(Ok(()), check)?;
361388 }
362삭제: output
363삭제: .seek(SeekFrom::Start(base + f.size as u64))
364삭제: .map_err(crate::space::io_error)?;
389추가: crate::resources::completed(
390추가: output
391추가: .seek(SeekFrom::Start(base + f.size as u64))
392추가: .map_err(crate::space::io_error),
393추가: check,
394추가: )?;
365395 }
366396 Ok(())
367397 }
@@ -370,7 +400,7 @@ fn digest(
370400 file: &mut std::fs::File,
371401 start: u64,
372402 size: u64,
373삭제: check: &mut impl FnMut() -> Result<()>,
403추가: check: &mut impl crate::resources::Monitor,
374404) -> Result<u32> {
375405 use std::io::{Read, Seek, SeekFrom};
376406 file.seek(SeekFrom::Start(start))
@@ -379,12 +409,13 @@ fn digest(
379409 let mut remaining = size;
380410 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
381411 while remaining != 0 {
382삭제: check()?;
412추가: check.check()?;
383413 let n = remaining.min(buffer.len() as u64) as usize;
384414 file.read_exact(&mut buffer[..n])
385415 .map_err(crate::space::io_error)?;
386416 crc = crc32(crc, &buffer[..n]);
387417 remaining -= n as u64;
418추가: crate::resources::completed(Ok(()), check)?;
388419 }
389420 Ok(crc)
390421}
@@ -392,6 +423,7 @@ fn files(
392423 r: &mut Reader<'_>,
393424 limits: Limits,
394425 streams: Option<&Streams>,
426추가: check: &mut impl crate::resources::Monitor,
395427) -> Result<(Vec<Member>, Vec<usize>)> {
396428 let count = r.number(limits.entries as usize)?;
397429 let mut empty = vec![false; count];
@@ -407,7 +439,7 @@ fn files(
407439 if !seen.insert(property) {
408440 return Err(ErrorCode::Integrity);
409441 }
410삭제: let len = r.number(MAX_METADATA_BYTES)?;
442추가: let len = r.number(check.metadata_limits().bytes)?;
411443 let mut value = Reader::new(r.take(len)?);
412444 match property {
413445 14 => {
@@ -432,6 +464,7 @@ fn files(
432464 let mut decoded = Vec::new();
433465 let mut budget = MetadataBudget::default();
434466 for _ in 0..count {
467추가: check.check()?;
435468 let mut units = Vec::new();
436469 loop {
437470 let n = u16::from_le_bytes(value.take(2)?.try_into().unwrap());
@@ -444,8 +477,9 @@ fn files(
444477 units.push(n);
445478 }
446479 let name = String::from_utf16(&units).map_err(|_| ErrorCode::Integrity)?;
447삭제: budget.charge(&name)?;
480추가: budget.charge_with(&name, check.metadata_limits())?;
448481 decoded.push(name);
482추가: crate::resources::completed(Ok(()), check)?;
449483 }
450484 names = Some(decoded);
451485 }
@@ -458,6 +492,7 @@ fn files(
458492 if set {
459493 *attr = Some(u32::from_le_bytes(value.take(4)?.try_into().unwrap()));
460494 }
495추가: crate::resources::completed(Ok(()), check)?;
461496 }
462497 }
463498 18..=20 => {
@@ -488,6 +523,7 @@ fn files(
488523 for (folder, compressed) in streams.folders.iter().zip(&streams.packed) {
489524 for (i, size) in folder.sizes.iter().enumerate() {
490525 descriptions.push((*size, if i == 0 { *compressed } else { 0 }));
526추가: crate::resources::completed(Ok(()), check)?;
491527 }
492528 }
493529 }
@@ -534,11 +570,12 @@ fn files(
534570 },
535571 data: Vec::new(),
536572 });
573추가: crate::resources::completed(Ok(()), check)?;
537574 }
538575 if descriptions.next().is_some() {
539576 return Err(ErrorCode::Integrity);
540577 }
541삭제: validate_members(&members)?;
578추가: validate_members_with(&members, check)?;
542579 Ok((members, stream_indices))
543580}
544581pub(crate) fn open(
@@ -546,10 +583,10 @@ pub(crate) fn open(
546583 length: u64,
547584 limits: Limits,
548585 decode: bool,
549삭제: check: &mut impl FnMut() -> Result<()>,
586추가: check: &mut impl crate::resources::Monitor,
550587) -> Result<crate::streaming::Catalog> {
551588 use std::io::{Read, Seek, SeekFrom};
552삭제: check()?;
589추가: check.check()?;
553590 if length > limits.input {
554591 return Err(ErrorCode::Limit);
555592 }
@@ -569,7 +606,7 @@ pub(crate) fn open(
569606 }
570607 let offset = u64::from_le_bytes(header[12..20].try_into().unwrap());
571608 let len = u64::from_le_bytes(header[20..28].try_into().unwrap());
572삭제: if len > MAX_METADATA_BYTES as u64 {
609추가: if len > check.metadata_limits().bytes as u64 {
573610 return Err(ErrorCode::Limit);
574611 }
575612 let start = offset.checked_add(32).ok_or(ErrorCode::Integrity)?;
@@ -602,16 +639,21 @@ pub(crate) fn open(
602639 if bytes[0] == 23 {
603640 let mut r = Reader::new(&bytes[1..]);
604641 let header_limits = Limits {
605삭제: output: MAX_METADATA_BYTES as u64,
642추가: output: check.metadata_limits().bytes as u64,
606643 ..limits
607644 };
608삭제: let streams = Streams::read(&mut r, header_limits)?;
645추가: let streams = Streams::read(&mut r, header_limits, check)?;
609646 r.end()?;
610647 if streams.folders.len() != 1 || streams.folders[0].sizes.len() != 1 {
611648 return Err(ErrorCode::UnsupportedFeature);
612649 }
613650 let ranges = streams.ranges(input, data_end, check)?;
614삭제: streams.decode_file(input, &ranges, &mut data, check)?;
651추가: streams.decode_file(
652추가: input,
653추가: &ranges,
654추가: &mut data,
655추가: &mut crate::resources::MetadataMonitor(check),
656추가: )?;
615657 data_end = 32u64
616658 .checked_add(streams.position as u64)
617659 .ok_or(ErrorCode::Integrity)?;
@@ -627,7 +669,7 @@ pub(crate) fn open(
627669 let mut tag = r.byte()?;
628670 if tag == 2 {
629671 while r.byte()? != 0 {
630삭제: let len = r.number(MAX_METADATA_BYTES)?;
672추가: let len = r.number(check.metadata_limits().bytes)?;
631673 r.take(len)?;
632674 }
633675 tag = r.byte()?;
@@ -636,11 +678,11 @@ pub(crate) fn open(
636678 return Err(ErrorCode::UnsupportedFeature);
637679 }
638680 if tag == 4 {
639삭제: streams = Some(Streams::read(&mut r, limits)?);
681추가: streams = Some(Streams::read(&mut r, limits, check)?);
640682 tag = r.byte()?;
641683 }
642684 let (members, stream_indices) = if tag == 5 {
643삭제: let f = files(&mut r, limits, streams.as_ref())?;
685추가: let f = files(&mut r, limits, streams.as_ref(), check)?;
644686 tag = r.byte()?;
645687 f
646688 } else {
@@ -650,6 +692,31 @@ pub(crate) fn open(
650692 return Err(ErrorCode::Integrity);
651693 }
652694 r.end()?;
695추가: let total = members.iter().try_fold(0u64, |n, m| {
696추가: crate::resources::completed(n.checked_add(m.entry.size).ok_or(ErrorCode::Limit), check)
697추가: })?;
698추가: let packed = streams
699추가: .as_ref()
700추가: .map(|s| {
701추가: s.packed.iter().try_fold(0u64, |sum, size| {
702추가: crate::resources::completed(
703추가: sum.checked_add(*size as u64).ok_or(ErrorCode::Integrity),
704추가: check,
705추가: )
706추가: })
707추가: })
708추가: .transpose()?;
709추가: check.observe(
710추가: ResourceUsage {
711추가: estimated_bytes: Some(total),
712추가: estimated_entries: Some(members.len() as u32),
713추가: compressed_bytes: packed,
714추가: ratio_output_bytes: Some(total),
715추가: ..ResourceUsage::default()
716추가: },
717추가: Some(&data),
718추가: )?;
719추가: crate::resources::completed(Ok(()), check)?;
653720 let mut offsets = vec![0; members.len()];
654721 if let Some(streams) = streams {
655722 if streams.folders.iter().map(|f| f.sizes.len()).sum::<usize>() != stream_indices.len() {
@@ -662,6 +729,7 @@ pub(crate) fn open(
662729 for size in &f.sizes {
663730 offsets[ids.next().ok_or(ErrorCode::Integrity)?] = at;
664731 at = at.checked_add(*size as u64).ok_or(ErrorCode::Limit)?;
732추가: crate::resources::completed(Ok(()), check)?;
665733 }
666734 }
667735 if at > limits.output {
@@ -682,7 +750,7 @@ pub(crate) fn parse(
682750 input: &[u8],
683751 limits: Limits,
684752 decode: bool,
685삭제: check: &mut impl FnMut() -> Result<()>,
753추가: check: &mut impl crate::resources::Monitor,
686754) -> Result<Vec<Member>> {
687755 use std::io::{Read, Seek, SeekFrom, Write};
688756 let mut source = crate::spool::temporary()?;
@@ -703,6 +771,7 @@ pub(crate) fn parse(
703771 .take(member.entry.size)
704772 .read_to_end(&mut member.data)
705773 .map_err(crate::space::io_error)?;
774추가: crate::resources::completed(Ok(()), check)?;
706775 }
707776 }
708777 Ok(catalog.members)
수정experiments/rust-archive-worker/src/space.rs+3-3
@@ -19,7 +19,7 @@ pub(crate) fn ensure(file: &File, bytes: u64) -> Result<()> {
1919}
2020
2121#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
22삭제: fn available(file: &File) -> Result<u128> {
22추가: pub(crate) fn available(file: &File) -> Result<u128> {
2323 use std::os::fd::AsRawFd;
2424 #[repr(C)]
2525 #[derive(Default)]
@@ -48,12 +48,12 @@ fn available(file: &File) -> Result<u128> {
4848}
4949
5050#[cfg(all(target_os = "linux", not(target_pointer_width = "64")))]
51삭제: fn available(_: &File) -> Result<u128> {
51추가: pub(crate) fn available(_: &File) -> Result<u128> {
5252 Err(ErrorCode::UnsupportedFeature)
5353}
5454
5555#[cfg(windows)]
56삭제: fn available(file: &File) -> Result<u128> {
56추가: pub(crate) fn available(file: &File) -> Result<u128> {
5757 use std::{
5858 ffi::OsString,
5959 os::windows::{
수정experiments/rust-archive-worker/src/spool.rs+39-13
@@ -73,9 +73,23 @@ pub(crate) fn temporary() -> Result<File> {
7373#[derive(Clone, Copy, Debug)]
7474pub(crate) enum Step {
7575 Check,
76추가: Activity,
7677 Read { bytes: u64, total: u64 },
7778}
7879
80추가: struct Progress<'a, F>(&'a mut F);
81추가: impl<F: FnMut(Step) -> Result<()>> crate::resources::Monitor for Progress<'_, F> {
82추가: fn check(&mut self) -> Result<()> {
83추가: self.0(Step::Check)
84추가: }
85추가: fn activity(&mut self) -> Result<()> {
86추가: self.0(Step::Activity)
87추가: }
88추가: }
89추가: fn completed<T>(result: Result<T>, step: &mut impl FnMut(Step) -> Result<()>) -> Result<T> {
90추가: crate::resources::completed(result, &mut Progress(step))
91추가: }
92추가:
7993pub(crate) struct Snapshot {
8094 pub file: File,
8195 pub len: u64,
@@ -101,24 +115,28 @@ impl Snapshot {
101115 use std::os::windows::fs::OpenOptionsExt;
102116 options.share_mode(1);
103117 }
104삭제: let mut source = options.open(path).map_err(|_| ErrorCode::Io)?;
118추가: let mut source = completed(options.open(path).map_err(|_| ErrorCode::Io), step)?;
105119 let snapshot = Self::capture_reporting(&mut source, limit, step)?;
106삭제: let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?;
120추가: let named = completed(
121추가: options.open(path).map_err(|_| ErrorCode::SourceChanged),
122추가: step,
123추가: )?;
107124 if filesystem::object(&named)? != snapshot.object
108125 || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file()
109126 {
110127 return Err(ErrorCode::SourceChanged);
111128 }
112삭제: Ok(snapshot)
129추가: completed(Ok(snapshot), step)
113130 }
114131 pub(crate) fn capture(
115132 source: &mut File,
116133 limit: u64,
117삭제: check: &mut impl FnMut() -> Result<()>,
134추가: check: &mut impl crate::resources::Monitor,
118135 ) -> Result<Self> {
119136 Self::capture_reporting(source, limit, &mut |step| match step {
120삭제: Step::Check => check(),
121삭제: Step::Read { .. } => Ok(()),
137추가: Step::Check => check.check(),
138추가: Step::Activity => crate::resources::completed(Ok(()), check),
139추가: Step::Read { .. } => check.check(),
122140 })
123141 }
124142 fn capture_reporting(
@@ -126,7 +144,7 @@ impl Snapshot {
126144 limit: u64,
127145 step: &mut impl FnMut(Step) -> Result<()>,
128146 ) -> Result<Self> {
129삭제: let before = source.metadata().map_err(|_| ErrorCode::Io)?;
147추가: let before = completed(source.metadata().map_err(|_| ErrorCode::Io), step)?;
130148 if !before.is_file() {
131149 return Err(ErrorCode::InvalidRequest);
132150 }
@@ -135,8 +153,8 @@ impl Snapshot {
135153 }
136154 source.rewind().map_err(|_| ErrorCode::Io)?;
137155 let object = filesystem::object(&source)?;
138삭제: let mut file = temporary()?;
139삭제: crate::space::ensure(&file, before.len())?;
156추가: let mut file = completed(temporary(), step)?;
157추가: completed(crate::space::ensure(&file, before.len()), step)?;
140158 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
141159 let mut hash = Sha256::new();
142160 let mut len = 0u64;
@@ -144,7 +162,10 @@ impl Snapshot {
144162 let mut reported = std::time::Instant::now();
145163 loop {
146164 step(Step::Check)?;
147삭제: let n = source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io)?;
165추가: let n = completed(
166추가: source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io),
167추가: step,
168추가: )?;
148169 if n == 0 {
149170 break;
150171 }
@@ -152,8 +173,10 @@ impl Snapshot {
152173 .checked_add(n as u64)
153174 .filter(|n| *n <= limit)
154175 .ok_or(ErrorCode::Limit)?;
155삭제: file.write_all(&buffer[..n])
156삭제: .map_err(crate::space::io_error)?;
176추가: completed(
177추가: file.write_all(&buffer[..n]).map_err(crate::space::io_error),
178추가: step,
179추가: )?;
157180 hash.update(&buffer[..n]);
158181 // 큰 파일에서도 진행이 보이도록 일정 간격으로만 알림.
159182 if reported.elapsed() >= std::time::Duration::from_millis(200) {
@@ -170,7 +193,10 @@ impl Snapshot {
170193 {
171194 return Err(ErrorCode::SourceChanged);
172195 }
173삭제: file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io)?;
196추가: completed(
197추가: file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io),
198추가: step,
199추가: )?;
174200 Ok(Self {
175201 file,
176202 len,
수정experiments/rust-archive-worker/src/streaming.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-archive-worker/src/wire.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-ui-memory-app/src/archive_process.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-ui-memory-app/src/archive_screen.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-ui-memory-app/src/archive_ui.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-real-worker/README.md

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-real-worker/conflict_flows.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-real-worker/flows.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-app-real-worker/guarded_flows.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-app-real-worker/supervisor_clock.c

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/README.md

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/capture.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/fake.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-app-ui/guarded.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/regressions.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/scenario_tests.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/scenarios.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/work_window.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/guarded.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/guarded_cases.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/header_budget.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/item_progress.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-archive-worker/main.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/metadata_policy.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/phase_clock.c

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/progress_clock.c

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/resource_budget.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/selection_wire.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기