about summary refs log tree commit diff
path: root/tvix/castore/src/directoryservice/traverse.rs
blob: 1d1de6e18faaac40e53b47d20e556769f6d6eda2 (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
use super::DirectoryService;
use crate::{proto::NamedNode, B3Digest, Error};
use std::{ops::Deref, os::unix::ffi::OsStrExt};
use tracing::{instrument, warn};

/// This descends from a (root) node to the given (sub)path, returning the Node
/// at that path, or none, if there's nothing at that path.
#[instrument(skip(directory_service))]
pub async fn descend_to<DS>(
    directory_service: DS,
    root_node: crate::proto::node::Node,
    path: &std::path::Path,
) -> Result<Option<crate::proto::node::Node>, Error>
where
    DS: Deref<Target = dyn DirectoryService>,
{
    // strip a possible `/` prefix from the path.
    let path = {
        if path.starts_with("/") {
            path.strip_prefix("/").unwrap()
        } else {
            path
        }
    };

    let mut cur_node = root_node;
    let mut it = path.components();

    loop {
        match it.next() {
            None => {
                // the (remaining) path is empty, return the node we're current at.
                return Ok(Some(cur_node));
            }
            Some(first_component) => {
                match cur_node {
                    crate::proto::node::Node::File(_) | crate::proto::node::Node::Symlink(_) => {
                        // There's still some path left, but the current node is no directory.
                        // This means the path doesn't exist, as we can't reach it.
                        return Ok(None);
                    }
                    crate::proto::node::Node::Directory(directory_node) => {
                        let digest: B3Digest = directory_node.digest.try_into().map_err(|_e| {
                            Error::StorageError("invalid digest length".to_string())
                        })?;

                        // fetch the linked node from the directory_service
                        match directory_service.get(&digest).await? {
                            // If we didn't get the directory node that's linked, that's a store inconsistency, bail out!
                            None => {
                                warn!("directory {} does not exist", digest);

                                return Err(Error::StorageError(format!(
                                    "directory {} does not exist",
                                    digest
                                )));
                            }
                            Some(directory) => {
                                // look for first_component in the [Directory].
                                // FUTUREWORK: as the nodes() iterator returns in a sorted fashion, we
                                // could stop as soon as e.name is larger than the search string.
                                let child_node = directory.nodes().find(|n| {
                                    n.get_name() == first_component.as_os_str().as_bytes()
                                });

                                match child_node {
                                    // child node not found means there's no such element inside the directory.
                                    None => {
                                        return Ok(None);
                                    }
                                    // child node found, return to top-of loop to find the next
                                    // node in the path.
                                    Some(child_node) => {
                                        cur_node = child_node;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::Arc;

    use crate::directoryservice::DirectoryService;
    use crate::fixtures::{DIRECTORY_COMPLICATED, DIRECTORY_WITH_KEEP};
    use crate::utils::gen_directory_service;

    use super::descend_to;

    #[tokio::test]
    async fn test_descend_to() {
        let directory_service: Arc<dyn DirectoryService> = gen_directory_service().into();

        let mut handle = directory_service.put_multiple_start();
        handle
            .put(DIRECTORY_WITH_KEEP.clone())
            .await
            .expect("must succeed");
        handle
            .put(DIRECTORY_COMPLICATED.clone())
            .await
            .expect("must succeed");

        // construct the node for DIRECTORY_COMPLICATED
        let node_directory_complicated =
            crate::proto::node::Node::Directory(crate::proto::DirectoryNode {
                name: "doesntmatter".into(),
                digest: DIRECTORY_COMPLICATED.digest().into(),
                size: DIRECTORY_COMPLICATED.size(),
            });

        // construct the node for DIRECTORY_COMPLICATED
        let node_directory_with_keep = crate::proto::node::Node::Directory(
            DIRECTORY_COMPLICATED.directories.first().unwrap().clone(),
        );

        // construct the node for the .keep file
        let node_file_keep =
            crate::proto::node::Node::File(DIRECTORY_WITH_KEEP.files.first().unwrap().clone());

        // traversal to an empty subpath should return the root node.
        {
            let resp = descend_to(
                directory_service.clone(),
                node_directory_complicated.clone(),
                &PathBuf::from(""),
            )
            .await
            .expect("must succeed");

            assert_eq!(Some(node_directory_complicated.clone()), resp);
        }

        // traversal to `keep` should return the node for DIRECTORY_WITH_KEEP
        {
            let resp = descend_to(
                directory_service.clone(),
                node_directory_complicated.clone(),
                &PathBuf::from("keep"),
            )
            .await
            .expect("must succeed");

            assert_eq!(Some(node_directory_with_keep), resp);
        }

        // traversal to `keep/.keep` should return the node for the .keep file
        {
            let resp = descend_to(
                directory_service.clone(),
                node_directory_complicated.clone(),
                &PathBuf::from("keep/.keep"),
            )
            .await
            .expect("must succeed");

            assert_eq!(Some(node_file_keep.clone()), resp);
        }

        // traversal to `keep/.keep` should return the node for the .keep file
        {
            let resp = descend_to(
                directory_service.clone(),
                node_directory_complicated.clone(),
                &PathBuf::from("/keep/.keep"),
            )
            .await
            .expect("must succeed");

            assert_eq!(Some(node_file_keep), resp);
        }

        // traversal to `void` should return None (doesn't exist)
        {
            let resp = descend_to(
                directory_service.clone(),
                node_directory_complicated.clone(),
                &PathBuf::from("void"),
            )
            .await
            .expect("must succeed");

            assert_eq!(None, resp);
        }

        // traversal to `void` should return None (doesn't exist)
        {
            let resp = descend_to(
                directory_service.clone(),
                node_directory_complicated.clone(),
                &PathBuf::from("//v/oid"),
            )
            .await
            .expect("must succeed");

            assert_eq!(None, resp);
        }

        // traversal to `keep/.keep/404` should return None (the path can't be
        // reached, as keep/.keep already is a file)
        {
            let resp = descend_to(
                directory_service.clone(),
                node_directory_complicated.clone(),
                &PathBuf::from("keep/.keep/foo"),
            )
            .await
            .expect("must succeed");

            assert_eq!(None, resp);
        }

        // traversal to a subpath of '/' should return the root node.
        {
            let resp = descend_to(
                directory_service.clone(),
                node_directory_complicated.clone(),
                &PathBuf::from("/"),
            )
            .await
            .expect("must succeed");

            assert_eq!(Some(node_directory_complicated), resp);
        }
    }
}