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(¶ms.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
385async fn ensure_daemon(endpoint: &str) -> Result<(), String> {
386 match check_daemon_version(endpoint).await {
387 VersionCheck::Ok | VersionCheck::DaemonNewer => return Ok(()),
388 VersionCheck::DaemonOlder { daemon_ver } => {
389 return Err(format!(
390 "daemon v{daemon_ver} is older than client v{}. Run `zccache stop` first.",
391 zccache_core::VERSION,
392 ));
393 }
394 VersionCheck::CommError => {
395 return Err(
396 "cannot communicate with daemon (possible protocol mismatch). Run `zccache stop` first."
397 .to_string(),
398 );
399 }
400 VersionCheck::Unreachable => {}
401 }
402
403 if let Some(pid) = zccache_ipc::check_running_daemon() {
404 for _ in 0..20 {
405 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
406 match check_daemon_version(endpoint).await {
407 VersionCheck::Ok | VersionCheck::DaemonNewer => return Ok(()),
408 VersionCheck::DaemonOlder { daemon_ver } => {
409 return Err(format!(
410 "daemon v{daemon_ver} is older than client v{}. Run `zccache stop` first.",
411 zccache_core::VERSION,
412 ));
413 }
414 VersionCheck::CommError => {
415 return Err(
416 "cannot communicate with daemon (possible protocol mismatch). Run `zccache stop` first."
417 .to_string(),
418 );
419 }
420 VersionCheck::Unreachable => continue,
421 }
422 }
423 return Err(format!(
424 "daemon process {pid} exists but not accepting connections"
425 ));
426 }
427
428 spawn_and_wait(endpoint).await
429}
430
431fn find_daemon_binary() -> Option<NormalizedPath> {
432 let name = if cfg!(windows) {
433 "zccache-daemon.exe"
434 } else {
435 "zccache-daemon"
436 };
437
438 if let Ok(exe) = std::env::current_exe() {
439 if let Some(dir) = exe.parent() {
440 let candidate = dir.join(name);
441 if candidate.exists() {
442 return Some(candidate.into());
443 }
444 }
445 }
446
447 which_on_path(name)
448}
449
450fn which_on_path(name: &str) -> Option<NormalizedPath> {
451 let path_var = std::env::var_os("PATH")?;
452 for dir in std::env::split_paths(&path_var) {
453 let candidate = dir.join(name);
454 if candidate.is_file() {
455 return Some(candidate.into());
456 }
457 #[cfg(windows)]
458 if Path::new(name).extension().is_none() {
459 let with_exe = dir.join(format!("{name}.exe"));
460 if with_exe.is_file() {
461 return Some(with_exe.into());
462 }
463 }
464 }
465 None
466}
467
468fn spawn_daemon(bin: &Path, endpoint: &str) -> Result<(), String> {
469 let mut cmd = std::process::Command::new(bin);
470 cmd.args(["--foreground", "--endpoint", endpoint]);
471 cmd.stdin(std::process::Stdio::null());
472 cmd.stdout(std::process::Stdio::null());
473 cmd.stderr(std::process::Stdio::null());
474
475 #[cfg(windows)]
476 {
477 use std::os::windows::process::CommandExt;
478 const CREATE_NO_WINDOW: u32 = 0x0800_0000;
479 cmd.creation_flags(CREATE_NO_WINDOW);
480 disable_handle_inheritance();
481 }
482
483 cmd.spawn()
484 .map_err(|e| format!("failed to spawn daemon: {e}"))?;
485
486 #[cfg(windows)]
487 restore_handle_inheritance();
488
489 Ok(())
490}
491
492#[cfg(windows)]
493fn disable_handle_inheritance() {
494 use std::os::windows::io::AsRawHandle;
495
496 extern "system" {
497 fn SetHandleInformation(handle: *mut std::ffi::c_void, mask: u32, flags: u32) -> i32;
498 }
499 const HANDLE_FLAG_INHERIT: u32 = 1;
500
501 unsafe {
502 let stdout = std::io::stdout().as_raw_handle();
503 let stderr = std::io::stderr().as_raw_handle();
504 let _ = SetHandleInformation(stdout.cast(), HANDLE_FLAG_INHERIT, 0);
505 let _ = SetHandleInformation(stderr.cast(), HANDLE_FLAG_INHERIT, 0);
506 }
507}
508
509#[cfg(windows)]
510fn restore_handle_inheritance() {
511 use std::os::windows::io::AsRawHandle;
512
513 extern "system" {
514 fn SetHandleInformation(handle: *mut std::ffi::c_void, mask: u32, flags: u32) -> i32;
515 }
516 const HANDLE_FLAG_INHERIT: u32 = 1;
517
518 unsafe {
519 let stdout = std::io::stdout().as_raw_handle();
520 let stderr = std::io::stderr().as_raw_handle();
521 let _ = SetHandleInformation(stdout.cast(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
522 let _ = SetHandleInformation(stderr.cast(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
523 }
524}
525
526#[derive(Debug, Clone)]
527pub struct SessionStartResponse {
528 pub session_id: String,
529 pub journal_path: Option<String>,
530}
531
532pub fn client_start(endpoint: Option<&str>) -> Result<(), String> {
533 let endpoint = resolve_endpoint(endpoint);
534 run_async(async move { ensure_daemon(&endpoint).await })
535}
536
537pub fn client_stop(endpoint: Option<&str>) -> Result<bool, String> {
538 let endpoint = resolve_endpoint(endpoint);
539 run_async(async move {
540 let mut conn = match connect_client(&endpoint).await {
541 Ok(c) => c,
542 Err(_) => return Ok(false),
543 };
544 conn.send(&zccache_protocol::Request::Shutdown)
545 .await
546 .map_err(|e| format!("failed to send to daemon: {e}"))?;
547 match conn.recv::<zccache_protocol::Response>().await {
548 Ok(Some(zccache_protocol::Response::ShuttingDown)) => Ok(true),
549 Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
550 Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
551 Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
552 Err(e) => Err(format!("broken connection to daemon: {e}")),
553 }
554 })
555}
556
557pub fn client_status(endpoint: Option<&str>) -> Result<zccache_protocol::DaemonStatus, String> {
558 let endpoint = resolve_endpoint(endpoint);
559 run_async(async move {
560 let mut conn = connect_client(&endpoint)
561 .await
562 .map_err(|e| format!("daemon not running at {endpoint}: {e}"))?;
563 conn.send(&zccache_protocol::Request::Status)
564 .await
565 .map_err(|e| format!("failed to send to daemon: {e}"))?;
566 match conn.recv::<zccache_protocol::Response>().await {
567 Ok(Some(zccache_protocol::Response::Status(status))) => Ok(status),
568 Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
569 Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
570 Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
571 Err(e) => Err(format!("broken connection to daemon: {e}")),
572 }
573 })
574}
575
576pub fn client_session_start(
577 endpoint: Option<&str>,
578 cwd: &Path,
579 log_file: Option<&Path>,
580 track_stats: bool,
581 journal_path: Option<&Path>,
582) -> Result<SessionStartResponse, String> {
583 let endpoint = resolve_endpoint(endpoint);
584 let cwd = cwd.to_path_buf();
585 let log_file = log_file.map(NormalizedPath::from);
586 let journal_path = journal_path.map(NormalizedPath::from);
587
588 run_async(async move {
589 ensure_daemon(&endpoint).await?;
590 let mut conn = connect_client(&endpoint)
591 .await
592 .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
593 conn.send(&zccache_protocol::Request::SessionStart {
594 client_pid: std::process::id(),
595 working_dir: cwd.into(),
596 log_file,
597 track_stats,
598 journal_path,
599 })
600 .await
601 .map_err(|e| format!("failed to send to daemon: {e}"))?;
602
603 match conn.recv::<zccache_protocol::Response>().await {
604 Ok(Some(zccache_protocol::Response::SessionStarted {
605 session_id,
606 journal_path,
607 })) => Ok(SessionStartResponse {
608 session_id,
609 journal_path: journal_path.map(|p| p.display().to_string()),
610 }),
611 Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
612 Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
613 Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
614 Err(e) => Err(format!("broken connection to daemon: {e}")),
615 }
616 })
617}
618
619pub fn client_session_end(
620 endpoint: Option<&str>,
621 session_id: &str,
622) -> Result<Option<zccache_protocol::SessionStats>, String> {
623 let endpoint = resolve_endpoint(endpoint);
624 let session_id = session_id.to_string();
625 run_async(async move {
626 let mut conn = connect_client(&endpoint)
627 .await
628 .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
629 conn.send(&zccache_protocol::Request::SessionEnd {
630 session_id: session_id.clone(),
631 })
632 .await
633 .map_err(|e| format!("failed to send to daemon: {e}"))?;
634
635 match conn.recv::<zccache_protocol::Response>().await {
636 Ok(Some(zccache_protocol::Response::SessionEnded { stats })) => Ok(stats),
637 Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
638 Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
639 Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
640 Err(e) => Err(format!("broken connection to daemon: {e}")),
641 }
642 })
643}
644
645pub fn client_session_stats(
646 endpoint: Option<&str>,
647 session_id: &str,
648) -> Result<Option<zccache_protocol::SessionStats>, String> {
649 let endpoint = resolve_endpoint(endpoint);
650 let session_id = session_id.to_string();
651 run_async(async move {
652 let mut conn = connect_client(&endpoint)
653 .await
654 .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
655 conn.send(&zccache_protocol::Request::SessionStats {
656 session_id: session_id.clone(),
657 })
658 .await
659 .map_err(|e| format!("failed to send to daemon: {e}"))?;
660
661 match conn.recv::<zccache_protocol::Response>().await {
662 Ok(Some(zccache_protocol::Response::SessionStatsResult { stats })) => Ok(stats),
663 Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
664 Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
665 Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
666 Err(e) => Err(format!("broken connection to daemon: {e}")),
667 }
668 })
669}
670
671#[derive(Debug, Clone)]
672pub struct FingerprintCheckResponse {
673 pub decision: String,
674 pub reason: Option<String>,
675 pub changed_files: Vec<String>,
676}
677
678pub fn fingerprint_check(
679 endpoint: Option<&str>,
680 cache_file: &Path,
681 cache_type: &str,
682 root: &Path,
683 extensions: &[String],
684 include_globs: &[String],
685 exclude: &[String],
686) -> Result<FingerprintCheckResponse, String> {
687 let endpoint = resolve_endpoint(endpoint);
688 let cache_file = cache_file.to_path_buf();
689 let cache_type = cache_type.to_string();
690 let root = root.to_path_buf();
691 let extensions = extensions.to_vec();
692 let include_globs = include_globs.to_vec();
693 let exclude = exclude.to_vec();
694
695 run_async(async move {
696 ensure_daemon(&endpoint).await?;
697 let mut conn = connect_client(&endpoint)
698 .await
699 .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
700
701 conn.send(&zccache_protocol::Request::FingerprintCheck {
702 cache_file: cache_file.into(),
703 cache_type,
704 root: root.into(),
705 extensions,
706 include_globs,
707 exclude,
708 })
709 .await
710 .map_err(|e| format!("failed to send to daemon: {e}"))?;
711
712 match conn.recv::<zccache_protocol::Response>().await {
713 Ok(Some(zccache_protocol::Response::FingerprintCheckResult {
714 decision,
715 reason,
716 changed_files,
717 })) => Ok(FingerprintCheckResponse {
718 decision,
719 reason,
720 changed_files,
721 }),
722 Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
723 Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
724 Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
725 Err(e) => Err(format!("broken connection to daemon: {e}")),
726 }
727 })
728}
729
730pub fn fingerprint_mark_success(endpoint: Option<&str>, cache_file: &Path) -> Result<(), String> {
731 fingerprint_mark(endpoint, cache_file, true)
732}
733
734pub fn fingerprint_mark_failure(endpoint: Option<&str>, cache_file: &Path) -> Result<(), String> {
735 fingerprint_mark(endpoint, cache_file, false)
736}
737
738fn fingerprint_mark(
739 endpoint: Option<&str>,
740 cache_file: &Path,
741 success: bool,
742) -> Result<(), String> {
743 let endpoint = resolve_endpoint(endpoint);
744 let cache_file = cache_file.to_path_buf();
745 run_async(async move {
746 ensure_daemon(&endpoint).await?;
747 let mut conn = connect_client(&endpoint)
748 .await
749 .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
750 let request = if success {
751 zccache_protocol::Request::FingerprintMarkSuccess {
752 cache_file: cache_file.into(),
753 }
754 } else {
755 zccache_protocol::Request::FingerprintMarkFailure {
756 cache_file: cache_file.into(),
757 }
758 };
759 conn.send(&request)
760 .await
761 .map_err(|e| format!("failed to send to daemon: {e}"))?;
762 match conn.recv::<zccache_protocol::Response>().await {
763 Ok(Some(zccache_protocol::Response::FingerprintAck)) => Ok(()),
764 Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
765 Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
766 Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
767 Err(e) => Err(format!("broken connection to daemon: {e}")),
768 }
769 })
770}
771
772pub fn fingerprint_invalidate(endpoint: Option<&str>, cache_file: &Path) -> Result<(), String> {
773 let endpoint = resolve_endpoint(endpoint);
774 let cache_file = cache_file.to_path_buf();
775 run_async(async move {
776 ensure_daemon(&endpoint).await?;
777 let mut conn = connect_client(&endpoint)
778 .await
779 .map_err(|e| format!("cannot connect to daemon at {endpoint}: {e}"))?;
780 conn.send(&zccache_protocol::Request::FingerprintInvalidate {
781 cache_file: cache_file.into(),
782 })
783 .await
784 .map_err(|e| format!("failed to send to daemon: {e}"))?;
785 match conn.recv::<zccache_protocol::Response>().await {
786 Ok(Some(zccache_protocol::Response::FingerprintAck)) => Ok(()),
787 Ok(Some(zccache_protocol::Response::Error { message })) => Err(message),
788 Ok(None) => Err("lost connection to daemon (no response received)".to_string()),
789 Ok(Some(other)) => Err(format!("unexpected response from daemon: {other:?}")),
790 Err(e) => Err(format!("broken connection to daemon: {e}")),
791 }
792 })
793}
794
795#[cfg(test)]
796mod tests {
797 use super::*;
798
799 #[test]
800 fn infer_download_path_keeps_url_filename() {
801 let path = infer_download_archive_path(
802 &DownloadSource::Url("https://example.com/releases/toolchain.tar.gz?download=1".into()),
803 ArchiveFormat::Auto,
804 );
805 let file_name = path.file_name().unwrap().to_string_lossy();
806 assert!(file_name.ends_with("-toolchain.tar.gz"));
807 }
808
809 #[test]
810 fn infer_download_path_uses_archive_format_suffix_when_needed() {
811 let path = infer_download_archive_path(
812 &DownloadSource::Url("https://example.com/download".into()),
813 ArchiveFormat::Zip,
814 );
815 let file_name = path.file_name().unwrap().to_string_lossy();
816 assert!(file_name.ends_with(".zip"));
817 }
818
819 #[test]
820 fn build_download_request_derives_archive_path_when_missing() {
821 let request = build_download_request(DownloadParams::new("https://example.com/file.zip"));
822 let file_name = request
823 .destination_path
824 .file_name()
825 .unwrap()
826 .to_string_lossy();
827 assert!(file_name.ends_with("-file.zip"));
828 }
829
830 #[test]
831 fn infer_download_path_strips_multipart_suffix_from_first_part() {
832 let path = infer_download_archive_path(
833 &DownloadSource::MultipartUrls(vec![
834 "https://example.com/toolchain.tar.zst.part-aa".into(),
835 "https://example.com/toolchain.tar.zst.part-ab".into(),
836 ]),
837 ArchiveFormat::Auto,
838 );
839 let file_name = path.file_name().unwrap().to_string_lossy();
840 assert!(file_name.ends_with("-toolchain.tar.zst"));
841 }
842}