Initial Tessera backup vault (M0–M2)
Scaffold Rust workspace, React canvas, vault engine, hub API, providers, agent wormhole path, and Docker compose per SPEC.
This commit is contained in:
22
crates/tessera-agent/Cargo.toml
Normal file
22
crates/tessera-agent/Cargo.toml
Normal file
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "tessera-agent"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "tessera-agent"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
tessera-core = { path = "../tessera-core" }
|
||||
tessera-providers = { path = "../tessera-providers" }
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid.workspace = true
|
||||
base64 = "0.22"
|
||||
58
crates/tessera-agent/src/http.rs
Normal file
58
crates/tessera-agent/src/http.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpStream;
|
||||
|
||||
pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> {
|
||||
let payload = serde_json::to_string(body)?;
|
||||
request("POST", url, Some(&payload), Some("application/json"), headers)
|
||||
}
|
||||
|
||||
fn request(
|
||||
method: &str,
|
||||
url: &str,
|
||||
body: Option<&str>,
|
||||
content_type: Option<&str>,
|
||||
headers: &[(&str, &str)],
|
||||
) -> Result<String> {
|
||||
let (host, port, path) = parse_url(url)?;
|
||||
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
|
||||
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
|
||||
for (k, v) in headers {
|
||||
req.push_str(&format!("{k}: {v}\r\n"));
|
||||
}
|
||||
if let Some(b) = body {
|
||||
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
|
||||
if let Some(ct) = content_type {
|
||||
req.push_str(&format!("Content-Type: {ct}\r\n"));
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
req.push_str(b);
|
||||
} else {
|
||||
req.push_str("\r\n");
|
||||
}
|
||||
stream.write_all(req.as_bytes())?;
|
||||
let mut buf = String::new();
|
||||
stream.read_to_string(&mut buf)?;
|
||||
let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0);
|
||||
Ok(buf[body_start..].trim().to_string())
|
||||
}
|
||||
|
||||
fn parse_url(url: &str) -> Result<(String, u16, String)> {
|
||||
let url = url.strip_prefix("http://").context("only http supported")?;
|
||||
let (host_port, path) = url.split_once('/').unwrap_or((url, ""));
|
||||
let path = if path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
format!("/{path}")
|
||||
};
|
||||
let (host, port) = if let Some((h, p)) = host_port.split_once(':') {
|
||||
(h.to_string(), p.parse()?)
|
||||
} else {
|
||||
(host_port.to_string(), 80)
|
||||
};
|
||||
Ok((host, port, path))
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub type HeaderMap = HashMap<String, String>;
|
||||
114
crates/tessera-agent/src/main.rs
Normal file
114
crates/tessera-agent/src/main.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
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")?;
|
||||
|
||||
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(())
|
||||
}
|
||||
19
crates/tessera-cli/Cargo.toml
Normal file
19
crates/tessera-cli/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "tessera-cli"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "tessera"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
tessera-core = { path = "../tessera-core" }
|
||||
tessera-store = { path = "../tessera-store" }
|
||||
tessera-providers = { path = "../tessera-providers" }
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
uuid.workspace = true
|
||||
54
crates/tessera-cli/src/http.rs
Normal file
54
crates/tessera-cli/src/http.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpStream;
|
||||
|
||||
pub fn get(url: &str) -> Result<String> {
|
||||
request("GET", url, None, None)
|
||||
}
|
||||
|
||||
pub fn post_json(url: &str, body: &serde_json::Value) -> Result<String> {
|
||||
let payload = serde_json::to_string(body)?;
|
||||
request("POST", url, Some(&payload), Some("application/json"))
|
||||
}
|
||||
|
||||
fn request(method: &str, url: &str, body: Option<&str>, content_type: Option<&str>) -> Result<String> {
|
||||
let (host, port, path) = parse_url(url)?;
|
||||
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
|
||||
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
|
||||
if let Some(b) = body {
|
||||
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
|
||||
if let Some(ct) = content_type {
|
||||
req.push_str(&format!("Content-Type: {ct}\r\n"));
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
req.push_str(b);
|
||||
} else {
|
||||
req.push_str("\r\n");
|
||||
}
|
||||
stream.write_all(req.as_bytes())?;
|
||||
let mut buf = String::new();
|
||||
stream.read_to_string(&mut buf)?;
|
||||
let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0);
|
||||
Ok(buf[body_start..].trim().to_string())
|
||||
}
|
||||
|
||||
fn parse_url(url: &str) -> Result<(String, u16, String)> {
|
||||
let url = url.strip_prefix("http://").context("only http supported")?;
|
||||
let (host_port, path) = url.split_once('/').unwrap_or((url, ""));
|
||||
let path = if path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
format!("/{path}")
|
||||
};
|
||||
let (host, port) = if let Some((h, p)) = host_port.split_once(':') {
|
||||
(h.to_string(), p.parse()?)
|
||||
} else {
|
||||
(host_port.to_string(), 80)
|
||||
};
|
||||
Ok((host, port, path))
|
||||
}
|
||||
|
||||
pub fn post_empty(url: &str) -> Result<()> {
|
||||
request("POST", url, None, None)?;
|
||||
Ok(())
|
||||
}
|
||||
202
crates/tessera-cli/src/main.rs
Normal file
202
crates/tessera-cli/src/main.rs
Normal file
@@ -0,0 +1,202 @@
|
||||
mod http;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
use tessera_store::Vault;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Parser, Clone)]
|
||||
#[command(name = "tessera", about = "Tessera backup vault CLI")]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Commands,
|
||||
#[arg(long, env = "TESSERA_DATA_DIR", default_value = "./data")]
|
||||
data_dir: String,
|
||||
#[arg(long, env = "TESSERA_VAULT_PASSPHRASE", default_value = "dev-vault-key")]
|
||||
vault_pass: String,
|
||||
#[arg(long, env = "TESSERA_HUB_URL", default_value = "http://127.0.0.1:8787")]
|
||||
hub_url: String,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Clone)]
|
||||
enum Commands {
|
||||
Init,
|
||||
Status,
|
||||
Orbit {
|
||||
name: String,
|
||||
#[arg(long, default_value = "filesystem")]
|
||||
provider: String,
|
||||
#[arg(long)]
|
||||
path: Option<String>,
|
||||
#[arg(long)]
|
||||
schedule: Option<String>,
|
||||
#[arg(long)]
|
||||
dry_run: bool,
|
||||
},
|
||||
Snap {
|
||||
#[arg(long)]
|
||||
orbit: Option<String>,
|
||||
},
|
||||
List,
|
||||
Reconstitute {
|
||||
snapshot_id: Uuid,
|
||||
target: String,
|
||||
},
|
||||
Decay {
|
||||
#[arg(long, default_value = "week-of-dailies")]
|
||||
preset: String,
|
||||
},
|
||||
Wormhole {
|
||||
#[command(subcommand)]
|
||||
cmd: WormholeCmd,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Clone)]
|
||||
enum WormholeCmd {
|
||||
Pair {
|
||||
code: String,
|
||||
#[arg(long, default_value = "outpost")]
|
||||
name: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
let command = cli.command.clone();
|
||||
match command {
|
||||
Commands::Init => cmd_init(&cli)?,
|
||||
Commands::Status => cmd_status(&cli)?,
|
||||
Commands::Orbit {
|
||||
name,
|
||||
provider,
|
||||
path,
|
||||
schedule,
|
||||
dry_run,
|
||||
} => cmd_orbit(&cli, name, provider, path, schedule, dry_run)?,
|
||||
Commands::Snap { orbit } => cmd_snap(&cli, orbit)?,
|
||||
Commands::List => cmd_list(&cli)?,
|
||||
Commands::Reconstitute {
|
||||
snapshot_id,
|
||||
target,
|
||||
} => cmd_reconstitute(&cli, snapshot_id, target)?,
|
||||
Commands::Decay { preset } => cmd_decay(&cli, &preset)?,
|
||||
Commands::Wormhole { ref cmd } => match cmd {
|
||||
WormholeCmd::Pair { code, name } => wormhole_pair(&cli, code, name)?,
|
||||
},
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn vault_path(data_dir: &str) -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(data_dir).join("vault")
|
||||
}
|
||||
|
||||
fn cmd_init(cli: &Cli) -> Result<()> {
|
||||
let vp = vault_path(&cli.data_dir);
|
||||
if vp.join("config").exists() {
|
||||
println!("Vault already initialized.");
|
||||
return Ok(());
|
||||
}
|
||||
Vault::init(&vp, &cli.vault_pass).context("init vault")?;
|
||||
println!("Vault initialized at {}", vp.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_status(cli: &Cli) -> Result<()> {
|
||||
match http::get(&format!("{}/health", cli.hub_url)) {
|
||||
Ok(body) => println!("Hub: {body}"),
|
||||
Err(_) => println!("Hub: offline (is tessera-hub running?)"),
|
||||
}
|
||||
let vp = vault_path(&cli.data_dir);
|
||||
if vp.join("config").exists() {
|
||||
let vault = Vault::open(&vp, &cli.vault_pass)?;
|
||||
let n = vault.list_snapshots()?.len();
|
||||
println!("Vault: online — {n} snapshots");
|
||||
} else {
|
||||
println!("Vault: not initialized (run tessera init)");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_orbit(
|
||||
cli: &Cli,
|
||||
name: String,
|
||||
provider: String,
|
||||
path: Option<String>,
|
||||
schedule: Option<String>,
|
||||
dry_run: bool,
|
||||
) -> Result<()> {
|
||||
let config = match provider.as_str() {
|
||||
"filesystem" => serde_json::json!({ "paths": [path.unwrap_or_else(|| ".".into())] }),
|
||||
"postgres" => serde_json::json!({ "connection_url": path.context("--path or connection url required")? }),
|
||||
_ => anyhow::bail!("unknown provider"),
|
||||
};
|
||||
let body = serde_json::json!({
|
||||
"name": name,
|
||||
"provider": provider,
|
||||
"provider_config": config,
|
||||
"schedule": schedule,
|
||||
"dry_run": dry_run,
|
||||
});
|
||||
let raw = http::post_json(&format!("{}/api/v1/orbits", cli.hub_url), &body)?;
|
||||
let orbit: serde_json::Value = serde_json::from_str(&raw)?;
|
||||
println!("Orbit registered: {}", orbit["id"]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_snap(cli: &Cli, orbit_name: Option<String>) -> Result<()> {
|
||||
let raw = http::get(&format!("{}/api/v1/orbits", cli.hub_url))?;
|
||||
let orbits: serde_json::Value = serde_json::from_str(&raw)?;
|
||||
let arr = orbits.as_array().context("orbits response")?;
|
||||
let id = if let Some(name) = orbit_name {
|
||||
arr.iter()
|
||||
.find(|o| o["name"] == name)
|
||||
.and_then(|o| o["id"].as_str())
|
||||
.context("orbit not found")?
|
||||
} else {
|
||||
arr.first()
|
||||
.and_then(|o| o["id"].as_str())
|
||||
.context("no orbits defined")?
|
||||
};
|
||||
http::post_empty(&format!("{}/api/v1/orbits/{id}/run", cli.hub_url))?;
|
||||
println!("Orbit run triggered.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_list(cli: &Cli) -> Result<()> {
|
||||
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
|
||||
for s in vault.list_snapshots()? {
|
||||
println!(
|
||||
"{} {} {} bytes orbit={}",
|
||||
s.taken_at.to_rfc3339(),
|
||||
s.id,
|
||||
s.size_bytes,
|
||||
s.manifest.orbit_name
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> {
|
||||
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
|
||||
let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?;
|
||||
println!("Reconstituted {n} bytes to {target}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> {
|
||||
let mut vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
|
||||
let pruned = vault.prune_with_decay(preset)?;
|
||||
println!("{} snapshots decayed.", pruned.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wormhole_pair(cli: &Cli, code: &str, name: &str) -> Result<()> {
|
||||
let body = serde_json::json!({ "code": code, "outpost_name": name });
|
||||
let raw = http::post_json(&format!("{}/api/v1/wormhole/claim", cli.hub_url), &body)?;
|
||||
let res: serde_json::Value = serde_json::from_str(&raw)?;
|
||||
println!("Paired outpost {}", res["outpost_id"]);
|
||||
println!("Set TESSERA_UPLOAD_TOKEN on the agent.");
|
||||
Ok(())
|
||||
}
|
||||
16
crates/tessera-core/Cargo.toml
Normal file
16
crates/tessera-core/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "tessera-core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
chrono.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
uuid.workspace = true
|
||||
hex.workspace = true
|
||||
sha2.workspace = true
|
||||
utoipa = { workspace = true }
|
||||
45
crates/tessera-core/src/config.rs
Normal file
45
crates/tessera-core/src/config.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VaultConfig {
|
||||
pub vault_id: Uuid,
|
||||
pub vault_path: String,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HubConfig {
|
||||
pub listen: String,
|
||||
pub data_dir: String,
|
||||
pub admin_password_hash: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for HubConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
listen: "0.0.0.0:8787".into(),
|
||||
data_dir: "./data".into(),
|
||||
admin_password_hash: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ProviderKind {
|
||||
Filesystem,
|
||||
Postgres,
|
||||
Command,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OrbitSpec {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub provider: ProviderKind,
|
||||
pub provider_config: serde_json::Value,
|
||||
pub schedule: Option<String>,
|
||||
pub decay_preset: String,
|
||||
pub dry_run: bool,
|
||||
}
|
||||
119
crates/tessera-core/src/decay.rs
Normal file
119
crates/tessera-core/src/decay.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DecayPolicy {
|
||||
pub keep_daily: usize,
|
||||
pub keep_weekly: usize,
|
||||
pub keep_monthly: usize,
|
||||
}
|
||||
|
||||
impl DecayPolicy {
|
||||
pub fn from_preset(name: &str) -> Self {
|
||||
match name {
|
||||
"week-of-dailies" => Self {
|
||||
keep_daily: 7,
|
||||
keep_weekly: 0,
|
||||
keep_monthly: 0,
|
||||
},
|
||||
"month-of-weeklies" => Self {
|
||||
keep_daily: 0,
|
||||
keep_weekly: 4,
|
||||
keep_monthly: 0,
|
||||
},
|
||||
"year-of-monthlies" => Self {
|
||||
keep_daily: 0,
|
||||
keep_weekly: 0,
|
||||
keep_monthly: 12,
|
||||
},
|
||||
_ => Self {
|
||||
keep_daily: 7,
|
||||
keep_weekly: 4,
|
||||
keep_monthly: 12,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SnapshotRef {
|
||||
pub id: Uuid,
|
||||
pub taken_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Returns snapshot IDs to forget (newest-first input).
|
||||
pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec<SnapshotRef>) -> Vec<Uuid> {
|
||||
snapshots.sort_by(|a, b| b.taken_at.cmp(&a.taken_at));
|
||||
let mut keep = std::collections::HashSet::new();
|
||||
|
||||
if policy.keep_daily > 0 {
|
||||
for s in snapshots.iter().take(policy.keep_daily) {
|
||||
keep.insert(s.id);
|
||||
}
|
||||
}
|
||||
|
||||
if policy.keep_weekly > 0 {
|
||||
let mut weeks: Vec<(i64, SnapshotRef)> = Vec::new();
|
||||
for s in &snapshots {
|
||||
let week = s.taken_at.timestamp() / (7 * 86400);
|
||||
if let Some(pos) = weeks.iter().position(|(w, _)| *w == week) {
|
||||
if s.taken_at > weeks[pos].1.taken_at {
|
||||
weeks[pos] = (week, s.clone());
|
||||
}
|
||||
} else {
|
||||
weeks.push((week, s.clone()));
|
||||
}
|
||||
}
|
||||
weeks.sort_by(|a, b| b.1.taken_at.cmp(&a.1.taken_at));
|
||||
for (_, s) in weeks.into_iter().take(policy.keep_weekly) {
|
||||
keep.insert(s.id);
|
||||
}
|
||||
}
|
||||
|
||||
if policy.keep_monthly > 0 {
|
||||
let mut months: Vec<(i32, u32, SnapshotRef)> = Vec::new();
|
||||
for s in &snapshots {
|
||||
let key = (s.taken_at.year(), s.taken_at.month());
|
||||
if let Some(pos) = months.iter().position(|(y, m, _)| *y == key.0 && *m == key.1) {
|
||||
if s.taken_at > months[pos].2.taken_at {
|
||||
months[pos] = (key.0, key.1, s.clone());
|
||||
}
|
||||
} else {
|
||||
months.push((key.0, key.1, s.clone()));
|
||||
}
|
||||
}
|
||||
months.sort_by(|a, b| b.2.taken_at.cmp(&a.2.taken_at));
|
||||
for (_, _, s) in months.into_iter().take(policy.keep_monthly) {
|
||||
keep.insert(s.id);
|
||||
}
|
||||
}
|
||||
|
||||
snapshots
|
||||
.into_iter()
|
||||
.filter(|s| !keep.contains(&s.id))
|
||||
.map(|s| s.id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
use chrono::Datelike;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::Duration;
|
||||
|
||||
#[test]
|
||||
fn keeps_n_dailies() {
|
||||
let policy = DecayPolicy::from_preset("week-of-dailies");
|
||||
let now = Utc::now();
|
||||
let snaps: Vec<SnapshotRef> = (0..10)
|
||||
.map(|i| SnapshotRef {
|
||||
id: Uuid::new_v4(),
|
||||
taken_at: now - Duration::days(i),
|
||||
})
|
||||
.collect();
|
||||
let forget = evaluate_decay(&policy, snaps);
|
||||
assert_eq!(forget.len(), 3);
|
||||
}
|
||||
}
|
||||
33
crates/tessera-core/src/errors.rs
Normal file
33
crates/tessera-core/src/errors.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum TesseraError {
|
||||
#[error("vault is locked: {0}")]
|
||||
VaultLocked(String),
|
||||
#[error("wrong passphrase")]
|
||||
WrongPassphrase,
|
||||
#[error("provider unreachable: {0}")]
|
||||
ProviderUnreachable(String),
|
||||
#[error("disk full: need {needed} bytes")]
|
||||
DiskFull { needed: u64 },
|
||||
#[error("{0}")]
|
||||
UserMessage(String),
|
||||
}
|
||||
|
||||
impl TesseraError {
|
||||
pub fn user_message(&self) -> &str {
|
||||
match self {
|
||||
TesseraError::VaultLocked(_) => {
|
||||
"Another orbit is still circling the vault. Try again when it finishes."
|
||||
}
|
||||
TesseraError::WrongPassphrase => "That key doesn't unlock this vault.",
|
||||
TesseraError::ProviderUnreachable(_) => {
|
||||
"We couldn't reach the source at this outpost."
|
||||
}
|
||||
TesseraError::DiskFull { .. } => {
|
||||
"The vault is out of space—free room or widen the hold."
|
||||
}
|
||||
TesseraError::UserMessage(m) => m.as_str(),
|
||||
}
|
||||
}
|
||||
}
|
||||
15
crates/tessera-core/src/lib.rs
Normal file
15
crates/tessera-core/src/lib.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
pub mod config;
|
||||
pub mod decay;
|
||||
pub mod errors;
|
||||
pub mod manifest;
|
||||
pub mod orbit;
|
||||
pub mod reconstitute;
|
||||
pub mod wormhole;
|
||||
|
||||
pub use config::*;
|
||||
pub use decay::*;
|
||||
pub use errors::*;
|
||||
pub use manifest::*;
|
||||
pub use orbit::*;
|
||||
pub use reconstitute::*;
|
||||
pub use wormhole::*;
|
||||
41
crates/tessera-core/src/manifest.rs
Normal file
41
crates/tessera-core/src/manifest.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SnapshotManifest {
|
||||
pub snapshot_id: Uuid,
|
||||
pub orbit_id: Uuid,
|
||||
pub orbit_name: String,
|
||||
pub labels: Vec<String>,
|
||||
pub provider: String,
|
||||
pub paths: Vec<String>,
|
||||
pub restore_hints: serde_json::Value,
|
||||
}
|
||||
|
||||
pub fn manifest_hash(manifest: &SnapshotManifest) -> String {
|
||||
let json = serde_json::to_vec(manifest).expect("manifest serializes");
|
||||
let digest = Sha256::digest(&json);
|
||||
hex::encode(digest)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn hash_is_stable() {
|
||||
let m = SnapshotManifest {
|
||||
snapshot_id: Uuid::nil(),
|
||||
orbit_id: Uuid::nil(),
|
||||
orbit_name: "nightly".into(),
|
||||
labels: vec!["filesystem".into()],
|
||||
provider: "filesystem".into(),
|
||||
paths: vec!["/tmp".into()],
|
||||
restore_hints: serde_json::json!({}),
|
||||
};
|
||||
let h1 = manifest_hash(&m);
|
||||
let h2 = manifest_hash(&m);
|
||||
assert_eq!(h1, h2);
|
||||
assert_eq!(h1.len(), 64);
|
||||
}
|
||||
}
|
||||
21
crates/tessera-core/src/orbit.rs
Normal file
21
crates/tessera-core/src/orbit.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OrbitRunState {
|
||||
Idle,
|
||||
Preparing,
|
||||
Capturing,
|
||||
Sealing,
|
||||
ApplyingDecay,
|
||||
Completed,
|
||||
Failed,
|
||||
Rehearsed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OrbitRun {
|
||||
pub state: OrbitRunState,
|
||||
pub dry_run: bool,
|
||||
pub message: Option<String>,
|
||||
}
|
||||
33
crates/tessera-core/src/reconstitute.rs
Normal file
33
crates/tessera-core/src/reconstitute.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const RECONSTITUTE_GRACE_SECS: u64 = 12;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ReconstituteState {
|
||||
Idle,
|
||||
Confirming,
|
||||
Countdown,
|
||||
Restoring,
|
||||
Completed,
|
||||
Failed,
|
||||
Aborted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
||||
pub struct ReconstituteSession {
|
||||
pub snapshot_id: Uuid,
|
||||
pub target: String,
|
||||
pub state: ReconstituteState,
|
||||
pub seconds_remaining: u64,
|
||||
}
|
||||
|
||||
impl ReconstituteSession {
|
||||
pub fn countdown_copy(&self) -> String {
|
||||
format!(
|
||||
"Reconstituting in {}s — abort restores nothing.",
|
||||
self.seconds_remaining
|
||||
)
|
||||
}
|
||||
}
|
||||
26
crates/tessera-core/src/wormhole.rs
Normal file
26
crates/tessera-core/src/wormhole.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PairingState {
|
||||
Unpaired,
|
||||
CodeShown,
|
||||
Claimed,
|
||||
Active,
|
||||
Offline,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PairingCode {
|
||||
pub code: String,
|
||||
pub expires_at: chrono::DateTime<chrono::Utc>,
|
||||
pub hub_outpost_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WormholeCredentials {
|
||||
pub outpost_id: Uuid,
|
||||
pub upload_token: String,
|
||||
pub hub_url: String,
|
||||
}
|
||||
32
crates/tessera-hub/Cargo.toml
Normal file
32
crates/tessera-hub/Cargo.toml
Normal file
@@ -0,0 +1,32 @@
|
||||
[package]
|
||||
name = "tessera-hub"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "tessera-hub"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
tessera-core = { path = "../tessera-core" }
|
||||
tessera-store = { path = "../tessera-store" }
|
||||
tessera-providers = { path = "../tessera-providers" }
|
||||
anyhow.workspace = true
|
||||
axum.workspace = true
|
||||
chrono.workspace = true
|
||||
cron.workspace = true
|
||||
include_dir = "0.7"
|
||||
rand.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
rusqlite.workspace = true
|
||||
tokio.workspace = true
|
||||
tower-http.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
utoipa.workspace = true
|
||||
uuid.workspace = true
|
||||
hex.workspace = true
|
||||
base64 = "0.22"
|
||||
indexmap = "=2.2.6"
|
||||
5
crates/tessera-hub/src/api/mod.rs
Normal file
5
crates/tessera-hub/src/api/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
mod orbit;
|
||||
mod routes;
|
||||
|
||||
pub use orbit::run_orbit_internal;
|
||||
pub use routes::router;
|
||||
71
crates/tessera-hub/src/api/orbit.rs
Normal file
71
crates/tessera-hub/src/api/orbit.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use crate::db::OrbitRow;
|
||||
use crate::state::HubState;
|
||||
use anyhow::{Context, Result};
|
||||
use tessera_core::config::ProviderKind;
|
||||
use tessera_core::manifest::SnapshotManifest;
|
||||
use tessera_providers::provider_from_config;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<()> {
|
||||
let orbits = state.db.list_orbits().await?;
|
||||
let orbit = orbits
|
||||
.into_iter()
|
||||
.find(|o| o.id == orbit_id)
|
||||
.context("orbit not found")?;
|
||||
run_orbit_row(state, orbit).await
|
||||
}
|
||||
|
||||
pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> {
|
||||
state.db.set_orbit_status(orbit.id, "running").await?;
|
||||
|
||||
let provider_kind = match orbit.provider.as_str() {
|
||||
"filesystem" => ProviderKind::Filesystem,
|
||||
"postgres" => ProviderKind::Postgres,
|
||||
_ => ProviderKind::Command,
|
||||
};
|
||||
let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?;
|
||||
let provider = provider_from_config(&provider_kind, &config)?;
|
||||
let capture = provider.capture().await.context("capture")?;
|
||||
|
||||
let manifest = SnapshotManifest {
|
||||
snapshot_id: Uuid::new_v4(),
|
||||
orbit_id: orbit.id,
|
||||
orbit_name: orbit.name.clone(),
|
||||
labels: capture.labels,
|
||||
provider: orbit.provider.clone(),
|
||||
paths: vec![],
|
||||
restore_hints: capture.restore_hints,
|
||||
};
|
||||
|
||||
let mut vault = state.vault.write().await;
|
||||
let snap = vault
|
||||
.snapshot(manifest, &capture.payload, orbit.dry_run)
|
||||
.context("vault snapshot")?;
|
||||
|
||||
if !orbit.dry_run {
|
||||
let _pruned = vault.prune_with_decay(&orbit.decay_preset)?;
|
||||
state
|
||||
.db
|
||||
.audit("decay.pruned", &format!("orbit={}", orbit.name))
|
||||
.await?;
|
||||
}
|
||||
|
||||
let status = if orbit.dry_run {
|
||||
"rehearsed"
|
||||
} else {
|
||||
"completed"
|
||||
};
|
||||
state.db.set_orbit_status(orbit.id, status).await?;
|
||||
state
|
||||
.db
|
||||
.audit(
|
||||
if orbit.dry_run {
|
||||
"orbit.rehearsed"
|
||||
} else {
|
||||
"orbit.completed"
|
||||
},
|
||||
&format!("snapshot={}", snap.id),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
440
crates/tessera-hub/src/api/routes.rs
Normal file
440
crates/tessera-hub/src/api/routes.rs
Normal file
@@ -0,0 +1,440 @@
|
||||
use crate::db::OrbitRow;
|
||||
use crate::state::{HubState, PairingEntry};
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::{header, StatusCode, Uri},
|
||||
response::IntoResponse,
|
||||
routing::{delete, get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use base64::Engine;
|
||||
use include_dir::{include_dir, Dir};
|
||||
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS};
|
||||
use tessera_core::wormhole::PairingState;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use utoipa::OpenApi;
|
||||
use uuid::Uuid;
|
||||
|
||||
static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
|
||||
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(
|
||||
paths(
|
||||
health,
|
||||
list_snapshots,
|
||||
list_orbits,
|
||||
create_orbit,
|
||||
trigger_orbit,
|
||||
start_reconstitute,
|
||||
pairing_start,
|
||||
pairing_claim,
|
||||
wormhole_upload_init,
|
||||
wormhole_upload_chunk,
|
||||
),
|
||||
components(schemas(
|
||||
SnapshotSummary,
|
||||
OrbitRow,
|
||||
CreateOrbitRequest,
|
||||
ReconstituteRequest,
|
||||
ReconstituteSession,
|
||||
PairingResponse,
|
||||
ClaimRequest,
|
||||
ClaimResponse,
|
||||
UploadInit,
|
||||
UploadChunk,
|
||||
))
|
||||
)]
|
||||
struct ApiDoc;
|
||||
|
||||
#[derive(serde::Serialize, utoipa::ToSchema)]
|
||||
struct SnapshotSummary {
|
||||
id: Uuid,
|
||||
taken_at: chrono::DateTime<chrono::Utc>,
|
||||
orbit_name: String,
|
||||
size_bytes: u64,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct CreateOrbitRequest {
|
||||
name: String,
|
||||
provider: String,
|
||||
provider_config: serde_json::Value,
|
||||
schedule: Option<String>,
|
||||
decay_preset: Option<String>,
|
||||
dry_run: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct ReconstituteRequest {
|
||||
snapshot_id: Uuid,
|
||||
target_path: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, utoipa::ToSchema)]
|
||||
struct PairingResponse {
|
||||
code: String,
|
||||
expires_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct ClaimRequest {
|
||||
code: String,
|
||||
outpost_name: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, utoipa::ToSchema)]
|
||||
struct ClaimResponse {
|
||||
outpost_id: Uuid,
|
||||
upload_token: String,
|
||||
hub_url: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct UploadInit {
|
||||
orbit_id: Uuid,
|
||||
total_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct UploadChunk {
|
||||
session_id: Uuid,
|
||||
offset: u64,
|
||||
data_b64: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, utoipa::ToSchema)]
|
||||
struct ReconstituteStartResponse {
|
||||
session_id: Uuid,
|
||||
session: ReconstituteSession,
|
||||
}
|
||||
|
||||
pub fn router(state: HubState) -> Router {
|
||||
let api = Router::new()
|
||||
.route("/health", get(health))
|
||||
.route("/api/v1/snapshots", get(list_snapshots))
|
||||
.route("/api/v1/orbits", get(list_orbits).post(create_orbit))
|
||||
.route("/api/v1/orbits/:id/run", post(trigger_orbit))
|
||||
.route("/api/v1/reconstitute", post(start_reconstitute))
|
||||
.route(
|
||||
"/api/v1/reconstitute/:id",
|
||||
get(reconstitute_status).delete(abort_reconstitute),
|
||||
)
|
||||
.route("/api/v1/wormhole/pairing", post(pairing_start))
|
||||
.route("/api/v1/wormhole/claim", post(pairing_claim))
|
||||
.route("/api/v1/wormhole/upload/init", post(wormhole_upload_init))
|
||||
.route("/api/v1/wormhole/upload/chunk", post(wormhole_upload_chunk))
|
||||
.with_state(state);
|
||||
|
||||
let api = api.route(
|
||||
"/api-doc/openapi.json",
|
||||
get(|| async { Json(ApiDoc::openapi()) }),
|
||||
);
|
||||
|
||||
api.fallback(spa_fallback)
|
||||
.layer(TraceLayer::new_for_http())
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))]
|
||||
async fn health() -> &'static str {
|
||||
"vault online"
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/snapshots", responses((status = 200, body = [SnapshotSummary])))]
|
||||
async fn list_snapshots(State(state): State<HubState>) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
|
||||
let vault = state.vault.read().await;
|
||||
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let out = snaps
|
||||
.into_iter()
|
||||
.map(|s| SnapshotSummary {
|
||||
id: s.id,
|
||||
taken_at: s.taken_at,
|
||||
orbit_name: s.manifest.orbit_name,
|
||||
size_bytes: s.size_bytes,
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(out))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitRow])))]
|
||||
async fn list_orbits(State(state): State<HubState>) -> Result<Json<Vec<OrbitRow>>, StatusCode> {
|
||||
state
|
||||
.db
|
||||
.list_orbits()
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitRow)))]
|
||||
async fn create_orbit(
|
||||
State(state): State<HubState>,
|
||||
Json(req): Json<CreateOrbitRequest>,
|
||||
) -> Result<Json<OrbitRow>, StatusCode> {
|
||||
let row = OrbitRow {
|
||||
id: Uuid::new_v4(),
|
||||
name: req.name,
|
||||
provider: req.provider,
|
||||
provider_config: serde_json::to_string(&req.provider_config).unwrap_or_else(|_| "{}".into()),
|
||||
schedule: req.schedule,
|
||||
decay_preset: req
|
||||
.decay_preset
|
||||
.unwrap_or_else(|| "week-of-dailies".into()),
|
||||
dry_run: req.dry_run.unwrap_or(false),
|
||||
last_status: "idle".into(),
|
||||
};
|
||||
state.db.upsert_orbit(&row).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(row))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204)))]
|
||||
async fn trigger_orbit(
|
||||
State(state): State<HubState>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
crate::api::run_orbit_internal(state, id)
|
||||
.await
|
||||
.map(|_| StatusCode::NO_CONTENT)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/reconstitute", request_body = ReconstituteRequest, responses((status = 200, body = ReconstituteStartResponse)))]
|
||||
async fn start_reconstitute(
|
||||
State(state): State<HubState>,
|
||||
Json(req): Json<ReconstituteRequest>,
|
||||
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
|
||||
let session_id = Uuid::new_v4();
|
||||
let session = ReconstituteSession {
|
||||
snapshot_id: req.snapshot_id,
|
||||
target: req.target_path.clone(),
|
||||
state: ReconstituteState::Countdown,
|
||||
seconds_remaining: RECONSTITUTE_GRACE_SECS,
|
||||
};
|
||||
state
|
||||
.reconstitute_sessions
|
||||
.write()
|
||||
.await
|
||||
.insert(session_id, session.clone());
|
||||
|
||||
let state_bg = state.clone();
|
||||
let target = req.target_path;
|
||||
tokio::spawn(async move {
|
||||
for remaining in (0..RECONSTITUTE_GRACE_SECS).rev() {
|
||||
{
|
||||
let mut map = state_bg.reconstitute_sessions.write().await;
|
||||
if let Some(s) = map.get_mut(&session_id) {
|
||||
if s.state == ReconstituteState::Aborted {
|
||||
return;
|
||||
}
|
||||
s.seconds_remaining = remaining;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
}
|
||||
let aborted = {
|
||||
let map = state_bg.reconstitute_sessions.read().await;
|
||||
map.get(&session_id)
|
||||
.map(|s| s.state == ReconstituteState::Aborted)
|
||||
.unwrap_or(true)
|
||||
};
|
||||
if aborted {
|
||||
return;
|
||||
}
|
||||
{
|
||||
let mut map = state_bg.reconstitute_sessions.write().await;
|
||||
if let Some(s) = map.get_mut(&session_id) {
|
||||
s.state = ReconstituteState::Restoring;
|
||||
s.seconds_remaining = 0;
|
||||
}
|
||||
}
|
||||
let dest = std::path::PathBuf::from(&target);
|
||||
let result = {
|
||||
let vault = state_bg.vault.read().await;
|
||||
vault.restore_snapshot(req.snapshot_id, &dest)
|
||||
};
|
||||
let mut map = state_bg.reconstitute_sessions.write().await;
|
||||
if let Some(s) = map.get_mut(&session_id) {
|
||||
s.state = if result.is_ok() {
|
||||
ReconstituteState::Completed
|
||||
} else {
|
||||
ReconstituteState::Failed
|
||||
};
|
||||
}
|
||||
let _ = state_bg.db.audit("reconstitute.done", &format!("session={session_id}")).await;
|
||||
});
|
||||
|
||||
Ok(Json(ReconstituteStartResponse {
|
||||
session_id,
|
||||
session,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn reconstitute_status(
|
||||
State(state): State<HubState>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<ReconstituteSession>, StatusCode> {
|
||||
let map = state.reconstitute_sessions.read().await;
|
||||
map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
async fn abort_reconstitute(
|
||||
State(state): State<HubState>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let mut map = state.reconstitute_sessions.write().await;
|
||||
if let Some(s) = map.get_mut(&id) {
|
||||
if matches!(
|
||||
s.state,
|
||||
ReconstituteState::Countdown | ReconstituteState::Confirming
|
||||
) {
|
||||
s.state = ReconstituteState::Aborted;
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
}
|
||||
Err(StatusCode::BAD_REQUEST)
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))]
|
||||
async fn pairing_start(State(state): State<HubState>) -> Json<PairingResponse> {
|
||||
let code: String = (0..6)
|
||||
.map(|_| {
|
||||
let n = rand::random::<u8>() % 36;
|
||||
if n < 10 {
|
||||
(b'0' + n) as char
|
||||
} else {
|
||||
(b'A' + n - 10) as char
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let expires = chrono::Utc::now() + chrono::Duration::minutes(10);
|
||||
let outpost_id = Uuid::new_v4();
|
||||
let upload_token = hex::encode(Uuid::new_v4().as_bytes());
|
||||
state.pairing_codes.write().await.push(PairingEntry {
|
||||
code: code.clone(),
|
||||
expires_at: expires,
|
||||
state: PairingState::CodeShown,
|
||||
outpost_id,
|
||||
upload_token: upload_token.clone(),
|
||||
});
|
||||
Json(PairingResponse { code, expires_at: expires })
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))]
|
||||
async fn pairing_claim(
|
||||
State(state): State<HubState>,
|
||||
Json(req): Json<ClaimRequest>,
|
||||
) -> Result<Json<ClaimResponse>, StatusCode> {
|
||||
let mut codes = state.pairing_codes.write().await;
|
||||
let now = chrono::Utc::now();
|
||||
let entry = codes
|
||||
.iter_mut()
|
||||
.find(|c| c.code == req.code && c.expires_at > now)
|
||||
.ok_or(StatusCode::GONE)?;
|
||||
entry.state = PairingState::Active;
|
||||
let hub_url =
|
||||
std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| "http://127.0.0.1:8787".into());
|
||||
state
|
||||
.db
|
||||
.audit("wormhole.paired", &req.outpost_name)
|
||||
.await
|
||||
.ok();
|
||||
Ok(Json(ClaimResponse {
|
||||
outpost_id: entry.outpost_id,
|
||||
upload_token: entry.upload_token.clone(),
|
||||
hub_url,
|
||||
}))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/upload/init", request_body = UploadInit, responses((status = 200)))]
|
||||
async fn wormhole_upload_init(
|
||||
State(state): State<HubState>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadInit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
verify_upload_token(&state, &headers).await?;
|
||||
let session_id = Uuid::new_v4();
|
||||
state
|
||||
.db
|
||||
.insert_upload_session(
|
||||
&session_id.to_string(),
|
||||
&body.orbit_id.to_string(),
|
||||
body.total_bytes.map(|t| t as i64),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(serde_json::json!({ "session_id": session_id })))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/upload/chunk", request_body = UploadChunk, responses((status = 204)))]
|
||||
async fn wormhole_upload_chunk(
|
||||
State(state): State<HubState>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadChunk>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
verify_upload_token(&state, &headers).await?;
|
||||
let data = base64::engine::general_purpose::STANDARD
|
||||
.decode(&body.data_b64)
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let tmp = state.data_dir.join("wormhole").join(format!("{}.part", body.session_id));
|
||||
if let Some(parent) = tmp.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
}
|
||||
use std::io::Write;
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&tmp)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
file.write_all(&data).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn verify_upload_token(
|
||||
state: &HubState,
|
||||
headers: &axum::http::HeaderMap,
|
||||
) -> Result<(), StatusCode> {
|
||||
let token = headers
|
||||
.get("x-tessera-upload-token")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
if state.upload_token_valid(token).await {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
|
||||
async fn spa_fallback(uri: Uri) -> impl IntoResponse {
|
||||
let mut path = uri.path().trim_start_matches('/').to_string();
|
||||
if path.is_empty() {
|
||||
path = "index.html".into();
|
||||
}
|
||||
if let Some(file) = WEB_DIST.get_file(&path) {
|
||||
let ct = content_type(&path);
|
||||
return (
|
||||
StatusCode::OK,
|
||||
[(header::CONTENT_TYPE, ct)],
|
||||
file.contents(),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
if let Some(index) = WEB_DIST.get_file("index.html") {
|
||||
return (
|
||||
StatusCode::OK,
|
||||
[(header::CONTENT_TYPE, "text/html")],
|
||||
index.contents(),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
(StatusCode::NOT_FOUND, "not found").into_response()
|
||||
}
|
||||
|
||||
fn content_type(path: &str) -> &'static str {
|
||||
if path.ends_with(".js") {
|
||||
"application/javascript"
|
||||
} else if path.ends_with(".css") {
|
||||
"text/css"
|
||||
} else if path.ends_with(".svg") {
|
||||
"image/svg+xml"
|
||||
} else {
|
||||
"text/html"
|
||||
}
|
||||
}
|
||||
145
crates/tessera-hub/src/db.rs
Normal file
145
crates/tessera-hub/src/db.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
use anyhow::Result;
|
||||
use rusqlite::{params, Connection};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Db {
|
||||
conn: Arc<Mutex<Connection>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
|
||||
pub struct OrbitRow {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub provider: String,
|
||||
pub provider_config: String,
|
||||
pub schedule: Option<String>,
|
||||
pub decay_preset: String,
|
||||
pub dry_run: bool,
|
||||
pub last_status: String,
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub async fn connect(path: &Path) -> Result<Self> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let conn = Connection::open(path)?;
|
||||
Ok(Self {
|
||||
conn: Arc::new(Mutex::new(conn)),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn migrate(&self) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute_batch(
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS orbits (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
provider TEXT NOT NULL,
|
||||
provider_config TEXT NOT NULL,
|
||||
schedule TEXT,
|
||||
decay_preset TEXT NOT NULL DEFAULT 'week-of-dailies',
|
||||
dry_run INTEGER NOT NULL DEFAULT 0,
|
||||
last_status TEXT NOT NULL DEFAULT 'idle'
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS outposts (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT,
|
||||
last_seen TEXT,
|
||||
pairing_state TEXT NOT NULL DEFAULT 'unpaired'
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at TEXT NOT NULL,
|
||||
event TEXT NOT NULL,
|
||||
detail TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS upload_sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
outpost_id TEXT,
|
||||
orbit_id TEXT,
|
||||
offset INTEGER NOT NULL DEFAULT 0,
|
||||
total INTEGER,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
"#,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn list_orbits(&self) -> Result<Vec<OrbitRow>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status FROM orbits ORDER BY name")?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
Ok(OrbitRow {
|
||||
id: Uuid::parse_str(&r.get::<_, String>(0)?).unwrap_or_else(|_| Uuid::new_v4()),
|
||||
name: r.get(1)?,
|
||||
provider: r.get(2)?,
|
||||
provider_config: r.get(3)?,
|
||||
schedule: r.get(4)?,
|
||||
decay_preset: r.get(5)?,
|
||||
dry_run: r.get::<_, i64>(6)? != 0,
|
||||
last_status: r.get(7)?,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}
|
||||
|
||||
pub async fn upsert_orbit(&self, row: &OrbitRow) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
r#"INSERT INTO orbits (id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
name=excluded.name, provider=excluded.provider, provider_config=excluded.provider_config,
|
||||
schedule=excluded.schedule, decay_preset=excluded.decay_preset, dry_run=excluded.dry_run"#,
|
||||
params![
|
||||
row.id.to_string(),
|
||||
row.name,
|
||||
row.provider,
|
||||
row.provider_config,
|
||||
row.schedule,
|
||||
row.decay_preset,
|
||||
row.dry_run as i64,
|
||||
row.last_status,
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_orbit_status(&self, id: Uuid, status: &str) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"UPDATE orbits SET last_status = ?1 WHERE id = ?2",
|
||||
params![status, id.to_string()],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn audit(&self, event: &str, detail: &str) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), ?1, ?2)",
|
||||
params![event, detail],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn insert_upload_session(
|
||||
&self,
|
||||
id: &str,
|
||||
orbit_id: &str,
|
||||
total: Option<i64>,
|
||||
) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO upload_sessions (id, orbit_id, offset, total, created_at) VALUES (?1, ?2, 0, ?3, datetime('now'))",
|
||||
params![id, orbit_id, total],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
30
crates/tessera-hub/src/main.rs
Normal file
30
crates/tessera-hub/src/main.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
mod api;
|
||||
mod db;
|
||||
mod scheduler;
|
||||
mod state;
|
||||
|
||||
use anyhow::Result;
|
||||
use state::HubState;
|
||||
use std::net::SocketAddr;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env().add_directive("tessera_hub=info".parse()?))
|
||||
.init();
|
||||
|
||||
let data_dir = std::env::var("TESSERA_DATA_DIR").unwrap_or_else(|_| "./data".into());
|
||||
let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "0.0.0.0:8787".into());
|
||||
let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE").unwrap_or_else(|_| "dev-vault-key".into());
|
||||
|
||||
let state = HubState::bootstrap(&data_dir, &vault_pass).await?;
|
||||
scheduler::start_orbit_scheduler(state.clone()).await?;
|
||||
|
||||
let app = api::router(state);
|
||||
let addr: SocketAddr = listen.parse()?;
|
||||
tracing::info!("Tessera hub listening on {addr}");
|
||||
let listener = tokio::net::TcpListener::bind(addr).await?;
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
46
crates/tessera-hub/src/scheduler.rs
Normal file
46
crates/tessera-hub/src/scheduler.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use crate::state::HubState;
|
||||
use anyhow::Result;
|
||||
use cron::Schedule;
|
||||
use std::str::FromStr;
|
||||
use tokio::time::{sleep, Duration};
|
||||
use tracing::{error, info};
|
||||
|
||||
pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
if let Err(e) = tick_schedules(state.clone()).await {
|
||||
error!("scheduler tick: {e}");
|
||||
}
|
||||
sleep(Duration::from_secs(30)).await;
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tick_schedules(state: HubState) -> Result<()> {
|
||||
let orbits = state.db.list_orbits().await?;
|
||||
let now = chrono::Utc::now();
|
||||
for orbit in orbits {
|
||||
let Some(cron_expr) = orbit.schedule.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
let schedule = match Schedule::from_str(cron_expr) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
error!("bad cron on orbit {}: {e}", orbit.name);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let upcoming = schedule.upcoming(chrono::Utc).take(1).collect::<Vec<_>>();
|
||||
if let Some(next) = upcoming.first() {
|
||||
let delta = (*next - now).num_seconds().abs();
|
||||
if delta < 35 {
|
||||
info!("scheduler firing orbit {}", orbit.name);
|
||||
if let Err(e) = crate::api::run_orbit_internal(state.clone(), orbit.id).await {
|
||||
error!("orbit {} failed: {e}", orbit.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
60
crates/tessera-hub/src/state.rs
Normal file
60
crates/tessera-hub/src/state.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use crate::db::Db;
|
||||
use anyhow::Result;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tessera_core::reconstitute::ReconstituteSession;
|
||||
use tessera_core::wormhole::PairingState;
|
||||
use tessera_store::Vault;
|
||||
use tokio::sync::RwLock;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HubState {
|
||||
pub db: Db,
|
||||
pub data_dir: PathBuf,
|
||||
pub vault_passphrase: String,
|
||||
pub vault: Arc<RwLock<Vault>>,
|
||||
pub pairing_codes: Arc<RwLock<Vec<PairingEntry>>>,
|
||||
pub reconstitute_sessions: Arc<RwLock<HashMap<Uuid, ReconstituteSession>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PairingEntry {
|
||||
pub code: String,
|
||||
pub expires_at: chrono::DateTime<chrono::Utc>,
|
||||
pub state: PairingState,
|
||||
pub outpost_id: Uuid,
|
||||
pub upload_token: String,
|
||||
}
|
||||
|
||||
impl HubState {
|
||||
pub async fn bootstrap(data_dir: &str, vault_pass: &str) -> Result<Self> {
|
||||
let data_dir = PathBuf::from(data_dir);
|
||||
std::fs::create_dir_all(&data_dir)?;
|
||||
let db_path = data_dir.join("tessera.db");
|
||||
let db = Db::connect(&db_path).await?;
|
||||
db.migrate().await?;
|
||||
|
||||
let vault_path = data_dir.join("vault");
|
||||
let vault = if vault_path.join("config").exists() {
|
||||
Vault::open(&vault_path, vault_pass)?
|
||||
} else {
|
||||
Vault::init(&vault_path, vault_pass)?
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
db,
|
||||
data_dir,
|
||||
vault_passphrase: vault_pass.to_string(),
|
||||
vault: Arc::new(RwLock::new(vault)),
|
||||
pairing_codes: Arc::new(RwLock::new(Vec::new())),
|
||||
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn upload_token_valid(&self, token: &str) -> bool {
|
||||
let codes = self.pairing_codes.read().await;
|
||||
codes.iter().any(|c| c.upload_token == token && c.state == PairingState::Active)
|
||||
}
|
||||
}
|
||||
15
crates/tessera-providers/Cargo.toml
Normal file
15
crates/tessera-providers/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "tessera-providers"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tessera-core = { path = "../tessera-core" }
|
||||
anyhow.workspace = true
|
||||
async-trait.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio = { workspace = true, features = ["process", "fs"] }
|
||||
tracing.workspace = true
|
||||
walkdir.workspace = true
|
||||
83
crates/tessera-providers/src/filesystem.rs
Normal file
83
crates/tessera-providers/src/filesystem.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use super::{BackupProvider, CaptureResult};
|
||||
use anyhow::{Context, Result};
|
||||
use async_trait::async_trait;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
use tessera_core::config::ProviderKind;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct FilesystemConfig {
|
||||
pub paths: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub max_file_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
pub struct FilesystemProvider {
|
||||
config: FilesystemConfig,
|
||||
}
|
||||
|
||||
impl FilesystemProvider {
|
||||
pub fn from_config(config: &serde_json::Value) -> Result<Self> {
|
||||
let config: FilesystemConfig = serde_json::from_value(config.clone())?;
|
||||
Ok(Self { config })
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackupProvider for FilesystemProvider {
|
||||
fn kind(&self) -> ProviderKind {
|
||||
ProviderKind::Filesystem
|
||||
}
|
||||
|
||||
async fn capture(&self) -> Result<CaptureResult> {
|
||||
let mut archive = Vec::new();
|
||||
let mut paths_meta = Vec::new();
|
||||
|
||||
for path_str in &self.config.paths {
|
||||
let root = PathBuf::from(path_str);
|
||||
if !root.exists() {
|
||||
anyhow::bail!("path not found: {path_str}");
|
||||
}
|
||||
if root.is_file() {
|
||||
let data = tokio::fs::read(&root).await.context("read file")?;
|
||||
if let Some(max) = self.config.max_file_bytes {
|
||||
if data.len() as u64 > max {
|
||||
anyhow::bail!("file exceeds max_file_bytes");
|
||||
}
|
||||
}
|
||||
archive.extend_from_slice(path_str.as_bytes());
|
||||
archive.push(0);
|
||||
archive.extend(&(data.len() as u64).to_le_bytes());
|
||||
archive.extend(&data);
|
||||
paths_meta.push(path_str.clone());
|
||||
} else {
|
||||
for entry in WalkDir::new(&root).into_iter().filter_map(|e| e.ok()) {
|
||||
if entry.file_type().is_file() {
|
||||
let p = entry.path();
|
||||
let rel = p.strip_prefix(&root).unwrap_or(p);
|
||||
let data = tokio::fs::read(p).await.context("read file")?;
|
||||
if let Some(max) = self.config.max_file_bytes {
|
||||
if data.len() as u64 > max {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let key = format!("{}/{}", path_str, rel.display());
|
||||
archive.extend_from_slice(key.as_bytes());
|
||||
archive.push(0);
|
||||
archive.extend(&(data.len() as u64).to_le_bytes());
|
||||
archive.extend(&data);
|
||||
paths_meta.push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(CaptureResult {
|
||||
payload: archive,
|
||||
labels: vec!["filesystem".into()],
|
||||
restore_hints: json!({ "paths": paths_meta, "format": "tessera-fs-v1" }),
|
||||
})
|
||||
}
|
||||
}
|
||||
31
crates/tessera-providers/src/lib.rs
Normal file
31
crates/tessera-providers/src/lib.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
mod filesystem;
|
||||
mod postgres;
|
||||
|
||||
pub use filesystem::*;
|
||||
pub use postgres::*;
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use serde_json::Value;
|
||||
use tessera_core::config::ProviderKind;
|
||||
|
||||
#[async_trait]
|
||||
pub trait BackupProvider: Send + Sync {
|
||||
fn kind(&self) -> ProviderKind;
|
||||
async fn capture(&self) -> Result<CaptureResult>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CaptureResult {
|
||||
pub payload: Vec<u8>,
|
||||
pub labels: Vec<String>,
|
||||
pub restore_hints: Value,
|
||||
}
|
||||
|
||||
pub fn provider_from_config(kind: &ProviderKind, config: &Value) -> Result<Box<dyn BackupProvider>> {
|
||||
match kind {
|
||||
ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)),
|
||||
ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)),
|
||||
ProviderKind::Command => anyhow::bail!("command provider not implemented in v1"),
|
||||
}
|
||||
}
|
||||
63
crates/tessera-providers/src/postgres.rs
Normal file
63
crates/tessera-providers/src/postgres.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use super::{BackupProvider, CaptureResult};
|
||||
use anyhow::{Context, Result};
|
||||
use async_trait::async_trait;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::process::Stdio;
|
||||
use tessera_core::config::ProviderKind;
|
||||
use tokio::process::Command;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct PostgresConfig {
|
||||
pub connection_url: String,
|
||||
#[serde(default = "default_format")]
|
||||
pub format: String,
|
||||
}
|
||||
|
||||
fn default_format() -> String {
|
||||
"custom".into()
|
||||
}
|
||||
|
||||
pub struct PostgresProvider {
|
||||
config: PostgresConfig,
|
||||
}
|
||||
|
||||
impl PostgresProvider {
|
||||
pub fn from_config(config: &serde_json::Value) -> Result<Self> {
|
||||
let config: PostgresConfig = serde_json::from_value(config.clone())?;
|
||||
Ok(Self { config })
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackupProvider for PostgresProvider {
|
||||
fn kind(&self) -> ProviderKind {
|
||||
ProviderKind::Postgres
|
||||
}
|
||||
|
||||
async fn capture(&self) -> Result<CaptureResult> {
|
||||
let mut cmd = Command::new("pg_dump");
|
||||
cmd.arg(&self.config.connection_url);
|
||||
match self.config.format.as_str() {
|
||||
"custom" => {
|
||||
cmd.arg("-Fc");
|
||||
}
|
||||
"plain" => {}
|
||||
other => anyhow::bail!("unknown pg format: {other}"),
|
||||
}
|
||||
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let output = cmd.output().await.context("pg_dump failed to start")?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
anyhow::bail!("pg_dump failed: {stderr}");
|
||||
}
|
||||
Ok(CaptureResult {
|
||||
payload: output.stdout,
|
||||
labels: vec!["postgres".into()],
|
||||
restore_hints: json!({
|
||||
"format": self.config.format,
|
||||
"restore_command_hint": "pg_restore -d $DATABASE_URL dump.file"
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
24
crates/tessera-store/Cargo.toml
Normal file
24
crates/tessera-store/Cargo.toml
Normal file
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "tessera-store"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tessera-core = { path = "../tessera-core" }
|
||||
anyhow.workspace = true
|
||||
aes-gcm.workspace = true
|
||||
pbkdf2.workspace = true
|
||||
hmac.workspace = true
|
||||
sha2.workspace = true
|
||||
chrono.workspace = true
|
||||
rand.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
hex.workspace = true
|
||||
tempfile.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio = { workspace = true, features = ["fs", "io-util"] }
|
||||
tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
walkdir.workspace = true
|
||||
90
crates/tessera-store/src/crypto.rs
Normal file
90
crates/tessera-store/src/crypto.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
use aes_gcm::aead::generic_array::GenericArray;
|
||||
use aes_gcm::aead::{Aead, NewAead};
|
||||
use aes_gcm::Aes256Gcm;
|
||||
use anyhow::{anyhow, Result};
|
||||
use hmac::Hmac;
|
||||
use pbkdf2::pbkdf2;
|
||||
use rand::RngCore;
|
||||
use sha2::Sha256;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
const NONCE_LEN: usize = 12;
|
||||
const SALT_LEN: usize = 16;
|
||||
|
||||
pub struct VaultKey {
|
||||
cipher: Aes256Gcm,
|
||||
}
|
||||
|
||||
impl VaultKey {
|
||||
pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result<Self> {
|
||||
let salt = if salt_path.exists() {
|
||||
fs::read(salt_path)?
|
||||
} else {
|
||||
let mut salt = [0u8; SALT_LEN];
|
||||
rand::thread_rng().fill_bytes(&mut salt);
|
||||
if let Some(parent) = salt_path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(salt_path, &salt)?;
|
||||
salt.to_vec()
|
||||
};
|
||||
|
||||
let mut key = [0u8; 32];
|
||||
pbkdf2::<Hmac<Sha256>>(passphrase.as_bytes(), &salt, 100_000, &mut key);
|
||||
|
||||
let cipher =
|
||||
Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?;
|
||||
Ok(Self { cipher })
|
||||
}
|
||||
|
||||
pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut nonce_bytes = [0u8; NONCE_LEN];
|
||||
rand::thread_rng().fill_bytes(&mut nonce_bytes);
|
||||
let nonce = GenericArray::from_slice(&nonce_bytes);
|
||||
let ciphertext = self
|
||||
.cipher
|
||||
.encrypt(nonce, plaintext)
|
||||
.map_err(|e| anyhow!("encrypt: {e}"))?;
|
||||
let mut out = nonce_bytes.to_vec();
|
||||
out.extend(ciphertext);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn decrypt(&self, blob: &[u8]) -> Result<Vec<u8>> {
|
||||
if blob.len() < NONCE_LEN {
|
||||
anyhow::bail!("blob too short");
|
||||
}
|
||||
let (nonce_bytes, ct) = blob.split_at(NONCE_LEN);
|
||||
let nonce = GenericArray::from_slice(nonce_bytes);
|
||||
self.cipher
|
||||
.decrypt(nonce, ct)
|
||||
.map_err(|e| anyhow!("decrypt: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn content_id(data: &[u8]) -> String {
|
||||
use sha2::Digest;
|
||||
hex::encode(Sha256::digest(data))
|
||||
}
|
||||
|
||||
pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf {
|
||||
let prefix = &id[..2.min(id.len())];
|
||||
data_dir.join(prefix).join(id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn roundtrip_crypto() {
|
||||
let dir = tempdir().unwrap();
|
||||
let salt = dir.path().join("salt");
|
||||
let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
|
||||
let enc = key.encrypt(b"stardust").unwrap();
|
||||
let plain = key.decrypt(&enc).unwrap();
|
||||
assert_eq!(plain, b"stardust");
|
||||
}
|
||||
}
|
||||
27
crates/tessera-store/src/index.rs
Normal file
27
crates/tessera-store/src/index.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct ChunkIndex {
|
||||
pub chunks: HashMap<String, ChunkEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ChunkEntry {
|
||||
pub pack_id: String,
|
||||
pub offset: u64,
|
||||
pub length: u64,
|
||||
}
|
||||
|
||||
impl ChunkIndex {
|
||||
pub fn record(&mut self, chunk_id: String, pack_id: String, offset: u64, length: u64) {
|
||||
self.chunks.insert(
|
||||
chunk_id,
|
||||
ChunkEntry {
|
||||
pack_id,
|
||||
offset,
|
||||
length,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
17
crates/tessera-store/src/lib.rs
Normal file
17
crates/tessera-store/src/lib.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
//! Restic-compatible path layout vault engine.
|
||||
//!
|
||||
//! Layout under vault root:
|
||||
//! - `config` — repository version marker (restic-compatible sentinel)
|
||||
//! - `data/` — content-addressed encrypted packs (`{prefix}/{id}`)
|
||||
//! - `snapshots/` — JSON snapshot metadata
|
||||
//! - `index/` — chunk index shards
|
||||
//! - `keys/` — key material (local key file)
|
||||
//!
|
||||
//! Full `rustic_core` integration is deferred until toolchain meets its MSRV;
|
||||
//! emergency verify may use external `rustic`/`restic` where formats align.
|
||||
|
||||
mod crypto;
|
||||
mod index;
|
||||
mod vault;
|
||||
|
||||
pub use vault::*;
|
||||
260
crates/tessera-store/src/vault.rs
Normal file
260
crates/tessera-store/src/vault.rs
Normal file
@@ -0,0 +1,260 @@
|
||||
use crate::crypto::{content_id, pack_path, VaultKey};
|
||||
use crate::index::ChunkIndex;
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tessera_core::decay::{evaluate_decay, DecayPolicy, SnapshotRef};
|
||||
use tessera_core::manifest::SnapshotManifest;
|
||||
use uuid::Uuid;
|
||||
|
||||
const RESTIC_CONFIG: &str = "{\n \"version\": 2,\n \"id\": \"tessera-restic-layout-v1\",\n \"tessera\": true\n}\n";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StoredSnapshot {
|
||||
pub id: Uuid,
|
||||
pub taken_at: DateTime<Utc>,
|
||||
pub manifest: SnapshotManifest,
|
||||
pub size_bytes: u64,
|
||||
pub tree_root: String,
|
||||
}
|
||||
|
||||
pub struct Vault {
|
||||
root: PathBuf,
|
||||
key: VaultKey,
|
||||
index: ChunkIndex,
|
||||
}
|
||||
|
||||
impl Vault {
|
||||
pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
|
||||
let root = root.as_ref().to_path_buf();
|
||||
fs::create_dir_all(root.join("data"))?;
|
||||
fs::create_dir_all(root.join("snapshots"))?;
|
||||
fs::create_dir_all(root.join("index"))?;
|
||||
fs::create_dir_all(root.join("keys"))?;
|
||||
|
||||
let config_path = root.join("config");
|
||||
if !config_path.exists() {
|
||||
fs::write(&config_path, RESTIC_CONFIG)?;
|
||||
}
|
||||
|
||||
let salt = root.join("keys/tessera.salt");
|
||||
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
|
||||
let index = ChunkIndex::default();
|
||||
let v = Self {
|
||||
root,
|
||||
key,
|
||||
index,
|
||||
};
|
||||
v.save_index()?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
pub fn open(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
|
||||
let root = root.as_ref().to_path_buf();
|
||||
if !root.join("config").exists() {
|
||||
anyhow::bail!("vault not initialized");
|
||||
}
|
||||
let salt = root.join("keys/tessera.salt");
|
||||
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
|
||||
let index = Self::load_index(&root)?;
|
||||
Ok(Self {
|
||||
root,
|
||||
key,
|
||||
index,
|
||||
})
|
||||
}
|
||||
|
||||
fn index_path(&self) -> PathBuf {
|
||||
self.root.join("index/tessera-main.json")
|
||||
}
|
||||
|
||||
fn load_index(root: &Path) -> Result<ChunkIndex> {
|
||||
let p = root.join("index/tessera-main.json");
|
||||
if !p.exists() {
|
||||
return Ok(ChunkIndex::default());
|
||||
}
|
||||
let data = fs::read_to_string(&p)?;
|
||||
Ok(serde_json::from_str(&data)?)
|
||||
}
|
||||
|
||||
fn save_index(&self) -> Result<()> {
|
||||
let data = serde_json::to_string_pretty(&self.index)?;
|
||||
fs::write(self.index_path(), data)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store_chunk(&mut self, plain: &[u8]) -> Result<String> {
|
||||
let id = content_id(plain);
|
||||
if self.index.chunks.contains_key(&id) {
|
||||
return Ok(id);
|
||||
}
|
||||
let enc = self.key.encrypt(plain)?;
|
||||
let pack_id = content_id(&enc);
|
||||
let path = pack_path(&self.root.join("data"), &pack_id);
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(&path, &enc)?;
|
||||
self.index.record(id.clone(), pack_id, 0, enc.len() as u64);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn read_chunk(&self, id: &str) -> Result<Vec<u8>> {
|
||||
let entry = self
|
||||
.index
|
||||
.chunks
|
||||
.get(id)
|
||||
.ok_or_else(|| anyhow!("unknown chunk {id}"))?;
|
||||
let path = pack_path(&self.root.join("data"), &entry.pack_id);
|
||||
let enc = fs::read(&path)?;
|
||||
self.key.decrypt(&enc)
|
||||
}
|
||||
|
||||
pub fn snapshot(
|
||||
&mut self,
|
||||
manifest: SnapshotManifest,
|
||||
payload: &[u8],
|
||||
dry_run: bool,
|
||||
) -> Result<StoredSnapshot> {
|
||||
if dry_run {
|
||||
return Ok(StoredSnapshot {
|
||||
id: manifest.snapshot_id,
|
||||
taken_at: Utc::now(),
|
||||
manifest,
|
||||
size_bytes: payload.len() as u64,
|
||||
tree_root: "dry-run".into(),
|
||||
});
|
||||
}
|
||||
|
||||
let chunk_id = self.store_chunk(payload)?;
|
||||
self.save_index()?;
|
||||
|
||||
let snap = StoredSnapshot {
|
||||
id: manifest.snapshot_id,
|
||||
taken_at: Utc::now(),
|
||||
manifest,
|
||||
size_bytes: payload.len() as u64,
|
||||
tree_root: chunk_id,
|
||||
};
|
||||
|
||||
let path = self
|
||||
.root
|
||||
.join("snapshots")
|
||||
.join(format!("{}.json", snap.id));
|
||||
fs::write(&path, serde_json::to_string_pretty(&snap)?)?;
|
||||
Ok(snap)
|
||||
}
|
||||
|
||||
pub fn list_snapshots(&self) -> Result<Vec<StoredSnapshot>> {
|
||||
let dir = self.root.join("snapshots");
|
||||
if !dir.exists() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for entry in fs::read_dir(&dir)? {
|
||||
let path = entry?.path();
|
||||
if path.extension().and_then(|e| e.to_str()) != Some("json") {
|
||||
continue;
|
||||
}
|
||||
let data = fs::read_to_string(&path)?;
|
||||
let snap: StoredSnapshot = serde_json::from_str(&data)?;
|
||||
out.push(snap);
|
||||
}
|
||||
out.sort_by(|a, b| b.taken_at.cmp(&a.taken_at));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
|
||||
let path = self.root.join("snapshots").join(format!("{id}.json"));
|
||||
let data = fs::read_to_string(&path).context("snapshot metadata")?;
|
||||
let snap: StoredSnapshot = serde_json::from_str(&data)?;
|
||||
let bytes = self.read_chunk(&snap.tree_root)?;
|
||||
if let Some(parent) = dest.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(dest, &bytes)?;
|
||||
Ok(bytes.len() as u64)
|
||||
}
|
||||
|
||||
pub fn forget(&mut self, ids: &[Uuid]) -> Result<usize> {
|
||||
let mut removed = 0;
|
||||
for id in ids {
|
||||
let path = self.root.join("snapshots").join(format!("{id}.json"));
|
||||
if path.exists() {
|
||||
fs::remove_file(&path)?;
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
|
||||
let policy = DecayPolicy::from_preset(preset);
|
||||
let snaps = self.list_snapshots()?;
|
||||
let refs: Vec<SnapshotRef> = snaps
|
||||
.iter()
|
||||
.map(|s| SnapshotRef {
|
||||
id: s.id,
|
||||
taken_at: s.taken_at,
|
||||
})
|
||||
.collect();
|
||||
let to_forget = evaluate_decay(&policy, refs);
|
||||
self.forget(&to_forget)?;
|
||||
Ok(to_forget)
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
use tessera_core::manifest::SnapshotManifest;
|
||||
|
||||
#[test]
|
||||
fn init_snap_list_restore() {
|
||||
let dir = tempdir().unwrap();
|
||||
let mut vault = Vault::init(dir.path(), "secret").unwrap();
|
||||
let manifest = SnapshotManifest {
|
||||
snapshot_id: Uuid::new_v4(),
|
||||
orbit_id: Uuid::new_v4(),
|
||||
orbit_name: "test".into(),
|
||||
labels: vec![],
|
||||
provider: "filesystem".into(),
|
||||
paths: vec![],
|
||||
restore_hints: serde_json::json!({}),
|
||||
};
|
||||
let snap = vault
|
||||
.snapshot(manifest, b"payload bytes", false)
|
||||
.unwrap();
|
||||
let list = vault.list_snapshots().unwrap();
|
||||
assert_eq!(list.len(), 1);
|
||||
assert_eq!(list[0].id, snap.id);
|
||||
let out = dir.path().join("restored.bin");
|
||||
let n = vault.restore_snapshot(snap.id, &out).unwrap();
|
||||
assert_eq!(n, 13);
|
||||
assert_eq!(fs::read(&out).unwrap(), b"payload bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dry_run_writes_nothing() {
|
||||
let dir = tempdir().unwrap();
|
||||
let mut vault = Vault::init(dir.path(), "secret").unwrap();
|
||||
let manifest = SnapshotManifest {
|
||||
snapshot_id: Uuid::new_v4(),
|
||||
orbit_id: Uuid::new_v4(),
|
||||
orbit_name: "rehearse".into(),
|
||||
labels: vec![],
|
||||
provider: "filesystem".into(),
|
||||
paths: vec![],
|
||||
restore_hints: serde_json::json!({}),
|
||||
};
|
||||
vault.snapshot(manifest, b"x", true).unwrap();
|
||||
assert!(vault.list_snapshots().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user