forked from DataDog/pup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogs.rs
More file actions
1406 lines (1262 loc) · 41.8 KB
/
Copy pathlogs.rs
File metadata and controls
1406 lines (1262 loc) · 41.8 KB
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use anyhow::{bail, Result};
use datadog_api_client::datadogV2::api_logs::{ListLogsOptionalParams, LogsAPI};
use datadog_api_client::datadogV2::api_logs_archives::LogsArchivesAPI;
use datadog_api_client::datadogV2::api_logs_custom_destinations::LogsCustomDestinationsAPI;
use datadog_api_client::datadogV2::api_logs_metrics::LogsMetricsAPI;
use datadog_api_client::datadogV2::model::{
LogsListRequest, LogsListRequestPage, LogsQueryFilter, LogsSort, LogsStorageTier,
};
use crate::config::Config;
use crate::formatter;
use crate::raw_client;
use crate::util;
use crate::util_ext;
const SAVED_VIEWS_PATH: &str = "/api/v1/logs/views";
pub struct AggregateArgs {
pub query: String,
pub from: String,
pub to: String,
pub compute: Vec<String>,
pub group_by: Vec<String>,
pub limit: i32,
pub index: Vec<String>,
pub storage: Option<String>,
pub sort: String,
pub interval: Option<String>,
}
pub struct SearchArgs {
pub query: String,
pub from: String,
pub to: String,
pub limit: i32,
pub cursor: Option<String>,
pub pages: u32,
pub sort: String,
pub storage: Option<String>,
pub index: Vec<String>,
}
fn normalize_storage_tier(storage: Option<String>) -> Result<Option<String>> {
match storage {
None => Ok(None),
Some(s) => match s.to_lowercase().as_str() {
"indexes" => Ok(Some("indexes".into())),
"online-archives" | "online_archives" => Ok(Some("online-archives".into())),
"flex" => Ok(Some("flex".into())),
other => anyhow::bail!(
"unknown storage tier {:?}; valid values are: indexes, online-archives, flex",
other
),
},
}
}
fn parse_storage_tier(storage: Option<String>) -> Result<Option<LogsStorageTier>> {
match normalize_storage_tier(storage)? {
None => Ok(None),
Some(tier) => match tier.as_str() {
"indexes" => Ok(Some(LogsStorageTier::INDEXES)),
"online-archives" => Ok(Some(LogsStorageTier::ONLINE_ARCHIVES)),
"flex" => Ok(Some(LogsStorageTier::FLEX)),
_ => unreachable!("storage tier is normalized"),
},
}
}
/// Split a comma-separated compute string into individual compute expressions,
/// respecting parentheses so that `percentile(@duration, 95)` is not split.
pub fn split_compute_args(input: &str) -> Vec<String> {
let mut result = Vec::new();
let mut current = String::new();
let mut depth = 0u32;
for ch in input.chars() {
match ch {
'(' => {
depth += 1;
current.push(ch);
}
')' => {
depth = depth.saturating_sub(1);
current.push(ch);
}
',' if depth == 0 => {
let trimmed = current.trim().to_string();
if !trimmed.is_empty() {
result.push(trimmed);
}
current.clear();
}
_ => current.push(ch),
}
}
let trimmed = current.trim().to_string();
if !trimmed.is_empty() {
result.push(trimmed);
}
result
}
const VALID_SORT_AGGREGATIONS: &[&str] = &[
"count",
"cardinality",
"pc75",
"pc90",
"pc95",
"pc98",
"pc99",
"sum",
"min",
"max",
];
fn parse_aggregate_sort(sort: &str) -> Result<serde_json::Value> {
let sort = sort.trim().to_lowercase();
if !VALID_SORT_AGGREGATIONS.contains(&sort.as_str()) {
bail!(
"unknown sort aggregation {:?}; valid values are: {}",
sort,
VALID_SORT_AGGREGATIONS.join(", ")
);
}
Ok(serde_json::json!({
"type": "measure",
"order": "desc",
"aggregation": sort
}))
}
#[allow(clippy::too_many_arguments)]
fn build_aggregate_body(
query: String,
from_ms: i64,
to_ms: i64,
computes: Vec<String>,
group_bys: Vec<String>,
limit: i32,
index: Vec<String>,
storage: Option<String>,
sort: &str,
interval: Option<String>,
) -> Result<serde_json::Value> {
let storage_tier = normalize_storage_tier(storage)?;
let interval = match interval {
Some(iv) => Some(util_ext::parse_duration_to_millis(&iv)?.to_string()),
None => None,
};
let mut filter = serde_json::json!({
"query": query,
"from": from_ms.to_string(),
"to": to_ms.to_string()
});
if !index.is_empty() {
filter["indexes"] = serde_json::json!(index);
}
if let Some(tier) = storage_tier {
filter["storage_tier"] = serde_json::Value::String(tier);
}
let compute_arr: Vec<serde_json::Value> = computes
.iter()
.map(|c| {
let (aggregation, metric) = util_ext::parse_compute_raw(c)?;
let mut obj = serde_json::json!({ "aggregation": aggregation });
if let Some(m) = metric {
obj["metric"] = serde_json::Value::String(m);
}
if let Some(iv) = &interval {
obj["type"] = serde_json::Value::String("timeseries".into());
obj["interval"] = serde_json::Value::String(iv.clone());
}
Ok(obj)
})
.collect::<Result<Vec<_>>>()?;
let mut body = serde_json::json!({
"filter": filter,
"compute": compute_arr
});
if !group_bys.is_empty() {
let sort_obj = parse_aggregate_sort(sort)?;
let group_by_arr: Vec<serde_json::Value> = group_bys
.iter()
.map(|facet| {
let mut obj = serde_json::json!({ "facet": facet, "sort": sort_obj });
if limit > 0 {
obj["limit"] = serde_json::json!(limit);
}
obj
})
.collect();
body["group_by"] = serde_json::json!(group_by_arr);
}
Ok(body)
}
fn parse_logs_sort(sort: &str) -> LogsSort {
match sort {
"timestamp" | "asc" | "+timestamp" => LogsSort::TIMESTAMP_ASCENDING,
_ => LogsSort::TIMESTAMP_DESCENDING,
}
}
fn append_log_page(aggregated: &mut Option<serde_json::Value>, page: serde_json::Value) {
if let Some(aggregated) = aggregated {
if let Some(page_data) = page.get("data").and_then(|value| value.as_array()) {
if let Some(data) = aggregated
.get_mut("data")
.and_then(|value| value.as_array_mut())
{
data.extend(page_data.iter().cloned());
} else {
aggregated["data"] = serde_json::Value::Array(page_data.to_vec());
}
}
if let Some(meta) = page.get("meta") {
aggregated["meta"] = meta.clone();
}
} else {
*aggregated = Some(page);
}
}
fn next_log_cursor(response: &serde_json::Value) -> Option<String> {
response
.pointer("/meta/page/after")
.and_then(|value| value.as_str())
.filter(|cursor| !cursor.is_empty())
.map(str::to_owned)
}
pub async fn search(cfg: &Config, args: SearchArgs) -> Result<()> {
let SearchArgs {
query,
from,
to,
limit,
cursor,
pages,
sort,
storage,
index,
} = args;
if pages == 0 {
bail!("--pages must be at least 1");
}
let api = crate::make_api!(LogsAPI, cfg);
let from_ms = util_ext::parse_time_to_unix_millis(&from)?;
let to_ms = util_ext::parse_time_to_unix_millis(&to)?;
let storage_tier = parse_storage_tier(storage)?;
let mut filter = LogsQueryFilter::new()
.query(query)
.from(from_ms.to_string())
.to(to_ms.to_string());
if !index.is_empty() {
filter = filter.indexes(index);
}
if let Some(tier) = storage_tier {
filter = filter.storage_tier(tier);
}
let mut request_cursor = cursor;
let mut response: Option<serde_json::Value> = None;
let mut next_cursor = None;
for _ in 0..pages {
let requested_cursor = request_cursor.clone();
let mut page = LogsListRequestPage::new().limit(limit);
if let Some(cursor) = requested_cursor.clone() {
page = page.cursor(cursor);
}
let body = LogsListRequest::new()
.filter(filter.clone())
.page(page)
.sort(parse_logs_sort(&sort));
let params = ListLogsOptionalParams::default().body(body);
let resp = api
.list_logs(params)
.await
.map_err(|e| anyhow::anyhow!("failed to search logs: {:?}", e))?;
let page_response = serde_json::to_value(&resp)?;
let has_results = page_response
.get("data")
.and_then(|data| data.as_array())
.is_some_and(|data| !data.is_empty());
let returned_cursor = next_log_cursor(&page_response);
append_log_page(&mut response, page_response);
next_cursor = returned_cursor.clone();
if !has_results {
next_cursor = None;
break;
}
match returned_cursor {
Some(after) if requested_cursor.as_deref() != Some(after.as_str()) => {
request_cursor = Some(after);
}
_ => {
next_cursor = None;
break;
}
}
}
let response = response.unwrap_or_else(|| serde_json::json!({}));
let meta = if cfg.agent_mode {
let count = response
.get("data")
.and_then(|data| data.as_array())
.map(|data| data.len());
let truncated = next_cursor.is_some() || count.is_some_and(|c| c as i32 >= limit);
Some(formatter::Metadata {
count,
truncated,
command: Some("logs search".into()),
next_action: next_cursor
.map(|cursor| format!("More results available. Use --cursor=\"{cursor}\" to retrieve the next page."))
.or_else(|| {
if truncated {
Some(format!(
"Results may be truncated at {limit}. Use --limit={} or narrow the --query",
limit + 1
))
} else {
None
}
}),
})
} else {
None
};
formatter::format_and_print(
&response,
&cfg.output_format,
cfg.agent_mode,
meta.as_ref(),
cfg.jq.as_deref(),
)?;
Ok(())
}
/// Alias for `search` with the same interface.
pub async fn list(cfg: &Config, args: SearchArgs) -> Result<()> {
search(cfg, args).await
}
/// Alias for `search` with the same interface.
pub async fn query(cfg: &Config, args: SearchArgs) -> Result<()> {
search(cfg, args).await
}
pub async fn aggregate(cfg: &Config, args: AggregateArgs) -> Result<()> {
let AggregateArgs {
query,
from,
to,
mut compute,
group_by,
limit,
index,
storage,
sort,
interval,
} = args;
if compute.is_empty() {
compute.push("count".into());
}
let from_ms = util_ext::parse_time_to_unix_millis(&from)?;
let to_ms = util_ext::parse_time_to_unix_millis(&to)?;
let body = build_aggregate_body(
query, from_ms, to_ms, compute, group_by, limit, index, storage, &sort, interval,
)?;
let data = raw_client::raw_post(cfg, "/api/v2/logs/analytics/aggregate", body).await?;
formatter::output(cfg, &data)?;
Ok(())
}
pub async fn archives_list(cfg: &Config) -> Result<()> {
let api = crate::make_api!(LogsArchivesAPI, cfg);
let resp = api
.list_logs_archives()
.await
.map_err(|e| anyhow::anyhow!("failed to list log archives: {:?}", e))?;
formatter::output(cfg, &resp)?;
Ok(())
}
pub async fn archives_get(cfg: &Config, archive_id: &str) -> Result<()> {
let api = crate::make_api!(LogsArchivesAPI, cfg);
let resp = api
.get_logs_archive(archive_id.to_string())
.await
.map_err(|e| anyhow::anyhow!("failed to get log archive: {:?}", e))?;
formatter::output(cfg, &resp)?;
Ok(())
}
pub async fn archives_delete(cfg: &Config, archive_id: &str) -> Result<()> {
let api = crate::make_api!(LogsArchivesAPI, cfg);
api.delete_logs_archive(archive_id.to_string())
.await
.map_err(|e| anyhow::anyhow!("failed to delete log archive: {:?}", e))?;
println!("Log archive {archive_id} deleted.");
Ok(())
}
pub async fn custom_destinations_list(cfg: &Config) -> Result<()> {
let api = crate::make_api!(LogsCustomDestinationsAPI, cfg);
let resp = api
.list_logs_custom_destinations()
.await
.map_err(|e| anyhow::anyhow!("failed to list custom destinations: {:?}", e))?;
formatter::output(cfg, &resp)?;
Ok(())
}
pub async fn custom_destinations_get(cfg: &Config, destination_id: &str) -> Result<()> {
let api = crate::make_api!(LogsCustomDestinationsAPI, cfg);
let resp = api
.get_logs_custom_destination(destination_id.to_string())
.await
.map_err(|e| anyhow::anyhow!("failed to get custom destination: {:?}", e))?;
formatter::output(cfg, &resp)?;
Ok(())
}
pub async fn metrics_list(cfg: &Config) -> Result<()> {
let api = crate::make_api!(LogsMetricsAPI, cfg);
let resp = api
.list_logs_metrics()
.await
.map_err(|e| anyhow::anyhow!("failed to list log-based metrics: {:?}", e))?;
formatter::output(cfg, &resp)?;
Ok(())
}
pub async fn metrics_get(cfg: &Config, metric_id: &str) -> Result<()> {
let api = crate::make_api!(LogsMetricsAPI, cfg);
let resp = api
.get_logs_metric(metric_id.to_string())
.await
.map_err(|e| anyhow::anyhow!("failed to get log-based metric: {:?}", e))?;
formatter::output(cfg, &resp)?;
Ok(())
}
pub async fn metrics_delete(cfg: &Config, metric_id: &str) -> Result<()> {
let api = crate::make_api!(LogsMetricsAPI, cfg);
api.delete_logs_metric(metric_id.to_string())
.await
.map_err(|e| anyhow::anyhow!("failed to delete log-based metric: {:?}", e))?;
println!("Log-based metric {metric_id} deleted.");
Ok(())
}
// ---------------------------------------------------------------------------
// Restriction Queries (raw HTTP - not available in typed client)
// ---------------------------------------------------------------------------
pub async fn restriction_queries_list(cfg: &Config) -> Result<()> {
let data = raw_client::raw_get(cfg, "/api/v2/logs/config/restriction_queries", &[]).await?;
formatter::output(cfg, &data)
}
pub async fn restriction_queries_get(cfg: &Config, query_id: &str) -> Result<()> {
let path = format!("/api/v2/logs/config/restriction_queries/{query_id}");
let data = raw_client::raw_get(cfg, &path, &[]).await?;
formatter::output(cfg, &data)
}
// ---------------------------------------------------------------------------
// Saved Views (raw HTTP - not available in typed client)
// ---------------------------------------------------------------------------
pub async fn saved_views_list(cfg: &Config) -> Result<()> {
let data = raw_client::raw_get(cfg, SAVED_VIEWS_PATH, &[]).await?;
formatter::output(cfg, &data)
}
pub async fn saved_views_get(cfg: &Config, view_id: &str) -> Result<()> {
let path = format!("{SAVED_VIEWS_PATH}/{view_id}");
let data = raw_client::raw_get(cfg, &path, &[]).await?;
formatter::output(cfg, &data)
}
pub async fn saved_views_create(cfg: &Config, file: &str) -> Result<()> {
let body: serde_json::Value = util::read_json_file(file)?;
let data = raw_client::raw_post(cfg, SAVED_VIEWS_PATH, body).await?;
formatter::output(cfg, &data)
}
pub async fn saved_views_delete(cfg: &Config, view_id: &str) -> Result<()> {
let path = format!("{SAVED_VIEWS_PATH}/{view_id}");
raw_client::raw_delete(cfg, &path).await?;
println!("Log saved view {view_id} deleted.");
Ok(())
}
#[cfg(test)]
mod tests {
use crate::config::{Config, OutputFormat};
use crate::test_support::*;
use super::*;
fn search_args(query: &str, storage: Option<String>, index: Vec<String>) -> SearchArgs {
SearchArgs {
query: query.into(),
from: "1h".into(),
to: "now".into(),
limit: 10,
cursor: None,
pages: 1,
sort: "-timestamp".into(),
storage,
index,
}
}
#[test]
fn test_append_log_page_combines_data_and_keeps_latest_meta() {
let mut response = None;
append_log_page(
&mut response,
serde_json::json!({
"data": [{"id": "log-1"}],
"meta": {"page": {"after": "cursor-2"}}
}),
);
append_log_page(
&mut response,
serde_json::json!({
"data": [{"id": "log-2"}],
"meta": {"page": {}}
}),
);
assert_eq!(
response.unwrap(),
serde_json::json!({
"data": [{"id": "log-1"}, {"id": "log-2"}],
"meta": {"page": {}}
})
);
}
#[test]
fn test_normalize_storage_tier_alias() {
let tier = normalize_storage_tier(Some("online_archives".into())).unwrap();
assert_eq!(tier.unwrap(), "online-archives");
}
#[test]
fn test_build_aggregate_body_includes_compute_group_by_limit_and_storage() {
let body = build_aggregate_body(
"service:web".into(),
1,
2,
vec!["avg(@duration)".into()],
vec!["service".into()],
3,
vec![],
Some("flex".into()),
"count",
None,
)
.unwrap();
assert_eq!(
body,
serde_json::json!({
"filter": {
"query": "service:web",
"from": "1",
"to": "2",
"storage_tier": "flex"
},
"compute": [{
"aggregation": "avg",
"metric": "@duration"
}],
"group_by": [{
"facet": "service",
"limit": 3,
"sort": {
"type": "measure",
"order": "desc",
"aggregation": "count"
}
}]
})
);
}
#[test]
fn test_build_aggregate_body_omits_group_by_for_plain_count() {
let body = build_aggregate_body(
"*".into(),
1,
2,
vec!["count".into()],
vec![],
10,
vec![],
None,
"count",
None,
)
.unwrap();
assert_eq!(
body,
serde_json::json!({
"filter": {
"query": "*",
"from": "1",
"to": "2"
},
"compute": [{
"aggregation": "count"
}]
})
);
}
#[test]
fn test_build_aggregate_body_multiple_computes() {
let body = build_aggregate_body(
"*".into(),
1,
2,
vec![
"count".into(),
"avg(@duration)".into(),
"percentile(@duration, 95)".into(),
],
vec![],
10,
vec![],
None,
"count",
None,
)
.unwrap();
assert_eq!(
body,
serde_json::json!({
"filter": {
"query": "*",
"from": "1",
"to": "2"
},
"compute": [
{ "aggregation": "count" },
{ "aggregation": "avg", "metric": "@duration" },
{ "aggregation": "pc95", "metric": "@duration" }
]
})
);
}
#[test]
fn test_build_aggregate_body_multiple_group_bys() {
let body = build_aggregate_body(
"*".into(),
1,
2,
vec!["count".into()],
vec!["service".into(), "status".into()],
5,
vec![],
None,
"count",
None,
)
.unwrap();
assert_eq!(
body,
serde_json::json!({
"filter": {
"query": "*",
"from": "1",
"to": "2"
},
"compute": [{ "aggregation": "count" }],
"group_by": [
{ "facet": "service", "limit": 5, "sort": { "type": "measure", "order": "desc", "aggregation": "count" } },
{ "facet": "status", "limit": 5, "sort": { "type": "measure", "order": "desc", "aggregation": "count" } }
]
})
);
}
#[test]
fn test_parse_aggregate_sort_valid_values() {
for agg in VALID_SORT_AGGREGATIONS {
let sort = parse_aggregate_sort(agg).unwrap();
assert_eq!(sort["aggregation"], *agg);
assert_eq!(sort["order"], "desc");
assert_eq!(sort["type"], "measure");
}
}
#[test]
fn test_parse_aggregate_sort_case_insensitive() {
let sort = parse_aggregate_sort("PC95").unwrap();
assert_eq!(sort["aggregation"], "pc95");
}
#[test]
fn test_parse_aggregate_sort_trims_whitespace() {
let sort = parse_aggregate_sort(" sum ").unwrap();
assert_eq!(sort["aggregation"], "sum");
}
#[test]
fn test_parse_aggregate_sort_invalid() {
let err = parse_aggregate_sort("invalid").unwrap_err();
assert!(err.to_string().contains("unknown sort aggregation"));
}
#[test]
fn test_build_aggregate_body_sort_pc95() {
let body = build_aggregate_body(
"*".into(),
1,
2,
vec!["count".into()],
vec!["host".into()],
10,
vec![],
None,
"pc95",
None,
)
.unwrap();
assert_eq!(
body["group_by"][0]["sort"],
serde_json::json!({
"type": "measure",
"order": "desc",
"aggregation": "pc95"
})
);
}
#[test]
fn test_build_aggregate_body_sort_not_included_without_group_by() {
let body = build_aggregate_body(
"*".into(),
1,
2,
vec!["count".into()],
vec![],
10,
vec![],
None,
"pc95",
None,
)
.unwrap();
assert!(body.get("group_by").is_none());
}
#[test]
fn test_build_aggregate_body_omits_empty_indexes() {
let body = build_aggregate_body(
"*".into(),
1,
2,
vec!["count".into()],
vec![],
10,
vec![],
None,
"count",
None,
)
.unwrap();
assert!(body["filter"].get("indexes").is_none());
}
#[test]
fn test_build_aggregate_body_includes_indexes() {
let body = build_aggregate_body(
"*".into(),
1,
2,
vec!["count".into()],
vec![],
10,
vec!["main".into(), "web".into()],
None,
"count",
None,
)
.unwrap();
assert_eq!(
body["filter"]["indexes"],
serde_json::json!(["main", "web"])
);
}
#[test]
fn test_build_aggregate_body_timeseries_interval() {
let body = build_aggregate_body(
"*".into(),
1,
2,
vec!["count".into(), "avg(@duration)".into()],
vec![],
10,
vec![],
None,
"count",
Some("5m".into()),
)
.unwrap();
assert_eq!(
body["compute"],
serde_json::json!([
{ "aggregation": "count", "type": "timeseries", "interval": "300000" },
{ "aggregation": "avg", "metric": "@duration", "type": "timeseries", "interval": "300000" }
])
);
}
#[test]
fn test_build_aggregate_body_invalid_interval() {
let err = build_aggregate_body(
"*".into(),
1,
2,
vec!["count".into()],
vec![],
10,
vec![],
None,
"count",
Some("bogus".into()),
)
.unwrap_err();
assert!(err.to_string().contains("unable to parse duration"));
}
#[test]
fn test_split_compute_args_single() {
assert_eq!(split_compute_args("count"), vec!["count"]);
}
#[test]
fn test_split_compute_args_multiple() {
assert_eq!(
split_compute_args("count,avg(@duration),max(@duration)"),
vec!["count", "avg(@duration)", "max(@duration)"]
);
}
#[test]
fn test_split_compute_args_preserves_parens_with_comma() {
assert_eq!(
split_compute_args("count,percentile(@duration, 95)"),
vec!["count", "percentile(@duration, 95)"]
);
}
#[test]
fn test_split_compute_args_trims_whitespace() {
assert_eq!(
split_compute_args(" count , avg(@duration) "),
vec!["count", "avg(@duration)"]
);
}
#[test]
fn test_split_compute_args_empty() {
assert!(split_compute_args("").is_empty());
}
#[tokio::test]
async fn test_logs_search() {
let _lock = lock_env().await;
let mut server = mockito::Server::new_async().await;
let cfg = test_config(&server.url());
let _mock = mock_any(&mut server, "POST", r#"{"data": [], "meta": {"page": {}}}"#).await;
let result = super::search(&cfg, search_args("status:error", None, vec![])).await;
assert!(result.is_ok(), "logs search failed: {:?}", result.err());
cleanup_env();
}
#[tokio::test]
async fn test_logs_search_supports_all_output_formats() {
let _lock = lock_env().await;
let mut server = mockito::Server::new_async().await;
let mut cfg = test_config(&server.url());
let _mock = mock_any(
&mut server,
"POST",
r#"{"data":[{"id":"log-1","attributes":{"message":"error"}}],"meta":{"page":{}}}"#,
)
.await;
for format in [
OutputFormat::Json,
OutputFormat::Yaml,
OutputFormat::Table,
OutputFormat::Csv,
OutputFormat::Tsv,
] {
cfg.output_format = format.clone();
let result = super::search(&cfg, search_args("status:error", None, vec![])).await;
assert!(
result.is_ok(),
"logs search failed for {format}: {:?}",
result.err()
);
}
cleanup_env();
}
#[tokio::test]
async fn test_logs_search_with_cursor() {
let _lock = lock_env().await;
let mut server = mockito::Server::new_async().await;
let cfg = test_config(&server.url());
let _mock = server
.mock("POST", mockito::Matcher::Any)
.match_query(mockito::Matcher::Any)
.match_body(mockito::Matcher::Regex(
r#""cursor":"cursor-abc""#.to_string(),
))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"data": [], "meta": {"page": {}}}"#)
.create_async()
.await;
let mut args = search_args("status:error", None, vec![]);
args.cursor = Some("cursor-abc".into());
let result = super::search(&cfg, args).await;
assert!(
result.is_ok(),
"logs search with cursor failed: {:?}",
result.err()
);
cleanup_env();
}
#[tokio::test]
async fn test_logs_search_fetches_requested_pages() {
let _lock = lock_env().await;
let mut server = mockito::Server::new_async().await;
let cfg = test_config(&server.url());
let first_page = server
.mock("POST", mockito::Matcher::Any)
.match_query(mockito::Matcher::Any)
.match_body(mockito::Matcher::Regex(
r#""page":\{"limit":10\}"#.to_string(),
))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"data":[{"id":"log-1"}],"meta":{"page":{"after":"cursor-2"}}}"#)
.expect(1)
.create_async()
.await;