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
use serde::Deserialize;
use serde_json::Value;

use crate::error::Result;

use crate::api_client::CxClient;
use crate::serde_helpers::string_or_number;

// --- Response types ---

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlertDef {
    #[serde(default, deserialize_with = "string_or_number")]
    pub id: Option<String>,
    pub name: Option<String>,
    pub description: Option<String>,
    pub enabled: Option<bool>,
    pub priority: Option<String>,
    #[serde(rename = "type")]
    pub alert_type: Option<String>,
    pub status: Option<String>,
    pub created_time: Option<String>,
    pub updated_time: Option<String>,
    pub last_triggered_time: Option<String>,
    pub alert_def_properties: Option<Value>,
}

impl AlertDef {
    /// Strip "ALERT_DEF_PRIORITY_" prefix → "P3"
    pub fn display_priority(&self) -> String {
        self.priority
            .as_deref()
            .or_else(|| {
                self.alert_def_properties
                    .as_ref()
                    .and_then(|p| p.get("priority"))
                    .and_then(|v| v.as_str())
            })
            .map(|s| {
                s.strip_prefix("ALERT_DEF_PRIORITY_")
                    .unwrap_or(s)
                    .to_string()
            })
            .unwrap_or_else(|| "-".to_string())
    }

    /// Strip "ALERT_DEF_TYPE_" prefix and convert to human name → "Logs Threshold"
    pub fn display_type(&self) -> String {
        self.alert_type
            .as_deref()
            .or_else(|| {
                self.alert_def_properties
                    .as_ref()
                    .and_then(|p| p.get("type"))
                    .and_then(|v| v.as_str())
            })
            .map(|s| {
                let stripped = s.strip_prefix("ALERT_DEF_TYPE_").unwrap_or(s);
                stripped
                    .split('_')
                    .map(|w| {
                        let mut c = w.chars();
                        match c.next() {
                            None => String::new(),
                            Some(first) => {
                                first.to_uppercase().to_string() + &c.as_str().to_lowercase()
                            }
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .unwrap_or_else(|| "-".to_string())
    }

    /// Get name, falling back to alert_def_properties.name
    pub fn display_name(&self) -> String {
        self.name
            .as_deref()
            .or_else(|| {
                self.alert_def_properties
                    .as_ref()
                    .and_then(|p| p.get("name"))
                    .and_then(|v| v.as_str())
            })
            .unwrap_or("-")
            .to_string()
    }

    /// Get description, falling back to alert_def_properties.description
    pub fn display_description(&self) -> String {
        self.description
            .as_deref()
            .or_else(|| {
                self.alert_def_properties
                    .as_ref()
                    .and_then(|p| p.get("description"))
                    .and_then(|v| v.as_str())
            })
            .unwrap_or("")
            .to_string()
    }

    /// Get enabled, falling back to alert_def_properties.enabled
    pub fn display_enabled(&self) -> Option<bool> {
        self.enabled.or_else(|| {
            self.alert_def_properties
                .as_ref()
                .and_then(|p| p.get("enabled"))
                .and_then(|v| v.as_bool())
        })
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListAlertsResponse {
    #[serde(default)]
    pub alert_defs: Vec<AlertDef>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAlertResponse {
    pub alert_def: Option<AlertDef>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateAlertResponse {
    pub alert_def: Option<AlertDef>,
}

#[derive(Debug, Deserialize)]
pub struct SetActiveResponse {}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlertEvent {
    #[serde(default, deserialize_with = "string_or_number")]
    pub id: Option<String>,
    #[serde(default, deserialize_with = "string_or_number")]
    pub alert_def_id: Option<String>,
    pub alert_name: Option<String>,
    pub severity: Option<String>,
    pub status: Option<String>,
    pub triggered_at: Option<String>,
    pub resolved_at: Option<String>,
}

impl AlertEvent {
    pub fn display_severity(&self) -> String {
        self.severity
            .as_deref()
            .map(|s| {
                s.strip_prefix("ALERT_EVENT_SEVERITY_")
                    .or_else(|| s.strip_prefix("ALERT_DEF_PRIORITY_"))
                    .unwrap_or(s)
                    .to_string()
            })
            .unwrap_or_else(|| "-".to_string())
    }

    pub fn display_status(&self) -> String {
        self.status
            .as_deref()
            .map(|s| {
                s.strip_prefix("ALERT_EVENT_STATUS_")
                    .unwrap_or(s)
                    .to_string()
            })
            .unwrap_or_else(|| "-".to_string())
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListAlertEventsResponse {
    #[serde(default)]
    pub alert_events: Vec<AlertEvent>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAlertEventStatsResponse {
    #[serde(default)]
    pub stats: Vec<serde_json::Value>,
}

// --- API ---

const ALERTS_BASE: &str = "/mgmt/openapi/latest/alerts/alerts-general/v3";

pub struct AlertsApi<'a> {
    client: &'a CxClient,
}

impl<'a> AlertsApi<'a> {
    pub fn new(client: &'a CxClient) -> Self {
        Self { client }
    }

    /// List all alert definitions.
    pub async fn list(&self) -> Result<ListAlertsResponse> {
        self.client.get(ALERTS_BASE, &[]).await
    }

    /// Get a single alert definition by alert def ID (returns raw JSON - preserves the full API response).
    pub async fn get(&self, id: &str) -> Result<Value> {
        let path = format!("{ALERTS_BASE}/{id}");
        self.client.get(&path, &[]).await
    }

    /// Get a single alert definition by alert version ID.
    pub async fn get_by_version_id(&self, version_id: &str) -> Result<Value> {
        let path = format!("{ALERTS_BASE}/alert-version-id/{version_id}");
        self.client.get(&path, &[]).await
    }

    /// Create an alert definition from a JSON body.
    pub async fn create(&self, body: &Value) -> Result<CreateAlertResponse> {
        self.client.post(ALERTS_BASE, body).await
    }

    /// Enable or disable an alert definition.
    pub async fn set_active(&self, id: &str, active: bool) -> Result<SetActiveResponse> {
        let path = format!("{ALERTS_BASE}/{id}:setActive");
        let val = if active { "true" } else { "false" };
        self.client.post_empty(&path, &[("active", val)]).await
    }

    /// List alert events.
    pub async fn list_events(&self, params: &[(&str, &str)]) -> Result<ListAlertEventsResponse> {
        let path = format!("{ALERTS_BASE}/all/events");
        self.client.get(&path, params).await
    }

    /// Get alert event statistics.
    pub async fn event_stats(&self) -> Result<GetAlertEventStatsResponse> {
        self.client
            .get("/mgmt/openapi/5/v3/alert-event-stats", &[])
            .await
    }
}

// --- Tests ---

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn deserialize_list_response() {
        let json = json!({
            "alertDefs": [
                {
                    "id": "abc-123",
                    "name": "High Error Rate",
                    "enabled": true,
                    "priority": "ALERT_DEF_PRIORITY_P2",
                    "type": "ALERT_DEF_TYPE_LOGS_THRESHOLD",
                    "status": "OK",
                    "updatedTime": "2024-06-01T12:00:00Z"
                },
                {
                    "id": "def-456",
                    "name": "CPU Alert",
                    "enabled": false,
                    "priority": "ALERT_DEF_PRIORITY_P1",
                    "type": "ALERT_DEF_TYPE_METRIC_THRESHOLD",
                    "status": "ALERTING"
                }
            ]
        });

        let resp: ListAlertsResponse = serde_json::from_value(json).unwrap();
        assert_eq!(resp.alert_defs.len(), 2);
        assert_eq!(resp.alert_defs[0].id.as_deref(), Some("abc-123"));
        assert_eq!(resp.alert_defs[0].name.as_deref(), Some("High Error Rate"));
        assert_eq!(resp.alert_defs[0].enabled, Some(true));
        assert_eq!(resp.alert_defs[1].status.as_deref(), Some("ALERTING"));
    }

    #[test]
    fn deserialize_empty_list() {
        let json = json!({});
        let resp: ListAlertsResponse = serde_json::from_value(json).unwrap();
        assert!(resp.alert_defs.is_empty());
    }

    #[test]
    fn display_priority_strips_prefix() {
        let alert = AlertDef {
            id: None,
            name: None,
            description: None,
            enabled: None,
            priority: Some("ALERT_DEF_PRIORITY_P3".to_string()),
            alert_type: None,
            status: None,
            created_time: None,
            updated_time: None,
            last_triggered_time: None,
            alert_def_properties: None,
        };
        assert_eq!(alert.display_priority(), "P3");
    }

    #[test]
    fn display_type_strips_prefix_and_titlecases() {
        let alert = AlertDef {
            id: None,
            name: None,
            description: None,
            enabled: None,
            priority: None,
            alert_type: Some("ALERT_DEF_TYPE_LOGS_THRESHOLD".to_string()),
            status: None,
            created_time: None,
            updated_time: None,
            last_triggered_time: None,
            alert_def_properties: None,
        };
        assert_eq!(alert.display_type(), "Logs Threshold");
    }

    #[test]
    fn display_type_metric_threshold() {
        let alert = AlertDef {
            id: None,
            name: None,
            description: None,
            enabled: None,
            priority: None,
            alert_type: Some("ALERT_DEF_TYPE_METRIC_THRESHOLD".to_string()),
            status: None,
            created_time: None,
            updated_time: None,
            last_triggered_time: None,
            alert_def_properties: None,
        };
        assert_eq!(alert.display_type(), "Metric Threshold");
    }

    #[test]
    fn display_fallback_to_properties() {
        let alert = AlertDef {
            id: None,
            name: None,
            description: None,
            enabled: None,
            priority: None,
            alert_type: None,
            status: None,
            created_time: None,
            updated_time: None,
            last_triggered_time: None,
            alert_def_properties: Some(json!({
                "name": "From Properties",
                "priority": "ALERT_DEF_PRIORITY_P5",
                "type": "ALERT_DEF_TYPE_LOGS_IMMEDIATE",
                "enabled": true
            })),
        };
        assert_eq!(alert.display_name(), "From Properties");
        assert_eq!(alert.display_priority(), "P5");
        assert_eq!(alert.display_type(), "Logs Immediate");
        assert_eq!(alert.display_enabled(), Some(true));
    }

    #[test]
    fn display_missing_fields() {
        let alert = AlertDef {
            id: None,
            name: None,
            description: None,
            enabled: None,
            priority: None,
            alert_type: None,
            status: None,
            created_time: None,
            updated_time: None,
            last_triggered_time: None,
            alert_def_properties: None,
        };
        assert_eq!(alert.display_name(), "-");
        assert_eq!(alert.display_priority(), "-");
        assert_eq!(alert.display_type(), "-");
        assert_eq!(alert.display_enabled(), None);
    }

    #[test]
    fn deserialize_get_response() {
        let json = json!({
            "alertDef": {
                "id": "abc-123",
                "name": "Test Alert"
            }
        });
        let resp: GetAlertResponse = serde_json::from_value(json).unwrap();
        assert_eq!(resp.alert_def.unwrap().id.as_deref(), Some("abc-123"));
    }

    #[test]
    fn deserialize_get_by_version_id_response() {
        // GetAlertDefByVersionIdResponse has the same shape as GetAlertResponse
        let json = json!({
            "alertDef": {
                "id": "abc-123",
                "name": "Versioned Alert"
            }
        });
        let resp: GetAlertResponse = serde_json::from_value(json).unwrap();
        let def = resp.alert_def.unwrap();
        assert_eq!(def.id.as_deref(), Some("abc-123"));
        assert_eq!(def.name.as_deref(), Some("Versioned Alert"));
    }

    #[test]
    fn deserialize_create_response() {
        let json = json!({
            "alertDef": {
                "id": "new-id",
                "name": "Created Alert"
            }
        });
        let resp: CreateAlertResponse = serde_json::from_value(json).unwrap();
        let def = resp.alert_def.unwrap();
        assert_eq!(def.id.as_deref(), Some("new-id"));
        assert_eq!(def.name.as_deref(), Some("Created Alert"));
    }

    #[test]
    fn deserialize_set_active_response() {
        let json = json!({});
        let _resp: SetActiveResponse = serde_json::from_value(json).unwrap();
    }
}