惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
B
Blog
A
About on SuperTechFans
大猫的无限游戏
大猫的无限游戏
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 三生石上(FineUI控件)
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
IT之家
IT之家
D
Docker
Google DeepMind News
Google DeepMind News
罗磊的独立博客
T
The Blog of Author Tim Ferriss
aimingoo的专栏
aimingoo的专栏
博客园 - 叶小钗
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
D
DataBreaches.Net
博客园 - 司徒正美
Engineering at Meta
Engineering at Meta

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Smart Resume for File Transfers in Rust — Never Start Over
hiyoyo · 2026-06-17 · via DEV Community
Cover image for Smart Resume for File Transfers in Rust — Never Start Over

hiyoyo

All tests run on an 8-year-old MacBook Air. All results from shipping 7 Mac apps as a solo developer. No sponsored opinion.

A 2GB video transfer that fails at 90% and restarts from zero is a terrible experience. HiyokoMTP and HiyokoAutoSync both implement smart resume. Here's how.


The problem

File transfers fail. USB connections drop. Devices sleep. The user unplugs at the wrong moment.

Without resume: start over. With resume: pick up where you left off.


The approach

Track transfer state in SQLite. On failure, record the partial state. On retry, check the record and resume from the last confirmed position.

CREATE TABLE transfer_state (
    id INTEGER PRIMARY KEY,
    file_path TEXT NOT NULL,
    total_bytes INTEGER NOT NULL,
    transferred_bytes INTEGER DEFAULT 0,
    file_hash TEXT,
    status TEXT DEFAULT 'in_progress',
    started_at INTEGER,
    updated_at INTEGER
);


Writing with resume support

pub async fn transfer_with_resume(
    source: &Path,
    dest: &Path,
    db: &Connection,
) -> Result<(), AppError> {
    let file_hash = compute_hash(source)?;

    // Check for existing partial transfer
    let existing = db.query_row(
        "SELECT transferred_bytes FROM transfer_state
         WHERE file_path = ? AND file_hash = ? AND status = 'in_progress'",
        params![source.to_str().unwrap(), &file_hash],
        |r| r.get::<_, i64>(0),
    ).ok();

    let start_offset = existing.unwrap_or(0) as u64;

    // Open source file, seek to offset
    let mut reader = File::open(source)?;
    reader.seek(SeekFrom::Start(start_offset))?;

    // Open dest file for append if resuming
    let mut writer = if start_offset > 0 {
        OpenOptions::new().append(true).open(dest)?
    } else {
        File::create(dest)?
    };

    // Transfer in chunks, updating DB periodically
    let mut transferred = start_offset;
    let mut buf = vec![0u8; 65536];

    loop {
        let n = reader.read(&mut buf)?;
        if n == 0 { break; }

        writer.write_all(&buf[..n])?;
        transferred += n as u64;

        // Update progress every 1MB
        if transferred % (1024 * 1024) == 0 {
            db.execute(
                "UPDATE transfer_state SET transferred_bytes = ?, updated_at = ? WHERE file_path = ?",
                params![transferred as i64, unix_now(), source.to_str().unwrap()],
            )?;
        }
    }

    // Mark complete
    db.execute(
        "UPDATE transfer_state SET status = 'complete' WHERE file_path = ?",
        params![source.to_str().unwrap()],
    )?;

    Ok(())
}


Validating resumed files

After a resume, verify the file hash of the completed transfer:

if compute_hash(dest)? != expected_hash {
    // Hash mismatch — delete and retry from scratch
    std::fs::remove_file(dest)?;
    return Err(AppError::Transfer("Hash mismatch after resume".into()));
}

A corrupted partial transfer is worse than starting over. Always validate.


The verdict

Smart resume is the difference between a frustrating tool and a reliable one. SQLite tracking + offset-based writes cover the implementation. The complexity is worth it for any app that transfers large files.


TL;DR: Track transfer state in SQLite with transferred_bytes and file_hash. On retry, seek to the last confirmed offset and append. Update progress every 1MB to keep DB writes cheap. Always verify the final hash — a corrupted resume is worse than starting over.


If this was useful, a ❤️ helps more than you'd think — thanks!

HiyokoAutoSync | X → @hiyoyok