Skip to main content

TreeModel

Struct TreeModel 

Source
pub struct TreeModel { /* private fields */ }
Expand description

The model of a local tree that TreeModel::scan walked and hashed.

For each entry, the model keeps the name, the metadata, and the index of the parent directory. For each regular file, it also keeps the number of payload bytes that the hash pass read. The model holds no file content, and it serializes a dirtree or a dirmeta object again from its fields on each request. Its memory grows with the number of entries and the length of their names.

§Object source

The model is the ObjectSource of the objects of the tree. object_names gives each object of the tree once. The model holds no commit.

  • open of a regular file opens the file again on the blocking pool, with the open and the checks of the hash pass. These are the type check, and on Unix the identity check. It gives the file as ObjectData::Content, whose size is the payload size that the hash pass read.
  • open of a symlink opens no file. open of a dirtree or a dirmeta object serializes the object again from the model. Each of the two is ObjectData::Encoded in the raw encoding.
  • content_size gives the sum of the payload sizes of the hash pass, in each encoding. It reads no file.
  • objects and detached_metadata name a commit, so each call returns Error::InvalidInput.

When the model sends a file, it gives the payload size of the hash pass and does not hash the file again. If a file changes after the hash pass, the server verifies the object and refuses it.

If a call names an object that the model does not hold, a commit included, it returns Error::InvalidInput. If the open of a file fails, the call returns Error::Walk with the path of the file and one of the kinds that scan lists. The session returns that error inside Error::Source.

Implementations§

Source§

impl TreeModel

Source

pub async fn scan(root: &Path, options: ScanOptions) -> Result<TreeModel>

Walks the directory root and hashes each object of its tree.

The scan gives the checksum of each object of the tree: a content object for each regular file and symlink, and a dirtree and a dirmeta object for each directory.

§Walk
  • The walk does not follow symlinks. The walk root must be a directory.
  • The walk holds one directory open at a time. It reads a listing to its end and closes the directory before it enters a subdirectory.
  • While it reads a listing, the walk reads the metadata of each entry with DirEntry::metadata and the target of each symlink. It reads only the walk root with symlink_metadata.
  • Each name must be valid UTF-8 and must pass the dirtree name rule of ostrya-core. Each symlink target must be valid UTF-8.
  • The walk takes regular files, directories, and symlinks. Any other entry stops the walk before the entry filter runs, so the filter never sees it. Other entries are device nodes, fifos, sockets, and Windows reparse points that are not symlinks.
  • After the walk closes a directory, it runs the EntryFilter on each entry in the order of the listing. Then it enters each kept subdirectory in turn, depth first.
  • The filter sees the root first, with the empty path.
  • EntryAction::Skip leaves out an entry, and for a directory its whole subtree. The walk does not open a skipped entry. Skip on the root stops the walk.
  • If a file has more than one hard link in the tree, the walk reads and hashes the file once for each of its paths.
§Hash pass
  • The pass reads each kept regular file once, on the blocking pool of the runtime. It hashes the file over its file header and its payload.
  • The pass starts each file as soon as the filter keeps it, in the order of the walk, with at most ScanOptions::hash_jobs files in flight.
  • A job reads its file in chunks of at most 64 KiB. Before each chunk, it checks the stop flag of the pass.
  • At the first error of the walk or of a job, the pass sets the stop flag and starts no new job. It returns the error after each job in flight stops, so no file of the pass is open when the scan returns.
  • If the future of the scan is dropped, the pass sets the stop flag. Each job in flight then stops at its next chunk.
  • On Unix, a job opens its file with O_NOFOLLOW | O_NONBLOCK. On Windows, it opens the file with FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS.
  • One metadata read of the open file must show a regular file. On Unix, the device and inode numbers must also equal those that the walk read. If a parent directory of the file becomes a symlink after the walk, the open can reach another file, and this check refuses it. Windows has no identity check.
  • The model records the number of payload bytes that each job read.
  • After the walk and the jobs end, the scan hashes each directory bottom up: its dirtree object, with the entries sorted by name, and its dirmeta object.
§Errors
  • Error::InvalidInput if ScanOptions::hash_jobs is Some(0). The walk does not start.
  • Error::Walk for each failure of the walk and of the hash pass. The error names the entry on the local filesystem, the walk root included. It keeps one of these io::ErrorKind values:
    • the kind of the call that failed, for example PermissionDenied or NotFound
    • InvalidInput if the walk root is not a directory, or if the filter returns Skip for the root
    • Unsupported for an entry that is not a regular file, a directory, or a symlink, and on Windows for a symlink whose target std cannot read
    • InvalidData for a name that is not valid UTF-8 or that fails the name rule, and for a symlink target that is not valid UTF-8
    • InvalidData for a change by the filter that EntryMeta does not allow, and for a file header that ostrya-core refuses, for example a symlink target with a NUL byte
    • InvalidData on Windows for a symlink target that holds \ or starts with a drive prefix, also if no filter runs
    • InvalidData for a file whose type or identity changed after the walk read it
    • InvalidData for a dirtree or a dirmeta object of more than MAX_METADATA_SIZE bytes, and for a tree of more than u32::MAX kept entries

If more than one entry fails, the error names one of the failing paths. If more than one hash job runs, the order of the failures is not fixed.

Examples found in repository?
examples/send_pass.rs (line 143)
139fn run(dir: &Path, count: u64, size: u64, compression: Compression) -> io::Result<()> {
140    fs::create_dir_all(dir)?;
141    write_files(dir, count, size)?;
142    ostrya_rt::block_on(async {
143        let model = TreeModel::scan(dir, ScanOptions::default())
144            .await
145            .map_err(io::Error::other)?;
146        let names: Vec<_> = model
147            .object_names()
148            .into_iter()
149            .filter(|name| name.ty == ObjectType::File)
150            .collect();
151        let session = PushSession::over_stream(
152            Cursor::new(scripted_replies().await?),
153            sink(),
154            &["main".to_string()],
155            SessionOptions::default(),
156        )
157        .await
158        .map_err(io::Error::other)?;
159        eprintln!("send pass: start");
160        let start = Instant::now();
161        session
162            .send(&model, &names, &[], compression)
163            .await
164            .map_err(io::Error::other)?;
165        let elapsed = start.elapsed();
166        let files = names.len().max(1) as f64;
167        println!(
168            "{} files of {size} bytes: {:.1} us per file, {:.3} s in all",
169            names.len(),
170            elapsed.as_secs_f64() * 1e6 / files,
171            elapsed.as_secs_f64()
172        );
173        if let Some(peak) = peak_rss() {
174            println!("VmHWM: {peak}");
175        }
176        Ok(())
177    })
178}
Source

pub fn root_dirtree(&self) -> Checksum

Returns the dirtree checksum of the walk root.

Source

pub fn root_dirmeta(&self) -> Checksum

Returns the dirmeta checksum of the walk root.

Source

pub fn object_names(&self) -> Vec<ObjectName>

Returns the name of each object of the tree, once each.

The list holds the content object of each regular file and symlink, and the dirtree and dirmeta objects of each directory. It holds no commit object. The order is the order in which the walk reached the first source of each object.

Examples found in repository?
examples/send_pass.rs (line 147)
139fn run(dir: &Path, count: u64, size: u64, compression: Compression) -> io::Result<()> {
140    fs::create_dir_all(dir)?;
141    write_files(dir, count, size)?;
142    ostrya_rt::block_on(async {
143        let model = TreeModel::scan(dir, ScanOptions::default())
144            .await
145            .map_err(io::Error::other)?;
146        let names: Vec<_> = model
147            .object_names()
148            .into_iter()
149            .filter(|name| name.ty == ObjectType::File)
150            .collect();
151        let session = PushSession::over_stream(
152            Cursor::new(scripted_replies().await?),
153            sink(),
154            &["main".to_string()],
155            SessionOptions::default(),
156        )
157        .await
158        .map_err(io::Error::other)?;
159        eprintln!("send pass: start");
160        let start = Instant::now();
161        session
162            .send(&model, &names, &[], compression)
163            .await
164            .map_err(io::Error::other)?;
165        let elapsed = start.elapsed();
166        let files = names.len().max(1) as f64;
167        println!(
168            "{} files of {size} bytes: {:.1} us per file, {:.3} s in all",
169            names.len(),
170            elapsed.as_secs_f64() * 1e6 / files,
171            elapsed.as_secs_f64()
172        );
173        if let Some(peak) = peak_rss() {
174            println!("VmHWM: {peak}");
175        }
176        Ok(())
177    })
178}

Trait Implementations§

Source§

impl ObjectSource for TreeModel

Source§

fn objects<'a>( &'a self, commit: &'a Checksum, ) -> BoxFuture<'a, Result<Vec<ObjectName>>>

Returns the name of each object that commit reaches, and of the commit. Read more
Source§

fn open<'a>( &'a self, name: &'a ObjectName, _encoding: Encoding, ) -> BoxFuture<'a, Result<ObjectData>>

Returns the data of the object name. Read more
Source§

fn detached_metadata<'a>( &'a self, commit: &'a Checksum, ) -> BoxFuture<'a, Result<Option<Value>>>

Returns the detached metadata for commit, an a{sv} dict. Read more
Source§

fn content_size<'a>( &'a self, names: &'a [ObjectName], _encoding: Encoding, ) -> BoxFuture<'a, Result<Option<u64>>>

Returns the content bytes of the file objects of names in encoding. Read more
Source§

fn detached_metadata_encoded<'a>( &'a self, commit: &'a Checksum, ) -> BoxFuture<'a, Result<Option<DetachedMetadata>>>

Returns the detached metadata for commit, as a dict or as its bytes. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more