Files
leleka/control-plane/tests/mtp_fetch/mirror.rs
T

162 lines
5.1 KiB
Rust

//! The fake HTTP mirror of the checkpoint: honest, ignoring `Range`, or flipping the bytes of chosen tensors.
use super::files;
use serde_json::Value;
use std::{
collections::{BTreeMap, HashSet},
io::{Read, Write},
net::{TcpListener, TcpStream},
sync::{Arc, Mutex},
thread,
};
/// How the fake mirror misbehaves (the Python tests' `Mirror`).
#[derive(Clone, Default)]
pub(super) struct Mode {
pub(super) ignore_range: bool,
pub(super) cut: bool,
/// Ranges of these tensors are returned bit-flipped.
pub(super) wrong: HashSet<String>,
}
type Ranges = Arc<Mutex<Vec<(String, u64, u64)>>>;
pub(super) struct Mirror {
pub(super) url: String,
pub(super) mode: Arc<Mutex<Mode>>,
pub(super) ranges: Ranges,
}
pub(super) fn span(name: &str, tensor: &str) -> Option<(u64, u64)> {
let raw = files().remove(name)?;
let n = u64::from_le_bytes(raw[..8].try_into().unwrap());
let header: Value = serde_json::from_slice(&raw[8..8 + n as usize]).unwrap();
let meta = header.get(tensor)?;
let (a, b) = (
meta["data_offsets"][0].as_u64().unwrap(),
meta["data_offsets"][1].as_u64().unwrap(),
);
Some((8 + n + a, 8 + n + b - 1))
}
fn read_request(stream: &mut TcpStream) -> Option<String> {
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
match stream.read(&mut buffer) {
Ok(0) | Err(_) => return None,
Ok(n) => request.extend_from_slice(&buffer[..n]),
}
}
Some(String::from_utf8_lossy(&request).into_owned())
}
/// `(method, path, range)` of a request.
fn parse_request(text: &str) -> (&str, &str, Option<(u64, u64)>) {
let first = text.lines().next().unwrap_or_default();
let mut parts = first.split(' ');
let method = parts.next().unwrap_or_default();
let path = parts.next().unwrap_or_default().trim_start_matches('/');
let range = text.lines().find_map(|l| {
l.to_ascii_lowercase()
.strip_prefix("range: bytes=")
.map(|r| {
let (a, b) = r.split_once('-').unwrap();
(
a.trim().parse::<u64>().unwrap(),
b.trim().parse::<u64>().unwrap(),
)
})
});
(method, path, range)
}
/// Writes one response; a `HEAD` gets the length of the whole file and no body.
fn respond(
stream: &mut TcpStream,
(method, body_len): (&str, usize),
(status, extra, bytes): (&str, &str, &[u8]),
) {
let length = if method == "HEAD" {
body_len
} else {
bytes.len()
};
let head = format!(
"HTTP/1.1 {status}\r\n{extra}Content-Length: {length}\r\nConnection: close\r\n\r\n"
);
let _ = stream.write_all(head.as_bytes());
if method != "HEAD" {
let _ = stream.write_all(bytes);
}
}
/// The answer to a range request under `mode`.
fn respond_ranged(
stream: &mut TcpStream,
(method, path): (&str, &str),
body: &[u8],
((a, b), mode): ((u64, u64), &Mode),
) {
if mode.ignore_range {
let sent = if mode.cut {
&body[..(b - a + 1) as usize]
} else {
body
};
respond(stream, (method, body.len()), ("200 OK", "", sent));
return;
}
let mut part = body[a as usize..=b as usize].to_vec();
if ["mtp.a", "mtp.b"]
.iter()
.any(|t| mode.wrong.contains(*t) && span(path, t) == Some((a, b)))
{
part.iter_mut().for_each(|x| *x ^= 0xff);
}
let header = format!("Content-Range: bytes {a}-{b}/{}\r\n", body.len());
let reply = ("206 Partial Content", header.as_str(), part.as_slice());
respond(stream, (method, body.len()), reply);
}
fn handle_connection(
mut stream: TcpStream,
(mode, ranges): (Arc<Mutex<Mode>>, Ranges),
files: &BTreeMap<String, Vec<u8>>,
) {
let Some(text) = read_request(&mut stream) else {
return;
};
let (method, path, range) = parse_request(&text);
let Some(body) = files.get(path) else {
let _ = stream
.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
return;
};
let mode = mode.lock().unwrap().clone();
match range {
None => respond(&mut stream, (method, body.len()), ("200 OK", "", body)),
Some((a, b)) => {
ranges.lock().unwrap().push((path.to_owned(), a, b));
respond_ranged(&mut stream, (method, path), body, ((a, b), &mode));
}
}
}
pub(super) fn serve() -> Mirror {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/", listener.local_addr().unwrap());
let mode = Arc::new(Mutex::new(Mode::default()));
let ranges: Ranges = Arc::new(Mutex::new(Vec::new()));
let (m, r) = (mode.clone(), ranges.clone());
thread::spawn(move || {
let files = files();
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let (mode, ranges, files) = (m.clone(), r.clone(), files.clone());
thread::spawn(move || handle_connection(stream, (mode, ranges), &files));
}
});
Mirror { url, mode, ranges }
}