Files
tessera/crates/tessera-agent/src/main.rs
Adnan Zahir 749c4cc828 feat: use Restic for encrypted incremental backups
Keep legacy restores readable while using Restic for new captures, scoped Wormhole repositories, and chunk garbage collection.
2026-11-10 10:48:05 +07:00

175 lines
5.6 KiB
Rust

mod http;
use anyhow::{Context, Result};
use base64::Engine;
use clap::{Parser, Subcommand};
use tessera_core::config::ProviderKind;
use tessera_providers::provider_from_config;
use tracing::info;
#[derive(Parser)]
#[command(name = "tessera-agent", about = "Tessera outpost daemon")]
struct Cli {
#[command(subcommand)]
command: Option<AgentCmd>,
#[arg(long, env = "TESSERA_HUB_URL")]
hub_url: Option<String>,
#[arg(long, env = "TESSERA_UPLOAD_TOKEN")]
upload_token: Option<String>,
#[arg(long, env = "TESSERA_ORBIT_ID")]
orbit_id: Option<String>,
}
#[derive(Clone, Subcommand)]
enum AgentCmd {
Run,
Pair {
code: String,
#[arg(long, default_value = "outpost")]
name: String,
},
Beam,
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let cli = Cli::parse();
match cli.command.clone().unwrap_or(AgentCmd::Run) {
AgentCmd::Run => run_daemon(&cli).await?,
AgentCmd::Pair { code, name } => pair(&cli, &code, &name)?,
AgentCmd::Beam => beam_once(&cli).await?,
}
Ok(())
}
fn pair(cli: &Cli, code: &str, name: &str) -> Result<()> {
let hub = cli
.hub_url
.clone()
.unwrap_or_else(|| "http://127.0.0.1:8787".into());
let body = serde_json::json!({ "code": code, "outpost_name": name });
let raw = http::post_json(
&format!("{hub}/api/v1/wormhole/claim"),
&body,
&[],
)?;
let res: serde_json::Value = serde_json::from_str(&raw)?;
println!("TESSERA_UPLOAD_TOKEN={}", res["upload_token"]);
println!("TESSERA_HUB_URL={}", res["hub_url"]);
println!("Outpost {}", res["outpost_id"]);
Ok(())
}
async fn run_daemon(cli: &Cli) -> Result<()> {
info!("outpost online — wormhole listening for beam cycles");
loop {
if let Err(e) = beam_once(cli).await {
tracing::warn!("beam failed: {e}");
}
tokio::time::sleep(std::time::Duration::from_secs(300)).await;
}
}
async fn beam_once(cli: &Cli) -> Result<()> {
let hub = cli
.hub_url
.clone()
.context("TESSERA_HUB_URL")?
.trim_end_matches('/')
.to_string();
let token = cli.upload_token.clone().context("TESSERA_UPLOAD_TOKEN")?;
let orbit_id = cli.orbit_id.clone().context("TESSERA_ORBIT_ID")?;
if let Some(repository) = std::env::var_os("TESSERA_RESTIC_REPOSITORY") {
let repository = repository
.to_str()
.context("TESSERA_RESTIC_REPOSITORY must be UTF-8")?;
let id = uuid::Uuid::parse_str(&orbit_id).context("invalid TESSERA_ORBIT_ID")?;
return beam_restic(repository, &hub, &token, id).await;
}
let config = serde_json::json!({ "paths": ["./"] });
let provider = provider_from_config(&ProviderKind::Filesystem, &config)?;
let capture = provider.capture().await?;
let chunk_b64 = base64::engine::general_purpose::STANDARD.encode(&capture.payload);
let init_body = serde_json::json!({
"orbit_id": orbit_id,
"total_bytes": capture.payload.len(),
});
let init_raw = http::post_json(
&format!("{hub}/api/v1/wormhole/upload/init"),
&init_body,
&[("x-tessera-upload-token", &token)],
)?;
let init: serde_json::Value = serde_json::from_str(&init_raw)?;
let session_id = init["session_id"].as_str().context("session_id")?;
let chunk_body = serde_json::json!({
"session_id": session_id,
"offset": 0,
"data_b64": chunk_b64,
});
http::post_json(
&format!("{hub}/api/v1/wormhole/upload/chunk"),
&chunk_body,
&[("x-tessera-upload-token", &token)],
)?;
info!("beamed {} bytes via wormhole session {session_id}", capture.payload.len());
Ok(())
}
async fn beam_restic(repository: &str, hub: &str, token: &str, orbit_id: uuid::Uuid) -> Result<()> {
let authority = repository
.strip_prefix("rest:https://")
.and_then(|url| url.split('/').next());
anyhow::ensure!(
authority.is_some_and(|host| !host.is_empty() && !host.contains('@')),
"TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials"
);
let output = tokio::process::Command::new("restic")
.env("RESTIC_REPOSITORY", repository)
.env_remove("RESTIC_REPOSITORY_FILE")
.args(["backup", "--json", "--quiet", "--force", "--", "."])
.stdin(std::process::Stdio::null())
.kill_on_drop(true)
.output()
.await
.context("starting restic (install restic on PATH)")?;
anyhow::ensure!(
output.status.success(),
"restic backup failed ({}): {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
);
let summary: serde_json::Value = serde_json::from_str(
std::str::from_utf8(&output.stdout)?
.lines()
.last()
.context("missing restic summary")?,
)?;
let snapshot = summary["snapshot_id"]
.as_str()
.context("missing restic snapshot ID")?;
let body = serde_json::json!({ "orbit_id": orbit_id, "snapshot_id": snapshot });
let reply = http::post_json(
&format!("{hub}/api/v1/wormhole/restic/commit"),
&body,
&[("x-tessera-upload-token", token)],
)
.with_context(|| format!("register Restic snapshot {snapshot}"))?;
let reply: serde_json::Value = serde_json::from_str(&reply)?;
let registered = reply["snapshot_id"]
.as_str()
.context("hub did not register the Restic snapshot")?;
info!(
snapshot,
registered,
stored_bytes = summary["data_added_packed"].as_u64(),
"committed Restic backup"
);
Ok(())
}