about summary refs log tree commit diff
path: root/tvix/castore/src/proto/mod.rs
blob: c12eb4ee3c9113594a65f73eea820f1b7309fed3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
use std::str;

use prost::Message;

mod grpc_blobservice_wrapper;
mod grpc_directoryservice_wrapper;

use crate::{B3Digest, DirectoryError};
pub use grpc_blobservice_wrapper::GRPCBlobServiceWrapper;
pub use grpc_directoryservice_wrapper::GRPCDirectoryServiceWrapper;

tonic::include_proto!("tvix.castore.v1");

#[cfg(feature = "tonic-reflection")]
/// Compiled file descriptors for implementing [gRPC
/// reflection](https://github.com/grpc/grpc/blob/master/doc/server-reflection.md) with e.g.
/// [`tonic_reflection`](https://docs.rs/tonic-reflection).
pub const FILE_DESCRIPTOR_SET: &[u8] = tonic::include_file_descriptor_set!("tvix.castore.v1");

#[cfg(test)]
mod tests;

/// Errors that occur during StatBlobResponse validation
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum ValidateStatBlobResponseError {
    /// Invalid digest length encountered
    #[error("Invalid digest length {0} for chunk #{1}")]
    InvalidDigestLen(usize, usize),
}

fn checked_sum(iter: impl IntoIterator<Item = u64>) -> Option<u64> {
    iter.into_iter().try_fold(0u64, |acc, i| acc.checked_add(i))
}

impl Directory {
    /// The size of a directory is the number of all regular and symlink elements,
    /// the number of directory elements, and their size fields.
    pub fn size(&self) -> u64 {
        if cfg!(debug_assertions) {
            self.size_checked()
                .expect("Directory::size exceeds u64::MAX")
        } else {
            self.size_checked().unwrap_or(u64::MAX)
        }
    }

    fn size_checked(&self) -> Option<u64> {
        checked_sum([
            self.files.len().try_into().ok()?,
            self.symlinks.len().try_into().ok()?,
            self.directories.len().try_into().ok()?,
            checked_sum(self.directories.iter().map(|e| e.size))?,
        ])
    }

    /// Calculates the digest of a Directory, which is the blake3 hash of a
    /// Directory protobuf message, serialized in protobuf canonical form.
    pub fn digest(&self) -> B3Digest {
        let mut hasher = blake3::Hasher::new();

        hasher
            .update(&self.encode_to_vec())
            .finalize()
            .as_bytes()
            .into()
    }
}

/// Accepts a name, and a mutable reference to the previous name.
/// If the passed name is larger than the previous one, the reference is updated.
/// If it's not, an error is returned.
fn update_if_lt_prev<'n>(prev_name: &mut &'n [u8], name: &'n [u8]) -> Result<(), DirectoryError> {
    if *name < **prev_name {
        return Err(DirectoryError::WrongSorting(bytes::Bytes::copy_from_slice(
            name,
        )));
    }
    *prev_name = name;
    Ok(())
}

// TODO: add a proper owned version here that moves various fields
impl TryFrom<Directory> for crate::Directory {
    type Error = DirectoryError;

    fn try_from(value: Directory) -> Result<Self, Self::Error> {
        (&value).try_into()
    }
}

impl TryFrom<&Directory> for crate::Directory {
    type Error = DirectoryError;

    fn try_from(directory: &Directory) -> Result<crate::Directory, DirectoryError> {
        let mut dir = crate::Directory::new();

        let mut last_file_name: &[u8] = b"";

        // TODO: this currently loops over all three types separately, rather
        // than peeking and picking from where would be the next.

        for file in directory.files.iter().map(move |file| {
            update_if_lt_prev(&mut last_file_name, &file.name).map(|()| file.clone())
        }) {
            let file = file?;

            let (name, node) = Node {
                node: Some(node::Node::File(file)),
            }
            .into_name_and_node()?;

            dir.add(name, node)?;
        }
        let mut last_directory_name: &[u8] = b"";
        for directory in directory.directories.iter().map(move |directory| {
            update_if_lt_prev(&mut last_directory_name, &directory.name).map(|()| directory.clone())
        }) {
            let directory = directory?;

            let (name, node) = Node {
                node: Some(node::Node::Directory(directory)),
            }
            .into_name_and_node()?;

            dir.add(name, node)?;
        }
        let mut last_symlink_name: &[u8] = b"";
        for symlink in directory.symlinks.iter().map(move |symlink| {
            update_if_lt_prev(&mut last_symlink_name, &symlink.name).map(|()| symlink.clone())
        }) {
            let symlink = symlink?;

            let (name, node) = Node {
                node: Some(node::Node::Symlink(symlink)),
            }
            .into_name_and_node()?;

            dir.add(name, node)?;
        }

        Ok(dir)
    }
}

// TODO: add a proper owned version here that moves various fields
impl From<crate::Directory> for Directory {
    fn from(value: crate::Directory) -> Self {
        (&value).into()
    }
}

impl From<&crate::Directory> for Directory {
    fn from(directory: &crate::Directory) -> Directory {
        let mut directories = vec![];
        let mut files = vec![];
        let mut symlinks = vec![];

        for (name, node) in directory.nodes() {
            match node {
                crate::Node::File {
                    digest,
                    size,
                    executable,
                } => files.push(FileNode {
                    name: name.clone(),
                    digest: digest.to_owned().into(),
                    size: *size,
                    executable: *executable,
                }),
                crate::Node::Directory { digest, size } => directories.push(DirectoryNode {
                    name: name.clone(),
                    digest: digest.to_owned().into(),
                    size: *size,
                }),
                crate::Node::Symlink { target } => {
                    symlinks.push(SymlinkNode {
                        name: name.clone(),
                        target: target.to_owned().into(),
                    });
                }
            }
        }
        Directory {
            directories,
            files,
            symlinks,
        }
    }
}

impl Node {
    /// Converts a proto [Node] to a [crate::Node], and splits off the name.
    pub fn into_name_and_node(self) -> Result<(bytes::Bytes, crate::Node), DirectoryError> {
        match self.node.ok_or_else(|| DirectoryError::NoNodeSet)? {
            node::Node::Directory(n) => {
                let digest = B3Digest::try_from(n.digest)
                    .map_err(|e| DirectoryError::InvalidNode(n.name.to_owned(), e.into()))?;

                let node = crate::Node::Directory {
                    digest,
                    size: n.size,
                };

                Ok((n.name, node))
            }
            node::Node::File(n) => {
                let digest = B3Digest::try_from(n.digest)
                    .map_err(|e| DirectoryError::InvalidNode(n.name.to_owned(), e.into()))?;

                let node = crate::Node::File {
                    digest,
                    size: n.size,
                    executable: n.executable,
                };

                Ok((n.name, node))
            }

            node::Node::Symlink(n) => {
                let node = crate::Node::Symlink {
                    target: n
                        .target
                        .try_into()
                        .map_err(|e| DirectoryError::InvalidNode(n.name.to_owned(), e))?,
                };

                Ok((n.name, node))
            }
        }
    }

    /// Construsts a [Node] from a name and [crate::Node].
    pub fn from_name_and_node(name: bytes::Bytes, n: crate::Node) -> Self {
        match n {
            crate::Node::Directory { digest, size } => Self {
                node: Some(node::Node::Directory(DirectoryNode {
                    name,
                    digest: digest.into(),
                    size,
                })),
            },
            crate::Node::File {
                digest,
                size,
                executable,
            } => Self {
                node: Some(node::Node::File(FileNode {
                    name,
                    digest: digest.into(),
                    size,
                    executable,
                })),
            },
            crate::Node::Symlink { target } => Self {
                node: Some(node::Node::Symlink(SymlinkNode {
                    name,
                    target: target.into(),
                })),
            },
        }
    }
}

impl StatBlobResponse {
    /// Validates a StatBlobResponse. All chunks must have valid blake3 digests.
    /// It is allowed to send an empty list, if no more granular chunking is
    /// available.
    pub fn validate(&self) -> Result<(), ValidateStatBlobResponseError> {
        for (i, chunk) in self.chunks.iter().enumerate() {
            if chunk.digest.len() != blake3::KEY_LEN {
                return Err(ValidateStatBlobResponseError::InvalidDigestLen(
                    chunk.digest.len(),
                    i,
                ));
            }
        }
        Ok(())
    }
}