Skip to main content

cloudflare_dns/tasks/
fetch_task.rs

1/// Fetch and refresh tasks for loading DNS records.
2use iocraft::prelude::*;
3
4use crate::api::CloudflareClient;
5use crate::ui::state::AppState;
6use crate::utils::{extract_unique_ips, format_records};
7
8/// Fetch all initial data: zone name and DNS records.
9///
10/// Uses the DNS cache if valid to avoid unnecessary API calls.
11pub async fn fetch_all(
12    client: &CloudflareClient,
13    state: &AppState,
14    rd: &mut State<String>,
15    st: &mut State<String>,
16) {
17    // Fetch zone name for display in title
18    match client.get_zone_name().await {
19        Ok(name) => {
20            *state.zone_name.lock().unwrap() = name;
21        }
22        Err(_) => {
23            // Keep default (zone ID) if fetch fails
24        }
25    }
26
27    // Check cache first
28    {
29        let cache = state.dns_cache.lock().unwrap();
30        if let Some(cached_records) = cache.get() {
31            let cached_records = cached_records.clone();
32            rd.set(format_records(&cached_records));
33            st.set(format!("Loaded {} DNS records (cached)", cached_records.len()));
34            *state.existing_ips.lock().unwrap() = extract_unique_ips(&cached_records);
35            *state.records.lock().unwrap() = cached_records;
36            return;
37        }
38    }
39
40    // Cache miss — fetch from API
41    match client.list_dns_records().await {
42        Ok(f) => {
43            rd.set(format_records(&f));
44            st.set(format!("Loaded {} DNS records", f.len()));
45            *state.existing_ips.lock().unwrap() = extract_unique_ips(&f);
46            *state.records.lock().unwrap() = f.clone();
47            state.dns_cache.lock().unwrap().set(f);
48        }
49        Err(e) => {
50            rd.set(format!("Error: {}", e));
51            st.set(format!("Error: {}", e));
52        }
53    }
54}
55
56/// Refresh DNS records only (used for manual refresh).
57///
58/// Invalidates the cache before fetching fresh records from the API.
59pub async fn refresh_task(
60    client: &CloudflareClient,
61    state: &AppState,
62    mut rd: State<String>,
63    mut st: State<String>,
64) {
65    // Invalidate cache before refreshing
66    state.dns_cache.lock().unwrap().invalidate();
67
68    match client.list_dns_records().await {
69        Ok(f) => {
70            rd.set(format_records(&f));
71            st.set(format!("Loaded {} DNS records", f.len()));
72            *state.existing_ips.lock().unwrap() = extract_unique_ips(&f);
73            *state.records.lock().unwrap() = f.clone();
74            state.dns_cache.lock().unwrap().set(f);
75        }
76        Err(e) => st.set(format!("Error: {}", e)),
77    }
78}