Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

pub async fn run(opts: RunOpts, config: Config, listener: UnixListener) ->…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Amazon Novaamazon-nova-experimental-chat-05-14’s answer.
  1. User

    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

  2. Claude Assistant

    Looking at this code, here are the key areas that would benefit from refactoring for cleaner, more maintainable code:

    1. Extract the massive scheduler task into a separate function

    The scheduler spawn block is over 60 lines and handles complex logic. Move it to something like spawn_scheduler_task().

    2. Break down the server request handling

    The main loop's closure is doing too much. Extract the request processing logic:

    async fn handle_server_request(
        decoded: ServerRequest,
        wayland_tx: &Sender<WaylandRequest>,
        // ... other params
    ) -> anyhow::Result<()>
    

    3. Eliminate the duplicated send_request closure

    This logic appears in multiple places with slight variations. Create a shared function:

    async fn apply_color_to_outputs(
        color: Color,
        mode: ScheduleMode,
        wayland: &Wayland,
        wayland_tx: &Sender<WaylandRequest>,
        // ... other params
    ) -> anyhow::Result<()>
    

    4. Extract color resolution logic

    The pattern of checking for output-specific colors vs default colors is repeated. Create:

    fn resolve_output_color(
        output_name: Option<&str>,
        default_color: Color,
        mode: ScheduleMode,
        outputs_config: &HashMap<String, OutputConfig>
    ) -> Color
    

    5. Reduce shared state complexity

    Consider grouping related shared state into structs:

    struct SchedulerState {
        current_mode: RwLockWrapper<Option<ScheduleMode>>,
        schedule_active: CondMutex<bool>,
        waiting: RwLockWrapper<bool>,
    }
    
    struct AppState {
        wayland: RwLockWrapper<Wayland>,
        outputs_config: RwLockWrapper<HashMap<String, OutputConfig>>,
        scheduler: SchedulerState,
    }
    

    6. Create a proper error handling wrapper

    The wrapper() function calls suggest error handling that could be more explicit and structured.

    7. Extract constants and magic numbers

    Values like 1000 (milliseconds) and buffer management should be named constants.

    8. Separate concerns in the main loop

    The socket handling, request parsing, and business logic are all mixed together. Consider a layered approach with proper separation.

    The biggest impact would come from extracting the scheduler task and request handling into separate functions, as these are the largest and most complex pieces of the current function.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.