rusticity-core 0.1.9

Core AWS SDK integration for Rusticity
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
use crate::config::AwsConfig;
use crate::metrics::{MetricQuery, MetricReader};
use anyhow::Result;

pub use aws_sdk_cloudwatch::types::Statistic;

#[derive(Clone, Debug)]
pub struct LambdaFunction {
    pub name: String,
    pub arn: String,
    pub application: Option<String>,
    pub description: String,
    pub package_type: String,
    pub runtime: String,
    pub architecture: String,
    pub code_size: i64,
    pub code_sha256: String,
    pub memory_mb: i32,
    pub timeout_seconds: i32,
    pub last_modified: String,
    pub layers: Vec<LambdaLayer>,
}

#[derive(Clone, Debug)]
pub struct LambdaLayer {
    pub arn: String,
    pub code_size: i64,
}

#[derive(Clone, Debug)]
pub struct LambdaVersion {
    pub version: String,
    pub aliases: String,
    pub description: String,
    pub last_modified: String,
    pub architecture: String,
}

#[derive(Clone, Debug)]
pub struct LambdaAlias {
    pub name: String,
    pub versions: String,
    pub description: String,
}

pub struct LambdaClient {
    config: AwsConfig,
}

impl LambdaClient {
    pub fn new(config: AwsConfig) -> Self {
        Self { config }
    }

    pub async fn list_functions(&self) -> Result<Vec<LambdaFunction>> {
        let client = self.config.lambda_client();

        let mut functions = Vec::new();
        let mut next_marker: Option<String> = None;

        loop {
            let mut request = client.list_functions().max_items(100);
            if let Some(marker) = next_marker {
                request = request.marker(marker);
            }

            let response = request.send().await?;

            if let Some(funcs) = response.functions {
                for func in funcs {
                    // AWS returns last_modified in format: "2024-10-31T12:30:45.000+0000"
                    let last_modified = func
                        .last_modified
                        .as_deref()
                        .map(|s| {
                            // Try parsing with timezone
                            if let Ok(dt) =
                                chrono::DateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.3f%z")
                            {
                                dt.format("%Y-%m-%d %H:%M:%S (UTC)").to_string()
                            } else if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
                                dt.format("%Y-%m-%d %H:%M:%S (UTC)").to_string()
                            } else {
                                s.to_string()
                            }
                        })
                        .unwrap_or_default();

                    let function_name = func.function_name.unwrap_or_default();

                    // Extract application name from function name pattern
                    // e.g., "storefront-studio-beta-api" -> "storefront-studio-beta"
                    let application = function_name
                        .rsplit_once('-')
                        .map(|(prefix, _)| prefix.to_string());

                    let layers = func
                        .layers
                        .unwrap_or_default()
                        .into_iter()
                        .map(|layer| LambdaLayer {
                            arn: layer.arn.unwrap_or_default(),
                            code_size: layer.code_size,
                        })
                        .collect();

                    functions.push(LambdaFunction {
                        name: function_name,
                        arn: func.function_arn.unwrap_or_default(),
                        application,
                        description: func.description.unwrap_or_default(),
                        package_type: func
                            .package_type
                            .map(|p| format!("{:?}", p))
                            .unwrap_or_default(),
                        runtime: func.runtime.map(|r| format!("{:?}", r)).unwrap_or_default(),
                        architecture: func
                            .architectures
                            .and_then(|a| a.first().map(|arch| format!("{:?}", arch)))
                            .unwrap_or_default(),
                        code_size: func.code_size,
                        code_sha256: func.code_sha256.unwrap_or_default(),
                        memory_mb: func.memory_size.unwrap_or(0),
                        timeout_seconds: func.timeout.unwrap_or(0),
                        last_modified,
                        layers,
                    });
                }
            }

            next_marker = response.next_marker;
            if next_marker.is_none() {
                break;
            }
        }

        Ok(functions)
    }

    pub async fn list_applications(&self) -> Result<Vec<LambdaApplication>> {
        let client = self.config.cloudformation_client();

        let mut applications = Vec::new();
        let mut next_token: Option<String> = None;

        loop {
            let mut request = client.list_stacks();
            if let Some(token) = next_token {
                request = request.next_token(token);
            }

            let response = request.send().await?;

            if let Some(stacks) = response.stack_summaries {
                for stack in stacks {
                    // Only include active stacks
                    let status = stack
                        .stack_status
                        .map(|s| format!("{:?}", s))
                        .unwrap_or_default();
                    if status.contains("DELETE") {
                        continue;
                    }

                    applications.push(LambdaApplication {
                        name: stack.stack_name.unwrap_or_default(),
                        arn: stack.stack_id.unwrap_or_default(),
                        description: stack.template_description.unwrap_or_default(),
                        status,
                        last_modified: stack
                            .last_updated_time
                            .or(stack.creation_time)
                            .map(|dt| {
                                let timestamp = dt.secs();
                                let datetime = chrono::DateTime::from_timestamp(timestamp, 0)
                                    .unwrap_or_default();
                                datetime.format("%Y-%m-%d %H:%M:%S (UTC)").to_string()
                            })
                            .unwrap_or_default(),
                    });
                }
            }

            next_token = response.next_token;
            if next_token.is_none() {
                break;
            }
        }

        Ok(applications)
    }

    pub async fn list_versions(&self, function_name: &str) -> Result<Vec<LambdaVersion>> {
        let client = self.config.lambda_client();

        let mut versions = Vec::new();
        let mut next_marker: Option<String> = None;

        loop {
            let mut request = client
                .list_versions_by_function()
                .function_name(function_name)
                .max_items(100);
            if let Some(marker) = next_marker {
                request = request.marker(marker);
            }

            let response = request.send().await?;

            if let Some(vers) = response.versions {
                for ver in vers {
                    let last_modified = ver
                        .last_modified
                        .as_deref()
                        .map(|s| {
                            if let Ok(dt) =
                                chrono::DateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.3f%z")
                            {
                                dt.format("%Y-%m-%d %H:%M:%S (UTC)").to_string()
                            } else if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
                                dt.format("%Y-%m-%d %H:%M:%S (UTC)").to_string()
                            } else {
                                s.to_string()
                            }
                        })
                        .unwrap_or_default();

                    versions.push(LambdaVersion {
                        version: ver.version.unwrap_or_default(),
                        aliases: String::new(), // Will be populated below
                        description: ver.description.unwrap_or_default(),
                        last_modified,
                        architecture: ver
                            .architectures
                            .and_then(|a| a.first().map(|arch| format!("{:?}", arch)))
                            .unwrap_or_default(),
                    });
                }
            }

            next_marker = response.next_marker;
            if next_marker.is_none() {
                break;
            }
        }

        // Fetch aliases for all versions
        let aliases_response = client
            .list_aliases()
            .function_name(function_name)
            .send()
            .await?;

        if let Some(aliases) = aliases_response.aliases {
            for alias in aliases {
                let alias_name = alias.name.unwrap_or_default();

                // Add alias to primary version
                if let Some(version) = alias.function_version {
                    if let Some(ver) = versions.iter_mut().find(|v| v.version == version) {
                        if !ver.aliases.is_empty() {
                            ver.aliases.push_str(", ");
                        }
                        ver.aliases.push_str(&alias_name);
                    }
                }

                // Add alias to additional versions in routing config
                if let Some(routing_config) = alias.routing_config {
                    if let Some(additional_version_weights) =
                        routing_config.additional_version_weights
                    {
                        for (version, _weight) in additional_version_weights {
                            if let Some(ver) = versions.iter_mut().find(|v| v.version == version) {
                                if !ver.aliases.is_empty() {
                                    ver.aliases.push_str(", ");
                                }
                                ver.aliases.push_str(&alias_name);
                            }
                        }
                    }
                }
            }
        }

        Ok(versions)
    }
}

#[derive(Clone, Debug)]
pub struct LambdaApplication {
    pub name: String,
    pub arn: String,
    pub description: String,
    pub status: String,
    pub last_modified: String,
}

impl LambdaClient {
    pub async fn list_aliases(&self, function_name: &str) -> Result<Vec<LambdaAlias>> {
        let client = self.config.lambda_client();
        let response = client
            .list_aliases()
            .function_name(function_name)
            .send()
            .await?;

        let mut aliases = Vec::new();
        if let Some(alias_list) = response.aliases {
            for alias in alias_list {
                let primary_version = alias.function_version.unwrap_or_default();

                // Check for additional versions in routing config
                let mut versions_str = primary_version.clone();
                if let Some(routing_config) = alias.routing_config {
                    if let Some(additional_version_weights) =
                        routing_config.additional_version_weights
                    {
                        for (version, weight) in additional_version_weights {
                            versions_str.push_str(&format!(
                                ", {} ({}%)",
                                version,
                                (weight * 100.0) as i32
                            ));
                        }
                    }
                }

                aliases.push(LambdaAlias {
                    name: alias.name.unwrap_or_default(),
                    versions: versions_str,
                    description: alias.description.unwrap_or_default(),
                });
            }
        }

        Ok(aliases)
    }

    pub async fn get_invocations_metric(
        &self,
        function_name: &str,
        resource: Option<&str>,
    ) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "Invocations", Statistic::Sum)
            .dimension("FunctionName", function_name);
        let query = if let Some(resource) = resource {
            query.dimension("Resource", resource)
        } else {
            query
        };
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_duration_metric(
        &self,
        function_name: &str,
        stat: aws_sdk_cloudwatch::types::Statistic,
    ) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "Duration", stat)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_errors_metric(&self, function_name: &str) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "Errors", Statistic::Sum)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_throttles_metric(&self, function_name: &str) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "Throttles", Statistic::Sum)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_concurrent_executions_metric(
        &self,
        function_name: &str,
    ) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "ConcurrentExecutions", Statistic::Maximum)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_recursive_invocations_dropped_metric(
        &self,
        function_name: &str,
    ) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "RecursiveInvocationsDropped", Statistic::Sum)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_async_event_age_metric(
        &self,
        function_name: &str,
        stat: aws_sdk_cloudwatch::types::Statistic,
    ) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "AsyncEventAge", stat)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_async_events_received_metric(
        &self,
        function_name: &str,
    ) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "AsyncEventsReceived", Statistic::Sum)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_async_events_dropped_metric(
        &self,
        function_name: &str,
    ) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "AsyncEventsDropped", Statistic::Sum)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_destination_delivery_failures_metric(
        &self,
        function_name: &str,
    ) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "DestinationDeliveryFailures", Statistic::Sum)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_dead_letter_errors_metric(
        &self,
        function_name: &str,
    ) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "DeadLetterErrors", Statistic::Sum)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }

    pub async fn get_iterator_age_metric(&self, function_name: &str) -> Result<Vec<(i64, f64)>> {
        let query = MetricQuery::new("AWS/Lambda", "IteratorAge", Statistic::Maximum)
            .dimension("FunctionName", function_name);
        MetricReader::new(self.config.cloudwatch_client())
            .recent(query, 60)
            .await
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_application_extraction_from_function_name() {
        // Test typical pattern: app-name-suffix
        let name = "storefront-studio-beta-api";
        let application = name.rsplit_once('-').map(|(prefix, _)| prefix).unwrap();
        assert_eq!(application, "storefront-studio-beta");

        // Test single dash
        let name = "myapp-api";
        let application = name.rsplit_once('-').map(|(prefix, _)| prefix).unwrap();
        assert_eq!(application, "myapp");

        // Test no dash
        let name = "simplefunction";
        let application = name.rsplit_once('-').map(|(prefix, _)| prefix);
        assert_eq!(application, None);

        // Test multiple dashes
        let name = "my-complex-app-name-worker";
        let application = name.rsplit_once('-').map(|(prefix, _)| prefix).unwrap();
        assert_eq!(application, "my-complex-app-name");
    }

    #[test]
    fn test_invocations_metric_data_structure() {
        // Test that metric data is a vector of (timestamp, value) tuples
        let data: Vec<(i64, f64)> =
            vec![(1700000000, 10.0), (1700000060, 15.0), (1700000120, 20.0)];
        assert_eq!(data.len(), 3);
        assert_eq!(data[0].0, 1700000000);
        assert_eq!(data[0].1, 10.0);
    }

    #[test]
    fn test_invocations_metric_sorting() {
        // Test that data should be sorted by timestamp
        let mut data: Vec<(i64, f64)> =
            vec![(1700000120, 20.0), (1700000000, 10.0), (1700000060, 15.0)];
        data.sort_by_key(|&(timestamp, _)| timestamp);
        assert_eq!(data[0].0, 1700000000);
        assert_eq!(data[1].0, 1700000060);
        assert_eq!(data[2].0, 1700000120);
    }
}