Coverage Report

Created: 2024-11-22 20:17

/build/source/nativelink-store/src/memory_store.rs
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2024 The NativeLink Authors. All rights reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (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
//    http://www.apache.org/licenses/LICENSE-2.0
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 std::fmt::Debug;
16
use std::ops::Bound;
17
use std::pin::Pin;
18
use std::sync::Arc;
19
use std::time::SystemTime;
20
21
use async_trait::async_trait;
22
use bytes::{Bytes, BytesMut};
23
use nativelink_config::stores::MemorySpec;
24
use nativelink_error::{Code, Error, ResultExt};
25
use nativelink_metric::MetricsComponent;
26
use nativelink_util::buf_channel::{DropCloserReadHalf, DropCloserWriteHalf};
27
use nativelink_util::evicting_map::{EvictingMap, LenEntry};
28
use nativelink_util::health_utils::{default_health_status_indicator, HealthStatusIndicator};
29
use nativelink_util::store_trait::{StoreDriver, StoreKey, UploadSizeInfo};
30
31
use crate::cas_utils::is_zero_digest;
32
33
#[derive(Clone)]
34
pub struct BytesWrapper(Bytes);
35
36
impl Debug for BytesWrapper {
37
0
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38
0
        f.write_str("BytesWrapper { -- Binary data -- }")
39
0
    }
40
}
41
42
impl LenEntry for BytesWrapper {
43
    #[inline]
44
10.2k
    fn len(&self) -> u64 {
45
10.2k
        Bytes::len(&self.0) as u64
46
10.2k
    }
47
48
    #[inline]
49
0
    fn is_empty(&self) -> bool {
50
0
        Bytes::is_empty(&self.0)
51
0
    }
52
}
53
54
0
#[derive(MetricsComponent)]
55
pub struct MemoryStore {
56
    #[metric(group = "evicting_map")]
57
    evicting_map: EvictingMap<StoreKey<'static>, BytesWrapper, SystemTime>,
58
}
59
60
impl MemoryStore {
61
300
    pub fn new(spec: &MemorySpec) -> Arc<Self> {
62
300
        let empty_policy = nativelink_config::stores::EvictionPolicy::default();
63
300
        let eviction_policy = spec.eviction_policy.as_ref().unwrap_or(&empty_policy);
64
300
        Arc::new(Self {
65
300
            evicting_map: EvictingMap::new(eviction_policy, SystemTime::now()),
66
300
        })
67
300
    }
68
69
    /// Returns the number of key-value pairs that are currently in the the cache.
70
    /// Function is not for production code paths.
71
30
    pub async fn len_for_test(&self) -> usize {
72
30
        self.evicting_map.len_for_test().
await0
73
30
    }
74
75
8
    pub async fn remove_entry(&self, key: StoreKey<'_>) -> bool {
76
8
        self.evicting_map.remove(&key.into_owned()).
await0
77
8
    }
78
}
79
80
#[async_trait]
81
impl StoreDriver for MemoryStore {
82
    async fn has_with_results(
83
        self: Pin<&Self>,
84
        keys: &[StoreKey<'_>],
85
        results: &mut [Option<u64>],
86
183
    ) -> Result<(), Error> {
87
        // TODO(allada): This is a dirty hack to get around the lifetime issues with the
88
        // evicting map.
89
225
        let 
digests: Vec<_> = keys.iter().map(183
|key| key.borrow().into_owned()).collect();
90
183
        self.evicting_map
91
183
            .sizes_for_keys(digests, results, false /* peek */)
92
0
            .await;
93
        // We need to do a special pass to ensure our zero digest exist.
94
183
        keys.iter()
95
183
            .zip(results.iter_mut())
96
225
            .for_each(|(key, result)| {
97
225
                if is_zero_digest(key.borrow()) {
  Branch (97:20): [True: 1, False: 224]
  Branch (97:20): [Folded - Ignored]
98
1
                    *result = Some(0);
99
224
                }
100
225
            });
101
183
        Ok(())
102
366
    }
103
104
    async fn list(
105
        self: Pin<&Self>,
106
        range: (Bound<StoreKey<'_>>, Bound<StoreKey<'_>>),
107
        handler: &mut (dyn for<'a> FnMut(&'a StoreKey) -> bool + Send + Sync + '_),
108
7
    ) -> Result<u64, Error> {
109
7
        let range = (
110
7
            range.0.map(StoreKey::into_owned),
111
7
            range.1.map(StoreKey::into_owned),
112
7
        );
113
7
        let iterations = self
114
7
            .evicting_map
115
13
            .range(range, move |key, _value| handler(key)
)7
116
0
            .await;
117
7
        Ok(iterations)
118
14
    }
119
120
    async fn update(
121
        self: Pin<&Self>,
122
        key: StoreKey<'_>,
123
        mut reader: DropCloserReadHalf,
124
        _size_info: UploadSizeInfo,
125
5.71k
    ) -> Result<(), Error> {
126
        // Internally Bytes might hold a reference to more data than just our data. To prevent
127
        // this potential case, we make a full copy of our data for long-term storage.
128
5.71k
        let final_buffer = {
129
5.71k
            let buffer = reader
130
5.71k
                .consume(None)
131
360
                .await
132
5.71k
                .err_tip(|| 
"Failed to collect all bytes from reader in memory_store::update"4
)
?4
;
133
5.71k
            let mut new_buffer = BytesMut::with_capacity(buffer.len());
134
5.71k
            new_buffer.extend_from_slice(&buffer[..]);
135
5.71k
            new_buffer.freeze()
136
5.71k
        };
137
5.71k
138
5.71k
        self.evicting_map
139
5.71k
            .insert(key.borrow().into_owned(), BytesWrapper(final_buffer))
140
0
            .await;
141
5.71k
        Ok(())
142
11.4k
    }
143
144
    async fn get_part(
145
        self: Pin<&Self>,
146
        key: StoreKey<'_>,
147
        writer: &mut DropCloserWriteHalf,
148
        offset: u64,
149
        length: Option<u64>,
150
4.46k
    ) -> Result<(), Error> {
151
4.46k
        let offset = usize::try_from(offset).err_tip(|| 
"Could not convert offset to usize"0
)
?0
;
152
4.46k
        let length = length
153
4.46k
            .map(|v| 
usize::try_from(v).err_tip(52
||
"Could not convert length to usize"0
)52
)
154
4.46k
            .transpose()
?0
;
155
156
4.46k
        if is_zero_digest(key.borrow()) {
  Branch (156:12): [True: 1, False: 4.45k]
  Branch (156:12): [Folded - Ignored]
157
1
            writer
158
1
                .send_eof()
159
1
                .err_tip(|| 
"Failed to send zero EOF in filesystem store get_part"0
)
?0
;
160
1
            return Ok(());
161
4.45k
        }
162
163
4.45k
        let 
value4.45k
= self
164
4.45k
            .evicting_map
165
4.45k
            .get(&key.borrow().into_owned())
166
0
            .await
167
4.45k
            .err_tip_with_code(|_| 
(Code::NotFound, format!("Key {key:?} not found"))7
)
?7
;
168
4.45k
        let default_len = usize::try_from(value.len())
169
4.45k
            .err_tip(|| 
"Could not convert value.len() to usize"0
)
?0
170
4.45k
            .saturating_sub(offset);
171
4.45k
        let length = length.unwrap_or(default_len).min(default_len);
172
4.45k
        if length > 0 {
  Branch (172:12): [True: 4.44k, False: 3]
  Branch (172:12): [Folded - Ignored]
173
4.44k
            writer
174
4.44k
                .send(value.0.slice(offset..(offset + length)))
175
0
                .await
176
4.44k
                .err_tip(|| 
"Failed to write data in memory store"0
)
?0
;
177
3
        }
178
4.45k
        writer
179
4.45k
            .send_eof()
180
4.45k
            .err_tip(|| 
"Failed to write EOF in memory store get_part"0
)
?0
;
181
4.45k
        Ok(())
182
8.92k
    }
183
184
83
    fn inner_store(&self, _digest: Option<StoreKey>) -> &dyn StoreDriver {
185
83
        self
186
83
    }
187
188
38
    fn as_any<'a>(&'a self) -> &'a (dyn std::any::Any + Sync + Send + 'static) {
189
38
        self
190
38
    }
191
192
0
    fn as_any_arc(self: Arc<Self>) -> Arc<dyn std::any::Any + Sync + Send + 'static> {
193
0
        self
194
0
    }
195
}
196
197
default_health_status_indicator!(MemoryStore);