coralogix-cli 0.1.28

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
pub mod api;

use std::sync::Arc;

use anyhow::Result;
use colored::Colorize;
use serde_json::Value;
use toon_format::encode_default as toon_encode;

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

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

pub struct CountCommandOptions<'a> {
    pub start: Option<&'a str>,
    pub end: Option<&'a str>,
    pub resolution: Option<&'a str>,
    pub subsystem_aggregation: bool,
    pub application_aggregation: bool,
    pub extra_params: &'a [String],
    pub output: OutputFormat,
}

fn build_count_query_params(options: &CountCommandOptions<'_>) -> Result<Vec<(String, String)>> {
    let from = match options
        .start
        .map(crate::time::parse_timestamp)
        .transpose()?
    {
        Some(s) => s,
        None => chrono::Utc::now()
            .checked_sub_signed(chrono::Duration::hours(24))
            .unwrap_or_else(chrono::Utc::now)
            .to_rfc3339(),
    };
    let to = match options.end.map(crate::time::parse_timestamp).transpose()? {
        Some(s) => s,
        None => chrono::Utc::now().to_rfc3339(),
    };
    let mut params = vec![
        ("date_range.fromDate".to_string(), from),
        ("date_range.toDate".to_string(), to),
    ];

    params.push((
        "resolution".to_string(),
        options.resolution.unwrap_or("1h").to_string(),
    ));
    if options.subsystem_aggregation {
        params.push(("subsystem_aggregation".to_string(), "true".to_string()));
    }
    if options.application_aggregation {
        params.push(("application_aggregation".to_string(), "true".to_string()));
    }
    for raw in options.extra_params {
        let (key, value) = raw
            .split_once('=')
            .ok_or_else(|| anyhow::anyhow!("query params must use KEY=VALUE format: {raw}"))?;
        if key.trim().is_empty() {
            anyhow::bail!("query param key cannot be empty: {raw}");
        }
        params.push((key.to_string(), value.to_string()));
    }

    Ok(params)
}

fn read_query_from_file(path: &str) -> Result<Value> {
    let raw = if path == "-" {
        eprintln!("{}", "Reading data usage query 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 data usage query from {path}...").dimmed()
        );
        std::fs::read_to_string(path)?
    };

    parse_query(&raw)
}

fn parse_query(raw: &str) -> Result<Value> {
    let query: Value = serde_json::from_str(raw)
        .map_err(|error| anyhow::anyhow!("data usage query must be valid JSON: {error}"))?;
    if !query.is_object() {
        anyhow::bail!("data usage query must be a JSON object");
    }
    Ok(query)
}

pub async fn run_summary(
    targets: &[Arc<ExecutionTarget>],
    start: Option<&str>,
    end: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching data usage summary...".dimmed());

    let include_profile = targets.len() > 1;
    let from = match start.map(crate::time::parse_timestamp).transpose()? {
        Some(s) => s,
        None => chrono::Utc::now()
            .checked_sub_signed(chrono::Duration::hours(24))
            .unwrap_or_else(chrono::Utc::now)
            .to_rfc3339(),
    };
    let to = match end.map(crate::time::parse_timestamp).transpose()? {
        Some(s) => s,
        None => chrono::Utc::now().to_rfc3339(),
    };

    let per_profile = fan_out(targets, |t| {
        let from = from.clone();
        let to = to.clone();
        async move {
            let api = DataUsageApi::new(&t.client);
            Ok(api
                .get_usage(&[
                    ("date_range.fromDate", &from),
                    ("date_range.toDate", &to),
                    ("resolution", "1h"),
                ])
                .await?)
        }
    })
    .await;

    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,
            crate::console_url::usage_url,
        )
        .await;
        all_results.push(val);
    }

    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 => {
            if all_results.is_empty() {
                render::print_no_results("No data usage found.");
                return Ok(());
            }
            for val in &all_results {
                println!("{}", serde_json::to_string_pretty(val)?);
            }
        }
    }

    Ok(())
}

pub async fn run_daily(
    targets: &[Arc<ExecutionTarget>],
    data_type: &str,
    start: Option<&str>,
    end: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    eprintln!(
        "{}",
        format!("Fetching daily {data_type} usage...").dimmed()
    );

    let include_profile = targets.len() > 1;
    let data_type = data_type.to_string();
    let from = match start.map(crate::time::parse_timestamp).transpose()? {
        Some(s) => s,
        None => chrono::Utc::now()
            .checked_sub_signed(chrono::Duration::hours(24))
            .unwrap_or_else(chrono::Utc::now)
            .to_rfc3339(),
    };
    let to = match end.map(crate::time::parse_timestamp).transpose()? {
        Some(s) => s,
        None => chrono::Utc::now().to_rfc3339(),
    };

    let per_profile = fan_out(targets, |t| {
        let data_type = data_type.clone();
        let from = from.clone();
        let to = to.clone();
        async move {
            let api = DataUsageApi::new(&t.client);
            let mut body = serde_json::Map::new();
            let mut date_range = serde_json::Map::new();
            date_range.insert("fromDate".into(), Value::String(from));
            date_range.insert("toDate".into(), Value::String(to));
            body.insert("date_range".into(), Value::Object(date_range));
            Ok(api.daily(&data_type, &Value::Object(body)).await?)
        }
    })
    .await;

    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,
            crate::console_url::usage_url,
        )
        .await;
        all_results.push(val);
    }

    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 => {
            if all_results.is_empty() {
                render::print_no_results("No daily usage data found.");
                return Ok(());
            }
            for val in &all_results {
                println!("{}", serde_json::to_string_pretty(val)?);
            }
        }
    }

    Ok(())
}

pub async fn run_logs_count(
    targets: &[Arc<ExecutionTarget>],
    options: CountCommandOptions<'_>,
) -> Result<()> {
    eprintln!("{}", "Fetching logs count...".dimmed());

    let include_profile = targets.len() > 1;
    let params = build_count_query_params(&options)?;

    let per_profile = fan_out(targets, |t| {
        let params = params.clone();
        async move {
            let api = DataUsageApi::new(&t.client);
            let params_ref: Vec<(&str, &str)> = params
                .iter()
                .map(|(k, v)| (k.as_str(), v.as_str()))
                .collect();
            Ok(api.logs_count(&params_ref).await?)
        }
    })
    .await;

    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,
            crate::console_url::usage_url,
        )
        .await;
        all_results.push(val);
    }

    match options.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 => {
            for val in &all_results {
                println!("{}", serde_json::to_string_pretty(val)?);
            }
        }
    }

    Ok(())
}

pub async fn run_spans_count(
    targets: &[Arc<ExecutionTarget>],
    options: CountCommandOptions<'_>,
) -> Result<()> {
    eprintln!("{}", "Fetching spans count...".dimmed());

    let include_profile = targets.len() > 1;
    let params = build_count_query_params(&options)?;

    let per_profile = fan_out(targets, |t| {
        let params = params.clone();
        async move {
            let api = DataUsageApi::new(&t.client);
            let params_ref: Vec<(&str, &str)> = params
                .iter()
                .map(|(k, v)| (k.as_str(), v.as_str()))
                .collect();
            Ok(api.spans_count(&params_ref).await?)
        }
    })
    .await;

    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,
            crate::console_url::usage_url,
        )
        .await;
        all_results.push(val);
    }

    match options.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 => {
            for val in &all_results {
                println!("{}", serde_json::to_string_pretty(val)?);
            }
        }
    }

    Ok(())
}

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

    let include_profile = targets.len() > 1;

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

    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,
            crate::console_url::usage_url,
        )
        .await;
        all_results.push(val);
    }

    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 => {
            for val in &all_results {
                println!("{}", serde_json::to_string_pretty(val)?);
            }
        }
    }

    Ok(())
}

/// Fetch the tenant's supported Data Usage Query API dimensions and limits.
pub async fn run_capabilities(
    targets: &[Arc<ExecutionTarget>],
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching data usage capabilities...".dimmed());

    let include_profile = targets.len() > 1;
    let per_profile = fan_out(targets, |t| async move {
        let api = DataUsageApi::new(&t.client);
        Ok(api.capabilities().await?)
    })
    .await;

    let mut all_results = Vec::new();
    for (profile, mut value) in report_errors_and_collect_successes(per_profile)? {
        if include_profile {
            render::tag_get_result(&mut value, &profile);
        }
        crate::execution::emit_console_link_for_profile(
            targets,
            &profile,
            crate::console_url::usage_url,
        )
        .await;
        all_results.push(value);
    }

    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 => {
            for value in &all_results {
                println!("{}", serde_json::to_string_pretty(value)?);
            }
        }
    }

    Ok(())
}

/// Submit a capabilities-derived Data Usage Query API request.
pub async fn run_query(
    targets: &[Arc<ExecutionTarget>],
    from_file: Option<&str>,
    inline_query: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    let query = match (from_file, inline_query) {
        (Some(path), None) => read_query_from_file(path)?,
        (None, Some(raw)) => parse_query(raw)?,
        _ => anyhow::bail!("provide exactly one of --from-file or --query"),
    };
    eprintln!("{}", "Querying data usage...".dimmed());

    let include_profile = targets.len() > 1;
    let per_profile = fan_out(targets, |t| {
        let query = query.clone();
        async move {
            let api = DataUsageApi::new(&t.client);
            Ok(api.query(&query).await?)
        }
    })
    .await;

    let mut all_results = Vec::new();
    for (profile, mut value) in report_errors_and_collect_successes(per_profile)? {
        if include_profile {
            render::tag_get_result(&mut value, &profile);
        }
        crate::execution::emit_console_link_for_profile(
            targets,
            &profile,
            crate::console_url::usage_url,
        )
        .await;
        all_results.push(value);
    }

    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 => {
            for value in &all_results {
                println!("{}", serde_json::to_string_pretty(value)?);
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{parse_query, read_query_from_file};
    use std::sync::atomic::{AtomicU64, Ordering};

    static NEXT_ID: AtomicU64 = AtomicU64::new(0);

    fn write_query(contents: &str) -> std::path::PathBuf {
        let path = std::env::temp_dir().join(format!(
            "cx-data-usage-query-unit-{}-{}.json",
            std::process::id(),
            NEXT_ID.fetch_add(1, Ordering::Relaxed)
        ));
        std::fs::write(&path, contents).unwrap();
        path
    }

    #[test]
    fn read_query_from_file_accepts_json_object() {
        let path = write_query(r#"{"daily":{"relativeRange":"DAILY_RELATIVE_RANGE_LAST_7_DAYS"}}"#);
        let query = read_query_from_file(path.to_str().unwrap()).unwrap();
        std::fs::remove_file(path).unwrap();

        assert_eq!(
            query["daily"]["relativeRange"],
            "DAILY_RELATIVE_RANGE_LAST_7_DAYS"
        );
    }

    #[test]
    fn read_query_from_file_rejects_non_object_json() {
        let path = write_query(r#"["not","a","query"]"#);
        let error = read_query_from_file(path.to_str().unwrap()).unwrap_err();
        std::fs::remove_file(path).unwrap();

        assert!(error.to_string().contains("must be a JSON object"));
    }

    #[test]
    fn parse_query_accepts_inline_json_object() {
        let query =
            parse_query(r#"{"daily":{"relativeRange":"DAILY_RELATIVE_RANGE_LAST_7_DAYS"}}"#)
                .unwrap();

        assert_eq!(
            query["daily"]["relativeRange"],
            "DAILY_RELATIVE_RANGE_LAST_7_DAYS"
        );
    }

    #[test]
    fn parse_query_reports_invalid_json_clearly() {
        let error = parse_query("sdfg").unwrap_err();

        assert!(error
            .to_string()
            .starts_with("data usage query must be valid JSON:"));
    }
}