/build/source/nativelink-store/src/memory_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::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 | | RemoveCallback, StoreDriver, StoreKey, StoreKeyBorrow, StoreOptimizations, UploadSizeInfo, |
35 | | }; |
36 | | use tracing::warn; |
37 | | |
38 | | use crate::callback_utils::RemoveCallbackHolder; |
39 | | use crate::cas_utils::is_zero_digest; |
40 | | |
41 | | #[derive(Clone)] |
42 | | pub struct BytesWrapper(Bytes); |
43 | | |
44 | | impl Debug for BytesWrapper { |
45 | 0 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
46 | 0 | f.write_str("BytesWrapper { -- Binary data -- }") |
47 | 0 | } |
48 | | } |
49 | | |
50 | | impl LenEntry for BytesWrapper { |
51 | | #[inline] |
52 | 234k | fn len(&self) -> u64 { |
53 | 234k | Bytes::len(&self.0) as u64 |
54 | 234k | } |
55 | | |
56 | | #[inline] |
57 | 0 | fn is_empty(&self) -> bool { |
58 | 0 | Bytes::is_empty(&self.0) |
59 | 0 | } |
60 | | } |
61 | | |
62 | | #[derive(Debug, MetricsComponent)] |
63 | | pub struct MemoryStore { |
64 | | #[metric(group = "evicting_map")] |
65 | | evicting_map: EvictingMap< |
66 | | StoreKeyBorrow, |
67 | | StoreKey<'static>, |
68 | | BytesWrapper, |
69 | | SystemTime, |
70 | | RemoveCallbackHolder, |
71 | | >, |
72 | | /// The eviction policy's `max_bytes` (0 = unbounded). Cached here so `update` |
73 | | /// can skip writes larger than the entire store budget without buffering |
74 | | /// them — see the note in `update`. |
75 | | #[metric(help = "Maximum bytes this store will hold before eviction (0 = unbounded)")] |
76 | | max_bytes: u64, |
77 | | } |
78 | | |
79 | | impl MemoryStore { |
80 | 932 | pub fn new(spec: &MemorySpec) -> Arc<Self> { |
81 | 932 | let empty_policy = nativelink_config::stores::EvictionPolicy::default(); |
82 | 932 | let eviction_policy = spec.eviction_policy.as_ref().unwrap_or(&empty_policy); |
83 | 932 | Arc::new(Self { |
84 | 932 | max_bytes: eviction_policy.max_bytes as u64, |
85 | 932 | evicting_map: EvictingMap::new(eviction_policy, SystemTime::now()), |
86 | 932 | }) |
87 | 932 | } |
88 | | |
89 | | /// Returns the number of key-value pairs that are currently in the the cache. |
90 | | /// Function is not for production code paths. |
91 | 33 | pub fn len_for_test(&self) -> usize { |
92 | 33 | self.evicting_map.len_for_test() |
93 | 33 | } |
94 | | |
95 | 48 | pub async fn remove_entry(&self, key: StoreKey<'_>) -> bool { |
96 | 48 | self.evicting_map.remove(&key.into_owned()).await |
97 | 48 | } |
98 | | } |
99 | | |
100 | | #[async_trait] |
101 | | impl StoreDriver for MemoryStore { |
102 | 10 | async fn post_init(self: Arc<Self>) -> Result<(), Error> { |
103 | | Ok(()) |
104 | 10 | } |
105 | | |
106 | 34 | async fn remove(self: Pin<&Self>, key: StoreKey<'_>) -> Result<bool, Error> { |
107 | | Ok(self.remove_entry(key).await) |
108 | 34 | } |
109 | | |
110 | | async fn has_with_results( |
111 | | self: Pin<&Self>, |
112 | | keys: &[StoreKey<'_>], |
113 | | results: &mut [Option<u64>], |
114 | 18.5k | ) -> Result<(), Error> { |
115 | | let own_keys = keys |
116 | | .iter() |
117 | 34.8k | .map(|sk| sk.borrow().into_owned()) |
118 | | .collect::<Vec<_>>(); |
119 | | self.evicting_map |
120 | | .sizes_for_keys(own_keys.iter(), results, false /* peek */) |
121 | | .await; |
122 | | // We need to do a special pass to ensure our zero digest exist. |
123 | | keys.iter() |
124 | | .zip(results.iter_mut()) |
125 | 34.8k | .for_each(|(key, result)| { |
126 | 34.8k | if is_zero_digest(key.borrow()) { |
127 | 16.2k | *result = Some(0); |
128 | 18.6k | } |
129 | 34.8k | }); |
130 | | Ok(()) |
131 | 18.5k | } |
132 | | |
133 | | async fn list( |
134 | | self: Pin<&Self>, |
135 | | range: (Bound<StoreKey<'_>>, Bound<StoreKey<'_>>), |
136 | | handler: &mut (dyn for<'a> FnMut(&'a StoreKey) -> bool + Send + Sync + '_), |
137 | 13 | ) -> Result<u64, Error> { |
138 | | let range = ( |
139 | | range.0.map(StoreKey::into_owned), |
140 | | range.1.map(StoreKey::into_owned), |
141 | | ); |
142 | | let iterations = self |
143 | | .evicting_map |
144 | 166 | .range(range, move |key, _value| handler(key.borrow())); |
145 | | Ok(iterations) |
146 | 13 | } |
147 | | |
148 | | async fn update( |
149 | | self: Pin<&Self>, |
150 | | key: StoreKey<'_>, |
151 | | mut reader: DropCloserReadHalf, |
152 | | size_info: UploadSizeInfo, |
153 | 5.77k | ) -> Result<u64, Error> { |
154 | | // A write whose exact size is at least this store's `max_bytes` can never |
155 | | // be usefully cached: the moment it's inserted, eviction drops it, since one |
156 | | // entry alone meets the budget. Buffering it into memory first is therefore |
157 | | // pure waste — and under concurrent large writes (e.g. a `memory` fast tier |
158 | | // inside a `fast_slow` store fronting CAS) it is a real OOM vector, because |
159 | | // each in-flight write materializes its whole payload before eviction ever |
160 | | // runs. Drain the stream and skip instead. |
161 | | // |
162 | | // `>=` deliberately matches the eviction comparator: `EvictingMap` evicts |
163 | | // while `sum_store_size >= max_bytes`, so a blob of exactly `max_bytes` is |
164 | | // also unstorable and must be skipped rather than buffered-then-evicted. |
165 | | // Only `ExactSize` is trusted; a `MaxSize` upper bound could over-estimate |
166 | | // and wrongly skip a blob that would actually fit. |
167 | | // |
168 | | // For CAS digest keys the size is part of the key, so a given key is either |
169 | | // always oversized or never — there is no "small write for this key" that the |
170 | | // removal callbacks fired below could spuriously invalidate. |
171 | | if self.max_bytes != 0 |
172 | | && let UploadSizeInfo::ExactSize(sz) = size_info |
173 | | && sz >= self.max_bytes |
174 | | { |
175 | | let drained = reader |
176 | | .drain() |
177 | | .await |
178 | | .err_tip(|| "Failed to drain oversized write in memory_store::update")?; |
179 | | size_info.validate_size(drained)?; |
180 | | warn!( |
181 | | ?key, |
182 | | size = sz, |
183 | | max_bytes = self.max_bytes, |
184 | | "Write is larger than this memory store's max_bytes; skipping it \ |
185 | | (it would be evicted immediately). If this store is a cache, large \ |
186 | | blobs are served from the backing store — raise max_bytes to cache \ |
187 | | them, or route large blobs around the memory tier.", |
188 | | ); |
189 | | // The write never enters the map, so the insert-then-evict removal |
190 | | // callbacks (which a wrapping `ExistenceCacheStore` relies on to drop |
191 | | // a just-written-then-evicted key) don't fire on their own. Fire them |
192 | | // explicitly so downstream listeners don't keep a stale "exists" |
193 | | // entry for a blob we didn't store. |
194 | | let owned_key = key.into_owned(); |
195 | | self.evicting_map.fire_remove_callbacks(&owned_key).await; |
196 | | return Ok(drained); |
197 | | } |
198 | | // Internally Bytes might hold a reference to more data than just our data. To prevent |
199 | | // this potential case, we make a full copy of our data for long-term storage. |
200 | | let final_buffer = { |
201 | | let buffer = reader |
202 | | .consume(None) |
203 | | .await |
204 | | .err_tip(|| "Failed to collect all bytes from reader in memory_store::update")?; |
205 | | let mut new_buffer = BytesMut::with_capacity(buffer.len()); |
206 | | new_buffer.extend_from_slice(&buffer[..]); |
207 | | new_buffer.freeze() |
208 | | }; |
209 | | |
210 | | let len = final_buffer.len().try_into().unwrap_or(0); |
211 | | size_info.validate_size(len)?; |
212 | | self.evicting_map |
213 | | .insert(key.into_owned().into(), BytesWrapper(final_buffer)) |
214 | | .await; |
215 | | Ok(len) |
216 | 5.77k | } |
217 | | |
218 | 795 | fn optimized_for(&self, optimization: StoreOptimizations) -> bool { |
219 | 795 | optimization == StoreOptimizations::SubscribesToUpdateOneshot |
220 | 795 | } |
221 | | |
222 | 50.8k | async fn update_oneshot(self: Pin<&Self>, key: StoreKey<'_>, data: Bytes) -> Result<(), Error> { |
223 | | // Fast path: Direct insertion without channel overhead. |
224 | | // We still need to copy the data to prevent holding references to larger buffers. |
225 | | let final_buffer = if data.is_empty() { |
226 | | data |
227 | | } else { |
228 | | let mut new_buffer = BytesMut::with_capacity(data.len()); |
229 | | new_buffer.extend_from_slice(&data[..]); |
230 | | new_buffer.freeze() |
231 | | }; |
232 | | |
233 | | self.evicting_map |
234 | | .insert(key.into_owned().into(), BytesWrapper(final_buffer)) |
235 | | .await; |
236 | | Ok(()) |
237 | 50.8k | } |
238 | | |
239 | | async fn get_part( |
240 | | self: Pin<&Self>, |
241 | | key: StoreKey<'_>, |
242 | | writer: &mut DropCloserWriteHalf, |
243 | | offset: u64, |
244 | | length: Option<u64>, |
245 | 38.7k | ) -> Result<(), Error> { |
246 | | let offset = usize::try_from(offset).err_tip(|| "Could not convert offset to usize")?; |
247 | | let length = length |
248 | 32.5k | .map(|v| usize::try_from(v).err_tip(|| "Could not convert length to usize")) |
249 | | .transpose()?; |
250 | | |
251 | | let owned_key = key.into_owned(); |
252 | | if is_zero_digest(owned_key.clone()) { |
253 | | writer |
254 | | .send_eof() |
255 | | .err_tip(|| "Failed to send zero EOF in filesystem store get_part")?; |
256 | | return Ok(()); |
257 | | } |
258 | | |
259 | | let value = self |
260 | | .evicting_map |
261 | | .get(&owned_key) |
262 | | .await |
263 | 74 | .err_tip_with_code(|_| (Code::NotFound, format!("Key {owned_key:?} not found")))?; |
264 | | let default_len = usize::try_from(value.len()) |
265 | | .err_tip(|| "Could not convert value.len() to usize")? |
266 | | .saturating_sub(offset); |
267 | | let length = length.unwrap_or(default_len).min(default_len); |
268 | | if length > 0 { |
269 | | writer |
270 | | .send(value.0.slice(offset..(offset + length))) |
271 | | .await |
272 | | .err_tip(|| "Failed to write data in memory store")?; |
273 | | } |
274 | | writer |
275 | | .send_eof() |
276 | | .err_tip(|| "Failed to write EOF in memory store get_part")?; |
277 | | Ok(()) |
278 | 38.7k | } |
279 | | |
280 | 897 | fn inner_store(&self, _digest: Option<StoreKey>) -> &dyn StoreDriver { |
281 | 897 | self |
282 | 897 | } |
283 | | |
284 | 121 | fn as_any<'a>(&'a self) -> &'a (dyn Any + Sync + Send + 'static) { |
285 | 121 | self |
286 | 121 | } |
287 | | |
288 | 0 | fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any + Sync + Send + 'static> { |
289 | 0 | self |
290 | 0 | } |
291 | | |
292 | 0 | fn register_health(self: Arc<Self>, registry: &mut HealthRegistryBuilder) { |
293 | 0 | registry.register_indicator(self); |
294 | 0 | } |
295 | | |
296 | 4 | fn enable_cache_size_metrics(&self, attrs: &[opentelemetry::KeyValue]) -> bool { |
297 | 4 | self.evicting_map.enable_cache_size_metrics(attrs.to_vec()); |
298 | 4 | true |
299 | 4 | } |
300 | | |
301 | 7 | fn register_remove_callback(self: Arc<Self>, callback: RemoveCallback) -> Result<(), Error> { |
302 | 7 | self.evicting_map |
303 | 7 | .add_remove_callback(RemoveCallbackHolder::new(callback)); |
304 | 7 | Ok(()) |
305 | 7 | } |
306 | | } |
307 | | |
308 | | default_health_status_indicator!(MemoryStore); |