1#![deny(missing_docs)]
30
31use eyre::{Result, bail, eyre};
32use log::warn;
33use reqwest::header::HeaderValue;
34use serde::{Deserialize, Serialize};
35use std::path::{Path, PathBuf};
36use std::time::{Duration, Instant};
37use url::Url;
38
39mod agent;
40mod client;
41mod local;
42mod path_mapping;
43mod remote_http;
44mod remote_s3;
45mod sigv4;
46mod uploads;
47
48pub use agent::{
49 AGENT_PROTOCOL_VERSION, AgentEvent, AgentEventObserver, AgentRemoteCache, AgentRequest,
50 AgentResponse, AgentStats, CacheAgent, CompilerStats, FileDigestCache, FileDigestScope,
51 FileIdentity, NoFileDigestCache, RecordedFileDigest, RestoreStats, is_task_identity,
52 task_manifest_actions,
53};
54pub use client::BlockingAgentClient;
55pub use local::{LocalActionCache, LocalCas};
56pub use mbx_cache_protocol::{
57 ACTION_PROMISE_MEDIA_TYPE, ACTION_RESULT_BATCH_MEDIA_TYPE, ACTION_RESULT_MEDIA_TYPE,
58 ActionPrediction, ActionPromiseCompletion, ActionPromiseJoin, ActionPromiseState,
59 ActionResult as RemoteActionResult, BLOB_MEDIA_TYPE, BLOB_PACK_BLOBS_HEADER,
60 BLOB_PACK_BYTES_HEADER, BLOB_PACK_HEADER_BYTES, BLOB_PACK_MAGIC, BLOB_PACK_MEDIA_TYPE,
61 BLOB_PACK_RECEIPT_MEDIA_TYPE, CLIENT_METADATA_MEDIA_TYPE, Capabilities, CapabilityFeatures,
62 CapabilityLimits, CapabilityProtocol, CcMetadata, DIGEST_LIST_MEDIA_TYPE, DIRECTORY_MEDIA_TYPE,
63 Digest as CacheDigest, DigestAlgorithm, Directory as CacheDirectory,
64 DirectoryNode as CacheDirectoryNode, FileNode as CacheFileNode, MAX_ACTION_PREDICTION_PAYLOAD,
65 MAX_ACTION_PROMISE_CLAIM_BYTES, NAMESPACE_HEADER, PROTOCOL_HEADER, PROTOCOL_VERSION,
66 RustcMetadata, SymlinkNode as CacheSymlinkNode, TASK_ACTION_MANIFEST_MEDIA_TYPE,
67 TaskActionManifest,
68};
69pub use path_mapping::{
70 PathMapping, PathNormalizationError, normalize_mapped_path, normalize_resolved_mapped_path,
71 resolve_path_mappings,
72};
73use remote_http::HttpRemoteCache;
74#[cfg(feature = "fuzzing")]
75#[doc(hidden)]
76pub use remote_http::fuzz_decode_blob_pack;
77pub(crate) use remote_http::{BlobPackLimits, blob_pack_chunk};
78use remote_s3::S3RemoteCache;
79pub use remote_s3::{S3ConditionalWrites, S3RemoteCacheConfig};
80pub use sigv4::S3Credentials;
81const MAX_REMOTE_JSON_BYTES: u64 = 16 * 1024 * 1024;
88const MAX_ETAG_BYTES: usize = 256;
93const MAX_REMOTE_BLOB_BYTES: u64 = 5 * 1024 * 1024 * 1024;
96const MAX_STAGED_BLOB_PACK_BYTES: u64 = 256 * 1024 * 1024;
97const MAX_STAGED_BLOB_PACK_ITEMS: usize = 2 * 1024;
98const BLOB_PACK_TIMEOUT_BYTES_PER_UNIT: u64 = MAX_STAGED_BLOB_PACK_BYTES / 4;
99const BLOB_PACK_TIMEOUT_ITEMS_PER_UNIT: usize = MAX_STAGED_BLOB_PACK_ITEMS / 4;
100const PACK_STREAM_CHUNK_BYTES: usize = 64 * 1024;
102const MAX_ACTION_BATCH_ITEMS: usize = 256;
108const MAX_ACTION_RESULT_BYTES: u64 = 64 * 1024;
110
111pub fn canonical_json(value: &impl Serialize) -> Result<Vec<u8>> {
116 Ok(mbx_cache_protocol::canonical_json(value)?)
117}
118
119#[derive(
120 Debug,
121 Clone,
122 Copy,
123 Serialize,
124 Deserialize,
125 Default,
126 strum::EnumString,
127 strum::Display,
128 PartialEq,
129 Eq,
130)]
131#[serde(rename_all = "kebab-case")]
132#[strum(serialize_all = "kebab-case")]
133pub enum RemoteCacheMode {
135 #[default]
137 ReadWrite,
138 ReadOnly,
140 WriteOnly,
142}
143
144impl RemoteCacheMode {
145 pub fn reads(self) -> bool {
147 matches!(self, Self::ReadWrite | Self::ReadOnly)
148 }
149
150 pub fn writes(self) -> bool {
152 matches!(self, Self::ReadWrite | Self::WriteOnly)
153 }
154}
155
156pub struct RemoteCacheConfig {
158 pub base_url: Url,
160 pub namespace: String,
162 pub token: Option<String>,
164 pub token_file: Option<PathBuf>,
166 pub oidc_audience: Option<String>,
168 pub connect_timeout: Duration,
170 pub read_timeout: Duration,
172 pub download_timeout: Duration,
181 pub retries: i64,
183}
184
185pub enum BlobSource {
187 Bytes(Vec<u8>),
189 File(tempfile::NamedTempFile),
191 Path(PathBuf),
193}
194
195pub struct BlobUpload {
197 pub digest: CacheDigest,
199 pub source: BlobSource,
201}
202
203pub struct RemoteActionManifest {
205 pub bytes: Vec<u8>,
207 pub etag: String,
209}
210
211pub struct RemoteBlobPack {
213 _directory: tempfile::TempDir,
214 pub blobs: Vec<(CacheDigest, PathBuf)>,
216 pub requests: u64,
218 pub requested: Vec<CacheDigest>,
220 pub blob_count: u64,
222 pub payload_bytes: u64,
224 pub framed_bytes: u64,
226}
227
228#[derive(Debug, Clone, Copy, Deserialize)]
230pub struct BlobPackReceipt {
231 #[serde(default)]
233 pub created: u64,
234 #[serde(default)]
236 pub existing: u64,
237}
238
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub enum ManifestPutOutcome {
242 Stored,
244 PreconditionFailed,
246}
247
248pub struct RemoteCacheClient {
258 backend: Backend,
259}
260
261enum Backend {
267 Http(HttpRemoteCache),
268 S3(S3RemoteCache),
269}
270
271impl RemoteCacheClient {
272 pub fn new(config: RemoteCacheConfig) -> Result<Self> {
274 Ok(Self {
275 backend: Backend::Http(HttpRemoteCache::new(config)?),
276 })
277 }
278
279 pub fn new_s3(config: S3RemoteCacheConfig) -> Result<Self> {
284 Ok(Self {
285 backend: Backend::S3(S3RemoteCache::new(config)?),
286 })
287 }
288
289 pub async fn check_connection(&self) -> Result<()> {
295 match &self.backend {
296 Backend::Http(client) => client.check_connection().await,
297 Backend::S3(store) => store.check_connection().await,
298 }
299 }
300
301 pub async fn get_blob_pack(
307 &self,
308 digests: &[CacheDigest],
309 staging_dir: &Path,
310 ) -> Result<Option<RemoteBlobPack>> {
311 match &self.backend {
312 Backend::Http(client) => client.get_blob_pack(digests, staging_dir).await,
313 Backend::S3(store) => store.get_blob_pack(digests, staging_dir).await,
314 }
315 }
316
317 pub(crate) async fn get_blob_pack_with_limit(
318 &self,
319 digests: &[CacheDigest],
320 staging_dir: &Path,
321 max_bytes: u64,
322 ) -> Result<Option<RemoteBlobPack>> {
323 match &self.backend {
324 Backend::Http(client) => {
325 client
326 .get_blob_pack_with_limit(digests, staging_dir, max_bytes)
327 .await
328 }
329 Backend::S3(store) => {
330 store
331 .get_blob_pack_with_limit(digests, staging_dir, max_bytes)
332 .await
333 }
334 }
335 }
336
337 pub async fn get_action_result(
339 &self,
340 action: &CacheDigest,
341 ) -> Result<Option<RemoteActionResult>> {
342 match &self.backend {
343 Backend::Http(client) => client.get_action_result(action).await,
344 Backend::S3(store) => store.get_action_result(action).await,
345 }
346 }
347
348 pub(crate) async fn action_batch_limit(&self) -> Result<Option<usize>> {
352 match &self.backend {
353 Backend::Http(client) => client.action_batch_limit().await,
354 Backend::S3(store) => store.action_batch_limit().await,
355 }
356 }
357
358 pub async fn get_action_results(
365 &self,
366 actions: &[CacheDigest],
367 ) -> Result<Option<Vec<RemoteActionResult>>> {
368 match &self.backend {
369 Backend::Http(client) => client.get_action_results(actions).await,
370 Backend::S3(store) => store.get_action_results(actions).await,
371 }
372 }
373
374 pub async fn put_action_result(&self, result: &RemoteActionResult) -> Result<()> {
376 match &self.backend {
377 Backend::Http(client) => client.put_action_result(result).await,
378 Backend::S3(store) => store.put_action_result(result).await,
379 }
380 }
381
382 pub async fn join_action_promise(
386 &self,
387 invocation: &CacheDigest,
388 adapter: &str,
389 ) -> Result<Option<ActionPromiseState>> {
390 match &self.backend {
391 Backend::Http(client) => client.join_action_promise(invocation, adapter).await,
392 Backend::S3(_) => Ok(None),
393 }
394 }
395
396 pub async fn complete_action_promise(
400 &self,
401 invocation: &CacheDigest,
402 completion: &ActionPromiseCompletion,
403 ) -> Result<bool> {
404 match &self.backend {
405 Backend::Http(client) => client.complete_action_promise(invocation, completion).await,
406 Backend::S3(_) => Ok(false),
407 }
408 }
409
410 pub async fn get_action_manifest(
412 &self,
413 key: &CacheDigest,
414 ) -> Result<Option<RemoteActionManifest>> {
415 match &self.backend {
416 Backend::Http(client) => client.get_action_manifest(key).await,
417 Backend::S3(store) => store.get_action_manifest(key).await,
418 }
419 }
420
421 pub async fn put_action_manifest(
423 &self,
424 key: &CacheDigest,
425 bytes: &[u8],
426 expected_etag: Option<&str>,
427 ) -> Result<ManifestPutOutcome> {
428 match &self.backend {
429 Backend::Http(client) => client.put_action_manifest(key, bytes, expected_etag).await,
430 Backend::S3(store) => store.put_action_manifest(key, bytes, expected_etag).await,
431 }
432 }
433
434 pub async fn get_blob(
436 &self,
437 digest: &CacheDigest,
438 media_type: &'static str,
439 ) -> Result<Vec<u8>> {
440 match &self.backend {
441 Backend::Http(client) => client.get_blob(digest, media_type).await,
442 Backend::S3(store) => store.get_blob(digest, media_type).await,
443 }
444 }
445
446 pub async fn get_blob_file(
448 &self,
449 digest: &CacheDigest,
450 staging_dir: &Path,
451 ) -> Result<tempfile::NamedTempFile> {
452 match &self.backend {
453 Backend::Http(client) => client.get_blob_file(digest, staging_dir).await,
454 Backend::S3(store) => store.get_blob_file(digest, staging_dir).await,
455 }
456 }
457
458 pub(crate) async fn blob_pack_upload_limits(&self) -> Result<Option<BlobPackLimits>> {
462 match &self.backend {
463 Backend::Http(client) => client.blob_pack_upload_limits().await,
464 Backend::S3(store) => store.blob_pack_upload_limits().await,
465 }
466 }
467
468 pub async fn put_blob_pack(&self, uploads: &[BlobUpload]) -> Result<Option<BlobPackReceipt>> {
476 match &self.backend {
477 Backend::Http(client) => client.put_blob_pack(uploads).await,
478 Backend::S3(store) => store.put_blob_pack(uploads).await,
479 }
480 }
481
482 pub async fn put_blob(&self, upload: &BlobUpload) -> Result<()> {
484 match &self.backend {
485 Backend::Http(client) => client.put_blob(upload).await,
486 Backend::S3(store) => store.put_blob(upload).await,
487 }
488 }
489}
490
491async fn read_bounded_json(response: reqwest::Response, what: &str) -> Result<Vec<u8>> {
497 read_json_within(response, what, MAX_REMOTE_JSON_BYTES).await
498}
499
500async fn read_json_within(response: reqwest::Response, what: &str, limit: u64) -> Result<Vec<u8>> {
501 if let Some(length) = response.content_length()
502 && length > limit
503 {
504 bail!("remote cache {what} declared {length} bytes, over the {limit} byte limit");
505 }
506 let mut response = response;
507 let mut bytes = Vec::new();
508 while let Some(chunk) = response.chunk().await? {
509 if bytes.len() as u64 + chunk.len() as u64 > limit {
510 bail!("remote cache {what} exceeded the {limit} byte limit");
511 }
512 bytes.extend_from_slice(&chunk);
513 }
514 Ok(bytes)
515}
516fn parse_strong_etag(value: Option<&HeaderValue>) -> Result<String> {
525 let value = value
526 .and_then(|value| value.to_str().ok())
527 .ok_or_else(|| eyre!("remote action manifest response is missing an ETag"))?;
528 if value.starts_with("W/") {
529 bail!("remote action manifest response has a weak ETag");
532 }
533 let etag = value
534 .strip_prefix('"')
535 .and_then(|value| value.strip_suffix('"'))
536 .filter(|value| is_entity_tag(value))
537 .ok_or_else(|| eyre!("remote action manifest response has an invalid ETag"))?;
538 Ok(etag.to_owned())
539}
540
541fn quoted_etag(etag: &str) -> Result<HeaderValue> {
542 if !is_entity_tag(etag) {
543 bail!("invalid remote action manifest ETag");
544 }
545 Ok(HeaderValue::from_str(&format!("\"{etag}\""))?)
546}
547
548fn is_entity_tag(value: &str) -> bool {
553 !value.is_empty()
554 && value.len() <= MAX_ETAG_BYTES
555 && value.bytes().all(|byte| matches!(byte, 0x21 | 0x23..=0x7e))
556}
557fn retry_delays(retries: i64) -> impl Iterator<Item = Duration> {
558 [200u64, 1_000, 4_000, 15_000]
559 .into_iter()
560 .chain(std::iter::repeat(15_000))
561 .map(Duration::from_millis)
562 .map(|duration| {
563 let factor = 0.5 + rand::random::<f64>() * 0.5;
564 Duration::from_secs_f64(duration.as_secs_f64() * factor)
565 })
566 .take(retries.max(0) as usize)
567}
568
569fn is_dns_error(error: &(dyn std::error::Error + 'static)) -> bool {
573 let mut current = Some(error);
574 while let Some(source) = current {
575 if source.to_string() == "dns error" {
576 return true;
577 }
578 current = source.source();
579 }
580 false
581}
582
583#[derive(Debug)]
590pub(crate) struct TransientRequest(pub(crate) &'static str);
591
592impl std::fmt::Display for TransientRequest {
593 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
594 formatter.write_str(self.0)
595 }
596}
597
598impl std::error::Error for TransientRequest {}
599
600fn is_transient(error: &eyre::Report) -> bool {
601 if is_dns_error(error.as_ref()) {
604 return false;
605 }
606 error.chain().any(|source| {
607 if source.downcast_ref::<TransientRequest>().is_some() {
608 return true;
609 }
610 let Some(error) = source.downcast_ref::<reqwest::Error>() else {
611 return false;
612 };
613 if error.is_timeout() || error.is_connect() || error.is_body() {
614 return true;
615 }
616 error.status().is_some_and(|status| {
617 let status = status.as_u16();
618 status == 408 || status == 429 || (500..600).contains(&status)
619 })
620 })
621}
622
623async fn retry_async<F, Fut, T>(verb: &str, url: &Url, retries: i64, mut operation: F) -> Result<T>
624where
625 F: FnMut() -> Fut,
626 Fut: std::future::Future<Output = Result<T>>,
627{
628 let mut delays = retry_delays(retries);
629 let mut attempt = 1;
630 loop {
631 let started_at = Instant::now();
632 match operation().await {
633 Ok(value) => return Ok(value),
634 Err(error) if is_transient(&error) => {
635 let Some(delay) = delays.next() else {
636 return Err(error);
637 };
638 warn!(
639 "HTTP {verb} {url} attempt {attempt} failed after {:?} (transient): {error}; retrying in {delay:?}",
640 started_at.elapsed()
641 );
642 tokio::time::sleep(delay).await;
643 attempt += 1;
644 }
645 Err(error) => return Err(error),
646 }
647 }
648}