lazycelery 0.8.3

A terminal UI for monitoring and managing Celery workers and tasks, inspired by lazydocker/lazygit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
mod app;
mod broker;
mod config;
mod error;
mod models;
mod ui;
mod update;
mod utils;

use anyhow::Result;
use clap::Parser;
use crossterm::{
    event::{DisableMouseCapture, EnableMouseCapture},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::{io, time::Duration};
use tokio::time;

use crate::app::App;
use crate::broker::{create_broker, Broker};
use crate::config::Config;
use crate::ui::events::{handle_key_event, next_event, AppEvent};

use clap::Subcommand;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Broker URL (e.g., redis://localhost:6379/0)
    #[arg(short, long, global = true)]
    broker: Option<String>,

    /// Result backend URL
    #[arg(long, global = true)]
    result_backend: Option<String>,

    /// Configuration file path
    #[arg(short, long, global = true)]
    config: Option<std::path::PathBuf>,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Initialize configuration with interactive setup
    Init,

    /// Show current configuration
    Config,

    /// Set broker URL in configuration
    SetBroker {
        /// Broker URL (e.g., redis://localhost:6379/0)
        url: String,
    },

    /// Set UI refresh interval in milliseconds
    SetRefresh {
        /// Refresh interval in milliseconds
        interval: u64,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Handle subcommands
    match cli.command {
        Some(Commands::Init) => {
            run_init_command().await?;
            return Ok(());
        }
        Some(Commands::Config) => {
            show_config()?;
            return Ok(());
        }
        Some(Commands::SetBroker { url }) => {
            set_broker_url(&url)?;
            return Ok(());
        }
        Some(Commands::SetRefresh { interval }) => {
            set_refresh_interval(interval)?;
            return Ok(());
        }
        None => {
            // Run the main TUI application
            run_tui_app(cli.broker, cli.config).await?;
        }
    }

    Ok(())
}

async fn run_tui_app(
    broker_arg: Option<String>,
    config_arg: Option<std::path::PathBuf>,
) -> Result<()> {
    // Load configuration
    let config = if let Some(config_path) = config_arg {
        Config::from_file(config_path)?
    } else {
        Config::load_or_create_default()?
    };

    // Check for updates (non-blocking)
    let current_version = env!("CARGO_PKG_VERSION");
    tokio::spawn(async move {
        if let Some(update) = update::check_for_update(current_version).await {
            update.print_notification();
        }
    });

    // Determine broker URL
    let broker_url = broker_arg.unwrap_or_else(|| config.broker.url.clone());

    // Connect to broker
    let broker: Box<dyn Broker> = match create_broker(&broker_url).await {
        Ok(broker) => broker,
        Err(e) => {
            let (broker_type, url_hint) = if broker_url.starts_with("redis://") {
                ("Redis", "redis://localhost:6379/0")
            } else if broker_url.starts_with("amqp://") {
                ("RabbitMQ", "amqp://guest:guest@localhost:5672//")
            } else {
                (
                    "Unknown",
                    "redis://localhost:6379/0 or amqp://localhost:5672//",
                )
            };
            eprintln!("\n❌ Failed to connect to {broker_type} broker at {broker_url}");
            eprintln!("\n{e}");
            eprintln!("\n📋 Quick Setup Guide:");
            eprintln!("1. For Redis:");
            eprintln!("   - Docker: docker run -d -p 6379:6379 redis");
            eprintln!("   - macOS: brew services start redis");
            eprintln!("   - Verify: redis-cli ping");
            eprintln!("\n2. For RabbitMQ:");
            eprintln!("   - Docker: docker run -d -p 5672:5672 rabbitmq");
            eprintln!("   - Verify: amqp://guest:guest@localhost:5672//");
            eprintln!("\n3. Run lazycelery:");
            eprintln!("   lazycelery --broker {url_hint}");
            eprintln!("\n💡 For more help: https://github.com/Fgudes90/lazycelery");
            std::process::exit(1);
        }
    };

    // Create app state
    let mut app = App::new(broker);

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Run the app
    let res = run_app(&mut terminal, &mut app, &config).await;

    // Restore terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    if let Err(err) = res {
        eprintln!("Error: {err}");
    }

    Ok(())
}

async fn run_app(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut App,
    config: &Config,
) -> Result<()> {
    // Initial data fetch
    app.refresh_data().await?;

    // Set up refresh interval
    let mut refresh_interval = time::interval(Duration::from_millis(config.ui.refresh_interval));
    let tick_rate = Duration::from_millis(50); // 20 FPS max

    loop {
        // Draw UI
        terminal.draw(|f| ui::draw(f, app))?;

        // Handle events
        tokio::select! {
            // Handle user input
            event = next_event(tick_rate) => {
                match event? {
                    AppEvent::Key(key) => {
                        // Check if confirmation dialog needs execution
                        let should_execute = app.show_confirmation && matches!(
                            key.code,
                            crossterm::event::KeyCode::Char('y') |
                            crossterm::event::KeyCode::Char('Y') |
                            crossterm::event::KeyCode::Enter
                        );

                        handle_key_event(key, app);

                        // Execute pending action if confirmed
                        if should_execute {
                            app.execute_pending_action().await?;
                        }

                        if app.should_quit {
                            return Ok(());
                        }
                    }
                    AppEvent::Tick => {}
                    AppEvent::Refresh => {
                        app.refresh_data().await?;
                    }
                }
            }
            // Auto-refresh data
            _ = refresh_interval.tick() => {
                app.refresh_data().await?;
            }
        }
    }
}

async fn run_init_command() -> Result<()> {
    use std::io::{self, Write};

    println!("🚀 Welcome to LazyCelery Setup!\n");

    // Get config directory
    let config_dir = dirs::config_dir()
        .ok_or_else(|| anyhow::anyhow!("Could not determine config directory"))?
        .join("lazycelery");
    let config_path = config_dir.join("config.toml");

    // Check if config already exists
    if config_path.exists() {
        print!(
            "⚠️  Configuration already exists at {}. Overwrite? (y/N): ",
            config_path.display()
        );
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        if !input.trim().eq_ignore_ascii_case("y") {
            println!("❌ Setup cancelled.");
            return Ok(());
        }
    }

    // Ask for broker URL
    print!("📡 Enter your Celery broker URL (default: redis://localhost:6379/0): ");
    io::stdout().flush()?;

    let mut broker_url = String::new();
    io::stdin().read_line(&mut broker_url)?;
    let broker_url = broker_url.trim();
    let broker_url = if broker_url.is_empty() {
        "redis://localhost:6379/0"
    } else {
        broker_url
    };

    // Validate broker URL
    if !broker_url.starts_with("redis://") && !broker_url.starts_with("amqp://") {
        eprintln!("❌ Invalid broker URL. Must start with redis:// or amqp://");
        return Ok(());
    }

    // Ask for refresh interval
    print!("🔄 Enter UI refresh interval in milliseconds (default: 1000): ");
    io::stdout().flush()?;

    let mut refresh_input = String::new();
    io::stdin().read_line(&mut refresh_input)?;
    let refresh_interval: u64 = refresh_input.trim().parse().unwrap_or(1000);

    // Create config
    let config = Config {
        broker: crate::config::BrokerConfig {
            url: broker_url.to_string(),
            timeout: 30,
            retry_attempts: 3,
        },
        ui: crate::config::UiConfig {
            refresh_interval,
            theme: "dark".to_string(),
        },
    };

    // Save config
    std::fs::create_dir_all(&config_dir)?;
    let toml_string = toml::to_string_pretty(&config)?;
    std::fs::write(&config_path, toml_string)?;

    println!("\n✅ Configuration saved to: {}", config_path.display());
    println!("\n📋 You can now run 'lazycelery' to start monitoring your Celery workers!");

    // Test connection
    print!("\n🔌 Test connection to broker? (Y/n): ");
    io::stdout().flush()?;

    let mut test_input = String::new();
    io::stdin().read_line(&mut test_input)?;
    if !test_input.trim().eq_ignore_ascii_case("n") {
        print!("🔄 Testing connection to {}... ", config.broker.url);
        io::stdout().flush()?;

        match test_broker_connection(&config.broker.url).await {
            Ok(_) => println!("✅ Success!"),
            Err(e) => println!("❌ Failed: {e}"),
        }
    }

    Ok(())
}

fn show_config() -> Result<()> {
    let config_dir = dirs::config_dir()
        .ok_or_else(|| anyhow::anyhow!("Could not determine config directory"))?
        .join("lazycelery");
    let config_path = config_dir.join("config.toml");

    if !config_path.exists() {
        eprintln!("❌ No configuration found. Run 'lazycelery init' to create one.");
        return Ok(());
    }

    let config = Config::from_file(config_path.clone())?;

    println!("📋 Current Configuration");
    println!("📍 Location: {}", config_path.display());
    println!("\n[broker]");
    println!("  url = \"{}\"", config.broker.url);
    println!("  timeout = {}", config.broker.timeout);
    println!("  retry_attempts = {}", config.broker.retry_attempts);
    println!("\n[ui]");
    println!("  refresh_interval = {}", config.ui.refresh_interval);
    println!("  theme = \"{}\"", config.ui.theme);

    Ok(())
}

fn set_broker_url(url: &str) -> Result<()> {
    // Validate URL
    if !url.starts_with("redis://") && !url.starts_with("amqp://") {
        eprintln!("❌ Invalid broker URL. Must start with redis:// or amqp://");
        return Ok(());
    }

    let config_dir = dirs::config_dir()
        .ok_or_else(|| anyhow::anyhow!("Could not determine config directory"))?
        .join("lazycelery");
    let config_path = config_dir.join("config.toml");

    // Load existing config or create default
    let mut config = if config_path.exists() {
        Config::from_file(config_path.clone())?
    } else {
        std::fs::create_dir_all(&config_dir)?;
        Config::default()
    };

    // Update broker URL
    config.broker.url = url.to_string();

    // Save config
    let toml_string = toml::to_string_pretty(&config)?;
    std::fs::write(&config_path, toml_string)?;

    println!("✅ Broker URL updated to: {url}");
    println!("📍 Configuration saved to: {}", config_path.display());

    Ok(())
}

fn set_refresh_interval(interval: u64) -> Result<()> {
    let config_dir = dirs::config_dir()
        .ok_or_else(|| anyhow::anyhow!("Could not determine config directory"))?
        .join("lazycelery");
    let config_path = config_dir.join("config.toml");

    // Load existing config or create default
    let mut config = if config_path.exists() {
        Config::from_file(config_path.clone())?
    } else {
        std::fs::create_dir_all(&config_dir)?;
        Config::default()
    };

    // Update refresh interval
    config.ui.refresh_interval = interval;

    // Save config
    let toml_string = toml::to_string_pretty(&config)?;
    std::fs::write(&config_path, toml_string)?;

    println!("✅ Refresh interval updated to: {interval}ms");
    println!("📍 Configuration saved to: {}", config_path.display());

    Ok(())
}
async fn test_broker_connection(url: &str) -> Result<()> {
    create_broker(url).await?;
    Ok(())
}