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:
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"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user