Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Resync

When a file moves, grows, or is otherwise modified, the saved state becomes outdated and opening an iterator fails with a mismatch error. resync updates the state’s file metadata to match the current file, so you can continue reading

The Resync Pattern

The standard approach is to catch the mismatch error, resync, and retry:

Rust

use preader::{Error, LineIterator, Mismatch, PReader};

fn resume(reader: &PReader, file: &std::path::Path) -> preader::Result<LineIterator> {
    match reader.lines(file).state("job-1").build() {
        Err(error @ Error::Mismatch {
            kind: Mismatch::Path | Mismatch::Size | Mismatch::Mtime | Mismatch::Missing,
            ..
        }) => {
            eprintln!("{error}, resyncing");
            reader.states().resync("job-1", file)?;
            reader.lines(file).state("job-1").build()
        }
        result => result,
    }
}

Python

from preader import LineIterator, PReader, StateOutdatedError


def resume(reader: PReader, file) -> LineIterator:
    try:
        return reader.lines(file, state="job-1")
    except StateOutdatedError as error:
        print(f"{error}, resyncing")
        reader.states.resync(error.name, file)
        return reader.lines(file, state="job-1")

In Rust, you match on the specific Mismatch variants that indicate a recoverable change. In Python, the same variants are grouped under StateOutdatedError

What Resync Does

resync(name, file) updates the saved state’s file metadata:

  • Path is set to the canonical path of the new file
  • Size is updated to the current file size
  • Mtime is updated to the current modification time
  • Fingerprint is recomputed from the first 4096 bytes

The read position is clamped to the new file size. If the file shrank below the saved position, the position is set to the new end of file

resync only updates the file metadata in the saved state. It does not re-read or revalidate file content beyond the first 4096 bytes used for the fingerprint

Complete Example

This example reads a file, saves state, moves the file, resyncs, appends data, and reads again:

Rust

use std::io::Write;
use preader::PReader;

let file = std::path::PathBuf::from("data.txt");
let moved = std::path::PathBuf::from("moved.txt");

std::fs::write(&file, "line-0\nline-1\n")?;

let reader = PReader::default();

// Read all lines and save
let mut lines = reader.lines(&file).state("job-1").build()?;

for line in lines.by_ref() {
    println!("read {}", line?);
}

lines.save()?;

// Move the file
std::fs::rename(&file, &moved)?;

// Resume after the move, triggers resync
let lines = resume(&reader, &moved)?;
println!("resumes at {:.1}% after the file moved", lines.percent());

// Append new data
std::fs::OpenOptions::new()
    .append(true)
    .open(&moved)?
    .write_all(b"line-2\nline-3\n")?;

// Resume after the file grew, triggers resync again
for line in resume(&reader, &moved)? {
    println!("read {} after the file grew", line?);
}

Python

from pathlib import Path
from preader import PReader

file = Path("data.txt")
moved = Path("moved.txt")

file.write_text("line-0\nline-1\n")

reader = PReader()

# Read all lines and save
lines = reader.lines(file, state="job-1")

for line in lines:
    print(f"read {line}")

lines.save()
# Move the file
file.rename(moved)

# Resume after the move
lines = resume(reader, moved)
print(f"resumes at {lines.percent():.1f}% after the file moved")

# Append new data
with moved.open("ab") as f:
    f.write(b"line-2\nline-3\n")

# Resume after the file grew
for line in resume(reader, moved):
    print(f"read {line} after the file grew")

The first resync updates the path to the new location. The second updates the file size and mtime after the append, and reading continues from where it left off