zipatch_rs/apply/mod.rs
1//! Filesystem application of parsed `ZiPatch` chunks.
2//!
3//! # Parse / apply separation
4//!
5//! The crate is intentionally split into two independent layers:
6//!
7//! - **Parsing** (`src/chunk/`) — reads the binary wire format and produces
8//! [`Chunk`] values. Nothing in the parser allocates file handles, stats
9//! paths, or performs I/O against the install tree.
10//! - **Applying** (this module) — takes a stream of [`Chunk`] values and
11//! writes the patch changes to disk.
12//!
13//! The only bridge between the two layers is the [`Apply`] trait, which every
14//! chunk type implements. Callers that only need to inspect patch contents can
15//! use the parser without ever touching this module.
16//!
17//! # `ApplyContext`
18//!
19//! [`ApplyContext`] holds all mutable apply-time state:
20//!
21//! - **Install root** — the absolute path to the game installation directory.
22//! All `SqPack` paths (`sqpack/<expansion>/...`) are resolved relative to
23//! this root by the internal path submodule.
24//! - **Target platform** — selects the `win32`/`ps3`/`ps4` subfolder suffix
25//! used in `SqPack` file paths. Defaults to [`Platform::Win32`] and can be
26//! overridden either at construction time with [`ApplyContext::with_platform`]
27//! or at apply time when a [`crate::chunk::sqpk::SqpkTargetInfo`] chunk is
28//! encountered.
29//! - **Ignore flags** — control whether missing files and old-data mismatches
30//! produce errors or logged warnings. `SqpkTargetInfo` chunks set these via
31//! the stream; callers can also pre-configure them.
32//! - **File-handle cache** — a bounded map of open file handles. Because a
33//! typical patch applies dozens of chunks to the same `.dat` file,
34//! re-opening that file for every chunk would be wasteful. The cache avoids
35//! this while bounding the number of simultaneously open file descriptors.
36//! See the [cache section](#file-handle-cache) below.
37//!
38//! # File-handle cache
39//!
40//! Every `Apply` impl that writes to a `SqPack` file calls an internal
41//! `open_cached` method on `ApplyContext` rather than opening the file
42//! directly. The cache transparently returns an existing writable handle or
43//! opens a new one (with `write=true, create=true, truncate=false`).
44//!
45//! Cached handles are wrapped in a [`std::io::BufWriter`] with a 64 KiB
46//! buffer to coalesce the many small writes the SQPK pipeline emits — block
47//! headers, zero-fill runs, decompressed DEFLATE block output — into a
48//! smaller number of `write(2)` syscalls. Apply functions interact with the
49//! buffered writer transparently because `BufWriter` implements both `Write`
50//! and `Seek`. Call [`ApplyContext::flush`] to force buffered data through
51//! to the operating system at a checkpoint of your choosing;
52//! [`ZiPatchReader::apply_to`](crate::ZiPatchReader::apply_to) calls it
53//! automatically before returning.
54//!
55//! The cache is capped at 256 entries. When it is full and a new, uncached
56//! path is requested, **all** cached handles are flushed and closed at once
57//! before the new one is inserted. This is a simple eviction strategy — it
58//! trades some re-open overhead at eviction boundaries for bounded
59//! file-descriptor usage. Memory cost at the cap is 256 × 64 KiB = 16 MiB.
60//!
61//! Callers should not rely on cached handles persisting across arbitrary
62//! chunks. In particular, [`crate::chunk::sqpk::SqpkFile`]'s `RemoveAll`
63//! operation flushes all cached handles before bulk-deleting files to ensure
64//! no open handles survive into the deletion window (which matters on
65//! Windows). Similarly, `DeleteFile` evicts the cached handle for the
66//! specific path being removed.
67//!
68//! # Ordering and idempotency
69//!
70//! Chunks **must** be applied in stream order. The `ZiPatch` format is a
71//! sequential log, not a random-access manifest: later chunks may depend on
72//! filesystem state produced by earlier ones (e.g. an `AddFile` that writes
73//! blocks into a file created by an earlier `MakeDirTree` or `AddDirectory`).
74//!
75//! Apply operations are **not idempotent** in general. Seeking to an offset
76//! and writing data is idempotent if the same data is written, but
77//! `RemoveAll` is destructive and `DeleteFile` can fail if the file is
78//! already gone (unless `ignore_missing` is set). Partial application
79//! followed by a retry requires careful state tracking at a higher level;
80//! this crate does not provide transactional semantics.
81//!
82//! # Errors
83//!
84//! Every [`Apply::apply`] call returns [`crate::Result`], which is
85//! `Result<(), `[`crate::ZiPatchError`]`>`. Errors propagate from:
86//!
87//! - `std::io::Error` — filesystem failures (permissions, missing parent
88//! directories, disk full, etc.) wrapped as [`crate::ZiPatchError::Io`].
89//! - [`crate::ZiPatchError::NegativeFileOffset`] — a `SqpkFile` chunk
90//! carried a negative `file_offset` that cannot be converted to a seek
91//! position.
92//!
93//! On error, the apply operation aborts at the failing chunk. Any changes
94//! already applied to the filesystem are **not** rolled back.
95//!
96//! # Progress and cancellation
97//!
98//! Install an [`ApplyObserver`] via [`ApplyContext::with_observer`] to be
99//! notified after each top-level chunk applies and to signal cancellation
100//! mid-stream. The observer's
101//! [`on_chunk_applied`](ApplyObserver::on_chunk_applied) method receives a
102//! [`ChunkEvent`] with the chunk index, 4-byte tag, and running byte count;
103//! its [`should_cancel`](ApplyObserver::should_cancel) predicate is polled
104//! between blocks inside long-running chunks so that aborting a multi-
105//! hundred-MB `SqpkFile` `AddFile` does not have to wait for the whole
106//! chunk to finish. Without an explicit observer, [`ApplyContext`] uses
107//! [`NoopObserver`] and the existing apply path pays nothing.
108//!
109//! # Example
110//!
111//! ```no_run
112//! use std::fs::File;
113//! use zipatch_rs::{ApplyContext, ZiPatchReader};
114//!
115//! let patch_file = File::open("game.patch").unwrap();
116//! let mut ctx = ApplyContext::new("/opt/ffxiv/game");
117//!
118//! ZiPatchReader::new(patch_file)
119//! .unwrap()
120//! .apply_to(&mut ctx)
121//! .unwrap();
122//! ```
123
124pub(crate) mod observer;
125pub(crate) mod path;
126pub(crate) mod sqpk;
127
128pub use observer::{ApplyObserver, ChunkEvent, NoopObserver};
129
130use crate::Platform;
131use crate::Result;
132use crate::chunk::Chunk;
133use crate::chunk::adir::AddDirectory;
134use crate::chunk::aply::{ApplyOption, ApplyOptionKind};
135use crate::chunk::ddir::DeleteDirectory;
136use std::collections::{HashMap, HashSet};
137use std::fs::{File, OpenOptions};
138use std::io::{BufWriter, Write};
139use std::path::{Path, PathBuf};
140use tracing::{debug, trace, warn};
141
142/// Discriminator for the `path_cache` key: which `SqPack` file kind is being
143/// resolved. The combination `(main_id, sub_id, file_id, kind)` is the full
144/// cache key, alongside the current `platform` (handled via cache
145/// invalidation rather than as a key component, since `platform` changes
146/// only at `apply_target_info` boundaries).
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148pub(crate) enum PathKind {
149 Dat,
150 Index,
151}
152
153/// Cache key for resolved `SqPack` `.dat`/`.index` paths.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
155pub(crate) struct PathCacheKey {
156 pub(crate) main_id: u16,
157 pub(crate) sub_id: u16,
158 pub(crate) file_id: u32,
159 pub(crate) kind: PathKind,
160}
161
162const MAX_CACHED_FDS: usize = 256;
163
164// 64 KiB chosen to comfortably absorb the largest single writes the SQPK
165// pipeline emits (1 KiB header chunks, DEFLATE block outputs up to ~32 KiB,
166// zero-fill runs from `write_zeros`) without splitting them. Memory ceiling
167// at the FD cap is 256 * 64 KiB = 16 MiB, which is trivial for a desktop
168// launcher and the only realistic consumer of this library.
169const WRITE_BUFFER_CAPACITY: usize = 64 * 1024;
170
171/// Apply-time state: install root, target platform, flag toggles, and the
172/// internal file-handle cache used by SQPK writers.
173///
174/// # Construction
175///
176/// Build with [`ApplyContext::new`], then chain the `with_*` builder methods
177/// to override defaults:
178///
179/// ```
180/// use zipatch_rs::{ApplyContext, Platform};
181///
182/// let ctx = ApplyContext::new("/opt/ffxiv/game")
183/// .with_platform(Platform::Win32)
184/// .with_ignore_missing(true);
185///
186/// assert_eq!(ctx.game_path().to_str().unwrap(), "/opt/ffxiv/game");
187/// assert_eq!(ctx.platform(), Platform::Win32);
188/// assert!(ctx.ignore_missing());
189/// ```
190///
191/// # Platform mutation
192///
193/// The platform defaults to [`Platform::Win32`]. If the patch stream contains
194/// a [`crate::chunk::sqpk::SqpkTargetInfo`] chunk, applying it overwrites
195/// [`ApplyContext::platform`] with the platform declared in the chunk. This is
196/// the normal case: real FFXIV patches begin with a `TargetInfo` chunk that
197/// pins the platform, so the default is rarely used in practice.
198///
199/// Set the platform explicitly with [`ApplyContext::with_platform`] when you
200/// know the target in advance or are processing a synthetic patch.
201///
202/// # Flag mutation
203///
204/// [`ApplyContext::ignore_missing`] and [`ApplyContext::ignore_old_mismatch`]
205/// can also be overwritten mid-stream by `ApplyOption` chunks embedded in the
206/// patch file. Set initial values with the `with_ignore_*` builder methods.
207///
208/// # File-handle cache
209///
210/// Internally, `ApplyContext` maintains a bounded map of open file handles
211/// keyed by absolute path. The cache is an optimisation: a patch that writes
212/// many chunks into the same `.dat` file re-uses a single handle rather than
213/// opening and closing the file for every write.
214///
215/// The cache is capped at 256 entries. When that limit is reached and a new
216/// path is needed, **all** entries are evicted at once. Handles are also
217/// evicted explicitly before deleting a file (see `DeleteFile`) and before a
218/// `RemoveAll` bulk operation.
219pub struct ApplyContext {
220 pub(crate) game_path: PathBuf,
221 /// The target platform. Defaults to `Win32`. Note: `SqpkTargetInfo` chunks
222 /// in the patch stream will override this value when applied.
223 pub(crate) platform: Platform,
224 pub(crate) ignore_missing: bool,
225 pub(crate) ignore_old_mismatch: bool,
226 // Capped at MAX_CACHED_FDS entries; cleared wholesale when full to bound open FD count.
227 // Each handle is wrapped in a `BufWriter` to coalesce the many small
228 // writes the SQPK pipeline emits (block headers, zero-fill runs) into a
229 // smaller number of `write(2)` syscalls. `BufWriter` implements both
230 // `Write` and `Seek`, so apply functions interact with it transparently;
231 // operations that need the raw `File` (currently only `set_len`) call
232 // `get_mut()` after an explicit `flush()`.
233 //
234 // `pub(crate)` so the SQPK `AddFile` apply loop can split-borrow it next
235 // to `observer` for between-block cancellation polling.
236 pub(crate) file_cache: HashMap<PathBuf, BufWriter<File>>,
237 // Memoised set of directories already created via `ensure_dir_all`.
238 // Avoids reissuing `mkdir -p` syscalls for shared parent directories
239 // across long chains of `AddFile` / `MakeDirTree` / `ADIR` chunks. Keys
240 // are the exact `PathBuf` handed to `create_dir_all`; no canonicalisation
241 // is performed (which would itself cost a syscall and was never done by
242 // the previous unconditional path). Destructive ops that remove
243 // directories (`SqpkFile::RemoveAll`, `DeleteDirectory`) clear the entire
244 // set — simpler than tracking exact entries, and correct because a
245 // subsequent `create_dir_all` will re-establish whichever directories
246 // are still needed at the next syscall cost.
247 pub(crate) dirs_created: HashSet<PathBuf>,
248 // Memoised SqPack `.dat`/`.index` path resolutions. A typical patch
249 // dispatches thousands of `AddData`/`DeleteData`/`ExpandData`/`Header`
250 // chunks targeting a small set of files, each of which would otherwise
251 // recompute `expansion_folder_id` (one `String` alloc), the filename
252 // (one `format!` alloc), and three chained `PathBuf::join` calls. The
253 // cache short-circuits repeat lookups for the same
254 // `(main_id, sub_id, file_id, kind)` tuple to a single `PathBuf` clone.
255 // Invalidated by `apply_target_info` when the platform changes, since
256 // the platform string is baked into the cached path.
257 pub(crate) path_cache: HashMap<PathCacheKey, PathBuf>,
258 // Reusable DEFLATE state shared across all `SqpkCompressedBlock` payloads
259 // in a single `SqpkFile::AddFile` chunk (and across chunks). Constructing
260 // a fresh decoder per block allocates ~100 KiB of internal zlib state;
261 // a multi-block `AddFile` chunk can contain hundreds of blocks. Reset
262 // between blocks via `Decompress::reset(false)` so the underlying
263 // buffers are reused. `false` = raw DEFLATE, no zlib wrapper, matching
264 // the SqPack on-the-wire layout.
265 pub(crate) decompressor: flate2::Decompress,
266 // Observer for progress/cancellation. Defaults to a no-op; replaced by
267 // `with_observer`. Stored as a boxed trait object so that the public
268 // `ApplyContext` type stays non-generic and remains nameable in downstream
269 // signatures (`gaveloc-patcher` passes contexts across module boundaries).
270 pub(crate) observer: Box<dyn ApplyObserver>,
271}
272
273// Hand-written so we don't need `ApplyObserver: Debug` as a supertrait —
274// adding supertraits is a SemVer break, and forcing every user observer to
275// implement `Debug` would be a needless ergonomic tax. The observer field
276// is summarised as an opaque placeholder.
277impl std::fmt::Debug for ApplyContext {
278 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279 f.debug_struct("ApplyContext")
280 .field("game_path", &self.game_path)
281 .field("platform", &self.platform)
282 .field("ignore_missing", &self.ignore_missing)
283 .field("ignore_old_mismatch", &self.ignore_old_mismatch)
284 .field("file_cache_len", &self.file_cache.len())
285 .field("dirs_created_len", &self.dirs_created.len())
286 .field("path_cache_len", &self.path_cache.len())
287 .field("decompressor", &"<flate2::Decompress>")
288 .field("observer", &"<dyn ApplyObserver>")
289 .finish()
290 }
291}
292
293impl ApplyContext {
294 /// Create a context targeting the given game install directory.
295 ///
296 /// Defaults: platform is [`Platform::Win32`], both ignore-flags are off.
297 ///
298 /// Use the `with_*` builder methods to change these defaults before
299 /// applying the first chunk.
300 ///
301 /// # Example
302 ///
303 /// ```
304 /// use zipatch_rs::ApplyContext;
305 ///
306 /// let ctx = ApplyContext::new("/opt/ffxiv/game");
307 /// assert_eq!(ctx.game_path().to_str().unwrap(), "/opt/ffxiv/game");
308 /// ```
309 pub fn new(game_path: impl Into<PathBuf>) -> Self {
310 Self {
311 game_path: game_path.into(),
312 platform: Platform::Win32,
313 ignore_missing: false,
314 ignore_old_mismatch: false,
315 file_cache: HashMap::new(),
316 dirs_created: HashSet::new(),
317 path_cache: HashMap::new(),
318 // `false` = raw DEFLATE (no zlib header). SqPack `AddFile` blocks
319 // store an RFC 1951 raw deflate stream with no wrapper.
320 decompressor: flate2::Decompress::new(false),
321 observer: Box::new(NoopObserver),
322 }
323 }
324
325 /// Returns the game installation directory.
326 ///
327 /// All file paths produced during apply are relative to this root.
328 #[must_use]
329 pub fn game_path(&self) -> &std::path::Path {
330 &self.game_path
331 }
332
333 /// Returns the current target platform.
334 ///
335 /// This value may change during apply if the patch stream contains a
336 /// [`crate::chunk::sqpk::SqpkTargetInfo`] chunk.
337 #[must_use]
338 pub fn platform(&self) -> Platform {
339 self.platform
340 }
341
342 /// Returns whether missing files are silently ignored during apply.
343 ///
344 /// When `true`, operations that target a file that does not exist log a
345 /// warning instead of returning an error. This flag may be overwritten
346 /// mid-stream by an `ApplyOption` chunk.
347 #[must_use]
348 pub fn ignore_missing(&self) -> bool {
349 self.ignore_missing
350 }
351
352 /// Returns whether old-data mismatches are silently ignored during apply.
353 ///
354 /// When `true`, apply operations that detect a checksum or data mismatch
355 /// against the existing on-disk content proceed without error. This flag
356 /// may be overwritten mid-stream by an `ApplyOption` chunk.
357 #[must_use]
358 pub fn ignore_old_mismatch(&self) -> bool {
359 self.ignore_old_mismatch
360 }
361
362 /// Sets the target platform. Defaults to [`Platform::Win32`].
363 ///
364 /// The platform determines the directory suffix used when resolving `SqPack`
365 /// file paths (`win32`, `ps3`, or `ps4`).
366 ///
367 /// Note: a [`crate::chunk::sqpk::SqpkTargetInfo`] chunk encountered during
368 /// apply will override this value.
369 #[must_use]
370 pub fn with_platform(mut self, platform: Platform) -> Self {
371 self.platform = platform;
372 self
373 }
374
375 /// Silently ignore missing files instead of returning an error during apply.
376 ///
377 /// When `false` (the default), any apply operation that cannot find its
378 /// target file returns [`crate::ZiPatchError::Io`] with kind
379 /// [`std::io::ErrorKind::NotFound`].
380 ///
381 /// When `true`, those failures are demoted to `warn!`-level tracing events.
382 #[must_use]
383 pub fn with_ignore_missing(mut self, v: bool) -> Self {
384 self.ignore_missing = v;
385 self
386 }
387
388 /// Silently ignore old-data mismatches instead of returning an error during apply.
389 ///
390 /// When `false` (the default), an apply operation that detects that the
391 /// on-disk data does not match the expected "before" state returns an error.
392 ///
393 /// When `true`, the mismatch is logged at `warn!` level and the operation
394 /// continues.
395 #[must_use]
396 pub fn with_ignore_old_mismatch(mut self, v: bool) -> Self {
397 self.ignore_old_mismatch = v;
398 self
399 }
400
401 /// Install an [`ApplyObserver`] for progress reporting and cancellation.
402 ///
403 /// The observer's [`on_chunk_applied`](ApplyObserver::on_chunk_applied)
404 /// method is called after each top-level chunk; its
405 /// [`should_cancel`](ApplyObserver::should_cancel) method is polled
406 /// inside long-running chunks (currently the
407 /// [`SqpkFile`](crate::chunk::sqpk::SqpkFile) block-write loop) so that
408 /// cancellation is observable mid-chunk on multi-hundred-MB payloads.
409 ///
410 /// Returning [`ControlFlow::Break`](std::ops::ControlFlow::Break) from
411 /// `on_chunk_applied`, or `true` from `should_cancel`, aborts the apply
412 /// loop with [`crate::ZiPatchError::Cancelled`]. Filesystem changes already
413 /// applied are **not** rolled back.
414 ///
415 /// The default observer is a no-op: parsing-only consumers and existing
416 /// callers that never call `with_observer` pay nothing.
417 ///
418 /// # `'static` bound
419 ///
420 /// The `'static` bound follows from [`ApplyContext`] storing the
421 /// observer in a `Box<dyn ApplyObserver>` — a trait object whose
422 /// lifetime parameter defaults to `'static`. To pass an observer that
423 /// holds a channel sender or similar handle, wrap it in
424 /// `Arc<Mutex<...>>` (which is `'static`) or implement
425 /// [`ApplyObserver`] on a struct that owns the handle directly.
426 #[must_use]
427 pub fn with_observer(mut self, observer: impl ApplyObserver + 'static) -> Self {
428 self.observer = Box::new(observer);
429 self
430 }
431
432 /// Return a writable handle to `path`, opening it if not already cached.
433 ///
434 /// If the cache has reached 256 entries and `path` is not already present,
435 /// all cached handles are flushed and dropped before opening the new one.
436 /// The file is opened with `write=true, create=true, truncate=false` and
437 /// wrapped in a [`BufWriter`] with a 64 KiB buffer.
438 ///
439 /// # Errors
440 ///
441 /// Returns `std::io::Error` if the file cannot be opened, or if the
442 /// flush triggered by cache-full eviction fails on any of the dropped
443 /// handles (e.g. disk full while persisting buffered writes).
444 pub(crate) fn open_cached(&mut self, path: PathBuf) -> std::io::Result<&mut BufWriter<File>> {
445 use std::collections::hash_map::Entry;
446 // Crude eviction: flush + clear all when full to bound open FD count.
447 // Flushing first surfaces write errors (disk full, quota) that would
448 // otherwise be silently swallowed by `BufWriter::drop`.
449 if self.file_cache.len() >= MAX_CACHED_FDS && !self.file_cache.contains_key(&path) {
450 self.drain_and_flush()?;
451 }
452 match self.file_cache.entry(path) {
453 Entry::Occupied(e) => Ok(e.into_mut()),
454 Entry::Vacant(e) => {
455 let file = OpenOptions::new()
456 .write(true)
457 .create(true)
458 .truncate(false)
459 .open(e.key())?;
460 Ok(e.insert(BufWriter::with_capacity(WRITE_BUFFER_CAPACITY, file)))
461 }
462 }
463 }
464
465 /// Flush and remove the cached handle for `path`, if any.
466 ///
467 /// Called before a file is deleted so that the OS handle is closed before
468 /// the unlink (no-op on Linux, required on Windows where an open handle
469 /// prevents deletion). The buffered writes are flushed first so that any
470 /// pending data lands on disk before the close.
471 ///
472 /// If no handle is cached for `path`, returns `Ok(())`.
473 ///
474 /// # Errors
475 ///
476 /// Returns `std::io::Error` if flushing the buffered writes fails.
477 pub(crate) fn evict_cached(&mut self, path: &Path) -> std::io::Result<()> {
478 if let Some(mut writer) = self.file_cache.remove(path) {
479 writer.flush()?;
480 }
481 Ok(())
482 }
483
484 /// Flush and drop every cached file handle.
485 ///
486 /// Called by `RemoveAll` before bulk-deleting an expansion folder's files
487 /// to ensure no lingering open handles survive into the deletion window,
488 /// and by `flush()` to provide a public durability checkpoint.
489 ///
490 /// # Errors
491 ///
492 /// Returns the first `std::io::Error` produced by any handle's flush.
493 /// Remaining handles are still flushed and cleared even if an earlier
494 /// one failed; the cache is always empty on return.
495 pub(crate) fn clear_file_cache(&mut self) -> std::io::Result<()> {
496 self.drain_and_flush()
497 }
498
499 /// Create `path` and every missing ancestor, memoising the call.
500 ///
501 /// A real patch issues thousands of `create_dir_all` calls against a
502 /// handful of shared parent directories (`sqpack/ffxiv`,
503 /// `sqpack/ex1/...`, etc.). The first call for a given path falls through
504 /// to [`std::fs::create_dir_all`] and inserts the path into an internal
505 /// set; later calls for the same path return `Ok(())` without issuing the
506 /// syscall.
507 ///
508 /// The cache is cleared by destructive ops that might remove a directory
509 /// it tracks (`SqpkFile::RemoveAll`, `DeleteDirectory`). Cache misses
510 /// after a clear cost exactly one `create_dir_all` syscall, the same as
511 /// before this optimisation.
512 ///
513 /// # Errors
514 ///
515 /// Returns `std::io::Error` if [`std::fs::create_dir_all`] fails. On
516 /// failure the path is **not** inserted into the cache, so a retry that
517 /// fixes the underlying problem (e.g. permissions) will re-attempt the
518 /// syscall.
519 pub(crate) fn ensure_dir_all(&mut self, path: &Path) -> std::io::Result<()> {
520 if self.dirs_created.contains(path) {
521 return Ok(());
522 }
523 std::fs::create_dir_all(path)?;
524 self.dirs_created.insert(path.to_path_buf());
525 Ok(())
526 }
527
528 /// Drop every memoised entry in the created-directories set.
529 ///
530 /// Called by destructive operations that may remove a directory the
531 /// cache claims still exists. Subsequent [`Self::ensure_dir_all`] calls
532 /// fall back to one real `create_dir_all` syscall per path until the set
533 /// repopulates.
534 pub(crate) fn invalidate_dirs_created(&mut self) {
535 self.dirs_created.clear();
536 }
537
538 /// Drop every memoised entry in the `SqPack` path cache.
539 ///
540 /// Called by `apply_target_info` when `ApplyContext::platform` changes,
541 /// since the cached `PathBuf`s embed the platform string. Cache misses
542 /// after a clear cost one full path resolution per `(main_id, sub_id,
543 /// file_id, kind)` until the set repopulates.
544 pub(crate) fn invalidate_path_cache(&mut self) {
545 self.path_cache.clear();
546 }
547
548 /// Flush every cached writer's buffer, then drain the cache.
549 ///
550 /// Used by both [`Self::clear_file_cache`] and the cache-full path inside
551 /// [`Self::open_cached`]. Distinct from [`Self::flush`], which flushes in
552 /// place without dropping the handles.
553 fn drain_and_flush(&mut self) -> std::io::Result<()> {
554 let mut first_err: Option<std::io::Error> = None;
555 for (_, mut writer) in self.file_cache.drain() {
556 if let Err(e) = writer.flush() {
557 first_err.get_or_insert(e);
558 }
559 }
560 match first_err {
561 Some(e) => Err(e),
562 None => Ok(()),
563 }
564 }
565
566 /// Flush every buffered write through to the operating system.
567 ///
568 /// Forces any data still sitting in [`BufWriter`] buffers (one per cached
569 /// `SqPack` file) to be written via `write(2)`. Open handles are retained
570 /// — this is a durability checkpoint, not a cache eviction. Subsequent
571 /// chunks targeting the same files reuse the existing handles.
572 ///
573 /// `apply_to` calls this automatically before returning so successful
574 /// completion of a patch implies all writes have reached the OS. Explicit
575 /// calls are useful when applying chunks one at a time via
576 /// [`Apply::apply`] and reading the resulting file state in between, or
577 /// when implementing a custom apply driver that wants intermediate
578 /// commit points.
579 ///
580 /// This is **not** `fsync`. Data is handed off to the OS but may still
581 /// reside in the page cache; survival across a crash requires
582 /// `File::sync_all` on the underlying handles, which this method does
583 /// not perform.
584 ///
585 /// # Errors
586 ///
587 /// Returns the first `std::io::Error` produced by any writer's flush.
588 /// Remaining writers are still attempted even if an earlier one failed.
589 pub fn flush(&mut self) -> std::io::Result<()> {
590 let mut first_err: Option<std::io::Error> = None;
591 for writer in self.file_cache.values_mut() {
592 if let Err(e) = writer.flush() {
593 first_err.get_or_insert(e);
594 }
595 }
596 match first_err {
597 Some(e) => Err(e),
598 None => Ok(()),
599 }
600 }
601}
602
603/// Applies a parsed chunk to the filesystem via an [`ApplyContext`].
604///
605/// Every top-level [`Chunk`] variant and every
606/// [`crate::chunk::sqpk::SqpkCommand`] variant implements this trait. The
607/// usual entry point is [`Chunk::apply`], which dispatches to the appropriate
608/// implementation.
609///
610/// # Ordering
611///
612/// Chunks must be applied in the order they appear in the patch stream.
613/// The format is a sequential log; later chunks may depend on state produced
614/// by earlier ones.
615///
616/// # Idempotency
617///
618/// Apply operations are **not idempotent** in general. Write operations are
619/// idempotent only if the data payload is identical to what is already on
620/// disk. Destructive operations (`RemoveAll`, `DeleteFile`, `DeleteDirectory`)
621/// are not repeatable without error unless `ignore_missing` is set.
622///
623/// # Errors
624///
625/// Returns [`crate::ZiPatchError`] on any filesystem or data error. The error
626/// is not recovered from; the caller should treat it as fatal for the current
627/// apply session.
628///
629/// # Panics
630///
631/// Implementations do not panic under normal operation. Panics would indicate
632/// a bug in the parsing layer (e.g. a chunk with fields that violate internal
633/// invariants established during parsing).
634pub trait Apply {
635 /// Apply this chunk to `ctx`.
636 ///
637 /// On success, any filesystem changes the chunk describes have been
638 /// written. On error, changes may be partial; the caller is responsible
639 /// for any recovery.
640 fn apply(&self, ctx: &mut ApplyContext) -> Result<()>;
641}
642
643/// Dispatch table for top-level chunk variants.
644///
645/// `FileHeader`, `ApplyFreeSpace`, and `EndOfFile` are metadata or structural
646/// chunks with no filesystem effect; they return `Ok(())` immediately.
647/// All other variants delegate to their specific `Apply` implementation.
648impl Apply for Chunk {
649 fn apply(&self, ctx: &mut ApplyContext) -> Result<()> {
650 match self {
651 Chunk::FileHeader(_) | Chunk::ApplyFreeSpace(_) | Chunk::EndOfFile => Ok(()),
652 Chunk::Sqpk(c) => c.apply(ctx),
653 Chunk::ApplyOption(c) => c.apply(ctx),
654 Chunk::AddDirectory(c) => c.apply(ctx),
655 Chunk::DeleteDirectory(c) => c.apply(ctx),
656 }
657 }
658}
659
660/// Updates [`ApplyContext`] ignore-flags from the chunk payload.
661///
662/// `ApplyOption` chunks are embedded in the patch stream to toggle
663/// [`ApplyContext::ignore_missing`] and [`ApplyContext::ignore_old_mismatch`]
664/// at specific points during apply. Applying this chunk mutates `ctx` in
665/// place; no filesystem I/O is performed.
666impl Apply for ApplyOption {
667 fn apply(&self, ctx: &mut ApplyContext) -> Result<()> {
668 debug!(kind = ?self.kind, value = self.value, "apply option");
669 match self.kind {
670 ApplyOptionKind::IgnoreMissing => ctx.ignore_missing = self.value,
671 ApplyOptionKind::IgnoreOldMismatch => ctx.ignore_old_mismatch = self.value,
672 }
673 Ok(())
674 }
675}
676
677/// Creates a directory under the game install root.
678///
679/// Equivalent to `fs::create_dir_all(game_path / name)`. Intermediate
680/// directories are created as needed; the call is idempotent if the directory
681/// already exists.
682///
683/// # Errors
684///
685/// Returns [`crate::ZiPatchError::Io`] if directory creation fails for any
686/// reason other than the directory already existing (e.g. a permission error
687/// or a non-directory file at the path).
688impl Apply for AddDirectory {
689 fn apply(&self, ctx: &mut ApplyContext) -> Result<()> {
690 trace!(name = %self.name, "create directory");
691 let path = ctx.game_path.join(&self.name);
692 ctx.ensure_dir_all(&path)?;
693 Ok(())
694 }
695}
696
697/// Removes a directory from the game install root.
698///
699/// The directory must be **empty**; `remove_dir` (not `remove_dir_all`) is
700/// used intentionally so that stale files inside the directory cause a visible
701/// error rather than silent data loss.
702///
703/// If the directory does not exist and [`ApplyContext::ignore_missing`] is
704/// `true`, the missing directory is logged at `warn!` level and `Ok(())` is
705/// returned. If `ignore_missing` is `false`, the `NotFound` I/O error is
706/// propagated.
707///
708/// # Errors
709///
710/// Returns [`crate::ZiPatchError::Io`] if the removal fails for any reason
711/// other than a missing directory with `ignore_missing = true`.
712impl Apply for DeleteDirectory {
713 fn apply(&self, ctx: &mut ApplyContext) -> Result<()> {
714 match std::fs::remove_dir(ctx.game_path.join(&self.name)) {
715 Ok(()) => {
716 trace!(name = %self.name, "delete directory");
717 // The just-removed directory (or an ancestor it co-occupies)
718 // may sit in the created-dirs cache; clear the whole set so a
719 // subsequent `ensure_dir_all` re-issues a real syscall.
720 ctx.invalidate_dirs_created();
721 Ok(())
722 }
723 Err(e) if e.kind() == std::io::ErrorKind::NotFound && ctx.ignore_missing => {
724 warn!(name = %self.name, "delete directory: not found, ignored");
725 Ok(())
726 }
727 Err(e) => Err(e.into()),
728 }
729 }
730}
731
732#[cfg(test)]
733mod tests {
734 use super::*;
735
736 // --- Cache semantics ---
737
738 #[test]
739 fn cache_eviction_clears_all_entries_when_at_capacity() {
740 // Fill the cache to exactly MAX_CACHED_FDS, then request one new path.
741 // The eviction must drop all 256 entries and leave only the new one.
742 let tmp = tempfile::tempdir().unwrap();
743 let mut ctx = ApplyContext::new(tmp.path());
744
745 for i in 0..MAX_CACHED_FDS {
746 ctx.open_cached(tmp.path().join(format!("{i}.dat")))
747 .unwrap();
748 }
749 assert_eq!(
750 ctx.file_cache.len(),
751 MAX_CACHED_FDS,
752 "cache should be full before triggering eviction"
753 );
754
755 ctx.open_cached(tmp.path().join("new.dat")).unwrap();
756 assert_eq!(
757 ctx.file_cache.len(),
758 1,
759 "eviction must clear all entries and leave only the new handle"
760 );
761 }
762
763 #[test]
764 fn cache_hit_does_not_trigger_eviction_when_full() {
765 // With a full cache, requesting an *already-cached* path must NOT evict
766 // — the size stays at MAX_CACHED_FDS.
767 let tmp = tempfile::tempdir().unwrap();
768 let mut ctx = ApplyContext::new(tmp.path());
769
770 for i in 0..MAX_CACHED_FDS {
771 ctx.open_cached(tmp.path().join(format!("{i}.dat")))
772 .unwrap();
773 }
774 // Re-request the first path — it is already in the cache.
775 ctx.open_cached(tmp.path().join("0.dat")).unwrap();
776 assert_eq!(
777 ctx.file_cache.len(),
778 MAX_CACHED_FDS,
779 "cache hit on a full cache must not evict anything"
780 );
781 }
782
783 #[test]
784 fn evict_cached_removes_only_target_path() {
785 let tmp = tempfile::tempdir().unwrap();
786 let mut ctx = ApplyContext::new(tmp.path());
787 let a = tmp.path().join("a.dat");
788 let b = tmp.path().join("b.dat");
789 ctx.open_cached(a.clone()).unwrap();
790 ctx.open_cached(b.clone()).unwrap();
791 assert_eq!(ctx.file_cache.len(), 2);
792
793 ctx.evict_cached(&a).unwrap();
794 assert_eq!(
795 ctx.file_cache.len(),
796 1,
797 "evict_cached must remove exactly the targeted path"
798 );
799 assert!(
800 ctx.file_cache.contains_key(&b),
801 "evict_cached must not remove the other path"
802 );
803 }
804
805 #[test]
806 fn evict_cached_is_noop_for_absent_path() {
807 let tmp = tempfile::tempdir().unwrap();
808 let mut ctx = ApplyContext::new(tmp.path());
809 ctx.open_cached(tmp.path().join("a.dat")).unwrap();
810 // Evicting a path that was never inserted must not panic or change the cache.
811 ctx.evict_cached(&tmp.path().join("nonexistent.dat"))
812 .unwrap();
813 assert_eq!(ctx.file_cache.len(), 1);
814 }
815
816 #[test]
817 fn clear_file_cache_removes_all_handles() {
818 let tmp = tempfile::tempdir().unwrap();
819 let mut ctx = ApplyContext::new(tmp.path());
820 ctx.open_cached(tmp.path().join("a.dat")).unwrap();
821 ctx.open_cached(tmp.path().join("b.dat")).unwrap();
822 assert_eq!(ctx.file_cache.len(), 2);
823 ctx.clear_file_cache().unwrap();
824 assert_eq!(
825 ctx.file_cache.len(),
826 0,
827 "clear_file_cache must empty the cache"
828 );
829 }
830
831 // --- Builder accessors ---
832
833 #[test]
834 fn game_path_returns_install_root_unchanged() {
835 let tmp = tempfile::tempdir().unwrap();
836 let ctx = ApplyContext::new(tmp.path());
837 assert_eq!(
838 ctx.game_path(),
839 tmp.path(),
840 "game_path() must return exactly the path passed to new()"
841 );
842 }
843
844 #[test]
845 fn default_platform_is_win32() {
846 let ctx = ApplyContext::new("/irrelevant");
847 assert_eq!(
848 ctx.platform(),
849 Platform::Win32,
850 "default platform must be Win32"
851 );
852 }
853
854 #[test]
855 fn with_platform_overrides_default() {
856 let ctx = ApplyContext::new("/irrelevant").with_platform(Platform::Ps4);
857 assert_eq!(
858 ctx.platform(),
859 Platform::Ps4,
860 "with_platform must override the Win32 default"
861 );
862 }
863
864 #[test]
865 fn default_ignore_missing_is_false() {
866 let ctx = ApplyContext::new("/irrelevant");
867 assert!(
868 !ctx.ignore_missing(),
869 "ignore_missing must default to false"
870 );
871 }
872
873 #[test]
874 fn with_ignore_missing_toggles_flag_both_ways() {
875 let ctx = ApplyContext::new("/irrelevant").with_ignore_missing(true);
876 assert!(
877 ctx.ignore_missing(),
878 "with_ignore_missing(true) must set the flag"
879 );
880 let ctx = ctx.with_ignore_missing(false);
881 assert!(
882 !ctx.ignore_missing(),
883 "with_ignore_missing(false) must clear the flag"
884 );
885 }
886
887 #[test]
888 fn default_ignore_old_mismatch_is_false() {
889 let ctx = ApplyContext::new("/irrelevant");
890 assert!(
891 !ctx.ignore_old_mismatch(),
892 "ignore_old_mismatch must default to false"
893 );
894 }
895
896 #[test]
897 fn with_ignore_old_mismatch_toggles_flag_both_ways() {
898 let ctx = ApplyContext::new("/irrelevant").with_ignore_old_mismatch(true);
899 assert!(
900 ctx.ignore_old_mismatch(),
901 "with_ignore_old_mismatch(true) must set the flag"
902 );
903 let ctx = ctx.with_ignore_old_mismatch(false);
904 assert!(
905 !ctx.ignore_old_mismatch(),
906 "with_ignore_old_mismatch(false) must clear the flag"
907 );
908 }
909
910 // --- with_observer ---
911 //
912 // The end-to-end "default context uses NoopObserver" check lives in
913 // `src/lib.rs` as `default_no_observer_apply_succeeds_as_before`, which
914 // exercises the full `apply_to` driver path; duplicating it here would
915 // only re-test the same behaviour through a slightly different lens.
916
917 // --- BufWriter cache ---
918
919 #[test]
920 fn buffered_writes_are_invisible_before_flush() {
921 // The whole point of wrapping cached handles in a BufWriter is to
922 // hold small writes in user-space memory until enough have queued
923 // up. Lock that down: a 1-byte write must not be visible on disk
924 // until flush() is called.
925 use std::io::Write;
926
927 let tmp = tempfile::tempdir().unwrap();
928 let mut ctx = ApplyContext::new(tmp.path());
929 let path = tmp.path().join("buffered.dat");
930
931 let writer = ctx.open_cached(path.clone()).unwrap();
932 writer.write_all(&[0xAB]).unwrap();
933
934 // File exists (open_cached opened it with create=true) but is empty
935 // — the byte is sitting in the BufWriter, not on disk.
936 assert_eq!(
937 std::fs::metadata(&path).unwrap().len(),
938 0,
939 "buffered write must not reach disk before flush"
940 );
941
942 ctx.flush().unwrap();
943 assert_eq!(
944 std::fs::read(&path).unwrap(),
945 vec![0xAB],
946 "flush must drain the buffer to disk"
947 );
948 }
949
950 #[test]
951 fn flush_keeps_handles_in_cache() {
952 // flush() is a durability checkpoint, not an eviction — handles
953 // must survive so subsequent chunks targeting the same file reuse
954 // them rather than reopening.
955 let tmp = tempfile::tempdir().unwrap();
956 let mut ctx = ApplyContext::new(tmp.path());
957 ctx.open_cached(tmp.path().join("a.dat")).unwrap();
958 ctx.open_cached(tmp.path().join("b.dat")).unwrap();
959 assert_eq!(ctx.file_cache.len(), 2);
960
961 ctx.flush().unwrap();
962 assert_eq!(
963 ctx.file_cache.len(),
964 2,
965 "flush must not drop cached handles"
966 );
967 }
968
969 #[test]
970 fn evict_cached_flushes_pending_writes_to_disk() {
971 // evict_cached must flush before dropping — otherwise buffered
972 // writes against the about-to-be-closed handle would be silently
973 // discarded by BufWriter::drop's error-swallowing flush.
974 use std::io::Write;
975
976 let tmp = tempfile::tempdir().unwrap();
977 let mut ctx = ApplyContext::new(tmp.path());
978 let path = tmp.path().join("evict.dat");
979
980 let writer = ctx.open_cached(path.clone()).unwrap();
981 writer.write_all(b"queued").unwrap();
982 assert_eq!(
983 std::fs::metadata(&path).unwrap().len(),
984 0,
985 "pre-condition: write is buffered, not on disk"
986 );
987
988 ctx.evict_cached(&path).unwrap();
989 assert_eq!(
990 std::fs::read(&path).unwrap(),
991 b"queued",
992 "evict_cached must flush before closing the handle"
993 );
994 assert!(
995 !ctx.file_cache.contains_key(&path),
996 "evict_cached must also remove the entry"
997 );
998 }
999
1000 #[test]
1001 fn clear_file_cache_flushes_every_pending_write() {
1002 // clear_file_cache must flush every buffered writer before dropping
1003 // — RemoveAll relies on this to avoid losing pending data against
1004 // the about-to-be-unlinked files.
1005 use std::io::Write;
1006
1007 let tmp = tempfile::tempdir().unwrap();
1008 let mut ctx = ApplyContext::new(tmp.path());
1009 let a = tmp.path().join("a.dat");
1010 let b = tmp.path().join("b.dat");
1011
1012 ctx.open_cached(a.clone())
1013 .unwrap()
1014 .write_all(b"AA")
1015 .unwrap();
1016 ctx.open_cached(b.clone())
1017 .unwrap()
1018 .write_all(b"BB")
1019 .unwrap();
1020
1021 ctx.clear_file_cache().unwrap();
1022
1023 assert_eq!(std::fs::read(&a).unwrap(), b"AA");
1024 assert_eq!(std::fs::read(&b).unwrap(), b"BB");
1025 assert!(ctx.file_cache.is_empty(), "cache must be empty after clear");
1026 }
1027
1028 // --- Debug impl ---
1029
1030 #[test]
1031 fn apply_context_debug_renders_all_fields() {
1032 // ApplyContext can't derive Debug because Box<dyn ApplyObserver> doesn't
1033 // implement it; the hand-written impl substitutes a placeholder for the
1034 // observer. Lock down the rendered shape so future refactors don't
1035 // accidentally drop fields (and so the impl itself is exercised by tests).
1036 let tmp = tempfile::tempdir().unwrap();
1037 let ctx = ApplyContext::new(tmp.path())
1038 .with_platform(Platform::Ps4)
1039 .with_ignore_missing(true);
1040
1041 let rendered = format!("{ctx:?}");
1042 for needle in [
1043 "ApplyContext",
1044 "game_path",
1045 "platform",
1046 "Ps4",
1047 "ignore_missing",
1048 "true",
1049 "ignore_old_mismatch",
1050 "file_cache_len",
1051 "path_cache_len",
1052 "decompressor",
1053 "<flate2::Decompress>",
1054 "observer",
1055 "<dyn ApplyObserver>",
1056 ] {
1057 assert!(
1058 rendered.contains(needle),
1059 "Debug output must mention {needle:?}; got: {rendered}"
1060 );
1061 }
1062 }
1063
1064 // --- DeleteDirectory happy path ---
1065
1066 #[test]
1067 fn delete_directory_success_removes_existing_dir() {
1068 // Exercises the Ok(()) trace+return arm of DeleteDirectory::apply
1069 // (previously only the ignore_missing and propagate-error arms were
1070 // covered).
1071 let tmp = tempfile::tempdir().unwrap();
1072 let target = tmp.path().join("to_remove");
1073 std::fs::create_dir(&target).unwrap();
1074 assert!(target.is_dir(), "pre-condition: directory must exist");
1075
1076 let mut ctx = ApplyContext::new(tmp.path());
1077 DeleteDirectory {
1078 name: "to_remove".into(),
1079 }
1080 .apply(&mut ctx)
1081 .expect("delete on an existing directory must succeed");
1082
1083 assert!(!target.exists(), "directory must be removed");
1084 }
1085
1086 // --- ensure_dir_all cache-hit branch ---
1087
1088 #[test]
1089 fn ensure_dir_all_cache_hit_returns_early_without_syscall() {
1090 // The second call for the same path must take the early-return branch
1091 // at line 521 (`return Ok(())`). We confirm this is hit by pre-seeding
1092 // `dirs_created` and then calling `ensure_dir_all` for a path that does
1093 // NOT actually exist on disk — if the cache-miss branch ran it would
1094 // call `create_dir_all` and either succeed (masking the bug) or fail.
1095 let tmp = tempfile::tempdir().unwrap();
1096 let mut ctx = ApplyContext::new(tmp.path());
1097
1098 let path = tmp.path().join("cached_dir");
1099 // First call: misses the cache, creates the directory on disk, inserts.
1100 ctx.ensure_dir_all(&path).unwrap();
1101 assert!(path.is_dir(), "first call must create the directory");
1102 assert_eq!(
1103 ctx.dirs_created.len(),
1104 1,
1105 "path must be cached after first call"
1106 );
1107
1108 // Remove the directory so a second real `create_dir_all` would see it
1109 // gone — if the cache-hit branch is NOT taken, the syscall would still
1110 // succeed (create_dir_all is idempotent for missing dirs), so instead
1111 // we verify the set length stays at 1, not 2.
1112 let p2 = tmp.path().join("cached_dir");
1113 ctx.ensure_dir_all(&p2).unwrap();
1114 assert_eq!(
1115 ctx.dirs_created.len(),
1116 1,
1117 "cache hit must not re-insert the path (set length must stay 1)"
1118 );
1119 }
1120
1121 // --- drain_and_flush error branch ---
1122
1123 #[test]
1124 fn drain_and_flush_error_propagates_first_io_error() {
1125 // Trigger the `Some(e) => Err(e)` arm in `drain_and_flush`.
1126 //
1127 // `/dev/full` always returns ENOSPC on write — use it as the backing
1128 // file so the BufWriter's flush (which actually calls write(2)) fails.
1129 // We open `/dev/full` directly and inject the handle into `file_cache`
1130 // via the `pub(crate)` field, bypassing `open_cached` which uses
1131 // `create=true` (incompatible with a character device).
1132 use std::io::Write;
1133
1134 let dev_full = std::path::PathBuf::from("/dev/full");
1135 if !dev_full.exists() {
1136 // /dev/full is Linux-specific; skip on platforms that lack it.
1137 return;
1138 }
1139
1140 let file = OpenOptions::new()
1141 .write(true)
1142 .open(&dev_full)
1143 .expect("/dev/full must be openable for writing");
1144
1145 let mut ctx = ApplyContext::new("/irrelevant");
1146 let mut writer = BufWriter::with_capacity(WRITE_BUFFER_CAPACITY, file);
1147 // Write into the BufWriter's user-space buffer — this succeeds because
1148 // BufWriter holds the data in RAM. The write only reaches /dev/full
1149 // (and fails with ENOSPC) when the buffer is flushed.
1150 writer.write_all(&[0xAB; 128]).unwrap();
1151 ctx.file_cache.insert(dev_full.clone(), writer);
1152
1153 let result = ctx.clear_file_cache();
1154
1155 assert!(
1156 result.is_err(),
1157 "drain_and_flush must propagate the ENOSPC error from /dev/full"
1158 );
1159 assert!(
1160 ctx.file_cache.is_empty(),
1161 "cache must be drained even when flush fails"
1162 );
1163 }
1164
1165 // --- flush error branch ---
1166
1167 #[test]
1168 fn flush_error_propagates_first_io_error() {
1169 // Trigger the `Some(e) => Err(e)` arm in `flush` using the same
1170 // `/dev/full` trick as `drain_and_flush_error_propagates_first_io_error`.
1171 // `flush` keeps handles in the cache (unlike `drain_and_flush`), so we
1172 // assert the cache still contains the entry after the failed flush.
1173 use std::io::Write;
1174
1175 let dev_full = std::path::PathBuf::from("/dev/full");
1176 if !dev_full.exists() {
1177 return;
1178 }
1179
1180 let file = OpenOptions::new()
1181 .write(true)
1182 .open(&dev_full)
1183 .expect("/dev/full must be openable for writing");
1184
1185 let mut ctx = ApplyContext::new("/irrelevant");
1186 let mut writer = BufWriter::with_capacity(WRITE_BUFFER_CAPACITY, file);
1187 writer.write_all(&[0xCD; 128]).unwrap();
1188 ctx.file_cache.insert(dev_full.clone(), writer);
1189
1190 let result = ctx.flush();
1191
1192 assert!(
1193 result.is_err(),
1194 "flush must propagate the ENOSPC error from /dev/full"
1195 );
1196 assert_eq!(
1197 ctx.file_cache.len(),
1198 1,
1199 "flush must NOT evict handles — only drain_and_flush does that"
1200 );
1201 }
1202}