use std::path::Path;
use std::sync::{Arc, Weak};
use std::time::Duration;
use saorsa_core::P2PNode;
use tokio_util::sync::CancellationToken;
use crate::logging::{info, warn};
const REPORT_INTERVAL: Duration = Duration::from_secs(15 * 60);
const LEGACY_ENV_DIR: &str = "chunks.mdb";
const RETIRED_SUFFIX: &str = ".retired";
const RETIRED_MARKER: &str = "RETIRED";
const SIGNAL_PREFIX: &str = "migration/";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MigrationSignal {
Legacy,
Files,
Unknown,
}
impl MigrationSignal {
const fn token(self) -> &'static str {
match self {
Self::Legacy => "legacy",
Self::Files => "files",
Self::Unknown => "unknown",
}
}
#[must_use]
pub fn from_disk(root_dir: &Path) -> Self {
let Ok(dirs) = legacy_directories(root_dir) else {
return Self::Unknown;
};
let mut answer = Self::Files;
for dir in dirs {
match classify(&dir) {
Leftover::Harmless => {}
Leftover::Holding => return Self::Legacy,
Leftover::Unreadable => answer = Self::Unknown,
}
}
answer
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Leftover {
Holding,
Harmless,
Unreadable,
}
fn legacy_directories(root_dir: &Path) -> Result<Vec<std::path::PathBuf>, Unreadable> {
let mut found = Vec::new();
let live = root_dir.join(LEGACY_ENV_DIR);
if !matches!(std::fs::symlink_metadata(&live), Err(ref e) if e.kind() == std::io::ErrorKind::NotFound)
{
found.push(live);
}
let entries = match std::fs::read_dir(root_dir) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(found),
Err(_) => return Err(Unreadable),
};
for entry in entries {
let Ok(entry) = entry else {
return Err(Unreadable);
};
if entry.file_name().to_str().is_some_and(is_tombstone_name) {
found.push(entry.path());
}
}
Ok(found)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Unreadable;
const MAX_TOMBSTONES: u32 = 64;
fn is_tombstone_name(name: &str) -> bool {
let base = format!("{LEGACY_ENV_DIR}{RETIRED_SUFFIX}");
if name == base {
return true;
}
let Some(suffix) = name.strip_prefix(&format!("{base}.")) else {
return false;
};
suffix
.parse::<u32>()
.is_ok_and(|n| (1..=MAX_TOMBSTONES).contains(&n) && suffix == n.to_string())
}
fn classify(dir: &Path) -> Leftover {
match std::fs::symlink_metadata(dir) {
Ok(meta) if meta.file_type().is_symlink() => return Leftover::Holding,
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Leftover::Harmless,
Err(_) => return Leftover::Unreadable,
}
match std::fs::symlink_metadata(dir.join(RETIRED_MARKER)) {
Ok(meta) if meta.is_file() => return Leftover::Harmless,
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(_) => return Leftover::Unreadable,
}
std::fs::read_dir(dir).map_or(Leftover::Unreadable, |mut entries| {
if entries.next().is_none() {
Leftover::Harmless
} else {
Leftover::Holding
}
})
}
#[must_use]
pub fn user_agent(signal: MigrationSignal) -> String {
format!(
"node/{} {SIGNAL_PREFIX}{}",
env!("CARGO_PKG_VERSION"),
signal.token()
)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PeerMigrationState {
Legacy,
Files,
Unknown,
Unreported,
NotANode,
}
#[must_use]
pub fn peer_state(user_agent: &str) -> PeerMigrationState {
if !user_agent.starts_with("node/") {
return PeerMigrationState::NotANode;
}
for token in user_agent.split_whitespace() {
let Some(state) = token.strip_prefix(SIGNAL_PREFIX) else {
continue;
};
return match state {
"legacy" => PeerMigrationState::Legacy,
"files" => PeerMigrationState::Files,
_ => PeerMigrationState::Unknown,
};
}
PeerMigrationState::Unreported
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PeerTally {
pub legacy: usize,
pub files: usize,
pub unknown: usize,
pub unreported: usize,
}
impl PeerTally {
#[must_use]
pub const fn outstanding(self) -> usize {
self.legacy + self.unknown + self.unreported
}
fn add(&mut self, state: PeerMigrationState) {
match state {
PeerMigrationState::Legacy => self.legacy += 1,
PeerMigrationState::Files => self.files += 1,
PeerMigrationState::Unknown => self.unknown += 1,
PeerMigrationState::Unreported => self.unreported += 1,
PeerMigrationState::NotANode => {}
}
}
}
pub async fn tally_peers(p2p: &Arc<P2PNode>) -> PeerTally {
let mut tally = PeerTally::default();
let transport = p2p.transport();
let observer = p2p.peer_id().to_hex();
for peer in transport.connected_peers().await {
let agent = transport.peer_user_agent(&peer).await;
let state = agent
.as_deref()
.map_or(PeerMigrationState::Unreported, peer_state);
if state != PeerMigrationState::Files && state != PeerMigrationState::NotANode {
info!(
migration_event = "peer_state",
observer = %observer,
peer = %peer.to_hex(),
state = peer_state_token(state),
agent = agent.as_deref().unwrap_or("none"),
"Storage migration: peer {} is {}",
peer.to_hex(),
peer_state_token(state)
);
}
tally.add(state);
}
tally
}
#[cfg_attr(not(feature = "logging"), allow(dead_code))]
const fn peer_state_token(state: PeerMigrationState) -> &'static str {
match state {
PeerMigrationState::Legacy => "legacy",
PeerMigrationState::Files => "files",
PeerMigrationState::Unknown => "unknown",
PeerMigrationState::Unreported => "unreported",
PeerMigrationState::NotANode => "not-a-node",
}
}
pub async fn report_until_shutdown(
p2p: Weak<P2PNode>,
root_dir: std::path::PathBuf,
shutdown: CancellationToken,
) {
loop {
tokio::select! {
() = shutdown.cancelled() => return,
() = tokio::time::sleep(REPORT_INTERVAL) => {}
}
let Some(node) = p2p.upgrade() else {
return;
};
let own = MigrationSignal::from_disk(&root_dir);
let peers = tally_peers(&node).await;
drop(node);
let seen = peers.outstanding() + peers.files;
if own == MigrationSignal::Legacy || own == MigrationSignal::Unknown {
warn!(
migration_event = "signal",
state = own.token(),
peers_legacy = peers.legacy,
peers_unknown = peers.unknown,
peers_unreported = peers.unreported,
peers_files = peers.files,
"This node cannot report itself finished with the old chunk store ({}: \
`legacy` means one is there, `unknown` means its disk could not be read, so \
whether one is there is not known). {} of the {seen} node(s) it can see are \
not reporting finished either.",
own.token(),
peers.outstanding()
);
} else {
info!(
migration_event = "signal",
state = own.token(),
peers_legacy = peers.legacy,
peers_unknown = peers.unknown,
peers_unreported = peers.unreported,
peers_files = peers.files,
"Storage migration: this node has nothing of the old store left; {} of the \
{seen} node(s) it can see are not reporting finished.",
peers.outstanding()
);
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
#[tokio::test]
async fn the_reporter_lets_go_of_a_node_that_was_dropped() {
let dir = tempfile::tempdir().expect("temp dir");
let root = dir.path().to_path_buf();
let shutdown = CancellationToken::new();
let owner = Arc::new(());
let weak = Arc::downgrade(&owner);
assert_eq!(Arc::strong_count(&owner), 1);
let handle = tokio::spawn({
let weak = weak.clone();
let shutdown = shutdown.clone();
async move {
loop {
tokio::select! {
() = shutdown.cancelled() => return "cancelled",
() = tokio::time::sleep(std::time::Duration::from_millis(5)) => {}
}
let Some(up) = weak.upgrade() else {
return "node went away";
};
drop(up);
}
}
});
assert_eq!(
Arc::strong_count(&owner),
1,
"starting the reporter must not add a strong holder"
);
drop(owner);
let outcome = tokio::time::timeout(std::time::Duration::from_secs(5), handle)
.await
.expect("the reporter must stop on its own")
.expect("task must not panic");
assert_eq!(
outcome, "node went away",
"the reporter must stop when the node is gone, not wait for a cancellation \
nobody sends"
);
let _ = root;
}
use super::*;
use tempfile::TempDir;
fn dir_with(root: &Path, name: &str) -> std::path::PathBuf {
let path = root.join(name);
std::fs::create_dir_all(&path).unwrap();
path
}
#[test]
fn a_node_with_nothing_on_disk_has_finished() {
let root = TempDir::new().unwrap();
assert_eq!(
MigrationSignal::from_disk(root.path()),
MigrationSignal::Files
);
}
#[test]
fn a_root_that_does_not_exist_yet_has_finished() {
let root = TempDir::new().unwrap();
let never = root.path().join("not-created");
assert_eq!(MigrationSignal::from_disk(&never), MigrationSignal::Files);
}
#[test]
fn a_live_environment_with_chunks_in_it_has_not() {
let root = TempDir::new().unwrap();
let env = dir_with(root.path(), LEGACY_ENV_DIR);
std::fs::write(env.join("data.mdb"), b"chunks").unwrap();
assert_eq!(
MigrationSignal::from_disk(root.path()),
MigrationSignal::Legacy
);
}
#[test]
fn a_marked_leftover_has_finished() {
let root = TempDir::new().unwrap();
let env = dir_with(root.path(), LEGACY_ENV_DIR);
std::fs::write(env.join("data.mdb"), b"chunks").unwrap();
std::fs::write(env.join(RETIRED_MARKER), b"").unwrap();
assert_eq!(
MigrationSignal::from_disk(root.path()),
MigrationSignal::Files
);
}
#[test]
fn an_empty_leftover_has_finished() {
let root = TempDir::new().unwrap();
dir_with(root.path(), "chunks.mdb.retired");
assert_eq!(
MigrationSignal::from_disk(root.path()),
MigrationSignal::Files
);
}
#[test]
fn a_tombstone_with_chunks_in_it_has_not() {
let root = TempDir::new().unwrap();
let tomb = dir_with(root.path(), "chunks.mdb.retired.3");
std::fs::write(tomb.join("data.mdb"), b"chunks").unwrap();
assert_eq!(
MigrationSignal::from_disk(root.path()),
MigrationSignal::Legacy
);
}
#[test]
fn an_entry_that_cannot_be_read_is_never_read_as_finished() {
let root = TempDir::new().unwrap();
let unreadable = root.path().join("locked");
std::fs::create_dir_all(&unreadable).unwrap();
let tomb = unreadable.join("chunks.mdb.retired");
std::fs::create_dir_all(&tomb).unwrap();
std::fs::write(tomb.join("data.mdb"), b"chunks").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).unwrap();
let answer = MigrationSignal::from_disk(&unreadable);
std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(
answer,
MigrationSignal::Unknown,
"a root that cannot be listed must never answer that it has finished"
);
}
}
#[test]
fn a_directory_that_only_looks_like_a_tombstone_is_not_one() {
assert!(is_tombstone_name("chunks.mdb.retired"));
assert!(is_tombstone_name("chunks.mdb.retired.1"));
assert!(is_tombstone_name("chunks.mdb.retired.42"));
assert!(!is_tombstone_name("chunks.mdb.retired-mine"));
assert!(!is_tombstone_name("chunks.mdb.retired."));
assert!(!is_tombstone_name("chunks.mdb.retired.backup"));
assert!(!is_tombstone_name("chunks.mdb"));
assert!(is_tombstone_name("chunks.mdb.retired.64"));
assert!(!is_tombstone_name("chunks.mdb.retired.65"));
assert!(!is_tombstone_name("chunks.mdb.retired.0"));
assert!(!is_tombstone_name("chunks.mdb.retired.007"));
assert!(!is_tombstone_name("chunks.mdb.retired.+1"));
assert!(!is_tombstone_name("chunks.mdb.retired.999999"));
let root = TempDir::new().unwrap();
let mine = dir_with(root.path(), "chunks.mdb.retired-mine");
std::fs::write(mine.join("data.mdb"), b"somebody else's").unwrap();
assert_eq!(
MigrationSignal::from_disk(root.path()),
MigrationSignal::Files
);
}
#[test]
fn a_linked_environment_is_never_read_as_finished() {
let root = TempDir::new().unwrap();
let elsewhere = dir_with(root.path(), "elsewhere");
std::fs::write(elsewhere.join(RETIRED_MARKER), b"").unwrap();
#[cfg(unix)]
{
std::os::unix::fs::symlink(&elsewhere, root.path().join(LEGACY_ENV_DIR)).unwrap();
assert_eq!(
MigrationSignal::from_disk(root.path()),
MigrationSignal::Legacy
);
}
}
#[test]
fn a_peer_on_the_previous_release_is_not_counted_as_finished() {
assert_eq!(
peer_state("node/0.19.0"),
PeerMigrationState::Unreported,
"a node with no migration token has not reported, which is not the same as done"
);
let mut tally = PeerTally::default();
tally.add(peer_state("node/0.19.0"));
assert_eq!(tally.files, 0, "it must not land in the finished bucket");
assert_eq!(tally.outstanding(), 1, "and must count against readiness");
}
#[test]
fn the_user_agent_keeps_the_prefix_that_gates_dht_membership() {
for signal in [
MigrationSignal::Legacy,
MigrationSignal::Files,
MigrationSignal::Unknown,
] {
assert!(user_agent(signal).starts_with("node/"));
}
}
#[test]
fn a_peer_reads_back_what_a_node_announced() {
assert_eq!(
peer_state(&user_agent(MigrationSignal::Legacy)),
PeerMigrationState::Legacy
);
assert_eq!(
peer_state(&user_agent(MigrationSignal::Files)),
PeerMigrationState::Files
);
assert_eq!(
peer_state(&user_agent(MigrationSignal::Unknown)),
PeerMigrationState::Unknown
);
}
#[test]
fn silence_is_counted_as_silence_and_not_as_completion() {
assert_eq!(peer_state("node/0.27.0"), PeerMigrationState::Unreported);
assert_eq!(
peer_state("node/0.17.2 migration/something-new"),
PeerMigrationState::Unknown
);
}
#[test]
fn a_client_is_not_a_node_that_failed_to_report() {
assert_eq!(peer_state("client/0.27.0"), PeerMigrationState::NotANode);
}
}