Skip to content

Commit 5eedde8

Browse files
committed
feat: refactor the be http response
1 parent b94af11 commit 5eedde8

File tree

7 files changed

+209
-102
lines changed

7 files changed

+209
-102
lines changed

src/tools/be/be_vars.rs

Lines changed: 11 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1+
use super::BeResponseHandler;
2+
use super::be_http_client;
13
use crate::config::Config;
24
use crate::error::{CliError, Result};
3-
use crate::tools::common::be_webserver;
45
use crate::tools::{ExecutionResult, Tool};
56
use crate::ui;
67
use dialoguer::{Input, theme::ColorfulTheme};
7-
use std::path::PathBuf;
88

99
/// Tool to query BE configuration variables
1010
pub struct BeVarsTool;
@@ -28,13 +28,16 @@ impl Tool for BeVarsTool {
2828
"Querying BE for variables matching: '{variable_name}'"
2929
));
3030

31-
let result = be_webserver::request_be_webserver_port("/varz", Some(&variable_name));
32-
handle_query_result(&variable_name, result);
31+
let result = be_http_client::request_be_webserver_port("/varz", Some(&variable_name));
3332

34-
Ok(ExecutionResult {
35-
output_path: PathBuf::from("console_output"),
36-
message: format!("Variable query completed for: {variable_name}"),
37-
})
33+
let handler = BeResponseHandler {
34+
success_message: "Query completed!",
35+
empty_warning: "No variables found matching '{}'.",
36+
error_context: "Failed to query BE",
37+
tips: "Ensure the BE service is running and accessible.",
38+
};
39+
40+
handler.handle_console_result(result, &variable_name)
3841
}
3942

4043
fn requires_pid(&self) -> bool {
@@ -56,22 +59,3 @@ fn prompt_for_variable_name() -> Result<String> {
5659
Ok(input)
5760
}
5861
}
59-
60-
fn handle_query_result(variable_name: &str, result: Result<String>) {
61-
match result {
62-
Ok(output) => {
63-
ui::print_success("Query completed!");
64-
println!();
65-
ui::print_info("Results:");
66-
if output.is_empty() {
67-
ui::print_warning(&format!("No variables found matching '{variable_name}'."));
68-
} else {
69-
println!("{output}");
70-
}
71-
}
72-
Err(e) => {
73-
ui::print_error(&format!("Failed to query BE: {e}."));
74-
ui::print_info("Tips: Ensure the BE service is running and accessible.");
75-
}
76-
}
77-
}

src/tools/be/mod.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
mod be_vars;
2+
mod be_http_client;
23
mod jmap;
3-
mod pipeline_tasks_tool;
4+
mod pipeline_tasks;
45
mod pstack;
6+
mod response_handler;
57

68
pub use be_vars::BeVarsTool;
79
pub use jmap::{JmapDumpTool, JmapHistoTool};
8-
pub use pipeline_tasks_tool::PipelineTasksTool;
10+
pub use pipeline_tasks::PipelineTasksTool;
911
pub use pstack::PstackTool;
12+
pub use response_handler::BeResponseHandler;

src/tools/be/pipeline_tasks.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
use super::BeResponseHandler;
2+
use super::be_http_client;
3+
use crate::config::Config;
4+
use crate::error::Result;
5+
use crate::tools::{ExecutionResult, Tool};
6+
use crate::ui;
7+
8+
/// Tool to fetch running pipeline tasks from BE node
9+
pub struct PipelineTasksTool;
10+
11+
impl Tool for PipelineTasksTool {
12+
fn name(&self) -> &str {
13+
"pipeline-tasks"
14+
}
15+
16+
fn description(&self) -> &str {
17+
"Get running pipeline tasks from BE node"
18+
}
19+
20+
fn execute(&self, config: &Config, _pid: u32) -> Result<ExecutionResult> {
21+
ui::print_info("Fetching running pipeline tasks from BE...");
22+
23+
let result = be_http_client::request_be_webserver_port("/api/running_pipeline_tasks", None);
24+
25+
let handler = BeResponseHandler {
26+
success_message: "Pipeline tasks fetched successfully!",
27+
empty_warning: "No running pipeline tasks found.",
28+
error_context: "Failed to fetch pipeline tasks",
29+
tips: "Ensure the BE service is running and accessible.",
30+
};
31+
32+
// First check if we have a result
33+
match &result {
34+
Ok(output) => {
35+
if output.len() < 100 || output.lines().count() <= 3 {
36+
return handler.handle_console_result(result, "pipeline tasks");
37+
}
38+
39+
// Otherwise save to file
40+
config.ensure_output_dir()?;
41+
handler.handle_file_result(config, result, "pipeline_tasks", get_summary)
42+
},
43+
Err(_) => {
44+
// For errors, just use the standard error handling
45+
handler.handle_console_result(result, "pipeline tasks")
46+
}
47+
}
48+
}
49+
50+
fn requires_pid(&self) -> bool {
51+
false
52+
}
53+
}
54+
55+
/// Get a summary of the response data for display in the console
56+
fn get_summary(data: &str) -> String {
57+
if data.trim().is_empty() {
58+
return "No running pipeline tasks found.".to_string();
59+
}
60+
61+
// Simple summary: show first few lines
62+
let preview_lines: Vec<&str> = data.lines().take(10).collect();
63+
let preview = preview_lines.join("\n");
64+
65+
if data.lines().count() > 10 {
66+
format!("{}\n... (more content in output file)", preview)
67+
} else {
68+
preview
69+
}
70+
}

src/tools/be/pipeline_tasks_tool.rs

Lines changed: 0 additions & 72 deletions
This file was deleted.

src/tools/be/response_handler.rs

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
use crate::config::Config;
2+
use crate::error::Result;
3+
use crate::tools::ExecutionResult;
4+
use crate::ui;
5+
use std::fs;
6+
use std::path::PathBuf;
7+
use chrono::Utc;
8+
9+
/// Configuration for handling BE API responses
10+
pub struct BeResponseHandler<'a> {
11+
pub success_message: &'a str,
12+
pub empty_warning: &'a str,
13+
pub error_context: &'a str,
14+
pub tips: &'a str,
15+
}
16+
17+
impl<'a> BeResponseHandler<'a> {
18+
/// Handle response for console-only output (like be_vars)
19+
pub fn handle_console_result(
20+
&self,
21+
result: Result<String>,
22+
context: &str,
23+
) -> Result<ExecutionResult> {
24+
match result {
25+
Ok(output) => {
26+
ui::print_success(self.success_message);
27+
println!();
28+
ui::print_info("Results:");
29+
30+
if output.is_empty() {
31+
ui::print_warning(&self.empty_warning.replace("{}", context));
32+
} else {
33+
println!("{output}");
34+
}
35+
36+
Ok(ExecutionResult {
37+
output_path: PathBuf::from("console_output"),
38+
message: format!("Query completed for: {context}"),
39+
})
40+
}
41+
Err(e) => {
42+
ui::print_error(&format!("{}: {e}.", self.error_context));
43+
ui::print_info(&format!("Tips: {}", self.tips));
44+
Err(e)
45+
}
46+
}
47+
}
48+
49+
/// Handle response with file output (like pipeline_tasks)
50+
pub fn handle_file_result<F>(
51+
&self,
52+
config: &Config,
53+
result: Result<String>,
54+
file_prefix: &str,
55+
summary_fn: F,
56+
) -> Result<ExecutionResult>
57+
where
58+
F: Fn(&str) -> String,
59+
{
60+
match result {
61+
Ok(output) => {
62+
ui::print_success(self.success_message);
63+
println!();
64+
ui::print_info("Results:");
65+
66+
if output.trim().is_empty() {
67+
ui::print_warning(self.empty_warning);
68+
69+
Ok(ExecutionResult {
70+
output_path: PathBuf::from("console_output"),
71+
message: "No data found".to_string(),
72+
})
73+
} else {
74+
let timestamp = Utc::now().format("%Y%m%d_%H%M%S");
75+
76+
let filename = format!("{}_{}.txt", file_prefix, timestamp);
77+
let output_path = config.output_dir.join(filename);
78+
79+
fs::write(&output_path, &output)?;
80+
81+
println!("{}", summary_fn(&output));
82+
83+
let message = format!(
84+
"{} saved to {}",
85+
file_prefix.replace('_', " ").to_title_case(),
86+
output_path.display()
87+
);
88+
89+
Ok(ExecutionResult {
90+
output_path,
91+
message,
92+
})
93+
}
94+
}
95+
Err(e) => {
96+
ui::print_error(&format!("{}: {e}.", self.error_context));
97+
ui::print_info(&format!("Tips: {}", self.tips));
98+
Err(e)
99+
}
100+
}
101+
}
102+
}
103+
104+
trait ToTitleCase {
105+
fn to_title_case(&self) -> String;
106+
}
107+
108+
impl ToTitleCase for str {
109+
fn to_title_case(&self) -> String {
110+
self.split_whitespace()
111+
.map(|word| {
112+
let mut chars = word.chars();
113+
match chars.next() {
114+
None => String::new(),
115+
Some(first) => {
116+
first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase()
117+
}
118+
}
119+
})
120+
.collect::<Vec<_>>()
121+
.join(" ")
122+
}
123+
}

src/tools/common/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
pub mod be_webserver;
21
pub mod jmap;

0 commit comments

Comments
 (0)