Coverage Report

Created: 2026-11-27 22:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-store/src/filesystem_store.rs
Line
Count
Source
1
// Copyright 2024 Trace Machina, Inc. All rights reserved.
2
//
3
// Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//    See LICENSE file for details
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
use core::cmp;
16
use core::fmt::{Debug, Display, Formatter};
17
use core::pin::Pin;
18
use core::sync::atomic::{AtomicU64, Ordering};
19
use core::time::Duration;
20
use std::borrow::Cow;
21
#[cfg(unix)]
22
use std::collections::HashMap;
23
use std::ffi::{OsStr, OsString};
24
use std::sync::{Arc, Weak};
25
use std::time::SystemTime;
26
27
#[cfg(unix)]
28
use async_lock::Mutex;
29
use async_lock::RwLock;
30
use async_trait::async_trait;
31
use bytes::{Bytes, BytesMut};
32
use futures::stream::{StreamExt, TryStreamExt};
33
use futures::{Future, TryFutureExt};
34
use jiff::Timestamp;
35
use nativelink_config::stores::FilesystemSpec;
36
use nativelink_error::{Code, Error, ResultExt, make_err};
37
use nativelink_metric::MetricsComponent;
38
use nativelink_util::background_spawn;
39
use nativelink_util::buf_channel::{
40
    DropCloserReadHalf, DropCloserWriteHalf, make_buf_channel_pair,
41
};
42
use nativelink_util::common::{DigestInfo, fs};
43
use nativelink_util::evicting_map::{EvictingMap, EvictionSnapshot, LenEntry};
44
use nativelink_util::fs::FileSlot;
45
use nativelink_util::health_utils::{HealthRegistryBuilder, HealthStatus, HealthStatusIndicator};
46
#[cfg(unix)]
47
use nativelink_util::spawn_blocking;
48
#[cfg(unix)]
49
use nativelink_util::store_trait::RemoveItemCallback;
50
use nativelink_util::store_trait::{
51
    RemoveCallback, StoreDriver, StoreKey, StoreKeyBorrow, StoreOptimizations, UploadSizeInfo,
52
};
53
use tokio::io::{AsyncReadExt, AsyncWriteExt, Take};
54
use tokio::sync::Semaphore;
55
use tokio::time::timeout;
56
use tokio_stream::wrappers::ReadDirStream;
57
use tracing::{debug, error, info, trace, warn};
58
59
use crate::callback_utils::RemoveCallbackHolder;
60
use crate::cas_utils::is_zero_digest;
61
62
// Default size to allocate memory of the buffer when reading files.
63
const DEFAULT_BUFF_SIZE: usize = 32 * 1024;
64
// Default block size of all major filesystems is 4KB
65
const DEFAULT_BLOCK_SIZE: u64 = 4 * 1024;
66
67
pub const STR_FOLDER_V1: &str = "s";
68
pub const DIGEST_FOLDER_V1: &str = "d";
69
70
pub const STR_FOLDER_V2: &str = "s2";
71
pub const DIGEST_FOLDER_V2: &str = "d2";
72
73
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74
enum Version {
75
    Flat,
76
    V1,
77
    V2,
78
}
79
80
/// Suffix for the sibling directory that holds per-digest read-only
81
/// **executable** (0o555) variants of CAS blobs (see
82
/// [`FilesystemStore::get_executable_hardlink_source`]). It is a sibling of
83
/// `content_path` rather than a child so the normal content/temp scan and prune
84
/// logic never touches it. Cleared on writable startup; entries are
85
/// regenerable. If the wipe is blocked by a read-only filesystem, executable
86
/// variants are disabled so surviving files are never trusted.
87
#[cfg(unix)]
88
const EXECUTABLE_DIR_SUFFIX: &str = ".exec";
89
90
const MAX_CONCURRENT_VARIANT_LOOKUPS: usize = 32;
91
92
#[derive(Clone, Copy, Debug)]
93
pub enum FileType {
94
    Digest,
95
    String,
96
}
97
98
#[derive(Debug, MetricsComponent)]
99
pub struct SharedContext {
100
    // Used in testing to know how many active drop() spawns are running.
101
    // TODO(palfrey) It is probably a good idea to use a spin lock during
102
    // destruction of the store to ensure that all files are actually
103
    // deleted (similar to how it is done in tests).
104
    #[metric(help = "Number of active drop spawns")]
105
    pub active_drop_spawns: AtomicU64,
106
    #[metric(help = "Path to the configured temp path")]
107
    temp_path: String,
108
    #[metric(help = "Path to the configured content path")]
109
    content_path: String,
110
}
111
112
#[derive(Eq, PartialEq, Debug)]
113
enum PathType {
114
    Content,
115
    Temp,
116
    Custom(OsString),
117
}
118
119
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
120
pub struct Generation(u64);
121
122
impl Generation {
123
4.32k
    pub const fn new(generation: u64) -> Self {
124
4.32k
        Self(generation)
125
4.32k
    }
126
127
1.52k
    pub const fn inner(&self) -> u64 {
128
1.52k
        self.0
129
1.52k
    }
130
}
131
132
impl Display for Generation {
133
10.9k
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
134
10.9k
        write!(f, "{}", self.0)
135
10.9k
    }
136
}
137
138
/// [`EncodedFilePath`] stores the path to the file
139
/// including the context, path type and key to the file.
140
/// The whole [`StoreKey`] is stored as opposed to solely
141
/// the [`DigestInfo`] so that it is more usable for things
142
/// such as BEP -see Issue #1108
143
#[derive(Debug)]
144
pub struct EncodedFilePath {
145
    shared_context: Arc<SharedContext>,
146
    path_type: PathType,
147
    key: StoreKey<'static>,
148
    generation: Generation,
149
    version: Version,
150
}
151
152
impl EncodedFilePath {
153
    #[inline]
154
9.13k
    fn get_file_path(&self) -> Cow<'_, OsStr> {
155
9.13k
        get_file_path_raw(
156
9.13k
            &self.path_type,
157
9.13k
            self.shared_context.as_ref(),
158
9.13k
            &self.key,
159
9.13k
            self.generation,
160
9.13k
            self.version,
161
        )
162
9.13k
    }
163
}
164
165
#[inline]
166
11.4k
fn get_file_path_raw<'a>(
167
11.4k
    path_type: &'a PathType,
168
11.4k
    shared_context: &SharedContext,
169
11.4k
    key: &StoreKey<'a>,
170
11.4k
    generation: Generation,
171
11.4k
    version: Version,
172
11.4k
) -> Cow<'a, OsStr> {
173
11.4k
    let 
folder10.9k
= match path_type {
174
4.62k
        PathType::Content => &shared_context.content_path,
175
6.29k
        PathType::Temp => &shared_context.temp_path,
176
550
        PathType::Custom(path) => return Cow::Borrowed(path),
177
    };
178
10.9k
    Cow::Owned(to_full_path_from_key(folder, key, generation, version))
179
11.4k
}
180
181
impl Drop for EncodedFilePath {
182
2.59k
    fn drop(&mut self) {
183
        // `drop()` can be called during shutdown, so we use `path_type` flag to know if the
184
        // file actually needs to be deleted.
185
2.59k
        if self.path_type == PathType::Content {
186
2.52k
            return;
187
74
        }
188
189
74
        let file_path = self.get_file_path().to_os_string();
190
74
        let shared_context = self.shared_context.clone();
191
        // .fetch_add returns previous value, so we add one to get approximate current value
192
74
        let current_active_drop_spawns = shared_context
193
74
            .active_drop_spawns
194
74
            .fetch_add(1, Ordering::Relaxed)
195
74
            + 1;
196
74
        debug!(
197
            %current_active_drop_spawns,
198
            ?file_path,
199
            "Spawned a filesystem_delete_file"
200
        );
201
74
        background_spawn!("filesystem_delete_file", async move 
{67
202
67
            match fs::remove_file(&file_path).await {
203
46
                Ok(()) => debug!(?file_path, "File deleted"),
204
                // The file already being gone is the desired end state of a
205
                // delete, not a failure — e.g. an entry marked Temp after an
206
                // already-gone unref points at a path that was never created.
207
5
                Err(err) if err.code == Code::NotFound => {
208
5
                    debug!(?file_path, "File already gone, nothing to delete");
209
                }
210
0
                Err(err) => error!(?file_path, ?err, "Failed to delete file"),
211
            }
212
            // .fetch_sub returns previous value, so we subtract one to get approximate current value
213
51
            let current_active_drop_spawns = shared_context
214
51
                .active_drop_spawns
215
51
                .fetch_sub(1, Ordering::Relaxed)
216
51
                - 1;
217
51
            debug!(
218
                ?current_active_drop_spawns,
219
                ?file_path,
220
                "Dropped a filesystem_delete_file"
221
            );
222
51
        });
223
2.59k
    }
224
}
225
226
/// This creates the file path from the [`StoreKey`]. If
227
/// it is a string, the string, prefixed with [`STR_PREFIX`]
228
/// for backwards compatibility, is stored.
229
///
230
/// If it is a [`DigestInfo`], it is prefixed by [`DIGEST_PREFIX`]
231
/// followed by the string representation of a digest - the hash in hex,
232
/// a hyphen then the size in bytes
233
///
234
/// Previously, only the string representation of the [`DigestInfo`] was
235
/// used with no prefix
236
#[inline]
237
10.9k
fn to_full_path_from_key(
238
10.9k
    folder: &str,
239
10.9k
    key: &StoreKey<'_>,
240
10.9k
    generation: Generation,
241
10.9k
    version: Version,
242
10.9k
) -> OsString {
243
10.9k
    match (key, version) {
244
1
        (StoreKey::Digest(digest_info), Version::Flat) => format!("{folder}/{digest_info}"),
245
0
        (StoreKey::Str(str), Version::Flat) => format!("{folder}/{str}"),
246
73
        (StoreKey::Str(str), Version::V2) => {
247
73
            format!("{folder}/{STR_FOLDER_V2}/{str}-{generation}")
248
        }
249
3
        (StoreKey::Str(str), Version::V1) => format!("{folder}/{STR_FOLDER_V1}/{str}"),
250
10.8k
        (StoreKey::Digest(digest_info), Version::V2) => {
251
10.8k
            format!("{folder}/{DIGEST_FOLDER_V2}/{digest_info}-{generation}")
252
        }
253
0
        (StoreKey::Digest(digest_info), Version::V1) => {
254
0
            format!("{folder}/{DIGEST_FOLDER_V1}/{digest_info}")
255
        }
256
    }
257
10.9k
    .into()
258
10.9k
}
259
260
pub trait FileEntry: LenEntry + Send + Sync + Debug + 'static {
261
    /// Responsible for creating the underlying `FileEntry`.
262
    fn create(
263
        data_size: u64,
264
        block_size: u64,
265
        generation: Generation,
266
        encoded_file_path: RwLock<EncodedFilePath>,
267
    ) -> Self;
268
269
    /// Creates a (usually) temp file, opens it and returns the path to the temp file.
270
    fn make_and_open_file(
271
        block_size: u64,
272
        generation: Generation,
273
        encoded_file_path: EncodedFilePath,
274
    ) -> impl Future<Output = Result<(Self, FileSlot, OsString), Error>> + Send
275
    where
276
        Self: Sized;
277
278
    /// Returns the file generation.
279
    fn generation(&self) -> Generation;
280
281
    /// Returns the underlying size of the data in bytes
282
    fn data_size(&self) -> u64;
283
284
    /// Returns the underlying reference to the size of the data in bytes
285
    fn data_size_mut(&mut self) -> &mut u64;
286
287
    /// Returns the actual size of the underlying file on the disk after accounting for filesystem block size.
288
    fn size_on_disk(&self) -> u64;
289
290
    /// Gets the underlying `EncodedfilePath`.
291
    fn get_encoded_file_path(&self) -> &RwLock<EncodedFilePath>;
292
293
    /// Returns a reader that will read part of the underlying file.
294
    fn read_file_part(
295
        &self,
296
        offset: u64,
297
        length: u64,
298
    ) -> impl Future<Output = Result<Take<FileSlot>, Error>> + Send;
299
300
    /// This function is a safe way to extract the file name of the underlying file. To protect users from
301
    /// accidentally creating undefined behavior we encourage users to do the logic they need to do with
302
    /// the filename inside this function instead of extracting the filename and doing the logic outside.
303
    /// This is because the filename is not guaranteed to exist after this function returns, however inside
304
    /// the callback the file is always guaranteed to exist and immutable.
305
    /// DO NOT USE THIS FUNCTION TO EXTRACT THE FILENAME AND STORE IT FOR LATER USE.
306
    fn get_file_path_locked<
307
        T,
308
        Fut: Future<Output = Result<T, Error>> + Send,
309
        F: FnOnce(OsString) -> Fut + Send,
310
    >(
311
        &self,
312
        handler: F,
313
    ) -> impl Future<Output = Result<T, Error>> + Send;
314
}
315
316
pub struct FileEntryImpl {
317
    data_size: u64,
318
    block_size: u64,
319
    // We lock around this as it gets rewritten when we move between temp and content types
320
    encoded_file_path: RwLock<EncodedFilePath>,
321
    generation: Generation,
322
}
323
324
impl FileEntryImpl {
325
0
    pub fn get_shared_context_for_test(&mut self) -> Arc<SharedContext> {
326
0
        self.encoded_file_path.get_mut().shared_context.clone()
327
0
    }
328
}
329
330
impl FileEntry for FileEntryImpl {
331
2.59k
    fn create(
332
2.59k
        data_size: u64,
333
2.59k
        block_size: u64,
334
2.59k
        generation: Generation,
335
2.59k
        encoded_file_path: RwLock<EncodedFilePath>,
336
2.59k
    ) -> Self {
337
2.59k
        Self {
338
2.59k
            data_size,
339
2.59k
            block_size,
340
2.59k
            encoded_file_path,
341
2.59k
            generation,
342
2.59k
        }
343
2.59k
    }
344
345
    /// This encapsulates the logic for the edge case of if the file fails to create
346
    /// the cleanup of the file is handled without creating a `FileEntry`, which would
347
    /// try to cleanup the file as well during `drop()`.
348
2.08k
    async fn make_and_open_file(
349
2.08k
        block_size: u64,
350
2.08k
        generation: Generation,
351
2.08k
        encoded_file_path: EncodedFilePath,
352
2.08k
    ) -> Result<(Self, FileSlot, OsString), Error> {
353
2.08k
        let temp_full_path = encoded_file_path.get_file_path().to_os_string();
354
2.08k
        let 
temp_file_result2.08k
= fs::create_file(temp_full_path.clone())
355
2.08k
            .or_else(|mut err| async 
{0
356
0
                let remove_result = fs::remove_file(&temp_full_path).await.err_tip(|| {
357
0
                    format!(
358
                        "Failed to remove file {} in filesystem store",
359
0
                        temp_full_path.display()
360
                    )
361
0
                });
362
0
                if let Err(remove_err) = remove_result {
363
0
                    err = err.merge(remove_err);
364
0
                }
365
0
                warn!(?err, ?block_size, ?temp_full_path, "Failed to create file",);
366
0
                Err(err).err_tip(|| {
367
0
                    format!(
368
                        "Failed to create {} in filesystem store",
369
0
                        temp_full_path.display()
370
                    )
371
0
                })
372
0
            })
373
2.08k
            .await
?0
;
374
375
2.08k
        Ok((
376
2.08k
            <Self as FileEntry>::create(
377
2.08k
                0, /* Unknown yet, we will fill it in later */
378
2.08k
                block_size,
379
2.08k
                generation,
380
2.08k
                RwLock::new(encoded_file_path),
381
2.08k
            ),
382
2.08k
            temp_file_result,
383
2.08k
            temp_full_path,
384
2.08k
        ))
385
2.08k
    }
386
387
97
    fn data_size(&self) -> u64 {
388
97
        self.data_size
389
97
    }
390
391
26
    fn generation(&self) -> Generation {
392
26
        self.generation
393
26
    }
394
395
2.07k
    fn data_size_mut(&mut self) -> &mut u64 {
396
2.07k
        &mut self.data_size
397
2.07k
    }
398
399
5.35k
    fn size_on_disk(&self) -> u64 {
400
5.35k
        self.data_size.div_ceil(self.block_size) * self.block_size
401
5.35k
    }
402
403
6.92k
    fn get_encoded_file_path(&self) -> &RwLock<EncodedFilePath> {
404
6.92k
        &self.encoded_file_path
405
6.92k
    }
406
407
804
    fn read_file_part(
408
804
        &self,
409
804
        offset: u64,
410
804
        length: u64,
411
804
    ) -> impl Future<Output = Result<Take<FileSlot>, Error>> + Send {
412
804
        self.get_file_path_locked(move |full_content_path| async move {
413
804
            let 
file799
= fs::open_file(&full_content_path, offset, length)
414
804
                .await
415
804
                .err_tip(|| 
{5
416
5
                    format!(
417
                        "Failed to open file in filesystem store {}",
418
5
                        full_content_path.display()
419
                    )
420
5
                })?;
421
799
            Ok(file)
422
1.60k
        })
423
804
    }
424
425
2.20k
    async fn get_file_path_locked<
426
2.20k
        T,
427
2.20k
        Fut: Future<Output = Result<T, Error>> + Send,
428
2.20k
        F: FnOnce(OsString) -> Fut + Send,
429
2.20k
    >(
430
2.20k
        &self,
431
2.20k
        handler: F,
432
2.20k
    ) -> Result<T, Error> {
433
2.20k
        let encoded_file_path = self.get_encoded_file_path().read().await;
434
2.20k
        handler(encoded_file_path.get_file_path().to_os_string()).await
435
2.20k
    }
436
}
437
438
impl Debug for FileEntryImpl {
439
0
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
440
0
        f.debug_struct("FileEntryImpl")
441
0
            .field("data_size", &self.data_size)
442
0
            .field("encoded_file_path", &"<behind mutex>")
443
0
            .finish()
444
0
    }
445
}
446
447
2.16k
fn make_temp_digest(mut digest: DigestInfo) -> DigestInfo {
448
    static DELETE_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
449
2.16k
    let mut hash = *digest.packed_hash();
450
2.16k
    hash[24..].clone_from_slice(
451
2.16k
        &DELETE_FILE_COUNTER
452
2.16k
            .fetch_add(1, Ordering::Relaxed)
453
2.16k
            .to_le_bytes(),
454
    );
455
2.16k
    digest.set_packed_hash(*hash);
456
2.16k
    digest
457
2.16k
}
458
459
2.16k
pub fn make_temp_key(key: &StoreKey) -> StoreKey<'static> {
460
2.16k
    StoreKey::Digest(make_temp_digest(key.borrow().into_digest()))
461
2.16k
}
462
463
/// Group-commit flush coalescer (macOS only).
464
///
465
/// On macOS, `File::sync_all` issues `fcntl(F_FULLFSYNC)` — a full
466
/// device-cache flush — once per call. The flush is serialized at the
467
/// device, costs multiple milliseconds, and dominates uploads of many
468
/// small blobs (a 4,400-tiny-file action input tree spends ~12s of its
469
/// ~14.5s materialization in these flushes). Linux does not have this
470
/// problem because concurrent `fsync` calls coalesce inside the
471
/// filesystem journal's group commit.
472
///
473
/// This applies the same group-commit idea in userspace, exploiting an
474
/// asymmetry in `F_FULLFSYNC`: writing a file's pages to the storage
475
/// device is per-file work (plain `fsync(2)`, cheap), while the expensive
476
/// device-cache drain is device-wide by nature. Each writer first pushes
477
/// its own data to the device with `fsync(2)`, then joins the current
478
/// commit round; a single long-lived flusher task per DEVICE issues one
479
/// `F_FULLFSYNC` (on a dedicated sentinel file) per round, covering every
480
/// previously-`fsync`ed blob at once. Rounds self-batch exactly like a
481
/// journal: while one flush is running, later writers accumulate into
482
/// the next round.
483
///
484
/// The coalescer (and its flusher task) is per store instance. Sharing
485
/// one coalescer across all stores on a device would amortize further —
486
/// the flush is device-wide — but a process-global flusher task cannot
487
/// safely outlive the tokio runtime that spawned it (multiple runtimes
488
/// coexist in one process, e.g. one per test); doing this correctly
489
/// needs a runtime-agnostic flusher (a dedicated OS thread) and is left
490
/// as a follow-up.
491
///
492
/// Durability is identical to per-file `F_FULLFSYNC`: a writer only
493
/// proceeds (and only renames its blob into the content directory) after
494
/// a device-cache flush that started after its own `fsync(2)` completed.
495
#[cfg(target_os = "macos")]
496
#[derive(Debug)]
497
struct FlushCoalescer {
498
    /// The round currently accepting waiters. Swapped out by the flusher
499
    /// right before it flushes, so writers whose `fsync(2)` finished
500
    /// after the flush began land in the next round.
501
    current_round: parking_lot::Mutex<Arc<FlushRound>>,
502
    /// Wakes the flusher task. Writers notify after subscribing to their
503
    /// round, so a wakeup can never be observed before its waiter.
504
    wake: Arc<tokio::sync::Notify>,
505
    /// Dedicated file the `F_FULLFSYNC` is issued on. A SIBLING of the
506
    /// store's content path (like the `.exec` variant directory), so
507
    /// neither the startup scan nor `move_old_cache`'s legacy root sweep
508
    /// ever sees it.
509
    sentinel: Arc<std::fs::File>,
510
    /// Number of device-wide barriers issued. Kept separately from the
511
    /// per-file `fsync(2)` count so tests can pin the coalescing invariant.
512
    full_flush_count: Arc<AtomicU64>,
513
}
514
515
#[cfg(target_os = "macos")]
516
#[derive(Debug)]
517
struct FlushRound {
518
    /// Broadcasts the flush outcome to every writer in the round.
519
    result_tx: tokio::sync::watch::Sender<Option<Result<(), Error>>>,
520
}
521
522
#[cfg(target_os = "macos")]
523
impl FlushRound {
524
    fn new() -> Arc<Self> {
525
        let (result_tx, _) = tokio::sync::watch::channel(None);
526
        Arc::new(Self { result_tx })
527
    }
528
}
529
530
/// Guarantees a [`FlushRound`]'s waiters always receive a result: if the
531
/// flusher task is cancelled at an await point (runtime shutdown), waiters
532
/// must get an error rather than pend forever — their own `Arc<FlushRound>`
533
/// keeps the channel alive, so a dropped-sender wakeup can never happen.
534
#[cfg(target_os = "macos")]
535
struct SendOnDrop(Option<Arc<FlushRound>>);
536
537
#[cfg(target_os = "macos")]
538
impl SendOnDrop {
539
    fn finish(mut self, result: Result<(), Error>) {
540
        if let Some(round) = self.0.take() {
541
            // Ignore send errors: every waiter may have been cancelled.
542
            drop(round.result_tx.send(Some(result)));
543
        }
544
    }
545
}
546
547
#[cfg(target_os = "macos")]
548
impl Drop for SendOnDrop {
549
    fn drop(&mut self) {
550
        if let Some(round) = self.0.take() {
551
            drop(round.result_tx.send(Some(Err(make_err!(
552
                Code::Internal,
553
                "Flush coalescer round task cancelled before completing"
554
            )))));
555
        }
556
    }
557
}
558
559
#[cfg(target_os = "macos")]
560
impl Drop for FlushCoalescer {
561
    fn drop(&mut self) {
562
        // Wake the flusher so it observes the dead Weak and exits instead
563
        // of parking forever.
564
        self.wake.notify_one();
565
    }
566
}
567
568
#[cfg(target_os = "macos")]
569
impl FlushCoalescer {
570
    /// Creates the coalescer for a store and spawns its flusher task on
571
    /// the current runtime (the same runtime the store's uploads run on).
572
    async fn for_content_path(content_path: &str) -> Result<Arc<Self>, Error> {
573
        // Sibling of `content_path` (never inside it): the startup scan
574
        // and `move_old_cache` sweep everything under the content root.
575
        let sentinel_path = format!("{content_path}.flush_sentinel");
576
        let sentinel = spawn_blocking!("filesystem_store_flush_sentinel_open", move || {
577
            std::fs::OpenOptions::new()
578
                .write(true)
579
                .create(true)
580
                .truncate(false)
581
                .open(&sentinel_path)
582
                .map_err(|e| {
583
                    make_err!(
584
                        Code::Internal,
585
                        "Failed to create flush sentinel {sentinel_path}: {e:?}"
586
                    )
587
                })
588
        })
589
        .await
590
        .err_tip(|| "Failed to join flush sentinel open task")??;
591
592
        let coalescer = Arc::new(Self {
593
            current_round: parking_lot::Mutex::new(FlushRound::new()),
594
            wake: Arc::new(tokio::sync::Notify::new()),
595
            sentinel: Arc::new(sentinel),
596
            full_flush_count: Arc::new(AtomicU64::new(0)),
597
        });
598
599
        let weak = Arc::downgrade(&coalescer);
600
        let wake = coalescer.wake.clone();
601
        background_spawn!("filesystem_store_flush_coalescer", async move {
602
            loop {
603
                wake.notified().await;
604
                let Some(coalescer) = weak.upgrade() else {
605
                    return;
606
                };
607
                coalescer.flush_one_round().await;
608
                // Drop the strong ref before parking so the store can be
609
                // torn down while the flusher is idle.
610
            }
611
        });
612
        Ok(coalescer)
613
    }
614
615
    /// Waits until a device-cache flush that started after this call has
616
    /// completed. Callers must have already `fsync(2)`ed their own file.
617
    async fn commit(&self) -> Result<(), Error> {
618
        let round = self.current_round.lock().clone();
619
        let mut result_rx = round.result_tx.subscribe();
620
        // Notify strictly after subscribing: the flusher skips rounds
621
        // with no receivers, so this ordering makes lost wakeups
622
        // impossible (a permit is stored even while the flusher is busy).
623
        self.wake.notify_one();
624
        let result_ref = result_rx
625
            .wait_for(Option::is_some)
626
            .await
627
            .map_err(|_| make_err!(Code::Internal, "Flush coalescer round dropped"))?;
628
        result_ref
629
            .clone()
630
            .unwrap_or_else(|| Err(make_err!(Code::Internal, "Flush round result missing")))
631
    }
632
633
    async fn flush_one_round(&self) {
634
        let round = self.current_round.lock().clone();
635
        if round.result_tx.receiver_count() == 0 {
636
            // Spurious wakeup (e.g. a permit left over from a round that
637
            // a previous iteration already served).
638
            return;
639
        }
640
        let send_guard = SendOnDrop(Some(round.clone()));
641
642
        // Brief accumulation window, only when this round actually has
643
        // multiple waiters: lets a burst pack more writers into the round
644
        // before it closes, trading ~3ms of publish latency (about the
645
        // cost of one device flush) for fewer device flushes. A solo
646
        // writer on an idle store skips it and pays only its own flush.
647
        if round.result_tx.receiver_count() > 1 {
648
            tokio::time::sleep(Duration::from_millis(3)).await;
649
        }
650
        // Close the round: writers arriving from here on cannot assume
651
        // this flush covers them, so they must get a fresh round.
652
        {
653
            let mut current = self.current_round.lock();
654
            if Arc::ptr_eq(&*current, &round) {
655
                *current = FlushRound::new();
656
            }
657
        }
658
        let sentinel = self.sentinel.clone();
659
        let full_flush_count = self.full_flush_count.clone();
660
        let flush_result = spawn_blocking!("filesystem_store_full_flush", move || {
661
            use std::os::fd::AsRawFd;
662
            use std::os::unix::fs::FileExt;
663
            // Keep the sentinel dirty so the flush is never a no-op.
664
            // Best-effort: a failed write (e.g. ENOSPC on a full CoW
665
            // volume) must not fail the whole round — the fcntl below is
666
            // what provides the device-cache drain.
667
            if let Err(err) = sentinel.write_at(b"f", 0) {
668
                warn!(?err, "Flush sentinel write failed; issuing flush anyway");
669
            }
670
            // Count the actual blocking operation, rather than merely counting
671
            // rounds scheduled by the async task.
672
            full_flush_count.fetch_add(1, Ordering::Relaxed);
673
            loop {
674
                if unsafe { libc::fcntl(sentinel.as_raw_fd(), libc::F_FULLFSYNC) } != -1 {
675
                    return Ok(());
676
                }
677
                let err = std::io::Error::last_os_error();
678
                // std's sync_all retries EINTR (cvt_r); match it.
679
                if err.kind() != std::io::ErrorKind::Interrupted {
680
                    return Err(Error::from(err).append("F_FULLFSYNC failed in flush coalescer"));
681
                }
682
            }
683
        })
684
        .await
685
        .unwrap_or_else(|e| {
686
            Err(Error::from_std_err(Code::Internal, &e).append("Flush coalescer task failed"))
687
        });
688
        send_guard.finish(flush_result);
689
    }
690
}
691
692
#[cfg(unix)]
693
214
async fn prepare_executable_dir(content_path: &str) -> Result<bool, Error> {
694
1
    fn is_non_writable_error(err: &std::io::Error) -> bool {
695
0
        matches!(
696
1
            err.kind(),
697
            std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::ReadOnlyFilesystem
698
        )
699
1
    }
700
701
214
    let executable_dir = format!("{content_path}{EXECUTABLE_DIR_SUFFIX}");
702
214
    let executable_digest_dir = format!("{executable_dir}/{DIGEST_FOLDER_V2}");
703
214
    spawn_blocking!("filesystem_store_prepare_executable_dir", move || {
704
214
        match std::fs::remove_dir_all(&executable_dir) {
705
7
            Ok(()) => {}
706
207
            Err(
err206
) if err.kind() == std::io::ErrorKind::NotFoun
d206
=>
{}206
707
            // A read-only cache must remain available for ordinary reads. Do
708
            // not reuse the directory, though: a surviving executable variant
709
            // may be stale or torn after an unclean shutdown.
710
1
            Err(err) if is_non_writable_error(&err) => return Ok(false),
711
0
            Err(err) => {
712
0
                return Err(Error::from(err)
713
0
                    .append(format!("Failed to clear executable dir {executable_dir}")));
714
            }
715
        }
716
717
213
        match std::fs::create_dir_all(&executable_digest_dir) {
718
213
            Ok(()) => Ok(true),
719
0
            Err(err) if is_non_writable_error(&err) => Ok(false),
720
0
            Err(err) => Err(Error::from(err).append(format!(
721
0
                "Failed to create executable dir {executable_digest_dir}"
722
0
            ))),
723
        }
724
214
    })
725
214
    .await
726
214
    .err_tip(|| "Failed to join executable-dir preparation task")
?0
727
214
}
728
729
impl LenEntry for FileEntryImpl {
730
    #[inline]
731
5.35k
    fn len(&self) -> u64 {
732
5.35k
        self.size_on_disk()
733
5.35k
    }
734
735
    /// The file's actual length; `len()` is rounded up to whole blocks.
736
    #[inline]
737
1.07k
    fn content_len(&self) -> u64 {
738
1.07k
        self.data_size
739
1.07k
    }
740
741
0
    fn is_empty(&self) -> bool {
742
0
        self.data_size == 0
743
0
    }
744
745
    // unref() only triggers when an item is removed from the eviction_map. It is possible
746
    // that another place in code has a reference to `FileEntryImpl` and may later read the
747
    // file. To support this edge case, we first move the file to a temp file and point
748
    // target file location to the new temp file. `unref()` should only ever be called once.
749
    #[inline]
750
54
    async fn unref(&self) {
751
54
        let mut encoded_file_path = self.encoded_file_path.write().await;
752
54
        if encoded_file_path.path_type == PathType::Temp {
753
            // We are already a temp file that is now marked for deletion on drop.
754
            // This is very rare, but most likely the rename into the content path failed.
755
1
            warn!(
756
1
                key = ?encoded_file_path.key,
757
                "File is already a temp file",
758
            );
759
1
            return;
760
53
        }
761
53
        let from_path = encoded_file_path.get_file_path();
762
53
        let new_key = make_temp_key(&encoded_file_path.key);
763
764
53
        let to_path = to_full_path_from_key(
765
53
            &encoded_file_path.shared_context.temp_path,
766
53
            &new_key,
767
53
            encoded_file_path.generation,
768
            // Legacy files may survive a failed migration, but only the new
769
            // temporary directories are guaranteed to exist on this startup.
770
53
            Version::V2,
771
        );
772
773
53
        if let Err(
err10
) = fs::rename(&from_path, &to_path).await {
774
            // ENOENT from rename is ambiguous: the source may be gone, or
775
            // a directory component of the destination (the temp dir) may
776
            // be missing. Confirm the source is genuinely gone before
777
            // treating it as benign — otherwise a removed temp dir would
778
            // flip an intact content file to Temp and orphan it on disk.
779
10
            let source_gone = err.code == Code::NotFound
780
9
                && matches!(
781
10
                    fs::metadata(&from_path).await,
782
9
                    Err(meta_err) if meta_err.code == Code::NotFound
783
                );
784
10
            if source_gone {
785
                // The file is already gone — typically another thread's
786
                // eviction beat us, or the entry never got its file on
787
                // disk. Benign here, and it dominates log volume under
788
                // heavy write+evict concurrency, so keep it at `debug`.
789
                // Mark the entry Temp (as a successful rename would) so a
790
                // repeat unref is a no-op and drop stops claiming the
791
                // content path.
792
9
                debug!(
793
9
                    key = ?encoded_file_path.key,
794
                    "Failed to rename file (already gone, treating as benign)",
795
                );
796
9
                encoded_file_path.path_type = PathType::Temp;
797
9
                encoded_file_path.key = new_key;
798
9
                encoded_file_path.version = Version::V2;
799
            } else {
800
                // Either a non-ENOENT failure (EACCES, EXDEV, EBUSY, …) or
801
                // ENOENT with the source still present (missing temp dir).
802
                // The content file is intact; leave the entry as Content.
803
1
                warn!(
804
1
                    key = ?encoded_file_path.key,
805
                    ?from_path,
806
                    ?to_path,
807
                    ?err,
808
                    "Failed to rename file",
809
                );
810
            }
811
        } else {
812
42
            debug!(
813
42
                key = ?encoded_file_path.key,
814
                ?from_path,
815
                ?to_path,
816
                "Renamed file (unref)",
817
            );
818
42
            encoded_file_path.path_type = PathType::Temp;
819
42
            encoded_file_path.key = new_key;
820
42
            encoded_file_path.version = Version::V2;
821
        }
822
53
    }
823
}
824
825
#[inline]
826
412
fn digest_from_filename(file_name: &str) -> Result<DigestInfo, Error> {
827
412
    let (hash, size) = file_name.split_once('-').err_tip(|| "")
?0
;
828
412
    let size = size.parse::<i64>()
?0
;
829
412
    DigestInfo::try_new(hash, size)
830
412
}
831
832
3
fn key_from_file_v1(file_name: &str, file_type: FileType) -> Result<StoreKey<'_>, Error> {
833
3
    match file_type {
834
2
        FileType::String => Ok(StoreKey::new_str(file_name)),
835
1
        FileType::Digest => digest_from_filename(file_name).map(StoreKey::Digest),
836
    }
837
3
}
838
839
459
pub fn key_and_generation_from_file_v2(
840
459
    file_name: &str,
841
459
    file_type: FileType,
842
459
) -> Result<(StoreKey<'_>, Generation), Error> {
843
459
    let (key, generation) = file_name.rsplit_once('-').err_tip(|| "")
?0
;
844
459
    let generation = Generation::new(generation.parse::<u64>()
?0
);
845
846
459
    let key = match file_type {
847
48
        FileType::String => StoreKey::new_str(key),
848
411
        FileType::Digest => digest_from_filename(key).map(StoreKey::Digest)
?0
,
849
    };
850
851
459
    Ok((key, generation))
852
459
}
853
854
/// The number of files to read the metadata for at the same time when running
855
/// `add_files_to_cache`.
856
const SIMULTANEOUS_METADATA_READS: usize = 200;
857
858
type FsEvictingMap<'a, Fe> =
859
    EvictingMap<StoreKeyBorrow, StoreKey<'a>, Arc<Fe>, SystemTime, RemoveCallbackHolder>;
860
861
214
async fn add_files_to_cache<Fe: FileEntry>(
862
214
    evicting_map: &FsEvictingMap<'_, Fe>,
863
214
    anchor_time: &SystemTime,
864
214
    shared_context: &Arc<SharedContext>,
865
214
    block_size: u64,
866
214
    rename_fn: fn(&OsStr, &OsStr) -> Result<(), std::io::Error>,
867
214
    migrate: bool,
868
214
) -> Result<Generation, Error> {
869
    #[expect(clippy::too_many_arguments)]
870
237
    async fn process_entry<Fe: FileEntry>(
871
237
        evicting_map: &FsEvictingMap<'_, Fe>,
872
237
        file_name: &str,
873
237
        file_type: FileType,
874
237
        version: Version,
875
237
        atime: SystemTime,
876
237
        data_size: u64,
877
237
        block_size: u64,
878
237
        anchor_time: &SystemTime,
879
237
        shared_context: &Arc<SharedContext>,
880
237
    ) -> Result<Generation, Error> {
881
237
        let (key, generation) = match version {
882
            Version::Flat | Version::V1 => {
883
3
                (key_from_file_v1(file_name, file_type)
?0
, Generation::new(0))
884
            }
885
234
            Version::V2 => key_and_generation_from_file_v2(file_name, file_type)
?0
,
886
        };
887
888
237
        let file_entry = Arc::new(Fe::create(
889
237
            data_size,
890
237
            block_size,
891
237
            generation,
892
237
            RwLock::new(EncodedFilePath {
893
237
                shared_context: shared_context.clone(),
894
237
                path_type: PathType::Content,
895
237
                key: key.borrow().into_owned(),
896
237
                generation,
897
237
                version,
898
237
            }),
899
        ));
900
237
        let time_since_anchor = if let Ok(
d236
) = anchor_time.duration_since(atime) {
901
236
            d
902
        } else {
903
1
            warn!(
904
                %file_name,
905
1
                atime = %Timestamp::try_from(atime)
?0
,
906
1
                anchor_time = %Timestamp::try_from(*anchor_time)
?0
,
907
                "File access time newer than FilesystemStore start time",
908
            );
909
1
            Duration::ZERO
910
        };
911
237
        let (inserted, _) = evicting_map
912
237
            .insert_with_time_if(
913
237
                key.into_owned().into(),
914
237
                file_entry.clone(),
915
1
                |present_entry, new_entry| present_entry.generation() < new_entry.generation(),
916
237
                i32::try_from(time_since_anchor.as_secs()).unwrap_or(i32::MAX),
917
            )
918
237
            .await;
919
237
        if !inserted {
920
            // Older generations can survive a crash before deferred cleanup.
921
            // Retire rejected files too so the next restart cannot revive them.
922
0
            file_entry.unref().await;
923
237
        }
924
237
        Ok(generation)
925
237
    }
926
927
1.71k
    async fn read_files(
928
1.71k
        folder: Option<&str>,
929
1.71k
        shared_context: &SharedContext,
930
1.71k
    ) -> Result<Vec<(String, SystemTime, u64, bool)>, Error> {
931
        // Note: In Dec 2024 this is for backwards compatibility with the old
932
        // way files were stored on disk. Previously all files were in a single
933
        // folder regardless of the StoreKey type. This allows old versions of
934
        // nativelink file version to be upgraded at startup time.
935
        // This logic can be removed once more time has passed.
936
1.71k
        let read_dir = folder.map_or_else(
937
214
            || format!("{}/", shared_context.content_path),
938
1.49k
            |folder| format!("{}/{folder}/", shared_context.content_path),
939
        );
940
941
1.71k
        let (
_permit882
,
dir_handle882
) = match fs::read_dir(read_dir).await {
942
882
            Ok(dir_handle) => dir_handle.into_inner(),
943
830
            Err(err) if err.code == Code::NotFound => return Ok(Vec::new()),
944
0
            Err(err) => {
945
0
                return Err(err).err_tip(
946
                    || "Failed opening content directory for iterating in filesystem store",
947
                );
948
            }
949
        };
950
951
882
        let read_dir_stream = ReadDirStream::new(dir_handle);
952
882
        read_dir_stream
953
1.13k
            .
map882
(|dir_entry| async move {
954
1.13k
                let dir_entry = dir_entry.unwrap();
955
1.13k
                let file_name = dir_entry.file_name().into_string().unwrap();
956
1.13k
                let metadata = dir_entry
957
1.13k
                    .metadata()
958
1.13k
                    .await
959
1.13k
                    .err_tip(|| "Failed to get metadata in filesystem store")
?0
;
960
                // We need to filter out folders - we do not want to try to cache
961
                // the per-version key folders.
962
1.13k
                let is_file = metadata.is_file()
963
882
                    || ![
964
882
                        STR_FOLDER_V2,
965
882
                        DIGEST_FOLDER_V2,
966
882
                        STR_FOLDER_V1,
967
882
                        DIGEST_FOLDER_V1,
968
882
                    ]
969
882
                    .contains(&file_name.as_str());
970
                // Using access time is not perfect, but better than random. We do not update the
971
                // atime when a file is actually "touched", we rely on whatever the filesystem does
972
                // when we read the file (usually update on read).
973
1.13k
                let atime = metadata
974
1.13k
                    .accessed()
975
1.13k
                    .or_else(|_| 
metadata0
.
modified0
())
976
1.13k
                    .unwrap_or(SystemTime::UNIX_EPOCH);
977
1.13k
                Result::<(String, SystemTime, u64, bool), Error>::Ok((
978
1.13k
                    file_name,
979
1.13k
                    atime,
980
1.13k
                    metadata.len(),
981
1.13k
                    is_file,
982
1.13k
                ))
983
2.27k
            })
984
882
            .buffer_unordered(SIMULTANEOUS_METADATA_READS)
985
882
            .try_collect()
986
882
            .await
987
1.71k
    }
988
989
    /// Best effort: a failure leaves the source where it is, so the loader
990
    /// still picks it up and a later startup retries.
991
18
    fn migrate_file(
992
18
        from_file: &OsStr,
993
18
        to_file: &OsStr,
994
18
        rename_fn: fn(&OsStr, &OsStr) -> Result<(), std::io::Error>,
995
18
    ) {
996
18
        if let Err(
err3
) = rename_fn(from_file, to_file) {
997
3
            warn!(?from_file, ?to_file, ?err, "Failed to migrate file");
998
        } else {
999
15
            debug!(?from_file, ?to_file, "Migrated file");
1000
        }
1001
18
    }
1002
1003
    /// Note: In Dec 2024 this is for backwards compatibility with the old
1004
    /// way files were stored on disk. Previously all files were in a single
1005
    /// folder regardless of the [`StoreKey`] type.
1006
214
    async fn migrate_old_cache_1(
1007
214
        shared_context: &Arc<SharedContext>,
1008
214
        rename_fn: fn(&OsStr, &OsStr) -> Result<(), std::io::Error>,
1009
214
    ) -> Result<(), Error> {
1010
214
        let file_infos = read_files(None, shared_context).await
?0
;
1011
214
        let from_path = &shared_context.content_path;
1012
214
        let to_path = format!("{}/{DIGEST_FOLDER_V2}", shared_context.content_path);
1013
1014
214
        for (
file_name3
, _, _, _) in file_infos.into_iter().filter(|x| x.3) {
1015
3
            migrate_file(
1016
3
                &OsString::from(format!("{from_path}/{file_name}")),
1017
3
                &OsString::from(format!("{to_path}/{file_name}-0")),
1018
3
                rename_fn,
1019
3
            );
1020
3
        }
1021
214
        Ok(())
1022
214
    }
1023
1024
    /// Moves [`Version::V1`] folders into [`Version::V2`].
1025
214
    async fn migrate_old_cache_2(
1026
214
        shared_context: &Arc<SharedContext>,
1027
214
        rename_fn: fn(&OsStr, &OsStr) -> Result<(), std::io::Error>,
1028
214
    ) -> Result<(), Error> {
1029
428
        for (legacy_folder, folder) in [
1030
214
            (DIGEST_FOLDER_V1, DIGEST_FOLDER_V2),
1031
214
            (STR_FOLDER_V1, STR_FOLDER_V2),
1032
214
        ] {
1033
428
            let file_infos = read_files(Some(legacy_folder), shared_context).await
?0
;
1034
428
            let from_path = format!("{}/{legacy_folder}", shared_context.content_path);
1035
428
            let to_path = format!("{}/{folder}", shared_context.content_path);
1036
1037
428
            for (
file_name15
, _, _, _) in file_infos.into_iter().filter(|x| x.3) {
1038
15
                migrate_file(
1039
15
                    &OsString::from(format!("{from_path}/{file_name}")),
1040
15
                    &OsString::from(format!("{to_path}/{file_name}-0")),
1041
15
                    rename_fn,
1042
15
                );
1043
15
            }
1044
        }
1045
214
        Ok(())
1046
214
    }
1047
1048
1.07k
    async fn add_folder_to_cache<Fe: FileEntry>(
1049
1.07k
        evicting_map: &FsEvictingMap<'_, Fe>,
1050
1.07k
        anchor_time: &SystemTime,
1051
1.07k
        shared_context: &Arc<SharedContext>,
1052
1.07k
        block_size: u64,
1053
1.07k
        folder: &str,
1054
1.07k
        file_type: FileType,
1055
1.07k
        version: Version,
1056
1.07k
    ) -> Result<Generation, Error> {
1057
1.07k
        let mut file_infos = read_files(Some(folder), shared_context).await
?0
;
1058
        // Load older generations first. Otherwise cache pressure could evict a
1059
        // newer generation before an older file for that key is encountered.
1060
1.07k
        if version == Version::V2 {
1061
428
            file_infos.sort_by_cached_key(|(file_name, ..)| 
{224
1062
224
                key_and_generation_from_file_v2(file_name, file_type)
1063
224
                    .map_or(Generation::new(0), |(_, generation)| generation)
1064
224
            });
1065
642
        }
1066
1067
1.07k
        let path_root = format!("{}/{folder}", shared_context.content_path);
1068
1069
1.07k
        let mut max_generation = 0;
1070
1071
1.07k
        for (
file_name237
,
atime237
,
data_size237
, _) in file_infos.into_iter().filter(|x| x.3) {
1072
237
            let result = process_entry(
1073
237
                evicting_map,
1074
237
                &file_name,
1075
237
                file_type,
1076
237
                version,
1077
237
                atime,
1078
237
                data_size,
1079
237
                block_size,
1080
237
                anchor_time,
1081
237
                shared_context,
1082
237
            )
1083
237
            .await;
1084
1085
237
            match result {
1086
237
                Ok(generation) => {
1087
237
                    max_generation = cmp::max(max_generation, generation.inner());
1088
237
                }
1089
0
                Err(err) => {
1090
0
                    warn!(?file_name, ?err, "Failed to add file to eviction cache",);
1091
                    // Ignore result.
1092
0
                    drop(fs::remove_file(format!("{path_root}/{file_name}")).await);
1093
                }
1094
            }
1095
        }
1096
1.07k
        Ok(Generation::new(max_generation))
1097
1.07k
    }
1098
1099
214
    if migrate {
1100
214
        migrate_old_cache_1(shared_context, rename_fn).await
?0
;
1101
214
        migrate_old_cache_2(shared_context, rename_fn).await
?0
;
1102
0
    }
1103
1104
214
    let mut max_generation = 0;
1105
1.07k
    for (folder, file_type, version) in [
1106
214
        ("", FileType::Digest, Version::Flat),
1107
214
        (DIGEST_FOLDER_V1, FileType::Digest, Version::V1),
1108
214
        (STR_FOLDER_V1, FileType::String, Version::V1),
1109
214
        (DIGEST_FOLDER_V2, FileType::Digest, Version::V2),
1110
214
        (STR_FOLDER_V2, FileType::String, Version::V2),
1111
214
    ] {
1112
1.07k
        let generation = add_folder_to_cache(
1113
1.07k
            evicting_map,
1114
1.07k
            anchor_time,
1115
1.07k
            shared_context,
1116
1.07k
            block_size,
1117
1.07k
            folder,
1118
1.07k
            file_type,
1119
1.07k
            version,
1120
1.07k
        )
1121
1.07k
        .await
?0
;
1122
1.07k
        max_generation = cmp::max(max_generation, generation.inner());
1123
    }
1124
1125
214
    Ok(Generation::new(max_generation.checked_add(1).ok_or_else(
1126
0
        || {
1127
0
            make_err!(
1128
0
                Code::ResourceExhausted,
1129
                "Filesystem generation counter exhausted"
1130
            )
1131
0
        },
1132
0
    )?))
1133
214
}
1134
1135
214
async fn prune_temp_path(temp_path: &str) -> Result<(), Error> {
1136
856
    async fn prune_temp_inner(temp_path: &str, subpath: &str) -> Result<(), Error> {
1137
856
        let (
_permit428
,
dir_handle428
) = match fs::read_dir(format!("{temp_path}/{subpath}")).await {
1138
428
            Ok(dir_handle) => dir_handle.into_inner(),
1139
428
            Err(err) if err.code == Code::NotFound => return Ok(()),
1140
0
            Err(err) => {
1141
0
                return Err(err).err_tip(|| {
1142
0
                    "Failed opening temp directory to prune partial downloads in filesystem store"
1143
0
                });
1144
            }
1145
        };
1146
1147
428
        let mut read_dir_stream = ReadDirStream::new(dir_handle);
1148
428
        while let Some(
dir_entry0
) = read_dir_stream.next().await {
1149
0
            let path = dir_entry?.path();
1150
0
            if let Err(err) = fs::remove_file(&path).await {
1151
0
                warn!(?path, ?err, "Failed to delete file",);
1152
0
            }
1153
        }
1154
428
        Ok(())
1155
856
    }
1156
1157
856
    for folder in [
1158
214
        STR_FOLDER_V2,
1159
214
        DIGEST_FOLDER_V2,
1160
214
        STR_FOLDER_V1,
1161
214
        DIGEST_FOLDER_V1,
1162
214
    ] {
1163
856
        prune_temp_inner(temp_path, folder).await
?0
;
1164
    }
1165
214
    Ok(())
1166
214
}
1167
1168
// Sometimes we get files to emplace that are identical to the existing files
1169
// Due to the evict/remove/replace cycle taking some amount of time, we actually
1170
// want to drop these
1171
// Return value is "is duplicate"
1172
2.35k
pub async fn check_duplicate_files<Fe>(
1173
2.35k
    evicting_map: &Arc<FsEvictingMap<'_, Fe>>,
1174
2.35k
    key: &StoreKey<'static>,
1175
2.35k
    entry: &Arc<Fe>,
1176
2.35k
) -> Result<bool, Error>
1177
2.35k
where
1178
2.35k
    Fe: FileEntry,
1179
2.35k
{
1180
2.35k
    let temp_file_encoded_file_path = entry.get_encoded_file_path().write().await;
1181
2.35k
    let maybe_existing_item = evicting_map.get(&key.borrow().into_owned()).await;
1182
2.35k
    if let Some(
existing_item32
) = maybe_existing_item {
1183
32
        if Arc::ptr_eq(entry, &existing_item) {
1184
1
            warn!("Tried to check duplicate of an entry we already have!");
1185
1
            return Ok(true);
1186
31
        }
1187
31
        let existing_item_encoded_file_path = existing_item.get_encoded_file_path().write().await;
1188
31
        if entry.data_size() == existing_item.data_size() {
1189
            const CHUNK_SIZE: usize = 16 * 1024; // 16kb chunks, kinda picked out of the air
1190
27
            let file_length = entry.data_size();
1191
27
            let existing_path = existing_item_encoded_file_path.get_file_path();
1192
27
            let temp_path = temp_file_encoded_file_path.get_file_path();
1193
27
            trace!(?existing_path, ?temp_path, "Checking duplicate files");
1194
27
            let mut temp_file = fs::open_file(&temp_path, 0, file_length).await
?0
;
1195
27
            let 
mut existing_file22
= match fs::open_file(&existing_path, 0, file_length).await {
1196
22
                Ok(file) => file,
1197
5
                Err(
err4
) if err.code == Code::NotFoun
d4
=> {
1198
4
                    warn!(
1199
                        ?key,
1200
                        ?err,
1201
                        "Map/disk divergence in check_duplicate_files: dropping stale entry",
1202
                    );
1203
                    // Removal calls unref(), which needs the path lock. Release
1204
                    // both locks and the open file before running callbacks.
1205
4
                    drop(temp_file);
1206
4
                    drop(existing_item_encoded_file_path);
1207
4
                    drop(temp_file_encoded_file_path);
1208
4
                    evicting_map
1209
4
                        .remove_if(key, |map_entry| Arc::ptr_eq(map_entry, &existing_item))
1210
4
                        .await;
1211
4
                    return Ok(false);
1212
                }
1213
1
                Err(err) => return Err(err),
1214
            };
1215
1216
22
            let mut temp_buffer: [u8; CHUNK_SIZE] = [0; CHUNK_SIZE];
1217
22
            let mut existing_buffer: [u8; CHUNK_SIZE] = [0; CHUNK_SIZE];
1218
22
            for offset in (0..file_length).step_by(CHUNK_SIZE) {
1219
22
                let buffer_size = if offset + (CHUNK_SIZE as u64) <= file_length {
1220
2
                    CHUNK_SIZE
1221
20
                } else if file_length < CHUNK_SIZE as u64 {
1222
18
                    usize::try_from(file_length)
1223
18
                        .expect("Always succeeds because file_length < 16384")
1224
                } else {
1225
2
                    usize::try_from(file_length - offset).expect("Always succeeds because offset < file_length, and offset-file_length must be < 16384")
1226
                };
1227
22
                if let Err(
err0
) = temp_file.read_exact(&mut temp_buffer[0..buffer_size]).await {
1228
0
                    warn!(
1229
                        ?err,
1230
                        ?temp_path,
1231
                        file_length,
1232
                        offset,
1233
                        buffer_size,
1234
                        "Failed to read temp file, skipping duplicate check"
1235
                    );
1236
0
                    return Ok(false);
1237
22
                }
1238
22
                if let Err(
err0
) = existing_file
1239
22
                    .read_exact(&mut existing_buffer[0..buffer_size])
1240
22
                    .await
1241
                {
1242
0
                    warn!(
1243
                        ?err,
1244
                        ?existing_path,
1245
                        file_length,
1246
                        offset,
1247
                        buffer_size,
1248
                        "Failed to read existing, skipping duplicate check"
1249
                    );
1250
0
                    return Ok(false);
1251
22
                }
1252
22
                if temp_buffer.ne(&existing_buffer) {
1253
11
                    trace!(
1254
                        ?existing_path,
1255
                        ?temp_path,
1256
                        "Files are different, so non-duplicate"
1257
                    );
1258
11
                    return Ok(false);
1259
11
                }
1260
            }
1261
11
            trace!(
1262
                ?existing_path,
1263
                ?temp_path,
1264
                "Identical files, so don't need to edit, skipping emplace"
1265
            );
1266
11
            drop(existing_file);
1267
11
            drop(temp_file);
1268
11
            drop(existing_item_encoded_file_path);
1269
11
            drop(temp_file_encoded_file_path);
1270
            // Comparison can overlap eviction. An identical retired file no
1271
            // longer satisfies this upload unless it is still the mapped entry.
1272
11
            return Ok(evicting_map
1273
11
                .get(key)
1274
11
                .await
1275
11
                .is_some_and(|current| Arc::ptr_eq(&current, &existing_item)));
1276
4
        }
1277
4
        trace!(
1278
4
            entry_data_size = entry.data_size(),
1279
4
            existing_data_size = existing_item.data_size(),
1280
4
            existing_path = ?existing_item_encoded_file_path.get_file_path(),
1281
            "Different data sizes, so non-duplicate"
1282
        );
1283
    } else {
1284
2.32k
        trace!(
1285
2.31k
            temp_file = ?temp_file_encoded_file_path.get_file_path(),
1286
            "No existing entry, so not duplicate"
1287
        );
1288
    }
1289
2.32k
    Ok(false)
1290
2.35k
}
1291
1292
/// Deletes a digest's `.exec` variant (see
1293
/// [`FilesystemStore::get_executable_hardlink_source`]) when that digest is
1294
/// evicted or replaced in the primary CAS `evicting_map`. Without this, the
1295
/// `.exec` directory is invisible to `max_bytes` and is only ever cleared by
1296
/// the startup `remove_dir_all`, so it grows without bound at runtime (#2474).
1297
/// Tying its lifetime to the primary entry instead bounds total disk use to
1298
/// roughly `2 * max_bytes` in the worst case (every blob also executable).
1299
#[cfg(unix)]
1300
#[derive(Debug)]
1301
struct ExecutableVariantRemover {
1302
    content_path: String,
1303
}
1304
1305
#[cfg(unix)]
1306
impl RemoveItemCallback for ExecutableVariantRemover {
1307
50
    fn callback<'a>(
1308
50
        &'a self,
1309
50
        store_key: StoreKey<'a>,
1310
50
    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
1311
50
        Box::pin(async move {
1312
50
            let StoreKey::Digest(
digest40
) = store_key else {
1313
10
                return;
1314
            };
1315
40
            let variant_path = format!(
1316
                "{}{EXECUTABLE_DIR_SUFFIX}/{DIGEST_FOLDER_V2}/{digest}",
1317
                self.content_path
1318
            );
1319
40
            match fs::remove_file(&variant_path).await {
1320
3
                Ok(()) => debug!(
1321
                    ?variant_path,
1322
                    "Deleted executable variant for evicted digest"
1323
                ),
1324
                // Common case: no variant was ever materialized for this digest.
1325
37
                Err(err) if err.code == Code::NotFound => {}
1326
0
                Err(err) => warn!(
1327
                    ?variant_path,
1328
                    ?err,
1329
                    "Failed to delete executable variant for evicted digest"
1330
                ),
1331
            }
1332
50
        })
1333
50
    }
1334
}
1335
1336
#[derive(Debug, MetricsComponent)]
1337
pub struct FilesystemStore<Fe: FileEntry = FileEntryImpl> {
1338
    #[metric]
1339
    shared_context: Arc<SharedContext>,
1340
    #[metric(group = "evicting_map")]
1341
    evicting_map: Arc<FsEvictingMap<'static, Fe>>,
1342
    #[metric(help = "Block size of the configured filesystem")]
1343
    block_size: u64,
1344
    #[metric(help = "Size of the configured read buffer size")]
1345
    read_buffer_size: usize,
1346
    /// See [`FilesystemSpec::evict_page_cache`]. When false (the default) the
1347
    /// per-blob `posix_fadvise(DONTNEED)` calls are skipped.
1348
    evict_page_cache: bool,
1349
    weak_self: Weak<Self>,
1350
    rename_fn: fn(&OsStr, &OsStr) -> Result<(), std::io::Error>,
1351
    /// Limits concurrent write operations to prevent disk I/O saturation.
1352
    write_semaphore: Option<Semaphore>,
1353
    /// A monotonic counter by which we stamp newly added files.
1354
    next_generation: AtomicU64,
1355
    /// See [`FlushCoalescer`]: amortizes the per-blob `F_FULLFSYNC` cost
1356
    /// across concurrent uploads without weakening durability. `None` when
1357
    /// the sentinel could not be created (e.g. read-only content volume);
1358
    /// uploads then fall back to per-file `sync_all`, matching the old
1359
    /// behavior (and such stores fail at write time anyway).
1360
    #[cfg(target_os = "macos")]
1361
    flush_coalescer: Option<Arc<FlushCoalescer>>,
1362
    /// Per-digest single-flight locks guarding creation of the executable
1363
    /// variant in `{content_path}.exec`, so each variant's writable fd is
1364
    /// opened exactly once. The outer lock is sync and only ever held to
1365
    /// get/insert/remove the per-digest async lock — never across I/O.
1366
    #[cfg(unix)]
1367
    executable_locks: std::sync::Mutex<HashMap<DigestInfo, Arc<Mutex<()>>>>,
1368
    /// False when the startup wipe could not safely remove old executable
1369
    /// variants from a read-only filesystem. Ordinary CAS reads remain
1370
    /// available, but executable hardlink sources must not reuse stale files.
1371
    #[cfg(unix)]
1372
    executable_variants_enabled: bool,
1373
}
1374
1375
impl<Fe: FileEntry> FilesystemStore<Fe> {
1376
197
    pub async fn new(spec: &FilesystemSpec) -> Result<Arc<Self>, Error> {
1377
2.34k
        
Self::new_with_timeout_and_rename_fn197
(
spec197
, |from, to| std::fs::rename(from, to)).
await197
1378
197
    }
1379
1380
214
    pub async fn new_with_timeout_and_rename_fn(
1381
214
        spec: &FilesystemSpec,
1382
214
        rename_fn: fn(&OsStr, &OsStr) -> Result<(), std::io::Error>,
1383
214
    ) -> Result<Arc<Self>, Error> {
1384
428
        async fn create_subdirs(path: &str) -> Result<bool, Error> {
1385
428
            let mut writable = true;
1386
856
            for folder in 
[STR_FOLDER_V2, DIGEST_FOLDER_V2]428
{
1387
856
                let dir = format!("{path}/{folder}");
1388
856
                writable &= fs::call_with_permit(move |_| match std::fs::create_dir_all(&dir) {
1389
856
                    Ok(()) => Ok(true),
1390
0
                    Err(err) if matches!(err.kind(), std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::ReadOnlyFilesystem) => {
1391
0
                        warn!(%dir, ?err, "Cannot create directory on read-only volume; retaining legacy files");
1392
0
                        Ok(false)
1393
                    }
1394
0
                    Err(err) => Err(Error::from(err).append(format!("Failed to create directory {dir}"))),
1395
856
                }).await
?0
;
1396
            }
1397
428
            Ok(writable)
1398
428
        }
1399
1400
214
        let now = SystemTime::now();
1401
1402
214
        let empty_policy = nativelink_config::stores::EvictionPolicy::default();
1403
214
        let eviction_policy = spec.eviction_policy.as_ref().unwrap_or(&empty_policy);
1404
214
        let evicting_map = Arc::new(EvictingMap::new(eviction_policy, now));
1405
1406
        // Create the generation-aware temp and content directories.
1407
1408
214
        let temp_dirs_writable = create_subdirs(&spec.temp_path).await
?0
;
1409
214
        let content_dirs_writable = create_subdirs(&spec.content_path).await
?0
;
1410
        // Nothing to migrate into; skip the scan rather than warn per file.
1411
214
        let migrate = temp_dirs_writable && content_dirs_writable;
1412
1413
        // Executable-variant directory: a sibling of `content_path` holding
1414
        // per-digest 0o555 copies used as hardlink sources for executable
1415
        // inputs (see `get_executable_hardlink_source`). Cleared on writable
1416
        // startup — the variants are regenerable and we never want a stale one
1417
        // to leak across runs. If a read-only filesystem prevents the wipe,
1418
        // ordinary CAS reads remain enabled but executable variants do not.
1419
        // Unix-only: the executable bit (and the ETXTBSY race it guards
1420
        // against) does not apply on Windows.
1421
        #[cfg(unix)]
1422
214
        let executable_variants_enabled = {
1423
214
            let enabled = prepare_executable_dir(&spec.content_path).await
?0
;
1424
214
            if !enabled {
1425
1
                warn!(
1426
1
                    executable_dir = %format!("{}{EXECUTABLE_DIR_SUFFIX}", spec.content_path),
1427
                    "Executable directory is not writable; serving CAS reads with executable variants disabled"
1428
                );
1429
213
            }
1430
214
            if enabled {
1431
213
                // Only register cleanup when executable variants are enabled.
1432
213
                // Otherwise surviving variants are deliberately quarantined,
1433
213
                // and repeated deletion warnings would obscure the fallback.
1434
213
                evicting_map.add_remove_callback(RemoveCallbackHolder::new(Arc::new(
1435
213
                    ExecutableVariantRemover {
1436
213
                        content_path: spec.content_path.clone(),
1437
213
                    },
1438
213
                )));
1439
213
            
}1
1440
214
            enabled
1441
        };
1442
1443
214
        let shared_context = Arc::new(SharedContext {
1444
214
            active_drop_spawns: AtomicU64::new(0),
1445
214
            temp_path: spec.temp_path.clone(),
1446
214
            content_path: spec.content_path.clone(),
1447
214
        });
1448
1449
214
        let block_size = if spec.block_size == 0 {
1450
172
            DEFAULT_BLOCK_SIZE
1451
        } else {
1452
42
            spec.block_size
1453
        };
1454
214
        let next_generation = add_files_to_cache(
1455
214
            evicting_map.as_ref(),
1456
214
            &now,
1457
214
            &shared_context,
1458
214
            block_size,
1459
214
            rename_fn,
1460
214
            migrate,
1461
214
        )
1462
214
        .await
?0
;
1463
214
        prune_temp_path(&shared_context.temp_path).await
?0
;
1464
1465
214
        let read_buffer_size = if spec.read_buffer_size == 0 {
1466
199
            DEFAULT_BUFF_SIZE
1467
        } else {
1468
15
            spec.read_buffer_size as usize
1469
        };
1470
214
        let write_semaphore = if spec.max_concurrent_writes > 0 {
1471
0
            Some(Semaphore::new(spec.max_concurrent_writes))
1472
        } else {
1473
214
            None
1474
        };
1475
        // Never make construction fail over the durability optimization:
1476
        // a read-only content volume must still serve reads, exactly as
1477
        // it did before the coalescer existed.
1478
        #[cfg(target_os = "macos")]
1479
        let flush_coalescer = FlushCoalescer::for_content_path(&shared_context.content_path)
1480
            .await
1481
            .inspect_err(|err| {
1482
                warn!(
1483
                    ?err,
1484
                    "Failed to create flush coalescer; falling back to per-file sync_all"
1485
                );
1486
            })
1487
            .ok();
1488
1489
214
        Ok(Arc::new_cyclic(|weak_self| Self {
1490
214
            shared_context,
1491
214
            evicting_map,
1492
214
            block_size,
1493
214
            read_buffer_size,
1494
214
            evict_page_cache: spec.evict_page_cache,
1495
214
            weak_self: weak_self.clone(),
1496
214
            rename_fn,
1497
214
            next_generation: AtomicU64::new(next_generation.inner()),
1498
214
            write_semaphore,
1499
            #[cfg(target_os = "macos")]
1500
            flush_coalescer,
1501
            #[cfg(unix)]
1502
214
            executable_locks: std::sync::Mutex::new(HashMap::new()),
1503
            #[cfg(unix)]
1504
214
            executable_variants_enabled,
1505
214
        }))
1506
214
    }
1507
1508
130
    pub fn get_arc(&self) -> Option<Arc<Self>> {
1509
130
        self.weak_self.upgrade()
1510
130
    }
1511
1512
    /// Reserve a digest before it is populated so active action inputs cannot
1513
    /// be evicted while they are being materialized.
1514
38
    pub fn lease_digest(&self, digest: &DigestInfo) {
1515
38
        let key: StoreKey<'static> = (*digest).into();
1516
38
        self.evicting_map.lease_key(StoreKeyBorrow::from(key));
1517
38
    }
1518
1519
    /// Release a batch of action-input leases and trim retained entries once.
1520
9
    pub async fn release_digests(&self, digests: &[DigestInfo]) {
1521
9
        self.evicting_map
1522
38
            .
release_keys9
(
digests9
.
iter9
().
map9
(|digest| StoreKey::Digest(*digest)))
1523
9
            .await;
1524
9
    }
1525
1526
2.35k
    fn get_and_update_generation(&self) -> Result<Generation, Error> {
1527
2.35k
        self.next_generation
1528
2.36k
            .
try_update2.35k
(
Ordering::Relaxed2.35k
,
Ordering::Relaxed2.35k
, |generation| {
1529
2.36k
                generation.checked_add(1)
1530
2.36k
            })
1531
2.35k
            .map(Generation::new)
1532
2.35k
            .map_err(|_| 
{0
1533
0
                make_err!(
1534
0
                    Code::ResourceExhausted,
1535
                    "Filesystem generation counter exhausted"
1536
                )
1537
0
            })
1538
2.35k
    }
1539
1540
    /// Path of the read-only executable (0o555) variant for `digest`.
1541
    #[cfg(unix)]
1542
28
    fn executable_variant_path(&self, digest: &DigestInfo) -> OsString {
1543
28
        format!(
1544
            "{}{EXECUTABLE_DIR_SUFFIX}/{DIGEST_FOLDER_V2}/{digest}",
1545
28
            self.shared_context.content_path
1546
        )
1547
28
        .into()
1548
28
    }
1549
1550
    /// Resolves the executable variant for many digests at once, batching the
1551
    /// warm path's existence checks into a single dispatch.
1552
    ///
1553
    /// Every input file carrying the executable bit resolves through here, and
1554
    /// in a toolchain-heavy input tree that is nearly all of them. The `stat(2)`
1555
    /// this needs costs single-digit microseconds on tmpfs, while the permit
1556
    /// acquisition and thread hop to dispatch one cost tens: asking per path
1557
    /// spent ~4.6s per action on a 15k-file tree, and asking once for the tree
1558
    /// spends ~37ms.
1559
    ///
1560
    /// A hit also counts as a use of the blob. The variant lives outside the
1561
    /// eviction index, so a toolchain binary that every action hardlinks from
1562
    /// its variant would otherwise never move in the LRU and be evicted as the
1563
    /// coldest entry of a full store, taking its variant with it under the
1564
    /// next action's batch. One batched lookup refreshes every hit's position.
1565
    /// A variant whose blob is no longer indexed is reported `NotFound`, not
1566
    /// handed out: the caller then fills the fast store again, which puts the
1567
    /// blob back in the index so its next eviction deletes the variant too.
1568
75
    pub async fn get_executable_hardlink_sources(
1569
75
        &self,
1570
75
        digests: &[DigestInfo],
1571
75
    ) -> Vec<Result<OsString, Error>> {
1572
75
        let hits = self.materialized_variants(digests).await;
1573
75
        let hit_keys: Vec<StoreKey<'static>> = digests
1574
75
            .iter()
1575
75
            .zip(&hits)
1576
75
            .filter(|(_, hit)| 
hit11
.
is_some11
())
1577
75
            .map(|(digest, _)| StoreKey::Digest(
*digest5
))
1578
75
            .collect();
1579
75
        let mut indexed = vec![None; hit_keys.len()];
1580
75
        if !hit_keys.is_empty() {
1581
5
            self.evicting_map
1582
5
                .sizes_for_keys(hit_keys.iter(), &mut indexed, false /* peek */)
1583
5
                .await;
1584
70
        }
1585
75
        let mut indexed = indexed.into_iter();
1586
1587
75
        let mut tasks = Vec::with_capacity(digests.len());
1588
75
        for (
digest11
,
hit11
) in digests.iter().copied().zip(hits) {
1589
11
            let orphaned = hit.is_some() && 
indexed5
.next().flatten().
is_none5
();
1590
11
            tasks.push(async move {
1591
5
                match hit {
1592
2
                    Some(_) if orphaned => Err(make_err!(
1593
2
                        Code::NotFound,
1594
2
                        "{digest} has an executable variant on disk but no indexed blob; fill the fast store again"
1595
2
                    )),
1596
3
                    Some(path) => Ok(path),
1597
6
                    None => self.get_executable_hardlink_source(&digest).await,
1598
                }
1599
11
            });
1600
        }
1601
75
        futures::stream::iter(tasks)
1602
75
            .buffered(MAX_CONCURRENT_VARIANT_LOOKUPS)
1603
75
            .collect()
1604
75
            .await
1605
75
    }
1606
1607
    /// Reports which digests already have an executable variant on disk, in one
1608
    /// batched existence check.
1609
    #[cfg(unix)]
1610
75
    async fn materialized_variants(&self, digests: &[DigestInfo]) -> Vec<Option<OsString>> {
1611
75
        let paths: Vec<OsString> = digests
1612
75
            .iter()
1613
75
            .map(|digest| 
self11
.
executable_variant_path11
(
digest11
))
1614
75
            .collect();
1615
1616
        // Variants disabled and a failed batch are the same situation: nothing
1617
        // is known to exist, so every digest takes the per-digest path, which
1618
        // reports real errors per file.
1619
75
        let exists = if self.executable_variants_enabled {
1620
75
            fs::exists_many(paths.iter().map(Into::into).collect())
1621
75
                .await
1622
75
                .ok()
1623
        } else {
1624
0
            None
1625
        }
1626
75
        .unwrap_or_else(|| 
vec!0
[false;
paths0
.
len0
()]);
1627
1628
75
        paths
1629
75
            .into_iter()
1630
75
            .zip(exists)
1631
75
            .map(|(path, hit)| 
hit11
.
then_some11
(
path11
))
1632
75
            .collect()
1633
75
    }
1634
1635
    /// Non-unix never builds executable variants, so there is never one on disk
1636
    /// to find and nothing to batch.
1637
    #[cfg(not(unix))]
1638
    async fn materialized_variants(&self, digests: &[DigestInfo]) -> Vec<Option<OsString>> {
1639
        vec![None; digests.len()]
1640
    }
1641
1642
    /// Returns the path to a private, read-only **executable** (0o555) copy of
1643
    /// the blob for `digest`, creating it at most once. Callers **hardlink**
1644
    /// the returned path into action input trees instead of copying the
1645
    /// executable per action.
1646
    ///
1647
    /// Why this exists: a CAS blob is stored read-only **0o444** and shared
1648
    /// across actions by hardlink, so it cannot carry the executable bit and
1649
    /// must never be `chmod`'d (that mutates the shared inode — the #2347
1650
    /// corruption class). Materializing an executable input therefore needs a
1651
    /// separate 0o555 inode. Doing that copy *per action* opens a writable fd
1652
    /// in the worker's hot path; under fork-heavy concurrency a child can
1653
    /// inherit that fd and a concurrent `execve` of the executable then fails
1654
    /// with `ETXTBSY` ("Text file busy", os error 26). Creating the 0o555 inode
1655
    /// **once** — writer fd fsync'd and closed, then atomically renamed into
1656
    /// place before the inode is ever hardlinked or executed — and hardlinking
1657
    /// it thereafter keeps the per-action path hardlink-only.
1658
    #[cfg(unix)]
1659
18
    pub async fn get_executable_hardlink_source(
1660
18
        &self,
1661
18
        digest: &DigestInfo,
1662
18
    ) -> Result<OsString, Error> {
1663
18
        if !self.executable_variants_enabled {
1664
1
            return Err(make_err!(
1665
1
                Code::FailedPrecondition,
1666
1
                "Executable hardlink sources are disabled because the startup wipe could not safely clear the read-only executable directory"
1667
1
            ));
1668
17
        }
1669
17
        let variant_path = self.executable_variant_path(digest);
1670
1671
        // Fast path: the variant already exists, so the caller can hardlink it
1672
        // with no writable fd anywhere in sight.
1673
17
        if fs::metadata(&variant_path).await.is_ok() {
1674
2
            return Ok(variant_path);
1675
15
        }
1676
1677
        // Single-flight: exactly one task ever opens a writable fd for this
1678
        // variant. Without this, a cold-cache burst of concurrent actions
1679
        // would each open a writer for the same executable — the very window
1680
        // ETXTBSY exploits.
1681
15
        let lock = {
1682
15
            let mut locks = self
1683
15
                .executable_locks
1684
15
                .lock()
1685
15
                .expect("executable_locks poisoned");
1686
15
            locks
1687
15
                .entry(*digest)
1688
15
                .or_insert_with(|| Arc::new(Mutex::new(())))
1689
15
                .clone()
1690
        };
1691
15
        let _guard = lock.lock().await;
1692
1693
        // Re-check: another task may have constructed it while we waited.
1694
15
        if fs::metadata(&variant_path).await.is_ok() {
1695
0
            self.forget_executable_lock(digest);
1696
0
            return Ok(variant_path);
1697
15
        }
1698
1699
15
        let result = self.create_executable_variant(digest, &variant_path).await;
1700
1701
        // The digest may have been evicted mid-copy: its eviction callback ran
1702
        // before the rename published the variant, so nothing owns the file
1703
        // anymore. This orphans the variant from eviction accounting, but the
1704
        // race is rare enough (needs an eviction to land in the narrow window
1705
        // between rename and this check, on a digest's first-ever variant
1706
        // materialization) that it's a self-limiting leak, not a systemic one
1707
        // — cheaper to log and let this action succeed with the still-valid
1708
        // file than to fail an otherwise-successful action over it.
1709
15
        if result.is_ok() && 
self.evicting_map11
.
get11
(&digest.into()).
await11
.
is_none11
() {
1710
0
            warn!(
1711
                %digest,
1712
                ?variant_path,
1713
                "Digest evicted while materializing its executable variant; \
1714
                 variant is now untracked by eviction accounting"
1715
            );
1716
15
        }
1717
1718
        // Drop the per-digest lock entry regardless of outcome so the map
1719
        // cannot grow unbounded; a concurrent waiter already cloned the Arc.
1720
15
        self.forget_executable_lock(digest);
1721
15
        result.map(|()| variant_path)
1722
18
    }
1723
1724
    /// Non-unix has no executable bit and no `ETXTBSY`, so just hardlink the
1725
    /// CAS blob directly.
1726
    #[cfg(not(unix))]
1727
    pub async fn get_executable_hardlink_source(
1728
        &self,
1729
        digest: &DigestInfo,
1730
    ) -> Result<OsString, Error> {
1731
        let file_entry = self.get_file_entry_for_digest(digest).await?;
1732
        file_entry
1733
            .get_file_path_locked(|p| async move { Ok(p) })
1734
            .await
1735
    }
1736
1737
    #[cfg(unix)]
1738
15
    fn forget_executable_lock(&self, digest: &DigestInfo) {
1739
15
        self.executable_locks
1740
15
            .lock()
1741
15
            .expect("executable_locks poisoned")
1742
15
            .remove(digest);
1743
15
    }
1744
1745
    /// Materializes the 0o555 executable variant for `digest`. Must be called
1746
    /// under the per-digest single-flight guard.
1747
    #[cfg(unix)]
1748
15
    async fn create_executable_variant(
1749
15
        &self,
1750
15
        digest: &DigestInfo,
1751
15
        variant_path: &OsStr,
1752
15
    ) -> Result<(), Error> {
1753
        // Resolve the on-disk CAS blob (0o444) to copy from. Must be present in
1754
        // this tier; callers populate the fast store first.
1755
15
        let 
file_entry11
= self
1756
15
            .get_file_entry_for_digest(digest)
1757
15
            .await
1758
15
            .err_tip(|| "Resolving CAS blob for executable variant")
?4
;
1759
11
        let src_path = file_entry
1760
22
            .
get_file_path_locked11
(|p| async move
{11
Ok(p)11
})
1761
11
            .await
?0
;
1762
1763
11
        let variant_owned = variant_path.to_os_string();
1764
11
        let mut temp_owned = variant_path.to_os_string();
1765
11
        temp_owned.push(".tmp");
1766
11
        let rename_fn = self.rename_fn;
1767
1768
        // All of this is blocking std::fs; run it off the async runtime. The
1769
        // writable fd opened by `copy` is fully closed before the `rename`
1770
        // publishes the inode, so no reachable hardlink of the variant ever has
1771
        // an open writer.
1772
11
        spawn_blocking!(
1773
            "filesystem_store_executable_variant",
1774
11
            move || -> Result<(), Error> {
1775
                use std::os::unix::fs::PermissionsExt;
1776
11
                std::fs::copy(&src_path, &temp_owned).map_err(|e| 
{0
1777
0
                    make_err!(Code::Internal, "executable-variant copy failed: {e:?}")
1778
0
                })?;
1779
11
                std::fs::set_permissions(&temp_owned, std::fs::Permissions::from_mode(0o555))
1780
11
                    .map_err(|e| 
{0
1781
0
                        make_err!(
1782
0
                            Code::Internal,
1783
                            "executable-variant chmod 0o555 failed: {e:?}"
1784
                        )
1785
0
                    })?;
1786
                // Belt-and-suspenders flush before publish. The `.exec`
1787
                // directory is cleared before executable variants are enabled,
1788
                // so durability is not needed across process restarts. The
1789
                // flush still ensures a published variant is complete for the
1790
                // current process. Non-macOS keeps the prior `sync_all`
1791
                // behavior; macOS uses plain `fsync(2)` (data handed to the
1792
                // device, no multi-ms `F_FULLFSYNC` device-cache drain), which
1793
                // covers kernel panics — the next writable startup wipe covers
1794
                // power loss.
1795
11
                let f = std::fs::File::open(&temp_owned)
1796
11
                    .map_err(|e| 
make_err!0
(
Code::Internal0
, "executable-variant reopen: {e:?}"))
?0
;
1797
                #[cfg(target_os = "macos")]
1798
                let flush_result = {
1799
                    use std::os::fd::AsRawFd;
1800
                    loop {
1801
                        if unsafe { libc::fsync(f.as_raw_fd()) } == 0 {
1802
                            break Ok(());
1803
                        }
1804
                        let err = std::io::Error::last_os_error();
1805
                        if err.kind() != std::io::ErrorKind::Interrupted {
1806
                            break Err(err);
1807
                        }
1808
                    }
1809
                };
1810
                #[cfg(not(target_os = "macos"))]
1811
11
                let flush_result = f.sync_all();
1812
11
                flush_result
1813
11
                    .map_err(|e| 
make_err!0
(
Code::Internal0
, "executable-variant fsync: {e:?}"))
?0
;
1814
11
                drop(f);
1815
11
                rename_fn(temp_owned.as_os_str(), variant_owned.as_os_str()).map_err(|e| 
{0
1816
0
                    make_err!(Code::Internal, "executable-variant rename failed: {e:?}")
1817
0
                })?;
1818
11
                Ok(())
1819
11
            }
1820
        )
1821
11
        .await
1822
11
        .err_tip(|| "executable-variant spawn_blocking join failed")
?0
1823
15
    }
1824
1825
1.67k
    pub async fn get_file_entry_for_digest(&self, digest: &DigestInfo) -> Result<Arc<Fe>, Error> {
1826
        // Zero-digest blobs have no backing file on disk (FilesystemStore
1827
        // never persists zero-byte content). The previous implementation
1828
        // returned a synthetic FileEntry whose content_path did not exist,
1829
        // which downstream callers would then try to hard_link from,
1830
        // silently producing missing or empty output files in worker
1831
        // execution directories. Return NotFound so callers are forced to
1832
        // take the explicit zero-digest path (e.g. fs::create_file).
1833
1.67k
        if is_zero_digest(digest) {
1834
1
            return Err(make_err!(
1835
1
                Code::NotFound,
1836
1
                "{digest} is a zero-digest; FilesystemStore does not persist zero-byte files. \
1837
1
                 Callers must materialise empty files directly rather than going through get_file_entry_for_digest."
1838
1
            ));
1839
1.66k
        }
1840
1.66k
        self.evicting_map
1841
1.66k
            .get(&digest.into())
1842
1.66k
            .await
1843
1.66k
            .ok_or_else(|| 
make_err!165
(
Code::NotFound165
, "{digest} not found in filesystem store. This may indicate the file was evicted due to cache pressure. Consider increasing 'max_bytes' in your filesystem store's eviction_policy configuration."))
1844
1.67k
    }
1845
1846
1.77k
    async fn update_file(
1847
1.77k
        self: Pin<&Self>,
1848
1.77k
        mut entry: Fe,
1849
1.77k
        mut temp_file: FileSlot,
1850
1.77k
        final_key: StoreKey<'static>,
1851
1.77k
        mut reader: DropCloserReadHalf,
1852
1.77k
        upload_size: UploadSizeInfo,
1853
1.77k
    ) -> Result<u64, Error> {
1854
1.77k
        let mut data_size = 0;
1855
        loop {
1856
3.55k
            let 
mut data3.55k
= reader
1857
3.55k
                .recv()
1858
3.55k
                .await
1859
3.55k
                .err_tip(|| "Failed to receive data in filesystem store")
?1
;
1860
3.55k
            let data_len = data.len();
1861
3.55k
            if data_len == 0 {
1862
1.77k
                break; // EOF.
1863
1.77k
            }
1864
1.77k
            temp_file
1865
1.77k
                .write_all_buf(&mut data)
1866
1.77k
                .await
1867
1.77k
                .err_tip(|| "Failed to write data into filesystem store")
?0
;
1868
1.77k
            data_size += data_len as u64;
1869
        }
1870
1871
1.77k
        upload_size.validate_size(data_size)
?4
;
1872
1.77k
        let permit = if let Some(
sem0
) = &self.write_semaphore {
1873
0
            Some(sem.acquire().await.map_err(|err| {
1874
0
                Error::from_std_err(Code::Internal, &err).append("Write semaphore closed")
1875
0
            })?)
1876
        } else {
1877
1.77k
            None
1878
        };
1879
1880
        // tokio defers write errors to the next write or flush call, so without an explicit flush
1881
        // the final write's failure is silently swallowed by `sync_all`, and a truncated file would
1882
        // be renamed into the content path.
1883
1.77k
        temp_file
1884
1.77k
            .flush()
1885
1.77k
            .await
1886
1.77k
            .err_tip(|| "Failed to flush in filesystem store")
?0
;
1887
1.77k
        self.flush_durably(&temp_file)
1888
1.77k
            .await
1889
1.77k
            .err_tip(|| "Failed to sync in filesystem store")
?0
;
1890
1891
1.77k
        drop(permit);
1892
1893
1.77k
        if self.evict_page_cache {
1894
0
            temp_file.advise_dontneed();
1895
1.77k
        }
1896
1.77k
        trace!(?temp_file, "Dropping file to update_file");
1897
1.77k
        drop(temp_file);
1898
1899
1.77k
        *entry.data_size_mut() = data_size;
1900
1.77k
        self.emplace_file(final_key, Arc::new(entry)).await
?1
;
1901
1.77k
        Ok(data_size)
1902
1.77k
    }
1903
1904
2.34k
    async fn emplace_file(&self, key: StoreKey<'static>, entry: Arc<Fe>) -> Result<(), Error> {
1905
        // Each generation owns a distinct content path. Publish the file before
1906
        // inserting it into the map, so readers only observe completed renames.
1907
        // A delayed unref of another generation cannot touch this file.
1908
2.34k
        let evicting_map = self.evicting_map.clone();
1909
2.34k
        let rename_fn = self.rename_fn;
1910
1911
        // We need to guarantee that this will get to the end even if the parent future is dropped.
1912
        // See: https://github.com/TraceMachina/nativelink/issues/495
1913
2.34k
        background_spawn!("filesystem_store_emplace_file", async move {
1914
            // Sometimes we get files to emplace that are identical to the existing files
1915
            // Due to the evict/remove/replace cycle taking some amount of time, we actually
1916
            // want to drop these
1917
2.34k
            if check_duplicate_files(&evicting_map, &key, &entry).await
?1
{
1918
10
                return Ok(());
1919
2.33k
            }
1920
1921
2.33k
            let mut encoded_file_path = entry.get_encoded_file_path().write().await;
1922
1923
2.33k
            let final_path = get_file_path_raw(
1924
2.33k
                &PathType::Content,
1925
2.33k
                encoded_file_path.shared_context.as_ref(),
1926
2.33k
                &key,
1927
2.33k
                encoded_file_path.generation,
1928
2.33k
                encoded_file_path.version,
1929
            );
1930
1931
2.33k
            let from_path = encoded_file_path.get_file_path();
1932
1933
            // Lock the blob down as read-only *before* it lands at its final
1934
            // content path, so every hardlink of it (the worker directory cache
1935
            // and `download_to_directory`) inherits an immutable, read-only
1936
            // inode. This is what preserves the input-tree hermeticity contract
1937
            // (actions cannot mutate their inputs) without a per-materialization
1938
            // chmod walk, and it means callers must never `chmod` a hardlinked
1939
            // blob — anything needing a different mode (e.g. an executable's +x
1940
            // bit) must take a private copy. Content-addressed blobs are
1941
            // write-once and replaced by `rename` rather than in-place writes,
1942
            // and unlink only needs the *parent directory* to be writable, so a
1943
            // read-only file mode is safe for both overwrite-by-rename and
1944
            // eviction. Best-effort: a failure here (e.g. the temp file was
1945
            // already evicted out from under us) must not abort the emplace.
1946
            #[cfg(unix)]
1947
            {
1948
                use std::os::unix::fs::PermissionsExt;
1949
0
                if let Err(err) =
1950
2.33k
                    fs::set_permissions(&from_path, std::fs::Permissions::from_mode(0o444)).await
1951
                {
1952
0
                    warn!(?err, ?from_path, "Failed to set CAS blob read-only");
1953
2.33k
                }
1954
            }
1955
2.33k
            let result = (rename_fn)(&from_path, &final_path).err_tip(|| 
{2
1956
2
                format!(
1957
                    "Failed to rename temp file to final path {}",
1958
2
                    final_path.display()
1959
                )
1960
2
            });
1961
1962
2.33k
            if let Err(
err2
) = result {
1963
2
                error!(?err, ?from_path, ?final_path, "Failed to rename file",);
1964
                // This entry was never visible in the map. Drop cleans up its
1965
                // temporary file and the previous generation remains usable.
1966
2
                return Err(err);
1967
2.33k
            }
1968
2.33k
            trace!(?key, "Finished emplace file");
1969
2.33k
            encoded_file_path.path_type = PathType::Content;
1970
2.33k
            encoded_file_path.key = key.clone();
1971
            // Insertion can unref this entry immediately under cache pressure.
1972
2.33k
            drop(encoded_file_path);
1973
2.33k
            let (
inserted2.33k
, _) = evicting_map
1974
2.33k
                .insert_if(key.clone().into(), entry.clone(), |present, new| 
{12
1975
12
                    present.generation() < new.generation()
1976
12
                })
1977
2.33k
                .await;
1978
2.33k
            if !inserted {
1979
                // A newer upload completed first. Retire our unindexed content
1980
                // file too, so it cannot leak or reappear after a restart.
1981
1
                info!(%key, "Newer generation already emplaced, dropping");
1982
1
                entry.unref().await;
1983
2.33k
            }
1984
2.33k
            Ok(())
1985
2.34k
        })
1986
2.34k
        .await
1987
2.34k
        .err_tip(|| "Failed to create spawn in filesystem store update_file")
?0
1988
2.34k
    }
1989
1990
    /// Makes `file`'s contents durable with `sync_all` semantics.
1991
    ///
1992
    /// On macOS the naive equivalent (`fcntl(F_FULLFSYNC)` per file) is a
1993
    /// full device-cache flush that serializes at the device and dominates
1994
    /// many-small-blob uploads, so the flush is split into the cheap
1995
    /// per-file part (`fsync(2)`: push this file's pages to the device)
1996
    /// and a device-wide cache drain shared with every concurrent upload
1997
    /// via [`FlushCoalescer`]. Other platforms get their journal's group
1998
    /// commit for free and keep plain `sync_all`.
1999
2.07k
    async fn flush_durably(&self, file: &FileSlot) -> Result<(), Error> {
2000
        #[cfg(target_os = "macos")]
2001
        {
2002
            use std::os::fd::AsRawFd;
2003
            let Some(flush_coalescer) = &self.flush_coalescer else {
2004
                return file.as_ref().sync_all().await.map_err(Into::into);
2005
            };
2006
            // Dup the handle so the blocking task owns its own fd: if
2007
            // this future is cancelled mid-await, the temp file's fd can
2008
            // close and be reused, and an already-started blocking task
2009
            // must never fsync an unrelated descriptor.
2010
            let file_dup = file
2011
                .as_ref()
2012
                .try_clone()
2013
                .await
2014
                .err_tip(|| "Failed to dup fd for fsync in filesystem store")?
2015
                .into_std()
2016
                .await;
2017
            // Deliberately NOT via `fs::call_with_permit`: the caller's
2018
            // `FileSlot` already holds an open-file permit, so requiring a
2019
            // second one here deadlocks when the semaphore is drained (the
2020
            // exact scenario the #2051 regression test pins at one
2021
            // permit). Concurrency is still bounded: every in-flight fsync
2022
            // belongs to an upload holding a `FileSlot` permit.
2023
            spawn_blocking!("filesystem_store_fsync", move || {
2024
                loop {
2025
                    if unsafe { libc::fsync(file_dup.as_raw_fd()) } == 0 {
2026
                        return Ok(());
2027
                    }
2028
                    let err = std::io::Error::last_os_error();
2029
                    // std's sync_all retries EINTR (cvt_r); match it.
2030
                    if err.kind() != std::io::ErrorKind::Interrupted {
2031
                        return Err(Error::from(err).append("fsync failed in filesystem store"));
2032
                    }
2033
                }
2034
            })
2035
            .await
2036
            .err_tip(|| "Failed to join fsync task in filesystem store")??;
2037
            flush_coalescer.commit().await
2038
        }
2039
        #[cfg(not(target_os = "macos"))]
2040
        {
2041
2.07k
            file.as_ref().sync_all().await.map_err(Into::into)
2042
        }
2043
2.07k
    }
2044
2045
0
    pub fn get_eviction_snapshot(&self) -> EvictionSnapshot {
2046
0
        self.evicting_map.get_snapshot()
2047
0
    }
2048
2049
    // Only for tests, so we can run check_duplicate_files
2050
8
    pub fn get_evicting_map(&self) -> Arc<FsEvictingMap<'static, Fe>> {
2051
8
        self.evicting_map.clone()
2052
8
    }
2053
2054
    /// Returns the number of device-wide durability barriers issued by this
2055
    /// store's macOS flush coalescer. Exposed so the integration test can pin
2056
    /// the batching behavior rather than only checking data correctness.
2057
    #[cfg(target_os = "macos")]
2058
    pub fn full_flush_count_for_test(&self) -> Option<u64> {
2059
        self.flush_coalescer
2060
            .as_ref()
2061
            .map(|coalescer| coalescer.full_flush_count.load(Ordering::Relaxed))
2062
    }
2063
2064
    // Separated out so tests can use this
2065
2.08k
    pub async fn make_temp_file(
2066
2.08k
        &self,
2067
2.08k
        temp_key: StoreKey<'static>,
2068
2.08k
    ) -> Result<(Fe, FileSlot, OsString), Error> {
2069
2.08k
        let generation = self.get_and_update_generation()
?0
;
2070
2071
2.08k
        Fe::make_and_open_file(
2072
2.08k
            self.block_size,
2073
2.08k
            generation,
2074
2.08k
            EncodedFilePath {
2075
2.08k
                shared_context: self.shared_context.clone(),
2076
2.08k
                path_type: PathType::Temp,
2077
2.08k
                key: temp_key,
2078
2.08k
                generation,
2079
2.08k
                version: Version::V2,
2080
2.08k
            },
2081
2.08k
        )
2082
2.08k
        .await
2083
2.08k
    }
2084
}
2085
2086
#[async_trait]
2087
impl<Fe: FileEntry> StoreDriver for FilesystemStore<Fe> {
2088
0
    async fn post_init(self: Arc<Self>) -> Result<(), Error> {
2089
        Ok(())
2090
0
    }
2091
2092
9
    async fn remove(self: Pin<&Self>, key: StoreKey<'_>) -> Result<bool, Error> {
2093
        Ok(self.evicting_map.remove(&key.into_owned()).await)
2094
9
    }
2095
2096
    async fn has_with_results(
2097
        self: Pin<&Self>,
2098
        keys: &[StoreKey<'_>],
2099
        results: &mut [Option<u64>],
2100
2.86k
    ) -> Result<(), Error> {
2101
        let own_keys = keys
2102
            .iter()
2103
2.86k
            .map(|sk| sk.borrow().into_owned())
2104
            .collect::<Vec<_>>();
2105
        self.evicting_map
2106
            .sizes_for_keys(own_keys.iter(), results, false /* peek */)
2107
            .await;
2108
        // We need to do a special pass to ensure our zero files exist.
2109
        // If our results failed and the result was a zero file, we need to
2110
        // create the file by spec.
2111
        for (key, result) in keys.iter().zip(results.iter_mut()) {
2112
            if result.is_some() || !is_zero_digest(key.borrow()) {
2113
                continue;
2114
            }
2115
            let (mut tx, rx) = make_buf_channel_pair();
2116
            let send_eof_result = tx.send_eof();
2117
            self.update(key.borrow(), rx, UploadSizeInfo::ExactSize(0))
2118
                .await
2119
0
                .err_tip(|| format!("Failed to create zero file for key {}", key.as_str()))
2120
                .merge(
2121
                    send_eof_result
2122
                        .err_tip(|| "Failed to send zero file EOF in filesystem store has"),
2123
                )?;
2124
2125
            *result = Some(0);
2126
        }
2127
        Ok(())
2128
2.86k
    }
2129
2130
    async fn update(
2131
        self: Pin<&Self>,
2132
        key: StoreKey<'_>,
2133
        mut reader: DropCloserReadHalf,
2134
        upload_size: UploadSizeInfo,
2135
2.04k
    ) -> Result<u64, Error> {
2136
        if is_zero_digest(key.borrow()) {
2137
            let size = reader.drain().await?;
2138
            UploadSizeInfo::ExactSize(0).validate_size(size)?;
2139
            upload_size.validate_size(size)?;
2140
            return Ok(0);
2141
        }
2142
2143
        let temp_key = make_temp_key(&key);
2144
2145
        // There's a possibility of deadlock here where we take all of the
2146
        // file semaphores with make_and_open_file and the semaphores for
2147
        // whatever is populating reader is exhasted on the threads that
2148
        // have the FileSlots and not on those which can't.  To work around
2149
        // this we don't take the FileSlot until there's something on the
2150
        // reader available to know that the populator is active.
2151
        reader.peek().await?;
2152
2153
        let (entry, temp_file, temp_full_path) = self.make_temp_file(temp_key).await?;
2154
2155
        self.update_file(entry, temp_file, key.into_owned(), reader, upload_size)
2156
            .await
2157
6
            .err_tip(|| {
2158
6
                format!(
2159
                    "While processing with temp file {}",
2160
6
                    temp_full_path.display()
2161
                )
2162
6
            })
2163
2.04k
    }
2164
2165
2.23k
    fn optimized_for(&self, optimization: StoreOptimizations) -> bool {
2166
1.96k
        matches!(
2167
2.23k
            optimization,
2168
            StoreOptimizations::FileUpdates | StoreOptimizations::SubscribesToUpdateOneshot
2169
        )
2170
2.23k
    }
2171
2172
302
    async fn update_oneshot(self: Pin<&Self>, key: StoreKey<'_>, data: Bytes) -> Result<(), Error> {
2173
        if is_zero_digest(key.borrow()) {
2174
            UploadSizeInfo::ExactSize(0).validate_size(data.len() as u64)?;
2175
            return Ok(());
2176
        }
2177
2178
        let temp_key = make_temp_key(&key);
2179
        let (mut entry, mut temp_file, temp_full_path) = self
2180
            .make_temp_file(temp_key)
2181
            .await
2182
            .err_tip(|| "Failed to create temp file in filesystem store update_oneshot")?;
2183
2184
        // Write directly without channel overhead
2185
        if !data.is_empty() {
2186
            temp_file
2187
                .write_all(&data)
2188
                .await
2189
0
                .err_tip(|| format!("Failed to write data to {}", temp_full_path.display()))?;
2190
        }
2191
2192
        let _permit = if let Some(sem) = &self.write_semaphore {
2193
0
            Some(sem.acquire().await.map_err(|err| {
2194
0
                Error::from_std_err(Code::Internal, &err).append("Write semaphore closed")
2195
0
            })?)
2196
        } else {
2197
            None
2198
        };
2199
2200
        // See comment in `update_file` above.
2201
        temp_file
2202
            .flush()
2203
            .await
2204
            .err_tip(|| "Failed to flush in filesystem store update_oneshot")?;
2205
        self.flush_durably(&temp_file)
2206
            .await
2207
            .err_tip(|| "Failed to sync in filesystem store update_oneshot")?;
2208
2209
        drop(_permit);
2210
2211
        if self.evict_page_cache {
2212
            temp_file.advise_dontneed();
2213
        }
2214
        drop(temp_file);
2215
2216
        *entry.data_size_mut() = data.len() as u64;
2217
        self.emplace_file(key.into_owned(), Arc::new(entry)).await
2218
302
    }
2219
2220
    async fn update_with_whole_file(
2221
        self: Pin<&Self>,
2222
        key: StoreKey<'_>,
2223
        path: OsString,
2224
        mut file: FileSlot,
2225
        upload_size: UploadSizeInfo,
2226
277
    ) -> Result<(u64, Option<FileSlot>), Error> {
2227
        file.flush()
2228
            .await
2229
            .err_tip(|| "Flushing whole-file upload before checking its size")?;
2230
        let file_size = file
2231
            .as_ref()
2232
            .metadata()
2233
            .await
2234
0
            .err_tip(|| format!("While reading metadata for {}", path.display()))?
2235
            .len();
2236
        upload_size.validate_size(file_size)?;
2237
        if is_zero_digest(key.borrow()) {
2238
            UploadSizeInfo::ExactSize(0).validate_size(file_size)?;
2239
            // Empty CAS blobs are implicit; ordinary empty values still need a file.
2240
            return Ok((0, None));
2241
        }
2242
        let generation = self.get_and_update_generation()?;
2243
        let entry = Fe::create(
2244
            file_size,
2245
            self.block_size,
2246
            generation,
2247
            RwLock::new(EncodedFilePath {
2248
                shared_context: self.shared_context.clone(),
2249
                path_type: PathType::Custom(path),
2250
                key: key.borrow().into_owned(),
2251
                generation,
2252
                version: Version::V2,
2253
            }),
2254
        );
2255
        // We are done with the file, if we hold a reference to the file here, it could
2256
        // result in a deadlock if `emplace_file()` also needs file descriptors.
2257
        trace!(?file, "Dropping file to to update_with_whole_file");
2258
        if self.evict_page_cache {
2259
            file.advise_dontneed();
2260
        }
2261
        drop(file);
2262
        self.emplace_file(key.into_owned(), Arc::new(entry))
2263
            .await
2264
            .err_tip(|| "Could not move file into store in upload_file_to_store, maybe dest is on different volume?")?;
2265
        return Ok((file_size, None));
2266
277
    }
2267
2268
    async fn get_part(
2269
        self: Pin<&Self>,
2270
        key: StoreKey<'_>,
2271
        writer: &mut DropCloserWriteHalf,
2272
        offset: u64,
2273
        length: Option<u64>,
2274
862
    ) -> Result<(), Error> {
2275
        if is_zero_digest(key.borrow()) {
2276
            self.has(key.borrow())
2277
                .await
2278
                .err_tip(|| "Failed to check if zero digest exists in filesystem store")?;
2279
            writer
2280
                .send_eof()
2281
                .err_tip(|| "Failed to send zero EOF in filesystem store get_part")?;
2282
            return Ok(());
2283
        }
2284
        let owned_key = key.into_owned();
2285
2
        let entry = self.evicting_map.get(&owned_key).await.ok_or_else(|| {
2286
2
            make_err!(
2287
2
                Code::NotFound,
2288
                "{} not found in filesystem store here",
2289
2
                owned_key.as_str()
2290
            )
2291
2
        })?;
2292
        let read_limit = length.unwrap_or(u64::MAX);
2293
        let mut temp_file = match entry.read_file_part(offset, read_limit).await {
2294
            Ok(file) => file,
2295
            Err(err) => {
2296
                // If the file is not found, we need to remove it from the eviction map.
2297
                if err.code == Code::NotFound {
2298
                    // Map said the file was present but `open()` hit ENOENT.
2299
                    // Self-heals: we remove the stale entry below and a
2300
                    // fast/slow caller re-populates from the slow store, so
2301
                    // this is a recoverable warn, not a fatal error.
2302
                    warn!(
2303
                        ?err,
2304
                        key = ?owned_key,
2305
                        "Filesystem store map/disk divergence: removing entry; reader will fall through to slow store",
2306
                    );
2307
                    self.evicting_map
2308
5
                        .remove_if(&owned_key, |map_entry| Arc::ptr_eq(map_entry, &entry))
2309
                        .await;
2310
                }
2311
                return Err(err);
2312
            }
2313
        };
2314
2315
        loop {
2316
            let mut buf = BytesMut::with_capacity(self.read_buffer_size);
2317
            temp_file
2318
                .read_buf(&mut buf)
2319
                .await
2320
                .err_tip(|| "Failed to read data in filesystem store")?;
2321
            if buf.is_empty() {
2322
                break; // EOF.
2323
            }
2324
            writer
2325
                .send(buf.freeze())
2326
                .await
2327
                .err_tip(|| "Failed to send chunk in filesystem store get_part")?;
2328
        }
2329
        if self.evict_page_cache {
2330
            temp_file.get_ref().advise_dontneed();
2331
        }
2332
        writer
2333
            .send_eof()
2334
            .err_tip(|| "Filed to send EOF in filesystem store get_part")?;
2335
2336
        Ok(())
2337
862
    }
2338
2339
2.09k
    fn inner_store(&self, _digest: Option<StoreKey>) -> &dyn StoreDriver {
2340
2.09k
        self
2341
2.09k
    }
2342
2343
130
    fn as_any<'a>(&'a self) -> &'a (dyn core::any::Any + Sync + Send + 'static) {
2344
130
        self
2345
130
    }
2346
2347
0
    fn as_any_arc(self: Arc<Self>) -> Arc<dyn core::any::Any + Sync + Send + 'static> {
2348
0
        self
2349
0
    }
2350
2351
0
    fn register_health(self: Arc<Self>, registry: &mut HealthRegistryBuilder) {
2352
0
        registry.register_indicator(self);
2353
0
    }
2354
2355
0
    fn enable_cache_size_metrics(&self, attrs: &[opentelemetry::KeyValue]) -> bool {
2356
0
        self.evicting_map.enable_cache_size_metrics(attrs.to_vec());
2357
0
        true
2358
0
    }
2359
2360
0
    fn register_remove_callback(self: Arc<Self>, callback: RemoveCallback) -> Result<(), Error> {
2361
0
        self.evicting_map
2362
0
            .add_remove_callback(RemoveCallbackHolder::new(callback));
2363
0
        Ok(())
2364
0
    }
2365
}
2366
2367
#[async_trait]
2368
impl<Fe: FileEntry> HealthStatusIndicator for FilesystemStore<Fe> {
2369
0
    fn get_name(&self) -> &'static str {
2370
0
        "FilesystemStore"
2371
0
    }
2372
2373
    /// Lightweight probe: `stat()` the `content_path` directory. No
2374
    /// write-semaphore / eviction-map contention with production
2375
    /// traffic, and bounded so a hung NFS / EBS mount can't wedge the
2376
    /// indicator.
2377
2
    async fn check_health(&self, _namespace: Cow<'static, str>) -> HealthStatus {
2378
        const HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
2379
2380
        let content_path = &self.shared_context.content_path;
2381
        let stat = tokio::fs::metadata(&content_path);
2382
        match timeout(HEALTH_PROBE_TIMEOUT, stat).await {
2383
            Ok(Ok(meta)) if meta.is_dir() => {
2384
                HealthStatus::new_ok(self, "FilesystemStore::check_health: ok".into())
2385
            }
2386
            Ok(Ok(_)) => HealthStatus::new_failed(
2387
                self,
2388
                format!(
2389
                    "FilesystemStore::check_health: content_path {content_path} is not a directory"
2390
                )
2391
                .into(),
2392
            ),
2393
            Ok(Err(e)) => {
2394
                warn!(
2395
                    ?e,
2396
                    %content_path,
2397
                    "FilesystemStore::check_health: stat errored",
2398
                );
2399
                HealthStatus::new_failed(
2400
                    self,
2401
                    format!("FilesystemStore::check_health: stat errored: {e}").into(),
2402
                )
2403
            }
2404
            Err(_) => {
2405
                warn!(
2406
                    %content_path,
2407
                    timeout_secs = HEALTH_PROBE_TIMEOUT.as_secs(),
2408
                    "FilesystemStore::check_health: stat timed out",
2409
                );
2410
                HealthStatus::Timeout {
2411
                    struct_name: self.struct_name(),
2412
                }
2413
            }
2414
        }
2415
2
    }
2416
}