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