use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::process::{Command, Output, Stdio};
use second_brain_sync::protocol::{BelowFloorLine, Hello, Merging, RefusedLine, SyncHeader};
fn hello() -> Hello {
Hello {
machine_id: "6f1c1d1e-0000-4000-8000-000000000001".to_string(),
wall_micros: 0,
synced: true,
cursor: None,
held_origin_seq: None,
keys: None,
peer_in: None,
log_floor: 0,
head: 0,
applied: None,
merging: None,
}
}
struct Reply {
status: u16,
content_type: &'static str,
body: Vec<u8>,
}
fn json(status: u16, body: String) -> Reply {
Reply {
status,
content_type: "application/json",
body: body.into_bytes(),
}
}
fn daemon(route: fn(&str, &[u8]) -> Reply) -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let version = serde_json::to_string(&SyncHeader::local()).unwrap();
std::thread::spawn(move || {
for stream in listener.incoming() {
let mut stream = stream.unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut request_line = String::new();
reader.read_line(&mut request_line).unwrap();
let path = request_line
.split_whitespace()
.nth(1)
.unwrap_or_default()
.to_string();
let mut length = 0usize;
let mut chunked = false;
loop {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
if line == "\r\n" || line.is_empty() {
break;
}
let lower = line.to_ascii_lowercase();
if let Some(v) = lower.strip_prefix("content-length:") {
length = v.trim().parse().unwrap();
}
chunked |= lower.starts_with("transfer-encoding:") && lower.contains("chunked");
}
let mut body = Vec::new();
if chunked {
loop {
let mut size = String::new();
reader.read_line(&mut size).unwrap();
let size = usize::from_str_radix(size.trim(), 16).unwrap();
let mut chunk = vec![0u8; size + 2];
reader.read_exact(&mut chunk).unwrap();
if size == 0 {
break;
}
body.extend_from_slice(&chunk[..size]);
}
} else {
body = vec![0u8; length];
reader.read_exact(&mut body).unwrap();
}
let reply = if path == "/v1/sync/version" {
json(200, version.clone())
} else {
route(&path, &body)
};
let head = format!(
"HTTP/1.1 {} X\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
reply.status,
reply.content_type,
reply.body.len()
);
stream.write_all(head.as_bytes()).unwrap();
stream.write_all(&reply.body).unwrap();
}
});
base
}
fn sb(api: &str, args: &[&str], stdin: &[u8]) -> Output {
let home = tempfile::tempdir().unwrap();
second_brain_core::api_token::ensure(&home.path().join(".second-brain")).unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_sb"))
.args(args)
.env("HOME", home.path())
.env("SECOND_BRAIN_API", api)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child.stdin.take().unwrap().write_all(stdin).unwrap();
child.wait_with_output().unwrap()
}
const SNAPSHOT: [u8; 6] = [0, 255, b'\n', 128, 0, 7];
#[test]
fn a_below_floor_refusal_becomes_the_below_floor_line_and_exit_0() {
let api = daemon(|path, _| {
assert_eq!(path, "/v1/sync/export");
json(
409,
r#"{"error":"below the log floor","below_floor":true,"after_seq":3,"log_floor":9}"#
.to_string(),
)
});
let output = sb(&api, &["sync-export", "--after-seq", "3"], b"");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "{stderr}");
let expected = format!(
"{}\n",
BelowFloorLine {
after_seq: 3,
log_floor: 9
}
.to_line()
);
assert_eq!(String::from_utf8_lossy(&output.stdout), expected);
}
#[test]
fn another_export_refusal_still_fails_with_the_daemons_text() {
let api = daemon(|_, _| json(409, r#"{"error":"peer is on another schema"}"#.to_string()));
let output = sb(&api, &["sync-export", "--after-seq", "0"], b"");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!output.status.success());
assert!(stderr.contains("peer is on another schema"), "{stderr}");
let refused = RefusedLine::parse_line(&String::from_utf8_lossy(&output.stdout))
.expect("the export answers with a refused line and nothing else");
assert_eq!(refused.error, "peer is on another schema");
assert!(!refused.identity);
}
#[test]
fn sync_snapshot_copies_the_daemons_stream_byte_for_byte() {
let api = daemon(|path, body| {
assert_eq!(path, "/v1/sync/snapshot");
let request: serde_json::Value = serde_json::from_slice(body).unwrap();
assert_eq!(request["with_chunks"], true);
assert_eq!(request["hello"]["machine_id"], hello().machine_id);
Reply {
status: 200,
content_type: "application/octet-stream",
body: SNAPSHOT.to_vec(),
}
});
let output = sb(&api, &["sync-snapshot", "--hello", &hello().to_arg()], b"");
assert!(output.status.success(), "{:?}", output.stderr);
assert_eq!(output.stdout, SNAPSHOT);
}
#[test]
fn sync_snapshot_fails_with_the_daemons_error_text() {
let api = daemon(|_, _| json(503, r#"{"error":"the daemon is starting"}"#.to_string()));
let output = sb(&api, &["sync-snapshot", "--hello", &hello().to_arg()], b"");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!output.status.success());
assert!(stderr.contains("the daemon is starting"), "{stderr}");
}
#[test]
fn sync_snapshot_apply_streams_stdin_and_prints_the_merging_line() {
let api = daemon(|path, body| {
assert_eq!(path, "/v1/sync/snapshot/apply");
assert_eq!(body, SNAPSHOT);
json(
200,
serde_json::to_string(&Merging {
snapshot_id: "s1".to_string(),
exporter: "peer".to_string(),
seq: 12,
})
.unwrap(),
)
});
let output = sb(&api, &["sync-snapshot", "--apply"], &SNAPSHOT);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let line = String::from_utf8(output.stdout).unwrap();
assert_eq!(line.lines().count(), 1, "{line}");
let merging: Merging = serde_json::from_str(line.trim()).unwrap();
assert_eq!((merging.snapshot_id.as_str(), merging.seq), ("s1", 12));
}
#[test]
fn sync_snapshot_apply_refuses_while_a_merge_runs() {
let api = daemon(|_, _| {
json(
409,
r#"{"error":"a snapshot merge is already running","merging":true}"#.to_string(),
)
});
let output = sb(&api, &["sync-snapshot", "--apply"], &SNAPSHOT);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!output.status.success());
assert!(stderr.contains("already running"), "{stderr}");
}