Skip to main content

harmos_storage/
object_admissions.rs

1/* ***
2 *
3 * Harmos
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * ***
8 */
9
10/* === Modules === */
11
12/* === Re-Exports === */
13
14/* === Imports === */
15
16// Standard Library Imports
17use std::num::NonZeroUsize;
18
19// Third Party Imports
20use sha2::{Digest, Sha256};
21
22// Local Imports
23use super::admissions::Mutation;
24use super::objects::invalid;
25use super::{ObjectReceipt, ObjectValue, StorageManager};
26use crate::Result;
27use crate::storage::MutationId;
28
29/* === Constants === */
30
31/* === Macros === */
32
33/* === Type Aliases === */
34
35/* === Structs === */
36
37/* === Enums === */
38
39/* === Traits === */
40
41/* === Implementations === */
42
43impl<C> StorageManager<C> {
44    #[tracing::instrument(name = "storage.object_admissions.write_objects_once", level = "debug", skip_all)]
45    pub async fn write_objects_once(&self, mutation: &MutationId, objects: Vec<ObjectValue>) -> Result<Vec<ObjectReceipt>> {
46        let count = NonZeroUsize::new(objects.len()).ok_or_else(|| invalid("object batch must not be empty"))?;
47        let mut hash = Sha256::new();
48        part(&mut hash, b"storage.write_objects:v1");
49        hash.update((objects.len() as u64).to_le_bytes());
50        for object in &objects {
51            part(&mut hash, object.schema.id.as_str().as_bytes());
52            hash.update(object.schema.version.get().to_le_bytes());
53            part(&mut hash, object.item.as_str().as_bytes());
54            part(&mut hash, &object.payload);
55        }
56        self.admit_object_group(
57            self.object_admission_bytes(),
58            count,
59            Some(Mutation { id: mutation, fingerprint: hash.finalize().into() }),
60            |group| {
61                for object in objects {
62                    group.write_value(object)?;
63                }
64                Ok(())
65            },
66        )
67        .await
68    }
69}
70
71/* === Public Functions === */
72
73/* === Private Functions === */
74
75fn part(hash: &mut Sha256, bytes: &[u8]) {
76    hash.update((bytes.len() as u64).to_le_bytes());
77    hash.update(bytes);
78}
79
80/* === Tests === */