use dashmap::DashMap;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use tokio::sync::{broadcast, Notify, Semaphore};
use tokio::time::{sleep, Duration};
use crate::config::{Config, ReplicationConfig};
use crate::git::{GitReplication, HeadRelation, PackApply, RepositoryHead, RepositoryScan};
use crate::state::AppState;
use crate::util::run_blocking;
use crate::validate;
const NOTIFICATION_CHANNEL_CAPACITY: usize = 1024;
pub const EVENT_HEARTBEAT_SECS: u64 = 20;
const EVENT_READ_TIMEOUT_SECS: u64 = 60;
const MAXIMUM_RECONNECT_BACKOFF_MS: u64 = 60_000;
const CONNECT_TIMEOUT_SECS: u64 = 10;
const STATE_TIMEOUT_SECS: u64 = 30;
const PACK_READ_TIMEOUT_SECS: u64 = 600;
const INCOMPLETE_RESCAN_MIN_SECS: u64 = 5;
const STALLED_AFTER_FAILURES: u32 = 3;
const REPLICA_SILENT_SECS: i64 = 120;
const DELETION_GUARD_MINIMUM_HELD: usize = 2;
const COLLISION_EXPIRY_SECS: i64 = 150;
const COLLISION_REPORT_AFTER_SECS: u64 = 2 * EVENT_HEARTBEAT_SECS;
const INSTANCE_BYTES: usize = 16;
const INDEX_RESCAN_SECS: u64 = 600;
const IDENTITY_FILE: &str = ".replication.json";
const IDENTITY_BYTES: usize = 32;
pub const URL_PREFIX: &str = "/_replication";
pub const PROTOCOL_VERSION: u32 = 1;
pub const PROTOCOL_HEADER: &str = "x-replication-protocol";
pub const HEAD_SHA_HEADER: &str = "x-replication-head-sha";
const INCOMING_DIRECTORY: &str = ".replication-incoming";
pub mod rfc3339 {
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn format(unix: i64) -> String {
DateTime::<Utc>::from_timestamp(unix, 0)
.map(|at| at.to_rfc3339_opts(SecondsFormat::Secs, true))
.unwrap_or_default()
}
pub fn parse(raw: &str) -> Option<i64> {
DateTime::parse_from_rfc3339(raw)
.ok()
.map(|at| at.timestamp())
}
pub fn serialize<S: Serializer>(unix: &i64, serializer: S) -> Result<S::Ok, S::Error> {
format(*unix).serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
let raw = String::deserialize(deserializer)?;
parse(&raw).ok_or_else(|| serde::de::Error::custom("expected an RFC 3339 date-time"))
}
pub mod option {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S: Serializer>(
unix: &Option<i64>,
serializer: S,
) -> Result<S::Ok, S::Error> {
unix.map(super::format).serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<i64>, D::Error> {
let raw = Option::<String>::deserialize(deserializer)?;
match raw {
None => Ok(None),
Some(raw) => super::parse(&raw)
.map(Some)
.ok_or_else(|| serde::de::Error::custom("expected an RFC 3339 date-time")),
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "event")]
pub enum ReplicationEvent {
#[serde(rename = "hello")]
Hello {
protocol: u32,
node_id: String,
#[serde(default)]
identity: Option<String>,
},
#[serde(rename = "heartbeat")]
Heartbeat,
#[serde(rename = "repository.updated")]
RepositoryUpdated {
collection_id: String,
tenant_id: String,
head_sha: String,
},
#[serde(rename = "repository.deleted")]
RepositoryDeleted {
collection_id: String,
tenant_id: String,
},
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RepositoryListing {
#[serde(default)]
pub protocol: u32,
#[serde(default)]
pub identity: Option<String>,
pub repositories: Vec<RepositoryEntry>,
pub complete: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RepositoryEntry {
pub collection_id: String,
pub tenant_id: String,
pub head_sha: String,
}
pub const NODE_ID_HEADER: &str = "x-replication-node-id";
pub const REPOSITORIES_HEADER: &str = "x-replication-repositories";
pub const PENDING_HEADER: &str = "x-replication-pending";
pub const SYNC_HEADER: &str = "x-replication-sync";
pub const INSTANCE_HEADER: &str = "x-replication-instance";
#[derive(Debug, Serialize, Deserialize)]
pub struct ReplicationHealth {
#[serde(default)]
pub protocol: u32,
#[serde(default)]
pub status: String,
#[serde(default)]
pub issues: Vec<Issue>,
pub node: NodeHealth,
pub master: MasterHealth,
pub replicas: Vec<ReplicaPresence>,
#[serde(skip_serializing_if = "Option::is_none")]
pub replica: Option<FollowerHealth>,
#[serde(with = "rfc3339")]
pub observed_at: i64,
#[serde(default, with = "rfc3339::option")]
pub replicas_observed_at: Option<i64>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NodeHealth {
pub node_id: String,
pub role: String,
pub identity: Option<String>,
pub repositories: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MasterHealth {
pub node_id: Option<String>,
pub url: Option<String>,
pub reachable: bool,
#[serde(default, with = "rfc3339::option")]
pub last_contact_at: Option<i64>,
pub last_error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicaPresence {
pub node_id: String,
pub stream_connected: bool,
#[serde(default, with = "rfc3339::option")]
pub connected_at: Option<i64>,
#[serde(default, with = "rfc3339::option")]
pub last_contact_at: Option<i64>,
pub packs_delivered: u64,
pub repositories: Option<usize>,
pub pending_repositories: Option<usize>,
pub sync: Option<String>,
#[serde(default, with = "rfc3339::option")]
pub reported_at: Option<i64>,
#[serde(skip)]
pub instance: Option<String>,
#[serde(skip)]
pub last_collision_at: Option<i64>,
#[serde(skip)]
pub collision_since: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FollowerHealth {
pub state: String,
pub sync: String,
pub stream_connected: bool,
#[serde(default, with = "rfc3339::option")]
pub last_reconcile_at: Option<i64>,
#[serde(default, with = "rfc3339::option")]
pub last_success_at: Option<i64>,
pub pending_repositories: usize,
pub locked_repositories: usize,
pub consecutive_failures: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncStatus {
Synced,
Lagging,
Stalled,
Halted,
}
impl SyncStatus {
pub fn as_str(self) -> &'static str {
match self {
SyncStatus::Synced => "synced",
SyncStatus::Lagging => "lagging",
SyncStatus::Stalled => "stalled",
SyncStatus::Halted => "halted",
}
}
fn parse(raw: &str) -> Option<Self> {
match raw {
"synced" => Some(SyncStatus::Synced),
"lagging" => Some(SyncStatus::Lagging),
"stalled" => Some(SyncStatus::Stalled),
"halted" => Some(SyncStatus::Halted),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum NodeStatus {
Healthy,
Degraded,
Halted,
}
impl NodeStatus {
pub fn as_str(self) -> &'static str {
match self {
NodeStatus::Healthy => "healthy",
NodeStatus::Degraded => "degraded",
NodeStatus::Halted => "halted",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum Issue {
#[serde(rename = "replica_ahead")]
ReplicaAhead {
collection_id: String,
tenant_id: String,
local: String,
remote: String,
#[serde(with = "rfc3339")]
since: i64,
},
#[serde(rename = "history_diverged")]
HistoryDiverged {
collection_id: String,
tenant_id: String,
local: String,
remote: String,
#[serde(with = "rfc3339")]
since: i64,
},
#[serde(rename = "identity_mismatch")]
IdentityMismatch {
pinned: String,
stated: String,
#[serde(with = "rfc3339")]
since: i64,
},
#[serde(rename = "deletion_refused")]
DeletionRefused {
would_delete: usize,
held: usize,
#[serde(with = "rfc3339")]
since: i64,
},
#[serde(rename = "identity_file_missing")]
IdentityFileMissing {
path: String,
#[serde(with = "rfc3339")]
since: i64,
},
#[serde(rename = "identity_file_changed")]
IdentityFileChanged {
path: String,
expected: String,
found: String,
#[serde(with = "rfc3339")]
since: i64,
},
#[serde(rename = "node_id_collision")]
NodeIdCollision {
node_id: String,
#[serde(with = "rfc3339")]
since: i64,
},
}
impl Issue {
fn since(&self) -> i64 {
match self {
Issue::ReplicaAhead { since, .. }
| Issue::HistoryDiverged { since, .. }
| Issue::IdentityMismatch { since, .. }
| Issue::DeletionRefused { since, .. }
| Issue::IdentityFileMissing { since, .. }
| Issue::IdentityFileChanged { since, .. }
| Issue::NodeIdCollision { since, .. } => *since,
}
}
fn set_since(&mut self, value: i64) {
match self {
Issue::ReplicaAhead { since, .. }
| Issue::HistoryDiverged { since, .. }
| Issue::IdentityMismatch { since, .. }
| Issue::DeletionRefused { since, .. }
| Issue::IdentityFileMissing { since, .. }
| Issue::IdentityFileChanged { since, .. }
| Issue::NodeIdCollision { since, .. } => *since = value,
}
}
}
pub struct Issues {
inner: Mutex<BTreeMap<String, Issue>>,
}
impl Issues {
pub fn new() -> Self {
Self {
inner: Mutex::new(BTreeMap::new()),
}
}
pub fn repository_key(collection_id: &str, tenant_id: &str) -> String {
format!("repository:{}/{}", collection_id, tenant_id)
}
pub fn collision_key(node_id: &str) -> String {
format!("node_id_collision:{}", node_id)
}
pub fn raise(&self, key: &str, mut issue: Issue) -> bool {
let Ok(mut inner) = self.inner.lock() else {
return false;
};
let new = match inner.get(key) {
Some(existing) => {
issue.set_since(existing.since());
false
}
None => true,
};
inner.insert(key.to_string(), issue);
new
}
pub fn clear(&self, key: &str) -> bool {
self.inner
.lock()
.map(|mut inner| inner.remove(key).is_some())
.unwrap_or(false)
}
pub fn get(&self, key: &str) -> Option<Issue> {
self.inner
.lock()
.ok()
.and_then(|inner| inner.get(key).cloned())
}
pub fn is_empty(&self) -> bool {
self.inner
.lock()
.map(|inner| inner.is_empty())
.unwrap_or(true)
}
pub fn count_with_prefix(&self, prefix: &str) -> usize {
self.inner
.lock()
.map(|inner| inner.keys().filter(|key| key.starts_with(prefix)).count())
.unwrap_or(0)
}
pub fn all(&self) -> Vec<Issue> {
let mut issues: Vec<Issue> = self
.inner
.lock()
.map(|inner| inner.values().cloned().collect())
.unwrap_or_default();
issues.sort_by_key(|issue| issue.since());
issues
}
}
impl Default for Issues {
fn default() -> Self {
Self::new()
}
}
const ISSUE_IDENTITY_MISMATCH: &str = "identity_mismatch";
const ISSUE_DELETION_REFUSED: &str = "deletion_refused";
const ISSUE_IDENTITY_FILE: &str = "identity_file";
const ISSUE_NODE_ID_COLLISION: &str = "node_id_collision";
#[derive(Debug, Default, Serialize, Deserialize)]
struct IdentityFile {
identity: String,
#[serde(flatten)]
extra: serde_json::Map<String, serde_json::Value>,
}
#[derive(Debug)]
pub enum IdentityDrift {
Missing {
path: String,
},
Changed {
path: String,
expected: String,
found: String,
},
}
pub struct ReplicationIdentity {
path: PathBuf,
identity: Mutex<Option<String>>,
}
impl ReplicationIdentity {
pub fn load(config: &Config) -> Result<Self, String> {
let path = config.server.repos_path.join(IDENTITY_FILE);
let Some(replication) = &config.replication else {
return Ok(Self {
path,
identity: Mutex::new(None),
});
};
let identity = match (Self::read_file(&path)?, replication.is_replica()) {
(Some(file), _) => {
tracing::info!(identity = %file.identity, path = %path.display(), "replication identity loaded");
Some(file.identity)
}
(None, true) => {
tracing::info!(path = %path.display(), "no replication identity pinned yet, will pin the master's on first reconcile");
None
}
(None, false) => {
let generated = Self::generate()?;
Self::write_file(&path, &generated, serde_json::Map::new())?;
tracing::info!(identity = %generated, path = %path.display(), "replication identity generated");
Some(generated)
}
};
Ok(Self {
path,
identity: Mutex::new(identity),
})
}
pub fn current(&self) -> Option<String> {
self.identity
.lock()
.ok()
.and_then(|identity| identity.clone())
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn verify_on_disk(&self) -> Result<(), IdentityDrift> {
let Some(expected) = self.current() else {
return Ok(());
};
let path = self.path.display().to_string();
match Self::read_file(&self.path) {
Ok(Some(file)) if file.identity == expected => Ok(()),
Ok(Some(file)) => Err(IdentityDrift::Changed {
path,
expected,
found: file.identity,
}),
Ok(None) => Err(IdentityDrift::Missing { path }),
Err(err) => {
tracing::warn!(err = %err, "replication identity file cannot be read");
Err(IdentityDrift::Missing { path })
}
}
}
pub fn pin(&self, identity: &str) -> Result<(), String> {
validate::replication_identity(identity).map_err(|err| err.to_string())?;
let extra = Self::read_file(&self.path)?
.map(|file| file.extra)
.unwrap_or_default();
Self::write_file(&self.path, identity, extra)?;
if let Ok(mut current) = self.identity.lock() {
*current = Some(identity.to_string());
}
tracing::info!(identity = %identity, path = %self.path.display(), "replication identity pinned");
Ok(())
}
fn read_file(path: &Path) -> Result<Option<IdentityFile>, String> {
let raw = match std::fs::read(path) {
Ok(raw) => raw,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(format!("cannot read {}: {}", path.display(), err)),
};
let file: IdentityFile = serde_json::from_slice(&raw)
.map_err(|err| format!("cannot parse {}: {}", path.display(), err))?;
validate::replication_identity(&file.identity)
.map_err(|err| format!("{} holds an invalid identity: {}", path.display(), err))?;
Ok(Some(file))
}
fn write_file(
path: &Path,
identity: &str,
extra: serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
let file = IdentityFile {
identity: identity.to_string(),
extra,
};
let encoded = serde_json::to_vec_pretty(&file)
.map_err(|err| format!("cannot encode {}: {}", path.display(), err))?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|err| format!("cannot create {}: {}", parent.display(), err))?;
}
let temporary = path.with_extension("json.tmp");
std::fs::write(&temporary, encoded)
.map_err(|err| format!("cannot write {}: {}", temporary.display(), err))?;
std::fs::rename(&temporary, path)
.map_err(|err| format!("cannot move {} into place: {}", temporary.display(), err))
}
fn generate() -> Result<String, String> {
generate_hex(IDENTITY_BYTES)
.map_err(|err| format!("cannot generate replication identity: {}", err))
}
}
fn generate_hex(bytes: usize) -> Result<String, String> {
let mut buffer = vec![0_u8; bytes];
getrandom::fill(&mut buffer).map_err(|err| err.to_string())?;
Ok(buffer.iter().map(|byte| format!("{:02x}", byte)).collect())
}
struct IndexEntry {
head: RepositoryHead,
announced_at: u64,
}
struct IndexInner {
heads: HashMap<String, IndexEntry>,
complete: bool,
scanned: bool,
sequence: u64,
last_scan: Option<Instant>,
}
pub struct RepositoryIndex {
repos_path: PathBuf,
inner: Mutex<IndexInner>,
scan_lock: Mutex<()>,
identity: Arc<ReplicationIdentity>,
issues: Arc<Issues>,
}
impl RepositoryIndex {
pub fn new(config: &Config, identity: Arc<ReplicationIdentity>, issues: Arc<Issues>) -> Self {
Self {
repos_path: config.server.repos_path.clone(),
inner: Mutex::new(IndexInner {
heads: HashMap::new(),
complete: false,
scanned: false,
sequence: 0,
last_scan: None,
}),
scan_lock: Mutex::new(()),
identity,
issues,
}
}
fn key(collection_id: &str, tenant_id: &str) -> String {
format!("{}/{}", collection_id, tenant_id)
}
pub fn record_head(&self, collection_id: &str, tenant_id: &str, head_sha: &str) {
let Ok(mut inner) = self.inner.lock() else {
return;
};
inner.sequence += 1;
let announced_at = inner.sequence;
inner.heads.insert(
Self::key(collection_id, tenant_id),
IndexEntry {
head: RepositoryHead {
collection_id: collection_id.to_string(),
tenant_id: tenant_id.to_string(),
head_sha: head_sha.to_string(),
},
announced_at,
},
);
}
pub fn remove(&self, collection_id: &str, tenant_id: &str) {
let Ok(mut inner) = self.inner.lock() else {
return;
};
inner.sequence += 1;
inner.heads.remove(&Self::key(collection_id, tenant_id));
}
pub fn snapshot(&self) -> RepositoryScan {
if self.needs_scan() {
let _scanning = self.scan_lock.lock();
if self.needs_scan() {
self.rescan();
}
}
let identity_intact = self.verify_identity_file();
let Ok(inner) = self.inner.lock() else {
return RepositoryScan::default();
};
let mut repositories: Vec<RepositoryHead> = inner
.heads
.values()
.map(|entry| RepositoryHead {
collection_id: entry.head.collection_id.clone(),
tenant_id: entry.head.tenant_id.clone(),
head_sha: entry.head.head_sha.clone(),
})
.collect();
repositories.sort_by(|left, right| {
(&left.collection_id, &left.tenant_id).cmp(&(&right.collection_id, &right.tenant_id))
});
RepositoryScan {
repositories,
complete: inner.complete && identity_intact,
}
}
fn needs_scan(&self) -> bool {
self.inner
.lock()
.map(|inner| {
if !inner.scanned {
return true;
}
if inner.complete {
return false;
}
inner
.last_scan
.map(|at| at.elapsed().as_secs() >= INCOMPLETE_RESCAN_MIN_SECS)
.unwrap_or(true)
})
.unwrap_or(true)
}
pub fn rescan(&self) {
let started_at = match self.inner.lock() {
Ok(inner) => inner.sequence,
Err(_) => return,
};
let identity_intact = self.verify_identity_file();
let mut scan = GitReplication::list_repositories(&self.repos_path);
scan.complete &= identity_intact;
let Ok(mut inner) = self.inner.lock() else {
return;
};
let mut scanned: HashMap<String, RepositoryHead> = scan
.repositories
.into_iter()
.map(|head| (Self::key(&head.collection_id, &head.tenant_id), head))
.collect();
if scan.complete {
inner
.heads
.retain(|key, entry| scanned.contains_key(key) || entry.announced_at > started_at);
}
for (key, head) in scanned.drain() {
let announced_since = inner
.heads
.get(&key)
.map(|entry| entry.announced_at > started_at)
.unwrap_or(false);
if announced_since {
continue;
}
inner.heads.insert(
key,
IndexEntry {
head,
announced_at: 0,
},
);
}
inner.complete = scan.complete;
inner.scanned = true;
inner.last_scan = Some(Instant::now());
tracing::debug!(
repositories = inner.heads.len(),
complete = inner.complete,
"repository index rescanned"
);
}
fn verify_identity_file(&self) -> bool {
let now = chrono::Utc::now().timestamp();
match self.identity.verify_on_disk() {
Ok(()) => {
if self.issues.clear(ISSUE_IDENTITY_FILE) {
tracing::info!("replication identity file is back, listing is complete again");
}
true
}
Err(IdentityDrift::Missing { path }) => {
let new = self.issues.raise(
ISSUE_IDENTITY_FILE,
Issue::IdentityFileMissing {
path: path.clone(),
since: now,
},
);
if new {
tracing::error!(
path = %path,
"replication identity file is missing: the repository store is not the one this process started with; \
serving the listing as incomplete so no replica infers deletions from it"
);
} else {
tracing::debug!(path = %path, "replication identity file still missing");
}
false
}
Err(IdentityDrift::Changed {
path,
expected,
found,
}) => {
let new = self.issues.raise(
ISSUE_IDENTITY_FILE,
Issue::IdentityFileChanged {
path: path.clone(),
expected: expected.clone(),
found: found.clone(),
since: now,
},
);
if new {
tracing::error!(
path = %path,
expected = %expected,
found = %found,
"replication identity file changed under this process; \
serving the listing as incomplete so no replica infers deletions from it"
);
} else {
tracing::debug!(path = %path, "replication identity file still changed");
}
false
}
}
}
}
pub fn redact_url(raw: &str) -> String {
match reqwest::Url::parse(raw) {
Ok(mut url) => {
if !url.username().is_empty() || url.password().is_some() {
let _ = url.set_username("");
let _ = url.set_password(None);
}
url.to_string().trim_end_matches('/').to_string()
}
Err(_) => "<invalid url>".to_string(),
}
}
pub struct ReplicaRegistry {
replicas: DashMap<String, ReplicaPresence>,
}
impl ReplicaRegistry {
pub fn new() -> Self {
Self {
replicas: DashMap::new(),
}
}
pub fn note_request(
&self,
node_id: &str,
repositories: Option<usize>,
pending: Option<usize>,
sync: Option<String>,
) {
let now = chrono::Utc::now().timestamp();
let mut presence = self.entry(node_id);
presence.last_contact_at = Some(now);
if repositories.is_some() || pending.is_some() || sync.is_some() {
presence.repositories = repositories;
presence.pending_repositories = pending;
presence.sync = sync;
presence.reported_at = Some(now);
}
}
pub fn note_pack_delivered(&self, node_id: &str) {
let now = chrono::Utc::now().timestamp();
let mut presence = self.entry(node_id);
presence.packs_delivered += 1;
presence.last_contact_at = Some(now);
}
pub fn stream_opened(&self, node_id: &str, instance: &str) -> Result<(), StreamCollision> {
let now = chrono::Utc::now().timestamp();
let mut presence = self.entry(node_id);
if presence.stream_connected {
if let Some(holder) = &presence.instance {
if holder != instance {
if presence
.last_collision_at
.map(|last| now - last > COLLISION_EXPIRY_SECS)
.unwrap_or(true)
{
presence.collision_since = None;
}
let since = *presence.collision_since.get_or_insert(now);
presence.last_collision_at = Some(now);
return Err(StreamCollision {
node_id: node_id.to_string(),
persisting: now - since >= COLLISION_REPORT_AFTER_SECS as i64,
since,
});
}
}
}
presence.stream_connected = true;
presence.connected_at = Some(now);
presence.last_contact_at = Some(now);
presence.instance = Some(instance.to_string());
presence.collision_since = None;
Ok(())
}
pub fn stream_closed(&self, node_id: &str, instance: &str) {
let mut presence = self.entry(node_id);
if presence.instance.as_deref() != Some(instance) {
return;
}
presence.stream_connected = false;
presence.last_contact_at = Some(chrono::Utc::now().timestamp());
}
pub fn roster(&self) -> Vec<ReplicaPresence> {
let mut roster: Vec<ReplicaPresence> = self
.replicas
.iter()
.map(|entry| entry.value().clone())
.collect();
roster.sort_by(|left, right| {
right
.last_contact_at
.cmp(&left.last_contact_at)
.then_with(|| left.node_id.cmp(&right.node_id))
});
roster
}
fn entry(&self, node_id: &str) -> dashmap::mapref::one::RefMut<'_, String, ReplicaPresence> {
self.replicas
.entry(node_id.to_string())
.or_insert_with(|| ReplicaPresence {
node_id: node_id.to_string(),
stream_connected: false,
connected_at: None,
last_contact_at: None,
packs_delivered: 0,
repositories: None,
pending_repositories: None,
sync: None,
reported_at: None,
instance: None,
last_collision_at: None,
collision_since: None,
})
}
pub fn expire_collisions(&self, issues: &Issues, now: i64) {
for entry in self.replicas.iter() {
let Some(last) = entry.value().last_collision_at else {
continue;
};
if now - last > COLLISION_EXPIRY_SECS
&& issues.clear(&Issues::collision_key(entry.key()))
{
tracing::info!(node_id = %entry.key(), "node id collision cleared");
}
}
}
}
#[derive(Debug)]
pub struct StreamCollision {
pub node_id: String,
pub persisting: bool,
pub since: i64,
}
impl Default for ReplicaRegistry {
fn default() -> Self {
Self::new()
}
}
pub struct ReplicationNotifier {
sender: broadcast::Sender<ReplicationEvent>,
enabled: bool,
index: Arc<RepositoryIndex>,
}
impl ReplicationNotifier {
pub fn new(config: &Config, index: Arc<RepositoryIndex>) -> Self {
let (sender, _receiver) = broadcast::channel(NOTIFICATION_CHANNEL_CAPACITY);
Self {
sender,
enabled: config.replication.is_some(),
index,
}
}
pub fn repository_updated(&self, collection_id: &str, tenant_id: &str, head_sha: &str) {
self.index.record_head(collection_id, tenant_id, head_sha);
self.publish(ReplicationEvent::RepositoryUpdated {
collection_id: collection_id.to_string(),
tenant_id: tenant_id.to_string(),
head_sha: head_sha.to_string(),
});
}
pub fn repository_deleted(&self, collection_id: &str, tenant_id: &str) {
self.index.remove(collection_id, tenant_id);
self.publish(ReplicationEvent::RepositoryDeleted {
collection_id: collection_id.to_string(),
tenant_id: tenant_id.to_string(),
});
}
fn publish(&self, event: ReplicationEvent) {
if !self.enabled {
return;
}
let _ = self.sender.send(event);
}
pub fn subscribe(&self) -> broadcast::Receiver<ReplicationEvent> {
self.sender.subscribe()
}
pub fn connected_replicas(&self) -> usize {
self.sender.receiver_count()
}
}
pub struct ReplicaStatus {
is_replica: bool,
bootstrapped: AtomicBool,
stream_connected: AtomicBool,
last_reconcile_unix: AtomicI64,
pending_repositories: AtomicUsize,
repositories: AtomicUsize,
identity_verified: AtomicBool,
consecutive_failures: AtomicU32,
last_success_unix: AtomicI64,
issues: Arc<Issues>,
master_view: Mutex<MasterView>,
}
#[derive(Default)]
struct MasterView {
node_id: Option<String>,
replicas: Vec<ReplicaPresence>,
observed_at: Option<i64>,
last_contact_at: Option<i64>,
last_error: Option<String>,
}
impl ReplicaStatus {
pub fn new(config: &Config, issues: Arc<Issues>) -> Self {
let is_replica = config
.replication
.as_ref()
.map(ReplicationConfig::is_replica)
.unwrap_or(false);
Self {
is_replica,
bootstrapped: AtomicBool::new(!is_replica),
stream_connected: AtomicBool::new(false),
last_reconcile_unix: AtomicI64::new(0),
pending_repositories: AtomicUsize::new(0),
repositories: AtomicUsize::new(0),
identity_verified: AtomicBool::new(false),
consecutive_failures: AtomicU32::new(0),
last_success_unix: AtomicI64::new(0),
issues,
master_view: Mutex::new(MasterView::default()),
}
}
pub fn note_pass(&self, failed: bool) {
if failed {
self.consecutive_failures.fetch_add(1, Ordering::Relaxed);
} else {
self.consecutive_failures.store(0, Ordering::Relaxed);
self.last_success_unix
.store(chrono::Utc::now().timestamp(), Ordering::Relaxed);
}
}
pub fn consecutive_failures(&self) -> u32 {
self.consecutive_failures.load(Ordering::Relaxed)
}
pub fn last_success(&self) -> Option<i64> {
match self.last_success_unix.load(Ordering::Relaxed) {
0 => None,
seconds => Some(seconds),
}
}
pub fn locked_repositories(&self) -> usize {
self.issues.count_with_prefix("repository:")
}
pub fn sync_status(&self) -> SyncStatus {
if !self.issues.is_empty() {
return SyncStatus::Halted;
}
if self.consecutive_failures() >= STALLED_AFTER_FAILURES {
return SyncStatus::Stalled;
}
if self.pending() > 0 || self.last_success().is_none() {
return SyncStatus::Lagging;
}
SyncStatus::Synced
}
pub fn set_identity_verified(&self, verified: bool) {
self.identity_verified.store(verified, Ordering::Relaxed);
}
pub fn identity_verified(&self) -> bool {
self.identity_verified.load(Ordering::Relaxed)
}
pub fn is_replica(&self) -> bool {
self.is_replica
}
pub fn is_bootstrapped(&self) -> bool {
self.bootstrapped.load(Ordering::Relaxed)
}
pub fn mark_bootstrapped(&self) {
if !self.bootstrapped.swap(true, Ordering::Relaxed) {
tracing::info!("replica bootstrapped, now serving reads");
}
}
pub fn set_stream_connected(&self, connected: bool) {
self.stream_connected.store(connected, Ordering::Relaxed);
}
pub fn stream_connected(&self) -> bool {
self.stream_connected.load(Ordering::Relaxed)
}
pub fn set_last_reconcile(&self, unix_seconds: i64) {
self.last_reconcile_unix
.store(unix_seconds, Ordering::Relaxed);
}
pub fn last_reconcile(&self) -> Option<i64> {
match self.last_reconcile_unix.load(Ordering::Relaxed) {
0 => None,
seconds => Some(seconds),
}
}
pub fn set_pending(&self, pending: usize) {
self.pending_repositories.store(pending, Ordering::Relaxed);
}
pub fn pending(&self) -> usize {
self.pending_repositories.load(Ordering::Relaxed)
}
pub fn set_repositories(&self, repositories: usize) {
self.repositories.store(repositories, Ordering::Relaxed);
}
pub fn repositories(&self) -> usize {
self.repositories.load(Ordering::Relaxed)
}
pub fn record_master_health(&self, node_id: Option<String>, replicas: Vec<ReplicaPresence>) {
let now = chrono::Utc::now().timestamp();
if let Ok(mut view) = self.master_view.lock() {
view.node_id = node_id;
view.replicas = replicas;
view.observed_at = Some(now);
view.last_contact_at = Some(now);
view.last_error = None;
}
}
pub fn record_master_identity(&self, node_id: String) {
if let Ok(mut view) = self.master_view.lock() {
view.node_id = Some(node_id);
view.last_contact_at = Some(chrono::Utc::now().timestamp());
view.last_error = None;
}
}
pub fn record_master_contact(&self) {
if let Ok(mut view) = self.master_view.lock() {
view.last_contact_at = Some(chrono::Utc::now().timestamp());
view.last_error = None;
}
}
pub fn record_master_error(&self, error: String) {
if let Ok(mut view) = self.master_view.lock() {
view.last_error = Some(error);
}
}
#[allow(clippy::type_complexity)]
pub fn master_snapshot(
&self,
) -> (
Option<String>,
Vec<ReplicaPresence>,
Option<i64>,
Option<i64>,
Option<String>,
) {
match self.master_view.lock() {
Ok(view) => (
view.node_id.clone(),
view.replicas.clone(),
view.observed_at,
view.last_contact_at,
view.last_error.clone(),
),
Err(_) => (None, Vec::new(), None, None, None),
}
}
}
#[derive(Debug, Default)]
struct SyncPass {
attempted: usize,
succeeded: usize,
locked: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SyncOutcome {
Synced,
Locked,
Failed,
}
#[derive(Debug, Clone)]
enum SyncTarget {
At { head_sha: String },
Deleted,
}
pub struct ReplicaFollower {
state: AppState,
replication: ReplicationConfig,
master_url: String,
master_url_display: String,
node_id: String,
instance: String,
transfer_client: Client,
pack_client: Client,
stream_client: Client,
pending: DashMap<String, (String, String, SyncTarget)>,
wake: Arc<Notify>,
full_reconcile_requested: AtomicBool,
download_sequence: AtomicU64,
}
pub fn spawn(state: AppState) {
let Some(replication) = state.config.replication.clone() else {
return;
};
let index = state.repository_index.clone();
tokio::spawn(async move {
loop {
sleep(Duration::from_secs(INDEX_RESCAN_SECS)).await;
let index = index.clone();
if let Err(err) = run_blocking(move || {
index.rescan();
Ok(())
})
.await
{
tracing::warn!(err = %err, "repository index rescan failed");
}
}
});
if !replication.is_replica() {
tracing::info!("replication role is master, serving the replication surface");
return;
}
let Some(master_url) = replication.master_url.clone() else {
return;
};
let master_url = master_url.trim_end_matches('/').to_string();
let follower = match ReplicaFollower::new(state, replication, master_url) {
Ok(follower) => Arc::new(follower),
Err(err) => {
tracing::error!(err = %err, "failed to start replication follower");
return;
}
};
tokio::spawn(follower.clone().run_event_stream());
tokio::spawn(follower.run_worker());
}
impl ReplicaFollower {
fn new(
state: AppState,
replication: ReplicationConfig,
master_url: String,
) -> Result<Self, String> {
let node_id = replication.node_id().to_string();
let instance = generate_hex(INSTANCE_BYTES).map_err(|err| {
tracing::error!(err = %err, "cannot generate replication instance token");
err
})?;
let transfer_client = Client::builder()
.connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))
.read_timeout(Duration::from_secs(STATE_TIMEOUT_SECS))
.build()
.map_err(|err| err.to_string())?;
let pack_client = Client::builder()
.connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))
.read_timeout(Duration::from_secs(PACK_READ_TIMEOUT_SECS))
.build()
.map_err(|err| err.to_string())?;
let stream_client = Client::builder()
.connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))
.read_timeout(Duration::from_secs(EVENT_READ_TIMEOUT_SECS))
.build()
.map_err(|err| err.to_string())?;
let master_url_display = redact_url(&master_url);
Ok(Self {
state,
replication,
master_url,
master_url_display,
node_id,
instance,
transfer_client,
pack_client,
stream_client,
pending: DashMap::new(),
wake: Arc::new(Notify::new()),
full_reconcile_requested: AtomicBool::new(true),
download_sequence: AtomicU64::new(0),
})
}
async fn run_worker(self: Arc<Self>) {
let index = self.state.repository_index.clone();
let already_holds_repositories =
run_blocking(move || Ok(!index.snapshot().repositories.is_empty()))
.await
.unwrap_or(false);
if already_holds_repositories {
tracing::info!(
"replica restarted with existing repositories, serving while it catches up"
);
self.state.replica_status.mark_bootstrapped();
} else {
tracing::info!("cold replica, holding traffic until the first catch-up completes");
}
let mut reconciled_once = false;
let mut stalled_passes = 0_u32;
let mut landed_total = 0_usize;
loop {
let mut reconcile_failed = false;
if self.full_reconcile_requested.swap(false, Ordering::SeqCst) {
match self.reconcile().await {
Ok(()) => reconciled_once = true,
Err(err) => {
tracing::warn!(err = %err, "replication reconcile failed, will retry");
self.state.replica_status.record_master_error(err.clone());
reconcile_failed = true;
self.full_reconcile_requested.store(true, Ordering::SeqCst);
}
}
}
let pass = self.drain_pending().await;
landed_total += pass.succeeded;
let attempted_unlocked = pass.attempted.saturating_sub(pass.locked);
let drain_failed = attempted_unlocked > 0 && pass.succeeded == 0;
let pass_failed = reconcile_failed || drain_failed;
self.state.replica_status.note_pass(pass_failed);
if drain_failed {
stalled_passes += 1;
} else {
stalled_passes = 0;
}
if reconciled_once && !self.state.replica_status.is_bootstrapped() {
if self.pending.is_empty() {
self.state.replica_status.mark_bootstrapped();
} else if stalled_passes >= 2 && landed_total > 0 {
tracing::error!(
pending = self.pending.len(),
landed = landed_total,
"replica catch-up has stalled, serving what it holds while retrying"
);
self.state.replica_status.mark_bootstrapped();
} else if stalled_passes >= 2 {
tracing::error!(
pending = self.pending.len(),
"cold replica catch-up has stalled with nothing landed, still refusing reads"
);
}
}
if pass.succeeded > 0 && !self.pending.is_empty() {
continue;
}
if drain_failed {
sleep(Duration::from_millis(self.replication.reconnect_backoff_ms)).await;
}
let poll = Duration::from_secs(self.replication.poll_interval_secs);
tokio::select! {
_ = sleep(poll) => {
self.full_reconcile_requested.store(true, Ordering::SeqCst);
}
_ = self.wake.notified() => {}
}
}
}
async fn reconcile(&self) -> Result<(), String> {
let listing = self.fetch_state().await?;
self.verify_master_identity(listing.identity.as_deref(), true)?;
let index = self.state.repository_index.clone();
let local = run_blocking(move || {
let mut local = std::collections::HashMap::new();
for repository in index.snapshot().repositories {
local.insert(
format!("{}/{}", repository.collection_id, repository.tenant_id),
repository.head_sha,
);
}
Ok(local)
})
.await
.map_err(|err| err.to_string())?;
let mut remote_keys = std::collections::HashSet::new();
let mut stale = 0_usize;
for repository in &listing.repositories {
if let Err(reason) = Self::validate_entry(
&repository.collection_id,
&repository.tenant_id,
&repository.head_sha,
) {
tracing::warn!(reason = %reason, "ignoring invalid repository in master listing");
continue;
}
let key = format!("{}/{}", repository.collection_id, repository.tenant_id);
remote_keys.insert(key.clone());
if local.get(&key) == Some(&repository.head_sha) {
continue;
}
if self.is_locked_at(
&repository.collection_id,
&repository.tenant_id,
&repository.head_sha,
) {
let removed_by_operator = !self
.repo_path(&repository.collection_id, &repository.tenant_id)
.join(".git")
.exists();
if !removed_by_operator {
continue;
}
tracing::info!(
collection_id = %repository.collection_id,
tenant_id = %repository.tenant_id,
"locked repository was removed locally, cloning it afresh from the master"
);
self.unlock(&repository.collection_id, &repository.tenant_id);
self.state
.repository_index
.remove(&repository.collection_id, &repository.tenant_id);
}
stale += 1;
self.pending.insert(
key,
(
repository.collection_id.clone(),
repository.tenant_id.clone(),
SyncTarget::At {
head_sha: repository.head_sha.clone(),
},
),
);
}
if !listing.complete {
tracing::warn!("master listing is incomplete, deletions will not be inferred from it");
} else {
let deletions: Vec<(String, String, String)> = local
.keys()
.filter(|key| !remote_keys.contains(*key))
.filter_map(|key| {
key.split_once('/').map(|(collection_id, tenant_id)| {
(
key.clone(),
collection_id.to_string(),
tenant_id.to_string(),
)
})
})
.collect();
let mass_deletion = self.replication.deletion_guard
&& local.len() >= DELETION_GUARD_MINIMUM_HELD
&& deletions.len() * 2 > local.len();
if mass_deletion {
let new = self.state.issues.raise(
ISSUE_DELETION_REFUSED,
Issue::DeletionRefused {
would_delete: deletions.len(),
held: local.len(),
since: chrono::Utc::now().timestamp(),
},
);
if new {
tracing::error!(
would_delete = deletions.len(),
held = local.len(),
master = %self.master_url_display,
"master listing would delete more than half of this replica's repositories; \
refusing the deletions and keeping every local copy until an operator intervenes \
(set replication.deletion_guard = false and restart to accept them)"
);
} else {
tracing::debug!(
would_delete = deletions.len(),
held = local.len(),
"master listing still asks for a mass deletion, still refusing"
);
}
} else {
if self.state.issues.clear(ISSUE_DELETION_REFUSED) {
tracing::info!(
"master listing no longer asks for a mass deletion, deletions resume"
);
}
for (key, collection_id, tenant_id) in deletions {
self.pending
.insert(key, (collection_id, tenant_id, SyncTarget::Deleted));
}
}
}
let status = &self.state.replica_status;
status.set_repositories(local.len());
status.set_last_reconcile(chrono::Utc::now().timestamp());
status.record_master_contact();
tracing::debug!(
remote_repositories = listing.repositories.len(),
local_repositories = local.len(),
stale = stale,
pending = self.pending.len(),
"replication reconcile complete"
);
self.refresh_master_health().await;
Ok(())
}
async fn refresh_master_health(&self) {
let url = format!("{}{}/health", self.master_url, URL_PREFIX);
let fetched = self
.reporting_request(&self.transfer_client, &url)
.send()
.await;
let response = match fetched {
Ok(response) if response.status().is_success() => response,
Ok(response) => {
tracing::debug!(status = %response.status(), "master health request rejected");
return;
}
Err(err) => {
tracing::debug!(err = %err, "master health request failed");
return;
}
};
match response.json::<ReplicationHealth>().await {
Ok(health) => {
self.state
.replica_status
.record_master_health(Some(health.node.node_id), health.replicas);
}
Err(err) => {
tracing::debug!(err = %err, "master health response is not valid");
}
}
}
async fn drain_pending(self: &Arc<Self>) -> SyncPass {
if !self.state.replica_status.identity_verified() {
if !self.pending.is_empty() {
tracing::debug!(
pending = self.pending.len(),
"holding replication catch-up until the master's identity is verified"
);
}
return SyncPass::default();
}
let targets: Vec<(String, (String, String, SyncTarget))> = self
.pending
.iter()
.map(|entry| (entry.key().clone(), entry.value().clone()))
.collect();
if targets.is_empty() {
self.state.replica_status.set_pending(0);
return SyncPass::default();
}
self.state.replica_status.set_pending(targets.len());
tracing::info!(
repositories = targets.len(),
"replication catch-up starting"
);
let semaphore = Arc::new(Semaphore::new(self.replication.parallelism));
let succeeded = Arc::new(AtomicUsize::new(0));
let locked = Arc::new(AtomicUsize::new(0));
let mut tasks = tokio::task::JoinSet::new();
let mut attempted = 0_usize;
for (key, (collection_id, tenant_id, target)) in targets {
self.pending.remove(&key);
attempted += 1;
let permit = semaphore.clone().acquire_owned().await;
if permit.is_err() {
break;
}
let follower = Arc::clone(self);
let succeeded = succeeded.clone();
let locked = locked.clone();
tasks.spawn(async move {
let _permit = permit;
match follower
.sync_repository(&collection_id, &tenant_id, target)
.await
{
SyncOutcome::Synced => {
succeeded.fetch_add(1, Ordering::Relaxed);
}
SyncOutcome::Locked => {
locked.fetch_add(1, Ordering::Relaxed);
}
SyncOutcome::Failed => {}
}
});
}
while tasks.join_next().await.is_some() {}
self.state.replica_status.set_pending(self.pending.len());
let pass = SyncPass {
attempted,
succeeded: succeeded.load(Ordering::Relaxed),
locked: locked.load(Ordering::Relaxed),
};
tracing::info!(
repositories = pass.attempted,
succeeded = pass.succeeded,
locked = pass.locked,
"replication catch-up finished"
);
pass
}
async fn sync_repository(
&self,
collection_id: &str,
tenant_id: &str,
target: SyncTarget,
) -> SyncOutcome {
let head_sha = match target {
SyncTarget::Deleted => {
self.delete_repository(collection_id, tenant_id).await;
return SyncOutcome::Synced;
}
SyncTarget::At { head_sha } => head_sha,
};
match self
.fetch_and_apply(collection_id, tenant_id, &head_sha)
.await
{
Ok(SyncOutcome::Synced) => {
self.unlock(collection_id, tenant_id);
SyncOutcome::Synced
}
Ok(outcome) => outcome,
Err(err) => {
tracing::warn!(
collection_id = %collection_id,
tenant_id = %tenant_id,
err = %err,
"replication sync failed, will retry on the next pass"
);
self.pending.insert(
format!("{}/{}", collection_id, tenant_id),
(
collection_id.to_string(),
tenant_id.to_string(),
SyncTarget::At { head_sha },
),
);
SyncOutcome::Failed
}
}
}
async fn fetch_and_apply(
&self,
collection_id: &str,
tenant_id: &str,
head_sha: &str,
) -> Result<SyncOutcome, String> {
let repo_path = self.repo_path(collection_id, tenant_id);
let probe_path = repo_path.clone();
let probe_sha = head_sha.to_string();
let (have, relation) = run_blocking(move || {
Ok((
GitReplication::head_sha(&probe_path),
GitReplication::relation_to(&probe_path, &probe_sha),
))
})
.await
.map_err(|err| err.to_string())?;
match relation {
HeadRelation::Same => return Ok(SyncOutcome::Synced),
HeadRelation::Ahead { local } => {
return Ok(self.lock_ahead(collection_id, tenant_id, &local, head_sha));
}
HeadRelation::Diverged { local } => {
return Ok(self.lock_diverged(collection_id, tenant_id, &local, head_sha));
}
HeadRelation::Unknown => {}
}
let (pack_path, pack_head_sha) = self
.download_pack(collection_id, tenant_id, have.as_deref())
.await?;
let apply_head = pack_head_sha.unwrap_or_else(|| head_sha.to_string());
let lock_key = format!("{}/{}", collection_id, tenant_id);
let lock = self.state.get_repo_lock(&lock_key);
let _lock_guard = lock.lock().await;
let apply_repo_path = repo_path.clone();
let apply_pack_path = pack_path.clone();
let checkout_files = self.state.config.server.checkout_files;
let outcome = run_blocking(move || {
GitReplication::apply_pack(
&apply_repo_path,
&apply_pack_path,
&apply_head,
checkout_files,
)
})
.await;
let _ = std::fs::remove_file(&pack_path);
match outcome.map_err(|err| err.to_string())? {
PackApply::FastForwarded { from, to } => {
tracing::info!(
collection_id = %collection_id,
tenant_id = %tenant_id,
from = %from.unwrap_or_else(|| "(new)".to_string()),
to = %to,
"replicated"
);
self.state
.maintenance
.schedule(&lock_key, repo_path, lock.clone());
self.state
.replication
.repository_updated(collection_id, tenant_id, &to);
Ok(SyncOutcome::Synced)
}
PackApply::UpToDate => Ok(SyncOutcome::Synced),
PackApply::Ahead { local, remote } => {
Ok(self.lock_ahead(collection_id, tenant_id, &local, &remote))
}
PackApply::Diverged { local, remote } => {
Ok(self.lock_diverged(collection_id, tenant_id, &local, &remote))
}
}
}
fn lock_ahead(
&self,
collection_id: &str,
tenant_id: &str,
local: &str,
remote: &str,
) -> SyncOutcome {
tracing::error!(
collection_id = %collection_id,
tenant_id = %tenant_id,
local = %local,
remote = %remote,
master = %self.master_url_display,
"replica is AHEAD of its master for this repository (the announced head is an ancestor of the local one); \
keeping and serving the local copy, replication of this repository is suspended until the master moves past it \
or an operator removes the local copy — see REPLICATION.md"
);
self.state.issues.raise(
&Issues::repository_key(collection_id, tenant_id),
Issue::ReplicaAhead {
collection_id: collection_id.to_string(),
tenant_id: tenant_id.to_string(),
local: local.to_string(),
remote: remote.to_string(),
since: chrono::Utc::now().timestamp(),
},
);
SyncOutcome::Locked
}
fn lock_diverged(
&self,
collection_id: &str,
tenant_id: &str,
local: &str,
remote: &str,
) -> SyncOutcome {
tracing::error!(
collection_id = %collection_id,
tenant_id = %tenant_id,
local = %local,
remote = %remote,
master = %self.master_url_display,
"replica history DIVERGED from its master for this repository (neither head descends from the other); \
keeping and serving the local copy, replication of this repository is suspended until an operator \
decides which history to keep — see REPLICATION.md"
);
self.state.issues.raise(
&Issues::repository_key(collection_id, tenant_id),
Issue::HistoryDiverged {
collection_id: collection_id.to_string(),
tenant_id: tenant_id.to_string(),
local: local.to_string(),
remote: remote.to_string(),
since: chrono::Utc::now().timestamp(),
},
);
SyncOutcome::Locked
}
fn unlock(&self, collection_id: &str, tenant_id: &str) {
if self
.state
.issues
.clear(&Issues::repository_key(collection_id, tenant_id))
{
tracing::info!(
collection_id = %collection_id,
tenant_id = %tenant_id,
"repository converged again, replication lock lifted"
);
}
}
fn is_locked_at(&self, collection_id: &str, tenant_id: &str, announced: &str) -> bool {
match self
.state
.issues
.get(&Issues::repository_key(collection_id, tenant_id))
{
Some(Issue::ReplicaAhead { remote, .. })
| Some(Issue::HistoryDiverged { remote, .. }) => remote == announced,
_ => false,
}
}
async fn download_pack(
&self,
collection_id: &str,
tenant_id: &str,
have: Option<&str>,
) -> Result<(PathBuf, Option<String>), String> {
let mut url = format!(
"{}{}/{}/{}/pack",
self.master_url, URL_PREFIX, collection_id, tenant_id
);
if let Some(have) = have {
url.push_str(&format!("?have={}", have));
}
let mut response = self
.request(&self.pack_client, &url)
.send()
.await
.map_err(|err| format!("pack request failed: {}", err))?;
if !response.status().is_success() {
return Err(format!("pack request returned {}", response.status()));
}
let pack_head_sha = response
.headers()
.get(HEAD_SHA_HEADER)
.and_then(|value| value.to_str().ok())
.and_then(|value| validate::commit_sha(value).ok())
.map(str::to_string);
let incoming_directory = self.state.config.server.repos_path.join(INCOMING_DIRECTORY);
std::fs::create_dir_all(&incoming_directory)
.map_err(|err| format!("cannot create incoming directory: {}", err))?;
let sequence = self.download_sequence.fetch_add(1, Ordering::Relaxed);
let pack_path =
incoming_directory.join(format!("{}_{}_{}.pack", collection_id, tenant_id, sequence));
let mut pack_file = tokio::fs::File::create(&pack_path)
.await
.map_err(|err| format!("cannot create pack file: {}", err))?;
let mut written = 0_u64;
loop {
let chunk = response
.chunk()
.await
.map_err(|err| format!("pack download failed: {}", err))?;
let Some(chunk) = chunk else {
break;
};
written += chunk.len() as u64;
tokio::io::AsyncWriteExt::write_all(&mut pack_file, &chunk)
.await
.map_err(|err| format!("cannot write pack file: {}", err))?;
}
tokio::io::AsyncWriteExt::flush(&mut pack_file)
.await
.map_err(|err| format!("cannot flush pack file: {}", err))?;
tracing::debug!(
collection_id = %collection_id,
tenant_id = %tenant_id,
bytes = written,
incremental = have.is_some(),
"replication pack downloaded"
);
Ok((pack_path, pack_head_sha))
}
async fn delete_repository(&self, collection_id: &str, tenant_id: &str) {
let repo_path = self.repo_path(collection_id, tenant_id);
if !repo_path.exists() {
return;
}
let lock_key = format!("{}/{}", collection_id, tenant_id);
let lock = self.state.get_repo_lock(&lock_key);
let _lock_guard = lock.lock().await;
match tokio::fs::remove_dir_all(&repo_path).await {
Ok(()) => {
self.state.maintenance.cancel(&lock_key);
self.state
.replication
.repository_deleted(collection_id, tenant_id);
tracing::info!(
collection_id = %collection_id,
tenant_id = %tenant_id,
"replicated tenant deletion"
);
}
Err(err) => {
tracing::error!(
collection_id = %collection_id,
tenant_id = %tenant_id,
err = %err,
"failed to remove replicated tenant"
);
}
}
}
async fn fetch_state(&self) -> Result<RepositoryListing, String> {
let url = format!("{}{}/state", self.master_url, URL_PREFIX);
let response = self
.reporting_request(&self.transfer_client, &url)
.send()
.await
.map_err(|err| format!("state request failed: {}", err))?;
if !response.status().is_success() {
return Err(format!("state request returned {}", response.status()));
}
response
.json::<RepositoryListing>()
.await
.map_err(|err| format!("state response is not valid: {}", err))
}
async fn run_event_stream(self: Arc<Self>) {
let url = format!("{}{}/events", self.master_url, URL_PREFIX);
let mut backoff_ms = self.replication.reconnect_backoff_ms;
let mut collision_since: Option<Instant> = None;
loop {
let attempt = self.request(&self.stream_client, &url).send().await;
match attempt {
Ok(response) if response.status().is_success() => {
tracing::info!(master = %self.master_url_display, "replication notification stream connected");
backoff_ms = self.replication.reconnect_backoff_ms;
collision_since = None;
if self.state.issues.clear(ISSUE_NODE_ID_COLLISION) {
tracing::info!(node_id = %self.node_id, "node id collision cleared");
}
self.state.replica_status.set_stream_connected(true);
self.request_full_reconcile();
self.consume_events(response).await;
self.state.replica_status.set_stream_connected(false);
tracing::warn!("replication notification stream closed");
}
Ok(response) if response.status() == reqwest::StatusCode::CONFLICT => {
let since = *collision_since.get_or_insert_with(Instant::now);
if since.elapsed().as_secs() >= COLLISION_REPORT_AFTER_SECS {
tracing::error!(
node_id = %self.node_id,
master = %self.master_url_display,
"master refused the notification stream: another process is connected under this node id; \
still converging by polling, but every replica needs a unique replication.node_id"
);
self.state.issues.raise(
ISSUE_NODE_ID_COLLISION,
Issue::NodeIdCollision {
node_id: self.node_id.clone(),
since: chrono::Utc::now().timestamp(),
},
);
} else {
tracing::warn!(
node_id = %self.node_id,
master = %self.master_url_display,
"master still holds a stream under this node id, retrying shortly \
(expected for a moment after this replica restarts)"
);
}
}
Ok(response) => {
tracing::warn!(
status = %response.status(),
"replication notification stream rejected"
);
}
Err(err) => {
tracing::warn!(err = %err, "replication notification stream unreachable");
}
}
self.state.replica_status.set_stream_connected(false);
sleep(Duration::from_millis(backoff_ms)).await;
backoff_ms = (backoff_ms * 2).min(MAXIMUM_RECONNECT_BACKOFF_MS);
}
}
async fn consume_events(&self, mut response: reqwest::Response) {
let mut buffer = String::new();
loop {
let chunk = match response.chunk().await {
Ok(Some(chunk)) => chunk,
Ok(None) => break,
Err(err) => {
tracing::debug!(err = %err, "replication stream read failed");
break;
}
};
buffer.push_str(&String::from_utf8_lossy(&chunk));
while let Some(newline) = buffer.find('\n') {
let line = buffer[..newline].trim().to_string();
buffer.drain(..=newline);
if line.is_empty() {
continue;
}
match serde_json::from_str::<ReplicationEvent>(&line) {
Ok(event) => {
if !self.handle_event(event) {
return;
}
}
Err(err) => {
tracing::debug!(err = %err, "ignoring unrecognised replication frame")
}
}
}
}
}
fn handle_event(&self, event: ReplicationEvent) -> bool {
match event {
ReplicationEvent::Hello {
protocol,
node_id,
identity,
} => {
if protocol != PROTOCOL_VERSION {
tracing::warn!(
master_protocol = protocol,
our_protocol = PROTOCOL_VERSION,
"master speaks a different replication protocol"
);
}
tracing::debug!(master = %node_id, protocol = protocol, "master identified itself");
if identity.is_some() {
if let Err(err) = self.verify_master_identity(identity.as_deref(), false) {
tracing::warn!(err = %err, "closing notification stream");
return false;
}
}
self.state.replica_status.record_master_identity(node_id);
}
ReplicationEvent::Heartbeat => {}
ReplicationEvent::RepositoryUpdated {
collection_id,
tenant_id,
head_sha,
} => {
if let Err(reason) = Self::validate_entry(&collection_id, &tenant_id, &head_sha) {
tracing::warn!(reason = %reason, "ignoring invalid repository.updated frame");
return true;
}
let key = format!("{}/{}", collection_id, tenant_id);
self.pending
.insert(key, (collection_id, tenant_id, SyncTarget::At { head_sha }));
self.wake.notify_one();
}
ReplicationEvent::RepositoryDeleted {
collection_id,
tenant_id,
} => {
if let Err(reason) = Self::validate_identifiers(&collection_id, &tenant_id) {
tracing::warn!(reason = %reason, "ignoring invalid repository.deleted frame");
return true;
}
tracing::debug!(
collection_id = %collection_id,
tenant_id = %tenant_id,
"repository.deleted frame received, reconciling to confirm it"
);
self.request_full_reconcile();
}
}
true
}
fn request_full_reconcile(&self) {
self.full_reconcile_requested.store(true, Ordering::SeqCst);
self.wake.notify_one();
}
fn verify_master_identity(&self, stated: Option<&str>, may_pin: bool) -> Result<(), String> {
let status = &self.state.replica_status;
let outcome = self.check_master_identity(stated, may_pin);
match &outcome {
Ok(()) => {
status.set_identity_verified(true);
if self.state.issues.clear(ISSUE_IDENTITY_MISMATCH) {
tracing::info!("master states the pinned identity again, syncing resumes");
}
}
Err(err) => {
status.set_identity_verified(false);
status.record_master_error(err.clone());
tracing::error!(err = %err, "refusing to sync from this master");
if let (Some(pinned), Some(stated)) = (self.state.identity.current(), stated) {
if pinned != stated {
self.state.issues.raise(
ISSUE_IDENTITY_MISMATCH,
Issue::IdentityMismatch {
pinned,
stated: stated.to_string(),
since: chrono::Utc::now().timestamp(),
},
);
}
}
}
}
outcome
}
fn check_master_identity(&self, stated: Option<&str>, may_pin: bool) -> Result<(), String> {
let Some(stated) = stated else {
return Err(format!(
"master {} stated no replication identity; a node that cannot say which data set it serves is not followed",
self.master_url_display
));
};
validate::replication_identity(stated).map_err(|err| {
format!(
"master {} stated an invalid identity: {}",
self.master_url_display, err
)
})?;
let identity = &self.state.identity;
match identity.current() {
Some(pinned) if pinned == stated => Ok(()),
Some(pinned) => {
let (master_node_id, ..) = self.state.replica_status.master_snapshot();
Err(format!(
"master identity mismatch: this replica ({}) is pinned to {} in {} but the master {} at {} states {}; \
refusing to sync. If the master was legitimately rebuilt or replaced, stop this replica, \
delete {} and restart it to pair with the new master",
self.node_id,
pinned,
identity.path().display(),
master_node_id.as_deref().unwrap_or("(unknown)"),
self.master_url_display,
stated,
identity.path().display(),
))
}
None if may_pin => identity.pin(stated),
None => Ok(()),
}
}
fn validate_identifiers(collection_id: &str, tenant_id: &str) -> Result<(), String> {
validate::collection_id(collection_id).map_err(|err| format!("collection id: {}", err))?;
validate::tenant_id(tenant_id).map_err(|err| format!("tenant id: {}", err))?;
Ok(())
}
fn validate_entry(collection_id: &str, tenant_id: &str, head_sha: &str) -> Result<(), String> {
Self::validate_identifiers(collection_id, tenant_id)?;
validate::commit_sha(head_sha).map_err(|err| format!("head sha: {}", err))?;
Ok(())
}
fn request(&self, client: &Client, url: &str) -> reqwest::RequestBuilder {
client
.get(url)
.bearer_auth(&self.replication.secret)
.header(NODE_ID_HEADER, &self.node_id)
.header(INSTANCE_HEADER, &self.instance)
.header(PROTOCOL_HEADER, PROTOCOL_VERSION.to_string())
}
fn reporting_request(&self, client: &Client, url: &str) -> reqwest::RequestBuilder {
let status = &self.state.replica_status;
self.request(client, url)
.header(REPOSITORIES_HEADER, status.repositories().to_string())
.header(PENDING_HEADER, status.pending().to_string())
.header(SYNC_HEADER, status.sync_status().as_str())
}
fn repo_path(&self, collection_id: &str, tenant_id: &str) -> PathBuf {
self.state
.config
.server
.repos_path
.join(collection_id)
.join(tenant_id)
}
}
pub fn build_health(state: &AppState, repositories: usize) -> ReplicationHealth {
let now = chrono::Utc::now().timestamp();
let server = &state.config.server;
let issues = state.issues.all();
let Some(replication) = &state.config.replication else {
let node_id = format!("{}:{}", server.host, server.port);
return ReplicationHealth {
protocol: PROTOCOL_VERSION,
status: NodeStatus::Healthy.as_str().to_string(),
issues,
node: NodeHealth {
node_id: node_id.clone(),
role: "standalone".to_string(),
identity: None,
repositories,
},
master: MasterHealth {
node_id: Some(node_id),
url: None,
reachable: true,
last_contact_at: Some(now),
last_error: None,
},
replicas: Vec::new(),
replica: None,
observed_at: now,
replicas_observed_at: Some(now),
};
};
let node_id = replication.node_id().to_string();
if !replication.is_replica() {
state.replica_registry.expire_collisions(&state.issues, now);
let issues = state.issues.all();
let replicas = state.replica_registry.roster();
let status = master_status(&replicas, issues.is_empty(), now);
return ReplicationHealth {
protocol: PROTOCOL_VERSION,
status: status.as_str().to_string(),
issues,
node: NodeHealth {
node_id: node_id.clone(),
role: "master".to_string(),
identity: state.identity.current(),
repositories,
},
master: MasterHealth {
node_id: Some(node_id),
url: None,
reachable: true,
last_contact_at: Some(now),
last_error: None,
},
replicas,
replica: None,
observed_at: now,
replicas_observed_at: Some(now),
};
}
let status = &state.replica_status;
let (master_node_id, replicas, replicas_observed_at, last_contact_at, last_error) =
status.master_snapshot();
let sync = status.sync_status();
let node_status = match sync {
SyncStatus::Halted => NodeStatus::Halted,
SyncStatus::Stalled => NodeStatus::Degraded,
SyncStatus::Synced | SyncStatus::Lagging if !status.is_bootstrapped() => {
NodeStatus::Degraded
}
SyncStatus::Synced | SyncStatus::Lagging => NodeStatus::Healthy,
};
ReplicationHealth {
protocol: PROTOCOL_VERSION,
status: node_status.as_str().to_string(),
issues,
node: NodeHealth {
node_id,
role: "replica".to_string(),
identity: state.identity.current(),
repositories,
},
master: MasterHealth {
node_id: master_node_id,
url: replication.master_url.as_deref().map(redact_url),
reachable: last_error.is_none() && last_contact_at.is_some(),
last_contact_at,
last_error,
},
replicas,
replica: Some(FollowerHealth {
state: if status.is_bootstrapped() {
"ready".to_string()
} else {
"bootstrapping".to_string()
},
sync: sync.as_str().to_string(),
stream_connected: status.stream_connected(),
last_reconcile_at: status.last_reconcile(),
last_success_at: status.last_success(),
pending_repositories: status.pending(),
locked_repositories: status.locked_repositories(),
consecutive_failures: status.consecutive_failures(),
}),
observed_at: now,
replicas_observed_at,
}
}
fn master_status(replicas: &[ReplicaPresence], no_issues: bool, now: i64) -> NodeStatus {
if !no_issues {
return NodeStatus::Halted;
}
let mut status = NodeStatus::Healthy;
for replica in replicas {
let reported = replica.sync.as_deref().and_then(SyncStatus::parse);
let verdict = match reported {
Some(SyncStatus::Halted) => NodeStatus::Halted,
Some(SyncStatus::Stalled) => NodeStatus::Degraded,
_ => {
let silent = replica
.last_contact_at
.map(|at| now - at > REPLICA_SILENT_SECS)
.unwrap_or(true);
if !replica.stream_connected && silent {
NodeStatus::Degraded
} else {
NodeStatus::Healthy
}
}
};
status = status.max(verdict);
}
status
}
pub fn cleanup_incoming_packs(repos_root: &Path) {
let incoming_directory = repos_root.join(INCOMING_DIRECTORY);
if !incoming_directory.exists() {
return;
}
if let Err(err) = std::fs::remove_dir_all(&incoming_directory) {
tracing::warn!(
path = %incoming_directory.display(),
err = %err,
"failed to clear abandoned replication downloads"
);
}
}