/build/source/nativelink-store/src/dedup_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::cmp; |
16 | | use core::pin::Pin; |
17 | | use std::sync::Arc; |
18 | | |
19 | | use async_trait::async_trait; |
20 | | use futures::stream::{self, FuturesOrdered, StreamExt, TryStreamExt}; |
21 | | use futures::try_join; |
22 | | use nativelink_config::stores::DedupSpec; |
23 | | use nativelink_error::{Code, Error, ResultExt, make_err}; |
24 | | use nativelink_metric::MetricsComponent; |
25 | | use nativelink_util::buf_channel::{DropCloserReadHalf, DropCloserWriteHalf}; |
26 | | use nativelink_util::common::DigestInfo; |
27 | | use nativelink_util::fastcdc::FastCDC; |
28 | | use nativelink_util::health_utils::{HealthStatusIndicator, default_health_status_indicator}; |
29 | | use nativelink_util::store_trait::{ |
30 | | RemoveCallback, Store, StoreDriver, StoreKey, StoreLike, UploadSizeInfo, |
31 | | }; |
32 | | use serde::{Deserialize, Serialize}; |
33 | | use tokio_util::codec::FramedRead; |
34 | | use tokio_util::io::StreamReader; |
35 | | use tracing::warn; |
36 | | |
37 | | use crate::cas_utils::is_zero_digest; |
38 | | use crate::compression_store::WincodeConfig; |
39 | | |
40 | | // NOTE: If these change update the comments in `stores.rs` to reflect |
41 | | // the new defaults. |
42 | | const DEFAULT_MIN_SIZE: u64 = 64 * 1024; |
43 | | const DEFAULT_NORM_SIZE: u64 = 256 * 1024; |
44 | | const DEFAULT_MAX_SIZE: u64 = 512 * 1024; |
45 | | const DEFAULT_MAX_CONCURRENT_FETCH_PER_GET: usize = 10; |
46 | | |
47 | | #[derive( |
48 | | Serialize, |
49 | | Deserialize, |
50 | | PartialEq, |
51 | | Eq, |
52 | | Debug, |
53 | | Default, |
54 | | Clone, |
55 | | wincode::SchemaRead, |
56 | 0 | wincode::SchemaWrite, |
57 | | )] |
58 | | pub struct DedupIndex { |
59 | | pub entries: Vec<DigestInfo>, |
60 | | } |
61 | | |
62 | | #[derive(MetricsComponent)] |
63 | | pub struct DedupStore { |
64 | | #[metric(group = "index_store")] |
65 | | index_store: Store, |
66 | | #[metric(group = "content_store")] |
67 | | content_store: Store, |
68 | | fast_cdc_decoder: FastCDC, |
69 | | #[metric(help = "Maximum number of concurrent fetches per get")] |
70 | | max_concurrent_fetch_per_get: usize, |
71 | | wincode_config: WincodeConfig, |
72 | | } |
73 | | |
74 | | impl core::fmt::Debug for DedupStore { |
75 | 0 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
76 | 0 | f.debug_struct("DedupStore") |
77 | 0 | .field("index_store", &self.index_store) |
78 | 0 | .field("content_store", &self.content_store) |
79 | 0 | .field("fast_cdc_decoder", &self.fast_cdc_decoder) |
80 | 0 | .field( |
81 | 0 | "max_concurrent_fetch_per_get", |
82 | 0 | &self.max_concurrent_fetch_per_get, |
83 | 0 | ) |
84 | 0 | .finish_non_exhaustive() |
85 | 0 | } |
86 | | } |
87 | | |
88 | | impl DedupStore { |
89 | 8 | pub fn new( |
90 | 8 | spec: &DedupSpec, |
91 | 8 | index_store: Store, |
92 | 8 | content_store: Store, |
93 | 8 | ) -> Result<Arc<Self>, Error> { |
94 | 8 | let min_size = if spec.min_size == 0 { |
95 | 0 | DEFAULT_MIN_SIZE |
96 | | } else { |
97 | 8 | u64::from(spec.min_size) |
98 | | }; |
99 | 8 | let normal_size = if spec.normal_size == 0 { |
100 | 0 | DEFAULT_NORM_SIZE |
101 | | } else { |
102 | 8 | u64::from(spec.normal_size) |
103 | | }; |
104 | 8 | let max_size = if spec.max_size == 0 { |
105 | 0 | DEFAULT_MAX_SIZE |
106 | | } else { |
107 | 8 | u64::from(spec.max_size) |
108 | | }; |
109 | 8 | let max_concurrent_fetch_per_get = if spec.max_concurrent_fetch_per_get == 0 { |
110 | 0 | DEFAULT_MAX_CONCURRENT_FETCH_PER_GET |
111 | | } else { |
112 | 8 | spec.max_concurrent_fetch_per_get as usize |
113 | | }; |
114 | 8 | Ok(Arc::new(Self { |
115 | 8 | index_store, |
116 | 8 | content_store, |
117 | 8 | fast_cdc_decoder: FastCDC::new( |
118 | 8 | usize::try_from(min_size).err_tip(|| "Could not convert min_size to usize")?0 , |
119 | 8 | usize::try_from(normal_size) |
120 | 8 | .err_tip(|| "Could not convert normal_size to usize")?0 , |
121 | 8 | usize::try_from(max_size).err_tip(|| "Could not convert max_size to usize")?0 , |
122 | | ), |
123 | 8 | max_concurrent_fetch_per_get, |
124 | 8 | wincode_config: WincodeConfig::new(), |
125 | | })) |
126 | 8 | } |
127 | | |
128 | 4 | async fn has(self: Pin<&Self>, key: StoreKey<'_>) -> Result<Option<u64>, Error> { |
129 | | // First we need to load the index that contains where the individual parts actually |
130 | | // can be fetched from. |
131 | 3 | let index_entries = { |
132 | 4 | let maybe_data = self |
133 | 4 | .index_store |
134 | 4 | .get_part_unchunked(key.borrow(), 0, None) |
135 | 4 | .await |
136 | 4 | .err_tip(|| "Failed to read index store in dedup store"); |
137 | 4 | let data3 = match maybe_data { |
138 | 1 | Err(e) => { |
139 | 1 | if e.code == Code::NotFound { |
140 | 1 | return Ok(None); |
141 | 0 | } |
142 | 0 | return Err(e); |
143 | | } |
144 | 3 | Ok(data) => data, |
145 | | }; |
146 | | |
147 | 3 | match wincode::config::deserialize::<DedupIndex, WincodeConfig>( |
148 | 3 | &data, |
149 | 3 | self.wincode_config, |
150 | 3 | ) { |
151 | 3 | Ok(dedup_index) => dedup_index, |
152 | 0 | Err(err) => { |
153 | 0 | warn!(?key, ?err, "Failed to deserialize index in dedup store",); |
154 | | // We return the equivalent of NotFound here so the client is happy. |
155 | 0 | return Ok(None); |
156 | | } |
157 | | } |
158 | | }; |
159 | | |
160 | 3 | let digests: Vec<_> = index_entries |
161 | 3 | .entries |
162 | 3 | .into_iter() |
163 | 3 | .map(StoreKey::Digest) |
164 | 3 | .collect(); |
165 | 3 | let mut sum = 0; |
166 | 8 | for size in self.content_store3 .has_many3 (&digests).await?0 { |
167 | 8 | let Some(size7 ) = size else { |
168 | | // A part is missing so return None meaning not-found. |
169 | | // This will abort all in-flight queries related to this request. |
170 | 1 | return Ok(None); |
171 | | }; |
172 | 7 | sum += size; |
173 | | } |
174 | 2 | Ok(Some(sum)) |
175 | 4 | } |
176 | | } |
177 | | |
178 | | #[async_trait] |
179 | | impl StoreDriver for DedupStore { |
180 | 0 | async fn post_init(self: Arc<Self>) -> Result<(), Error> { |
181 | | try_join!( |
182 | | self.index_store.clone().into_inner().post_init(), |
183 | | self.content_store.clone().into_inner().post_init(), |
184 | | )?; |
185 | | Ok(()) |
186 | 0 | } |
187 | | |
188 | | async fn has_with_results( |
189 | | self: Pin<&Self>, |
190 | | digests: &[StoreKey<'_>], |
191 | | results: &mut [Option<u64>], |
192 | 5 | ) -> Result<(), Error> { |
193 | | digests |
194 | | .iter() |
195 | | .zip(results.iter_mut()) |
196 | 5 | .map(|(key, result)| async move { |
197 | 5 | if is_zero_digest(key.borrow()) { |
198 | 1 | *result = Some(0); |
199 | 1 | return Ok(()); |
200 | 4 | } |
201 | | |
202 | 4 | match self.has(key.borrow()).await { |
203 | 4 | Ok(maybe_size) => { |
204 | 4 | *result = maybe_size; |
205 | 4 | Ok(()) |
206 | | } |
207 | 0 | Err(err) => Err(err), |
208 | | } |
209 | 10 | }) |
210 | | .collect::<FuturesOrdered<_>>() |
211 | | .try_collect() |
212 | | .await |
213 | 5 | } |
214 | | |
215 | | async fn update( |
216 | | self: Pin<&Self>, |
217 | | key: StoreKey<'_>, |
218 | | reader: DropCloserReadHalf, |
219 | | _size_info: UploadSizeInfo, |
220 | 7 | ) -> Result<u64, Error> { |
221 | | let mut bytes_reader = StreamReader::new(reader); |
222 | | let frame_reader = FramedRead::new(&mut bytes_reader, self.fast_cdc_decoder.clone()); |
223 | | let index_entries: Vec<_> = frame_reader |
224 | 83 | .map(|r| r.err_tip(|| "Failed to decode frame from fast_cdc")) |
225 | 83 | .map_ok(|frame| async move { |
226 | 83 | let hash = blake3::hash(&frame[..]).into(); |
227 | 83 | let index_entry = DigestInfo::new(hash, frame.len() as u64); |
228 | 83 | if self |
229 | 83 | .content_store |
230 | 83 | .has(index_entry) |
231 | 83 | .await |
232 | 83 | .err_tip(|| "Failed to call .has() in DedupStore::update()")?0 |
233 | 83 | .is_some() |
234 | | { |
235 | | // If our store has this digest, we don't need to upload it. |
236 | 0 | return Result::<_, Error>::Ok(index_entry); |
237 | 83 | } |
238 | 83 | self.content_store |
239 | 83 | .update_oneshot(index_entry, frame) |
240 | 83 | .await |
241 | 83 | .err_tip(|| "Failed to update content store in dedup_store")?0 ; |
242 | 83 | Ok(index_entry) |
243 | 166 | }) |
244 | | .try_buffered(self.max_concurrent_fetch_per_get) |
245 | | .try_collect() |
246 | | .await?; |
247 | | |
248 | | let total_size = index_entries.iter().map(DigestInfo::size_bytes).sum(); |
249 | | |
250 | | let serialized_index = wincode::config::serialize( |
251 | | &DedupIndex { |
252 | | entries: index_entries, |
253 | | }, |
254 | | self.wincode_config, |
255 | | ) |
256 | 0 | .map_err(|e| { |
257 | 0 | make_err!( |
258 | 0 | Code::Internal, |
259 | | "Failed to serialize index in dedup_store : {:?}", |
260 | | e |
261 | | ) |
262 | 0 | })?; |
263 | | |
264 | | self.index_store |
265 | | .update_oneshot(key, serialized_index.into()) |
266 | | .await |
267 | | .err_tip(|| "Failed to insert our index entry to index_store in dedup_store")?; |
268 | | |
269 | | Ok(total_size) |
270 | 7 | } |
271 | | |
272 | | async fn get_part( |
273 | | self: Pin<&Self>, |
274 | | key: StoreKey<'_>, |
275 | | writer: &mut DropCloserWriteHalf, |
276 | | offset: u64, |
277 | | length: Option<u64>, |
278 | 935 | ) -> Result<(), Error> { |
279 | | // Special case for if a client tries to read zero bytes. |
280 | | if length == Some(0) { |
281 | | writer |
282 | | .send_eof() |
283 | | .err_tip(|| "Failed to write EOF out from get_part dedup")?; |
284 | | return Ok(()); |
285 | | } |
286 | | // First we need to download the index that contains where the individual parts actually |
287 | | // can be fetched from. |
288 | | let index_entries = { |
289 | | let data = self |
290 | | .index_store |
291 | | .get_part_unchunked(key, 0, None) |
292 | | .await |
293 | | .err_tip(|| "Failed to read index store in dedup store")?; |
294 | | wincode::config::deserialize::<DedupIndex, WincodeConfig>(&data, self.wincode_config) |
295 | 0 | .map_err(|e| { |
296 | 0 | make_err!( |
297 | 0 | Code::Internal, |
298 | | "Failed to deserialize index in dedup_store::get_part : {:?}", |
299 | | e |
300 | | ) |
301 | 0 | })? |
302 | | }; |
303 | | |
304 | | let mut start_byte_in_stream: u64 = 0; |
305 | | let entries = { |
306 | | if offset == 0 && length.is_none() { |
307 | | index_entries.entries |
308 | | } else { |
309 | | let mut current_entries_sum = 0; |
310 | | let mut entries = Vec::with_capacity(index_entries.entries.len()); |
311 | | for entry in index_entries.entries { |
312 | | let first_byte = current_entries_sum; |
313 | | let entry_size = entry.size_bytes(); |
314 | | current_entries_sum += entry_size; |
315 | | // Filter any items who's end byte is before the first requested byte. |
316 | | if current_entries_sum <= offset { |
317 | | start_byte_in_stream = current_entries_sum; |
318 | | continue; |
319 | | } |
320 | | // If we are not going to read any bytes past the length we are done. |
321 | | if let Some(length) = length |
322 | | && first_byte >= offset + length |
323 | | { |
324 | | break; |
325 | | } |
326 | | entries.push(entry); |
327 | | } |
328 | | entries |
329 | | } |
330 | | }; |
331 | | |
332 | | // Second we we create a stream of futures for each chunk, but buffer/limit them so only |
333 | | // `max_concurrent_fetch_per_get` will be executed at a time. |
334 | | // The results will be streamed out in the same order they are in the entries table. |
335 | | // The results will execute in a "window-like" fashion, meaning that if we limit to |
336 | | // 5 requests at a time, and request 3 is stalled, request 1 & 2 can be output and |
337 | | // request 4 & 5 can be executing (or finished) while waiting for 3 to finish. |
338 | | // Note: We will buffer our data here up to: |
339 | | // `spec.max_size * spec.max_concurrent_fetch_per_get` per `get_part()` request. |
340 | | let mut entries_stream = stream::iter(entries) |
341 | 2.11k | .map(move |index_entry| async move { |
342 | 2.11k | let data2.11k = self |
343 | 2.11k | .content_store |
344 | 2.11k | .get_part_unchunked(index_entry, 0, None) |
345 | 2.11k | .await |
346 | 2.11k | .err_tip(|| "Failed to get_part in content_store in dedup_store")?1 ; |
347 | | |
348 | 2.11k | Result::<_, Error>::Ok(data) |
349 | 4.22k | }) |
350 | | .buffered(self.max_concurrent_fetch_per_get); |
351 | | |
352 | | // Stream out the buffered data one at a time and write the data to our writer stream. |
353 | | // In the event any of these error, we will abort early and abandon all the rest of the |
354 | | // streamed data. |
355 | | // Note: Need to take special care to ensure we send the proper slice of data requested. |
356 | | let mut bytes_to_skip = usize::try_from(offset - start_byte_in_stream) |
357 | | .err_tip(|| "Could not convert (offset - start_byte_in_stream) to usize")?; |
358 | | let mut bytes_to_send = usize::try_from(length.unwrap_or(u64::MAX - offset)) |
359 | | .err_tip(|| "Could not convert length to usize")?; |
360 | | while let Some(result) = entries_stream.next().await { |
361 | | let mut data = result.err_tip(|| "Inner store iterator closed early in DedupStore")?; |
362 | | assert!( |
363 | | bytes_to_skip <= data.len(), |
364 | | "Formula above must be wrong, {} > {}", |
365 | | bytes_to_skip, |
366 | | data.len() |
367 | | ); |
368 | | let end_pos = cmp::min(data.len(), bytes_to_send + bytes_to_skip); |
369 | | if bytes_to_skip != 0 || data.len() > bytes_to_send { |
370 | | data = data.slice(bytes_to_skip..end_pos); |
371 | | } |
372 | | writer |
373 | | .send(data) |
374 | | .await |
375 | | .err_tip(|| "Failed to write data to get_part dedup")?; |
376 | | bytes_to_send -= end_pos - bytes_to_skip; |
377 | | bytes_to_skip = 0; |
378 | | } |
379 | | |
380 | | // Finish our stream by writing our EOF and shutdown the stream. |
381 | | writer |
382 | | .send_eof() |
383 | | .err_tip(|| "Failed to write EOF out from get_part dedup")?; |
384 | | Ok(()) |
385 | 935 | } |
386 | | |
387 | 0 | fn inner_store(&self, _digest: Option<StoreKey>) -> &dyn StoreDriver { |
388 | 0 | self |
389 | 0 | } |
390 | | |
391 | 0 | fn as_any<'a>(&'a self) -> &'a (dyn core::any::Any + Sync + Send + 'static) { |
392 | 0 | self |
393 | 0 | } |
394 | | |
395 | 0 | fn as_any_arc(self: Arc<Self>) -> Arc<dyn core::any::Any + Sync + Send + 'static> { |
396 | 0 | self |
397 | 0 | } |
398 | | |
399 | 0 | fn register_remove_callback(self: Arc<Self>, callback: RemoveCallback) -> Result<(), Error> { |
400 | 0 | self.index_store |
401 | 0 | .register_remove_callback(callback.clone())?; |
402 | 0 | self.content_store.register_remove_callback(callback)?; |
403 | 0 | Ok(()) |
404 | 0 | } |
405 | | } |
406 | | |
407 | | default_health_status_indicator!(DedupStore); |