Skip to main content

zccache_cli/
lib.rs

1#![allow(clippy::missing_errors_doc)]
2
3use std::path::Path;
4use zccache_core::NormalizedPath;
5
6#[cfg(feature = "python")]
7mod python;
8
9pub use zccache_download_client::{
10    ArchiveFormat, DownloadSource, FetchRequest, FetchResult, FetchState, FetchStateKind,
11    FetchStatus, WaitMode,
12};
13
14#[derive(Debug, Clone)]
15pub struct InoConvertOptions {
16    pub clang_args: Vec<String>,
17    pub inject_arduino_include: bool,
18}
19
20impl Default for InoConvertOptions {
21    fn default() -> Self {
22        Self {
23            clang_args: Vec::new(),
24            inject_arduino_include: true,
25        }
26    }
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct InoConvertResult {
31    pub cache_hit: bool,
32    pub skipped_write: bool,
33}
34
35#[derive(Debug, Clone)]
36pub struct DownloadParams {
37    pub source: DownloadSource,
38    pub archive_path: Option<std::path::PathBuf>,
39    pub unarchive_path: Option<std::path::PathBuf>,
40    pub expected_sha256: Option<String>,
41    pub archive_format: ArchiveFormat,
42    pub max_connections: Option<usize>,
43    pub min_segment_size: Option<u64>,
44    pub wait_mode: WaitMode,
45    pub dry_run: bool,
46    pub force: bool,
47}
48
49impl DownloadParams {
50    #[must_use]
51    pub fn new(source: impl Into<DownloadSource>) -> Self {
52        Self {
53            source: source.into(),
54            archive_path: None,
55            unarchive_path: None,
56            expected_sha256: None,
57            archive_format: ArchiveFormat::Auto,
58            max_connections: None,
59            min_segment_size: None,
60            wait_mode: WaitMode::Block,
61            dry_run: false,
62            force: false,
63        }
64    }
65}
66
67pub fn run_ino_convert_cached(
68    input: &Path,
69    output: &Path,
70    options: &InoConvertOptions,
71) -> Result<InoConvertResult, Box<dyn std::error::Error>> {
72    let input_hash = zccache_hash::hash_file(input)?;
73    let mut hasher = zccache_hash::StreamHasher::new();
74    hasher.update(b"zccache-ino-convert-v1");
75    hasher.update(input_hash.as_bytes());
76    hasher.update(input.as_os_str().to_string_lossy().as_bytes());
77    hasher.update(if options.inject_arduino_include {
78        b"include-arduino-h"
79    } else {
80        b"no-arduino-h"
81    });
82    if let Some(libclang_hash) = zccache_compiler::arduino::libclang_hash() {
83        hasher.update(libclang_hash.as_bytes());
84    }
85    for arg in &options.clang_args {
86        hasher.update(arg.as_bytes());
87        hasher.update(b"\0");
88    }
89    let cache_key = hasher.finalize().to_hex();
90
91    let cache_dir = zccache_core::config::default_cache_dir().join("ino");
92    std::fs::create_dir_all(&cache_dir)?;
93    let cached_cpp = cache_dir.join(format!("{cache_key}.ino.cpp"));
94
95    if cached_cpp.exists() {
96        return restore_cached_ino_output(&cached_cpp, output);
97    }
98
99    let generated = zccache_compiler::arduino::generate_ino_cpp(
100        input,
101        &zccache_compiler::arduino::ArduinoConversionOptions {
102            clang_args: options.clang_args.clone(),
103            inject_arduino_include: options.inject_arduino_include,
104        },
105    )?;
106
107    write_file_atomically(&cached_cpp, generated.cpp.as_bytes())?;
108    restore_cached_ino_output(&cached_cpp, output).map(|_| InoConvertResult {
109        cache_hit: false,
110        skipped_write: false,
111    })
112}
113
114fn restore_cached_ino_output(
115    cached_cpp: &Path,
116    output: &Path,
117) -> Result<InoConvertResult, Box<dyn std::error::Error>> {
118    if output.exists() {
119        let output_hash = zccache_hash::hash_file(output)?;
120        let cached_hash = zccache_hash::hash_file(cached_cpp)?;
121        if output_hash == cached_hash {
122            return Ok(InoConvertResult {
123                cache_hit: true,
124                skipped_write: true,
125            });
126        }
127    }
128
129    if let Some(parent) = output.parent() {
130        std::fs::create_dir_all(parent)?;
131    }
132    std::fs::copy(cached_cpp, output)?;
133    Ok(InoConvertResult {
134        cache_hit: true,
135        skipped_write: false,
136    })
137}
138
139fn write_file_atomically(path: &Path, data: &[u8]) -> Result<(), std::io::Error> {
140    let parent = path.parent().unwrap_or_else(|| Path::new("."));
141    std::fs::create_dir_all(parent)?;
142
143    let tmp = tempfile::NamedTempFile::new_in(parent)?;
144    std::fs::write(tmp.path(), data)?;
145    match tmp.persist(path) {
146        Ok(_) => Ok(()),
147        Err(err) => Err(err.error),
148    }
149}
150
151fn resolve_endpoint(explicit: Option<&str>) -> String {
152    if let Some(ep) = explicit {
153        return ep.to_string();
154    }
155    if let Ok(ep) = std::env::var("ZCCACHE_ENDPOINT") {
156        return ep;
157    }
158    zccache_ipc::default_endpoint()
159}
160
161pub fn infer_download_archive_path(
162    source: &DownloadSource,
163    archive_format: ArchiveFormat,
164) -> std::path::PathBuf {
165    let file_name = infer_download_file_name(source, archive_format);
166    zccache_core::config::default_cache_dir()
167        .join("downloads")
168        .join("artifacts")
169        .join(file_name)
170        .into_path_buf()
171}
172
173#[must_use]
174pub fn build_download_request(params: DownloadParams) -> FetchRequest {
175    let archive_path = params
176        .archive_path
177        .unwrap_or_else(|| infer_download_archive_path(&params.source, params.archive_format));
178    let mut request = FetchRequest::new(params.source, archive_path);
179    request.destination_path_expanded = params.unarchive_path;
180    request.expected_sha256 = params.expected_sha256;
181    request.archive_format = params.archive_format;
182    request.wait_mode = params.wait_mode;
183    request.dry_run = params.dry_run;
184    request.force = params.force;
185    request.download_options.force = params.force;
186    request.download_options.max_connections = params.max_connections;
187    request.download_options.min_segment_size = params.min_segment_size;
188    request
189}
190
191pub fn client_download(
192    endpoint: Option<&str>,
193    params: DownloadParams,
194) -> Result<FetchResult, String> {
195    let request = build_download_request(params);
196    let client = zccache_download_client::DownloadClient::new(endpoint.map(ToOwned::to_owned));
197    client.fetch(request)
198}
199
200pub fn client_download_exists(
201    endpoint: Option<&str>,
202    params: DownloadParams,
203) -> Result<FetchState, String> {
204    let request = build_download_request(params);
205    let client = zccache_download_client::DownloadClient::new(endpoint.map(ToOwned::to_owned));
206    client.exists(&request)
207}
208
209fn infer_download_file_name(source: &DownloadSource, archive_format: ArchiveFormat) -> String {
210    let base = infer_source_file_name(source);
211    let hash = blake3::hash(download_source_key(source).as_bytes())
212        .to_hex()
213        .to_string();
214    let suffix = archive_suffix(archive_format);
215
216    if base.contains('.') || suffix.is_empty() {
217        format!("{hash}-{base}")
218    } else {
219        format!("{hash}-{base}{suffix}")
220    }
221}
222
223fn infer_source_file_name(source: &DownloadSource) -> String {
224    match source {
225        DownloadSource::Url(url) => {
226            infer_url_file_name(url).unwrap_or_else(|| "download".to_string())
227        }
228        DownloadSource::MultipartUrls(urls) => infer_multipart_file_name(urls),
229    }
230}
231
232fn infer_url_file_name(url: &str) -> Option<String> {
233    url.split(['?', '#'])
234        .next()
235        .and_then(|value| value.rsplit('/').next())
236        .filter(|value| !value.is_empty())
237        .map(sanitize_download_file_name)
238        .filter(|value| !value.is_empty())
239}
240
241fn infer_multipart_file_name(urls: &[String]) -> String {
242    let base = urls
243        .first()
244        .and_then(|url| infer_url_file_name(url))
245        .map(|name| strip_part_suffix(&name).to_string())
246        .filter(|name| !name.is_empty())
247        .unwrap_or_else(|| "multipart-download".to_string());
248    if base.contains('.') {
249        base
250    } else {
251        "multipart-download".to_string()
252    }
253}
254
255fn strip_part_suffix(value: &str) -> &str {
256    if let Some((base, suffix)) = value.rsplit_once(".part-") {
257        if !base.is_empty() && !suffix.is_empty() {
258            return base;
259        }
260    }
261    if let Some((base, suffix)) = value.rsplit_once(".part_") {
262        if !base.is_empty() && !suffix.is_empty() {
263            return base;
264        }
265    }
266    if let Some(index) = value.rfind(".part") {
267        let suffix = &value[index + ".part".len()..];
268        if !suffix.is_empty()
269            && suffix
270                .chars()
271                .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')
272        {
273            return &value[..index];
274        }
275    }
276    value
277}
278
279fn download_source_key(source: &DownloadSource) -> String {
280    match source {
281        DownloadSource::Url(url) => url.clone(),
282        DownloadSource::MultipartUrls(urls) => urls.join("\n"),
283    }
284}
285
286fn sanitize_download_file_name(value: &str) -> String {
287    value
288        .chars()
289        .map(|ch| match ch {
290            '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*' => '_',
291            c if c.is_control() => '_',
292            c => c,
293        })
294        .collect()
295}
296
297fn archive_suffix(format: ArchiveFormat) -> &'static str {
298    match format {
299        ArchiveFormat::Auto | ArchiveFormat::None => "",
300        ArchiveFormat::Zst => ".zst",
301        ArchiveFormat::Zip => ".zip",
302        ArchiveFormat::Xz => ".xz",
303        ArchiveFormat::TarGz => ".tar.gz",
304        ArchiveFormat::TarXz => ".tar.xz",
305        ArchiveFormat::TarZst => ".tar.zst",
306        ArchiveFormat::SevenZip => ".7z",
307    }
308}
309
310fn run_async<T>(future: impl std::future::Future<Output = Result<T, String>>) -> Result<T, String> {
311    tokio::runtime::Builder::new_current_thread()
312        .enable_all()
313        .build()
314        .map_err(|e| format!("failed to create tokio runtime: {e}"))?
315        .block_on(future)
316}
317
318#[derive(Debug)]
319enum VersionCheck {
320    Ok,
321    Unreachable,
322    DaemonOlder { daemon_ver: String },
323    DaemonNewer,
324    CommError,
325}
326
327#[cfg(unix)]
328async fn connect_client(
329    endpoint: &str,
330) -> Result<zccache_ipc::IpcConnection, zccache_ipc::IpcError> {
331    zccache_ipc::connect(endpoint).await
332}
333
334#[cfg(windows)]
335async fn connect_client(
336    endpoint: &str,
337) -> Result<zccache_ipc::IpcClientConnection, zccache_ipc::IpcError> {
338    zccache_ipc::connect(endpoint).await
339}
340
341async fn check_daemon_version(endpoint: &str) -> VersionCheck {
342    let mut conn = match connect_client(endpoint).await {
343        Ok(c) => c,
344        Err(_) => return VersionCheck::Unreachable,
345    };
346    if conn.send(&zccache_protocol::Request::Status).await.is_err() {
347        return VersionCheck::CommError;
348    }
349    match conn.recv::<zccache_protocol::Response>().await {
350        Ok(Some(zccache_protocol::Response::Status(s))) => {
351            if s.version == zccache_core::VERSION {
352                return VersionCheck::Ok;
353            }
354            let client_ver = zccache_core::version::current();
355            match zccache_core::version::Version::parse(&s.version) {
356                Some(daemon_ver) => match daemon_ver.cmp(&client_ver) {
357                    std::cmp::Ordering::Equal => VersionCheck::Ok,
358                    std::cmp::Ordering::Greater => VersionCheck::DaemonNewer,
359                    std::cmp::Ordering::Less => VersionCheck::DaemonOlder {
360                        daemon_ver: s.version,
361                    },
362                },
363                None => VersionCheck::DaemonOlder {
364                    daemon_ver: s.version,
365                },
366            }
367        }
368        _ => VersionCheck::CommError,
369    }
370}
371
372async fn spawn_and_wait(endpoint: &str) -> Result<(), String> {
373    let daemon_bin = find_daemon_binary().ok_or("cannot find zccache-daemon binary")?;
374    spawn_daemon(&daemon_bin, endpoint)?;
375
376    for _ in 0..100 {
377        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
378        if connect_client(endpoint).await.is_ok() {
379            return Ok(());
380        }
381    }
382    Err("daemon started but not accepting connections after 10s".to_string())
383}
384
385/// Stop a stale daemon that is unreachable or version-incompatible.
386async fn stop_stale_daemon(endpoint: &str) {
387    if let Ok(mut conn) = connect_client(endpoint).await {
388        let _ = conn.send(&zccache_protocol::Request::Shutdown).await;
389        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
390    }
391
392    if let Some(pid) = zccache_ipc::check_running_daemon() {
393        if zccache_ipc::force_kill_process(pid).is_ok() {
394            for _ in 0..50 {
395                if !zccache_ipc::is_process_alive(pid) {
396                    break;
397                }
398                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
399            }
400        }
401        zccache_ipc::remove_lock_file();
402    }
403
404    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
405}
406
407async fn ensure_daemon(endpoint: &str) -> Result<(), String> {
408    match check_daemon_version(endpoint).await {
409        VersionCheck::Ok | VersionCheck::DaemonNewer => return Ok(()),
410        VersionCheck::DaemonOlder { daemon_ver } => {
411            tracing::info!(
412                daemon_ver,
413                client_ver = zccache_core::VERSION,
414                "daemon is older than client, auto-recovering"
415            );
416            stop_stale_daemon(endpoint).await;
417            return spawn_and_wait(endpoint).await;
418        }
419        VersionCheck::CommError => {
420            tracing::info!("cannot communicate with daemon, auto-recovering");
421            stop_stale_daemon(endpoint).await;
422            return spawn_and_wait(endpoint).await;
423        }
424        VersionCheck::Unreachable => {}
425    }
426
427    if let Some(pid) = zccache_ipc::check_running_daemon() {
428        for _ in 0..20 {
429            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
430            match check_daemon_version(endpoint).await {
431                VersionCheck::Ok | VersionCheck::DaemonNewer => return Ok(()),
432                VersionCheck::DaemonOlder { daemon_ver } => {
433                    tracing::info!(
434                        daemon_ver,
435                        client_ver = zccache_core::VERSION,
436                        "daemon is older than client during startup, auto-recovering"
437                    );
438                    stop_stale_daemon(endpoint).await;
439                    return spawn_and_wait(endpoint).await;
440                }
441                VersionCheck::CommError => {
442                    stop_stale_daemon(endpoint).await;
443                    return spawn_and_wait(endpoint).await;
444                }
445                VersionCheck::Unreachable => continue,
446            }
447        }
448        return Err(format!(
449            "daemon process {pid} exists but not accepting connections"
450        ));
451    }
452
453    spawn_and_wait(endpoint).await
454}
455
456fn find_daemon_binary() -> Option<NormalizedPath> {
457    let name = if cfg!(windows) {
458        "zccache-daemon.exe"
459    } else {
460        "zccache-daemon"
461    };
462
463    if let Ok(exe) = std::env::current_exe() {
464        if let Some(dir) = exe.parent() {
465            let candidate = dir.join(name);
466            if candidate.exists() {
467                return Some(candidate.into());
468            }
469        }
470    }
471
472    which_on_path(name)
473}
474
475fn which_on_path(name: &str) -> Option<NormalizedPath> {
476    let path_var = std::env::var_os("PATH")?;
477    for dir in std::env::split_paths(&path_var) {
478        let candidate = dir.join(name);
479        if candidate.is_file() {
480            return Some(candidate.into());
481        }
482        #[cfg(windows)]
483        if Path::new(name).extension().is_none() {
484            let with_exe = dir.join(format!("{name}.exe"));
485            if with_exe.is_file() {
486                return Some(with_exe.into());
487            }
488        }
489    }
490    None
491}
492
493fn spawn_daemon(bin: &Path, endpoint: &str) -> Result<(), String> {
494    let mut cmd = std::process::Command::new(bin);
495    cmd.args(["--foreground", "--endpoint", endpoint]);
496    cmd.stdin(std::process::Stdio::null());
497    cmd.stdout(std::process::Stdio::null());
498    cmd.stderr(std::process::Stdio::null());
499
500    #[cfg(windows)]
501    {
502        use std::os::windows::process::CommandExt;
503        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
504        cmd.creation_flags(CREATE_NO_WINDOW);
505        disable_handle_inheritance();
506    }
507
508    cmd.spawn()
509        .map_err(|e| format!("failed to spawn daemon: {e}"))?;
510
511    #[cfg(windows)]
512    restore_handle_inheritance();
513
514    Ok(())
515}
516
517#[cfg(windows)]
518fn disable_handle_inheritance() {
519    use std::os::windows::io::AsRawHandle;
520
521    extern "system" {
522        fn SetHandleInformation(handle: *mut std::ffi::c_void, mask: u32, flags: u32) -> i32;
523    }
524    const HANDLE_FLAG_INHERIT: u32 = 1;
525
526    unsafe {
527        let stdout = std::io::stdout().as_raw_handle();
528        let stderr = std::io::stderr().as_raw_handle();
529        let _ = SetHandleInformation(stdout.cast(), HANDLE_FLAG_INHERIT, 0);
530        let _ = SetHandleInformation(stderr.cast(), HANDLE_FLAG_INHERIT, 0);
531    }
532}
533
534#[cfg(windows)]
535fn restore_handle_inheritance() {
536    use std::os::windows::io::AsRawHandle;
537
538    extern "system" {
539        fn SetHandleInformation(handle: *mut std::ffi::c_void, mask: u32, flags: u32) -> i32;
540    }
541    const HANDLE_FLAG_INHERIT: u32 = 1;
542
543    unsafe {
544        let stdout = std::io::stdout().as_raw_handle();
545        let stderr = std::io::stderr().as_raw_handle();
546        let _ = SetHandleInformation(stdout.cast(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
547        let _ = SetHandleInformation(stderr.cast(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
548    }
549}
550
551#[derive(Debug, Clone)]
552pub struct SessionStartResponse {
553    pub session_id: String,
554    pub journal_path: Option<String>,
555}
556
557pub fn client_start(endpoint: Option<&str>) -> Result<(), String> {
558    let endpoint = resolve_endpoint(endpoint);
559    run_async(async move { ensure_daemon(&endpoint).await })
560}
561
562pub fn client_stop(endpoint: Option<&str>) -> Result<bool, String> {
563    let endpoint = resolve_endpoint(endpoint);
564    run_async(async move {
565        let mut conn = match connect_client(&endpoint).await {
566            Ok(c) => c,
567            Err(_) => return Ok(false),
568        };
569        conn.send(&zccache_protocol::Request::Shutdown)
570            .await
571            .map_err(|e| format!("failed to send to daemon: {e}"))?;
572        match conn.recv::<zccache_protocol::Response>().await {
573            Ok(Some(zccache_protocol::Response::ShuttingDown)) => Ok(true),
574            Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
575            Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
576            Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
577            Err(e) => Err(format!("broken connection to daemon: {e}")),
578        }
579    })
580}
581
582pub fn client_status(endpoint: Option<&str>) -> Result<zccache_protocol::DaemonStatus, String> {
583    let endpoint = resolve_endpoint(endpoint);
584    run_async(async move {
585        let mut conn = connect_client(&endpoint)
586            .await
587            .map_err(|e| format!("daemon not running at {endpoint}: {e}"))?;
588        conn.send(&zccache_protocol::Request::Status)
589            .await
590            .map_err(|e| format!("failed to send to daemon: {e}"))?;
591        match conn.recv::<zccache_protocol::Response>().await {
592            Ok(Some(zccache_protocol::Response::Status(status))) => Ok(status),
593            Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
594            Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
595            Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
596            Err(e) => Err(format!("broken connection to daemon: {e}")),
597        }
598    })
599}
600
601pub fn client_session_start(
602    endpoint: Option<&str>,
603    cwd: &Path,
604    log_file: Option<&Path>,
605    track_stats: bool,
606    journal_path: Option<&Path>,
607) -> Result<SessionStartResponse, String> {
608    let endpoint = resolve_endpoint(endpoint);
609    let cwd = cwd.to_path_buf();
610    let log_file = log_file.map(NormalizedPath::from);
611    let journal_path = journal_path.map(NormalizedPath::from);
612
613    run_async(async move {
614        ensure_daemon(&endpoint).await?;
615        let mut conn = connect_client(&endpoint)
616            .await
617            .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
618        conn.send(&zccache_protocol::Request::SessionStart {
619            client_pid: std::process::id(),
620            working_dir: cwd.into(),
621            log_file,
622            track_stats,
623            journal_path,
624        })
625        .await
626        .map_err(|e| format!("failed to send to daemon: {e}"))?;
627
628        match conn.recv::<zccache_protocol::Response>().await {
629            Ok(Some(zccache_protocol::Response::SessionStarted {
630                session_id,
631                journal_path,
632            })) => Ok(SessionStartResponse {
633                session_id,
634                journal_path: journal_path.map(|p| p.display().to_string()),
635            }),
636            Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
637            Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
638            Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
639            Err(e) => Err(format!("broken connection to daemon: {e}")),
640        }
641    })
642}
643
644pub fn client_session_end(
645    endpoint: Option<&str>,
646    session_id: &str,
647) -> Result<Option<zccache_protocol::SessionStats>, String> {
648    let endpoint = resolve_endpoint(endpoint);
649    let session_id = session_id.to_string();
650    run_async(async move {
651        let mut conn = connect_client(&endpoint)
652            .await
653            .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
654        conn.send(&zccache_protocol::Request::SessionEnd {
655            session_id: session_id.clone(),
656        })
657        .await
658        .map_err(|e| format!("failed to send to daemon: {e}"))?;
659
660        match conn.recv::<zccache_protocol::Response>().await {
661            Ok(Some(zccache_protocol::Response::SessionEnded { stats })) => Ok(stats),
662            Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
663            Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
664            Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
665            Err(e) => Err(format!("broken connection to daemon: {e}")),
666        }
667    })
668}
669
670pub fn client_session_stats(
671    endpoint: Option<&str>,
672    session_id: &str,
673) -> Result<Option<zccache_protocol::SessionStats>, String> {
674    let endpoint = resolve_endpoint(endpoint);
675    let session_id = session_id.to_string();
676    run_async(async move {
677        let mut conn = connect_client(&endpoint)
678            .await
679            .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
680        conn.send(&zccache_protocol::Request::SessionStats {
681            session_id: session_id.clone(),
682        })
683        .await
684        .map_err(|e| format!("failed to send to daemon: {e}"))?;
685
686        match conn.recv::<zccache_protocol::Response>().await {
687            Ok(Some(zccache_protocol::Response::SessionStatsResult { stats })) => Ok(stats),
688            Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
689            Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
690            Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
691            Err(e) => Err(format!("broken connection to daemon: {e}")),
692        }
693    })
694}
695
696#[derive(Debug, Clone)]
697pub struct FingerprintCheckResponse {
698    pub decision: String,
699    pub reason: Option<String>,
700    pub changed_files: Vec<String>,
701}
702
703pub fn fingerprint_check(
704    endpoint: Option<&str>,
705    cache_file: &Path,
706    cache_type: &str,
707    root: &Path,
708    extensions: &[String],
709    include_globs: &[String],
710    exclude: &[String],
711) -> Result<FingerprintCheckResponse, String> {
712    let endpoint = resolve_endpoint(endpoint);
713    let cache_file = cache_file.to_path_buf();
714    let cache_type = cache_type.to_string();
715    let root = root.to_path_buf();
716    let extensions = extensions.to_vec();
717    let include_globs = include_globs.to_vec();
718    let exclude = exclude.to_vec();
719
720    run_async(async move {
721        ensure_daemon(&endpoint).await?;
722        let mut conn = connect_client(&endpoint)
723            .await
724            .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
725
726        conn.send(&zccache_protocol::Request::FingerprintCheck {
727            cache_file: cache_file.into(),
728            cache_type,
729            root: root.into(),
730            extensions,
731            include_globs,
732            exclude,
733        })
734        .await
735        .map_err(|e| format!("failed to send to daemon: {e}"))?;
736
737        match conn.recv::<zccache_protocol::Response>().await {
738            Ok(Some(zccache_protocol::Response::FingerprintCheckResult {
739                decision,
740                reason,
741                changed_files,
742            })) => Ok(FingerprintCheckResponse {
743                decision,
744                reason,
745                changed_files,
746            }),
747            Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
748            Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
749            Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
750            Err(e) => Err(format!("broken connection to daemon: {e}")),
751        }
752    })
753}
754
755pub fn fingerprint_mark_success(endpoint: Option<&str>, cache_file: &Path) -> Result<(), String> {
756    fingerprint_mark(endpoint, cache_file, true)
757}
758
759pub fn fingerprint_mark_failure(endpoint: Option<&str>, cache_file: &Path) -> Result<(), String> {
760    fingerprint_mark(endpoint, cache_file, false)
761}
762
763fn fingerprint_mark(
764    endpoint: Option<&str>,
765    cache_file: &Path,
766    success: bool,
767) -> Result<(), String> {
768    let endpoint = resolve_endpoint(endpoint);
769    let cache_file = cache_file.to_path_buf();
770    run_async(async move {
771        ensure_daemon(&endpoint).await?;
772        let mut conn = connect_client(&endpoint)
773            .await
774            .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
775        let request = if success {
776            zccache_protocol::Request::FingerprintMarkSuccess {
777                cache_file: cache_file.into(),
778            }
779        } else {
780            zccache_protocol::Request::FingerprintMarkFailure {
781                cache_file: cache_file.into(),
782            }
783        };
784        conn.send(&request)
785            .await
786            .map_err(|e| format!("failed to send to daemon: {e}"))?;
787        match conn.recv::<zccache_protocol::Response>().await {
788            Ok(Some(zccache_protocol::Response::FingerprintAck)) => Ok(()),
789            Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
790            Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
791            Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
792            Err(e) => Err(format!("broken connection to daemon: {e}")),
793        }
794    })
795}
796
797pub fn fingerprint_invalidate(endpoint: Option<&str>, cache_file: &Path) -> Result<(), String> {
798    let endpoint = resolve_endpoint(endpoint);
799    let cache_file = cache_file.to_path_buf();
800    run_async(async move {
801        ensure_daemon(&endpoint).await?;
802        let mut conn = connect_client(&endpoint)
803            .await
804            .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
805        conn.send(&zccache_protocol::Request::FingerprintInvalidate {
806            cache_file: cache_file.into(),
807        })
808        .await
809        .map_err(|e| format!("failed to send to daemon: {e}"))?;
810        match conn.recv::<zccache_protocol::Response>().await {
811            Ok(Some(zccache_protocol::Response::FingerprintAck)) => Ok(()),
812            Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
813            Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
814            Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
815            Err(e) => Err(format!("broken connection to daemon: {e}")),
816        }
817    })
818}
819
820#[cfg(test)]
821mod tests {
822    use super::*;
823
824    #[test]
825    fn infer_download_path_keeps_url_filename() {
826        let path = infer_download_archive_path(
827            &DownloadSource::Url("https://example.com/releases/toolchain.tar.gz?download=1".into()),
828            ArchiveFormat::Auto,
829        );
830        let file_name = path.file_name().unwrap().to_string_lossy();
831        assert!(file_name.ends_with("-toolchain.tar.gz"));
832    }
833
834    #[test]
835    fn infer_download_path_uses_archive_format_suffix_when_needed() {
836        let path = infer_download_archive_path(
837            &DownloadSource::Url("https://example.com/download".into()),
838            ArchiveFormat::Zip,
839        );
840        let file_name = path.file_name().unwrap().to_string_lossy();
841        assert!(file_name.ends_with(".zip"));
842    }
843
844    #[test]
845    fn build_download_request_derives_archive_path_when_missing() {
846        let request = build_download_request(DownloadParams::new("https://example.com/file.zip"));
847        let file_name = request
848            .destination_path
849            .file_name()
850            .unwrap()
851            .to_string_lossy();
852        assert!(file_name.ends_with("-file.zip"));
853    }
854
855    #[test]
856    fn infer_download_path_strips_multipart_suffix_from_first_part() {
857        let path = infer_download_archive_path(
858            &DownloadSource::MultipartUrls(vec![
859                "https://example.com/toolchain.tar.zst.part-aa".into(),
860                "https://example.com/toolchain.tar.zst.part-ab".into(),
861            ]),
862            ArchiveFormat::Auto,
863        );
864        let file_name = path.file_name().unwrap().to_string_lossy();
865        assert!(file_name.ends_with("-toolchain.tar.zst"));
866    }
867}