coralogix-cli 0.1.33

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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
use std::sync::Arc;

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

pub mod api;

use crate::config::OutputFormat;
use crate::error::CxError;
use crate::execution::{fan_out, report_errors_and_collect_successes, ExecutionTarget};
use crate::render;
use api::{normalize_alert_payload, AlertDef, AlertsApi};

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

fn alert_to_json(alert: &AlertDef, include_profile: bool, profile: &str) -> Value {
    let mut v = json!({
        "id": alert.id,
        "name": alert.display_name(),
        "description": alert.display_description(),
        "type": alert.display_type(),
        "priority": alert.display_priority(),
        "enabled": alert.display_enabled(),
        "status": alert.status,
        "created_time": alert.created_time,
        "updated_time": alert.updated_time,
        "last_triggered_time": alert.last_triggered_time,
    });
    if include_profile {
        if let Value::Object(ref mut m) = v {
            m.insert("profile".to_string(), Value::String(profile.to_string()));
        }
    }
    v
}

fn event_field(event: &Value, keys: &[&str]) -> String {
    for key in keys {
        if let Some(value) = event.get(*key) {
            if let Some(s) = value.as_str() {
                return s.to_string();
            }
            if value.is_number() || value.is_boolean() {
                return value.to_string();
            }
        }
    }
    String::new()
}

fn event_to_json(event: &Value, include_profile: bool, profile: &str) -> Value {
    let mut v = event.clone();
    if include_profile {
        if let Value::Object(ref mut m) = v {
            m.insert("profile".to_string(), Value::String(profile.to_string()));
        }
    }
    v
}

fn next_page_token(pagination: Option<&Value>) -> Option<String> {
    pagination
        .and_then(|p| {
            p.get("nextPageToken")
                .or_else(|| p.get("next_page_token"))
                .or_else(|| p.get("next_page"))
        })
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .map(ToString::to_string)
}

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

pub async fn run_list(
    targets: &[Arc<ExecutionTarget>],
    name_filter: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching alerts...".dimmed());

    let include_profile = targets.len() > 1;

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

    // Merge & filter
    let mut all_json: Vec<Value> = Vec::new();
    let mut all_items: Vec<(String, AlertDef)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        let matching: Vec<AlertDef> = resp
            .alert_defs
            .into_iter()
            .filter(|alert| match name_filter {
                Some(filter) => alert
                    .display_name()
                    .to_lowercase()
                    .contains(&filter.to_lowercase()),
                None => true,
            })
            .collect();
        // Print the alerts list page link to stderr once per profile. Skip
        // when nothing matched (post-filter), since there's nothing to view.
        if !matching.is_empty() {
            crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                crate::console_url::alerts_url(b)
            })
            .await;
        }
        for alert in matching {
            let json = alert_to_json(&alert, include_profile, &profile);
            all_json.push(json);
            all_items.push((profile.clone(), alert));
        }
    }

    // Render
    match output {
        OutputFormat::Json => render::render_json(&all_json)?,
        OutputFormat::Toon => {
            let toon =
                toon_encode(&all_json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_items.is_empty() {
                render::print_no_results("No alerts found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = all_items
                .iter()
                .map(|(profile, alert)| {
                    vec![
                        profile.clone(),
                        alert.id.clone().unwrap_or_default(),
                        alert.display_name(),
                        alert.display_type(),
                        alert.display_priority(),
                        render::bool_display(alert.display_enabled()),
                        alert.status.clone().unwrap_or_default(),
                        alert.updated_time.clone().unwrap_or_default(),
                    ]
                })
                .collect();
            render::render_table(
                &[
                    "ID", "Name", "Type", "Priority", "Enabled", "Status", "Updated",
                ],
                rows,
                include_profile,
            );
        }
    }

    Ok(())
}

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

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

    let per_profile = fan_out(targets, |t| {
        let id = id.clone();
        async move {
            let api = AlertsApi::new(&t.client);
            match api.get(&id).await {
                Ok(val) => Ok(val),
                Err(CxError::Api { status: 404, .. }) => Ok(api.get_by_version_id(&id).await?),
                Err(e) => Err(anyhow::Error::from(e)),
            }
        }
    })
    .await;

    // Merge - collect raw API responses
    let mut all_results: Vec<Value> = Vec::new();
    for (profile, mut val) in report_errors_and_collect_successes(per_profile)? {
        if include_profile {
            render::tag_get_result(&mut val, &profile);
        }
        crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
            crate::console_url::alert_url(b, alert_id)
        })
        .await;
        all_results.push(val);
    }

    // Render
    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Toon => {
            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,
                "Alert not found.",
                Some(&|val| {
                    if let Some(alert_def) = val.get("alertDef") {
                        if let Ok(alert) = serde_json::from_value::<AlertDef>(alert_def.clone()) {
                            println!("{}:        {}", "Name".bold(), alert.display_name());
                            println!(
                                "{}:          {}",
                                "ID".bold(),
                                alert.id.as_deref().unwrap_or("-")
                            );
                            println!("{}:        {}", "Type".bold(), alert.display_type());
                            println!("{}:    {}", "Priority".bold(), alert.display_priority());
                            println!(
                                "{}:     {}",
                                "Enabled".bold(),
                                render::bool_display(alert.display_enabled())
                            );
                            println!(
                                "{}:      {}",
                                "Status".bold(),
                                alert.status.as_deref().unwrap_or("-")
                            );
                            let desc = alert.display_description();
                            if !desc.is_empty() {
                                println!("{}: {}", "Description".bold(), desc);
                            }
                        }
                    }
                }),
            )?;
        }
    }

    Ok(())
}

pub async fn run_create(
    targets: &[Arc<ExecutionTarget>],
    from_file: &str,
    output: OutputFormat,
) -> Result<()> {
    // Read JSON from file or stdin
    let raw = if from_file == "-" {
        eprintln!("{}", "Reading alert definition from stdin...".dimmed());
        use std::io::Read;
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf)?;
        buf
    } else {
        eprintln!(
            "{}",
            format!("Reading alert definition from {from_file}...").dimmed()
        );
        std::fs::read_to_string(from_file)?
    };

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

    // Validate that alertDefProperties exists
    if body.get("alertDefProperties").is_none() {
        bail!("JSON must contain an 'alertDefProperties' key. See `cx alerts create --help`.");
    }
    normalize_alert_payload(&mut body);

    eprintln!("{}", "Creating alert...".dimmed());

    let include_profile = targets.len() > 1;

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

    // Merge
    let mut all_results: Vec<Value> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        if let Some(alert) = resp.alert_def {
            let name = alert.display_name();
            render::print_created(
                "Created",
                "alert",
                Some(&name),
                alert.id.as_deref(),
                &profile,
            );
            if let Some(id) = alert.id.as_deref() {
                crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                    crate::console_url::alert_url(b, id)
                })
                .await;
            }
            let json = alert_to_json(&alert, include_profile, &profile);
            all_results.push(json);
        } else {
            eprintln!(
                "{}",
                format!("Alert created in profile '{profile}' but response was empty.").yellow()
            );
        }
    }

    // Render
    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Toon => {
            let toon = toon_encode(&all_results)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            // Status messages already printed to stderr above
        }
    }

    Ok(())
}

pub async fn run_delete(targets: &[Arc<ExecutionTarget>], alert_id: &str) -> Result<()> {
    eprintln!("{}", format!("Deleting alert {alert_id}...").dimmed());

    let id = alert_id.to_string();

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

    for (profile, ()) in report_errors_and_collect_successes(per_profile)? {
        eprintln!(
            "{}",
            format!("Deleted alert {alert_id} in profile '{profile}'.").green()
        );
    }

    Ok(())
}

fn replace_body_with_enabled(
    mut alert_response: Value,
    alert_id: &str,
    active: bool,
) -> Result<Value> {
    let alert_def = alert_response
        .get_mut("alertDef")
        .and_then(Value::as_object_mut)
        .ok_or_else(|| anyhow::anyhow!("Alert response did not contain 'alertDef'."))?;

    let mut properties = alert_def
        .remove("alertDefProperties")
        .ok_or_else(|| anyhow::anyhow!("Alert response did not contain 'alertDefProperties'."))?;

    let props = properties
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("'alertDefProperties' was not a JSON object."))?;
    props.insert("enabled".to_string(), Value::Bool(active));

    let mut body = json!({
        "id": alert_id,
        "alertDefProperties": properties,
    });
    normalize_alert_payload(&mut body);
    Ok(body)
}

pub async fn run_enable(targets: &[Arc<ExecutionTarget>], alert_id: &str) -> Result<()> {
    eprintln!("{}", format!("Enabling alert {alert_id}...").dimmed());

    let id = alert_id.to_string();

    let per_profile = fan_out(targets, |t| {
        let id = id.clone();
        async move {
            let api = AlertsApi::new(&t.client);
            let alert = api.get(&id).await?;
            let body = replace_body_with_enabled(alert, &id, true)?;
            api.replace(&body).await?;
            Ok(())
        }
    })
    .await;

    for (profile, ()) in report_errors_and_collect_successes(per_profile)? {
        eprintln!(
            "{}",
            format!("Alert {alert_id} enabled in profile '{profile}'.").green()
        );
        crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
            crate::console_url::alert_url(b, alert_id)
        })
        .await;
    }

    Ok(())
}

pub async fn run_disable(targets: &[Arc<ExecutionTarget>], alert_id: &str) -> Result<()> {
    eprintln!("{}", format!("Disabling alert {alert_id}...").dimmed());

    let id = alert_id.to_string();

    let per_profile = fan_out(targets, |t| {
        let id = id.clone();
        async move {
            let api = AlertsApi::new(&t.client);
            let alert = api.get(&id).await?;
            let body = replace_body_with_enabled(alert, &id, false)?;
            api.replace(&body).await?;
            Ok(())
        }
    })
    .await;

    for (profile, ()) in report_errors_and_collect_successes(per_profile)? {
        eprintln!(
            "{}",
            format!("Alert {alert_id} disabled in profile '{profile}'.").green()
        );
        crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
            crate::console_url::alert_url(b, alert_id)
        })
        .await;
    }

    Ok(())
}

pub async fn run_events(
    targets: &[Arc<ExecutionTarget>],
    alert_version_ids: &[String],
    start: Option<&str>,
    end: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching alert events...".dimmed());

    let include_profile = targets.len() > 1;
    let alert_version_ids = alert_version_ids.to_vec();
    let start_owned = start.unwrap_or("now-24h").to_string();
    let end_owned = end.unwrap_or("now").to_string();

    let per_profile = fan_out(targets, |t| {
        let alert_version_ids = alert_version_ids.clone();
        let start = start_owned.clone();
        let end = end_owned.clone();
        async move {
            let api = AlertsApi::new(&t.client);
            let start = crate::time::parse_timestamp(&start)?;
            let end = crate::time::parse_timestamp(&end)?;
            let mut all_events = Vec::new();
            let mut page_token: Option<String> = None;

            loop {
                let mut params: Vec<(&str, String)> = Vec::new();
                if alert_version_ids.is_empty() {
                    params.push(("filter.timestamp.from", start.clone()));
                    params.push(("filter.timestamp.to", end.clone()));
                    params.push(("pagination.page_size", "100".to_string()));
                } else {
                    for id in &alert_version_ids {
                        params.push(("alert_ids", id.clone()));
                    }
                    params.push(("timestamp_range.from", start.clone()));
                    params.push(("timestamp_range.to", end.clone()));
                }
                if let Some(token) = &page_token {
                    params.push(("pagination.page_token", token.clone()));
                }

                let params_ref: Vec<(&str, &str)> =
                    params.iter().map(|(k, v)| (*k, v.as_str())).collect();

                let resp = if alert_version_ids.is_empty() {
                    api.list_events(&params_ref).await?
                } else {
                    api.list_alert_events(&params_ref).await?
                };
                let next = next_page_token(resp.pagination.as_ref());
                all_events.extend(if resp.events.is_empty() {
                    resp.alert_events
                } else {
                    resp.events
                });

                match next {
                    Some(next) if page_token.as_deref() != Some(next.as_str()) => {
                        page_token = Some(next);
                    }
                    _ => break,
                }
            }
            Ok(all_events)
        }
    })
    .await;

    let mut all_json: Vec<Value> = Vec::new();
    let mut all_items: Vec<(String, Value)> = Vec::new();
    for (profile, events) in report_errors_and_collect_successes(per_profile)? {
        for event in events {
            all_json.push(event_to_json(&event, include_profile, &profile));
            all_items.push((profile.clone(), event));
        }
    }

    match output {
        OutputFormat::Json => render::render_json(&all_json)?,
        OutputFormat::Toon => {
            let toon =
                toon_encode(&all_json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_items.is_empty() {
                render::print_no_results("No alert events found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = all_items
                .iter()
                .map(|(profile, event)| {
                    vec![
                        profile.clone(),
                        event_field(event, &["cxEventKey", "id", "eventId"]),
                        event_field(event, &["cxEventType", "type", "status"]),
                        event_field(event, &["cxEventPayloadType", "alertName", "alert_name"]),
                        event_field(event, &["cxEventTimestamp", "triggeredAt", "triggered_at"]),
                        event_field(event, &["cxEventDedupKey", "dedupKey"]),
                    ]
                })
                .collect();
            render::render_table(
                &[
                    "Event Key",
                    "Type",
                    "Payload Type",
                    "Timestamp",
                    "Dedup Key",
                ],
                rows,
                include_profile,
            );
        }
    }

    Ok(())
}

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

    let include_profile = targets.len() > 1;

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

    let mut all_json: Vec<Value> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        for mut stat in resp.stats {
            if include_profile {
                if let Value::Object(ref mut m) = stat {
                    m.insert("profile".to_string(), Value::String(profile.clone()));
                }
            }
            all_json.push(stat);
        }
    }

    match output {
        OutputFormat::Json => render::render_json(&all_json)?,
        OutputFormat::Toon => {
            let toon =
                toon_encode(&all_json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_json.is_empty() {
                render::print_no_results("No alert event statistics found.");
                return Ok(());
            }
            for val in &all_json {
                println!("{}", serde_json::to_string_pretty(val)?);
            }
        }
    }

    Ok(())
}