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