kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! Files (PROTOCOL.md §9, ADR 0017 §3): `put` copies the bytes into a
//! content-addressed staging folder and queues the `file/put`; the bytes
//! upload in the background, off the socket reader, and leave staging once
//! the put is acked. `download` streams to disk and verifies the SHA-256.

use std::collections::HashMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use serde_json::{json, Value};
use sha2::{Digest, Sha256};

use crate::api::seg;
use crate::engine::Ctx;
use crate::error::{Error, Result};
use crate::protocol::FileState;
use crate::store::PendingMutation;
use crate::transport::{resolve, Body, HttpRequest};

/// Where staged bytes wait for their upload.
pub(crate) struct Staging {
    dir: Option<PathBuf>,
    memory: Mutex<HashMap<String, Arc<Vec<u8>>>>,
}

impl Staging {
    pub fn new(dir: Option<PathBuf>) -> Staging {
        Staging { dir, memory: Mutex::new(HashMap::new()) }
    }

    /// Stages bytes; returns their SHA-256 (hex) and size.
    pub fn stage_bytes(&self, bytes: &[u8]) -> Result<(String, u64)> {
        let sha = hex::encode(Sha256::digest(bytes));
        match &self.dir {
            Some(d) => {
                std::fs::create_dir_all(d).map_err(Error::storage)?;
                let path = d.join(&sha);
                if !path.exists() {
                    let tmp = d.join(format!("{sha}.tmp"));
                    std::fs::write(&tmp, bytes).map_err(Error::storage)?;
                    std::fs::rename(&tmp, &path).map_err(Error::storage)?;
                }
            }
            None => {
                self.memory.lock().unwrap().insert(sha.clone(), Arc::new(bytes.to_vec()));
            }
        }
        Ok((sha, bytes.len() as u64))
    }

    /// Stages a local file by streaming it.
    pub fn stage_file(&self, src: &Path) -> Result<(String, u64)> {
        let Some(d) = &self.dir else {
            let bytes = std::fs::read(src).map_err(Error::storage)?;
            return self.stage_bytes(&bytes);
        };
        std::fs::create_dir_all(d).map_err(Error::storage)?;
        let tmp = d.join(format!("in-{}.tmp", uuid::Uuid::now_v7()));
        let mut f = std::fs::File::open(src).map_err(Error::storage)?;
        let mut out = std::fs::File::create(&tmp).map_err(Error::storage)?;
        let mut h = Sha256::new();
        let mut buf = vec![0u8; 1 << 16];
        let mut size = 0u64;
        loop {
            let n = f.read(&mut buf).map_err(Error::storage)?;
            if n == 0 {
                break;
            }
            h.update(&buf[..n]);
            std::io::Write::write_all(&mut out, &buf[..n]).map_err(Error::storage)?;
            size += n as u64;
        }
        let sha = hex::encode(h.finalize());
        std::fs::rename(&tmp, d.join(&sha)).map_err(Error::storage)?;
        Ok((sha, size))
    }

    fn body(&self, sha: &str) -> Result<Body> {
        if let Some(d) = &self.dir {
            let p = d.join(sha);
            if p.exists() {
                return Ok(Body::File(p));
            }
        }
        match self.memory.lock().unwrap().get(sha) {
            Some(b) => Ok(Body::Bytes(b.as_ref().clone())),
            None => Err(Error::new("blob_missing", format!("the staged bytes {sha} are gone"))
                .with_hint("Put the file again: its staged copy was removed before it uploaded.")),
        }
    }

    pub fn remove(&self, sha: &str) {
        if let Some(d) = &self.dir {
            let _ = std::fs::remove_file(d.join(sha));
        }
        self.memory.lock().unwrap().remove(sha);
    }
}

/// Uploads the bytes a pending file put needs (steps 2–3 of PROTOCOL.md §9).
pub(crate) async fn upload(ctx: &Ctx, space_id: &str, p: &PendingMutation) -> Result<()> {
    let Some(u) = &p.upload else { return Ok(()) };
    let path = format!("/v1/spaces/{}/files/uploads", seg(space_id));
    let v = ctx
        .api
        .json("POST", &path, Some(&json!({"sha256": u.sha256, "size_bytes": u.size_bytes, "mime_type": u.mime_type})))
        .await?;
    if v.get("exists").and_then(Value::as_bool) == Some(true) {
        return Ok(());
    }
    let up = v.get("upload").ok_or_else(|| Error::new("invalid_response", "upload answer without upload"))?;
    let method = up.get("method").and_then(Value::as_str).unwrap_or("PUT").to_string();
    let url = resolve(ctx.api.base(), up.get("url").and_then(Value::as_str).unwrap_or_default());
    let mut headers: Vec<(String, String)> = up
        .get("headers")
        .and_then(Value::as_object)
        .map(|h| h.iter().map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_string())).collect())
        .unwrap_or_default();
    if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) {
        headers.push(("content-type".into(), u.mime_type.clone()));
    }
    let body = ctx.staging.body(&u.sha256)?;
    let res = ctx.auth.transport().http(HttpRequest { method, url, headers, body, save_to: None }).await?;
    if !(200..300).contains(&res.status) {
        let mut e = Error::new(
            if res.status >= 500 { "internal" } else { "upload_failed" },
            format!("upload answered HTTP {}", res.status),
        );
        e.status = Some(res.status);
        // The presigned URL expired or was refused: ask again on the next try.
        if res.status == 403 || res.status == 400 {
            e.status = Some(503);
        }
        return Err(e);
    }
    Ok(())
}

/// One file's metadata (`GET …/files/{id}`).
pub(crate) async fn get(ctx: &Ctx, space_id: &str, id: &str) -> Result<FileState> {
    let v = ctx.api.json("GET", &format!("/v1/spaces/{}/files/{}", seg(space_id), seg(id)), None).await?;
    Ok(serde_json::from_value(v.get("file").cloned().unwrap_or(v))?)
}

/// Streams a file to `to` and verifies its SHA-256.
pub(crate) async fn download(ctx: &Ctx, space_id: &str, id: &str, to: &Path) -> Result<FileState> {
    let meta = get(ctx, space_id, id).await?;
    let d = ctx.api.json("GET", &format!("/v1/spaces/{}/files/{}/download", seg(space_id), seg(id)), None).await?;
    let url = resolve(ctx.api.base(), d.get("url").and_then(Value::as_str).unwrap_or_default());
    let headers: Vec<(String, String)> = d
        .get("headers")
        .and_then(Value::as_object)
        .map(|h| h.iter().map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_string())).collect())
        .unwrap_or_default();
    let tmp = to.with_extension("kovlet-download");
    let res = ctx
        .auth
        .transport()
        .http(HttpRequest {
            method: d.get("method").and_then(Value::as_str).unwrap_or("GET").into(),
            url,
            headers,
            body: Body::Empty,
            save_to: Some(tmp.clone()),
        })
        .await?;
    if !(200..300).contains(&res.status) {
        let _ = std::fs::remove_file(&tmp);
        let mut e = Error::new("download_failed", format!("download answered HTTP {}", res.status));
        e.status = Some(res.status);
        return Err(e);
    }
    let sha = {
        let tmp = tmp.clone();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mut f = std::fs::File::open(&tmp).map_err(Error::storage)?;
            let mut h = Sha256::new();
            std::io::copy(&mut f, &mut h).map_err(Error::storage)?;
            Ok(hex::encode(h.finalize()))
        })
        .await
        .map_err(Error::storage)??
    };
    if !meta.sha256.is_empty() && sha != meta.sha256 {
        let _ = std::fs::remove_file(&tmp);
        return Err(Error::new("checksum_mismatch", format!("downloaded bytes hash to {sha}, want {}", meta.sha256)));
    }
    std::fs::rename(&tmp, to).map_err(Error::storage)?;
    Ok(meta)
}

/// Lists live files under `prefix` (all pages).
pub(crate) async fn list(ctx: &Ctx, space_id: &str, prefix: Option<&str>) -> Result<Vec<FileState>> {
    let mut out = Vec::new();
    let mut after: Option<i64> = None;
    loop {
        let query = {
            let mut q = form_urlencoded::Serializer::new(String::new());
            if let Some(p) = prefix {
                q.append_pair("prefix", p);
            }
            if let Some(a) = after {
                q.append_pair("after_seq", &a.to_string());
            }
            q.append_pair("limit", "1000");
            q.finish()
        };
        let v = ctx.api.json("GET", &format!("/v1/spaces/{}/files?{}", seg(space_id), query), None).await?;
        let files: Vec<FileState> = serde_json::from_value(v.get("files").cloned().unwrap_or(Value::Array(vec![])))?;
        out.extend(files);
        match v.get("next_after_seq").and_then(Value::as_i64) {
            Some(n) if Some(n) != after => after = Some(n),
            _ => break,
        }
    }
    Ok(out)
}