pub async fn run(opts: RunOpts, config: Config, listener: UnixListener) ->…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
pub async fn run(opts: RunOpts, config: Config, listener: UnixListener) -> anyhow::Result<()> { logger::init(opts);
let wayland = RwLockWrapper::new(Wayland::new(true)?);
let (wayland_tx, wayland_rx) = channel(1);
{
let wayland = wayland.clone();
spawn(async move {
wayland.process_requests(wayland_rx).await;
});
}
let current_mode = RwLockWrapper::new(None);
let mut schedule_active = CondMutex::new(true);
let waiting = RwLockWrapper::new(false);
let outputs_config = RwLockWrapper::new(config.outputs);
{
let wayland = wayland.clone();
let wayland_tx = wayland_tx.clone();
let current_mode = current_mode.clone();
let schedule_active = schedule_active.clone();
let waiting = waiting.clone();
let outputs_config = outputs_config.clone();
spawn(async move {
wrapper(
async {
let mut timerfd =
TimerFd::new_custom(timerfd::ClockId::Boottime, false, false)?;
let mut scheduler = Scheduler::new(config.schedule, config.location)?;
let mut animate = config.animation.animate_on_start;
loop {
let end = Local::now() + TimeDelta::milliseconds(scheduler.delay_ms);
if !current_mode.read().is_some_and(|m| m == scheduler.mode) {
let color = match scheduler.mode {
ScheduleMode::Day => config.day,
ScheduleMode::Night => config.night,
};
let duration_sec = if animate {
config.animation.duration
} else {
0.0
};
let refresh_rate = config.animation.refresh_rate;
for (id, name) in wayland.get_outputs() {
let specific_color =
name.and_then(|n| match outputs_config.read().get(&n) {
Some(c) => match scheduler.mode {
ScheduleMode::Day => c.day,
ScheduleMode::Night => c.night,
},
None => None,
});
wayland_tx
.send(WaylandRequest {
id,
request_type: WaylandRequestType::ColorChange {
color: specific_color.unwrap_or(color),
duration_sec,
refresh_rate,
},
})
.await
.unwrap();
}
*current_mode.write() = Some(scheduler.mode);
animate = true;
log::info!("{}", LogTemplate::NextMode(Some(&scheduler.mode), end));
} else {
log::info!("{}", LogTemplate::NextMode(None, end));
}
timerfd.set_state(
TimerState::Oneshot(Duration::from_millis(scheduler.delay_ms as u64)),
SetTimeFlags::Default,
);
timerfd = spawn_blocking(move || {
timerfd.read();
timerfd
})
.await
.unwrap();
*waiting.write() = true;
schedule_active.wait();
*waiting.write() = false;
if (Local::now() - end).num_milliseconds() >= 1000 {
animate = false;
log::debug!("{}", LogTemplate::AnimationCancel);
}
scheduler.next()?;
}
}
.await,
);
});
}
loop {
let closure = async {
let (mut socket, _) = listener.accept().map_err(ServerError::Accept)?;
let mut buf = Vec::new();
socket.read_to_end(&mut buf).map_err(ServerError::Read)?;
let decoded: ServerRequest = decode_from_slice(&buf, standard())
.map(|r| r.0)
.map_err(ServerError::Decode)?;
log::info!("{}", LogTemplate::ServerRequest(&decoded));
let send_request = async |color, mode| {
for (id, name) in wayland.get_outputs() {
let specific_color = name.and_then(|n| match outputs_config.read().get(&n) {
Some(c) => match mode {
ScheduleMode::Day => c.day,
ScheduleMode::Night => c.night,
},
None => None,
});
wayland_tx
.send(WaylandRequest {
id,
request_type: WaylandRequestType::ColorChange {
color: specific_color.unwrap_or(color),
duration_sec: config.animation.duration,
refresh_rate: config.animation.refresh_rate,
},
})
.await
.unwrap();
}
*current_mode.write() = Some(mode);
};
match decoded {
ServerRequest::Mode(mode) => match mode {
DayNightMode::Day => {
send_request(config.day, ScheduleMode::Day).await;
}
DayNightMode::Night => {
send_request(config.night, ScheduleMode::Night).await;
}
DayNightMode::Toggle => {
let (color, new_mode) = match *current_mode.read() {
Some(ScheduleMode::Day) => (config.night, ScheduleMode::Night),
Some(ScheduleMode::Night) => (config.day, ScheduleMode::Day),
None => return anyhow::Ok(()),
};
send_request(color, new_mode).await;
}
},
ServerRequest::Profile(label) => {
let profile = if let Some(l) = label {
config.profiles.iter().find(|p| p.label == l)
} else {
None
};
if let Some(p) = profile {
schedule_active.update(false);
for (id, name) in wayland.get_outputs() {
let specific_color = name.and_then(|n| p.outputs.get(&n));
wayland_tx
.send(WaylandRequest {
id,
request_type: WaylandRequestType::ColorChange {
color: *specific_color.unwrap_or(&p.color),
duration_sec: p
.animation
.duration
.unwrap_or(config.animation.duration),
refresh_rate: p
.animation
.refresh_rate
.unwrap_or(config.animation.refresh_rate),
},
})
.await
.unwrap();
}
} else {
if !*waiting.read() {
let (color, new_mode) = match *current_mode.read() {
Some(ScheduleMode::Day) => (config.day, ScheduleMode::Day),
Some(ScheduleMode::Night) => (config.night, ScheduleMode::Night),
None => return anyhow::Ok(()),
};
send_request(color, new_mode).await;
}
schedule_active.update(true);
}
}
ServerRequest::Adjust(output, property, value) => {
for (id, name) in wayland.get_outputs() {
if name.is_none_or(|n| n != output) && output != "*" {
continue;
}
wayland_tx
.send(WaylandRequest {
id,
request_type: WaylandRequestType::PropertyChange(
property.clone(),
value,
),
})
.await
.unwrap();
}
}
}
Ok(())
}
.await;
wrapper(closure);
}
}
tell me places that needs to refactor for more "clean" code
Certainly! Here are several places in your code that could be refactored for cleaner, more maintainable code:
Cloning Arcs repeatedly can make the code harder to read. Instead, clone them once at the beginning of the block where they are needed.
{
let wayland = wayland.clone();
let wayland_tx = wayland_tx.clone();
let current_mode = current_mode.clone();
let schedule_active = schedule_active.clone();
let waiting = waiting.clone();
let outputs_config = outputs_config.clone();
spawn(async move {
// ...
});
}
let wayland = wayland.clone();
let wayland_tx = wayland_tx.clone();
let current_mode = current_mode.clone();
let schedule_active = schedule_active.clone();
let waiting = waiting.clone();
let outputs_config = outputs_config.clone();
spawn(async move {
// ...
});
The body of the loop that handles client requests is quite large and can be extracted into a separate async function for better readability.
loop {
let closure = async {
// Large block of code
}
.await;
wrapper(closure);
}
loop {
let result = handle_client_request(listener.clone(), wayland.clone(), wayland_tx.clone(), current_mode.clone(), schedule_active.clone(), waiting.clone(), outputs_config.clone(), config.clone()).await;
wrapper(result);
}
async fn handle_client_request(
listener: UnixListener,
wayland: RwLockWrapper<Wayland>,
wayland_tx: Sender<WaylandRequest>,
current_mode: RwLockWrapper<Option<ScheduleMode>>,
schedule_active: CondMutex<bool>,
waiting: RwLockWrapper<bool>,
outputs_config: RwLockWrapper<HashMap<String, OutputConfig>>,
config: Config,
) -> anyhow::Result<()> {
// Large block of code from the loop
}
There are several places where the same logic is repeated. For example sending a WaylandRequest and handling colours based on the schedule mode. These can be extracted into their functions.
fn get_color(
name: Option<&str>,
outputs_config: &RwLockWrapper<HashMap<String, OutputConfig>>,
mode: ScheduleMode,
config: &Config,
) -> Colour {
name.and_then(|n| {
outputs_config
.read()
.get(n)
.map(|c| match mode {
ScheduleMode::Day => c.day,
ScheduleMode::Night => c.night,
})
})
.unwrap_or_else(|| match mode {
ScheduleMode::Day => config.day,
ScheduleMode::Night => config.night,
})
}
async fn send_wayland_request(
wayland_tx: &Sender<WaylandRequest>,
id: u32,
colour: Colour,
duration_sec: f64,
refresh_rate: u32,
) {
wayland_tx
.send(WaylandRequest {
id,
request_type: WaylandRequestType::ColorChange {
color: colour,
duration_sec,
refresh_rate,
},
})
.await
.unwrap();
}
You can then replace the repeated code with calls to these functions.
The match statements, especially the nested ones, can be simplified for better readability.
let (color, new_mode) = match *current_mode.read() {
Some(ScheduleMode::Day) => (config.night, ScheduleMode::Night),
Some(ScheduleMode::Night) => (config.day, ScheduleMode::Day),
None => return anyhow::Ok(()),
};
let (color, new_mode) = match current_mode.read().as_ref() {
Some(ScheduleMode::Day) => (config.night, ScheduleMode::Night),
Some(ScheduleMode::Night) => (config.day, ScheduleMode::Day),
None => return anyhow::Ok(()),
};
Instead of using unwrap(), which can panic, use proper error handling to make the code more robust.
wayland_tx
.send(WaylandRequest { /* ... */ })
.await
.unwrap();
if let Err(e) = wayland_tx
.send(WaylandRequest { /* ... */ })
.await
{
return Err(anyhow::Error::new(e));
}
Cloning the entire config every time it is needed can be inefficient. Instead, clone only the necessary fields or use references where possible.
Here is an excerpt of the refactored code incorporating the suggestions above:
pub async fn run(opts: RunOpts, config: Config, listener: UnixListener) -> anyhow::Result<()> {
logger::init(opts);
let wayland = RwLockWrapper::new(Wayland::new(true)?);
let (wayland_tx, wayland_rx) = channel(1);
let wayland_clone = wayland.clone();
spawn(async move {
wayland_clone.process_requests(wayland_rx).await;
});
let current_mode = RwLockWrapper::new(None);
let mut schedule_active = CondMutex::new(true);
let waiting = RwLockWrapper::new(false);
let outputs_config = RwLockWrapper::new(config.outputs.clone());
let wayland = wayland.clone();
let wayland_tx = wayland_tx.clone();
let current_mode = current_mode.clone();
let schedule_active = schedule_active.clone();
let waiting = waiting.clone();
let outputs_config = outputs_config.clone();
let config = config.clone();
spawn(async move {
wrapper(
async {
let mut timerfd =
TimerFd::new_custom(timerfd::ClockId::Boottime, false, false)?;
let mut scheduler = Scheduler::new(config.schedule.clone(), config.location.clone())?;
let mut animate = config.animation.animate_on_start;
loop {
let end = Local::now() + TimeDelta::milliseconds(scheduler.delay_ms);
if !current_mode.read().is_some_and(|m| m == scheduler.mode) {
let color = get_color(None, &outputs_config, scheduler.mode, &config);
let duration_sec = if animate {
config.animation.duration
} else {
0.0
};
let refresh_rate = config.animation.refresh_rate;
for (id, name) in wayland.get_outputs() {
let specific_color = get_color(name.as_deref(), &outputs_config, scheduler.mode, &config);
if let Err(e) = send_wayland_request(&wayland_tx, id, specific_color.unwrap_or(color), duration_sec, refresh_rate).await {
return Err(anyhow::Error::new(e));
}
}
*current_mode.write() = Some(scheduler.mode);
animate = true;
log::info!("{}", LogTemplate::NextMode(Some(&scheduler.mode), end));
} else {
log::info!("{}", LogTemplate::NextMode(None, end));
}
timerfd.set_state(
TimerState::Oneshot(Duration::from_millis(scheduler.delay_ms as u64)),
SetTimeFlags::Default,
);
timerfd = spawn_blocking(move || {
timerfd.read();
timerfd
})
.await
.unwrap();
*waiting.write() = true;
schedule_active.wait();
*waiting.write() = false;
if (Local::now() - end).num_milliseconds() >= 1000 {
animate = false;
log::debug!("{}", LogTemplate::AnimationCancel);
}
scheduler.next()?;
}
}
.await,
);
});
loop {
let result = handle_client_request(
listener.clone(),
wayland.clone(),
wayland_tx.clone(),
current_mode.clone(),
schedule_active.clone(),
waiting.clone(),
outputs_config.clone(),
config.clone()
).await;
wrapper(result);
}
}
async fn handle_client_request(
listener: UnixListener,
wayland: RwLockWrapper<Wayland>,
wayland_tx: Sender<WaylandRequest>,
current_mode: RwLockWrapper<Option<ScheduleMode>>,
schedule_active: CondMutex<bool>,
waiting: RwLockWrapper<bool>,
outputs_config: RwLockWrapper<HashMap<String, OutputConfig>>,
config: Config,
) -> anyhow::Result<()> {
let (mut socket, _) = listener.accept().map_err(ServerError::Accept)?;
let mut buf = Vec::new();
socket.read_to_end(&mut buf).map_err(ServerError::Read)?;
let decoded: ServerRequest = decode_from_slice(&buf, standard())
.map(|r| r.0)
.map_err(ServerError::Decode)?;
log::info!("{}", LogTemplate::ServerRequest(&decoded));
match decoded {
ServerRequest::Mode(mode) => match mode {
DayNightMode::Day => {
let color = config.day;
let mode = ScheduleMode::Day;
for (id, name) in wayland.get_outputs() {
let specific_color = get_color(name.as_deref(), &outputs_config, mode, &config);
if let Err(e) = send_wayland_request(&wayland_tx, id, specific_color.unwrap_or(color), config.animation.duration, config.animation.refresh_rate).await {
return Err(anyhow::Error::new(e));
}
}
*current_mode.write() = Some(mode);
}
DayNightMode::Night => {
let color = config.night;
let mode = ScheduleMode::Night;
for (id, name) in wayland.get_outputs() {
let specific_color = get_color(name.as_deref(), &outputs_config, mode, &config);
if let Err(e) = send_wayland_request(&wayland_tx, id, specific_color.unwrap_or(color), config.animation.duration, config.animation.refresh_rate).await {
return Err(anyhow::Error::new(e));
}
}
*current_mode.write() = Some(mode);
}
DayNightMode::Toggle => {
let (color, new_mode) = match current_mode.read().as_ref() {
Some(ScheduleMode::Day) => (config.night, ScheduleMode::Night),
Some(ScheduleMode::Night) => (config.day, ScheduleMode::Day),
None => return anyhow::Ok(()),
};
for (id, name) in wayland.get_outputs() {
let specific_color = get_color(name.as_deref(), &outputs_config, new_mode, &config);
if let Err(e) = send_wayland_request(&wayland_tx, id, specific_color.unwrap_or(color), config.animation.duration, config.animation.refresh_rate).await {
return Err(anyhow::Error::new(e));
}
}
*current_mode.write() = Some(new_mode);
}
},
ServerRequest::Profile(label) => {
let profile = if let Some(l) = label {
config.profiles.iter().find(|p| p.label == l)
} else {
None
};
if let Some(p) = profile {
schedule_active.update(false);
for (id, name) in wayland.get_outputs() {
let specific_color = name.and_then(|n| p.outputs.get(&n));
if let Err(e) = wayland_tx
.send(WaylandRequest {
id,
request_type: WaylandRequestType::ColorChange {
color: *specific_color.unwrap_or(&p.color),
duration_sec: p
.animation
.duration
.unwrap_or(config.animation.duration),
refresh_rate: p
.animation
.refresh_rate
.unwrap_or(config.animation.refresh_rate),
},
})
.await
{
return Err(anyhow::Error::new(e));
}
}
} else {
if !*waiting.read() {
let (color, new_mode) = match *current_mode.read() {
Some(ScheduleMode::Day) => (config.day, ScheduleMode::Day),
Some(ScheduleMode::Night) => (config.night, ScheduleMode::Night),
None => return anyhow::Ok(()),
};
for (id, name) in wayland.get_outputs() {
let specific_color = get_color(name.as_deref(), &outputs_config, new_mode, &config);
if let Err(e) = send_wayland_request(&wayland_tx, id, specific_color.unwrap_or(color), config.animation.duration, config.animation.refresh_rate).await {
return Err(anyhow::Error::new(e));
}
}
*current_mode.write() = Some(new_mode);
}
schedule_active.update(true);
}
}
ServerRequest::Adjust(output, property, value) => {
for (id, name) in wayland.get_outputs() {
if name.as_deref() != Some(output) && output != "*" {
continue;
}
if let Err(e) = wayland_tx
.send(WaylandRequest {
id,
request_type: WaylandRequestType::PropertyChange(property.clone(), value),
})
.await
{
return Err(anyhow::Error::new(e));
}
}
}
}
Ok(())
}
fn get_color(
name: Option<&str>,
outputs_config: &RwLockWrapper<HashMap<String, OutputConfig>>,
mode: ScheduleMode,
config: &Config,
) -> Colour {
name.and_then(|n| {
outputs_config
.read()
.get(n)
.map(|c| match mode {
ScheduleMode::Day => c.day,
ScheduleMode::Night => c.night,
})
})
.unwrap_or_else(|| match mode {
ScheduleMode::Day => config.day,
ScheduleMode::Night => config.night,
})
}
async fn send_wayland_request(
wayland_tx: &Sender<WaylandRequest>,
id: u32,
colour: Colour,
duration_sec: f64,
refresh_rate: u32,
) -> anyhow::Result<()> {
wayland_tx
.send(WaylandRequest {
id,
request_type: WaylandRequestType::ColorChange {
color: colour,
duration_sec,
refresh_rate,
},
})
.await
.map_err(|e| anyhow::Error::new(e))
}
Arcs once at the beginning of the block.as_ref() to simplify match statements.unwrap() with proper error handling.config instead of the entire struct.These changes will make your code more readable, maintainable, and robust.