use std::fmt;
use serde::{Deserialize, Serialize};
use crate::{ArtifactFormat, RemoteRepository};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Disposition {
Existing,
Create,
Collision {
existing_format: String,
},
UnmappedFormat,
}
impl Disposition {
pub fn is_refusal(&self) -> bool {
matches!(
self,
Disposition::Collision { .. } | Disposition::UnmappedFormat
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepoPlan {
pub source_repo: String,
pub source_format: String,
pub target_repo: String,
pub target_format: String,
pub disposition: Disposition,
pub assets: u64,
pub bytes: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MigrationPlan {
pub repos: Vec<RepoPlan>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanRefused {
pub reasons: Vec<String>,
}
impl fmt::Display for PlanRefused {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "migration refused: {}", self.reasons.join("; "))
}
}
impl std::error::Error for PlanRefused {}
impl MigrationPlan {
pub fn to_create(&self) -> Vec<&RepoPlan> {
self.repos
.iter()
.filter(|r| r.disposition == Disposition::Create)
.collect()
}
pub fn existing(&self) -> Vec<&RepoPlan> {
self.repos
.iter()
.filter(|r| r.disposition == Disposition::Existing)
.collect()
}
pub fn refusals(&self) -> Vec<&RepoPlan> {
self.repos
.iter()
.filter(|r| r.disposition.is_refusal())
.collect()
}
pub fn total_assets(&self) -> u64 {
self.repos.iter().map(|r| r.assets).sum()
}
pub fn total_bytes(&self) -> u64 {
self.repos.iter().map(|r| r.bytes).sum()
}
pub fn refuse_collisions(&self) -> Result<(), PlanRefused> {
let reasons: Vec<String> = self
.repos
.iter()
.filter_map(|r| match &r.disposition {
Disposition::Collision { existing_format } => Some(format!(
"'{}' exists in holger as format '{}', but the source calls it '{}' \
(mapped: '{}') — refusing to create or write into a repository of a \
different format",
r.target_repo, existing_format, r.source_format, r.target_format
)),
Disposition::UnmappedFormat => Some(format!(
"'{}' has source format '{}', which holger has no repository format for",
r.source_repo, r.source_format
)),
_ => None,
})
.collect();
if reasons.is_empty() {
Ok(())
} else {
Err(PlanRefused { reasons })
}
}
pub fn dry_run_report(&self) -> String {
let mut out = String::new();
out.push_str("MIGRATION DRY RUN — nothing is created and no bytes move\n");
let create = self.to_create();
out.push_str(&format!("\nWOULD CREATE ({}):\n", create.len()));
if create.is_empty() {
out.push_str(" (none — every source repository already exists in holger)\n");
}
for r in &create {
out.push_str(&format!(
" + {} (holger format '{}', from source format '{}') — {} assets, {} bytes\n",
r.target_repo, r.target_format, r.source_format, r.assets, r.bytes
));
}
let existing = self.existing();
out.push_str(&format!(
"\nWOULD FILL, ALREADY EXISTS ({}):\n",
existing.len()
));
if existing.is_empty() {
out.push_str(" (none)\n");
}
for r in &existing {
out.push_str(&format!(
" = {} (holger format '{}') — {} assets, {} bytes\n",
r.target_repo, r.target_format, r.assets, r.bytes
));
}
let refusals = self.refusals();
if !refusals.is_empty() {
out.push_str(&format!("\nREFUSED ({}):\n", refusals.len()));
if let Err(e) = self.refuse_collisions() {
for reason in e.reasons {
out.push_str(&format!(" ! {reason}\n"));
}
}
}
out.push_str(&format!(
"\nTOTAL: {} repositories, {} assets, {} bytes advertised by the source listing\n",
self.repos.len(),
self.total_assets(),
self.total_bytes()
));
if refusals.is_empty() {
out.push_str("This plan would RUN. Re-run without --dry-run to execute it.\n");
} else {
out.push_str("This migration plan is REFUSED and will not run until the refusals above are resolved.\n");
}
out
}
}
pub fn plan_one(
source: &RemoteRepository,
existing: &[RemoteRepository],
assets: u64,
bytes: u64,
) -> RepoPlan {
let target_repo = source.name.clone();
let mapped = ArtifactFormat::from_format_str(&source.format);
let (target_format, disposition) = match mapped {
None => (String::new(), Disposition::UnmappedFormat),
Some(fmt) => {
let config_key = fmt.home().config_key.to_string();
let found = existing.iter().find(|e| e.name == target_repo);
let disp = match found {
None => Disposition::Create,
Some(e) => {
match ArtifactFormat::from_format_str(&e.format) {
Some(existing_fmt) if existing_fmt == fmt => Disposition::Existing,
_ => Disposition::Collision {
existing_format: e.format.clone(),
},
}
}
};
(config_key, disp)
}
};
RepoPlan {
source_repo: source.name.clone(),
source_format: source.format.clone(),
target_repo,
target_format,
disposition,
assets,
bytes,
}
}
#[async_trait::async_trait]
pub trait MigrationSink: Send + Sync {
async fn already_has(
&self,
repository: &str,
path: &str,
want_sha256: Option<&str>,
) -> anyhow::Result<bool>;
async fn store(&self, repository: &str, path: &str, data: &[u8]) -> anyhow::Result<()>;
async fn create_repository(&self, repository: &str, format: &str) -> anyhow::Result<()>;
}
pub fn ron_declaration(repository: &str, format: &str) -> String {
format!(
"( ron_name: \"{repository}\", ron_repo_type: \"{format}\", \
ron_data_dir: Some(\"<data-root>/{repository}\"), ron_upstreams: [], ron_in: None, \
ron_out: Some(( ron_storage_endpoint: \"<storage>\", ron_exposed_endpoint: \"<endpoint>\" )) )"
)
}
pub fn cannot_create_repository(repository: &str, format: &str) -> String {
let declaration = ron_declaration(repository, format);
format!(
"repository '{repository}' does not exist on the destination and cannot be created \
while the server is running: holger wires its route table from its config at boot \
and it is immutable thereafter. Declare it and restart:\n \
{declaration}\n\
A dry run lists EVERY repository a migration would create, so the whole set can be \
declared in one pass before the move."
)
}
#[cfg(test)]
mod tests {
use super::*;
fn repo(name: &str, format: &str) -> RemoteRepository {
RemoteRepository {
name: name.to_string(),
format: format.to_string(),
repo_type: "hosted".to_string(),
url: None,
}
}
#[test]
fn an_unknown_target_name_is_created_in_the_mapped_format() {
let p = plan_one(&repo("libs-release", "maven2"), &[], 12, 340);
assert_eq!(p.disposition, Disposition::Create);
assert_eq!(p.target_repo, "libs-release");
assert_eq!(p.target_format, "maven3");
assert_eq!(p.assets, 12);
assert_eq!(p.bytes, 340);
}
#[test]
fn a_name_that_exists_in_the_same_format_is_filled_not_created() {
let p = plan_one(&repo("libs", "maven"), &[repo("libs", "maven3")], 1, 1);
assert_eq!(p.disposition, Disposition::Existing);
assert!(p.to_string_check());
}
#[test]
fn generic_and_raw_are_the_same_repository() {
let p = plan_one(&repo("drops", "generic"), &[repo("drops", "raw")], 0, 0);
assert_eq!(
p.disposition,
Disposition::Existing,
"Artifactory 'generic' IS holger 'raw'"
);
}
#[test]
fn a_name_that_exists_in_a_different_format_collides_and_the_plan_refuses() {
let p = plan_one(&repo("shared", "maven2"), &[repo("shared", "npm")], 5, 5);
assert_eq!(
p.disposition,
Disposition::Collision {
existing_format: "npm".into()
}
);
let plan = MigrationPlan { repos: vec![p] };
let err = plan
.refuse_collisions()
.expect_err("a collision must refuse the whole run");
assert!(
err.reasons[0].contains("different format"),
"{:?}",
err.reasons
);
}
#[test]
fn a_format_holger_cannot_serve_refuses_rather_than_guessing_raw() {
let p = plan_one(&repo("weird", "p2"), &[], 3, 3);
assert_eq!(p.disposition, Disposition::UnmappedFormat);
assert_eq!(
p.target_format, "",
"an unmapped format names no target format"
);
let plan = MigrationPlan { repos: vec![p] };
assert!(plan.refuse_collisions().is_err());
}
#[test]
fn the_creation_refusal_hands_over_a_declaration_that_names_both_words() {
let text = cannot_create_repository("libs", "maven3");
assert!(text.contains("ron_name: \"libs\""), "{text}");
assert!(text.contains("ron_repo_type: \"maven3\""), "{text}");
assert!(
text.contains("dry run"),
"it must point at the preview: {text}"
);
}
#[test]
fn the_refusal_embeds_the_very_same_declaration_the_ui_shows() {
let declaration = ron_declaration("libs", "maven3");
assert!(
declaration.starts_with("( ron_name: \"libs\""),
"{declaration}"
);
assert!(
cannot_create_repository("libs", "maven3").contains(&declaration),
"the refusal must quote the one renderer verbatim"
);
}
#[test]
fn the_dry_run_report_names_every_repository_it_would_create() {
let plan = MigrationPlan {
repos: vec![
plan_one(&repo("libs-release", "maven2"), &[], 10, 1000),
plan_one(&repo("pypi-local", "pypi"), &[], 4, 40),
plan_one(&repo("kept", "npm"), &[repo("kept", "npm")], 2, 20),
],
};
let text = plan.dry_run_report();
assert!(text.contains("WOULD CREATE (2)"), "{text}");
assert!(
text.contains("+ libs-release (holger format 'maven3'"),
"{text}"
);
assert!(text.contains("+ pypi-local (holger format 'pip'"), "{text}");
assert!(text.contains("= kept (holger format 'npm')"), "{text}");
assert!(
text.contains("TOTAL: 3 repositories, 16 assets, 1060 bytes"),
"{text}"
);
assert!(text.contains("would RUN"), "{text}");
assert_eq!(plan.to_create().len(), 2);
assert_eq!(plan.existing().len(), 1);
}
#[test]
fn a_refused_plan_says_so_in_its_report_and_never_says_it_would_run() {
let plan = MigrationPlan {
repos: vec![plan_one(
&repo("shared", "maven2"),
&[repo("shared", "npm")],
1,
1,
)],
};
let text = plan.dry_run_report();
assert!(text.contains("REFUSED (1)"), "{text}");
assert!(
!text.contains("would RUN"),
"a refused plan must never invite execution: {text}"
);
}
impl RepoPlan {
fn to_string_check(&self) -> bool {
!self.target_format.is_empty()
}
}
}