team-ljyzipelo

공개

대용량 작업 승인과 자원 감시를 추가한다

작성자
시로사키 하나
작성 시각
커밋
b719523146fab432a6a55881e1e63357f7d830fa
부모
a5f11f7
이 시점의 파일 보기

변경된 파일 22개

+1,455-123
수정experiments/rust-archive-worker/README.md+19-3
@@ -4,7 +4,7 @@
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 한도를 유지합니다.
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 한도를 유지합니다.
88- 경로 깊이는 64개 구성 요소, 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다.
99- GZip 내부 형식은 완전한 USTAR magic이 있을 때만 TAR로 판별합니다. magic이 없는 영값 데이터는 길이와 무관하게 raw GZip으로 유지하며 명시 출력명이 필요합니다.
1010- ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다.
@@ -16,7 +16,7 @@
1616
1717revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도를 유지하고, 히나타 님과 합의한 공간 부족 오류 DiskFull(tag 13)을 추가합니다. 구버전 앱은 새 tag를 거부하므로 앱 오류 변환과 화면 매핑을 작업자와 함께 갱신해야 합니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 세부 계약은 contract.json의 streaming_limits에 있습니다.
1818
19삭제: - 압축비는 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다.
19추가: - 기존 Start와 StartInteractive는 압축비를 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다.
2020- 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. 기존 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-)을 따릅니다.
2121- 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 오류 문구는 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"이며, detail 문자열을 오류 판정에 사용하지 않습니다.
2222- 입력과 검증된 해제 내용은 임시 파일에 저장합니다. 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 외의 시스템 메모리를 사용합니다.
@@ -76,7 +76,7 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
7676
7777## 공유 codec
7878
79삭제: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 3 원문이며 `extract_conflicts.status`에서 구현 상태를 구분합니다.
79추가: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 3 원문이며 `extract_conflicts.status`와 `guarded_resources.status`에서 구현 및 화면 연동 상태를 구분합니다.
8080
8181헤더는 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를 거부합니다.
8282
@@ -101,6 +101,22 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
101101
102102교체 동작의 근거는 [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)입니다.
103103
104추가: ## 큰 작업의 명시적 승인 계약
105추가:
106추가: `StartGuarded`는 기존 요청과 분리된 선택적 확장입니다. 작업자 구현만 포함하며 앱에서 새 요청과 승인 화면을 사용하는 연동, `--ui-scenario` 및 가이드 갱신은 frontend 범위입니다. 기존 앱의 요청에는 새 질문을 보내지 않습니다. 구버전 작업자가 새 요청을 거부하면 자동 재시도하지 않습니다.
107추가:
108추가: - kind 6의 본문은 `GuardedStart { start: Start, ceiling: Limits, interactive: bool }` 순서입니다. start.limits는 기존 16 GiB 및 10,000개 이하이고 ceiling은 이를 늘리되 64 GiB 및 200,000개 이하입니다. 입력 한도는 동일해야 합니다. interactive는 Extract에서만 허용하며 기존 암호와 충돌 처리를 함께 사용합니다.
109추가: - 작업자는 Accepted 뒤, 입력 캡처와 소스 탐색 전에 요청된 상한 확대 범위를 확인합니다. 입력 사본 작성부터 300초를 넘을 수 있으므로 승인을 먼저 받습니다. 이때 예상량과 실제량은 아직 미확인(None)이고 임시 저장 볼륨의 여유 공간을 알립니다. 허용 전에는 확대 한도가 적용되지 않으며 거부하면 Cancelled로 끝납니다. 작은 기존 작업은 Start를 계속 사용할 수 있습니다.
110추가: - 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으로 바꾸지 않습니다. 여유 공간은 관찰 중인 저장 볼륨의 값이며 공간 예약이나 모든 볼륨의 합계가 아닙니다.
111추가: - kind 7의 `ResourceReply`는 challenge_id u64, scope, allow bool입니다. 프레임의 작업 ID, 현재 질문 ID와 요청한 scope가 모두 일치하는 응답 한 개만 허용합니다. 중복, 오래된 응답과 다른 종류의 질문 응답은 Protocol입니다. 승인은 해당 작업의 해당 범위에만 적용하며 재사용하지 않습니다.
112추가: - 해제량이 256 MiB 이상이고 압축률이 1,000배를 초과하면 ratio 범위를 별도로 묻습니다. ZIP은 항목별, 7z는 solid 폴더와 전체, 압축 TAR와 GZip은 스트림 전체의 크기로 검사합니다. 예상량과 실제량을 구분하고 u128 곱셈으로 비교합니다. 승인 중에는 추가 해제와 쓰기를 멈추며 취소는 별도 제어 읽기에서 처리합니다.
113추가: - 승인 후에도 64 GiB와 200,000개 정책 상한, 메타데이터와 사전 예산, 경로 및 무결성, 임시 저장소와 목적지 공간 검사를 적용합니다. ZIP 생성은 원본 논리 크기 합계를 제한하며 ZIP 구조와 암호화로 늘어나는 저장 공간을 별도로 계산합니다. 이미 게시한 출력은 실패나 취소 시 유지하고 게시 및 정리 상태를 보고합니다.
114추가: - 승인된 작업은 전체 300초 대신 진행이 60초 동안 없을 때 Limit로 중단합니다. 실제 읽기, 해독, 쓰기와 메타데이터 수집만 진행으로 계산하며 반복 check 호출은 기한을 늘리지 않습니다. 암호, 충돌과 자원 질문은 한 번에 하나이며 각 응답 대기는 300초입니다. 유효한 응답 뒤에는 사용자 대기 시간을 제외하고 정체 감시를 재개합니다. 기존 요청의 전체 300초 제한은 유지합니다. OS의 블로킹 I/O를 강제로 중단하는 보장은 아닙니다.
115추가:
116추가: 현재 남은 제약: 기존 8 MiB 메타데이터 예산과 32,768개 노드 상한을 유지하므로 실제 항목 200,000개까지 처리할 수 있다는 뜻은 아닙니다. 소스 경로도 이 예산을 사용합니다. 메타데이터 저장 방식과 예산 결정, 정확한 codec 인계 검토 및 화면 연동 전까지 초안을 유지합니다.
117추가:
118추가: 시험은 실제 64 GiB를 쓰지 않고 수치 경계와 축소한 limits/ceiling을 사용합니다. `resource_budget.rs`는 16 GiB 아래/경계/초과, 64 GiB 초과, 10,000개 및 200,000개 경계, 압축률 경계와 가상 시계의 60초 정체를 검사합니다. `guarded.rs`는 실제 작업자 승인/거부, 오래된 응답, 암호/충돌 순서, 승인 뒤 공간 실패, 여러 형식과 작은 고압축 입력의 경고 및 취소를 검사합니다.
119추가:
104120## 검증과 의존성
105121
106122시험은 `tests/rust-archive-worker`에 있습니다. Python 표준 라이브러리로 만든 ZIP/TAR/GZ fixture와 실제 자식 프로세스를 사용합니다. 전체 검증 명령은 저장소 루트의 `python3 tests/ci/run_rust.py local`입니다. Windows 교차 빌드는 실제 Windows 실행 검증을 대신하지 않습니다.
수정experiments/rust-archive-worker/contract.json+18-2
@@ -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.",
@@ -222,5 +225,18 @@
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-implemented; frontend activation and exact wire handoff review 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, 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추가: "open_constraint": "The unchanged 8 MiB MetadataBudget and 32768 node cap currently prevent reaching 200000 entries, and source paths consume the same budget. Metadata storage/budget policy requires a manager decision before claiming support for 200000 real entries. Keep the PR draft until this and frontend activation are resolved.",
240추가: "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. Do not write 64 GiB in tests."
225241 }
226242}
수정experiments/rust-archive-worker/src/archive.rs+22-14
@@ -158,13 +158,13 @@ fn inflate(
158158 input: &[u8],
159159 gzip: bool,
160160 limit: u64,
161삭제: check: &mut impl FnMut() -> Result<()>,
161추가: check: &mut impl crate::resources::Monitor,
162162) -> Result<(Vec<u8>, usize)> {
163163 let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
164164 let mut out = Vec::new();
165165 let mut buffer = [0; 65536];
166166 loop {
167삭제: check()?;
167추가: check.check()?;
168168 let before_in = stream.total_in();
169169 let before_out = stream.total_out();
170170 let status = stream
@@ -184,7 +184,11 @@ fn inflate(
184184 }
185185 }
186186}
187삭제: fn gzip(input: &[u8], limits: Limits, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> {
187추가: fn gzip(
188추가: input: &[u8],
189추가: limits: Limits,
190추가: check: &mut impl crate::resources::Monitor,
191추가: ) -> Result<Vec<u8>> {
188192 let mut at = 0;
189193 let mut result = Vec::new();
190194 while at < input.len() {
@@ -230,14 +234,14 @@ fn tar(
230234 input: &[u8],
231235 limits: Limits,
232236 decode: bool,
233삭제: check: &mut impl FnMut() -> Result<()>,
237추가: check: &mut impl crate::resources::Monitor,
234238) -> Result<Vec<Member>> {
235239 let mut at = 0;
236240 let mut members = Vec::new();
237241 let mut total = 0u64;
238242 let mut metadata = MetadataBudget::default();
239243 loop {
240삭제: check()?;
244추가: check.check()?;
241245 let header = part(input, at, 512)?;
242246 if header.iter().all(|b| *b == 0) {
243247 if part(input, at + 512, 512)?.iter().any(|b| *b != 0)
@@ -394,7 +398,7 @@ fn zip(
394398 limits: Limits,
395399 decode: bool,
396400 password: Option<&[u8]>,
397삭제: check: &mut impl FnMut() -> Result<()>,
401추가: check: &mut impl crate::resources::Monitor,
398402) -> Result<Vec<Member>> {
399403 if input.len() < 22 {
400404 return Err(ErrorCode::Integrity);
@@ -432,7 +436,7 @@ fn zip(
432436 let mut total = 0u64;
433437 let mut metadata = MetadataBudget::default();
434438 for id in 0..count {
435삭제: check()?;
439추가: check.check()?;
436440 let h = part(input, at, 46)?;
437441 if &h[..4] != b"PK\x01\x02" {
438442 return Err(ErrorCode::Integrity);
@@ -604,7 +608,7 @@ pub fn parse(
604608 input: &[u8],
605609 limits: Limits,
606610 decode: bool,
607삭제: check: &mut impl FnMut() -> Result<()>,
611추가: check: &mut impl crate::resources::Monitor,
608612) -> Result<Catalog> {
609613 parse_with_password(input, limits, decode, None, check)
610614}
@@ -613,7 +617,7 @@ pub fn parse_with_password(
613617 limits: Limits,
614618 decode: bool,
615619 password: Option<&[u8]>,
616삭제: check: &mut impl FnMut() -> Result<()>,
620추가: check: &mut impl crate::resources::Monitor,
617621) -> Result<Catalog> {
618622 if !limits.valid() {
619623 return Err(ErrorCode::Limit);
@@ -666,12 +670,16 @@ pub fn parse_with_password(
666670 }
667671 Err(ErrorCode::UnsupportedFormat)
668672}
669삭제: fn deflate(input: &[u8], limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> {
673추가: fn deflate(
674추가: input: &[u8],
675추가: limit: u64,
676추가: check: &mut impl crate::resources::Monitor,
677추가: ) -> Result<Vec<u8>> {
670678 let mut stream = Deflate::new(6, false, 15);
671679 let mut output = Vec::new();
672680 let mut buffer = [0; 65536];
673681 loop {
674삭제: check()?;
682추가: check.check()?;
675683 let a = stream.total_in();
676684 let b = stream.total_out();
677685 let status = stream
@@ -700,7 +708,7 @@ pub fn create_zip(
700708 members: &[Member],
701709 method: Method,
702710 limits: Limits,
703삭제: check: &mut impl FnMut() -> Result<()>,
711추가: check: &mut impl crate::resources::Monitor,
704712) -> Result<Vec<u8>> {
705713 create_zip_with_password(members, method, limits, None, check)
706714}
@@ -709,7 +717,7 @@ pub fn create_zip_with_password(
709717 method: Method,
710718 limits: Limits,
711719 password: Option<&[u8]>,
712삭제: check: &mut impl FnMut() -> Result<()>,
720추가: check: &mut impl crate::resources::Monitor,
713721) -> Result<Vec<u8>> {
714722 if !limits.valid() {
715723 return Err(ErrorCode::Limit);
@@ -723,7 +731,7 @@ pub fn create_zip_with_password(
723731 let mut cd = Vec::new();
724732 let mut total = 0u64;
725733 for m in members {
726삭제: check()?;
734추가: check.check()?;
727735 total = total
728736 .checked_add(m.data.len() as u64)
729737 .filter(|n| *n <= limits.output)
수정experiments/rust-archive-worker/src/compressed_tar.rs+57-16
@@ -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,24 @@ 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추가: self.check
51추가: .borrow_mut()
52추가: .activity()
53추가: .map_err(|e| io::Error::other(InputError(e)))?;
54추가: }
55추가: Ok(n)
4256 }
4357}
4458
@@ -60,14 +74,26 @@ pub(crate) fn decode(
6074 source: &mut File,
6175 compression: Compression,
6276 limit: u64,
63삭제: check: &mut impl FnMut() -> Result<()>,
77추가: check: &mut impl crate::resources::Monitor,
6478) -> Result<(File, u64)> {
65삭제: check()?;
79추가: check.check()?;
6680 let expected = if matches!(compression, Compression::Xz) {
6781 Some(xz_layout(source, limit, check)?)
6882 } else {
6983 None
7084 };
85추가: let packed_length = source.metadata().map_err(space::io_error)?.len();
86추가: if let Some(expected) = expected {
87추가: check.observe(
88추가: ResourceUsage {
89추가: estimated_bytes: Some(expected),
90추가: compressed_bytes: Some(packed_length),
91추가: ratio_output_bytes: Some(expected),
92추가: ..ResourceUsage::default()
93추가: },
94추가: Some(source),
95추가: )?;
96추가: }
7197 source.rewind().map_err(space::io_error)?;
7298 let mut output = spool::temporary()?;
7399 let check = RefCell::new(check);
@@ -88,7 +114,7 @@ pub(crate) fn decode(
88114 let mut buffer = Zeroizing::new([0; CHUNK]);
89115 let mut total = 0u64;
90116 loop {
91삭제: (check.borrow_mut())()?;
117추가: check.borrow_mut().check()?;
92118 let count = reader.read(&mut buffer[..]).map_err(decode_error)?;
93119 if count == 0 {
94120 break;
@@ -97,13 +123,23 @@ pub(crate) fn decode(
97123 .checked_add(count as u64)
98124 .filter(|total| *total <= limit)
99125 .ok_or(ErrorCode::Limit)?;
126추가: check.borrow_mut().observe(
127추가: ResourceUsage {
128추가: actual_bytes: Some(total),
129추가: compressed_bytes: Some(packed_length),
130추가: ratio_output_bytes: Some(total),
131추가: ..ResourceUsage::default()
132추가: },
133추가: Some(&output),
134추가: )?;
135추가: check.borrow_mut().activity()?;
100136 // 전체 검증 전에는 비공개 임시 파일에만 기록함.
101137 space::ensure(&output, count as u64)?;
102138 output
103139 .write_all(&buffer[..count])
104140 .map_err(space::io_error)?;
105141 }
106삭제: (check.borrow_mut())()?;
142추가: check.borrow_mut().check()?;
107143 if expected.is_some_and(|expected| expected != total) {
108144 return Err(ErrorCode::Integrity);
109145 }
@@ -114,9 +150,9 @@ fn read_at(
114150 source: &mut File,
115151 offset: u64,
116152 bytes: &mut [u8],
117삭제: check: &mut impl FnMut() -> Result<()>,
153추가: check: &mut impl crate::resources::Monitor,
118154) -> Result<()> {
119삭제: check()?;
155추가: check.check()?;
120156 source
121157 .seek(std::io::SeekFrom::Start(offset))
122158 .map_err(space::io_error)?;
@@ -126,7 +162,8 @@ fn read_at(
126162 } else {
127163 ErrorCode::Io
128164 }
129삭제: })
165추가: })?;
166추가: check.activity()
130167}
131168
132169fn vli(bytes: &[u8], cursor: &mut usize) -> Result<u64> {
@@ -150,7 +187,7 @@ fn lzma2_size(
150187 mut at: u64,
151188 end: u64,
152189 expected: u64,
153삭제: check: &mut impl FnMut() -> Result<()>,
190추가: check: &mut impl crate::resources::Monitor,
154191) -> Result<()> {
155192 let mut size = 0u64;
156193 while at < end {
@@ -202,7 +239,7 @@ fn xz_block(
202239 unpadded: u64,
203240 size: u64,
204241 check_size: u64,
205삭제: check: &mut impl FnMut() -> Result<()>,
242추가: check: &mut impl crate::resources::Monitor,
206243) -> Result<()> {
207244 let mut header = [0; 1024];
208245 read_at(source, start, &mut header[..1], check)?;
@@ -262,7 +299,11 @@ fn xz_block(
262299}
263300
264301// 역방향 인덱스 검사는 디코더의 할당과 실제 해제량 검사보다 먼저 수행함.
265삭제: fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<u64> {
302추가: fn xz_layout(
303추가: source: &mut File,
304추가: limit: u64,
305추가: check: &mut impl crate::resources::Monitor,
306추가: ) -> Result<u64> {
266307 use zlib_rs::crc32::crc32;
267308 let mut end = source.metadata().map_err(space::io_error)?.len();
268309 let mut total = 0u64;
@@ -316,7 +357,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<(
316357 let mut blocks = 0u64;
317358 let mut records = Vec::new();
318359 for _ in 0..count {
319삭제: check()?;
360추가: check.check()?;
320361 let unpadded = vli(&index[..data_end], &mut cursor)?;
321362 let size = vli(&index[..data_end], &mut cursor)?;
322363 if unpadded == 0 {
수정experiments/rust-archive-worker/src/create.rs+22-10
@@ -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,11 +52,13 @@ 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추가: check.activity()?;
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;
@@ -68,12 +70,12 @@ fn pack(
6870 }
6971 let mut stream = Deflate::new(6, false, 15);
7072 loop {
71삭제: check()?;
73추가: check.check()?;
7274 let n = io(input.read(&mut buffer[..]))?;
7375 crc = crc32(crc, &buffer[..n]);
7476 let mut used = 0;
7577 loop {
76삭제: check()?;
78추가: check.check()?;
7779 let a = stream.total_in();
7880 let b = stream.total_out();
7981 let status = stream
@@ -89,7 +91,11 @@ fn pack(
8991 .map_err(|_| ErrorCode::Internal)?;
9092 used += (stream.total_in() - a) as usize;
9193 let written = (stream.total_out() - b) as usize;
94추가: crate::space::ensure(output, written as u64)?;
9295 io(output.write_all(&encoded[..written]))?;
96추가: if used != 0 || written != 0 {
97추가: check.activity()?;
98추가: }
9399 size = size.checked_add(written as u64).ok_or(ErrorCode::Limit)?;
94100 if status == Status::StreamEnd {
95101 if stream.total_in() != length {
@@ -110,7 +116,7 @@ pub(crate) use crate::create_sources::Plan;
110116pub(crate) fn plan(
111117 sources: &[Source],
112118 limits: Limits,
113삭제: check: &mut impl FnMut() -> Result<()>,
119추가: check: &mut impl crate::resources::Monitor,
114120) -> Result<Plan> {
115121 Plan::new(sources, limits, check)
116122}
@@ -119,7 +125,7 @@ pub(crate) fn zip(
119125 method: Method,
120126 limits: Limits,
121127 password: Option<&[u8]>,
122삭제: check: &mut impl FnMut() -> Result<()>,
128추가: check: &mut impl crate::resources::Monitor,
123129) -> Result<(File, u64)> {
124130 let mut output = spool::temporary()?;
125131 let mut central = Vec::new();
@@ -130,7 +136,7 @@ pub(crate) fn zip(
130136 let directory = member.entry.kind == EntryKind::Directory;
131137 let method = if directory { Method::Store } else { method };
132138 let password = if directory { None } else { password };
133삭제: check()?;
139추가: check.check()?;
134140 let remaining = limits
135141 .input
136142 .min(limits.output)
@@ -229,12 +235,14 @@ pub(crate) fn zip(
229235 } else {
230236 let mut buffer = Zeroizing::new([0; 65536]);
231237 loop {
232삭제: check()?;
238추가: check.check()?;
233239 let n = io(packed.read(&mut buffer[..]))?;
234240 if n == 0 {
235241 break;
236242 }
243추가: crate::space::ensure(&output, n as u64)?;
237244 io(output.write_all(&buffer[..n]))?;
245추가: check.activity()?;
238246 }
239247 }
240248 let mut extra = zip64_extra(length, packed_size, Some(offset));
@@ -277,13 +285,17 @@ pub(crate) fn zip(
277285 central.extend(name);
278286 central.extend(extra);
279287 }
280삭제: check()?;
288추가: check.check()?;
281289 let at = io(output.stream_position())?;
282290 crate::space::ensure(&output, central.len() as u64 + 98)?;
283291 io(output.write_all(&central))?;
284292 let large_at = io(output.stream_position())?;
285293 let mut end = Vec::new();
286삭제: if have_zip64 || at >= u32::MAX as u64 || central.len() >= u32::MAX as usize {
294추가: if have_zip64
295추가: || plan.items.len() >= u16::MAX as usize
296추가: || at >= u32::MAX as u64
297추가: || central.len() >= u32::MAX as usize
298추가: {
287299 end.extend(b"PK\x06\x06");
288300 put64(&mut end, 44);
289301 put16(&mut end, 45);
수정experiments/rust-archive-worker/src/create_sources.rs+26-7
@@ -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,7 +214,7 @@ 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);
@@ -241,9 +241,9 @@ impl Plan {
241241 path: PathBuf,
242242 name: String,
243243 input: Input,
244삭제: check: &mut impl FnMut() -> Result<()>,
244추가: check: &mut impl crate::resources::Monitor,
245245 ) -> Result<()> {
246삭제: check()?;
246추가: check.check()?;
247247 if self.items.len() >= self.limits.entries as usize {
248248 return Err(ErrorCode::Limit);
249249 }
@@ -258,6 +258,15 @@ impl Plan {
258258 .checked_add(size)
259259 .filter(|n| *n <= self.limits.input.min(self.limits.output))
260260 .ok_or(ErrorCode::Limit)?;
261추가: check.observe(
262추가: ResourceUsage {
263추가: estimated_bytes: Some(self.total),
264추가: actual_entries: Some(self.items.len() as u32 + 1),
265추가: ..ResourceUsage::default()
266추가: },
267추가: None,
268추가: )?;
269추가: check.activity()?;
261270 self.items.push(Planned {
262271 member: Member {
263272 entry: Entry {
@@ -281,7 +290,7 @@ impl Plan {
281290 if directory {
282291 let mut children = Vec::new();
283292 for entry in input.children(&path)? {
284삭제: check()?;
293추가: check.check()?;
285294 if self.items.len() + children.len() >= self.limits.entries as usize {
286295 return Err(ErrorCode::Limit);
287296 }
@@ -292,6 +301,15 @@ impl Plan {
292301 .map_err(|_| ErrorCode::UnsafePath)?;
293302 self.budget.charge(&leaf)?;
294303 children.push(leaf);
304추가: check.observe(
305추가: ResourceUsage {
306추가: estimated_bytes: Some(self.total),
307추가: estimated_entries: Some((self.items.len() + children.len()) as u32),
308추가: ..ResourceUsage::default()
309추가: },
310추가: None,
311추가: )?;
312추가: check.activity()?;
295313 }
296314 children.sort();
297315 for leaf in children {
@@ -301,10 +319,11 @@ impl Plan {
301319 }
302320 Ok(())
303321 }
304삭제: pub fn verify(&self, check: &mut impl FnMut() -> Result<()>) -> Result<()> {
322추가: pub fn verify(&self, check: &mut impl crate::resources::Monitor) -> Result<()> {
305323 for item in &self.items {
306삭제: check()?;
324추가: check.check()?;
307325 item.open()?;
326추가: check.activity()?;
308327 }
309328 Ok(())
310329 }
수정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추가: check.activity()?;
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추가: check.activity()?;
337340 }
338341 output
339342 .write_all(&mac.finalize().into_bytes()[..10])
수정experiments/rust-archive-worker/src/filesystem.rs+3-2
@@ -90,7 +90,7 @@ pub fn object(file: &File) -> Result<SourceObject> {
9090pub fn snapshot(
9191 path: &Path,
9292 limit: u64,
93삭제: check: &mut impl FnMut() -> Result<()>,
93추가: check: &mut impl crate::resources::Monitor,
9494) -> Result<Snapshot> {
9595 let mut options = OpenOptions::new();
9696 options.read(true);
@@ -117,7 +117,7 @@ pub fn snapshot(
117117 let mut hash = Sha256::new();
118118 let mut buffer = [0; 65536];
119119 loop {
120삭제: check()?;
120추가: check.check()?;
121121 let n = file.read(&mut buffer).map_err(|_| ErrorCode::Io)?;
122122 if n == 0 {
123123 break;
@@ -663,6 +663,7 @@ pub fn publish_reader_mode(
663663 if n == 0 {
664664 return Err(ErrorCode::Io);
665665 }
666추가: crate::space::ensure(&file, n as u64)?;
666667 file.write_all(&buffer[..n])
667668 .map_err(crate::space::io_error)?;
668669 remaining -= n as u64;
수정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추가: check.activity()?;
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추가: check.activity()?;
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+97-0
@@ -0,0 +1,97 @@
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 check(&mut self) -> Result<()>;
8추가: fn activity(&mut self) -> Result<()> {
9추가: self.check()
10추가: }
11추가: fn observe(&mut self, _usage: ResourceUsage, _storage: Option<&std::fs::File>) -> Result<()> {
12추가: self.check()
13추가: }
14추가: }
15추가: impl<F: FnMut() -> Result<()>> Monitor for F {
16추가: fn check(&mut self) -> Result<()> {
17추가: self()
18추가: }
19추가: }
20추가:
21추가: pub(crate) struct Budget {
22추가: pub soft: Limits,
23추가: pub ceiling: Limits,
24추가: pub granted: ResourceScope,
25추가: }
26추가: impl Budget {
27추가: pub fn required(&self, usage: ResourceUsage) -> Result<ResourceScope> {
28추가: let bytes = usage
29추가: .estimated_bytes
30추가: .into_iter()
31추가: .chain(usage.actual_bytes)
32추가: .max();
33추가: let entries = usage
34추가: .estimated_entries
35추가: .into_iter()
36추가: .chain(usage.actual_entries)
37추가: .max();
38추가: if bytes.is_some_and(|n| n > self.ceiling.output)
39추가: || entries.is_some_and(|n| n > self.ceiling.entries)
40추가: {
41추가: return Err(ErrorCode::Limit);
42추가: }
43추가: let ratio = match (usage.ratio_output_bytes, usage.compressed_bytes) {
44추가: (Some(output), Some(input)) => {
45추가: output >= 256 * 1024 * 1024 && u128::from(output) > u128::from(input) * 1000
46추가: }
47추가: _ => false,
48추가: };
49추가: Ok(ResourceScope {
50추가: output: !self.granted.output && bytes.is_some_and(|n| n > self.soft.output),
51추가: entries: !self.granted.entries && entries.is_some_and(|n| n > self.soft.entries),
52추가: ratio: !self.granted.ratio && ratio,
53추가: })
54추가: }
55추가: pub fn grant(&mut self, scope: ResourceScope) {
56추가: self.granted.output |= scope.output;
57추가: self.granted.entries |= scope.entries;
58추가: self.granted.ratio |= scope.ratio;
59추가: }
60추가: }
61추가:
62추가: pub(crate) struct Watchdog {
63추가: last_activity: Duration,
64추가: approved: bool,
65추가: }
66추가: impl Watchdog {
67추가: pub fn new() -> Self {
68추가: Self {
69추가: last_activity: Duration::ZERO,
70추가: approved: false,
71추가: }
72추가: }
73추가: pub fn check(&self, elapsed: Duration) -> Result<()> {
74추가: if if self.approved {
75추가: elapsed.saturating_sub(self.last_activity) >= Duration::from_secs(60)
76추가: } else {
77추가: elapsed > Duration::from_secs(300)
78추가: } {
79추가: Err(ErrorCode::Limit)
80추가: } else {
81추가: Ok(())
82추가: }
83추가: }
84추가: pub fn activity(&mut self, elapsed: Duration) -> Result<()> {
85추가: self.check(elapsed)?;
86추가: self.last_activity = elapsed;
87추가: Ok(())
88추가: }
89추가: pub fn resume(&mut self, elapsed: Duration, approved: bool) {
90추가: self.approved |= approved;
91추가: self.last_activity = elapsed;
92추가: }
93추가: }
94추가:
95추가: #[cfg(test)]
96추가: #[path = "../../../tests/rust-archive-worker/resource_budget.rs"]
97추가: mod tests;
수정experiments/rust-archive-worker/src/runtime.rs+173-25
@@ -2,6 +2,7 @@ use crate::{
22 archive,
33 filesystem::{self, Dir},
44 protocol::*,
5추가: resources::{Budget, Monitor, Watchdog},
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
@@ -168,9 +250,6 @@ impl<W: Write> Job<W> {
168250 }
169251 fn check(&mut self) -> Result<()> {
170252 self.parent.check()?;
171삭제: if self.started.elapsed() > Duration::from_secs(300) {
172삭제: return Err(ErrorCode::Limit);
173삭제: }
174253 let state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
175254 if let Some(error) = state.fault {
176255 return Err(error);
@@ -178,7 +257,7 @@ impl<W: Write> Job<W> {
178257 if state.cancelled && state.phase == 0 {
179258 return Err(ErrorCode::None);
180259 }
181삭제: Ok(())
260추가: self.watchdog.check(self.started.elapsed())
182261 }
183262 fn cutoff(&mut self) -> Result<()> {
184263 self.check()?;
@@ -220,7 +299,12 @@ impl<W: Write> Job<W> {
220299 Some(length),
221300 self.terminal.created_count as u32,
222301 )?;
302추가: let mut first_chunk = true;
223303 let p = filesystem::publish_reader_mode(root, name, data, length, replace, &mut |commit| {
304추가: if !first_chunk {
305추가: self.activity()?;
306추가: }
307추가: first_chunk = false;
224308 if commit && last {
225309 self.cutoff()
226310 } else {
@@ -272,11 +356,23 @@ impl<W: Write> Job<W> {
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::Read { bytes, total } => {
392추가: self.activity()?;
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,
@@ -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;
@@ -554,7 +650,7 @@ impl<W: Write> Job<W> {
554650 let name = archive::valid_name(leaf, false)?;
555651 let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?;
556652 filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?;
557삭제: let members = crate::create::plan(&sources, start.limits, &mut || self.check())?;
653추가: let members = crate::create::plan(&sources, limits, self)?;
558654 let secret = if encryption == Encryption::Aes256 {
559655 let secret = self.password(PasswordPurpose::Encrypt, 1)?;
560656 if secret.0.is_empty() {
@@ -567,9 +663,9 @@ impl<W: Write> Job<W> {
567663 let (mut data, length) = crate::create::zip(
568664 &members,
569665 method,
570삭제: start.limits,
666추가: limits,
571667 secret.as_ref().map(|s| s.0.as_slice()),
572삭제: &mut || self.check(),
668추가: self,
573669 )?;
574670 filesystem::preflight_space(&root, &[(name.clone(), length)], None)?;
575671 self.output_reader(&root, &name, &mut data, length, None, true, None)?;
@@ -580,6 +676,27 @@ impl<W: Write> Job<W> {
580676 Ok(())
581677 }
582678}
679추가: impl<W: Write> Monitor for Job<W> {
680추가: fn check(&mut self) -> Result<()> {
681추가: Job::check(self)
682추가: }
683추가: fn activity(&mut self) -> Result<()> {
684추가: self.check()?;
685추가: self.watchdog.activity(self.started.elapsed())
686추가: }
687추가: fn observe(&mut self, usage: ResourceUsage, storage: Option<&std::fs::File>) -> Result<()> {
688추가: self.check()?;
689추가: let Some(budget) = &self.budget else {
690추가: return Ok(());
691추가: };
692추가: let scope = budget.required(usage)?;
693추가: if !scope.any() {
694추가: return Ok(());
695추가: }
696추가: self.request_resource(scope, usage, storage)
697추가: }
698추가: }
699추가:
583700pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
584701 input: R,
585702 output: W,
@@ -590,9 +707,17 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
590707 let (job, _, message) = reader
591708 .read()?
592709 .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),
710추가: let (start, interactive, budget) = match message {
711추가: Message::Start(start) => (start, false, None),
712추가: Message::StartInteractive(start) => (start, true, None),
713추가: Message::StartGuarded(guarded) if guarded.valid() => {
714추가: let budget = Budget {
715추가: soft: guarded.start.limits,
716추가: ceiling: guarded.ceiling,
717추가: granted: ResourceScope::default(),
718추가: };
719추가: (guarded.start, guarded.interactive, Some(budget))
720추가: }
596721 _ => {
597722 return Err(std::io::Error::new(
598723 std::io::ErrorKind::InvalidData,
@@ -608,6 +733,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
608733 challenge: None,
609734 conflict_reply: None,
610735 password: None,
736추가: resource_reply: None,
611737 input_closed: false,
612738 }));
613739 let wake = Arc::new(Condvar::new());
@@ -668,6 +794,24 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
668794 }
669795 control_wake.notify_all();
670796 }
797추가: Message::ResourceReply {
798추가: challenge_id,
799추가: scope,
800추가: allow,
801추가: } => {
802추가: if state.phase != 0
803추가: || state.challenge != Some(Challenge::Resource(challenge_id, scope))
804추가: || state.resource_reply.is_some()
805추가: {
806추가: state.fault = Some(ErrorCode::Protocol);
807추가: } else {
808추가: state.challenge = None;
809추가: if !state.cancelled {
810추가: state.resource_reply = Some(allow);
811추가: }
812추가: }
813추가: control_wake.notify_all();
814추가: }
671815 Message::Cancel => {
672816 let status = match state.phase {
673817 2 => CancelStatus::Finished,
@@ -703,6 +847,9 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
703847 wake,
704848 next_challenge: 0,
705849 interactive,
850추가: action: start.action.kind(),
851추가: budget,
852추가: watchdog: Watchdog::new(),
706853 remaining_choice: None,
707854 parent,
708855 started: Instant::now(),
@@ -733,6 +880,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
733880 state.challenge = None;
734881 state.password = None;
735882 state.conflict_reply = None;
883추가: state.resource_reply = None;
736884 if let Some(error) = state.fault.or(error) {
737885 context.terminal.error = error;
738886 context.terminal.outcome = if error == ErrorCode::None {
수정experiments/rust-archive-worker/src/seven_zip.rs+42-9
@@ -266,7 +266,7 @@ impl Streams {
266266 &self,
267267 input: &mut std::fs::File,
268268 data_end: u64,
269삭제: check: &mut impl FnMut() -> Result<()>,
269추가: check: &mut impl crate::resources::Monitor,
270270 ) -> Result<Vec<(u64, u64)>> {
271271 let mut at = 32u64
272272 .checked_add(self.position as u64)
@@ -293,7 +293,7 @@ impl Streams {
293293 input: &mut std::fs::File,
294294 ranges: &[(u64, u64)],
295295 output: &mut std::fs::File,
296삭제: check: &mut impl FnMut() -> Result<()>,
296추가: check: &mut impl crate::resources::Monitor,
297297 ) -> Result<()> {
298298 use std::io::{Read, Seek, SeekFrom, Write};
299299 let total = self.folders.iter().try_fold(0u64, |sum, f| {
@@ -301,8 +301,16 @@ impl Streams {
301301 })?;
302302 crate::space::ensure(output, total)?;
303303 for (f, (start, size)) in self.folders.iter().zip(ranges) {
304삭제: check()?;
304추가: check.check()?;
305305 let base = output.stream_position().map_err(crate::space::io_error)?;
306추가: check.observe(
307추가: ResourceUsage {
308추가: compressed_bytes: Some(*size),
309추가: ratio_output_bytes: Some(f.size as u64),
310추가: ..ResourceUsage::default()
311추가: },
312추가: Some(output),
313추가: )?;
306314 input
307315 .seek(SeekFrom::Start(*start))
308316 .map_err(crate::space::io_error)?;
@@ -314,15 +322,17 @@ impl Streams {
314322 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
315323 let mut remaining = *size;
316324 while remaining != 0 {
317삭제: check()?;
325추가: check.check()?;
318326 let n = remaining.min(buffer.len() as u64) as usize;
319327 input
320328 .read_exact(&mut buffer[..n])
321329 .map_err(|_| ErrorCode::Integrity)?;
330추가: crate::space::ensure(output, n as u64)?;
322331 output
323332 .write_all(&buffer[..n])
324333 .map_err(crate::space::io_error)?;
325334 remaining -= n as u64;
335추가: check.activity()?;
326336 }
327337 }
328338 [3, 1, 1] | [0x21] => crate::lzma::decode_stream(
@@ -370,7 +380,7 @@ fn digest(
370380 file: &mut std::fs::File,
371381 start: u64,
372382 size: u64,
373삭제: check: &mut impl FnMut() -> Result<()>,
383추가: check: &mut impl crate::resources::Monitor,
374384) -> Result<u32> {
375385 use std::io::{Read, Seek, SeekFrom};
376386 file.seek(SeekFrom::Start(start))
@@ -379,12 +389,13 @@ fn digest(
379389 let mut remaining = size;
380390 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
381391 while remaining != 0 {
382삭제: check()?;
392추가: check.check()?;
383393 let n = remaining.min(buffer.len() as u64) as usize;
384394 file.read_exact(&mut buffer[..n])
385395 .map_err(crate::space::io_error)?;
386396 crc = crc32(crc, &buffer[..n]);
387397 remaining -= n as u64;
398추가: check.activity()?;
388399 }
389400 Ok(crc)
390401}
@@ -546,10 +557,10 @@ pub(crate) fn open(
546557 length: u64,
547558 limits: Limits,
548559 decode: bool,
549삭제: check: &mut impl FnMut() -> Result<()>,
560추가: check: &mut impl crate::resources::Monitor,
550561) -> Result<crate::streaming::Catalog> {
551562 use std::io::{Read, Seek, SeekFrom};
552삭제: check()?;
563추가: check.check()?;
553564 if length > limits.input {
554565 return Err(ErrorCode::Limit);
555566 }
@@ -650,6 +661,28 @@ pub(crate) fn open(
650661 return Err(ErrorCode::Integrity);
651662 }
652663 r.end()?;
664추가: let total = members.iter().try_fold(0u64, |n, m| {
665추가: n.checked_add(m.entry.size).ok_or(ErrorCode::Limit)
666추가: })?;
667추가: let packed = streams
668추가: .as_ref()
669추가: .map(|s| {
670추가: s.packed.iter().try_fold(0u64, |sum, size| {
671추가: sum.checked_add(*size as u64).ok_or(ErrorCode::Integrity)
672추가: })
673추가: })
674추가: .transpose()?;
675추가: check.observe(
676추가: ResourceUsage {
677추가: estimated_bytes: Some(total),
678추가: estimated_entries: Some(members.len() as u32),
679추가: compressed_bytes: packed,
680추가: ratio_output_bytes: Some(total),
681추가: ..ResourceUsage::default()
682추가: },
683추가: Some(&data),
684추가: )?;
685추가: check.activity()?;
653686 let mut offsets = vec![0; members.len()];
654687 if let Some(streams) = streams {
655688 if streams.folders.iter().map(|f| f.sizes.len()).sum::<usize>() != stream_indices.len() {
@@ -682,7 +715,7 @@ pub(crate) fn parse(
682715 input: &[u8],
683716 limits: Limits,
684717 decode: bool,
685삭제: check: &mut impl FnMut() -> Result<()>,
718추가: check: &mut impl crate::resources::Monitor,
686719) -> Result<Vec<Member>> {
687720 use std::io::{Read, Seek, SeekFrom, Write};
688721 let mut source = crate::spool::temporary()?;
수정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+3-3
@@ -114,11 +114,11 @@ impl Snapshot {
114114 pub(crate) fn capture(
115115 source: &mut File,
116116 limit: u64,
117삭제: check: &mut impl FnMut() -> Result<()>,
117추가: check: &mut impl crate::resources::Monitor,
118118 ) -> Result<Self> {
119119 Self::capture_reporting(source, limit, &mut |step| match step {
120삭제: Step::Check => check(),
121삭제: Step::Read { .. } => Ok(()),
120추가: Step::Check => check.check(),
121추가: Step::Read { .. } => check.activity(),
122122 })
123123 }
124124 fn capture_reporting(
수정experiments/rust-archive-worker/src/streaming.rs+53-10
@@ -52,7 +52,7 @@ impl Catalog {
5252 limits: Limits,
5353 decode: bool,
5454 password: Option<&[u8]>,
55삭제: check: &mut impl FnMut() -> Result<()>,
55추가: check: &mut impl crate::resources::Monitor,
5656 ) -> Result<Self> {
5757 let mut magic = [0; 6];
5858 let n = len.min(6) as usize;
@@ -121,7 +121,7 @@ fn tar(
121121 len: u64,
122122 limits: Limits,
123123 format: Format,
124삭제: check: &mut impl FnMut() -> Result<()>,
124추가: check: &mut impl crate::resources::Monitor,
125125) -> Result<Catalog> {
126126 let mut cursor = 0u64;
127127 let mut total = 0u64;
@@ -129,7 +129,7 @@ fn tar(
129129 let mut offsets = Vec::new();
130130 let mut metadata = MetadataBudget::default();
131131 loop {
132삭제: check()?;
132추가: check.check()?;
133133 let mut header = [0; 512];
134134 if add(cursor, 512)? > len {
135135 return Err(ErrorCode::Integrity);
@@ -142,13 +142,14 @@ fn tar(
142142 let mut buffer = Zeroizing::new([0; CHUNK]);
143143 let mut remaining = len - cursor - 512;
144144 while remaining != 0 {
145삭제: check()?;
145추가: check.check()?;
146146 let n = remaining.min(CHUNK as u64) as usize;
147147 io(data.read_exact(&mut buffer[..n]))?;
148148 if buffer[..n].iter().any(|b| *b != 0) {
149149 return Err(ErrorCode::Integrity);
150150 }
151151 remaining -= n as u64;
152추가: check.activity()?;
152153 }
153154 break;
154155 }
@@ -193,6 +194,15 @@ fn tar(
193194 .checked_add(size)
194195 .filter(|n| *n <= limits.output)
195196 .ok_or(ErrorCode::Limit)?;
197추가: check.observe(
198추가: ResourceUsage {
199추가: estimated_bytes: Some(total),
200추가: actual_entries: Some(members.len() as u32 + 1),
201추가: ..ResourceUsage::default()
202추가: },
203추가: Some(&data),
204추가: )?;
205추가: check.activity()?;
196206 let start = add(cursor, 512)?;
197207 cursor = add(
198208 start,
@@ -232,8 +242,9 @@ fn inflate(
232242 gzip: bool,
233243 limit: u64,
234244 output: &mut File,
235삭제: check: &mut impl FnMut() -> Result<()>,
245추가: check: &mut impl crate::resources::Monitor,
236246) -> Result<(u64, u32)> {
247추가: let base = io(output.stream_position())?;
237248 let mut remaining = length;
238249 let mut buffer = Zeroizing::new([0; CHUNK]);
239250 let mut plain = Zeroizing::new([0; CHUNK]);
@@ -244,7 +255,7 @@ fn inflate(
244255 loop {
245256 let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
246257 loop {
247삭제: check()?;
258추가: check.check()?;
248259 if used == have && remaining != 0 {
249260 have = input
250261 .read(&mut buffer[..remaining.min(CHUNK as u64) as usize])
@@ -266,6 +277,18 @@ fn inflate(
266277 .checked_add(n as u64)
267278 .filter(|n| *n <= limit)
268279 .ok_or(ErrorCode::Limit)?;
280추가: check.observe(
281추가: ResourceUsage {
282추가: actual_bytes: Some(base.checked_add(total).ok_or(ErrorCode::Limit)?),
283추가: compressed_bytes: Some(length),
284추가: ratio_output_bytes: Some(total),
285추가: ..ResourceUsage::default()
286추가: },
287추가: Some(output),
288추가: )?;
289추가: if n != 0 {
290추가: check.activity()?;
291추가: }
269292 crc = crc32(crc, &plain[..n]);
270293 crate::space::ensure(output, n as u64)?;
271294 io(output.write_all(&plain[..n]))?;
@@ -398,7 +421,7 @@ fn zip(
398421 limits: Limits,
399422 decode: bool,
400423 password: Option<&[u8]>,
401삭제: check: &mut impl FnMut() -> Result<()>,
424추가: check: &mut impl crate::resources::Monitor,
402425) -> Result<Catalog> {
403426 if len < 22 {
404427 return Err(ErrorCode::Integrity);
@@ -463,6 +486,13 @@ fn zip(
463486 if count > limits.entries as u64 {
464487 return Err(ErrorCode::Limit);
465488 }
489추가: check.observe(
490추가: ResourceUsage {
491추가: estimated_entries: Some(count as u32),
492추가: ..ResourceUsage::default()
493추가: },
494추가: Some(source),
495추가: )?;
466496 if add(central, central_size)? != central_end {
467497 return Err(ErrorCode::Integrity);
468498 }
@@ -473,7 +503,7 @@ fn zip(
473503 let mut packed = Vec::new();
474504 let mut spans = Vec::new();
475505 for id in 0..count {
476삭제: check()?;
506추가: check.check()?;
477507 if add(cursor, 46)? > central_end {
478508 return Err(ErrorCode::Integrity);
479509 }
@@ -532,6 +562,17 @@ fn zip(
532562 .checked_add(size)
533563 .filter(|n| *n <= limits.output)
534564 .ok_or(ErrorCode::Limit)?;
565추가: check.observe(
566추가: ResourceUsage {
567추가: estimated_bytes: Some(total),
568추가: estimated_entries: Some(count as u32),
569추가: compressed_bytes: Some(compressed - overhead),
570추가: ratio_output_bytes: Some(size),
571추가: ..ResourceUsage::default()
572추가: },
573추가: Some(source),
574추가: )?;
575추가: check.activity()?;
535576 let mode = u32at(&h, 38) >> 16;
536577 let kind = match mode & 0xf000 {
537578 0xa000 => EntryKind::Link,
@@ -654,7 +695,7 @@ fn zip(
654695 }
655696 let mut offsets = Vec::new();
656697 for (member, packed) in members.iter().zip(packed) {
657삭제: check()?;
698추가: check.check()?;
658699 offsets.push(io(data.stream_position())?);
659700 if !decode {
660701 continue;
@@ -691,7 +732,7 @@ fn zip(
691732 let mut total = 0u64;
692733 let mut crc = 0;
693734 loop {
694삭제: check()?;
735추가: check.check()?;
695736 let n = io(reader.read(&mut buffer[..]))?;
696737 if n == 0 {
697738 break;
@@ -700,6 +741,8 @@ fn zip(
700741 .checked_add(n as u64)
701742 .filter(|n| *n <= member.entry.size)
702743 .ok_or(ErrorCode::Integrity)?;
744추가: check.activity()?;
745추가: crate::space::ensure(&data, n as u64)?;
703746 crc = crc32(crc, &buffer[..n]);
704747 io(data.write_all(&buffer[..n]))?;
705748 }
수정experiments/rust-archive-worker/src/wire.rs+72-0
@@ -158,6 +158,25 @@ structure!(ListId {
158158});
159159structure!(Source { path, archive_name });
160160structure!(Start { action, limits });
161추가: structure!(GuardedStart {
162추가: start,
163추가: ceiling,
164추가: interactive
165추가: });
166추가: structure!(ResourceScope {
167추가: output,
168추가: entries,
169추가: ratio
170추가: });
171추가: structure!(ResourceUsage {
172추가: estimated_bytes,
173추가: actual_bytes,
174추가: estimated_entries,
175추가: actual_entries,
176추가: compressed_bytes,
177추가: ratio_output_bytes,
178추가: available_bytes
179추가: });
161180structure!(Entry {
162181 entry_id,
163182 name,
@@ -341,6 +360,39 @@ impl Message {
341360 apply_to_remaining.enc(&mut e)?;
342361 5
343362 }
363추가: Self::StartGuarded(v) => {
364추가: if !v.valid() {
365추가: return Err(invalid());
366추가: }
367추가: v.enc(&mut e)?;
368추가: 6
369추가: }
370추가: Self::ResourceReply {
371추가: challenge_id,
372추가: scope,
373추가: allow,
374추가: } => {
375추가: challenge_id.enc(&mut e)?;
376추가: scope.enc(&mut e)?;
377추가: allow.enc(&mut e)?;
378추가: 7
379추가: }
380추가: Self::ResourceRequired {
381추가: challenge_id,
382추가: action,
383추가: scope,
384추가: usage,
385추가: soft_limits,
386추가: ceiling,
387추가: } => {
388추가: challenge_id.enc(&mut e)?;
389추가: action.enc(&mut e)?;
390추가: scope.enc(&mut e)?;
391추가: usage.enc(&mut e)?;
392추가: soft_limits.enc(&mut e)?;
393추가: ceiling.enc(&mut e)?;
394추가: 110
395추가: }
344396 Self::Accepted { action, encryption } => {
345397 action.enc(&mut e)?;
346398 encryption.enc(&mut e)?;
@@ -460,6 +512,26 @@ impl Message {
460512 choice: Wire::dec(&mut d)?,
461513 apply_to_remaining: Wire::dec(&mut d)?,
462514 },
515추가: 6 => {
516추가: let start = GuardedStart::dec(&mut d)?;
517추가: if !start.valid() {
518추가: return Err(invalid());
519추가: }
520추가: Self::StartGuarded(start)
521추가: }
522추가: 7 => Self::ResourceReply {
523추가: challenge_id: Wire::dec(&mut d)?,
524추가: scope: Wire::dec(&mut d)?,
525추가: allow: Wire::dec(&mut d)?,
526추가: },
527추가: 110 => Self::ResourceRequired {
528추가: challenge_id: Wire::dec(&mut d)?,
529추가: action: Wire::dec(&mut d)?,
530추가: scope: Wire::dec(&mut d)?,
531추가: usage: Wire::dec(&mut d)?,
532추가: soft_limits: Wire::dec(&mut d)?,
533추가: ceiling: Wire::dec(&mut d)?,
534추가: },
463535 100 => Self::Accepted {
464536 action: Wire::dec(&mut d)?,
465537 encryption: Wire::dec(&mut d)?,
추가tests/rust-archive-worker/guarded.rs+554-0
@@ -0,0 +1,554 @@
1추가: use super::*;
2추가: use std::{io::Read, process::Child, sync::mpsc, time::Duration};
3추가:
4추가: struct Running(Child);
5추가: impl Drop for Running {
6추가: fn drop(&mut self) {
7추가: let _ = self.0.kill();
8추가: let _ = self.0.wait();
9추가: }
10추가: }
11추가: fn run(
12추가: s: &Scratch,
13추가: start: GuardedStart,
14추가: respond: impl FnMut(&Message) -> Option<Vec<Message>>,
15추가: ) -> Vec<Message> {
16추가: run_fault(s, start, None, respond)
17추가: }
18추가: fn run_fault(
19추가: s: &Scratch,
20추가: start: GuardedStart,
21추가: fault: Option<&str>,
22추가: mut respond: impl FnMut(&Message) -> Option<Vec<Message>>,
23추가: ) -> Vec<Message> {
24추가: let mut command = s.worker();
25추가: #[cfg(target_os = "linux")]
26추가: if let Some(fault) = fault {
27추가: let shim = s.0.join("io_fault.so");
28추가: assert!(
29추가: Command::new("cc")
30추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
31추가: .arg(
32추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
33추가: .join("../../tests/rust-archive-worker/io_fault.c")
34추가: )
35추가: .args(["-ldl", "-o"])
36추가: .arg(&shim)
37추가: .status()
38추가: .unwrap()
39추가: .success()
40추가: );
41추가: command
42추가: .env("LD_PRELOAD", shim)
43추가: .env("ZIPELO_TEST_FAULT", fault)
44추가: .env("ZIPELO_TEST_MARKER", s.0.join("marker"));
45추가: }
46추가: #[cfg(not(target_os = "linux"))]
47추가: assert!(fault.is_none());
48추가: let mut child = Running(
49추가: command
50추가: .stdin(Stdio::piped())
51추가: .stdout(Stdio::piped())
52추가: .stderr(Stdio::piped())
53추가: .spawn()
54추가: .unwrap(),
55추가: );
56추가: let mut writer = Some(Writer::new(child.0.stdin.take().unwrap(), 17));
57추가: writer
58추가: .as_mut()
59추가: .unwrap()
60추가: .send(&Message::StartGuarded(start))
61추가: .unwrap();
62추가: let stdout = child.0.stdout.take().unwrap();
63추가: let mut stderr = child.0.stderr.take().unwrap();
64추가: let (send, receive) = mpsc::channel();
65추가: let reader = std::thread::spawn(move || {
66추가: let mut reader = Reader::new(stdout);
67추가: loop {
68추가: let frame = reader.read();
69추가: let done = !matches!(frame, Ok(Some(_)));
70추가: if send.send(frame).is_err() || done {
71추가: break;
72추가: }
73추가: }
74추가: });
75추가: let mut events = Vec::new();
76추가: loop {
77추가: let Some((job, _, event)) = receive
78추가: .recv_timeout(Duration::from_secs(20))
79추가: .expect("worker timeout")
80추가: .unwrap()
81추가: else {
82추가: break;
83추가: };
84추가: assert_eq!(job, 17);
85추가: if let Some(messages) = respond(&event) {
86추가: if messages.is_empty() {
87추가: writer = None;
88추가: } else {
89추가: for message in messages {
90추가: writer.as_mut().unwrap().send(&message).unwrap();
91추가: }
92추가: }
93추가: }
94추가: let done = matches!(event, Message::Terminal(_));
95추가: events.push(event);
96추가: if done {
97추가: writer = None;
98추가: }
99추가: }
100추가: assert!(child.0.wait().unwrap().success(), "{events:?}");
101추가: let mut errors = Vec::new();
102추가: stderr.read_to_end(&mut errors).unwrap();
103추가: assert!(errors.is_empty(), "{errors:?}");
104추가: reader.join().unwrap();
105추가: assert!(matches!(events.last(), Some(Message::Terminal(_))));
106추가: events
107추가: }
108추가: fn request(s: &Scratch, output: u64, ceiling: u64) -> GuardedStart {
109추가: GuardedStart {
110추가: start: Start {
111추가: action: Action::Extract {
112추가: archive: s.path("input"),
113추가: destination: s.path("output"),
114추가: selection: Selection::All,
115추가: list_id: None,
116추가: gzip_output_name: None,
117추가: },
118추가: limits: Limits {
119추가: output,
120추가: ..Limits::default()
121추가: },
122추가: },
123추가: ceiling: Limits {
124추가: output: ceiling,
125추가: entries: 200_000,
126추가: ..Limits::default()
127추가: },
128추가: interactive: false,
129추가: }
130추가: }
131추가: fn setup() -> Scratch {
132추가: let s = Scratch::new();
133추가: fs::write(s.0.join("input"), include_bytes!("fixtures/deflate.zip")).unwrap();
134추가: fs::create_dir(s.0.join("output")).unwrap();
135추가: #[cfg(unix)]
136추가: {
137추가: use std::os::unix::fs::PermissionsExt;
138추가: fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
139추가: }
140추가: s
141추가: }
142추가: fn approve(event: &Message) -> Option<Vec<Message>> {
143추가: if let Message::ResourceRequired {
144추가: challenge_id,
145추가: scope,
146추가: ..
147추가: } = event
148추가: {
149추가: Some(vec![Message::ResourceReply {
150추가: challenge_id: *challenge_id,
151추가: scope: *scope,
152추가: allow: true,
153추가: }])
154추가: } else {
155추가: None
156추가: }
157추가: }
158추가: #[test]
159추가: fn scaled_output_boundaries_and_approval() {
160추가: for limit in [
161추가: PAYLOAD.len() as u64 + 1,
162추가: PAYLOAD.len() as u64,
163추가: PAYLOAD.len() as u64 - 1,
164추가: ] {
165추가: let s = setup();
166추가: let events = run(&s, request(&s, limit, 64), approve);
167추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
168추가: assert_eq!(
169추가: events
170추가: .iter()
171추가: .filter(|e| matches!(e, Message::ResourceRequired { .. }))
172추가: .count(),
173추가: 1
174추가: );
175추가: assert_eq!(
176추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
177추가: PAYLOAD
178추가: );
179추가: }
180추가: }
181추가: #[test]
182추가: fn decline_cancel_and_eof_publish_nothing() {
183추가: for mode in 0..3 {
184추가: let s = setup();
185추가: let events = run(&s, request(&s, 16, 64), |event| {
186추가: if let Message::ResourceRequired {
187추가: challenge_id,
188추가: scope,
189추가: usage,
190추가: ..
191추가: } = event
192추가: {
193추가: assert_eq!(usage.estimated_bytes, None);
194추가: assert_eq!(usage.actual_bytes, None);
195추가: assert!(usage.available_bytes.is_some());
196추가: Some(match mode {
197추가: 0 => vec![Message::ResourceReply {
198추가: challenge_id: *challenge_id,
199추가: scope: *scope,
200추가: allow: false,
201추가: }],
202추가: 1 => vec![Message::Cancel],
203추가: _ => vec![],
204추가: })
205추가: } else {
206추가: None
207추가: }
208추가: });
209추가: assert_eq!(
210추가: terminal(&events).outcome,
211추가: if mode == 2 {
212추가: Outcome::Failed
213추가: } else {
214추가: Outcome::Cancelled
215추가: },
216추가: "{events:?}"
217추가: );
218추가: assert_eq!(terminal(&events).publication, Publication::None);
219추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
220추가: if mode == 1 {
221추가: assert!(events.iter().any(|e| matches!(
222추가: e,
223추가: Message::CancelAck {
224추가: status: CancelStatus::Requested,
225추가: ..
226추가: }
227추가: )));
228추가: }
229추가: }
230추가: }
231추가: #[test]
232추가: fn stale_duplicate_wrong_scope_and_premature_replies_are_rejected() {
233추가: for mode in 0..4 {
234추가: let s = setup();
235추가: let events = run(&s, request(&s, 16, 64), |event| {
236추가: if mode == 3 && matches!(event, Message::Accepted { .. }) {
237추가: return Some(vec![Message::ResourceReply {
238추가: challenge_id: 99,
239추가: scope: ResourceScope::default(),
240추가: allow: true,
241추가: }]);
242추가: }
243추가: if let Message::ResourceRequired {
244추가: challenge_id,
245추가: scope,
246추가: ..
247추가: } = event
248추가: {
249추가: let reply = |id, scope| Message::ResourceReply {
250추가: challenge_id: id,
251추가: scope,
252추가: allow: true,
253추가: };
254추가: Some(match mode {
255추가: 0 => vec![reply(challenge_id + 1, *scope)],
256추가: 1 => vec![reply(*challenge_id, ResourceScope::default())],
257추가: 2 => vec![reply(*challenge_id, *scope), reply(*challenge_id, *scope)],
258추가: _ => vec![],
259추가: })
260추가: } else {
261추가: None
262추가: }
263추가: });
264추가: assert_eq!(
265추가: terminal(&events).error,
266추가: ErrorCode::Protocol,
267추가: "{mode}: {events:?}"
268추가: );
269추가: assert_eq!(terminal(&events).publication, Publication::None);
270추가: }
271추가: }
272추가: #[test]
273추가: fn ceiling_bytes_and_entries_cannot_be_approved_away() {
274추가: for entries in [false, true] {
275추가: let s = setup();
276추가: let mut start = request(&s, 1, 16);
277추가: if entries {
278추가: start.start.limits.output = 64;
279추가: start.ceiling.output = 64;
280추가: start.start.limits.entries = 1;
281추가: start.ceiling.entries = 2;
282추가: let members = (0..3)
283추가: .map(|id| archive::Member {
284추가: entry: Entry {
285추가: entry_id: id,
286추가: name: format!("empty{id}"),
287추가: kind: EntryKind::File,
288추가: size: 0,
289추가: compressed_size: 0,
290추가: encrypted: false,
291추가: },
292추가: data: Vec::new(),
293추가: })
294추가: .collect::<Vec<_>>();
295추가: let zip =
296추가: archive::create_zip(&members, Method::Store, Limits::default(), &mut || Ok(()))
297추가: .unwrap();
298추가: fs::write(s.0.join("input"), zip).unwrap();
299추가: }
300추가: let mut approved = false;
301추가: let events = run(&s, start, |event| {
302추가: if matches!(event, Message::ResourceRequired { .. }) {
303추가: approved = true;
304추가: }
305추가: approve(event)
306추가: });
307추가: assert!(approved);
308추가: assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}");
309추가: assert_eq!(terminal(&events).created_count, 0);
310추가: }
311추가: }
312추가: #[test]
313추가: fn entries_have_a_separate_approval() {
314추가: let s = setup();
315추가: let mut start = request(&s, 64, 64);
316추가: start.start.limits.entries = 1;
317추가: start.ceiling.entries = 3;
318추가: let events = run(&s, start, |event| {
319추가: if let Message::ResourceRequired { scope, .. } = event {
320추가: assert!(scope.entries);
321추가: assert!(!scope.output);
322추가: }
323추가: approve(event)
324추가: });
325추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
326추가: }
327추가: #[test]
328추가: fn resource_then_password_then_conflict_use_distinct_questions() {
329추가: let s = setup();
330추가: fs::write(
331추가: s.0.join("input"),
332추가: include_bytes!("fixtures/aes2-deflate.zip"),
333추가: )
334추가: .unwrap();
335추가: fs::create_dir_all(s.0.join("output/folder")).unwrap();
336추가: fs::write(s.0.join("output/payload.bin"), b"old").unwrap();
337추가: let mut start = request(&s, 16, 8192);
338추가: start.interactive = true;
339추가: let mut ids = Vec::new();
340추가: let events = run(&s, start, |event| match event {
341추가: Message::ResourceRequired { challenge_id, .. } => {
342추가: ids.push(*challenge_id);
343추가: approve(event)
344추가: }
345추가: Message::PasswordRequired { challenge_id, .. } => {
346추가: ids.push(*challenge_id);
347추가: Some(vec![Message::Password {
348추가: challenge_id: *challenge_id,
349추가: secret: Secret(TEST_PASSWORD.to_vec()),
350추가: }])
351추가: }
352추가: Message::ConflictRequired { challenge_id, .. } => {
353추가: ids.push(*challenge_id);
354추가: Some(vec![Message::ConflictReply {
355추가: challenge_id: *challenge_id,
356추가: choice: ConflictChoice::Overwrite,
357추가: apply_to_remaining: false,
358추가: }])
359추가: }
360추가: _ => None,
361추가: });
362추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
363추가: assert!(ids.len() >= 3, "{events:?}");
364추가: assert!(ids.windows(2).all(|w| w[0] < w[1]));
365추가: }
366추가: #[test]
367추가: fn create_source_total_is_approved_before_password() {
368추가: let s = setup();
369추가: fs::write(s.0.join("source"), b"12345678").unwrap();
370추가: let mut start = request(&s, 7, 8);
371추가: start.start.action = Action::CreateZip {
372추가: sources: vec![Source {
373추가: path: s.path("source"),
374추가: archive_name: "source".into(),
375추가: }],
376추가: output_file: s.path("new.zip"),
377추가: method: Method::Store,
378추가: encryption: Encryption::Aes256,
379추가: };
380추가: let mut approved = false;
381추가: let events = run(&s, start, |event| match event {
382추가: Message::ResourceRequired { action, .. } => {
383추가: assert_eq!(*action, ActionKind::CreateZip);
384추가: approved = true;
385추가: approve(event)
386추가: }
387추가: Message::PasswordRequired { challenge_id, .. } => {
388추가: assert!(approved);
389추가: Some(vec![Message::Password {
390추가: challenge_id: *challenge_id,
391추가: secret: Secret(b"secret".to_vec()),
392추가: }])
393추가: }
394추가: _ => None,
395추가: });
396추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
397추가: assert!(s.0.join("new.zip").exists());
398추가: }
399추가: #[test]
400추가: fn guarded_wire_round_trip_and_invalid_ceiling() {
401추가: let s = setup();
402추가: let start = request(&s, 16, 64);
403추가: let mut bytes = Vec::new();
404추가: Writer::new(&mut bytes, 17)
405추가: .send(&Message::StartGuarded(start.clone()))
406추가: .unwrap();
407추가: assert_eq!(&bytes[6..8], &6u16.to_le_bytes());
408추가: match Reader::new(bytes.as_slice()).read().unwrap().unwrap().2 {
409추가: Message::StartGuarded(decoded) => assert_eq!(decoded, start),
410추가: other => panic!("{other:?}"),
411추가: }
412추가: let mut invalid = start;
413추가: invalid.ceiling.output = 64 * 1024 * 1024 * 1024 + 1;
414추가: assert!(!invalid.valid());
415추가: assert!(
416추가: Writer::new(Vec::new(), 17)
417추가: .send(&Message::StartGuarded(invalid))
418추가: .is_err()
419추가: );
420추가: let mut reply = Vec::new();
421추가: Writer::new(&mut reply, 17)
422추가: .send(&Message::ResourceReply {
423추가: challenge_id: 4,
424추가: scope: ResourceScope {
425추가: ratio: true,
426추가: ..ResourceScope::default()
427추가: },
428추가: allow: true,
429추가: })
430추가: .unwrap();
431추가: assert_eq!(&reply[6..8], &7u16.to_le_bytes());
432추가: reply[43] = 2;
433추가: assert!(Reader::new(reply.as_slice()).read().is_err());
434추가: }
435추가:
436추가: fn generate(s: &Scratch, case: &str) {
437추가: let result = Command::new("python3")
438추가: .arg(
439추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
440추가: .join("../../tests/rust-archive-worker/guarded_cases.py"),
441추가: )
442추가: .arg(&s.0)
443추가: .arg(case)
444추가: .output()
445추가: .unwrap();
446추가: assert!(
447추가: result.status.success(),
448추가: "{}",
449추가: String::from_utf8_lossy(&result.stderr)
450추가: );
451추가: }
452추가: #[test]
453추가: fn compressed_formats_keep_limits_after_permission() {
454추가: for kind in ["gz", "tar", "targz", "bz2", "xz", "7z"] {
455추가: let s = setup();
456추가: match kind {
457추가: "gz" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.gz")).unwrap(),
458추가: "tar" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar")).unwrap(),
459추가: "targz" => {
460추가: fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar.gz")).unwrap()
461추가: }
462추가: "bz2" | "xz" => generate(&s, kind),
463추가: "7z" => fs::write(
464추가: s.0.join("input"),
465추가: fs::read(
466추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
467추가: .join("../../tests/rust-archive-worker/fixtures/7z/copy.7z"),
468추가: )
469추가: .unwrap(),
470추가: )
471추가: .unwrap(),
472추가: _ => unreachable!(),
473추가: }
474추가: let mut start = request(&s, 16, 65536);
475추가: if kind == "gz" {
476추가: if let Action::Extract {
477추가: gzip_output_name, ..
478추가: } = &mut start.start.action
479추가: {
480추가: *gzip_output_name = Some("payload".into());
481추가: }
482추가: }
483추가: let events = run(&s, start, approve);
484추가: assert_eq!(
485추가: terminal(&events).outcome,
486추가: Outcome::Completed,
487추가: "{kind}: {events:?}"
488추가: );
489추가: }
490추가: }
491추가: #[test]
492추가: fn small_high_ratio_stream_requires_another_scope_and_cancels_promptly() {
493추가: let s = setup();
494추가: generate(&s, "bomb");
495추가: assert!(fs::metadata(s.0.join("input")).unwrap().len() < 1024 * 1024);
496추가: let mut start = request(&s, 16 * 1024 * 1024 * 1024, 64 * 1024 * 1024 * 1024);
497추가: if let Action::Extract {
498추가: gzip_output_name, ..
499추가: } = &mut start.start.action
500추가: {
501추가: *gzip_output_name = Some("payload".into());
502추가: }
503추가: let mut ratio = false;
504추가: let mut cancelled = None;
505추가: let events = run(&s, start, |event| {
506추가: if let Message::ResourceRequired { scope, usage, .. } = event {
507추가: if scope.ratio {
508추가: ratio = true;
509추가: assert!(!scope.output && !scope.entries);
510추가: assert!(usage.actual_bytes.unwrap() >= 256 * 1024 * 1024);
511추가: assert!(usage.compressed_bytes.unwrap() < 1024 * 1024);
512추가: cancelled = Some(std::time::Instant::now());
513추가: return Some(vec![Message::Cancel]);
514추가: }
515추가: }
516추가: if matches!(event, Message::CancelAck { .. }) {
517추가: assert!(cancelled.unwrap().elapsed() < Duration::from_secs(2));
518추가: }
519추가: approve(event)
520추가: });
521추가: assert!(ratio);
522추가: assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}");
523추가: assert_eq!(terminal(&events).created_count, 0);
524추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
525추가: }
526추가:
527추가: #[cfg(target_os = "linux")]
528추가: #[test]
529추가: fn disk_space_and_write_failures_remain_enforced_after_permission() {
530추가: for fault in ["space-destination", "codec-full", "full"] {
531추가: let s = setup();
532추가: let mut permitted = false;
533추가: let events = run_fault(&s, request(&s, 16, 64), Some(fault), |event| {
534추가: if matches!(event, Message::ResourceRequired { .. }) {
535추가: permitted = true;
536추가: }
537추가: approve(event)
538추가: });
539추가: assert!(permitted);
540추가: assert_eq!(
541추가: terminal(&events).error,
542추가: ErrorCode::DiskFull,
543추가: "{fault}: {events:?}"
544추가: );
545추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete, "{events:?}");
546추가: assert!(!s.0.join("output/folder/hello.txt").exists());
547추가: assert!(!fs::read_dir(s.0.join("output")).unwrap().any(|e| {
548추가: e.unwrap()
549추가: .file_name()
550추가: .to_string_lossy()
551추가: .starts_with(".zipelo-")
552추가: }));
553추가: }
554추가: }
추가tests/rust-archive-worker/guarded_cases.py+20-0
@@ -0,0 +1,20 @@
1추가: import bz2
2추가: import gzip
3추가: import lzma
4추가: from pathlib import Path
5추가: import sys
6추가:
7추가:
8추가: root = Path(sys.argv[1])
9추가: case = sys.argv[2]
10추가: if case == "bomb":
11추가: with gzip.open(root / "input", "wb", compresslevel=9) as output:
12추가: block = bytes(1024 * 1024)
13추가: for _ in range(257):
14추가: output.write(block)
15추가: elif case in {"bz2", "xz"}:
16추가: source = Path(__file__).with_name("fixtures").joinpath("sample.tar").read_bytes()
17추가: encode = bz2.compress if case == "bz2" else lzma.compress
18추가: (root / "input").write_bytes(encode(source))
19추가: else:
20추가: raise ValueError(case)
수정tests/rust-archive-worker/main.rs+2-0
@@ -1615,3 +1615,5 @@ mod conflict_wire;
16151615mod conflicts;
16161616
16171617mod compressed_tar;
1618추가:
1619추가: mod guarded;
추가tests/rust-archive-worker/resource_budget.rs+180-0
@@ -0,0 +1,180 @@
1추가: use super::*;
2추가:
3추가: fn budget() -> Budget {
4추가: Budget {
5추가: soft: Limits::default(),
6추가: ceiling: Limits {
7추가: input: u64::MAX,
8추가: output: 64 * 1024 * 1024 * 1024,
9추가: entries: 200_000,
10추가: },
11추가: granted: ResourceScope::default(),
12추가: }
13추가: }
14추가: #[test]
15추가: fn output_boundaries_and_absolute_ceiling() {
16추가: let mut b = budget();
17추가: let soft = b.soft.output;
18추가: for n in [soft - 1, soft] {
19추가: assert!(
20추가: !b.required(ResourceUsage {
21추가: actual_bytes: Some(n),
22추가: ..ResourceUsage::default()
23추가: })
24추가: .unwrap()
25추가: .any()
26추가: );
27추가: }
28추가: let usage = ResourceUsage {
29추가: actual_bytes: Some(soft + 1),
30추가: ..ResourceUsage::default()
31추가: };
32추가: let scope = b.required(usage).unwrap();
33추가: assert_eq!(
34추가: scope,
35추가: ResourceScope {
36추가: output: true,
37추가: ..ResourceScope::default()
38추가: }
39추가: );
40추가: b.grant(scope);
41추가: assert!(!b.required(usage).unwrap().any());
42추가: assert!(
43추가: !b.required(ResourceUsage {
44추가: actual_bytes: Some(b.ceiling.output),
45추가: ..ResourceUsage::default()
46추가: })
47추가: .unwrap()
48추가: .any()
49추가: );
50추가: assert_eq!(
51추가: b.required(ResourceUsage {
52추가: actual_bytes: Some(b.ceiling.output + 1),
53추가: ..ResourceUsage::default()
54추가: }),
55추가: Err(ErrorCode::Limit)
56추가: );
57추가: }
58추가: #[test]
59추가: fn entries_need_their_own_grant_and_keep_absolute_ceiling() {
60추가: let mut b = budget();
61추가: b.grant(ResourceScope {
62추가: output: true,
63추가: ..ResourceScope::default()
64추가: });
65추가: assert!(
66추가: !b.required(ResourceUsage {
67추가: estimated_entries: Some(10_000),
68추가: ..ResourceUsage::default()
69추가: })
70추가: .unwrap()
71추가: .any()
72추가: );
73추가: let usage = ResourceUsage {
74추가: estimated_entries: Some(10_001),
75추가: ..ResourceUsage::default()
76추가: };
77추가: assert!(b.required(usage).unwrap().entries);
78추가: b.grant(ResourceScope {
79추가: entries: true,
80추가: ..ResourceScope::default()
81추가: });
82추가: assert!(
83추가: !b.required(ResourceUsage {
84추가: estimated_entries: Some(200_000),
85추가: ..ResourceUsage::default()
86추가: })
87추가: .unwrap()
88추가: .any()
89추가: );
90추가: assert_eq!(
91추가: b.required(ResourceUsage {
92추가: actual_entries: Some(200_001),
93추가: ..ResourceUsage::default()
94추가: }),
95추가: Err(ErrorCode::Limit)
96추가: );
97추가: }
98추가: #[test]
99추가: fn ratio_floor_boundary_unknown_and_zero_input() {
100추가: let b = budget();
101추가: let usage = |output, input| ResourceUsage {
102추가: ratio_output_bytes: Some(output),
103추가: compressed_bytes: input,
104추가: ..ResourceUsage::default()
105추가: };
106추가: assert!(
107추가: !b.required(usage(256 * 1024 * 1024 - 1, Some(1)))
108추가: .unwrap()
109추가: .ratio
110추가: );
111추가: assert!(!b.required(usage(300_000_000, Some(300_000))).unwrap().ratio);
112추가: assert!(b.required(usage(300_000_001, Some(300_000))).unwrap().ratio);
113추가: assert!(b.required(usage(256 * 1024 * 1024, Some(0))).unwrap().ratio);
114추가: assert!(!b.required(usage(256 * 1024 * 1024, None)).unwrap().ratio);
115추가: assert!(!b.required(ResourceUsage::default()).unwrap().any());
116추가: }
117추가: #[test]
118추가: fn estimated_and_actual_totals_are_both_enforced() {
119추가: let b = budget();
120추가: for usage in [
121추가: ResourceUsage {
122추가: estimated_bytes: Some(b.soft.output + 1),
123추가: actual_bytes: Some(0),
124추가: ..ResourceUsage::default()
125추가: },
126추가: ResourceUsage {
127추가: estimated_bytes: Some(0),
128추가: actual_bytes: Some(b.soft.output + 1),
129추가: ..ResourceUsage::default()
130추가: },
131추가: ] {
132추가: assert!(b.required(usage).unwrap().output);
133추가: }
134추가: }
135추가: #[test]
136추가: fn idle_timeout_and_activity_use_virtual_time() {
137추가: let mut w = Watchdog::new();
138추가: assert!(w.check(Duration::from_secs(300)).is_ok());
139추가: assert_eq!(w.check(Duration::from_secs(301)), Err(ErrorCode::Limit));
140추가: w.resume(Duration::from_secs(299), true);
141추가: assert!(w.check(Duration::from_secs(358)).is_ok());
142추가: assert_eq!(w.check(Duration::from_secs(359)), Err(ErrorCode::Limit));
143추가: w.activity(Duration::from_secs(350)).unwrap();
144추가: assert!(w.check(Duration::from_secs(409)).is_ok());
145추가: assert_eq!(w.check(Duration::from_secs(410)), Err(ErrorCode::Limit));
146추가: }
147추가: #[test]
148추가: fn approved_progress_can_run_longer_than_five_minutes() {
149추가: let mut w = Watchdog::new();
150추가: w.resume(Duration::ZERO, true);
151추가: for t in (1..=3600).step_by(30) {
152추가: w.activity(Duration::from_secs(t)).unwrap();
153추가: }
154추가: assert!(w.check(Duration::from_secs(3600)).is_ok());
155추가: w.resume(Duration::from_secs(3900), false);
156추가: assert!(w.check(Duration::from_secs(3959)).is_ok());
157추가: assert_eq!(w.check(Duration::from_secs(3960)), Err(ErrorCode::Limit));
158추가: }
159추가:
160추가: #[test]
161추가: fn granted_entry_policy_keeps_independent_metadata_budget() {
162추가: let mut b = budget();
163추가: b.grant(ResourceScope {
164추가: entries: true,
165추가: ..ResourceScope::default()
166추가: });
167추가: assert!(
168추가: !b.required(ResourceUsage {
169추가: estimated_entries: Some(200_000),
170추가: ..ResourceUsage::default()
171추가: })
172추가: .unwrap()
173추가: .any()
174추가: );
175추가: let mut metadata = crate::archive::MetadataBudget::default();
176추가: for _ in 0..32768 {
177추가: metadata.charge("").unwrap();
178추가: }
179추가: assert_eq!(metadata.charge(""), Err(ErrorCode::Limit));
180추가: }