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
//! Command handlers that open multi-account / read-only overlays
//! (`:accounts`, `:org-health`, `:find-env`). These are the heaviest
//! arms in `execute_command` — each spawns a fan-out across profiles
//! and AssumeRole accounts and lands the result as a TextOverlay. Same
//! `&mut self` pattern as the inline arms; just lifted out so
//! `execute_command` reads more like a dispatcher and the file size
//! comes down.
//!
//! Pulling overlay-only commands first (not state-mutating writes)
//! keeps the blast radius small — each method ends with a `tokio::spawn`
//! and the result lands via `AppMsg::TextOverlay`, so the refactor
//! doesn't change any sync state-transition behaviour.
use super::{flatten_err_to_string, format_org_accounts, App, AppMsg};
impl App {
/// Handler for `:accounts` — fetches the AWS Organizations account
/// list and renders it as a TextOverlay. AccessDenied surfaces a
/// templated hint pointing at the `accounts.NAME` config workaround
/// instead of the raw SDK error chain.
pub(crate) fn cmd_accounts(&mut self) {
let aws = self.aws.clone();
let tx = self.msg_tx.clone();
let gen = self.generation;
let configured: std::collections::HashMap<String, String> = self
.accounts
.keys()
.map(|n| (n.clone(), n.clone()))
.collect();
self.status_message = Some("fetching org accounts…".into());
tokio::spawn(async move {
let body = match aws.list_org_accounts().await {
Ok(accounts) => format_org_accounts(&accounts, &configured),
Err(e) => {
let s = flatten_err_to_string(&e);
if s.to_lowercase().contains("access") || s.to_lowercase().contains("denied") {
"no organizations:* access from this credential.\n\n\
`:accounts` needs to be run from the org's management account\n\
(or a delegated administrator). Configure child accounts manually\n\
via `accounts.NAME.role_arn = …` in config.toml and use `:account NAME`\n\
to switch into them.\n\nesc / q to close"
.to_string()
} else {
format!("organizations:ListAccounts failed:\n{s}\n\nesc / q to close")
}
}
};
let _ = tx.send(AppMsg::TextOverlay {
gen,
title: "org accounts".into(),
body,
});
});
}
/// Handler for `:org-health` — fans out `list_environments` across
/// every profile in `~/.aws/{config,credentials}` plus every
/// `accounts.NAME` AssumeRole entry, aggregates per-source counts
/// (env total + Red total) into a single overlay.
pub(crate) fn cmd_org_health(&mut self) {
let profiles = crate::profiles::load_profiles();
let accounts: Vec<(String, crate::config::AccountSpec)> = self
.accounts
.iter()
.map(|(n, s)| (n.clone(), s.clone()))
.collect();
let region = self.context.region.clone();
let tx = self.msg_tx.clone();
let gen = self.generation;
self.status_message = Some(format!(
"scanning {} profile(s) + {} assume-role account(s) in {region}…",
profiles.len(),
accounts.len()
));
tokio::spawn(async move {
use futures::future::join_all;
enum SourceKind {
Profile,
AssumeRole,
}
let profile_tasks: Vec<_> = profiles
.iter()
.cloned()
.map(|p| {
let r = region.clone();
async move {
let res = crate::aws::list_environments_in_region(Some(p.clone()), r).await;
(p, SourceKind::Profile, res)
}
})
.collect();
let account_tasks: Vec<_> = accounts
.iter()
.cloned()
.map(|(name, spec)| {
let r = region.clone();
async move {
let res =
crate::aws::list_environments_for_account(&name, &spec, Some(r)).await;
(name, SourceKind::AssumeRole, res)
}
})
.collect();
type OrgHealthRow = (
String,
SourceKind,
color_eyre::Result<Vec<crate::aws::Environment>>,
);
type BoxedTask =
std::pin::Pin<Box<dyn std::future::Future<Output = OrgHealthRow> + Send>>;
let mut all_tasks: Vec<BoxedTask> =
Vec::with_capacity(profile_tasks.len() + account_tasks.len());
for t in profile_tasks {
all_tasks.push(Box::pin(t));
}
for t in account_tasks {
all_tasks.push(Box::pin(t));
}
let results = join_all(all_tasks).await;
let mut lines: Vec<String> = vec![
"Org-wide health (one row per profile / assume-role account)".into(),
"─────────────────────────────────────".into(),
String::new(),
];
let mut total = 0usize;
let mut total_red = 0usize;
for (label, kind, r) in results {
let suffix = match kind {
SourceKind::Profile => "",
SourceKind::AssumeRole => " (assume-role)",
};
let display = format!("{label}{suffix}");
match r {
Ok(envs) => {
let n = envs.len();
total += n;
let red = envs
.iter()
.filter(|e| {
e.health.eq_ignore_ascii_case("Red")
|| e.health.eq_ignore_ascii_case("Severe")
})
.count();
total_red += red;
let warning = if red > 0 { " ⚠" } else { "" };
lines.push(format!(" {display:<34} envs:{n:<4} red:{red}{warning}"));
}
Err(e) => {
lines.push(format!(" {display:<34} ERROR: {e}"));
}
}
}
lines.push(String::new());
lines.push(format!(
"Total: {total} envs, {total_red} in Red across all sources"
));
lines.push("esc / q to close".into());
let _ = tx.send(AppMsg::TextOverlay {
gen,
title: "org health".into(),
body: lines.join("\n"),
});
});
}
/// Handler for `:find-env SUBSTRING` — same fan-out shape as
/// `cmd_org_health` but the per-source closure filters envs by
/// case-insensitive name / application match and emits one line
/// per hit. Errors per source are collected separately so a
/// failed AssumeRole on one account doesn't poison the others.
pub(crate) fn cmd_find_env(&mut self, needle: &str) {
let needle = needle.to_string();
let profiles = crate::profiles::load_profiles();
let accounts: Vec<(String, crate::config::AccountSpec)> = self
.accounts
.iter()
.map(|(n, s)| (n.clone(), s.clone()))
.collect();
let region = self.context.region.clone();
let tx = self.msg_tx.clone();
let gen = self.generation;
self.status_message = Some(format!(
"searching '{needle}' across {} profile(s) + {} assume-role account(s) in {region}…",
profiles.len(),
accounts.len(),
));
tokio::spawn(async move {
use futures::future::join_all;
type Hit = Result<Vec<String>, String>;
type RowFuture =
std::pin::Pin<Box<dyn std::future::Future<Output = (String, Hit)> + Send>>;
let needle_lc = needle.to_lowercase();
let mut tasks: Vec<RowFuture> = Vec::with_capacity(profiles.len() + accounts.len());
for p in &profiles {
let p = p.clone();
let r = region.clone();
let n = needle_lc.clone();
tasks.push(Box::pin(async move {
let label = p.clone();
match crate::aws::list_environments_in_region(Some(p.clone()), r).await {
Ok(envs) => {
let hits: Vec<String> = envs
.into_iter()
.filter(|e| {
e.name.to_lowercase().contains(&n)
|| e.application.to_lowercase().contains(&n)
})
.map(|e| format!(" • {p} / {} ({})", e.name, e.health))
.collect();
(label, Ok(hits))
}
Err(e) => (label, Err(format!("{e}"))),
}
}));
}
for (name, spec) in &accounts {
let name = name.clone();
let spec = spec.clone();
let r = region.clone();
let n = needle_lc.clone();
tasks.push(Box::pin(async move {
let label = format!("{name} (assume-role)");
match crate::aws::list_environments_for_account(&name, &spec, Some(r)).await {
Ok(envs) => {
let hits: Vec<String> = envs
.into_iter()
.filter(|e| {
e.name.to_lowercase().contains(&n)
|| e.application.to_lowercase().contains(&n)
})
.map(|e| {
format!(" • {name} (assume-role) / {} ({})", e.name, e.health)
})
.collect();
(label, Ok(hits))
}
Err(e) => (label, Err(format!("{e}"))),
}
}));
}
let results = join_all(tasks).await;
let mut hits: Vec<String> = Vec::new();
let mut errs: Vec<String> = Vec::new();
for (label, r) in results {
match r {
Ok(mut h) if !h.is_empty() => hits.append(&mut h),
Ok(_) => {}
Err(e) => errs.push(format!(" {label}: {e}")),
}
}
let body = format!(
"Cross-account search for '{needle}'\n\
─────────────────────────────────\n\n\
{}\n\n\
{}\n\nesc / q to close",
if hits.is_empty() {
"(no matches)".to_string()
} else {
hits.join("\n")
},
if errs.is_empty() {
String::new()
} else {
format!("Errors:\n{}", errs.join("\n"))
},
);
let _ = tx.send(AppMsg::TextOverlay {
gen,
title: format!("cross-account search — {needle}"),
body,
});
});
}
}