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
//! Miscellaneous commands — `:custom-platforms`, `:versions`,
//! `:delete-version`, `:pending`, `:resources`, `:custom-platform-delete`,
//! `:metric`. Pulled out as the final slice of the `execute_command`
//! split: cohesive enough as "read overlays + custom-metric admin" and
//! all that's left after the alarm / config / write / option / nav /
//! settings / view / overlay clusters were lifted.
//!
//! Tenth (and final) slice of the `execute_command` split. Same
//! parent-module visibility pattern as the other `cmd_*` sub-modules.
use std::time::Instant;
use super::{
flatten_err, humanize_short_age, parse_metric_extra_args, write_audit_line, App, AppMsg,
DetailTab, Overlay,
};
impl App {
pub(crate) fn cmd_custom_platforms(&mut self) {
let aws = self.aws.clone();
let tx = self.msg_tx.clone();
let gen = self.generation;
self.status_message = Some("fetching custom platforms…".into());
tokio::spawn(async move {
let result = aws
.list_custom_platforms()
.await
.map_err(|e| flatten_err("list_custom_platforms", e));
let body = match result {
Ok(platforms) if platforms.is_empty() => "Custom platforms: none\n\n\
This account hasn't built any custom EB platforms.\n\
`eb platform create` is the usual CLI entry.\n\nesc / q to close"
.to_string(),
Ok(platforms) => {
let lines: Vec<String> = platforms
.iter()
.map(|p| {
format!(
" ▸ {} v{}\n branch: {}\n status: {} / lifecycle: {}\n {}",
if p.branch.is_empty() { "(unnamed)" } else { &p.branch },
p.version,
p.branch,
p.status,
p.lifecycle,
p.arn
)
})
.collect();
format!(
"Custom platforms ({})\n\
─────────────────────\n\n\
{}\n\nesc / q to close",
platforms.len(),
lines.join("\n\n")
)
}
Err(e) => format!("custom platforms: {e}\n\nesc / q to close"),
};
let _ = tx.send(AppMsg::TextOverlay {
gen,
title: "custom platforms".into(),
body,
});
});
}
pub(crate) fn cmd_versions(&mut self) {
let Some(env) = self.selected_env().cloned() else {
self.error_message = Some("no env selected".into());
return;
};
let app_name = env.application.clone();
// Capture the env's current label at dispatch time so the
// resulting overlay can mark "this is what's deployed".
let deployed_label = if env.version_label.is_empty() {
None
} else {
Some(env.version_label.clone())
};
let aws = self.aws.clone();
let tx = self.msg_tx.clone();
let gen = self.generation;
self.status_message = Some(format!("fetching application versions for {app_name}…"));
tokio::spawn(async move {
let result = aws
.list_application_versions(&app_name)
.await
.map_err(|e| flatten_err("list_application_versions", e));
let _ = tx.send(AppMsg::AppVersions {
gen,
application: app_name,
deployed_label,
result,
});
});
}
pub(crate) fn cmd_delete_version(&mut self, rest: &[&str]) {
match rest.first().copied() {
None => {
self.error_message = Some(
"usage: :delete-version <label> [--force] (selected env's app; --force also removes the S3 source bundle)".into(),
);
}
Some(label) => {
let force = rest.iter().skip(1).any(|s| *s == "--force" || *s == "-f");
self.spawn_delete_app_version(label.to_string(), force);
}
}
}
/// `:abort-rollback [ENV]` — explicit disarm. No arg drains
/// every armed watchdog in the current context; with an env
/// name, just that one. Audit-logged so a post-mortem can pin
/// down "operator aborted the rollback at HH:MM" even if the
/// auto-rollback never fired.
///
/// The fire-and-forget tokio task that backs each watchdog
/// survives the abort — no JoinHandle for cancellation — but
/// `apply_refresh`'s decision pass will find the slot empty and
/// no-op when the deadline message lands. So aborts are
/// genuinely synchronous from the operator's perspective.
///
/// Not gated by `deny_write`: aborting a rollback is a
/// "clean up state I previously armed" action, not a write to
/// AWS. Per-env safety pins added mid-window must not block the
/// operator from clearing the watchdog they themselves armed.
pub(crate) fn cmd_abort_rollback(&mut self, rest: &[&str]) {
match rest.first().copied() {
Some(env_name) => {
if self.armed_watchdogs.remove(env_name).is_some() {
write_audit_line(
self.context.account_id.as_deref(),
self.context.profile.as_deref(),
&self.context.region,
&format!("stage=dispatched action=AbortRollback target={env_name}"),
);
self.pin_status(format!("aborted auto-rollback for {env_name}"));
} else {
self.error_message = Some(format!(
"no auto-rollback armed for '{env_name}' — try :rollbacks-armed"
));
}
}
None => {
if self.armed_watchdogs.is_empty() {
self.pin_status("no auto-rollbacks armed to abort");
return;
}
let names: Vec<String> = self.armed_watchdogs.keys().cloned().collect();
let n = names.len();
for env_name in &names {
write_audit_line(
self.context.account_id.as_deref(),
self.context.profile.as_deref(),
&self.context.region,
&format!(
"stage=dispatched action=AbortRollback target={env_name} reason=batch"
),
);
}
self.armed_watchdogs.clear();
self.pin_status(format!(
"aborted {n} auto-rollback{}: {}",
if n == 1 { "" } else { "s" },
names.join(", ")
));
}
}
}
/// `:rollbacks-armed` (alias `:rb-armed`) — dump the table of
/// currently-armed `--auto-rollback` watchdogs. Each row shows
/// env / target_label / armed_at age / remaining-until-deadline.
/// Updates every refresh tick because the overlay re-renders
/// from `App.armed_watchdogs` every draw. Empty state yields a
/// status toast rather than a thin overlay.
pub(crate) fn cmd_rollbacks_armed(&mut self) {
if self.armed_watchdogs.is_empty() {
self.pin_status(
"no auto-rollbacks armed — `:deploy LABEL --auto-rollback Nm` arms one",
);
return;
}
let body = super::format_armed_rollbacks(&self.armed_watchdogs, chrono::Utc::now());
self.current_overlay = Some(Overlay::TextDump {
title: format!("auto-rollbacks armed ({})", self.armed_watchdogs.len()),
body,
});
}
pub(crate) fn cmd_pending(&mut self) {
if self.pending_actions.is_empty() {
self.pin_status("no actions in flight or recently completed");
} else {
let now = Instant::now();
let mut lines: Vec<String> = Vec::with_capacity(self.pending_actions.len() + 2);
for entry in self.pending_actions.iter().rev() {
let age = humanize_short_age(now.duration_since(entry.started));
let status = match &entry.completed {
None => " ⏳ in flight".to_string(),
Some((c, Ok(()))) => {
format!(" ✓ ok ({} ago)", humanize_short_age(now.duration_since(*c)))
}
Some((c, Err(e))) => format!(
" ✗ err ({} ago): {}",
humanize_short_age(now.duration_since(*c)),
e.chars().take(80).collect::<String>()
),
};
lines.push(format!(
" {} → {} ({} ago){}",
entry.label, entry.target, age, status
));
}
self.current_overlay = Some(Overlay::TextDump {
title: "in-flight + recently-completed actions".into(),
body: lines.join("\n"),
});
}
}
pub(crate) fn cmd_resources(&mut self) {
let Some(env) = self.selected_env().cloned() else {
self.error_message = Some("no env selected".into());
return;
};
let aws = self.aws.clone();
let tx = self.msg_tx.clone();
let gen = self.generation;
let env_name = env.name.clone();
let tier = env.tier.clone();
self.status_message = Some(format!("fetching env resources for {env_name}…"));
let env_name_for_title = env_name.clone();
tokio::spawn(async move {
let result = aws
.describe_env_resources(&env_name)
.await
.map_err(|e| flatten_err("describe_env_resources", e));
let body = match result {
Ok(res) => super::render_env_resources_tree(&res, &env_name, &tier),
Err(e) => format!("resources: {e}\n\nesc / q to close"),
};
let _ = tx.send(AppMsg::TextOverlay {
gen,
title: format!("resources — {env_name_for_title}"),
body,
});
});
}
pub(crate) fn cmd_custom_platform_delete(&mut self, rest: &[&str]) {
match rest.first().copied() {
None => {
self.error_message = Some(
"usage: :custom-platform-delete <platform-arn> (fails if any env still uses it)".into(),
);
}
Some(arn) => {
// Custom platforms are account-scoped, not env-scoped —
// an empty env name in deny_write fires the global /
// account pin but doesn't match any per-env entry.
if self.deny_write("", "custom-platform-delete") {
return;
}
let arn = arn.to_string();
write_audit_line(
self.context.account_id.as_deref(),
self.context.profile.as_deref(),
&self.context.region,
&format!("stage=dispatched action=DeleteCustomPlatform target={arn}"),
);
self.push_pending("Delete custom platform", arn.clone());
// In-flight ack lives on the pending pill.
let aws = self.aws.clone();
let tx = self.msg_tx.clone();
let gen = self.generation;
let arn_for_msg = arn.clone();
let account = self.context.account_id.clone();
let profile = self.context.profile.clone();
let region = self.context.region.clone();
tokio::spawn(async move {
let result = aws
.delete_custom_platform(&arn_for_msg)
.await
.map_err(|e| flatten_err("delete_custom_platform", e));
let outcome = match &result {
Ok(()) => format!(
"stage=completed action=DeleteCustomPlatform target={arn_for_msg} ok"
),
Err(e) => format!(
"stage=completed action=DeleteCustomPlatform target={arn_for_msg} err=\"{}\"",
e.replace('"', "'")
),
};
write_audit_line(account.as_deref(), profile.as_deref(), ®ion, &outcome);
// Reuse OptionSettingsUpdate's plumbing so the pending
// row is closed and a toast fires — the variant's
// shape (env_name + summary) maps cleanly to
// (target_arn + summary).
let _ = tx.send(AppMsg::OptionSettingsUpdate {
gen,
env_name: arn_for_msg,
summary: "Delete custom platform".into(),
result,
});
});
}
}
}
/// `:metric add LABEL NAMESPACE NAME [STAT]` upserts a custom
/// metric chart for the Metrics tab; `:metric remove LABEL`
/// drops it; `:metric list` dumps the table. STAT defaults to
/// Average. Persists to state.toml automatically via
/// `persist_state`.
pub(crate) fn cmd_metric(&mut self, rest: &[&str]) {
let sub = rest.first().copied();
match sub {
Some("list") | Some("ls") | None => {
if self.custom_metrics.is_empty() {
self.status_message = Some(
"no custom metrics — add with `:metric add LABEL NAMESPACE NAME [STAT]`"
.into(),
);
} else {
let mut lines = String::new();
for (label, spec) in &self.custom_metrics {
lines.push_str(&format!(
"{label:<24} {:<32} {:<32} {}\n",
spec.namespace, spec.name, spec.stat
));
}
self.current_overlay = Some(Overlay::TextDump {
title: format!("custom metrics ({} total)", self.custom_metrics.len()),
body: lines,
});
}
}
Some("add") => match (
rest.get(1).copied(),
rest.get(2).copied(),
rest.get(3).copied(),
) {
(Some(label), Some(namespace), Some(name)) => {
// Args after NAME are STAT and/or DIMS in any order.
// The token containing `=` is dims (e.g.
// `InstanceId=i-abc,Foo=bar`); the other is stat.
// STAT defaults to Average; DIMS defaults to the
// env-scoped dimension (resolved at fetch time).
let (stat, dimensions) = parse_metric_extra_args(&rest[4..]);
self.custom_metrics.insert(
label.to_string(),
crate::state::CustomMetricSpec {
namespace: namespace.to_string(),
name: name.to_string(),
stat,
dimensions,
},
);
self.persist_state();
self.status_message = Some(format!(
"custom metric '{label}' added — re-open Detail/Metrics to see"
));
// If we're on the Metrics tab, refetch so the
// chart appears without the user toggling tabs.
if let Some(d) = self.detail.as_ref() {
if d.tab() == DetailTab::Metrics {
let env_name = d.env_name.clone();
self.spawn_detail_metrics(env_name);
}
}
}
_ => {
self.error_message = Some(
"usage: :metric add LABEL NAMESPACE NAME [STAT] [DIM=VAL,DIM=VAL] (dimensions default to EnvironmentName=<env>; pass overrides for AWS/EC2 InstanceId, AWS/ApplicationELB LoadBalancer, etc.)".into(),
);
}
},
Some("remove") | Some("rm") | Some("delete") => match rest.get(1).copied() {
None => {
self.error_message = Some("usage: :metric remove LABEL".into());
}
Some(label) => {
if self.custom_metrics.remove(label).is_some() {
self.persist_state();
self.status_message = Some(format!("custom metric '{label}' removed"));
if let Some(d) = self.detail.as_ref() {
if d.tab() == DetailTab::Metrics {
let env_name = d.env_name.clone();
self.spawn_detail_metrics(env_name);
}
}
} else {
self.error_message = Some(format!("no custom metric named '{label}'"));
}
}
},
Some(other) => {
self.error_message = Some(format!(
"unknown subcommand '{other}' (use: list | add LABEL NS NAME [STAT] | remove LABEL)"
));
}
}
}
}