ballista-cli 55.0.0

Command Line Client for Ballista distributed query engine.
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

mod app;
mod domain;
mod error;
mod event;
mod http_client;
mod infrastructure;
mod terminal;
mod ui;

use crate::tui::error::TuiError;

pub type TuiResult<OK> = Result<OK, TuiError>;

#[cfg(not(feature = "web"))]
pub(crate) use _tui::main;
#[cfg(feature = "web")]
pub(crate) use web::main;

#[cfg(not(feature = "web"))]
mod _tui {
    use crate::tui::{
        TuiResult,
        app::App,
        event::{Event, UiData, tui::EventHandler},
        infrastructure::Settings,
        terminal::TuiWrapper,
        ui,
    };
    use std::sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    };
    use std::time::Duration;

    pub async fn main(tui_mode: Arc<AtomicBool>) -> TuiResult<()> {
        tui_mode.store(true, Ordering::Release);
        tracing::info!("Starting the Ballista TUI application");

        let config = Settings::new()?;
        tracing::debug!("TUI configuration: {:?}", config);

        let mut tui_wrapper = TuiWrapper::new()?;
        let mut events = EventHandler::new(
            Duration::from_millis(config.data_reload_interval_ms),
            Duration::from_millis(config.repaint_interval_ms),
        );
        let mut app = App::new(config)?;

        let (app_tx, mut app_rx) = tokio::sync::mpsc::channel(16);
        app.set_event_tx(app_tx);

        let data = match app.http_client.get_scheduler_state().await {
            Ok(state) => UiData::SchedulerState(Some(state)),
            Err(e) => {
                tracing::error!("Failed to load scheduler state: {e:?}");
                UiData::SchedulerState(None)
            }
        };
        app.send_event(Event::DataLoaded { data }).await.ok();

        loop {
            tui_wrapper.terminal.draw(|f| ui::render(f, &app))?;

            tokio::select! {
                maybe_event = events.next() => {
                    match maybe_event {
                        Some(Event::Key(key)) => app.on_key(key).await?,
                        Some(Event::Repaint) => {},
                        Some(Event::DataReload) => app.on_tick().await,
                        Some(evt) => tracing::warn!("Unexpected event: {evt:?}"),
                        None => break,
                    }
                }
                Some(app_event) = app_rx.recv() => {
                    if let Event::DataLoaded { data } = app_event {
                        app.apply_ui_data(data);
                    }
                }
            }

            tokio::task::yield_now().await;

            if app.should_quit() {
                tracing::info!("Stopping the Ballista TUI application!");
                break;
            }
        }

        Ok(())
    }
}

#[cfg(feature = "web")]
pub(crate) mod web {
    use crate::tui::domain::jobs::stages::StagePlanTab;
    use crate::tui::{
        TuiResult,
        app::{App, WebKeyAsyncAction},
        domain::jobs::{CancelJobResult, JobConfigEntry, JobConfigPopup},
        event::{
            Event, UiData,
            web::{EventHandler, Sender},
        },
        http_client::HttpClient,
        infrastructure::Settings,
        terminal::TuiWrapper,
        ui,
    };

    /// Entry point for the web browser TUI (WASM target). Sets up Ratzilla callbacks and starts
    /// the Ratatui render loop via `draw_web`.
    pub async fn main() -> TuiResult<()> {
        use ratzilla::WebRenderer;
        use std::cell::{Cell, RefCell};
        use std::rc::Rc;
        use wasm_bindgen_futures::spawn_local;

        let config = Settings::new()?;
        let data_reload_interval_ms =
            u32::try_from(config.data_reload_interval_ms).unwrap_or(u32::MAX);
        let repaint_interval_ms =
            u32::try_from(config.repaint_interval_ms).unwrap_or(u32::MAX);

        let mut wrapper = TuiWrapper::new()?;
        let app = Rc::new(RefCell::new(App::new(config)?));

        /// Reset the tick in flight flag on tick event handler drop.
        struct ResetOnDrop(Rc<Cell<bool>>);
        impl Drop for ResetOnDrop {
            fn drop(&mut self) {
                self.0.set(false);
            }
        }
        let tick_in_flight = Rc::new(Cell::new(false));

        let (tx, mut rx) = EventHandler::new(
            data_reload_interval_ms,
            repaint_interval_ms,
            &mut wrapper.terminal,
        );
        app.borrow_mut().set_event_tx(tx.clone());

        // Initial data load — http_client extracted with a brief borrow, no borrow held across await
        {
            tracing::info!("Initial data load");
            let http_client = app.borrow().http_client.clone();
            let tx = tx.clone();
            spawn_local(async move {
                let data = match http_client.get_scheduler_state().await {
                    Ok(state) => UiData::SchedulerState(Some(state)),
                    Err(e) => {
                        tracing::error!("Failed to load scheduler state: {e:?}");
                        UiData::SchedulerState(None)
                    }
                };
                tx.send(Event::DataLoaded { data }).await.ok();
                tx.send(Event::DataReload).await.ok();
            });
        }

        // ── Render loop (driven by requestAnimationFrame) ─────────────────
        let app_render = Rc::clone(&app);
        wrapper.terminal.draw_web(move |f| {
            while let Some(event) = rx.next() {
                match event {
                    Event::DataLoaded { data } => {
                        // Brief synchronous borrow — safe, no await held
                        app.borrow_mut().apply_ui_data(data);
                    }
                    Event::Repaint => {
                        // just repaint
                    }
                    Event::DataReload => {
                        if tick_in_flight.get() {
                            continue;
                        }
                        tick_in_flight.set(true);
                        // Extract state with brief borrows, then spawn async data load
                        let http_client = app.borrow().http_client.clone();
                        let is_executors = app.borrow().is_executors_view();
                        let is_jobs = app.borrow().is_jobs_view();
                        let tx = tx.clone();
                        let _tick_in_flight_done =
                            ResetOnDrop(Rc::clone(&tick_in_flight));
                        spawn_local(async move {
                            let data = load_tick_data_for_view(
                                &http_client,
                                is_executors,
                                is_jobs,
                            )
                            .await;
                            tx.send(Event::DataLoaded { data }).await.ok();
                        });
                    }
                    Event::Key(key_event) => {
                        // on_key_sync is purely synchronous — brief borrow_mut, no await
                        let action = app.borrow_mut().on_key_sync(&key_event);
                        if let Some(action) = action {
                            let http_client = app.borrow().http_client.clone();
                            let is_executors = app.borrow().is_executors_view();
                            let is_jobs = app.borrow().is_jobs_view();
                            let tx = tx.clone();
                            spawn_local(async move {
                                execute_web_async_action(
                                    http_client,
                                    tx,
                                    is_executors,
                                    is_jobs,
                                    action,
                                )
                                .await;
                            });
                        }
                    }
                }
            }

            let app = app_render.borrow();
            ui::render(f, &app);
        });

        Ok(())
    }

    /// Loads data for the currently active view without borrowing `App` during the await.
    async fn load_tick_data_for_view(
        http_client: &HttpClient,
        is_executors: bool,
        is_jobs: bool,
    ) -> UiData {
        if is_executors {
            let (scheduler_result, executors_result, jobs_result) = tokio::join!(
                http_client.get_scheduler_state(),
                http_client.get_executors(),
                http_client.get_jobs(),
            );
            UiData::Executors(
                scheduler_result
                    .map_err(|e| tracing::error!("Failed to load scheduler state: {e:?}"))
                    .ok(),
                executors_result.unwrap_or_else(|e| {
                    tracing::error!("Failed to load executors: {e:?}");
                    vec![]
                }),
                jobs_result.unwrap_or_else(|e| {
                    tracing::error!("Failed to load jobs: {e:?}");
                    vec![]
                }),
            )
        } else if is_jobs {
            UiData::Jobs(http_client.get_jobs().await.unwrap_or_else(|e| {
                tracing::error!("Failed to load jobs: {e:?}");
                vec![]
            }))
        } else {
            UiData::Metrics(http_client.get_metrics().await.unwrap_or_else(|e| {
                tracing::error!("Failed to load metrics: {e:?}");
                vec![]
            }))
        }
    }

    /// Executes an async action triggered by a key press, sending the result through `tx`.
    // Captures only `Arc<HttpClient>` and `Sender<Event>` — no `Rc<RefCell<App>>` borrow.
    async fn execute_web_async_action(
        http_client: std::sync::Arc<HttpClient>,
        tx: Sender<Event>,
        is_executors: bool,
        is_jobs: bool,
        action: WebKeyAsyncAction,
    ) {
        async fn send_data(data: UiData, tx: Sender<Event>) {
            tx.send(Event::DataLoaded { data }).await.ok();
        }

        match action {
            WebKeyAsyncAction::LoadJobStages(id) => {
                match http_client
                    .get_job_stages(&id, &StagePlanTab::Default)
                    .await
                {
                    Ok(mut stages) => {
                        stages.stages.sort_by_key(|s| {
                            s.stage_id.parse::<u64>().unwrap_or(u64::MAX)
                        });
                        send_data(UiData::JobStagesData(id, stages), tx).await;
                    }
                    Err(e) => {
                        tracing::error!("Failed to load stages for job '{id}': {e:?}")
                    }
                }
            }
            WebKeyAsyncAction::LoadExecutorDetails(id) => {
                match http_client.get_executor(&id).await {
                    Ok(executor) => {
                        send_data(UiData::ExecutorDetails(executor), tx).await;
                    }
                    Err(e) => tracing::error!("Failed to load executor '{id}': {e:?}"),
                }
            }
            WebKeyAsyncAction::LoadJobDot(id) => match http_client.get_job_dot(&id).await
            {
                Ok(dot_content) => {
                    let graph = ui::dot_parser::parse_dot(&id, &dot_content);
                    send_data(UiData::JobStagesGraph(graph), tx).await;
                }
                Err(e) => tracing::error!("Failed to load job dot for '{id}': {e:?}"),
            },
            WebKeyAsyncAction::LoadJobConfig(id) => {
                match http_client.get_job_config(&id).await {
                    Ok(config) => {
                        let entries = config
                            .into_iter()
                            .map(|(key, value)| JobConfigEntry { key, value })
                            .collect();
                        send_data(
                            UiData::JobConfig(JobConfigPopup::new(id, entries)),
                            tx,
                        )
                        .await;
                    }
                    Err(e) => {
                        tracing::error!("Failed to load job config for '{id}': {e:?}")
                    }
                }
            }
            WebKeyAsyncAction::CancelJob(id) => {
                let result = match http_client.cancel_job(&id).await {
                    Ok(resp) if resp.canceled => CancelJobResult::Success { job_id: id },
                    Ok(_) => CancelJobResult::NotCanceled { job_id: id },
                    Err(e) => CancelJobResult::Failure {
                        job_id: id,
                        error: e.to_string(),
                    },
                };
                send_data(UiData::CancelJobResult(result), tx).await;
            }
            WebKeyAsyncAction::UpdateJobDetails(job_id) => {
                if let Some(id) = job_id {
                    match http_client
                        .get_job_details(&id, &StagePlanTab::Default)
                        .await
                    {
                        Ok(details) => {
                            send_data(UiData::JobDetails(details), tx).await;
                        }
                        Err(e) => {
                            tracing::error!(
                                "Failed to load job details for '{id}': {e:?}"
                            )
                        }
                    }
                }
            }
            WebKeyAsyncAction::LoadJobPlanTree(id) => {
                match http_client.get_job_details(&id, &StagePlanTab::Tree).await {
                    Ok(mut details) => {
                        details.physical_plan_tree = details.physical_plan.take();
                        send_data(UiData::JobDetails(details), tx).await;
                    }
                    Err(e) => {
                        tracing::error!("Failed to load tree plan for '{id}': {e:?}")
                    }
                }
            }
            WebKeyAsyncAction::LoadStagePlan(job_id, tab) => {
                match http_client.get_job_stages(&job_id, &tab).await {
                    Ok(mut stages) => {
                        stages.stages.sort_by_key(|s| {
                            s.stage_id.parse::<u64>().unwrap_or(u64::MAX)
                        });
                        send_data(UiData::JobStagesPlanData(tab, stages), tx).await;
                    }
                    Err(e) => {
                        tracing::error!("Failed to load stage plan for '{job_id}': {e:?}")
                    }
                }
            }
            WebKeyAsyncAction::ReloadView => {
                let data =
                    load_tick_data_for_view(&http_client, is_executors, is_jobs).await;
                send_data(data, tx).await;
            }
        }
    }
}