Coverage Report

Created: 2026-12-01 07:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-util/src/digest_hasher.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 std::sync::OnceLock;
16
17
use blake3::Hasher as Blake3Hasher;
18
use bytes::BytesMut;
19
use futures::Future;
20
use nativelink_config::stores::ConfigDigestHashFunction;
21
use nativelink_error::{Code, Error, ResultExt, make_err, make_input_err};
22
use nativelink_metric::{
23
    MetricFieldData, MetricKind, MetricPublishKnownKindData, MetricsComponent,
24
};
25
use nativelink_proto::build::bazel::remote::execution::v2::digest_function::Value as ProtoDigestFunction;
26
use opentelemetry::context::Context;
27
use serde::{Deserialize, Serialize};
28
use sha2::{Digest, Sha256};
29
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt};
30
31
use crate::common::DigestInfo;
32
use crate::{fs, spawn_blocking};
33
34
static DEFAULT_DIGEST_HASHER_FUNC: OnceLock<DigestHasherFunc> = OnceLock::new();
35
36
/// Utility function to make a context with a specific hasher function set.
37
14.7k
pub fn make_ctx_for_hash_func<H>(hasher: H) -> Result<Context, Error>
38
14.7k
where
39
14.7k
    H: TryInto<DigestHasherFunc>,
40
14.7k
    H::Error: Into<Error>,
41
{
42
14.7k
    let digest_hasher_func = hasher
43
14.7k
        .try_into()
44
14.7k
        .err_tip(|| "Could not convert into DigestHasherFunc")
?0
;
45
46
14.7k
    let new_ctx = Context::current_with_value(digest_hasher_func);
47
48
14.7k
    Ok(new_ctx)
49
14.7k
}
50
51
/// Get the default hasher.
52
432
pub fn default_digest_hasher_func() -> DigestHasherFunc {
53
432
    *DEFAULT_DIGEST_HASHER_FUNC.get_or_init(|| DigestHasherFunc::Sha256)
54
432
}
55
56
/// Get the hasher requested by the client from the active context (set via
57
/// [`make_ctx_for_hash_func`]), falling back to the default hasher.
58
189
pub fn digest_hasher_func_from_context() -> DigestHasherFunc {
59
189
    Context::current()
60
189
        .get::<DigestHasherFunc>()
61
189
        .map_or_else(default_digest_hasher_func, |v| *v)
62
189
}
63
64
/// Sets the default hasher to use if no hasher was requested by the client.
65
1
pub fn set_default_digest_hasher_func(hasher: DigestHasherFunc) -> Result<(), Error> {
66
1
    DEFAULT_DIGEST_HASHER_FUNC
67
1
        .set(hasher)
68
1
        .map_err(|_| 
make_err!0
(
Code::Internal0
, "default_digest_hasher_func already set"))
69
1
}
70
71
/// Supported digest hash functions.
72
#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash, Serialize, Deserialize)]
73
pub enum DigestHasherFunc {
74
    Sha256,
75
    Blake3,
76
}
77
78
impl MetricsComponent for DigestHasherFunc {
79
0
    fn publish(
80
0
        &self,
81
0
        kind: MetricKind,
82
0
        field_metadata: MetricFieldData,
83
0
    ) -> Result<MetricPublishKnownKindData, nativelink_metric::Error> {
84
0
        format!("{self:?}").publish(kind, field_metadata)
85
0
    }
86
}
87
88
impl DigestHasherFunc {
89
48.9k
    pub fn hasher(&self) -> DigestHasherImpl {
90
48.9k
        self.into()
91
48.9k
    }
92
93
    #[must_use]
94
15.6k
    pub const fn proto_digest_func(&self) -> ProtoDigestFunction {
95
15.6k
        match self {
96
15.5k
            Self::Sha256 => ProtoDigestFunction::Sha256,
97
29
            Self::Blake3 => ProtoDigestFunction::Blake3,
98
        }
99
15.6k
    }
100
101
    /// The `{digest_function/}` segment `REv2` puts in blob resource names
102
    /// and `MISSING` violation subjects. It MUST be omitted for SHA256 (and
103
    /// the other functions identifiable by hash length), and present for
104
    /// the rest, which here means BLAKE3.
105
    #[must_use]
106
0
    pub const fn resource_name_segment(&self) -> Option<&'static str> {
107
0
        match self {
108
0
            Self::Sha256 => None,
109
0
            Self::Blake3 => Some("blake3"),
110
        }
111
0
    }
112
}
113
114
impl From<ConfigDigestHashFunction> for DigestHasherFunc {
115
0
    fn from(value: ConfigDigestHashFunction) -> Self {
116
0
        match value {
117
0
            ConfigDigestHashFunction::Sha256 => Self::Sha256,
118
0
            ConfigDigestHashFunction::Blake3 => Self::Blake3,
119
        }
120
0
    }
121
}
122
123
impl TryFrom<ProtoDigestFunction> for DigestHasherFunc {
124
    type Error = Error;
125
126
8
    fn try_from(value: ProtoDigestFunction) -> Result<Self, Self::Error> {
127
8
        match value {
128
6
            ProtoDigestFunction::Sha256 => Ok(Self::Sha256),
129
0
            ProtoDigestFunction::Blake3 => Ok(Self::Blake3),
130
2
            v => Err(make_input_err!(
131
2
                "Unknown or unsupported digest function for proto conversion {v:?}"
132
2
            )),
133
        }
134
8
    }
135
}
136
137
impl TryFrom<&str> for DigestHasherFunc {
138
    type Error = Error;
139
140
19
    fn try_from(value: &str) -> Result<Self, Self::Error> {
141
19
        match value.to_uppercase().as_str() {
142
19
            "SHA256" => 
Ok(Self::Sha256)16
,
143
3
            "BLAKE3" => Ok(Self::Blake3),
144
0
            v => Err(make_input_err!(
145
0
                "Unknown or unsupported digest function for string conversion: {v:?}"
146
0
            )),
147
        }
148
19
    }
149
}
150
151
impl core::fmt::Display for DigestHasherFunc {
152
21.3k
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
153
21.3k
        match self {
154
21.3k
            Self::Sha256 => write!(f, "SHA256"),
155
24
            Self::Blake3 => write!(f, "BLAKE3"),
156
        }
157
21.3k
    }
158
}
159
160
impl TryFrom<i32> for DigestHasherFunc {
161
    type Error = Error;
162
163
42.6k
    fn try_from(value: i32) -> Result<Self, Self::Error> {
164
        // Zero means not-set.
165
42.6k
        if value == 0 {
166
86
            return Ok(default_digest_hasher_func());
167
42.5k
        }
168
42.5k
        match ProtoDigestFunction::try_from(value) {
169
42.4k
            Ok(ProtoDigestFunction::Sha256) => Ok(Self::Sha256),
170
38
            Ok(ProtoDigestFunction::Blake3) => Ok(Self::Blake3),
171
0
            value => Err(make_input_err!(
172
                "Unknown or unsupported digest function for int conversion: {:?}",
173
0
                value.map(|v| v.as_str_name())
174
            )),
175
        }
176
42.6k
    }
177
}
178
179
impl From<&DigestHasherFunc> for DigestHasherImpl {
180
48.9k
    fn from(value: &DigestHasherFunc) -> Self {
181
48.9k
        let hash_func_impl = match value {
182
43.6k
            DigestHasherFunc::Sha256 => DigestHasherFuncImpl::Sha256(Sha256::new()),
183
5.29k
            DigestHasherFunc::Blake3 => DigestHasherFuncImpl::Blake3(Box::default()),
184
        };
185
48.9k
        Self {
186
48.9k
            hashed_size: 0,
187
48.9k
            hash_func_impl,
188
48.9k
        }
189
48.9k
    }
190
}
191
192
/// Wrapper to compute a hash of arbitrary data.
193
pub trait DigestHasher {
194
    /// Update the hasher with some additional data.
195
    fn update(&mut self, input: &[u8]);
196
197
    /// Finalize the hash function and collect the results into a digest.
198
    fn finalize_digest(&mut self) -> DigestInfo;
199
200
    /// Specialized version of the hashing function that is optimized for
201
    /// handling files. These optimizations take into account things like,
202
    /// the file size and the hasher algorithm to decide how to best process
203
    /// the file and feed it into the hasher.
204
    fn digest_for_file(
205
        self,
206
        file_path: impl AsRef<std::path::Path>,
207
        file: fs::FileSlot,
208
        size_hint: Option<u64>,
209
    ) -> impl Future<Output = Result<(DigestInfo, fs::FileSlot), Error>>;
210
211
    /// Utility function to compute a hash from a generic reader.
212
281
    fn compute_from_reader<R: AsyncRead + Unpin + Send>(
213
281
        &mut self,
214
281
        mut reader: R,
215
281
    ) -> impl Future<Output = Result<DigestInfo, Error>> {
216
281
        async move {
217
281
            let mut chunk = BytesMut::with_capacity(fs::DEFAULT_READ_BUFF_SIZE);
218
            loop {
219
742
                reader
220
742
                    .read_buf(&mut chunk)
221
742
                    .await
222
742
                    .err_tip(|| "Could not read chunk during compute_from_reader")
?0
;
223
742
                if chunk.is_empty() {
224
281
                    break; // EOF.
225
461
                }
226
461
                DigestHasher::update(self, &chunk);
227
461
                chunk.clear();
228
            }
229
281
            Ok(DigestHasher::finalize_digest(self))
230
281
        }
231
281
    }
232
}
233
234
#[expect(
235
    variant_size_differences,
236
    reason = "some variants are already boxed; this is acceptable"
237
)]
238
#[derive(Debug)]
239
pub enum DigestHasherFuncImpl {
240
    Sha256(Sha256),
241
    Blake3(Box<Blake3Hasher>), // Box because Blake3Hasher is 1.3kb in size.
242
}
243
244
/// The individual implementation of the hash function.
245
#[derive(Debug)]
246
pub struct DigestHasherImpl {
247
    hashed_size: u64,
248
    hash_func_impl: DigestHasherFuncImpl,
249
}
250
251
impl DigestHasherImpl {
252
    #[inline]
253
281
    async fn hash_file(
254
281
        &mut self,
255
281
        mut file: fs::FileSlot,
256
281
    ) -> Result<(DigestInfo, fs::FileSlot), Error> {
257
281
        let digest = self
258
281
            .compute_from_reader(&mut file)
259
281
            .await
260
281
            .err_tip(|| "In digest_for_file")
?0
;
261
281
        Ok((digest, file))
262
281
    }
263
}
264
265
impl DigestHasher for DigestHasherImpl {
266
    #[inline]
267
50.8k
    fn update(&mut self, input: &[u8]) {
268
50.8k
        self.hashed_size += input.len() as u64;
269
50.8k
        match &mut self.hash_func_impl {
270
45.3k
            DigestHasherFuncImpl::Sha256(h) => sha2::digest::Update::update(h, input),
271
5.50k
            DigestHasherFuncImpl::Blake3(h) => {
272
5.50k
                Blake3Hasher::update(h, input);
273
5.50k
            }
274
        }
275
50.8k
    }
276
277
    #[inline]
278
48.9k
    fn finalize_digest(&mut self) -> DigestInfo {
279
48.9k
        let hash = match &mut self.hash_func_impl {
280
43.6k
            DigestHasherFuncImpl::Sha256(h) => h.finalize_reset().into(),
281
5.29k
            DigestHasherFuncImpl::Blake3(h) => h.finalize().into(),
282
        };
283
48.9k
        DigestInfo::new(hash, self.hashed_size)
284
48.9k
    }
285
286
281
    async fn digest_for_file(
287
281
        mut self,
288
281
        file_path: impl AsRef<std::path::Path>,
289
281
        mut file: fs::FileSlot,
290
281
        size_hint: Option<u64>,
291
281
    ) -> Result<(DigestInfo, fs::FileSlot), Error> {
292
281
        let file_position = file
293
281
            .stream_position()
294
281
            .await
295
281
            .err_tip(|| "Couldn't get stream position in digest_for_file")
?0
;
296
281
        if file_position != 0 {
297
0
            return self.hash_file(file).await;
298
281
        }
299
        // If we are a small file, it's faster to just do it the "slow" way.
300
        // Great read: https://github.com/david-slatinek/c-read-vs.-mmap
301
281
        if let Some(size_hint) = size_hint
302
281
            && size_hint <= fs::DEFAULT_READ_BUFF_SIZE as u64
303
        {
304
280
            return self.hash_file(file).await;
305
1
        }
306
1
        let file_path = file_path.as_ref().to_path_buf();
307
1
        match self.hash_func_impl {
308
1
            DigestHasherFuncImpl::Sha256(_) => self.hash_file(file).await,
309
0
            DigestHasherFuncImpl::Blake3(mut hasher) => {
310
0
                spawn_blocking!("digest_for_file", move || {
311
0
                    hasher.update_mmap(file_path).map_err(|e| {
312
0
                        Error::from_std_err(Code::Internal, &e)
313
0
                            .append("Error in blake3's update_mmap")
314
0
                    })?;
315
0
                    Result::<_, Error>::Ok((
316
0
                        DigestInfo::new(hasher.finalize().into(), hasher.count()),
317
0
                        file,
318
0
                    ))
319
0
                })
320
0
                .await
321
0
                .err_tip(|| "Could not spawn blocking task in digest_for_file")?
322
            }
323
        }
324
281
    }
325
}