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