1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3use std::sync::atomic::AtomicBool;
4
5use crate::app::ProviderFormBaseline;
6use crate::app::forms::ProviderFormFields;
7use crate::providers::config::{ProviderConfig, ProviderConfigId};
8
9#[derive(Debug, Clone)]
11pub struct SyncRecord {
12 pub timestamp: u64,
13 pub message: String,
14 pub is_error: bool,
15}
16
17impl SyncRecord {
18 pub fn load_all() -> HashMap<String, SyncRecord> {
21 let mut map = HashMap::new();
22 let Some(home) = dirs::home_dir() else {
23 return map;
24 };
25 let path = home.join(".purple").join("sync_history.tsv");
26 let Ok(content) = std::fs::read_to_string(&path) else {
27 return map;
28 };
29 for line in content.lines() {
30 let parts: Vec<&str> = line.splitn(4, '\t').collect();
31 if parts.len() < 4 {
32 continue;
33 }
34 let Some(ts) = parts[1].parse::<u64>().ok() else {
35 continue;
36 };
37 let is_error = parts[2] == "1";
38 map.insert(
39 parts[0].to_string(),
40 SyncRecord {
41 timestamp: ts,
42 message: parts[3].to_string(),
43 is_error,
44 },
45 );
46 }
47 map
48 }
49
50 pub fn save_all(history: &HashMap<String, SyncRecord>) {
52 if crate::demo_flag::is_demo() {
53 return;
54 }
55 let Some(home) = dirs::home_dir() else { return };
56 let dir = home.join(".purple");
57 let path = dir.join("sync_history.tsv");
58 let mut lines = Vec::new();
59 for (provider, record) in history {
60 lines.push(format!(
61 "{}\t{}\t{}\t{}",
62 provider,
63 record.timestamp,
64 if record.is_error { "1" } else { "0" },
65 record.message
66 ));
67 }
68 if let Err(e) = crate::fs_util::atomic_write(&path, lines.join("\n").as_bytes()) {
69 log::warn!(
70 "[config] failed to save sync_history.tsv at {}: {e}",
71 path.display()
72 );
73 }
74 }
75
76 pub fn load_from_content(content: &str) -> HashMap<String, SyncRecord> {
78 let mut map = HashMap::new();
79 for line in content.lines() {
80 let parts: Vec<&str> = line.splitn(4, '\t').collect();
81 if parts.len() < 4 {
82 continue;
83 }
84 let Some(ts) = parts[1].parse::<u64>().ok() else {
85 continue;
86 };
87 let is_error = parts[2] == "1";
88 map.insert(
89 parts[0].to_string(),
90 SyncRecord {
91 timestamp: ts,
92 message: parts[3].to_string(),
93 is_error,
94 },
95 );
96 }
97 map
98 }
99}
100
101pub struct ProviderState {
107 pub(in crate::app) config: ProviderConfig,
108 pub(in crate::app) form: ProviderFormFields,
109 pub(in crate::app) syncing: HashMap<String, Arc<AtomicBool>>,
110 pub(in crate::app) sync_done: Vec<String>,
112 pub(in crate::app) sync_had_errors: bool,
114 pub(in crate::app) batch_added: usize,
118 pub(in crate::app) batch_updated: usize,
119 pub(in crate::app) batch_stale: usize,
120 pub(in crate::app) batch_total: usize,
124 pub(in crate::app) pending_delete: Option<String>,
125 pub(in crate::app) pending_delete_id: Option<ProviderConfigId>,
128 pub(in crate::app) sync_history: HashMap<String, SyncRecord>,
129 pub(in crate::app) form_baseline: Option<ProviderFormBaseline>,
130 pub(in crate::app) expanded_providers: HashSet<String>,
133 pub(in crate::app) pending_label_migration: Option<PendingLabelMigration>,
140}
141
142#[derive(Debug, Clone)]
145pub struct PendingLabelMigration {
146 pub provider: String,
147 pub existing_label: String,
149 pub new_label: String,
151 pub focused: LabelMigrationField,
153 pub cursor_pos: usize,
155}
156
157impl PendingLabelMigration {
158 pub fn focused_value(&self) -> &str {
160 match self.focused {
161 LabelMigrationField::Existing => &self.existing_label,
162 LabelMigrationField::New => &self.new_label,
163 }
164 }
165
166 pub fn focused_value_mut(&mut self) -> &mut String {
168 match self.focused {
169 LabelMigrationField::Existing => &mut self.existing_label,
170 LabelMigrationField::New => &mut self.new_label,
171 }
172 }
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub enum LabelMigrationField {
177 Existing,
178 New,
179}
180
181#[derive(Debug, Clone)]
183pub enum ProviderRow {
184 Header { name: String, config_count: usize },
187 Leaf { id: ProviderConfigId },
189}
190
191impl ProviderRow {
192 pub fn provider_name(&self) -> &str {
193 match self {
194 ProviderRow::Header { name, .. } => name,
195 ProviderRow::Leaf { id } => &id.provider,
196 }
197 }
198}
199
200impl ProviderState {
201 pub fn reset_batch_if_idle(&mut self) {
211 if self.syncing.is_empty() && self.sync_done.is_empty() {
212 self.batch_total = 0;
213 self.batch_added = 0;
214 self.batch_updated = 0;
215 self.batch_stale = 0;
216 self.sync_had_errors = false;
217 }
218 }
219
220 pub fn finish_batch(&mut self) {
224 self.sync_done.clear();
225 self.sync_had_errors = false;
226 self.batch_added = 0;
227 self.batch_updated = 0;
228 self.batch_stale = 0;
229 self.batch_total = 0;
230 }
231
232 pub fn request_delete(&mut self, id: ProviderConfigId) {
238 self.pending_delete = Some(id.provider.clone());
239 self.pending_delete_id = Some(id);
240 }
241
242 pub fn cancel_delete(&mut self) {
244 self.pending_delete = None;
245 self.pending_delete_id = None;
246 }
247
248 pub fn toggle_expanded(&mut self, name: &str) -> bool {
253 let added = !self.expanded_providers.contains(name);
254 if added {
255 self.expanded_providers.insert(name.to_string());
256 } else {
257 self.expanded_providers.remove(name);
258 }
259 added
260 }
261
262 pub fn cancel_label_migration(&mut self) {
264 self.pending_label_migration = None;
265 }
266
267 pub fn config(&self) -> &ProviderConfig {
268 &self.config
269 }
270
271 pub fn config_mut(&mut self) -> &mut ProviderConfig {
272 &mut self.config
273 }
274
275 pub fn form(&self) -> &ProviderFormFields {
276 &self.form
277 }
278
279 pub fn form_mut(&mut self) -> &mut ProviderFormFields {
280 &mut self.form
281 }
282
283 pub fn syncing(&self) -> &HashMap<String, Arc<AtomicBool>> {
284 &self.syncing
285 }
286
287 pub fn syncing_mut(&mut self) -> &mut HashMap<String, Arc<AtomicBool>> {
288 &mut self.syncing
289 }
290
291 pub fn sync_done(&self) -> &[String] {
292 &self.sync_done
293 }
294
295 pub fn push_sync_done(&mut self, name: String) {
296 self.sync_done.push(name);
297 }
298
299 pub fn clear_sync_done(&mut self) {
300 self.sync_done.clear();
301 }
302
303 pub fn sync_had_errors(&self) -> bool {
304 self.sync_had_errors
305 }
306
307 pub fn set_sync_had_errors(&mut self, value: bool) {
308 self.sync_had_errors = value;
309 }
310
311 pub fn batch_added(&self) -> usize {
312 self.batch_added
313 }
314
315 pub fn batch_updated(&self) -> usize {
316 self.batch_updated
317 }
318
319 pub fn batch_stale(&self) -> usize {
320 self.batch_stale
321 }
322
323 pub fn add_batch_diff(&mut self, added: usize, updated: usize, stale: usize) {
326 self.batch_added += added;
327 self.batch_updated += updated;
328 self.batch_stale += stale;
329 }
330
331 pub fn batch_total(&self) -> usize {
332 self.batch_total
333 }
334
335 pub fn set_batch_total(&mut self, value: usize) {
336 self.batch_total = value;
337 }
338
339 pub fn bump_batch_total(&mut self) {
343 self.batch_total = self
344 .batch_total
345 .max(self.sync_done.len() + self.syncing.len());
346 }
347
348 pub fn pending_delete(&self) -> Option<&str> {
349 self.pending_delete.as_deref()
350 }
351
352 pub fn take_pending_delete(&mut self) -> Option<String> {
353 self.pending_delete.take()
354 }
355
356 pub fn pending_delete_id(&self) -> Option<&ProviderConfigId> {
357 self.pending_delete_id.as_ref()
358 }
359
360 pub fn take_pending_delete_id(&mut self) -> Option<ProviderConfigId> {
361 self.pending_delete_id.take()
362 }
363
364 pub fn sync_history(&self) -> &HashMap<String, SyncRecord> {
365 &self.sync_history
366 }
367
368 pub fn sync_history_mut(&mut self) -> &mut HashMap<String, SyncRecord> {
369 &mut self.sync_history
370 }
371
372 pub fn record_sync(&mut self, key: String, record: SyncRecord) {
375 self.sync_history.insert(key, record);
376 }
377
378 pub fn form_baseline(&self) -> Option<&ProviderFormBaseline> {
379 self.form_baseline.as_ref()
380 }
381
382 pub fn set_form_baseline(&mut self, baseline: Option<ProviderFormBaseline>) {
383 self.form_baseline = baseline;
384 }
385
386 pub fn expanded_providers(&self) -> &HashSet<String> {
387 &self.expanded_providers
388 }
389
390 pub fn expanded_providers_mut(&mut self) -> &mut HashSet<String> {
391 &mut self.expanded_providers
392 }
393
394 pub fn pending_label_migration(&self) -> Option<&PendingLabelMigration> {
395 self.pending_label_migration.as_ref()
396 }
397
398 pub fn pending_label_migration_mut(&mut self) -> Option<&mut PendingLabelMigration> {
399 self.pending_label_migration.as_mut()
400 }
401
402 pub fn set_pending_label_migration(&mut self, migration: Option<PendingLabelMigration>) {
403 self.pending_label_migration = migration;
404 }
405}
406
407impl Default for ProviderState {
408 fn default() -> Self {
412 Self {
413 config: ProviderConfig::default(),
414 form: ProviderFormFields::new(),
415 syncing: HashMap::new(),
416 sync_done: Vec::new(),
417 sync_had_errors: false,
418 batch_added: 0,
419 batch_updated: 0,
420 batch_stale: 0,
421 batch_total: 0,
422 pending_delete: None,
423 pending_delete_id: None,
424 sync_history: HashMap::new(),
425 form_baseline: None,
426 expanded_providers: HashSet::new(),
427 pending_label_migration: None,
428 }
429 }
430}
431
432impl ProviderState {
433 pub fn load() -> Self {
435 Self {
436 config: crate::providers::config::ProviderConfig::load(),
437 sync_history: SyncRecord::load_all(),
438 ..Self::default()
439 }
440 }
441
442 pub fn provider_list_rows(&self) -> Vec<ProviderRow> {
447 let mut rows = Vec::new();
448 for name in self.sorted_names() {
449 let configs = self.config.sections_for_provider(&name);
450 rows.push(ProviderRow::Header {
451 name: name.clone(),
452 config_count: configs.len(),
453 });
454 if configs.len() >= 2 && self.expanded_providers.contains(&name) {
455 let mut sorted = configs.clone();
456 sorted.sort_by(|a, b| {
457 a.id.label
458 .as_deref()
459 .unwrap_or("")
460 .cmp(b.id.label.as_deref().unwrap_or(""))
461 });
462 for s in sorted {
463 rows.push(ProviderRow::Leaf { id: s.id.clone() });
464 }
465 }
466 }
467 rows
468 }
469
470 pub fn sorted_names(&self) -> Vec<String> {
474 use crate::providers;
475 let mut names: Vec<String> = providers::PROVIDER_NAMES
476 .iter()
477 .map(|s| s.to_string())
478 .collect();
479 for section in &self.config.sections {
481 let name = section.provider().to_string();
482 if !names.contains(&name) {
483 names.push(name);
484 }
485 }
486 let max_ts = |provider: &str| -> u64 {
491 self.sync_history
492 .iter()
493 .filter(|(k, _)| {
494 k.as_str() == provider || k.split_once(':').is_some_and(|(p, _)| p == provider)
495 })
496 .map(|(_, r)| r.timestamp)
497 .max()
498 .unwrap_or(0)
499 };
500 names.sort_by(|a, b| {
501 let conf_a = self.config.section(a.as_str()).is_some();
502 let conf_b = self.config.section(b.as_str()).is_some();
503 let ts_a = max_ts(a.as_str());
504 let ts_b = max_ts(b.as_str());
505 conf_b.cmp(&conf_a).then(ts_b.cmp(&ts_a)).then(a.cmp(b))
507 });
508 names
509 }
510}
511
512#[cfg(test)]
513mod tests {
514 use super::*;
515
516 #[test]
517 fn default_is_empty() {
518 let s = ProviderState::default();
522 assert!(s.config.sections.is_empty());
523 assert!(s.config.path_override.is_none());
524 assert!(s.syncing.is_empty());
525 assert!(s.sync_done.is_empty());
526 assert!(!s.sync_had_errors);
527 assert!(s.pending_delete.is_none());
528 assert!(s.sync_history.is_empty());
529 assert!(s.form_baseline.is_none());
530 }
531
532 #[test]
533 fn sorted_names_returns_configured_providers_before_unconfigured() {
534 use crate::providers::config::ProviderSection;
535
536 let mut state = ProviderState::default();
537 state.config.sections.push(ProviderSection {
538 id: crate::providers::config::ProviderConfigId::bare("vultr"),
539 token: "tok".to_string(),
540 alias_prefix: "vultr".to_string(),
541 ..ProviderSection::default()
542 });
543 state.config.sections.push(ProviderSection {
544 id: crate::providers::config::ProviderConfigId::bare("digitalocean"),
545 token: "tok".to_string(),
546 alias_prefix: "do".to_string(),
547 ..ProviderSection::default()
548 });
549 state.sync_history.insert(
550 "digitalocean".to_string(),
551 SyncRecord {
552 timestamp: 2_000,
553 message: "ok".to_string(),
554 is_error: false,
555 },
556 );
557 state.sync_history.insert(
558 "vultr".to_string(),
559 SyncRecord {
560 timestamp: 1_000,
561 message: "ok".to_string(),
562 is_error: false,
563 },
564 );
565
566 let names = state.sorted_names();
567 assert_eq!(&names[0], "digitalocean");
569 assert_eq!(&names[1], "vultr");
570 for &known in crate::providers::PROVIDER_NAMES {
572 assert!(names.iter().any(|n| n == known), "missing {}", known);
573 }
574 let unconfigured: Vec<&String> = names.iter().skip(2).collect();
576 let mut sorted = unconfigured.clone();
577 sorted.sort();
578 assert_eq!(unconfigured, sorted);
579 }
580
581 #[test]
582 fn sorted_names_includes_unknown_providers_from_config() {
583 use crate::providers::config::ProviderSection;
584
585 let mut state = ProviderState::default();
586 state.config.sections.push(ProviderSection {
587 id: crate::providers::config::ProviderConfigId::bare("someday_provider"),
588 token: "tok".to_string(),
589 alias_prefix: "x".to_string(),
590 ..ProviderSection::default()
591 });
592
593 let names = state.sorted_names();
594 assert!(names.iter().any(|n| n == "someday_provider"));
595 }
596
597 #[test]
598 fn request_delete_sets_both_pending_fields() {
599 let mut s = ProviderState::default();
600 let id = crate::providers::config::ProviderConfigId::bare("digitalocean");
601 s.request_delete(id.clone());
602 assert_eq!(s.pending_delete.as_deref(), Some("digitalocean"));
603 assert_eq!(s.pending_delete_id.as_ref(), Some(&id));
604 }
605
606 #[test]
607 fn request_delete_with_labeled_id_keeps_provider_name_in_pending_delete() {
608 let mut s = ProviderState::default();
609 let id = crate::providers::config::ProviderConfigId::labeled("digitalocean", "work");
610 s.request_delete(id.clone());
611 assert_eq!(s.pending_delete.as_deref(), Some("digitalocean"));
614 assert_eq!(s.pending_delete_id.as_ref(), Some(&id));
615 }
616
617 #[test]
618 fn request_delete_overwrites_existing_pending() {
619 let mut s = ProviderState::default();
620 s.request_delete(crate::providers::config::ProviderConfigId::bare("vultr"));
621 let new_id = crate::providers::config::ProviderConfigId::bare("hetzner");
622 s.request_delete(new_id.clone());
623 assert_eq!(s.pending_delete.as_deref(), Some("hetzner"));
624 assert_eq!(s.pending_delete_id.as_ref(), Some(&new_id));
625 }
626
627 #[test]
628 fn cancel_delete_clears_both_pending_fields() {
629 let mut s = ProviderState::default();
630 s.request_delete(crate::providers::config::ProviderConfigId::bare("vultr"));
631 s.cancel_delete();
632 assert!(s.pending_delete.is_none());
633 assert!(s.pending_delete_id.is_none());
634 }
635
636 #[test]
637 fn cancel_delete_is_idempotent() {
638 let mut s = ProviderState::default();
639 s.cancel_delete();
640 s.cancel_delete();
641 assert!(s.pending_delete.is_none());
642 assert!(s.pending_delete_id.is_none());
643 }
644
645 #[test]
646 fn toggle_expanded_adds_when_absent_and_returns_true() {
647 let mut s = ProviderState::default();
648 assert!(!s.expanded_providers.contains("digitalocean"));
649 let added = s.toggle_expanded("digitalocean");
650 assert!(added);
651 assert!(s.expanded_providers.contains("digitalocean"));
652 }
653
654 #[test]
655 fn toggle_expanded_removes_when_present_and_returns_false() {
656 let mut s = ProviderState::default();
657 s.expanded_providers.insert("digitalocean".to_string());
658 let added = s.toggle_expanded("digitalocean");
659 assert!(!added);
660 assert!(!s.expanded_providers.contains("digitalocean"));
661 }
662
663 #[test]
664 fn cancel_label_migration_clears_pending() {
665 let mut s = ProviderState {
666 pending_label_migration: Some(PendingLabelMigration {
667 provider: "digitalocean".to_string(),
668 existing_label: "old".to_string(),
669 new_label: "new".to_string(),
670 focused: LabelMigrationField::Existing,
671 cursor_pos: 0,
672 }),
673 ..Default::default()
674 };
675 s.cancel_label_migration();
676 assert!(s.pending_label_migration.is_none());
677 }
678
679 #[test]
680 fn cancel_label_migration_is_idempotent_when_already_none() {
681 let mut s = ProviderState::default();
682 s.cancel_label_migration();
683 s.cancel_label_migration();
684 assert!(s.pending_label_migration.is_none());
685 }
686
687 #[test]
688 fn add_batch_diff_accumulates_each_counter() {
689 let mut s = ProviderState::default();
690 s.add_batch_diff(3, 1, 2);
691 s.add_batch_diff(1, 0, 4);
692 assert_eq!(s.batch_added(), 4);
693 assert_eq!(s.batch_updated(), 1);
694 assert_eq!(s.batch_stale(), 6);
695 }
696
697 #[test]
698 fn bump_batch_total_raises_to_done_plus_syncing() {
699 let mut s = ProviderState::default();
700 s.push_sync_done("aws".to_string());
701 s.syncing_mut()
702 .insert("vultr".to_string(), Arc::new(AtomicBool::new(false)));
703 s.bump_batch_total();
704 assert_eq!(s.batch_total(), 2);
705 }
706
707 #[test]
708 fn bump_batch_total_never_lowers_existing_peak() {
709 let mut s = ProviderState::default();
710 s.set_batch_total(5);
711 s.push_sync_done("aws".to_string());
712 s.bump_batch_total();
713 assert_eq!(s.batch_total(), 5);
714 }
715
716 #[test]
717 fn finish_batch_clears_all_batch_state() {
718 let mut s = ProviderState::default();
719 s.push_sync_done("aws".to_string());
720 s.set_sync_had_errors(true);
721 s.add_batch_diff(2, 3, 4);
722 s.set_batch_total(7);
723 s.finish_batch();
724 assert!(s.sync_done().is_empty());
725 assert!(!s.sync_had_errors());
726 assert_eq!(s.batch_added(), 0);
727 assert_eq!(s.batch_updated(), 0);
728 assert_eq!(s.batch_stale(), 0);
729 assert_eq!(s.batch_total(), 0);
730 }
731}