use anyhow::Result;
use chrono::Utc;
use rusqlite::{OptionalExtension, Transaction, params};
use serde::Serialize;
use uuid::Uuid;
use super::SqliteStore;
use super::delete::DeleteScope;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DeleteStatus {
pub id: Uuid,
pub scope: String,
pub target: String,
pub seq: u64,
pub deleted_at: i64,
pub peers: Vec<PeerDeleteAck>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PeerDeleteAck {
pub peer_id: String,
pub acked_seq: Option<u64>,
pub acked: bool,
pub live: bool,
}
impl SqliteStore {
pub fn delete_status(&self, key: &str) -> Result<Option<DeleteStatus>> {
let row: Option<(String, String, String, i64, i64)> = self
.reader()
.query_row(
"SELECT id, scope, target, seq, deleted_at FROM deletes \
WHERE id = ?1 OR target = ?1 ORDER BY id = ?1 DESC, deleted_at DESC LIMIT 1",
params![key],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
)
.optional()?;
let Some((id, scope, target, seq, deleted_at)) = row else {
return Ok(None);
};
let seq = u64::try_from(seq)?;
let peers = self
.peer_acks()?
.into_iter()
.map(|ack| PeerDeleteAck {
acked: ack.acked_seq.is_some_and(|acked| acked >= seq),
peer_id: ack.peer_id,
acked_seq: ack.acked_seq,
live: ack.live,
})
.collect();
Ok(Some(DeleteStatus {
id: Uuid::parse_str(&id)?,
scope,
target,
seq,
deleted_at,
peers,
}))
}
}
pub(super) fn record(tx: &Transaction<'_>, scope: &DeleteScope) -> Result<(Uuid, u64)> {
let (name, target) = match scope {
DeleteScope::Memory(id) => ("memory", id.to_string()),
DeleteScope::Session(key) => ("session", key.clone()),
DeleteScope::Project(path) => ("project", path.clone()),
};
let seq: i64 = tx.query_row(
"SELECT COALESCE(MAX(local_seq), 0) FROM sync_log",
[],
|r| r.get(0),
)?;
let id = Uuid::new_v4();
tx.execute(
"INSERT INTO deletes (id, scope, target, seq, deleted_at) VALUES (?1, ?2, ?3, ?4, ?5)",
params![
id.to_string(),
name,
target,
seq,
Utc::now().timestamp_micros()
],
)?;
Ok((id, u64::try_from(seq)?))
}