Skip to main content

send_pass/
send_pass.rs

1//! Times the send pass of a tree push over a scripted server.
2//!
3//! Usage: `send_pass COUNT SIZE raw|deflate [DIR]`
4//!
5//! The program writes COUNT files of SIZE bytes each under DIR (a new
6//! directory in the temporary directory by default). If COUNT is more than 1,
7//! SIZE must be at least 8. The program scans the files into a tree model.
8//! Then it sends each content object to a server that needs each object.
9//!
10//! The bytes of the session go to a sink, so the program holds no object.
11//! The program writes `send pass: start` to standard error immediately before
12//! the send, so that a trace of the process can be cut at that write.
13//!
14//! After the send, the program prints the mean time for each file and the
15//! total time. On Linux, it also prints the peak resident set size
16//! (`VmHWM`).
17
18use std::fs;
19use std::io::{self, Write};
20use std::path::{Path, PathBuf};
21use std::process::ExitCode;
22use std::time::Instant;
23
24use futures_lite::io::{Cursor, sink};
25use ostrya_core::ObjectType;
26use ostrya_remote::proto::{
27    FrameWriter, HelloReply, MIN_FRAME_LIMIT, Message, ObjectsReply, RefState,
28};
29use ostrya_remote::tree::{ScanOptions, TreeModel};
30use ostrya_remote::{Compression, Encoding, PushSession, SessionOptions};
31
32/// The largest write of file data: 1 MiB.
33const WRITE_CHUNK: usize = 1024 * 1024;
34
35/// Returns the replies of a server that lists `raw` and `deflate`, needs
36/// each object, and takes one object stream.
37async fn scripted_replies() -> io::Result<Vec<u8>> {
38    let msgs = [
39        Message::HelloReply(HelloReply {
40            version: 1,
41            mode: "archive".into(),
42            collection_id: None,
43            collection: None,
44            max_frame: MIN_FRAME_LIMIT,
45            max_have: 16_384,
46            encodings: vec![Encoding::Raw, Encoding::Deflate],
47            parallel_uploads: 1,
48            refs: vec![RefState {
49                name: "main".into(),
50                commit: None,
51            }],
52        }),
53        Message::ObjectsReply(ObjectsReply {
54            objects: 0,
55            payload_bytes: 0,
56        }),
57    ];
58    let mut w = FrameWriter::new(Vec::new());
59    for msg in &msgs {
60        w.write_message(msg).await.map_err(io::Error::other)?;
61    }
62    Ok(w.into_inner())
63}
64
65/// Writes `count` files of `size` bytes under `dir`. The first 8 bytes of each
66/// file hold its index, so no two files share a content object.
67fn write_files(dir: &Path, count: u64, size: u64) -> io::Result<()> {
68    let mut chunk = vec![0u8; WRITE_CHUNK];
69    for (i, byte) in chunk.iter_mut().enumerate() {
70        *byte = (i % 251) as u8;
71    }
72    for index in 0..count {
73        let mut file = io::BufWriter::new(fs::File::create(dir.join(format!("f{index:07}")))?);
74        let mut left = size;
75        let tag = index.to_le_bytes();
76        let head = left.min(tag.len() as u64) as usize;
77        file.write_all(&tag[..head])?;
78        left -= head as u64;
79        while left > 0 {
80            let n = left.min(WRITE_CHUNK as u64) as usize;
81            file.write_all(&chunk[..n])?;
82            left -= n as u64;
83        }
84        file.flush()?;
85    }
86    Ok(())
87}
88
89/// Returns the peak resident set size of the process, as `/proc/self/status`
90/// gives it.
91fn peak_rss() -> Option<String> {
92    let status = fs::read_to_string("/proc/self/status").ok()?;
93    let line = status.lines().find(|line| line.starts_with("VmHWM:"))?;
94    Some(line["VmHWM:".len()..].trim().to_owned())
95}
96
97fn usage() -> ExitCode {
98    eprintln!("usage: send_pass COUNT SIZE raw|deflate [DIR]");
99    ExitCode::from(2)
100}
101
102fn main() -> ExitCode {
103    let args: Vec<String> = std::env::args().skip(1).collect();
104    let (Some(count), Some(size), Some(encoding)) = (
105        args.first().and_then(|a| a.parse::<u64>().ok()),
106        args.get(1).and_then(|a| a.parse::<u64>().ok()),
107        args.get(2),
108    ) else {
109        return usage();
110    };
111    if count > 1 && size < 8 {
112        return usage();
113    }
114    let compression = match encoding.as_str() {
115        "raw" => Compression::None,
116        "deflate" => Compression::Deflate { level: 6 },
117        _ => return usage(),
118    };
119    let (dir, remove) = match args.get(3) {
120        Some(dir) => (PathBuf::from(dir), false),
121        None => (
122            std::env::temp_dir().join(format!("ostrya-send-pass-{}", std::process::id())),
123            true,
124        ),
125    };
126    let result = run(&dir, count, size, compression);
127    if remove {
128        let _ = fs::remove_dir_all(&dir);
129    }
130    match result {
131        Ok(()) => ExitCode::SUCCESS,
132        Err(e) => {
133            eprintln!("send_pass: {e}");
134            ExitCode::FAILURE
135        }
136    }
137}
138
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}