Coverage Report

Created: 2025-12-16 15:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-store/src/memory_store.rs
Line
Count
Source
1
// Copyright 2024 The NativeLink Authors. 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::any::Any;
16
use core::borrow::Borrow;
17
use core::fmt::Debug;
18
use core::ops::Bound;
19
use core::pin::Pin;
20
use std::sync::Arc;
21
use std::time::SystemTime;
22
23
use async_trait::async_trait;
24
use bytes::{Bytes, BytesMut};
25
use nativelink_config::stores::MemorySpec;
26
use nativelink_error::{Code, Error, ResultExt};
27
use nativelink_metric::MetricsComponent;
28
use nativelink_util::buf_channel::{DropCloserReadHalf, DropCloserWriteHalf};
29
use nativelink_util::evicting_map::{EvictingMap, LenEntry};
30
use nativelink_util::health_utils::{
31
    HealthRegistryBuilder, HealthStatusIndicator, default_health_status_indicator,
32
};
33
use nativelink_util::store_trait::{
34
    RemoveItemCallback, StoreDriver, StoreKey, StoreKeyBorrow, StoreOptimizations, UploadSizeInfo,
35
};
36
37
use crate::callback_utils::RemoveItemCallbackHolder;
38
use crate::cas_utils::is_zero_digest;
39
40
#[derive(Clone)]
41
pub struct BytesWrapper(Bytes);
42
43
impl Debug for BytesWrapper {
44
0
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
45
0
        f.write_str("BytesWrapper { -- Binary data -- }")
46
0
    }
47
}
48
49
impl LenEntry for BytesWrapper {
50
    #[inline]
51
10.2k
    fn len(&self) -> u64 {
52
10.2k
        Bytes::len(&self.0) as u64
53
10.2k
    }
54
55
    #[inline]
56
0
    fn is_empty(&self) -> bool {
57
0
        Bytes::is_empty(&self.0)
58
0
    }
59
}
60
61
#[derive(Debug, MetricsComponent)]
62
pub struct MemoryStore {
63
    #[metric(group = "evicting_map")]
64
    evicting_map: EvictingMap<
65
        StoreKeyBorrow,
66
        StoreKey<'static>,
67
        BytesWrapper,
68
        SystemTime,
69
        RemoveItemCallbackHolder,
70
    >,
71
}
72
73
impl MemoryStore {
74
341
    pub fn new(spec: &MemorySpec) -> Arc<Self> {
75
341
        let empty_policy = nativelink_config::stores::EvictionPolicy::default();
76
341
        let eviction_policy = spec.eviction_policy.as_ref().unwrap_or(&empty_policy);
77
341
        Arc::new(Self {
78
341
            evicting_map: EvictingMap::new(eviction_policy, SystemTime::now()),
79
341
        })
80
341
    }
81
82
    /// Returns the number of key-value pairs that are currently in the the cache.
83
    /// Function is not for production code paths.
84
30
    pub fn len_for_test(&self) -> usize {
85
30
        self.evicting_map.len_for_test()
86
30
    }
87
88
8
    pub async fn remove_entry(&self, key: StoreKey<'_>) -> bool {
89
8
        self.evicting_map.remove(&key.into_owned()).await
90
8
    }
91
}
92
93
#[async_trait]
94
impl StoreDriver for MemoryStore {
95
    async fn has_with_results(
96
        self: Pin<&Self>,
97
        keys: &[StoreKey<'_>],
98
        results: &mut [Option<u64>],
99
196
    ) -> Result<(), Error> {
100
        let own_keys = keys
101
            .iter()
102
230
            .map(|sk| sk.borrow().into_owned())
103
            .collect::<Vec<_>>();
104
        self.evicting_map
105
            .sizes_for_keys(own_keys.iter(), results, false /* peek */)
106
            .await;
107
        // We need to do a special pass to ensure our zero digest exist.
108
        keys.iter()
109
            .zip(results.iter_mut())
110
230
            .for_each(|(key, result)| {
111
230
                if is_zero_digest(key.borrow()) {
  Branch (111:20): [True: 3, False: 227]
  Branch (111:20): [Folded - Ignored]
112
3
                    *result = Some(0);
113
227
                }
114
230
            });
115
        Ok(())
116
196
    }
117
118
    async fn list(
119
        self: Pin<&Self>,
120
        range: (Bound<StoreKey<'_>>, Bound<StoreKey<'_>>),
121
        handler: &mut (dyn for<'a> FnMut(&'a StoreKey) -> bool + Send + Sync + '_),
122
7
    ) -> Result<u64, Error> {
123
        let range = (
124
            range.0.map(StoreKey::into_owned),
125
            range.1.map(StoreKey::into_owned),
126
        );
127
        let iterations = self
128
            .evicting_map
129
13
            .range(range, move |key, _value| handler(key.borrow()));
130
        Ok(iterations)
131
7
    }
132
133
    async fn update(
134
        self: Pin<&Self>,
135
        key: StoreKey<'_>,
136
        mut reader: DropCloserReadHalf,
137
        _size_info: UploadSizeInfo,
138
5.14k
    ) -> Result<(), Error> {
139
        // Internally Bytes might hold a reference to more data than just our data. To prevent
140
        // this potential case, we make a full copy of our data for long-term storage.
141
        let final_buffer = {
142
            let buffer = reader
143
                .consume(None)
144
                .await
145
                .err_tip(|| "Failed to collect all bytes from reader in memory_store::update")?;
146
            let mut new_buffer = BytesMut::with_capacity(buffer.len());
147
            new_buffer.extend_from_slice(&buffer[..]);
148
            new_buffer.freeze()
149
        };
150
151
        self.evicting_map
152
            .insert(key.into_owned().into(), BytesWrapper(final_buffer))
153
            .await;
154
        Ok(())
155
5.14k
    }
156
157
141
    fn optimized_for(&self, optimization: StoreOptimizations) -> bool {
158
141
        optimization == StoreOptimizations::SubscribesToUpdateOneshot
159
141
    }
160
161
626
    async fn update_oneshot(self: Pin<&Self>, key: StoreKey<'_>, data: Bytes) -> Result<(), Error> {
162
        // Fast path: Direct insertion without channel overhead.
163
        // We still need to copy the data to prevent holding references to larger buffers.
164
        let final_buffer = if data.is_empty() {
165
            data
166
        } else {
167
            let mut new_buffer = BytesMut::with_capacity(data.len());
168
            new_buffer.extend_from_slice(&data[..]);
169
            new_buffer.freeze()
170
        };
171
172
        self.evicting_map
173
            .insert(key.into_owned().into(), BytesWrapper(final_buffer))
174
            .await;
175
        Ok(())
176
626
    }
177
178
    async fn get_part(
179
        self: Pin<&Self>,
180
        key: StoreKey<'_>,
181
        writer: &mut DropCloserWriteHalf,
182
        offset: u64,
183
        length: Option<u64>,
184
4.37k
    ) -> Result<(), Error> {
185
        let offset = usize::try_from(offset).err_tip(|| "Could not convert offset to usize")?;
186
        let length = length
187
54
            .map(|v| usize::try_from(v).err_tip(|| "Could not convert length to usize"))
188
            .transpose()?;
189
190
        let owned_key = key.into_owned();
191
        if is_zero_digest(owned_key.clone()) {
192
            writer
193
                .send_eof()
194
                .err_tip(|| "Failed to send zero EOF in filesystem store get_part")?;
195
            return Ok(());
196
        }
197
198
        let value = self
199
            .evicting_map
200
            .get(&owned_key)
201
            .await
202
8
            .err_tip_with_code(|_| (Code::NotFound, format!("Key {owned_key:?} not found")))?;
203
        let default_len = usize::try_from(value.len())
204
            .err_tip(|| "Could not convert value.len() to usize")?
205
            .saturating_sub(offset);
206
        let length = length.unwrap_or(default_len).min(default_len);
207
        if length > 0 {
208
            writer
209
                .send(value.0.slice(offset..(offset + length)))
210
                .await
211
                .err_tip(|| "Failed to write data in memory store")?;
212
        }
213
        writer
214
            .send_eof()
215
            .err_tip(|| "Failed to write EOF in memory store get_part")?;
216
        Ok(())
217
4.37k
    }
218
219
166
    fn inner_store(&self, _digest: Option<StoreKey>) -> &dyn StoreDriver {
220
166
        self
221
166
    }
222
223
39
    fn as_any<'a>(&'a self) -> &'a (dyn Any + Sync + Send + 'static) {
224
39
        self
225
39
    }
226
227
0
    fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any + Sync + Send + 'static> {
228
0
        self
229
0
    }
230
231
0
    fn register_health(self: Arc<Self>, registry: &mut HealthRegistryBuilder) {
232
0
        registry.register_indicator(self);
233
0
    }
234
235
5
    fn register_remove_callback(
236
5
        self: Arc<Self>,
237
5
        callback: Arc<dyn RemoveItemCallback>,
238
5
    ) -> Result<(), Error> {
239
5
        self.evicting_map
240
5
            .add_remove_callback(RemoveItemCallbackHolder::new(callback));
241
5
        Ok(())
242
5
    }
243
}
244
245
default_health_status_indicator!(MemoryStore);