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!(
34                "Loaded {} DNS records (cached)",
35                cached_records.len()
36            ));
37            *state.existing_ips.lock().unwrap() = extract_unique_ips(&cached_records);
38            *state.records.lock().unwrap() = cached_records;
39            return;
40        }
41    }
42
43    // Cache miss — fetch from API
44    match client.list_dns_records().await {
45        Ok(f) => {
46            rd.set(format_records(&f));
47            st.set(format!("Loaded {} DNS records", f.len()));
48            *state.existing_ips.lock().unwrap() = extract_unique_ips(&f);
49            *state.records.lock().unwrap() = f.clone();
50            state.dns_cache.lock().unwrap().set(f);
51        }
52        Err(e) => {
53            rd.set(format!("Error: {}", e));
54            st.set(format!("Error: {}", e));
55        }
56    }
57}
58
59/// Refresh DNS records only (used for manual refresh).
60///
61/// Invalidates the cache before fetching fresh records from the API.
62pub async fn refresh_task(
63    client: &CloudflareClient,
64    state: &AppState,
65    mut rd: State<String>,
66    mut st: State<String>,
67) {
68    // Invalidate cache before refreshing
69    state.dns_cache.lock().unwrap().invalidate();
70
71    match client.list_dns_records().await {
72        Ok(f) => {
73            rd.set(format_records(&f));
74            st.set(format!("Loaded {} DNS records", f.len()));
75            *state.existing_ips.lock().unwrap() = extract_unique_ips(&f);
76            *state.records.lock().unwrap() = f.clone();
77            state.dns_cache.lock().unwrap().set(f);
78        }
79        Err(e) => st.set(format!("Error: {}", e)),
80    }
81}