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