Skip to main content

harmos_storage/
file_hash.rs

1/* ***
2 *
3 * Harmos
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * ***
8 */
9
10// Hash A Bounded File Range Without Retaining The Complete Payload.
11
12/* === Modules === */
13
14/* === Re-Exports === */
15
16/* === Imports === */
17
18// Standard Library Imports
19
20// Third Party Imports
21use sha2::{Digest, Sha256};
22
23// Local Imports
24use crate::FileRead;
25use crate::{Result, StorageManager};
26use harmos_domain::model::storage::files::FileHash;
27
28/* === Constants === */
29
30/* === Macros === */
31
32/* === Type Aliases === */
33
34/* === Structs === */
35
36/* === Enums === */
37
38/* === Traits === */
39
40/* === Implementations === */
41
42impl<C> StorageManager<C> {
43    pub async fn hash_file(&self, request: FileRead) -> Result<FileHash> {
44        let context = crate::execution::Context::current();
45        let span = context.sync(|| tracing::debug_span!("storage.file.hash_file", outcome = "cancelled"));
46        context
47            .result(span, async {
48                let mut reader = self
49                    .read_file(FileRead {
50                        source: request.source,
51                        range: request.range,
52                    })
53                    .await?;
54                let mut hash = Sha256::new();
55                let local = reader.is_local();
56                while let Some(batch) = reader.next().await? {
57                    if local {
58                        hash.update(batch.bytes());
59                    }
60                }
61                let completion = reader.completion()?;
62                Ok(reader.stored_hash()?.unwrap_or_else(|| FileHash {
63                    bytes_read: completion.bytes,
64                    sha256: hash.finalize().into(),
65                }))
66            })
67            .await
68    }
69}
70
71/* === Public Functions === */
72
73/* === Private Functions === */
74
75/* === Tests === */