use std::path::PathBuf;
use cheetah_string::CheetahString;
use clap::Parser;
use rocketmq_error::Result as CanonicalResult;
use rocketmq_model::common::config::TopicConfig;
use tokio::fs::File;
use tokio::io::AsyncReadExt;
use crate::commands::CommandExecute;
use rocketmq_admin_core::client_adapter::services::topic::TopicService;
use rocketmq_admin_core::client_adapter::services::topic::TopicTarget;
use rocketmq_admin_core::client_adapter::services::topic::UpdateTopicListRequest;
use rocketmq_admin_core::client_adapter::services::topic::UpdateTopicListResult;
#[derive(Parser)]
pub struct UpdateTopicListSubCommand {
#[arg(short = 'f', long)]
file: PathBuf,
#[arg(short = 'b', long, conflicts_with = "cluster")]
broker_addr: Option<String>,
#[arg(short = 'c', long, conflicts_with = "broker_addr")]
cluster: Option<String>,
#[arg(long)]
dry_run: bool,
}
impl UpdateTopicListSubCommand {
fn target(&self) -> CanonicalResult<TopicTarget> {
if let Some(broker) = &self.broker_addr {
return Ok(TopicTarget::Broker(CheetahString::from(broker.trim())));
}
if let Some(cluster) = &self.cluster {
return Ok(TopicTarget::Cluster(CheetahString::from(cluster.trim())));
}
Err(crate::errors::argument_invalid(
"a broker or cluster is required for command UpdateTopicList",
))
}
fn request(&self, topic_configs: Vec<TopicConfig>) -> CanonicalResult<UpdateTopicListRequest> {
UpdateTopicListRequest::try_new(self.target()?, topic_configs)
}
fn print_result(result: &UpdateTopicListResult) {
for broker_addr in &result.broker_addrs {
println!(
"submit batch of topic config to {} success, please check the result later",
broker_addr
);
}
}
}
impl CommandExecute for UpdateTopicListSubCommand {
async fn execute(
&self,
credentials: Option<rocketmq_admin_core::core::security::AdminCredentials>,
client_runtime: std::sync::Arc<rocketmq_admin_core::client_adapter::ClientRuntime>,
) -> rocketmq_error::Result<()> {
if !self.file.is_file() {
return Err(crate::errors::argument_invalid(
"the file path doesn't point to a valid file",
));
}
let mut topic_config_list_bytes = vec![];
File::open(&self.file)
.await
.map_err(|source| crate::errors::io_failed_by("open_topic_config_list", source))?
.read_to_end(&mut topic_config_list_bytes)
.await
.map_err(|source| crate::errors::io_failed_by("read_topic_config_list", source))?;
let topic_configs =
if let Ok(topic_configs) = serde_json::from_slice::<Vec<TopicConfig>>(&topic_config_list_bytes) {
topic_configs
} else if let Ok(topic_configs) = serde_yaml::from_slice::<Vec<TopicConfig>>(&topic_config_list_bytes) {
topic_configs
} else {
return Err(crate::errors::argument_invalid("the file isn't in json or yaml format"));
};
let result = TopicService::update_topic_config_list_by_request_with_credentials(
self.request(topic_configs)?,
credentials,
client_runtime,
)
.await?;
Self::print_result(&result);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn update_topic_list_sub_command_builds_broker_request() {
let command = UpdateTopicListSubCommand::try_parse_from([
"updateTopicList",
"-f",
"topics.json",
"-b",
" 127.0.0.1:10911 ",
])
.unwrap();
let request = command.request(vec![TopicConfig::default()]).unwrap();
assert_eq!(
request.target(),
&TopicTarget::Broker(CheetahString::from_static_str("127.0.0.1:10911"))
);
assert_eq!(request.topic_configs().len(), 1);
}
#[test]
fn update_topic_list_sub_command_builds_cluster_request() {
let command = UpdateTopicListSubCommand::try_parse_from([
"updateTopicList",
"-f",
"topics.json",
"-c",
" DefaultCluster ",
])
.unwrap();
let request = command.request(vec![TopicConfig::default()]).unwrap();
assert_eq!(
request.target(),
&TopicTarget::Cluster(CheetahString::from_static_str("DefaultCluster"))
);
assert_eq!(request.topic_configs().len(), 1);
}
#[test]
fn update_topic_list_sub_command_rejects_missing_target() {
let command = UpdateTopicListSubCommand::try_parse_from(["updateTopicList", "-f", "topics.json"]).unwrap();
assert!(command.request(vec![TopicConfig::default()]).is_err());
}
}