Skip to content

Commit

Permalink
rename sozu_command_lib::CommandResponse to Response
Browse files Browse the repository at this point in the history
rename CommandStatus to ResponseStatus
rename ResponseStatus::Error to Failure
rename CommandResponseContent to ResponseContent
  • Loading branch information
Keksoj committed Mar 13, 2023
1 parent 1421f6c commit a39d905
Show file tree
Hide file tree
Showing 7 changed files with 110 additions and 117 deletions.
31 changes: 13 additions & 18 deletions bin/src/acme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use acme_lib::{create_p384_key, persist::FilePersist, Directory, DirectoryUrl};
use anyhow::{bail, Context};
use mio::net::UnixStream;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use tiny_http::{Response, Server};
use tiny_http::{Response as HttpResponse, Server};

use sozu_command_lib::{
certificate::{
Expand All @@ -14,9 +14,7 @@ use sozu_command_lib::{
channel::Channel,
config::Config,
order::{AddCertificate, Order, RemoveBackend, ReplaceCertificate},
response::{
Backend, CommandResponse, CommandStatus, HttpFrontend, PathRule, Route, RulePosition,
},
response::{Backend, HttpFrontend, PathRule, Response, ResponseStatus, Route, RulePosition},
};

use crate::util;
Expand Down Expand Up @@ -91,7 +89,7 @@ pub fn main(

let tls_versions = vec![TlsVersion::TLSv1_2, TlsVersion::TLSv1_3];

let mut channel: Channel<Order, CommandResponse> = Channel::new(stream, 10000, 20000);
let mut channel: Channel<Order, Response> = Channel::new(stream, 10000, 20000);
channel
.blocking()
.with_context(|| "Could not block channel")?;
Expand Down Expand Up @@ -172,15 +170,15 @@ pub fn main(
info!("got request to URL: {}", request.url());
if request.url() == path {
if let Err(e) = request.respond(
Response::from_data(key_authorization.as_bytes()).with_status_code(200),
HttpResponse::from_data(key_authorization.as_bytes()).with_status_code(200),
) {
error!("Error responding with 200 to request: {}", e);
}
info!("challenge request answered");
// the challenge can be called multiple times
//return true;
} else if let Err(e) =
request.respond(Response::from_data(&b"not found"[..]).with_status_code(404))
} else if let Err(e) = request
.respond(HttpResponse::from_data(&b"not found"[..]).with_status_code(404))
{
error!("Error responding with 404 to request: {}", e);
}
Expand Down Expand Up @@ -283,7 +281,7 @@ fn generate_app_id(app_id: &str) -> String {
}

fn set_up_proxying(
channel: &mut Channel<Order, CommandResponse>,
channel: &mut Channel<Order, Response>,
frontend: &SocketAddr,
cluster_id: &str,
hostname: &str,
Expand Down Expand Up @@ -316,7 +314,7 @@ fn set_up_proxying(
}

fn remove_proxying(
channel: &mut Channel<Order, CommandResponse>,
channel: &mut Channel<Order, Response>,
frontend: &SocketAddr,
cluster_id: &str,
hostname: &str,
Expand Down Expand Up @@ -346,7 +344,7 @@ fn remove_proxying(
}

fn add_certificate(
channel: &mut Channel<Order, CommandResponse>,
channel: &mut Channel<Order, Response>,
frontend: &SocketAddr,
hostname: &str,
certificate_path: &str,
Expand Down Expand Up @@ -396,10 +394,7 @@ fn add_certificate(
.with_context(|| "Could not send the certificate order")
}

fn order_command(
channel: &mut Channel<Order, CommandResponse>,
order: Order,
) -> anyhow::Result<()> {
fn order_command(channel: &mut Channel<Order, Response>, order: Order) -> anyhow::Result<()> {
channel
.write_message(&order.clone())
.with_context(|| "Could not write message on the channel")?;
Expand All @@ -410,15 +405,15 @@ fn order_command(
.with_context(|| "Could not read response on channel")?;

match response.status {
CommandStatus::Processing => {
ResponseStatus::Processing => {
// do nothing here
// for other messages, we would loop over read_message
// until an error or ok message was sent
}
CommandStatus::Error => {
ResponseStatus::Failure => {
bail!("could not execute order: {}", response.message);
}
CommandStatus::Ok => {
ResponseStatus::Ok => {
// TODO: remove the pattern matching and only display the response message
match order {
Order::AddBackend(_) => {
Expand Down
32 changes: 16 additions & 16 deletions bin/src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ use sozu_command_lib::{
config::Config,
order::{InnerOrder, MetricsConfiguration, Order},
response::{
CommandResponse, CommandResponseContent, CommandStatus, Event, ProxyResponse,
ProxyResponseContent, ProxyResponseStatus, RunState,
Event, ProxyResponse, ProxyResponseContent, ProxyResponseStatus, Response, ResponseContent,
ResponseStatus, RunState,
},
scm_socket::{Listeners, ScmSocket},
state::ConfigState,
Expand All @@ -51,7 +51,7 @@ pub use worker::*;
enum CommandMessage {
ClientNew {
client_id: String,
sender: Sender<CommandResponse>, // to send things back to the client
sender: Sender<Response>, // to send things back to the client
},
ClientClose {
client_id: String,
Expand Down Expand Up @@ -85,13 +85,13 @@ pub enum Advancement {
// in which case Success caries the response data.
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Success {
ClientClose(String), // the client id
ClientNew(String), // the client id
DumpState(CommandResponseContent), // the cloned state
ClientClose(String), // the client id
ClientNew(String), // the client id
DumpState(ResponseContent), // the cloned state
HandledClientOrder,
ListFrontends(CommandResponseContent), // the list of frontends
ListListeners(CommandResponseContent), // the list of listeners
ListWorkers(CommandResponseContent),
ListFrontends(ResponseContent), // the list of frontends
ListListeners(ResponseContent), // the list of listeners
ListWorkers(ResponseContent),
LoadState(String, usize, usize), // state path, oks, errors
Logging(String), // new logging level
Metrics(MetricsConfiguration), // enable / disable / clear metrics on the proxy
Expand All @@ -101,10 +101,10 @@ pub enum Success {
// Metrics,
NotifiedClient(String), // client id
PropagatedWorkerEvent,
Query(CommandResponseContent),
Query(ResponseContent),
ReloadConfiguration(usize, usize), // ok, errors
SaveState(usize, String), // amount of written commands, path of the saved state
Status(CommandResponseContent), // Vec<WorkerInfo>
Status(ResponseContent), // Vec<WorkerInfo>
SubscribeEvent(String),
UpgradeMain(i32), // pid of the new main process
UpgradeWorker(u32), // worker id
Expand Down Expand Up @@ -189,7 +189,7 @@ pub struct CommandServer {
/// where the main loop receives messages
command_rx: Receiver<CommandMessage>,
/// All client loops. id -> cloned command_tx
clients: HashMap<String, Sender<CommandResponse>>,
clients: HashMap<String, Sender<Response>>,
/// handles to the workers as seen from the main process
workers: Vec<Worker>,
/// A map of requests sent to workers.
Expand Down Expand Up @@ -718,11 +718,11 @@ impl CommandServer {
let event: Event = proxy_event.into();
for client_id in self.event_subscribers.iter() {
if let Some(client_tx) = self.clients.get_mut(client_id) {
let event = CommandResponse::new(
let event = Response::new(
// response.id.to_string(),
CommandStatus::Processing,
ResponseStatus::Processing,
format!("{worker_id}"),
Some(CommandResponseContent::Event(event.clone())),
Some(ResponseContent::Event(event.clone())),
);
client_tx
.send(event)
Expand Down Expand Up @@ -916,7 +916,7 @@ async fn client_loop(
client_id: String,
stream: Async<UnixStream>,
mut command_tx: Sender<CommandMessage>,
mut client_rx: Receiver<CommandResponse>,
mut client_rx: Receiver<Response>,
) {
let read_stream = Arc::new(stream);
let mut write_stream = read_stream.clone();
Expand Down
38 changes: 19 additions & 19 deletions bin/src/command/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ use sozu_command_lib::{
order::{FrontendFilters, InnerOrder, MetricsConfiguration, Order, QueryClusterType},
parser::parse_several_commands,
response::{
AggregatedMetricsData, CommandResponse, CommandResponseContent, CommandStatus,
ListedFrontends, ListenersList, ProxyResponseContent, ProxyResponseStatus, QueryAnswer,
RunState, WorkerInfo,
AggregatedMetricsData, ListedFrontends, ListenersList, ProxyResponseContent,
ProxyResponseStatus, QueryAnswer, Response, ResponseContent, ResponseStatus, RunState,
WorkerInfo,
},
scm_socket::Listeners,
state::get_cluster_ids_by_domain,
Expand Down Expand Up @@ -152,9 +152,9 @@ impl CommandServer {
pub async fn dump_state(&mut self) -> anyhow::Result<Option<Success>> {
let state = self.state.clone();

Ok(Some(Success::DumpState(CommandResponseContent::State(
Box::new(state),
))))
Ok(Some(Success::DumpState(ResponseContent::State(Box::new(
state,
)))))
}

pub async fn load_state(
Expand Down Expand Up @@ -389,14 +389,14 @@ impl CommandServer {
}
}

Ok(Some(Success::ListFrontends(
CommandResponseContent::FrontendList(listed_frontends),
)))
Ok(Some(Success::ListFrontends(ResponseContent::FrontendList(
listed_frontends,
))))
}

fn list_listeners(&self) -> anyhow::Result<Option<Success>> {
Ok(Some(Success::ListListeners(
CommandResponseContent::ListenersList(ListenersList {
ResponseContent::ListenersList(ListenersList {
http_listeners: self.state.http_listeners.clone(),
https_listeners: self.state.https_listeners.clone(),
tcp_listeners: self.state.tcp_listeners.clone(),
Expand All @@ -417,7 +417,7 @@ impl CommandServer {

debug!("workers: {:#?}", workers);

Ok(Some(Success::ListWorkers(CommandResponseContent::Workers(
Ok(Some(Success::ListWorkers(ResponseContent::Workers(
workers,
))))
}
Expand Down Expand Up @@ -937,7 +937,7 @@ impl CommandServer {
return_success(
command_tx,
thread_client_id,
Success::Status(CommandResponseContent::Status(worker_info_vec)),
Success::Status(ResponseContent::Status(worker_info_vec)),
)
.await;
})
Expand Down Expand Up @@ -1118,19 +1118,19 @@ impl CommandServer {
&Order::QueryClustersHashes | &Order::QueryClusters(_) => {
let main = main_query_answer.unwrap(); // we should refactor to avoid this unwrap()
query_answers.insert(String::from("main"), main);
Success::Query(CommandResponseContent::Query(query_answers))
Success::Query(ResponseContent::Query(query_answers))
}
&Order::QueryCertificates(_) => {
info!("certificates query answer received: {:?}", query_answers);
Success::Query(CommandResponseContent::Query(query_answers))
Success::Query(ResponseContent::Query(query_answers))
}
Order::QueryMetrics(options) => {
debug!("metrics query answer received: {:?}", query_answers);

if options.list {
Success::Query(CommandResponseContent::Query(query_answers))
Success::Query(ResponseContent::Query(query_answers))
} else {
Success::Query(CommandResponseContent::Metrics(AggregatedMetricsData {
Success::Query(ResponseContent::Metrics(AggregatedMetricsData {
main: main_metrics,
workers: query_answers,
}))
Expand Down Expand Up @@ -1333,13 +1333,13 @@ impl CommandServer {
_ => None,
};

CommandResponse::new(CommandStatus::Ok, success_message, command_response_data)
Response::new(ResponseStatus::Ok, success_message, command_response_data)
}
Advancement::Processing(processing_message) => {
CommandResponse::new(CommandStatus::Processing, processing_message, None)
Response::new(ResponseStatus::Processing, processing_message, None)
}
Advancement::Error(error_message) => {
CommandResponse::new(CommandStatus::Error, error_message, None)
Response::new(ResponseStatus::Failure, error_message, None)
}
};

Expand Down

0 comments on commit a39d905

Please sign in to comment.