Clavem

Software update checks and downloads in a Rust app

GET /v1/releases/<product id>/latest with the key in the X-License-Key header, parse the release with serde, and compare its version with the semver crate. Download the signed link when the user confirms, then replace the running binary with self-replace.

The releases endpoint is public, and what it returns depends on the key. A license that is valid for the product gets release notes and files with signed download links. Any other key gets only version and published_at. The fields and limits are in the release docs. This page covers the Rust side. It assumes a license check like the one in license key validation in Rust.

Check

use semver::Version;
use serde::Deserialize;
use std::time::Duration;

#[derive(Debug, Deserialize)]
pub struct ReleaseFile { pub id: u64, pub filename: String, pub size: u64, pub platform: Option<String>, pub url: Option<String> }

#[derive(Debug, Deserialize)]
pub struct Release {
    pub version: String,
    pub notes: Option<String>,
    pub published_at: String,
    #[serde(default)]
    pub files: Vec<ReleaseFile>,
}

pub enum Update { UpToDate, Available(Release), Locked(String), NoRelease, Failed(String) }

pub fn check(base: &str, product_id: u64, current: &Version, key: Option<&str>, platform: &str) -> Update {
    let agent: ureq::Agent = ureq::Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(8)))
        .http_status_as_error(false)
        .build().into();
    let mut req = agent.get(&format!("{base}/v1/releases/{product_id}/latest")).query("platform", platform);
    if let Some(key) = key { req = req.header("X-License-Key", key); }

    let mut res = match req.call() { Ok(r) => r, Err(e) => return Update::Failed(format!("offline: {e}")) };
    match res.status().as_u16() {
        200 => {}
        404 => return Update::NoRelease,
        429 => return Update::Failed("rate limited: retry after 60 s".into()),
        s => return Update::Failed(format!("HTTP {s}")),
    }
    let Ok(release) = res.body_mut().read_json::<Release>() else { return Update::Failed("unreadable reply".into()) };
    let Ok(latest) = Version::parse(&release.version) else { return Update::Failed("version is not semver".into()) };
    if latest <= *current { Update::UpToDate }
    else if release.files.iter().any(|f| f.url.is_some()) { Update::Available(release) }
    else { Update::Locked(release.version) }
}

Locked is the useful middle case. A lapsed customer still learns that a newer version exists, and you can send them to renew. Only a valid key adds links.

What came back

From a local stub that returns the documented responses, with the program on 3.2.0 and one live call:

with key:                       Available(3.2.1 files=["Inkwell-3.2.1.dmg", "inkwell-3.2.1.zip"])
without key:                    Locked("3.2.1")
already on 3.10.0:              UpToDate
program on 3.2.1-beta.1:        Available(3.2.1 ...)
other product:                  NoRelease
live demo product:              NoRelease

The live call is real: the demo product has no published release, so the API answers 404 with {"error":{"code":"not_found","message":"This product has no published release yet."}}. The pre-release line is the reason to use semver rather than comparing numbers: 3.2.1-beta.1 sorts below 3.2.1, so a beta tester is offered the final build.

Name platform labels yourself when you upload. A label is 1 to 40 characters of lowercase letters, digits, dots, dashes and underscores. format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH) gives macos-aarch64 or linux-x86_64. A file with no label is offered to every platform.

Download

Request the link when the user confirms, not when the check ran. Links last one hour. This version streams to a .part file, resumes with Range, and renames only when the size matches:

use std::{fs, fs::OpenOptions, io, path::Path};

pub fn download(file: &ReleaseFile, dest: &Path) -> io::Result<()> {
    let url = file.url.as_deref().ok_or_else(|| io::Error::new(io::ErrorKind::PermissionDenied, "no download link for this license"))?;
    let part = dest.with_extension("part");
    let mut have = fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
    if have > file.size { fs::remove_file(&part)?; have = 0; }

    if have < file.size {
        // No global timeout: a 50 MB download would hit an 8 second limit.
        let agent: ureq::Agent = ureq::Agent::config_builder()
            .timeout_connect(Some(Duration::from_secs(10))).http_status_as_error(false).build().into();
        let mut req = agent.get(url);
        if have > 0 { req = req.header("Range", format!("bytes={have}-")); }
        let res = req.call().map_err(io::Error::other)?;
        let mut out = match res.status().as_u16() {
            206 => OpenOptions::new().append(true).open(&part)?,
            200 => fs::File::create(&part)?, // Range ignored: start over
            403 => return Err(io::Error::new(io::ErrorKind::PermissionDenied, "link expired: check again")),
            s => return Err(io::Error::other(format!("HTTP {s}"))),
        };
        io::copy(&mut res.into_body().into_reader(), &mut out)?;
        out.sync_all()?;
    }
    if fs::metadata(&part)?.len() != file.size {
        return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "size mismatch: keep the .part file and resume"));
    }
    fs::rename(&part, dest)
}

Test results: with 1 MiB already in the .part file of a 3 MiB download, the call resumed with a 206 and ended at 3,145,728 bytes. A link with a bad signature returned link expired: check again. A file declared 10 bytes larger than the server’s returned size mismatch. The response has no checksum field, so size is the only integrity check the API gives. Sign the binary you ship, and verify it with the platform’s tools.

Replace the running binary

pub fn install(new_exe: &Path) -> io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(new_exe, fs::Permissions::from_mode(0o755))?;
    }
    self_replace::self_replace(new_exe)?;
    fs::remove_file(new_exe)
}

The permission line matters: a file written by File::create has no execute bit. On Windows a running .exe cannot be overwritten. The self-replace crate handles that case, and on Unix it is a rename. Ask the user to restart afterward. For a GUI app in a bundle or installer, download the installer and launch it instead.

Limits and timing

The endpoint allows 120 requests a minute per IP address, counted apart from validation. Check once per run, or once a day for a long-running program. “Latest” is the most recently published release, not the highest version: a backport published after 3.2.1 becomes what the endpoint returns, so users on 3.2.1 see nothing newer.

Doing this with Clavem

Upload each build once in the dashboard, give each file a platform label and publish. The same key that turns the app on fetches the download, and imported licenses, which have no order page, get their downloads through this endpoint. The limits and storage rules are in the release docs.

Questions

How do I compare versions in Rust?

Use the semver crate. Version::parse reads 3.10.0 and 4.0.0-beta.2, and the ordering puts a pre-release below its release, so an app on 3.2.1-beta.1 is offered 3.2.1.

Can a Rust program replace its own executable?

On Unix a rename is enough. On Windows a running exe cannot be overwritten, which is why the self-replace crate exists. Download the new binary next to the old one, mark it executable on Unix, then call self_replace.

Why does a download time out after 8 seconds?

A global timeout in ureq covers the whole request, including reading the body. Use a short global timeout for the check and a connect timeout only for the download.

Sources

  1. ureq 3 ConfigBuilder, timeout_global (checked November 2026)
  2. self-replace crate README (checked November 2026)