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            max_frame: MIN_FRAME_LIMIT,
44            max_have: 16_384,
45            encodings: vec![Encoding::Raw, Encoding::Deflate],
46            parallel_uploads: 1,
47            refs: vec![RefState {
48                name: "main".into(),
49                commit: None,
50            }],
51        }),
52        Message::ObjectsReply(ObjectsReply {
53            objects: 0,
54            payload_bytes: 0,
55        }),
56    ];
57    let mut w = FrameWriter::new(Vec::new());
58    for msg in &msgs {
59        w.write_message(msg).await.map_err(io::Error::other)?;
60    }
61    Ok(w.into_inner())
62}
63
64/// Writes `count` files of `size` bytes under `dir`. The first 8 bytes of each
65/// file hold its index, so no two files share a content object.
66fn write_files(dir: &Path, count: u64, size: u64) -> io::Result<()> {
67    let mut chunk = vec![0u8; WRITE_CHUNK];
68    for (i, byte) in chunk.iter_mut().enumerate() {
69        *byte = (i % 251) as u8;
70    }
71    for index in 0..count {
72        let mut file = io::BufWriter::new(fs::File::create(dir.join(format!("f{index:07}")))?);
73        let mut left = size;
74        let tag = index.to_le_bytes();
75        let head = left.min(tag.len() as u64) as usize;
76        file.write_all(&tag[..head])?;
77        left -= head as u64;
78        while left > 0 {
79            let n = left.min(WRITE_CHUNK as u64) as usize;
80            file.write_all(&chunk[..n])?;
81            left -= n as u64;
82        }
83        file.flush()?;
84    }
85    Ok(())
86}
87
88/// Returns the peak resident set size of the process, as `/proc/self/status`
89/// gives it.
90fn peak_rss() -> Option<String> {
91    let status = fs::read_to_string("/proc/self/status").ok()?;
92    let line = status.lines().find(|line| line.starts_with("VmHWM:"))?;
93    Some(line["VmHWM:".len()..].trim().to_owned())
94}
95
96fn usage() -> ExitCode {
97    eprintln!("usage: send_pass COUNT SIZE raw|deflate [DIR]");
98    ExitCode::from(2)
99}
100
101fn main() -> ExitCode {
102    let args: Vec<String> = std::env::args().skip(1).collect();
103    let (Some(count), Some(size), Some(encoding)) = (
104        args.first().and_then(|a| a.parse::<u64>().ok()),
105        args.get(1).and_then(|a| a.parse::<u64>().ok()),
106        args.get(2),
107    ) else {
108        return usage();
109    };
110    if count > 1 && size < 8 {
111        return usage();
112    }
113    let compression = match encoding.as_str() {
114        "raw" => Compression::None,
115        "deflate" => Compression::Deflate { level: 6 },
116        _ => return usage(),
117    };
118    let (dir, remove) = match args.get(3) {
119        Some(dir) => (PathBuf::from(dir), false),
120        None => (
121            std::env::temp_dir().join(format!("ostrya-send-pass-{}", std::process::id())),
122            true,
123        ),
124    };
125    let result = run(&dir, count, size, compression);
126    if remove {
127        let _ = fs::remove_dir_all(&dir);
128    }
129    match result {
130        Ok(()) => ExitCode::SUCCESS,
131        Err(e) => {
132            eprintln!("send_pass: {e}");
133            ExitCode::FAILURE
134        }
135    }
136}
137
138fn run(dir: &Path, count: u64, size: u64, compression: Compression) -> io::Result<()> {
139    fs::create_dir_all(dir)?;
140    write_files(dir, count, size)?;
141    ostrya_rt::block_on(async {
142        let model = TreeModel::scan(dir, ScanOptions::default())
143            .await
144            .map_err(io::Error::other)?;
145        let names: Vec<_> = model
146            .object_names()
147            .into_iter()
148            .filter(|name| name.ty == ObjectType::File)
149            .collect();
150        let session = PushSession::over_stream(
151            Cursor::new(scripted_replies().await?),
152            sink(),
153            &["main".to_string()],
154            SessionOptions::default(),
155        )
156        .await
157        .map_err(io::Error::other)?;
158        eprintln!("send pass: start");
159        let start = Instant::now();
160        session
161            .send(&model, &names, &[], compression)
162            .await
163            .map_err(io::Error::other)?;
164        let elapsed = start.elapsed();
165        let files = names.len().max(1) as f64;
166        println!(
167            "{} files of {size} bytes: {:.1} us per file, {:.3} s in all",
168            names.len(),
169            elapsed.as_secs_f64() * 1e6 / files,
170            elapsed.as_secs_f64()
171        );
172        if let Some(peak) = peak_rss() {
173            println!("VmHWM: {peak}");
174        }
175        Ok(())
176    })
177}