coralogix-cli 0.1.4

Coralogix CLI - the observability backbone for AI agents and engineering teams.
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
use std::io::Read;
use std::sync::Arc;

use anyhow::{bail, Result};
use colored::Colorize;
use rand::RngExt;
use serde_json::{json, Value};
use toon_format::encode_default as toon_encode;

pub mod api;

use api::{DashboardFolderItem, DashboardsApi};

use crate::config::OutputFormat;
use crate::execution::{fan_out, ExecutionTarget};
use crate::render;

// ── Helpers ───────────────────────────────────────────────────────────────────

fn catalog_item_to_json(
    item: &api::DashboardCatalogItem,
    include_profile: bool,
    profile: &str,
) -> Value {
    let mut v = json!({
        "id": item.id,
        "name": item.name,
        "description": item.description,
        "slug_name": item.slug_name,
        "create_time": item.create_time,
        "update_time": item.update_time,
        "is_default": item.is_default,
        "is_pinned": item.is_pinned,
        "is_locked": item.is_locked,
        "folder": item.folder.as_ref().map(|f| json!({
            "id": f.id,
            "name": f.name,
            "parent_id": f.parent_id,
        })),
    });
    if include_profile {
        if let Value::Object(ref mut m) = v {
            m.insert("profile".to_string(), Value::String(profile.to_string()));
        }
    }
    v
}

// ── Subcommand runners ────────────────────────────────────────────────────────

pub async fn run_catalog(targets: &[Arc<ExecutionTarget>], output: OutputFormat) -> Result<()> {
    eprintln!("{}", "Fetching dashboard catalog...".dimmed());

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| async move {
        let api = DashboardsApi::new(&t.client);
        Ok(api.catalog().await?)
    })
    .await;

    // Merge
    let mut all_rows: Vec<Value> = Vec::new();
    let mut all_items: Vec<(String, api::DashboardCatalogItem)> = Vec::new();
    for (profile, result) in per_profile {
        match result {
            Ok(resp) => {
                for item in resp.items {
                    all_rows.push(catalog_item_to_json(&item, include_profile, &profile));
                    all_items.push((profile.clone(), item));
                }
            }
            Err(e) => eprintln!("{}", format!("error from profile '{profile}': {e:#}").red()),
        }
    }

    // Render
    match output {
        OutputFormat::Json => render::render_json(&all_rows)?,
        OutputFormat::Agents => {
            let toon =
                toon_encode(&all_rows).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_items.is_empty() {
                render::print_no_results("No dashboards found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = all_items
                .iter()
                .map(|(profile, item)| {
                    vec![
                        profile.clone(),
                        item.id.clone().unwrap_or_default(),
                        item.name.clone().unwrap_or_default(),
                        item.folder
                            .as_ref()
                            .and_then(|f| f.name.clone())
                            .unwrap_or_default(),
                        item.update_time.clone().unwrap_or_default(),
                        render::bool_display(item.is_pinned),
                        render::bool_display(item.is_locked),
                    ]
                })
                .collect();
            render::render_table(
                &["ID", "Name", "Folder", "Updated", "Pinned", "Locked"],
                rows,
                include_profile,
            );
        }
    }

    Ok(())
}

pub async fn run_get(
    targets: &[Arc<ExecutionTarget>],
    dashboard_id: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!(
        "{}",
        format!("Fetching dashboard {dashboard_id}...").dimmed()
    );

    let include_profile = targets.len() > 1;
    let id = dashboard_id.to_string();

    let per_profile = fan_out(targets, |t| {
        let id = id.clone();
        async move {
            let api = DashboardsApi::new(&t.client);
            Ok(api.get(&id).await?)
        }
    })
    .await;

    // Merge
    let mut all_results: Vec<Value> = Vec::new();
    for (profile, result) in per_profile {
        match result {
            Ok(mut val) => {
                if include_profile {
                    render::tag_get_result(&mut val, &profile);
                }
                all_results.push(val);
            }
            Err(e) => eprintln!("{}", format!("error from profile '{profile}': {e:#}").red()),
        }
    }

    // Render
    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Agents => {
            let toon = toon_encode(&all_results)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            render::render_get_text(
                &all_results,
                include_profile,
                "Dashboard not found.",
                Some(&|val| {
                    let name = val
                        .get("name")
                        .or_else(|| val.get("dashboard").and_then(|d| d.get("name")))
                        .and_then(|v| v.as_str())
                        .unwrap_or("-");
                    let id = val
                        .get("id")
                        .or_else(|| val.get("dashboard").and_then(|d| d.get("id")))
                        .and_then(|v| v.as_str())
                        .unwrap_or("-");
                    let desc = val
                        .get("description")
                        .or_else(|| val.get("dashboard").and_then(|d| d.get("description")))
                        .and_then(|v| v.as_str())
                        .unwrap_or("");

                    println!("{}: {}", "Name".bold(), name);
                    println!("{}:   {}", "ID".bold(), id);
                    if !desc.is_empty() {
                        println!("{}: {}", "Desc".bold(), desc);
                    }
                }),
            )?;
        }
    }

    Ok(())
}

// ── Create ────────────────────────────────────────────────────────────────────

/// Generate a random hex string for the `requestId` envelope field.
fn new_request_id() -> String {
    let mut rng = rand::rng();
    (0..16)
        .map(|_| format!("{:02x}", rng.random::<u8>()))
        .collect()
}

/// Read a JSON payload from a file path or stdin (when `from_file == "-"`),
/// and normalize it into the inner `dashboard` object expected by the
/// `CreateDashboard` API. Accepts either the bare dashboard JSON or the
/// `{ "dashboard": {...} }` wrapper form.
fn read_dashboard_body(from_file: &str) -> Result<Value> {
    let raw = if from_file == "-" {
        eprintln!("{}", "Reading dashboard definition from stdin...".dimmed());
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf)?;
        buf
    } else {
        eprintln!(
            "{}",
            format!("Reading dashboard definition from {from_file}...").dimmed()
        );
        std::fs::read_to_string(from_file)?
    };

    let parsed: Value = serde_json::from_str(&raw)?;

    // Allow either a bare dashboard doc or a pre-wrapped request payload.
    let dashboard = if parsed.get("dashboard").is_some() {
        parsed
            .get("dashboard")
            .cloned()
            .unwrap_or_else(|| json!({}))
    } else {
        parsed
    };

    if !dashboard.is_object() {
        bail!("Dashboard JSON must be a JSON object (got {})", dashboard);
    }
    if dashboard.get("layout").is_none() {
        bail!(
            "Dashboard JSON is missing required 'layout' field. See `cx dashboards create --help`."
        );
    }

    Ok(dashboard)
}

pub async fn run_create(
    targets: &[Arc<ExecutionTarget>],
    from_file: &str,
    folder_id: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    let mut dashboard = read_dashboard_body(from_file)?;

    // Inject folder assignment if the caller provided one.
    if let Some(folder) = folder_id {
        if let Value::Object(ref mut m) = dashboard {
            m.insert(
                "folderId".to_string(),
                json!({ "value": folder.to_string() }),
            );
        }
    }

    let name = dashboard
        .get("name")
        .and_then(|v| v.as_str())
        .unwrap_or("<unnamed>")
        .to_string();

    eprintln!("{}", format!("Creating dashboard '{name}'...").dimmed());

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| {
        let dashboard = dashboard.clone();
        async move {
            let body = json!({
                "requestId": new_request_id(),
                "dashboard": dashboard,
            });
            let api = DashboardsApi::new(&t.client);
            Ok(api.create(&body).await?)
        }
    })
    .await;

    let mut all_results: Vec<(String, String, Value)> = Vec::new();
    for (profile, result) in per_profile {
        match result {
            Ok(mut resp) => {
                let created_id = resp
                    .get("dashboardId")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
                    .or_else(|| {
                        resp.get("id")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
                    })
                    .or_else(|| {
                        resp.get("dashboard")
                            .and_then(|d| d.get("id"))
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
                    })
                    .unwrap_or_else(|| "unknown".to_string());

                if include_profile {
                    render::tag_get_result(&mut resp, &profile);
                }
                all_results.push((profile, created_id, resp));
            }
            Err(e) => eprintln!("{}", format!("error from profile '{profile}': {e:#}").red()),
        }
    }

    match output {
        OutputFormat::Json => {
            let vals: Vec<Value> = all_results.iter().map(|(_, _, v)| v.clone()).collect();
            render::render_json_auto(&vals)?;
        }
        OutputFormat::Agents => {
            let vals: Vec<&Value> = all_results.iter().map(|(_, _, v)| v).collect();
            let toon =
                toon_encode(&vals).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_results.is_empty() {
                // Per-profile errors already surfaced via eprintln! above.
                return Ok(());
            }
            if include_profile {
                let rows: Vec<Vec<String>> = all_results
                    .iter()
                    .map(|(profile, id, _)| vec![profile.clone(), id.clone(), name.clone()])
                    .collect();
                render::render_table(&["ID", "Name"], rows, true);
            } else {
                let (_, id, _) = &all_results[0];
                println!(
                    "{}",
                    format!("Created dashboard '{name}' (ID: {id})")
                        .green()
                        .bold()
                );
            }
        }
    }

    Ok(())
}

// ── Delete ────────────────────────────────────────────────────────────────────

pub async fn run_delete(targets: &[Arc<ExecutionTarget>], id: &str) -> Result<()> {
    eprintln!("{}", format!("Deleting dashboard {id}...").dimmed());
    let id = id.to_string();
    let per_profile = fan_out(targets, |t| {
        let id = id.clone();
        async move {
            let api = DashboardsApi::new(&t.client);
            api.delete(&id).await?;
            Ok(())
        }
    })
    .await;
    for (profile, result) in per_profile {
        match result {
            Ok(()) => eprintln!(
                "{}",
                format!("Dashboard {id} deleted in profile '{profile}'.").green()
            ),
            Err(e) => eprintln!("{}", format!("error from profile '{profile}': {e:#}").red()),
        }
    }
    Ok(())
}

// ── Folders ───────────────────────────────────────────────────────────────────

fn folder_item_to_json(item: &DashboardFolderItem, include_profile: bool, profile: &str) -> Value {
    let mut v = json!({
        "id": item.id_str(),
        "name": item.name,
        "parent_id": item.parent_id_str(),
    });
    if include_profile {
        if let Value::Object(ref mut m) = v {
            m.insert("profile".to_string(), Value::String(profile.to_string()));
        }
    }
    v
}

pub async fn run_folders_list(
    targets: &[Arc<ExecutionTarget>],
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching dashboard folders...".dimmed());

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| async move {
        let api = DashboardsApi::new(&t.client);
        Ok(api.folders().await?)
    })
    .await;

    let mut all_rows: Vec<Value> = Vec::new();
    let mut all_items: Vec<(String, DashboardFolderItem)> = Vec::new();
    for (profile, result) in per_profile {
        match result {
            Ok(resp) => {
                for item in resp.folders {
                    all_rows.push(folder_item_to_json(&item, include_profile, &profile));
                    all_items.push((profile.clone(), item));
                }
            }
            Err(e) => eprintln!("{}", format!("error from profile '{profile}': {e:#}").red()),
        }
    }

    match output {
        OutputFormat::Json => render::render_json(&all_rows)?,
        OutputFormat::Agents => {
            let toon =
                toon_encode(&all_rows).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_items.is_empty() {
                render::print_no_results("No dashboard folders found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = all_items
                .iter()
                .map(|(profile, item)| {
                    vec![
                        profile.clone(),
                        item.id_str().unwrap_or("").to_string(),
                        item.name.clone().unwrap_or_default(),
                        item.parent_id_str().unwrap_or("").to_string(),
                    ]
                })
                .collect();
            render::render_table(&["ID", "Name", "Parent ID"], rows, include_profile);
        }
    }

    Ok(())
}

pub async fn run_folders_create(
    targets: &[Arc<ExecutionTarget>],
    name: &str,
    parent_id: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    eprintln!(
        "{}",
        format!("Creating dashboard folder '{name}'...").dimmed()
    );

    let include_profile = targets.len() > 1;
    let name_owned = name.to_string();
    let parent_id_owned = parent_id.map(|s| s.to_string());

    let per_profile = fan_out(targets, |t| {
        let name = name_owned.clone();
        let parent_id = parent_id_owned.clone();
        async move {
            let mut folder = json!({ "name": name });
            if let (Some(p), Value::Object(ref mut m)) = (parent_id.as_ref(), &mut folder) {
                m.insert("parentId".to_string(), Value::String(p.clone()));
            }
            let body = json!({
                "requestId": new_request_id(),
                "folder": folder,
            });
            let api = DashboardsApi::new(&t.client);
            Ok(api.folders_create(&body).await?)
        }
    })
    .await;

    let mut all_results: Vec<(String, String, Value)> = Vec::new();
    for (profile, result) in per_profile {
        match result {
            Ok(mut resp) => {
                let created_id = resp
                    .get("folderId")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
                    .or_else(|| {
                        resp.get("id")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
                    })
                    .unwrap_or_else(|| "unknown".to_string());
                if include_profile {
                    render::tag_get_result(&mut resp, &profile);
                }
                all_results.push((profile, created_id, resp));
            }
            Err(e) => eprintln!("{}", format!("error from profile '{profile}': {e:#}").red()),
        }
    }

    match output {
        OutputFormat::Json => {
            let vals: Vec<Value> = all_results.iter().map(|(_, _, v)| v.clone()).collect();
            render::render_json_auto(&vals)?;
        }
        OutputFormat::Agents => {
            let vals: Vec<&Value> = all_results.iter().map(|(_, _, v)| v).collect();
            let toon =
                toon_encode(&vals).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_results.is_empty() {
                return Ok(());
            }
            if include_profile {
                let rows: Vec<Vec<String>> = all_results
                    .iter()
                    .map(|(profile, id, _)| vec![profile.clone(), id.clone(), name.to_string()])
                    .collect();
                render::render_table(&["ID", "Name"], rows, true);
            } else {
                let (_, id, _) = &all_results[0];
                println!(
                    "{}",
                    format!("Created folder '{name}' (ID: {id})").green().bold()
                );
            }
        }
    }

    Ok(())
}

pub async fn run_folders_delete(targets: &[Arc<ExecutionTarget>], id: &str) -> Result<()> {
    eprintln!("{}", format!("Deleting dashboard folder {id}...").dimmed());
    let id = id.to_string();
    let per_profile = fan_out(targets, |t| {
        let id = id.clone();
        async move {
            let api = DashboardsApi::new(&t.client);
            api.folders_delete(&id).await?;
            Ok(())
        }
    })
    .await;
    for (profile, result) in per_profile {
        match result {
            Ok(()) => eprintln!(
                "{}",
                format!("Folder {id} deleted in profile '{profile}'.").green()
            ),
            Err(e) => eprintln!("{}", format!("error from profile '{profile}': {e:#}").red()),
        }
    }
    Ok(())
}