ebman 0.34.1

k9s-style TUI for AWS Elastic Beanstalk
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
//! Cost Explorer: fetch, cache, truncation, the fleet rollup.
//!
//! Split out of the 9,515-line `app/tests.rs`. Bodies moved
//! unchanged apart from one rewrite: `super::` meant `crate::app` in
//! the flat file and would mean `crate::app::tests` here, so every
//! explicit `super::` path was re-anchored (rustfmt reflowed some
//! lines as a result, since the new path is longer).

use super::super::*;
#[allow(unused_imports)]
use super::support::*;

#[test]
fn render_fleet_cost_breaks_down_by_app_tier_health() {
    let envs = vec![
        mk_env("api-prod", "api", "Web", "Green"),
        mk_env("api-staging", "api", "Web", "Yellow"),
        mk_env("worker-prod", "api", "Worker", "Green"),
        mk_env("billing-prod", "billing", "Web", "Red"),
    ];
    let mut costs = std::collections::HashMap::new();
    costs.insert("api-prod".to_string(), 100.0);
    costs.insert("api-staging".to_string(), 25.5);
    costs.insert("worker-prod".to_string(), 40.0);
    costs.insert("billing-prod".to_string(), 60.25);
    let now = chrono::Utc::now();
    let body = crate::app::render_fleet_cost(&envs, &costs, Some(now), now);
    assert!(body.contains("Total: $225.75/mo"), "total: {body}");
    assert!(body.contains("4 env(s) covered"), "covered count: {body}");
    // Per-app cost: api = 100 + 25.5 + 40 = 165.5
    assert!(body.contains("$    165.50/mo  api"), "by app: {body}");
    assert!(body.contains("$     60.25/mo  billing"), "by app: {body}");
    // Per-tier: Web = 100 + 25.5 + 60.25 = 185.75
    assert!(body.contains("$    185.75/mo  Web"), "by tier: {body}");
    assert!(body.contains("$     40.00/mo  Worker"), "by tier: {body}");
    // Per-health: Green = 100 + 40 = 140
    assert!(body.contains("$    140.00/mo  Green"), "by health: {body}");
}

#[test]
fn render_fleet_cost_flags_uncovered_envs() {
    let envs = vec![
        mk_env("api-prod", "api", "Web", "Green"),
        mk_env("api-uncached", "api", "Web", "Green"),
    ];
    let mut costs = std::collections::HashMap::new();
    costs.insert("api-prod".to_string(), 50.0);
    let now = chrono::Utc::now();
    let body = crate::app::render_fleet_cost(&envs, &costs, Some(now), now);
    assert!(
        body.contains("1 env(s) covered, 1 without cost data"),
        "missing count: {body}"
    );
}

#[test]
fn render_fleet_cost_flags_stale_cache() {
    let envs = vec![mk_env("a", "x", "Web", "Green")];
    let mut costs = std::collections::HashMap::new();
    costs.insert("a".to_string(), 10.0);
    let now = chrono::Utc::now();
    let stale = now - chrono::Duration::hours(36);
    let body = crate::app::render_fleet_cost(&envs, &costs, Some(stale), now);
    assert!(body.contains("stale"), "stale marker: {body}");
}

#[test]
fn render_fleet_cost_no_freshness_line_when_unset() {
    let envs = vec![mk_env("a", "x", "Web", "Green")];
    let mut costs = std::collections::HashMap::new();
    costs.insert("a".to_string(), 10.0);
    let now = chrono::Utc::now();
    let body = crate::app::render_fleet_cost(&envs, &costs, None, now);
    assert!(!body.contains("Cached:"), "no cached line: {body}");
    assert!(body.contains("Total: $10.00/mo"));
}

#[test]
fn instance_hourly_usd_known_types() {
    assert!(instance_hourly_usd("t3.micro").unwrap() > 0.0);
    assert!(instance_hourly_usd("m5.large").unwrap() > 0.0);
    assert_eq!(instance_hourly_usd("not-a-real-type"), None);
}

#[test]
fn estimate_cost_handles_mixed() {
    let mk = |t: &str, az: &str| Instance {
        id: "i-1".into(),
        health: "Ok".into(),
        color: "Green".into(),
        causes: vec![],
        instance_type: t.into(),
        availability_zone: az.into(),
        launched_at: None,
    };
    let instances = vec![
        mk("t3.micro", "us-east-1a"),
        mk("t3.micro", "us-east-1b"),
        mk("unknown-type-xyz", "us-east-1c"),
    ];
    let (hourly, missing) = estimate_cost(&instances);
    assert_eq!(missing, 1);
    // Two t3.micro at $0.0104/hr each.
    assert!((hourly - 0.0208).abs() < 1e-9);
}

#[tokio::test]
async fn render_cost_column_red_tints_expensive_envs() {
    // `:cost on`: a >= $500/mo env paints its COST cell health_red.
    // poly-prod-api ($612, Green health) is the only red in its row
    // (its health dot is green), while the cheaper green-bucket
    // poly-staging-worker ($28, Green) has no red at all.
    let mut app = test_app();
    crate::demo_fixture::install(&mut app);
    app.table_state.select(None);
    let theme = app.theme.clone();
    let buf = render_buf(&mut app, 160, 30);
    let pricey = find_row(&buf, "poly-prod-api").expect("prod-api row");
    let cheap = find_row(&buf, "poly-staging-worker").expect("staging-worker row");
    assert!(
        row_has_fg(&buf, pricey, theme.health_red),
        "the $612 env should paint a health_red COST cell"
    );
    assert!(
        !row_has_fg(&buf, cheap, theme.health_red),
        "a cheap green-health env row should have no red cell"
    );
}

// --- cost refresh truncation ------------------------------------------

#[tokio::test]
async fn a_truncated_cost_refresh_keeps_the_previous_map() {
    // The truncation flag protected the 24-hour disk cache but the
    // handler still cleared and replaced the live map first — so 25 of
    // 40 envs would flip from real numbers to `—`, which renders
    // identically to "untagged", while `:fleet-cost` under-reported.
    let mut app = test_app();
    app.costs
        .set_complete([("api-prod".into(), 100.0)], chrono::Utc::now());
    app.costs
        .set_complete([("web-prod".into(), 200.0)], chrono::Utc::now());
    app.costs
        .set_complete([("worker-prod".into(), 50.0)], chrono::Utc::now());
    let before = app.costs.by_env().clone();

    app.handle_msg(AppMsg::CostsFetched {
        gen: app.generation,
        account: Some("123456789012".into()),
        region: "us-east-1".into(),
        result: Ok(crate::aws::EnvCosts {
            rows: vec![crate::aws::EnvCost {
                env_name: "api-prod".into(),
                cost_usd: 111.0,
            }],
            truncated: true,
        }),
    });

    assert_eq!(
        app.costs.by_env(),
        &before,
        "a partial walk must not replace a good map"
    );
    let msg = app.error_message.as_deref().expect("must say so");
    assert!(msg.contains("INCOMPLETE"), "{msg}");
    assert_no_run_on_spaces(msg);
}

#[tokio::test]
async fn a_truncated_cost_refresh_with_nothing_cached_shows_what_it_has() {
    // With no previous map there is nothing to preserve, so partial
    // beats blank — but it must be labelled and must not stamp a fetch
    // time that would suppress the retry.
    let mut app = test_app();
    assert!(app.costs.is_empty());

    app.handle_msg(AppMsg::CostsFetched {
        gen: app.generation,
        account: None,
        region: "us-east-1".into(),
        result: Ok(crate::aws::EnvCosts {
            rows: vec![crate::aws::EnvCost {
                env_name: "api-prod".into(),
                cost_usd: 111.0,
            }],
            truncated: true,
        }),
    });

    assert_eq!(app.costs.len(), 1, "partial data still renders");
    assert!(
        app.costs.fetched_at().is_none(),
        "an incomplete walk must not stamp a fetch time"
    );
    let msg = app.error_message.as_deref().expect("must say so");
    assert!(msg.contains("INCOMPLETE"), "{msg}");
    assert_no_run_on_spaces(msg);
}

#[tokio::test]
async fn a_complete_cost_refresh_replaces_the_map() {
    let mut app = test_app();
    app.costs
        .set_complete([("stale".into(), 999.0)], chrono::Utc::now());

    app.handle_msg(AppMsg::CostsFetched {
        gen: app.generation,
        account: None,
        region: "us-east-1".into(),
        result: Ok(crate::aws::EnvCosts {
            rows: vec![crate::aws::EnvCost {
                env_name: "api-prod".into(),
                cost_usd: 111.0,
            }],
            truncated: false,
        }),
    });

    assert_eq!(app.costs.len(), 1);
    assert!(app.costs.by_env().contains_key("api-prod"));
    assert!(
        !app.costs.by_env().contains_key("stale"),
        "a complete walk replaces"
    );
    assert!(app.costs.fetched_at().is_some());
}

#[tokio::test]
async fn a_partial_cost_map_does_not_become_permanent() {
    // The "do we already have costs?" test made partial data sticky:
    // the first truncated walk populated the map, and every later one
    // then saw a non-empty map and kept it — so the first failure's
    // data survived the session while each retry paid for twenty
    // metered Cost Explorer pages and threw them away.
    let mut app = test_app();
    assert!(app.costs.is_empty());

    let truncated = |env: &str, usd: f64| crate::aws::EnvCosts {
        rows: vec![crate::aws::EnvCost {
            env_name: env.into(),
            cost_usd: usd,
        }],
        truncated: true,
    };

    // First truncated walk: nothing to preserve, take it, mark partial.
    app.handle_msg(AppMsg::CostsFetched {
        gen: app.generation,
        account: None,
        region: "us-east-1".into(),
        result: Ok(truncated("api-prod", 100.0)),
    });
    assert!(!app.costs.is_complete(), "a truncated walk is not complete");
    assert_eq!(app.costs.get("api-prod"), Some(100.0));

    // Second truncated walk: what we hold is itself partial, so the
    // fresher partial data must replace it rather than be discarded.
    app.handle_msg(AppMsg::CostsFetched {
        gen: app.generation,
        account: None,
        region: "us-east-1".into(),
        result: Ok(truncated("web-prod", 55.0)),
    });
    assert!(!app.costs.is_complete());
    assert_eq!(app.costs.get("web-prod"), Some(55.0));
    assert!(
        !app.costs.by_env().contains_key("api-prod"),
        "the stale partial map must not accumulate"
    );

    // A complete walk clears the partial flag and wins outright.
    app.handle_msg(AppMsg::CostsFetched {
        gen: app.generation,
        account: None,
        region: "us-east-1".into(),
        result: Ok(crate::aws::EnvCosts {
            rows: vec![crate::aws::EnvCost {
                env_name: "full".into(),
                cost_usd: 1.0,
            }],
            truncated: false,
        }),
    });
    assert!(app.costs.is_complete());
    assert_eq!(app.costs.len(), 1);

    // And now a truncated walk must NOT replace the complete map.
    app.handle_msg(AppMsg::CostsFetched {
        gen: app.generation,
        account: None,
        region: "us-east-1".into(),
        result: Ok(truncated("partial", 9.0)),
    });
    assert!(
        app.costs.is_complete(),
        "a complete map survives a truncated walk"
    );
    assert_eq!(app.costs.get("full"), Some(1.0));
}

#[tokio::test]
async fn cost_status_and_fleet_cost_say_when_the_data_is_partial() {
    // A truncated walk deliberately leaves `costs_fetched_at` unset so
    // a retry isn't suppressed — which meant `:cost status` reported
    // "no data yet" while dollar figures were on screen, and
    // `:fleet-cost` rendered an under-reporting total with no marker.
    let mut app = test_app();
    app.costs.set_enabled(true);
    app.environments = vec![mk_env("api-prod", "uflexi", "Web", "Green")];
    app.rebuild_view();
    app.handle_msg(AppMsg::CostsFetched {
        gen: app.generation,
        account: None,
        region: "us-east-1".into(),
        result: Ok(crate::aws::EnvCosts {
            rows: vec![crate::aws::EnvCost {
                env_name: "api-prod".into(),
                cost_usd: 100.0,
            }],
            truncated: true,
        }),
    });
    assert!(!app.costs.is_complete());

    app.execute_command("cost status");
    let status = app.status_message.as_deref().unwrap_or_default();
    assert!(
        status.contains("INCOMPLETE"),
        ":cost status must not present partial data as settled: {status:?}"
    );

    app.error_message = None;
    app.execute_command("fleet-cost");
    let err = app.error_message.as_deref().unwrap_or_default();
    assert!(
        err.contains("under-reports"),
        ":fleet-cost must mark a partial total: {err:?}"
    );
}

#[tokio::test]
async fn switching_context_resets_the_cost_completeness_verdict() {
    // The flag belonged to the previous account; leaving it set meant
    // a fresh context inherited a stale "partial" verdict.
    let mut app = test_app();
    app.costs.set_enabled(true); // `:cost off` early-returns when already off
    app.costs
        .set_complete([("old".into(), 1.0)], chrono::Utc::now());
    // A partial walk: `set_partial` is the only way to reach this state now.
    app.costs.set_partial(app.costs.by_env().clone());
    app.execute_command("cost off");
    assert!(app.costs.is_empty());
    assert!(
        app.costs.is_complete(),
        "a torn-down map carries no verdict"
    );
}

#[tokio::test]
async fn cost_on_retries_an_incomplete_walk_instead_of_saying_already_on() {
    // `spawn_cost_fetch` has exactly one caller — the `:cost on`
    // transition — so there is no periodic refetch. Answering "already
    // on" made a truncated walk terminal for the session: the partial
    // map stayed, the INCOMPLETE toast was cleared by the next refresh
    // tick, and every env past the cap showed `—`, indistinguishable
    // from untagged.
    let mut app = test_app();
    app.costs.set_enabled(true);
    app.costs
        .set_complete([("api-prod".into(), 1.0)], chrono::Utc::now());
    // A partial walk: `set_partial` is the only way to reach this state now.
    app.costs.set_partial(app.costs.by_env().clone());

    app.execute_command("cost on");
    let msg = app.status_message.as_deref().unwrap_or_default();
    assert!(
        msg.contains("retrying"),
        ":cost on must retry an incomplete walk, not report 'already on': {msg:?}"
    );

    // With complete data it still short-circuits — no metered refetch
    // for an operator who typed it twice. Simulating "the walk finished"
    // now means saying so through `set_complete`, which also stamps the
    // fetch time — you can no longer flip the flag on its own.
    app.costs
        .set_complete(app.costs.by_env().clone(), chrono::Utc::now());
    app.execute_command("cost on");
    let msg = app.status_message.as_deref().unwrap_or_default();
    assert!(msg.contains("already on"), "{msg:?}");
}

#[tokio::test]
async fn cost_status_does_not_call_a_partial_result_cached() {
    // Reachable when a truncated walk lands over a non-empty map: the
    // previous timestamp stays, so the arm that formats it said
    // "cached" for data the handler had explicitly refused to cache.
    let mut app = test_app();
    app.costs.set_enabled(true);
    // Aged deliberately: `set_complete` takes the stamp, so "when did
    // this land" cannot be set independently of the data any more.
    app.costs.set_complete(
        [("api-prod".into(), 1.0)],
        chrono::Utc::now() - chrono::Duration::hours(3),
    );
    // A partial walk: `set_partial` is the only way to reach this state now.
    app.costs.set_partial(app.costs.by_env().clone());

    app.execute_command("cost status");
    let msg = app.status_message.as_deref().unwrap_or_default();
    assert!(msg.contains("INCOMPLETE"), "{msg:?}");
    assert!(
        !msg.contains("env(s) cached"),
        "a partial result was never cached: {msg:?}"
    );
}